Skip to content

[rl] Send each trainer DP rank only its column of the grid - #5309

Merged
felipemello1 merged 70 commits into
mainfrom
felipemello1/trainer-pull/4-scatter
Oct 15, 2026
Merged

felipemello1 merged 70 commits into
mainfrom
felipemello1/trainer-pull/4-scatter

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: The controller called trainer.forward_backward on the whole trainer mesh with the step's whole [num_microbatches][dp_degree] grid, and each rank kept only its column. Now each trainer DP rank receives only its column. By value (the default), a 2.6 GB step at dp 4 goes from 5.3 to 2.1 s and peak memory per rank from 7.6 to 1.9 GB (CPU Monarch, one host, an earlier version of this PR). With RDMA handles each rank already reads just its column; this shrinks the handle message (41 -> 19 ms per call at dp 2, 1.5 s -> 22 ms with a dp-64 grid sent to 4 ranks on one host), so it matters at high DP.

Problem

  1. The batcher packs each step as a [num_microbatches][dp_degree] grid: TrainingMicrobatches by value, or MonarchRDMAMicrobatch handles (~5 KB each) with the fast path.
  2. The controller calls trainer.forward_backward on the whole trainer mesh with the whole grid.
  3. Every rank receives and unpickles every column, then keeps (or reads) only its own.
  4. By value, each rank unpickles dp times the bytes it trains on. With handles, at dp 64 that is 14.4 MB per rank and ~1.5 s per call; at dp 2 it is 0.45 MB.

Solution

  1. The trainer lays its ranks out as (dp, cp, tp), and RL rejects PP, so the ranks at one DP rank are cp * tp consecutive ranks.
  2. Controller.setup_async cuts the trainer mesh into one sub-mesh per DP rank with Monarch's split, once. It checks that layout once: each rank reports its DP rank through a new get_dp_rank endpoint, and setup raises if a sub-mesh's ranks don't all report its DP rank.
  3. Controller._trainer_loop sends one call per DP rank, each with its column, and awaits them together. It reads rank 0's metrics as before.
  4. Trainer.forward_backward takes that column, microbatches: [num_microbatches] (by value or handles), instead of the grid.
  5. Unchanged: the batcher, the grid, the global loss and routing token counts, the reads, and every other trainer call.
before: trainer[0..3].forward_backward(grid [M][2])               -> each of the 4 ranks receives M x 2 microbatches
after:  trainer[0, 1].forward_backward([row[0] for row in grid])  -> M each
        trainer[2, 3].forward_backward([row[1] for row in grid])  -> M each

Results

By value, CPU Monarch, one host, 2.6 GB step (an earlier version of this PR; a separate run from the RDMA PR's table):

               per step         peak memory per rank
dp 2 x tp 2    5.0 -> 3.0 s     7.6 -> 3.8 GB
dp 4           5.3 -> 2.1 s     7.6 -> 1.9 GB

Handles, CPU Monarch, one host, 4 rank processes, 46 microbatches per DP rank, routed expert ids and top-32 logprobs in model_kwargs. Bytes are len(cloudpickle.dumps(...)) of the grid vs one column; the call is a median of 5 to an endpoint that returns len():

          handles per rank           call to 4 ranks
dp        whole grid -> column       whole grid -> column
2         0.45 MB -> 0.22 MB         41 ms -> 19 ms
8         1.8 MB  -> 0.22 MB         153 ms -> 16 ms
32        7.2 MB  -> 0.22 MB         946 ms -> 20 ms
64        14.4 MB -> 0.22 MB         1475 ms -> 22 ms
  • Summed over dp 64 x tp 4 ranks: 3.7 GB -> 58 MB per step (computed, not measured).
  • These handles carry only TCP contexts; on ibverbs hosts and across hosts each is larger, so these bytes are a lower bound.

GPU, Qwen3-0.6B, H100, batch invariant, lockstep, one TP 1 generator, Monarch 0.7, 5 steps:

  • Trainer DP 2 (3 GPUs), TCP, with RDMA buffers (an earlier version of this stack): loss/mean bitwise equal to main's DP 2 run at every step.
  • The previous push of the whole stack, trainer DP 1 (2 GPUs): loss/mean with rdma_min_tensor_bytes=1024 bitwise equal to a by-value run of an earlier push (same config and seed); timing/trainer/read_microbatches/max 147, 17, 10, 12, 15 ms at steps 1-5 (step 1 includes RDMA setup).

CPU mesh check: the controller's real setup and _trainer_loop code against real Monarch actor meshes, with a fake trainer that has the real DP-rank lines and a collective spanning DP ranks (an earlier version of this PR, same split and layout check):

  • dp 2 x tp 2, dp 4, dp 1 x tp 4, dp 2 x cp 2, and HSDP 2 x 2 x 2 on a 2-level mesh: each rank got exactly its column every step, and rank 0's metrics came from global rank 0.
  • With DP as the innermost dimension, the startup check raised.
  • When one DP rank's call raised, the step raised within 20 ms and the batch release ran once.

You may ask:

  • Why not one call per rank? Each column would be pickled cp * tp times on the controller's event loop.
  • Why slice by layout instead of asking each rank where it belongs? A Monarch slice needs consecutive ranks anyway; the startup check turns a layout drift into an error instead of silently wrong gradients.
  • Why scatter handles too? It's the same code on both paths; a by-value-only scatter would need forward_backward to take the grid again (a second signature or a shape branch).
  • Does it make the controller cheaper? No: pickling 64 columns costs the same as one grid (0.43 vs 0.42 s at dp 64). It cuts what each rank receives and unpickles.

NOTE:

  • The cp * tp ranks at one DP rank still each receive the same column (the read-once-and-broadcast TODO in Trainer.forward_backward).
  • The GPU run is DP 2 x TP 1, so one rank sits at each DP rank; the CPU mesh check covers several ranks per DP rank.
  • Not tested on more than one host.

Test plan

  • pytest tests/rl/unit_tests/cpu (repo root, Monarch 0.7, merged with main): 498 passed, 5 skipped.
  • test_trainer.py: forward_backward trains a column by value, and a column of MonarchRDMAMicrobatches through the read-ahead prefetcher.
  • GPU parity and the CPU mesh check above.

Felipe Mello added 5 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.
- 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.
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.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 12, 2026
@felipemello1
felipemello1 added this pull request to stack #5310 October 12, 2026 06:16
Felipe Mello added 10 commits October 11, 2026 23:39
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.
…aphs

forward_backward moved every microbatch of the optimizer step to the device
before the first forward, so input memory grew with the number of microbatches
even in eager mode, where nothing needs the inputs up front. Before
"Capture gradient accumulation in one CUDA graph", eager copied one microbatch
at a time.

Without a CUDA graph (and without SDC replay, which reruns the step on the same
inputs), preprocess each group inside the accumulation loop just before its
forward. The CUDA graph paths keep preprocessing every group up front.
Each rank read its whole column before compute, so the reads were exposed
and the whole column sat in host memory. MicrobatchStream now reads this
rank's microbatches on a background thread, two ahead of the one the engine
waits on, and the engine (which now preprocesses one group at a time when
eager) trains each as it arrives. A rank holds at most 4 microbatches on the
host, and a wait_for_microbatch span records any read time training did not
hide.
The cancel test passed even without the pool shutdown. It now also asserts
that close() waited for the running read before the queued one was skipped.
…ntroller's GIL

The controller's event loop serves rollouts and holds the GIL most of the time. build_from_group
runs on that loop and blocks it; add_training_samples runs in asyncio.to_thread, where each torch
op releases the GIL and then waits up to the 5 ms switch interval to get it back. In a CPU
benchmark with a busy loop, one batch took 3.7-5.4 s instead of 0.2 s.

BatcherActor runs the builder and the batcher in a one-process mesh on the controller host, like
the router. It registers each microbatch as an RDMAMicrobatch, keeps the tensors, and returns
those, so trainer ranks read from its process and the controller no longer registers or drops
them. It also takes over the TCP switch (monarch.configure unless enable_rdma) and
the CUDA context from the controller. The trainer loop frees the oldest batch with a broadcast
after forward_backward. Under the same load, a batch takes 0.61-0.70 s.
drop() returns before Monarch 0.6 lets go of a buffer's storage. Freeing the
batch's tensors right after the drops let that late release free the storage
while Monarch's RDMA cache lock was held, and the batcher process deadlocked
in 5 of 10 1,500-step stress runs. Keeping the dropped batch until the next
release ran 13 of 13 runs clean, at the cost of one more batch of host memory.

Also trace the ref registration (register_rdma_microbatches) and state the
release contract: once per trained batch, in order, after forward_backward.
The trainer loop now releases the batch in a finally.
- The batcher test now produces two batches and releases the first; the
  second still reads back exactly over RDMA, so a release never frees an
  unread batch.
- Comments: why each held batch keeps its tensors (Monarch 0.6 drop
  deadlock), and that the batcher drops the buffers it owns, on its host.
The batcher held each batch's TrainerStepBatch next to its buffers, and
the last released batch until the next release, only to dodge Monarch
0.6's drop deadlock. Monarch 0.7 makes that lock reentrant, and each
buffer keeps its tensor's storage alive until drop(), so the batcher now
keeps just the RDMAMicrobatches. Needs torchmonarch>=0.7.0.
The controller called forward_backward on the whole trainer mesh with the
step's [num_microbatches][dp_degree] grid of RDMAMicrobatches, so every
rank received every column's handles and read one. It now splits the
trainer mesh into DP replicas (the trainer orders ranks as (dp, cp, tp))
and calls each replica with only its column; a startup check confirms
each replica's ranks report its DP rank. Trainer.forward_backward takes
that column.

The handles each rank receives no longer grow with dp. This only matters
at very high DP.
@felipemello1
felipemello1 force-pushed the felipemello1/trainer-pull/4-scatter branch from d9fdcbf to d4083c1 Compare October 12, 2026 06:41
Felipe Mello added 10 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".
The reads now run in MicrobatchStream, so timing/trainer/read_microbatches/max comes from its read_s (each read's time on the read thread, hidden or not).
…ess PR

BatcherActor takes microbatch_rdma_transport and calls init_rdma_microbatch_owner. Tests follow main's numpy RolloutTurn fields, and main's run() test helper sets controller.batcher.
forward_backward keeps the MicrobatchStream in a local, since the read-time metric reads its read_s.
- 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.
The stream reads ahead only for RDMAMicrobatches; by value, the trainer passes its column as is. timing/trainer/read_microbatches/max comes from the stream's read_s, on the RDMA path only.
BatcherActor takes rdma_fast_path_threshold: with it, it registers and holds each batch and creates the CUDA context; without it, it returns the batch by value. The controller releases batches only with the threshold set.
Each DP replica gets its column as TrainingMicrobatches by value, or as RDMAMicrobatches with the threshold set.

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

comments

Comment thread torchtitan/rl/controller/controller.py Outdated
trainer_by_dp_rank = self.trainer.flatten("rank").split(
rank=("dp", "cp_tp"), dp=self.trainer_dp_degree
)
self._trainer_dp_replicas = [

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.

"replica" is not a great name with FSDP, which shards the params across the dp axis. Could you come up with something more accurate?

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 to the trainer's existing dp_rank vocabulary: self._trainer_by_dp_rank[i] is the cp * tp trainer ranks at DP rank i, and the loop variable is trainer_at_dp_rank. The title and body now say "each trainer DP rank" too.

fwd_bwd_results = await asyncio.gather(
*(
trainer_dp_replica.forward_backward.call(
[row[dp_rank] for row in packed.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.

seems no change to the RDMAMicrobatch path as it's passing by reference anyway

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: Right: with handles each rank already reads only its own column, so here the scatter only shrinks the handle message. I kept one path because it's the same line for both; a by-value-only scatter would need forward_backward to take the grid again (a second signature or a shape branch).
What it's worth: by value, 5.3 -> 2.1 s per step at dp 4 (2.6 GB step); with RDMA, 41 -> 19 ms per call at dp 2 and 1.5 s -> 22 ms with a dp-64 grid (4 ranks, one host). So if RDMA becomes the default, this PR matters mainly at high DP.

With FSDP the ranks at one DP rank do not hold a full copy of the model, so
"replica" was inaccurate. Use the trainer's existing dp_rank vocabulary:
_trainer_by_dp_rank[dp_rank] is the cp * tp trainer ranks at that DP rank.
@felipemello1 felipemello1 changed the title [rl] Send each trainer DP replica only its column of the grid [rl] Send each trainer DP rank only its column of the grid Oct 15, 2026
Base automatically changed from felipemello1/trainer-pull/3-batcher-process to main October 15, 2026 06:08
@pytorch-bot pytorch-bot Bot added the ciflow/b200 Trigger B200 CI label Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI 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.

2 participants