cast_lm_head_to_fp32 is ignored during GRPO generations (both BF16 autocast and vLLM)
Reproduction
Currently, GRPO trains with an FP32 LM head on backward pass, but neither generation backend samples from an FP32 head (both samples from BF16 heads). Rollouts therefore come from a different policy than the one that is scored, which is a mismatch with the paper ScaleRL. For chunked head, only the vLLM generation gaps is present.
Code Flow
GRPOTrainer.__init__ replaces the head's forward with an FP32 linear, but does not deactivate autocast. Trainer.train() prepares the model with Accelerate, which runs its forward under BF16 autocast, and both model.generate() and generate_batch() sample from that forward.
When the flag is set, chunked head used for training log-probabilities disables autocast.
GRPOTrainer.__init__ builds VLLMGeneration without cast_lm_head_to_fp32, and VLLMGeneration creates the colocated vllm.LLM with no head dtype override, so vLLM projects the head in the model dtype. Since v0.26.0, vLLM can run the head in FP32 through the head_dtype override:
LLM(..., hf_overrides={"head_dtype": "float32"})Good to know: vLLM cans accumulates the head in FP32 but keeps its weight in the model dtype, so a small rounding gap remains (better than nothing); versions before it that TRL supports (0.20.0 to 0.25.x) cannot run the head in FP32 during generation. I guess we should warn user in such case.
In server mode, the server needs --hf-overrides '{"head_dtype": "float32"}'.
Reproduction
import tempfile
import torch
from datasets import Dataset
from tokenizers import Tokenizer
from tokenizers.models import WordLevel
from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
from trl import GRPOConfig, GRPOTrainer
torch.manual_seed(0)
config = LlamaConfig(vocab_size=32, hidden_size=16, intermediate_size=32, num_hidden_layers=1, num_attention_heads=2)
tokenizer = PreTrainedTokenizerFast(
tokenizer_object=Tokenizer(WordLevel({"<pad>": 0, "<eos>": 1, "a": 2}, unk_token="a")),
pad_token="<pad>",
eos_token="<eos>",
)
trainer = GRPOTrainer(
model=LlamaForCausalLM(config).to(torch.bfloat16),
processing_class=tokenizer,
reward_funcs=lambda completions, **kwargs: [0.0] * len(completions),
args=GRPOConfig(
output_dir=tempfile.mkdtemp(),
use_cpu=True,
bf16=True,
cast_lm_head_to_fp32=True,
per_device_train_batch_size=2,
num_generations=2,
report_to="none",
),
train_dataset=Dataset.from_dict({"prompt": ["a", "a"]}),
)
# `train()` prepares the model like this, wrapping its forward in bf16 autocast
model = trainer.accelerator.unwrap_model(trainer.accelerator.prepare(trainer.model))
input_ids = torch.tensor([[2, 2, 2]])
with torch.no_grad():
logits = model(input_ids).logits
hidden = model.model(input_ids).last_hidden_state
fp32_logits = torch.nn.functional.linear(hidden.float(), model.lm_head.weight)
print("lm_head weight dtype:", model.lm_head.weight.dtype)
print("max abs error vs FP32 projection:", (logits - fp32_logits).abs().max().item())Observed:
lm_head weight dtype: torch.float32
max abs error vs FP32 projection: 0.0003738701343536377Expected:
lm_head weight dtype: torch.float32
max abs error vs FP32 projection: 0.0IMHO no need to reproduce vLLM side, the flag is never set. But for those interested, here is vLLM discussion: https://github.com/vllm-project/vllm/issues/19925
System Info
- Platform: Linux-6.18.44-fc-v37-x86_64-with-glibc2.39
- Python version: 3.12.3
- TRL version: 1.15.0.dev0
- PyTorch version: 2.14.0
- accelerator(s): cpu
- Transformers version: 5.17.0
- Accelerate version: 1.15.0
- Accelerate config: not found
- Datasets version: 5.0.1
- HF Hub version: 1.33.0
- bitsandbytes version: not installed
- DeepSpeed version: not installed
- Liger-Kernel version: not installed
- PEFT version: 0.21.0
- vLLM version: not installed
Checklist
- I have checked that my issue isn't already filed (see open issues)
- I have included my system information
- Any code provided is minimal, complete, and reproducible (more on MREs)
- Any code provided is properly formatted in code blocks, (no screenshot, more on code blocks)
- Any traceback provided is complete
Source: huggingface/trl