Repository navigation
[rl] Add an opt-in RDMA fast path for trainer microbatches - #5285
Conversation
c3770de to
3270bdc
Compare
pzhan9
left a comment
There was a problem hiding this comment.
Overall lgtm. Left comments on some details.
My agent said it saw log spew:
For workaround, we might need to create a cuda context on control. For long term, we need a monarch fix.
|
@claude review it please |
|
Claude finished @felipemello1's task in 2m 52s —— View job Review of PR #5285: trainer ranks read their own microbatches by RDMA ref
Overall the design is sound. The call now carries refs, each rank reads only 1. Drop is skipped when the call raises (agree with @pzhan9)
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))
2. Reads run one microbatch at a time, each with its own thread hop and RDMA action
(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 3. Tiny tensors each get their own RDMA bufferThe batcher (
Each costs ~0.15 ms to register, one GIL handoff, and one On @pzhan9's 4. The env default may not reach trainer procs on other hosts
The PR already lists multiple hosts as untested. I'd add a sentence to the 5.
|
|
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 |
|
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): 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:
Changes:
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 |
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.
|
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? |
7f70396 to
a8c6e70
Compare
|
reply from claude: Updated: this replaces my earlier text here; my other replies on this PR describe earlier versions. Current design, as you proposed:
|
- 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.
|
reply from claude: |
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.
|
reply from claude: Two updates from your suggestions:
|
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.
a875707 to
edbeb05
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".
- 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.
| lambda: [ | ||
| [ | ||
| RDMAMicrobatch.register( | ||
| microbatch, min_bytes=min_bytes |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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] |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| ) | ||
| engine = self.engine | ||
| microbatches = [rank_batches[self.dp_rank] for rank_batches in training_data] | ||
| uses_rdma = bool(microbatches) and isinstance(microbatches[0], RDMAMicrobatch) |
There was a problem hiding this comment.
This check will become unnecessary if we do: https://github.com/pytorch/torchtitan/pull/5285/changes#r4259920948
There was a problem hiding this comment.
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.
|
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
left a comment
There was a problem hiding this comment.
looks good in general, please address comments
| _CU_LIMIT_STACK_SIZE = 0 | ||
|
|
||
|
|
||
| def create_cuda_context_to_silence_monarch_log() -> None: |
There was a problem hiding this comment.
@pzhan9 is there a monarch-native way to do this? wouldn't block this PR though
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
does this work on CW cluster now?
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
Given this dependency, are you OK with calling it
| class RDMAMicrobatch: | |
| class MonarchRDMAMicrobatch: |
There was a problem hiding this comment.
reply from claude: Done, MonarchRDMAMicrobatch, in all four PRs.
| # 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: |
There was a problem hiding this comment.
Can we make if-else branch clearly separate RMDA path vs. value path, instead of mingle them together?
There was a problem hiding this comment.
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()| `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 |
There was a problem hiding this comment.
current name is not tied to controller -> trainer data sending, could you rename to something more meaningful?
There was a problem hiding this comment.
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.
- 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.
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.
|
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: |
|
reply from claude: After the reorg, |
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
trainer.forward_backwardwith the step's whole[num_microbatches][dp_degree]grid ofTrainingMicrobatch, by value.row[dp_rank], so it unpickles dp_degree times the data it trains on.Solution
MonarchRDMAMicrobatch(newtorchtitan/rl/trainer/rdma_microbatch.py):register(microbatch, min_bytes=...)swaps each tensor of at leastmin_bytes,model_kwargsincluded, for anRDMABufferhandle;read()copies them into fresh tensors with one RDMA action;drop()releases them.asyncio.to_thread) and keeps it untilmaybe_release_oldest_batch(). Each handle carries the batch, DP rank and position it was registered for.packed.microbatcheseither way and callsbatcher.maybe_release_oldest_batch()in afinally.ValueErroron a mismatch), reads its column one microbatch at a time, and reportstiming/trainer/read_microbatches/max.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_stepand weight sync are unchanged either way.Results (all for the opt-in path)
Data path per step: packed batch -> every rank holds its column -> drop.
model_kwargs.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:
GPU, Qwen3-0.6B, H100, batch invariant, lockstep, trainer DP 1 + one TP 1 generator (2 GPUs), 4,096-token microbatches, 5 steps, ibverbs:
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:
MONARCH_RDMA_DISABLE_IBVERBS=1forces TCP in every process, weight sync included.RDMABufferrejects empty tensors. At 1 KiB, per-token tensors go out of band from 1,024 tokens up.TrainingEnginemode.ControllerStorageVolumesand cleanup on both sides.NOTE:
[RdmaXcel] No CUDA contextonce 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.timing/step/forward_backwardincludes reading and dropping; registering shows in thebatcher_packspan; tokens/s and MFU exclude the reads.Follow up:
Trainer.forward_backward).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 atmin_bytes=1024, aTrainingMicrobatchround-trips (tensors ≥ 1 KiB become refs, one inmodel_kwargs; smaller and empty ones stay) anddropreleases every buffer. Unset, the batcher never registers; set,maybe_release_oldest_batchfrees 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 reportstiming/trainer/read_microbatches/max. A handle for another batch, rank or position raisesValueErrorbefore any read.Batcheroutput plus a nestedmodel_kwargstensor, registered at 1 KiB and read from a child process: every field equal, over TCP and ibverbs.