GRPOTrainer / RLOOTrainer keep moving the weights on steps where every advantage is zero (AdamW momentum)
Reproduction
If every group in a step has the same reward, every advantage is 0. With beta=0.0 (the GRPO default), the gradient is exactly 0. The trainer still calls optimizer.step(), and AdamW's momentum keeps moving the weights for many steps after the reward saturates. frac_reward_zero_std=1.0 shows the step has no signal, but nothing acts on it.
import random
import torch
from datasets import Dataset
from transformers import TrainerCallback
from trl import GRPOConfig, GRPOTrainer
calls = 0
def saturating_reward(completions, **kwargs):
# Random for the first 5 steps, then constant: every group has zero std, so every advantage is 0.
global calls
calls += 1
return [random.random() if calls <= 5 else 1.0 for _ in completions]
class ParamDelta(TrainerCallback):
def __init__(self, model):
self.model, self.prev = model, None
def flat(self):
return torch.cat([p.detach().flatten().clone() for p in self.model.parameters()])
def on_train_begin(self, args, state, control, **kwargs):
self.prev = self.flat()
def on_log(self, args, state, control, logs=None, **kwargs):
if "grad_norm" not in logs: # end-of-training summary
return
cur = self.flat()
print(f"step {state.global_step:2d} frac_reward_zero_std={logs.get('frac_reward_zero_std')} "
f"grad_norm={logs.get('grad_norm'):.3g} |Δθ|={(cur - self.prev).norm():.3g}")
self.prev = cur
trainer = GRPOTrainer(
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
reward_funcs=saturating_reward,
args=GRPOConfig(
output_dir="/tmp/zero_signal",
per_device_train_batch_size=8,
num_generations=4,
max_completion_length=8,
max_steps=15,
learning_rate=1e-3,
lr_scheduler_type="constant",
logging_steps=1,
report_to="none",
save_strategy="no",
),
train_dataset=Dataset.from_dict({"prompt": [f"Count to {i}:" for i in range(200)]}),
)
trainer.add_callback(ParamDelta(trainer.model))
trainer.train()
Output (trimmed):
step 5 frac_reward_zero_std=0.0 grad_norm=0.313 |Δθ|=0.633
step 6 frac_reward_zero_std=1.0 grad_norm=0 |Δθ|=0.544
...
step 15 frac_reward_zero_std=1.0 grad_norm=0 |Δθ|=0.194
Over a 30-step version (5 steps with signal, then 25 with zero gradient; constant LR 1e-3):
| run | net ‖Δθ‖, 5 signal steps | net ‖Δθ‖, 25 zero-grad steps | cos(signal, drift) |
|---|---|---|---|
| GRPO, AdamW (default) | 3.07 | 4.78 | 0.79 |
GRPO, optim="sgd" |
7.9e-4 | 0.0 | n/a |
RLOO, beta=0.0 |
3.20 | 5.19 | 0.81 |
RLOO, beta=0.05 (default) |
3.20 | 5.21 | 0.80 |
The SGD control does not move at all, so the motion comes entirely from optimizer state. With RLOO's default beta=0.05, the KL penalty makes the rewards slightly different, so frac_reward_zero_std reads 0.0. The remaining gradient is ~150× smaller than on signal steps (0.002–0.006 vs 0.8–0.9), yet the weights move as far as with beta=0.
AsyncGRPO already drops zero-std groups (#7609), so this affects only the synchronous GRPOTrainer and RLOOTrainer.
How did you hit this?
In format-reward RL on Qwen3-1.7B-Base (my own RLOO trainer, not TRL), the reward saturated at about step 17. The last 25 steps had no gradient, yet KL to the base model tripled, and a downstream behavior I was measuring fell from 0.41 to 0.13. I then checked whether TRL behaves the same, and it does.
This is not a request to change the objective (unlike #5588). The objective's gradient on these steps is exactly zero, and the weights move anyway.
Possible fixes, smallest first. Which, if any, would you accept?
- A docs note next to
frac_reward_zero_std: when it is 1.0 for a whole step, AdamW still moves the weights. Suggest stopping at saturation or using AsyncGRPO. - A one-time warning when an entire optimizer step has zero-std rewards in every group and
beta == 0. - An opt-in config flag that skips the optimizer step (and scheduler step) when the accumulated batch carries no advantage signal.
I'm happy to send a PR for whichever you prefer.
System Info
- Platform: macOS-27.2-arm64-arm-64bit
- Python version: 3.12.2
- TRL version: 1.17.1 (also checked
mainat 4ae4d34: same code path, no skip) - PyTorch version: 2.15.0
- accelerator(s): MPS
- Transformers version: 5.22.2
- Accelerate version: 1.15.0
- Datasets version: 5.1.0
Checklist
- [x] I have checked that my issue isn't already filed (closest: #5588, #3708, #7747)
- [x] I have included my system information
- [x] Any code provided is minimal, complete, and reproducible
- [x] Any code provided is properly formatted in code blocks
- [x] Any traceback provided is complete
I have a fix ready for options 1 and 2. It adds a note on frac_reward_zero_std to the GRPO and RLOO docs. It also adds a one-time warning in both trainers when every group in a generation batch receives identical rewards, with a regression test for each trainer. Could you assign this issue to me so I can open the PR? If you would rather have only the docs note, or option 3, I'll adjust it.
I can confirm this end to end and I've traced where the motion lives. tl;dr for the maintainers: the drift is purely stale first-moment state being amplified by a frozen second moment, it is exactly reproducible with grad_norm == 0 steps, and skipping optimizer.step() on exactly-zero gradients removes it completely — so option 3 is implementable with a trigger that cannot false-positive by construction.
Setup. trl 1.17.1, transformers 5.17.0, torch 2.14.1, CPU, trl-internal-testing/tiny-Qwen2ForCausalLM-2.5, your saturating-reward script. I additionally hooked the real AdamW's step (pre/post) to read gradients and optimizer state at the moment they matter — at on_step_end time the grads are already None (zero_grad(set_to_none=True)), which is why a callback-based check can look clean while the weights still move.
Attribution. Steps 1–5 carry signal (||g||₂ ≈ 0.31–0.35). From step 6 on, every gradient tensor is exactly zero (abs().max() == 0.0 on all 27 params), yet the weights keep moving:
| step | ‖Δθ‖ | ‖exp_avg‖ | ‖exp_avg_sq‖ | predicted ‖lr·m̂/(√v̂+ε)‖ |
|---|---|---|---|---|
| 6 | 0.1687 | 5.359e-2 | 1.9728e-5 | 0.1687 |
| 7 | 0.1471 | 4.823e-2 | 1.9708e-5 | 0.1471 |
| 8 | 0.1294 | 4.341e-2 | 1.9689e-5 | 0.1294 |
| 9 | 0.1147 | 3.907e-2 | 1.9669e-5 | 0.1147 |
| 10 | 0.1022 | 3.516e-2 | 1.9649e-5 | 0.1022 |
| 15 | 0.0603 | 2.076e-2 | 1.9551e-5 | 0.0603 |
Three observations:
- The predicted momentum-only update matches the realized ‖Δθ‖ to 4 decimals at every drift step — the motion is 100% optimizer state, zero contribution from fresh gradients. This is the mechanism behind your SGD control (drift = 0.0).
‖exp_avg‖decays by exactly ×0.9 per step (β₁), while‖exp_avg_sq‖is nearly frozen (×0.999, β₂). Since AdamW's update islr·m̂/√v̂, a frozen denominator means the per-step drift decays as 0.9ᵏ — i.e. it persists for ~2/(1−β₁) ≈ 20 effective steps. Over the 10 zero-grad steps I measured, cumulative drift is ‖Δθ‖ ≈ 1.04, i.e. ~37% of the entire 5-step signal-phase displacement (2.84), in a phase with zero gradient.- The trainer's logged
grad_normis 0 on these steps and matches the exact-zero grads I measured — sograd_norm == 0is a reliable, already-computed signal for the trigger.
Control run (option 3 works). Re-running with optimizer.step() skipped whenever every gradient is exactly zero: 10 skips (steps 6–15), zero weight movement on all of them, signal steps unaffected. So the smallest fix is self-guarding: a true zero-gradient AdamW step contributes nothing except momentum decay, skipping it is mathematically a no-op on the weights.
One design trap for the trigger condition. The two candidate triggers diverge exactly where your RLOO beta=0.05 measurement sits:
grad_norm == 0covers GRPO withbeta=0(your measured case; grads are exactly zero, not just tiny). It does not cover RLOO with the defaultbeta=0.05, where the KL term keeps gradients at 0.002–0.006 — nonzero, so an exact-zero trigger won't fire there.frac_reward_zero_std == 1.0covers the RLOO case (in that run it reads 0.0 only because KL perturbs the rewards — the advantage signal is still zero) but needs thebeta == 0… guard you proposed to avoid skipping steps that carry a small-but-real gradient.
They could ship together: skip on grad_norm == 0 (safe, loss-free) and emit the one-time warning on frac_reward_zero_std == 1.0 (broader coverage, no behavior change). That would compose cleanly with @Abraham-y's warning/docs PR rather than duplicate it.
Two footnotes if option 3 is implemented:
- AdamW's decoupled weight decay lives in the same
step()call, so skipping the step also pauses weight decay. Defaultweight_decay=0.0makes this moot today, but the flag's docstring should say what happens when it isn't. - Decide whether
scheduler.step()keeps running during skipped steps. Continuing preserves the LR timeline vs. wall-steps (my preference — it keepsmax_stepsschedules comparable between runs); pausing shifts the schedule.
Happy to open a PR for option 3 (skip on exactly-zero gradients + a regression test asserting ‖Δθ‖ == 0 across zero-grad steps, in the spirit of the ParamDelta callback) if maintainers want it — and happy to hand the numbers/scripts to whoever implements it.
Thanks @Abraham-y, but this is just AdamW working as expected rather than GRPO/RLOO: with a zero gradient, exp_avg decays by β1 each step, so the weights keep moving along the last update for about ten steps' worth, then stop. Any Adam loop does this.
With the default batch sizes, steps where every group has zero std are routine, so a warning or a skip-step flag would fire on ordinary steps
If you want those groups out of the update, AsyncGRPOTrainer drops zero-std groups before they reach the optimizer.