Skip to content

perf(checkpoint): defer rollout and trainer data-plane persistence - #5139

Merged
terrykong merged 9 commits into
mainfrom
amahishi/async-tq-rollout-snapshots-main
Nov 20, 2026
Merged

terrykong merged 9 commits into
mainfrom
amahishi/async-tq-rollout-snapshots-main

Conversation

@macandro96

@macandro96 macandro96 commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack

PR 2 of 2, based on #5137. Review this PR against the foundation branch; merge #5137 first, then retarget this PR to main.

Rebased onto main at bf50129f25 on 2026-11-19 (CI allows at most 10 commits behind main); the commit SHAs below are the rebased ones. 262 tests across every test file this PR touches, tests/unit/telemetry/test_metrics.py (49) and the Gym-marked lane (7) passed after the rebase; Ruff and Pyrefly passed.

Summary

  • Integrate the two-phase data-plane API into RolloutSnapshotter: capture TQ and detach matching recovery metadata under the barrier, resume the environment/dispatch, then persist the retained storage view before publishing the snapshot.
  • Extend the same retained-view path to full trainer checkpoints in a separate follow-up commit (57daccd49b): capture under the controller mutation barrier, then persist and release after the barrier opens, before model saves and publication. Canonical TQ writes can resume during persistence; the trainer save itself still awaits it.
  • Keep temporary ownership in a separate SnapshotCapture wrapper, with failure/cancellation cleanup. CapturedRolloutState remains recovery metadata only. Rollout snapshot metrics split capture/persist/release timing.
  • Serialize and hash the rollout-recovery state after the barrier opens, in separate commits (a211758851, with the persist(extra_metadata=...) API from 12da50adad). See Recovery serialization after resume.

Scope

Changes relative to #5137 are limited to the snapshot coordinator, single-controller trainer-save integration, tests, and documentation. No Gym, prefix-cut, router-replay, writer-actor, or launcher dependency.

The deferred path requires data_plane.simple.async_checkpoint: true, with SSD offload disabled. Trainer checkpoints additionally require checkpointing.save_data_plane: true. Unsupported adapters/configurations keep their synchronous behavior. Trainer checkpoints do not pause Gym or capture in-progress Gym sessions: the controller barrier protects recovery-owned rows, not every live staging write. Environment recovery still requires a rollout snapshot.

The snapshot-save lock remains held through publication, so optimizer commits can still wait. This change moves TQ persistence outside mutation/environment pauses, not the whole trainer save into the background.

Flow

A rollout snapshot with data_plane.simple.async_checkpoint: true. The shaded block is the data-plane barrier: TQ mutations are drained and blocked, and Gym stays parked.

sequenceDiagram
    participant S as RolloutSnapshotter<br/>(controller event loop)
    participant G as Gym
    participant T as Worker thread
    participant C as TQ controller
    participant U as TQ storage units

    S->>G: Close admission, prepare, export episodes, drain replies
    rect rgba(255, 170, 0, 0.15)
        Note over S,U: Data-plane barrier held, Gym parked
        S->>C: KV_LIST(replay), compare with the replay index
        S->>S: Build the detached recovery state from the ledger
        S->>C: KV_LIST(staging), compare with recovery ownership
        S->>C: Serialize controller metadata to bytes
        S->>U: Retain shard views
        Note over S: Copy dataloader, reserve and replay metadata
    end
    S->>G: Release the barrier, resume Gym and dispatch
    Note over S,U: Rollouts run again from here
    S->>T: torch.save + sha256 of the recovery state
    par Persist TQ
        S->>C: Write controller bytes
    and
        S->>U: Write retained shards
    end
    S->>S: Write metadata.json with the recovery digest (persist extra_metadata)
    S->>C: Release views
    S->>U: Release views
    S->>S: Write sidecars and manifest, publish the snapshot
Loading

Trainer checkpoints with checkpointing.save_data_plane: true take the same steps without Gym, and finish persisting before the model save. Backends without a retained view keep main's flow:

flowchart LR
    subgraph main["main: everything under the barrier"]
        direction LR
        m1["Replay inventory"] --> m2["Ledger build"] --> m3["torch.save + sha256"] --> m4["Staging inventory"] --> m5["TQ save<br/>(write every shard)"]
    end
    subgraph pr["This PR: retained view, writes after resume"]
        direction LR
        p1["Replay inventory"] --> p2["Ledger build"] --> p3["Staging inventory"] --> p4["TQ capture<br/>(retain views)"] --> p5(["Barrier released,<br/>Gym resumes"]) --> p6["torch.save + sha256"] --> p7["TQ persist<br/>+ metadata.json"]
    end
Loading

Barrier phase timing

e95dbedb8d splits the rest of the rollout-snapshot barrier hold, beyond the TQ capture, into four timing/rollout_checkpoint metrics:

Metric Phase
replay_inventory_seconds Compare TQ replay keys with the replay index
recovery_state_build_seconds Copy and validate the rollout-recovery ledger
recovery_state_serialize_seconds torch.save and sha256 of that state; after the barrier with a retained view since a211758851, inside it otherwise
staging_inventory_seconds Compare TQ staging keys with recovery ownership

A phase that does not run for the configuration logs 0. tq_persist_seconds excludes the recovery serialization that precedes the write. These four and tq_capture_seconds, tq_persist_seconds, and tq_release_seconds are also registered as rl.checkpoint.duration phases for OTel/Lens. Together with exclusive_hold_seconds and gym_parked_seconds, they show which part of the pause to target next. The data-plane README lists them.

Validation

471 CPU checkpoint/restore/dispatch-race/policy regression tests passed on this rebased stack, including rollout resume/barrier-release, cleanup, trainer capture/publication ordering, cancellation settlement, and synchronous fallback. The suite uses --noconftest with an explicitly bounded two-CPU, zero-GPU local Ray instance for an existing policy metrics test.

The foundation's controller-byte follow-up also passed real Ray/ZMQ concurrent mutation/failure/fresh-actor restore tests and a nine-trial saved-metadata timing comparison in the production container; see #5137. Controller serialization remains inside capture, but now produces immutable bytes directly instead of recursively copying metadata first. Controller-byte and shard persistence happen after resume/barrier release.

The integration commits were rebased onto the lifecycle follow-up in #5137. An additional runtime safeguard stops checkpointing and retains the unpublished directory if capture release cannot be confirmed; scoped Ruff and Pyrefly checks passed for the updated runtime.

The earlier rollout integration has a separate 10-node GPU save/restart/restore smoke. This exact main-based port, trainer extension, and controller-byte follow-up have not had their own GPU smoke. The snapshot-save lock still protects the trainer anchor through publication, so optimizer commits can still wait.

Lifecycle review follow-up

Rebased onto #5137's context-manager, single-attempt persistence, and bounded RPC-wait changes. 1718e4fdef makes failed cleanup fail closed: if release cannot be confirmed, raise an invariant error and retain unpublished files because remote RPCs may still be writing. The checkpoint pump treats this as fatal rather than retrying a new capture. A new regression verifies both retained files and no publication.

The existing save lock is acquired before the mutation barrier and held through persist/release/publication, so snapshot N+1 cannot capture while N is still persisting. The one-view error remains an invariant, not scheduling flow control.

471 combined CPU checkpoint/restore/dispatch-race/policy regressions passed using the exact pinned Gym checkout and a bounded two-CPU, zero-GPU local Ray instance. The tests use --noconftest. Scoped Ruff and Pyrefly passed; real Ray/ZMQ timeout/late-release/concurrent-mutation/restore validation passed on the foundation. No new GPU allocation was used.

Recovery serialization after resume

a211758851 moves torch.save and sha256 of the rollout-recovery state out of the barrier on the retained-view path:

  • The recovery state is still built under the barrier. It shares no containers with the live ledger (receipts are deep-copied, dataclasses projected, and controller maps copied by their validators), so live writes after the barrier cannot reach it.
  • The hash is only needed in the data-plane metadata.json, which SimpleCheckpointCapture writes at the end of persist(). CheckpointCapture.persist(*, extra_metadata=...) now accepts metadata computed after capture. It rejects a key given at capture, or a value JSON cannot record, before writing anything.
  • SnapshotCapture.persist() serializes, hashes, and persists. Rollout snapshots and trainer checkpoints both use it. Serialization failures follow the existing release and no-publication path.
  • Backends without a retained view keep serializing inside the barrier, then save synchronously.

Behavior change: after resume, torch.save of the recovery state runs in a thread and competes with the controller's event loop for the GIL. On a CPU benchmark of a 308 MB state (measured for #5241), a 1 ms loop ticker saw median lag 5 ms, p99 25 ms and one 0.37 s stall over 6.5 s. Dispatch keeps running, but is slower for that window.

Recovery-state validation (parse_rollout_recovery_state) and the replay/staging inventory checks still run under the barrier. Re-validation stays for a follow-up after #5185, which changes rollout_recovery.py. #5241 runs the inventory checks, the build and the TQ capture concurrently under the barrier.

Validation for this commit: 30 targeted CPU tests passed. They cover deferred and fallback rollout snapshots, trainer deferred persistence and native fallback, recovery-hash binding, and SimpleStorage persistence. A new test checks the order pause → capture → resume → serialize → persist → release. It also checks that the persisted hash matches the published rollout_recovery.pt and that a live change after resume is not saved. Two SimpleStorage tests cover adding metadata at persist, and rejecting a captured key or an unserializable value without writing anything. A mutation that drops the late metadata fails the new test. Ruff and Pyrefly passed on the changed files. The broader unit suites, the CPU functional test, and a GPU run have not been rerun for this commit.

Measurements

CPU only, one node, real Ray + TQ 0.1.11 SimpleStorage (2 storage units), synthetic sealed ledger: 8,192 groups × 16 siblings × 20 model calls (131k rollouts, 2.6M staging keys, 131k replay keys), 64-byte tags per key. A script reproduces the barrier phases with the real ledger, TQ listing and capture code; it is not a GPU run. Median of 3 rounds with the variants run in rotating order; ranges in parentheses.

Both rows use the retained SimpleStorage view, so this isolates the serialization commit. The earlier commits' TQ-persistence deferral, relative to main's synchronous save, is not part of this comparison.

Barrier hold Recovery serialization, after resume
Before a211758851 (e95dbedb8d) 22.82 s (22.76–23.23) inside the hold
This PR (12da50adad) 15.21 s (15.15–15.40) 6.57 s (6.49–6.58)

The hold drops 7.6 s (33%). The TQ capture inside it took 1.93–2.28 s: about 10 ms of setup (actor handles, layout and directories, for 2 units), 1.9–2.2 s for the TQ controller to serialize 450 MB of metadata, and 0.05–0.13 s for the storage units. Most of the rest is the tagged staging listing and the ledger build, which #5241 runs concurrently.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Nov 9, 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 ff6cd89

@macandro96
macandro96 added this pull request to stack #5140 November 9, 2026 20:06
@macandro96 macandro96 changed the title perf(checkpoint): persist rollout snapshots after environment resume perf(checkpoint): defer rollout and trainer data-plane persistence Nov 9, 2026
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test e7b0f3a

@macandro96
macandro96 force-pushed the amahishi/async-tq-rollout-snapshots-main branch from e7b0f3a to 5586eb6 Compare November 10, 2026 01:07
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test 5586eb6

@macandro96
macandro96 force-pushed the amahishi/async-tq-rollout-snapshots-main branch from 5586eb6 to 1b29553 Compare November 10, 2026 23:27
@macandro96 macandro96 added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Nov 10, 2026
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test 1b29553

@ZhiyuLi-Nvidia

ZhiyuLi-Nvidia commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the update. I wrote a CPU test for writers racing a SimpleStorage capture. It is on zhiyul/test/simple-capture-concurrent-writers (git cherry-pick 43b38767b). It runs real Ray/ZMQ actors and uses the real DataPlaneCheckpointBarrier: checkpoint() for capture, mutation(kind) for writers.

  • Unfenced: a clear between the controller RPC and the shard RPCs, with no barrier, leaves k0 listed but not served after restore.
  • Drained: a writer inside mutation() makes checkpoint() wait. The cut contains its clear.
  • Fenced: a writer that asks for mutation() during checkpoint() waits. The restore matches the cut.
  • Stress: 3 of 3 restores match an oracle while an async writer runs.

@macandro96
macandro96 force-pushed the amahishi/async-tq-rollout-snapshots-main branch from 1b29553 to da03aaa Compare November 16, 2026 00:28
Base automatically changed from amahishi/async-simple-tq-snapshots-main to main November 16, 2026 20:20
@macandro96
macandro96 force-pushed the amahishi/async-tq-rollout-snapshots-main branch from 400c3a2 to bb8bc1f Compare November 16, 2026 23:22
@macandro96

Copy link
Copy Markdown
Contributor Author

@ZhiyuLi-Nvidia thanks for writing this, and sorry for the slow reply. Good to see the drained and fenced cases hold with real Ray/ZMQ actors and the real barrier, and the unfenced case shows why the capture has to run under checkpoint(). Did you want it in this PR? If so, I'll cherry-pick 43b3876 and run it in L1_Functional_Tests_SingleController_3 next to data_plane_simple_checkpoint_cpu.sh. Otherwise it could land as its own PR.

@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 this, Anish. The split between the ownership handle (SnapshotCapture) and the recovery data (CapturedRolloutState) is clean, and persist(extra_metadata=...) keeps the data-plane layer unaware of recovery details. Both of Zhiyu's threads are fixed at c98a132. We found no crash or data-loss bug: the detached recovery state shares nothing with the live ledger, persist finishes before adoption renames tmp_path, and the save lock keeps a new capture from racing the previous persist.

What's left:

  1. (C1) Add a test that the deferred trainer save writes rollout_recovery.pt and records its hash.
  2. (C4) Add a test for the deferred-path timing metrics.
  3. (C5) Replace the new README section with a short usage section, and fix the stale lines in docs/guides/single-controller.md and docs/observability/metrics.md.

All 304 tests in the changed test files pass on a CPU-only run; ruff (pinned 0.9.9) is clean.

Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-5139-tq-write-after-pause.html

Generated by Claude Code

Comment thread nemo_rl/data_plane/README.md Resolved
@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Nov 19, 2026
@terrykong
terrykong enabled stacked auto-merge (squash) November 19, 2026 18:17
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test fa83aa4

stacked auto-merge was automatically disabled November 19, 2026 18:27

Pull request removed from stack

@macandro96
macandro96 removed this pull request from stack #5140 November 19, 2026 18:27
@macandro96
macandro96 added this pull request to stack #5317 November 19, 2026 18:27
macandro96 and others added 9 commits November 19, 2026 10:29
Capture trainer data-plane views and controller metadata under the mutation barrier, then persist and release the retained view after canonical mutations resume. Wait for checkpoint I/O before model saves and publication; settle cancellation before releasing retained storage.

Preserve synchronous fallback and existing trainer/Gym recovery semantics. Add tests for barrier release, detached cursor state, publication ordering, persistence/release failures, cancellation, and native fallback.

Validation: 395 focused checkpoint/restore tests passed; Ruff and scoped Pyrefly checks passed.
Signed-off-by: Anish Mahishi <[email protected]>
…rier

Split the barrier hold left after the TQ capture into the replay inventory
check, rollout-recovery state build, its serialization, and the staging
inventory check, and log each under timing/rollout_checkpoint. Register
these and the TQ capture/persist/release phases for the OTel checkpoint
duration series.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
With a retained SimpleStorage view, the rollout-recovery state is built
under the mutation barrier and serialized and hashed after the barrier
opens and the environment resumes. The state shares no containers with
the live ledger, so live writes after the barrier cannot reach it.

The recovery hash is only needed in the data-plane metadata.json, which
SimpleCheckpointCapture writes at the end of persist(). persist() now
accepts metadata computed after capture and rejects any key given at
capture before writing anything. SnapshotCapture.persist() serializes,
hashes, and persists; both rollout snapshots and trainer checkpoints use
it. Backends without a retained view keep serializing inside the barrier.

tq_persist_seconds excludes the serialization, which stays in
recovery_state_serialize_seconds.

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

Make the metadata persist() adds after capture keyword-only and name it
extra_metadata, matching the stacked barrier-hold PR. The tests now also
cover a value JSON cannot record, and check that a rejected call writes
nothing and leaves the capture persistable.

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

Review follow-up. The three rollout_recovery_* keys reached metadata.json
by two routes, and the serialize, hash and build-keys steps were written
twice. _serialize_recovery_state now returns the payload, its seconds and
the binding. The synchronous fallback updates the metadata with it; the
deferred path passes it as extra_metadata. This drops the metadata
builder's rollout_recovery parameter and _rollout_recovery_metadata.

_save_data_plane_checkpoint only saves again, as on main. capture() calls
the capture API through _capture_data_plane_checkpoint, which logs
"captured" or "capture failed". A retained view no longer logs a "save
started" with no "completed", and a backend that cannot capture no longer
logs "save started" twice for one save.

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

Review follow-up, tests as proposed by the reviewer. A deferred trainer
save must write rollout_recovery.pt and bind its hash in
data_plane/metadata.json; dropping the persisted state returned by
SnapshotCapture.persist() now fails a test. A deferred rollout snapshot
must log tq_persist_seconds without the serialization before it,
tq_release_seconds, tq_save_seconds as capture plus persist, and keep
the write out of exclusive_hold_seconds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
Review follow-up. Replace the README's internals section with a short
usage section for
data_plane.simple.async_checkpoint. The removed section named
environment_paused_seconds, which is never logged (the key is
gym_parked_seconds), and copied the logged phase names. Update the
Single-Controller guide's barrier sentence and the metrics doc's
save-phase nesting for the deferred path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
@macandro96
macandro96 force-pushed the amahishi/async-tq-rollout-snapshots-main branch from fa83aa4 to 1c6f7c4 Compare November 19, 2026 18:42
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test 1c6f7c4

@terrykong
terrykong merged commit 2bb26a0 into main Nov 20, 2026
99 checks passed
@terrykong
terrykong deleted the amahishi/async-tq-rollout-snapshots-main branch November 20, 2026 08:49
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