nemo_rl.algorithms.single_controller#
SingleController: asyncio orchestrator for the RL training loop.
CPU-only Ray actor that runs two concurrent pumps plus a watchdog, and coordinates the other actors via lightweight RPCs. SC sends control signals and reads metadata only — model tensors still move through DataPlane or NCCL.
Data flow: _rollout_pump → gen.generate_and_push(prompt, dp_client) ← RPC to GenWorker GenWorker → dp_client.put_samples(…) _train_pump → sampler.evict/select against TQReplayBuffer → _value_stage(meta) (PPO only) → value.get_values_from_meta(…) Value → dp_client.get/put_samples(…) (via its own client) → _advantage_stage(meta) → dp_client.get_samples(…) → adv_estimator.compute_advantage(…) → dp_client.put_samples(…) → trainer.begin/train_microbatches/finish_train_step (split API, driver-side TQPolicy via asyncio.to_thread) Trainer → dp_client.get_samples(…) (via its own client) → early policy refit (PPO, separate generation GPUs) → _value_train_epochs(full_batch_meta) (PPO only) → value.train_from_meta(…) Value → dp_client.get_samples(…) (via its own client) → dp_client.clear_samples(…) ← SC clears after train _sync_weights → WeightSynchronizer.sync_weights()
Module Contents#
Classes#
CPU-only Ray actor that orchestrates the RL training loop. |
Functions#
Return the latest value keyed by generation data-parallel worker. |
|
Return a deterministic nearest-rank percentile for telemetry. |
|
Compute whole-step OPD metrics from exact pooled sufficient statistics. |
|
Snapshot source reading every rank’s data-plane counters in one fan-out. |
Data#
API#
- nemo_rl.algorithms.single_controller.Generation#
None
- nemo_rl.algorithms.single_controller.log#
‘getLogger(…)’
- nemo_rl.algorithms.single_controller._SUPERVISOR_DRAIN_TIMEOUT_S#
30.0
- nemo_rl.algorithms.single_controller._latest_generation_values(
- metrics: dict[str, Any],
- metric_name: str,
Return the latest value keyed by generation data-parallel worker.
- nemo_rl.algorithms.single_controller._percentile(values: list[float], quantile: float) float#
Return a deterministic nearest-rank percentile for telemetry.
- nemo_rl.algorithms.single_controller._pooled_opd_metrics(
- stat_sum: float,
- stat_sumsq: float,
- count: int,
- gap_sum: float,
Compute whole-step OPD metrics from exact pooled sufficient statistics.
stat_*pool the advantage andgap_sumthe raw teacher-student gap over the same tokens. They differ once TROPD (proximal_teacher_alpha < 1) or subtract_global_baseline reshapes the advantage.
- nemo_rl.algorithms.single_controller._worker_group_snapshots(
- worker_group: Any,
Snapshot source reading every rank’s data-plane counters in one fan-out.
- class nemo_rl.algorithms.single_controller.SingleControllerActor(
- master_config: nemo_rl.algorithms.single_controller_utils.config.MasterConfig,
- actor_args: nemo_rl.algorithms.single_controller_utils.setup.SingleControllerActorArgs,
- setup_timing_metrics: nemo_rl.algorithms.metric_utils.SetupTimingMetrics,
CPU-only Ray actor that orchestrates the RL training loop.
Owns three concurrent asyncio tasks:
_rollout_pump: dispatches prompts to GenerationWorkerActor
_train_pump: claims DataPlane meta, trains, clears consumed rows, then runs _sync_weights (drain gate + weight synchronization) inline after each optimizer step
_stall_watchdog_pump: publishes rollout counters and reports stalls or unhealthy environments, which are the failures that otherwise produce no signal at all
Plus _gen_fleet_probe_pump when fleet health is enabled, which probes generation shard liveness on its own, much shorter clock.
All other actors are passive — they expose methods and wait to be called.
Initialization
Initialize the SingleController actor.
- Parameters:
master_config – SC MasterConfig.
actor_args – Pre-built actor args from setup_single_controller.
setup_timing_metrics – Driver-side setup timings; logged here (Logger isn’t cloudpickleable).
- _defer_checkpoint_finalize: bool#
False
- _pending_checkpoint: Optional[tuple[nemo_rl.utils.checkpoint.PathLike, int]]#
None
- _rollout_trace: nemo_rl.algorithms.rollout_checkpointing.trace.RolloutTrace#
‘RolloutTrace(…)’
- _recovering_from_refit: bool#
False
- _tracer: Any#
None
- async run() dict[str, Any]#
Main entry point. Runs until max_train_steps is reached.
- async _run_pumps() dict[str, Any]#
Start the rollout / train / watchdog pumps and run until one finishes.
- _maybe_start_trainer_warmup() None#
Run the warm-up beside the first rollouts if setup chose it and did not run it.
- async _finish_trainer_warmup() None#
- async ping() dict[str, Any]#
Liveness check — returns immediately if event loop is running.
- _step_assembler() nemo_rl.algorithms.single_controller_utils.step_assembly.StepAssembler#
Track the step the train pump is assembling and charge lost groups to it.
Built on first use so the cursor seeds from the current
_trainer_version(the restored step on resume) and so controller instances that unit tests construct viaobject.__new__get it without a hand-written assignment.
- _training_progress() nemo_rl.algorithms.rollout_checkpointing.state.TrainingProgress#
Return the training counters a checkpoint reads.
- _build_rollout_checkpointing(
- *,
- bootstrap_identity: Optional[nemo_rl.algorithms.rollout_checkpointing.manifest.BootstrapCompatibilityIdentity],
- resume: nemo_rl.algorithms.rollout_checkpointing.state.ResumeSource,
Build the rollout snapshotter and restorer, which share the controller’s parts.
- _log_telemetry_metrics(
- metrics: dict[str, float],
- *,
- step: int,
- prefix: str,
Log benchmark telemetry on an axis independent of trainer steps.
- _record_rollout_timing(
- *,
- work_started: float,
- dispatch_started: float,
Record one committed group’s queue and execution durations.
- _require_unoccupied_target_step(
- target_step: Optional[int],
Reject a sampler admission that collides with existing buffer ownership.
- async _dispatch_reservation( ) collections.abc.AsyncIterator[Optional[nemo_rl.algorithms.async_utils.replay_buffer.DataPlaneMutationCut]]#
Hold a data-plane mutation cut for one dispatch change, when recorded.
With ledger dispatch, the change and its ledger records are one checkpoint-atomic step counted as
kind. Without it nothing is recorded, so the change takes no mutation slot and yieldsNone.
- _reserve_prompt_group(
- cut: Optional[nemo_rl.algorithms.async_utils.replay_buffer.DataPlaneMutationCut],
- prompt: nemo_rl.data.interfaces.DatumSpec,
- *,
- target_step: Optional[int],
- admitted: bool = True,
- admission_id: Optional[str] = None,
Record a prompt group in the ledger, or return
Nonewhen unrecorded.Without a group ID the rollout manager mints one when it runs the group.
- _discard_prompt_group(
- cut: Optional[nemo_rl.algorithms.async_utils.replay_buffer.DataPlaneMutationCut],
- group_id: Optional[str],
Drop a recorded group’s ledger ownership; unrecorded groups have none.
- async _admit_step(
- group_ids: list[Optional[str]],
- *,
- wait_until_admissible: Optional[Callable[[], Awaitable[None]]] = None,
Admit one step’s prompts through the sampler and return its target step.
- async _admit_reserved_prompt_groups(
- group_ids: list[str],
- *,
- wait_until_admissible: Optional[Callable[[], Awaitable[None]]] = None,
Commit one admission and mark every reserved group as admitted.
- Parameters:
group_ids – The reserved groups this admission stamps.
wait_until_admissible – Pump-owned admission wait that can refill prompts. Omitted when draining reserves after final data exhaustion.
- Returns:
The target-step stamp assigned to every group.
- async _ray_get(obj_ref: Any) Any#
Await a Ray ObjectRef without blocking the asyncio event loop.
- async _call_dp(method_name: str, **kwargs) Any#
Call a DataPlaneClient method or a Ray actor exposing that method.
- static _request_staging_keys( ) list[str]#
Return the full receipt-manifest staging ownership for a request.
- async _cleanup_known_finalization_request_unlocked(
- cut: nemo_rl.algorithms.async_utils.replay_buffer.DataPlaneMutationCut,
- request: nemo_rl.experience.rollout_reassembler_actor.ReassemblyRequest,
Clear known request ownership while holding a barrier mutation slot.
- async _cleanup_known_finalization_request( ) None#
Clear a known request outcome without racing a native TQ snapshot.
- _valid_fraction_counts( ) Optional[tuple[int, int]]#
Return (valid, total) when the group falls below the valid-fraction bar.
- async _claim_filtered_spare() collections.abc.AsyncIterator[None]#
Promise a finalizing group a filtered spare, in case it is rejected.
A rejected group’s spare is taken inside the finalize cut, which cannot wait for the pump to refill an empty pool. Claiming first waits until the pool holds a spare no other finalizing group has claimed. A claim only counts against the pool; the spare is popped inside the cut, and only on rejection.
Once the dataloader is exhausted, no group waits for another spare: rejection takes whatever remains or closes its step short.
- async _finalize_with_actor(
- request: nemo_rl.experience.rollout_reassembler_actor.ReassemblyRequest,
- rollout_metrics: dict[str, Any],
- *,
- target_step: Optional[int],
- replacements_used: int,
Finalize and index one group atomically with respect to TQ saves.
Returns the committed FinalizedGroup once the group is committed to the replay buffer, or None when the finalizer itself dropped it as a structural outcome (ownership already cleaned up; the caller credits the step short).
A group below
token_capture.min_valid_fraction_per_group, or with dynamic sampling on one whose voting rewards carry no signal, is rejected beforecommit_finalizedmarks its slot ready, so the sampler can never select it. Its cleanup, the spare prompt that replaces it (or the step’s shortfall credit), and that spare’s ledger reservation share the commit’s mutation cut, so no snapshot sees the group gone without its replacement. Returns aBelowValidFractionGrouporZeroVarianceGroupin that case. A zero-variance group takes its spare from the filtered pool, which cannot be waited on inside the cut: the caller holds_claim_filtered_spareacross this call so the pool is not empty when the group is rejected.
- async _cleanup_consumed_metas_unlocked(
- cut: nemo_rl.algorithms.async_utils.replay_buffer.DataPlaneMutationCut,
- metas: list[nemo_rl.data_plane.KVBatchMeta],
Clear consumed ownership while holding a barrier mutation slot.
- async _log_data_plane_metrics(total_step_time: float) None#
Log this step’s data-plane cost. Never raises.
On by default, so this runs every step of every recipe. Mirrors
grpo_sync._log_data_plane_metrics.
- async _log_data_plane_metrics_impl(total_step_time: float) None#
Log this step’s data-plane cost.
This client’s share depends on the configuration: it writes the rollout rows unless token capture moves that to the finalizer actors, and it issues the advantage get and put unless advantage workers take them. The trainer merges this client’s counters with its worker ranks’, the finalizer, advantage, generation, critic and teacher sources into one cluster view. The fan-out blocks on
ray.get, so it runs off the event loop.nixl’s unit metrics (retired memory, SSD spills) and Mooncake’s master counters (memory use, SSD offload) are logged even with observability off: a leak only shows over a long run, in the runs that need it, and the first SSD spill / offload of a run logs its warning from here.
- static _group_ids_from_meta(
- meta: nemo_rl.data_plane.KVBatchMeta,
Return stable prompt-group IDs in canonical sample order.
Reads the same tag the advantage stage keys its baseline on rather than parsing the
_g{i}suffix back off the sample ids, so the two do not disagree about what a group is. The stage would raise on a batch whose tag is missing anyway; doing it here fails one stage earlier in the same iteration.
- async _rollout_pump() None#
Continuously dispatch rollout tasks until cancellation.
Per batch: 0. Under on_dropped_prompt=”replace” or dynamic sampling, divert the batch into the spare pool if the pool is below its low-water mark, and skip admission entirely. Otherwise await sampler.admit(…) to wait until the batch may dispatch and obtain its target_step stamp.
Per prompt:
Acquire _buffer_capacity slot (backpressure)
Acquire sem (cap concurrent in-flight rollouts)
Wait for _rollout_permitted (paused during weight sync)
Call rollout_manager.generate_and_push(prompt) — local async RolloutManager reserves a slot, runs the rollout, then commits the group via TQReplayBuffer (→ dp_client.put_samples + mark ready). In token-capture mode (finalizer actors present) the rollout is run via generate_for_finalization instead and its metadata-only request is submitted to the finalizer actor pool.
If the prompt was dropped, substitute a spare and repeat step 4 – for this step, or for whichever step lends this one a finished group in its place (see _take_replacement, _pop_filtered_replacement, _promote_into_step) – or credit the step short so the train pump can close it
Decrement _inflight_rollouts
Once every epoch is done, whatever is left in the spare pool is dispatched as ordinary steps rather than discarded (see _drain_reserve_into_steps).
- _iter_prompt_batches() collections.abc.Iterator[nemo_rl.distributed.batched_data_dict.BatchedDataDict[nemo_rl.data.interfaces.DatumSpec]]#
Traverse epochs for both ordinary dispatch and on-demand refills.
- async _divert_batch_to_reserve(
- prompt_batch: nemo_rl.distributed.batched_data_dict.BatchedDataDict[nemo_rl.data.interfaces.DatumSpec],
Consume a whole batch as spare prompts instead of admitting it as a step.
Returns whether the batch was taken, in which case the caller must not admit it. Diverting before
admitis what keeps the stamp sequence honest: admitting a batch and then dispatching nothing for it would leave a target step that no group is ever generated for, which is exactly the hang the shortfall accounting exists to prevent.A whole batch at a time because the dataloader only yields batches. The spares that go unused are not wasted work – nothing has been generated for them – and they stay in the pool for later steps.
Nothing is diverted for a sampler that does not use the pool, or before the first batch has been admitted. The cost of the latter is that the first batch is always admitted rather than diverted; in practice the pool is filled while that first batch’s rollouts are still running, so it is available by the time any of them can be given up on.
- async _drain_reserve_into_steps(
- launch: Callable[[nemo_rl.data.interfaces.DatumSpec, Optional[int], Optional[str]], Awaitable[None]],
Train on the leftover spares once the dataloader has nothing more to give.
Spares were consumed from the dataset like any other prompt, so leaving them in the pool at the end of the last epoch throws away data the run already paid for.
It also restores the step count.
_clamp_max_num_stepsderivesmax_num_stepsfromlen(dataloader), and every diverted batch is one fewer batch the loop can admit – so without this a replace-mode run quietly finishes one step short of the budget it was configured with, per divert.Whole steps only. A partial pool dispatched as a step is short by construction, and
min_step_batch_fractionwould then reject it and fail a run that had otherwise completed cleanly. In the ordinary case the pool holds exactly one batch (the dataloader usesbatch_size=num_prompts_per_step), so the common outcome is that the whole thing is recovered.Not gated on
on_dropped_prompt: an empty pool makes this a no-op anyway, and only a run that replaces something ever fills one, so the gate would buy nothing while stranding a pool restored from a checkpoint into a run that has since switched to “shrink”.
- _take_replacement(
- replacements_used: int,
A spare prompt to stand in for a dropped group, or None to shrink instead.
For rollout failures only. A group dropped by dynamic sampling goes through
_pop_filtered_replacement, which spends a different budget.None covers the four ways a replacement can be unavailable: it was not asked for, the sampler does not use a spare pool, the per-slot budget is spent, or the pool is empty because the dataloader is exhausted. Every one of them falls back to
on_dropped_prompt="shrink"rather than waiting, because a step whose replacements keep failing still has to close.The sampler’s uses_pooled_replacements flag decides whether it uses a pool.
- _record_filtered_prompt(target_step: Optional[int]) None#
Count one resampled prompt against its step, without enforcing the budget.
Unstamped prompts are charged to the step currently being assembled. A pooled sampler draws a replacement synchronously, so it checks the budget in the same step; windowed draws none and relies on later dispatches, so the train pump checks after selection instead (see
_check_filtered_budget).
- _check_filtered_budget(step: int) None#
Fail the run once a step has drawn past its generation-batch allowance.
v1 bounds a step by
dynamic_sampling_max_gen_batchesgeneration batches. SC resamples per slot rather than per batch, so the same allowance is counted in prompts: a step may draw this many batches’ worth in total, the batch it was admitted with included. A step that cannot be filled within it means the filter is rejecting faster than the data can refill it, which v1 also ends the run on.- Raises:
RuntimeError – The step has spent its whole generation-batch allowance.
- _charge_filtered_prompt(target_step: Optional[int]) None#
Record a pooled resample and fail the run past the allowance.
A pooled sampler has the replacement in hand, so it enforces the budget in the same step the prompt is drawn.
- _enforce_windowed_filtered_budget(
- step: int,
- selected_groups: int,
Fail a non-pooled step once its total draw exceeds the allowance.
Windowed draws no spare per filter, so unlike the pooled path it cannot enforce the budget as each filter arrives; the train pump calls this after every selection instead. The check is against the groups actually selected, not a full
num_prompts_per_step, so an EOF tail that legitimately selected fewer groups keeps its full resample allowance rather than being overcounted. A still-starved step (nothing selected yet) keeps accumulating draws across polls, so an all-filtered wrapping loader still trips the budget.- Raises:
RuntimeError – Selected plus filtered draws spent the whole allowance.
- async _wait_for_filtered_reserve() None#
Wait for pump refill without holding a checkpoint mutation cut.
- _pop_filtered_replacement(
- target_step: Optional[int],
Consume an available spare, or finish a step after data exhaustion.
- async _replacement_mutation(
- *,
- filtered: bool,
Keep spare consumption and ledger transfer atomic without blocking saves.
- _allow_short_drained_step(target_step: Optional[int]) None#
Mark a drained-pool step for the final train-or-skip floor check.
- _promote_into_step(
- target_step: Optional[int],
Fill a dropped step from a later step’s finished work, and name the lender.
Where a replacement goes, rather than whether one happens. The lost step closes on generation that already exists instead of waiting out a rollout with the trainer idle, and the caller redirects its spare prompt to the lender, which is due a training step later and has the slack to absorb the wait. The same prompt is generated either way.
Only ever reached with a spare already in hand, which is what makes the borrow safe to take: an unrepaid loan is the same hole one step later.
Returns None – leaving the caller filling the dropped step directly – when nothing is stamped so no step is stranded, when the trainer has already moved past this step (a second drop can land after the first one closed it short, and a group stamped for a finished step would only be evicted), or when no later step has a finished group to lend. The last is always the case at
in_order.max_lookahead_versions=0, where the next batch is not dispatched until this step trains.- Returns:
The step that lent the group, which the caller now owes a rollout, or None.
- _substitute_dropped_group(
- cut: Optional[nemo_rl.algorithms.async_utils.replay_buffer.DataPlaneMutationCut],
- replacement: Optional[nemo_rl.data.interfaces.DatumSpec],
- target_step: Optional[int],
- *,
- filtered: bool = False,
Stand a spare prompt in for a dropped group, or close its step short.
Call inside the cut that removed the dropped group, so no snapshot sees the group gone without its replacement. A finished group from a later step fills the dropped step when one exists, and the spare is then generated for that lender.
- Parameters:
cut – The cut the group was removed in;
Nonewhen nothing is recorded.replacement – The spare already taken from its pool, or
Noneif there was none, which creditstarget_stepshort.target_step – The step the dropped group was stamped for.
filtered – Whether the group was dropped by dynamic-sampling filtering rather than a rollout failure. A filtered group that closes its step short is allowed below the floor; a failed one is not.
- Returns:
The ledger ID reserved for the spare (
Nonewithout rollout recovery or without a spare) and the step the spare is generated for.
- _target_groups_for_step(step: int) int#
How many prompt groups this step should train on, after dropped prompts.
num_prompts_per_stepis the target; groups charged to this step that were given up on are subtracted, because they are never arriving. Which step a lost group is charged to is the sampler’s call (charge_step_for_lost_group): the step it was stamped for, the step being assembled, or none. Without this the pump waits on a group no one is generating.Steps explicitly allowed to close short return their remaining target even below the floor, letting the train pump drain their groups and abort accumulated gradients. The final floor check decides whether to train or skip. Data exhaustion alone does not grant this permission.
How much smaller is bounded by
min_step_batch_fraction, and that bound has to live here because neither drop budget provides it. Both budgets are run-scoped – the consecutive counter is cleared by any commit, including commits for other steps – so drops landing on one step while other steps succeed can shrink it without ever tripping them.- Raises:
RuntimeError – A step not permitted to close below the floor fell below
min_step_batch_fractionofnum_prompts_per_step.
- async _train_pump() None#
Per-prompt-group streaming train loop.
Per step, with 1-4 running per streaming chunk and 5-6 once the chunk loop closes: 1. Select the rollouts to train on. a. sampler.evict drops stale groups from the buffer and clears their TQ rows. b. sampler.select returns K prompt groups, or None, and claims them for training. The DP rows survive, already training-shaped because the buffer wrote them that way at rollout time. c. Claimed groups retain their _buffer_capacity permits until step cleanup; evicted groups release theirs immediately. 2. Prepare the batch. a. Value model forward (PPO only), parking policy parameters and optimizer on CPU where supported. Pending policy gradients stay on GPU. b. Policy and reference logprobs. c. _advantage_stage. 3. Train on the chunk. a. Policy model: train_microbatches_from_meta accumulates gradients. b. Full-batch PPO closes each actor epoch here (kept for ppo_epochs > 1); streaming PPO and GRPO accumulate across chunks and close the policy step in 5. Streaming PPO requires ppo.ppo_epochs=1. 4. Close the chunk. Refresh min_sample_version and the dispatch tally. The consumed rows stay in TQ: staged capture deltas are read by the policy workers during 3, so nothing is cleared until the step closes. Streaming PPO prepares the critic before waiting for the next chunk. 5. Finish training the step. a. finish_train_step all_reduces the accumulated policy gradients, rescales, and runs optimizer.step, unless full-batch PPO already closed its actor epochs in 3. b. PPO refits separate generation GPUs early, then runs all ppo.critic_ppo_epochs on the concatenated full batch. c. _cleanup_consumed_metas clears every consumed canonical row and its staged capture deltas, releasing training claims and capacity. 6. Refit the model. Sync the new policy weights to generation unless PPO already refit in 5. Generation sharing the training GPUs stays asleep until critic training finishes.
PPO critic warmup (ppo.policy_training_start_step > 0) changes which of those run. For the first N steps 5b still trains the critic every step, but policy training and refit are skipped. The trainer version still advances, and the sampler’s lookahead is widened while the policy is frozen.
- async _stall_watchdog_pump() None#
Report rollout health, and detect stalls nothing else catches.
Progress is the pair (committed groups, completed train steps) rather than a timestamp: both counters already exist, and “neither has moved” is the property that actually matters.
Deliberately not conditioned on rollouts being in flight. An earlier version required that, on the reasoning that an idle controller has legitimately no work – and a fault-injection run walked straight through the gap. Killing a generation worker wedged the loop with zero rollouts in flight and zero failures recorded: the rollout pump was blocked on backpressure behind a train pump that could no longer finish a step, so nothing was in flight to count. The watchdog observed six minutes of idleness and said nothing.
What separates a real stall from an idle gap is whether work remains, so that is what is checked instead.
- async _gen_fleet_probe_pump() None#
Probe the generation fleet on its own clock.
Separate from the watchdog because the two cadences answer different questions. The watchdog publishes counters and notices a stalled run, which is a minutes-scale concern; liveness detection is the input to every recovery decision and has to be seconds-scale.
Sharing the watchdog’s loop made
probe_interval_sdecorative – probes ran atwatchdog.interval_sand nothing read the configured value. With the shipped defaults that put detection at30s * unhealthy_threshold, i.e. 60-90s, which is longer than the refit deadline: by the time a hung refit aborted, the monitor still had the dead shard as SUSPECT, so the rebuild that abort exists to trigger saw an empty absent set and did nothing. Arithmetic, not a race – it could never have worked. Job 5925668.
- async _probe_generation_fleet() None#
Ask every serving generation shard whether it is still alive.
Ray actor liveness is the cheap authoritative signal for “the process is gone”, and it is what the probe uses. It does not catch every failure – a vLLM engine core can die while the worker process and its HTTP thread survive – which is why the routing adapters also report the failures they observe. The two signals feed the same counters.
Only serving shards are probed: a quarantined shard answering again says nothing about whether its weights are current, and the monitor ignores such probes anyway.
Shards are probed concurrently. Sequentially, a tick costs up to
probe_timeout_sper shard, so a fleet of four would take 8s to complete a round the config promises every 5s – and config validation only checksprobe_timeout_s < probe_interval_s, which silently assumes one probe per tick. Concurrent, a round is bounded byprobe_timeout_sat any fleet size.
- async _push_router_membership() None#
Tell the NeMo-Gym router which backends are currently serving.
Pushed as the full set rather than a delta, so a dropped or reordered update – or a restarted router, which comes up believing every backend serves – converges on the next tick without sequence numbers or replay.
Pushed unconditionally, not gated on the membership epoch moving. The gate looked free – an unchanged serving set costs nothing to skip – but it made the router’s own restart unrecoverable: a recreated actor rebuilds
_servingas every backend, while the epoch it was last pushed at has not moved, so the gate blocked every corrective push and Gym routed to a quarantined shard for the rest of the run. The payload is a short list of strings on a probe-interval timer; the gate bought nothing and cost the guarantee both docstrings advertised.It is also what makes the router’s reflex drop safe: dropping a failing backend locally is only correct because a later push puts it back.
- async _drain_router_failures() None#
Fold the router’s observed backend outcomes into the fleet ledger.
The router is the only component that sees a wedged engine: it answers
is_alivefrom a healthy worker process, so no probe can condemn it. The router holds no monitor reference by design – membership flows one way – so it counts per backend URL and this drains them here, on the tick that already talks to it.BOTH halves, and the successes first.
consecutive_reported_failuresis the only counter that can condemn a wedged engine, and it is a streak – but on the router path nothing ever cleared it.report_successhas exactly one caller, on the native adapter, so a router run made the streak monotonic and every shard reachedunhealthy_thresholdeventually, however healthy. Three unrelated blips days apart, with thousands of successes between them, condemned a shard.Successes first because they describe the same window: replaying failures onto a streak that a success in that window should already have cleared is what made the count monotonic in the first place. A genuinely wedged shard produces no successes, so its condemnation timing is unchanged.
Deliberately not a reset on a clean probe: the reported streak is kept separate from the probe streak precisely because a wedged engine still answers
is_alive.
- _stand_down_refit_deadline(shard_idx: int) None#
Tell every policy worker to cancel an in-flight refit deadline.
Fire-and-forget, and deliberately not awaited: this runs inside a probe whose job is to keep the ledger current, and a worker that cannot answer is already the larger problem. Reaching the worker at all depends on the refit running off its event loop – see await_off_loop.
Only ever called for a CONFIRMED actor death. A frozen rank never produces one, so its deadline still fires and still ends the run attributably.
- async _reconcile_refit_membership(
- force: bool = False,
Ask the weight transport to match the live fleet before the refit runs.
A no-op without fleet health: with no monitor there is no notion of a shard being gone, so the transport keeps the membership it was built with – which is the pre-existing behaviour, and why this is inert by default.
Returns whether the communicator was actually rebuilt, or None when the transport owns no membership at all. The recovery path needs all three: after an abort the old communicator is gone, so “nothing to reconcile” means there is nothing to retry with either – but “this transport has no membership” is a different refusal and deserves a different message.
forcesays the communicator is gone rather than merely unchanged. The synchronizers skip a rebuild when the absent set matches what they last built with, which is what stops a lost shard costing two full rebuilds on every subsequent step – but after an abort the membership is identical and the communicator is dead, so the recovery path has to override that or it retries over nothing.
- _recovery_window() collections.abc.Iterator[None]#
Mark the span where the serving set is deliberately empty.
_recover_from_failed_refit marks every serving shard partial, so they all go STALE and serving_shards() is empty until _record_refit_landed runs – after a rebuild and a full retry refit, both of which await and yield the event loop.
_stall_watchdog_pump is a task on that same loop and calls raise_if_exhausted() on every tick, defaulting to one every 30s. With min_healthy_shards=1 and zero serving, any tick landing in this window ends the run over an exhausted fleet while the retry that would have refilled it is still in flight – killing the recovery that was about to succeed, and blaming the wrong thing in the log.
A flag rather than deferring mark_weights_partial until after the rebuild: that would also close the window, but it would leave shards holding a mix of old and new weights in the serving set while it did.
- async _recover_from_failed_refit(
- failure: BaseException,
- *,
- refit_started: bool,
Drop whatever stopped participating, rebuild the communicator, allow a retry.
Two failures arrive here and they are not the same event:
RefitAborted– pausing timed out, or a rank went silent inside the collective and a watchdog broke it. Only the latter leaves receiving engines holding partial weights; those cannot serve until a refit completes.RayActorError– a shard died before transfer, or in the epilogue after the collective finished. Nothing is partial; survivors have complete weights.Both need the same repair, because both leave a communicator that no longer matches the fleet, and in the abort case no communicator at all.
The probe here is the point. Waiting for the health monitor to reach its own conclusion is what failed before: its verdict is paced by probe rounds while this is an event, so the abort arrived first and the rebuild saw an empty absent set and did nothing. Asking now, on this thread, turns a race into a lookup.
- _refit_participants() set[int]#
Shards eligible to receive this refit’s weights, as of right now.
Captured at the moment membership settles rather than read at promotion time, because a restart finishing mid-transfer turns its shard STALE – which is not absent – and the communicator was already built without it.
Derived from the fleet rather than from the transport’s membership so it holds for backends that own no membership at all: a shard that is absent when the transfer starts receives nothing either way.
- _record_refit_landed(participants: set[int]) None#
Write down what each shard now holds, and return the STALE ones to service.
Two things, because they are the same fact seen from two sides: this refit reached these shards. The version is what they hold; promotion is what that entitles them to.
Promotion is the exit from STALE, and the reason marking partial weights is safe rather than terminal. An aborted refit leaves every engine that was receiving with a mix of old and new weights, so they are pulled out of service – but nothing else moves a shard out of STALE, so without this the recovery would succeed and then leave the fleet empty, which
raise_if_exhaustedwould end the run over. A worse failure than the one being recovered from, and reached only on the recovery path.Only STALE shards are promoted. A SUSPECT shard also took part in the refit, but it is failing probes for its own reasons and promoting it here would reset the failure count that is supposed to condemn it. It is still stamped: what weights an engine holds is not a verdict on how well it is serving them.
And only STALE shards that were IN the refit. Asking “is this shard STALE?” alone was correct until restart existed, because nothing could turn a shard STALE while a refit was in flight. A restart can: it takes minutes, nothing blocks it, and mark_loaded moves the shard DEAD -> STALE at whatever moment the reload lands. A shard absent when membership settled received no weights from this transfer, so promoting it would return it to service holding the checkpoint it read off disk – the outcome this module’s docstring exists to prevent. It stays STALE, is not absent, and the next refit picks it up.
The stamp used to live inside
report_refitalone, which meant it was only ever written by a promotion. Nothing turns a shard STALE on a refit that succeeds, so a fleet that has never lost a shard reports version 0 for the life of the run however many refits it received – and a metric that reads 0 on every healthy shard is one nobody watches, which is the part that matters: this is the reading that would catch the next bug of this shape.- Parameters:
participants – shards eligible for this refit, from :meth:
_refit_participantsat the point membership settled.
- async _check_env_health(timeout_s: float) list[str]#
Ask each environment actor that exposes a health check whether it is whole.
Returns the problems found, empty when everything is well. It reports rather than raises so the caller can route the verdict through
stall_action, the same way the stall path does. Raising here bypassedstall_actionentirely: under the documented default ("warn", which promises to “only report”), and withgym_subprocess_checkdefaulting to true, an unhealthy environment killed the run – a run-ending path switched on by default, in a feature whose whole posture is inert-by-default.Each probe is bounded.
NemoGymis an asyncio actor, so a wedged environment – precisely the case this check exists to catch – left the await hanging forever, the pump never ticked again, and stall detection was dead exactly when it was needed. A probe that does not answer within one tick IS the unhealthy signal; it is not a reason to stop watching.Environments without the method are skipped rather than treated as unhealthy; only NeMo-Gym has subprocess servers to lose.
- async _abort_stale_inflight() int#
Abort in-flight rollouts that the sampler can no longer select.
- _prune_finalizer_state(selected_group_ids: set[str]) None#
Release pending finalizer state for groups evicted before training.
Eviction reports only a count, so reconcile against the groups that can still be consumed: those in the buffer plus those already selected by the step in progress.
- async _rollout_telemetry_pump() None#
Sample generation and publication throughput at a fixed cadence.
- async _log_rollout_throughput_metrics(*, emit: bool = True) None#
Serialize backend sampling so cumulative counters have one baseline.
- async _collect_and_log_rollout_throughput_metrics(
- *,
- emit: bool = True,
Compare generation-engine output with canonical TQ publication.
- async _save_checkpoint(
- step_metrics: dict[str, Any],
- *,
- is_policy_training_step: bool,
- is_final_checkpoint: bool,
- publish_now: bool = False,
Serialize full and rollout-only checkpoint publication.
publish_nowstarts publishing step_N in the background even withdefer_async_checkpoint_finalize, as the checkpoint deadline needs.
- async _save_checkpoint_impl(
- step_metrics: dict[str, Any],
- *,
- is_policy_training_step: bool,
- is_final_checkpoint: bool,
- publish_now: bool = False,
Write a full checkpoint for the just-finished train step.
Everything except the (possibly async) policy weight write must be on disk before
_publish_when_policy_write_done, which is why it runs last. Non-colocated engines keep serving rollouts throughout. Colocated engines are stood down for the save. The policy optimizer is skipped during critic warmup: it has never stepped.
- async _publish_when_policy_write_done(
- checkpoint_path: nemo_rl.utils.checkpoint.PathLike,
- *,
- publish_now: bool = False,
Arrange for tmp_step_N to become step_N once the policy write lands.
The only way a full checkpoint gets published. Call it only after every other part of the checkpoint is on disk.
- async _finish_pending_save(*, blocking: bool) None#
Finalize and publish a save deferred by defer_async_checkpoint_finalize.
Called from the train pump between policy-worker calls, and once at teardown after the pumps stop: the finalize runs collectives on the training communicator, so every rank must reach it at the same point. A non-blocking poll finalizes the save on every worker only once all ranks’ background writes are done; until then the write overlaps training. tmp_step_N becomes step_N after the finalize, under the same lock as every other checkpoint publication. The save stays pending until the rename has started, so a cancellation while waiting for the lock leaves it for the teardown publish.
- _REFIT_UNWIND_GRACE_S#
60.0
- _GENERATION_CONTROL_TIMEOUT_S#
360.0
- _refit_await_budget_s() Optional[float]#
How long to wait for the refit before giving up, or None to wait forever.
- async _sync_weights_within(kv_scales, what: str) None#
Run the refit off-loop, and stop waiting if it outlives the deadline.
WHY THIS IS NEEDED ON TOP OF EVERY WORKER-SIDE BOUND. A frozen-but-alive rank is a Ray actor that never answers, and Ray puts no timeout on an actor call. So the controller’s await never resolves however well the workers behave. Job 6508251 measured that end state: the deadline fired, the workers aborted, the trainers returned, every actor was idle – and the run still sat for 1800s because this await had no bound. It is the last unbounded wait on the refit path, and unlike the others it is not in NCCL or CUDA.
Timing out raises RefitAborted so this joins the existing recovery path rather than inventing a second one: the caller reconciles membership and retries once. By then the fleet probe has usually condemned the silent shard, so the rebuild can exclude it and the retry may genuinely succeed.
A DEDICATED DAEMON THREAD, not asyncio.to_thread. to_thread runs on the default ThreadPoolExecutor, whose workers are non-daemon and are joined at interpreter exit – so a thread still blocked on the frozen actor would hang shutdown, trading a wedge in the refit for a wedge on the way out. asyncio.wait_for cannot cancel a running thread either way; this only controls whether the orphan can block exit.
The orphan is a real consequence, not a free win. If the retry succeeds the run continues with a thread still parked inside the old sync_weights, and if that rank were ever resumed it would wake up holding a communicator that has since been replaced. Acceptable against a guaranteed 30-minute stall, and it is why this path is bounded-failure-first rather than resume-and-forget.
- async _sync_weights_in_refit_actor(
- kv_scales: Optional[dict[str, float]],
- what: str,
- budget_s: Optional[float],
_sync_weights_withinfor a RefitActor: await its ObjectRef, no thread.
- async _sync_weights(
- *,
- calibration_data: Optional[nemo_rl.distributed.batched_data_dict.BatchedDataDict[Any]] = None,
Pause rollout dispatch and generation, synchronize weights, resume.
SC owns the rollout-dispatch gate and asks every generation backend to pause in-flight work through the common refit lifecycle hooks. Backends without native pause support warn and retain their existing in-flight update behavior. Continuous-serving vLLM preserves request state while paused. A colocated engine is already stood down before training; the synchronizer’s sync remains its weight-carrying wake.
Flow:
_rollout_permitted.clear() — no new dispatches
Reconcile refit membership and optionally calibrate FP8 KV-cache scales.
Materialize deferred policy parameter all-gathers.
generation.pause_generation_for_refit(clear_cache=…)
weight_synchronizer.sync_weights(kv_scales=…)
generation.resume_generation_after_refit()
_rollout_permitted.set() — resume dispatch
- Parameters:
calibration_data – Optional data used to calibrate FP8 KV-cache scales before synchronizing weights.
- Returns:
The number of stale in-flight rollout groups aborted before the weight synchronization.
- async _value_stage(
- meta: nemo_rl.data_plane.KVBatchMeta,
- *,
- already_prepared: bool = False,
Run the PPO value model’s forward pass over the selected chunk.
Tensors never touch SC: workers fetch the sequence columns from DataPlane and commit the per-token prediction back under
values, which the advantage stage then reads alongside the rewards. Shared workers offload after the forward; dedicated workers keep it resident. Streaming may prepare it before the chunk’s rollout data is ready.- Parameters:
meta – Selected chunk’s metadata.
already_prepared – Reuse the critic residency prepared before waiting for this chunk instead of loading the model again.
- Returns:
The batch metadata with the
valuescolumn recorded on it.
- async _value_train_epochs(
- metas: list[nemo_rl.data_plane.KVBatchMeta],
- *,
- num_epochs: int,
Replay all step chunks per critic epoch under one residency cycle.
- async _advantage_stage(
- meta: nemo_rl.data_plane.KVBatchMeta,
- *,
- policy_logprobs_required: Optional[bool] = None,
Fetch advantage inputs, compute advantages, and write them back.
SC owns the prompt-group-scoped advantage stage because the selected
KVBatchMetastill contains complete prompt groups before trainer DP sharding. Tensor payloads still move through DataPlane: SC fetches only the configured advantage input columns and writes the computedadvantagescolumn back under the samesample_ids.- Returns:
The updated batch metadata and whether the batch contains at least one valid training token.
- async _flush_advantage_dumps() None#
Wait until every advantage writer has stored this step’s dump chunks.
- async _run_advantage_stage( ) nemo_rl.algorithms.single_controller_utils.advantage_stage.AdvantageOutcome#
Run one advantage stage on the pool, or in-process without one.
- _absorb_advantage_outcome( ) None#
Fold one call’s reduced results into this step’s accumulators.
- _retune_lookahead_versions() None#
Widen the sampler’s lookahead while the policy is frozen, then shrink it back.
Port of ppo.py’s _async_ppo_generation_lead_steps.