Repository navigation
feat(sc): contain rollout failures in the SingleController path - #3470
asolergi-nv wants to merge 34 commits into
Conversation
Splits rollout failures into infrastructure (the prompt is fine, the fleet is not) and data (deterministic and prompt-specific). That split drives the retry policy landing in follow-up commits: infra failures re-dispatch the prompt onto another generation shard, data failures get a small budget because another shard would fail identically. HTTP errors are classified by status rather than by type. vLLM answers an over-long prompt with 400 "This model's maximum context length is ...", so treating every aiohttp ClientError as infrastructure would spend the retry budget on a prompt no shard can serve. 5xx plus 408/429 are infra, which matches the set NeMo-Gym itself retries in nemo_gym/openai_utils.py. Anything unrecognized is classified as data so that unexpected exceptions fail loudly rather than being retried into silence. Adds the async_rl.rollout_failure and async_rl.watchdog config blocks plus the three timeout fields. Every default is inert: the timeouts default to null, so a config that does not mention these fields behaves exactly as it did before. The validators reject combinations that would silently do nothing -- notably on_data_exhausted=skip with a zero skip budget, which would otherwise behave exactly like fail_fast while reading as though bad prompts were tolerated. No behaviour change yet: nothing consumes the taxonomy or the config until the following commits. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: asolergibert <[email protected]>
_run_single_rollout caught every exception from _generate_response, printed it,
and broke out of the turn loop. Execution then fell through and built a
Completion holding only the prompt with reward=0.0, which generate_and_push
committed as a training row.
It did not even crash downstream. add_grpo_token_loss_masks_and_generation_logprobs
zero-fills a missing generation_logprobs and sets token_loss_mask=0, so the row is
well formed and contributes no gradient -- but its zero reward does enter the
per-prompt GRPO baseline. With use_leave_one_out_baseline a single dead vLLM
worker silently shifts the advantage of every sibling in the group, for the rest
of the run, with nothing in the logs but a print.
Generation failures are now classified and raised: infrastructure errors become
GenerationUnavailable, everything else RolloutDataFailure, both carrying the
prompt and trajectory coordinates a raw traceback lacks. The try body is narrowed
to the generation call so the surrounding bookkeeping can no longer be skipped
half-done, and CancelledError still passes through untouched because it is not an
Exception.
Two adjacent fixes the propagation exposes:
- asyncio.gather propagates the first exception but leaves the remaining
awaitables running detached, so a failed group left N-1 generations queued
against the fleet for a result already being discarded.
_gather_cancelling_siblings cancels and drains them first. This was latent
before -- calculate_rewards could already raise -- and matters more once
retries land.
- The gen_leader_worker_idx catch is narrowed from Exception to
(IndexError, TypeError, ValueError). It is a load-accounting metric and must
not fail a rollout, but the catch should not hide unrelated errors.
Behaviour change: a dead generation shard now fails the run loudly instead of
quietly degrading the batch. The re-dispatch policy that keeps the run alive
lands in a follow-up commit; correctness first.
Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: asolergibert <[email protected]>
Nothing in the SingleController rollout path had a deadline. NeMo-Gym compounds this: it passes aiohttp ClientTimeout() -- every field None, so all timeouts disabled -- and retries ClientOSError and ServerDisconnectedError in uncapped 0.5s loops. A dead vLLM endpoint therefore parks a rollout forever, and each parked rollout permanently holds one _buffer_capacity and one max_inflight_prompts permit. Enough of them and the rollout pump blocks on sem.acquire() while the train pump spins, with no exception raised anywhere. Adds deadlines at the three waits, resolved from async_rl into a RolloutTimeouts dataclass so async_rl remains the single place a default lives: - the whole NeMo-Gym prompt-group stream (rollout_timeout_s) - one generate_async turn on the native path (generation_timeout_s) - one calculate_rewards environment step (env_timeout_s) The gym deadline deliberately spans the entire stream rather than each await. Gym yields rows as they finish, so a per-await budget would reset every time a fast row landed and never fire for the slow row actually holding the group up. The env deadline frees the rollout, not the thread: Python cannot kill a running thread, so a hung env call keeps its thread-pool slot until its own ray.get returns. Unblocking the rollout is still the point. _Deadline wraps asyncio.timeout and consults expired() before relabelling, so a TimeoutError raised by the wrapped code is not reported with our deadline's duration -- that would send anyone debugging it to the wrong knob. Expiry surfaces as RolloutTimeout, an infra failure, so the retry policy will treat it as retriable. Outer cancellation still propagates as CancelledError. Also reclassifies the truncated-gym-stream error from bare RuntimeError to GymTransportError and names the missing rows. Rows going missing is a transport problem and must be retriable rather than reading as a bad prompt. All three default to null, so a config that does not set them behaves exactly as before. Two pre-existing object.__new__ test fakes are updated for the new attribute. Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: asolergibert <[email protected]>
P0.2 made a dead generation shard fail the run loudly rather than quietly
corrupting the batch. This restores availability without giving the corruption
back: generate_and_push now retries, and no prompt is discarded for
infrastructure reasons.
An infra failure says the fleet is unwell, not the prompt, so the attempt is
retried. The retry re-enters generation-shard selection, which is what makes it
land somewhere else -- generate_and_push itself knows nothing about shard health,
and does not need to. Exhausting the infra budget therefore means the same
failure followed the prompt across repeated selections, which is reported as
RolloutRedispatchExhausted rather than absorbed.
Deterministic failures get their own, much smaller budget. Another shard rejects
the prompt identically, so retrying mostly burns time -- but one retry is still
worth taking, because a shard under memory pressure can return an empty
generation that looks deterministic and is not. On exhaustion the default is to
fail the run, since a genuinely deterministic failure is almost always a config
bug (usually max_total_sequence_length versus the engine's max_model_len).
on_data_exhausted=skip exists for long soaks and is bounded by a run-wide
max_skipped_prompts.
Details worth knowing when reading this:
- The slot is reserved inside the loop, so each attempt owns a fresh group_id
and a failed attempt's rows cannot collide with the retry's.
- The loop condition is the infra budget, so exhaustion exits through a normal
terminal rather than raising from inside the handler. RolloutRetryPolicy
rejects a zero budget, which is what makes that terminal's invariant hold.
- Data failures do not back off. Waiting cannot help a deterministic failure.
- Cancellation is caught by a separate `except BaseException` and never
retried: tearing down the controller must not look like a transient fault.
- A SKIPPED prompt never reaches the buffer, so the train pump will never
release its backpressure permit. _dispatch_one_prompt releases it directly;
getting this wrong leaks one slot per skipped prompt until the pump wedges.
There is a parametrized test pinning both branches.
RolloutStats counts commits, skips, re-dispatches and data failures by reason.
A rising re-dispatch count is the only externally visible sign that the fleet is
degrading, so it is not optional bookkeeping. Wiring it into the SC logger comes
with the watchdog.
Known gap, deliberately deferred: a gym retry currently redoes the whole prompt
group rather than only the rows that never arrived. _run_rollouts already tracks
received_row_indices and trajectory_collector.py has the prior art, so partial
re-dispatch is a follow-up rather than a redesign. Correct and wasteful before
efficient.
Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: asolergibert <[email protected]>
Every other guard in this phase reacts to something raising. The wedge this work exists to prevent raises nothing at all: rollouts sit in NeMo-Gym's uncapped retry loop, the train pump spins on sleep(0.005), and Ray reports everything healthy. The only way to see it is to notice that committed groups stopped moving while rollouts are still in flight. _watchdog_pump runs as a third asyncio task and does two things. It publishes the RolloutStats counters plus in-flight and idle-time gauges, so a degrading fleet is visible before it wedges -- rollout/idle_s is the leading indicator. And it reports a stall, defined as in-flight rollouts with no commits for stall_timeout_s. Progress is measured by the committed counter rather than a timestamp because "no group has landed" is the property that matters, whatever the cause. An idle controller with nothing in flight is explicitly not a stall; between epochs there is legitimately no work. stall_action defaults to warn so the threshold can be tuned against a real workload before it is allowed to end a run. NemoGym gains health_check(), a thin wrapper over NeMo-Gym's own RunHelper.poll(). Gym already implements that check and calls it every 60s from run_forever(); NeMo-RL only ever called rh.start(), so it never ran. Without it a dead tool server surfaces as unexplained rollout timeouts rather than a named process. The watchdog polls every environment handle that exposes the method and skips those that do not -- only NeMo-Gym has subprocess servers to lose. While there: NemoGym now declares rh/rch/head_server_config/node_ip/ head_server_port in __init__ and guards the methods that need them. Ray recreates a restarted actor through __init__ alone, which does not start the Gym servers, so a restarted NemoGym previously surfaced that state as an AttributeError from deep inside a rollout. It now says what actually happened. shutdown() became a no-op in that state too, since it runs in a finally block and must not mask a real training error. run() awaits the watchdog first when several tasks finish together: it only completes by raising, and its diagnosis is more specific than the pumps', whose own symptom would just be "waiting". Co-Authored-By: Claude Opus 5 <[email protected]> Signed-off-by: asolergibert <[email protected]>
Fault injection found this: killing a vLLM generation worker wedged the loop for
six minutes while the watchdog watched and said nothing.
The stall condition required rollouts to be in flight, on the reasoning that an
idle controller has legitimately no work. The wedge has none. _sync_weights
clears _rollout_permitted on entry and only sets it on exit, so a hung weight
sync leaves the gate shut and the rollout pump parked at
`await self._rollout_permitted.wait()` -- before dispatch, before anything can
fail. Nothing is in flight to count, nothing fails, and the run sits there.
The watchdog's own metrics from that run diagnose it exactly:
rollout/inflight: 0.0 at every sample
rollout/idle_s: 371.8 <- it saw the idleness
rollout/redispatch_total: 0.0 <- no rollout ever failed
rollout/committed_total: 10, frozen
and train/loss stopping one step short of the watchdog's own step counter places
the hang inside _sync_weights: _train_pump increments _train_steps, then syncs,
then logs. The sync is a NCCL broadcast to an inference rank that no longer
exists, and ray.get on the trainer future comes before the one that would have
raised ActorDiedError.
Progress is now the pair (committed groups, completed train steps), and what
separates a stall from an idle gap is whether work remains, not whether anything
is in flight. rollout/train_steps is published alongside so the two can be told
apart from outside.
Also adds tests/functional/grpo_dp_single_controller_chaos.sh, the harness that
found this. Two things it has to do that are not obvious:
- Teardown reaps VLLM::EngineCore and the policy workers, not just the driver.
vLLM runs its engine in a child process that survives its parent actor being
killed -- which is exactly what this test does on purpose -- and the orphan
holds tens of GB of device memory. A leaked run made the next one fail in
placement-group setup, reading as an unrelated flake. It is hard to spot
because nvidia-smi in a container reports host pids, so the offender is
invisible to `ps -p`.
- Startup refuses to run on a dirty GPU, so a leftover allocation cannot be
misreported as a failure of the code under test.
On the run that passes, the re-dispatch path catches the kill in ~10s:
ActorDiedError -> GenerationUnavailable -> three attempts -> exhausted. Ray
reports actor death immediately, so the generation deadline never has to fire.
Not in any CI lane: it needs GPUs and is timing-sensitive.
Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: asolergibert <[email protected]>
A gym retry redid the whole prompt group. NeMo-Gym's stream dies on its first
failing row, so one bad row takes every later row with it -- at
num_generations_per_prompt=16 that means paying 16 generations to recover
however many were actually lost.
_run_rollouts now keeps completed rows across attempts and re-sends only the
pending ones, which is the same shape as the legacy collector's pending-group
retry in trajectory_collector.py. A 5-row group that loses rows 3-4 costs 7
row-generations instead of 10.
Three details that shape the implementation:
- The deadline still belongs to the prompt group, not to each attempt.
Wrapping each attempt instead would silently multiply rollout_timeout_s by
max_gym_row_attempts.
- Only infrastructure failures are re-dispatched. A prompt NeMo-Gym cannot
serve fails the same way every time, and retrying it here would also
multiply against the outer data budget in generate_and_push.
- Row indices are validated against the original group rather than the pending
subset, because a re-dispatched row keeps its original _rowidx so results
stay ordered. That makes "_rowidx equals position" a contract of
_run_rollouts, so it is now checked up front -- the alternative is a KeyError
several frames deeper.
max_gym_row_attempts defaults to 3, matching the legacy
_MAX_NEMO_GYM_STREAM_RETRIES. The RolloutRetryPolicy default stays 1 so a
directly-constructed RolloutManager does not silently gain retries.
Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: asolergibert <[email protected]>
The harness selected its victim with pgrep -f 'ray::.*[Gg]eneration'. In a run against vLLM 0.25.1 that matched a process which was NOT the serving generation worker: the kill landed, generation carried on, training reached step 3/50, and the test was on course to report a wedge that never happened -- a false failure of exactly the containment behaviour it exists to prove. Widen the pattern to match both forms the worker appears as (ray::-titled and isolated-venv path; both were observed), but the assertions matter more than the pattern: * print the victim's cmdline, so a mis-target is visible in the log rather than masquerading as a hang; * refuse to proceed unless the victim looks like a generation worker; * verify it actually died, rather than assuming SIGKILL landed. Also raise DEATH_DEADLINE_S from 300s to 600s. An observed run took 222s to fail -- 5 re-dispatch attempts with capped exponential backoff, which is the designed behaviour -- leaving only 26% headroom on a workstation that is faster than CI. Verified on 2xA6000 with TransformerEngine rebuilt for sm_86: [chaos] killing generation worker pid=69107 [chaos] cmdline: ray::VllmAsyncGenerationWorker [chaos] PASS: bounded, attributable failure 222s after the kill Signed-off-by: asolergibert <[email protected]>
The harness was excluded as 'inherently timing-sensitive'. That no longer holds: the death deadline is 600s against an observed 222s, and the victim is now asserted rather than assumed. The recovery tests already in this lane kill processes the same way, so excluding this one was also inconsistent. It matters more than the others. A wedge raises no exception and fails no assertion anywhere else, so without this test a regression that restores the silent hang -- the failure this whole series exists to remove -- would be caught by nothing. Full mode only; it costs ~10 minutes and deliberately drives the job to a non-zero exit. Signed-off-by: asolergibert <[email protected]>
Adding `timeouts` as a required positional argument broke every direct construction of AsyncRolloutImpl. That went unnoticed because production always builds it through the config path, which passes the field -- the only direct construction is in tests. Upstream's new tests/unit/experience/test_rollout_manager_router_replay.py (from NVIDIA-NeMo#3378) is one, so after syncing onto current main it failed with TypeError: __init__() missing 1 required positional argument: 'timeouts'. The rebase was textually clean; the incompatibility is in the signature, not in any line either side edited, so nothing flagged it. RolloutTimeouts is a frozen dataclass whose fields all default to None, meaning "no deadline, wait indefinitely" -- the historical behaviour. So defaulting the parameter restores the old semantics for callers that do not ask for deadlines, rather than silently imposing one. Same reasoning already applied to RolloutRetryPolicy, whose defaults reproduce single-attempt behaviour so a directly-constructed manager does not silently gain retries. No separate regression test: upstream's file is the regression test, and it runs in our lane. Signed-off-by: asolergibert <[email protected]>
…ich state
Victim selection was a coin flip. `pgrep -f` on a loose
'[Gg]enerationWorker' substring, then `head -1`, which picks by pid
order. Sampling a live run 378 times shows what that actually matched:
/opt/ray_venvs/...VllmAsyncGenerationWorker/bin/python a CHILD, not the actor
bash -c exec /opt/ray_venvs/...GenerationWorker... the launcher shell
ray::VllmAsyncGenerationWorker the actor, between calls
ray::vllm_policy-0-0:VllmAsyncGenerationWorker.__init__ the actor, constructing
ray::VllmAsyncGenerationWorker.generate_async the actor, serving a rollout
ray::VllmAsyncGenerationWorker.init_collective_async the actor, setting up refit
ray::VllmAsyncGenerationWorker.shutdown the actor, tearing down
Three distinct processes across five states, because Ray retitles a
worker with setproctitle for the exact duration of each call.
It never failed, and that is the point: every one of those scenarios does
end in a bounded attributable failure, which is all the test asserted. The
divergence was only visible as wall-clock across branches -- 7s on one,
222s on another, for what was supposed to be the same test.
The existing guard did not help. `case $VICTIM_CMD in *[Gg]enerationWorker*`
was added earlier to catch a mis-targeted kill, and it passes for all
seven forms above, including the launcher shell and the venv child. It
checked WHAT was killed and never IN WHAT STATE, so it was structurally
blind to this while reading like protection against it.
Now the actor is matched structurally -- anchored ray:: prefix, optional
<name>: infix -- so the child and the shell cannot match, and the state is
pinned:
idle (default) no method suffix. Nothing is in flight, so the loss
must be DETECTED, by health probe or by the stall detector.
serving .generate_async. An in-flight rollout RPC dies with the worker
and surfaces immediately, detection doing no work.
Not "any method suffix": __init__, init_collective_async and shutdown are
three further distinct scenarios, and folding them in would reintroduce
the ambiguity being removed. The title is re-read immediately before the
kill and the run fails if it changed, so the sub-millisecond window
between scan and kill cannot quietly restore the coin flip.
Both modes registered in the lane. Pinning to idle alone would silently
drop a scenario the old selection used to hit by chance, and the serving
path costs seconds.
Verified on 2xA6000: idle twice -> ray::VllmAsyncGenerationWorker, 222s
both times; serving -> ray::VllmAsyncGenerationWorker.generate_async, 12s,
GenerationUnavailable + RolloutRedispatchExhausted. Regexes checked
against all seven observed titles: each mode matches exactly one.
Signed-off-by: asolergibert <[email protected]>
The pre-flight check took the max memory.used across every GPU and aborted above 1GiB. That is an OR over the whole host, so it gets likelier to trip the bigger the machine: this test pins itself to 2 GPUs, so on an 8-GPU CI runner a single unrelated process on one GPU aborts it with six sitting idle. The message says 'clean up before running', which reads like a real problem with the machine rather than an over-strict check. Count free GPUs and require $GPUS of them instead. It still catches the case the check was written for -- a previous test in the lane leaking a VLLM::EngineCore -- because that drops the free count below the requirement. Verified across simulated host sizes: 2-GPU box, both idle free=2 proceed 2-GPU box, leftover EngineCore free=1 ABORT (still caught) 8-GPU node, all idle free=8 proceed 8-GPU node, one GPU busy free=7 proceed (was: ABORT) 8-GPU node, six busy free=2 proceed 8-GPU node, seven busy free=1 ABORT GPUS is now defined once and feeds both cluster.gpus_per_node and the check, so the two cannot drift apart. Re-ran the chaos test after the change: killed ray::VllmAsyncGenerationWorker in state idle, bounded failure at 222s -- identical to the two runs before it. Signed-off-by: asolergibert <[email protected]>
|
/ok to test 97b309a |
1 similar comment
|
/ok to test 97b309a |
Two files imported the same module twice instead of merging the names,
which ruff's isort rules (I001) reject:
from nemo_rl.experience.rollout_manager import RolloutManager, RolloutTimeouts
from nemo_rl.experience.rollout_manager import (RolloutRetryPolicy,)
`ruff check` did not catch this locally, and neither did the SLURM run --
both reported "All checks passed!". The repo's .pre-commit-config.yaml
registers the ruff hook twice:
- id: ruff
args: ["--fix"]
- id: ruff
args: ["check", "--select", "I", "--fix"]
Only the second selects `I`, and `I` is not in the default selection that
a plain `ruff check` uses. So the rule that failed in CI was never being
run locally. Verified by reproducing it: `ruff check --select I` reports
exactly the two errors GitHub reported, and the fix it applies is
byte-identical to the diff in the CI log.
Both files are ones this branch introduced changes to; no unrelated files
were touched.
Signed-off-by: asolergibert <[email protected]>
|
/ok to test 85afdb2 |
|
/ok to test 85afdb2 |
|
/ok to test 8bb7148 |
Merging main brought in NVIDIA-NeMo#2518, which moves GRPOConfig from TypedDict to a pydantic BaseModel, so `master_config.grpo["key"]` becomes `master_config.grpo.key`. The merge was textually clean and left three sites broken. Two were visible: test_rollout_pump.py fed `grpo={"max_num_epochs": 1}` into _rollout_pump, which NVIDIA-NeMo#2518 migrated to attribute access, giving "AttributeError: 'dict' object has no attribute 'max_num_epochs'" on both parametrisations. The third was not visible, and is the one that mattered. single_controller.py read `self._master_config.grpo["max_num_steps"]` while test_watchdog_pump.py passed a dict -- self-consistent, so the unit tests stayed green while production, which now receives a real pydantic config, would have raised at runtime in the watchdog. A functional test would have caught it; no unit test could, because the fake and the code agreed with each other and both disagreed with reality. Fixtures now build GRPOConfig.model_construct(...), matching how NVIDIA-NeMo#2518 migrated upstream's own fixtures in the same file. 315 passed across tests/unit/single_controller and tests/unit/experience. Signed-off-by: asolergibert <[email protected]>
GRPOConfig.model_construct(...) made two assignments exceed the line limit, so ruff-format wanted to wrap them. CI's ruff-format hook would have rejected this. It was reported as clean locally because the check itself was wrong: `ruff format --check ... | grep -o 'already formatted'` matches the tail of "2 files would be reformatted, 542 files already formatted". Checking the exit code instead of grepping the message. Signed-off-by: asolergibert <[email protected]>
The chaos harness picked its victim by matching `ray::` process titles. That worked on a workstation and found ZERO generation actors on a GB200 cluster (job 5861743): the poll never matched, the run simply finished, and both chaos variants reported "job died before the kill" -- a green-looking failure that never killed anything. Process titles are a runtime implementation detail; the GCS actor table is the runtime's own record, so ask that instead. Titles are still used for the idle-vs-serving distinction, because Ray only exposes the running method through the dashboard state API and init_ray disables the dashboard. So: discover authoritatively, refine by title where titles exist, and say so plainly where they do not -- VICTIM_STATE=any then kills a generation actor without pinning the state, which still asserts a bounded attributable failure but stops separating the detection path from the in-flight-RPC path. Also unbuffers the driver. The harness detects progress by grepping the run log, and the driver's stdout is a redirected file, so Python block-buffered it: job 5892910 wrote "train step 3/24" at 10:40:38 and the harness did not see it until 10:48:21, by which time there was nothing left to kill. The actor prints with flush=True, but that only reaches the driver. The remaining changes are all about being able to diagnose the next failure: ACTOR_WAIT_S separates "no actors yet" from "actors never reached the state", which were previously indistinguishable in the log; ACTOR_QUERY_TIMEOUT_S bounds one discovery attempt; and the helper's stderr is printed inline rather than to a side file, because two attempts at a side file never produced one that survived to be read. Developed while getting the recovery tests to run on the cluster, and belongs here: none of it depends on anything the later branches add, and without it this branch's chaos test cannot pass on that hardware at all. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
…01-containment # Conflicts: # nemo_rl/environments/nemo_gym.py
The main sync brought upstream's test_logs_setup_timing_metrics, which builds
actor_args as a SimpleNamespace listing only the fields upstream's own __init__
reads. env_handles is not among them -- upstream declares it on
SingleControllerActorArgs but never touches it in __init__ -- so our
environment-health-check read turned a field nobody else needs into a
construction requirement, and the test died with AttributeError.
getattr with a {} default. Every production caller goes through the dataclass and
still supplies it, so behaviour is unchanged; only test fixtures that do not
exercise environment health are let off.
Identical in shape to the `timeouts` regression from the previous main sync: a
required parameter we added, discovered by an upstream test constructing the
object directly. Worth remembering as the recurring cost of reading new fields
in __init__ rather than where they are used.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: asolergibert <[email protected]>
|
/ok to test 9a3e424 |
b7d4e79 to
933cf55
Compare
|
/ok to test 933cf55 |
chaos-serving failed in GitHub CI without running a line of product code: 19:51:42.05 [chaos] PASS (chaos-idle) 19:51:43.40 chaos-idle's bash exits, cleanup trap done 19:51:43.56 [chaos] FAIL: need 2 free GPUs, found 1 19:51:43.58 0, 50479 MiB <- still held, by a live pid Three things compound. cleanup() signals and returns, but SIGKILL does not free device memory synchronously -- a worker holding ~50GB stays in nvidia-smi for seconds while the driver tears its context down. run_test is just `time "$@"`, so the next test starts with no gap. And the pre-flight was a single sample with no retry, on a 2-GPU runner where one leaked GPU is the whole margin. It passed on the cluster only because submit-ci.sh sleeps 5s between tests. That hygiene belongs in the test that makes the mess, not in one driver: cleanup() now waits for the memory to come back, and the pre-flight waits rather than sampling, so it is robust to anything else on the box too. Also moves the pre-flight above the training launch. It used to run after, so a refusal was not a refusal -- the driver was already up and the EXIT trap shot it down, which is where the stray "line 129: <pid> Killed" in the CI log came from. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
terrykong
left a comment
There was a problem hiding this comment.
Team review — 5 agents (RL expert, bug finder, test reviewer, design reviewer, devil's advocate); every finding below survived an adversarial verification pass (4 candidate findings were dropped by it).
This is a well-built PR solving a real, previously unowned problem — the failure taxonomy's module-function shape, the pydantic→dataclass layering (with its dependency-direction rationale), the watchdog pump's mirroring of the sibling pumps, and the chaos harness's pinned victim selection are all genuinely good work, and the unit suite is unusually thorough (it even cross-checks Gym's own retry-status list against the classifier).
Two items we'd ask to address in this PR (both inline): the Ray-boundary classification defect — as written, the status-based INFRA/DATA split and the max_attempts_per_prompt re-dispatch budget cannot engage on the NeMo-Gym path, which is where the motivating dead-endpoint failure lives — and the env-health check's bypass of stall_action plus its unbounded await. Everything else is a suggestion or follow-up.
On the two pre-flagged reviewer questions: (1) the attempt budgets in rollout_failure apply to both rollout paths (the retry loop sits above the impl split); the genuinely path-specific, silently-ignored keys are the async_rl timeout trio — see the inline comment proposing a setup-time guard. (2) Neither "prompt longer than max_model_len" nor "generated to the token limit" can kill a run: the native path returns a zero-generation / truncated result without raising, and Gym absorbs the context-length 400 into an empty finish_reason="length" completion before it ever reaches NeMo-RL — verified on both paths.
Linters: all pre-commit hooks pass locally (pyrefly not runnable on this host; CI covers it). failures.py is correctly registered in pyrefly.toml.
Generated by Claude Code
| # the retriable 4xx mean the endpoint is unwell, which another shard can serve. | ||
| status = _http_status(exc) | ||
| if status is not None: | ||
| return status >= 500 or status in _RETRIABLE_HTTP_STATUSES |
There was a problem hiding this comment.
nemo_rl/experience/failures.py:197
2 action items — please fix in this PR.
TL;DR — every NeMo-Gym HTTP failure crosses the NemoGym Ray actor boundary, which destroys the exception's type and .status, so this status-based INFRA/DATA split never runs in production: a 503 from a sick vLLM endpoint classifies DATA and kills the run after 2 attempts under the default on_data_exhausted: fail_fast — the 5-attempt max_attempts_per_prompt re-dispatch never engages.
PR-introduced (defect in PR-introduced code). Mechanism:
- Gym raises
aiohttp.ClientResponseErrorinside theNemoGymactor (nemo_gym.py#L533). - Ray pickles the cause into
RayTaskError. A realClientResponseErrorcarriesCIMultiDictProxyheaders (aiohttp'sraise_for_statuspassesheaders=self.headers), which cannot pickle — so Ray replaces the cause with a bareRayError(str). - On the driver:
isinstance(e, ClientResponseError)isFalse,getattr(e, "status", None)isNone,__cause__isNone. Verified empirically (live Ray 2.57 + aiohttp 3.14.3): 400 and 503 both arrive as bareRayTaskError→ DATA. - The unit tests stay green because they construct
ClientResponseError(None, (), ...)— headerless, hence picklable — and never cross a Ray boundary.
Two facts make this the dominant gym failure path, not a corner case: Gym's exception middleware converts inner-server errors to 500 (server_utils.py#L562-L571) — exactly the status this branch would call INFRA — and Gym's transport layer retries ServerDisconnectedError/ClientOSError in an uncapped while True (server_utils.py#L219-L245), so those never reach NeMo-RL at all. Net: out of the box, max_attempts_per_prompt effectively cannot apply on the gym path — the path whose dead-endpoint scenario motivates this PR. To be clear, this is an unmet promise rather than a regression: main was 1-attempt-fatal here, this PR makes it 2.
The same boundary affects the native path: RayTaskError itself is not in _INFRA_TYPES (and issubclass(RayTaskError, RayActorError) is False), so an exception raised inside a still-alive worker — vLLM EngineDeadError, CUDA OOM, both RuntimeErrors — arrives as RayTaskError(RuntimeError) → DATA → 2 attempts → fail_fast, bypassing the re-dispatch machinery built for exactly that. The chaos test kills the worker process (→ RayActorError → INFRA), so it only exercises the covered branch.
AI-1
Classify on the raising side, where the status is still in hand — in NemoGym.run_rollouts's except block (nemo_gym.py#L533), raise a picklable typed failure before the Ray boundary. One way to do it:
status = getattr(error, "status", None)
if status is not None:
detail = f"NeMo-Gym /run failed with HTTP {status}: {error}"
if status >= 500 or status in (408, 429):
raise GymTransportError(detail) from None
raise RolloutDataFailure(detail) from None
raise(GymTransportError/RolloutDataFailure are plain Exception subclasses with a str arg, so they pickle cleanly and classify_rollout_failure's explicit-class fast path wins.)
AI-2
Harden _INFRA_TYPES (failures.py#L136) for the native vector: add ray.exceptions.ObjectLostError (the parent of the already-listed OwnerDiedError/ObjectFetchTimedOutError), ray.exceptions.OutOfMemoryError, ObjectStoreFullError, RaySystemError — and consider treating a RayTaskError whose cause was degraded as INFRA rather than DATA (the infra budget is bounded and backed off, so a genuine bug still surfaces after 5 attempts, whereas a genuine infra event under DATA is unrecoverable).
A test that would have caught this: round-trip the exception the way Ray does (cloudpickle.dumps on a ClientResponseError carrying CIMultiDictProxy headers) before classifying, or assert whatever NemoGym.run_rollouts raises is pickle-round-trippable and still classifies INFRA.
There was a problem hiding this comment.
Confirmed and fixed. Reproduced across a live Ray actor:
503, before RayTaskError -> DATA
503, after RayTaskError(GymTransportError) -> INFRA
400, after RayTaskError(RolloutDataFailure) -> DATA
AI-1 (29299d0): NemoGym.run_rollouts now classifies at the source and raises a picklable GymTransportError/RolloutDataFailure before the boundary. http_status_is_infra is public so both sides share one rule, with a test asserting they agree. TestTheRayActorBoundary builds the realistic headers-carrying error, asserts it cannot be pickled, and checks that what we raise survives and still classifies.
AI-2, partly: added ObjectLostError, OutOfMemoryError, ObjectStoreFullError, RaySystemError — all confirmed uncovered.
Not taken: treating any degraded RayTaskError as INFRA inside classify_rollout_failure. That function is also consulted from the main retry loop and the gym row-retry loop, so it would reach env-step and gym-postprocessing failures — a reward-fn bug or Generation logprobs contain NaN would get up to 15 dispatches before surfacing wrapped, and would inflate redispatch_total, the conflation the :1147 thread asks us to remove.
Scoped it to the generation call site instead (c000b31): a Ray-boundary error from a generation RPC is INFRA, since we know the RPC's purpose there. That also closed a real inconsistency — 2/4's _generate_on_shard already maps RayError to GenerationUnavailable, so the same exception was INFRA there and DATA here. Happy to widen it if you'd rather, though it's probably worth deciding together with 2/4, which makes the same trade implicitly.
| if health_check is None: | ||
| continue | ||
| try: | ||
| await self._ray_get(health_check.remote()) |
There was a problem hiding this comment.
nemo_rl/algorithms/single_controller.py:676
2 action items, 1 follow-up.
PR-introduced. Two ways _check_env_health escapes the watchdog's own safety contract:
- A health failure raises
RuntimeErrorout of_watchdog_pump, whichrun()awaits — so the run dies even under the defaultstall_action: "warn", whose doc says it decides whether the watchdog "only reports, or ends the run". Withgym_subprocess_checkdefaulting totrue, this is a new run-killing path enabled by default, in a PR whose stated posture is inert-by-default. await self._ray_get(health_check.remote())has no deadline.NemoGymis an asyncio actor, so if it is wedged — the motivating case for this watchdog — the await never returns, the pump never reaches the stall check again, and stall detection is dead exactly when it is needed.
AI-1
Route health-check failures through stall_action (warn → print, abort → raise), matching the stall path.
AI-2
Wrap the health RPC in asyncio.wait_for(..., timeout=<interval_s>) and treat a timeout as unhealthy (reported per AI-1) rather than blocking the pump.
Follow-up
gym_subprocess_check gates a generic hook — _check_env_health iterates every env handle exposing health_check; only NeMo-Gym has one today. env_health_check would be the honest name once another env grows one (fine to fold into this PR or defer).
There was a problem hiding this comment.
Both fixed in ac6565e.
AI-1: _check_env_health returns the problems it found; _watchdog_pump routes them through stall_action.
AI-2: each probe is wrapped in asyncio.wait_for(..., interval_s), and a timeout counts as unhealthy.
The second was the sharper catch — the watchdog could be silently disabled by exactly the wedge it exists to detect. Tests cover abort-raises, warn-only-warns, and a health check that never returns not stopping the pump.
On the rename: agreed env_health_check is the honest name. Not done yet — happy to fold in here or take it as a follow-up.
| ) | ||
| # Deadline for one NeMo-Gym prompt-group rollout, covering the whole streaming | ||
| # response. None disables. | ||
| rollout_timeout_s: Optional[PositiveFloat] = None |
There was a problem hiding this comment.
nemo_rl/algorithms/single_controller_utils/config.py:125
1 action item.
PR-introduced. The fault-tolerance keys are split across two levels with mixed scoping, and the path-specific ones are silent no-ops when set for the wrong path: rollout_timeout_s is read only by AsyncNemoGymRolloutImpl (rollout_manager.py#L815); generation_timeout_s/env_timeout_s only by AsyncRolloutImpl (#L504, #L404); rollout_failure.max_gym_row_attempts only by the gym impl — while the rest of rollout_failure governs both paths via the shared retry loop in generate_and_push. A native-path operator who sets rollout_timeout_s: 900 (the most generic-sounding key) gets no deadline and no warning; the YAML comments say all this, but nothing enforces or structures it.
A second cost of the current shape: the three timeouts dangle directly on async_rl among unrelated pump/buffer knobs (max_inflight_prompts, min_groups_for_streaming_train, ...), even though they are fault-tolerance controls — while rollout_failure and watchdog are already blocks. Gathering the whole FT surface into one block fixes both problems at once.
Action: collect the fault-tolerance config into one block — shared budgets at the top level, path-specific knobs in named sub-blocks — so the YAML structure itself carries the scoping and nothing FT-related dangles at the root (one way to shape it, following the repo's nested-BaseModel convention; naming the block fault_tolerance instead of rollout_failure also works):
class NativeRolloutFTConfig(BaseModel, extra="allow"):
# Deadline for a single generate_async turn. None disables.
generation_timeout_s: Optional[PositiveFloat] = None
# Deadline for one environment step. None disables.
env_timeout_s: Optional[PositiveFloat] = None
class NemoGymRolloutFTConfig(BaseModel, extra="allow"):
# Deadline for one whole prompt-group rollout, re-dispatches included. None disables.
rollout_timeout_s: Optional[PositiveFloat] = None
# Re-dispatch just the rows that never arrived before retrying the whole group.
max_row_attempts: PositiveInt = 3
class RolloutFailureConfig(BaseModel, extra="allow"):
# ── shared: consumed by generate_and_push, which sits above the impl split ──
max_infra_attempts_per_prompt: PositiveInt = 5
max_data_attempts_per_prompt: PositiveInt = 2
backoff_base_s: PositiveFloat = 1.0
max_backoff_s: PositiveFloat = 30.0
# 0 = fail fast on first data-budget exhaustion; N > 0 = skip up to N prompts.
# (Collapses on_data_exhausted + max_skipped_prompts -- see the thread on L66.)
max_skipped_prompts: NonNegativeInt = 0
# ── path-specific ──
native: NativeRolloutFTConfig = Field(default_factory=NativeRolloutFTConfig)
nemo_gym: NemoGymRolloutFTConfig = Field(default_factory=NemoGymRolloutFTConfig)async_rl:
rollout_failure: # shared budgets — both rollout paths
max_infra_attempts_per_prompt: 5
max_data_attempts_per_prompt: 2
backoff_base_s: 1.0
max_backoff_s: 30.0
max_skipped_prompts: 0 # 0 = fail fast; N > 0 = skip up to N prompts
native: # AsyncRolloutImpl only
generation_timeout_s: null
env_timeout_s: null
nemo_gym: # AsyncNemoGymRolloutImpl only
rollout_timeout_s: null
max_row_attempts: 3Two things to carry along with the move: (1) _check_watchdog_outlasts_rollouts currently compares stall_timeout_s only against the gym-only rollout_timeout_s, so the invariant it advertises is unchecked against generation_timeout_s/env_timeout_s on the native path — re-point it at the new locations and cover the native pair; (2) nesting fixes readability but a populated wrong-path sub-block is still a silent no-op, so a cheap setup-time check in validate_single_controller_config (reject/warn when the inapplicable sub-block carries non-default values — same idiom as the val_temperature guard in grpo.py#L411-L432) closes the loop.
There was a problem hiding this comment.
Done in 1590e24, close to your sketch: shared budgets at the top of rollout_failure, path-specific knobs under native/nemo_gym (max_gym_row_attempts → nemo_gym.max_row_attempts).
Both carry-alongs:
_check_watchdog_outlasts_rolloutsnow checks all three deadlines rather than only the gym one — that was a genuine gap on the native path; tests parametrize over all three.validate_single_controller_configrejects a populated wrong-path sub-block. It immediately caught the chaos harness setting the gym-onlyrollout_timeout_son a native run, where it had never done anything.
Added one thing beyond the sketch: since every key here is renamed or moved under extra="allow", the old spellings would parse and quietly stop taking effect — for on_data_exhausted: skip that is a behaviour change with no diagnostic. Both levels now reject the old names and name the replacement.
| # Attempts for infrastructure failures (timeout, dead shard, transport). Each retry | ||
| # re-enters shard selection, so it lands elsewhere. Exhausting this means the fleet | ||
| # is broken rather than the prompt, and the run fails. | ||
| max_attempts_per_prompt: PositiveInt = 5 |
There was a problem hiding this comment.
nemo_rl/algorithms/single_controller_utils/config.py:56
1 action item.
PR-introduced. max_attempts_per_prompt beside max_data_attempts_per_prompt reads as "total budget" + "sub-budget", but the two counters are disjoint: infra_attempts gates the loop (rollout_manager.py#L1095) while data_attempts is tracked independently (#L1128) — under the shipped defaults (5, 2) one prompt can consume 6 attempts. The internal dataclass already has the honest name, max_infra_attempts; only _build_retry_policy records the equivalence, so grepping this key never reaches the retry loop.
Action: rename to max_infra_attempts_per_prompt (update the exemplar YAML), and add one docstring line: the two budgets are independent — worst case is their sum minus one.
There was a problem hiding this comment.
Renamed to max_infra_attempts_per_prompt in 1590e24, with the independence of the two budgets stated where the defaults live (worst case is their sum minus one). Exemplar YAML updated, and the old key now raises rather than being silently accepted.
8658257 cleans up what the rename left behind — including the RolloutRedispatchExhausted message, which was telling operators to look for a key that no longer exists.
|
|
||
| missing = [i for i, result in enumerate(results) if result is None] | ||
| if missing: | ||
| raise GymTransportError( |
There was a problem hiding this comment.
nemo_rl/experience/rollout_manager.py:844
2 action items.
PR-introduced. When an intermediate re-dispatch attempt absorbs an INFRA error and a later attempt ends the stream cleanly-but-short, this raise carries no from — the actual transport error (the reason the rows are missing) is lost at exactly the point the operator reads it. Separately, row-level re-dispatches never call record_redispatch, so rollout/redispatch_total — "the only externally visible sign that the fleet is degrading" per RolloutStats' own docstring — stays flat while gym silently retries rows all run.
AI-1
Keep last_error across attempts and raise GymTransportError(...) from last_error.
AI-2
Count row re-dispatches (thread the stats object or a callback into AsyncNemoGymRolloutImpl) under their own reason key.
There was a problem hiding this comment.
Both in e3d0430.
AI-1: last_error is kept across attempts and chained (raise GymTransportError(...) from last_error), with a test where attempt 1 dies on transport and attempt 2 ends cleanly-but-short.
AI-2: row re-dispatches now increment rollout/gym_row_redispatch_total, which meant threading the owning manager's stats object into AsyncNemoGymRolloutImpl.
| f"NeMo-Gym returned invalid row index {rowidx!r} for " | ||
| f"{total_rows} inputs" | ||
| ) | ||
| if rowidx not in dispatched: |
There was a problem hiding this comment.
nemo_rl/experience/rollout_manager.py:768
1 action item.
PR-introduced test gap. Of the three row-index guards in _stream_rows, only the duplicate guard is pinned by a test (match="duplicate row index 0" in test_rollouts.py#L1482); this "not dispatched in this attempt" guard — new in this PR, and the thing that stops a stale echo of an already-landed row from silently overwriting a good results[rowidx] during re-dispatch — has none. Delete these two lines and the suite stays green.
Action: add a case next to the partial-re-dispatch tests: attempt 1 lands row 0 then dies; attempt 2's stream echoes row 0 again → expect ValueError matching "which was not dispatched".
There was a problem hiding this comment.
Added in e3d0430: test_a_stale_echo_of_a_landed_row_is_rejected — attempt 1 lands row 0 then dies, attempt 2 echoes row 0.
Checked it the way you framed it: with the two lines deleted the new test fails, and with them restored it passes.
| ) | ||
| self._stats.skipped += 1 | ||
| return RolloutOutcome.SKIPPED | ||
| self._stats.record_redispatch(reason) |
There was a problem hiding this comment.
nemo_rl/experience/rollout_manager.py:1147
1 action item.
PR-introduced. Data-failure retries are recorded into the same redispatches_by_reason namespace as infra re-dispatches, so rollout/redispatch_total conflates "fleet degrading" with "prompts are bad" — the very distinction the two-budget design exists to make.
Action: record data retries under their own key (e.g. rollout/data_retries_total/<reason>).
There was a problem hiding this comment.
Done in e3d0430 — data retries record under rollout/data_retry_total/<reason>.
Also gave every family an aggregate while in there: data failures previously had only per-exception series, so alerting on "any data failure" required knowing the exception names in advance.
| # Registered in the SingleController L1 lane (full mode). It was originally kept out as | ||
| # "timing-sensitive", but that no longer justifies exclusion: the death deadline is now | ||
| # 600s against an observed 222s, the victim selection is asserted rather than assumed, and | ||
| # the recovery tests in the same lane kill processes the same way. Leaving it out meant |
There was a problem hiding this comment.
tests/functional/grpo_dp_single_controller_chaos.sh:14
1 action item.
PR-introduced. This line, #L79 and #L240 justify decisions by pointing at "the recovery test(s)", which don't exist in this branch — the lane contains only grpo_dp_single_controller.sh and grpo_async_gym_single_controller.sh, neither of which kills processes. Presumably a forward reference to the next PR in the #3454 stack.
Action: name the target explicitly ("the recovery harness added in ") or inline the one-sentence reason at each site.
There was a problem hiding this comment.
Fixed in 19a9506 — two are inlined with the actual reason, and the third names the part of the series that adds the harness.
| """ | ||
|
|
||
| # Attempts for infrastructure failures. 1 means no retry. | ||
| max_infra_attempts: int = 1 |
There was a problem hiding this comment.
nemo_rl/experience/rollout_manager.py:79
1 action item (low severity).
PR-introduced. This dataclass carries a full second set of defaults (1/1/1) that contradict RolloutFailureConfig's (5/2/3). The intent — a directly-constructed RolloutManager must not silently gain retries — is documented and sound, but defaults now live in two places, and a reader here walks away believing the default budget is 1.
Action: make these fields required and have the None-fallbacks construct the explicit single-attempt policy (RolloutRetryPolicy(max_infra_attempts=1, max_data_attempts=1, max_gym_row_attempts=1)), so the only defaults in the codebase are the BaseModel's.
There was a problem hiding this comment.
Done in e3d0430. The three attempt budgets are now required, and RolloutRetryPolicy.single_attempt(**overrides) is the explicit no-retry construction used by the direct-construction fallbacks. RolloutFailureConfig is the only place a retry default lives now.
Used a named constructor rather than making callers spell out all three, so tests don't have to state budgets irrelevant to what they're testing.
| # Ceiling on the exponential backoff, so a long outage retries at a steady rate. | ||
| max_backoff_s: PositiveFloat = 30.0 | ||
| # After max_data_attempts_per_prompt: fail the run, or continue without the prompt. | ||
| on_data_exhausted: Literal["fail_fast", "skip"] = "fail_fast" |
There was a problem hiding this comment.
nemo_rl/algorithms/single_controller_utils/config.py:66
1 action item.
This enum/int pair encodes exactly two meaningful states, and the _check_consistent branch below exists only to reject their one degenerate combination (skip + 0). A single knob makes the illegal state unrepresentable:
max_skipped_prompts: 0(default) → fail fast on the first data-budget exhaustion (re-raise the original error — currentfail_fast), andmax_skipped_prompts: N > 0→ skip up to N prompts, then fail (currentskip).
Nothing is lost: fail_fast with a positive skip count is meaningless today, and skip already requires N ≥ 1. The name self-documents ("allow at most 0 skipped prompts" reads as fail-on-first).
Action: drop on_data_exhausted, keep only max_skipped_prompts. This also deletes the skip+0 validator branch, its test, and RolloutRetryPolicy.skip_on_data_exhausted — the retry loop in generate_and_push just compares against the budget (at 0 the first exhaustion re-raises, which is exactly today's fail_fast).
There was a problem hiding this comment.
Agreed — done in 1590e24. on_data_exhausted is gone; max_skipped_prompts: 0 (the default) fails on the first exhaustion and re-raises the original error, exactly as fail_fast did. The skip+0 validator branch, its test, and RolloutRetryPolicy.skip_on_data_exhausted are all removed.
|
@asolergi-nv I've mirrored this branch (and parts 2–4) from your fork into This PR now continues as #3589 (stack #3593):
Branches were pushed unchanged — head SHA here is identical ( |
…01-containment Signed-off-by: asolergibert <[email protected]> # Conflicts: # nemo_rl/algorithms/single_controller.py # nemo_rl/experience/rollout_manager.py # tests/unit/single_controller/test_rollout_pump.py
Addresses the blocking review finding on NVIDIA-NeMo#3470 (failures.py:197). The status-based INFRA/DATA split never ran in production. Every NeMo-Gym HTTP failure is raised inside the NemoGym actor and must cross back to the driver; aiohttp's raise_for_status passes headers=self.headers, a CIMultiDictProxy, which cloudpickle cannot serialize, so Ray drops the cause and the driver gets a bare RayTaskError with no type and no .status. Everything classified DATA -- capping the gym path at 2 attempts and leaving max_attempts_per_prompt (5) unreachable on the path whose dead-endpoint scenario motivates this series. Verified against a live Ray actor: 503, before RayTaskError -> DATA 503, after RayTaskError(GymTransportError) -> INFRA 400, after RayTaskError(RolloutDataFailure) -> DATA Two things made this the dominant gym path rather than a corner case: Gym's middleware turns inner-server failures into 500 -- exactly the status the INFRA branch is for -- and its transport layer retries disconnects in an uncapped loop, so those never arrive at all. The unit suite stayed green because every case in it builds a headerless ClientResponseError, which pickles. TestTheRayActorBoundary now pins the real shape: it asserts the realistic error CANNOT be pickled, and that what _typed_gym_failure produces survives and still classifies correctly. Also hardens _INFRA_TYPES for the native vector: ObjectLostError, OutOfMemoryError, ObjectStoreFullError and RaySystemError were all falling through to DATA, so a node running out of memory got two attempts and killed the run. Deliberately NOT included: treating a degraded RayTaskError as INFRA. That inverts this module's documented default (unknown -> DATA, because an unrecognized exception is more likely a bug than a blip) and deserves its own discussion, alongside the equivalent trade part 2/4 already makes implicitly. http_status_is_infra is public so the two sides cannot drift, with a test asserting they agree. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
…ging the pump Addresses the blocking review finding on NVIDIA-NeMo#3470 (single_controller.py:676). Two ways _check_env_health escaped the watchdog's own contract: 1. A health failure raised straight out of _watchdog_pump, so the run died even under stall_action="warn" -- whose documented job is to decide exactly that. With gym_subprocess_check defaulting to true, that was a run-killing path switched on by default, in a feature whose stated posture is inert until configured. It now reports problems and lets the caller route them through stall_action, the same way the stall path does. 2. The health RPC had no deadline. NemoGym is 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. The detector could be disabled by the fault it was watching for, silently. Each probe is now bounded by one tick, and a probe that does not answer IS the unhealthy signal. Tests cover all three: abort still raises and names the env, warn only warns, and a health check that never returns does not stop the pump ticking. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
Addresses the review finding on NVIDIA-NeMo#3470 (chaos.sh:26). Both SingleController lane entries run this script with the same EXP_NAME, and it opens with `rm -rf "$EXP_DIR"` -- so the serving run deleted the idle run's run.log and tensorboard artifacts. When serving then failed in CI, the idle evidence you would compare it against was already gone. Suffixing with VICTIM_STATE gives each variant its own directory. submit-ci.sh globs tests/functional/*/run.log, so both directories are collected without any change there. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
… it applies Addresses three review findings on NVIDIA-NeMo#3470 (config.py:56, :66, :125) together -- they rewrite the same lines, so splitting them would leave intermediate commits that do not build. config.py:125 -- the three deadlines dangled on async_rl among unrelated pump and buffer knobs, and each was silently ignored on the wrong path. An operator setting the most generic-sounding one, rollout_timeout_s, on a native run got no deadline and no warning. They now live in named native/nemo_gym sub-blocks, so the structure carries the scoping. Nesting alone does not close it -- these models are extra="allow", so a populated wrong-path block is still inert. validate_single_controller_config now rejects one. The chaos harness turned out to be guilty of exactly this: it set the gym-only rollout_timeout_s on a native run, which had never done anything. Carried along, and a bug in its own right: _check_watchdog_outlasts_rollouts compared stall_timeout_s only against the gym-only rollout_timeout_s, so on the native path the invariant it advertises went unchecked. It now checks every deadline, parametrized over all three in the tests. config.py:56 -- max_attempts_per_prompt beside max_data_attempts_per_prompt read as a total and a sub-total, but the counters are disjoint: under the defaults one prompt can consume six attempts. Renamed to max_infra_attempts_per_prompt, matching the name the internal policy object already used, and the independence is now stated where the defaults are. config.py:66 -- on_data_exhausted plus max_skipped_prompts encoded one decision in two keys that could contradict each other, with a validator existing purely to reject the degenerate pair. Collapsed to max_skipped_prompts alone: 0 (the default) fails on the first exhaustion, propagating the original error exactly as fail_fast did. The illegal state is now unrepresentable, and the validator branch, its test, and RolloutRetryPolicy.skip_on_data_exhausted are gone. Because every one of these is a rename or a move under extra="allow", the old spellings would parse and quietly stop taking effect -- for on_data_exhausted: skip that is a behaviour change delivered with no diagnostic. Both levels now reject the previous names with a message naming the replacement, with tests. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
Follow-on to the fault-tolerance restructure. Four places still named keys that no longer exist, the last of which is the one that matters: the RolloutRedispatchExhausted message told an operator to look for max_attempts_per_prompt, which they would not find in any config. An error whose remedy names a nonexistent key is worse than one that names none. The other three are a RolloutOutcome comment, the RolloutTimeouts docstring, and the generate_and_push docstring. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
Three review findings on NVIDIA-NeMo#3470, all in the same counters (rollout_manager.py :1147, :844, :79). :1147 -- data retries were recorded into redispatches_by_reason, so rollout/redispatch_total conflated "the fleet is degrading" with "the prompts are bad". That is the one distinction the two-budget design exists to draw, and the metric documented as the only externally visible sign of fleet trouble was counting both. Data retries now have their own family. :844 -- NeMo-Gym row-level re-dispatches were counted nowhere at all: they recover a partial group instead of retrying the prompt, so gym could retry rows for a whole run with every visible counter flat. They now have their own counter, which meant threading the owning manager's stats object into AsyncNemoGymRolloutImpl. Also :844 -- the "rows missing" failure carried no `from`, so when an intermediate attempt absorbed a transport error and a later one ended cleanly-but-short, the error that actually lost the rows was discarded at exactly the point an operator reads it. Kept across attempts and chained. Every counter family now also emits an aggregate. Previously data failures had only per-exception series, so alerting on "any data failure" required knowing the exception names in advance. :79 -- RolloutRetryPolicy carried a second set of defaults (1/1/1) contradicting RolloutFailureConfig's (5/2/3); a reader here concluded the shipped budget was 1. The attempt budgets are now required, and callers needing the historical no-retry behaviour ask by name via single_attempt(). The only retry defaults in the codebase are the BaseModel's. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
Addresses the review finding on NVIDIA-NeMo#3470 (single_controller.py:135). env_handles is a required, non-defaulted field of SingleControllerActorArgs and every production caller passes it; the getattr default existed only so upstream's partial SimpleNamespace fixtures kept working. The cost was a silent failure mode: rename or drop the field and watchdog.gym_subprocess_check: true degrades to a health check that iterates nothing and reports nothing -- the exact class of silent failure this series exists to remove. A missing field should break at construction, where it costs five minutes, not at hour three of a run. test_logs_setup_timing_metrics -- the test this getattr was originally added for, twice -- now carries env_handles={} explicitly. That is the recurring cost, and it is the right one: a loud break we fix, rather than a quiet degradation we ship. _fleet_monitor and _policy_router keep their getattr in part 2/4 for a genuinely different reason: None there means the feature is off. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
Addresses the review finding on NVIDIA-NeMo#3470 (chaos.sh:14). Three comments justified decisions by pointing at "the recovery test(s)", which do not exist on this branch -- they arrive in part 3/4 of the series. A reader on this PR has nothing to look at. Two are now inlined with the actual reason, which is what a reader wanted anyway; the third names the part of the series that adds the harness. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
Closes the remaining half of the classification review finding (AI-2 on NVIDIA-NeMo#3470), scoped rather than blanket. An exception raised inside a still-LIVING generation worker -- vLLM EngineDeadError, a CUDA OOM -- arrives as a bare RayTaskError. It is not a RayActorError and is not in _INFRA_TYPES, so classify_rollout_failure could only fall through to DATA: 2 attempts and fail-fast, on a failure the bounded, backed-off 5-attempt infra path was built for. Demonstrated: PR1 generation-RPC RayTaskError -> RolloutDataFailure -> DATA PR2 same exception, _generate_on_shard -> GenerationUnavailable -> INFRA so the two paths in this series disagreed about one exception. They now agree. Deliberately NOT the reviewer's wider suggestion of treating any degraded RayTaskError as INFRA inside classify_rollout_failure. Globally, "unrecognized means DATA" is the right default -- it governs exceptions we can inspect and do not recognize, and flipping it would retry genuine bugs everywhere, five times, before surfacing them wrapped. At this call site we have information the classifier does not: the RPC was a generation, so "that shard could not serve it" is the correct reading whatever the boundary destroyed, and re-dispatching elsewhere is the right response. A real bug in the worker still surfaces, chained, once the infra budget runs out. Same principle as classifying gym failures at the source: decide where the information still exists, rather than widening a guess on the driver. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
classify_rollout_failure was inserted mid-block. The repo's ruff `select` is ["D", "F"], so `ruff check` does not catch this -- pre-commit runs a separate `ruff check --select I --fix` hook, which does. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
|
Thanks — this was a genuinely useful review. All twelve are addressed; the work is pushed to #3589, which is where the series continues.
Two things worth surfacing rather than leaving in the threads. One divergence. On the classification finding I took the source-side fix and the explicit A correction to something I had wrong. Your answer to my second question stands, and it fixes a mistake of mine: I had measured the native path (over-long prompt → The related gap that remains, and is orthogonal to this PR: an over-long prompt on the native path produces an empty rollout marked |
pyrefly rejects an Optional in a `from` clause -- `raise ... from None` is legal at runtime, but the checker wants a value it can prove derives from BaseException. Narrowing to two explicit raises satisfies it and reads no worse. Also tightened the annotation to Optional[Exception], matching the only writer (`except Exception as error`). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: asolergibert <[email protected]>
…01-containment Signed-off-by: asolergibert <[email protected]> # Conflicts: # examples/configs/grpo_math_1B_megatron_single_controller.yaml # nemo_rl/algorithms/single_controller.py # tests/functional/L1_Functional_Tests_SingleController.sh # tests/unit/single_controller/test_rollout_pump.py # tests/unit/single_controller/test_single_controller.py
Part 1/4 of #3454
What this fixes
Two failure modes in the SingleController async-GRPO path, both silent. Neither produces an exception, a log line, or an unhealthy Ray actor — which is why they have not been noticed.
1. The GRPO path silently corrupts training.
AsyncRolloutImplcaught every exception from generation and committed the rollout anyway, with empty text and zero reward. Those rows enter the GRPO leave-one-out baseline as legitimate zero-reward samples, so a transient generation failure does not fail the run — it quietly biases the advantage estimate. This is a live data-correctness bug independent of any resiliency feature.2. The NeMo-Gym path silently wedges. Gym's HTTP client is constructed with
ClientTimeout()— every timeout disabled — and retriesClientOSError/ServerDisconnectedErrorin an uncapped loop. A dead vLLM endpoint therefore parks the rollout forever. Each parked rollout holds amax_inflight_promptspermit, so the rollout pump eventually blocks entirely while the train pump spins on an empty buffer. Ray reports every actor healthy throughout.What it does
rollout_manager.py). The single highest-value change here: failures are classified and raised instead of being committed as zero-reward rows.ClientResponseErrorcarrying 503 is infrastructure, one carrying 400 is data.None(disabled).Inert by default — all timeouts default to
None. The two always-on changes are that errors stop being swallowed and retries are bounded; both convert silent failure into loud failure, which can surface pre-existing problems that were previously invisible. That is the intent.Tests
ruffandpyreflyclean.grpo_dp_single_controller.sh(all 5 metric checks) andgrpo_async_gym_single_controller.sh(10 steps, mediangen_kl_error0.0010579, reward 0.5).The chaos harness
tests/functional/grpo_dp_single_controller_chaos.shSIGKILLs a generation worker and asserts the job fails fast and attributably rather than wedging. It found the stall-detector bug above, and it is registered in the SingleController L1 laneRegistered twice, because Ray retitles a worker for the duration of each call and the two states fail by different routes:
idle)ray::VllmAsyncGenerationWorkerRolloutStall— the loss must be detectedVICTIM_STATE=servingray::VllmAsyncGenerationWorker.generate_asyncGenerationUnavailable+RolloutRedispatchExhausted— an in-flight RPC diesVictim selection is pinned rather than left to
pgrep ... | head -1, which matched three distinct processes across five states and so silently chose a different scenario run to run. It never failed — every scenario ends in a bounded attributable failure, which is all the test asserted — so the divergence was only visible as wall-clock. Three consecutiveidleruns now give an identical victim title and 222s.Issues
List issues that this PR closes (syntax):
Usage
# Add a code snippet demonstrating how to use thisBefore your PR is "Ready for review"
Pre checks:
Additional Information