Repository navigation
feat(checkpoint): recover router replay across prefixes - #4612
Conversation
ae76def to
34d6e39
Compare
34d6e39 to
2548c67
Compare
1 similar comment
terrykong
left a comment
There was a problem hiding this comment.
This PR keeps MoE router-replay routes across vLLM generation-prefix cuts, so prefix recovery and router replay can run together. That combination is needed, and removing the old guard is the right goal.
Size. The PR adds ~610 source and ~470 test lines. A realistic target is ~450 source and ~300 test lines:
- take one route snapshot at cut time instead of copying chunks on every decode step (vllm_worker_async.py#L391-L405): about −160 source, −50 test;
- delete dead or no-op code: the two shape checks (generation_cut_capture.py#L183-L199),
snapshot_new_routed_expert_chunks(#L449-L466), and thefetch_for_finalizationbranch (#L558-L561); - shrink the two big route tests with shared helpers (test_vllm_token_capture_hosting.py#L1376): about −125 test.
Main bug. A resumed call whose saved prefix is already finished gets no routes and fails (vllm_worker_async.py#L1459).
Before merge.
- One GPU run of an MoE recipe with router replay and prefix kill/restore, or keep the removed guard (setup.py#L1264-L1267, linked at the base).
- Re-pin Gym to a Gym main commit (3rdparty/Gym-workspace/Gym).
Thanks for the careful route integrity work: the routes are covered by the extras digest and checked for order and shape on resume. The row math was also checked by simulation on every normal path (multi-turn, repeated cuts, resume) and is correct.
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4612-what-routes-train.html
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4612-finished-prefix-crash.html
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4612-size.html
Generated by Claude Code
2548c67 to
1324ec0
Compare
|
/ok to test 1324ec0 |
1324ec0 to
0af80f2
Compare
|
/ok to test 0af80f2 |
|
/ok to test e530379 |
## What does this PR do? Lets `RolloutTokenCapture.build_generation_chunk_record` carry `extras` on a generation-cut chunk. Today it always stages `extras=None`. NeMo RL's MoE router replay needs this when a call is recovered from a generation prefix (NVIDIA-NeMo/RL#4612). Each cut chunk stages the routes of the tokens it adds. The chunk's extras digest has to cover them, so that a restore rebuilds the same prefix digest that Gym's `begin_call` checks. The change is the new optional keyword `extras`, which flows into `StagedCallRecord.from_components` and `compute_extras_digest`. Omitting it produces exactly today's record and digest. No linked issue: this is the one Gym change NVIDIA-NeMo/RL#4612 depends on. That RL PR currently pins a branch containing this commit, and will re-pin to the Gym main commit this lands in. ## Validation - `pytest tests/unit_tests/test_token_capture_staging_worker.py`: 66 passed. This includes the new `test_generation_chunk_record_commits_optional_extras`, which checks that the extras are stored and change both the extras digest and the record digest, while a chunk built without them is unchanged. - `ruff check` and `ruff format --check` on both changed files: clean. - End to end in NVIDIA-NeMo/RL#4612, with this commit applied on Gym: - a router-replay run on a small MoE model was hard-killed mid-generation and restored from its saved generation prefixes; - every restored call rebuilt the advertised prefix digest from its chunks (extras included) and trained on its restored routes. ## Rollouts N/A: no environment, agent or verifier behavior changes. Only the staging library's chunk builder gains an optional argument. ## Compatibility and benchmark impact None. The argument is keyword-only and optional, with a default of `None` that keeps the current record and digest. ## Checklist - [x] I have read the [contributing guidelines](https://github.com/NVIDIA-NeMo/Gym/blob/main/CONTRIBUTING.md). - [x] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [x] Tests added or updated and pass locally. - [x] Documentation N/A: internal staging API used by RL framework integrations; the new argument is documented by its signature and test. - [x] Pre-commit checks pass locally (ruff check / format on the changed files). - [x] New source files include the required Apache-2.0 SPDX header (no new files). - [x] All commits have DCO sign-off (`git commit -s`). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Anish Mahishi <[email protected]>
f47c6b4 to
350e216
Compare
350e216 to
f06773e
Compare
f06773e to
92977f3
Compare
terrykong
left a comment
There was a problem hiding this comment.
Thanks for the round-1 fixes. 13 of the 16 comments are fully fixed, including the main bug: a finished prefix now resumes with its routes (C1). f47c6b4 is a good change: one route read per cut, taken from the same output boundary as the tokens, and it removed 108 source lines. decode_routed_experts(dtype=None) also removed two copied dtype tables.
Size. The main ask from round 1 still stands. Net lines now, against the round-1 target:
| Round 1 | Now | Target | |
|---|---|---|---|
| Source | +573 | +534 | ~450 |
| Unit tests | +471 | +747 | ~300 |
| Functional tests | +408 / −134 |
The shared phase helpers in the functional tests are good reuse. Most of the growth comes from 352f46c (+55 source, +90 test) and from new unit tests. The inline asks bring source to about 370 and unit tests to about 630:
- (C17) Return only the chunk from
frozen_cut_routed_experts; the cumulative tensor is never read and copies the call's whole route history on every cut. - (C18) Drop the doubling route buffer from this PR and bring it back in #4508 with timing numbers.
- (C19) Do the restored-route splice inside
_delta_align_routed_expertsand delete_merge_generation_cut_routed_experts. - (C20) Replace the
prefix_routes_sha256check, which always matches, with aprefix_routes=kept|droppedfield. - (C21) Read only
routed_experts; vLLM 0.29 has noprompt_routed_experts. - (C22) Shorten the router-replay docs section and note the one token a finished prefix trains with the fallback route.
- (C23) Delete three checks that cannot fire, reuse
_final_route_placeholder, merge one test, and shorten long docstrings.
Feature gap: (C26) prefix still refuses score centering, and no stack PR lifts it. This PR already carries routes across a cut, so carry the sampler top-k the same way here.
Two more asks, not tied to a line:
- Please refresh the PR description. It still describes
snapshot_routed_expertswith an engine-loop timeout, a setup check of vLLM's fields that does not exist, a section on the Gym pin 25062eb18 (this PR no longer touches Gym), and route tests intest_vllm_generation.py(linked at d1bda11, the only commit that has them) that f47c6b4 deleted. - Please squash f47c6b4 into d1bda11. d1bda11 adds an engine-loop route read (7–21 s per cut in your runs, longer than the cut timeout) and about 220 lines that f47c6b4 then deletes. Squashing keeps that slow path out of history and out of
git bisect.
CI. No test job has run on this head yet (C24).
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4612-size-round-2.html
Generated by Claude Code
|
/ok to test 2459562 |
39206e2 to
09a1769
Compare
|
/ok to test 09a1769 |
Lift the setup refusal of generation-prefix recovery with router replay. A cut stages the routes of the tokens it freezes on its chunk row, one per chunk token, as a tensor attachment whose metadata rides the row's extras like a terminal row's routes; each chunk's own digest covers its routes, and the advertised prefix digest covers tokens and call extras only. The cut's progress read copies each router-replay call's vLLM route pieces in the same lock hold as its tokens, and the call's route cache joins only the pieces appended since its last cut, into a buffer that doubles when full, so a cut costs the rows decoded since the previous one. A finished call's final output supplies its routes instead. On restore every chunk's routes are verified against its digest and joined; the resumed call trains with those saved routes for its restored prefix and with its own routes for the token at the cut and the new tail. A call whose routes cannot be read or do not cover every token it saved is not cut and regenerates from its last saved turn. The route helpers live in prefix_recovery/routes.py; PrefixRecoveryParts gains router_replay, and the ProgressReader read takes the calls whose route pieces it copies. Adds a tiny-MoE router-replay prefix-recovery functional test to L1, and unit coverage of cuts, races, resumes and the progress read's route copy. The new test and the Omni one share their snapshot paths, common overrides, two-phase run and checks through _gym_prefix_recovery_phases.sh, and verify-completion --require-routes compares the restored and staged route hashes in the existing prefix boundary check. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
…very A prefix cut now stages its tokens' sampler top-k as attachments, sliced from vLLM's live logprobs container like the sampled logprobs. A restore fetches and joins every chunk's top-k, and the resumed call's final row writes the restored prefix's top-k ahead of its tail's, so each row keeps one top-k row per generated token. Drops the refusal of rollout_recovery.target_level=prefix with policy.generation.top_logprobs. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
- A later cut's route chunk is a slice of the engine's route buffer, not a rebuild of the call's route history; only a call's first chunk concatenates, for its placeholder (C17). With that, the route cache copies only the rows decoded since the last cut (C18). - The restored prefix's routes are spliced inside _delta_align_routed_experts; _merge_generation_cut_routed_experts is gone (C19). - The completion log reports prefix_routes=kept|dropped|none, which is what --require-routes checks, instead of two hashes of the same rows (C20). - A finished call's routes come only from routed_experts, which the pinned vLLM returns for the prompt and generated tokens together (C21). - Docs: the router-replay guide points to the Single-Controller rules, which now note the one fallback token of a finished restored prefix (C22). - Drop route-join checks that cannot fire, build every -1 route row with _final_route_placeholder, fold a duplicate test, and shorten docstrings (C23). - The prefix parity L1 line runs with score centering and sampler replay (C29). - The Omni pruning test's prefix-cuts case gives its worker a config, which setup now reads to decide whether cuts stage router-replay routes. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
…ture path After the rebase onto #4979, both native and Dynamo calls restore through prompt_and_capture.start_capture, which now carries the restored routes and sampler top-k on RestoredCall. Test that path and run router replay with prefix recovery behind Dynamo: - The restored-call wiring test asserts the routes and top-k reach the call's capture, and that a prefix that had already finished answers with its restored routes. - Router-replay and score-centering hosting tests restore through start_capture on a real worker and check the trained row: the routes keep the saved prefix's rows, the sampler top-k starts with them, and a prefix that had already finished stages its saved rows alone. - Fakes of resolve_restore return _ResolvedGenerationCut, and the fake chat handler worker sets _cut_routes_dtype. - run_prefix_recovery_phases sets PHASE1_RUN_LOG, so stop_phase1 cleans up phase one's Dynamo services for every caller. - L1_Functional_Tests_Dynamo.sh runs the router-replay prefix-recovery test behind Dynamo on the tiny DeepSeek model. - The router-replay prefix test serves string_match's environment server through legacy_agent: the Gym bump (#5195) made it typed, which prefix recovery refuses. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
09a1769 to
7292c6c
Compare
|
/ok to test 7292c6c |
CI sets FAST=1 when it reuses the main image (CI:Lfast), so a run_test line without `fast` is skipped there. This line is the one that broke main after #4612; marking it fast lets this PR's own CI run it. Signed-off-by: Terry Kong <[email protected]>
What does this PR do ?
Keeps MoE router-replay routes and score-centering sampler top-k across vLLM generation-prefix checkpoints. A recovered rollout trains its restored prefix with the expert routes it was sampled under, and with the sampler top-k it was sampled from.
This PR is based on
main, which now includes #4507 and the multimodal prefix recovery from #4583. #4508 (batched prefix TQ I/O) will be rebased onto this PR.Background
Prefix recovery already stores generated token IDs and sampling logprobs in TQ, then re-prefills those tokens after a restart. Two training inputs were still missing for the restored prefix:
policy.generation.top_logprobs > 0with theprefixtarget.Implementation
Router replay
One route read per cut. A cut freezes the call's token count and reads its route pieces in the same progress read as its tokens. That read copies vLLM's
RequestState.routed_experts_chunksunder the output-processor lock, on the cut's thread. The cut keeps only the rows its frozen tokens need. Decoding does no route work. A finished request uses its final output's routes.Staging. The first cut chunk carries the prefix's full delta-aligned routes; each later chunk carries one route per new token. They ride in the chunk's
extras, so its extras digest covers them, and the cut advertises the cumulative digest. The final placeholder row is-1(ROUTE_MISSING_SENTINEL), built by one helper on both the save and the restore path.Restore. The chunks' route fragments come back in the same
fetch_for_finalizationread as their tokens. Each is checked against its digest, the fragments are joined, andresolve_restorereturns them beside the verified prefix (_ResolvedGenerationCut) while vLLM re-prefills it. Media still comes back from the verified snapshot, as onmain.Finalization. The staged row keeps the restored routes for the restored prefix, and this call's routes for the parent's last token, the token at the cut and the new tail. A prefix that was already finished answers with its restored routes, since the engine never runs for it.
Fail per call, never the whole cut. A call is not cut, gets
durable_failure, and restarts from its last saved turn when:The rest of the checkpoint goes on, and the next checkpoint tries the call again.
Resumed calls whose routes don't fit the restored prefix are logged and staged without routes, matching
_delta_align_routed_experts.The completion log says whether a resumed call kept its restored prefix routes (
prefix_routes=kept|dropped|none).Score centering
extract_score_centering_slice), through the same extractors as a finished output, for both the list andFlatLogprobslayouts.sampler_topk_token_ids/sampler_topk_logprobsattachments, outside the prefix digest. A cut that cannot read a staged position's top-k fails only that call (sampler_topk_unavailable).Checkpoint flow
flowchart LR SC["Single Controller checkpoint"] --> GW["vLLM generation worker"] GW -->|"freeze token count"| ST["Capture state"] GW -->|"progress read under the output-processor lock"| VLLM["vLLM request state"] VLLM -->|"tokens, route pieces, logprobs container"| GW ST --> CUT["Chunk tokens + routes + sampler top-k for the frozen count"] GW --> CUT CUT --> REC["Gym generation-chunk record (routes in extras, top-k as attachments)"] REC --> TQ["TQ staging row"] TQ --> ACK["Durable prefix acknowledgement"] ACK --> SCRecovery and finalization flow
sequenceDiagram participant G as Gym participant W as Generation worker participant Q as TQ participant V as vLLM participant F as Finalizer G->>W: Resume with prefix staging keys W->>Q: Fetch chunks with route fragments and sampler top-k Q-->>W: Return ordered chunks W->>W: Verify digests, join the routes and top-k W->>V: Re-prefill the durable token prefix V-->>W: Return the tail's tokens, routes and top-k W->>W: Keep the restored prefix's routes and top-k ahead of the tail's W->>F: Publish the completed rolloutConstraints and assumptions
mainsince the vLLM 0.33 bump, router replay needspolicy.generation.vllm_cfg.enable_prefix_caching=true.main's progress reader already checks the vLLM release (0.33) and the fields it reads at setup; this PR adds no second check.async_rl.recompute_kv_cache_after_weight_updatesis false, the default.-1for the parent's last token, because no prefill routes it; Megatron routes that one token itself.Issues
None.
Usage
No new setting. Configure generation-prefix recovery with router replay or score centering through their existing options; the setup guards that rejected those combinations are removed. See "Prefix-Level Rollout Recovery" in
docs/guides/router-replay.mdand theprefixtarget indocs/guides/single-controller.md.Before your PR is "Ready for review"
Pre checks:
single-controller.mdandrouter-replay.md.Validation
Run on H100 against this head (
mainat705953be8plus these two commits), withmain's pinned Gym and vLLM 0.33:tests/functional/grpo_async_gym_single_controller_prefix_recovery.shwithpolicy.generation.top_logprobs=4,loss_fn.score_centering=true, sampler replay on andtop_k=4(the test samples withtop_p=1e-6).top_p=1e-6only one token survives sampling, so this checks that top-k is carried through recovery, not the estimator's values.tests/functional/grpo_router_replay_prefix_recovery_single_controller_1n2g.sh(fast tier ofL1_Functional_Tests_SingleController_3.sh). A seeded, random-weight Qwen3-MoE is hard-killed mid-generation and restored.prefix_routes=kept, required byverify-completion --require-routes). No router-replay fallback occurred.prefix_routes=kept.gen_kl_errorfinite.main's vLLM 0.33 bump.test_vllm_token_capture_hosting.py,test_captured_media.py,test_tq_token_sink.py,test_gym_prefix_recovery_parity.py(--nemo-gym-only): 369 passed.single_controller/test_setup.py,test_score_centering.py,test_routed_experts_codec.py,test_gym_prefix_recovery_parity.py: 393 passed.test_vllm_generation.py: 8 passed.test_score_centering.pyslice tests against vLLM 0.33's own logprobs containers (--vllm-only): 2 passed.Additional Information
mainin a reviewed form that restores media from the verified snapshot. This PR's restore path follows that design and only adds routes and sampler top-k beside it.extrason generation chunks) is inmain's Gym pin, so this PR doesn't move the pin.🤖 Generated with Claude Code