Skip to content

[rl] A streamed forward_backward call starts its RDMA reads when it arrives - #5764

Draft
felipemello1 wants to merge 24 commits into
felipemello1/stream-microbatches/4-segment-graphsfrom
felipemello1/stream-microbatches/5-rdma-reads-on-arrival
Draft

felipemello1 wants to merge 24 commits into
felipemello1/stream-microbatches/4-segment-graphsfrom
felipemello1/stream-microbatches/5-rdma-reads-on-arrival

Conversation

@felipemello1

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: With streamed microbatches, a queued forward_backward call 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.

before:   call k     | launch | GPU wait, event loop blocked |
          call k+1                                           | read 0 (GPU idle) | launch | GPU wait |
this PR:  call k     | launch | GPU wait, event loop free    |
          call k+1            | read 0, read 1               | launch | GPU wait |
prefetcher = RDMAMicrobatchPrefetcher(microbatches)  # before: reads start when the engine iterates it
                                                     # now: the first 2 reads start here
async with self._forward_backward_lock:  # new: first in, first out
    result = engine.forward_backward(microbatch_groups=prefetcher)
    await asyncio.to_thread(torch.accelerator.current_stream(engine.device).synchronize)  # new

Problem

  1. With stream_microbatches, the controller sends call k+1 while call k runs.
  2. Monarch starts queued calls in order. But Trainer.forward_backward never awaited, so call k+1's body started only after call k returned.
  3. The prefetcher started its reads when the engine first iterated it. So every call's first read was exposed, and the GPU sat idle during it.
  4. Cost: ~0.15 s per call for an 82 MB microbatch over TCP (0.5-0.65 GB/s per rank, 4 ranks reading at once).

Solution

  1. RDMAMicrobatchPrefetcher submits its first 2 reads in __init__. The new close() cancels the reads not started yet, also for a prefetcher that was never iterated.
  2. Trainer.forward_backward checks the RDMA identities and makes its prefetchers on arrival. Then it takes a first-in, first-out asyncio.Lock around the engine calls and the metric collectives.
  3. Inside the lock, it waits for the GPU in asyncio.to_thread. During that wait, a queued call starts its reads.
  4. Busy time (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.
  5. Unchanged: the engine runs the same calls in the same order.

Most of trainer.py's diff (+88/-66) is re-indentation. With whitespace hidden it is +48/-26.

Results

Numerics: no change. The engine gets the same calls in the same order.

CPU model of both behaviors: a real Monarch actor with a fake read and a fake GPU (a 1-thread executor).
Per call: one 0.15 s read, then 3 groups x 0.5 s of GPU, with a host sync between groups. 2 calls in flight, 6 calls.
                            before     this PR
exposed read, 6 calls       0.902 s    0.150 s (call 0 only)
wall time                   10.27 s    9.52 s   (GPU work alone: 9.36 s)
  • The timings follow dapo_math (Qwen3-4B-Base, 1 GB300 trainer): 505-578 ms of forward/backward per microbatch, vs ~0.15 s per read.
  • End to end, only the 1-2 calls after the step's last group add wall time: 0.15-0.3 s per step. This is an estimate, not a measurement.
RL run at the top of this stack: Qwen3-0.6B, 2 GPUs (trainer + generator), streaming + RDMA + lazy preprocessing
+ accelerator graphs + compile, 5 steps, 3-7 calls per step. Time each call waits for its next microbatch:
  each step's first call   37.8 ms mean over 5 calls (155 ms in step 1, 1-13 ms in steps 2-5)
  later calls              1.2 ms mean, 4.2 ms max, over 24 calls
  • W&B. Later calls' reads are hidden. Each step's first read is still exposed (NOTE). There is no before column: no run without this PR used this setup.

You may ask:

  • Why the lock? Without it, call k+1 would launch its engine work during call k's GPU wait. Ranks could then issue the metric collectives in different orders and hang.
  • Why not run the engine on its own thread? It would hide reads that take longer than a microbatch's GPU time. But every engine or CUDA endpoint would then have to run on that thread, because FSDP2 swaps unsharded parameters into the modules during forward. On dapo_math the GPU time (505-578 ms) is far above the read (~0.15 s).

NOTE:

  • Still exposed: each step's first call's first read. The controller sends that call only after optim_step returns (existing TODO in controller.py).
  • The read leaks when a microbatch's GPU time is below its read time. Same CPU model with 0.15 s of GPU per group and a 0.2 s read: 0.449 s exposed over 6 calls, vs 0.200 s for call 0 alone.
  • Host memory: with 2 calls in flight, a rank holds up to 6 microbatches instead of 4 (~0.5 GB at 82 MB each).
  • A split first call (graphs with HSDP or deferred reduction) makes both prefetchers on arrival, so their first reads share the link. No recipe uses that combination today.
  • push_model_state_dict can now start during a call's GPU wait. It issues no collectives and copies on its own stream.
  • The trainer's forward_backward trace span now includes a queued call's wait for the lock. The engine's span inside it marks the work.

Test plan

# At this head, CPU (the same command across this stack)
pytest tests/rl/unit_tests/cpu torchtitan/experiments/torchft/tests tests/unit_tests/cpu/{test_trainer.py,\
models/common/test_aux_loss.py,observability/test_sdc_replayer.py,config/test_config_validation.py,\
distributed/test_accelerator_graph.py,test_integration_test_definitions.py,components/test_invalid_loss.py}
       # 696 passed, 9 skipped
  • New 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.
  • New test_prefetcher_never_iterated_starts_reading_and_close_cancels_the_queued_reads: fails when close() doesn't cancel.

Felipe Mello added 8 commits November 2, 2026 16:58
…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
# Conflicts:
#	tests/rl/unit_tests/cpu/test_trainer.py
#	torchtitan/rl/trainer/trainer.py
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 3, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 3, 2026
@felipemello1
felipemello1 added this pull request to stack #5762 November 3, 2026 06:35
@felipemello1

Copy link
Copy Markdown
Contributor Author

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

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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

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

  1. 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_step ordering depends only on the controller (inline).
  • torchtitan/rl/trainer/trainer.py:325 -- the step_started comment 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 a device.type == "cpu" branch (line 157). Is a CPU-device trainer still supported end to end? Every CPU unit test now has to patch current_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_backward never 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_max in the metric reduction) runs while the lock is held. Python 3.12's asyncio.Lock doesn'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_context doesn't stay entered across an await. 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_start moved 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 first dist_sum(...) on last-stage ranks, so the measured interval covers the same work.
  • Error path. close() is idempotent (shutdown twice is fine). On a failed call, the trainer's finally blocks 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, the current_stream patch, and recording groups in side_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:

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.

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.

Comment on lines +325 to +327
# `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.

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.

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.

Suggested change
# `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.

Felipe Mello added 16 commits November 3, 2026 00:03
…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.
…007cc z-loss) into stream-microbatches/5-rdma-reads-on-arrival
… dead flag reset) into stream-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.
tianyu-l added a commit that referenced this pull request Nov 26, 2026
…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.

This branch has not been deployed

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

Labels

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.

1 participant