Repository navigation
feat(checkpoint): recover active vLLM generation prefixes - #4506
Conversation
a5073d8 to
f0eafb4
Compare
f0eafb4 to
96a25ea
Compare
96a25ea to
0c54ff7
Compare
0c54ff7 to
834241a
Compare
1 similar comment
terrykong
left a comment
There was a problem hiding this comment.
Thanks for reshaping #4319 into this PR. Several things got clearly better since the earlier rounds:
- The config is now
rollout_recovery.target_level: prefix, which matches the target-level ask on #4266. - Gym's wire models are imported instead of copied.
- The enum properties
requires_gym_checkpoint/preserves_generation_prefixreplace the scatteredis TURNchecks. - The CPU tests are thorough: all ~2,300 CPU-runnable tests this PR touches pass locally.
Correctness. Two inline comments are about restored output that does not match what the same call returns without a restart: stop strings and presence/frequency penalties across a cut (on to_sampling_params), and a stop string added back to a call that was cut after it finished (on _restore_response_prefix). Please fix the first one in this PR, since it breaks the PR's "a missing cut costs time, never correctness" promise.
Size. This PR adds 3,752 lines: 2,007 source, 1,150 unit tests, 581 functional tests, 14 docs. The whole feature stack is about 21k lines: #4500 8,171, #4501 1,362, #4506 3,752, #4507 2,098, #4583 1,131, #4612 913, #4508 2,786, and about 893 of #4655's own (GitHub shows +17,969 for #4655 only because its base is stale). The rework from #4319 cut tests, not source: the cut module went from 904 to 821 lines and the worker changes from 786 to 761. Together, the size comments on this PR remove about 300 source lines (about 15%) plus about 55 test lines: the two output accumulators, the capture buffers, the controller fence setup, the fallback ack, the repeated snapshot checks, the dead compatibility code, the duplicate logprob loop, and the copied functional-test helpers. Please apply them before the next PRs in the stack build on this code.
Design question. The snapshot fence (~250 source lines) and #4655's 253-line cleanup module both exist so the terminal path can delete chunk rows while a checkpoint runs. Was moving that delete to a point outside the checkpoint considered? If so, please say in the PR body why it does not work.
Follow-up, not for this PR. GenerationCutCaptureMixin holds its own closed state, two executors and the gate, and borrows 11 worker attributes (3 declared). A GenerationCutCapture object built in setup_token_capture, like Gym's RolloutTokenCapture, could be tested on its own. It gets smaller if the buffer simplification and the design question above land.
PR description.
- The follow-up "A
turnoverride under globalprefixis accepted but has no effect" is not true: the validator raises (config.py L757-L764). Please drop that line. - Please state that no CI has run on #4506 itself (only bot checks so far).
Stack-wide merge blocker. The Gym pin 120d516f is not on Gym main (81 commits ahead, 140 behind, and Gym main has no nemo_gym/_checkpoint/). #4500 sets it, so it blocks the whole stack, not only this PR.
Linter: ruff and ruff-format pass; pyrefly could not run locally.
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4506-prefix-vs-turn.html
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4506-size-and-reuse.html
Generated by Claude Code
834241a to
6da5c10
Compare
Remove checks that Gym's models, setup or a sole caller already make: the doubled continuation and staging-source guards on restore (now one _resolve_generation_cut), the None output limit, the observe() gap branch (start is always read from the recorded count), the duplicate vLLM-backend check in setup, the worker's repeat of the setup-time media and top-k rejections, the inner token-capture check, the classifier's repeats of Gym's validators, and the hasattr scan the pinned vLLM version check covers. Share the inventory-identity check and the partial-cut rollback, skip recording finished outputs when prefix cuts are off, and fix two comments that still described per-step observation. Tests drop setup the cut never reads, a strict subset of the fence abort test, the RequestOutputKind fakes nothing imports, and rebuild the restore test from the existing helpers. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
…e's link The batch-age trace (#5049) already maps each vLLM request ID to its captured model call, through a context variable set when capture begins the call and the HTTP client's _captured_requests. Generation cuts kept a second link for the same thing: a context variable set when sampling params are built, an on_generate callback writing engine_request_id onto the capture state, and a _serving_request_ids set. Read progress by model call ID through the trace's map instead, and keep finished-request state for the requests it lists. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
With flat_logprobs, indexing a FlatLogprobs position builds a dict of Logprob objects only for the cut to pick one value out of it, for every token a cut reads and for every token of each captured call's final output, which runs on the worker's HTTP event loop. Read the sampled token's value straight from the position's candidate range instead, keeping vLLM's mapping behavior (the last repeated token wins) and the logprob floor. On vLLM 0.29 FlatLogprobs with 16k generated tokens this takes 0.9 ms instead of 6.6 ms with one stored logprob per position, and 2.7 ms instead of 23.9 ms with five. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
- C26: forest training keeps a restored cut on the rebuilt admission and serves it, so a restored prefix is spliced instead of regenerated. - C27: allow_restart_only_gym_servers applies to target_level prefix too; the restart-only refusal names both levels. - C29: completed-call evidence is kept only while generation cuts are on. - C30: replace the snapshot fence with a retired-row list. A call's terminal write only retires its chunk rows; each snapshot first deletes the rows retired before it (flush_obsolete_generation_cut_rows, epoch guarded) and waits for the delete, so no clear overlaps the TQ save. - C31: drop the per-reason uncut counters; each cut that leaves calls uncut logs one INFO line with the reasons. - C32: document what prefix cannot cut or does not support. - C33: build test workers through _init_token_capture_state instead of a hand-copied SimpleNamespace; the mixin calls become plain self calls. - C34: decide the seed blocker with vLLM's SamplingType.RANDOM_SEED, and drop the presence/frequency-penalty blockers the chat route refuses. - C35: the progress-read patch refuses a vLLM without its hooks and marks the wrapped OutputProcessor so a second client cannot wrap it again. - C36: unit-test the restored-terminal classifier and the serving path's prompt, max_tokens and min_tokens for a restored call. - C37: sort the hosting test imports. - C38: drop the unreachable prefix-without-turn check. - C44: test the Megatron prefix refusal through setup and directly. - C46: type the generation and data-plane handles. - C47: read the sampled logprob from each flat position's first slot and share extract_generation_logprobs with chat_generation_tokens. - C50: pin, in a vLLM-lane test, that truncate_prompt_tokens applies only while the chat is tokenized, before the restore splice. - C54: a vLLM-lane test pins the release and every private vLLM field the progress read and cut checks rely on. Also fix test_rollout_recovery's mark_group_dispatched call for #5011's environment_instance_id rename. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
… hard to misuse Address three design items from the third review of generation-prefix recovery: - C52: bind vLLM's chat_completion_full_generator arguments by name. Setup checks that its signature still has parser and request_metadata, a restored call wraps the bound parser, and the wrapper forwards any other parser attribute to vLLM's parser. A vLLM-lane test pins the real signature. - C55: carry a finished-at-cut restored call to the engine client in a context variable, as the model-call link already is, instead of a private key in vLLM's prompt dict that vLLM may rebuild. max_tokens=1 stays as the backstop. The wiring test now runs such a call through preprocess_chat and then _generate on one task. - C51: _RequestCaptureState takes its own short lock in record, record_error, mark_uncuttable, set_effective_output_limit and snapshot. Freezing, sealing and rolling back a cut and starting the terminal write exist only on the _CallLifecycle that lifecycle() (or try_lifecycle() for the non-blocking abort) yields while it holds the lifecycle lock; it stops working when the block ends, and a cut the block did not seal is rolled back. Fields are private and the class uses __slots__, and a test fails if anything outside the two classes touches their locks or fields. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
…orker owns Address C49 (with C35's move, C40 and C53) from the third review of generation-prefix recovery. The vLLM worker no longer inherits a mixin and its prefix-only fields; setup_token_capture builds one PrefixRecovery, or a NoPrefixRecovery when target_level is not prefix, and the worker calls it at fixed points: when a call begins and gets its sampling settings, when its final output arrives and its terminal row is written, at each cut and snapshot flush. The "are cuts on?" checks are gone. New layout: - prefix_recovery/recovery.py: PrefixRecovery and NoPrefixRecovery (the cut loop, completed-call evidence, retired-row flush, restore resolution and counts). - prefix_recovery/state.py: the per-call record and its lifecycle, and a CaptureRegistry the worker and recovery share. - prefix_recovery/restore.py (C40): plan_restore, restore_reply_text, restore_reply_usage, wrap_parser_for_restore and the finished-call marker as plain functions, so the Dynamo frontend (#4979) can call them. - prefix_recovery/progress.py and parts.py: the ProgressReader interface, the one backend-specific seam, and the inputs the worker hands in. - vllm/progress_reader.py (C35): VllmProgressReader wraps vLLM's OutputProcessor; the HTTP client exposes captured_request_ids, is_captured, add_request_done_listener and output_processor instead of having its private state read. - vllm/generation_cut_route.py: the Gym cut route. C53: tests/unit/models/generation/prefix_restore_cases.py holds restore cases (a tool call or reasoning split by the cut, a stop string or token in the saved part, min_tokens still owed, an output limit reached); a vLLM-lane test checks the native path's reply text, parser input and usage against the uninterrupted call. vllm_worker_async.py drops from 3,743 to 3,026 lines; generation_cut_capture.py is removed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
Address C28 from the third review of generation-prefix recovery. The end-to-end prefix-recovery test lands once, in #4507, in its final form, instead of here in a form #4507 rewrites. Restore the turn-recovery hook and the L1 runner to main's. Signed-off-by: Anish Mahishi <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hard Address C48 from the third review of generation-prefix recovery. The rebase onto main added the three generation-cut arguments to _TokenCaptureSetup, so restart_shard replays them, but the restart tests still built it from the four original fields and failed. Give them all seven, and add a case that sets up capture with prefix cuts on and checks the replacement leader's setup_token_capture gets the same three arguments. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
… stop string Address C56 and C57 from the fourth review of generation-prefix recovery: - C56: decide_capture_input serves a forest-training first call (a text root Gym replays from its source history) with its restored cut. - C57: a shared restore case keeps a stop string in the output (include_stop_str_in_output=True) when the cut saved it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
a706836 to
a3a8811
Compare
The end-to-end test of generation-prefix recovery, moved here from #4506 (C28): Gym's policy proxy holds a long Workplace call mid-decode, a rollout snapshot cuts it, and after a hard kill the restored call must resume from its saved prefix and train on the same rows as an uninterrupted run. Signed-off-by: Anish Mahishi <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
…snapshot #4506's third review defers a finished call's chunk-row delete to the next snapshot, so restored prefix rows are still live when phase two first trains. Phase two now trains one step past the reference, so the snapshot after the compared step runs while the run is alive, and the hook records the live staging keys right after each flush. The parity check requires the restored rows to be live at the first training step and gone after the first flush, and compares only the reference's steps. grpo.max_num_steps is excluded from the rollout fingerprint in both phases, since only phase two's stopping point changes. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
|
/ok to test a3a8811 |
…recovery inputs Two tests main added before this PR fail against it: - test_nemo_gym.py builds a Gym actor config without generation_prefix_cuts_enabled, which this PR made required; pass False as the tests already pass turn_checkpointing_enabled=False. - test_capture_bypasses_upstream_route_encoding_without_changing_plain_requests sends vLLM's plain ChatCompletionRequest through the chat override, which reads NeMoRLChatCompletionRequest's restored-prefix fields and the renderer's tokenizer. Give its requests that class's defaults and its server a renderer, as the sibling capture test does. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
|
/ok to test ce99798 |
|
/ok to test ce99798 |
test_rollout_checkpoint_mapping_matches_logged_keys finds the keys an environment snapshot logs by reading a dict literal returned from its metrics(). Building the dict and adding the generation-cut counts in a loop hid gym_parked_seconds and gym_restarted_episodes from it, so the test reported their rl.checkpoint.* mappings as stale. Return a literal again, with the generation-cut counts spread into it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
|
/ok to test 7d75696 |
What does this PR do ?
Adds
rollout_recovery.target_level: prefix: at each coordinated Gym checkpoint, every active vLLM model call stages the tokens it has decoded so far, and after a restart the restored call resumes from that prefix and generates only its remaining tail.Based on
main. The rollout-checkpointing stack this was built on (#5011, #5048, #5049, #5056) has merged, and this PR is rebased onto it. The end-to-end parity test is in #4507, stacked on this one.Issues
How it works
Save side. A Gym checkpoint already parks rollouts and commits participant state (turn level). With
prefix, the controller first deletes the chunk rows of calls that ended since the last snapshot, then Gym asks each worker to cut its admitted calls:sequenceDiagram autonumber participant SC as SingleController participant W as vLLM worker participant G as Gym participant TQ as TransferQueue SC->>W: flush_obsolete_generation_cut_rows(epoch) W->>TQ: delete chunk rows retired before this snapshot (waits for the clear) SC->>G: prepare + commit checkpoint G->>W: POST /ng-control/v1/generation-cut (frozen inventory) W->>W: read every inventory call's new tokens from vLLM, under its output lock W->>TQ: stage each call's new tokens as a chunk row W-->>G: receipt (durable_prefix | durable_failure per call) SC->>TQ: save data-plane snapshotTerminal writes are never held: a call that finishes during a checkpoint writes its final row at once and only retires its chunk keys. The next snapshot deletes them (see "Why deletes wait for the next snapshot").
Where the code lives. The vLLM worker builds one
PrefixRecoveryinsetup_token_capturewhentarget_levelisprefix, or aNoPrefixRecoverywhose hooks do nothing, and calls it at fixed points: when a call begins and gets its sampling settings, when its final output arrives and its terminal row is written, at each cut and snapshot flush. Only theProgressReaderit is given knows the engine.prefix_recovery/recovery.pyPrefixRecovery/NoPrefixRecovery: the cut loop, completed-call evidence, the retired-row flush, restore resolution, countsprefix_recovery/state.pyrecord/snapshotlock themselves;freeze/seal/rollback/begin_terminalexist only whilelifecycle()holds the call), and theCaptureRegistrythe worker and recovery shareprefix_recovery/restore.pyplan_restore,restore_reply_text,restore_reply_usage,wrap_parser_for_restore, the finished-call marker; reusable by the Dynamo frontend (#4979)prefix_recovery/progress.py,parts.pyProgressReaderinterface; the inputs the worker hands invllm/progress_reader.pyVllmProgressReader, the one vLLM-specific seamvllm/generation_cut_route.pyReading decode progress. Captured calls keep vLLM's own output kind (
FINAL_ONLYfor non-streaming chat); nothing is copied per decode step.VllmProgressReaderwraps vLLM'sOutputProcessor.process_outputsso each output chunk runs under one lock. A cut finds each inventory call's vLLM request through the map #5049 keeps from engine request ID to captured model call, takes that lock once per inventory, copies every call's tokens past what it has already recorded, and reads their logprobs outside the lock. Reading this way instead of queuing a read onto vLLM's engine loop matters at scale: the same pattern for router-replay route reads measured 52 ms median, 588 ms p95 and 40.68 s worst through the engine loop, against 1.36 ms / 4.24 ms / 15.3 ms read directly (10-node A/B runs)._finish_requestis also wrapped to keep a finished request's state until its consumer has the final output, so a call vLLM just finished is still cut whole. Withvllm_cfg.flat_logprobs, the sampled token's logprob is read from the first slot of eachFlatLogprobsposition, where vLLM's sampler writes it.Restore side. The restored call's admission carries its chunk keys. The worker fetches and verifies the saved rows (digest and token count; anything unusable regenerates), splices them into the prompt, shrinks
max_tokens/min_tokensby the prefix length, and prepends the decoded prefix to vLLM's tail text before the response is parsed, so Gym, parsers, and verifiers see one uninterrupted completion. A call that had already finished at the cut is answered from its saved tokens without decoding.Safety properties
token_capture.control_timeout_s. If vLLM holds its output lock past it, each call is cut at the tokens it had already recorded; calls the cut does not reach in time are acknowledged as failures and regenerate.bad_words, and a per-request seed while sampling (vLLM'sSamplingType.RANDOM_SEED). Gym also never cuts structured-output or constrained-tool_choicecalls.Changes
target_level: prefixrequires the turn-level prerequisites and the vLLM async engine;allow_restart_only_gym_serversapplies to it too. Megatron inference, multimodal capture, router replay and sampler top-k capture (policy.generation.top_logprobs > 0) are refused at setup, each with a test.prefix_recovery/preserves_generation_prefixrecovery level.decide_capture_input's rebuilt admissions.prefix_restore_cases.py, vLLM lane). The functional test is in #4507.Commits, in order: the feature, Gym's generation-cut wire names (Ananth), two review rounds, reading progress from vLLM at cut time, single-token bad words, failure-reason counters (later replaced by a log line), direct reads under vLLM's output lock, a cleanup, finding a cut call's vLLM request through #5049's link, reading sampled logprobs from vLLM's flat arrays, then the third review: one commit of fixes, one making restore wiring and per-call locking hard to misuse, one making prefix recovery an object the worker owns, one moving the functional test to #4507, one testing that a restarted vLLM shard keeps its prefix cuts, and one covering a forest-training first call's restored cut and a stop string kept in the output (C56, C57).
Lines vs
main: source +3366 / −207, unit tests +3982 / −139, docs/config +45 / −20.Usage
Testing
Local, in the CI container image, with no packages installed, on this head:
--nemo-gym-only: token-capture hosting, captured media, capture-route tensors, capture context: 263 passed, 1 skipped.test_vllm_generation.pycapture, abort and cut-route cases: 16 passed.--vllm-only: the progress-read layout pins, the restored-prefix replay and the shared restore cases: 45 passed;test_vllm_generation_restart.py: 6 passed.grpo_async_gym_single_controller_prefix_recovery.shpasses (Qwen3-1.7B, 1 node, 470 s): 8 calls cut and restored (139–156 tokens), every row matches the uninterrupted run, the restored calls' 16 chunk rows are live at the first training step and gone after the next snapshot's flush.grpo_async_gym_single_controller_turn_recovery.shpasses (260 s).main: the checkpointing and Gym-checkpoint unit tests (218), hosting and capture context (132), the vLLM lane (30) and test(checkpoint): add Workplace prefix-recovery parity #4507's parity tests (33) pass, and so does test(checkpoint): add Workplace prefix-recovery parity #4507's prefix-recovery functional test (477 s, all 8 rows match).token_capture.forest_training): context compaction passes. The prefix test passes end to end once fix(checkpoint): keep the calls a restored turn carried over under forest training #5147 is applied; onmainalone, a turn or prefix restore under forest training is regenerated instead of continued (fix(checkpoint): keep the calls a restored turn carried over under forest training #5147 has the cause).CI status
No GPU CI has run on #4506 itself yet.
Metrics
Per rollout checkpoint (
timing/rollout_checkpoint/*): Gym's cut outcome asgeneration_cut_calls,generation_cut_failed_calls,generation_cut_skipped_calls.Per training step (
generation_prefix/*, totals since the vLLM workers started):restored_callsandrestored_prefix_tokens;progress_reads,progress_read_calls,progress_read_wait_usandprogress_read_hold_us(time spent waiting for and holding vLLM's output lock).Each cut that leaves calls uncut logs one INFO line with the reasons, for example
generation cut <id> left 1 of 1 model calls uncut: {'zero_generated_tokens': 1}.Why deletes wait for the next snapshot
A Gym checkpoint can name a call's chunk rows, so they must survive until that checkpoint's TQ snapshot is saved. Only deleting them is unsafe; a terminal row written during the checkpoint is harmless (turn level already accepts it, and restore clears unreferenced rows). So a call's terminal write, abort or unusable restore only retires its chunk keys, and the next snapshot deletes every key retired before it started: those calls ended before Gym froze that snapshot's inventory, which names a finished call by its terminal row only, and a saved snapshot keeps its own copy of TQ. A worker restart drops its retired keys; the next restore clears those rows.
Known follow-ups
dtype mismatch: existing=torch.int64, incoming=torch.float32once forrollout_staging. It appears in every functional run on refactor(checkpoint): move rollout checkpointing out of the single controller #5011 and later and does not fail the run; not yet investigated.generation_prefix/progress_read_*).gym_prefix_timeout_sinstead of an hour.async_rl.generation_fleet_health, the flush fans out to every worker, so a dead shard fails the snapshot (and the run aftermax_consecutive_failures).restore.py; cuts need the frontend to reach the engine that holds each call.🤖 Generated with Claude Code