Repository navigation
perf(checkpoint): batch obsolete prefix cleanup in background - #4655
macandro96 wants to merge 48 commits into
Conversation
|
/ok to test 6f488cb |
7eb9a01 to
a82e2a2
Compare
a82e2a2 to
5498a0a
Compare
6f488cb to
495ce13
Compare
terrykong
left a comment
There was a problem hiding this comment.
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:
- A bug when the flag is on: one failed CLEAR makes every later completion and checkpoint on that worker fail (inline on
_drain). - 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 onpause). 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:
- No CI has run on this head (495ce13). The only
/ok to testwas for 6f488cb, and that run failed lint in #4508-owned files. - A latency number for the gain (inline on
GenerationPrefixCleanupConfig).
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 (
RL/nemo_rl/models/generation/vllm/vllm_worker_async.py
Lines 3493 to 3498 in 495ce13
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
5498a0a to
acb663b
Compare
495ce13 to
bf39032
Compare
|
/ok to test bf39032 |
|
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 |
def6e59 to
c3eb2e4
Compare
bf39032 to
af5d065
Compare
|
/ok to test af5d065 |
…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]>
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]>
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]>
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]>
c3eb2e4 to
6c72a0f
Compare
Signed-off-by: Anish Mahishi <[email protected]>
- 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]>
af5d065 to
fd86c61
Compare
6c72a0f to
788133a
Compare
|
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
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 A rebase was not mechanical anyway: every function this PR changed has been removed or moved into the |
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-ioat6c72a0f19. Gym pin5911d628(unchanged from #4508).How it works
_TokenCaptureSnapshotGatepermit 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.max_pending) blocks that completion but holds no permit the fence waits on.batch_sizecompleted calls, waiting at mostwait_secondsfor more, deduplicates their keys and sends one CLEAR.Usage
Off by default. For vLLM prefix recovery:
The config rejects non-positive
batch_size/max_pending,max_pending < batch_size, a negative or non-finitewait_seconds, and unknown keys. Enabling cleanup requirestarget_level: prefixwith generation-prefix cuts; Megatron inference rejects it. Defaults live onGenerationPrefixCleanupConfig/RolloutRecoveryConfigonly, 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_cutand 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.
batch_size: 4batch_size: 32, wait_seconds: 0.01batch_size: 4batch_size: 16batch_size: 32, wait_seconds: 0.01These 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
max_pendingcounts 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 (aboutmax_pending + batch_size), the excess reply only after the fence ends.Testing
On
fd86c61e7(rebased onto #4508 at6c72a0f19), Gym at5911d628:--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_capturethrough 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.tests/functional/grpo_async_gym_single_controller_prefix_recovery.shwith++rollout_recovery.generation_prefix_cleanup.enabled=truepasses 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_rateandcapture_poisoned_rolloutsboth 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"
All commits include DCO sign-off.
🤖 Generated with Claude Code