Repository navigation
[WIP] [rl] Trainer DP replica leaders read their rollouts from the rollout workers and pack them - #6303
[WIP] [rl] Trainer DP replica leaders read their rollouts from the rollout workers and pack them#6303wwwjn wants to merge 1 commit into
Conversation
|
@claude review |
There was a problem hiding this comment.
Verdict: Needs discussion -- the data path checks out, but packing now sits on the step's critical path and the controller's GC is higher at T1, and neither is measured on this head. Maintainers need those numbers to decide.
What this PR does. The batcher now returns only a StepPlan. The controller keeps each trainable group's summary and arrays until its step. It then sends each DP replica's leader (pp 0, cp/tp 0) that replica's column of the plan, plus only the rollouts the column names. On every rank, a MicrobatchGroupReader thread produces the step's microbatch groups: the leader materializes and packs each group and broadcasts it over a per-replica gloo group, the other ranks receive it, and every rank preprocesses its images. The RDMA microbatch path is deleted.
Example. dp=2, tp=2, one microbatch per group, plan [[[s00, s01]], [[s10, s11]]]:
before: batcher packs mb00..mb11 -> controller -> ranks 0 and 1 each get [[mb00],[mb10]],
ranks 2 and 3 each get [[mb01],[mb11]] (2 copies per replica)
after: rank 0 <- ReplicaColumn([[[s00]],[[s10]]], groups named by s00/s10, select_rollouts)
rank 0 packs mb00, broadcasts it over gloo{0,1}, packs mb10, broadcasts it, ...
rank 2 does the same for column 1 over gloo{2,3}
forward_backward(num_microbatch_groups=2, global counts) (no tensors)
Must fix
-
PR description. Three things:
- The human-written summary is still "TODO (Jiani)".
- The 4K rows come from an earlier commit, and the PR says the 4K exposure run is "pending".
- The T1 step-time comparison is confounded by the generator pull, which main has since fixed.
Please report head vs. parent on the same base for the claims the PR rests on (4K RSS/CPU and step time, T1 step time).
-
controller.py:1374-- packing moved from the pipelined batcher into the step, and that cost is unmeasured on this head (inline). -
torchtitan/rl/actors/monarch/README.md:111,117-118(not in the diff) -- two lines are stale:- "The batcher ... sees RDMA values only through
RDMAObject": the batcher and the trainer no longer touch RDMA. - The
TrainerHandledescription doesn't mentionleader_by_dp_rank.
- "The batcher ... sees RDMA values only through
Should consider
tests/rl/unit_tests/cpu/test_async_controller.py:120--_PackingBatcherre-implements_replica_columnswithoutselect_rolloutsandwithout_metrics(inline).tests/rl/unit_tests/cpu/test_microbatch_group_reader.py:312-- the wall-clock assert is redundant and could flake (inline).tests/rl/unit_tests/cpu/test_microbatch_group_reader.py:9,128-129-- the docstrings narrate history ("the microbatches the batcher used to pack"). Describe the reference as "packed in plan order from the full groups".tests/rl/unit_tests/gpu/test_cp_images.py:14-- the docstring says the column crosses the broadcast, but the packed group does (inline).
Questions
controller.py:1280-- the T1 controller GC goes from 44 to 350 ms per step, and every other step it lands on the critical path. Was the alternative considered where the batcher keeps the arrays and sends each column to its leader directly? Otherwise, should this PR land together with the group RDMA handle PR (inline)?
Details
Gate: the problem is real and measured (7.84 GB controller RSS and a 2.33 s add_group at 4K). The leader-plus-gloo design is justified by the microbench in the description: it breaks even at 2-3 ranks per replica and keeps controller bytes flat in N. Nothing in direction.md conflicts with it.
Checked at HEAD, no issue found:
TrainingEngine.forward_backwardreads the reader in a single pass on both paths: the list comprehension in_preprocess_microbatch_groupswhen lazy is off,enumeratein_forward_backward_bodywhen it is on. Lazy mode is banned with accelerator graphs and SDC replay, so the reader is never replayed.TrainingSampleBuilder.materializematches specs to rollouts byrollout_id, and the advantage lives on the rollout. So the subset thatselect_rolloutssends builds the same samples as the full group.build_dp_replica_groupuses the(pp, dp_replicate, dp_shard, cp, tp)dense mesh, folds DP replicate-major, and makes the leader(pp0, cp0, tp0). That matchestrainer_pp_dp_cp_tp.slice(pp=0, dp=d, cp_tp=0). If the two ever disagree,receive_replica_columnfails on its assert rather than training on the wrong data._step_num_tokens_per_dp_rankequals groups xnum_pp_microbatches(1 without PP), which matches what the batcher plans.- A grep found no references left to the removed symbols (
rdma_min_tensor_bytes,TrainerStepBatch,maybe_release_oldest_batch, ...).
Metric keys: payload/forward_backward_bytes_per_dp_rank and timing/trainer/read_microbatches/max are removed. Added: timing/trainer/{pack,broadcast}_microbatches/max, timing/step/send_replica_columns, timing/hop/receive_replica_column/* and payload/replica_column_array_bytes. Consider listing these in the description.
Not verified: GPU and multi-host gloo runs, and the 4K performance on this head.
| # TODO(async): can't stream microbatches (interleave pack->train) -- the loss is normalized by | ||
| # global counts over ALL microbatches, needed before any fwd/bwd. To | ||
| # support streaming, accumulate raw loss/token counts across microbatches and scale before optimizer. | ||
| # TODO: the leaders pack only once forward_backward starts. With |
There was a problem hiding this comment.
This TODO marks a main-path change that the PR's numbers don't measure yet. In the parent, the batcher packed step N+1 in its own process while the trainer ran step N, so packing was pipelined and the trainer only waited for the transfer (forward_backward transfer: 1.09 s at 4K, 241 ms at T1). Now everything below runs inside step N+1 before the first forward with preprocess_microbatch_groups_lazily=False, which is the default and what the recipes use: send_replica_columns, then the leader's materialize, pack and broadcast.
Rough sum from the PR's own figures: at 4K that is about 0.65 s + ~1.4 s against 1.09 s before. At T1 it is 374 ms + 89 ms against 241 ms. The only 4K step time in the PR comes from an earlier commit, and the T1 step time is confounded by the generator pull.
Please post head vs. parent on the same base at T1 and 4K, with lazy off. Rebase both on main, which already has the push fix. Break out send_replica_columns and the reader wait. Then maintainers can decide whether this exposure is acceptable until the "send columns during the previous step" follow-up, or whether that follow-up should be part of this PR.
| add_group_handler_s.append(handler_s) | ||
| if not group_is_trainable: | ||
| if group_is_trainable: | ||
| self._finished_groups_by_id[ |
There was a problem hiding this comment.
Question: this is where the T1 controller GC regression comes from. GC goes from 44 to 350 ms per step, with about 1.5 gen-2 collections per step, and every other step it lands inside send_replica_columns. The controller now holds every trainable group's Python object graph from add_group until its step, and before this PR the batcher process held it.
An alternative keeps the groups out of the controller: the batcher keeps the arrays, as the parent did, and sends each leader its column directly. The controller's pickling cost stays the same (it pickles the arrays once, to the batcher instead of to the leader), but its RSS and GC go back to the parent's. The cost is that the batcher gets the leader handles.
Was that considered? If the plan is instead for the group RDMA handle PR to fix this, should the two land together, so that main never carries the regression?
| @@ -114,6 +118,84 @@ def _variable_length_group(group_id: int, *, token_lengths: list[int]) -> Rollou | |||
| ) | |||
|
|
|||
|
|
|||
There was a problem hiding this comment.
_PackingBatcher is about 75 lines that re-implement Controller._replica_columns, and it differs from it in two ways:
- It passes whole groups, not
select_rollouts(...). - It skips
without_metrics().
It also reaches into self.batcher._training_sample_builder and forwards attributes through __getattr__. If the production column logic changes, these tests keep passing against the old behavior.
Fix: rewrite these planning tests to assert on StepPlan specs. The multiprocess test in test_microbatch_group_reader.py already covers plan -> packed microbatches. If packed output really is needed here, call the real _replica_columns instead of a copy of it.
| ) | ||
|
|
||
| # Within seconds, not the 60 s gloo timeout. | ||
| assert time.monotonic() - start < 50 |
There was a problem hiding this comment.
This wall-clock bound adds nothing and could flake. It includes spawning four processes that each import torchtitan, and it sits only 10 s below the 60 s gloo timeout. A rank that hangs until the timeout would get a gloo timeout error, and that already fails the startswith("RuntimeError: The DP replica's leader failed") check below. Drop the timing assert and start.
| distinct image once per microbatch, every placeholder token pointing at its row of the image | ||
| embeddings) and broadcasts it to the replica's other ranks, and `Trainer.forward_backward` | ||
| trains it: once without CP (FSDP=2, two one-rank replicas, each the same microbatch) and once | ||
| per CP layout (one replica of the two CP ranks, so the column crosses the gloo broadcast). |
There was a problem hiding this comment.
This docstring describes the data flow wrongly. Only the leader receives the column. What crosses the gloo broadcast is the packed microbatch group (MicrobatchGroupReader._send). Suggest "so the packed microbatch crosses the gloo broadcast".
f2b93f4 to
01072dd
Compare
01072dd to
20e59e4
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- this version answers the last review's open points with numbers from this head. The controller keeps one packed buffer per group, so its GC is back at the parent's level (150 vs 144 ms per step at T1). The data path still on the critical path is under 1% of the step at both T1 and 4K. A maintainer still needs to review: this touches the core of the RL controller, trainer and batcher, and it merges together with #6302.
What changed since the last review. The rollout worker now packs each finished group into byte regions (PackedRolloutGroup) and returns them next to a summary whose arrays are empty. The controller keeps only those regions, and sends each leader select(...) of them without unpickling. The leader unpacks one rollout group at a time, then packs and broadcasts over gloo as before.
Example. dp=2, tp=2; group 7 has rollouts 0..3, and DP rank 0's column names rollouts 0 and 2:
worker: pack_rollout_group(g7) -> summary (arrays empty), packed (4 rollout regions + 1 image region)
controller: batcher.add_group(summary); _packed_groups_by_id[7] = packed
step: leader 0 <- ReplicaColumn(specs, [packed.select({0, 2})]) # 2 regions + the image, no copy
leader 0: unpack -> materialize -> pack -> gloo broadcast to rank 1
all ranks: forward_backward(num_microbatch_groups, global counts) # no tensors
Earlier findings
- Resolved:
- The 4K and T1 numbers now come from this head against the parent, on the same base.
- The critical-path cost is measured: 125 ms at T1 and 1.57 s at 4K, under 1% of the step in both. The TODO points to read-ahead.
- The Monarch README lines are fixed.
- The planning tests now go through the real
Controller._replica_columnsinstead of_PackingBatcher. - The wall-clock assert is gone.
- The docstrings no longer narrate history, and the
test_cp_images.pydocstring is fixed. - The controller GC question is answered.
- Still open: the human-written summary.
Must fix
- PR description: the human-written summary is still "TODO (Jiani)". The author has to write it; agents leave it as is.
tests/rl/unit_tests/cpu/test_microbatch_group_reader.py:397-401:group_1_doneis set beforepacked.append(1), so the final assert races the reader thread (see inline).
Should consider
tests/rl/unit_tests/cpu/test_microbatch_group_reader.py:261: the test name says "the batcher packed", but the leaders pack now (see inline).tests/rl/unit_tests/cpu/test_finished_group.py:203: the "same samples as the full group" half of this test repeatstest_packed_group.py:177. Also,select({0, 1, 2})on a 3-rollout group returnspackeditself, so the "leader" step does nothing. Either keep only the checks for the slimmed fields here, or select a strict subset.
Details
Checked at HEAD, no issue found:
packed_group.py:- Pack and unpack compute the same arrays offset (
_align(8 + len(metadata))). selectkeeps the regions as views, so pickling writes only the kept bytes.- The regions come from a writable buffer, so they unpickle writable.
- Pack and unpack compute the same arrays offset (
- The rollouter sets
Rollout.advantagebefore the worker packs the group (rollouter.py:570), so the leaders' rollouts carry it. - Images: specs decided from the summary hold
data=b""._build_training_sampletakes the bytes from all of the rollout's turns'prompt_delta_images, which covers images that come before the spec's first turn. _packed_groups_by_id:- Only trainable groups are added.
- Every
plan.trainable_group_idsentry is deleted before the send, and the dict is cleared on shutdown. _take_groupsputs every trainable group into a plan, so nothing leaks.
- Leader failure: each rank reads on one worker thread. After the
_LeaderErrorbroadcast, later reads raise on every rank without a collective, so no rank waits for a broadcast that never comes. - Metric keys in the description match the code: the added and renamed keys, and the removed
payload/forward_backward_bytes_per_dp_rankandtiming/trainer/read_microbatches/max. - Minor, validation only: a validation group keeps its messages in both the summary and the packed metadata, so they cross from the worker twice. This is not on the training path.
Not verified: multi-host gloo replica groups (e.g. a PP replica that spans hosts) and GPU runs.
| if index == 1: | ||
| group_1_started.set() | ||
| time.sleep(0.2) | ||
| group_1_done.set() | ||
| packed.append(index) |
There was a problem hiding this comment.
This test has a race. group_1_done.set() runs before packed.append(1). After close(), pool.shutdown(wait=False) doesn't wait for the running read, so the only thing keeping assert packed == [0, 1] from seeing [0] is the 50 ms sleep. On a loaded CI host that can fail. Fix: set the event after the append. Keep the sleep: it is what lets a group 2 that wasn't cancelled show up.
| if index == 1: | |
| group_1_started.set() | |
| time.sleep(0.2) | |
| group_1_done.set() | |
| packed.append(index) | |
| if index == 1: | |
| group_1_started.set() | |
| time.sleep(0.2) | |
| packed.append(index) | |
| if index == 1: | |
| group_1_done.set() |
| ], | ||
| ids=["dp2_tp2", "pp2_tp2"], | ||
| ) | ||
| def test_every_rank_trains_on_the_microbatches_the_batcher_packed( |
There was a problem hiding this comment.
The name still says the batcher packs, but in this PR the leaders pack. The docstring already describes the reference correctly.
| def test_every_rank_trains_on_the_microbatches_the_batcher_packed( | |
| def test_every_rank_trains_on_its_column_packed_in_plan_order( |
|
@claude review again |
20e59e4 to
25dead1
Compare
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging -- the new push fixes the test race and both should-consider items from the last review. The only item left is the human-written summary. A maintainer still needs to review: this touches the core of the RL controller, trainer and batcher, and it merges together with #6302.
What this PR does. The rollout worker packs each finished group into byte regions and returns them next to a summary that has empty arrays. The batcher plans from the summaries only. The controller keeps only the packed regions and sends each DP replica's leader its column of the plan plus select(...) of the rollouts that column names. The leader unpacks, packs and broadcasts the microbatch groups over a per-replica gloo group.
Example. dp=2, tp=2. Group 7 has rollouts 0..3, and DP rank 0's column names rollouts 0 and 2:
worker: pack_rollout_group(g7) -> summary (arrays empty), packed (4 rollout regions + images)
controller: batcher.add_group(summary); keep packed
step: leader 0 <- ReplicaColumn(specs, [packed.select({0, 2})])
leader 0: unpack -> materialize -> pack -> gloo broadcast to rank 1
all ranks: forward_backward(num_microbatch_groups, global counts) # no tensors
Earlier findings
- Resolved:
test_microbatch_group_reader.py:400-402:group_1_doneis now set afterpacked.append(index), so the final assert no longer races the reader thread.test_microbatch_group_reader.py:261: the test is renamed totest_every_rank_trains_on_its_column_packed_in_plan_order.test_finished_group.py:200: the test now selects a strict subset ({0, 2}of 3 rollouts) and checks only the slimmed fields. It points totest_packed_group.pyfor the sample equality.
- Still open: the human-written summary.
Must fix
- PR description: the human-written summary is still "TODO (Jiani)". The author has to write it; agents leave it as is.
Not verified: I couldn't run the CPU tests in this job. Multi-host gloo replica groups and GPU runs are also unverified.
25dead1 to
4e38191
Compare
4e38191 to
770c439
Compare
4d1c3b3 to
bd7a62e
Compare
e36318f to
4876523
Compare
|
@claude review again |
|
Claude finished @wwwjn's task in 12m 40s —— View job Request changes: the opt-in RDMA group path folded in from #6323 has no recipe or CI config that turns it on, and on this head it is measured on only one host. Also, the group store's logic sits in the Monarch actor instead of the rollout worker. See the review. |
There was a problem hiding this comment.
Verdict: Request changes -- folding in #6323 added an opt-in RDMA group path (~1.5K lines with tests) that no recipe or CI config enables. On this head it is measured only on one host, and there it saves 30 ms per step. The rest of the new design is sound.
What this PR does. Since my last full review, rollout workers keep each training group (RolloutGroupStore) instead of the controller holding packed groups. A worker returns the group's metadata to the batcher and a small ref to the controller. At the step, each DP replica leader gets its column plus refs and fetches only its rollouts: one get_rollouts call per worker, or an RDMA read when rdma_min_group_bytes is set. It then packs and gloo-broadcasts as before. After the weight pull, release_groups tells the workers to drop the step's groups.
Example. dp=2, tp=2. Worker 3 keeps group 7 (rollouts 0..3). DP rank 0's column names rollouts 0 and 2:
worker 3: run_group -> store.keep(g7) -> (metadata, WorkerRolloutGroupRef(rank=3, g7))
controller: batcher.add_group(metadata); _rollout_group_refs_by_id[7] = ref
step N: leader 0 <- ReplicaColumn(specs, [ref.select({0, 2})])
leader 0: rollout_workers[3].get_rollouts([(7, (0, 2))]) -> build -> pack -> gloo to rank 1
after pull N: rollouter.release_groups([..., 7]) -> worker 3 drops g7
Earlier findings
- Resolved: the human-written summary (the "Human note" at the top of the description).
Must fix
- The RDMA group path has no in-repo consumer, and its evidence is thin. This covers
rdma_min_group_bytes(rollouter.py:426),rollout/rdma_rollout_group.py(452 lines),transport/torch_transport_rdma.py(340), the probe plumbing across the worker, rollouter, trainer and controller, and about 690 lines of tests.- No recipe or integration config sets the knob, so the worker buffers, probes and leader reads never run end to end in CI.
config.mdsays "expose only options a verified recipe uses". - On this head the only number is one host: 0.27 -> 0.24 s per step. The cross-host case it targets (GB300, 509 MB per leader) ran on an earlier version.
- The fetch path (
WorkerRolloutGroupRef) stands on its own. Either split the RDMA path into its own PR, stacked with #6334, which builds on its pool, or keep it here with two things: a cross-host measurement on this head, and an existing integration entry that turns it on.
- No recipe or integration config sets the knob, so the worker buffers, probes and leader reads never run end to end in CI.
actors/monarch/rollout_worker.py:58-65-- the store's keep/get/release/probe logic lives in the Monarch actor, not inBaseRolloutWorker(design.md: wrappers are thin adapters; see inline).- Stale docs:
torchtitan/rl/README.md:60(not in the diff) still says the controller loops "pack batches". They plan now, and the trainer leaders pack.batcher.py:11names the wrong packer method (see inline).actors/monarch/README.md:27has a stalerollout_worker.pyrow (see inline).rollouter.py:436-440narrates the earlier design (see inline).
Should consider
trainer.py:169--rollout_groups_by_rdmais a bool derived from the rollouter's config; you can drop it (see inline).trainer.py:110-- the leader choice andgroup_src=0agree only by mesh layout; derive the leader from the group rank (see inline).test_trainer_loop.py:331-- the wall-clock upper bound could flake (see inline).- If the RDMA path stays in this PR:
rdma_rollout_group.py:349-358: if_serializeraises afterallocate, the pooled buffer is never released.torch_transport_rdma.py:RDMAByteBuffers.readhas no timeout, unlikeModelStateDictTransport, and the private-API TODO at line 41 has no issue link.
Questions
- #6423 (tianyu-l) renames
Batcher->TrainingBatchBuilderandTrainerStepBatch->TrainingBatchacrossbatcher.py,controller.pyandtrainer.py. This PR deletesTrainerStepBatchand rewrites those files. Which lands first? - The replica's gloo group uses
comm.train_timeout_seconds(100 s by default). Before broadcasting group 0, the leader fetches and builds its whole column. Is 100 s enough for the Terminal-Bench case over endpoint calls across hosts?
Details
Overlap search (gh pr list --search): "rollout group store", "torch_transport", "microbatch prefetcher", "batcher controller rl". Found:
- #6423, the rename above.
- #6283, which runs the batcher on the last trainer host with RDMA. This PR mostly supersedes it.
- The stream-microbatches stack (#5729, #5764), which builds on the RDMA microbatch prefetcher this PR deletes.
- #6324 and #6334, this PR's own stack.
Checked at HEAD, no issue found:
- Release order: trained groups are released only in
_pull_model_state_dict_and_release_groups, after the gather over every DP rank'sforward_backward. Each leader's fetch or RDMA wait finishes inside it, so no group is dropped before its last read. - Every
keephas a release:- Untrainable groups are released in
_batcher_loop. - A failed group has no ref, but the release is broadcast by id, so a worker that kept it drops it.
- Validation groups aren't kept.
- Untrainable groups are released in
_rollout_group_refs_by_id: each trainable ref is consumed by_replica_columnsand deleted before the send, and it is cleared on shutdown.- Gloo symmetry:
num_microbatch_groupsis the same on every rank of a replica. A leader failure broadcasts_LeaderError, and later groups raise on every rank without a collective. - No
torch.cudain the new code. No references remain to removed symbols (TrainerStepBatch,RDMAMicrobatch,rdma_min_tensor_bytes,read_microbatches,PackedRolloutGroup). The metric keys match the description. NIXL was already pinned ininstall_rl_env.sh, andtorch.distributed._transportis imported lazily.
Not verified: I couldn't run the CPU tests in this job, and I couldn't check whether the requires_nixl tests run or skip on the CPU RL runner. Multi-host gloo replica groups and GPU runs are also unverified.
| # With `rdma_min_group_bytes`, large training groups stay here in registered memory for | ||
| # the trainer to read by RDMA (`RolloutGroupStore`). | ||
| self._rdma_min_group_bytes = worker_config.rdma_min_group_bytes | ||
| self._rdma_byte_buffers: RDMAByteBuffers | None = None | ||
| if worker_config.rdma_min_group_bytes is not None: | ||
| self._rdma_byte_buffers = RDMAByteBuffers() | ||
| # Set by `setup_async`, which gets this worker's rank in its pool. | ||
| self._store: RolloutGroupStore | None = None |
There was a problem hiding this comment.
The group store's lifecycle lives in the Monarch actor, not in the worker core. The actor does all of this itself:
- reads
worker_config.rdma_min_group_bytes(BaseRolloutWorker.__init__never reads it); - builds
RDMAByteBuffersandRolloutGroupStore; - chooses keep vs. not by
is_validationinrun_group; - implements
get_rollouts,release_groups,make_rdma_probeanddrop_rdma_probeon top of the store.
design.md says actor wrappers are thin adapters: "any sequencing (setup, metrics, shutdown) that every actor system would need lives in the core". A second actor system would have to copy this keep/get/release logic, and the rule exists to prevent exactly that.
Fix: BaseRolloutWorker owns the store. It builds it from its own config plus the worker_rank it gets in setup_async, run_group returns (metadata, ref), and the store methods live on the worker. These endpoints then become one-line forwards, as sync_log_step is. This mostly moves about 40 lines and adds none.
| training samples into microbatches (`MicrobatchPacker`, on each trainer DP replica's leader). | ||
|
|
||
| Batcher: metadata -> plan_training_samples -> plan the batch -> `TrainingBatchPlan` | ||
| replica leader: plan column + rollout arrays -> build_training_samples -> `MicrobatchPacker.pack` |
There was a problem hiding this comment.
The leaders call pack_planned (MicrobatchGroupPrefetcher._pack), not pack. Also, they get rollouts here, not "rollout arrays".
| replica leader: plan column + rollout arrays -> build_training_samples -> `MicrobatchPacker.pack` | |
| replica leader: plan column + its rollouts -> build_training_samples -> `MicrobatchPacker.pack_planned` |
| | `rdma_object.py` | `MonarchRDMAObject`, the `RDMAObject` (`rl/transport/rdma_object.py`) on Monarch RDMA buffers: the owner keeps a value's large tensors and bytes, and a reader reads them in one RDMA action. The batcher keeps microbatches for the trainer ranks, and a rollout worker keeps prompt image files for generator rank 0. | | ||
| | `batcher.py` | `BatcherActor`, the endpoints of `rl/trainer/batcher.py`'s `Batcher`, in its own CPU process. | | ||
| | `rdma_object.py` | `MonarchRDMAObject`, the `RDMAObject` (`rl/transport/rdma_object.py`) on a Monarch RDMA buffer: the owner keeps a large bytes value, and a reader reads it by RDMA. A rollout worker keeps prompt image files for generator rank 0. | | ||
| | `rollout_worker.py` | `RolloutWorkerActor`, a rollout worker in the controller-host CPU pool; supplies `MonarchRDMAObject.register`. | |
There was a problem hiding this comment.
This row is stale. The rollout worker actor now keeps each training group until its step (RolloutGroupStore). It also serves get_rollouts and release_groups to the trainer leaders and the controller, plus the RDMA probe endpoints when rdma_min_group_bytes is set. Please say that here, since this table is where a reader looks to learn what each actor does.
| 17 MB per 16-rollout group at 4K tokens), routed experts, or images. Keep small groups | ||
| fetched: a leader reads every group of its column before its first microbatch, and by | ||
| RDMA alphabet sort's 8.7 KB groups (256 per step) added ~32 ms to that wait over taking | ||
| them by value (63 -> 95 ms, measured when the controller still held the groups); ~1 MiB | ||
| is a reasonable threshold. |
There was a problem hiding this comment.
"measured when the controller still held the groups" describes an earlier design. Docs describe the current state, so it doesn't belong in the docstring. Either re-measure 63 -> 95 ms on this head, or keep the number and drop the parenthetical. The same applies to the docstring at tests/rl/unit_tests/cpu/transport/test_torch_transport_rdma.py:135-137.
| pad_id: int, | ||
| temperature: float, | ||
| vision_processor: VisionProcessor.Config | None, | ||
| rollout_groups_by_rdma: bool, |
There was a problem hiding this comment.
rollout_groups_by_rdma is an enable_*-style boolean. The controller computes it from another component's config (config.rollouter.worker.rdma_min_group_bytes is not None, controller.py:871). It does two things:
- builds
RDMAByteBufferson the leaders; - decides whether
payload/trainer_read_bytes/maxexists.
You could drop the parameter:
- Build the leader's
RDMAByteBuffersincheck_rdma_probes, which setup calls exactly when the path is on. - Always report the read bytes. The value is 0 when every group is fetched, so the metric key no longer depends on the config.
That removes about 10 lines. If the RDMA path moves to its own PR (see the review body), this moves with it.
| return None, True | ||
| replica_group, _ = dist.new_subgroups_by_enumeration( | ||
| ranks_by_dp_rank, timeout=timeout, backend="gloo" | ||
| ) |
There was a problem hiding this comment.
The leader is replica_ranks[0], the first rank in (pp, cp, tp) order. The prefetcher, though, broadcasts from group_src=0, and new_group sorts its ranks, so group rank 0 is min(replica_ranks). The two agree only while the dense mesh is row-major with pp outermost. That holds today, but nothing checks it. If they ever diverged, a non-leader would be the broadcast source. Its column is None, so _receive would deadlock the replica until the gloo timeout.
To tie the leader to the broadcast source by construction:
| ) | |
| return replica_group, dist.get_group_rank(replica_group, dist.get_rank()) == 0 |
receive_replica_column's assert still catches a mismatch with the actor system's slice(pp=0, cp_tp=0).
| assert metrics["timing/step/send_replica_columns"].value.value >= 0.05 | ||
| assert metrics["timing/step/forward_backward"].value.value < 0.05 |
There was a problem hiding this comment.
forward_backward < 0.05 is a wall-clock upper bound, so a loaded CI runner can fail it. The test's point is that the column send isn't inside the forward_backward timer, and comparing the two timers checks that without an absolute bound:
| assert metrics["timing/step/send_replica_columns"].value.value >= 0.05 | |
| assert metrics["timing/step/forward_backward"].value.value < 0.05 | |
| assert metrics["timing/step/send_replica_columns"].value.value >= 0.05 | |
| assert ( | |
| metrics["timing/step/forward_backward"].value.value | |
| < metrics["timing/step/send_replica_columns"].value.value | |
| ) |
4876523 to
0434059
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Needs discussion -- every must-fix from the last review is fixed. What's left is the merge order with tianyu-l's open stack (#6423, then #6427), which rewrites the packing code this PR moves to the trainer leaders. That's a maintainer decision, not something the author can settle alone.
What changed since the last review. The branch is now one commit.
- The opt-in RDMA group path (
rdma_min_group_bytes,rdma_rollout_group.py,torch_transport_rdma.py, the probes,rollout_groups_by_rdma) moved to #6469. A grep at HEAD finds none of it left. BaseRolloutWorkernow owns theRolloutGroupStore(start_group_store,keep_group,get_rollouts,release_groups). The Monarch actor's endpoints just forward to it, and the Verifiers worker callsstart_group_storeitself.
Example. dp=2, tp=2. Worker 3 runs group 7 (rollouts 0..3), and DP rank 0's column names rollouts 0 and 2:
worker 3: run_group -> finish_rollout_group -> keep_group -> (metadata, RolloutGroupRef(3, 7, (0,1,2,3)))
controller: batcher.add_group(metadata); _rollout_group_refs_by_id[7] = ref
step N: leader 0 <- ReplicaColumn(specs, [ref.select({0, 2})])
leader 0 thread: by_rank[3].get_rollouts([(7, (0, 2))]) -> build -> pack_planned -> gloo to rank 1
after pull N: rollouter.release_groups([..., 7]) -> worker 3 drops group 7; the other workers ignore the id
Earlier findings
- Resolved:
- The RDMA group path with no consumer is out of this PR (moved to #6469).
- The store's lifecycle now lives in
BaseRolloutWorker(rollouter.py:486-515), not the Monarch actor. - The stale docs are fixed:
rl/README.md:60,batcher.py:11, therollout_worker.pyrow inactors/monarch/README.md, and therollouter.pyparenthetical, which left with the RDMA path. rollout_groups_by_rdmais gone.- The leader is now group rank 0 (
trainer.py:107), the broadcast source by construction. - The
test_trainer_loop.pywall-clock bound now compares the two timers. - The gloo timeout question is answered in the NOTE.
- Still open: the land order with #6423 (see below).
Must fix
- Coordinate with #6423 and #6427 (tianyu-l, both open).
- #6423 renames
Batcher->TrainingBatchBuilderandTrainerStepBatch->TrainingBatch. This PR deletesTrainerStepBatchand addsTrainingBatchPlan,MicrobatchPackerandBatcher.Config.microbatch_packer. - #6427, stacked on #6423, rewrites
_pack_training_samplesto sharepack_microbatch_fieldswith the pretraining collators. That is the code this PR moves intoMicrobatchPacker, which the leaders run. - Whichever lands second has to redo its half by hand, and the names (
BatchervsTrainingBatchBuilder,TrainingBatchPlanvsTrainingBatch) need one answer. Please agree on the order with tianyu-l and note it in the stack table.
- #6423 renames
Should consider
rollout/rollout_group_store.py:80: the kept group keeps itsrecorder_linesuntil release (inline).trainer/microbatch_group_prefetcher.py:278,289: the broadcast value's type says a 4-tuple, but the code sends 3 values (inline).
Details
Overlap search: "rollout group store", "TrainingBatchBuilder". Found #6423 and #6427 (above), this PR's own stack (#6302, #6324, #6334, #6469), and unrelated RL PRs (#6380, #5303, #5948, #6269, #5919, #6406).
Checked at HEAD, no issue found:
- Every kept group is released exactly once by id:
- An untrainable group (including a failed one with no ref) is released in
_batcher_loop. - A trained group is released in
_pull_model_state_dict_and_release_groups, after every DP rank'sforward_backward. Each leader'sget_rolloutsfinishes inside that call, so no group is dropped before its last read. - Validation groups are never kept.
- An untrainable group (including a failed one with no ref) is released in
- Slot accounting is unchanged:
release_active_groups(len(group_ids))releases 1 slot per untrainable group, andlen(trainable_group_ids) == num_prompts_per_train_stepper step. read_rollout_groupsmakes one call per worker and returns the groups in ref order. A failed fetch raises inside_pack, so the replica gets_LeaderErrorand the run stops.build_dp_replica_groupreturns early only for one-rank replicas. Replicas are uniform, so either every rank skips the collectivenew_subgroups_by_enumerationor none does.- Every
setup_asyncoverride in the repo (Verifiers, the test fakes) starts the group store. - The metric keys match the description:
send_replica_columnsis also counted in the step's accounted time.
Not verified: I couldn't run the CPU tests in this job. Multi-host gloo replica groups and GPU runs are also unverified.
My earlier REQUEST_CHANGES still blocks the PR. A code owner can lift it with @claude override, or I'll approve once the merge order is settled.
| def keep(self, group: RolloutGroup) -> tuple[RolloutGroupMetadata, RolloutGroupRef]: | ||
| """Keep training group `group` here. Returns its metadata for the batcher and its | ||
| ref.""" | ||
| self._groups_by_id[group.group_id] = group |
There was a problem hiding this comment.
The kept group still carries recorder_lines, which finish_rollout_group filled in just before this. The worker holds that JSONL string until the group's release, even though the controller already got it through the metadata and get never returns it. Dropping it here costs nothing, and the metadata is still built from the full group below:
| self._groups_by_id[group.group_id] = group | |
| self._groups_by_id[group.group_id] = replace(group, recorder_lines="") |
| return [samples_by_id.pop(spec.rollout_id) for spec in specs] | ||
|
|
||
| def _send( | ||
| self, value: tuple[list[TrainingMicrobatch], float, float, int] | _LeaderError |
There was a problem hiding this comment.
This annotation (and the one at line 289) declares a 4-tuple ending in int, but _prefetch sends (microbatch_group, self.pack_s, self.read_s) and _receive unpacks three values. It looks like a leftover from the removed RDMA read-bytes field.
| self, value: tuple[list[TrainingMicrobatch], float, float, int] | _LeaderError | |
| self, value: tuple[list[TrainingMicrobatch], float, float] | _LeaderError |
0434059 to
04184d7
Compare
04184d7 to
597037a
Compare
|
from claude: Rebased onto #6301's new head 6e2d4ba, where each rollout worker records its own groups ( |
There was a problem hiding this comment.
Verdict: Needs discussion -- the rebase onto #6301's new head is consistent, and both should-consider items from the last review are resolved. The open item is still the merge order with tianyu-l's open #6423 and #6427, and that's a maintainer decision.
What changed since the last review.
- On the new base, each rollout worker records its own groups (
run_and_record_group), andrecorder_linesis gone. A grep at HEAD finds no references left to it. Rollouter.setup_asyncnow callssetup_async.call_one(worker_rank=...)on eachpool.by_rank[i]. It no longer readscurrent_rank().rankinside the actor. So the rank in aRolloutGroupRefand the recorder file's rank both come from one source, the pool index.
Example. One training group on worker 1 of 2:
rollouter: by_rank[1].setup_async(worker_rank=1) -> start_group_store(1), start_recorder(worker_rank=1)
worker 1: run_and_record_group(g7) -> recorded here; keep_group(g7) -> (metadata, RolloutGroupRef(1, 7, ...))
controller: _rollout_group_refs_by_id[7] = ref; batcher.add_group(metadata)
leader: by_rank[1].get_rollouts([(7, ids)]) -> build -> pack_planned -> gloo
after pull: rollouter.release_groups([..., 7]) -> worker 1 drops g7
Earlier findings
- Resolved:
rollout_group_store.py:80: the kept group no longer carries recorder lines, because the field no longer exists.microbatch_group_prefetcher.py:278,289: the broadcast value is now annotated as the 3-tuple that_prefetchsends.
- Still open: coordinating the merge order with #6423 (
Batcher->TrainingBatchBuilder,TrainerStepBatch->TrainingBatch) and #6427 (shares_pack_training_sampleswith the pretraining collators, which is the code this PR moves intoMicrobatchPacker). Both are still open and unmerged, and the stack table doesn't mention them yet.
Must fix
- Agree on the land order with tianyu-l, and on a single set of names (
Batcher/TrainingBatchPlanvsTrainingBatchBuilder/TrainingBatch). Note the decision in the stack table.
Details
Checked at HEAD, no issue found:
- Every
setup_asyncthat matters now takesworker_rankand starts the group store:BaseRolloutWorker, Verifiers (examples/verifiers/rollouter.py:263), and the fakes intest_rollout_group_store.pyandtest_rollouter_pool.py. OnlyRolloutWorkerActor.__init__'s structured-logger rank still readscurrent_rank().rank, and that is the same index asworkers.slice(cpus=rank). - Validation reads its rewards and metrics from
RolloutGroupMetadata.group(controller.py:968-970), and the worker has already recorded the group, so the controller records nothing. - A group that fails after
keep_grouphas no ref._batcher_loopreleases its id to every worker anyway, so it doesn't leak.
Overlap search: "TrainingBatchBuilder". It found only #6423 and #6427, the same as last time.
Not verified: I couldn't run the CPU tests in this job, and I couldn't fetch the previously reviewed head to diff the rebase directly. Multi-host gloo replica groups and GPU runs are also unverified.
My earlier REQUEST_CHANGES still blocks the PR. A code owner can lift it with @claude override, or I'll approve once the merge order is settled.
…workers and pack them
597037a to
7dfd499
Compare
Human note:
TLDR: Rollout workers now keep each scored training group and send the controller only its metadata (for the batcher) and a small ref. At the group's step, each trainer DP replica leader fetches the rollouts its column names straight from the workers, packs the replica's microbatches and broadcasts them over gloo. The controller never holds a group's arrays. At 4K completions with score centering, batcher RSS drops 3.24 -> 1.14 GB,
add_group2.31 -> 0.40 s per step and controller RSS 3.31 -> 2.40 GB.Merge bottom-up. This PR now includes #6323 (closed); its opt-in RDMA path for large groups moved to #6469.
Problem
add_groupstill sends it every group's arrays, and it holds every trainable group until its step.TrainerStepBatch).add_group2.31 s per step, 508 ms of gen-2 GC per step in the batcher.Solution
BaseRolloutWorker.keep_group, which holds aRolloutGroupStorefrom newrollout/rollout_group_store.py) and returns its metadata (RolloutGroupMetadata.from_group: arrays cut to 0 rows plusRolloutTurnLengths) and aRolloutGroupRef(the worker's rank, the group id and its rollout ids).TrainingBatchPlan(spec grid, global token counts, metrics);TrainerStepBatchis deleted. Packing moves toMicrobatchPacker(inbatcher.py,Batcher.Config.microbatch_packer).Controller._rollout_group_refs_by_id) and sends each replica leader (rank 0 of the replica's gloo group: pipeline stage 0, CP and TP rank 0) its column plus refs to the rollouts it names (Trainer.receive_replica_column). A ref names its worker by rank; each leader gets the worker handles once at setup (Trainer.receive_rollout_workers).MicrobatchGroupPrefetcherthread runs. The leader fetches its rollouts (read_rollout_groups: oneget_rolloutscall per worker, all in flight), builds the samples, packs them (pack_planned) and broadcasts them over a per-replica gloo group (build_dp_replica_group).Rollouter.release_groupstells every worker to drop the step's groups.rdma_min_tensor_bytes,RDMAMicrobatch, its prefetcher) andMonarchRDMAObject's tensor, dataclass and by-value paths. Unchanged: the group's fields, filters, plan, packing, samples and losses.timing/trainer/read_microbatches/max. Added: on the trainertiming/trainer/{read_rollout_groups,pack_microbatches,broadcast_microbatches}/max; on the controllertiming/step/send_replica_columnsandperf/trainer/step_time_ratio/send_replica_columns.Results
NOTE:
rdma_min_group_bytes) moved to [WIP] [rl] Trainer leaders read large rollout groups by RDMA over torch transport #6469, which carries its measurements; every row here is the endpoint fetch.BaseRolloutWorker; both are bitwise-equal (Results). T1 on this head: column send 69 ms, first microbatch wait 103 ms (146 and 154 ms in the other lane order, on a busy host).comm.train_timeout_seconds(100 s by default). Before broadcasting group 0 the leader fetches and builds its whole column (4K, one host: 0.27 s fetch); a column fetched across hosts has to stay under that bound.Test plan
pytest tests/rl/unit_tests/cpu: 795 passed, 8 skipped, 4 failed ([WIP] [rl] Split the batcher into a metadata half and a bytes half #6302: 793; this PR deletes the RDMA microbatch tests). The 4 also fail on main076f2e88b(770 passed): recipe tests whosetorch_checkpointing.storage.fsspec_storageimport fails locally.tests/rl/unit_tests/gpu/test_cp_images.py(CP=2, images cross the gloo broadcast): 4 passed on 2 A100s, this head.test_microbatch_group_prefetcher.py: multi-process gloo, dp2_tp2 and pp2_tp2: every rank trains on exactly its column's microbatches, and a failing leader fails its replica.test_the_leader_raises_when_a_sample_disagrees_with_its_specfails without thepack_plannedchecks.test_rollout_group_store.py(new): a leader reads only its rollouts, with oneget_rolloutscall per worker; a leader thread reads from a real Monarch rollout worker actor, and a released group is gone.