Repository navigation
Description
Describe the bug
GRPOTrainer crashes on its first collected batch when gradient_accumulation_steps > 1 and the batch runs more than one micro-step, which is how both GRPO SOTA scripts configure it.
MixedPrecisionOptimizationStepper.step adds grad_norm to its metrics only on the micro-steps that step the optimizer (trainers.py:515 sets grad_norm = None, and trainers.py:550-551 adds the key only when it isn't None). The running average in Trainer.optim_steps assumes every step returns the same keys:
# trainers.py:2083-2088
if average_losses is None:
average_losses: TensorDictBase = losses_detached
else:
for key, item in losses_detached.items():
val = average_losses.get(key)
average_losses.set(key, val * j / (j + 1) + item / (j + 1))The first micro-step has no grad_norm, so when the step that does step the optimizer arrives, average_losses.get("grad_norm") returns None and the multiplication raises.
Both SOTA scripts run several micro-steps per collected batch: grpo-sync.py passes optim_steps_per_batch=None (iterate over the replay buffer) and grpo-async.py passes optim_steps_per_batch=gradient_accumulation_steps, and the shipped configs set gradient_accumulation_steps to 8 or 16. I couldn't run the scripts themselves (they need a GPU and vLLM), but the repro below uses the grpo-async.py settings. The GRPO tests in test/test_trainer.py use optim_steps_per_batch=1, so each average only ever sees one step.
To Reproduce
import warnings
import torch
from tensordict import TensorDict
from torchrl.objectives.common import LossModule
from torchrl.trainers.algorithms.grpo import GRPOTrainer
warnings.filterwarnings("ignore")
class ToyLoss(LossModule):
def __init__(self):
super().__init__()
self.lin = torch.nn.Linear(3, 1)
def forward(self, td):
return TensorDict({"loss_objective": self.lin(td["observation"]).pow(2).mean()})
class OneBatchCollector:
init_random_frames = 0
def __iter__(self):
yield TensorDict(
{"observation": torch.randn(8, 3), ("next", "reward"): torch.ones(8, 1)},
[8],
)
def shutdown(self):
pass
loss = ToyLoss()
trainer = GRPOTrainer(
collector=OneBatchCollector(),
total_frames=8,
loss_module=loss,
optimizer=torch.optim.SGD(loss.parameters(), lr=0.1),
# As in grpo-async.py: one optimizer step per collected batch.
gradient_accumulation_steps=2,
optim_steps_per_batch=2,
progress_bar=False,
)
reported = {}
trainer.register_op(
"post_optim_complete_log",
lambda optim_steps, average_losses: reported.update(average_losses.to_dict()),
)
trainer.train()
print("optimizer steps:", trainer.optimization_stepper.optimizer_step_count)
print("averaged metrics:", {k: round(float(v), 4) for k, v in sorted(reported.items())})On main at fdf01c1:
File "/home/.../torchrl/trainers/trainers.py", line 1811, in train
self.optim_steps(batch)
File "/home/.../torchrl/trainers/trainers.py", line 2088, in optim_steps
average_losses.set(key, val * j / (j + 1) + item / (j + 1))
~~~~^~~
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
With optim_steps_per_batch=None and a replay buffer holding several micro-batches (the grpo-sync.py setup) it fails the same way.
Expected behavior
Training runs, and grad_norm is averaged over the steps that report it:
optimizer steps: 1
averaged metrics: {'grad_norm': 0.9387, 'loss_objective': 0.2045}
(This is the output with the fix below applied.)
System info
Installed from source (main at fdf01c1), Python 3.12.15, torch 2.15.0+cpu, tensordict 0.15.5, Linux (WSL2 Ubuntu 24.04).
Reason and Possible fixes
Average each key over the number of steps that reported it, so a key that is missing on some steps (like grad_norm here) doesn't break the average. I tried this in a local copy of main and it gives the expected output above, for both the grpo-async.py and grpo-sync.py settings.
The other option is to have the stepper always return grad_norm, but there is no real value for it on micro-steps that don't step the optimizer, and a placeholder such as 0.0 would pull the logged average down. Fixing the average also covers any other stepper whose metrics vary between steps.
My open PR #4688 (for #4687) rewrites this running average to count steps across epochs, but it keeps average_losses.get(key), so it doesn't fix this. The per-key fix fits on top of either version. I'm happy to send a PR with a test.
Checklist
- I have checked that there is no similar issue in the repo (required)
- I have read the documentation (required)
- I have provided a minimal working example to reproduce the bug (required)
Activity
JonnyFaeth commentedon Nov 16, 2026
I reproduced the
NoneType * intfailure onfdf01c1454and tested your per-key counting approach with a real GRPO accumulation regression. The added test exercises two optimizer windows in one call, then another call, rather than only checking that training stops crashing.With a one-weight linear model and fixed data, four microsteps report losses
10, 10, 2.5, 2.5, while only the two optimizer steps report gradient norms10, 5. The proposed averaging gives loss 6.25, gradient norm 7.5, and the expected model weight 1.5. The next call resets the metric counts and reports loss 0.625, norm 2.5, and weight 1.75. This also detects treating missing gradient norms as zero.Your suggested fix plus the regression passes 53 tests across
TestGRPOTrainer,TestPostOptimCompleteLog, andTestOptimizationStepper. The regression fails on unchanged main. Windows/Python 3.12.14, Torch 2.11 CPU and TensorDict nightly; no vLLM/GPU or full SOTA run claimed.git diff --checkpasses; the 29 E402 test-file import diagnostics are unchanged from main.Since you offered to send the PR, here is the candidate/test patch for you to use or adapt; I have not opened a competing PR. The fix approach is yours; this adds independent analytical coverage.
Patch against fdf01c1
AI-assisted investigation and test development; the stated results were executed locally.