Skip to content

[BugFix] Register TargetNetUpdaterHook at post_optim in register() - #4724

Merged
bsprenger merged 4 commits into
pytorch:mainfrom
sramireddy2:fix/target-net-updater-hook-register
Nov 30, 2026
Merged

bsprenger merged 4 commits into
pytorch:mainfrom
sramireddy2:fix/target-net-updater-hook-register

Conversation

@sramireddy2

@sramireddy2 sramireddy2 commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #4723. TargetNetUpdaterHook.register() registered the hook at post_steps, so the target network was updated once per collected batch instead of after every optimizer step. It now registers at post_optim, as the class docstring and the built-in trainers do.

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.

@pytorch-bot

pytorch-bot Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 5 Pending, 3 Unrelated Failures

As of commit 7d000c4 with merge base 82a55f6 (image):

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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 11, 2026
@JonnyFaeth

Copy link
Copy Markdown

A behavioral addition to the counter assertion: the patch below checks the actual target parameters after three optimizer-stepper calls with a hard-update interval of two. Online weights advance 0→1→2→3; target weights must contain 2, not the initial 0 or final 3. It uses the real Trainer, DQNLoss and HardUpdate with a deterministic custom stepper, extending your existing test class.

At 54f7d5be, the two hook tests pass. Restoring only trainers.py to the parent makes the new weight assertion fail; the PR source is restored afterward. Hook, optimization-stepper and on-policy updater selections: 7 passed, 273 deselected on Windows/Python 3.12.14/Torch 2.11 CPU, using TensorDict source 5622aa29. No rollout, GPU, or full-suite claim. Ruff reports the same 29 pre-existing E402 errors on HEAD and the edited file; formatting changes suggested outside the added method were left alone.

diff --git a/test/test_trainer.py b/test/test_trainer.py
index 1f32cc04..f5aacd3f 100644
--- a/test/test_trainer.py
+++ b/test/test_trainer.py
@@ -2764,6 +2764,42 @@ class TestOnPolicyTargetNetUpdater:
 
 
 class TestTargetNetUpdaterHook:
+    def test_register_copies_post_step_parameters_at_interval(self):
+        loss_module = DQNLoss(
+            TensorDictModule(nn.Linear(3, 2), ["observation"], ["action_value"]),
+            action_space="one-hot",
+            delay_value=True,
+        )
+        with torch.no_grad():
+            for parameter in loss_module.value_network_params.values(True, True):
+                parameter.zero_()
+        updater = HardUpdate(loss_module, value_network_update_interval=2)
+
+        class IncrementingStepper(_CountingStepper):
+            def step(self, trainer, sub_batch):
+                with torch.no_grad():
+                    for parameter in trainer.loss_module.value_network_params.values(
+                        True, True
+                    ):
+                        parameter.add_(1)
+                return super().step(trainer, sub_batch)
+
+        trainer = Trainer(
+            collector=MockingCollector(),
+            total_frames=None,
+            frame_skip=None,
+            optim_steps_per_batch=3,
+            loss_module=loss_module,
+            optimization_stepper=IncrementingStepper(),
+        )
+        trainer._pbar_str = OrderedDict()
+        TargetNetUpdaterHook(updater).register(trainer, "target_net_updater")
+        trainer.optim_steps(TensorDict())
+        for parameter in loss_module.value_network_params.values(True, True):
+            torch.testing.assert_close(parameter, torch.full_like(parameter, 3))
+        for parameter in loss_module.target_value_network_params.values(True, True):
+            torch.testing.assert_close(parameter, torch.full_like(parameter, 2))
+
     def test_register_steps_after_every_optim_step(self):
         loss_module = DQNLoss(
             TensorDictModule(nn.Linear(3, 2), ["observation"], ["action_value"]),

AI-assisted test development and local verification.

@sramireddy2

sramireddy2 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the extra test. I checked it: it passes on this branch and fails with trainers.py reverted to the parent. The existing counter assertion also fails on the parent, so I'd like to keep this PR to the one-line fix and its small test. If a maintainer would rather have the weight-level check, I'm happy to fold it in.

@sramireddy2

Copy link
Copy Markdown
Contributor Author

Hi @bsprenger, could you approve CI on this when you have time? It's a one-line fix (post_steps to post_optim) with a test that fails on main.

@bsprenger
bsprenger force-pushed the fix/target-net-updater-hook-register branch from 54f7d5b to 1fc062c Compare November 29, 2026 22:24

@bsprenger bsprenger left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

couple nits!

Comment thread test/test_trainer.py Outdated
)


class TestTargetNetUpdaterHook:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we either work this test class into an existing one, or make this more generic (maybe TestTrainerHookRegistration or similar), rather than making a whole test class for really just one function?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in cd0ecaa: renamed it to TestTrainerHookRegistration so other hooks can go there. It also checks the new warning.

Comment thread torchrl/trainers/trainers.py Resolved
@bsprenger
bsprenger force-pushed the fix/target-net-updater-hook-register branch from b1a538b to 7d000c4 Compare November 30, 2026 08:22
@bsprenger
bsprenger merged commit a68419e into pytorch:main Nov 30, 2026
121 of 124 checks passed
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] TargetNetUpdaterHook.register() updates the target network once per batch instead of after every optimizer step

3 participants