Skip to content

[rl] Add an opt-in RDMA fast path for trainer microbatches - #5285

Merged
felipemello1 merged 19 commits into
mainfrom
felipemello1/trainer-pull/1-microbatch-refs
Oct 15, 2026
Merged

felipemello1 merged 19 commits into
mainfrom
felipemello1/trainer-pull/1-microbatch-refs

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: Adds an opt-in RDMA fast path for trainer microbatches, async_loop.batcher.rdma_min_tensor_bytes: the batcher keeps tensors of at least that many bytes as Monarch RDMA buffers, and each trainer rank reads only its own column. A 5.2 GB step at dp 2 x tp 2 goes from 9.1-11.1 s to 3.3-5.1 s (CPU Monarch, one host, TCP), mostly from that column. None (the default) keeps main's by-value RPC.

Problem

  1. One message per step. The controller calls trainer.forward_backward with the step's whole [num_microbatches][dp_degree] grid of TrainingMicrobatch, by value.
  2. Every rank gets every column. Each rank keeps only row[dp_rank], so it unpickles dp_degree times the data it trains on.
  3. Extra per-token fields make it big. Main's fields are 38 B/token (~1.1 GB per rank for a 29M-token step); router replay plus top-32 logprobs make it 614 B/token.
  4. The run dies. In a router-replay run (replay is still a draft PR), main's step-3 call took 93-100 s to reach the last of 4 trainer ranks (17.8-19.9 GB each; at most 20.7 s at steps 1-2), and the job died on Monarch's 60 s proc-state timeout.

Solution

  1. MonarchRDMAMicrobatch (new torchtitan/rl/trainer/rdma_microbatch.py): register(microbatch, min_bytes=...) swaps each tensor of at least min_bytes, model_kwargs included, for an RDMABuffer handle; read() copies them into fresh tensors with one RDMA action; drop() releases them.
  2. Batcher: registers each batch right after packing (already in asyncio.to_thread) and keeps it until maybe_release_oldest_batch(). Each handle carries the batch, DP rank and position it was registered for.
  3. Training loop: no RDMA branch. It passes packed.microbatches either way and calls batcher.maybe_release_oldest_batch() in a finally.
  4. Trainer: checks each handle's batch, DP rank and position (ValueError on a mismatch), reads its column one microbatch at a time, and reports timing/trainer/read_microbatches/max.
  5. Unchanged: with None (the default) the grid goes by value, as on main, and the release is a no-op. Packing, the token counts, the loss, the engine, optim_step and weight sync are unchanged either way.
default:  controller --forward_backward.call(grid of TrainingMicrobatch)--> every trainer rank
opt-in:   batcher: register each batch after packing
          controller --forward_backward.call(grid of MonarchRDMAMicrobatch, ~0.8 MB)--> every trainer rank
          trainer rank: read its column out of band | train 0 | train 1 | ...
          batcher: drop the oldest batch's buffers after the call returns (or fails)

Results (all for the opt-in path)

Data path per step: packed batch -> every rank holds its column -> drop.

  • CPU Monarch, one host, TCP, 4 rank processes, 131,072-token microbatches; medians of steps 2-5, ranges are separate runs.
  • 614 B/token adds routed expert ids and top-32 logprobs in model_kwargs.
  • From an earlier benchmark copy that buffered every non-empty tensor; at 1 KiB only the 8 B token counts move into the message.
                                     by value      fast path      peak memory per rank
dp 2 x tp 2, 0.64 GB, 38 B/token     1.3 s         1.0 s          2.5 -> 0.2 GB
dp 2 x tp 2, 2.6 GB, 614 B/token     7.5 s         2.5 s          7.5 -> 1.3 GB
dp 2 x tp 2, 5.2 GB, 614 B/token     9.1-11.1 s    3.3-5.1 s      15-18 -> 2.6-3.1 GB
dp 4 x tp 1, 2.6 GB, 614 B/token     4.9 s         1.0 s          7.5 -> 0.7 GB
dp 1 x tp 4, 2.6 GB, 614 B/token     5.0 s         3.8 s          7.5 -> 2.4 GB

Most of the gain is the column (each rank reads 1/dp of the step), which the scatter PR later in this stack gets by value too:

2.6 GB step       by value, whole grid    by value, own column    fast path
dp 2 x tp 2       7.5 s                   3.0 s                   2.5 s
dp 4 x tp 1       4.9 s                   2.05 s                  1.0 s
  • At dp 1 x tp 4 there is no column to save; the fast path still wins (5.0 -> 3.8 s) by skipping the grid's pickle, copy and unpickle.
  • The real transport saving needs ibverbs: 25 vs 1.3 GB/s over TCP, reading 256 MiB on one host (CPU probe).
  • Router-replay GPU run from Problem 4 (multiple hosts), not a controlled A/B: a later job of the same recipe with an earlier version of this PR (resumed at step 10) trained steps 11-16, but with the proc-state timeout raised to 300 s. So it shows the handles work at this size, not that they alone avoid the timeout.

GPU, Qwen3-0.6B, H100, batch invariant, lockstep, trainer DP 1 + one TP 1 generator (2 GPUs), 4,096-token microbatches, 5 steps, ibverbs:

                     by value (default)   rdma_min_tensor_bytes=1024
loss/mean            bitwise equal at all 5 steps
read_microbatches    -                    126, 16, 5, 6, 7 ms at steps 1-5 (step 1 includes RDMA setup)
[RdmaXcel] lines     0                    0

The by-value run is from an earlier push (same config and seed). One earlier push read 203 and 102 ms at steps 2 and 4; its rerun and the previous head did not.

You may ask:

  • Why opt-in? RPC stays the one way to orchestrate. Over TCP most of the saving is the column, which the scatter PR gets by value; the transport saving needs ibverbs, which not every host has.
  • Why no transport switch? Monarch uses ibverbs where the host has it, else TCP. A host whose ibverbs devices fail doesn't fall back: MONARCH_RDMA_DISABLE_IBVERBS=1 forces TCP in every process, weight sync included.
  • Why a byte threshold? An 8 B token count costs more to register (~0.15 ms per buffer) than to send, and RDMABuffer rejects empty tensors. At 1 KiB, per-token tensors go out of band from 1,024 tokens up.
  • Why not overlap the reads? The prefetch PR in this stack does; it needs an opt-in TrainingEngine mode.
  • Why not gather the reads? Microbatch 0 would arrive no sooner than the whole column, and each RDMA action would last as long as the column (3.2 vs 0.17 s at 5.2 GB, dp 2 x tp 2), against its 60 s deadline. Only 0-19% faster (one host, TCP).
  • Why does the batcher own the threshold? It makes the microbatches and registers right after packing, off the training loop; the batcher-process PR moves this code into its own process unchanged.
  • Why one buffer per tensor, not one per microbatch or column? Packing costs a controller copy (0.3-0.8 s at 5.2 GB) and twice the step's memory, without cheaper registration; packed reads only tie at ≤16 MiB TCP chunks and are 1.3x slower at Monarch's default 64 MiB.
  • Why not TorchStore? TitanRL's store only accepts the weight sync's planned keys; a second store needs the deprecated ControllerStorageVolumes and cleanup on both sides.
  • Why no checksum of the bytes? Each batch gets fresh tensors that are never refilled, and is released only after every rank read it (or the step failed, which stops the run), so a read never sees another batch's bytes. The identity check covers a handle read twice or by the wrong rank.

NOTE:

  • CI integration runs go by value (the default). The fast path is covered by CPU unit tests (faked RDMA, plus 4 ranks over real Monarch TCP), a CPU probe (TCP and ibverbs) and the GPU run above.
  • CUDA context: without one, Monarch prints [RdmaXcel] No CUDA context once per registered buffer. So with the threshold set, the controller makes one current on GPU 0 with the stack limit at 0: ~256 MiB on H100 plus ~100 MiB of host memory, until Monarch logs it once (TODO). On exclusive-process GPUs, the controller and trainer rank 0 race for GPU 0.
  • Contention: one controller actor serves the TCP reads, so per-rank read speed falls as readers grow. Registering in a thread slows down while the event loop is busy (320 buffers: 19 s vs 0.06 s with the loop held 100%, CPU).
  • Metrics: with the fast path, timing/step/forward_backward includes reading and dropping; registering shows in the batcher_pack span; tokens/s and MFU exclude the reads.
  • Memory: up to 3 registered batches (training, queued, waiting to be queued); by value the same batches are held as tensors.
  • Multiple hosts: an earlier always-on version ran in all our multi-host runs, but correctness is verified on one host only and multi-host step time is not measured.

Follow up:

  • Overlap the reads with compute (the prefetch PR in this stack).
  • Read once per DP replica and broadcast (TODO in Trainer.forward_backward).
  • Send each DP replica only its column (last PR in this stack).

Test plan

  • pytest tests/rl/unit_tests/cpu (repo root, Monarch 0.7, merged with main): 494 passed, 5 skipped.
  • test_rdma_microbatch.py: with fake RDMA at min_bytes=1024, a TrainingMicrobatch round-trips (tensors ≥ 1 KiB become refs, one in model_kwargs; smaller and empty ones stay) and drop releases every buffer. Unset, the batcher never registers; set, maybe_release_oldest_batch frees only the oldest batch.
  • test_rdma_microbatch.py::test_four_ranks_read_their_columns_exactly_across_released_batches: real Monarch RDMA over TCP; 4 rank processes read their columns at once, byte-exact to the by-value batch, across 3 batches that release and register fresh buffers (~10 s).
  • test_trainer.py: by value and with the fast path, each rank trains only its column; with the fast path it reads only that column and reports timing/trainer/read_microbatches/max. A handle for another batch, rank or position raises ValueError before any read.
  • CPU Monarch probe: a real Batcher output plus a nested model_kwargs tensor, registered at 1 KiB and read from a child process: every field equal, over TCP and ibverbs.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 11, 2026
@felipemello1
felipemello1 added this pull request to stack #5287 October 11, 2026 18:13
@felipemello1
felipemello1 force-pushed the felipemello1/trainer-pull/1-microbatch-refs branch from c3770de to 3270bdc Compare October 11, 2026 18:17
@felipemello1
felipemello1 marked this pull request as ready for review October 11, 2026 19:04
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 11, 2026

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

Overall lgtm. Left comments on some details.

My agent said it saw log spew:

https://github.com/meta-pytorch/monarch/blob/v0.6.0/rdmaxcel-sys/src/driver_api.cpp#L241-L253

For workaround, we might need to create a cuda context on control. For long term, we need a monarch fix.

Comment thread torchtitan/rl/_runtime.py Resolved
Comment thread torchtitan/rl/controller.py Resolved
Comment thread torchtitan/rl/trainer.py Resolved
Comment thread torchtitan/rl/trainer.py Resolved
Comment thread torchtitan/rl/trainer.py Resolved
@felipemello1

Copy link
Copy Markdown
Contributor Author

@claude review it please

@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 52s —— View job


Review of PR #5285: trainer ranks read their own microbatches by RDMA ref

  • Gather diff and context
  • Review microbatch_ref.py
  • Review controller / trainer / runtime changes
  • Review tests
  • Post review

Overall the design is sound. The call now carries refs, each rank reads only row[dp_rank], the engine call doesn't change, and the drop-ordering trick for the Monarch 0.6 deadlock has a comment explaining it. The PR description is very thorough. Below are the issues I found, most important first. I didn't run the tests here: running Python needed approval in this environment.


1. Drop is skipped when the call raises (agree with @pzhan9)

torchtitan/rl/controller.py:1126-1144: when forward_backward.call raises, ref.drop() never runs, so the step's buffers leak. In practice the job is probably going down at that point, so the cost is small. Still, try/finally is the right shape:

microbatch_refs = await asyncio.to_thread(...)
try:
    fwd_bwd_metrics = self._get_rank_0_value(await self.trainer.forward_backward.call(...))
finally:
    # Drop while `packed` still holds the tensors (Monarch 0.6 deadlock).
    await asyncio.gather(*(ref.drop() for row in microbatch_refs for ref in row))

packed stays alive through the finally, so the deadlock invariant still holds. On the success path, the NaN break already runs after the drop, so that path is fine.

2. Reads run one microbatch at a time, each with its own thread hop and RDMA action

torchtitan/rl/trainer.py:273: [await asyncio.to_thread(ref.read) for ref in refs] waits for each microbatch to finish before starting the next. That's one thread handoff and one submit().get() round trip per microbatch. Two ways to fix it:

  • (a) Take @pzhan9's suggestion: make read async with await action.submit(), then asyncio.gather(*(ref.read() for ref in refs)). This also avoids blocking a worker thread on .get().
  • (b) Queue every read for the column into one RDMAAction and submit once.

(a) is the smaller change, and the next PR (prefetch) needs per-microbatch async reads anyway. One caveat from your own measurements: with the TCP fallback served by one controller actor, many concurrent reads per rank may not be faster than serial ones. Please check the read_microbatches span after the change.

3. Tiny tensors each get their own RDMA buffer

The batcher (torchtitan/rl/components/batcher.py:718-733) gives every microbatch 10 top-level tensors, and all of them get a buffer. Some are very small:

  • loss_token_counts and routing_token_counts have 1 + num_mtp_layers elements (from torch.stack in get_mtp_token_counts).
  • temperature is a full_like of a constant.

Each costs ~0.15 ms to register, one GIL handoff, and one [RdmaXcel] No CUDA context log line, while carrying only a few bytes. A byte-size threshold in register (small tensors go by value, like empty tensors already do) is a cheap win. It also reduces the ~1.6K log lines per step.

On @pzhan9's _runtime.py comment: I see the threshold and MONARCH_RDMA_DISABLE_IBVERBS as separate concerns. The threshold is about per-buffer overhead. The env var is about the ibverbs transport failing on some fabrics, and a threshold can't replace it. Both could exist. If you add the threshold, MicrobatchRef is still an accurate name: it is still a ref to a microbatch, with some fields inlined.

4. The env default may not reach trainer procs on other hosts

torchtitan/rl/_runtime.py:40-48: apply_env_defaults() runs when torchtitan.rl is imported.

  • Single host: spawned trainer procs inherit the controller's environment after setdefault, so this works.
  • Remote host meshes: the actor proc has already imported monarch before it unpickles anything that imports torchtitan.rl, and it doesn't inherit the controller's environment. On those procs the new warning fires and the default may not apply.

The PR already lists multiple hosts as untested. I'd add a sentence to the RL_ENV_DEFAULTS comment saying multi-host launchers must export the variable themselves.

5. read() assumes CPU, and register() assumes contiguous tensors

  • queue_read allocates with torch.empty(shape, dtype=dtype), which is always CPU. That matches what the old unpickled path produced, so it's fine today. A short comment would help, since _TensorRef doesn't record the device.
  • tensor.view(-1) in _TensorRef.register raises on non-contiguous tensors. That fails loudly rather than silently, which is good. As @pzhan9 asked, say in the comment that the batcher guarantees contiguity. On main every tensor comes from torch.tensor(...), full_like, or torch.stack, so this holds.

6. Silent fallback for unknown containers in model_kwargs

pytree.tree_map_only only walks containers pytree knows (dict, list, tuple, namedtuple, registered dataclasses). Suppose a future model_kwargs value is a custom object holding tensors. Its tensors are treated as one opaque leaf and pickled by value, with no error and no warning, and the message grows back silently. Today model_kwargs is empty on main (nothing in torchtitan/rl fills it), so this isn't urgent. A docstring note on MicrobatchRef.fields would be enough for now.

7. Minor / nits

  • trainer.py:266-270: I agree with @pzhan9 that the two TODOs could be shorter. The numbers (230 MB/s vs 1 GB/s, 0.15% / 2%) belong in the PR description. In code they will go stale.
  • test_microbatch_ref.py: assert len(tensor_refs) == 11 depends on the field count of TrainingMicrobatch. Counting tree_leaves(ref.fields) that are _TensorRef and comparing to the number of non-empty tensors in the input would survive adding a field.
  • test_microbatch_ref.py: the fake submit() returns SimpleNamespace(get=...). If you switch to await action.submit() (point 2), make the fake return an awaitable, or the test will stop exercising the real call shape.
  • test_trainer.py: switching to dp_rank = 1 plus other_rank_ref.read.assert_not_called() is a nice way to prove each rank reads only its own column. 👍

Things that look correct

  • Message shape: the controller still owns packed for the whole step, and the tensors outlive the buffers, so the deadlock comment is accurate.
  • _step_compute_start is now set after the reads, so tokens/s and MFU exclude read time. That matches the description.
  • 0-dim tensors: view(-1) gives shape [1] and torch.empty(()) restores the 0-dim shape. Bool tensors: view(torch.uint8) works because the element sizes match.
  • Every caller of Trainer.forward_backward has been updated: the controller is the only production caller, and the actor endpoint's type hint changed with it.

Summary: one real fix (try/finally around drop), one likely performance improvement (no serial thread hop per microbatch), and one small-tensor threshold that would cut both overhead and log spam. The rest are documentation and tests.

@pzhan9

pzhan9 commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

Actually reading the PR description again, I realize it does not measure e2e improvement, including the RDMA fetch part. We should include that. Otherwise it is hard to say whether this PR is improving things, or just move reads into async through RDMABuffers.

If it is the latter, we should do a compaction by copying list[TrainingMicrobatch] into 1 contiguous memory, and passing over 1 ref. RDMABuffer supports contiguous memory view, not just Tensor.

@felipemello1

felipemello1 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor Author

reply from claude:

Thanks Peng! I pushed one commit that addresses the comments, and rebased the PRs above it.

E2E, reads included (CPU Monarch, one host, TCP, 4 ranks, 131K-token microbatches):

                        main (by value)   refs        peak memory per rank
dp2 x tp2, 5.2 GB/step  9.1-11.1 s        3.3-5.1 s   15-18 -> 2.6-3.1 GB
dp1 x tp4, 2.6 GB/step  5.0 s             3.8 s       7.5 -> 2.4 GB

Refs win even at dp 1, where there's no scatter: main pickles the grid, copies it to every rank, and every rank unpickles all of it. On GPU, loss is bitwise equal to main.

Compaction: I tried one buffer per microbatch and one per column, and kept one buffer per tensor:

  • packing costs a copy on the controller (0.3-0.8 s at 5.2 GB);
  • it doesn't make registration cheaper;
  • packed reads tie with ≤16 MiB TCP chunks, and are 1.3x slower at Monarch's 64 MiB default.

Changes:

  • read() is async on the actor loop, awaited one read at a time. With gather, every read lasts as long as the whole column, against its own 60 s timeout.
  • Tensors under 1 KiB go by value. It's a constant; at 1 KiB, CI's small microbatches still go over RDMA.
  • drop() is in a finally, and the TODOs and comments are as you suggested.

Env var: it switches to TCP where Monarch's ibverbs fails without falling back (our RoCE devservers, GB300's InfiniBand). Refs work either way.

Two Monarch asks: fall back to TCP when an ibverbs op fails, and print the [RdmaXcel] line once (today it's one per registered buffer).

Felipe Mello added 3 commits October 11, 2026 17:32
The controller sent each step's whole [num_microbatches][dp_degree] grid of
TrainingMicrobatch by value, in one Monarch call, to every trainer rank, and
each rank kept only its DP column. The message grew with the step, and every
rank unpickled every column.

The controller now registers each microbatch's tensors as RDMA buffers
(MicrobatchRef, every non-empty tensor including model_kwargs), and the call
carries only the refs. Each rank reads its own column before compute, then
calls the engine with a plain list as before. The controller drops the
buffers after the call returns, while the step's tensors are still alive.

RL now defaults MONARCH_RDMA_DISABLE_IBVERBS=1, since Monarch's ibverbs path
fails without a fallback on some RoCE hosts and on native InfiniBand.
…p in finally

- MicrobatchRef.read is async (await action.submit()), so it runs on the
  actor loop without a thread. The trainer awaits one microbatch at a time:
  gathered reads share the controller's bandwidth, so each RDMA action would
  last as long as the whole column against its own 60 s timeout.
- Tensors under 1 KiB (the per-microbatch token counts, empty tensors) go
  in the message; a buffer costs more than pickling them. Every per-token
  tensor still goes by ref from 1,024 tokens up.
- The controller drops the buffers in a finally, so a failed call doesn't
  keep them registered.
- Shorter TODOs, and comments on contiguity, the delayed free, and the env
  default on other hosts.
The RDMA path is now behind async_loop.rdma_fast_path_threshold. None (the
default) sends microbatches by value, as on main. With a threshold, tensors
of at least that many bytes go as Monarch RDMA buffers, and each trainer
rank reads its own column.

- MicrobatchRef is now RDMAMicrobatch, in rdma_microbatch.py, and register
  takes min_bytes instead of the fixed 1 KiB.
- The trainer reads only when it gets RDMAMicrobatch objects.
- The MONARCH_RDMA_DISABLE_IBVERBS default is gone. The config docstring
  says to set it where Monarch's ibverbs fails.
@pzhan9

pzhan9 commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

For [RdmaXcel] log spew. I created a monarch issue: meta-pytorch/monarch#5049

But for workaround, is it possible to create dummy CUDA context on controller for now?

@felipemello1
felipemello1 force-pushed the felipemello1/trainer-pull/1-microbatch-refs branch from 7f70396 to a8c6e70 Compare October 12, 2026 01:09
@felipemello1 felipemello1 changed the title [rl] trainer ranks read their own microbatches by RDMA ref [rl] Add an opt-in RDMA fast path for trainer microbatches Oct 12, 2026
@felipemello1

felipemello1 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor Author

reply from claude:

Updated: this replaces my earlier text here; my other replies on this PR describe earlier versions. Current design, as you proposed:

  • async_loop.rdma_fast_path_threshold: int | None = None.
    • None (default): microbatches go by value in the Monarch message, as on main. No RDMABuffer, no monarch.configure, no CUDA context.
    • An int: tensors of at least that many bytes go as RDMAMicrobatch handles; smaller ones (token counts, empty tensors) stay in the message.
  • No transport knob: Monarch uses ibverbs where the host has it, else TCP. MONARCH_RDMA_DISABLE_IBVERBS=1 forces TCP.
  • The trainer reads only when it gets RDMAMicrobatches, and then reports timing/trainer/read_microbatches/max (the slowest rank).
  • Scatter (each DP replica gets only its column) is a separate PR at the top of the stack, and it works by value too.
  • GPU (Qwen3-0.6B, H100, 2 GPUs, 5 steps): loss/mean is bitwise equal with the threshold unset vs 1024.

- The controller's comment about keeping the step's tensors alive past
  drop() goes: `packed` outlives the drop anyway.
- The config docstring no longer names RoCE hosts as an ibverbs failure
  case: Monarch 0.7 ibverbs works on our H100 RoCE devserver.
@felipemello1

felipemello1 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor Author

reply from claude:
@pzhan9
ibverbs: you were right. On Monarch 0.7 it works on this devserver: a 0.5 GB CPU-memory read at 5.1 GB/s, ~6x the TCP fallback (0.6 still fails with status 12). The docstring and PR body no longer name RoCE hosts; the PR's numbers are still TCP. I also removed the controller's Monarch 0.6 comment.

Monarch checks every registered pointer with a CUDA driver call and, in a
process without a CUDA context, logs one line per buffer. With the RDMA
fast path on, the controller now makes a CUDA context current on GPU 0,
with the per-thread stack limit at 0, since the driver raises it when a
kernel needs more: ~256 MiB on H100 instead of ~520 MiB. It skips hosts
without CUDA and only warns if the context fails. A TODO links the Monarch
issue; it still logs in torchmonarch 0.7.0.
@felipemello1

Copy link
Copy Markdown
Contributor Author

reply from claude:

Two updates from your suggestions:

  • CUDA context: added, only when the fast path is on. With the per-thread stack limit at 0, it's ~256 MiB on H100 instead of ~520 MiB, and the [RdmaXcel] lines go from ~31 per step to 0 in our GPU runs. It lives in the controller here and moves into the batcher process in the next PRs. A TODO links your Monarch issue.
  • Per-DP-replica scatter: now the 4th PR in this stack. With the fast path off, each DP replica gets only its column. CPU Monarch at a 2.6 GB step: 5.3 → 2.1 s at dp 4, and peak memory per rank 7.6 → 1.9 GB. Loss is bitwise equal to main at DP 2, with the fast path on and off.

@felipemello1
felipemello1 removed this pull request from stack #5287 October 12, 2026 04:09
@felipemello1
felipemello1 added this pull request to stack #5302 October 12, 2026 04:10
@felipemello1
felipemello1 removed this pull request from stack #5302 October 12, 2026 04:43
@felipemello1
felipemello1 added this pull request to stack #5306 October 12, 2026 04:44
@felipemello1 felipemello1 changed the title [rl] Add an opt-in RDMA fast path for trainer microbatches [rl] Trainer ranks read their own microbatches from Monarch RDMA buffers Oct 12, 2026
One way to reach the trainer instead of two: the controller always
registers each microbatch's large tensors, and each rank reads its column.
The whole-grid-by-value path and the rdma_fast_path_threshold config are
removed: over TCP, refs beat even sending each DP replica only its column
by value (2.6 GB step: 3.0 -> 2.5 s at dp 2 x tp 2, 2.05 -> 1.0 s at dp 4).
Tensors under 1 KiB still go by value. The controller now always creates
its CUDA context (~256 MiB on GPU 0) to silence Monarch's per-buffer log.

The bytes move over TCP unless async_loop.enable_rdma is set. Like
TorchStore's RDMA switch, it means RDMA (ibverbs) where the host has it,
else TCP. With it off, the controller turns ibverbs off for its own process
after spawning, so trainer and generator processes keep ibverbs for weight
sync.
@felipemello1
felipemello1 force-pushed the felipemello1/trainer-pull/1-microbatch-refs branch from a875707 to edbeb05 Compare October 12, 2026 06:41
Felipe Mello added 2 commits October 12, 2026 08:18
- AsyncLoopConfig.enable_rdma -> microbatch_rdma_transport: Literal["tcp", "ibverbs"] = "tcp";
  "ibverbs" falls back to TCP on hosts without it.
- init_rdma_microbatch_owner(transport=...) does the owner-process setup (transport switch +
  CUDA context) in rdma_microbatch.py; the controller no longer imports monarch.
- timing/trainer/read_microbatches/max: the slowest rank's read time per step.
- Docstrings say "owner" instead of "controller".
Comment thread torchtitan/rl/controller.py Resolved
Felipe Mello added 2 commits October 12, 2026 12:44
- AsyncLoopConfig.rdma_fast_path_threshold: int | None = None replaces microbatch_rdma_transport.
  None: microbatches go by value in the Monarch message (no RDMA buffer, no CUDA context).
  An int: tensors of at least that many bytes go as RDMA buffers; Monarch picks ibverbs or TCP.
- RDMAMicrobatch.register takes min_bytes; init_rdma_microbatch_owner and monarch.configure are gone.
- The trainer reads and reports timing/trainer/read_microbatches/max only for RDMAMicrobatches.
@felipemello1 felipemello1 changed the title [rl] Trainer ranks read their own microbatches from Monarch RDMA buffers [rl] Add an opt-in RDMA fast path for trainer microbatches Oct 12, 2026
Comment thread torchtitan/rl/controller.py Outdated
lambda: [
[
RDMAMicrobatch.register(
microbatch, min_bytes=min_bytes

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.

We could make RDMAMicrobatch.register's min_bytes parameter's type int | None, and move the if min_bytes is not None logic inside register. That likely works better with #5291, since Batcher will just hand off RDMAMicrobatch directly to controller in packed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reply from claude: Done in the batcher instead of register: the setting is now Batcher.Config.rdma_min_tensor_bytes (Tianyu's ask), and the batcher registers right after packing, so packed already holds MonarchRDMAMicrobatches, in this PR and in the batcher-process PR. The None check lives there once, so register keeps min_bytes: int.

with sl.log_trace_span("read_microbatches"):
# One at a time, not asyncio.gather: gathered reads share the controller's bandwidth,
# so each takes as long as the whole column and can hit its 60 s RDMA timeout.
microbatches = [await microbatch.read() for microbatch in microbatches]

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.

I am not sure this is right. RDMABuffer supports concurrent read iiuc. The controller host might have multiple nics so concurrent read is desirable.

If RDMABuffer does not handle concurrent read well, we should raise that as an issue to Monarch.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reply from claude: Concurrent reads work fine; I keep them one at a time for the order:

  • One at a time, microbatch 0 arrives first; the prefetch PR trains on it while it reads two ahead. Gathered, all reads finish together.
  • Gathered was 0-19% faster (5.2 GB, dp 2 x tp 2, one host, TCP), but each action took as long as the whole column (3.2 s vs 0.17 s), against its own deadline (60 s by default).
  • Multiple NICs: Monarch 0.7 stripes one transfer over NIC pairs (rdma_min_stripe_size_kb), and the owner already serves every rank at once.

Happy to revisit with multi-host numbers.

Comment thread torchtitan/rl/trainer.py Outdated
)
engine = self.engine
microbatches = [rank_batches[self.dp_rank] for rank_batches in training_data]
uses_rdma = bool(microbatches) and isinstance(microbatches[0], RDMAMicrobatch)

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reply from claude: I kept it. By value the trainer gets plain TrainingMicrobatches, so the default path has no RDMA type at all: None skips the RDMA path completely, as you asked. The check also gates the read metric and, in the prefetch PR, the read-ahead thread. If you'd rather have one type on both paths, register(min_bytes=None) can return a MonarchRDMAMicrobatch with no buffers; the cost is that wrapper, a read and the read-ahead thread on the default path.

@pzhan9

pzhan9 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

overall lgtm, except some minor comments left. But we should benchmark this in a multi-host setup so we have data on how it actually improves things.

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

looks good in general, please address comments

_CU_LIMIT_STACK_SIZE = 0


def create_cuda_context_to_silence_monarch_log() -> None:

@tianyu-l tianyu-l Oct 13, 2026 •

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.

@pzhan9 is there a monarch-native way to do this? wouldn't block this PR though

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.

No, we do not. This is just to a hack to workaround the monarch side bug. We should not need this after the bug is fixed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reply from claude: Thanks, Peng. The TODO in this function already says to remove it once that Monarch issue is fixed.

from typing import Any

import torch
from monarch.rdma import RDMAAction, RDMABuffer

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.

does this work on CW cluster now?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reply from claude: It ran in all our multi-host runs on both clusters we use (an earlier version, with RDMA always on), but I've only verified correctness on one host: loss/mean bitwise equal by value vs RDMA, and a new CPU test where 4 rank processes read their columns byte-exact over real Monarch RDMA. The trainer now also checks each microbatch's batch, rank and position before reading. By default nothing changes there: microbatches go in Monarch messages, as on main.



@dataclasses.dataclass(frozen=True, slots=True)
class RDMAMicrobatch:

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.

Given this dependency, are you OK with calling it

Suggested change
class RDMAMicrobatch:
class MonarchRDMAMicrobatch:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reply from claude: Done, MonarchRDMAMicrobatch, in all four PRs.

Comment thread torchtitan/rl/controller.py Outdated
# Empty by value (no threshold): the call sends packed.microbatches; the drop frees nothing.
rdma_microbatches: list[list[RDMAMicrobatch]] = []
min_bytes = self.config.async_loop.rdma_fast_path_threshold
if min_bytes is not None:

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.

Can we make if-else branch clearly separate RMDA path vs. value path, instead of mingle them together?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reply from claude: The training loop has no RDMA branch now. The batcher picks the path when it packs: with rdma_min_tensor_bytes unset it returns the batch as is; set, it registers it. The loop passes packed.microbatches either way and calls batcher.maybe_release_oldest_batch() in finally, a no-op when unset:

try:
    fwd_bwd_metrics = self._get_rank_0_value(
        await self.trainer.forward_backward.call(packed.microbatches, ...)
    )
finally:
    # With RDMA, every rank has read its column (or the step failed).
    await batcher.maybe_release_oldest_batch()

Comment thread torchtitan/rl/controller.py Outdated
`target_offpolicy_steps + n`. A value of 1 is FIFO by batch. See
``torchtitan/rl/components/WINDOWED_FIFO.md``."""

rdma_fast_path_threshold: int | None = None

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.

current name is not tied to controller -> trainer data sending, could you rename to something more meaningful?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reply from claude: Renamed and moved: async_loop.batcher.rdma_min_tensor_bytes. It lives with the batcher, which makes the microbatches the trainer reads, and says what it is: tensors of at least that many bytes go to the trainer by RDMA.

Felipe Mello added 3 commits October 13, 2026 20:06
- The threshold moves from AsyncLoopConfig.rdma_fast_path_threshold to
  Batcher.Config.rdma_min_tensor_bytes.
- With it set, the batcher registers each batch right after packing and
  keeps it until maybe_release_oldest_batch(); with it unset, it returns the
  batch by value and the release is a no-op.
- The training loop has no RDMA branch: it passes packed.microbatches and
  calls batcher.maybe_release_oldest_batch() in a finally.
- RDMAMicrobatch is renamed MonarchRDMAMicrobatch.
Felipe Mello added 3 commits October 14, 2026 10:02
Main reorganized torchtitan/rl into role packages. rdma_microbatch.py moves to
torchtitan/rl/trainer/, next to batcher.py and trainer.py, its users; imports follow
the new paths. test_trainer_loop.py passes a batcher to _trainer_loop.
…tion it was packed for

- Each MonarchRDMAMicrobatch carries (batch_index, dp_rank, microbatch_index)
  by value. The batcher stamps them when it registers a batch; before reading,
  the trainer raises ValueError unless they match its count of batches read,
  its DP rank and the position in its column. This catches a wrong column, and
  a batch read twice or out of order.
- New CPU test over real Monarch RDMA (TCP): 4 trainer-rank processes read
  their columns at once, byte-exact to the by-value batch, across 3 batches
  that release and register fresh buffers.
@felipemello1

Copy link
Copy Markdown
Contributor Author

reply from claude: Thanks! It ran in all our multi-host runs (an earlier version, with RDMA always on), but I've only verified correctness and measured it on one host: loss/mean bitwise equal by value vs RDMA, a 4-rank byte-exact CPU test over real Monarch RDMA, and the numbers in the PR body. The trainer now raises if a microbatch arrives for another batch, rank or position. It's opt-in, so default runs keep main's path.

@felipemello1

Copy link
Copy Markdown
Contributor Author

reply from claude: After the reorg, rdma_microbatch.py stays in torchtitan/rl/trainer/. Main put the RL TrainingMicrobatch in trainer/batcher.py, and MonarchRDMAMicrobatch is its RDMA form: the trainer owns the format of what it reads.

@felipemello1
felipemello1 removed this pull request from stack #5310 October 15, 2026 02:41
@felipemello1
felipemello1 added this pull request to stack #5406 October 15, 2026 02:47
@felipemello1
felipemello1 merged commit bdb253e into main Oct 15, 2026
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