Skip to content

[BugFix] Fix optim step count and loss average in Trainer.optim_steps - #4688

Open
sramireddy2 wants to merge 1 commit into
pytorch:mainfrom
sramireddy2:fix/trainer-optim-steps-count
Open

sramireddy2 wants to merge 1 commit into
pytorch:mainfrom
sramireddy2:fix/trainer-optim-steps-count

Conversation

@sramireddy2

@sramireddy2 sramireddy2 commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #4687. Two bookkeeping fixes in Trainer.optim_steps:

  • _optim_count no longer counts a step when the sampler is exhausted or the batch hook returns None. With ReplayBufferTrainer(iterate=True) (the PPOTrainer default path) it overcounted by one per epoch. The increment still happens before the step runs, so post_optim hooks see the same count as before.
  • average_losses now averages over every step of the call. It used the per-epoch index j, so with num_epochs > 1 only the last epoch was averaged.

loop_started replaces the j >= 0 check before post_optim_complete_log; it is true under the same conditions.

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 run the checks. I've read and tested every changed line.

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.
@pytorch-bot

pytorch-bot Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

🔗 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.

⚠️ 16 Awaiting Approval

As of commit d2cc715 with merge base e295ed6 (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 5, 2026
@sramireddy2
sramireddy2 marked this pull request as ready for review November 5, 2026 17:29
@JonnyFaeth

Copy link
Copy Markdown

I added a complementary integration regression on d2cc7154 for the ordinary optimizer path: real SGD updates, a SamplerWithoutReplacement exhausted each epoch, and two successive optim_steps() calls. It uses the existing trainer fixtures and the public post_optim_complete_log hook.

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 trainers.py restored to its parent it fails because the first mean is approximately 0.55 instead of 0.75, even though the optimizer reached the correct parameter value. After restoring the PR, the adjacent TestPostOptimCompleteLog and TestOptimizationStepper classes pass: 46 passed.

git diff --check passes. Ruff has the same 29 pre-existing E402 import diagnostics; its formatting suggestions are confined to three unchanged regions. Windows/Python 3.12.14, Torch 2.11 CPU, TensorDict nightly; no CUDA/Ray or compiled-extension validation.

Additional regression patch
diff --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.

@sramireddy2

Copy link
Copy Markdown
Contributor Author

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.)

@sramireddy2

Copy link
Copy Markdown
Contributor Author

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 Trainer.optim_steps counting steps that never ran and averaging losses over only the last epoch, with a test for each.

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] Trainer.optim_steps counts optimization steps that never ran and averages losses over the last epoch only

2 participants