Skip to content

perf(checkpoint): batch obsolete prefix cleanup in background - #4655

Closed
macandro96 wants to merge 48 commits into
amahishi/ckpt-v2-prefix-batched-iofrom
amahishi/perf-background-prefix-cleanup
Closed

macandro96 wants to merge 48 commits into
amahishi/ckpt-v2-prefix-batched-iofrom
amahishi/perf-background-prefix-cleanup

Conversation

@macandro96

@macandro96 macandro96 commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

When a captured call finishes after one or more generation-prefix cuts, its serving thread stages the canonical terminal row and then CLEARs the call's obsolete prefix chunks before replying. Both TQ calls run inside the token-capture snapshot gate, so a checkpoint fence waits for both. This PR optionally moves the CLEAR to a per-generation-owner background thread that batches deletes across calls. The completion returns once its canonical row is acknowledged, and the fence only waits for terminal writes plus at most one running CLEAR.

Stacked on #4508, targeting amahishi/ckpt-v2-prefix-batched-io at 6c72a0f19. Gym pin 5911d628 (unchanged from #4508).

How it works

  • PUT before CLEAR. The terminal staging path still waits for TQ to acknowledge the canonical row. Only then does the completion hand its obsolete generation-cut keys to the cleanup queue. As in perf(checkpoint): batch generation prefix TQ I/O #4508, a call's generation-cut rows are retired whether or not its terminal row staged, because a failed call restarts from its task or previous boundary, never from them.
  • The existing snapshot gate fences cleanup. The cleanup thread holds a _TokenCaptureSnapshotGate permit around each CLEAR. A fence waits for a running CLEAR, and no CLEAR starts while the gate is closed, so queued deletes wait until the fence ends. There is no separate pause/resume protocol.
  • Submit outside the gate. A completion submits its keys after leaving the gate. A full queue (max_pending) blocks that completion but holds no permit the fence waits on.
  • Batching. The thread takes up to batch_size completed calls, waiting at most wait_seconds for more, deduplicates their keys and sends one CLEAR.
  • Failures. A failed CLEAR is logged and dropped. It is never retried, because it may have partly succeeded, and it never affects later completions or checkpoints. A lost delete only leaves extra obsolete rows.
  • Aborted calls are unchanged. The base stack clears an aborted call's generation-cut rows on its own per-call cleanup thread, behind the same gate. This PR batches the completion path only.
  • Canonical rows are protected on both paths. A canonical row restored through a terminal-completion cut may still be referenced by Gym's imported ledger. Only generation-cut keys count as obsolete, whether cleanup runs inline or in the background.

Usage

Off by default. For vLLM prefix recovery:

rollout_recovery:
  target_level: prefix
  generation_prefix_cleanup:
    enabled: true
    batch_size: 32
    max_pending: 128
    wait_seconds: 0.01

The config rejects non-positive batch_size/max_pending, max_pending < batch_size, a negative or non-finite wait_seconds, and unknown keys. Enabling cleanup requires target_level: prefix with generation-prefix cuts; Megatron inference rejects it. Defaults live on GenerationPrefixCleanupConfig/RolloutRecoveryConfig only, and are documented in both single-controller exemplars and the guide. The knobs are excluded from the bootstrap fingerprint, so they can change on resume.

Performance

A harness (not a training run) drove the real worker code: VllmAsyncGenerationWorkerImpl._finish_request_capture, the snapshot gate and fence, _checkpoint_generation_cut and this PR's cleanup, against a real Simple-TQ deployment, with no vLLM engine. Each worker completes a burst of calls with two pre-cut prefix chunks each. The checkpoint fence closes with a fixed number of completions in flight per worker. The setup was 2 H100 nodes, 16 workers and 2 storage units (8 workers per storage unit, the ratio planned for 128 workers on 16 units), with 3 repetitions per arm in rotated order.

"Fence released" is the time from trigger until every worker's fence is released, including draining in-flight completions and cutting 64 active calls per worker. "All work done" is the time from the burst starting until every completion and every delete has finished.

In flight per worker Arm Fence released All work done Delete RPCs
64 inline (default) 2.63 s 11.3 s 3072
64 background, batch_size: 4 1.40 s 7.7 s 784
64 background, batch_size: 32, wait_seconds: 0.01 1.44 s 5.5 s 116
128 inline (default) 7.93 s 35.3 s 6144
128 background, batch_size: 4 2.48 s 18.0 s 1552
128 background, batch_size: 16 2.30 s 11.9 s 400
128 background, batch_size: 32, wait_seconds: 0.01 2.55 s 11.3 s 208
  • Moving deletes out of the gate is what shortens the fence: 1.8× at depth 64 and 3.1× at depth 128. Inline deletes double the storage calls each in-flight completion makes inside the fence, so the gap widens with depth.
  • Batching is what keeps deletes from backing up. In a separate run at depth 128, one call per CLEAR released the fence in 3.6 s but took 46.6 s to finish all work, which is later than inline.
  • Every trial verified that all canonical and cut rows were readable and no obsolete rows remained. Some fences closed while a background CLEAR was running and correctly waited for it.

These are harness numbers, not end-to-end training numbers. In a 1-node GRPO run with 64 calls in flight, step time was unchanged, because fences there are short.

Limitations

  • The cleanup queue is process-local and not checkpointed. A crash or actor shutdown can leave extra obsolete rows, never a missing required prefix. There is no orphan collection.
  • max_pending counts calls, not keys or bytes. It bounds memory if deletes fall behind; it never delays a checkpoint, because completions submit after leaving the gate and Gym's cut acknowledges an already-staged call without waiting for its reply. If more completions are inside the gate when a fence closes than the queue can take (about max_pending + batch_size), the excess reply only after the fence ends.
  • A fence still waits for an already-running CLEAR, and a completion can still wait for queue space or for its terminal PUT.
  • The cleanup thread is a daemon and is never joined. As with synchronous cleanup, a stalled delete can still delay actor shutdown while completions wait on a full queue.

Testing

On fd86c61e7 (rebased onto #4508 at 6c72a0f19), Gym at 5911d628:

  • ruff check/format and every pre-commit hook pass, including pyrefly with the new module in the allow-list.
  • Gym lane (--nemo-gym-only): vLLM and Megatron token-capture hosting, prefix read batcher, TQ token sink, background cleanup and captured media: 416 passed. The hosting tests drive the real _finish_request_capture through a failed CLEAR, a full queue during a fence (a mutation that submits inside the gate makes the fence time out) and a restored canonical row on both cleanup paths.
  • Default lane: background cleanup, generation interfaces, single-controller setup and rollout checkpoint: 398 passed.
  • Functional: tests/functional/grpo_async_gym_single_controller_prefix_recovery.sh with ++rollout_recovery.generation_prefix_cleanup.enabled=true passes locally: 8/8 rows match the uninterrupted run, no restored row whose phase-1 prefix differed from the reference, 8 restored prefixes (148–229 tokens), 99.09% bit-identical generation logprobs over 9,312 tokens (max |diff| 0.18), invalid_row_rate and capture_poisoned_rollouts both 0, and no failed cut, fallback regeneration or failed clear in the log. The cleanup thread logs only failures, so the run shows the path was enabled and no CLEAR failed, not a count of batched deletes.

Before your PR is "Ready for review"

  • Read the contributor guidelines.
  • Added focused concurrency, failure, config and worker tests.
  • Ran the full unit suite in the supported runtime. (The prefix-recovery GPU functional test passes; see Testing.)
  • Added usage and lifecycle documentation.

All commits include DCO sign-off.

🤖 Generated with Claude Code

@macandro96 macandro96 added the CI:L0 Run doctests and unit tests label Oct 10, 2026
@copy-pr-bot

copy-pr-bot Bot commented Oct 10, 2026

Copy link
Copy Markdown

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

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test 6f488cb

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Oct 10, 2026
@macandro96
macandro96 force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from 7eb9a01 to a82e2a2 Compare October 12, 2026 23:10
@macandro96
macandro96 added this pull request to stack #4686 October 12, 2026 23:32
@macandro96
macandro96 force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from a82e2a2 to 5498a0a Compare October 15, 2026 02:17
@macandro96
macandro96 force-pushed the amahishi/perf-background-prefix-cleanup branch from 6f488cb to 495ce13 Compare October 15, 2026 02:17

@terrykong terrykong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for splitting this out as an opt-in, off by default, with the PUT-before-CLEAR order and capacity reservation outside the terminal gate spelled out. The docs and exemplar YAMLs are updated, and the config validation fails loudly.

Two main points:

  1. A bug when the flag is on: one failed CLEAR makes every later completion and checkpoint on that worker fail (inline on _drain).
  2. Size: this adds a 253-line module whose pause/resume fence repeats _TokenCaptureSnapshotGate. Holding that gate around each CLEAR brings the module to about 25 lines and removes the 4 worker hooks (inline on pause). This is the same ask as the #4501 review ("check whether the stack already has one", #4501 (review)), and it answers part of the open design question in the #4506 review (#4506 (review)) about why the delete has to run during a checkpoint. The feature stack is already ~20k lines, so cuts here add up.

Before merge:

Small PR-description fixes: the Gym pin at head is 34ac4533, not 120d516f. And shutdown does not avoid an endless wait on a stalled CLEAR: close(wait=False) runs after the HTTP server join (

if self.server_thread is not None:
self.http_server.should_exit = True
await asyncio.to_thread(self.server_thread.join)
self.server_thread = None
if prefix_cleanup is not None:
prefix_cleanup.close(wait=False)
), and handlers blocked on a full queue keep that join waiting. The sync path had the same hang, so it predates this PR; just drop the claim.

Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4655-size-and-reuse.html
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-4655-failed-clear.html

Generated by Claude Code

Comment thread nemo_rl/models/generation/interfaces.py Resolved
@macandro96
macandro96 force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from 5498a0a to acb663b Compare October 19, 2026 01:53
@macandro96
macandro96 force-pushed the amahishi/perf-background-prefix-cleanup branch from 495ce13 to bf39032 Compare October 19, 2026 20:06
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test bf39032

@macandro96

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All seven threads are addressed in bf39032 (rebased onto #4508 at def6e59), and the description is updated: gate-based design, Gym pin 25062eb1, the shutdown claim replaced with the actual caveat, and latency numbers. CI is triggered on bf39032. It will likely show #4508's existing failures, including test_omni_capture_setup_rejects_video_pruning[0.0-*] (_fetch_generation_cut_rows missing on the test's fake worker), which fails the same way on #4508's head.

@macandro96
macandro96 requested a review from terrykong October 19, 2026 20:40
@macandro96
macandro96 removed this pull request from stack #4686 October 20, 2026 14:59
@macandro96
macandro96 added this pull request to stack #4819 October 20, 2026 14:59
@macandro96
macandro96 force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from def6e59 to c3eb2e4 Compare October 21, 2026 00:37
@macandro96
macandro96 force-pushed the amahishi/perf-background-prefix-cleanup branch from bf39032 to af5d065 Compare October 21, 2026 00:46
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test af5d065

@macandro96
macandro96 removed this pull request from stack #4819 November 2, 2026 22:19
@macandro96
macandro96 added this pull request to stack #5032 November 2, 2026 22:50
macandro96 and others added 7 commits November 2, 2026 14:52
…nd rollout snapshots

The full trainer checkpoint and the rollout snapshot each built the replay
metadata, validated the replay and staging inventories, built, serialized
and hashed the recovery ledger, saved TQ and wrote the same sidecar files,
in two copies. Both now call _capture_rollout_state(cut, path, kind) under
their exclusive cut and write sidecars through _write_controller_sidecars.

The kind keeps the real differences:
- a trainer checkpoint saves TQ only with checkpointing.save_data_plane,
  refuses rows a streamed step still owns, saves replay metadata only for a
  sampler that restores buffered groups, and the ledger only while dispatch
  records prompt groups;
- a rollout snapshot always saves all three and re-indexes training-owned
  rows into the persisted cut.

Behavior is unchanged. Two details move within the exclusive cut: the
trainer checkpoint reads the dataloader state and spare pool after
init_tmp_checkpoint rather than before it, and rollout snapshots write
sidecars with the MSC-aware save helpers trainer checkpoints already used
(torch.save for local paths, as before).

single_controller.py: +127 / -183. Tests: one call site renamed.
Unit: 2048 passed (default lane), 98 passed (Gym lane), as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…RuntimeState

The spare-prompt pool, the per-step shortfall, whether the sampler stamps
target steps, and the retained finalizer metrics and rewards were five
separate controller attributes that the pumps change, checkpoints save and
restore fills. They now live in one RolloutRuntimeState the controller owns
as self._rollout_runtime, so the checkpoint code extracted next can read and
fill one object instead of five controller fields.

Behavior is unchanged: every access is renamed, and a field that was
reassigned (restore's shortfall and finalizer dicts, the train pump's
shortfall rebuild) is now reassigned on the shared object. The per-field
comments move onto the dataclass.

Test fixtures that build the controller with object.__new__ create a
RolloutRuntimeState only where a test reaches these fields (22 fixtures),
and drop the lines that reset a field to its default. The pump tests'
_init_pump_ledgers helper creates one when its controller has none.

single_controller.py: +103 / -69. Tests: +120 / -79.
Unit: 2048 passed (default lane, all of tests/unit/single_controller plus
the rollout-recovery, rollout-manager and Gym-checkpoint suites), 98 passed
(Gym lane), as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…checkpoint interface

The controller built the Gym checkpoint coordinator, owned Gym's dispatch
gate, retired and forgot Gym episodes, drained on-wire replies, validated
the Gym manifest against the TQ cut, parsed gym_checkpoint.json on restore,
and branched on whether a Gym coordinator existed. All of it moves behind
EnvironmentCheckpoint:

- nemo_rl/environments/checkpointing/interfaces.py: the backend-neutral
  contract (check_startup, snapshot, restored, is_unavailable,
  holds_rollout_state) and NoEnvironmentCheckpoint for backends that keep
  no rollout state;
- nemo_rl/environments/checkpointing/nemo_gym.py: GymEnvironmentCheckpoint,
  wrapping the existing coordinator, adapter and checkpoint format;
- nemo_rl/environments/checkpointing/__init__.py: picks the backend once,
  from rollout_recovery.turn_checkpointing_enabled, as before.

The controller now pauses, snapshots, validates and restores the
environment only through that interface.

Behavior is unchanged, including telemetry: the snapshot outcome reason for
a briefly unreachable environment keeps its old name, gym_unavailable, so
existing dashboards keep working. Error and warning texts that named Gym in
the controller now come from the Gym module.

Tests that exercised only the Gym checkpoint, through a bare controller,
move to tests/unit/environments/test_gym_environment_checkpoint.py and
build GymEnvironmentCheckpoint directly. New builder tests cover the
backend choice, the dispatch gate installed on the rollout manager, and
the staging partition the Gym checkpoint lists.

Source: +867 / -530. Tests: +1203 / -980.
Unit: 2050 passed (default lane; 2048 as before plus the 2 builder tests),
98 passed (Gym lane). ruff and pyrefly clean.

Co-authored-by: Terry Kong <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…ting package

The controller held the save lock shared by trainer checkpoints and rollout
snapshots, the optimizer-commit window snapshots skip, the snapshot pump,
the TQ capture and sidecar writer, outcome telemetry and warnings, and
eight fields of snapshot state. All of it moves into a package:

  nemo_rl/algorithms/rollout_checkpointing/
      state.py      runtime and captured state, TrainingProgress, and
                    RolloutParts: the controller parts it reads
      inventory.py  TQ inventory checks, which restore (still in the
                    controller) runs too
      snapshots.py  RolloutSnapshotter: save lock, optimizer-commit
                    window, capture, snapshot pump and publication
      manifest.py   snapshot manifests, anchors, publication and
                    retention (moved from single_controller_utils/
                    rollout_checkpoint.py)

The controller builds RolloutParts once and calls the snapshotter:
- run() and stop_requested in _run_pumps;
- begin_optimizer_commit(drain_snapshot=...) and end_optimizer_commit()
  where the train pump opened and closed the window;
- trainer_checkpoint() in place of the save lock, around a trainer
  checkpoint's save and around a deferred save's publish;
- trainer_checkpoint_published() where the controller woke the snapshot
  pump once a trainer checkpoint was published, which it still does only
  when the environment holds rollout state;
- capture() and write_controller_sidecars() in _save_checkpoint_impl.
capture() also records the trainer checkpoint's TQ mutation version, which
_save_checkpoint_impl used to do.

The snapshotter reads training counters through a read_progress callback,
never controller fields. save_snapshot names its two phases:
_resolve_anchor (bootstrap or step_<N> anchor, or a skip when it is not
durable yet) and _publish (sidecars, config and manifest, then the atomic
commit under retention). manifest.py imports MasterConfig for annotations
only, because single_controller_utils, whose setup imports it, would
otherwise import it back.

Behavior is unchanged: the window, lock and wakeup open and close at the
same points, telemetry keys and log lines are the same, and the anchor
phase reads the training counters once where the old code read them
several times with no await in between.

Tests reach the moved state through controller._rollout_snapshots.
Controllers built without __init__ get one from
tests/unit/single_controller/_rollout_checkpoints.py, and tests that swap
the environment checkpoint rebuild it, as __init__ would.

Source: +1355 / -920 (single_controller.py 6232 -> 5403 lines; package
1932 lines including the 676-line manifest module that moved in).
Tests: +250 / -102.
Unit: 2050 passed (default lane), 98 passed (Gym lane), as before.
ruff and pyrefly clean; each new module imports on its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
Replay-buffer restore, recovery-ledger restore (including the environment
restore scope), spare-prompt restore, prompt rehydration, the sampler
cursor check, restore metrics and the redispatch of restored groups move
from the controller into RolloutRestorer in
nemo_rl/algorithms/rollout_checkpointing/restore.py.

It is built from the same RolloutParts as the snapshotter; the two halves
share only those read-only inputs and never call each other. The controller
now calls:
- restore() once in _run_pumps, after the weight sync, in place of the
  five-call chain. It fills the shared RolloutRuntimeState directly and
  takes one replay-capacity permit per restored group, at the same point
  as before; it returns whether restore queued groups only ledger-recorded
  dispatch can launch, and the controller then turns that dispatch on;
- redispatch_restored(launch, admit) from the rollout pump, passing its
  launch and sampler-admission callbacks.

The restore-only controller fields are gone; the restorer gets the
resumed checkpoint's path, kind, TQ metadata and load timings from setup,
and owns the queue of replay groups to regenerate. Reading and verifying
the recovery-ledger sidecar is a plain function, read_recovery_sidecar.
Method names drop the controller's _maybe_ prefixes.

Behavior is unchanged. The only reordering: ledger dispatch is now turned
on when restore() returns rather than inside it, and no restore step reads
it.

Tests drive restore through controller._rollout_restorer; tests that
build the controller without __init__ attach it from the controller's
parts, carrying the restore inputs.

Source: +868 / -733 (single_controller.py 5403 -> 4716 lines;
restore.py 820 lines). Tests: +178 / -53.
Unit: 2050 passed (default lane), 98 passed (Gym lane), as before.
ruff and pyrefly clean.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…h path

The rollout pump kept two copies of the dataloader loop and of the
end-of-run spare-pool drain, one recording each prompt group in the
recovery ledger and one not, and branched on _rollout_recovery_enabled in
seven places across the pump, the drain, the stale-group abort and the
finalizer's drop path.

Each now exists once. Three small helpers make the difference in one place:
- _dispatch_reservation(kind) holds a data-plane mutation cut, counted as
  kind, only with ledger dispatch; otherwise it takes no mutation slot and
  yields None;
- _reserve_prompt_group / _discard_prompt_group record in the ledger under
  that cut, or do nothing without one (the rollout manager then mints the
  group ID, as before);
- _admit_step admits a step through the sampler: the ledger's transactional
  admission with ledger dispatch, the sampler's own admit() otherwise.

Ledger dispatch is unchanged: the same mutation kinds over the same
statements, with no await moved inside a cut. Without it, three small
differences, none of which changes what is trained:
- the end-of-run drain now marks the sampler as stamping target steps when
  it stamps, as the dataloader loop always did; the flag only gates
  diverting batches into the spare pool, and the drain runs after the last
  epoch;
- a dropped prompt's replacement borrows from a later step before the
  "substituting a spare prompt" log line rather than after it, so the
  line names the step the spare commits to, as it did with the ledger;
- a prompt with no spare left credits its step short just before, rather
  than just after, releasing its replay-capacity permit; nothing awaits
  in between.

New test: unrecorded dispatch takes no mutation slot and records nothing.

single_controller.py: +123 / -128 (4716 -> 4711 lines). Tests: +49.
Unit: 2051 passed (default lane; 2050 as before plus the new test),
98 passed (Gym lane). ruff and pyrefly clean.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
RolloutRestorer took the resumed checkpoint as four separate
arguments: its path, whether it is a rollout snapshot, its native TQ
metadata and setup's load timings. They always travel together and only
restore reads them, so they become one frozen ResumeSource whose defaults
describe a fresh run.

Behavior is unchanged.

Tests set controller._resume = ResumeSource(...) instead of four
controller fields, and the test helper reads that one value instead of
a table of field names with fresh-run fallbacks.

Source: +41 / -44. Tests: +115 / -105; roughly line-neutral because a
ResumeSource call wraps over more lines than the assignments it replaces.
Unit: 2051 passed (default lane), 98 passed (Gym lane). ruff and pyrefly
clean.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
macandro96 and others added 5 commits November 3, 2026 16:22
Parity data and gates:
- Compare runs on the trainer's own async_rl.log_full_train_data dump
  (read from the run's exp_NNN directory) instead of a recorder in the
  hook; the hook now only probes live staging keys per train step.
- Require exact parity for every row. The one exception is a restored
  row whose phase-1 prefix already differed from the reference before the
  cut (vLLM sampling is not batch-invariant): it must start with exactly
  the restored tokens (prefix_ids_sha256), match up to its closing call,
  and keep its reward and admission; at least one restored row must match
  outright.
- Gate generation logprobs on bit-identical fraction and max |diff|.
- Default to one train step and say the test checks data, not learning
  (top_p=1e-6 zeroes the policy gradient).

Removed: the ordering/timeline/Kendall report, the hand-rolled
Spearman/Pearson gate and parity-report.json, the metric comparison, the
prefix+tail==total tautology, the duplicate trained-once check, the
unreachable successor Gym-manifest check, the single-cut selection
fallback, and the swallowed Workplace layout errors. The JSON readers and
the restored-prefix log parser are shared in _gym_recovery_snapshot_helpers.
The L1 runner comment now says the test performs three runs.
The Workplace calendar sentinel count lives with the shared readers, and the
Workplace test rows are built by one jq module (_workplace_calendar_rows.jq).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…agent

Gym main has no checkpoint test agent, so the prefix-recovery parity test
now runs the stock workplace_assistant_simple_agent behind the test hook's
policy proxy, as the turn-recovery test does. With no hold and no
follow-up tool, the proxy sends every call after the tool result with
tool_choice none and leaves its length to the model, which is what the
test agent did for the closing turn.

Gym only cuts a call whose decoding is unconstrained, judged from the
request its agent sends, so the rows leave tool_choice auto instead of
forcing calendar_create_event: a forced tool would keep every turn out of
the cut. The prompt asks for the call, and the snapshot selector already
requires the calendar write to have happened exactly once.

The rows name workplace_assistant_simple_agent, the script drops the test
agent's config_paths override and environment-server removal, and the
hook writes the proxy's events to the prefix test's events file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…y active call

The snapshot records only the cuts that succeeded, so a snapshot where Gym
failed or skipped an active call's cut still qualified, and that call
quietly regenerated after the restore. Read the trainer's save line for the
snapshot and require zero failed and skipped cuts; a bug that keeps failing
cuts now times out the selection with the counts instead of passing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…identical

On Gym main's Workplace agent the workload generates ~9.3k tokens, and four
runs scored 98.89-99.13% bit-identical with every exact token, mask and
reward gate passing; three fell below the old 99% floor across three
different progress-read implementations. The bf16 noise floor is a property
of the smaller workload, not of the restore, so the gate now sits at 98%.
The max-|diff| bound stays at 0.5.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…s end

The prefix-recovery parity checks located a restored call at the start of
its row's last unmasked segment. When top-k/top-p filtering is on, the
trainer drops positions whose recomputed logprob is -inf from token_mask
(#4154), and the rows these checks read are dumped after that pass, so a
masked token inside the call made the check start the call too late,
miscount its tokens, and fail a correct restore.

A restored call closes its row, so the total_generation_tokens it logs on
completion end the row. _assert_prefix_boundary now counts back from the
row's end, requires the token before the call to be untrained, checks the
completion's prefix + tail = total accounting, and requires the restored
prefix at that position; a dropped or duplicated token moves the position.
It returns where each call starts, which _rows_diverged_before_cut reuses
to compare the reference row at the same position.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
@macandro96
macandro96 added this pull request to stack #5057 November 4, 2026 19:47
macandro96 and others added 9 commits November 4, 2026 12:00
Lift the setup refusal of generation-prefix recovery with media capture.

A media call's first durable prefix row carries its media spans and a
SHA-256 digest of each packed media tensor in its extras, not the
pixels; later chunks carry no media. The restored prefix digest covers
those extras. On restore the worker reads the items and digests from
that row, reprocesses the reissued request's media, checks it against
them (retained_media_changed on a mismatch), and stages the reprocessed
tensors in the canonical terminal row. A row whose media metadata
cannot be read makes the call regenerate from its turn boundary.

Adds an Omni CLEVR multimodal prefix-recovery functional test, unit
coverage of media cuts, races and restores, and shares the prefix
recovery functional phases (_gym_prefix_recovery_phases.sh).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
Lift the setup refusal of generation-prefix recovery with router replay.

A cut reads the live call's routes from vLLM after freezing its tokens and
stages one route per chunk token on its chunk row; each chunk's own digest
covers its routes, and the advertised prefix digest covers tokens and call
extras only. A cut converts only the route pieces vLLM appended since the
call's last cut, so its cost follows the new tokens, not the prefix. 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.

Uses Gym main's chunk extras (NVIDIA-NeMo/Gym#4726), adds a tiny-MoE
router-replay prefix-recovery functional test to L1, and unit coverage of
cuts, races, resumes and the engine-loop route read. 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]>
…re-copying it

Each cut joined the route pieces vLLM appended since the call's last cut,
then torch.cat'ed them onto every row already joined, so a cut still copied
the call's whole route history. Keep the joined routes in a buffer that
doubles when full and copy only the new rows into it; a cut now costs the
rows decoded since the previous one, and the total copying is linear in
the request's length. The returned routes are a view of the buffer, and
rows already returned are never written again.

New pieces are joined in one numpy concatenate in vLLM's own dtype, so a
cut checks them in C rather than one piece at a time in Python; pieces of
mixed dtypes fall back to per-piece checks. vLLM publishes unsigned expert
IDs (uint8, or uint16 past 256 experts) and the cache keeps the signed
checkpoint dtype for the -1 placeholder, so IDs that do not fit it are
rejected instead of wrapping onto a wrong expert.

Also reject a route piece vLLM replaced after it was joined (the last
joined piece must still be the same object) and non-integer route pieces.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
A cut read each router-replay call's routes by queuing a callback onto
vLLM's engine loop and waiting for it, behind everything else on that
loop: 7-21 s per cut in live runs, single reads up to 31 s. Prefix cuts
already read every call's new tokens once per inventory, under the output
lock vLLM's process_outputs runs under. Copy each router-replay call's
route pieces in that same lock hold, from the request state its tokens
come from: a cut waits on vLLM once however many calls it holds, a call's
routes come from the output boundary its tokens do, and a call vLLM has
just finished is read from the state kept until its consumer has the
final output. Calls whose final output already carries routes are not
copied.

The engine-loop read, its per-call request lookup and its setup check go
away. The base's progress-read setup already pins the vLLM release whose
fields these reads use, and every call the read cannot supply routes for
fails its cut the same way the per-call read did.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…refix I/O tests

NeMo Gym's GenerationCutPrefix names its attempt attempt, as EpisodeId
does; it was attempt_index.

Signed-off-by: Ananth Subramaniam <[email protected]>
- PrefixReadBatcher: a failed multi-key GET re-reads each key alone, once,
  for any error, so one bad row fails only its own callers and a TQ outage
  costs N+1 GETs instead of 2N-1.
- Reads are capped by rows only. Every key was charged max_model_len
  tokens, so the token budget silently acted as a ~32-key cap tied to the
  write knob.
- One cut path: every cut goes through the batched transaction loop
  (batch size 1 writes one row per put). Remove
  _checkpoint_active_generation_cut and TQTokenSink.stage_generation_prefix.
- stage_generation_prefix_batch raises on the first failure and returns the
  written keys. A failed put discards every key of the batch; flush() clears
  written rows whose transaction never sealed. The transaction receives the
  staged key instead of a StageResult.
- Config defaults live only on RolloutRecoveryConfig: setup_token_capture
  and PrefixReadBatcher take the limits without defaults, and
  GenerationPrefixBatchLimits with its helpers is gone (Field(gt=0) already
  validates).
- Drop the benchmark tools and their test; results go in the PR description
  and the tools live on amahishi/ckpt-v2-prefix-io-benchmarks.

Signed-off-by: Anish Mahishi <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The class-qualified calls only existed so a SimpleNamespace test fake could
run them. #4506 replaced that fake with a real worker; the two setup tests
that build the prefix reader now use one too (_real_worker), so production
code calls the method on self.

Signed-off-by: Anish Mahishi <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The base now acknowledges a call that cannot be cut as a durable_failure
and lets it regenerate after a restore, instead of failing the receipt for
every call on the worker. Do the same in the batched path:

- A failed freeze, acknowledgement or seal fails only its own call. A cut
  frozen before the transaction's rollback scope begins is released by the
  caller, as the base's per-call loop did.
- A failed batch put is retried one row per put (the sink has already
  discarded the batch), so one bad row fails only its own call.
- Rows written but never handed to a call, which only an interruption can
  leave, are still cleared.

Restores take the base's regenerate-on-failure path: the worker's batched
reader fetches the chunks and _resolve_usable_generation_cut uses them,
reading the rows alone if the shared read failed.

Signed-off-by: Anish Mahishi <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@macandro96
macandro96 force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from c3eb2e4 to 6c72a0f Compare November 5, 2026 00:02
macandro96 and others added 2 commits November 4, 2026 16:13
- Fence background CLEARs with the existing token-capture snapshot gate:
  the cleanup thread holds a gate permit around each CLEAR, so a fence
  waits for a running CLEAR and no CLEAR starts while the gate is closed.
  This drops the module's own pause/resume epochs and the four worker
  hooks that drove them.
- A failed CLEAR is logged and dropped, never retried or latched, so one
  failed delete no longer fails every later completion and checkpoint on
  the worker. A lost delete only leaves extra rows.
- Completions submit their obsolete keys after leaving the gate, so a full
  cleanup queue blocks that completion without holding a permit the
  snapshot fence waits on.
- Remove stats()/PrefixCleanupStats, which had no production reader.
- Both cleanup paths keep a restored terminal-completion canonical row:
  only generation-cut keys are obsolete, whether or not the terminal row
  staged. Previously only the background path skipped it.
- setup_token_capture takes generation_prefix_cleanup without a default;
  RolloutRecoveryConfig is its only default, as for the batch limits.
- Docs: the guide describes the gate design and no longer claims shutdown
  avoids waiting on a stalled CLEAR; docstring order matches the signature.
- Tests drive the real _finish_request_capture through a failed CLEAR, a
  full queue during a fence, and a restored canonical row on both paths.

Signed-off-by: Anish Mahishi <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@macandro96
macandro96 force-pushed the amahishi/perf-background-prefix-cleanup branch from af5d065 to fd86c61 Compare November 5, 2026 01:07
@terrykong terrykong added CI:L1 Run doctests, unit tests, and functional tests CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) and removed CI:L0 Run doctests and unit tests CI:L1 Run doctests, unit tests, and functional tests labels Nov 5, 2026
@macandro96
macandro96 force-pushed the amahishi/ckpt-v2-prefix-batched-io branch from 6c72a0f to 788133a Compare November 11, 2026 04:51
@macandro96

Copy link
Copy Markdown
Contributor Author

Closing as superseded by #4506 (merged), which now handles obsolete generation-cut rows with a retire-and-flush design.

Why this PR is no longer needed

  • No delete on the completion path. A finished or aborted call calls PrefixRecovery.retire(keys), which only appends the keys to an in-memory list (nemo_rl/models/generation/prefix_recovery/recovery.py).
  • No delete inside the checkpoint fence. At the start of the next snapshot, before Gym's admission gate closes, each worker deletes everything retired so far in a single sink.clear on its cleanup thread. An epoch check keeps a late flush from deleting rows a newer snapshot may still name, and a failed delete is logged and dropped.
  • Better batching and no settings. That is one CLEAR per worker per snapshot, with no queue, background thread or generation_prefix_cleanup config.

The measurements in this PR still apply: moving deletes off the fence cut fence time 1.8–3.1× at 8 workers per storage unit. #4506's design gets that win without this PR. What this PR would still add is deleting rows promptly instead of at the next snapshot, and avoiding the one bulk CLEAR at snapshot start. Neither has shown a measured cost, so it doesn't justify the extra machinery.

On @terrykong's review: thanks. The gate, failure and test feedback shaped the design, and the …953 canonical-row concern does not carry over. In #4506's design, a restored terminal_completion call is re-issued with a new model call ID and commits a new canonical row under a new key. Gym drops the restored cut once that call's response starts, and if a snapshot cuts the call before then, it exports the new key instead. So the old row is unreferenced by the time the next snapshot's flush deletes it.

A rebase was not mechanical anyway: every function this PR changed has been removed or moved into the prefix_recovery package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants