Repository navigation
[Train] Add NCCL RAS health callback - #64928
Conversation
Signed-off-by: Mark Towers <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a new NCCL RAS-based hang detector callback (NCCLRASCallback) for Ray Train v2. This callback monitors the NCCL Reliability/Availability/Serviceability (RAS) subsystem to detect deadlocks and unresponsive ranks by tracking collective op-counts across communicators. If a hang is confirmed over multiple consecutive polls, it can raise a non-retryable NCCLHangError and dump worker stack traces using py-spy for debugging. The PR also includes unit and end-to-end tests for this new callback. The review comments point out three important issues: a potential ValueError in parse_ras_addr when parsing bare hostnames or bracketed IPv6 addresses without a port, a potential TypeError in query_ras_on_workers when calling ray.cancel(None) if worker.execute_async fails, and a thread leak due to the ThreadPoolExecutor not being shut down when the worker group is stopped.
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
JasonLi1909
left a comment
There was a problem hiding this comment.
Thanks! Left some comments, main things:
- The current default observe mode does not collect stack traces. Users may still want to see the stack traces while also not wanting their job to terminate. It will also help us to with identifying false positives rates moving forward. Without the stack traces, we will not be able to tell if the detection was valid.
- This PR only detect hangs if their is a misalignment between collectives, but it's possible for the hang to occur inside the collectives while they're all aligned. We should investigate this case and if we can detect it without many false positives.
- Because the ncclras query is run on the train worker, it may contend with the health check that runs every ~2s. Wondering if we need to run this on the train worker or if it can just be done as a separate task.
- Can we provide an example in the pr description for when the hang would be detected, showing the nccl ras output?
|
|
||
| # How often (seconds) to query the NCCL RAS subsystem on a worker | ||
| NCCL_RAS_POLL_INTERVAL_S_ENV_VAR = "RAY_TRAIN_NCCL_RAS_POLL_INTERVAL_S" | ||
| DEFAULT_NCCL_RAS_POLL_INTERVAL_S: float = 15.0 |
There was a problem hiding this comment.
nit: maybe rename to NCCL_RAS_MIN_POLL_INTERVAL_S because the 15.0 isn't the true poll interval but instead serves to throttle querying to no more than every 15s
| # Number of consecutive RAS reports that must agree a hang is occurring before | ||
| # the detector acts. Default settings means ~10 minutes before fully confirmed. | ||
| NCCL_RAS_CONFIRM_COUNT_ENV_VAR = "RAY_TRAIN_NCCL_RAS_CONFIRM_COUNT" | ||
| DEFAULT_NCCL_RAS_CONFIRM_COUNT: int = 40 |
There was a problem hiding this comment.
Can we make this time based instead? I assume the 10 minute assumption is based off the 15s poll interval * 40 = 10 mins, but this is fragile as depends on the poll interval. Because we need to collect stack traces prior to the nccl watchdog error, the time guarantee here is useful to have. And maybe we can update the timer only when a report is collected and misalignment confirmed. Then the 10 mins can be the min amount of time the hang must have persisted.
There was a problem hiding this comment.
Thats fair, I'll update that the env-vars use time in seconds for a confirmed hang allowing it to be modified more easily.
| ray.shutdown() | ||
|
|
||
|
|
||
| HANG, FAIL, MAYBE = "hang", "fail", "maybe" |
There was a problem hiding this comment.
Why are we testing for these FAIL and MAYBE cases? I think we should keep the scope of the feature to just detecting the hang case for now as that is the highest value case. Other cases may be more nuanced and we can't say much about them. We can consider adding those in an extension
There was a problem hiding this comment.
From testing, for the maybes, I found that depending on tensor size and how long you leave it to done, depends on if it would hang or not.
# Conflicts: # python/ray/train/__init__.py # python/ray/train/v2/_internal/execution/failure_handling/default.py # python/ray/train/v2/tests/test_failure_policy.py
|
Thanks for the review
Yes, will fix
With nccl-ras no, this is part of the reason that NVIDIA Resiliency Extension (NVRx) uses collective time taken instead as a proxy for hangs which might be more reliable. However, this requires users to update their implementation to hook into tracking this information. In comparison, ras runs asynchronously of the user without any setup requirements and works in most software based cases. The cases where a hang occurs with equal collective calls, I believe this primarily occurs for hardware based failures, therefore, the new DCGM view should help users more.
The query runs asynchronously in a different thread within the worker node so I'm aiming (and expecting) this callback to cause zero drag on other callbacks / health checks.
Yes, will provide |
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
… hanging on successful detection Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
| logger.warning( | ||
| "NCCL hang still suspected! %d of %d communicators (%s) have made " | ||
| "no progress. %s", |
There was a problem hiding this comment.
can you include some snippets of the logs seen by the user from your e2e testing?
| def drive_ras_query(self) -> Optional[RASReport]: | ||
| """Drive the throttled JSON RAS poll without blocking the event loop. | ||
|
|
||
| Only the periodic JSON poll goes through here. The one-off human-readable | ||
| ``-f text`` report fetched at hang time uses :meth:`query_ras_text` | ||
| directly so it doesn't share this method's single-in-flight future or | ||
| poll-interval throttle. |
There was a problem hiding this comment.
consdier putting this into a longrunning loop in a thread instead of submitting new tasks to the threadpool every once in a while
| Warning: RAS requires that all nodes are communicating, therefore, if there | ||
| is no "world" communicator with all ranks on, RAS will return a subset of | ||
| the ranks and communicators. |
There was a problem hiding this comment.
Could you clarify this comment? what is the "world communicator"?
There was a problem hiding this comment.
When doing tensor parallelism (or other parallelism strategies) then you can have rank 0 and 1 using one set of tensors and rank 2 and 3 using another set of tensors. If you have a torch distributed process (i.e., communicator) that only exists between rank 0 and 1, and 2 and 3 then NCCL will only see 0 and 1, then 2 and 3 and not all the ranks together. This matters as RAS runs on top of NCCL and doesn't search out more ranks.
Therefore, the problem is that if you query RAS on rank 0, then it would only return the data for rank 0 and 1 (as it doesn't know that ranks 2 and 3 exist). In practice this shouldn't exist as parallelism strategies will have a world communicator between all ranks to share global information.
However, in the case where this isn't the case then users might run in this bug.
I hope that makes sense. I can rewrite the comment with more detail.
| detector can degrade to a no-op) from transient errors. | ||
| """ | ||
| host, port = parse_ras_addr( | ||
| os.environ.get(NCCL_RAS_ADDR_ENV_VAR, "localhost:28028") |
There was a problem hiding this comment.
put this default in the constants.py
There was a problem hiding this comment.
Reading RAS again, we don't need to pass address and nccl will just use its own default, therefore, I'm updated to let nccl use its own value unless the user overrides it
There was a problem hiding this comment.
I've removed this and let ras use its internal default variable in case it changes in the future. Users need to intentionally override it for us to pass the variable to ras
| last_failure_reason: Optional[str] = None | ||
| last_failure_stderr: Optional[str] = None | ||
| for worker in workers: | ||
| ref = None | ||
| try: |
There was a problem hiding this comment.
can simplify by capturing the loop logic into a helper function so we don't have a continue on every branch of the try catch.
for worker in workers:
value, reason = self._try_query_worker(worker, ras_format)
if value is not None:
return value
last_failure_reason = reason| for ref in not_ready: | ||
| ray.cancel(ref) |
There was a problem hiding this comment.
log that we weren't able to get these rank stack traces in time
There was a problem hiding this comment.
Great idea, done
There was a problem hiding this comment.
Great idea, done
| if isinstance(training_failed_error, NCCLHangError): | ||
| # NCCL hangs are usually deterministic, so a restart would just hang again. | ||
| return False |
There was a problem hiding this comment.
hmm I would actually vote to remove this special case; nccl hangs could be caused by flaky hardware (nic) that would benefit from a restart. and plus we'll only retry up to max_failures times
There was a problem hiding this comment.
I'll remove this and leave it up to a future PR
| f" - Your experiment directory contains the per-rank stack traces ({dump_dir})\n" | ||
| ) | ||
| if self._action == NCCL_RAS_ACTION_FAIL: | ||
| raise NCCLHangError(message, worker_failures={}) |
There was a problem hiding this comment.
do we have worker specific stuff we could populate worker_failures with? ex: the rank's stack traces
There was a problem hiding this comment.
Would this double the stack traces from both the controller and workers? Also worker_failures: Dict[int, Exception] and the stack trace isn't an exception object strictly
| def evaluate_comm_mismatch(self, report: RASReport): | ||
| """Track frozen communicators and escalate user-facing hang messaging. | ||
|
|
||
| A communicator is deadlocked only when *no* rank advanced *any* op since |
There was a problem hiding this comment.
can you break up the logic in here into a few parts for easier readability and testing?
ex:
def evaluate_comm_mismatch(self, report):
if self.prev_report is None:
return
op_diff = compute_report_op_diff(self.prev_report, report)
# 1. Classify each communicator
frozen = {}
for comm_id in report.mismatched_comms:
if comm_id not in op_diff:
continue
if all(d == 0 for deltas in op_diff[comm_id].values() for d in deltas.values()):
frozen[comm_id] = self.comm_deadlock_count.get(comm_id, 0) + 1
confirmed = [c for c, n in frozen.items() if n == self._confirm_poll_counts]
recovered = [c for c in self.comm_deadlock_count if c not in frozen
and self.comm_deadlock_count[c] > self._suspicion_polls]
# 2. Update state
self.comm_deadlock_count = frozen
# 3. Act
for comm_id in recovered:
self._log_recovery(comm_id, ...)
if confirmed:
self._handle_confirmed_hang(confirmed, report)
elif frozen:
self._log_suspicion_warnings(report)Signed-off-by: Mark Towers <[email protected]>
Signed-off-by: Mark Towers <[email protected]>
| f"({self._confirm_poll_counts} polls). " | ||
| "This usually means that the collective is deadlocked / hanging. " | ||
| "The possible reasons for this is: a rank hit a divergent code " | ||
| "path, exited early, a GPU or network hardware failure, or a " |
There was a problem hiding this comment.
does exited early actually trigger this? I remember in the presentation there was some issues with early exited ranks
There was a problem hiding this comment.
If a GPU fails then the Ray worker health checker will pick up the issue more quickly but I don't know if there are cases where the Ray health checker misses something and RAS catches
| if ref is not None: | ||
| ray.cancel(ref) |
There was a problem hiding this comment.
let's remove ray.cancel since they don't affect running actor tasks
| math.ceil(_FIRST_SUSPICION_AFTER_S / self._poll_interval_s), | ||
| self._confirm_poll_counts - 1, | ||
| ) | ||
| assert self._suspicion_polls >= 0 |
There was a problem hiding this comment.
should we raise value error here too?
Signed-off-by: Mark Towers <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit cd52bab. Configure here.
Signed-off-by: Mark Towers <[email protected]>
## Description The hang detector polls NCCL RAS frequently to check if ranks have different numbers of collectives launched. Currently, we log that data regularly, however, this makes the post-mortem analyses difficult. Therefore, this PR adds a circular buffer for recording a history of the NCCL RAS queries and on confirmation are dumped into the diagnostic folder. To ensure that the history can include RAS queries from before a hang started, the length of the circular buffer is the number of number of polls required for confirmation plus a fixed value. ## Related issues Continuation of #64928 --------- Signed-off-by: Mark Towers <[email protected]> Co-authored-by: Mark Towers <[email protected]>
## Description This PR adds an opt-in callback that detects hanging distributed training jobs by polling NCCL's RAS (Reliability/Availability/Serviceability) subsystem. NCCL ≥ 2.24 runs a monitoring thread inside every NCCL process that forms a peer mesh tracking per-rank health and collective op-counts. By querying the `ncclras` client and diffing collective-counts between successive polls, Ray Train can automatically detect and act on hangs that would otherwise stall a job until a torch process group timeout occurs. As RAS gives a snapshot of the current NCCL state, to determine if a mismatch is a temporary issue or a permanent one, the callback polls RAS every N seconds. If a communicator is mismatched *and* makes no progress at all across multiple sequential polls, then this most likely indicates that a deadlock / wedge / hang is in progress for that communicator. It's important to note that it's possible for NCCL to continue (not hang) with incorrect data depending on the NCCL operation, tensor size, NCCL version, etc. In these cases, users will observe the collective-count continue to increase but often with a constant mismatch. In this version of the callback, we are not detecting those issues and focusing purely on NCCL collective mismatches which cause hangs. The callback is disabled by default and enabled with `RAY_TRAIN_ENABLE_NCCL_HANG_DETECTOR=1`, as the detection heuristics still need validation against real-world hangs (spot preemptions, pipeline-parallel send/recv comms that legitimately sit skewed for long periods) before it can be considered for default-on. ### Requirements - RAS itself landed in 2.24, but the poller parses `ncclras -f json`, and the `-f` flag requires NCCL 2.28+. If the binary isn't on PATH, or rejects `-f`, the callback logs a warning once and disables itself for the rest of the run rather than retrying forever. - `ci/docker/base.gpu.Dockerfile` pins and holds `libnccl2`/`libnccl-dev` at `2.28.9-1+cuda12.9` (previously whatever the CUDA base image shipped) so `ncclras` is present and JSON-capable in GPU CI. The build fails fast if the pin doesn't stick or the client binary is missing. This affects all GPU CI images, not just Train tests. - `py-spy` (and `SYS_PTRACE` in the container) for native stack traces at hang time. When unavailable, the callback falls back to a Python-only traceback of every thread. ### How it works - `NCCLRASCallback` lives on the controller and polls `ncclras` on a worker (RAS forms a mesh network between ranks, so only one worker needs to be polled to receive the whole network's state). Workers are tried in turn until one returns a usable report. The periodic JSON query runs on a single long-running poller thread, started with the worker group and stopped with it, that queries every `RAY_TRAIN_NCCL_RAS_MIN_POLL_INTERVAL_S` and hands each report to the controller through a queue; the controller's poll hook drains one report per poll and never blocks on a query. The one-off `ncclras -f text` report and the stack-trace capture at escalation and confirmation time run synchronously in the poll hook, since at that point the job is already stalled. - A communicator's frozen streak only advances when the RAS report shows a collective-count mismatch, every rank in that communicator is `RUNNING`, and *no* rank advanced *any* collective since the previous poll. Any progress on any op resets that communicator's streak; streaks are tracked per communicator so each one is confirmed on its own. - A confirmed hang requires the streak to persist for `RAY_TRAIN_NCCL_RAS_CONFIRM_DURATION_S` (default 600s), converted to a consecutive-poll count using `RAY_TRAIN_NCCL_RAS_MIN_POLL_INTERVAL_S` (default 15s), 40 polls by default, to ensure that a mismatch isn't a snapshot issue. The confirm window is counted in polls of the poller thread, whose cadence is independent of the controller's health-check loop, so the real wall-clock time to confirmation is at least the configured duration and typically a little more (the first frozen poll needs a previous report to diff against, and the controller only acts on a report at its next poll). - Before confirmation there is an escalation ladder: a `WARNING` when a communicator first crosses ~60s frozen, then a periodic `WARNING` every ~120s naming every still-frozen communicator, its stalled duration, and (in `fail` mode) the time remaining until `NCCLHangError`, with the human-readable `ncclras -f text` report logged at INFO level on the same poll. A communicator that resumes progress after being suspected logs an explicit recovery message. - On a confirmed hang, the callback logs the `ncclras -f text` report and captures py-spy stack traces from all workers (uploaded to `<experiment_path>/nccl_ras_hang_stack_traces/` as `rank_<i>.log`). Then, depending on the callback mode, in `fail` an `NCCLHangError` is raised and in `observe` a detailed log message is produced but nothing more. `observe` is the default; set `RAY_TRAIN_NCCL_RAS_ACTION=fail` to fail the run. - `NCCLHangError` (a `WorkerGroupError` subclass, `DeveloperAPI`, exported as `ray.train.NCCLHangError`) goes through the `DefaultFailurePolicy` like any other worker failure, so the run is restarted up to `max_failures` times. An earlier revision made it non-retryable; that was dropped since a hang can be caused by flaky hardware (e.g. a NIC) that a restart onto other nodes would fix. Making it non-retryable can be revisited in a follow-up. ### Configuration | Env var | Default | Read on | | --- | --- | --- | | `NCCL_RAS_ADDR` | unset (NCCL's own default) | worker | | `RAY_TRAIN_ENABLE_NCCL_HANG_DETECTOR` | `0` | driver | | `RAY_TRAIN_NCCL_RAS_ACTION` | `observe` | driver | | `RAY_TRAIN_NCCL_RAS_MIN_POLL_INTERVAL_S` | `15` | driver | | `RAY_TRAIN_NCCL_RAS_CONFIRM_DURATION_S` | `600` | driver | The `RAY_TRAIN_*` knobs are read once when the callback is constructed on the driver and validated eagerly (invalid values raise at construction). `NCCL_RAS_ADDR` is NCCL's own variable and is read on the worker at query time; it is only passed to `ncclras` (as `-h`/`-p`) when the user has set it, otherwise `ncclras` uses NCCL's built-in default so Ray never has to track that value. It has been added to `ENV_VARS_TO_PROPAGATE` so setting it on the driver reaches the workers. ### Known limitations - **Symmetric in-collective hangs are not detected.** RAS reports collective *launch* counts, so if every rank launches the same collective and the fabric wedges mid-op, all counts match and skew is zero. - **A rank that exited early is not detected.** A communicator is only considered for detection when all of its ranks report `RUNNING`, so a `FINALIZE`/`ABORT` rank alongside frozen peers is currently skipped. This could be handled here, but the Ray health checker should catch it first. - **Legitimately idle, skewed communicators look like hangs.** A communicator that sits with a non-zero skew and no progress for the whole confirm window (for example a pipeline-parallel send/recv comm waiting on a slow stage) will be confirmed as a hang and, in `fail` mode, fail the run. This false-positive mode is the main reason the callback is default-off and the action mode is `observe` by default. - Detection is only acted on from the controller's poll hook, so the time from the confirming RAS report to the `NCCLHangError` is bounded by the controller's health-check interval; the poller thread itself runs independently of that loop. - The missing-binary degradation is decided from the last worker tried. If an earlier worker lacks the binary and a later one times out, the poll is treated as transient and retried instead of disabling the detector. - `missing_ranks` (unresponsive / considered-dead peers) is parsed but not yet used as a signal. - No metrics are emitted yet, and there is no culprit-rank attribution. `NCCLHangError.worker_failures` is empty; the RAS text report and stack traces are the only diagnostics. These will be added in future versions of the detector. ### Testing - `test_nccl_ras_callback.py` — CPU unit coverage of RAS JSON parsing (including the malformed `missing_ranks[]` comma NCCL 2.28.9 emits), `NCCL_RAS_ADDR` parsing, frozen-vs-advancing classification, per-communicator streak independence, communicators appearing and disappearing between polls, the `RASPoller` thread (publishes each report, keeps polling through transient failures, publishes a fatal `RASQueryError` and exits on a misconfiguration, worker fallback in `query`), the callback's poller lifecycle (start/stop with the worker group, fresh poller on an elastic restart, degrade on a fatal result), confirm-duration → poll-count conversion, config validation, the escalation/observe messaging, and that a failed stack dump does not suppress the hang error. - `test_nccl_ras_hang_detection.py` — GPU end-to-end scenarios (`train_v2_gpu`) inducing real NCCL desyncs in a `TorchTrainer` with the detector configured for fast confirmation. Requires ≥ 2 visible GPUs and `ncclras` on PATH; the multi-communicator subset test requires 4 GPUs and skips otherwise. --------- Signed-off-by: Mark Towers <[email protected]> Co-authored-by: Mark Towers <[email protected]>
## Description The hang detector polls NCCL RAS frequently to check if ranks have different numbers of collectives launched. Currently, we log that data regularly, however, this makes the post-mortem analyses difficult. Therefore, this PR adds a circular buffer for recording a history of the NCCL RAS queries and on confirmation are dumped into the diagnostic folder. To ensure that the history can include RAS queries from before a hang started, the length of the circular buffer is the number of number of polls required for confirmation plus a fixed value. ## Related issues Continuation of ray-project#64928 --------- Signed-off-by: Mark Towers <[email protected]> Co-authored-by: Mark Towers <[email protected]>
## Description For the hang detector, it currently has a suite of diagnostics for identifying software based causes for a hang (stack trace, pytorch flight recorder, nccl ras, etc). However, a hang can be caused by both hardware and software like networks or GPU failures. Therefore, this PR adds `nvidia-smi -q` as a diagnostic tool on confirmations to understand the state of the underlying hardware used during training and save this data at the end. ## Related issues Continuation of #64928 --------- Signed-off-by: Mark Towers <[email protected]> Co-authored-by: Mark Towers <[email protected]>
## Description Flight recorder is a pytorch feature that records metadata on collectives that are run on each ranks like shape, dtype, etc and helps users diagnose collective related issues like hangs. Therefore, this PR integrates the flight recorder into the NCCL hang detector as a diagnostic tool. The flight recorder is armed through the env-var then the buffer can be dumped at any point through `_dump_fr_trace_json`. On confirmation we dump all the buffers and save each rank's data to different file. To explore is saving the buffers on suspicion to prevent other communicators to override the hanging communicator on the same rank. This is the last diagnostic PR for the hang detector (stack trace, nvidia-smi, ras-history and flight recorder), therefore, I've rewritten the testing script to combine the separate diagnostic tests into parameterized tests ## Related issues Continuation of #64928 --------- Signed-off-by: Mark Towers <[email protected]> Co-authored-by: Mark Towers <[email protected]>
…#67794) ## Problem - The NCCL hang detector dumps a hung worker's stack with an unprivileged `py-spy dump --pid <pid> --native`. - In containers with restricted ptrace that call always fails. The dump then has no native frames, so it cannot show where NCCL is blocked. - py-spy reports: `Permission Denied: Try running again with elevated permissions by going 'sudo env "PATH=$PATH" !!'` - Verified on an Anyscale worker: `CapEff: 0000000000000000`, `/proc/sys/kernel/yama/ptrace_scope` is `1`, so a child py-spy cannot trace its parent. - The `ray` user there has passwordless sudo, and `sudo env PATH=$PATH py-spy dump --pid <pid> --native` succeeds with native frames. ## Change - Try the unprivileged py-spy first, as today. - If it fails and `sudo -n true` succeeds, retry as `sudo -n env PATH=... py-spy dump --pid <pid> --native` with the same timeout. - Otherwise fall through to the Python-only dump, with py-spy's own error message. - This mirrors `_can_passwordless_sudo` in `python/ray/dashboard/modules/reporter/profile_manager.py`, run synchronously. - `dump_stack_trace` is split into `_run_py_spy(cmd, timeout_s)` and `_can_passwordless_sudo()`. ``` py-spy dump --native ──fail──> sudo -n true ok? ──yes──> sudo -n env PATH=... py-spy dump --native └──no──> Python-only dump (as today) ``` ## Decisions to confirm - The sudo check is cached per process, since the hung worker may dump more than once. - `sudo -n` is used everywhere so it can never prompt for a password. - The `sudo -n true` check has a 5 s timeout. - sudo is not tried when py-spy is not on `PATH`. A missing binary is not a permission problem. - The timeout is a budget for the whole dump. The sudo check and retry only get what the first attempt left, so the fan-out timeout still holds. ## Related - Detector PRs by @pseudo-rnd-thoughts: #64928, #66203, #66629, #66627. - Companion PR #67795 adds thread names to the Python-only fallback; the two touch different parts of `dump_stack_trace` and apply independently. Duplicate-work check: `gh pr list -R ray-project/ray --search "nccl_ras OR hang detector"` and `--search "py-spy sudo"` returned nothing related (only the unrelated Grafana PRs #66958 and #66810). Tests: `python -m pytest python/ray/train/v2/tests/test_nccl_ras_callback.py -v` passes, 120 passed, including four new `dump_stack_trace` sudo tests. AI assistance (Claude Code) was used for this PR. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]>
…mp (#67795) ## Problem - py-spy is refused on many workers because ptrace is restricted in containers. Every Anyscale worker is one of them (empty `CapEff`, Yama `ptrace_scope` 1). - The Python-only fallback is therefore the dump users actually see. - It labels each thread with its numeric ident only. The reader has to infer from the frames which one is Ray Train's `TrainingThread(train_func)`, which is the `MonitoringThread`, and which is the actor main thread. - Current output, from a hung Ray Train worker on Anyscale: ``` # Thread 137667459151424 File "/usr/lib/python3.12/threading.py", line 1030, in _bootstrap self._bootstrap_inner() ``` ## Change - `dump_stack_trace` looks up thread names once through `threading.enumerate()` and prints the name next to the ident. - The rest of the dump is unchanged. ``` before: # Thread 137667459151424 after: # Thread 137667459151424 (TrainingThread(train_func)) ``` ## Decisions to confirm - Threads that are not in `threading.enumerate()` (threads not started through `threading`, for example C-created ones) are labelled `unknown`. ## Related - Detector PRs by @pseudo-rnd-thoughts: #64928, #66203, #66629, #66627. - #67794 (sudo retry for py-spy) touches the same function but not these lines. The two apply independently. Duplicate-work check: `gh pr list -R ray-project/ray --search "nccl_ras OR hang detector"` and a search for "thread name" with "nccl_ras" found no PR making this change (only the Grafana and user-guide PRs #66958, #66810, #67068 and the sibling #67794). Test: `python -m pytest python/ray/train/v2/tests/test_nccl_ras_callback.py -v` passes, 117 tests. `pre-commit run --files` on both files passes. AI assistance (Claude Code) was used for this PR. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]>

Description
This PR adds an opt-in callback that detects hanging distributed training jobs by polling NCCL's RAS (Reliability/Availability/Serviceability) subsystem. NCCL ≥ 2.24 runs a monitoring thread inside every NCCL process that forms a peer mesh tracking per-rank health and collective op-counts. By querying the
ncclrasclient and diffing collective-counts between successive polls, Ray Train can automatically detect and act on hangs that would otherwise stall a job until a torch process group timeout occurs.As RAS gives a snapshot of the current NCCL state, to determine if a mismatch is a temporary issue or a permanent one, the callback polls RAS every N seconds. If a communicator is mismatched and makes no progress at all across multiple sequential polls, then this most likely indicates that a deadlock / wedge / hang is in progress for that communicator.
It's important to note that it's possible for NCCL to continue (not hang) with incorrect data depending on the NCCL operation, tensor size, NCCL version, etc. In these cases, users will observe the collective-count continue to increase but often with a constant mismatch. In this version of the callback, we are not detecting those issues and focusing purely on NCCL collective mismatches which cause hangs.
The callback is disabled by default and enabled with
RAY_TRAIN_ENABLE_NCCL_HANG_DETECTOR=1, as the detection heuristics still need validation against real-world hangs (spot preemptions, pipeline-parallel send/recv comms that legitimately sit skewed for long periods) before it can be considered for default-on.Requirements
ncclras -f json, and the-fflag requires NCCL 2.28+. If the binary isn't on PATH, or rejects-f, the callback logs a warning once and disables itself for the rest of the run rather than retrying forever.ci/docker/base.gpu.Dockerfilepins and holdslibnccl2/libnccl-devat2.28.9-1+cuda12.9(previously whatever the CUDA base image shipped) soncclrasis present and JSON-capable in GPU CI. The build fails fast if the pin doesn't stick or the client binary is missing. This affects all GPU CI images, not just Train tests.py-spy(andSYS_PTRACEin the container) for native stack traces at hang time. When unavailable, the callback falls back to a Python-only traceback of every thread.How it works
NCCLRASCallbacklives on the controller and pollsncclrason a worker (RAS forms a mesh network between ranks, so only one worker needs to be polled to receive the whole network's state). Workers are tried in turn until one returns a usable report. The periodic JSON query runs on a single long-running poller thread, started with the worker group and stopped with it, that queries everyRAY_TRAIN_NCCL_RAS_MIN_POLL_INTERVAL_Sand hands each report to the controller through a queue; the controller's poll hook drains one report per poll and never blocks on a query. The one-offncclras -f textreport and the stack-trace capture at escalation and confirmation time run synchronously in the poll hook, since at that point the job is already stalled.RUNNING, and no rank advanced any collective since the previous poll. Any progress on any op resets that communicator's streak; streaks are tracked per communicator so each one is confirmed on its own.RAY_TRAIN_NCCL_RAS_CONFIRM_DURATION_S(default 600s), converted to a consecutive-poll count usingRAY_TRAIN_NCCL_RAS_MIN_POLL_INTERVAL_S(default 15s), 40 polls by default, to ensure that a mismatch isn't a snapshot issue. The confirm window is counted in polls of the poller thread, whose cadence is independent of the controller's health-check loop, so the real wall-clock time to confirmation is at least the configured duration and typically a little more (the first frozen poll needs a previous report to diff against, and the controller only acts on a report at its next poll).WARNINGwhen a communicator first crosses ~60s frozen, then a periodicWARNINGevery ~120s naming every still-frozen communicator, its stalled duration, and (infailmode) the time remaining untilNCCLHangError, with the human-readablencclras -f textreport logged at INFO level on the same poll. A communicator that resumes progress after being suspected logs an explicit recovery message.ncclras -f textreport and captures py-spy stack traces from all workers (uploaded to<experiment_path>/nccl_ras_hang_stack_traces/asrank_<i>.log). Then, depending on the callback mode, infailanNCCLHangErroris raised and inobservea detailed log message is produced but nothing more.observeis the default; setRAY_TRAIN_NCCL_RAS_ACTION=failto fail the run.NCCLHangError(aWorkerGroupErrorsubclass,DeveloperAPI, exported asray.train.NCCLHangError) goes through theDefaultFailurePolicylike any other worker failure, so the run is restarted up tomax_failurestimes. An earlier revision made it non-retryable; that was dropped since a hang can be caused by flaky hardware (e.g. a NIC) that a restart onto other nodes would fix. Making it non-retryable can be revisited in a follow-up.Configuration
NCCL_RAS_ADDRRAY_TRAIN_ENABLE_NCCL_HANG_DETECTOR0RAY_TRAIN_NCCL_RAS_ACTIONobserveRAY_TRAIN_NCCL_RAS_MIN_POLL_INTERVAL_S15RAY_TRAIN_NCCL_RAS_CONFIRM_DURATION_S600The
RAY_TRAIN_*knobs are read once when the callback is constructed on the driver and validated eagerly (invalid values raise at construction).NCCL_RAS_ADDRis NCCL's own variable and is read on the worker at query time; it is only passed toncclras(as-h/-p) when the user has set it, otherwisencclrasuses NCCL's built-in default so Ray never has to track that value. It has been added toENV_VARS_TO_PROPAGATEso setting it on the driver reaches the workers.Known limitations
RUNNING, so aFINALIZE/ABORTrank alongside frozen peers is currently skipped. This could be handled here, but the Ray health checker should catch it first.failmode, fail the run. This false-positive mode is the main reason the callback is default-off and the action mode isobserveby default.NCCLHangErroris bounded by the controller's health-check interval; the poller thread itself runs independently of that loop.missing_ranks(unresponsive / considered-dead peers) is parsed but not yet used as a signal.NCCLHangError.worker_failuresis empty; the RAS text report and stack traces are the only diagnostics. These will be added in future versions of the detector.Testing
test_nccl_ras_callback.py— CPU unit coverage of RAS JSON parsing (including the malformedmissing_ranks[]comma NCCL 2.28.9 emits),NCCL_RAS_ADDRparsing, frozen-vs-advancing classification, per-communicator streak independence, communicators appearing and disappearing between polls, theRASPollerthread (publishes each report, keeps polling through transient failures, publishes a fatalRASQueryErrorand exits on a misconfiguration, worker fallback inquery), the callback's poller lifecycle (start/stop with the worker group, fresh poller on an elastic restart, degrade on a fatal result), confirm-duration → poll-count conversion, config validation, the escalation/observe messaging, and that a failed stack dump does not suppress the hang error.test_nccl_ras_hang_detection.py— GPU end-to-end scenarios (train_v2_gpu) inducing real NCCL desyncs in aTorchTrainerwith the detector configured for fast confirmation. Requires ≥ 2 visible GPUs andncclrason PATH; the multi-communicator subset test requires 4 GPUs and skips otherwise.