Repository navigation
Conversation
|
@claude review |
There was a problem hiding this comment.
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
- 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_microbatchand for step time, with a noise estimate (e.g. repeated lanes or swapped GPU halves).
Should consider
controller.py:1507: onetry/finallywould replace both cancel sites and cover every exit (inline).controller.py:1609:trainer/read_aheadis redundant with the read-ahead hop key (inline).microbatch_group_reader.py:233:_new_threadis a@staticmethodthat returns a pool (inline).test_microbatch_group_reader.py:510: possible race betweenstart()andclose()(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'sget()unblocks the batcher'sput(). The read-ahead task now does too, so up to one plan is held beyond the queue'smaxsize=1.
Questions
- How often is plan N+1 already in the queue when step N starts, i.e. is
timing/step/wait_for_training_batchabout 0 in steady state? If that's the usual case, aget_nowait()before the gather (no read-ahead otherwise) captures most of the win. It drops thetakenevent, the not-taken cancel branch andtest_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.getremoves the item only throughget_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 afterget()returns, sotakenis set exactly when the plan was consumed. - Column order on the leader. Each
forward_backward(orstart_reading) pops the oldest column, and at most two columns are ever held, so thelen < 2assert holds. - Off-policy bound unchanged. Staleness is bounded by the
(target_offpolicy_steps + 1) * Pslots, 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 duringoptim_stepcan't interleave with training collectives. - No extra GPU memory.
preprocess_imagesruns 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.
| for trainer_at_dp_rank in self.trainer.by_dp_rank | ||
| ) | ||
| ) | ||
| except BaseException: |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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().
| assert read_threads[0] is not threading.main_thread() | ||
|
|
||
|
|
||
| def test_close_stops_a_started_reader_no_step_consumed() -> None: |
There was a problem hiding this comment.
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.
e0af5c8 to
804c8d6
Compare
|
@claude review again |
There was a problem hiding this comment.
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.pycancel sites: now a singletry/finallyfrom the gather through_read_ahead, covering the NaNbreakand any exception.- The
trainer/read_aheadmetric and its assertion are removed. _new_threadis now the module-level_new_read_pool().test_closing_a_started_reader_cancels_its_queued_reads: now waits on astartedevent beforeclose(), so there is no race.- The mock-only
test_close_stops_a_started_reader_no_step_consumedis removed. - The backpressure docstrings (module and
_batcher_loop) now sayget_nowaitalso unblocks the batcher, and that up to one plan beyondmaxsizeis held.
Must fix
- 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 thefinally, the run is already exiting (exception or NaNbreak), 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_readerpops the oldest column. A leader holds at most step N's column (popped at fwd_bwd N or at the previousstart_reading) plus N+1's, solen < 2inreceive_replica_columnholds. - On-policy. Plan N+1's groups wait for pull N, so the queue is empty at fwd_bwd N,
get_nowaitreturns None, and the path is unchanged. Removingtest_no_read_ahead_when_the_next_plan_comes_after_forward_backwardis fine: that branch is now oneexcept QueueEmpty: return None. - Timing.
timing/step/read_aheadis recorded on every step (about 0 when nothing was taken), socompute_perf_ratio_metricsalways sees the key.
Not verified: perf on this head (needs GPUs). A maintainer still needs to review.
804c8d6 to
60f00a2
Compare
|
@claude review again |
There was a problem hiding this comment.
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
-
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_aheadand ~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.
- At T1 the PR hides ~122 ms per step but adds ~20 ms of
Questions
- Most of the new optimizer-step cost is the reader thread holding the GIL (
pickle.loads, materialize, pack) whileoptim_stepruns. Would deferringstart_readinguntil afteroptim_stepreturns keep most of the hiding? It would still overlap the push wait and the next step'ssync_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_backwardgather, so column N+1 can reach a leader beforeforward_backwardN's message does. The deque handles it either way:forward_backwardN pops column N (the oldest), and thelen < 2assert holds because at most columns N and N+1 are held.test_each_step_trains_on_the_oldest_columncovers this. - Dispatch delay. The send task runs
_replica_columns(plan)(selects rollouts per DP rank) synchronously before theforward_backwardcalls are dispatched. Pickling happens in the per-leader send tasks, which run after the dispatch. Soforward_backwardN starts later only by the selection cost. It should be small, but it's untimed, and its cost lands intiming/step/forward_backward. - NaN break after a read-ahead. Breaking at step N+1 leaves N+2's readers started.
Trainer.closestops them, and thefinallycancels the already-finished send task (a no-op). - No other callers of
_replica_column,receive_replica_columnor 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.
|
@claude review again |
|
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 |
There was a problem hiding this comment.
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_readingquestion has a measured answer in "You may ask".
Must fix
- 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 afteroptim_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 leavestiming/step/optimizerunchanged. Is there a reason besides noise to keep the reads overlappingoptim_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_backwardvarying 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 singletry/finallycancel, and the on-policy no-op.
Not verified: the perf numbers (needs GPUs). A maintainer still needs to review.
|
@claude review again |
There was a problem hiding this comment.
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 duringoptim_stepis justified. Thetry/finallycovering onlyforward_backwardand the read-ahead matches the description.
Must fix
- 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_nowaitplan accounting, the leader popping the oldest column (len < 2), the singletry/finallycancel (including the NaNbreak),Trainer.closestopping 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.
60f00a2 to
56ba36d
Compare
56ba36d to
a25506e
Compare
|
@claude review again |
fedba88 to
1f1bdcf
Compare
1f1bdcf to
05f8582
Compare
05f8582 to
7822a60
Compare
7822a60 to
8a8dd54
Compare
8a8dd54 to
6e75731
Compare
6e75731 to
4edc8fd
Compare
|
from claude: Rebased onto #6301's new head 6e2d4ba, where each rollout worker records its own groups ( |
|
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. |
There was a problem hiding this comment.
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_backwardtakes it before any await. - A pull error that
get_nowaittakes from the queue now raises beforeforward_backwardN. 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 startingforward_backwardN beforereceive_replica_columnN+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
_ReadAheadhand-off, atry/finallycancel, a new endpoint,start/closeon 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_columnscreates the send task before the gather, but the task runs only after the gather's generator has issued everyforward_backward.call. This holds if.callsends 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
finallycancels the send on an exception or the NaNbreak. The NaN check runs before_read_ahead, so a NaN step never leaves prefetchers started. An optim, push or pull failure after_read_aheadleaves them started, andTrainer.closecancels their queued groups. - Accounting.
commit_training_sample_idsstill 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_aheadis recorded on every non-NaN step. - Prefetcher.
start()submitsmin(N, 2)groups and__iter__continues fromlen(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.
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
ff19c36 to
968fbf7
Compare
|
from claude: @claude review |
|
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. |
There was a problem hiding this comment.
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.pyone-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
_ReadAheadhand-off, thetry/finallycancel, thestart_prefetchingendpoint, the leader deque, andstart/closeon 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_backwardtakes_started_prefetcheror pops before it awaits, andstart_prefetchingruns only after_send_replica_columnshas awaited every leader'scall_one. So(column is not None) == self._is_replica_leaderholds in every order. - Exits. The
finallycancels the send task on an exception or on the NaNbreak. The NaN check runs before_read_ahead, so a NaN step never starts prefetchers.Trainer.closecloses a started prefetcher that no step consumed. - Pull error via read-ahead.
_start_sending_next_columnsraises the queued exception before the gather.test_a_pull_failure_taken_by_read_ahead_fails_the_loop_before_forward_backwardcovers it. - Accounting.
timing/step/read_aheadis recorded on every step except a NaN break, socompute_perf_ratio_metricsalways 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.
| # Before any await: the next step's column comes in while this runs | ||
| # (`Controller._start_sending_next_columns`), and the slot holds one. |
There was a problem hiding this comment.
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:
| # 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. |
There was a problem hiding this comment.
from claude: Applied your wording. 5ff6a36
| 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.""" |
There was a problem hiding this comment.
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.:
| 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`).""" |
There was a problem hiding this comment.
from claude: Applied: the ordering claim is gone; the docstring keeps the overlap and points at the leader's arrival-order queue. 5ff6a36
968fbf7 to
5ff6a36
Compare
There was a problem hiding this comment.
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 inforward_backwardnow 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 inforward_backwardis 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
_ReadAheadhand-off, thetry/finallycancel, thestart_prefetchingendpoint, the leader deque, andstart/closeon 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_leaderholds in either arrival order.test_a_column_that_arrives_early_waits_for_the_one_before_itcovers the case where N+1 arrives first. - Exits. The
finallycancels the send task on an exception or on the NaNbreak. A NaN step never starts prefetchers.Trainer.closecloses a started prefetcher that no step consumed. - Accounting.
timing/step/read_aheadis 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.
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_backwardN and starts the next step's prefetchers after it returns. So the send overlapsforward_backwardN, 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.Merge bottom-up.
Problem
training.preprocess_microbatch_groups_lazily=False(the default), for every group.Solution
forward_backwardN, if the batcher queued plan N+1, the controller takes it (get_nowait) and starts a task sending its columns; else nothing changes.forward_backwardcalls went out (.callsends at once), so each leader takes column N inforward_backwardN before column N+1's handler starts. Monarch runsreceive_replica_columnonceforward_backwardreturns, so pickling and transfer overlapforward_backwardN; unpickling does not.forward_backwardN, the controller waits for the send and callsTrainer.start_prefetchingon every rank; optimizer step N and push N follow.Trainer.start_prefetchingbuilds and starts step N+1'sMicrobatchGroupPrefetcher, whose thread makes the first two groups;forward_backwardN+1 trains on it.forward_backwardN, as the step's own take does. Atry/finallycancels the send on any exit.timing/step/read_ahead(exposed time afterforward_backwardN), its share of the stepperf/trainer/step_time_ratio/read_ahead, andtrainer/read_ahead(1 on a read-ahead step).Results
NOTE:
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.forward_backwardN 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 main076f2e88b(770 passed): recipe tests whosetorch_checkpointing.storage.fsspec_storageimport 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 beforeforward_backwardN 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 anAttributeErrorthat hides the pull error.test_trainer_loop.py::test_the_next_steps_columns_go_out_during_forward_backward: with plan 2 queued,forward_backward1 starts before column 2 is handled, and the column goes out beforeforward_backward1 returns (fake endpoints).test_microbatch_group_prefetcher.pypp2_tp2_startedandtest_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.