Repository navigation
[rl] Finish the weight push before forward/backward - #5235
felipemello1 merged 24 commits into
Conversation
tushar00jain
left a comment
There was a problem hiding this comment.
Looks like this is changing the ordering of trainer's push vs fwd/bwd. We should overlap them instead which should be solved by #5107
64be4c5 to
530ac4d
Compare
a2188a5 to
3fbae95
Compare
3fbae95 to
f3d3d73
Compare
The trainer actor runs every endpoint on one event loop, and forward_backward blocks it. The push's TorchStore put (after waiting for the GPU -> CPU copy) already runs in a worker thread, but the push replied from the event loop, so only after forward_backward ended. The generator pull starts on that reply, so the loop waited for it after the optimizer (timing/step/blocking_generator_pull_model_state_dict). push_model_state_dict now takes an explicit response port, and the worker thread replies right after the put. The loop's order is unchanged. Errors still reach the caller as an ActorError. Tests: on a real Monarch actor on CPU, the reply arrives while a blocking forward_backward runs, and a failed push raises ActorError in the caller. on_published runs in the worker thread after the put.
f3d3d73 to
3fd5850
Compare
tianyu-l
left a comment
There was a problem hiding this comment.
oh nice finding, the idea makes a lot of sense to me. Will trigger a claude to help confirm no other side effects.
|
@claude review this PR. As we are explicitly allowing out-of-order trainer actor control from monarch, check if anything unexpected could ever happen, even in the extremal cases. |
|
Claude finished @tianyu-l's task in 4m 51s —— View job Review of #5235: replying to the weight push from its worker thread
Verdict: I found no correctness hazard. This PR changes only when the push replies. It does not change when the push runs relative to forward/backward. The push is still sent and started before 1. Invariants with the earlier replyAll trainer endpoints are
What's new is a short window in which push N's coroutine is still alive on the trainer (waiting for
2. Extremal cases
3. Suggestions (non-blocking)
SummaryUnder every ordering the controller can now produce, the safety invariants (no torn snapshot, no optimizer write during staging, no overwrite during a pull, born-fresh rollouts) still hold. They depend on I didn't run the tests. I also couldn't inspect the installed torchmonarch source to confirm what |
|
@felipemello1 please address claude review "3. Suggestions (non-blocking)" before merging |
- The endpoint tracks whether it replied. An error after the reply is re-raised, so the actor fails with that error instead of a second reply on a port that takes one. - Catch BaseException, so a CancelledError from inside the put reaches the caller as an ActorError instead of leaving it waiting. - Trainer.push_model_state_dict: on_published is required. - The actor test spawns the actor in the test process; forward_backward blocks on a threading.Event the test sets after the push reply, instead of sleeps. Split into a reply test and an error test. - WEIGHT_SYNC.md: the generator update can slow forward/backward N+1.
|
reply from claude: @tushar00jain reworked since your review. The order is main's again: the push is sent before forward/backward N+1 and still overlaps it in the worker thread. The only change is where the push replies from: the worker thread, right after the TorchStore put, instead of the actor's event loop, which forward/backward holds. So the pull starts during forward/backward instead of after it. Could you take another look and dismiss the change request if it looks right? @tianyu-l addressed claude's §3 in the last commit:
From §2:
|
|
@claude please review. What bothers me here is that we have to await BEFORE the fwd_bwd, instead of before the optimizer step. But it seems that there is no other way doing this simply, so its better to await before the next fwd. This is a bit silly though, because there is much to overlap with. Howver, since its gpu-> host, it would be quick anyway. Another issue here is that apparently push is waiting for more than weight push. I remember hearing that our push does more than just push. There is also some processing, etc. In the future we might do quantization. So i wonder if theres a way here to wait only for gpu->cpu, nothing else. |
|
Claude finished @felipemello1's task in 4m 5s —— View job Verdict: I found no correctness issue, and your instinct is right on both points. The await sits before forward/backward because of how the push replies, not because of what the push has to finish. And most of what it waits for besides the GPU -> CPU copy is the TorchStore put. There is a simple way to wait for neither, and it is already on this branch (option 4a below). Details1. Correctness of the movePush N is now awaited before forward/backward N+1. That is strictly earlier than before optimizer N+1, so every invariant from the base branch still holds:
I also checked the exit and error paths:
The tests were updated to match, and no 2. Why before forward/backward and not before the optimizer stepFor correctness, only the base branch's await before the optimizer step is needed. The await moved because pull N starts on push N's reply. That reply is sent from the trainer actor's event loop ( As long as the reply goes through the event loop, this PR's placement is the only one that keeps the pull early. Putting it after the wait for the batch is the best version of that placement. Splitting the push into two endpoints (stage, then put) does not help on its own. The put endpoint's reply would wait behind forward/backward in the same way. 3. What the await covers todayThese are the steps of
Your microbenchmark of Qwen3.5-35B-A3B gives 0.38 s for GPU -> CPU and 0.76 s for the put. So about two thirds of the wait is the put. That is the "push does more than push" you remembered; the GPU -> CPU copy is the smaller part. 4. Ways to wait only for GPU -> CPUa) Reply from the worker thread (recommended). This is commits 3fd5850 and 6f4f4f9 on this branch. tianyu-l approved that version, and it already addresses the earlier review's suggestions. The put's completion reaches the controller without going through the event loop, so:
The cost is an explicit response port plus an The PR's "You may ask" section explains why you dropped the compute thread, but not why you dropped this version. It is the simplest option that satisfies both reviewers. I'd reconsider it, or at least say in the description why it was dropped. b) TorchStore-owned staging. This is the TODO at c) Quantization later. Run it on the GPU, on the staging stream, in 5. What this PR costs as it isIt only costs time when batch N+1 is ready before push N ends, that is, when the trainer is the bottleneck. In that case each step waits for the whole push:
For large models where the trainer is the bottleneck, that adds straight to step time. On main that time was hidden behind forward/backward, but the pull started one forward/backward late. 6. Minor
I did not run the tests or anything on a GPU; this is from reading the code. There was no |
Takes main's tree: drops this branch's earlier versions and the trainer thread-count change, so the PR can target main directly.
The trainer actor runs every endpoint on one event loop, and forward_backward blocks it. On main the controller sends push N, then forward/backward N+1 as soon as batch N+1 is ready, so push N replies only after that forward/backward ends, and the generators' pull N starts one forward/backward late. The controller now awaits the push inline, right after the wait for pull N-1, and only then starts pull N in the background. The pull still overlaps forward/backward N+1. The push time is now logged at its own step.
|
Reply from claude: Reworked on today's main (4 files against main; the earlier commits stay so old comments keep their anchors).
@tushar00jain this drops the overlap you asked for, on purpose:
Could you take another look, and dismiss the change request if this works for you? @tianyu-l your approval was for the worker-thread reply, which this version drops, so claude's §3.1-3.3 (double reply, The pull still overlaps forward/backward (the perf note from the earlier review). At Qwen3-0.6B on one GB300 host, with every batch ready, trainer tokens/s went from 10.8k to 10.6k with the pull overlapping forward/backward (a forward/backward-on-a-thread version with the same pull placement), within noise over 8 steps. Not measured across hosts. @claude please review. Check the push/pull ordering under every interleaving the controller can produce, including the error and shutdown paths, and whether the TODO at the push's await is the right follow-up. |
|
Claude finished @felipemello1's task in 4m 19s —— View job Needs discussion: the push/pull ordering is safe under every interleaving, including the error and shutdown paths, but dropping the overlap is tushar00jain's call. Review |
There was a problem hiding this comment.
Verdict: Needs discussion -- I traced every interleaving the controller can produce, including the error and shutdown paths, and the push/pull ordering holds in all of them. What's left is a trade-off only tushar00jain can accept: this PR drops the push-vs-forward/backward overlap he asked for.
What this PR does. After optimizer step N and the wait for pull N-1, the controller now awaits push N inline. Only then does it start pull N -> release groups in the background. The pull overlaps forward/backward N+1; the push overlaps nothing. The PR removes _start_push_model_state_dict and the pull's after= argument, and logs the push time at its own step.
Example. Batch N+1 is already queued (Qwen3-0.6B, one trainer GPU):
main: optim N | send push N | fwd/bwd N+1 (1.68 s, holds the trainer's loop) | push N replies | pull N | optim N+1 | wait 0.15 s for pull N
PR: optim N | push N (inline, short) | fwd/bwd N+1, pull N runs alongside | optim N+1 | pull N already done
Must fix
- PR description -- "Summary (human-written)" is empty. The author needs to write it.
- tushar00jain's CHANGES_REQUESTED is still open. He asked for the push to overlap forward/backward, and this version drops that on purpose. He needs to accept the cost or ask for the worker-thread reply. The cost: every step whose batch is ready waits for the whole push. That is about 0.12 s with the default transport and about 0.4 s with TorchStore at 27B, and up to about 1.7 s with delta sync.
Should consider
controller.py:1427-- the TODO is the right direction. It should lead with the worker-thread reply rather than forward/backward on a thread, and optimizer N+1 can be ordered on the device rather than with a host wait.controller.py:1487-- the TODO dropped the "Task exception was never retrieved" case, which still applies to the pull.trainer.py:204-- the comment no longer says why the dedicated push stream exists.
Questions
- At 27B on today's main, the pull wait was 0-3.4% of a step, with the cause not checked. Is the net gain positive at that scale once the push is serialized? A 10-step comparison of
timing/step/totalon the 27B setup would settle it.
Ordering under every interleaving
The trainer side is now fully serialized. In the loop, the controller awaits each trainer call before sending the next: sync_log_step -> forward_backward (per DP rank, gathered) -> optim_step -> push_model_state_dict. So no two trainer endpoints ever run at the same time, and the out-of-order concurrent_endpoint concern from the earlier review no longer arises. Pull tasks and validation tasks touch only the generators and the group buffer. .call() collects a reply from every rank, so no rank can start forward/backward N+1, with its collectives, while another rank is still pushing N.
| Invariant | Enforced by | Holds |
|---|---|---|
| Stage/put N reads weights after optimizer N | _mark_model_state_dict_ready_for_push in optim_step, plus the push-stream sync |
yes |
| Optimizer N+1 doesn't write while push N reads | push N is awaited before forward/backward N+1 is sent | yes, with margin |
| Pull N reads a complete policy N | pull N starts after .call() returns from all ranks |
yes |
| Push N+1 doesn't overwrite staging or the TorchStore key mid-pull | await pull_task before push N+1 |
yes |
| Born-fresh rollouts | release_active_groups runs after the pull |
yes |
| Pull N vs forward/backward and optimizer N+1 | pull reads the pinned staging buffer through one-sided transport reads, or StorageVolume copies; the optimizer writes only GPU params | yes |
Error and shutdown paths
- Push N raises. Pull N-1 has already been awaited, so no task is left in flight. This also fixes main's case where the pull task held a copy of the push error that nobody read.
- Pull N-1 raises. The error surfaces at the blocking await after optimizer N, so push N is never sent.
- Forward/backward N+1, optimizer N+1, or a failed validation raises. Pull N is orphaned while
run()tears down. Main had the same problem, with a push also orphaned. See the inline comment on the TODO. run()cancels the trainer task during the inline push (a producer crashed). The trainer finishes the push, but no pull starts, so no generator reads a half-staged buffer. I assumed Monarch doesn't propagate the cancel to the trainer; that is unverified.packed is None, the NaNbreak, and the last step. Each ends withawait pull_task, so the generators hold the last pushed policy beforevalidate_after_training. After a NaN in forward/backward N+1 that is policy N, the same as main.- Resume. The first iteration has no pull task, and the setup push/pull (
controller.py:864-867) finishes before the loop starts.
Metrics. timing/weight_sync/trainer_push_model_state_dict and timing/step/blocking_trainer_push_model_state_dict now time the same await. Keeping both preserves the keys; the description says so.
Tests. test_forward_backward_waits_for_the_previous_push is the only test that tells this PR apart from main. The full-sequence test uses instant fakes, which produce the same order either way.
Not verified: no GPU run of this version, and whether Monarch propagates a cancelled .call() to the trainer.
A pull still running when the loop raises only matters for a run that has already failed: close() and asyncio.run's shutdown end it.
This reverts commit dfcf575.
The TODO at the push's await leads with the worker-thread reply and orders the next optimizer step after the stage on the device. The end-of-loop TODO keeps the pull's never-read error. The push stream's comment says why it stays.
|
Reply from claude: Addressed the review in e67e429 (comments only, no behavior change):
On the 27B question: not measured yet. There, the push adds 0.12 s per step with a ready batch, and main waited 0-3.4% of a ~45 s step for the pull (up to ~1.5 s, cause not checked). A 10-step A/B on the default transport is owed before merge. @claude please review the new commit. |
|
Claude finished @felipemello1's task in 1m 32s —— View job Needs discussion: e67e429 resolves the three inline comments from the last review, but the empty human-written summary, tushar00jain's open change request and the 27B A/B are still open. Review |
There was a problem hiding this comment.
Verdict: Needs discussion -- e67e429 resolves all three inline comments from the last review. The two blocking items haven't changed: the empty human-written summary and tushar00jain's open change request. The 27B A/B is also still owed.
What the new commit does. It changes comments only, with no behavior change:
- The TODO at the push's await now leads with the reply from the worker thread. It says to order optimizer N+1 after the stage on the device, and names
timing/step/blocking_trainer_push_model_state_dictas the signal to act on. - The TODO at the end of the loop has the "nobody reads its error" clause back for the pull.
- The push-stream comment now says why the stream stays.
Earlier review, at HEAD
controller.py:1427TODO wording: resolved.controller.py:1488pull error that is never retrieved: resolved.trainer.py:204why the push stream exists: partly resolved. See the inline comment. The new reason ("skip compute-stream work queued after this point") is empty today, becauseoptim_stepsyncs the host after this call (.tolist()indist_mean, thengrad_norm.item()). The stream is kept only for the TODO, and the comment should say so.
Must fix
- PR description -- "Summary (human-written)" is still empty. The author needs to write it.
- tushar00jain's CHANGES_REQUESTED is still open. This version drops the push-vs-forward/backward overlap on purpose. On a step whose batch is already ready, the step waits for the whole push: about 0.12 s with the default transport, about 0.4 s with TorchStore at 27B, and up to about 1.7 s with delta sync. He needs to accept that cost, or ask for the reply from the worker thread.
- Run the 10-step A/B on the 27B default-transport setup that the author says is owed before merge, and put
timing/step/total(and the blocking pull/push timings) in the description. The gain at that scale is still unmeasured: main's 0-3.4% pull wait has no known cause.
Should consider
trainer.py:205-- the push-stream comment describes a saving that doesn't happen today (inline).
Details
I re-checked only the new commit; the ordering analysis from the previous review still applies, because e67e429 doesn't touch code. The new TODO's claims match the code:
- With a
ModelStateDictTransport, the push isstageon the push stream plusstream.synchronize(trainer.py:476-482). A device-side event before optimizer N+1 would be enough. - The TorchStore path calls
ts.put_state_dictfrom a worker thread (trainer.py:490-512), so it still needs a host wait.
A maintainer still needs to review. Not verified: no GPU run of this version.
optim_step syncs the host (grad_norm.item(), and dist_mean with DP) before the push starts, so no compute-stream work is queued for the push to skip.
|
Reply from claude: Fixed the last inline comment in 46c0501: the push-stream comment now says it saves nothing today ( tushar00jain approved. The human-written summary is the author's, and the GPU A/B is still owed before merge. @claude please review the new commit. |
|
Claude finished @felipemello1's task in 40s —— View job Approve -- please address the items below before merging: 46c0501 fixes the last inline comment. The human-written summary and the 27B A/B are still owed. Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. 46c0501 resolves the last inline comment, and tushar00jain's change request is now an approval. The two items left are the author's to do and need no further code review.
What the new commit does. It changes one comment, in trainer.py:204-207, and no code. The comment now says the dedicated push stream saves nothing today, and that it is kept for the TODO in Controller._trainer_loop.
Earlier review, at HEAD
trainer.py:205push-stream comment: resolved. I checked the claim againstoptim_step._mark_model_state_dict_ready_for_push()runs at line 388. After it,float(grad_norm.item())at line 422 always syncs the host, and with DP so doesdist_meanat line 395. So the compute stream is drained before push N starts, and forward/backward N+1 isn't sent until push N ends.- tushar00jain's CHANGES_REQUESTED: resolved. He approved on 2026-11-20.
- The ordering analysis from the earlier review still applies. Neither e67e429 nor 46c0501 touches code.
Must fix
- PR description -- "Summary (human-written)" is still empty. The author has to write it.
- Run the 10-step A/B on the 27B default-transport setup that the author says is owed. Put
timing/step/totaland the blocking push and pull timings in the description. Main's 0-3.4% pull wait at that scale has no known cause, so the net gain there is still unmeasured. If the A/B shows a net loss, this approval no longer holds.
A maintainer still needs to review: tianyu-l's approval was for the earlier worker-thread-reply version.
Not verified: no GPU run of this version.
Summary (human-written)
Agent details
TLDR: The trainer's weight push N replies from the trainer's event loop, and forward/backward N+1 holds that loop until it ends. When push N outlasts the time until forward/backward N+1 starts (~20 ms at Qwen3-0.6B), its reply and the generators' pull start one forward/backward late. The controller now awaits the push right after the optimizer step and the wait for the previous pull, then starts the pull in the background. Cost: the push itself, 0.022 s per step at Qwen3-0.6B and 0.12 s next to a 45 s forward/backward at Qwen3.5-27B.
Problem
Trainer.forward_backwardhas noawait, so it holds that loop until it ends.Solution
Controller._trainer_loopawaits the push inline, after the wait for pull N-1. Only then does it start pull N -> release groups in the background._start_push_model_state_dictand the pull'safter=argument.metrics.py: the comment on the blocking push ratio now says it is the whole push.Results
Numerics: the trainer's math is unchanged. When the push would lose the race, generators load policy N one forward/backward earlier.
Metrics:
timing/step/blocking_trainer_push_model_state_dictis now the whole push.timing/weight_sync/trainer_push_model_state_dictis logged at its own step, not one step late.trainer_push_model_state_dictspan in the loop:blocking_trainer_push_model_state_dictcovers the same time.You may ask:
after=and a push metric one step late.push_taskandafter=(delta sync among them). Whichever lands second rebases.NOTE:
Test plan
test_forward_backward_waits_for_the_previous_push: push 1 ends beforefwd_bwd 2. Fails on main.test_push_time_is_logged_at_its_step_and_pull_time_one_step_late. Fails on main.pytest tests/rl/unit_tests/cpu: 685 passed, 7 skipped, on this PR and on main.pre-commit runon the changed files: clean. Pyrefly was skipped; its config excludestorchtitan/rl/and tests.