Skip to content

[rl] Finish the weight push before forward/backward - #5235

Merged
felipemello1 merged 24 commits into
mainfrom
felipemello1/weight-push/2-finish-push-before-forward-backward
Nov 20, 2026
Merged

felipemello1 merged 24 commits into
mainfrom
felipemello1/weight-push/2-finish-push-before-forward-backward

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

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.

main: if push N outlasts the ~20 ms until forward/backward N+1, its reply waits for forward/backward N+1, so pull N starts late (a 0.06 s TorchStore push cost a 0.15 s pull wait per step, 8%, Qwen3-0.6B, main on Nov 3; today's 0.014 s push ends in time). This PR: the controller awaits push N first, so pull N runs during forward/backward N+1.

# before: push N runs in the background, and pull N waits for its reply
push_task = self._start_push_model_state_dict()
pull_task = asyncio.create_task(
    self._pull_model_state_dict_and_release_groups(optimizer_result.policy_version, after=push_task)
)

# after: push N ends before forward/backward N+1 is sent
await self.trainer.all_ranks.push_model_state_dict.call()
pull_task = asyncio.create_task(
    self._pull_model_state_dict_and_release_groups(optimizer_result.policy_version)
)

Problem

  1. Background push. After optimizer N, the controller starts push N -> pull N in the background. It sends forward/backward N+1 as soon as batch N+1 is ready.
  2. One event loop. The trainer actor runs every endpoint on one asyncio loop. Trainer.forward_backward has no await, so it holds that loop until it ends.
  3. A race. Push N waits for its GPU -> CPU copy in a worker thread, then replies from the loop. With batch N+1 ready, forward/backward N+1 starts about 20 ms after push N, so a longer push replies only after forward/backward N+1.
  4. Late pull. Pull N, and then the release of the next rollout groups, start on that reply: one forward/backward late. The trainer then waits for pull N after optimizer N+1.
  5. How much. Qwen3-0.6B, 1 trainer GPU + 1 generator GPU (GB300), next batch ready in 8 of 8 steps. main on Nov 3 (TorchStore push, 0.06 s): the trainer waited 0.15 s per step for the pull, 8% of a 1.85 s step. Today's main (default transport): the push ends after 0.014 s, before forward/backward N+1 starts at 0.021 s, and the trainer never waits. Qwen3.5-27B's stage alone takes 0.12 s.

Solution

  1. Controller._trainer_loop awaits the push inline, after the wait for pull N-1. Only then does it start pull N -> release groups in the background.
  2. The pull still overlaps forward/backward N+1. Nothing overlaps the push.
  3. Removed: _start_push_model_state_dict and the pull's after= argument.
  4. metrics.py: the comment on the blocking push ratio now says it is the whole push.
  5. Unchanged: pull N-1 ends before push N starts, the trainer's push code, and every metric name.

Results

Numerics: the trainer's math is unchanged. When the push would lose the race, generators load policy N one forward/backward earlier.

A/B, main vs this PR, today's default transport. Qwen3-0.6B AlphabetSort, 1 trainer GPU + 1 generator GPU (GB300),
10 steps, next batch ready in steps 2-9. Medians of steps 2-9, in seconds:
                                              main    this PR
  blocking_trainer_push_model_state_dict      0.000   0.022
  blocking_generator_pull_model_state_dict    0.000   0.000
  step time outside forward/backward          0.017   0.040    (+0.023: the push)
  forward_backward                            1.48    1.68     (different rollouts in each run)
  total                                       1.50    1.72
Here main's push wins the race, so this PR costs 0.022 s per step (1.5% of a 1.5 s step) and gains nothing.

Cost at scale: the step waits for the whole push when batch N+1 is ready. Otherwise the push replaces part of the
wait for the batch.
  ModelStateDictTransport (default):
    Qwen3.5-27B, 2 GB300 hosts, trainer FSDP 2 x TP 2    stage alone 0.12 s     forward/backward 44.5-45.3 s
    Muse Spark, 18 GB300 hosts (10 trainer hosts)        push 0.33 s (median of pushes 2+)
  TorchStore (model_state_dict_transport=None, needed for gpu_fetch):
    Qwen3.5-27B, same setup, TorchStore arm              stage alone 0.39-0.41 s
From the runs in the PRs that added ModelStateDictTransport and made it the default.

Gain, when main loses the race (main on Nov 3, TorchStore push, same 0.6B setup):
  timing/step/blocking_generator_pull_model_state_dict   0.15 s per step (8% of a 1.85 s step)
  net of the push this PR now waits for (0.06 s): ~0.09 s
At Qwen3.5-27B, main waited 0-3.4% of each step for the pull. Its 0.12 s stage is longer than the 0.6B race window,
which fits a lost race. The window and this PR's gain at 27B are not measured.

Metrics:

  • timing/step/blocking_trainer_push_model_state_dict is now the whole push.
  • timing/weight_sync/trainer_push_model_state_dict is logged at its own step, not one step late.
  • The controller trace has no separate trainer_push_model_state_dict span in the loop: blocking_trainer_push_model_state_dict covers the same time.

You may ask:

  • Why not keep main's order, since its push wins the race at 0.6B? It wins by about 7 ms. A push over ~20 ms (TorchStore, 27B's stage, delta sync's compression) costs a whole pull instead.
  • Why not keep the push in the background and await it right before forward/backward (this PR's previous version)? It waits the same when the batch is ready, and needs a push task, the pull's after= and a push metric one step late.
  • Why not hide the push behind forward/backward? Its reply must get out while forward/backward holds the trainer's loop. The small way is a reply from the push's worker thread (an earlier version of this PR); the big way is forward/backward on its own thread, which brings back concurrent trainer endpoints. Both add threading for a 0.1-0.3 s push. The TODO at the await names both.
  • Why not let the next optimizer step wait only for the GPU -> CPU copy? With the default transport it needs no host wait at all: an event on the push stream can order the optimizer after the stage on the device. That only matters once the push overlaps forward/backward. Same TODO.
  • What if the push grows? Delta sync's stage plus compress (0.37-1.7 s at 27B) would cost a ready step up to ~1.7 s, 4-5% of forward/backward. On main, with a ready batch, the stage overlaps forward/backward but the compression starts only after it (from reading the code). Without a ready batch, both hide behind the batch wait. The TODO at the await is the fix once this matters.
  • Do other PRs touch these lines? Yes, a few open ones edit push_task and after= (delta sync among them). Whichever lands second rebases.

NOTE:

  • The A/B ran on one host: the pull used UCX over TCP and CUDA IPC, not RDMA. The 27B multi-host A/B is not run.
  • The branch keeps its earlier commits, so old review comments keep their anchors. A merge commit resets the tree to main; the commits after it hold the change.

Test plan

  • test_forward_backward_waits_for_the_previous_push: push 1 ends before fwd_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 run on the changed files: clean. Pyrefly was skipped; its config excludes torchtitan/rl/ and tests.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Oct 9, 2026
@felipemello1
felipemello1 added this pull request to stack #5236 October 9, 2026 18:04
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 9, 2026

@tushar00jain tushar00jain left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@felipemello1
felipemello1 force-pushed the felipemello1/weight-push/1-timing-kind-names branch from 64be4c5 to 530ac4d Compare October 11, 2026 19:54
@felipemello1
felipemello1 force-pushed the felipemello1/weight-push/2-finish-push-before-forward-backward branch 2 times, most recently from a2188a5 to 3fbae95 Compare October 11, 2026 21:32
@felipemello1 felipemello1 changed the title [rl] Finish the weight push before the next forward/backward (2/2) [rl] Reply to the weight push from its worker thread, so the pull overlaps forward/backward (2/2) Oct 11, 2026
@felipemello1
felipemello1 removed this pull request from stack #5236 October 12, 2026 04:32
@felipemello1
felipemello1 force-pushed the felipemello1/weight-push/2-finish-push-before-forward-backward branch from 3fbae95 to f3d3d73 Compare October 12, 2026 04:32
@felipemello1
felipemello1 changed the base branch from felipemello1/weight-push/1-timing-kind-names to main October 12, 2026 04:33
@felipemello1
felipemello1 added this pull request to stack #5304 October 12, 2026 04:33
@felipemello1 felipemello1 changed the title [rl] Reply to the weight push from its worker thread, so the pull overlaps forward/backward (2/2) [rl] Reply to the weight push from its worker thread, so the pull overlaps forward/backward (1/2) Oct 12, 2026
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.
@felipemello1
felipemello1 marked this pull request as ready for review October 12, 2026 04:39
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 12, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/weight-push/2-finish-push-before-forward-backward branch from f3d3d73 to 3fd5850 Compare October 12, 2026 04:39

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

oh nice finding, the idea makes a lot of sense to me. Will trigger a claude to help confirm no other side effects.

@tianyu-l

Copy link
Copy Markdown
Contributor

@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

claude Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 4m 51s —— View job


Review of #5235: replying to the weight push from its worker thread

  • Gather diff and context
  • Analyze out-of-order actor control (concurrency, ordering, errors, extremal cases)
  • Post review

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 forward_backward N+1, as on main. So the concern in the earlier CHANGES_REQUESTED review applies to this PR's first version (await the push before fwd/bwd), not to the current diff. Below I check each invariant against the earlier reply, then list the extremal cases and a few small suggestions.


1. Invariants with the earlier reply

All trainer endpoints are @concurrent_endpoint, so the only ordering on the trainer comes from the controller's awaits plus the single asyncio loop. With this PR the controller can now see "push N done" while forward_backward N+1 still holds the trainer's loop. Here is what depends on that reply:

Invariant Who enforces it Still holds?
The GPU->CPU copy of push N is done reading params before optimizer N+1 changes them staging_complete.synchronize() runs before the put, which runs before on_published (trainer.py:416-427). The controller's wait_prev_push() comes before optim_step (controller.py:1160) ✅ The reply still comes after the sync
Staging stream is ordered after optimizer N _mark_model_state_dict_ready_for_staging() in optim_step ✅ Unchanged
Pull N reads a complete policy N _generator_pull_and_release_buffer_slots awaits push_task, which is .call() over all trainer ranks. Each rank replies only after its own put ✅ The pull still starts after every rank's put
Push N+1 doesn't overwrite _staging_state_dict or the TorchStore key while pull N reads them wait_prev_pull() comes before start_async_push_pull (controller.py:1190-1195) ✅ Unchanged
Push N's worker thread is done with _staging_state_dict before push N+1 writes it on_published is the last thing in the thread (trainer.py:425-427) ✅ The comment there captures this. Please keep it last
Born-fresh rollouts release_active_groups runs after the pull ✅ Unchanged

What's new is a short window in which push N's coroutine is still alive on the trainer (waiting for to_thread to resume after fwd/bwd N+1 ends) while the controller is already moving on. I traced what can run in that window:

  • optim_step N+1: can't start before fwd/bwd N+1 returns (they share the loop). Push N has no work left after the thread except leaving the span. ✅
  • push_model_state_dict N+1: needs pull N first. In theory it can land on the loop before push N's coroutine resumes (both are queued behind fwd/bwd). The only shared state is _staging_state_dict, and the thread is already done with it. Two push_model_state_dict spans may overlap in the trainer trace. This is cosmetic only (spans are per-task through contextvars).
  • model_state_dict (the local inside push N) now stays alive until after fwd/bwd N+1. On main this was also the case in the slow case. No change in peak memory.

2. Extremal cases

  1. Push message runs after forward_backward N+1 on the trainer. This can happen if both messages are queued and the trainer loop is busy. The push then starts after fwd/bwd, as could already happen on main, and simply overlaps less. It's slower but correct. In the real loop the sync_log_step.call() await separates the push send from the fwd/bwd send, so the push normally gets to to_thread first.
  2. Multi-rank, partial failure. Say rank 0 replies and rank 1 calls port.exception(...). .call() raises ActorError and the pull never starts, which matches main. The actor isn't marked failed in either case. ✅ The CPU test uses only 1 proc, so the mesh case (explicit port plus .call() collecting replies from N ranks) has no CPU coverage. It's worth a 2-proc variant if that's cheap.
  3. NaN break / packed is None / last step. Each of these goes through wait_inflight_push_pull() before teardown. ✅
  4. Controller fails while a push thread is in flight (e.g. forward_backward raises ActorError). The worker thread can't be cancelled, so it will still call port.send after the caller is gone. If that raises, the except calls port.exception, which will likely also raise. The coroutine then fails out of an explicit-port endpoint, which is an actor fault during teardown. Main has a similar teardown race (its implicit reply also fails). The difference is that the failure now starts in a non-actor thread. Low severity, but worth knowing.
  5. asyncio.CancelledError / BaseException. These aren't caught by except Exception. With an explicit port, Monarch won't reply for you, so the caller gets no reply from that rank. This only matters at actor stop, but it's a change: before, Monarch's own handler replied.
  6. Undocumented Monarch contract. Port.send from a non-actor thread works today. The CPU test pins this on 0.6.0/0.7.0, which is the right mitigation. Consider a one-line comment at the endpoint pointing at that test, so whoever upgrades Monarch knows what to look for.

3. Suggestions (non-blocking)

  • Don't reply twice. After on_published succeeds, the endpoint still runs the span exit and the return. If anything there raises, the code calls port.exception on a port that already replied. Depending on Monarch, that either drops silently or raises an unhandled fault, and the fault would exit the controller even though the push succeeded. A small flag avoids this (monarch_actors/trainer.py:73-77):
    published = False
    def on_published() -> None:
        nonlocal published
        port.send(None)
        published = True
    try:
        await super().push_model_state_dict(on_published=on_published)
    except Exception as e:
        if published:
            raise
        port.exception(ActorError(e))
    This is low probability. I'd still prefer it, because the failure mode (controller process exit) is out of proportion to the cause. Fix this ->
  • on_published: ... | None = None in Trainer.push_model_state_dict. The only production caller is the actor endpoint, which always passes it. Under the CLAUDE.md rule against speculative defaults, consider making it required. You'd then have to update the existing direct-call unit test (test_push_model_state_dict_stages_on_dedicated_cuda_stream) to pass lambda: None. Optional.
  • The test depends on timing. It relies on 0.1 s vs 2 s sleeps and on message order between two ensure_futures. The margin is large, so it's probably fine on CI. If it ever flakes, have forward_backward block on a threading.Event that the test sets after the push reply arrives, instead of sleeping.
  • Perf note for large models. Pull N now actually overlaps fwd/bwd N+1. Your own data shows one fwd/bwd at 3.36 s vs ~3.02 s next to a 2.57 s pull. For large models where the pull's TCP/host-memory traffic shares a NIC or host with the trainer, that contention could grow. It would be good to call out in WEIGHT_SYNC.md that the overlap trades a small fwd/bwd slowdown for removing the pull wait.

Summary

Under 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 synchronize -> put -> reply inside the thread and on the controller's existing wait_prev_push and wait_prev_pull awaits, and this PR leaves all of those alone. The remaining risks are in error and teardown paths (a possible double reply, CancelledError, a send after the caller is gone) and the undocumented cross-thread Port.send. None of them is a correctness issue on the happy path.

I didn't run the tests. I also couldn't inspect the installed torchmonarch source to confirm what Port does on a second send, so suggestion 1 is based on reasoning rather than on Monarch's code.

@tianyu-l

Copy link
Copy Markdown
Contributor

@felipemello1 please address claude review "3. Suggestions (non-blocking)" before merging

Felipe Mello added 2 commits October 12, 2026 08:18
- 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.
@felipemello1 felipemello1 changed the title [rl] Reply to the weight push from its worker thread, so the pull overlaps forward/backward (1/2) [rl] Reply to the weight push from its worker thread, so the pull overlaps forward/backward Oct 12, 2026
@felipemello1
felipemello1 removed this pull request from stack #5304 October 12, 2026 17:39
@felipemello1

Copy link
Copy Markdown
Contributor Author

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:

  1. Double reply: added the flag. With .call() the port takes one reply, so a second one already raised OncePortRef already used and failed the actor (probed). The flag keeps that outcome, but the actor now fails with the real error.
  2. on_published is required.
  3. Test: the actor runs in the test process (this_proc().spawn), and the fake forward_backward blocks on a threading.Event that the test sets after the push reply. No sleeps (10 s -> 0.03 s), no spawned procs. Split into a reply test (fails with main's endpoint) and an error test.
  4. WEIGHT_SYNC.md: the update reads from StorageVolumes on the trainer's processes, so it can slow forward/backward N+1.

From §2:

  • §2.5 was real: a CancelledError raised inside the put would have left the controller waiting forever. The endpoint now catches BaseException, so the caller gets an ActorError, as on main.
  • §2.2, §2.4, §2.6: no change. Every @concurrent_endpoint already replies per rank with port.send; only the calling thread is new, and the test covers it.

@felipemello1

Copy link
Copy Markdown
Contributor Author

@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

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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

Details

1. Correctness of the move

Push 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:

  • Staging finishes reading the params before optimizer N+1 writes them.
  • Pull N-1 finishes before push N starts.
  • Pull N starts only after every rank's put, because push_model_state_dict.call() (controller.py:1321) collects a reply from all ranks.

I also checked the exit and error paths:

  • A failing push now raises before forward/backward instead of before the optimizer step.
  • packed is None, the NaN break, and the final await push_task all still work. Awaiting a finished task twice is fine.

The tests were updated to match, and no .md file or test still claims the push overlaps forward/backward.

2. Why before forward/backward and not before the optimizer step

For 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 (actors/monarch/trainer.py:68-70), and forward_backward holds that loop. So if forward/backward N+1 starts before push N's put returns, the pull starts late again, wherever the await sits.

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 today

These are the steps of Trainer.push_model_state_dict (trainer.py:415-477):

Step Runs on Needed before optimizer N+1? Needed before pull N?
model.state_dict() and _stage_model_state_dict: queue the per-tensor copy_ into pinned buffers on the staging stream, casting to the generator dtype (the cast runs by default: training.dtype is float32, generator.model_dtype is bfloat16) actor loop (queueing) + GPU yes yes
staging_complete.synchronize() worker thread yes yes
ts.put_state_dict(...): a second CPU copy, from the pinned snapshot into TorchStore's StorageVolume (see the TODO at trainer.py:432), plus the TCP fallback transport worker thread no yes
reply actor loop -- yes

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 -> CPU

a) 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:

  • You can keep main's await before the optimizer step, and nothing blocks before forward/backward.
  • Staging and the put overlap forward/backward, which is what [rl] Stage trainer weight casts in pinned CPU memory #5107 intended and what tushar00jain asked for.
  • The pull still starts right after the put.

The cost is an explicit response port plus an on_published callback (about 20 lines). It also relies on Monarch accepting Port.send from a non-actor thread, which the CPU test pins.

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 trainer.py:432. If the GPU -> CPU copy wrote straight into the StorageVolume buffer, the put would shrink to publishing metadata, and this PR's await would be roughly the GPU -> CPU time. It needs a new TorchStore API, so it is longer term. It also combines with (a).

c) Quantization later. Run it on the GPU, on the staging stream, in _stage_model_state_dict's per-tensor loop, as the dtype cast is today. It then counts as part of the GPU -> CPU step and shrinks the bytes for both the copy and the put. If quantization instead runs on the CPU in the worker thread, it adds to this PR's wait. Under (a) it would also compete for the GIL with forward/backward's Python dispatch.

5. What this PR costs as it is

It 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:

  • about 0.08 s at Qwen3-0.6B
  • about 1.1 s at Qwen3.5-35B-A3B (from your microbenchmark)

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. timing/step/blocking_trainer_push_model_state_dict is the right metric to watch.

6. Minor

  • _mark_model_state_dict_ready_for_staging still records the staging dependency at optimizer time. With this PR, no forward/backward N+1 kernels can be queued before stage N, so the reason in the removed comment no longer applies. I'd keep the call anyway: it is harmless, and (a) needs it again. If you go with (a), restore the sentence you removed.
  • tushar00jain's request for changes was against this ordering (push before forward/backward), so the PR still needs his re-review.

I did not run the tests or anything on a GPU; this is from reading the code. There was no pr-review skill in this environment, so I posted the review in this comment.

Felipe Mello added 2 commits November 19, 2026 21:54
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.
@felipemello1
felipemello1 changed the base branch from felipemello1/weight-push/0-trainer-num-threads to main November 20, 2026 05:59
@felipemello1
felipemello1 marked this pull request as ready for review November 20, 2026 05:59
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude:

Reworked on today's main (4 files against main; the earlier commits stay so old comments keep their anchors).

  • The controller now awaits the push right after the optimizer step and the wait for pull N-1. Then it starts pull N in the background, so the pull still overlaps forward/backward N+1. Nothing overlaps the push.
  • The base is now main. This PR no longer stacks on the trainer thread-count change: the default transport's push is a cast plus a GPU -> CPU copy, with no copy on the CPU.
  • A TODO at the await names how to hide the push later: forward/backward on a thread, or a reply from the push's worker thread. Then the next optimizer step would wait only for the copy.

@tushar00jain this drops the overlap you asked for, on purpose:

  • The push is short with the default transport: 0.12 s next to a 45 s forward/backward (Qwen3.5-27B, 2 GB300 hosts), 0.33 s at 18 GB300 hosts.
  • With delta sync, a step with a ready batch would wait for stage plus compress: 0.37-1.7 s next to a 35-41 s forward/backward at 27B. On main, with a ready batch, the stage overlaps forward/backward, but the compression (0.10-0.17 s) starts only after it: the push's coroutine resumes on the trainer's event loop between the stream sync and the compression to_thread (from reading the code, not measured). Without a ready batch, both hide behind the batch wait, on main and with this PR.
  • The TODO at the await is the fix if the push grows enough to matter.

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, on_published, the threaded test) no longer apply. §3.4, the pull overlapping forward/backward, is below. Could you take another look?

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.

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

  1. PR description -- "Summary (human-written)" is empty. The author needs to write it.
  2. 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/total on 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 NaN break, and the last step. Each ends with await pull_task, so the generators hold the last pushed policy before validate_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.

Comment thread torchtitan/rl/controller/controller.py Resolved
Comment thread torchtitan/rl/controller/controller.py Resolved
Comment thread torchtitan/rl/trainer/trainer.py Resolved
Felipe Mello added 3 commits November 19, 2026 22:13
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.
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.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude:

Addressed the review in e67e429 (comments only, no behavior change):

  • The TODO at the push's await leads with the worker-thread reply, orders optimizer N+1 after the stage on the device, and names timing/step/blocking_trainer_push_model_state_dict as the signal.
  • The end-of-loop TODO keeps the never-retrieved pull error.
  • trainer.py: the push-stream comment says why the stream stays.

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

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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_dict as 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:1427 TODO wording: resolved.
  • controller.py:1488 pull error that is never retrieved: resolved.
  • trainer.py:204 why the push stream exists: partly resolved. See the inline comment. The new reason ("skip compute-stream work queued after this point") is empty today, because optim_step syncs the host after this call (.tolist() in dist_mean, then grad_norm.item()). The stream is kept only for the TODO, and the comment should say so.

Must fix

  1. PR description -- "Summary (human-written)" is still empty. The author needs to write it.
  2. 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.
  3. 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 is stage on the push stream plus stream.synchronize (trainer.py:476-482). A device-side event before optimizer N+1 would be enough.
  • The TorchStore path calls ts.put_state_dict from 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.

Comment thread torchtitan/rl/trainer/trainer.py Resolved
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.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude:

Fixed the last inline comment in 46c0501: the push-stream comment now says it saves nothing today (optim_step syncs the host first) and is kept for the TODO. Comments only.

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

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:205 push-stream comment: resolved. I checked the claim against optim_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 does dist_mean at 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

  1. PR description -- "Summary (human-written)" is still empty. The author has to write it.
  2. Run the 10-step A/B on the 27B default-transport setup that the author says is owed. Put timing/step/total and 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants