Skip to content

[BugFix] Average each loss key over the steps that report it - #4767

Draft
sramireddy2 wants to merge 2 commits into
pytorch:mainfrom
sramireddy2:fix/grpo-average-missing-keys
Draft

sramireddy2 wants to merge 2 commits into
pytorch:mainfrom
sramireddy2:fix/grpo-average-missing-keys

Conversation

@sramireddy2

@sramireddy2 sramireddy2 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #4733. Trainer.optim_steps averaged each loss key with the step index, which assumes every step returns the same keys. MixedPrecisionOptimizationStepper only reports grad_norm on the micro-steps that step the optimizer, so GRPOTrainer with gradient_accumulation_steps > 1 crashed on its first batch. The average now counts, for each key, the steps that reported it.

The counts reset every epoch, as the step index did, so keys reported on every step are averaged exactly as before. #4688 changes that per-epoch reset separately; both PRs touch these lines, so whichever lands second needs a small rebase.

Motivation and Context

  • I have raised an issue to propose this change (required for new features and bug fixes)

Types of changes

  • Bug fix (non-breaking change which fixes an issue)

Checklist

  • I have read the CONTRIBUTION guide (required)
  • My change requires a change to the documentation.
  • I have updated the tests accordingly (required for a bug fix or a new feature).
  • I have updated the documentation accordingly.

I used an AI assistant (Claude Code) to help find the bug and write and test the change. I'm still reviewing it, so this is a draft.

GRPOTrainer with gradient_accumulation_steps > 1 crashed on its first batch:
MixedPrecisionOptimizationStepper only reports grad_norm on the micro-steps
that step the optimizer, and Trainer.optim_steps averaged every key with the
step index, so the first grad_norm met a missing running value. Count the steps
per key instead.

Fixes pytorch#4733
@pytorch-bot

pytorch-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/rl/4767

Note: Links to docs will display an error until the docs builds have been completed.

⚠️ 16 Awaiting Approval

As of commit 4ab41ef with merge base df1db3d (image):

AWAITING APPROVAL - The following workflows need approval before CI can run:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 23, 2026
@JonnyFaeth

Copy link
Copy Markdown

Test suggestion for 7b825fb: extend the existing regression to four micro-steps as well as two. That exercises a second, different grad_norm after an intervening step without that key, so it checks the per-key denominator as well as first-key insertion.

With the default gradient clipping, the two reported norms are 10 and 9.75 (mean 9.875); the four losses are 10, 10, 9.50625, 9.50625 (mean 9.753125). This small extension passed all 11 TestGRPOTrainer cases locally. As a mutation check, I retained the new missing-key handling but changed only the averaging expression back to val * j / (j + 1) + item / (j + 1): the two-step case still passed, while the four-step case failed with 9.9375 instead of 9.875. Production source was restored afterward.

Suggested changes to test_gradient_accumulation_within_a_batch:

-    def test_gradient_accumulation_within_a_batch(self):
+    @pytest.mark.parametrize(
+        "micro_steps, expected_loss, expected_norm, expected_weight",
+        [(2, 10.0, 10.0, 0.05), (4, 9.753125, 9.875, 0.1)],
+    )
+    def test_gradient_accumulation_within_a_batch(
+        self, micro_steps, expected_loss, expected_norm, expected_weight
+    ):
@@
-                optim_steps_per_batch=2,
+                optim_steps_per_batch=micro_steps,

Replace its final assertions/comments with:

        assert trainer.optimization_stepper.optimizer_step_count == micro_steps // 2
        assert reported["loss_objective"] == pytest.approx(expected_loss)
        assert reported["grad_norm"] == pytest.approx(expected_norm)
        assert model.weight.item() == pytest.approx(expected_weight)

Validation: python -m pytest test/test_trainer.py -k TestGRPOTrainer -q -p no:cacheprovider — 11 passed. Windows, Python 3.12, PyTorch 2.11 CPU; the optional TorchRL C++ extension was unavailable. No GPU/mixed-precision or full-suite validation. git diff --check passed; the configured Flake8 dependency was not cached, so that lint check did not run.

AI disclosure: prepared and executed by Codex under Jonathan’s standing authorization; not independently human-reviewed.

With two micro-steps grad_norm is reported once, so nothing is averaged. With
four it is reported twice with different values, which checks that each key is
averaged over the steps that reported it.

Suggested by JonnyFaeth in a comment on pytorch#4767.
@sramireddy2

Copy link
Copy Markdown
Contributor Author

Thanks, good catch: with two steps grad_norm is only reported once, so nothing gets averaged. I added your four-step case in 4ab41ef. Restoring the old averaging formula locally passed the two-step case and failed the four-step one, as you described.

@sramireddy2
sramireddy2 marked this pull request as draft November 29, 2026 23:10

This branch has not been deployed

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

Labels

BugFix CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. Trainers

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants