Skip to content

[BUG] GRPOTrainer crashes on the first batch when gradient_accumulation_steps > 1 #4733

Open

Description

@sramireddy2

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

  1. JonnyFaeth commented on Nov 16, 2026

    @JonnyFaeth

    I reproduced the NoneType * int failure on fdf01c1454 and 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 norms 10, 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, and TestOptimizationStepper. 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 --check passes; 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
    diff --git a/test/test_trainer.py b/test/test_trainer.py
    index 160664ab..7ce7774d 100644
    --- a/test/test_trainer.py
    +++ b/test/test_trainer.py
    @@ -3510,6 +3510,39 @@ class _BufferWritingCollector:
     
     
     class TestGRPOTrainer:
    +    def test_multiple_accumulation_windows_average_only_reported_metrics(self):
    +        model = nn.Linear(1, 1, bias=False)
    +        nn.init.zeros_(model.weight)
    +        with pytest.warns(UserWarning, match="experimental"):
    +            trainer = GRPOTrainer(
    +                collector=MockingCollector(),
    +                total_frames=2,
    +                frame_skip=1,
    +                loss_module=_GRPORegressionLoss(model),
    +                optimizer=torch.optim.SGD(model.parameters(), lr=0.1),
    +                gradient_accumulation_steps=2,
    +                optim_steps_per_batch=4,
    +                clip_norm=100.0,
    +                progress_bar=False,
    +            )
    +        reported = TensorDict({}, [])
    +
    +        def capture(optim_steps, average_losses):
    +            reported.update(average_losses.clone())
    +
    +        trainer.register_op("post_optim_complete_log", capture)
    +        trainer.optim_steps(_make_grpo_batch())
    +        # Four microsteps report losses 10,10,2.5,2.5; only two report norms 10,5.
    +        torch.testing.assert_close(model.weight, torch.tensor([[1.5]]))
    +        torch.testing.assert_close(reported["loss_objective"], torch.tensor(6.25))
    +        torch.testing.assert_close(reported["grad_norm"], torch.tensor(7.5))
    +        assert trainer.optimization_stepper.optimizer_step_count == 2
    +        trainer.optim_steps(_make_grpo_batch(), optim_steps_per_batch=2)
    +        torch.testing.assert_close(model.weight, torch.tensor([[1.75]]))
    +        torch.testing.assert_close(reported["loss_objective"], torch.tensor(0.625))
    +        torch.testing.assert_close(reported["grad_norm"], torch.tensor(2.5))
    +        assert trainer.optimization_stepper.optimizer_step_count == 3
    +
         def test_train_updates_policy_syncs_weights_and_logs_metrics(self):
             model = nn.Linear(1, 1, bias=False)
             nn.init.zeros_(model.weight)
    diff --git a/torchrl/trainers/trainers.py b/torchrl/trainers/trainers.py
    index be75c98c..1392bfc4 100644
    --- a/torchrl/trainers/trainers.py
    +++ b/torchrl/trainers/trainers.py
    @@ -2036,6 +2036,7 @@ class Trainer:
             hooks and logging behavior.
             """
             average_losses = None
    +        metric_counts = {}
     
             self._pre_optim_hook()
             if optim_steps_per_batch is _OPTIM_STEPS_UNSET:
    @@ -2082,10 +2083,18 @@ class Trainer:
     
                     if average_losses is None:
                         average_losses: TensorDictBase = losses_detached
    +                    metric_counts = dict.fromkeys(losses_detached.keys(), 1)
                     else:
                         for key, item in losses_detached.items():
    -                        val = average_losses.get(key)
    -                        average_losses.set(key, val * j / (j + 1) + item / (j + 1))
    +                        count = metric_counts.get(key, 0)
    +                        if count == 0:
    +                            average_losses.set(key, item)
    +                        else:
    +                            val = average_losses.get(key)
    +                            average_losses.set(
    +                                key, val * count / (count + 1) + item / (count + 1)
    +                            )
    +                        metric_counts[key] = count + 1
                     del sub_batch, losses_detached
     
                 # LOGGING POINT 5: Post-epoch logging (e.g., epoch completion metrics)
    

    AI-assisted investigation and test development; the stated results were executed locally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions