Repository navigation
Conversation
6d8e740 to
e99bb12
Compare
43d7c83 to
7a0d11b
Compare
|
@claude review |
There was a problem hiding this comment.
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
- The PR description: "Summary (human-written)" is still the placeholder (
**Human note:** TODO (Jiani)). The author needs to fill it in before merge. torchtitan/rl/controller/controller.py:1540andtests/rl/unit_tests/cpu/test_trainer_loop.py:172: unrelated renames to "retire". They contradict the PR's ownretire->release_slotsrename. 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_groupsis now redundant withlen(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. Twoadd_workcalls sendnotify()to two distinct waiters.take_finalized: the batcher loop is the only caller. It always rescans before waiting. The window anchor moves only whentake_finalizedremoves the oldest entry, so a finalize outside the window doesn't lose a wakeup.wait_for_slot:_data_input_loopis the only waiter, sonotify(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.
|
|
||
| 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( |
There was a problem hiding this comment.
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.
| 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} | ||
| ) |
There was a problem hiding this comment.
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(...)| 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], |
There was a problem hiding this comment.
_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.
e99bb12 to
b4d1a8a
Compare
7a0d11b to
b1791f5
Compare
|
@claude review again |
There was a problem hiding this comment.
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) andtest_push_then_pull_then_release_after_each_optimizer_stepkeep their original names. - Resolved:
release_slots(work_buffer.py:540-547) now checkslen(set) < len(list)in O(n). It builds theCounteronly on the raise path. - Resolved:
_take_groupsno longer returnsnum_trainable_groups._pack_one_training_batchderives it aslen(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
- 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.
…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.
…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.
…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.
b1791f5 to
6e267e1
Compare
b4d1a8a to
16baba8
Compare
16baba8 to
f01cd7a
Compare
6e267e1 to
c51e747
Compare
f01cd7a to
650e7dc
Compare
|
@claude review again |
There was a problem hiding this comment.
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_slotsdoes an O(n) duplicate check and builds theCounteronly when it raises (work_buffer.py:245)._take_groupsno longer returns a redundantnum_trainable_groups(batcher.py:523). - Still open: the human-written summary.
Must fix
- 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, therolloutpackage depends oncontrollerfor the first time.compute_rollout_metricsnow runs mainly in the rollout worker. Moving it next to its new main caller (e.g. intorollout/finished_group.py, or arollout/metrics.py) would keep the dependency pointing from controller to rollout. The import is light today (controller/metrics.pyonly importsrollout.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.
650e7dc to
688e876
Compare
|
@claude review again |
There was a problem hiding this comment.
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
- PR description -- the author needs to fill in the human-written summary.
Details
Wakeup analysis at HEAD (work_buffer.py).
claim_next(:155-165): everyadd_worksends onenotify().asyncio.Condition.notifyskips futures that are already resolved, so two back-to-backadd_workcalls 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_idsvs_work_by_group_id: an id leaves the dict only throughtake_finalized, which needs FINALIZED and so a prior claim (pop), or throughclose(), which clears both. Soself._work_by_group_id[popleft()]at:162can't raiseKeyError.take_finalized(:202-218):controller.py:1330is the only caller, and it rescans before every wait. The window anchor moves only when this same caller removes the head. So thenotify_alldropped on removal had no consumer.wait_for_slot:_data_input_loop(controller.py:1241) is the only waiter, andadd_workstill raises without a slot. Sonotify(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 inrun()'sfinally, afterclose()(controller.py:1155). So that case doesn't arise. - No stale
_condition/notify_allreferences remain intorchtitan/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.
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
add_work,finalize_work,take_finalized, a slot release,close) callsnotify_allon one condition, so all (target_offpolicy_steps+ 1) x P rollout loops wake up.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).claim_nextis 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 sforward_backward.Solution
asyncio.Conditions on one lock, one per kind of wait (controller/work_buffer.py):add_workwakes oneclaim_nextwaiter, which pops a FIFO of WAITING ids instead of scanning.finalize_workwakes onetake_finalizedwaiter; taking a group wakes no one (the batcher loop is the only caller).release_active_groups(count)wakes up tocountslot waiters.close()wakes everyone.release_active_groupsby count), the admission bound, claims oldest-WAITING-first,take_finalized's window, the buffer metrics, the losses.Results
You may ask:
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.forward_backward28.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:
forward_backwardended, which added ~1.7 s per step at 256 prompts (timing/step/blocking_generator_pull_model_state_dict). Main now finishes the weight push beforeforward_backward, which removes it.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 mainaf04091d6. The wakeup logic is unchanged. The bitwise check ran on this head.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.