Repository navigation
feat(cc): reconstruct training segments from ordinary rollout history - #4124
Conversation
Stage exact token deltas and processed Nemotron image tensors together in TQ, then verify and assemble selected media in the rollout finalizer. Adapt geometry validation, processor-cache handling, and packed publication from #4124. Pin the paired Gym attachment support built on Gym #3301; compaction is excluded. Signed-off-by: Pranav Prashant Thombre <[email protected]>
Stage exact token deltas and processed Nemotron image tensors together in TQ, then verify and assemble selected media in the rollout finalizer. Adapt geometry validation, processor-cache handling, and packed publication from #4124. Pin the paired Gym attachment support built on Gym #3301; compaction is excluded. Signed-off-by: Pranav Prashant Thombre <[email protected]>
0c98c99 to
abb2583
Compare
|
/ok to test 083ece0 |
083ece0 to
33ad46e
Compare
|
/ok to test 33ad46e |
terrykong
left a comment
There was a problem hiding this comment.
Please rebase on main. The PR now conflicts with it in single_controller.py and rollout_reassembler_actor.py.
This PR moves context compaction (CC) onto the ordinary rollout path. The RL vLLM worker decides at request time whether a call continues its parent or starts a new root (decide_capture_input), TransferQueue stores each call as its difference from its parent call, and the reassembler rebuilds one training row per chain from ordinary Gym output. Compared with the earlier design, much less data moves, and harnesses no longer have to return a result per segment.
What works well: the training math is right — one advantage per logical rollout, a global token-level loss denominator, and one scheduler step per training step. decide_capture_input is a pure function, and the worker branches on the request protocol, not on a flag. CC reuses the GRPO estimator and finalize_rollout instead of adding parallel copies. Commit f5fc1d4 also fixed two problems this review had found: a failed or pending model call now masks only its own rollout instead of stopping the run (nemo_gym.py#L1114-L1120), and a group with no valid owner now goes down the existing drop path (rollout_reassembler.py#L840-L852). 83783cb waits a bounded time for in-flight calls before masking. A request whose continuation cannot be spliced now starts a new segment instead of failing the rollout.
The most important comment is on context-compaction.md#L47: under CC, any dropped prompt group stops the run, because CC turns off both of the ordinary path's safety nets: retrying the group, and training the step without it. That comment asks for the second one in this PR, so a step trains on the groups it kept. Retry can follow in #4557.
Merge order. CI at the current Gym pin fails at test collection. This PR can land only with or after the submodule bump to a Gym main that includes NVIDIA-NeMo/Gym#3368, as the PR description says.
Test status. No unit-test CI has run on this PR yet (only the semantic, DCO, copyright and submodule checks). A local CPU run with the paired Gym at 5ff98a4 (two pushes before the current head) passed 195 tests in default mode, and 265 passed / 7 skipped in nemo_gym mode. GPU tests were not run.
Follow-ups for NVIDIA-NeMo/Gym#3368 (not this PR):
- In
simple_agent_with_compaction, end the episode as incomplete when the context guard raisesContextGuardRejected(client.py#L183). Today the uncaught error reaches RL as an HTTP 500. RL treats that as an infrastructure failure and drops the whole prompt group, which then stops the run (rollout_manager.py#L2210-L2214). Ending the episode instead would mask only that rollout, as an overflow without a guard already does. - Make
_RESPONSE_OUTPUT_BOUNDARY_TYPESpublic; RL now imports the private name (gym_selection.py#L24). - Export
PREDECESSOR_TAIL_ROUTE_FIELDand the measure-response keys (ng_context_measured,prompt_token_count) as constants, so RL can import them instead of copying the strings (vllm_worker_async.py#L849,vllm_worker_async.py#L1578-L1579). - Export the list of length finish reasons; RL copies it at
nemo_gym.py#L1133andnemo_gym.py#L1148. - The
simple_agent_with_compactionREADME says streaming and resampling are rejected (README.md#L9), but buffered Responses SSE is now accepted (base_responses_api_model.py#L304-L312) and the client supports resampling (client.py#L199).
The performance evidence (four 20-step runs) is enough for an opt-in feature; no ask there.
Visual explainer (1 · old vs new design): https://terrykong.github.io/gh-pages-poc/terryk/pr-4124-cc-old-vs-new.html
Visual explainer (2 · data flow): https://terrykong.github.io/gh-pages-poc/terryk/pr-4124-data-flow.html
Visual explainer (3 · calls → rows): https://terrykong.github.io/gh-pages-poc/terryk/pr-4124-calls-to-rows.html
Visual explainer (4 · tree vs forest): https://terrykong.github.io/gh-pages-poc/terryk/pr-4124-tree-vs-forest.html
Visual explainer (5 · reward → rows): https://terrykong.github.io/gh-pages-poc/terryk/pr-4124-reward-to-rows.html
Visual explainer (6 · dropped group stops the run): https://terrykong.github.io/gh-pages-poc/terryk/pr-4124-dropped-group.html
Visual explainer (7 · batch size under CC): https://terrykong.github.io/gh-pages-poc/terryk/pr-4124-cc-batch-size.html
Generated by Claude Code
Signed-off-by: Ali Roshan Ghias <[email protected]>
Signed-off-by: Ali Roshan Ghias <[email protected]>
Signed-off-by: Ali Roshan Ghias <[email protected]>
Signed-off-by: Ali Roshan Ghias <[email protected]>
Signed-off-by: Ali Roshan Ghias <[email protected]>
|
/ok to test 5f84f82 |
…to 4 Turn-level recovery changes the rollout-recovery ledger's shape: a group records its restore level instead of its recovery granularity, and each attempt records its Gym instance and attempt. Main had meanwhile moved to schema 4 for token-capture receipts (#4124), so this shape is schema 5. Accepting schema 5 only would fail any run resumed from a checkpoint main wrote; main itself loads schema 2 checkpoints again since #4551. Schemas 2 to 4 now load and are rewritten in the schema 5 shape. A group's recovery_granularity becomes its restore level; the values are the same. Each attempt starts with no Gym turn state, as a new attempt does, because those schemas predate it. An old checkpoint that already carries a restore level, Gym attempt state or the turn level is refused rather than guessed at. Signed-off-by: Anish Mahishi <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
…to 5 Turn-level recovery changes the rollout-recovery ledger's shape: a group records its restore level instead of its recovery granularity, and each attempt records its Gym instance and attempt. Main had meanwhile moved to schema 4 for token-capture receipts (#4124) and schema 5 for forest selections (#4200), so this shape is schema 6. Accepting schema 6 only would fail any run resumed from a checkpoint main wrote; main itself loads schema 2 checkpoints again since #4551. Schemas 2 to 5 now load and are rewritten in the schema 6 shape. A group's recovery_granularity becomes its restore level; the values are the same. Each attempt starts with no Gym turn state, as a new attempt does, because those schemas predate it. An old checkpoint that already carries a restore level, Gym attempt state or the turn level is refused rather than guessed at. Main's per-version rules (receipts before schema 4, the forest selection from schema 5) still apply to the version the checkpoint was written with. Signed-off-by: Anish Mahishi <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
…to 5 Turn-level recovery changes the rollout-recovery ledger's shape: a group records its restore level instead of its recovery granularity, and each attempt records its Gym instance and attempt. Main had meanwhile moved to schema 4 for token-capture receipts (#4124) and schema 5 for forest selections (#4200), so this shape is schema 6. Accepting schema 6 only would fail any run resumed from a checkpoint main wrote; main itself loads schema 2 checkpoints again since #4551. Schemas 2 to 5 now load and are rewritten in the schema 6 shape. A group's recovery_granularity becomes its restore level; the values are the same. Each attempt starts with no Gym turn state, as a new attempt does, because those schemas predate it. An old checkpoint that already carries a restore level, Gym attempt state or the turn level is refused rather than guessed at. Main's per-version rules (receipts before schema 4, the forest selection from schema 5) still apply to the version the checkpoint was written with. Signed-off-by: Anish Mahishi <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
…to 5 Turn-level recovery changes the rollout-recovery ledger's shape: a group records its restore level instead of its recovery granularity, and each attempt records its Gym instance and attempt. Main had meanwhile moved to schema 4 for token-capture receipts (#4124) and schema 5 for forest selections (#4200), so this shape is schema 6. Accepting schema 6 only would fail any run resumed from a checkpoint main wrote; main itself loads schema 2 checkpoints again since #4551. Schemas 2 to 5 now load and are rewritten in the schema 6 shape. A group's recovery_granularity becomes its restore level; the values are the same. Each attempt starts with no Gym turn state, as a new attempt does, because those schemas predate it. An old checkpoint that already carries a restore level, Gym attempt state or the turn level is refused rather than guessed at. Main's per-version rules (receipts before schema 4, the forest selection from schema 5) still apply to the version the checkpoint was written with. Signed-off-by: Anish Mahishi <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ics-20260930 Conflict in advantage_stage.py with #4124 (Forest logical owners): - Feed _apply_async_sample_masks the new owner_sample_mask in place of main's inline mask_sample/overlong multiply. Ordinary batches are unchanged; on Forest batches it zeroes the same rows, and main's owner fanout and owner-level num_mask_sample_filtered still follow. - Report no per-reason counts for Forest batches: the counts are per physical row, while owners are masked whole and execution padding arrives masked. test_logical_advantage.py pins this. Signed-off-by: Peter Jin <[email protected]>
…kind-advantages Main added rollout recovery schema v4 (token-capture receipts, #4124) and v5 (logical_selection, #4200), so failure_kind moves to schema v6. The ledger still loads v2 to v5, with failure_kind=None. Conflicts kept both sides: failure_kind next to logical_selection in the ledger, SiblingSealResult and both seal calls; infra_failure next to the Forest fields in ReassemblyRequest; the infra metric next to the logical owner counts; the infra sample_mask next to the sampler top-k copy. Main moved row building into _publish_rows, so finalize_group now passes infra_failure in. With forest_training, each segment row takes its rollout's flag, and infra_failure_sample_rate counts rollouts. Tests: the v3 load test is now a v5 load test; the finalizer test sets capture_key, as main's receipts need; a new Forest test checks that the segment rows of a flagged rollout get sample_mask 0. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]>
…rest training Turn-level recovery (#4500) continues a restored episode as its next attempt (<rollout_id>-a<N>) and keeps the calls the earlier attempt made, still staged under that attempt's key. Forest training's ownership checks (#4124, #4200) predate this and required every manifest row to be staged under the current attempt's key. So every continued episode that had made a model call before the checkpoint failed with "Forest recovery has foreign staging ownership"; the rollout manager counted a data retry and regenerated the episode from its prompt without logging why. Training stayed correct, but turn (and prefix) recovery saved nothing under forest training. Accept a row staged under the current attempt or an earlier attempt of the same rollout, the rule Gym's rebuild already applies through each carried row's source_capture_key, at all four Forest ownership checks: the recovery ledger, the finalizer request, selected-call planning and logical-row finalization. Rows of another rollout or a later attempt are still refused. Also print each data retry with its error, so a prompt that is silently regenerated shows why in the log. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
PR 4128 coverage — feat(capture): support framework-owned context reconstruction
Existing coverage
Contract
Doc check (2026-11-12, workflow wf_554f4197-ab2, Gym 5d22439f4)model-call-capture.mdx L65-196 + external-agent-harnesses.mdx L405-423. 5/5 checkers returned (26/34/30/24/34 Decisions
Design (Gym-only case
|
| # | Gym | Cases | Result | Run |
|---|---|---|---|---|
| 1 | 0a5110a6c |
both | ENV: h100 uv 0.12.20 < Gym main's required 0.13.4; upgraded bootstrap venv uv → 0.13.8 | 20261112T184424576448Z-4a650ffc |
| 2 | 0a5110a6c |
both | BLOCKED before Gym ran: vllm serve exits in 15 s, ModuleNotFoundError: Could not import module 'MistralCommonBackend' ← pycountry missing from the local_vllm_model venv. Same for token_capture_external_staging (not caused by this change) |
20261112T184514318207Z-57419a36 |
| 3 | 0a5110a6c |
both | BLOCKED: engine init No module named 'torchvision' (pycountry workaround in) |
20261112T190328741843Z-69ed0590 |
| 4 | 0a5110a6c |
both | harness PASS; external_staging PASS; README FAIL = test bug: ledger is <key>.lineage.jsonl, case globbed *.tokens.jsonl. Real data: qa-sh-4 tool call → continuation admitted as candidate (parent = first call) → worker_rooted; 4 rollouts answered without tools. Fixed glob; 5 repeats per example |
20261112T190745945428Z-ea473c29 |
| 5 | efaa56a17 |
both | harness PASS; external_staging PASS; README FAIL = test bug in the stand-in's verify: it passed all 39 staged rows (25 rollouts) for a 2-row manifest (row_count_mismatch). Fixed: filter staged rows by capture_key. Evidence: 10/25 rollouts called tools, 14 candidate admissions |
20261112T191327438857Z-cb87ec63 |
| 6 | efaa56a17 |
all 3 | PASS (README 73.3 s, harness 45.1 s, external_staging 41.8 s), pycountry + torchvision workaround | 20261112T191640267263Z-f8f15a82 |
| 7 | 330c46109 |
source_history | PASS 2/2 (README 85.1 s, harness 45.0 s) after the CodeRabbit fix (first rollout tool_choice: required); forced qa-sh-0-r0: 2 tool_calls turns, 2nd a candidate; 8/25 rollouts proposed candidates. Workaround installed in the new checkout |
20261112T201258514469Z-45d79a11 |
| control | efaa56a17 |
source_history case with parent_resolution: fingerprint (1-line copy, direct run) |
FAIL ×2 on behavior: first call has no root_reason; first continuation is a Gym-chosen token_in staging_chain admission, which the source-history worker refuses (CaptureError … prefix_token_ids) → 500 |
direct 20261112T191949Z, 20261112T192231Z (kept) |
Registry: status: fail, nvbugs: ["7087161"] (open), reason in the docstring. Branch commit c1990fee on
nmfw_tests main a9f72574; MR body mr-body.md; NVBug comment draft
../nvb-7087161-local-vllm-pycountry/nvbug-comment-torchvision.html.
Blocker: vLLM 0.29 cannot start from a Gym-main local_vllm_model venv (2026-11-12)
Filed as NVBug 7087161 (board bugs/nvb-7087161-local-vllm-pycountry.md). Workaround per user: uv pip install --no-config --no-deps "pycountry==26.2.16" into h100's checkout venv for 0a5110a6cb (survives Gym's --inexact
pre-warm). Runs from 3 on carry this workaround; the MR says so. Run 3 then died on torchvision (same
never-install group, imported at engine init); from run 4 the venv also has torchvision==0.28.0+cu130 (cu130 index,
--no-deps).
- Cause (observed): Gym feat(flint): add Automodel and SGLang GRPO support #4837 (
1203b0be21, 2026-11-04) added"pycountry; sys_platform == 'never'"to
responses_api_models/local_vllm_model/pyproject.tomloverride-dependencies(legal exclusion, feat(data-plane): add TQ fault tolerance APIs #2492). vLLM 0.29
backend_guidance→transformers.MistralCommonBackend→mistral_common→pydantic_extra_types.language_code
→pycountry. Reproduced in isolation on h100:python -c "from vllm.v1.structured_output.backend_guidance import GuidanceBackend"in that venv fails the same way. - Gym's own GPU e2e works around it:
tests/e2e/gpu_e2e_test.sh:143-146installspycountry==26.2.16"even for
non-Mistral models".docker/install_excluded_deps.sh(the documented opt-in) says pycountry is for VLMs and is
documented for containers only;local_vllm_model/README.mddoes not mention it. - Suite:
lib/image_requirements.pyruns that installer only whenNEMO_GYM_CONTAINER=1; checkout-lane vLLM cases
get nothing, so everyvllmcase on the h100 lane is blocked on Gym main since 11-04 (board trap
environment-traps.md:238recorded it for the nightly image only, when main still had pycountry).
Review (fresh agent, 2026-11-12): Minor fix needed
- Needs run evidence on main + a control (pending; blocked above).
- Case 1
continued > 0depends on Qwen3-0.6B calling a tool on ≥1 of 5 tasks → decide after the first real run. - Measure assertion
prompt_tokens == worker countcould not fail → dropped; the served-prompt equality stays.
Worker protocol, root reasons, manifest fields, measure path and the external-staging refactor: no issue found.
Handoff
2026-11-12: MR !539 open (branch
qiaochuz/nemo-gym-pr4128-framework-context, commit c1990fee on nmfw_tests main a9f72574). NVBug 7087161 comment
#1 posted. Next:
/gym-review-bots !539once Greptile/CodeRabbit have posted.- When NVBug 7087161 is fixed: rerun on h100 without the workaround, then flip the registry to
passand drop
nvbugs(a/gym-merged-style follow-up MR). - NeMo-RL compaction run against Gym main: proposed as its own session (card "NeMo-RL compaction run vs Gym main").
- h100 state left behind: uv 0.13.8 in
~/.local/share/nemo-qa-bootstrap; pycountry + torchvision in the
local_vllm_modelvenvs of checkouts0a5110a6cb…,efaa56a175…and330c461093…; landing worktree
~/nemo/workdir/pr4128-framework-context/nmfw_tests(itsconfig/config.pyis modified by the runner).
2026-11-12, /gym-review-bots !539: Greptile 5/5, no inline findings. CodeRabbit, 1 thread (Minor: the README
case's continued > 0 rests on sampling): fixed in 55345296 (first rollout tool_choice: required), run 7
PASS on Gym main 330c461093, replied and resolved. No unresolved bot threads; MR head 55345296.
Context compaction can split one rollout into several independent model contexts. This PR reconstructs those contexts in NeMo-RL from shared capture, while each harness retains its compaction policy. A 20-call rollout produces one training row without compaction and two rows with one context rewrite; continuations retain parent-linked token/media deltas.
The underlying mechanism is forest training. The worker determines context continuity during rollout. Ingestion selects captured calls, reconstruction validates their committed ancestry and finds endpoints in the selected forest, and the existing backward assembler builds training rows. Concurrent and interleaved contexts can resume earlier chains. A selected call with only discarded children remains an endpoint. Shared ancestors remain context in every path, with generated loss and action counts owned once across paths.
Physical rows retain one logical-rollout reward and GRPO advantage. Training consumes captured tokens, logprobs, processor outputs and applicable router-replay data. Retained-image changes and ambiguous attribution fail explicitly. There is no harness-specific
LogicalCCResult, client parent-header requirement, new media store, or upstream vLLM patch.Configuration and training membership
For a compatible SingleController/Gym GRPO configuration:
The former
token_capture.context_compactionkey is rejected at startup with migration instructions; rename it while preserving its value.returned_history(default): match ordinary returned history or call references to captured whole generations. Calls absent from that history are excluded. Native identities and content fingerprints constrain attribution; ambiguous or contradictory evidence raises. Capture alone cannot recover an independent accepted chain omitted entirely from returned evidence.all_captured(explicit opt-in): select all recorded calls, including abandoned retries and independent branches. Full execution history is unnecessary, but the scored terminal must still be attributable through a declared ID or returned response identity/content. ForA → BandA → C, both branches train; this does not choose the latest sibling. SharedAcontributes loss once.Both policies reuse completion/integrity checks, forest reconstruction and logical-owner accounting. Pending or failed capture, and failed selected executions, still mask the logical rollout. Capture order does not identify the scored terminal, and that terminal need not be the last captured call. Neither policy infers agent roles or provides separate subagent rewards.
Learner support and limits
grpo.seq_logprob_error_thresholdchecks the mean error across all uniquely owned generated tokens of a logical rollout. A failing rollout has all its rows masked from loss. The sharedgrpo.masked_reward_policycontrols whether its reward remains in baseline statistics:includeretains it once;excluderemoves it. Sequence-error metrics remain per physical row.The path remains opt-in, token-level GRPO on non-interleaved Megatron with supported routing. Dynamic batching, partial-step batches, non-unit dataset loss multipliers, message-level advantage overrides, incompatible objectives and deferred route assembly remain guarded. Checkpoint/resume is separate work in #4200. Stock OpenCode, general multi-session aggregation, per-agent rewards and broad live multi-agent qualification are not claimed here. See the guide for the full configuration and execution restrictions.
Integration and merge order
Targets RL
main, which includes #4191. Shared capture requires Gym #4128, which is merged. The native compaction example additionally requires Gym #3368; external harnesses that own compaction do not need that native agent. Gym #3368 is optional and does not block this foundation PR. Normal upstream Gym dependency integration must be available before merging.No dependency declaration, lockfile, Gym submodule pin or secrets-baseline change is introduced by the forest-training update. Validation uses paired Gym source privately. The shared naming, reconstruction, clipping, masking and packing belong in this foundation; the stacked #4285 should reuse them for additional selection policies. Its latest-continuation selection is distinct from
all_capturedand must not silently replace the default.Validation
Main-merge follow-up at
bf6926a35: resolved conflicts against main95719f8e8, preserving upstream agent routing and DebugWriter support. 1,072 Mac CPU tests passed, including include/exclude masked-reward participation with unequal segment counts. Focused type checks, formatting, lint and recipe minimize checks passed. No new GPU validation is claimed.Receipt-schema follow-up at
6fb615a69: 781 CPU tests passed on Mac, including receipt-free v2/v3 recovery, current receipt round trips, and explicit rejection of pre-v4 captured receipts. Focused pinned Pyrefly, formatting and lint checks passed. No new GPU runs are claimed for this checkpoint-format fix.Current CPU validation at
bd026028a: 1,528 tests passed and 350 skipped on Mac using paired Gym checkouts: 89 capture/selection tests and 1,439 controller, setup, configuration, advantage and loss-accounting tests. Coverage includes shared ancestors, context rewrites, once-only selected loss, whole-rollout filtering, clipping, packing accounting, config migration, and exporter-style synthetic IDs. Eight added attribution cases check unique versus ambiguous content and a scored call followed by later worker completion. Ruff, formatting and whitespace checks passed. These tests use synthetic generations and do not qualify distributed GPU numerics or a live external harness.Packed runtime validation: manufactured no-compaction and image-K2 runs completed 20 optimizer steps each. Audits passed selected membership, captured token/media/reward checks and once-only selected loss. Maximum TMPE was approximately 1.000003 and 1.000026, respectively. OpenCode identity and compaction runs did not complete the same qualification: logprob-error filtering stopped them. Packing GPU numerical agreement and OpenCode TMPE remain under investigation; CPU passes and the manufactured runs do not close those gates.
Historical forest regressions, before this update: the four runs below completed 20 optimizer steps, with saved-capture audits of membership, tokens/masks/generation logprobs, applicable media and once-only selected loss. They are retained as baseline evidence, not validation of the current head.
Two historical sequential-forest controls also passed capture/learner audits: free-form, lookahead 0 and ACK, lookahead 1. Each covered 40 owners, 280 calls and 160 rows. Their live forests used disjoint chains; shared-ancestor coverage comes from component/loss/media tests.
The custom OpenCode fork used a temporary collector ordering correction and a bounded verifier preserving post-completion probes. These results do not establish stock OpenCode or SWE-bench compatibility. Final CI, paired dependency integration and the outstanding GPU qualification remain merge gates.