Skip to content

[rl] Wake one waiter per work-buffer event - #6269

Draft
wwwjn wants to merge 1 commit into
mainfrom
wwwjn/data-plane/1-slots-by-group-id
Draft

wwwjn wants to merge 1 commit into
mainfrom
wwwjn/data-plane/1-slots-by-group-id

Conversation

@wwwjn

@wwwjn wwwjn commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Human note: TODO (Jiani)

TLDR: Each work-buffer event now wakes only the waiter it can unblock, instead of every rollout loop. This removes the controller as the bottleneck at large prompt counts: at 1,024 prompts per step, the step goes from 262 s (and growing) to 55.6 s and is now trainer-bound; at 256 prompts, controller CPU per step drops from 29-40 s to 4.6 s. Loss is bitwise identical.

This PR is on main and independent of the RL data-plane stack (#6303 -> #6323 -> #6334). That stack does not use this change; its measurements apply it on both sides, because without it the controller saturates at 256 prompts per step and hides their gains.

Problem

  1. Every buffer change (add_work, finalize_work, take_finalized, a slot release, close) calls notify_all on one condition, so all (target_offpolicy_steps + 1) x P rollout loops wake up.
  2. Each woken loop runs claim_next, which scans the whole buffer dict for the first WAITING entry. One claims; the others go back to wait. Each event costs (S+1) x P wakeups x O(entries).
  3. Cost: at 256 prompts per step, claim_next is 69-76% of the controller's CPU samples. The controller burns 29-40 s of CPU per step, and the trainer waits up to 9.6 s per step for a batch. At 1,024 prompts per step the step takes 262 s and keeps growing, for a 57 s forward_backward.

Solution

  1. Three asyncio.Conditions on one lock, one per kind of wait (controller/work_buffer.py):
    • add_work wakes one claim_next waiter, which pops a FIFO of WAITING ids instead of scanning.
    • finalize_work wakes one take_finalized waiter; taking a group wakes no one (the batcher loop is the only caller).
    • release_active_groups(count) wakes up to count slot waiters.
    • close() wakes everyone.
  2. Unchanged: slot accounting (release_active_groups by count), the admission bound, claims oldest-WAITING-first, take_finalized's window, the buffer metrics, the losses.
before:  add_work -> notify_all -> (S+1) x P loops wake -> each scans the dict -> 1 claims, the rest sleep again
after:   add_work -> notify(1)  -> 1 loop wakes -> pops the oldest WAITING id

Results

Qwen3-0.6B alphabet sort (T1), 4 GPUs on one host (trainer FSDP 2, two generators TP 1), target_offpolicy_steps=3
medians; before = main, 2 runs
256 prompts x 4 samples, 12 steps:
  controller CPU per step            29-40 s -> 4.6 s
  claim_next share of controller     69-76% -> 0%
  trainer waits for a batch          10 ms-9.6 s -> 11 ms
  add_group span per call            54-107 ms -> 5.9 ms
  generator requests in flight       7.5-11 -> 245
  step time                          28.9-38.3 s -> 30.4 s (forward_backward 28.5 s; 1.7 s generator pull, see NOTE)
1,024 prompts x 2 samples, 6 steps:
  step time                          262 s, growing (207, 248, 275, 304) -> 55.6 s (forward_backward 55.4 s)
  trainer waits for a batch          202 s -> 33 ms
  controller CPU per step            253 s -> 14.6 s
with score centering (k=32), 256 prompts: controller CPU 33-38 s -> 5.2 s, trainer wait 0.6-10 s -> 13 ms
correctness, this head: loss/mean, grad_norm and all 52 non-timing TensorBoard tags equal to main af04091d6 at
  every step, sorted rollout_samples.jsonl md5 equal (rl_grpo_qwen3_0_6b_varlen_batch_invariant, seed 42, 10 steps)

You may ask:

  • Why three conditions instead of one with notify(1)? The waiters wait for different events. notify(1) on a shared condition can wake the wrong kind of waiter: a slot release can wake an idle rollout loop instead of the data input loop waiting for a slot, and that wakeup is lost.
  • Why does the step at 256 prompts not get faster? That run is trainer-bound once the controller keeps up (forward_backward 28.5 s of 30.4 s). Main's 28.9 s run was in its fast regime; its slow regime is 38.3 s. The win there is the trainer no longer waiting and 6-9x less controller CPU.

NOTE:

  • Main at 256 prompts per step sits on the controller's saturation edge on this host. Within one run, a step costs 11-12 s or 30-45 s of controller CPU. So 256-prompt baselines are ranges over several runs, and 1,024 prompts gives the clean comparison.
  • With a fast controller, each weight push replied only after the next forward_backward ended, which added ~1.7 s per step at 256 prompts (timing/step/blocking_generator_pull_model_state_dict). Main now finishes the weight push before forward_backward, which removes it.
  • The timing results come from the same wakeup change on main (cc020983a), together with releasing slots by group id (now in [WIP] [rl] Trainer DP replica leaders read their rollouts from the rollout workers and pack them #6303, no timing effect), before rebasing onto main af04091d6. The wakeup logic is unchanged. The bitwise check ran on this head.
  • One host only; no multi-host run.

Test plan

  • pytest tests/rl/unit_tests/cpu: 712 passed, 8 skipped (main: 710 passed, 8 skipped).
  • test_add_work_wakes_one_claim_next_waiter: 5 condition waits instead of 9, i.e. no spurious wakeups. Fails on main.
  • test_close_unblocks_every_waiter: guards the new structure (passes on main too).
  • pre-commit run --files <touched files>: clean.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 20, 2026
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/1-slots-by-group-id branch from 6d8e740 to e99bb12 Compare November 20, 2026 16:55
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/0-hop-metrics branch from 43d7c83 to 7a0d11b Compare November 20, 2026 16:55
@wwwjn wwwjn changed the title [rl] Name the active rollout slots by group id [rl] Wake one waiter per work-buffer event; release slots by group id Nov 20, 2026
@wwwjn

wwwjn commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 1m 54s —— View job


Approve -- please address the items before merging (the human-written summary placeholder, and reverting the unrelated "retire" renames). See the review.

@claude claude Bot 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.

Verdict: Approve -- please address the items below before merging. This PR fixes the thundering-herd root cause that the old TODO in work_buffer.py already named, and the three-condition design has no lost wakeups on the current call graph. What's left is local cleanup.

What this PR does. RolloutGroupWorkBuffer drops its single notify_all condition. It now has three conditions on one lock: work added, work finalized and slot freed. Each event wakes only the waiters it can unblock. claim_next pops a FIFO of WAITING ids instead of scanning the dict. Slots are now tracked as a set of group ids. release_slots(ids) replaces release_active_groups(count) and raises when an id holds no slot or appears twice. The ids come from the new TrainerStepBatch.trainable_group_ids.

Example. S=3, P=256, so there are 1,024 rollout loops waiting in claim_next:

before: add_work(g) -> notify_all -> 1,024 loops wake, each scans ~1,024 entries, 1 claims, 1,023 wait again
after:  add_work(g) -> notify()   -> 1 loop wakes, popleft() -> g
before: release_active_groups(256) after a step that trained {0..255}   (any 256 slots)
after:  release_slots([0..255])    -> a double or unknown release raises RuntimeError

Must fix

  1. The PR description: "Summary (human-written)" is still the placeholder (**Human note:** TODO (Jiani)). The author needs to fill it in before merge.
  2. torchtitan/rl/controller/controller.py:1540 and tests/rl/unit_tests/cpu/test_trainer_loop.py:172: unrelated renames to "retire". They contradict the PR's own retire -> release_slots rename. Restore the original names (see inline).

Should consider

  • torchtitan/rl/controller/work_buffer.py:243-247: the duplicate check is O(n^2) under the lock on every trained release (see inline).
  • torchtitan/rl/trainer/batcher.py:643: num_trainable_groups is now redundant with len(trainable_group_ids) (see inline).
Details

Gate. The problem is real and measured: claim_next was 69-76% of controller CPU, and the 1,024-prompt step went from 262 s and growing to 55.6 s. The root cause is correct: notify_all plus a linear scan per wakeup. It's fixed in the layer that owns it. No open PR overlaps.

Wakeup analysis (checked against HEAD).

  • claim_next: if a loop that isn't waiting grabs the lock before the notified waiter, it consumes the item and the notified waiter waits again, so the counts stay balanced. Two add_work calls send notify() to two distinct waiters.
  • take_finalized: the batcher loop is the only caller. It always rescans before waiting. The window anchor moves only when take_finalized removes the oldest entry, so a finalize outside the window doesn't lose a wakeup.
  • wait_for_slot: _data_input_loop is the only waiter, so notify(len(ids)) is enough.
  • Cancelling a notified waiter passes the notify on to another waiter (Python 3.13+; CI runs 3.14).
  • close() notifies all three conditions. Active slots survive close, so an in-flight pull task can still release its slots.

Release-by-id consistency. The batcher loop releases a group when group_is_trainable is false, i.e. bool(training_sample_group.training_samples) after oversize filtering (batcher.py:450). trainable_group_ids uses the same predicate on the same stored groups (batcher.py:643). So the two paths partition group_ids exactly, and the trained path releases exactly num_prompts_per_train_step ids, the same count as before. TrainerStepBatch is only constructed in batcher.py, so no other constructor needs the new field.

Not verified: the perf and bitwise-loss numbers (they need GPUs). A maintainer still needs to review.

Comment thread torchtitan/rl/controller/controller.py Outdated

async def _pull_model_state_dict_and_release_groups(
self, version: int, *, after: asyncio.Task[float]
async def _pull_model_state_dict_and_retire_groups(

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.

Unrelated rename, and it goes against this PR's own naming. The description says a review renamed retire to release_slots, but this method went from _release_groups to _retire_groups. That leaves "retire" as a second name for "release slots". The same thing happened to test_push_then_pull_then_release_after_each_optimizer_step (test_trainer_loop.py:172). Please keep the original names, _pull_model_state_dict_and_release_groups and ..._then_release_after_.... Adding the trainable_group_ids parameter doesn't require a rename.

Comment thread torchtitan/rl/controller/work_buffer.py Outdated
Comment on lines +243 to +247
released_group_ids = set(group_ids)
not_active = released_group_ids - self._active_group_ids
repeated = sorted(
{group_id for group_id in group_ids if group_ids.count(group_id) > 1}
)

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.

group_ids.count(group_id) for each id is O(n^2). It runs on every trained release, with n = num_prompts_per_train_step (1,024 in the PR's own benchmark), inside the buffer lock on the controller's event loop. That is about 1M comparisons per step just to check the case that never happens. Compare lengths first, and build the repeated list only when you are about to raise, e.g.:

released_group_ids = set(group_ids)
not_active = released_group_ids - self._active_group_ids
if not_active or len(released_group_ids) != len(group_ids):
    repeated = sorted(g for g, c in collections.Counter(group_ids).items() if c > 1)
    raise RuntimeError(...)

Comment thread torchtitan/rl/trainer/batcher.py Outdated
num_trainable_groups,
num_metric_only_groups,
[group.group_id for group in taken_groups],
[group.group_id for group in taken_groups if group.training_samples],

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.

_take_groups now returns both num_trainable_groups (the third element) and trainable_group_ids. The int is always len(trainable_group_ids). You could drop it and use len(trainable_group_ids) in _pack_one_training_batch. That keeps the tuple at five elements, with no redundant pair to keep in sync.

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/1-slots-by-group-id branch from e99bb12 to b4d1a8a Compare November 20, 2026 17:05
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/0-hop-metrics branch from 7a0d11b to b1791f5 Compare November 20, 2026 17:05
@wwwjn

wwwjn commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 49s —— View job


Approve. Please fill in the human-written summary before merging. All three code findings from the last review are fixed. See the review.

@claude claude Bot 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.

Verdict: Approve -- please address the item below before merging. The amended commit fixes all three code findings from the last review. The only item left is the human-written summary.

Earlier findings

  • Resolved: the unrelated "retire" renames are reverted. _pull_model_state_dict_and_release_groups (controller.py:1543) and test_push_then_pull_then_release_after_each_optimizer_step keep their original names.
  • Resolved: release_slots (work_buffer.py:540-547) now checks len(set) < len(list) in O(n). It builds the Counter only on the raise path.
  • Resolved: _take_groups no longer returns num_trainable_groups. _pack_one_training_batch derives it as len(trainable_group_ids) (batcher.py:544).
  • Still open: the description's "Summary (human-written)" is still the placeholder (**Human note:** TODO (Jiani)). The author needs to fill it in.

Must fix

  1. PR description -- fill in the human-written summary.

The new commit has no new problems. I re-checked the trainable_group_ids flow at HEAD: TrainerStepBatch -> packed.trainable_group_ids (controller.py:1460) -> release_slots(..., reason="trained"). It still splits group_ids cleanly against the batcher loop's untrainable releases. No callers of release_active_groups remain.

Not verified: the perf and bitwise-loss numbers (they need GPUs). A maintainer still needs to review.

wwwjn added a commit that referenced this pull request Nov 20, 2026
…plan

Stack: #5862 -> #6268 (hop metrics) -> #6269 (slots by group id) -> slim group
-> batcher split -> this.

Why: the batcher packed every microbatch of a step, so each step's bytes went
worker -> controller -> batcher -> controller -> every trainer rank (pp * cp * tp
copies per DP replica): four bulk pickles, two of them through the controller's
event loop, and serial image preprocessing on every trainer rank.

What changes:
1. The rollout worker returns its group split (`FinishedRolloutGroup(summary,
   arrays, recorder_lines)`); the work buffer holds it.
   `split_rollout_group` -> (`RolloutGroupSummary`, `RolloutGroupArrays`): the
   summary is the group with every ndarray field emptied (same dtype and
   trailing shape, not a view) and image files emptied, plus its turn lengths;
   the arrays hold every ndarray field by name and each image file once.
   `join_rollout_group` reverses it. Before splitting, the worker runs
   `check_prompt_prefixes` on every rollout, the one check that reads token
   values (in the batcher split PR it ran in `add_group`).
2. The batcher gets only summaries and returns the step's `StepPlan`: no
   tensors (`TrainerStepBatch` is deleted). `MicrobatchPacker` is a
   `Configurable`; its config (`per_sample_pad_multiple`, `num_mtp_layers`,
   `build_mrope_positions`) moves under `Batcher.Config.microbatch_packer`, so
   the planner and the packer read one source. The trainer builds the packer
   from it, with `pad_id`, `temperature` and `vision_processor`.
3. The controller keeps each trainable group's summary and arrays until its
   step, without the group metrics the batcher logs from its copy
   (`FinishedRolloutGroup.without_metrics`). It then sends each DP replica's
   leader (pipeline stage 0, CP and TP rank 0) its plan column and only the
   rollouts that column names (`Trainer.receive_replica_column`), under its
   own span and step timer (`timing/step/send_replica_columns`).
   `forward_backward` carries the group count and the global token counts.
4. On every trainer rank a `MicrobatchGroupReader` thread makes the step's
   microbatch groups up to two ahead of the one the engine waits on: the
   leader materializes and packs each group (`MicrobatchPacker.pack_planned`,
   which checks each sample's length and each microbatch's token counts
   against its specs) and broadcasts it, with its packing time, over a
   per-replica gloo group; the other ranks receive it; every rank
   preprocesses images. The replica groups come from the trainer's dense mesh
   (`build_dp_replica_group`). A leader that fails to pack broadcasts its
   error, so the replica fails instead of hanging. PP works from the start:
   every stage of a replica is in its group. The leader materializes one
   rollout group at a time and drops its arrays once its samples exist, and
   drops each microbatch group's samples once it is packed.
5. Deleted: the RDMA microbatch path (`Batcher.Config.rdma_min_tensor_bytes`,
   `RDMAMicrobatch`, `RDMAMicrobatchPrefetcher`, `maybe_release_oldest_batch`,
   the trainer's RDMA identity check, the controller's RDMA warning and PP
   rejection), the now-unused tensor and dataclass paths of
   `MonarchRDMAObject` (it registers bytes only: prompt image files), and
   `share_image_data` (the split keeps one copy per image).

Cost: the leaders pack only once forward_backward starts. With
training.preprocess_microbatch_groups_lazily=False (the default), the engine
reads every microbatch group before its first forward, so the column send and
the leaders' materialize, pack and broadcast are on the step's critical path;
with it on, the first group still waits for the column's materialize. Sending
the columns during the previous step (a follow-up) hides them.

Unchanged: the plan (FFD/LPT/zig-zag), the packing, the samples and the
numerics; the push/pull ordering; #5862's image-file path.
wwwjn added a commit that referenced this pull request Nov 20, 2026
…plan

Stack: #5862 -> #6268 (hop metrics) -> #6269 (slots by group id) -> slim group
-> batcher split -> this.

Why: the batcher packed every microbatch of a step, so each step's bytes went
worker -> controller -> batcher -> controller -> every trainer rank (pp * cp * tp
copies per DP replica): four bulk pickles, two of them through the controller's
event loop, and serial image preprocessing on every trainer rank.

What changes:
1. The rollout worker packs each finished group once
   (`pack_rollout_group`, new `rollout/packed_group.py`) and returns
   `FinishedRolloutGroup(summary, packed, recorder_lines)`; the work buffer
   holds it. The summary (`RolloutGroupSummary`, moved to `rollout/types.py`)
   is the group with every ndarray field emptied (same dtype and trailing
   shape) and image files emptied, plus its turn lengths. `PackedRolloutGroup`
   holds the bytes as uint8 regions of one buffer: per rollout, the rollout
   pickled without its arrays, then every ndarray field by name (64-byte
   aligned); per distinct image file, its bytes. `select` keeps the named
   rollouts' regions and their images' without copying;
   `unpack_rollout_group` rebuilds the rollouts, with arrays viewing the
   regions. Before packing, the worker runs `check_prompt_prefixes` on every
   rollout, the one check that reads token values (in the batcher split PR it
   ran in `add_group`).
2. The batcher gets only summaries and returns the step's `StepPlan`: no
   tensors (`TrainerStepBatch` is deleted). `MicrobatchPacker` is a
   `Configurable`; its config (`per_sample_pad_multiple`, `num_mtp_layers`,
   `build_mrope_positions`) moves under `Batcher.Config.microbatch_packer`, so
   the planner and the packer read one source. The trainer builds the packer
   from it, with `pad_id`, `temperature` and `vision_processor`.
3. The controller keeps only each trainable group's packed regions until its
   step: one GC-tracked object per group, not the per-turn object graph,
   which held for several steps made its full collections frequent and slow.
   It then sends each DP replica's leader (pipeline stage 0, CP and TP rank 0)
   its plan column and only the rollouts that column names
   (`Trainer.receive_replica_column`), under its own span and step timer
   (`timing/step/send_replica_columns`).
   `forward_backward` carries the group count and the global token counts.
4. On every trainer rank a `MicrobatchGroupReader` thread makes the step's
   microbatch groups up to two ahead of the one the engine waits on: the
   leader materializes and packs each group (`MicrobatchPacker.pack_planned`,
   which checks each sample's length and each microbatch's token counts
   against its specs) and broadcasts it, with its packing time, over a
   per-replica gloo group; the other ranks receive it; every rank
   preprocesses images. The replica groups come from the trainer's dense mesh
   (`build_dp_replica_group`). A leader that fails to pack broadcasts its
   error, so the replica fails instead of hanging. PP works from the start:
   every stage of a replica is in its group. The leader unpacks and materializes
   one rollout group at a time and drops its bytes once its samples exist, and
   drops each microbatch group's samples once it is packed.
5. Deleted: the RDMA microbatch path (`Batcher.Config.rdma_min_tensor_bytes`,
   `RDMAMicrobatch`, `RDMAMicrobatchPrefetcher`, `maybe_release_oldest_batch`,
   the trainer's RDMA identity check, the controller's RDMA warning and PP
   rejection), the now-unused tensor and dataclass paths of
   `MonarchRDMAObject` (it registers bytes only: prompt image files), and
   `share_image_data` (the packed group keeps one copy per image).

Cost: the leaders pack only once forward_backward starts. With
training.preprocess_microbatch_groups_lazily=False (the default), the engine
reads every microbatch group before its first forward, so the column send and
the leaders' materialize, pack and broadcast are on the step's critical path;
with it on, the first group still waits for the column's materialize. Sending
the columns during the previous step (a follow-up) hides them.

Unchanged: the plan (FFD/LPT/zig-zag), the packing, the samples and the
numerics; the push/pull ordering; #5862's image-file path.
wwwjn added a commit that referenced this pull request Nov 22, 2026
…plan

Stack: #5862 -> #6268 (hop metrics) -> #6269 (slots by group id) -> slim group
-> batcher split -> this.

Why: the batcher packed every microbatch of a step, so each step's bytes went
worker -> controller -> batcher -> controller -> every trainer rank (pp * cp * tp
copies per DP replica): four bulk pickles, two of them through the controller's
event loop, and serial image preprocessing on every trainer rank.

What changes:
1. The rollout worker packs each finished group once
   (`pack_rollout_group`, new `rollout/packed_group.py`) and returns
   `FinishedRolloutGroup(summary, packed, recorder_lines)`; the work buffer
   holds it. The summary (`RolloutGroupSummary`, moved to `rollout/types.py`)
   is the group with every ndarray field emptied (same dtype and trailing
   shape) and image files emptied, plus its turn lengths. `PackedRolloutGroup`
   holds the bytes as uint8 regions of one buffer: per rollout, the rollout
   pickled without its arrays, then every ndarray field by name (64-byte
   aligned); per distinct image file, its bytes. `select` keeps the named
   rollouts' regions and their images' without copying;
   `unpack_rollout_group` rebuilds the rollouts, with arrays viewing the
   regions. Before packing, the worker runs `check_prompt_prefixes` on every
   rollout, the one check that reads token values (in the batcher split PR it
   ran in `add_group`).
2. The batcher gets only summaries and returns the step's `StepPlan`: no
   tensors (`TrainerStepBatch` is deleted). `MicrobatchPacker` is a
   `Configurable`; its config (`per_sample_pad_multiple`, `num_mtp_layers`,
   `build_mrope_positions`) moves under `Batcher.Config.microbatch_packer`, so
   the planner and the packer read one source. The trainer builds the packer
   from it, with `pad_id`, `temperature` and `vision_processor`.
3. The controller keeps only each trainable group's packed regions until its
   step: one GC-tracked object per group, not the per-turn object graph,
   which held for several steps made its full collections frequent and slow.
   It then sends each DP replica's leader (pipeline stage 0, CP and TP rank 0)
   its plan column and only the rollouts that column names
   (`Trainer.receive_replica_column`), under its own span and step timer
   (`timing/step/send_replica_columns`).
   `forward_backward` carries the group count and the global token counts.
4. On every trainer rank a `MicrobatchGroupReader` thread makes the step's
   microbatch groups up to two ahead of the one the engine waits on: the
   leader materializes and packs each group (`MicrobatchPacker.pack_planned`,
   which checks each sample's length and each microbatch's token counts
   against its specs) and broadcasts it, with its packing time, over a
   per-replica gloo group; the other ranks receive it; every rank
   preprocesses images. The replica groups come from the trainer's dense mesh
   (`build_dp_replica_group`). A leader that fails to pack broadcasts its
   error, so the replica fails instead of hanging. PP works from the start:
   every stage of a replica is in its group. The leader unpacks and materializes
   one rollout group at a time and drops its bytes once its samples exist, and
   drops each microbatch group's samples once it is packed.
5. Deleted: the RDMA microbatch path (`Batcher.Config.rdma_min_tensor_bytes`,
   `RDMAMicrobatch`, `RDMAMicrobatchPrefetcher`, `maybe_release_oldest_batch`,
   the trainer's RDMA identity check, the controller's RDMA warning and PP
   rejection), the now-unused tensor and dataclass paths of
   `MonarchRDMAObject` (it registers bytes only: prompt image files), and
   `share_image_data` (the packed group keeps one copy per image).

Cost: the leaders pack only once forward_backward starts. With
training.preprocess_microbatch_groups_lazily=False (the default), the engine
reads every microbatch group before its first forward, so the column send and
the leaders' materialize, pack and broadcast are on the step's critical path;
with it on, the first group still waits for the column's materialize. Sending
the columns during the previous step (a follow-up) hides them.

Unchanged: the plan (FFD/LPT/zig-zag), the packing, the samples and the
numerics; the push/pull ordering; #5862's image-file path.
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/0-hop-metrics branch from b1791f5 to 6e267e1 Compare November 23, 2026 20:35
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/1-slots-by-group-id branch from b4d1a8a to 16baba8 Compare November 23, 2026 20:35
@wwwjn
wwwjn added this pull request to stack #6343 November 23, 2026 21:31
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/1-slots-by-group-id branch from 16baba8 to f01cd7a Compare November 24, 2026 17:53
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/0-hop-metrics branch from 6e267e1 to c51e747 Compare November 24, 2026 17:53
@wwwjn
wwwjn removed this pull request from stack #6343 November 24, 2026 20:05
@wwwjn
wwwjn changed the base branch from wwwjn/data-plane/0-hop-metrics to wwwjn/rl-rdma-object November 24, 2026 20:05
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/1-slots-by-group-id branch from f01cd7a to 650e7dc Compare November 24, 2026 20:05
@wwwjn wwwjn changed the title [rl] Wake one waiter per work-buffer event; release slots by group id [rl] Wake one waiter per work-buffer event; rollout workers return a slim group Nov 24, 2026
@wwwjn

wwwjn commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 2m 9s —— View job


Approve. Please fill in the human-written summary before merging. The earlier fixes are still in place, and the slim-group commits have no blocking issues. See the review.

@wwwjn
wwwjn added this pull request to stack #6362 November 24, 2026 20:15

@claude claude Bot 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.

Verdict: Approve -- please address the item below before merging. The fixes from the last review are still in place at HEAD. The newly folded-in slim-group half drops only fields that nothing on the training path reads. The one thing left is the human-written summary.

What changed since the last review. The branch was rebased, and the slim-group change (4461049c, 650e7dc3) was folded in. For training groups, RolloutWorkerActor.run_group now runs compute_rollout_metrics and the recorder encoding on the full group. It then returns FinishedRolloutGroup(slim_group, recorder_lines). The controller only appends the lines. Validation still returns the full group.

Example. One training group of G=8 rollouts, each with the same 1 MiB image:

before: worker --full group (msgs, logs, 8x 1 MiB)--> controller: compute_rollout_metrics + record --> add_group
after:  worker: compute_rollout_metrics + encode --slim group (1x 1 MiB) + lines--> controller: append_lines --> add_group

Earlier findings

  • Resolved, still at HEAD: no "retire" renames are left. release_slots does an O(n) duplicate check and builds the Counter only when it raises (work_buffer.py:245). _take_groups no longer returns a redundant num_trainable_groups (batcher.py:523).
  • Still open: the human-written summary.

Must fix

  1. PR description: "Summary (human-written)" is still the placeholder (**Human note:** TODO (Jiani)). The author needs to fill it in.

Should consider

  • torchtitan/rl/rollout/finished_group.py:13: with this import, the rollout package depends on controller for the first time. compute_rollout_metrics now runs mainly in the rollout worker. Moving it next to its new main caller (e.g. into rollout/finished_group.py, or a rollout/metrics.py) would keep the dependency pointing from controller to rollout. The import is light today (controller/metrics.py only imports rollout.types), so this is not blocking.
Details

Dropped fields vs. training readers (checked at HEAD). slim_rollout_group empties prompt_messages, completion_message, env_messages, env_rewards, turn metrics, reward_breakdown and logs. Outside the env, rubric and recorder, the only reader of these is compute_rollout_metrics (controller/metrics.py:286, :302), and it now runs before the slim. The batcher and training_sample_builder read only group.metrics (training_sample_builder.py:143, batcher.py:443/601), and the slim copy keeps those.

group.metrics.extend vs. the old =. Every in-repo RolloutGroup is built with empty metrics (rollouter.py:560, verifiers/rollouter.py:296), so the metric values are unchanged.

Overrides. No in-repo Rollouter overrides run_group_rollouts. VerifiersRollouter only overrides setup_async, and it forwards rollout_recorder_config. An out-of-repo override that returns a bare RolloutGroup fails on .recorder_lines. The rollout loop's except logs that and drops the group as a failure, so the failure is loud.

Failure semantics. Before, an exception in metrics or encoding on the controller turned the group into a failure group. Now the same exception raises in the worker and ends up in the same except. The behavior is unchanged.

Image dedup. PromptImage is a frozen dataclass whose data field is excluded from comparison, so replace(image, data=shared) keeps equality and hashing the same. Only prompt_delta_images carries image bytes on RolloutTurn.

Not verified: the perf and bitwise-loss numbers (they need GPUs). A maintainer still needs to review.

Problem:
Every RolloutGroupWorkBuffer change (add_work, finalize_work, take_finalized, a slot release,
close) called notify_all() on one Condition. All (S+1) x P rollout loops woke up, and each
scanned every entry for a WAITING one; one claimed it and the rest waited again. At P=256
claim_next was 69-76% of the controller's CPU samples; at P=1024 the controller saturated a core
and steps grew from 207 s to 304 s while the trainer waited 202 s per step for a batch.

Solution:
Each wait has its own Condition on one shared lock, and each event wakes only the waiters it
can unblock: add_work() wakes one claim_next() waiter, which pops a FIFO of WAITING group ids
instead of scanning; finalize_work() wakes one take_finalized() waiter; release_active_groups(n)
wakes up to n slot waiters; close() wakes every waiter.

Unchanged: slot accounting (release_active_groups by count), claims oldest-WAITING-first,
take_finalized's window, the buffer metrics, and numerics.

Tests: add_work wakes one of five waiting claimers (main wakes all five, and four wait again);
close unblocks every waiter.
@wwwjn
wwwjn removed this pull request from stack #6362 November 24, 2026 22:25
@wwwjn
wwwjn changed the base branch from wwwjn/rl-rdma-object to main November 24, 2026 22:25
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/1-slots-by-group-id branch from 650e7dc to 688e876 Compare November 24, 2026 22:26
@wwwjn wwwjn changed the title [rl] Wake one waiter per work-buffer event; rollout workers return a slim group [rl] Wake one waiter per work-buffer event Nov 24, 2026
@wwwjn

wwwjn commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 1m 22s —— View job


Approve. Please fill in the human-written summary before merging. The PR is now down to the wakeup fix, and I found no lost wakeup at HEAD. See the review.

@claude claude Bot 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.

Verdict: Approve -- please address the item below before merging. The PR is now down to the wakeup fix alone (2 files). I found no lost wakeup at HEAD. The only item left is the human-written summary.

What changed since the last review. The branch was cut down to one commit (688e876a). Release-by-group-id (release_slots, trainable_group_ids) moved to #6303. The slim-group change is gone too. release_active_groups(count) is back unchanged. So the earlier findings on release_slots, the "retire" renames, _take_groups, and the rollout -> controller import no longer apply.

Example. S=3, P=256, so 1,024 rollout loops wait in claim_next:

before: add_work(g) -> notify_all -> 1,024 loops wake, each scans the dict, 1 claims, 1,023 wait again
after:  add_work(g) -> _work_added.notify() -> 1 loop wakes, _waiting_group_ids.popleft() -> g
        release_active_groups(256) -> _slot_freed.notify(256) -> the one _data_input_loop waiter wakes
        take_finalized() removes g -> notifies nobody (only the batcher loop waits on _work_finalized)

Earlier findings

  • Still open: "Summary (human-written)" in the description is still the placeholder (**Human note:** TODO (Jiani)).

Must fix

  1. PR description -- the author needs to fill in the human-written summary.
Details

Wakeup analysis at HEAD (work_buffer.py).

  • claim_next (:155-165): every add_work sends one notify(). asyncio.Condition.notify skips futures that are already resolved, so two back-to-back add_work calls wake two different waiters. A notified waiter can lose the lock race to a rollout loop that wasn't waiting. In that case the other loop takes the item and the waiter goes back to wait, so no WAITING id is ever stranded while a loop is idle.
  • _waiting_group_ids vs _work_by_group_id: an id leaves the dict only through take_finalized, which needs FINALIZED and so a prior claim (pop), or through close(), which clears both. So self._work_by_group_id[popleft()] at :162 can't raise KeyError.
  • take_finalized (:202-218): controller.py:1330 is the only caller, and it rescans before every wait. The window anchor moves only when this same caller removes the head. So the notify_all dropped on removal had no consumer.
  • wait_for_slot: _data_input_loop (controller.py:1241) is the only waiter, and add_work still raises without a slot. So notify(count) can't over-admit.
  • Cancelling a notified waiter: before 3.13, asyncio could lose that notification (requires-python >=3.11). The rollout loops are cancelled only in run()'s finally, after close() (controller.py:1155). So that case doesn't arise.
  • No stale _condition / notify_all references remain in torchtitan/rl/.

Tests. test_add_work_wakes_one_claim_next_waiter fails on main and guards the perf invariant without a GPU. test_close_unblocks_every_waiter guards the new invariant that close() must notify all three conditions.

Not verified: the perf and bitwise-loss numbers (they need GPUs). A maintainer still needs to review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

1 participant