Skip to content

refactor(data_plane): share one base and start helper for the controller's CPU actors - #5256

Closed
terrykong wants to merge 23 commits into
NVIDIA-NeMo:amahishi/pr4508-prefix-write-pipeline-actorfrom
terrykong:terryk/offload-client-pool
Closed

terrykong wants to merge 23 commits into
NVIDIA-NeMo:amahishi/pr4508-prefix-write-pipeline-actorfrom
terrykong:terryk/offload-client-pool

Conversation

@terrykong

@terrykong terrykong commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do ?

A sketch, stacked on #5176, of shared code for the two CPU Ray actors the controller owns: the advantage actor and the rollout reassembler (finalizers). Both build their own storage-lending TQ client and repeat the same start-up, ready check, cleanup on failure, and checkpoint/metrics hooks. This gives them one small base class and one start helper, so each keeps only its job and its placement.

Not meant to merge as is; it shows the shape. It does not change any code that #5176 adds: #5176's prefix writer stays its own class (see below).

Visual explainer (what the three actors share and don't, and each shared actor before and after, as pseudocode): https://terrykong.github.io/gh-pages-poc/terryk/pr-5176-one-actor-pattern.html

What changes

New nemo_rl/data_plane/delegate.py:

Piece What it does
DataPlaneDelegate Base class. Builds the connect-only client, names the actor in Ray logs with __repr__, and holds mooncake_checkpoint / get_data_plane_snapshot once.
start_cpu_actors(make_actor, *, n, ready, timeout_s) Creates the actors, waits for a ready method on each, and kills all of them if one fails.
spread_off_head() The advantage actor's placement (round-robin off a dedicated head node), moved here.
CPU_ACTOR_OPTIONS num_cpus=1, num_gpus=0, max_restarts=0, max_task_retries=0, written once.
Actor Change
AdvantageActor Subclass of DataPlaneDelegate; keeps run. create_advantage_actors is one start_cpu_actors(...) call with spread_off_head().
RolloutReassemblerActor Subclass of DataPlaneDelegate; keeps finalize and check_dependencies. Its start function is one start_cpu_actors(..., ready="check_dependencies") call.

How they are called does not change: setup calls the same two start functions and gets the same lists of handles, and the controller still calls run / finalize from its own queues of free actors.

Why the prefix writer is left out. It looks similar but differs in what matters: one per vLLM engine and owned by the worker (not a controller pool), pinned to its node, rows arrive through Ray instead of being read from TQ, it holds no storage, and it runs one call at a time. An earlier commit on this branch put all three behind one base and one pool; that needed a process() rename nobody called generically and a pool of one for the writer, and added 128 lines. The last commit narrows it to the two that really are the same.

Line count (source): delegate.py +119 (13 of them the license), the two actor files −82 net, so +37 overall. Roughly break-even; the gain is one copy of the start-up and hook code.

Testing

Ran locally on macOS (CPU only, Python 3.13, torch 2.11, Ray 2.58):

  • New tests/unit/data_plane/test_delegate.py (placement, start waits on each actor, failed start kills all even if one kill fails, base client/repr/hooks): 6 passed.
  • Advantage actor, reassembler, forest, advantage-stage, finalizer-lifecycle, logical-advantage, controller-actor, setup, prefix-writer and prefix-pipeline tests: 1,034 passed. One setup test cannot run here (it imports Megatron).
  • Pinned ruff (v0.9.9) check and format pass.

No GPU or functional run.

🤖 Generated with Claude Code

macandro96 and others added 21 commits November 10, 2026 16:02
The end-to-end test of generation-prefix recovery, moved here from NVIDIA-NeMo#4506
(C28): Gym's policy proxy holds a long Workplace call mid-decode, a rollout
snapshot cuts it, and after a hard kill the restored call must resume from
its saved prefix and train on the same rows as an uninterrupted run.

Signed-off-by: Anish Mahishi <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Make the parity test exercise many restored prefixes and separate recovery
faults from run-to-run sampling noise:

- Workload: four Workplace prompts per step whose closing turn lists 1..N
  (N = 150/250/350/450) at natural length. Group lengths are far apart, so
  prompt-group readiness order is deterministic. One prompt expects a
  different duration so rewards are not constant. Runs Qwen3-1.7B for 3
  steps.
- Selection/verification: require a recoverable prefix in every Workplace
  prompt group at the crash (Gym refuses dispatches that land during a
  checkpoint, so siblings may start late), and verify each cut returns to
  its Gym owner under attempt+1, restores its exact prefix digest, and
  completes once with its trained generated-token count equal to the
  restored prefix plus the regenerated tail.
- Parity: classify token divergences relative to the restored prefix. A
  divergence inside the prefix is excused as phase-one noise only when the
  trained prefix tokens hash-match what the worker restored, and excused
  rows still require equal rewards and sample masks; a prompt divergence
  always fails. Gate vLLM generation_logprobs in aggregate over token-
  matched rows (bit-identical fraction, Spearman, max abs diff) since they
  are not batch-invariant, and require exact prompt-group readiness order.
  Report Kendall tau for arrival and sealing order, per-rollout timelines,
  and logprob statistics in parity-report.json before the strict checks
  run.
- Hook: timestamp every event and record completion arrival separately
  from the ledger seal.
- Relies on the Gym checkpoint test agent's natural-length closing turn
  (NEMO_GYM_TEST_PREFIX_MIN_TOKENS=0), pinned by the base branch.

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

The prefix-recovery parity harness reads each restored cut from Gym's
checkpoint records and reports it. NeMo Gym now names the staged prefix
prefix_token_count and prefix_digest, so the harness, its report, and
its unit tests use those keys.

Signed-off-by: Ananth Subramaniam <[email protected]>

Signed-off-by: Anish Mahishi <[email protected]>
… test

The prefix-recovery snapshot helper now imports
_gym_recovery_snapshot_helpers as a sibling module. Put tests/functional on
sys.path before loading it by file path, as running it as a script does.

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
(NVIDIA-NeMo#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]>
…logprobs

Main's sampler replay (NVIDIA-NeMo#5006) refuses top_k/top_p filtering unless vLLM
returns logprobs after the filter, since the trainer now replays it. The
parity test samples with top_p=1e-6 to make regenerated tails comparable
token for token, so it failed at startup. Set
vllm_cfg.logprobs_mode=processed_logprobs, as main's score-centering
functional test does.

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

NVIDIA-NeMo#4506's third review defers a finished call's chunk-row delete to the next
snapshot, so restored prefix rows are still live when phase two first
trains. Phase two now trains one step past the reference, so the snapshot
after the compared step runs while the run is alive, and the hook records
the live staging keys right after each flush. The parity check requires
the restored rows to be live at the first training step and gone after the
first flush, and compares only the reference's steps.

grpo.max_num_steps is excluded from the rollout fingerprint in both phases,
since only phase two's stopping point changes.

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

Address C28's follow-ups from the third review of generation-prefix
recovery:
- The recovery hook reads one events variable, SC_GYM_RECOVERY_TEST_EVENTS,
  which the turn and prefix scripts both set; the turn-only name and its
  fallback are gone.
- The prefix-recovery test runs in fast CI lanes: three launches on 2 GPUs,
  7-9 minutes locally.
- The turn-recovery script imports ledger_episode_index,
  participant_records, matching_siblings and calendar_sentinel_count from
  _gym_recovery_snapshot_helpers instead of keeping its own copies.

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

Under token_capture.forest_training the trainer names each row
<group>_g<i>_s<segment>, and the parity check rejected them as invalid
sample IDs. Accept the single segment _s0, which still compares one
trained row per rollout, and fail clearly on a later segment.

With NVIDIA-NeMo#5147 applied, the prefix-recovery test passes under forest
training: 8 restored episodes seal as their next attempt and all 8
trained rows match the uninterrupted run.

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

- C16: fail when more than one restored row is set aside as diverged
  before its cut. Nothing checks that a set-aside row diverged rather than
  restored the wrong tokens, so the cap bounds what a run leaves unchecked.
- C19: build the row index once in compare and pass it to every check, and
  merge the prefix-boundary and divergence checks into _check_cuts, which
  reads the recovery log once. Same checks, order and messages. Drop the
  step-mixing check: JsonDebugWriter writes one file per step.
- C20: inline the Workplace row builder into the prefix script and delete
  _workplace_calendar_rows.jq; the turn-recovery test builds its own rows.
  The generated test data is byte-identical.
- C21: drop min_cuts, the top-level longest-cut fields and the unread
  per-cut resources_manifest and sentinel_event from the snapshot selection.
- C25: run the test at full tier, not in fast lanes. It relies on three
  runs making the same near-greedy choices, and local runs have failed for
  reasons outside recovery, so it waits for a CI-GPU pass rate.

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 stages the routes of the tokens it freezes on its chunk row, one per
chunk token, as a tensor attachment whose metadata rides the row's extras
like a terminal row's routes; each chunk's own digest covers its routes,
and the advertised prefix digest covers tokens and call extras only. The
cut's progress read copies each router-replay call's vLLM route pieces in
the same lock hold as its tokens, and the call's route cache joins only the
pieces appended since its last cut, into a buffer that doubles when full,
so a cut costs the rows decoded since the previous one. A finished call's
final output supplies its routes instead. 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.

The route helpers live in prefix_recovery/routes.py; PrefixRecoveryParts
gains router_replay, and the ProgressReader read takes the calls whose
route pieces it copies. Adds a tiny-MoE router-replay prefix-recovery
functional test to L1, and unit coverage of cuts, races, resumes and the
progress read's route copy. 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]>
A checkpoint cut wrote one TransferQueue row per active call, so a worker
with hundreds of calls in flight spent the cut in per-row put overhead.
Write the cut's chunk rows in batches instead.

- PrefixRecovery._cut_transaction keeps a call's cut frozen, under its
  lifecycle, until its batch is written and every acknowledgement in the
  batch is built; only then does each call seal. Leaving the lifecycle
  rolls an unsealed cut back and clears its row.
- checkpoint_cut batches rows up to rollout_recovery.
  generation_prefix_batch_size rows and generation_prefix_batch_max_tokens
  tokens per put; one larger row is written alone, never split.
- Failures stay per call, as Gym acknowledges them: a failed freeze,
  acknowledgement or seal fails only its call. A failed batch put is
  retried one row per put, so one bad row fails only its own call. Rows
  written but never handed to a call (only an interruption leaves them)
  are cleared. Past the control deadline no further put starts.
- TQTokenSink.stage_generation_prefix_batch groups rows by field dtype and
  shape and writes each group with one put_many; a failed put discards
  every key of the batch and raises. Single and batched rows share
  _encode_record. The single-row stage_generation_prefix is removed.
- Both limits are runtime knobs on RolloutRecoveryConfig, passed to the
  workers through setup_token_capture and PrefixRecoveryParts, and
  excluded from the bootstrap fingerprint.

Co-authored-by: Ananth Subramaniam <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
After a restart every cut call on a worker resumes at once, and each
restore read its chunk rows in its own TQ GET. Share those reads.

- PrefixReadBatcher is an event-loop-local coalescer: concurrent reads
  share GETs of at most rollout_recovery.generation_prefix_batch_size
  distinct keys, deduplicated, with each caller's chain order preserved.
  Cancelling one caller does not cancel the shared GET for the others. If a
  multi-key GET fails, each key is read alone once, so a bad row fails only
  the callers that asked for it and an outage costs N+1 GETs.
- PrefixRecovery owns the reader. The worker awaits read_restore_chunks on
  the serving loop and passes the rows to resolve_restore, which reads them
  itself if the shared read failed and regenerates the call if they still
  cannot be used. The worker closes the reader before shutting recovery
  down.

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

Sketch for review, stacked on NVIDIA-NeMo#5176. The advantage actor, the rollout
reassembler (finalizers) and NVIDIA-NeMo#5176's prefix writer each own a connect-only
data-plane client and repeat the same start-up, ready check, cleanup,
checkpoint hooks and free-actor queue. This moves that into
nemo_rl/data_plane/offload.py:

- OffloadClient: base class. Builds the client, names the actor in Ray
  logs via __repr__, and holds the checkpoint and metrics hooks. A
  subclass overrides process(request). owns_storage decides whether the
  client lends Mooncake memory (and so needs the checkpoint hook).
- OffloadPool: start(cls, *args, n, placement, **ray_options) with the
  options all three used; wait_ready / wait_ready_async (kill all on
  failure); acquire / release for the controller's free-actor handling.
- Placements: on_this_node() (hard pin, the prefix writer) and
  spread_off_head() (moved from the advantage actor).

Each actor now keeps only its job: AdvantageActor.process (was run),
RolloutReassemblerActor.process (was finalize), PrefixWriterActor.process
(was put). The controller's two hand-built asyncio queues become
OffloadPools. No behavior change intended.

Signed-off-by: Terry Kong <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 16, 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.

…legate/DelegatePool

"Offload" already means SSD offload in the data plane. The module moves to nemo_rl/data_plane/delegate.py; no behavior change.

Signed-off-by: Terry Kong <[email protected]>
@terrykong terrykong changed the title refactor(data_plane): share one offload client and pool across CPU actors refactor(data_plane): share one data-plane delegate and pool across CPU actors Nov 16, 2026
…ctors

The class-per-everything version cost more than it saved: the prefix writer
differs in owner, count, placement, transport and concurrency, and a pool
and a common process() method had no generic caller. Keep only what the
advantage actor and the rollout reassembler really share:

- DataPlaneDelegate: owns the storage-lending client, names the actor in Ray
  logs, and holds the checkpoint and metrics hooks once.
- start_cpu_actors: create, wait for a ready method, kill all on failure.
- spread_off_head: the advantage actor's placement, now reusable.

run/finalize keep their names, the controller keeps its queues, and the
prefix writer is as in NVIDIA-NeMo#5176.

Signed-off-by: Terry Kong <[email protected]>
@terrykong terrykong changed the title refactor(data_plane): share one data-plane delegate and pool across CPU actors refactor(data_plane): share one base and start helper for the controller's CPU actors Nov 16, 2026
@macandro96
macandro96 force-pushed the amahishi/pr4508-prefix-write-pipeline-actor branch from 981376a to d42cf30 Compare November 17, 2026 06:03
@macandro96
macandro96 force-pushed the amahishi/pr4508-prefix-write-pipeline-actor branch 2 times, most recently from 6e59987 to 9d9d34e Compare November 21, 2026 07:01
@terrykong
terrykong deleted the branch NVIDIA-NeMo:amahishi/pr4508-prefix-write-pipeline-actor November 21, 2026 08:57
@terrykong terrykong closed this Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants