Skip to content

[rl] Build and pack training batches in their own process - #5291

Merged
felipemello1 merged 56 commits into
mainfrom
felipemello1/trainer-pull/3-batcher-process
Oct 15, 2026
Merged

felipemello1 merged 56 commits into
mainfrom
felipemello1/trainer-pull/3-batcher-process

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

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

  1. One GIL. _batcher_loop builds training samples and packs microbatches inside the controller process.
  2. Busy loop. On large runs, the controller's event loop holds that GIL most of the time, serving rollouts.
  3. Build and pack wait. build_from_group and add_training_samples run in asyncio.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.
  4. How much. A batch is thousands of small torch ops: 0.2 s alone, 3.7-5.4 s next to a busy loop.
  5. At scale. On a 10-node agentic run, the trainer idled 54% of each step: the batcher took 100-180 s per batch vs 80 s of forward/backward.

Solution

  1. Own GIL. Build and pack in a separate process, as the router already does.
  2. BatcherActor (torchtitan/rl/actors/monarch/batcher.py): a thin Monarch wrapper over Batcher, like VLLMGeneratorActor, spawned by setup_async on a one-process mesh on the controller host. The new Batcher.add_group(rollout_group=...) builds the group's training samples and packs them. It returns each finished batch by value or, with rdma_min_tensor_bytes set, as MonarchRDMAMicrobatches whose tensors it keeps (the RDMA PR's code, unchanged).
  3. Release. After forward_backward, in a finally, the trainer loop calls batcher.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.
  4. Config: Batcher.Config now owns training_sample_builder (moved from AsyncLoopConfig) next to rdma_min_tensor_bytes; the controller reads neither.
  5. Unchanged: packing, TrainingSampleBuilder, the batch order, the one-batch queue, and the trainer side (it reads as before, now from the batcher's process).
before (controller process, one GIL)
  event loop thread:  serve rollouts, ...                                     <- holds the GIL most of the time
  to_thread worker:   build_from_group, add_training_samples, then register  <- every torch op: release, wait up to 5 ms

after
  controller:       await batcher.add_group.call_one(rollout_group=group)          <- pickle a group, unpickle the batch
                    await trainer.forward_backward.call(packed.microbatches, ...)   <- by value, or MonarchRDMAMicrobatches
                    batcher.maybe_release_oldest_batch.broadcast()                   <- a no-op by value
  batcher process:  build_from_group + add_training_samples (+ register buffers on the fast path; its own GIL)
  trainer ranks:    by value: the column arrives in the call; fast path: read it from the batcher 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):

                 main (in the controller)   this PR, by value (default)   this PR, fast path
loop idle        0.23-0.25 s                not measured                  0.35-0.36 s
loop 50% busy    0.39-0.41 s                not measured                  0.36-0.45 s
loop 100% busy   3.7-5.4 s                  2.0-4.5 s                     0.61-0.70 s

On an idle loop it costs ~0.1 s more per batch, for pickling the groups and registering buffers.

You may ask:

  • Why not a ProcessPoolExecutor? Its pipe moves the batch in 64 KB reads, each one a GIL handoff: 26 s at 100% load.
  • Why async endpoints? 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.
  • Why FIFO release, not keyed by step? The batcher doesn't know a batch's step when it packs it, and batches train in order. A lost broadcast holds one extra batch; it never frees an unread one.
  • Why not 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.
  • Why not fewer torch ops in the packer? The cost is still ops x 5 ms, and it grows with the microbatch count.
  • Why not move rollout serving out of the controller? It removes the load at its source but is a larger change; the batcher should stay off the controller's GIL either way.

NOTE:

  • BC-breaking: async_loop.training_sample_builder -> async_loop.batcher.training_sample_builder. Old configs fail loudly (TypeError at construction, AttributeError on access).
  • The input side remains: sending a group pickles it on the event loop: 0.02 s for 8 rollouts x 8 turns, 0.04-0.07 s for 8 x 40 turns (measured when each turn stored its full prompt; main now stores a delta). Router replay and top-k add per-token data.
  • Memory (fast path): the batcher holds up to 3 batches (training, queued, one more if _batcher_loop is 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.
  • CUDA context (fast path): moves from the controller into the batcher process, which now registers the buffers (~256 MiB on GPU 0; 0 [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.
  • Needs Monarch ≥ 0.7 for the fast path (main pins it): its reentrant drop lock lets the batcher keep only the MonarchRDMAMicrobatches. On 0.6 the batcher hangs within its first few steps.
  • Reads don't slow down while the batcher packs: the owner side of a read needs neither its GIL nor its actor loop (CPU probe, 4 readers, 81.7 MB microbatches: 115 ms per microbatch idle vs 105-117 ms while the batcher spins, packs or registers).
  • Spans: training_sample_builder and batcher_pack move to a new rl_batcher structured log; the controller logs batcher_add_group around the call and sends the step with broadcast.
  • Config errors (e.g. num_tokens_per_microbatch_per_dp_rank not a multiple of max_context_length) now fail at actor spawn, in the batcher process's traceback.
  • The 10-node run used a branch whose 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.
  • Not tested: multiple hosts, the RL GPU CI.

Follow up:

  • Send only the fields the builder reads, or let rollouts reach the batcher directly, if group pickling shows up in 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: spawns BatcherActor in its own process (TCP), with and without rdma_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 at call_one.
  • GPU, Qwen3-0.6B, H100, batch invariant, lockstep, Monarch 0.7, 5 steps:
    • trainer DP 2 (3 GPUs), RDMA buffers over ibverbs (now rdma_min_tensor_bytes=1024): loss/mean bitwise 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.
    • the whole stack at the previous push (the next PR's head), DP 1 (2 GPUs), rdma_min_tensor_bytes=1024: loss/mean bitwise equal to the by-value run (earlier push, same config and seed), 0 [RdmaXcel] lines, and the rl_batcher log written by the actor.

@felipemello1
felipemello1 added this pull request to stack #5287 October 11, 2026 19:39
@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 force-pushed the felipemello1/trainer-pull/3-batcher-process branch from f13d2d7 to b158175 Compare October 11, 2026 19:40
@felipemello1
felipemello1 marked this pull request as ready for review October 11, 2026 19:49
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 11, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/trainer-pull/3-batcher-process branch 2 times, most recently from 87f9449 to ff3fdc9 Compare October 11, 2026 22:43
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 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.

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.

Comment thread torchtitan/rl/controller/controller.py Resolved
@felipemello1
felipemello1 force-pushed the felipemello1/trainer-pull/3-batcher-process branch from ff3fdc9 to 20649e2 Compare October 12, 2026 01:09
@felipemello1

Copy link
Copy Markdown
Contributor Author

reply from claude:

Thanks! I pushed one commit:

  • Your test: the batcher makes batches A and B and releases A once; B still reads back exactly. A second actor on the same mesh with the threshold unset (the new default) returns both batches by value.
  • Comments:
    • Why each held batch keeps its tensors: Monarch 0.6's drop deadlock.
    • The batcher drops the buffers it owns itself, in release_oldest_batch, so the drop stays on the owner's host even if the batcher moves. The controller doesn't drop anything in this PR.
  • Monarch 0.7: I'm testing it in a separate PR. If it fixes the deadlock in our stress repro, I'll drop the delayed free and the held batches here.

- 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 force-pushed the felipemello1/trainer-pull/3-batcher-process branch from 20649e2 to ced9e33 Compare October 12, 2026 03:18
@felipemello1

felipemello1 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor Author

reply from claude:
@pzhan9
Moved to Monarch 0.7 in one new commit. The batcher keeps only the RDMAMicrobatches; the held TrainerStepBatch and the delayed free are gone. Both were only there for 0.6's drop deadlock, and 0.7's cache lock is reentrant.

CPU, TCP fallback                0.6.0               0.7.0
free the tensors, then drop()    hangs at step 0     600 of 600 steps x 200 buffers
drop(), then free right away     3 of 18 runs hang   0 of 22 runs, 120K buffers each

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 BatcherActor in this order was clean over TCP and ibverbs. On GPU (Qwen3-0.6B, 5 steps through the batcher process), loss is bitwise equal with the fast path on and off. This needs the Monarch 0.7 floor, which lands first.

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.
Felipe Mello added 10 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.
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.
@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
Base automatically changed from felipemello1/trainer-pull/2-prefetch to main October 15, 2026 06:05
@pytorch-bot pytorch-bot Bot added the ciflow/b200 Trigger B200 CI label Oct 15, 2026
@felipemello1
felipemello1 merged commit 9a14d25 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/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.

3 participants