Skip to content

feat(sglang): engine fault tolerance for rollouts - #3613

Merged
yuki-97 merged 20 commits into
NVIDIA-NeMo:mainfrom
Kh4L:recut/sglang-fault-tolerance
Sep 29, 2026
Merged

yuki-97 merged 20 commits into
NVIDIA-NeMo:mainfrom
Kh4L:recut/sglang-fault-tolerance

Conversation

@Kh4L

@Kh4L Kh4L commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Original work: #3187 by @xiuhu17. The original commit and authorship are preserved, including its sign-off.

Adds opt-in SGLang engine fault tolerance. A serving health monitor detects rollout failures; before each refit, a separate actor/process liveness probe also detects deaths while the monitor is paused or the engine is offloaded. Recovery precedes the first weights-onload RPC, deregisters failed router workers, and replaces the whole logical engine group before reconnecting the weight-update transport. A per-engine restart budget bounds repeated failures. Child-process guards prevent an abruptly killed actor from leaving a GPU server behind.

Generation continues on healthy survivors within the existing nonstreaming retry budget. Verified sglang-router==0.3.2 can repeatedly choose a dead cache-affine worker until its circuit opens; NeMo-RL's existing outer HTTP retries allow the single-worker failure case to reach a survivor. Started streams, retry exhaustion, trainer death, and death during an active weight transfer are not guaranteed recovery cases. Engine replacement takes place at the next refit so fresh policy weights are applied before rollout resumes.

Validation at final head 9399a3223: HSG CPU job 7014630 passed 107 tests, including two real-Ray helper-serialization cases; pyrefly reported 0 errors. GPU job 7014647 passed all six real-engine chaos cases, including offloaded server/actor death and survival of an observed in-flight SIGKILL. All four interrupted-batch requests completed with 2,048 tokens. The full SGLang functional lane includes the new EXPECT=survival chaos harness; this local harness is generation/recovery, not a full GRPO training run. A maintainer must run /ok to test 9399a32230cacb855de3e5cb6a8153ec3f963594 after the updated head is published.

@copy-pr-bot

copy-pr-bot Bot commented Aug 12, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@Kh4L
Kh4L marked this pull request as ready for review August 13, 2026 01:33
@Kh4L
Kh4L requested review from a team as code owners August 13, 2026 01:33
@Kh4L
Kh4L force-pushed the recut/sglang-fault-tolerance branch from 0c651a6 to 40a296c Compare August 13, 2026 05:39

@Kh4L Kh4L left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Self-review (/review-pr-team), per the contributor self-review policy

Ran the four reviewer roles the skill specifies — rl-expert, bug-finder, design-reviewer, test-agent — as a real agent team this time (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1), so the mandatory devil's-advocate challenge could interrogate the reporting agent across both rounds instead of re-deriving findings alone. Scoped to this PR's increment only, not the refit layer below it.

Three blockers, all reproduced by executing the real source rather than by reading it, all fixed in 5314f53 and be50156. Every one of them is invisible today, because all five shipped sglang recipes set use_fault_tolerance: false and nothing in CI turns it on. The feature as submitted could not be enabled, and would have been broken once enabled.

1. _recover disarmed the weight refit on every refit — silently, on the colocated path

_recover ran unconditionally, including the overwhelmingly common case where nothing died. _start_engines rewrites num_new_engines regardless of whether the previous value has been consumed, so a no-op recovery reset the count to 0 before _refit read it. That count is the only gate on _connect, and _connect is the only place the trainer-side transport is ever built.

The consequence differs by transport, and the difference matters:

  • Colocated (weight_transfer_mode: ipc, what all five shipped recipes use) — silent. send_hf_buckets_via_ipc_actor_impl reads _ipc_gather_group / _ipc_gather_src / _ipc_engine_index out of a worker_state that connect_colocate_topology never populated, finds all three None, and takes the placeholder-rank early return on every rank. Training then continues against stale rollout weights, forever, with no error anywhere and no metric that would show it.
  • Disaggregated (broadcast) — loud. Rank 0 raises RuntimeError("connect_sglang_rollout_engines_distributed must be called before ...").

Fixed by returning early from _recover when dead_indices is empty.

Worth recording that the first proposed fix — num_new_engines += len(...) at the _start_engines write site — was wrong, and the devil's advocate caught it: __init__ leaves the count at N, the first _recover adds 0, and the assert self.num_new_engines == len(dead_indices) immediately below then fires. The agent that proposed it withdrew it.

2. The boot grace period made the monitor never probe anything

_need_first_wait was re-armed on every resume(). resume() runs once per training step, so any generation phase shorter than rollout_health_check_first_wait (default 60s) left the monitor permanently inside its grace period. Enabled, and dead — it would never health-check an engine, which is the entire feature.

Replaced with an absolute monotonic deadline armed at start() and after a recovery, never reset by resume(). Time spent paused now counts toward it, and a pause part-way through no longer restarts the clock. Restarted engines re-arm it explicitly, since a freshly booted SGLang server is still loading weights and would be killed by a probe.

Over a representative generate/pause cycle, probes went 0 → 21. The unit-test version of that scenario sees 0 → 2.

3. Flipping use_fault_tolerance: true in any shipped recipe raised KeyError

Config and code disagreed in both directions:

  • use_fault_tolerance was declared required, but both readers use .get() and three of the five shipped sglang recipes never set it. The declaration was unenforced — PolicyConfig.generation is typed as the base GenerationConfig, which has no sglang_cfg field, so test_config_validation.py never reaches SglangSpecificArgs at all — but it documented a contract the recipes do not honor. Now NotRequired[bool], matching use_external_router three declarations above it.
  • The three rollout_health_check_* knobs were declared NotRequired and read with bare subscripts. Every sglang recipe inherits grpo_math_1B.yaml, which carries no sglang keys, so none of them pick these up from grpo_math_1B_sglang.yaml. Turning the feature on therefore raised KeyError: 'rollout_health_check_interval' from a daemon-thread constructor. They stay NotRequired — they genuinely only matter when the feature is on — but RolloutHealthMonitor now asserts up front, naming every missing key and where the documented values live. This mirrors the existing sglang_router_ip / sglang_router_port handling, which is conditionally required the same way.

Tests

Three regressions added, all of which fail against the pre-fix source and pass after: the missing-key message, _recover leaving num_new_engines alone when nothing died, and _recover re-arming the grace period for restarted engines. test_first_wait_delays_checks_after_resume is renamed to test_first_wait_delays_the_initial_checks — it asserted semantics the fix deliberately removed, and it passed both before and after, so it was never load-bearing.

What the adversarial pass rejected

  • A claim that SGLANG_ENABLE_HEALTH_ENDPOINT_GENERATION must be set for /health_generate to exist — disputed at confidence 99 and dropped. It would have sent the author chasing a non-issue.
  • The unguarded self._health_monitor.pause() in recover_updatable_engines was reported as a null-deref and downgraded to a nit: its only caller is already behind the same use_fault_tolerance gate that creates the monitor, so it is unreachable. Left as the one inline comment below rather than changed unilaterally.

Environment caveats

No GPU on the review machine and no sglang extra, so nothing runtime-dependent was executed against a real engine. The three blockers were instead reproduced by loading the real fault_tolerance.py and the real SGLangGeneration._recover bytes with ray stubbed — that is stronger than reading, weaker than a GPU run. pytest could not be run locally (no ray/torch/omegaconf, no network to install them); the new tests were validated by executing their bodies against both the pre-fix and post-fix source. A GPU re-run with use_fault_tolerance: true would be the real confirmation, and is worth doing before merge.

Generated by Claude Code

@Kh4L

Kh4L commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Addendum to the self-review above — a fourth defect, found after posting.

stop() clears _thread, _stop_event and _pause_event even when the join times out. The thread it failed to reap is still inside _health_monitor_loop, so its next iteration dereferences the now-None event and dies with AttributeError: 'NoneType' object has no attribute 'wait'.

I originally judged this path unreachable and left it out. That was wrong. The join budget is timeout + interval + 5, but one probe is bounded at 2 * timeout by the outer ray.get, and a probe that times out then calls _kill_engine, which spends up to another timeout on the graceful shutdown before ray.kill. With the shipped 60s timeout that is up to 180s of work against a 125s budget — and it happens precisely when an engine is hung, which is the case this feature exists for.

Reproduced by driving stop() against an in-flight health check that outlasts the join, executing the real fault_tolerance.py: pre-fix the thread dies with the AttributeError; post-fix it observes the set stop event and exits cleanly. That scenario is now a regression test, which fails against the pre-fix source.

fixed in 00b8af6

Severity is moderate, not blocker-grade: a stray traceback from a daemon thread during teardown, not wrong training results. Flagging it rather than folding it in silently, since the review above said three findings.

@Kh4L
Kh4L force-pushed the recut/sglang-fault-tolerance branch 5 times, most recently from 40d161c to ba3f5af Compare August 18, 2026 19:24
@Kh4L
Kh4L requested a review from a team as a code owner August 18, 2026 19:24
@Kh4L
Kh4L force-pushed the recut/sglang-fault-tolerance branch from ba3f5af to 4ba11c5 Compare August 18, 2026 19:29
@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Aug 18, 2026
@Kh4L
Kh4L force-pushed the recut/sglang-fault-tolerance branch from 4ba11c5 to 487027b Compare August 25, 2026 03:15
@Kh4L
Kh4L requested a review from a team as a code owner August 25, 2026 03:15
@Kh4L

Kh4L commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 487027b

@Kh4L
Kh4L force-pushed the recut/sglang-fault-tolerance branch from 487027b to 25f3a01 Compare August 26, 2026 03:24
@Kh4L Kh4L added the CI:L1 Run doctests, unit tests, and functional tests label Aug 26, 2026
@Kh4L

Kh4L commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 25f3a01

@Kh4L
Kh4L force-pushed the recut/sglang-fault-tolerance branch from 25f3a01 to 0ae89f8 Compare August 26, 2026 16:31
@Kh4L

Kh4L commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 0ae89f8

@Kh4L

Kh4L commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

HSG real-GPU validation passed at 0ae89f8b1f8484ee82cebf6613bb10342d08be9a.

  • Qwen3-0.6B with 2 live SGLang TP=1 engines
  • Injected engine crash was detected; the worker was killed and recreated
  • Replacement health check and post-recovery generation both returned 200
  • SGLang 0.5.17.dev30+g3003d70f6; decode CUDA graphs enabled, only prefill capture disabled
  • Test passed and the Slurm job completed with exit 0

xiuhu17 and others added 17 commits September 16, 2026 15:53
A hung or dead SGLang engine currently wedges the whole run: the refit's
`ray.get` on its actor never returns, and the router keeps sending
`/generate` to it.

Add `RolloutHealthMonitor`, a daemon thread that polls `/health_generate`
on every node-0 engine and, on failure, kills and restarts the actor. The
refit picks the survivors up through the engine registry this PR's base
already exposes (`get_updatable_engines_and_lock`), so a recovered engine is
reconnected on the next weight update.

The monitor must not run while the engines are offloaded: `/health_generate`
always executes a real one-token generation (the
`SGLANG_ENABLE_HEALTH_ENDPOINT_GENERATION=false` bypass only covers
`/health`), so probing a released engine reports a false failure and kills a
live actor. It is therefore wired to the generation lifecycle — resumed by
`prepare_for_generation` once the KV cache is back, paused by
`finish_generation` and for the duration of a refit.

`pause()` blocks on an in-flight probe rather than only setting a flag,
so a probe cannot overlap `release_memory_occupation`. `_kill_engine` bounds
its graceful-shutdown `ray.get` and kills the actor even when that shutdown
fails, which is the exact case the monitor exists to handle.

Signed-off-by: zhihaow6 <[email protected]>
(cherry picked from commit f563fa9)
Signed-off-by: Serge Panev <[email protected]>
…grace

Two defects made the fault-tolerance path unusable once enabled. Both are
invisible today because every shipped recipe sets `use_fault_tolerance:
false`, so `_recover` is never reached.

`_recover` ran unconditionally on every refit, including the common case
where nothing died. `_start_engines` rewrites `num_new_engines` without
regard for whether the previous value has been consumed, so the no-op
recovery reset the count to 0 before the refit read it. That count is the
only gate on `_connect` in the weight synchronizer, and `_connect` is the
only place the trainer-side transport is ever built.

What that costs depends on the transport. Colocated
(`weight_transfer_mode: ipc`, which is what all five shipped sglang
recipes use) fails silently: `send_hf_buckets_via_ipc_actor_impl` reads
`_ipc_gather_group` / `_ipc_gather_src` / `_ipc_engine_index` out of a
`worker_state` that `connect_colocate_topology` never populated, finds all
three None, and takes the placeholder-rank early return on every rank.
Training then continues against stale rollout weights with no error
anywhere. Disaggregated (`broadcast`) at least fails loudly, since rank 0
raises RuntimeError from `update_weights_to_sglang_distributed`. Return
early when there are no dead engines.

The boot grace period was a `_need_first_wait` boolean re-armed on every
`resume()`. `resume()` runs once per training step, so any generation
phase shorter than `rollout_health_check_first_wait` left the monitor
permanently inside its grace period and no probe ever ran -- the feature
was enabled but dead. Replace the flag with an absolute monotonic
deadline that is armed at `start()` and after a recovery, and is not
reset by `resume()`. Time spent paused now counts toward the deadline,
and a pause part-way through no longer restarts the clock. Restarted
engines re-arm it explicitly, since a freshly booted server is still
loading weights and a probe would kill it.

Verified by executing the real source: `num_new_engines` survives at 4
across a no-op recovery, and health probes over a representative
generate/pause cycle went from 0 to 21.

Signed-off-by: Serge Panev <[email protected]>
`use_fault_tolerance` was declared required while both readers used
`.get()`, and three of the five shipped sglang recipes never set it at
all. The declaration was unenforced -- `PolicyConfig.generation` is typed
as the base `GenerationConfig`, which has no `sglang_cfg` field, so
`test_config_validation.py` never validates `SglangSpecificArgs` -- but it
documented a contract the recipes do not honor. Declare it
`NotRequired[bool]`, matching `use_external_router` in the same file and
the `.get()` truthiness reads that already exist.

The three `rollout_health_check_*` knobs had the inverse problem: declared
`NotRequired`, read with bare subscripts. Every sglang recipe inherits
`grpo_math_1B.yaml`, which carries no sglang keys, so none of them pick
the knobs up from the sglang exemplar -- flipping `use_fault_tolerance:
true` in any shipped recipe raised `KeyError:
'rollout_health_check_interval'` from a daemon-thread constructor. They
stay `NotRequired`, since they only matter when the feature is on, but
`RolloutHealthMonitor` now asserts on them up front and names every
missing key plus where the documented values live. This follows the
existing precedent for `sglang_router_ip`/`sglang_router_port`, which are
conditionally required in the same way.

Tests cover all three blockers fixed on this branch: the missing-key
message, `_recover` leaving `num_new_engines` alone when nothing died, and
`_recover` re-arming the boot grace period for restarted engines. Against
the pre-fix source those three fail (KeyError, `_start_engines` invoked,
no re-arm) and the first-wait regression sees 0 probes where the fixed
code sees 2. `test_first_wait_delays_checks_after_resume` is renamed to
`test_first_wait_delays_the_initial_checks`: the grace period is armed at
`start()` now, not on every resume.

Signed-off-by: Serge Panev <[email protected]>
…hread

When the join times out, `stop` logged a warning and then cleared
`_thread`, `_stop_event` and `_pause_event` regardless. The thread it
failed to reap is still inside `_health_monitor_loop`, so its next
iteration dereferenced the now-`None` event and the thread died with
`AttributeError: 'NoneType' object has no attribute 'wait'` at the
`self._stop_event.wait(self._check_interval)` at the bottom of the loop.

The join budget is not generous enough to treat that path as unreachable.
It is `timeout + interval + 5`, but a single probe is bounded at
`2 * timeout` by the outer `ray.get`, and a probe that times out then
calls `_kill_engine`, which spends up to another `timeout` on the
graceful `shutdown` before `ray.kill`. With the shipped 60s timeout that
is up to 180s of work against a 125s budget -- and it happens exactly
when an engine is hung, which is the case the feature exists for.

Clear `_is_checking_enabled` either way, since checking really has
stopped, but leave the events in place when the thread outlived the join
so it can observe the set stop event and exit on its own.

The regression test drives `stop` against an in-flight health check that
outlasts the join. Against the pre-fix source it fails on the first
assertion and the monitor thread raises the AttributeError above; after
the fix the thread exits cleanly and `threading.excepthook` records
nothing. It cannot run faster than the join's fixed +5s floor.

Signed-off-by: Serge Panev <[email protected]>
The pinned SGLang server replaced disable_piecewise_cuda_graph with per-phase graph backends. The real fault-tolerance smoke already disables CUDA graphs entirely, so remove the stale argument that would otherwise fail ServerArgs construction.

Signed-off-by: Serge Panev <[email protected]>
Honor rearmed monitor deadlines, centralize validated recovery settings, and expose independent router and client retry budgets. Replace the duplicate L1 wrapper with real GRPO survival and restart-budget failure scenarios that verify training, refit, and replacement serving.

Signed-off-by: Serge Panev <[email protected]>
@Kh4L
Kh4L force-pushed the recut/sglang-fault-tolerance branch from 9147673 to 62868ae Compare September 17, 2026 02:31
@Kh4L

Kh4L commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 62868ae

@Kh4L
Kh4L requested a review from yuki-97 September 18, 2026 00:23

@yuki-97 yuki-97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update — the follow-ups all landed, and the new L1 scenarios are the right shape: killing a genuinely busy engine, requiring the replacement to serve strictly newer weights, and requiring real training afterwards is a much stronger check than the L0 cases it replaced. The post-replacement train/grad_norm > 0 and train/global_valid_toks > 0 assertions in particular mean a fully-masked batch can't pass it.

Checked: every earlier thread re-read against this head; the restart-budget reservation (per logical engine, atomic, never reset); the first-wait re-arm fix and that its controlled-clock test genuinely fails without it; the router and client retry plumbing; and that both EXPECT=survival and EXPECT=bounded_failure actually execute in the SGLang L1 lane rather than being skipped.

Remaining comments are cleanup on the new config surface and the harness layout — none of them block.

Could you also rebase or merge main in and re-run? The branch is a bit behind, and the red check may well clear with a fresh run.

Kh4L and others added 3 commits September 28, 2026 19:58
@yuki-97

yuki-97 commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

/ok to test 73a0fb5

@yuki-97
yuki-97 enabled auto-merge (squash) September 29, 2026 09:31
@yuki-97
yuki-97 merged commit 44903f5 into NVIDIA-NeMo:main Sep 29, 2026
205 of 208 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:L1 Run doctests, unit tests, and functional tests Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants