Repository navigation
[rl] Build and pack training batches in their own process - #5291
Conversation
f13d2d7 to
b158175
Compare
87f9449 to
ff3fdc9
Compare
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
left a comment
There was a problem hiding this comment.
over all lgtm. But we should move to 0.7 if possible, since it seems to fix the deadlock bug this PR tries to workaround.
Also please check if you need to add this test:
The main invariant isn't tested. test_batcher_actor.py only produces one batch. The PR relies on "FIFO release never frees an
unread batch", so a cheap extra case would help: produce batches A and B, call release_oldest_batch once, then confirm B's refs
still read back exactly.
ff3fdc9 to
20649e2
Compare
|
reply from claude: Thanks! I pushed one commit:
|
- 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.
20649e2 to
ced9e33
Compare
|
reply from claude: Your A/B test now also covers this: B reads back exactly after the batcher has dropped its references to B's tensors. A stress run of the real |
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.
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.
monarch_actors/batcher.py moves to actors/monarch/batcher.py with main's layout; imports follow the new paths. test_trainer_loop.py gives its controller a batcher.
- New training.preprocess_microbatch_groups_lazily (default False). TrainingEngine.Config rejects it with CUDA graphs or SDC replay, and GraphTrainer rejects it. The RL controller warns when the RDMA microbatch path is on without it. - TrainingEngine._preprocess_microbatch_group prepares one group; _preprocess_microbatch_groups loops over it, and the lazy path calls it directly. The lazy flag reaches _forward_backward_body through its partial. - preprocess_inputs takes global_routing_token_counts, and each model with an aux loss returns it as aux_loss_denominators; _set_aux_loss_denominators is removed. - MicrobatchStream is renamed RDMAMicrobatchPrefetcher; its wait helper is an inner function.
…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.
TrainingEngine filled each model's aux_loss_denominators after preprocessing, guessing PP vs non-PP from the prepared tuple's length. preprocess_inputs now takes global_routing_token_counts, and each model with an aux loss returns it as aux_loss_denominators where it wrote the None placeholder. The HF backend accepts and drops the keyword. Same tensor, same kwarg.
…to the prefetch PR
…to the batcher-process PR
…h) into the batcher-process PR
…o the aux-denominator PR
…o the prefetch PR
…atcher-process PR # Conflicts: # torchtitan/rl/trainer/batcher.py
TLDR: On a busy controller the batcher waits on the GIL: one batch takes 3.7-5.4 s instead of 0.2 s (CPU benchmark). This PR moves building and packing into their own process (
BatcherActor). Under the same load a batch then takes 0.61-0.70 s with the RDMA fast path on (trainer ranks read from the batcher's process), and 2.0-4.5 s by value (the default; the controller still unpickles each batch under its GIL).Problem
_batcher_loopbuilds training samples and packs microbatches inside the controller process.build_from_groupandadd_training_samplesrun inasyncio.to_thread; each time that thread gives up the GIL (e.g. every torch op in the packer), it waits up to 5 ms (sys.getswitchinterval()) to get it back.Solution
BatcherActor(torchtitan/rl/actors/monarch/batcher.py): a thin Monarch wrapper overBatcher, likeVLLMGeneratorActor, spawned bysetup_asyncon a one-process mesh on the controller host. The newBatcher.add_group(rollout_group=...)builds the group's training samples and packs them. It returns each finished batch by value or, withrdma_min_tensor_bytesset, asMonarchRDMAMicrobatches whose tensors it keeps (the RDMA PR's code, unchanged).forward_backward, in afinally, the trainer loop callsbatcher.maybe_release_oldest_batch.broadcast()(a no-op by value). Not awaited: awaited, it waited p50 255 ms behind an in-flight pack. Batches train in order through the one-batch queue.Batcher.Confignow ownstraining_sample_builder(moved fromAsyncLoopConfig) next tordma_min_tensor_bytes; the controller reads neither.TrainingSampleBuilder, the batch order, the one-batch queue, and the trainer side (it reads as before, now from the batcher's process).Results
Wall time per batch. CPU benchmark, one host, torch 2.15 nightly, torchmonarch 0.6.0: 8 groups x 8 rollouts x 8 turns -> 1 batch of 32 microbatches, dp 4; a task on the controller's event loop burns CPU for of every 10 ms. "main" built on the event loop; main now builds in
asyncio.to_thread(not re-measured):On an idle loop it costs ~0.1 s more per batch, for pickling the groups and registering buffers.
You may ask:
ProcessPoolExecutor? Its pipe moves the batch in 64 KB reads, each one a GIL handoff: 26 s at 100% load.asyncendpoints? Monarch rejects mixing sync and async endpoints, and the release awaits the buffer drops. They stay plain@endpoint, so groups are processed one at a time, in arrival order.sys.setswitchinterval(0.0005)? It cuts the busy-loop time 4x (3.2 -> 0.75 s), but it's process-wide: the event loop gets preempted 10x more often.NOTE:
async_loop.training_sample_builder->async_loop.batcher.training_sample_builder. Old configs fail loudly (TypeErrorat construction,AttributeErroron access)._batcher_loopis blocked on the queue): ~53 GB at 17.8 GB per batch with router replay, plus transient copies on TCP; the controller holds none. A released batch's memory returns by the batcher's next call.[RdmaXcel]lines in the GPU run vs 152 before). Created at spawn while trainer rank 0 starts on GPU 0: on exclusive-process GPUs one of them fails.MonarchRDMAMicrobatches. On 0.6 the batcher hangs within its first few steps.training_sample_builderandbatcher_packmove to a newrl_batcherstructured log; the controller logsbatcher_add_grouparound the call and sends the step withbroadcast.num_tokens_per_microbatch_per_dp_ranknot a multiple ofmax_context_length) now fail at actor spawn, in the batcher process's traceback.TrainingSamples hold tensors, so many more torch ops per pack (0.1 -> 18 s under this benchmark, vs main's 0.2 -> 3.6-4.1 s). This PR has not run at scale.Follow up:
batcher_add_group.Test plan
pytest tests/rl/unit_tests/cpu(repo root, Monarch 0.7, merged with main): 498 passed, 5 skipped.test_batcher_actor.py: spawnsBatcherActorin its own process (TCP), with and withoutrdma_min_tensor_bytes=1024. 5 groups (one untrainable) make batches A and B; after releasing A, B still reads back to the in-process batch, every tensor exact (256-token microbatches: the int64 fields cross by ref, the token counts by value). Unset, both batches come back by value and match. A builder error surfaces atcall_one.rdma_min_tensor_bytes=1024):loss/meanbitwise equal to main's DP 2 at every step, 0[RdmaXcel]lines. Over TCP, the next PR's head matches too. Both before the merge with main.rdma_min_tensor_bytes=1024:loss/meanbitwise equal to the by-value run (earlier push, same config and seed), 0[RdmaXcel]lines, and therl_batcherlog written by the actor.