Repository navigation
[BugFix] Fix optim step count and loss average in Trainer.optim_steps - #4688
sramireddy2 wants to merge 1 commit into
Conversation
Trainer.optim_steps incremented _optim_count before checking whether process_optim_batch raised StopIteration or returned None, so an exhausted sampler counted one optimization step per epoch that never ran. The running loss average used the per-epoch loop index, so with num_epochs > 1 it only covered the last epoch. Count a step only once it is known to run, and average losses over all steps of the call.
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/rl/4688
Note: Links to docs will display an error until the docs builds have been completed.
|
|
I added a complementary integration regression on With a scalar parameter initially 1, unit gradients and SGD lr=0.1, the first call performs six updates: the parameter becomes 0.4, the reported mean loss is 0.75, and the reported cumulative step count is 6. A second call performs two more updates: parameter 0.2, per-call mean loss 0.35, cumulative count 8. This checks that averaging resets between calls while the step count does not. The regression passes on this PR; with only
Additional regression patchdiff --git a/test/test_trainer.py b/test/test_trainer.py
index dfdb155c..d2ecb5a9 100644
--- a/test/test_trainer.py
+++ b/test/test_trainer.py
@@ -2127,6 +2127,15 @@ class _CountingStepper(OptimizationStepper):
self.calls = state_dict["calls"]
+class _UnitGradientLoss(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(()))
+
+ def forward(self, td: TensorDict) -> TensorDict:
+ return TensorDict({"loss": (self.weight * td["x"]).mean()}, [])
+
+
class _IncreasingLossStepper(_CountingStepper):
"""Returns 1.0, 2.0, 3.0, ... as the loss of successive steps."""
@@ -2295,6 +2304,39 @@ class TestPostOptimCompleteLog:
assert "optim_steps" not in trainer._log_dict
assert "loss" not in trainer._log_dict
+ def test_real_optimizer_average_and_exhaustion_across_calls(self):
+ loss = _UnitGradientLoss()
+ trainer = self._make_trainer(
+ loss_module=loss,
+ optimizer=torch.optim.SGD(loss.parameters(), lr=0.1),
+ )
+ rb = TensorDictReplayBuffer(
+ storage=LazyTensorStorage(4),
+ sampler=SamplerWithoutReplacement(),
+ batch_size=2,
+ )
+ rb_trainer = ReplayBufferTrainer(rb, iterate=True)
+ trainer.register_op("pre_epoch", rb_trainer.extend)
+ trainer.register_op("process_optim_batch", rb_trainer.sample)
+ reported = TensorDict({}, [])
+
+ def capture(optim_steps, average_losses):
+ reported.update(average_losses.clone())
+ reported["optim_steps"] = torch.tensor(optim_steps)
+
+ trainer.register_op("post_optim_complete_log", capture)
+ data = TensorDict({"x": torch.ones(4)}, [4])
+ trainer.optim_steps(data, optim_steps_per_batch=None, num_epochs=3)
+ # Six unit gradients: weights 1 -> .4, losses 1, .9, ..., .5.
+ torch.testing.assert_close(loss.weight, torch.tensor(0.4))
+ torch.testing.assert_close(reported["loss"], torch.tensor(0.75))
+ assert reported["optim_steps"].item() == 6
+ trainer.optim_steps(data, optim_steps_per_batch=None, num_epochs=1)
+ # Averages are per call; the public hook's step count is cumulative.
+ torch.testing.assert_close(loss.weight, torch.tensor(0.2))
+ torch.testing.assert_close(reported["loss"], torch.tensor(0.35))
+ assert reported["optim_steps"].item() == 8
+
def test_average_losses_span_all_epochs(self):
captured = {}
AI-assisted test development; the before/after checks were executed locally. |
|
Thanks, I checked this and the numbers match: 0.55 on the parent vs 0.75 with the fix. Each of the two tests already in the PR fails on the parent for one of the two bugs, and the stepper and plain-optimizer paths share the same averaging and counting code, so I'll keep the PR as is. Happy to add the real-SGD variant if a maintainer wants it. (Reply drafted with AI assistance; the check was run locally.) |
|
Hi @bsprenger, thanks for the quick review on #4724! When you have time, could you take a look at this one and approve CI? It fixes |
Description
Fixes #4687. Two bookkeeping fixes in
Trainer.optim_steps:_optim_countno longer counts a step when the sampler is exhausted or the batch hook returnsNone. WithReplayBufferTrainer(iterate=True)(thePPOTrainerdefault path) it overcounted by one per epoch. The increment still happens before the step runs, sopost_optimhooks see the same count as before.average_lossesnow averages over every step of the call. It used the per-epoch indexj, so withnum_epochs > 1only the last epoch was averaged.loop_startedreplaces thej >= 0check beforepost_optim_complete_log; it is true under the same conditions.Motivation and Context
Types of changes
Checklist
I used an AI assistant (Claude Code) to help find the bug and run the checks. I've read and tested every changed line.