Skip to content

perf(checkpoint): batch generation prefix TQ I/O - #4508

Merged
terrykong merged 3 commits into
mainfrom
amahishi/ckpt-v2-prefix-batched-io
Nov 20, 2026
Merged

terrykong merged 3 commits into
mainfrom
amahishi/ckpt-v2-prefix-batched-io

Conversation

@macandro96

@macandro96 macandro96 commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

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 inside PrefixRecovery.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]
    end
Loading
  • Writes (prefix_recovery/recovery.py, tq_token_sink.py): PrefixRecovery._cut_transaction turns 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_cut batches the records (_cut_batched). Every cut takes this path; prefix_write_max_rows: 1 writes each call in its own PUT. stage_generation_prefix_batch writes the batch in one put_many and 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_batched writes 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_failure and counted under the base's failure reasons (cut_error, or control_deadline past 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): PrefixReadBatcher is an event-loop-local coalescer for restore-time GETs, owned by PrefixRecovery. Concurrent requests share GETs of at most prefix_read_max_rows distinct 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. With prefix_read_max_rows: 1 there is no batcher: each restore reads in its own thread, as before this PR. resolve_restore is 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_call awaits 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 the RolloutRecoveryConfig fields; setup_single_controller passes them through GenerationInterface.setup_token_capture to the vLLM workers, which hand them to PrefixRecovery in PrefixRecoveryParts and forward them to child HTTP frontends (multi_api.py). restart_shard replays them into a replacement worker. Megatron generation accepts and ignores them.

    rollout_recovery:
      prefix_write_max_rows: 256        # rows per TQ write at a checkpoint cut
      prefix_write_max_tokens: 4194304  # tokens per cut write; a larger row is written alone
      prefix_read_max_rows: 256         # rows per TQ read at restore; 1 = each restore reads alone

    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 simple backend, synthetic rows (no routes or media). The tools call the production sink and PrefixReadBatcher directly; they are kept off this PR on branch amahishi/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.

prefix tokens rows/PUT PUT calls wall (s) rows/s mean row wait (ms)
1,024 1 8,192 10.08 813 36.8
1,024 256 32 0.44 18,471 188.4
16,384 1 8,192 10.20 803 26.1
16,384 256 32 3.75 2,184 561.1

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_thread GET. "coalesced" is PrefixReadBatcher (256 keys/GET, 2 ms coalescing window). Each mode ran twice, in alternating order; the table shows the slower run.

scenario mode GETs keys/GET wall (s) request p50 (ms) request p99 (ms)
mass resume: 128 workers × 64 restores, 16k tokens per-request 8,192 1.0 12.57 6,877 9,731
coalesced 128 64.0 1.80 1,334 1,742
mass resume, 2k tokens per-request 8,192 1.0 12.02 6,719 9,240
coalesced 128 64.0 0.86 535 823
mass resume, 4 cut chunks per restore per-request 8,192 4.0 30.02 17,253 27,205
coalesced 155 211.4 2.33 1,465 2,203
128 workers, a restore every 5 ms per worker per-request 8,192 1.0 12.38 6,625 9,235
coalesced 300 27.3 2.19 1,735 2,093
128 workers, a restore every 20 ms per worker per-request 8,192 1.0 11.89 6,465 8,016
coalesced 488 16.8 2.41 1,181 1,663
light: 8 workers, a restore every 10 ms per-request 512 1.0 2.54 363 596
coalesced 96 5.3 0.74 98 161
light: 8 workers, a restore every 50 ms per-request 512 1.0 4.52 17.3 24.2
coalesced 512 1.0 3.19 27.4 34.2
  • Mass resume is the production pattern: after a restart, every cut call on a worker resumes at once. Coalescing cuts the GET count by 64–98× and wall time by 6–13×.
  • Light load is the worst case. At one restore per 50 ms per worker there is nothing to coalesce. GET time is the same in both modes (25.0 vs 24.9 ms in the second repeat), so a restore pays the 2 ms coalescing window plus noise. By one restore per 10 ms per worker, coalescing is already 3.7× faster.
  • Head-of-line blocking: the batcher issues one GET at a time per worker. A GET that hangs now stalls every restore on that worker, where before it stalled only its own request. None of the runs above triggered this.
  • Caveats: all clients ran on one node, so the per-request numbers include client-side contention that spreading workers over nodes would reduce; the TQ storage units are shared either way. The read tool reads through TQTokenSource.fetch rather than fetch_for_finalization. A restore's staging_chain reads through ChainPrefixCache are not coalesced in either mode.

Changes

Area Files
Batched cut writes + deadline nemo_rl/models/generation/prefix_recovery/{recovery,parts}.py, nemo_rl/data_plane/tq_token_sink.py
Coalesced restore reads nemo_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}.py
Config plumbing single_controller_utils/{config,setup}.py, rollout_checkpointing/manifest.py, generation/{interfaces,vllm/vllm_generation,vllm/multi_api,megatron/megatron_generation}.py, example SC configs
Tests test_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.sh

Lines: +1867 / −445 (product and configs +779 / −330, tests +1087 / −115).

Testing

Unit tests on this branch (4d254b812f, on main 83151e70d2); functional runs on the same changes on main e8508839da, with Gym, Megatron-Bridge and Megatron-LM at main's pins:

  • Unit, Gym lane (--nemo-gym-only): every Gym-marked test file this PR touches (hosting, batcher, sink, captured media, Megatron hosting, Dynamo adapter capture, rollout checkpoint, setup) plus test_nemo_gym_token_capture.py: 478 passed.
    • Batched-path coverage includes 1000-prefix batching with a cached receipt, ragged and oversized rows under the token limit, a call whose rows always fail leaving the other calls' cuts intact (through the per-row retry), a failed acknowledgement failing only its call, an interruption keeping earlier cuts sealed and clearing rows no call received, a later batch's failure keeping earlier cuts, and the cut deadline passing both between batches and while rows are pending. A batch whose rows differ in column names, dtypes or trailing dims is rejected before any write.
    • Score centering: two calls cut in one batch are restored through one shared read, each with its own sampler top-k; the test fails if the read drops include_sampler_topk.
    • Read-side coverage: a bad row fails only its own caller, a failed batch re-reads each key alone exactly once, closing the reader does not hang on a stopped serving loop, and with prefix_read_max_rows: 1 four concurrent restores make four parallel reads without the batcher.
  • Unit, vLLM + Gym lane: 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 real resolve_restored_call sharing one TQ read; the test fails if resolve_restore bypasses the batcher.
  • Unit, default lane: test_interfaces.py, test_vllm_multi_api.py, test_rollout_checkpoint.py, the test_setup.py token-capture plumbing test, test_vllm_generation_restart.py, test_config_validation.py and the Dynamo config, managed-runtime, generation-cut and decoupling tests: 561 passed.
  • Functional, Workplace parity (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, and invalid_row_rate and capture_poisoned_rollouts both 0. The restores shared two TQ reads (4 and 28 keys, no failed keys), and the script now requires the generation_prefix_read_batch keys= line.
  • Functional, router replay (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_rate and capture_poisoned_rollouts both 0, and gen_kl_error finite.
  • Functional, behind Dynamo (both scripts with the flags L1_Functional_Tests_Dynamo.sh passes, on 4d254b812f):
    • Workplace parity with ++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_rate and capture_poisoned_rollouts both 0. Restores shared two TQ reads (1 and 7 keys).
    • Router replay with the tiny DeepSeek model: passes. All 4 restored calls completed and trained (one shared read of 12 keys); invalid_row_rate and capture_poisoned_rollouts both 0, and gen_kl_error finite.

Additional Information

  • Pending: timing/rollout_checkpoint/total_save_seconds before 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.
  • In each functional run the TQ controller logged one non-fatal dtype mismatch: existing=torch.int64, incoming=torch.float32 for partition rollout_staging right 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

@copy-pr-bot

copy-pr-bot Bot commented Oct 5, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@macandro96
macandro96 added this pull request to stack #4509 October 5, 2026 17:00
@macandro96
macandro96 requested a review from terrykong October 5, 2026 17:00
@macandro96
macandro96 force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from e4dc44d to 079933e Compare October 6, 2026 02:47
@github-actions

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 079933e (PR #4508 from amahishi/ckpt-v2-prefix-batched-io)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@macandro96
macandro96 force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from 079933e to 7eb9a01 Compare October 7, 2026 04:02
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 7eb9a01 (PR #4508 from amahishi/ckpt-v2-prefix-batched-io)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: a82e2a2 (PR #4508 from amahishi/ckpt-v2-prefix-batched-io)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@macandro96
macandro96 removed this pull request from stack #4509 October 12, 2026 23:15
@macandro96
macandro96 changed the base branch from amahishi/ckpt-v2-prefix-recovery to amahishi/r3-prefix-recovery October 12, 2026 23:16
@macandro96
macandro96 added this pull request to stack #4685 October 12, 2026 23:16
@macandro96
macandro96 removed this pull request from stack #4685 October 12, 2026 23:30
@macandro96
macandro96 added this pull request to stack #4686 October 12, 2026 23:32
@macandro96
macandro96 force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from a82e2a2 to 5498a0a Compare October 15, 2026 02:17

@terrykong terrykong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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_seconds before 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.py is 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):

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

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

Comment thread nemo_rl/models/generation/interfaces.py Resolved
Comment thread tools/benchmark_tq_prefix_writes.py Resolved
Comment thread nemo_rl/data_plane/tq_token_sink.py Resolved
@macandro96 macandro96 added the CI:L1 Run doctests, unit tests, and functional tests label Oct 19, 2026
@terrykong terrykong added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Nov 5, 2026
@macandro96
macandro96 force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from 6c72a0f to 788133a Compare November 11, 2026 04:51
@macandro96
macandro96 removed this pull request from stack #5057 November 12, 2026 15:29
@macandro96
macandro96 added this pull request to stack #5181 November 12, 2026 15:29
@terrykong
terrykong force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from 788133a to 507a670 Compare November 12, 2026 21:16

@terrykong terrykong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

  1. (C8) One step to build the ack and seal, and one loop in flush().
  2. (C9) Leftovers in tq_token_sink.py from removing stage_generation_prefix.
  3. (C10) Drop two guards that can never fire, and max_pending.
  4. (C11) Test helpers and two repeated tests — do this after C10.
  5. (C12) Small: aclose() hangs on a stopped loop.
  6. (C13) After the rebase onto #4979, restores stop using the batcher on both native and Dynamo; move the batched read into resolve_restore.
  7. (C14) Tests that fail if restores stop sharing reads: one unit test through resolve_restored_call, one grep in the functional script.
  8. (C15) One put per batch instead of grouping rows by their column set, plus a column check.
  9. (C16) Delete a test that repeats an existing per-row retry test.
  10. (C17) Rename the two batch settings to prefix_write_max_rows / prefix_write_max_tokens and add prefix_read_max_rows; a read limit of 1 should read the old way, in parallel.
  11. (C18) #4612's head now saves sampler top-k in cut rows; carry it through _cut_transaction and _fetch_rows when 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_shard replay 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 deadline kwarg on run_cut.
  • Append the new _TokenCaptureSetup fields (three after C17), in order, to #4979's _TokenCaptureSetup(...) call.
  • In shutdown(), await prefix_recovery.aclose() before setting http_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_call as 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_seconds run 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 test was on def6e59 (2026-10-19). Please trigger it on the current head.
  • timing/rollout_checkpoint/total_save_seconds before 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

Comment thread nemo_rl/data_plane/tq_token_sink.py Resolved
Comment thread nemo_rl/data_plane/tq_token_sink.py Resolved
@macandro96
macandro96 force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from 507a670 to 46c9ea6 Compare November 16, 2026 23:44
Base automatically changed from amahishi/r3-prefix-recovery to main November 19, 2026 01:13
@macandro96
macandro96 force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from 46c9ea6 to a3b78ae Compare November 19, 2026 06:08
terrykong
terrykong previously approved these changes Nov 19, 2026
@terrykong
terrykong enabled stacked auto-merge (squash) November 19, 2026 07:02
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test a3b78ae

macandro96 and others added 3 commits November 20, 2026 07:46
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]>
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test 4d254b8

@terrykong
terrykong merged commit 1a78def into main Nov 20, 2026
170 of 172 checks passed
@terrykong
terrykong deleted the amahishi/ckpt-v2-prefix-batched-io branch November 20, 2026 19:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants