Repository navigation
[rl] A streamed forward_backward call starts its RDMA reads when it arrives - #5764
Conversation
…rrives With stream_microbatches, the controller sends call k+1 while call k runs. Trainer.forward_backward never awaited, so call k+1's body, and with it its first RDMA read, started only after call k returned: every call's first read was exposed. Now: - RDMAMicrobatchPrefetcher submits its first reads in __init__. close() cancels the reads not started, also for a prefetcher that was never iterated. - forward_backward checks the RDMA identities and creates its prefetcher when the call arrives. Then it takes a first-in, first-out asyncio.Lock around the engine work and the metric collectives, so every rank issues the collectives in the same order. - It waits for the GPU in asyncio.to_thread. The event loop is free during that wait, so a queued call checks its microbatches and starts its reads then. - Busy time starts after the lock is taken, so a queued call does not also count the running call's GPU wait. The step's first call's first read stays exposed (the controller's TODO).
# Conflicts: # torchtitan/rl/trainer/trainer.py
… test on events - forward_backward makes one prefetcher per engine call on arrival, also for a split first call. Their first reads then share the link, and the code is simpler. - push_model_state_dict's docstring says push can also start while forward_backward waits for the GPU, and why that is safe. - The close() test holds read 0 until read 1 is cancelled, instead of a 0.2 s sleep. - Clearer comment on why step_started is current when a call arrives.
# Conflicts: # torchtitan/rl/trainer/trainer.py
…; loop over the engine inputs
# Conflicts: # tests/rl/unit_tests/cpu/test_trainer.py # torchtitan/rl/trainer/trainer.py
|
Reply from claude: Third follow-up: a streamed forward_backward call starts its RDMA reads when it arrives. Most of the trainer.py diff is re-indentation; review with whitespace hidden. @claude please review |
|
Claude finished @felipemello1's task in 4m 5s —— View job Approve -- please address the items before merging (fill in the human-written summary; a maintainer still needs to review): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The design is the smallest one that hides a streamed call's first read. To start its reads early, a queued call has to run while the previous call waits, so the previous call must yield (the to_thread sync). The lock then keeps the metric collectives in the same order on every rank. I found no correctness bug. This touches the RL trainer's core call path, so a maintainer still needs to review it.
What this PR does. RDMAMicrobatchPrefetcher now submits its first 2 reads in __init__, and a new close() cancels the queued reads. Trainer.forward_backward checks the RDMA identities and builds its prefetchers before taking a FIFO asyncio.Lock. Inside the lock it runs the engine calls, then waits for the GPU with asyncio.to_thread(stream.synchronize), then reduces the metrics. While call k waits for the GPU, queued call k+1 runs up to the lock, so its first reads overlap call k's GPU work.
Example. Streamed step, 2 calls in flight, one RDMA microbatch per group:
before: call 0 engine launch | sync inside dist_sum (loop blocked) | return
call 1 | read 0 (GPU idle) | engine ...
after: call 0 engine launch | to_thread(sync), loop free | metrics | return
call 1 | check ids, read 0 + read 1 | wait for lock -> engine (read 0 already done)
Must fix
- PR description: the "Summary (human-written)" section is empty. The author needs to write it.
Should consider
torchtitan/rl/trainer/trainer.py:353-- other endpoints can now run in the middle of a call;optim_stepordering depends only on the controller (inline).torchtitan/rl/trainer/trainer.py:325-- thestep_startedcomment can give the direct reason (inline, with a suggestion).
Questions
trainer.py:368: before this PR,torch.accelerator.current_stream(engine.device)ran only on ranks without the last pipeline stage. Now it runs on every call.Trainer.__init__still has adevice.type == "cpu"branch (line 157). Is a CPU-device trainer still supported end to end? Every CPU unit test now has to patchcurrent_stream. If CPU is unsupported, that branch could go. If it is supported, this call probably raises on CPU (unverified).
Details
- Gate. The problem is real on the base branch:
forward_backwardnever awaited, so a queued call started only after the previous call returned, and its first read was always exposed. The measured end-to-end gain on dapo_math is small (0.15-0.3 s of ~97 s). The gain grows when the trainer, not generation, is the bottleneck: each call's first read (~0.15 s) is then exposed. The cost is +48/-26 lines of logic plus one new concurrency invariant (first inline comment). - Collective order. Every collective in
forward_backward(FSDP inside the engine,dist_sum/dist_maxin the metric reduction) runs while the lock is held. Python 3.12'sasyncio.Lockdoesn't let a new caller take the lock ahead of queued waiters, and Monarch starts queued calls in send order. So every rank issues them in the same order. - Push during the GPU wait. The staging stream's dependency on the optimizer is recorded in
optim_step(_mark_model_state_dict_ready_for_staging), not when the push starts.stream_contextdoesn't stay entered across anawait. A push that starts during the wait therefore neither waits for call N+1's kernels nor redirects them. The FSDP host state during the wait is the same as between calls, which was already allowed. The PR's claim holds. - Busy time.
forward_backward_startmoved inside the lock, so a queued call doesn't count the running call's GPU wait. The new explicit sync replaces the implicit one in the firstdist_sum(...)on last-stage ranks, so the measured interval covers the same work. - Error path.
close()is idempotent (shutdowntwice is fine). On a failed call, the trainer'sfinallyblocks the event loop until the running read finishes; the iterator already did this before the PR. A queued call still runs after a failed one, also as before. - Tests. Both new tests guard real invariants: a queued call reads during the GPU wait, and
close()cancels the queued reads of a prefetcher that was never iterated. The edits to the existing tests are mechanical: lock attributes, thecurrent_streampatch, and recording groups inside_effect, because a closed prefetcher can't be iterated again.
Not verified: GPU behavior of Stream.synchronize from a worker thread, and the CPU-device question above.
| ) | ||
| try: | ||
| # One call at a time, so every rank issues its metric collectives in the same order. | ||
| async with self._forward_backward_lock: |
There was a problem hiding this comment.
Before this PR, forward_backward never yielded, so no other trainer endpoint could run in the middle of a call. Now every @concurrent_endpoint (optim_step, push_model_state_dict, sync_log_step, close, ...) can run during the to_thread GPU wait. The lock only orders forward_backward calls against each other. Today optim_step is safe only because the controller exits its TaskGroup (controller.py:1146) before sending it. Nothing in the trainer enforces that. A future controller change that sends optim_step early would step the optimizer on partial gradients and issue its grad-norm collectives in the middle of the metric collectives.
Smallest fix: wrap the body of optim_step in async with self._forward_backward_lock: (one line plus re-indent; the lock is uncontended today). Then "optimizer after every queued forward_backward" is an invariant the trainer owns. If you'd rather keep relying on the controller, the docstring here or in system.py should at least list which endpoints may run during the GPU wait.
| # `step_started` is current here. The controller sends the step's first call after | ||
| # optim_step returns, and call k only after call k-2 returned. By then call k-1 holds the | ||
| # lock and has run its engine call. |
There was a problem hiding this comment.
The conclusion is right, but the reason given is indirect. It also depends on event-loop scheduling: after call k-2 releases the lock, call k-1's waiter has been woken but has not yet run. The direct reason is simpler. The step's first call arrives after optim_step returns, so it takes an uncontended lock, and asyncio.Lock.acquire doesn't yield when the lock is free. That call then runs its engine call before its first await. So every later call of the step sees step_started set.
| # `step_started` is current here. The controller sends the step's first call after | |
| # optim_step returns, and call k only after call k-2 returned. By then call k-1 holds the | |
| # lock and has run its engine call. | |
| # `step_started` is current here: the step's first call arrives after optim_step returns, | |
| # takes the free lock without yielding and runs its engine call, so later calls see it set. |
…ay limit) into w138/f2 # Conflicts: # torchtitan/rl/trainer/trainer.py
…/5-rdma-reads-on-arrival Conflicts: - rl/trainer/trainer.py forward_backward: this PR's structure (prefetchers made on arrival, the lock, the GPU wait off the event loop); each engine call's FLOPs add to the step's total. - push_model_state_dict docstring: main's push stream and direct TorchStore put (#5659), plus this PR's note that the push can start while forward_backward waits for the GPU. - RL test_trainer.py: main's push test needs ANY again; FLOPs plumbing in the queued-call test.
…ches/5-rdma-reads-on-arrival
…-reads-on-arrival
…007cc z-loss) into stream-microbatches/5-rdma-reads-on-arrival
… dead flag reset) into stream-microbatches/5-rdma-reads-on-arrival
…microbatches/5-rdma-reads-on-arrival
…am-microbatches/5-rdma-reads-on-arrival Conflict: this PR restructures Trainer.forward_backward; the TODO goes above its loop.
…er override; agent self-review; rl/transport (#6407) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it approved, 30 then got a formal "request changes" from a maintainer, and about 20 more got substantive inline asks. In nearly all of them the bot either saw the problem and approved anyway, or never asked the questions maintainers ask most ("does the repo already do this?", "who should own this?"). The opposite failure, the bot blocking something a maintainer was fine with, is rare: in the PRs we sampled, 2 of its 81 must-fix items were wrong and about a third were minor (the empty human-written summary was the biggest source). **Example** (#6112, controller sizes the rollout worker pool): ``` before: bot approved 10 times; tianyu-l then blocked: "the controller reads rollouter.rollouts_per_worker to compute a count it hands back to the Rollouter -- violates encapsulation" after: same commit, new skill -> Request changes, must-fix #1: "controller.py:589 -- wrong owner for the worker count ..." ``` There was also no way for a code owner to overrule the bot except dismissing its review in the GitHub UI, and a later `@claude review again` would block again. ## What changed **Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`): - Verdict rules: Approve only when every remaining item is an edit the bot could write itself. Anything the author still owes (a design change, an unexplained golden change, evidence the PR rests on) is Request changes; anything only a maintainer can decide is Needs discussion. A hedge like "a maintainer should decide" can't come with Approve. - Always must-fix: a violated written rule, a silent wrong result, a second definition of an existing concept, a gate finding. - Design gate: new questions for the existing counterpart, in-repo ownership, and the design behind a bug; "ban only what doesn't work on main"; read the numbers behind a claim. The overlapping-PR search is mandatory and reported. - Re-review covers every commit since the last full review, including code taken from the bot's own suggestions. A scoped question gets a `COMMENT`, not a whole-PR verdict. - The bot fact-checks its own proposed fixes, and cites a source for claims about external tools or marks them unverified (never must-fix). - An empty "Summary (human-written)" is a one-line "Before merge" note that never affects the verdict. - Checklist: config ownership direction, general shared wrappers, dead code the PR creates, model variants as flavors, a mechanical pass over every new or changed function. **Code owner override** (`SKILL.md`, `claude-code.yml`, `CONTRIBUTING.md`): a code owner comments `@claude override` (optionally `@claude override 2,3: <reason>`); the bot approves if nothing else is open and doesn't re-raise the overridden items. A code owner's GitHub approval or "LGTM" is not an override, so a teammate can approve without the bot dropping its findings. Dismissing the bot's review still unblocks the PR, but isn't an override: the bot can't tell who dismissed it. **Agent self-review** (`CLAUDE.md`, `pr-description`): an agent preparing a PR runs `pr-review` in branch mode first and records unaddressed items in an optional "Self-review" section. PRs written without an agent are unaffected; a missing section is never a finding. Where each new rule comes from (maintainer asks the bot missed): | Change | PRs | | --- | --- | | No Approve with open design/evidence items or a "maintainer should decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 | | Author waiver can't clear a must-fix | #6201, #6202, #6203 | | Existing counterpart; one source of truth | #5228, #6169, #5881, #5823, #5824, #6059, #5812 | | Responsibility owner; config ownership direction | #6112, #6332, #5802, #5803, #6325 | | Fix the design behind the bug; a TODO doesn't justify a workaround | #5572, #5689, #5657 | | Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819, #5543 | | Re-review covers all new commits; scoped asks don't approve | #5824, #5842 | | Mandatory overlap search | #5885, #6248 | | Ban only what doesn't work on main | #5543 | | Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868 | **Rules**: `design.md` gets the one-general-wrapper rule (moved from `models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the consumer owning its values; `config.md` gets ownership direction and "a Config doesn't read runtime state"; `direction.md` calls all-to-all the MoE reference implementation, so a new vendor-specific dispatch path (e.g. #6242) needs a reason the existing backends can't serve. **Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/` -> d4l3k. **Mechanical, skim**: `torchtitan/rl/transport/` holds data movement between RL actors. - `rl/model_state_dict_transport.py` -> `rl/transport/model_state_dict.py` - `rl/MODEL_STATE_DICT_TRANSPORT.md` -> `rl/transport/MODEL_STATE_DICT_TRANSPORT.md` - `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py` - tests: `tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py` -> `tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py` - imports, READMEs and `scripts/install_rl_env.sh` updated; no code changes. ## User-facing changes | Before | After | | --- | --- | | Overrule the bot: dismiss its review in the UI, and it blocks again on the next run | `@claude override [items]: <reason>`; the bot approves and doesn't re-raise them | | Empty human-written summary: bot must-fix | One "Before merge" line, no effect on the verdict | | `from torchtitan.rl.model_state_dict_transport import ...` | `from torchtitan.rl.transport.model_state_dict import ...` | | `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from torchtitan.rl.transport.rdma_microbatch import ...` | ## Testing Backtest: the new skill run locally (nothing posted) on each PR at the commit and thread state the bot originally saw. | PR | Bot then | New skill | What the maintainer asked | | --- | --- | --- | --- | | #6112 | Approve | Request changes | worker-count ownership (caught) | | #5837 | Approve | Request changes | apply to `dp_shard` too (caught) | | #5572 | Approve | Request changes | delete the injection design (caught) | | #6201 | Approve after author waived pins | Request changes, waiver ignored | pins broke GPU tests after merge (caught) | | #6007 | Approve | Request changes | fold K3.1 into K3 (caught) | | #5543 | Request changes: "ban it" | Request changes: keep main's path | don't break gpt-oss + DeepEP (fixed) | | #6144, #5905 (controls) | Approve | Approve | -- | | #6137 (control) | Approve | Needs discussion | -- (merge gate on an upstream API) | Code owner override, simulated on #6201: override by a code owner lifts the named item; `@claude override` from the author changes nothing; a code owner's "LGTM" approval followed by "review again" keeps Request changes. Transport move: 83 RL CPU unit tests pass locally (`transport/test_model_state_dict.py`, `test_trainer.py`, `test_engine_loop.py`). `transport/test_rdma_microbatch.py`, `test_generator.py` and `test_batcher_actor.py` fail to collect in my env on `origin/main` too (stale attention-gym / Monarch), so CI is the check for those. ## Known issues / follow-ups - Open PRs that edit the moved files rebase cleanly (git follows the renames), but new imports of the old module paths will break: #6309 (adds a delta transport that should live in `rl/transport/`), #6237, #6176, #6177, #5862, and drafts #6127, #6393, #6163, #5764. - The Actions bot can't read dependency source (e.g. SGLang); follow-up for the workflow. ## Self-review pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch mode diffs against `origin/main` and skips description findings before a description exists; the "Config doesn't read runtime state" rule no longer contradicts hardware validation; dismissal dropped as an override form (the bot can't tell who dismissed); `test_rdma_microbatch.py` added to the transport area. Not addressed: - One concern per PR -- the five changes ship together at the maintainer's request. - Open PRs touching the moved files -- listed above; the maintainer will coordinate.
Summary (human-written)
Agent details
TLDR: With streamed microbatches, a queued
forward_backwardcall now starts its RDMA reads while the previous call waits for the GPU. In a CPU model with dapo_math-like timings, the exposed read time over 6 calls drops from 0.902 s to 0.150 s. End to end the gain is small, an estimated 0.15-0.3 s of a ~97 s dapo_math step, because most calls already run while the trainer waits for generation.Numerics: no change. The engine gets the same calls in the same order. Only the host's wait for the GPU moved.
Problem
stream_microbatches, the controller sends call k+1 while call k runs.Trainer.forward_backwardnever awaited, so call k+1's body started only after call k returned.Solution
RDMAMicrobatchPrefetchersubmits its first 2 reads in__init__. The newclose()cancels the reads not started yet, also for a prefetcher that was never iterated.Trainer.forward_backwardchecks the RDMA identities and makes its prefetchers on arrival. Then it takes a first-in, first-outasyncio.Lockaround the engine calls and the metric collectives.asyncio.to_thread. During that wait, a queued call starts its reads.trainer/tokens_per_second, TFLOPS, MFU) starts after the lock is taken, so a queued call doesn't count the running call's GPU wait.Most of
trainer.py's diff (+88/-66) is re-indentation. With whitespace hidden it is +48/-26.Results
You may ask:
NOTE:
optim_stepreturns (existing TODO incontroller.py).push_model_state_dictcan now start during a call's GPU wait. It issues no collectives and copies on its own stream.forward_backwardtrace span now includes a queued call's wait for the lock. The engine's span inside it marks the work.Test plan
test_queued_forward_backward_reads_while_the_running_call_waits_for_the_gpu: call 1 must start its read before call 0 returns. It fails without this PR, and with only the trainer change.test_prefetcher_never_iterated_starts_reading_and_close_cancels_the_queued_reads: fails whenclose()doesn't cancel.