Repository navigation
[BugFix] Average each loss key over the steps that report it - #4767
sramireddy2 wants to merge 2 commits into
Conversation
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
🔗 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.
|
|
Test suggestion for 7b825fb: extend the existing regression to four micro-steps as well as two. That exercises a second, different 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 Suggested changes to - 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: 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.
|
Thanks, good catch: with two steps |
Description
Fixes #4733.
Trainer.optim_stepsaveraged each loss key with the step index, which assumes every step returns the same keys.MixedPrecisionOptimizationStepperonly reportsgrad_normon the micro-steps that step the optimizer, soGRPOTrainerwithgradient_accumulation_steps > 1crashed 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
Types of changes
Checklist
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.