Skip to content

[WIP] [rl] Read the next step's rollout groups during the optimizer step - #6324

Draft
wwwjn wants to merge 1 commit into
wwwjn/data-plane/4-trainer-packsfrom
wwwjn/data-plane/6-read-ahead
Draft

wwwjn wants to merge 1 commit into
wwwjn/data-plane/4-trainer-packsfrom
wwwjn/data-plane/6-read-ahead

Conversation

@wwwjn

@wwwjn wwwjn commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Human note: TODO (Jiani)
[drag pr_images/6324_076f/lanes_v2.png here]

TLDR: When the next step's plan is already queued, the controller sends its columns during forward_backward N and starts the next step's prefetchers after it returns. So the send overlaps forward_backward N, and the leaders' first fetch, sample building and packing overlap optimizer step N. At T1, the per-step data path (send, read-ahead, optimizer, push and first microbatch wait) drops 483 -> 392-402 ms in both lane orders: the first microbatch waits 0.4 ms instead of 102-112 ms. With 2048 px image groups it drops 874 -> 597 ms (first wait 449 -> 0.7 ms), and the step is 0.26 s faster lane-corrected.

# PR Independent? Needs
0 RDMA object for microbatches and prompts (#5862) yes -
1 Rollout workers compute and record each group's rollouts (#6301) yes - (stacked on 0 for merge order only)
2 Split the batcher into a metadata half and a bytes half (#6302) yes 0 (its batcher code)
3 Trainer DP replica leaders read their rollouts from the rollout workers and pack them (#6303) no 1, 2
4 Read the next step's rollout groups during the optimizer step (#6324, this PR) no 3
5 Trainer leaders read large rollout groups by RDMA over torch transport (#6469) no 3 (stacked on 4 for merge order only)
6 Prompt image files share the rollout worker's torch transport pool (#6334) no 5

Merge bottom-up.

Problem

  1. After [WIP] [rl] Trainer DP replica leaders read their rollouts from the rollout workers and pack them #6303, each step's first microbatch group waits for its leader to get its column, fetch the rollouts from the workers, build the samples, pack and broadcast them.
  2. The first forward waits for the first group; with training.preprocess_microbatch_groups_lazily=False (the default), for every group.
  3. Nothing hides it: the controller sends columns only at step start.
  4. Cost per step on [WIP] [rl] Trainer DP replica leaders read their rollouts from the rollout workers and pack them #6303's head at T1: 171 ms (send 69 + first microbatch wait 102; 180 ms with lanes swapped).

Solution

  1. Before forward_backward N, if the batcher queued plan N+1, the controller takes it (get_nowait) and starts a task sending its columns; else nothing changes.
  2. The task runs once the controller yields, after the forward_backward calls went out (.call sends at once), so each leader takes column N in forward_backward N before column N+1's handler starts. Monarch runs receive_replica_column once forward_backward returns, so pickling and transfer overlap forward_backward N; unpickling does not.
  3. After forward_backward N, the controller waits for the send and calls Trainer.start_prefetching on every rank; optimizer step N and push N follow.
  4. Trainer.start_prefetching builds and starts step N+1's MicrobatchGroupPrefetcher, whose thread makes the first two groups; forward_backward N+1 trains on it.
  5. A failed pull's error that read-ahead takes from the queue raises before forward_backward N, as the step's own take does. A try/finally cancels the send on any exit.
  6. New metrics: timing/step/read_ahead (exposed time after forward_backward N), its share of the step perf/trainer/step_time_ratio/read_ahead, and trainer/read_ahead (1 on a read-ahead step).
before: fwd/bwd N | optim N, push N | take plan N+1, send columns | fwd/bwd N+1 (first group: fetch, build samples, pack)
after:  take plan N+1 | fwd/bwd N (send columns) | start prefetchers | optim N, push N (leaders make 2 groups) | fwd/bwd N+1

Results

A100, one host; #6303 and this PR on two 4-GPU lanes at once, then lanes swapped; per-step medians of steps 3-12.
T1 = Qwen3-0.6B alphabet sort, 256 prompts x 4, trainer FSDP 2, off-policy, groups taken lazily (an earlier head; see NOTE).
Images = Qwen3.5-0.8B Geometry3K, 2048 px, 16 prompts x 8, trainer FSDP 2 (previous head; see NOTE).
T1 data path per step               483 -> 392 ms (swapped: 483 -> 402) (send + read_ahead + optimizer + push + first wait)
T1 send_replica_columns             68.8 -> 0.1 ms (swapped: 67.6 -> 0.1)
T1 first wait_for_microbatch        102 -> 0.4 ms (swapped: 112 -> 0.4) (slowest rank)
T1 optim_step (controller span)     46 -> 131 ms (swapped: 50 -> 133) (see NOTE)
T1 step                             29.13 -> 28.65 s (swapped: 29.14 -> 29.41): within lane noise, trainer-bound
images data path per step           874 -> 597 ms (swapped: 878 -> 597)
images first wait_for_microbatch    449 -> 0.7 ms (swapped: 460 -> 0.6)
images timing/step/optimizer        48 -> 99 ms (swapped: 48 -> 125)
images step                         21.77 -> 21.76 s (swapped: 20.99 -> 20.48), 0.26 s faster lane-corrected
correctness vs main 076f2e88b (seed 42, deterministic, 10 steps, on-policy: no read-ahead): 62/62 tags at TP 2
and 63/63 at PP 2 x FSDP 2, on #6334's head, which includes this PR

NOTE:

  • The prefetch thread holds the GIL while it fetches the column's rollouts and builds its samples, so the optimizer step is ~80 ms slower at T1; with images the optimizer step and the push are each ~50-80 ms slower. Starting the prefetchers after the optimizer step instead only moves that cost into the push (data path 402 vs 407 ms).
  • On-policy runs (target_offpolicy_steps=0) never read ahead, so the bitwise runs skip it. Read-ahead trains on plan N+1 as queued, only sent earlier; the off-policy bound comes from the active rollout slots, released after each pull, which this PR does not change.
  • The T1 rows ran before [WIP] [rl] Trainer DP replica leaders read their rollouts from the rollout workers and pack them #6303's RDMA group path moved into its own PR and before this PR's last edits (one column-send helper folded into the other, tests). Rerun after the split (T1, one lane order): data path 490 -> 402 ms, first wait 103 -> 0.4 ms; the other order ran on a busy host (689 -> 551 ms). On this head (T1, a busy host): first wait 0.4 ms, data path 424 ms.
  • The image rows ran on this PR's previous head; the changes since (the read-ahead error path, the leader's column queue, wording) do not touch the data path.
  • At 4K completions with score centering the run is generation-bound (the controller waits 111 s of a 238 s step for the next plan), so plan N+1 is never queued when forward_backward N starts: read-ahead does not trigger and [WIP] [rl] Trainer DP replica leaders read their rollouts from the rollout workers and pack them #6303's first microbatch wait (371 ms) stays.

Test plan

  • pytest tests/rl/unit_tests/cpu: 807 passed, 8 skipped, 4 failed ([WIP] [rl] Trainer DP replica leaders read their rollouts from the rollout workers and pack them #6303: 795). The 4 also fail on main 076f2e88b (770 passed): recipe tests whose torch_checkpointing.storage.fsspec_storage import fails locally.
  • pytest tests/rl/unit_tests/gpu/test_cp_images.py (2 A100s, [WIP] [rl] Prompt image files share the rollout worker's torch transport pool #6334's head): 4 passed.
  • test_trainer.py::test_a_column_that_arrives_early_waits_for_the_one_before_it: the leader keeps columns in arrival order and each prefetcher takes the oldest, so column N+1 arriving before forward_backward N takes column N does not depend on Monarch ordering two endpoints; fails with a one-slot column.
  • test_trainer_loop.py::test_a_pull_failure_taken_by_read_ahead_fails_the_loop_before_forward_backward: without the check, the run trains step 2 and dies with an AttributeError that hides the pull error.
  • test_trainer_loop.py::test_the_next_steps_columns_go_out_during_forward_backward: with plan 2 queued, forward_backward 1 starts before column 2 is handled, and the column goes out before forward_backward 1 returns (fake endpoints).
  • test_microbatch_group_prefetcher.py pp2_tp2_started and test_a_leader_that_fails_to_pack_fails_every_rank_of_its_replica[started]: every rank of a 4-rank replica starts its prefetcher before taking the groups, as read-ahead does, over a real gloo group.

@wwwjn

wwwjn commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 4m 35s —— View job


Needs discussion: the code looks correct, but it hides under 1% of the step and its numbers were measured before the rebase onto #6303. 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: Needs discussion -- The read-ahead logic looks correct. But by the PR's own numbers it hides under 1% of the step on the current stack, and the measurements were taken on an older version of the stack. Maintainers should decide whether ~250 lines of controller/trainer concurrency are worth that.

What this PR does. While forward_backward N runs, a background controller task waits for plan N+1, takes it from the queue and sends its columns to the replica leaders. After forward_backward N returns, the controller calls a new Trainer.start_reading endpoint on every rank. Each rank starts its MicrobatchGroupReader early, so the leader's reads, materialize and first two packed groups overlap the push wait and optimizer step N. If the plan isn't queued in time (always the case on-policy), the task is cancelled and the plan stays in the queue.

Example. Off-policy, with plan 2 queued during forward_backward 1:

before: fwd_bwd 1 | push wait, optim 1 | get plan 2, send columns | fwd_bwd 2 (group 0 waits: read, materialize, pack)
after:  fwd_bwd 1 (task: get plan 2, pickle and send columns)
        | read_ahead: leaders unpickle, start_reading on all ranks   (14-76 ms exposed)
        | push wait, optim 1  (+10-18 ms from the GIL; leaders pack groups 0 and 1)
        | fwd_bwd 2 (group 0 ready)
on-policy: plan 2 only appears after pull 1 -> task cancelled when fwd_bwd 1 returns; the step runs as before

Must fix

  1. The PR description doesn't yet make the case for merging. "Human note: TODO" is unfilled. Every number was measured before the rebase onto #6303's packed format, and the rerun on this head is pending. On the current head, the PR says the hideable cost is 125 ms at T1 and 1.57 s at 4K (0.46% / 0.67%). The measured step-time change (1.1-2.3%) is inside the ~1 s lane-to-lane noise, and the optimizer step gets 10-18 ms slower. Before a maintainer can weigh this against +526 LoC, they need current-head numbers for the first group's wait_for_microbatch and for step time, with a noise estimate (e.g. repeated lanes or swapped GPU halves).

Should consider

  • controller.py:1507: one try/finally would replace both cancel sites and cover every exit (inline).
  • controller.py:1609: trainer/read_ahead is redundant with the read-ahead hop key (inline).
  • microbatch_group_reader.py:233: _new_thread is a @staticmethod that returns a pool (inline).
  • test_microbatch_group_reader.py:510: possible race between start() and close() (inline).
  • test_trainer.py:310: a test that only checks mock calls (inline).
  • controller.py:87-93: the backpressure docstring still says only _trainer_loop's get() unblocks the batcher's put(). The read-ahead task now does too, so up to one plan is held beyond the queue's maxsize=1.

Questions

  • How often is plan N+1 already in the queue when step N starts, i.e. is timing/step/wait_for_training_batch about 0 in steady state? If that's the usual case, a get_nowait() before the gather (no read-ahead otherwise) captures most of the win. It drops the taken event, the not-taken cancel branch and test_no_read_ahead_when_the_next_plan_comes_after_forward_backward; roughly 30 lines and one test fewer.
Details

What I checked and found sound:

  • No lost plan. CPython's Queue.get removes the item only through get_nowait() after the getter wakes, so cancelling a woken but not-yet-resumed get leaves the plan in the queue. taken.set() runs synchronously right after get() returns, so taken is set exactly when the plan was consumed.
  • Column order on the leader. Each forward_backward (or start_reading) pops the oldest column, and at most two columns are ever held, so the len < 2 assert holds.
  • Off-policy bound unchanged. Staleness is bounded by the (target_offpolicy_steps + 1) * P slots, which are released only after the pull. Taking plan N+1 early doesn't free slots. Policy age is still computed when the step consumes the plan, against _trainer_policy_version.
  • No concurrent collectives on a shared group. The reader broadcasts on its own gloo subgroup (new_subgroups_by_enumeration), so running during optim_step can't interleave with training collectives.
  • No extra GPU memory. preprocess_images runs on the CPU, so the GPU memory peak during the optimizer step doesn't change.
  • Step tags. The reader thread copies step N's contextvars, but it logs no trace spans, so no step-tagged records are mis-attributed.

The cost of the new code: a background task plus an event, two cancel sites, a new endpoint, a leader-side deque, start/close on the reader, and four new metric families.

Not verified: perf on this head (needs GPUs); the flake in test_closing_a_started_reader_cancels_its_queued_reads. A maintainer still needs to review.

Comment thread torchtitan/rl/controller/controller.py Outdated
for trainer_at_dp_rank in self.trainer.by_dp_rank
)
)
except BaseException:

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.

The cleanup for the background send lives in two places: this except BaseException and the NaN break at L1535. Any other exit between the gather and _read_ahead still leaks the task. For example, the next(...) at L1518 raises StopIteration if no rank returned metrics.

Task.cancel() does nothing on a finished task. So one try: ... finally: if next_columns is not None: next_columns[0].cancel() around everything from the gather through await self._read_ahead(...) covers every exit. It replaces both cancel sites, and the break still runs the finally.

# 1 when this step's columns went and its readers started during the
# previous step.
m.Metric(
"trainer/read_ahead", m.NoReduce(float(read_ahead_started))

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.

trainer/read_ahead repeats what the metrics already show. A read-ahead step is exactly a step that logs timing/hop/receive_replica_column_read_ahead/* instead of timing/hop/receive_replica_column/*. The PR already adds three new metric families, so consider dropping this one, along with its assertion in test_the_next_steps_columns_go_out_during_forward_backward.

pool.shutdown(wait=False, cancel_futures=True)

@staticmethod
def _new_thread() -> ThreadPoolExecutor:

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.

This is a @staticmethod that doesn't use self. Its name, _new_thread, is also wrong: it returns a pool, not a thread. design.md says such a method should be a function. Either make it a module-level _new_read_pool() or inline the ThreadPoolExecutor(...) call at its two call sites.


reader = _counting_reader(5, [], pack=pack)
reader.start()
reader.close()

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.

This can flake (unverified). start() submits groups 0 and 1, then returns. If the pool's worker thread hasn't taken group 0 off the work queue yet, close() → shutdown(cancel_futures=True) cancels both, packed == [], and the assertion fails.

To make it deterministic, wait until group 0 is running before closing: set a started = threading.Event() at the top of pack, then call started.wait(timeout=10) before reader.close().

Comment thread tests/rl/unit_tests/cpu/test_trainer.py Outdated
assert read_threads[0] is not threading.main_thread()


def test_close_stops_a_started_reader_no_step_consumed() -> None:

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.

This test only checks that a mock's close was called and that an attribute was then set to None. It re-reads the four lines it covers, so it guards no invariant that could break silently (tests.md: no tests that just repeat mock calls). Consider dropping it.

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/6-read-ahead branch from e0af5c8 to 804c8d6 Compare November 23, 2026 03:23
@wwwjn

wwwjn commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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


Needs discussion: all round-1 code comments are fixed and I found no new problems. The PR still needs numbers measured on this head to justify the change, which hides under 1% of the step. 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: Needs discussion -- Every code comment from round 1 is fixed and I found no new problems in 804c8d6. The open question is still whether this is worth merging: the measured win is under 1% of the step, and there are no numbers from this head yet.

What changed since the last review. The background task that waited for the plan is replaced by a get_nowait() before forward_backward, which was the earlier question. That removes the taken event, the not-taken cancel branch and its test. Net: -52 lines.

Example. Off-policy, with plan 2 queued when step 1 starts:

step 1: get_nowait -> plan 2 | fwd_bwd 1 (task: send plan 2's columns) | read_ahead: start_reading on all ranks | push wait, optim 1
step 2: plan = read_ahead.plan, no column send | fwd_bwd 2 (group 0 already packed)
plan 2 not queued yet (on-policy, or 4K): get_nowait raises QueueEmpty -> None; step 2 runs as before

Resolved from the last review

  • controller.py cancel sites: now a single try/finally from the gather through _read_ahead, covering the NaN break and any exception.
  • The trainer/read_ahead metric and its assertion are removed.
  • _new_thread is now the module-level _new_read_pool().
  • test_closing_a_started_reader_cancels_its_queued_reads: now waits on a started event before close(), so there is no race.
  • The mock-only test_close_stops_a_started_reader_no_step_consumed is removed.
  • The backpressure docstrings (module and _batcher_loop) now say get_nowait also unblocks the batcher, and that up to one plan beyond maxsize is held.

Must fix

  1. Still open: the description doesn't yet make the case for merging. "Human note: TODO (Jiani)" is still unfilled. Every number in Results was measured before the rebase onto #6303, and the rerun on this head is still pending. By the PR's own estimate, the cost left to hide on #6303's head is 0.46% of the step at T1 and 0.67% at 4K. Read-ahead never triggers at 4K, and the measured step-time change is within the ~1 s lane noise. Maintainers need current-head numbers (first wait_for_microbatch, read_ahead, optimizer, step time, with a noise estimate) to weigh them against about +470 net LoC of controller/trainer concurrency.
Details

Rechecked at HEAD:

  • Plan accounting with get_nowait. The plan is taken synchronously before the gather. If the send task is cancelled in the finally, the run is already exiting (exception or NaN break), so losing the plan doesn't matter. After a normal _read_ahead, cancel() on the finished task does nothing.
  • Leader column order. start_reading -> _new_reader pops the oldest column. A leader holds at most step N's column (popped at fwd_bwd N or at the previous start_reading) plus N+1's, so len < 2 in receive_replica_column holds.
  • On-policy. Plan N+1's groups wait for pull N, so the queue is empty at fwd_bwd N, get_nowait returns None, and the path is unchanged. Removing test_no_read_ahead_when_the_next_plan_comes_after_forward_backward is fine: that branch is now one except QueueEmpty: return None.
  • Timing. timing/step/read_ahead is recorded on every step (about 0 when nothing was taken), so compute_perf_ratio_metrics always sees the key.

Not verified: perf on this head (needs GPUs). A maintainer still needs to review.

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/6-read-ahead branch from 804c8d6 to 60f00a2 Compare November 23, 2026 03:27
@wwwjn

wwwjn commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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


Needs discussion: the code hasn't changed since round 2, but the new numbers from this head show only a ~0.2% net saving per step and no step-time change outside noise. 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: Needs discussion -- The code hasn't changed since the last review, and I still found no problems in it. The new numbers from this head show no step-time win, though. Maintainers need to decide whether ~470 net lines of controller/trainer concurrency are worth a ~51 ms per step (0.2%) net saving that the measurements can't tell apart from noise.

What changed since the last review. The diff at 60f00a2 is the same as what I reviewed in round 2. The description now has numbers measured on this head, plus a noise estimate from a lane-swapped T1 repeat. That was round 2's request.

Example. Off-policy, with plan 2 already queued when step 1 starts:

step 1: get_nowait -> plan 2 | fwd_bwd 1 (task: send plan 2's columns) | read_ahead (~20 ms) | push wait, optim 1 (+~51 ms GIL; leaders pack groups 0-1)
step 2: no column send (59 -> 0.1 ms) | fwd_bwd 2, first wait_for_microbatch 63 -> 0.4 ms
on-policy, or 4K (generation-bound): get_nowait finds nothing -> no change; timing/step/read_ahead = 0

Must fix

  1. The description's own data now argue against merging, and the human note is still "TODO (Jiani)".

    • At T1 the PR hides ~122 ms per step but adds ~20 ms of read_ahead and ~51 ms of optimizer time. That nets ~51 ms per step (0.2%).
    • Step time is +0.24 s per step once the lane difference is taken out, inside the ~1 s noise.
    • At 4K, read-ahead never triggers.
    • The only case that might matter is images: an estimated ~0.25 s net per 22 s step (~1.1%), but those lanes weren't swapped, and the 0.52 s lane bias is half of that.

    The author (in the human note) and a maintainer should either:

    • name the workload where this pays off (e.g. a lane-swapped images run, or a recipe that trains on more images per step) and show it, or
    • park the PR until the data path is a bigger share of the step.

Questions

  • Most of the new optimizer-step cost is the reader thread holding the GIL (pickle.loads, materialize, pack) while optim_step runs. Would deferring start_reading until after optim_step returns keep most of the hiding? It would still overlap the push wait and the next step's sync_log_step/plan handling. Or is the push wait too short for that?
Details

Rechecked at HEAD (60f00a2), beyond round 2's checks:

  • Message order on the leader. The send task is created before the forward_backward gather, so column N+1 can reach a leader before forward_backward N's message does. The deque handles it either way: forward_backward N pops column N (the oldest), and the len < 2 assert holds because at most columns N and N+1 are held. test_each_step_trains_on_the_oldest_column covers this.
  • Dispatch delay. The send task runs _replica_columns(plan) (selects rollouts per DP rank) synchronously before the forward_backward calls are dispatched. Pickling happens in the per-leader send tasks, which run after the dispatch. So forward_backward N starts later only by the selection cost. It should be small, but it's untimed, and its cost lands in timing/step/forward_backward.
  • NaN break after a read-ahead. Breaking at step N+1 leaves N+2's readers started. Trainer.close stops them, and the finally cancels the already-finished send task (a no-op).
  • No other callers of _replica_column, receive_replica_column or the reader exist outside the PR's call sites (validation doesn't use them).

Not verified: the perf numbers (needs GPUs). A maintainer still needs to review.

@wwwjn

wwwjn commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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


Needs discussion: the code is the same as in round 3. The lane-swapped image runs now show a ~1.4% saving per step, against ~0.2% at T1 and 0% at 4K. Two things are still open: the human note is unfilled, and the description doesn't explain why start_reading runs during optim_step rather than after it. 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: Needs discussion -- The code hasn't changed since round 3 and I still found no problems in it. The images arm now has lane-swapped numbers, which shows the one workload where this pays off. The remaining question is for the author and the maintainers: is ~1.4% on image runs, ~0.2% at T1 and 0% at 4K worth ~474 net lines of controller/trainer concurrency?

What changed since the last review. Head is still 60f00a2, so the diff is the same one reviewed in rounds 2 and 3. Only the description changed:

  • The images pair was rerun with the lanes swapped.
  • The round-3 question (start the readers after optim_step) is answered with a measured variant.

Example. Images run (5.1 MB groups), per step, previous PR -> this PR. The two values are the first pair, then the lane-swapped pair:

send_replica_columns   232 -> 0.1 ms   | 246 -> 0.1 ms
wait_for_microbatch    2104 -> 1954 ms | 2215 -> 2070 ms   (first group 135 -> 0.7 ms)
read_ahead + optimizer 47 -> 168 ms    | 46 -> 193 ms
push wait              362 -> 328 ms   | 364 -> 322 ms
net hidden             ~295 ms         | ~286 ms           (~1.4% of a 21 s step)

I rechecked both "net hidden" totals against the components, and they add up.

Resolved from the last review

  • Images were the only case that might pay off, and they are now lane-swapped. The component accounting reproduces across both lane orders (~290 ms per step).
  • The deferred-start_reading question has a measured answer in "You may ask".

Must fix

  1. The human note is still "TODO (Jiani)". The numbers are now in the description, but the author still needs to make the merge case in their own words. In particular: which recipe or workload this is for. At T1 it nets ~0.2%, at 4K it never triggers, and only image-heavy steps (~1.4%) see a real gain.

Questions

  • Placement of start_reading. The description's own component accounting favors the deferred variant (readers started after optim_step) or ties with it: ~42 vs ~48 ms at T1 and ~380 vs ~290 ms with images. It was rejected as "inside the spread between runs". But that spread is step-time noise, and the comparison was made on per-component timings, which are much less noisy. The deferred variant is the same code with one call moved, and it leaves timing/step/optimizer unchanged. Is there a reason besides noise to keep the reads overlapping optim_step?
Details
  • Net LoC: +564 / -90.
  • Rechecked "net hidden" for images with this PR's costs included (read_ahead, the optimizer delta, the push-wait delta):
    • pair 1: (232 + 2104 + 47 + 362) - (0.1 + 1954 + 44 + 124 + 328) = ~295 ms
    • pair 2: (246 + 2215 + 46 + 364) - (0.1 + 2070 + 68 + 125 + 322) = ~286 ms
  • The lane-corrected step-time drop (-1.36 s) is ~4.5x the data-path saving. The description already attributes the rest to forward_backward varying between runs, so step time alone can't confirm the gain.
  • Correctness checks from rounds 2-3 still hold at this head: plan accounting with get_nowait, the oldest-column pop on the leader, the single try/finally cancel, and the on-policy no-op.

Not verified: the perf numbers (needs GPUs). A maintainer still needs to review.

@wwwjn

wwwjn commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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


Needs discussion: the code is unchanged and the placement question from round 4 is now answered. Only the unfilled human note is still open. 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: Needs discussion -- The code is unchanged since round 2 (head is still 60f00a2) and I found no problems in it. The round-4 placement question now has an answer. The only open item is the unfilled human note, which has to make the merge case for ~474 net lines that save ~1.4% per step with images, ~0.2% at T1 and 0% at 4K.

What changed since the last review. Only the description. "Why not start the readers after the optimizer step?" now compares each run's own data-path total (send_replica_columns + wait_for_microbatch + read_ahead + optimizer + push wait) instead of "net hidden", which also depends on the baseline run each one was paired with.

Example. Data-path ms per step, from the description:

                        previous PR   readers during optim (this PR)   readers after optim
T1                      477           432                              433
images                  2845          2518                             2501
"net hidden" (T1)                     ~48 (vs. baselines 483, 478)     ~42 (vs. 475, 474)

The two placements tie on their own totals. The gap in "net hidden" that I raised in round 4 comes from the baselines, not from the placement. I rechecked the averages (477.5, 2845, 480.5 - 432 = 48.5, 474.5 - 433 = 41.5, 2808 - 2518 = 290, 2882 - 2501 = 381), and they match.

Resolved from the last review

  • Placement of start_reading: the totals tie, so keeping it during optim_step is justified. The try/finally covering only forward_backward and the read-ahead matches the description.

Must fix

  1. Still open: "Human note: TODO (Jiani)". The numbers are complete, but the author has to make the merge case in their own words, and agents don't write this section (CLAUDE.md, PR expectations 2). The note should say which workload this is for. Only image-heavy steps gain measurably (~0.29 s of a 21 s step). At T1 the gain is within noise, and at 4K read-ahead never triggers.
Details
  • Net LoC: +564 / -90, unchanged.
  • The correctness checks from rounds 2-4 still hold at 60f00a2: get_nowait plan accounting, the leader popping the oldest column (len < 2), the single try/finally cancel (including the NaN break), Trainer.close stopping an unconsumed started reader, and the on-policy no-op.
  • If maintainers weigh only the image case: groups 2 onward stay exposed (wait_for_microbatch ~2 s per step), so the data-path cost left in image runs is mostly outside what this PR hides.

Not verified: the perf numbers (needs GPUs). A maintainer still needs to review.

@wwwjn

wwwjn commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/6-read-ahead branch from fedba88 to 1f1bdcf Compare December 1, 2026 15:38
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/6-read-ahead branch from 1f1bdcf to 05f8582 Compare December 1, 2026 16:48
@wwwjn
wwwjn added this pull request to stack #6467 December 1, 2026 16:52
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/6-read-ahead branch from 05f8582 to 7822a60 Compare December 1, 2026 19:16
@wwwjn
wwwjn removed this pull request from stack #6467 December 1, 2026 21:17
@wwwjn
wwwjn added this pull request to stack #6471 December 1, 2026 21:18
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/6-read-ahead branch from 7822a60 to 8a8dd54 Compare December 1, 2026 21:29
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/6-read-ahead branch from 8a8dd54 to 6e75731 Compare December 1, 2026 22:31
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/6-read-ahead branch from 6e75731 to 4edc8fd Compare December 1, 2026 22:50
@wwwjn wwwjn changed the title [rl] Read the next step's rollout groups during the optimizer step [WIP] [rl] Read the next step's rollout groups during the optimizer step Dec 1, 2026
@wwwjn

wwwjn commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

from claude: Rebased onto #6301's new head 6e2d4ba, where each rollout worker records its own groups (recorder_lines is gone, so nothing here carries recorder lines anymore). Built on the latest heads of this stack. RL CPU suite: same 4 local env failures as before; 10-step bitwise run with one validation: all non-timing TensorBoard tags and the recorded rollouts match #5862. @claude review

@claude

claude Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

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


Needs discussion: no correctness bug after the rebase, but maintainers need to decide whether ~1.2% on image steps is worth the added concurrency, and whether the new one-slot leader column can depend on Monarch's message ordering, which I couldn't verify. 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: Needs discussion -- I found no correctness bug after the rebase. Two things are left for a maintainer: whether ~475 net lines of controller/trainer concurrency are worth a ~1.2% gain on image runs (noise at T1, zero at 4K), and whether the new one-slot column design can rely on a Monarch ordering guarantee I couldn't verify.

What changed since round 9 (4e4dd9e). Besides the rebase (Reader -> Prefetcher, start_reading -> start_prefetching, _send_columns folded into _send_replica_columns):

  • The leader holds one pending column instead of a two-entry deque. forward_backward takes it before any await.
  • A pull error that get_nowait takes from the queue now raises before forward_backward N. The new test covers it.

Example. Off-policy, with plan 2 queued when step 1 starts:

step 1: get_nowait -> plan 2 | fwd_bwd 1 (send task: plan 2's columns; leader handles them after fwd_bwd 1 returns)
        | read_ahead: start_prefetching on all ranks | optim 1 (+~80 ms GIL at T1), pull 0 wait, push 1
step 2: no column send (69 -> 0.1 ms) | fwd_bwd 2, first wait_for_microbatch 102 -> 0.4 ms
queue holds a pull error at step N's get_nowait -> raised before fwd_bwd N
on-policy, or 4K: get_nowait finds nothing -> unchanged; trainer/read_ahead = 0

Resolved from the last review

  • The human note no longer blocks the verdict (see the last line).
  • The step-time numbers now match the data-path saving. With images, the lane-corrected step is -0.26 s, against a 277 ms data-path saving. At T1 it is -0.1 s, with 0.375 s of lane bias, so it's noise.

Should consider

  • trainer.py:363 -- the one-slot column depends on Monarch starting forward_backward N before receive_replica_column N+1 (two endpoints, two mesh views). The previous deque didn't depend on message order (inline).

Questions

  • For maintainers: on the measured workloads, this saves ~0.26 s of a ~21 s image step, nothing outside noise at T1, and never triggers at 4K. It also slows the optimizer step by ~50-85 ms through the GIL. Is that worth the read-ahead state machine (the _ReadAhead hand-off, a try/finally cancel, a new endpoint, start/close on the prefetcher)?
  • #5764 (felipemello1) also makes a prefetcher start its first two reads early and adds close() for a prefetcher that was never iterated, on a different stack. Should the two share one mechanism once both land?
Details

Rechecked at this head:

  • Send ordering on the controller. _start_sending_next_columns creates the send task before the gather, but the task runs only after the gather's generator has issued every forward_backward.call. This holds if .call sends eagerly, which the docstring says and #5764's description also assumes (unverified: Monarch isn't installed here).
  • Pull error via read-ahead. It raises after this step's columns were sent and before forward_backward. The failed pull is already in _model_state_dict_pull_tasks, so teardown awaits it.
  • Exits. The finally cancels the send on an exception or the NaN break. The NaN check runs before _read_ahead, so a NaN step never leaves prefetchers started. An optim, push or pull failure after _read_ahead leaves them started, and Trainer.close cancels their queued groups.
  • Accounting. commit_training_sample_ids still covers only plan N. Policy age is computed when the step consumes the plan (test_a_read_ahead_batch_policy_age_uses_the_version_it_trains_at). timing/step/read_ahead is recorded on every non-NaN step.
  • Prefetcher. start() submits min(N, 2) groups and __iter__ continues from len(prefetches), so the order and depth are the same as an unstarted pass.
  • Overlap search: "read-ahead rl", "prefetcher in:title", "controller.py rl trainer_loop". Found the rest of this stack (#6302, #6303, #6334, #6469), #5764 (above), and #6423 (a rename of Batcher; touches the same controller and will conflict mechanically).
  • Net LoC: +565 / -89.

Not verified: Monarch's cross-endpoint message ordering and eager .call sends; perf numbers (they need GPUs); the CPU tests at this head. A maintainer still needs to review.

Before merge: fill in the human-written summary.

Comment thread torchtitan/rl/trainer/trainer.py Outdated
the rollouts it names, for that step's prefetcher to read and pack. With read-ahead, step
N+1's column comes after step N's `forward_backward` took column N: the controller sends
`forward_backward` first."""
assert self._is_replica_leader and self._replica_column is None

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.

New since round 9: the leader now has one column slot instead of the two-entry deque. That makes this assert depend on a Monarch delivery guarantee that I couldn't verify. forward_backward N goes out through self.trainer.by_dp_rank[i].forward_backward.call, and column N+1 goes out through leader_by_dp_rank[i].receive_replica_column.call_one. Those are two endpoints, reached through two mesh views. The slot is only safe if Monarch starts the forward_backward N handler before the receive_replica_column N+1 handler.

_start_sending_next_columns's docstring states this ordering, but nothing else in the repo relies on it or cites it. The unit test can't check it, because its fake endpoints are ordered by asyncio's ready queue, not by Monarch. If a Monarch change or a transport path reorders the two messages, a read-ahead step crashes here with a bare AssertionError. With python -O it would be worse: column N+1 would silently overwrite column N.

The deque from the previous head did not depend on message order, because forward_backward N always popped the oldest column. Either bring it back (about 3 lines), or link the Monarch doc or source that guarantees per-sender ordering across endpoints in the docstring.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from claude: Restored an ordered queue: receive_replica_column appends and each prefetcher takes the oldest column, so column N+1 arriving before forward_backward N takes column N no longer depends on how Monarch orders the two endpoints. test_a_column_that_arrives_early_waits_for_the_one_before_it fails with the one-slot version. 968fbf7

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/6-read-ahead branch 2 times, most recently from ff19c36 to 968fbf7 Compare December 2, 2026 00:43
@wwwjn

wwwjn commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

from claude: @claude review

@claude

claude Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

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


Needs discussion: the round-10 ordering concern is fixed (the leader keeps columns in a deque again) and I found no correctness bug. Two comments still describe the old one-slot design, and maintainers still need to decide whether ~1.2% on image steps is worth the added concurrency. 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: Needs discussion -- The round-10 ordering concern is fixed and I found no correctness bug at 968fbf7. What's left is the maintainers' call from round 10: are ~500 net lines of controller/trainer concurrency worth ~1.2% on image steps, which is noise at T1 and zero at 4K?

What changed since round 10. The leader holds its columns in a collections.deque again. receive_replica_column appends a column, and _new_prefetcher pops the oldest. The new test_a_column_that_arrives_early_waits_for_the_one_before_it fails with the one-slot version. The description adds a lanes image (still a placeholder) and the regression the test catches. Net LoC: +591 / -94.

Example. The leader sees the two columns in either order:

read-ahead step N:  fwd_bwd N uses the prefetcher started at N-1 (no pop)
                    column N+1 arrives -> deque [N+1] -> start_prefetching pops N+1
plain step N, column N+1 early:  deque [N, N+1] -> fwd_bwd N pops N -> start_prefetching pops N+1
non-leader:         deque empty -> column None (assert holds)

Resolved from the last review

  • trainer.py one-slot column depending on Monarch's cross-endpoint ordering: fixed. The order no longer matters.

Should consider

  • trainer.py:434 -- this comment is stale since the deque came back ("the slot holds one", "before any await") (inline).
  • controller.py:1674 -- the docstring still presents the unverified Monarch ordering claim as if the code relied on it (inline).

Questions

  • Still open from round 10, for maintainers: is the read-ahead machinery worth it for the measured workloads? That machinery is the _ReadAhead hand-off, the try/finally cancel, the start_prefetching endpoint, the leader deque, and start/close on the prefetcher. The measured gain: images save ~0.26 s of a ~21 s step lane-corrected, T1 is within lane noise, and 4K never triggers. It also costs ~50-85 ms of optimizer step through the GIL.
  • Still open: #5764 also starts a prefetcher's first reads early and adds a close(). Should the two share one mechanism?
Details

Rechecked at 968fbf7:

  • Column order. Every pop goes through _new_prefetcher (popleft). The leader holds at most columns N and N+1. forward_backward takes _started_prefetcher or pops before it awaits, and start_prefetching runs only after _send_replica_columns has awaited every leader's call_one. So (column is not None) == self._is_replica_leader holds in every order.
  • Exits. The finally cancels the send task on an exception or on the NaN break. The NaN check runs before _read_ahead, so a NaN step never starts prefetchers. Trainer.close closes a started prefetcher that no step consumed.
  • Pull error via read-ahead. _start_sending_next_columns raises the queued exception before the gather. test_a_pull_failure_taken_by_read_ahead_fails_the_loop_before_forward_backward covers it.
  • Accounting. timing/step/read_ahead is recorded on every step except a NaN break, so compute_perf_ratio_metrics always has the key.
  • Overlap search: "read-ahead rl", "prefetcher in:title". It found only this stack (#6302, #6303, #6334, #6469) and #5764, the same as round 10.

Not verified: the perf numbers (they need GPUs), and the CPU tests at this head. A maintainer still needs to review.

Before merge: fill in the human-written summary.

Comment thread torchtitan/rl/trainer/trainer.py Outdated
Comment on lines +434 to +435
# Before any await: the next step's column comes in while this runs
# (`Controller._start_sending_next_columns`), and the slot holds one.

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.

This comment was written for the one-slot version, and the deque made it stale. "The slot holds one" is no longer true. "Before any await" also no longer matters for correctness: _new_prefetcher pops the oldest column, so it picks column N even if column N+1 is already queued. A reader would think there is an ordering invariant to protect here when there isn't one. Either drop the comment or say why the order doesn't matter:

Suggested change
# Before any await: the next step's column comes in while this runs
# (`Controller._start_sending_next_columns`), and the slot holds one.
# A started prefetcher (read-ahead) already holds this step's column; else take the
# oldest one, which is this step's even if the next step's column came in first.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from claude: Applied your wording. 5ff6a36

Comment thread torchtitan/rl/controller/controller.py Outdated
Comment on lines +1674 to +1679
columns; else None, and the next step takes its plan itself. The task runs once the loop
yields, after the `forward_backward` calls went out (`.call` sends at once), and an actor
starts one sender's calls in send order: each leader takes its column in
`forward_backward` (before any await) before the next column's handler starts. That
handler runs once `forward_backward` returns, but the pickling and the transfer overlap
it."""

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.

This docstring still makes the Monarch ordering claim from the one-slot version: "an actor starts one sender's calls in send order: each leader takes its column in forward_backward (before any await) before the next column's handler starts". It is unverified, and the leader's deque made it unnecessary. As written, it reads as an invariant the code depends on. Keep the perf part and drop the ordering claim, e.g.:

Suggested change
columns; else None, and the next step takes its plan itself. The task runs once the loop
yields, after the `forward_backward` calls went out (`.call` sends at once), and an actor
starts one sender's calls in send order: each leader takes its column in
`forward_backward` (before any await) before the next column's handler starts. That
handler runs once `forward_backward` returns, but the pickling and the transfer overlap
it."""
columns; else None, and the next step takes its plan itself. The task runs once the loop
yields, after the `forward_backward` calls went out, so the pickling and the transfer
overlap `forward_backward`. A column may reach a leader before or after `forward_backward`
takes the current one; the leader keeps them in arrival order (`Trainer._replica_columns`)."""

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from claude: Applied: the ordering claim is gone; the docstring keeps the overlap and points at the leader's arrival-order queue. 5ff6a36

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/6-read-ahead branch from 968fbf7 to 5ff6a36 Compare December 2, 2026 01:10
@wwwjn

wwwjn commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

from claude: @claude review

This round (5ff6a36): the two stale ordering comments, as suggested.

@claude

claude Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

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


Needs discussion: both comment fixes from round 11 are in at 5ff6a36 and I found no new problems. Maintainers still need to decide whether ~1.2% on image steps is worth the read-ahead machinery. 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: Needs discussion -- Both comments from round 11 are fixed at 5ff6a36, and I found no new problems. The maintainers still have to decide whether the read-ahead machinery is worth ~1.2% on image steps.

What changed since round 11. Two comments were reworded, as I suggested. No code changed.

  • trainer.py:1093 (diff side): the comment in forward_backward now says that taking the oldest column picks this step's column, even when the next step's column arrived first. The one-slot wording ("the slot holds one", "before any await") is gone.
  • controller.py _start_sending_next_columns: the docstring no longer claims that Monarch keeps message order across endpoints. It keeps the overlap part and points at the leader's arrival-order queue (Trainer._replica_columns).

I reread the rest of the diff at this head. It matches what I reviewed in round 11 at 968fbf7. 968fbf7 can't be fetched in this checkout, so I couldn't diff the two heads directly.

Example. Off-policy, with plan 2 already queued when step 1 starts:

step 1: get_nowait -> plan 2 | fwd_bwd 1 (send task: plan 2's columns -> leader deque)
        | read_ahead: start_prefetching on all ranks (pops column 2) | optim 1, pull 0 wait, push 1
step 2: no column send | fwd_bwd 2 trains on the prefetcher started in step 1
on-policy, or 4K: get_nowait finds nothing -> unchanged; trainer/read_ahead = 0

Resolved from the last review

  • trainer.py: the stale one-slot comment in forward_backward is replaced.
  • controller.py: the unverified Monarch ordering claim is dropped from _start_sending_next_columns.

Questions

  • Still open from rounds 10-11, for maintainers: is the read-ahead machinery worth it? That machinery is the _ReadAhead hand-off, the try/finally cancel, the start_prefetching endpoint, the leader deque, and start/close on the prefetcher. Measured gains: about 0.26 s of a ~21 s image step (lane-corrected), within lane noise at T1, and read-ahead never triggers at 4K. The cost is 50-85 ms more optimizer-step time, because the prefetch thread holds the GIL.
  • Still open: #5764 also starts a prefetcher's reads early. Should the two share one mechanism once both land?
Details

Rechecked at 5ff6a36:

  • Column order. Every pop goes through _new_prefetcher (popleft). A leader holds at most columns N and N+1, so the assertion (column is not None) == self._is_replica_leader holds in either arrival order. test_a_column_that_arrives_early_waits_for_the_one_before_it covers the case where N+1 arrives first.
  • Exits. The finally cancels the send task on an exception or on the NaN break. A NaN step never starts prefetchers. Trainer.close closes a started prefetcher that no step consumed.
  • Accounting. timing/step/read_ahead is recorded on every step except a NaN break.
  • Overlap search: "read-ahead rl", "prefetcher in:title". It found only this stack (#6302, #6303, #6334, #6469) and #5764, the same as rounds 10-11.
  • Net LoC: +590 / -94.

Not verified: the perf numbers (they need GPUs), the CPU tests at this head, and an exact diff from 968fbf7 (not fetchable here). A maintainer still needs to review.

Before merge: fill in the human-written summary.

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