Repository navigation
perf(checkpoint): batch generation prefix TQ I/O - #4508
Conversation
e4dc44d to
079933e
Compare
079933e to
7eb9a01
Compare
7eb9a01 to
a82e2a2
Compare
a82e2a2 to
5498a0a
Compare
terrykong
left a comment
There was a problem hiding this comment.
Thanks for this. The write-side batching has a good shape: pulling out _encode_record so single-row and batch writes share one encoder, and the freeze → yield → seal generator, are both the right moves. These hold up: partial-PUT rollback, ack-before-seal, the deadline release, the oversized row written alone, lock order, dtype grouping, and the fingerprint exclusion (a mutation test confirms the test catches it). All the PR's CPU tests pass.
Before merge
- Rebase: GitHub shows conflicts with the base branch.
- The description says "Stacked on #4507", but the base is #4612's branch (
amahishi/r3-prefix-recovery). Please update it. - This is a perf PR with no numbers. Please add
timing/rollout_checkpoint/total_save_secondsbefore vs after to the description, from a run with hundreds of active calls per DP leader. It is already logged, and dispatch is blocked during the save, so it is the time the run loses. - Please close #4389 as superseded. It is the older copy of this PR, and its
tools/benchmark_tq_prefix_writes.pyis byte-for-byte the same.
Size. This PR is +2,802 lines, on a feature that is already over 20k lines across the stack. With the inline asks it drops to about +1,000 (≈ +500 product):
- one cut path (comment at L1399): ≈ −75 product, −30 to −40 test
- no copied config defaults or limits class (comment at L647): ≈ −30
- benchmark tools out (comment on the writes tool): −1,235
- no per-row results in the batch write (comment at L741): ≈ −20 to −30
- read side to its own PR (comment on
PrefixReadBatcher): ≈ −440
Smaller and optional: put could call put_many (−8), and a shared "rolled back" assert helper (first copy) plus pytest-asyncio in the batcher tests would save ≈ 23.
Open #4506 threads that also apply here
- r4262413829 (abort on the event loop waits on
lifecycle_lock): please fix it in #4506; this PR then needs no change. Until then, batching widens the stall from one call to up to 256 calls held across one put. - r4262414074 / r4262414095 (call on
self, not through the class, for the test fake): this PR adds 3 more class-qualified calls (generation_cut_capture.py L577, vllm_worker_async.py L903, L964) and grows the fake's name list from 21 to 24 (test L649-L652). - r4262413947 (simplify the frozen/sealed buffer): this PR adds one more rollback (L1096) and widens the rollback
excepttoBaseException(L1188).
Question, no change needed. Cut batches count tokens only (L1340). With MoE router replay, each token also carries layers × top-k int16 routes: about 3.2 GB at 48 layers / top-8 for a full 4M-token batch (arithmetic only; each chunk holds only the tokens since the last cut). What is the largest single put you have seen with routes on?
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4508-batched-prefix-io.html
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4508-size-and-reuse.html
Generated by Claude Code
6c72a0f to
788133a
Compare
788133a to
507a670
Compare
terrykong
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround. All 7 round-1 comments are fixed and still hold at 507a670. The PR is now two commits and +1,740/−334, down from +2,802, and the description leads with restore numbers. _encode_record is a clean move of existing code, and the new _next_inventory and _assert_rolled_back test helpers already cover what I was going to ask for there.
Size. This is part 10 of 11 in a stack that is already past 20k lines. C8–C11, C15 and C16 remove about 90 product lines and about 140 test lines, with no behavior change except the one noted in C8. C13 removes about 25 more product lines.
- (C8) One step to build the ack and seal, and one loop in
flush(). - (C9) Leftovers in
tq_token_sink.pyfrom removingstage_generation_prefix. - (C10) Drop two guards that can never fire, and
max_pending. - (C11) Test helpers and two repeated tests — do this after C10.
- (C12) Small:
aclose()hangs on a stopped loop. - (C13) After the rebase onto #4979, restores stop using the batcher on both native and Dynamo; move the batched read into
resolve_restore. - (C14) Tests that fail if restores stop sharing reads: one unit test through
resolve_restored_call, one grep in the functional script. - (C15) One put per batch instead of grouping rows by their column set, plus a column check.
- (C16) Delete a test that repeats an existing per-row retry test.
- (C17) Rename the two batch settings to
prefix_write_max_rows/prefix_write_max_tokensand addprefix_read_max_rows; a read limit of 1 should read the old way, in parallel. - (C18) #4612's head now saves sampler top-k in cut rows; carry it through
_cut_transactionand_fetch_rowswhen you rebase.
Dynamo and the rebase. The merge plan is #4583 → main, then #4979 on #4583, #4612 on #4979, and this PR on #4612. After that, this PR has to work on native vLLM and with ++policy.generation.dynamo=true. C13 and C14 are the only Dynamo-specific asks. These already work on Dynamo with no change:
- Cut-time batched writes: Dynamo's cut calls the shared
run_cut, so the batched put runs the same way on both paths. - Config plumbing for the new batch settings (three after C17), including the
restart_shardreplay of_TokenCaptureSetup. - Event loops: each worker has one serving loop per mode (native: the uvicorn thread's loop; Dynamo: the actor loop).
- Teardown.
When you rebase:
- Keep #4979's
deadlinekwarg onrun_cut. - Append the new
_TokenCaptureSetupfields (three after C17), in order, to #4979's_TokenCaptureSetup(...)call. - In
shutdown(), awaitprefix_recovery.aclose()before settinghttp_server.should_exit, so the serving loop is still running when the reader closes (see C12). - #4612 moved to
2459562(score centering with prefix recovery). Port its sampler top-k cut and restore steps into the batched path (C18).
PR description.
- Name
start_capture/resolve_restored_callas the restore call site after the rebase. - Update the "an outage costs N+1 GETs" and "The worker awaits
read_restore_chunks" lines to match C13. - List the Dynamo L1 run from C14.
- Say which path (native or Dynamo) the pending
total_save_secondsrun used.
Before merge (still open from round 1):
- No unit or functional CI has run on 507a670; only the DCO, copyright and semantic-title checks ran. The last
/ok to testwas on def6e59 (2026-10-19). Please trigger it on the current head. timing/rollout_checkpoint/total_save_secondsbefore vs after is still "pending" in the description. This number is what justifies the size of the batching. In the same run, please also report terminal-response latency during a cut at batch size 256 vs 1. Each batch holds up to 256 calls' lifecycle locks until its put returns. A call that finishes meanwhile waits for its lock on an event-loop worker thread (asyncio.to_thread(_finish_request_capture); after #4979, prompt_and_capture.py L524); 32 of those fill the default pool and stall other off-loop work until the put returns.- Route bytes: your 2026-10-19 comment promised the largest put's size with routes on, from an R3 run (a full 4,194,304-token batch could carry ~3.2 GB of routes). Please post it, or cap the put by bytes.
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4508-how-it-works.html
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4508-what-can-shrink.html
Generated by Claude Code
507a670 to
46c9ea6
Compare
46c9ea6 to
a3b78ae
Compare
|
/ok to test a3b78ae |
A checkpoint cut wrote one TransferQueue row per active call, so a worker with hundreds of calls in flight spent the cut in per-row put overhead. Write the cut's chunk rows in batches instead. - PrefixRecovery._cut_transaction keeps a call's cut frozen, under its lifecycle, until its batch is written and every acknowledgement in the batch is built; only then does each call seal. Leaving the lifecycle rolls an unsealed cut back and clears its row. - checkpoint_cut batches rows up to rollout_recovery. generation_prefix_batch_size rows and generation_prefix_batch_max_tokens tokens per put; one larger row is written alone, never split. - Failures stay per call, as Gym acknowledges them: a failed freeze, acknowledgement or seal fails only its call. A failed batch put is retried one row per put, so one bad row fails only its own call. Rows written but never handed to a call (only an interruption leaves them) are cleared. Past the control deadline no further put starts. - TQTokenSink.stage_generation_prefix_batch groups rows by field dtype and shape and writes each group with one put_many; a failed put discards every key of the batch and raises. Single and batched rows share _encode_record. The single-row stage_generation_prefix is removed. - Both limits are runtime knobs on RolloutRecoveryConfig, passed to the workers through setup_token_capture and PrefixRecoveryParts, and excluded from the bootstrap fingerprint. Co-authored-by: Ananth Subramaniam <[email protected]> Signed-off-by: Anish Mahishi <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
After a restart every cut call on a worker resumes at once, and each restore read its chunk rows in its own TQ GET. Share those reads. - PrefixReadBatcher is an event-loop-local coalescer: concurrent reads share GETs of at most rollout_recovery.generation_prefix_batch_size distinct keys, deduplicated, with each caller's chain order preserved. Cancelling one caller does not cancel the shared GET for the others. If a multi-key GET fails, each key is read alone once, so a bad row fails only the callers that asked for it and an outage costs N+1 GETs. - PrefixRecovery owns the reader. The worker awaits read_restore_chunks on the serving loop and passes the rows to resolve_restore, which reads them itself if the shared read failed and regenerates the call if they still cannot be used. The worker closes the reader before shutting recovery down. Signed-off-by: Anish Mahishi <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Seal each batched cut as its key arrives: drop the transaction's second yield and drive each call with one send; reuse stage() for the row-by-row fallback after a failed batch put. An interruption now keeps the cuts sealed before it, as a batch of one already did. - Write a generation-prefix batch in one put and reject rows whose column names, dtypes or trailing dims differ, since the TensorDict takes row 0's columns and stack_or_nest would promote a dtype or nest a trailing dim without raising. - Fold the single-caller sink helper into stage() and keep one discard helper that takes a key list. - Drop the prefix reader's unreachable unique-key and short-read guards and its unused max_pending semaphore. - Do not hang closing the prefix reader on a stopped but open serving loop. - Rename the limits to prefix_write_max_rows / prefix_write_max_tokens and add prefix_read_max_rows; with 1, no batcher is built and each restore reads on its own thread, as before batching. - Read restored prefixes inside the now-async resolve_restore, which native and Dynamo serving both await through resolve_restored_call, so every restore shares reads; drop read_restore_chunks and the caller's fallback read. A failed read now warns and regenerates the call. - Forward the three limits to child HTTP frontends' token capture. - Test that concurrent restores through resolve_restored_call share one read, that a batched cut carries each call's sampler top-k back through that read, and require the shared-read log line in the prefix-recovery functional test. Deduplicate the reader, batch-stage and retry tests. Signed-off-by: Anish Mahishi <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
a3b78ae to
4d254b8
Compare
|
/ok to test 4d254b8 |
What does this PR do ?
Batches the TransferQueue I/O behind generation-prefix recovery: a checkpoint cut stages all of a worker's active prefixes in a few bounded PUTs instead of one PUT per call, and resumed requests share coalesced GETs for their restored prefixes.
On 8,192 rows across 32 TQ clients, a cut's writes finish 23× faster at 1k-token prefixes (10.1 s → 0.44 s) and 2.7× faster at 16k (10.2 s → 3.75 s). A mass resume of 8,192 restores across 128 workers finishes 6–13× faster, with p50 restore latency down from 6.9 s to 1.3 s. See Benchmarks.
Based on main, now that #4612 (router-replay prefix recovery) and #4979 (Dynamo) have merged.
Rebased onto main: the batched cut stages each chunk's sampler top-k (score centering) beside its routes, and the restore read fetches it back. Since #4979, native vLLM and Dynamo both restore through
prompt_and_capture.resolve_restored_call, so the shared read now happens insidePrefixRecovery.resolve_restore, which that function awaits. The PR is three commits: batched cut writes, coalesced restore reads, then the second-round review changes and the rebase onto main.Issues
How it works
flowchart LR subgraph Cut["Checkpoint cut (per vLLM DP leader)"] I[Gym inventory<br/>active calls] --> F[Freeze each call<br/>lifecycle lock held] F --> B[Group rows into batches<br/>≤ batch_size rows, ≤ max_tokens] B --> P[One TQ PUT per batch] P --> S[Build each call's ack<br/>and seal it] end subgraph Restore["Resume after restore"] R1[request A] --> Q[PrefixReadBatcher] R2[request B] --> Q Q --> G[Coalesced TQ GET<br/>≤ batch_size keys, deduplicated,<br/>chain order kept] endWrites (
prefix_recovery/recovery.py,tq_token_sink.py):PrefixRecovery._cut_transactionturns each active call's cut into a generator transaction. It freezes the call under its lifecycle, yields its chunk record, then receives its staged key, builds its acknowledgement, and seals; leaving the lifecycle rolls an unsealed cut back.checkpoint_cutbatches the records (_cut_batched). Every cut takes this path;prefix_write_max_rows: 1writes each call in its own PUT.stage_generation_prefix_batchwrites the batch in oneput_manyand returns the written keys. Rows must share column names, dtypes and trailing dims (one worker's cut does); otherwise it raises before writing and_cut_batchedwrites each row alone. On a failed put it discards every key of the batch, since the put may have written some fields, and raises. A row larger than the token limit is written alone and never split. Router-replay routes and score centering's sampler top-k ride as tensor attachments, as on the single-row path; a call whose top-k is missing fails its own cut (sampler_topk_unavailable).Failure handling: as in the base stack, failures are per call: a call that cannot be cut is acknowledged as
durable_failureand counted under the base's failure reasons (cut_error, orcontrol_deadlinepast the deadline), its frozen cut rolls back, and it regenerates after a restore, while the other calls keep their cuts. A failed batched PUT is retried one row per PUT, so one bad row fails only its own call. A failed acknowledgement or seal fails only its call, whose transaction clears its own row. Rows written but never handed to a call, which only an interruption can leave, are cleared too, so no unsealed key is ever advertised to Gym.Cut deadline: the base stack bounds a cut by Gym's control timeout. Past the deadline no new TQ write starts. Rows frozen for the next batch roll back, and they and every call not yet reached are acknowledged as
durable_failure; they regenerate after restore.Reads (
prefix_read_batcher.py,prefix_recovery/recovery.py,vllm/prompt_and_capture.py):PrefixReadBatcheris an event-loop-local coalescer for restore-time GETs, owned byPrefixRecovery. Concurrent requests share GETs of at mostprefix_read_max_rowsdistinct keys, with keys deduplicated and each request's chain order preserved. Cancelling one request does not cancel the shared GET for others. If a multi-key GET fails for any reason, each key is re-read alone once, so a bad row fails only the requests that asked for it, and an outage costs N+1 GETs. Withprefix_read_max_rows: 1there is no batcher: each restore reads in its own thread, as before this PR.resolve_restoreis async: on the serving loop it reads the call's rows through the shared reader, then rebuilds and verifies the prefix off the loop.start_capture→resolve_restored_callawaits it on both native vLLM and Dynamo. Any failed read or unusable prefix logs a WARNING and the call regenerates from its turn boundary; the worker closes the reader before shutting recovery down.Config: three new knobs under
rollout_recovery. Their only defaults are theRolloutRecoveryConfigfields;setup_single_controllerpasses them throughGenerationInterface.setup_token_captureto the vLLM workers, which hand them toPrefixRecoveryinPrefixRecoveryPartsand forward them to child HTTP frontends (multi_api.py).restart_shardreplays them into a replacement worker. Megatron generation accepts and ignores them.All three are runtime knobs, excluded from the rollout-checkpoint bootstrap fingerprint, so changing them does not invalidate an existing checkpoint.
Benchmarks
One 128-CPU node, TQ
simplebackend, synthetic rows (no routes or media). The tools call the production sink andPrefixReadBatcherdirectly; they are kept off this PR on branchamahishi/ckpt-v2-prefix-io-benchmarks, with the exact commands in its commit message.Cut-time writes
8,192 rows from 32 process-isolated TQ clients sharing one deployment. Batch size 1 is one PUT per call, as before this PR.
A row waits longer for its own PUT, but a cut returns its receipt only after every row is written, so wall time is what the cut deadline sees.
Restore reads
"per-request" is the old path: each restore reads its keys in its own
asyncio.to_threadGET. "coalesced" isPrefixReadBatcher(256 keys/GET, 2 ms coalescing window). Each mode ran twice, in alternating order; the table shows the slower run.TQTokenSource.fetchrather thanfetch_for_finalization. A restore'sstaging_chainreads throughChainPrefixCacheare not coalesced in either mode.Changes
nemo_rl/models/generation/prefix_recovery/{recovery,parts}.py,nemo_rl/data_plane/tq_token_sink.pynemo_rl/models/generation/prefix_read_batcher.py(new),nemo_rl/models/generation/prefix_recovery/recovery.py,nemo_rl/models/generation/vllm/{prompt_and_capture,vllm_worker_async}.pysingle_controller_utils/{config,setup}.py,rollout_checkpointing/manifest.py,generation/{interfaces,vllm/vllm_generation,vllm/multi_api,megatron/megatron_generation}.py, example SC configstest_prefix_read_batcher.py(new);test_vllm_token_capture_hosting.py,test_tq_token_sink.py,test_captured_media.py,test_megatron_token_capture_hosting.py,test_interfaces.py,test_vllm_generation.py,test_vllm_generation_restart.py,test_vllm_multi_api.py,test_dynamo_vllm_adapter_capture.py,test_vllm_chat_template_wiring.py,test_setup.py,test_rollout_checkpoint.py;grpo_async_gym_single_controller_prefix_recovery.shLines: +1867 / −445 (product and configs +779 / −330, tests +1087 / −115).
Testing
Unit tests on this branch (
4d254b812f, on main83151e70d2); functional runs on the same changes on maine8508839da, with Gym, Megatron-Bridge and Megatron-LM at main's pins:--nemo-gym-only): every Gym-marked test file this PR touches (hosting, batcher, sink, captured media, Megatron hosting, Dynamo adapter capture, rollout checkpoint, setup) plustest_nemo_gym_token_capture.py: 478 passed.include_sampler_topk.prefix_read_max_rows: 1four concurrent restores make four parallel reads without the batcher.test_vllm_token_capture_hosting.py,test_dynamo_vllm_adapter_capture.py,test_vllm_chat_template_wiring.py,test_captured_media.py,test_dynamo_vllm_adapter.py,test_dynamo_chat_engine.py,test_dynamo_generation_cut.py: 52 passed. This includes four concurrent restores through the realresolve_restored_callsharing one TQ read; the test fails ifresolve_restorebypasses the batcher.test_interfaces.py,test_vllm_multi_api.py,test_rollout_checkpoint.py, thetest_setup.pytoken-capture plumbing test,test_vllm_generation_restart.py,test_config_validation.pyand the Dynamo config, managed-runtime, generation-cut and decoupling tests: 561 passed.tests/functional/grpo_async_gym_single_controller_prefix_recovery.sh, native vLLM): passes locally: 8 rows match the uninterrupted run, no restored row's phase-1 prefix differed from the reference, 8 restored prefixes, 100% bit-identical generation logprobs over 9,312 tokens, andinvalid_row_rateandcapture_poisoned_rolloutsboth 0. The restores shared two TQ reads (4 and 28 keys, no failed keys), and the script now requires thegeneration_prefix_read_batch keys=line.tests/functional/grpo_router_replay_prefix_recovery_single_controller_1n2g.sh, native vLLM): passes locally. Every restored call completed and trained on its restored prefix (one shared read of 16 keys);invalid_row_rateandcapture_poisoned_rolloutsboth 0, andgen_kl_errorfinite.L1_Functional_Tests_Dynamo.shpasses, on4d254b812f):++policy.generation.dynamo=true: passes. The Dynamo frontend routed 40 requests; 8 rows match the uninterrupted run, no restored row's phase-1 prefix differed from the reference, 8 restored prefixes, 100% bit-identical generation logprobs over 9,312 tokens,invalid_row_rateandcapture_poisoned_rolloutsboth 0. Restores shared two TQ reads (1 and 7 keys).invalid_row_rateandcapture_poisoned_rolloutsboth 0, andgen_kl_errorfinite.Additional Information
timing/rollout_checkpoint/total_save_secondsbefore vs after, from a run with hundreds of active calls per DP leader. The microbenchmarks above isolate TQ I/O; that run will show the end-to-end save time the training loop loses.dtype mismatch: existing=torch.int64, incoming=torch.float32for partitionrollout_stagingright after the native TQ checkpoint restore. The batched writer rejects a batch whose rows differ in dtype, and all checks passed; I have not yet confirmed whether the same line appears on the base stack.🤖 Generated with Claude Code