Repository navigation
perf(token-capture): bulk-pack columns and compute staging digests once - #4213
Conversation
a960319 to
7e20865
Compare
b2fde6b to
9d0ac5b
Compare
9d0ac5b to
e6d58e4
Compare
|
/ok to test e6d58e4 |
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class EncodedPrefixDigest: |
There was a problem hiding this comment.
EncodedPrefixDigest has no production caller yet. grep finds it only in tests/unit_tests/test_token_capture_staging_worker.py, it is not exported, and I could not find a consumer in NeMo RL upstream/main or in the local RL working copies. The "avoid duplicate digest work" half of the title is delivered by the bulk encoders and from_components, which do not depend on this class.
Could this land together with its first consumer, for example the checkpoint stack or the RL integration? The memory cost, the weight_version and mask behavior of extend, and the adopt-after-success contract are easiest to get right against real use, and a reviewer cannot validate them from tests alone. If you would rather keep it here, a sentence in the PR description naming the intended consumer and keeping the class out of any public export would help.
There was a problem hiding this comment.
Agreed. Removed EncodedPrefixDigest, its supporting helpers, and its tests in f0e84c2. This PR now contains only bulk column encoding and single-digest construction, both used by Gym's existing complete_call path. The cache will be reviewed separately alongside its RL consumer. I also updated the title and removed the cache-enabled performance figures.
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class EncodedPrefixDigest: |
There was a problem hiding this comment.
Naming: "prefix" already means the prompt tokens a call must match in this package (_PrefixIndex, enter_prefix, prefix_token_ids, required_prefix_token_ids). Here it means the parent plus delta columns of one call, which the rest of the package calls cumulative, delta, parent, and chain (cumulative_hash, cum_len, chain_hash). The name also ends in Digest, but the class is a cache that holds a digest rather than a digest.
Something like StagedCallEncodedColumns would describe the one job it has: it holds one staged call's encoded columns so a child call can append tokens and recompute the digest without re-encoding the parent.
There was a problem hiding this comment.
Removed the cache class from this PR in f0e84c2. I'll revisit the name alongside its consumer in the follow-up, using a name that describes the staged-call encoding cache rather than overloading the existing prompt-prefix terminology.
|
|
||
| @dataclass(frozen=True) | ||
| class EncodedPrefixDigest: | ||
| """Immutable per-call cache of validated v2 prefix columns. |
There was a problem hiding this comment.
The docstring uses "cut", "staged and sealed", and "candidate". Those are NeMo RL and checkpoint-stack terms that Gym main does not define, so a reader of this file cannot tell what they refer to. Could this say what the class does in Gym terms, for example "extend returns a new instance; keep the old one until the new call is durably staged"?
Two more details worth stating here: the public digest field is undocumented, and the instance keeps about 8 bytes per parent token plus 16 bytes per delta token, which a maintainer needs to know to bound its lifetime.
There was a problem hiding this comment.
Removed the cache and its docstring from this PR in f0e84c2. Its digest meaning, retained memory, lifetime, and adoption contract will be documented with the consumer in the follow-up.
| return digest.hexdigest() | ||
|
|
||
|
|
||
| @dataclass(frozen=True) |
There was a problem hiding this comment.
The generated dataclass repr includes every byte column. At 65,536 tokens len(repr(cache)) is about 3.85 MB, so a failing assertion or a %r log line would dump all of it. field(repr=False) on the byte fields, or @dataclass(frozen=True, repr=False), avoids that.
There was a problem hiding this comment.
Confirmed the large repr. The cache class is removed from this PR in f0e84c2; suppressing byte-column representations belongs in the follow-up that reintroduces it with its consumer.
| ) | ||
| return replace(candidate, digest=candidate._compute_digest()) | ||
|
|
||
| def _compute_digest(self) -> str: |
There was a problem hiding this comment.
_compute_digest is a second hand-written copy of the formulas that compute_chain_hash and hash_token_ids own, including their domain constants and length prefixes. If either layout changes, this copy can drift silently, and today only the equality tests would notice.
Could the public functions and this method share small private helpers, for example one that builds the chain hash from a parent hash and token column bytes, and one that builds the cumulative hash from the total length plus parent and delta bytes? Then each formula has a single owner. If the class stays, it could also live in its own module, which removes the TYPE_CHECKING import of StagedCallRecord from this otherwise pure encoding module.
There was a problem hiding this comment.
Removed the cache's _compute_digest, its supporting hash helpers, and the TYPE_CHECKING import in f0e84c2. The original compute_chain_hash, hash_token_ids, and staging-digest payload construction remain, so this PR no longer duplicates the formulas.
| ([10, 11, 99], admission.parent_chain_hash), | ||
| ([10, 11, 12], "f" * 64), | ||
| ]: | ||
| with pytest.raises(ValueError, match="prefix cache"): |
There was a problem hiding this comment.
Two mutants survive here. Deleting the len(parent_token_ids) != record.prev_len check in from_record still passes, because the digest check raises a message that also contains "prefix cache". Deleting the length check in extend still passes at line 838, because a later ValueError satisfies the bare pytest.raises(ValueError). Tighter matches kill both:
def test_encoded_prefix_cache_extend_rejects_mismatched_lengths_before_encoding() -> None:
from nemo_gym.token_id_capture.staging.digest import EncodedPrefixDigest
record = _completed_record(prompt_token_ids=[10], generated_token_ids=[11], generated_logprobs=[-0.25])
cache = EncodedPrefixDigest.from_record(record, parent_chain_hash=None, parent_token_ids=[])
for tokens, logprobs in (([1], []), ([1], [-0.1, -0.2]), ([], [-0.1])):
with pytest.raises(ValueError, match="equal lengths"):
cache.extend(generated_token_ids=tokens, generated_logprobs=logprobs)
def test_encoded_prefix_cache_reports_parent_length_mismatch_distinctly() -> None:
from nemo_gym.token_id_capture.staging.digest import EncodedPrefixDigest
record = _completed_record(
child=True, prompt_token_ids=[10, 11, 12], generated_token_ids=[13], generated_logprobs=[-0.25]
)
with pytest.raises(ValueError, match="parent length"):
EncodedPrefixDigest.from_record(
record, parent_chain_hash=_child().parent_chain_hash, parent_token_ids=[10]
)I ran both against this branch and they pass, and each one fails when the matching check is removed.
There was a problem hiding this comment.
Removed the cache and its tests from this PR in f0e84c2. Thanks for the mutation examples; those specific parent-length and extension-length checks should accompany the cache when it is reviewed with its consumer.
| raise ValueError("prefix cache contents or parent do not match record digest") | ||
| return cache | ||
|
|
||
| def extend( |
There was a problem hiding this comment.
extend carries weight_version from the base record with no way to change it, appends mask 1.0 for every new token, and does not recheck the mask and log-probability invariant that StagedCallRecord enforces. That fits generated tokens within one weight version, but it is not stated anywhere, and a caller that extends after a weight update would get a digest that differs from a fresh complete_call. The docstring also says the cache is never serialized, but a frozen dataclass pickles fine. These contracts are easiest to settle together with the consumer, or at least to document here.
There was a problem hiding this comment.
Removed the cache from this PR in f0e84c2. The weight-version, generated-token mask, and lifetime contracts will be settled alongside its RL consumer. The follow-up should describe exclusion from checkpoint state rather than imply that the dataclass cannot be pickled.
| raise ValueError(f"token_id must be an unsigned 64-bit integer, got {token_id!r}") | ||
| # Pack the column in C rather than allocating and extending once per token. | ||
| # Explicit big-endian widths preserve the v2 wire bytes on every host. | ||
| return length + struct.pack(f">{len(token_ids)}Q", *token_ids) |
There was a problem hiding this comment.
Behavior change worth a look: the old loop visited the sequence once and could only raise ValueError. Here the sequence is read twice, once by the validation loop and once by struct.pack(*token_ids). A sequence whose __len__ disagrees with its iteration, or a list mutated between the two reads, raises a raw struct.error, and complete_call and rebuild._recompute_integrity catch only TypeError, ValueError, and OverflowError. Production callers pass freshly built lists, so I do not see a reachable path today. Wrapping the pack in try/except struct.error and raising ValueError, as _encode_float32_values does, would keep the contract the same as before.
There was a problem hiding this comment.
Addressed in f0e84c2: token-ID bulk packing catches struct.error and OverflowError and translates them to ValueError. Added an inconsistent-sequence regression test to verify that the raw packing error does not escape.
| ("extras", {"changed": True}), | ||
| ], | ||
| ) | ||
| def test_local_record_builder_keeps_integrity_checks(field: str, value: object) -> None: |
There was a problem hiding this comment.
Could this file also pin that an arbitrary context= does not skip digest verification, for example StagedCallSnapshot.model_validate(corrupted, context=object()) still raising "digest does not match"? I checked it by hand and it holds, but the safety of the build path rests on only the private sentinel skipping verification, and nothing currently guards that. Also, the parametrized cases here assert a bare ValidationError, so a case that fails for an unrelated reason would still pass. A match= per case would make each one prove the check it is named for.
There was a problem hiding this comment.
Addressed in f0e84c2. Added a corrupted-wire-record case using context=object() that still raises "digest does not match", and added specific match= assertions to each local-builder integrity case. All 445 selected token-capture tests pass locally.
|
/ok to test f0e84c2 |
…t work Signed-off-by: Anish Mahishi <[email protected]>
…ashing Remove the encoded-prefix cache and its support code so the PR benefits Gym main without an RL consumer. Preserve the original digest layout, normalize bulk token packing errors, and strengthen integrity and duplicate-hash regression tests. Signed-off-by: Anish Mahishi <[email protected]>
f0e84c2 to
40710ef
Compare
|
/ok to test 40710ef |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/38456074943 |
…VIDIA-NeMo#3884) ## What changed and why An inference worker that serves generation cuts needs three helpers from `RolloutTokenCapture`. This PR adds them: - `begin_call(generation_cut=..., generation_cut_staging_keys=...)` validates the durable prefix a replacement call continues against its admission: the staging keys, source call, digest, lineage, generated-token count, and that the prefix's policy version is not newer than the current one. It also checks that the prefix extends the replacement's exact parent tokens: it recomputes the chain hash from the admission's parent chain hash and the prefix's tokens, and the cumulative hash from the resolved prefix plus those tokens. The snapshot's digest authenticates only its own fields, so without this a prefix built on other parent tokens, with the same parent call ID and length, would be spliced in silently. This costs one hash of the prefix per recovered call. - `build_prefix_record` snapshots a live call without completing it, so a cut can stage the prefix while the request keeps decoding. For a continued call it produces the old prefix plus the new tail, stamped with the oldest contributing policy version. - `build_generation_chunk_record` stages only newly generated tokens, for workers that flush a long generation in chunks. `complete_call` now builds its record through `build_prefix_record` and claims completion only after the record is valid. Both builders use `StagedCallRecord.from_components` from NVIDIA-NeMo#4213, so every locally built record computes its digest once. Why: the policy model PR sends cut requests and attaches restored cuts, but a real worker (for example NeMo RL's vLLM worker) could not serve them, because these helpers existed only on the old prefix-recovery branch. **Policy workers are logged as they come and go.** The policy checkpoint coordinator in the main process now logs each worker by process ID, so its lines match uvicorn's own `Child process [<pid>] died`: - an info line when a worker joins, with how many of the expected workers are connected; - an info line when a worker stops cleanly: a worker that shuts down tells the coordinator first, with a short timeout; - a warning when a worker is lost without saying so (a crash, or uvicorn killing a hung worker), with how many workers remain and whether an open checkpoint can no longer commit. Before, a lost worker showed up only as a readiness blocker or an `export_failed` commit during a checkpoint, and outside one only in the status route's `workers` count. uvicorn restarts a lost worker on its own, and the replacement registers with the coordinator and adopts its state. ## How it works ### Where this PR sits in the overall flow The highlighted part is what this PR adds. ```mermaid flowchart LR C["Controller<br/>NeMo RL, or rollout collection"] CO["Coordination<br/>prepare, commit, restore, resume,<br/>retire, forget"] K["Control plane on every server<br/>phases, lease, storage,<br/>retire: refuse, stop, free;<br/>forget"] subgraph G["One participant per Gym server"] E["Environment server<br/>episode steps"] M["Policy model<br/>held responses, generation cuts"] A["Agent<br/>sessions parked at boundaries"] R["Resources server<br/>session state"] end W["Inference worker<br/>stages cut prefixes"] D[("Checkpoint directory<br/>records, then manifest")] L[("Capture ledger<br/>retire and delete from NVIDIA-NeMo#3938, NVIDIA-NeMo#3939")] C --> CO --> K K --> E & M & A & R M --> W M --> L G --> D classDef this fill:#fde68a,stroke:#b45309,stroke-width:2px,color:#1f2937 class W this ``` One checkpoint, a crash, and the restore, end to end: ```mermaid sequenceDiagram participant C as Controller participant G as Gym participants participant D as Checkpoint directory C->>G: prepare, in order environment, model, agent, resources Note over G: admission closes, in-flight work parks at a boundary,<br/>undelivered model responses are held G-->>C: prepared, or blockers at the deadline C->>G: commit with the episodes the controller continues G->>D: each participant writes its records, then its manifest Note over G: restored state the commit's scope leaves out is deleted C->>C: publish the checkpoint with the controller's own state C->>G: resume, in order resources, agent, model, environment Note over C,G: crash - every Gym process dies C->>G: restore the checkpoint in fresh processes, all or nothing D-->>G: records installed under attempt N+1, attempt N's capture ledger retired C->>G: resume C->>G: /run as attempt N+1 continues each episode from its boundary Note over C,G: retiring an episode, only while no checkpoint is open C->>G: retire - environment, then agent, then model and resources Note over G: each server marks the attempt, stops its work, waits, frees its state, then replies C->>G: forget, once the rollout is done for good - same order Note over G: the mark refusing the retired attempt goes away ``` ### This PR What an inference worker does with these helpers when the policy model asks for a cut, and when a replacement call continues it. ```mermaid sequenceDiagram participant P as Policy model server participant W as Inference worker participant S as Token staging P->>W: POST /ng-control/v1/generation-cut with the in-flight calls W->>S: build_prefix_record stages the tokens so far, the call keeps decoding W-->>P: receipt - staging keys and digest per call Note over P,W: after a crash and restore P->>W: replacement call carrying the continuation W->>S: begin_call checks keys, source call, digest, lineage, parent tokens, token count, policy version W->>W: decode only the rest of the generation ``` ## Where this sits in the stack This is one PR in a stack of draft PRs that re-cut partial-rollout checkpointing onto environment servers. Each PR is one commit, and its base is the branch of the PR before it, so each diff shows only that PR's change. The stack builds on the token-capture cleanup PRs NVIDIA-NeMo#3938 (capture ledger `retire` and `delete`) and NVIDIA-NeMo#3939 (complete-record `retire` and `delete`), which have merged. NVIDIA-NeMo#3882 and NVIDIA-NeMo#3883 have merged too, so NVIDIA-NeMo#3884's base is `main`. The checkpoint stack uses those operations to free the ledgers of retired attempts and to clear a dead execution's capture files before a restore. The capture-ledger cache bound (NVIDIA-NeMo#4268) and the striped lock files (NVIDIA-NeMo#3937) are independent of the stack. 1. NVIDIA-NeMo#3882 (`ananthsub/partial-ckpt-core`): feat(checkpoint): add the participant control plane, episode steps, and coordination (merged) 2. NVIDIA-NeMo#3883 (`ananthsub/partial-ckpt-policy-model`): feat(checkpoint): make policy model servers checkpoint participants with generation cuts (merged) 3. NVIDIA-NeMo#3884 (`ananthsub/partial-ckpt-model-worker-cuts`): feat(token-capture): add worker staging helpers for generation cuts **(this PR)** 4. NVIDIA-NeMo#3885 (`ananthsub/partial-ckpt-environment`): feat(checkpoint): continue environment server episodes from their boundaries 5. NVIDIA-NeMo#3886 (`ananthsub/partial-ckpt-resources`): feat(checkpoint): add the resources server participant with asynchronous session hooks 6. NVIDIA-NeMo#3887 (`ananthsub/partial-ckpt-verifier-declarations`): feat(checkpoint): declare five training verifiers stateless with replayable verification 7. NVIDIA-NeMo#3888 (`ananthsub/partial-ckpt-agent`): feat(checkpoint): add the agent session participant and Simple Agent continuation 8. NVIDIA-NeMo#3889 (`ananthsub/partial-ckpt-e2e`): test(checkpoint): add a process-level end-to-end suite driven by coordination 9. NVIDIA-NeMo#3893 (`ananthsub/partial-ckpt-rollout-collection`): feat(checkpoint): checkpoint evaluation runs from rollout collection 10. NVIDIA-NeMo#3903 (`ananthsub/partial-ckpt-telemetry`): feat(checkpoint): spans and metrics for partial-rollout checkpoints 11. NVIDIA-NeMo#3909 (`ananthsub/partial-ckpt-multi-worker`): feat(checkpoint): resources, agent, and environment servers with several workers 12. NVIDIA-NeMo#4197 (`ananthsub/partial-ckpt-fault-tests`): test(checkpoint): check checkpoint invariants over random sequences of operations Partial-rollout checkpointing lets a training controller, such as NeMo RL, checkpoint Gym while rollouts are in flight and, after a crash, continue those rollouts from their last safe point instead of starting them over. Checkpointing is off by default; with the `checkpoint:` block unset, no server installs any checkpoint routes or behavior. ## Relationship to the old stack (NVIDIA-NeMo#2939 to NVIDIA-NeMo#2946) None of NVIDIA-NeMo#2939 to NVIDIA-NeMo#2946 had these helpers. They are ported from NVIDIA-NeMo#3412 (prefix token-level recovery), which was built on the old stack; the wire contract is unchanged. ## Issue No tracking issue exists for this re-cut. The design and the mapping from the old stack are described in this PR series, and the old stack's PRs (NVIDIA-NeMo#2939 to NVIDIA-NeMo#2946) carry the original discussion. ## Validation Run on this branch, on the current `main`, which includes NVIDIA-NeMo#4213: - `test_workers_are_logged_by_pid_as_they_join_and_a_lost_one_as_a_warning`, `test_a_worker_lost_during_a_checkpoint_is_logged_as_blocking_its_commit` and `test_a_worker_that_stops_cleanly_is_not_reported_as_lost`: a worker connection dropped without notice is a warning, a clean stop is not; all three fail without the change, which logged nothing. - `test_generation_chunk_record_computes_staging_digest_once` and NVIDIA-NeMo#4213's `test_complete_call_computes_staging_digest_once`: each builder computes its digest once; all three cases fail with this PR's previous builders, which hashed before building the record. - `RAY_TMPDIR=/tmp .venv/bin/python -m pytest -q -p no:cacheprovider tests/unit_tests/test_checkpoint_*.py`: passed. - `RAY_TMPDIR=/tmp .venv/bin/python -m pytest -q -p no:cacheprovider tests/unit_tests/test_token_capture_*.py tests/unit_tests/test_token_id_capture.py tests/unit_tests/test_base_responses_api_model.py`: passed. `test_generation_cut_resume_rejects_a_prefix_built_on_other_parent_tokens` fails without the parent-token check. - The full core unit suite (`tests/unit_tests`, eight processes, without `test_opensandbox_compose.py`, which needs the optional `opensandbox` package): passed except a sandbox retry test, which fails the same way on `main` in this development environment. - `pre-commit run --files <files changed by this PR>`: all hooks passed, and no hook modified a file. - Every commit carries a `Signed-off-by` line. ## Rollout evidence - The end-to-end suite in the top PR uses these helpers in its fake inference worker, so the cut record Gym restores is validated exactly as a real worker validates it (generation-cut scenario). - A real vLLM worker serving generation cuts: **pending**. ## Compatibility Additive keyword arguments and new methods on `RolloutTokenCapture`; existing callers are unaffected. `complete_call` produces the same records as before. Signed-off-by: Ananth Subramaniam <[email protected]>
…ging The generation-cut staging series (#3883, #4213) and this branch added fields next to each other: main's capture_key beside this branch's finish_reason on CallRecord and on the ledger row read in lineage.py, and main's EpisodeId import beside this branch's incomplete_reason_for_finish_reason import in rebuild.py. Both sides are kept. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: alexandery <[email protected]>
What changed and why
Token capture encodes each token column for integrity hashing. Previously, those encoders packed one value at a time, and
RolloutTokenCapture.complete_callcomputed the staging digest before constructing a record whose validator computed it again. This PR speeds up the existing Gym capture path with two changes:struct.pack, retaining strict value checks, explicit big-endian widths, and the original length headers.StagedCallRecord.from_componentsand use it inRolloutTokenCapture.complete_call. Field, integrity, and extras validators still run, but a locally constructed record computes its staging digest once. Ordinary wire construction still requires and verifies a supplied digest, including when an unrelated validation context is supplied.Token-ID packing errors are translated to
ValueError, preserving the exception handling used by capture and reconstruction. Tests cover numeric edge cases, root and child capture, tamper detection, strict length types, and specific integrity failures.This PR targets Gym
maindirectly (base:7204f6badf8f4af54d6e480e0a46a0822dd7dc74) and requires no NeMo RL change or checkpoint-stack dependency. The encoded-prefix cache and its support code have been removed from the final diff; that optimization will be reviewed separately with its RL consumer. Existing hash formulas remain in their original functions. No separate issue is needed for this focused performance improvement to existing token capture.Observed performance
Historical single-node CPU contention measurements from October 6, 2026 motivate this change. They were collected on the experimental checkpoint stack before this PR was adapted to main, rather than against this exact Gym-main diff. The workload used one generation worker, 768 active sequences, four Simple TQ storage actors, 32 terminal writers, two finalizer consumers, 64 Torch threads, physical-core caching enabled, and audit I/O disabled. Token observation and terminal/read/retire traffic ran concurrently; prompt/prefix lengths were 2,048 / 8,192 / 32,768 / 65,536 tokens.
sink.terminal_putacross completed operationsMean
cut.build_cumulative_recordfell from 58.21 ms (1,536 observations) to 20.85 ms (2,304 observations). These are observations from single synthetic runs, not repeated controlled trials or isolated measurements of bulk packing alone. Completed work and checkpoint counts differ. The cut metric excludes fence drain and prefix readback; it is not full Gym prepare/commit or checkpoint-save latency. No TQ transport speedup is claimed. Both runs reported zero remaining staging rows after finalization.Cache-enabled measurements are excluded because the cache and companion RL integration are outside this PR's final scope. No new performance measurement against Gym main is claimed.
Compatibility
No schema, digest version, checkpoint format, or migration changes. Golden vectors and v2 wire bytes remain unchanged. Bulk/scalar byte comparisons cover empty and long columns, signed zero, subnormal and maximum finite float32 values, and maximum uint64 token IDs. Invalid types, nonfinite values, and float32 overflow remain rejected. Wire records still require a supplied digest and reject altered contents.
Validation
Commands were executed via
uv run --no-projectagainst the narrowed final code with a temporary Python 3.12.3 diagnostics environment; supported Python 3.13.14+ CI validation remains pending:python -m pytest -o addopts= -o log_cli=false -q tests/unit_tests/test_token_capture*.py tests/unit_tests/test_token_id_capture.py: 445 passed in 11.42 s.PRE_COMMIT_NO_CONCURRENCY=1 pre-commit run --all-files: passed. Serial hook execution avoids an existing README-generator race when multiple invocations write the same file. No README or hook changes are included.git diff --check: passed.complete_callregression tests.Rollout evidence
N/A for a new model-backed rollout: this changes CPU encoding and record construction, not agent/environment behavior. The historical contention measurements exercise capture and staging with synthetic generation and exclude GPU generation, Gym HTTP coordination, training, and checkpoint export.