Repository navigation
[rl] Send each trainer DP rank only its column of the grid - #5309
Conversation
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.
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.
d9fdcbf to
d4083c1
Compare
- 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.
…h) into the batcher-process PR
…h, batcher process) into the scatter PR
…o the aux-denominator PR
…o the prefetch PR
…atcher-process PR # Conflicts: # torchtitan/rl/trainer/batcher.py
| trainer_by_dp_rank = self.trainer.flatten("rank").split( | ||
| rank=("dp", "cp_tp"), dp=self.trainer_dp_degree | ||
| ) | ||
| self._trainer_dp_replicas = [ |
There was a problem hiding this comment.
"replica" is not a great name with FSDP, which shards the params across the dp axis. Could you come up with something more accurate?
There was a problem hiding this comment.
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], |
There was a problem hiding this comment.
seems no change to the RDMAMicrobatch path as it's passing by reference anyway
There was a problem hiding this comment.
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.
TLDR: The controller called
trainer.forward_backwardon 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
[num_microbatches][dp_degree]grid:TrainingMicrobatches by value, orMonarchRDMAMicrobatchhandles (~5 KB each) with the fast path.trainer.forward_backwardon the whole trainer mesh with the whole grid.Solution
(dp, cp, tp), and RL rejects PP, so the ranks at one DP rank arecp * tpconsecutive ranks.Controller.setup_asynccuts the trainer mesh into one sub-mesh per DP rank with Monarch'ssplit, once. It checks that layout once: each rank reports its DP rank through a newget_dp_rankendpoint, and setup raises if a sub-mesh's ranks don't all report its DP rank.Controller._trainer_loopsends one call per DP rank, each with its column, and awaits them together. It reads rank 0's metrics as before.Trainer.forward_backwardtakes that column,microbatches: [num_microbatches](by value or handles), instead of the grid.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):
Handles, CPU Monarch, one host, 4 rank processes, 46 microbatches per DP rank, routed expert ids and top-32 logprobs in
model_kwargs. Bytes arelen(cloudpickle.dumps(...))of the grid vs one column; the call is a median of 5 to an endpoint that returnslen():GPU, Qwen3-0.6B, H100, batch invariant, lockstep, one TP 1 generator, Monarch 0.7, 5 steps:
loss/meanbitwise equal to main's DP 2 run at every step.loss/meanwithrdma_min_tensor_bytes=1024bitwise equal to a by-value run of an earlier push (same config and seed);timing/trainer/read_microbatches/max147, 17, 10, 12, 15 ms at steps 1-5 (step 1 includes RDMA setup).CPU mesh check: the controller's real setup and
_trainer_loopcode 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):You may ask:
cp * tptimes on the controller's event loop.forward_backwardto take the grid again (a second signature or a shape branch).NOTE:
cp * tpranks at one DP rank still each receive the same column (the read-once-and-broadcast TODO inTrainer.forward_backward).Test plan
pytest tests/rl/unit_tests/cpu(repo root, Monarch 0.7, merged with main): 498 passed, 5 skipped.test_trainer.py:forward_backwardtrains a column by value, and a column ofMonarchRDMAMicrobatches through the read-ahead prefetcher.