Repository navigation
[c10d] Flight recorder for backends without native support, and dump it on failure - #192233
tushar00jain wants to merge 7 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/192233
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (2 Unrelated Failures)As of commit f514adc with merge base b9410b6 ( BROKEN TRUNK - The following jobs failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
…it on failure Gives backends with no native FlightRecorder -- nccl2 in particular -- a working flight recorder, and makes a hang leave a post-mortem on disk. Before this nccl2 produced nothing at all when it hung, which was the operability regression blocking its rollout. A backend-agnostic FlightRecorderHook records collectives from the c10d dispatcher pre/post hooks, so it works for anything routed through c10d ops. It is attached during process-group creation, gated on the buffer-size knob the recorder already reads (TORCH_FR_BUFFER_SIZE, alias TORCH_NCCL_TRACE_BUFFER_SIZE), so existing job configuration needs no change. Recording. Each hooked backend gets its own recorder instance, keyed by backend name in a registry inside libtorch_cpu; ops served by a backend that records itself are skipped, resolved per op rather than per group so a mixed cpu:gloo,cuda:nccl2 group records its CUDA half instead of being skipped whole. ProcessGroupGloo and the singleton it writes to are untouched. profiling_name carries the real backend name (nccl2:all_reduce), taken from the backend rather than the ProcessGroup, which answers "custom" for anything outside the builtin BackendType enum. A group that cannot supply a real global rank mapping publishes none, rather than identity ranks that are only correct for the world group -- for a subgroup the fabricated mapping made every member claim a group-local rank, and since the dump filename carries the rank and the analyzer parses it back out, members collided on one file and a post-mortem was lost. Completion. Entries are retired when the collective actually completes, not when it is issued. The post-hook fires at issue, so retiring there made duration_ms host-side wall clock, made device state a race two ranks could disagree on, and made "completed" unreachable -- a dump could not tell a finished collective from a hung one. The hook holds the Work from the post-hook and sweeps it, both on later post-hooks and at dump time; the dump-time sweep is the load-bearing one, since a quiescent healthy process would otherwise look hung. A hang needs no observer at all: work that never completes is never retired, so "not completed" is the resting state. Completion requires isCompleted() AND isSuccess(), because isCompleted() is also true for failed work. duration_ms comes from Work::getDuration() and is omitted when the backend cannot supply it, rather than filled with a number that measures how late the hook looked. Ops issued under CUDA graph capture are not recorded, since Work::isCompleted() queries an event and stock skips recording under capture too. Dumping. dump_fr_trace and friends take a backend argument defaulting to gloo, so existing callers get what they get today; the control-plane handlers and the debug server take the same parameter, without which the debug server's FlightRecorder page would silently stop showing nccl2. On failure only the failing backend's instance reaches disk, matching stock, where the sole DebugInfoWriter caller is ProcessGroupNCCL. The trigger is the abort hook, which is what Hooks.hpp already describes an abort hook as being for. nccl2 runs its hooks where a failure is detected, not only where it tears down: abortProcess() runs no hook unless TORCH_NCCL_ASYNC_ERROR_HANDLING asks for teardown, i.e. it runs none in exactly the configurations where the process survives and the trace is worth the most. A single failure can therefore invoke the hook more than once, from different threads, and that is deliberately not deduplicated at the call site -- the thread that detects the failure is usually the watchdog while the thread that reaches ::abort() is the next synchronous collective, so a skip-if-already-ran guard would let the process die mid-write. The one-shot lives in the hook, where it blocks rather than skips. The dump attempts stack traces under a bounded wait and falls back to without, because symbolizing may need the GIL on a thread about to abort; hard-coding them off left every torchfrtrace culprit report with no code location. Analyzer. A hook trace did not analyze at all before this. all_reduce and reduce reached the hook with no output tensors, so every all-reduce was reported as a cross-rank size mismatch -- which poisoned the process group so no later collective could match, and aborted the run at the mismatch cap -- and reduce crashed torchfrtrace outright. Those are producer bugs, fixed by mirroring inputs to outputs for in-place collectives as the native backends do. The list spellings of all_gather and reduce_scatter are the reverse: the trace is faithful and the analyzer's numel rule assumed the single flattened buffer only native backends produce, so the check now tries the native rule first and falls back. Op names the dispatcher distinguishes are no longer collapsed, recv_any_source records its peer as unknown instead of -1 (which the analyzer read as an index and attributed to the highest-ranked member), and "_all_gather_base" is spelled correctly, which means that numel check runs for the first time -- including for native nccl. Diverges from torchcomms in one place worth naming: its flight recorder abort hook does not dump, it flips a health-check flag and sleeps so an external poller can scrape the process. That needs infrastructure a pytorch user may not have running, so the hook writes the trace itself. Test Plan: Hung versus healthy, the property the feature exists for, on a real 2-rank nccl2 run: ``` HEALTHY seq=2 state=completed retired=True duration_ms=0.0096 HUNG seq=3 state=scheduled retired=False duration_ms=- RECOVERED seq=3 state=completed retired=True duration_ms=14998.53 ``` 14998 ms is exactly the time the peer spent not arriving; the old design reported 0.01-0.06 ms of host wall clock for the same op. A real watchdog timeout under default settings, where the rank does die: ``` [rank0] Operation timed out after 10657 ms [rank0] FlightRecorderHook: dumping trace on collective failure [rank0] Aborting process on rank 0 due to timeout rank0 exit code: -6 seq=1 nccl2:all_reduce state=completed retired=True seq=2 nccl2:all_reduce state=scheduled retired=False ``` with stack frames present in the on-disk pickle, and the bounded fallback verified by forcing TORCH_FR_WAIT_TIMEOUT_DUMP_MILSEC=0. A real 2-rank run through the torchfrtrace CLI, zero mismatches: ``` id pass_check collective_name input_sizes output_sizes type_of_mismatch 0 True nccl2:all_reduce [[8]] [[8]] 1 True nccl2:reduce [[8]] [[8]] 2 True nccl2:all_gather [[8]] [[8], [8]] 3 True nccl2:reduce_scatter [[8], [8]] [[8]] 4 True nccl2:barrier [] [] ``` ``` python test/distributed/test_c10d_fr_hook.py -v python test/distributed/test_c10d_nccl2.py -v python test/distributed/flight_recorder/test_fr_analysis.py python test/distributed/flight_recorder/test_loader.py python test/distributed/test_c10d_nccl.py NCCLTraceTest -v python test/distributed/test_c10d_gloo.py ProcessGroupGlooFRTest -v python test/distributed/elastic/test_control_plane.py python test/distributed/test_c10d_nan_check.py python test/distributed/test_c10d_common.py -v ``` ``` Ran 55 tests in 285.510s OK (skipped=6) test_c10d_fr_hook.py Ran 39 tests in 251.640s OK test_c10d_nccl2.py Ran 23 tests in 2.127s OK test_fr_analysis.py Ran 3 tests in 1.787s OK test_loader.py Ran 61 tests in 518.314s OK NCCLTraceTest Ran 71 tests in 377.998s OK (skipped=1) ProcessGroupGlooFRTest Ran 12 tests in 2.399s OK test_control_plane.py Ran 20 tests in 108.198s OK test_c10d_nan_check.py Ran 72 tests in 142.081s OK test_c10d_common.py ``` NCCLTraceTest and test_c10d_nan_check are not incidental: the first is the only coverage of the native _all_gather_base numel check this enables, and the second covers the other consumer of the HookOpName enum. lintrunner --revision HEAD: clean. Authored with the assistance of an AI coding agent. ghstack-source-id: 30c46bf Pull-Request: #192233
| # on every device is still skipped -- a hook there would record nothing. | ||
| if all( | ||
| backend_str in _FR_SELF_RECORDING_BACKENDS | ||
| for backend_str in backend_config.get_device_backend_map().values() |
There was a problem hiding this comment.
will this be an issue when we switch nccl to point to nccl2?
There was a problem hiding this comment.
what problem do you think? We're skipping flight recorder for NCCL, but we will have it for NCCL2
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 0 checks: Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
Merge failedReason: Command Details for Dev Infra teamRaised by workflow job |
| } | ||
|
|
||
| bool recordsFlightRecorderNatively(const std::string& backend) { | ||
| return backend == "gloo" || backend == "nccl" || backend == "xccl"; |
There was a problem hiding this comment.
when we switch the backend default to point nccl to nccl2 this will break?
|
Starting merge as part of PR stack under #192858 |
2 similar comments
|
Starting merge as part of PR stack under #192858 |
|
Starting merge as part of PR stack under #192858 |
Tests for the commit below this one, split out to keep each PR under the 2000 LOC review limit. They do not stand alone -- the implementation is in that commit. test_c10d_fr_hook.py is the bulk, parameterized over a backend that pushes completion (nccl2) and one that does not (fake), so both tiers are covered: the pushed path gets a real device duration and reaches "completed", the fallback retires at issue with neither. The gloo cases assert the hook records nothing, since ProcessGroupGloo records itself and a second recording would duplicate every collective. The ones worth knowing about, because they encode properties rather than behaviour: - a hung collective must read not-completed, and flip to completed once the peer arrives. This is the property the whole feature exists for, so it is a test and not just a drill. - an op still in flight must not report completed. Driven deterministically by making the backend throw between the pre- and post-hook rather than by timing. - recording inside torch.cuda.graph must not invalidate the capture. - a subgroup on a backend with no rank mapping must publish neither ranks nor a process-wide rank, since a fabricated one collides dump filenames. - hook-produced entries must survive the real analyzer: test_fr_analysis.py runs build_db over hook-shaped entries for the in-place and list-form collectives, with negative cases so the list-form allowance cannot silently accept anything. Test Plan: ``` python test/distributed/test_c10d_fr_hook.py -v python test/distributed/test_c10d_nccl2.py -v python test/distributed/flight_recorder/test_fr_analysis.py python test/distributed/elastic/test_control_plane.py ``` Results are quoted in the implementation commit's message; these files are the tests that produced them. Authored with the assistance of an AI coding agent. Pull Request resolved: #192837 Approved by: https://github.com/d4l3k ghstack dependencies: #192233
…mpletion race (#192858) Two defects in the flight recorder, found in review. Separate from the commits below only because they do not fit inside the 2000 LOC review limit. The backend string "nccl" had two sources of truth for what it builds, and only one of them read TORCH_DIST_USE_NCCL2. _register_builtin_nccl_backend picks its creator from that flag; _FR_SELF_RECORDING_BACKENDS hard-coded Backend.NCCL as self-recording regardless. They agree today by luck, because the flag defaults off and "nccl" builds stock ProcessGroupNCCL, which does record natively. The moment the default flips, "nccl" builds nccl2 and the flight recorder skips it as self-recording -- so the default path loses the feature entirely, and silently. Existing tests never caught it because they all request "nccl2" explicitly. Rather than special-case the name, the registration now records what it actually built: the set is derived from the creator that was chosen, keyed off creator identity rather than re-reading the env, so flipping the default is still a one-line change to the existing ternary and there is no second site to keep in sync. Ordering holds because _ensure_backend_registered runs well before the attach decision, for both new_group and split_group. "nccl-legacy" is added to the set for the same reason -- it builds stock, so the hook it was getting could never record anything. The second is a race. A completion is delivered with the Work, and the hook can only map a Work to its trace entry from the post-hook, which is the one place op_id and the Work are both visible. A fast collective can be completed by the backend's watchdog after it is enqueued but before that post-hook runs, and the callback was then dropped on the floor -- leaving a healthy op unretired and reading "scheduled" forever, which is precisely the false hang signal this feature exists to rule out. A completion that arrives early is no longer a special case. The post-hook, once it has registered the mapping, simply asks the Work whether it already finished successfully and retires it if so. There is then no interval in which a completion can be missed: if it landed before registration this catches it, and if after, the callback finds the mapping. Retirement is claiming rather than checking, so it happens exactly once however the two interleave -- the lookup and both erases happen under one lock, and the loser takes the same early return a Work that was never ours would. An earlier version of this fix stashed early completions keyed by Work* and replayed them, bounded three ways. That was a workaround: Work* is not a stable identity, since the allocator can reuse the address once the original is destroyed, and a stale entry would then report a *different* op as completed while it was still in flight -- a false "completed", which is worse than the false "hang" being fixed. The bounds only shrank the window in which the key could lie. One consequence worth knowing: asking the Work also advances its status, so a short healthy collective now usually retires on the issuing thread rather than from the watchdog push, and pays one event query per op on the issue path. Hook maps become ordered so hooks fire by id. That is what lets the race be tested deterministically rather than with a sleep, and the flight recorder hook's id already assumed ordering against user hooks. Test Plan: The race test does not sleep. A user post-hook with a lower id holds the window open and, inside it, issues a sentinel collective behind the target on the same stream queue; nccl2 pops that queue in order, so a retired sentinel proves the target's completion was already delivered. It then asserts the target is not yet retired -- i.e. the race really occurred -- and that it is retired, completed and still carries a duration once the post-hook returns. Without the fix the last assertion fails, since the completion fires once per Work and no second one is coming. The attach test asserts on what was built rather than on the env var, so it holds either side of the default flip. ``` python test/distributed/test_c10d_fr_hook.py python test/distributed/test_c10d_nccl2.py python test/distributed/test_c10d_nccl.py NCCLTraceTest python test/distributed/flight_recorder/test_fr_analysis.py python test/distributed/test_c10d_hooks.py python test/distributed/test_c10d_nan_check.py ``` ``` Ran 63 tests in 323.043s OK (skipped=9) Ran 50 tests in 345.898s OK (skipped=1) Ran 61 tests in 496.705s OK Ran 23 tests in 1.790s OK Ran 2 tests in 7.803s OK Ran 20 tests in 102.351s OK ``` The last two cover the other consumers of the hook plumbing whose map ordering changed. lintrunner --revision HEAD: clean. Authored with the assistance of an AI coding agent. Pull Request resolved: #192858 Approved by: https://github.com/d4l3k ghstack dependencies: #192233, #192837
…it on failure (pytorch#192233) Gives backends with no native FlightRecorder -- nccl2 in particular -- a working flight recorder, and makes a hang leave a post-mortem on disk. Before this nccl2 produced nothing at all when it hung, which was the operability regression blocking its rollout. A backend-agnostic FlightRecorderHook records collectives from the c10d dispatcher pre/post hooks, so it works for anything routed through c10d ops. It is attached during process-group creation, gated on the buffer-size knob the recorder already reads (TORCH_FR_BUFFER_SIZE, alias TORCH_NCCL_TRACE_BUFFER_SIZE), so existing job configuration needs no change. Recording. Each hooked backend gets its own recorder instance, keyed by backend name in a registry inside libtorch_cpu; ops served by a backend that records itself are skipped, resolved per op rather than per group so a mixed cpu:gloo,cuda:nccl2 group records its CUDA half instead of being skipped whole. ProcessGroupGloo and the singleton it writes to are untouched. profiling_name carries the real backend name (nccl2:all_reduce), taken from the backend rather than the ProcessGroup, which answers "custom" for anything outside the builtin BackendType enum. A group that cannot supply a real global rank mapping publishes none, rather than identity ranks that are only correct for the world group -- for a subgroup the fabricated mapping made every member claim a group-local rank, and since the dump filename carries the rank and the analyzer parses it back out, members collided on one file and a post-mortem was lost. Completion. Entries are retired when the collective actually completes, not when it is issued. The post-hook fires at issue, so retiring there made duration_ms host-side wall clock, made device state a race two ranks could disagree on, and made "completed" unreachable -- a dump could not tell a finished collective from a hung one. The hook holds the Work from the post-hook and sweeps it, both on later post-hooks and at dump time; the dump-time sweep is the load-bearing one, since a quiescent healthy process would otherwise look hung. A hang needs no observer at all: work that never completes is never retired, so "not completed" is the resting state. Completion requires isCompleted() AND isSuccess(), because isCompleted() is also true for failed work. duration_ms comes from Work::getDuration() and is omitted when the backend cannot supply it, rather than filled with a number that measures how late the hook looked. Ops issued under CUDA graph capture are not recorded, since Work::isCompleted() queries an event and stock skips recording under capture too. Dumping. dump_fr_trace and friends take a backend argument defaulting to gloo, so existing callers get what they get today; the control-plane handlers and the debug server take the same parameter, without which the debug server's FlightRecorder page would silently stop showing nccl2. On failure only the failing backend's instance reaches disk, matching stock, where the sole DebugInfoWriter caller is ProcessGroupNCCL. The trigger is the abort hook, which is what Hooks.hpp already describes an abort hook as being for. nccl2 runs its hooks where a failure is detected, not only where it tears down: abortProcess() runs no hook unless TORCH_NCCL_ASYNC_ERROR_HANDLING asks for teardown, i.e. it runs none in exactly the configurations where the process survives and the trace is worth the most. A single failure can therefore invoke the hook more than once, from different threads, and that is deliberately not deduplicated at the call site -- the thread that detects the failure is usually the watchdog while the thread that reaches ::abort() is the next synchronous collective, so a skip-if-already-ran guard would let the process die mid-write. The one-shot lives in the hook, where it blocks rather than skips. The dump attempts stack traces under a bounded wait and falls back to without, because symbolizing may need the GIL on a thread about to abort; hard-coding them off left every torchfrtrace culprit report with no code location. Analyzer. A hook trace did not analyze at all before this. all_reduce and reduce reached the hook with no output tensors, so every all-reduce was reported as a cross-rank size mismatch -- which poisoned the process group so no later collective could match, and aborted the run at the mismatch cap -- and reduce crashed torchfrtrace outright. Those are producer bugs, fixed by mirroring inputs to outputs for in-place collectives as the native backends do. The list spellings of all_gather and reduce_scatter are the reverse: the trace is faithful and the analyzer's numel rule assumed the single flattened buffer only native backends produce, so the check now tries the native rule first and falls back. Op names the dispatcher distinguishes are no longer collapsed, recv_any_source records its peer as unknown instead of -1 (which the analyzer read as an index and attributed to the highest-ranked member), and "_all_gather_base" is spelled correctly, which means that numel check runs for the first time -- including for native nccl. Diverges from torchcomms in one place worth naming: its flight recorder abort hook does not dump, it flips a health-check flag and sleeps so an external poller can scrape the process. That needs infrastructure a pytorch user may not have running, so the hook writes the trace itself. - Learn about completion from the backend instead of polling for it. nccl2's watchdog already establishes completion when it garbage-collects its work queue, and we were throwing that away and re-deriving it by polling Work::isCompleted() -- from a later post-hook and again at dump time, the latter reaching every live hook through a process-global weak-ptr map. Backend now carries a completion hook alongside the abort hook, opt-in with a capability query, and nccl2 fires it per work once, only for COMPLETED, so a failed or timed-out work stays un-retired and a dump keeps reporting it as never seen to finish. The backend supplies the duration too, since it is what knows whether timing was enabled. The sweep, the global hook registry and the duration-unavailable latch are all deleted; dump_fr_trace is one statement. Backends without the hook fall back to retiring in the post-hook: no duration and never "completed", which is honest, since without a push signal we do not know when the op finished. Two lock orders this required. The hook cannot be invoked under the work-queue lock, or every enqueue queues behind whatever the hook waits on -- so completions are collected under the lock and fired after releasing it. And detaching cannot hold the hook's own lock: releasing the last ProcessGroup reference destroys the backend, which joins the watchdog, which may be blocked on that same lock inside the hook. Removal is published under the lock, then unregistration and release happen with nothing held. Consequence for callers: a just-finished op can read as pending for up to one watchdog tick, because nothing polls at dump time any more. Tests are split into the commit above this one, to keep each PR under the 2000 LOC review limit. The results quoted below were produced with both applied. Test Plan: Hung versus healthy, the property the feature exists for, on a real 2-rank nccl2 run: ``` HEALTHY seq=2 state=completed retired=True duration_ms=0.0096 HUNG seq=3 state=scheduled retired=False duration_ms=- RECOVERED seq=3 state=completed retired=True duration_ms=14998.53 ``` 14998 ms is exactly the time the peer spent not arriving; the old design reported 0.01-0.06 ms of host wall clock for the same op. A real watchdog timeout under default settings, where the rank does die: ``` [rank0] Operation timed out after 10657 ms [rank0] FlightRecorderHook: dumping trace on collective failure [rank0] Aborting process on rank 0 due to timeout rank0 exit code: -6 seq=1 nccl2:all_reduce state=completed retired=True seq=2 nccl2:all_reduce state=scheduled retired=False ``` with stack frames present in the on-disk pickle, and the bounded fallback verified by forcing TORCH_FR_WAIT_TIMEOUT_DUMP_MILSEC=0. A real 2-rank run through the torchfrtrace CLI, zero mismatches: ``` id pass_check collective_name input_sizes output_sizes type_of_mismatch 0 True nccl2:all_reduce [[8]] [[8]] 1 True nccl2:reduce [[8]] [[8]] 2 True nccl2:all_gather [[8]] [[8], [8]] 3 True nccl2:reduce_scatter [[8], [8]] [[8]] 4 True nccl2:barrier [] [] ``` ``` python test/distributed/test_c10d_fr_hook.py -v python test/distributed/test_c10d_nccl2.py -v python test/distributed/flight_recorder/test_fr_analysis.py python test/distributed/flight_recorder/test_loader.py python test/distributed/test_c10d_nccl.py NCCLTraceTest -v python test/distributed/test_c10d_gloo.py ProcessGroupGlooFRTest -v python test/distributed/elastic/test_control_plane.py python test/distributed/test_c10d_nan_check.py python test/distributed/test_c10d_common.py -v ``` ``` Ran 55 tests in 285.510s OK (skipped=6) test_c10d_fr_hook.py Ran 39 tests in 251.640s OK test_c10d_nccl2.py Ran 23 tests in 2.127s OK test_fr_analysis.py Ran 3 tests in 1.787s OK test_loader.py Ran 61 tests in 518.314s OK NCCLTraceTest Ran 71 tests in 377.998s OK (skipped=1) ProcessGroupGlooFRTest Ran 12 tests in 2.399s OK test_control_plane.py Ran 20 tests in 108.198s OK test_c10d_nan_check.py Ran 72 tests in 142.081s OK test_c10d_common.py ``` NCCLTraceTest and test_c10d_nan_check are not incidental: the first is the only coverage of the native _all_gather_base numel check this enables, and the second covers the other consumer of the HookOpName enum. lintrunner --revision HEAD: clean. Authored with the assistance of an AI coding agent. Pull Request resolved: pytorch#192233 Approved by: https://github.com/kapilsh, https://github.com/d4l3k
Tests for the commit below this one, split out to keep each PR under the 2000 LOC review limit. They do not stand alone -- the implementation is in that commit. test_c10d_fr_hook.py is the bulk, parameterized over a backend that pushes completion (nccl2) and one that does not (fake), so both tiers are covered: the pushed path gets a real device duration and reaches "completed", the fallback retires at issue with neither. The gloo cases assert the hook records nothing, since ProcessGroupGloo records itself and a second recording would duplicate every collective. The ones worth knowing about, because they encode properties rather than behaviour: - a hung collective must read not-completed, and flip to completed once the peer arrives. This is the property the whole feature exists for, so it is a test and not just a drill. - an op still in flight must not report completed. Driven deterministically by making the backend throw between the pre- and post-hook rather than by timing. - recording inside torch.cuda.graph must not invalidate the capture. - a subgroup on a backend with no rank mapping must publish neither ranks nor a process-wide rank, since a fabricated one collides dump filenames. - hook-produced entries must survive the real analyzer: test_fr_analysis.py runs build_db over hook-shaped entries for the in-place and list-form collectives, with negative cases so the list-form allowance cannot silently accept anything. Test Plan: ``` python test/distributed/test_c10d_fr_hook.py -v python test/distributed/test_c10d_nccl2.py -v python test/distributed/flight_recorder/test_fr_analysis.py python test/distributed/elastic/test_control_plane.py ``` Results are quoted in the implementation commit's message; these files are the tests that produced them. Authored with the assistance of an AI coding agent. Pull Request resolved: pytorch#192837 Approved by: https://github.com/d4l3k ghstack dependencies: pytorch#192233
…mpletion race (pytorch#192858) Two defects in the flight recorder, found in review. Separate from the commits below only because they do not fit inside the 2000 LOC review limit. The backend string "nccl" had two sources of truth for what it builds, and only one of them read TORCH_DIST_USE_NCCL2. _register_builtin_nccl_backend picks its creator from that flag; _FR_SELF_RECORDING_BACKENDS hard-coded Backend.NCCL as self-recording regardless. They agree today by luck, because the flag defaults off and "nccl" builds stock ProcessGroupNCCL, which does record natively. The moment the default flips, "nccl" builds nccl2 and the flight recorder skips it as self-recording -- so the default path loses the feature entirely, and silently. Existing tests never caught it because they all request "nccl2" explicitly. Rather than special-case the name, the registration now records what it actually built: the set is derived from the creator that was chosen, keyed off creator identity rather than re-reading the env, so flipping the default is still a one-line change to the existing ternary and there is no second site to keep in sync. Ordering holds because _ensure_backend_registered runs well before the attach decision, for both new_group and split_group. "nccl-legacy" is added to the set for the same reason -- it builds stock, so the hook it was getting could never record anything. The second is a race. A completion is delivered with the Work, and the hook can only map a Work to its trace entry from the post-hook, which is the one place op_id and the Work are both visible. A fast collective can be completed by the backend's watchdog after it is enqueued but before that post-hook runs, and the callback was then dropped on the floor -- leaving a healthy op unretired and reading "scheduled" forever, which is precisely the false hang signal this feature exists to rule out. A completion that arrives early is no longer a special case. The post-hook, once it has registered the mapping, simply asks the Work whether it already finished successfully and retires it if so. There is then no interval in which a completion can be missed: if it landed before registration this catches it, and if after, the callback finds the mapping. Retirement is claiming rather than checking, so it happens exactly once however the two interleave -- the lookup and both erases happen under one lock, and the loser takes the same early return a Work that was never ours would. An earlier version of this fix stashed early completions keyed by Work* and replayed them, bounded three ways. That was a workaround: Work* is not a stable identity, since the allocator can reuse the address once the original is destroyed, and a stale entry would then report a *different* op as completed while it was still in flight -- a false "completed", which is worse than the false "hang" being fixed. The bounds only shrank the window in which the key could lie. One consequence worth knowing: asking the Work also advances its status, so a short healthy collective now usually retires on the issuing thread rather than from the watchdog push, and pays one event query per op on the issue path. Hook maps become ordered so hooks fire by id. That is what lets the race be tested deterministically rather than with a sleep, and the flight recorder hook's id already assumed ordering against user hooks. Test Plan: The race test does not sleep. A user post-hook with a lower id holds the window open and, inside it, issues a sentinel collective behind the target on the same stream queue; nccl2 pops that queue in order, so a retired sentinel proves the target's completion was already delivered. It then asserts the target is not yet retired -- i.e. the race really occurred -- and that it is retired, completed and still carries a duration once the post-hook returns. Without the fix the last assertion fails, since the completion fires once per Work and no second one is coming. The attach test asserts on what was built rather than on the env var, so it holds either side of the default flip. ``` python test/distributed/test_c10d_fr_hook.py python test/distributed/test_c10d_nccl2.py python test/distributed/test_c10d_nccl.py NCCLTraceTest python test/distributed/flight_recorder/test_fr_analysis.py python test/distributed/test_c10d_hooks.py python test/distributed/test_c10d_nan_check.py ``` ``` Ran 63 tests in 323.043s OK (skipped=9) Ran 50 tests in 345.898s OK (skipped=1) Ran 61 tests in 496.705s OK Ran 23 tests in 1.790s OK Ran 2 tests in 7.803s OK Ran 20 tests in 102.351s OK ``` The last two cover the other consumers of the hook plumbing whose map ordering changed. lintrunner --revision HEAD: clean. Authored with the assistance of an AI coding agent. Pull Request resolved: pytorch#192858 Approved by: https://github.com/d4l3k ghstack dependencies: pytorch#192233, pytorch#192837
…it on failure (pytorch#192233) Gives backends with no native FlightRecorder -- nccl2 in particular -- a working flight recorder, and makes a hang leave a post-mortem on disk. Before this nccl2 produced nothing at all when it hung, which was the operability regression blocking its rollout. A backend-agnostic FlightRecorderHook records collectives from the c10d dispatcher pre/post hooks, so it works for anything routed through c10d ops. It is attached during process-group creation, gated on the buffer-size knob the recorder already reads (TORCH_FR_BUFFER_SIZE, alias TORCH_NCCL_TRACE_BUFFER_SIZE), so existing job configuration needs no change. Recording. Each hooked backend gets its own recorder instance, keyed by backend name in a registry inside libtorch_cpu; ops served by a backend that records itself are skipped, resolved per op rather than per group so a mixed cpu:gloo,cuda:nccl2 group records its CUDA half instead of being skipped whole. ProcessGroupGloo and the singleton it writes to are untouched. profiling_name carries the real backend name (nccl2:all_reduce), taken from the backend rather than the ProcessGroup, which answers "custom" for anything outside the builtin BackendType enum. A group that cannot supply a real global rank mapping publishes none, rather than identity ranks that are only correct for the world group -- for a subgroup the fabricated mapping made every member claim a group-local rank, and since the dump filename carries the rank and the analyzer parses it back out, members collided on one file and a post-mortem was lost. Completion. Entries are retired when the collective actually completes, not when it is issued. The post-hook fires at issue, so retiring there made duration_ms host-side wall clock, made device state a race two ranks could disagree on, and made "completed" unreachable -- a dump could not tell a finished collective from a hung one. The hook holds the Work from the post-hook and sweeps it, both on later post-hooks and at dump time; the dump-time sweep is the load-bearing one, since a quiescent healthy process would otherwise look hung. A hang needs no observer at all: work that never completes is never retired, so "not completed" is the resting state. Completion requires isCompleted() AND isSuccess(), because isCompleted() is also true for failed work. duration_ms comes from Work::getDuration() and is omitted when the backend cannot supply it, rather than filled with a number that measures how late the hook looked. Ops issued under CUDA graph capture are not recorded, since Work::isCompleted() queries an event and stock skips recording under capture too. Dumping. dump_fr_trace and friends take a backend argument defaulting to gloo, so existing callers get what they get today; the control-plane handlers and the debug server take the same parameter, without which the debug server's FlightRecorder page would silently stop showing nccl2. On failure only the failing backend's instance reaches disk, matching stock, where the sole DebugInfoWriter caller is ProcessGroupNCCL. The trigger is the abort hook, which is what Hooks.hpp already describes an abort hook as being for. nccl2 runs its hooks where a failure is detected, not only where it tears down: abortProcess() runs no hook unless TORCH_NCCL_ASYNC_ERROR_HANDLING asks for teardown, i.e. it runs none in exactly the configurations where the process survives and the trace is worth the most. A single failure can therefore invoke the hook more than once, from different threads, and that is deliberately not deduplicated at the call site -- the thread that detects the failure is usually the watchdog while the thread that reaches ::abort() is the next synchronous collective, so a skip-if-already-ran guard would let the process die mid-write. The one-shot lives in the hook, where it blocks rather than skips. The dump attempts stack traces under a bounded wait and falls back to without, because symbolizing may need the GIL on a thread about to abort; hard-coding them off left every torchfrtrace culprit report with no code location. Analyzer. A hook trace did not analyze at all before this. all_reduce and reduce reached the hook with no output tensors, so every all-reduce was reported as a cross-rank size mismatch -- which poisoned the process group so no later collective could match, and aborted the run at the mismatch cap -- and reduce crashed torchfrtrace outright. Those are producer bugs, fixed by mirroring inputs to outputs for in-place collectives as the native backends do. The list spellings of all_gather and reduce_scatter are the reverse: the trace is faithful and the analyzer's numel rule assumed the single flattened buffer only native backends produce, so the check now tries the native rule first and falls back. Op names the dispatcher distinguishes are no longer collapsed, recv_any_source records its peer as unknown instead of -1 (which the analyzer read as an index and attributed to the highest-ranked member), and "_all_gather_base" is spelled correctly, which means that numel check runs for the first time -- including for native nccl. Diverges from torchcomms in one place worth naming: its flight recorder abort hook does not dump, it flips a health-check flag and sleeps so an external poller can scrape the process. That needs infrastructure a pytorch user may not have running, so the hook writes the trace itself. - Learn about completion from the backend instead of polling for it. nccl2's watchdog already establishes completion when it garbage-collects its work queue, and we were throwing that away and re-deriving it by polling Work::isCompleted() -- from a later post-hook and again at dump time, the latter reaching every live hook through a process-global weak-ptr map. Backend now carries a completion hook alongside the abort hook, opt-in with a capability query, and nccl2 fires it per work once, only for COMPLETED, so a failed or timed-out work stays un-retired and a dump keeps reporting it as never seen to finish. The backend supplies the duration too, since it is what knows whether timing was enabled. The sweep, the global hook registry and the duration-unavailable latch are all deleted; dump_fr_trace is one statement. Backends without the hook fall back to retiring in the post-hook: no duration and never "completed", which is honest, since without a push signal we do not know when the op finished. Two lock orders this required. The hook cannot be invoked under the work-queue lock, or every enqueue queues behind whatever the hook waits on -- so completions are collected under the lock and fired after releasing it. And detaching cannot hold the hook's own lock: releasing the last ProcessGroup reference destroys the backend, which joins the watchdog, which may be blocked on that same lock inside the hook. Removal is published under the lock, then unregistration and release happen with nothing held. Consequence for callers: a just-finished op can read as pending for up to one watchdog tick, because nothing polls at dump time any more. Tests are split into the commit above this one, to keep each PR under the 2000 LOC review limit. The results quoted below were produced with both applied. Test Plan: Hung versus healthy, the property the feature exists for, on a real 2-rank nccl2 run: ``` HEALTHY seq=2 state=completed retired=True duration_ms=0.0096 HUNG seq=3 state=scheduled retired=False duration_ms=- RECOVERED seq=3 state=completed retired=True duration_ms=14998.53 ``` 14998 ms is exactly the time the peer spent not arriving; the old design reported 0.01-0.06 ms of host wall clock for the same op. A real watchdog timeout under default settings, where the rank does die: ``` [rank0] Operation timed out after 10657 ms [rank0] FlightRecorderHook: dumping trace on collective failure [rank0] Aborting process on rank 0 due to timeout rank0 exit code: -6 seq=1 nccl2:all_reduce state=completed retired=True seq=2 nccl2:all_reduce state=scheduled retired=False ``` with stack frames present in the on-disk pickle, and the bounded fallback verified by forcing TORCH_FR_WAIT_TIMEOUT_DUMP_MILSEC=0. A real 2-rank run through the torchfrtrace CLI, zero mismatches: ``` id pass_check collective_name input_sizes output_sizes type_of_mismatch 0 True nccl2:all_reduce [[8]] [[8]] 1 True nccl2:reduce [[8]] [[8]] 2 True nccl2:all_gather [[8]] [[8], [8]] 3 True nccl2:reduce_scatter [[8], [8]] [[8]] 4 True nccl2:barrier [] [] ``` ``` python test/distributed/test_c10d_fr_hook.py -v python test/distributed/test_c10d_nccl2.py -v python test/distributed/flight_recorder/test_fr_analysis.py python test/distributed/flight_recorder/test_loader.py python test/distributed/test_c10d_nccl.py NCCLTraceTest -v python test/distributed/test_c10d_gloo.py ProcessGroupGlooFRTest -v python test/distributed/elastic/test_control_plane.py python test/distributed/test_c10d_nan_check.py python test/distributed/test_c10d_common.py -v ``` ``` Ran 55 tests in 285.510s OK (skipped=6) test_c10d_fr_hook.py Ran 39 tests in 251.640s OK test_c10d_nccl2.py Ran 23 tests in 2.127s OK test_fr_analysis.py Ran 3 tests in 1.787s OK test_loader.py Ran 61 tests in 518.314s OK NCCLTraceTest Ran 71 tests in 377.998s OK (skipped=1) ProcessGroupGlooFRTest Ran 12 tests in 2.399s OK test_control_plane.py Ran 20 tests in 108.198s OK test_c10d_nan_check.py Ran 72 tests in 142.081s OK test_c10d_common.py ``` NCCLTraceTest and test_c10d_nan_check are not incidental: the first is the only coverage of the native _all_gather_base numel check this enables, and the second covers the other consumer of the HookOpName enum. lintrunner --revision HEAD: clean. Authored with the assistance of an AI coding agent. Pull Request resolved: pytorch#192233 Approved by: https://github.com/kapilsh, https://github.com/d4l3k
Tests for the commit below this one, split out to keep each PR under the 2000 LOC review limit. They do not stand alone -- the implementation is in that commit. test_c10d_fr_hook.py is the bulk, parameterized over a backend that pushes completion (nccl2) and one that does not (fake), so both tiers are covered: the pushed path gets a real device duration and reaches "completed", the fallback retires at issue with neither. The gloo cases assert the hook records nothing, since ProcessGroupGloo records itself and a second recording would duplicate every collective. The ones worth knowing about, because they encode properties rather than behaviour: - a hung collective must read not-completed, and flip to completed once the peer arrives. This is the property the whole feature exists for, so it is a test and not just a drill. - an op still in flight must not report completed. Driven deterministically by making the backend throw between the pre- and post-hook rather than by timing. - recording inside torch.cuda.graph must not invalidate the capture. - a subgroup on a backend with no rank mapping must publish neither ranks nor a process-wide rank, since a fabricated one collides dump filenames. - hook-produced entries must survive the real analyzer: test_fr_analysis.py runs build_db over hook-shaped entries for the in-place and list-form collectives, with negative cases so the list-form allowance cannot silently accept anything. Test Plan: ``` python test/distributed/test_c10d_fr_hook.py -v python test/distributed/test_c10d_nccl2.py -v python test/distributed/flight_recorder/test_fr_analysis.py python test/distributed/elastic/test_control_plane.py ``` Results are quoted in the implementation commit's message; these files are the tests that produced them. Authored with the assistance of an AI coding agent. Pull Request resolved: pytorch#192837 Approved by: https://github.com/d4l3k ghstack dependencies: pytorch#192233
…mpletion race (pytorch#192858) Two defects in the flight recorder, found in review. Separate from the commits below only because they do not fit inside the 2000 LOC review limit. The backend string "nccl" had two sources of truth for what it builds, and only one of them read TORCH_DIST_USE_NCCL2. _register_builtin_nccl_backend picks its creator from that flag; _FR_SELF_RECORDING_BACKENDS hard-coded Backend.NCCL as self-recording regardless. They agree today by luck, because the flag defaults off and "nccl" builds stock ProcessGroupNCCL, which does record natively. The moment the default flips, "nccl" builds nccl2 and the flight recorder skips it as self-recording -- so the default path loses the feature entirely, and silently. Existing tests never caught it because they all request "nccl2" explicitly. Rather than special-case the name, the registration now records what it actually built: the set is derived from the creator that was chosen, keyed off creator identity rather than re-reading the env, so flipping the default is still a one-line change to the existing ternary and there is no second site to keep in sync. Ordering holds because _ensure_backend_registered runs well before the attach decision, for both new_group and split_group. "nccl-legacy" is added to the set for the same reason -- it builds stock, so the hook it was getting could never record anything. The second is a race. A completion is delivered with the Work, and the hook can only map a Work to its trace entry from the post-hook, which is the one place op_id and the Work are both visible. A fast collective can be completed by the backend's watchdog after it is enqueued but before that post-hook runs, and the callback was then dropped on the floor -- leaving a healthy op unretired and reading "scheduled" forever, which is precisely the false hang signal this feature exists to rule out. A completion that arrives early is no longer a special case. The post-hook, once it has registered the mapping, simply asks the Work whether it already finished successfully and retires it if so. There is then no interval in which a completion can be missed: if it landed before registration this catches it, and if after, the callback finds the mapping. Retirement is claiming rather than checking, so it happens exactly once however the two interleave -- the lookup and both erases happen under one lock, and the loser takes the same early return a Work that was never ours would. An earlier version of this fix stashed early completions keyed by Work* and replayed them, bounded three ways. That was a workaround: Work* is not a stable identity, since the allocator can reuse the address once the original is destroyed, and a stale entry would then report a *different* op as completed while it was still in flight -- a false "completed", which is worse than the false "hang" being fixed. The bounds only shrank the window in which the key could lie. One consequence worth knowing: asking the Work also advances its status, so a short healthy collective now usually retires on the issuing thread rather than from the watchdog push, and pays one event query per op on the issue path. Hook maps become ordered so hooks fire by id. That is what lets the race be tested deterministically rather than with a sleep, and the flight recorder hook's id already assumed ordering against user hooks. Test Plan: The race test does not sleep. A user post-hook with a lower id holds the window open and, inside it, issues a sentinel collective behind the target on the same stream queue; nccl2 pops that queue in order, so a retired sentinel proves the target's completion was already delivered. It then asserts the target is not yet retired -- i.e. the race really occurred -- and that it is retired, completed and still carries a duration once the post-hook returns. Without the fix the last assertion fails, since the completion fires once per Work and no second one is coming. The attach test asserts on what was built rather than on the env var, so it holds either side of the default flip. ``` python test/distributed/test_c10d_fr_hook.py python test/distributed/test_c10d_nccl2.py python test/distributed/test_c10d_nccl.py NCCLTraceTest python test/distributed/flight_recorder/test_fr_analysis.py python test/distributed/test_c10d_hooks.py python test/distributed/test_c10d_nan_check.py ``` ``` Ran 63 tests in 323.043s OK (skipped=9) Ran 50 tests in 345.898s OK (skipped=1) Ran 61 tests in 496.705s OK Ran 23 tests in 1.790s OK Ran 2 tests in 7.803s OK Ran 20 tests in 102.351s OK ``` The last two cover the other consumers of the hook plumbing whose map ordering changed. lintrunner --revision HEAD: clean. Authored with the assistance of an AI coding agent. Pull Request resolved: pytorch#192858 Approved by: https://github.com/d4l3k ghstack dependencies: pytorch#192233, pytorch#192837
…96786) `_World` grew a `pg_flight_recorder_hooks` dict in #192233, but `ThreadLocalWorld` -- the per-thread stand-in that `_install_threaded_pg()` swaps into `distributed_c10d._world` for `MultiThreadedTestCase` and `spawn_threads_and_init_comms` -- was never taught to mirror it. Every threaded-PG teardown has raised since then: ``` File "torch/testing/_internal/common_distributed.py", line 1594, in run_test_with_threaded_pg c10d.destroy_process_group() File "torch/distributed/distributed_c10d.py", line 3181, in destroy_process_group _world.pg_flight_recorder_hooks.clear() AttributeError: 'ThreadLocalWorld' object has no attribute 'pg_flight_recorder_hooks' ``` ## Why it matters `destroy_process_group()` clears world state in a fixed order, and `_world.pg_flight_recorder_hooks.clear()` is third from the end. The groups do get shut down, but the `AttributeError` means `_unregister_all_process_groups()` and the `_world.group_count = 0` reset never run. The exception then escapes the `finally:` in `run_test_with_threaded_pg`, so `perThreadTearDown()` is skipped and the rank's thread dies. `_abort_process_group()` breaks in exactly the same place. This went unnoticed for a month because each rank runs in its own thread: pytest turns the escaped exception into a `PytestUnhandledThreadExceptionWarning` and the test still reports PASSED. Nothing in CI goes red; it only shows up as warning spam in FSDP, DTensor and `_composable` multithread logs. For context on how it surfaced: it turned up while reading mi350 trunk logs for an unrelated PR, where several `distributed/_composable/fsdp` tests timed out. Those timeouts did not reproduce locally and this PR is **not** claimed to fix them. The teardown breakage is a real bug on its own and is what this PR fixes. ## Fix Mirror `pg_flight_recorder_hooks` on `ThreadLocalWorld`. `pg_config_info` had drifted out of the mirror as well, and it has its own live failure: `ExecutionTraceObserver._record_pg_config()` reads `_world.pg_config_info` whenever distributed is initialized, so starting an execution-trace capture under a threaded PG raises `'ThreadLocalWorld' object has no attribute 'pg_config_info'` on `main` today. It is derived entirely from state that is already mirrored, so `ThreadLocalWorld` reuses `_World`'s property object instead of duplicating its body. `WorldData`'s fields now default-construct, so adding a field can no longer silently shift the positional constructor the way it did here. The new `test_mirrors_world_state` asserts that every `_World` property is reachable on `ThreadLocalWorld`, which is the check that would have caught #192233 at review time. `test_destroy_process_group_runs_to_completion` asserts `group_count == 0` afterwards, i.e. that teardown reached its final statement rather than bailing out midway. ## Test plan All runs on a 4x MI250X (gfx90a) host, ROCm 7.14, built from this branch. Both new tests fail on `main` and pass with the fix: ``` python test/distributed/test_multi_threaded_pg.py TestThreadLocalWorld -v ``` Before: `Ran 2 tests ... FAILED (failures=1, errors=1)`. After: `Ran 25 tests in 2.064s / OK` for the whole file. The four `distributed/_composable/fsdp` files whose logs showed the warning, run with the warning promoted to an error so any surviving thread exception fails the run: ``` python -m pytest distributed/_composable/fsdp/test_fully_shard_extensions.py -m "not multigpu" -p no:xdist -W "error::pytest.PytestUnhandledThreadExceptionWarning" python -m pytest distributed/_composable/fsdp/test_fully_shard_init.py -m "not multigpu" -p no:xdist -W "error::pytest.PytestUnhandledThreadExceptionWarning" python -m pytest distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -m "not multigpu" -p no:xdist -W "error::pytest.PytestUnhandledThreadExceptionWarning" python -m pytest distributed/_composable/fsdp/test_fully_shard_autograd.py -p no:xdist -W "error::pytest.PytestUnhandledThreadExceptionWarning" ``` `5 passed`, `43 passed 1 skipped`, `7 passed`, `5 passed`. On `main` the first three emit the traceback above once per rank per test and still report PASSED. Wider threaded-PG coverage, same warning-as-error flag: ``` python -m pytest distributed/test_functional_api.py distributed/tensor/test_op_strategy.py distributed/test_functional_differentials.py -p no:xdist -W "error::pytest.PytestUnhandledThreadExceptionWarning" python -m pytest distributed/_composable/fsdp/ -m "not multigpu" -p no:xdist -W "error::pytest.PytestUnhandledThreadExceptionWarning" ``` `24 passed 17 skipped`, `56 passed`, `176 passed 9 skipped`, and `74 passed 12 skipped` for the whole FSDP directory. `ExecutionTraceObserver.register_callback()` + `start()` under a threaded PG raises `'ThreadLocalWorld' object has no attribute 'pg_config_info'` before the change and succeeds after it. The non-threaded `_World` path is unchanged: a plain gloo `init_process_group` / `destroy_process_group` still reports `pg_flight_recorder_hooks == {}`, a populated `pg_config_info`, and `group_count == 0` after teardown. ``` spin quicklint ``` clean on both changed files. This PR was authored with the assistance of an AI agent (Claude). The root-cause analysis and every test result above were reproduced and verified by hand on the machine described. Pull Request resolved: #196786 Approved by: https://github.com/jeffdaily, https://github.com/Skylion007 Co-authored-by: Jeff Daily <[email protected]>
Stack from ghstack (oldest at bottom):
Gives backends with no native FlightRecorder -- nccl2 in particular -- a working
flight recorder, and makes a hang leave a post-mortem on disk. Before this nccl2
produced nothing at all when it hung, which was the operability regression
blocking its rollout.
A backend-agnostic FlightRecorderHook records collectives from the c10d
dispatcher pre/post hooks, so it works for anything routed through c10d ops. It
is attached during process-group creation, gated on the buffer-size knob the
recorder already reads (TORCH_FR_BUFFER_SIZE, alias TORCH_NCCL_TRACE_BUFFER_SIZE),
so existing job configuration needs no change.
Recording. Each hooked backend gets its own recorder instance, keyed by backend
name in a registry inside libtorch_cpu; ops served by a backend that records
itself are skipped, resolved per op rather than per group so a mixed
cpu:gloo,cuda:nccl2 group records its CUDA half instead of being skipped whole.
ProcessGroupGloo and the singleton it writes to are untouched. profiling_name
carries the real backend name (nccl2:all_reduce), taken from the backend rather
than the ProcessGroup, which answers "custom" for anything outside the builtin
BackendType enum. A group that cannot supply a real global rank mapping
publishes none, rather than identity ranks that are only correct for the world
group -- for a subgroup the fabricated mapping made every member claim a
group-local rank, and since the dump filename carries the rank and the analyzer
parses it back out, members collided on one file and a post-mortem was lost.
Completion. Entries are retired when the collective actually completes, not when
it is issued. The post-hook fires at issue, so retiring there made duration_ms
host-side wall clock, made device state a race two ranks could disagree on, and
made "completed" unreachable -- a dump could not tell a finished collective from
a hung one. The hook holds the Work from the post-hook and sweeps it, both on
later post-hooks and at dump time; the dump-time sweep is the load-bearing one,
since a quiescent healthy process would otherwise look hung. A hang needs no
observer at all: work that never completes is never retired, so "not completed"
is the resting state. Completion requires isCompleted() AND isSuccess(), because
isCompleted() is also true for failed work. duration_ms comes from
Work::getDuration() and is omitted when the backend cannot supply it, rather than
filled with a number that measures how late the hook looked. Ops issued under
CUDA graph capture are not recorded, since Work::isCompleted() queries an event
and stock skips recording under capture too.
Dumping. dump_fr_trace and friends take a backend argument defaulting to gloo, so
existing callers get what they get today; the control-plane handlers and the
debug server take the same parameter, without which the debug server's
FlightRecorder page would silently stop showing nccl2. On failure only the
failing backend's instance reaches disk, matching stock, where the sole
DebugInfoWriter caller is ProcessGroupNCCL.
The trigger is the abort hook, which is what Hooks.hpp already describes an abort
hook as being for. nccl2 runs its hooks where a failure is detected, not only
where it tears down: abortProcess() runs no hook unless
TORCH_NCCL_ASYNC_ERROR_HANDLING asks for teardown, i.e. it runs none in exactly
the configurations where the process survives and the trace is worth the most. A
single failure can therefore invoke the hook more than once, from different
threads, and that is deliberately not deduplicated at the call site -- the thread
that detects the failure is usually the watchdog while the thread that reaches
::abort() is the next synchronous collective, so a skip-if-already-ran guard
would let the process die mid-write. The one-shot lives in the hook, where it
blocks rather than skips. The dump attempts stack traces under a bounded wait and
falls back to without, because symbolizing may need the GIL on a thread about to
abort; hard-coding them off left every torchfrtrace culprit report with no code
location.
Analyzer. A hook trace did not analyze at all before this. all_reduce and reduce
reached the hook with no output tensors, so every all-reduce was reported as a
cross-rank size mismatch -- which poisoned the process group so no later
collective could match, and aborted the run at the mismatch cap -- and reduce
crashed torchfrtrace outright. Those are producer bugs, fixed by mirroring inputs
to outputs for in-place collectives as the native backends do. The list spellings
of all_gather and reduce_scatter are the reverse: the trace is faithful and the
analyzer's numel rule assumed the single flattened buffer only native backends
produce, so the check now tries the native rule first and falls back. Op names
the dispatcher distinguishes are no longer collapsed, recv_any_source records its
peer as unknown instead of -1 (which the analyzer read as an index and attributed
to the highest-ranked member), and "_all_gather_base" is spelled correctly, which
means that numel check runs for the first time -- including for native nccl.
Diverges from torchcomms in one place worth naming: its flight recorder abort
hook does not dump, it flips a health-check flag and sleeps so an external poller
can scrape the process. That needs infrastructure a pytorch user may not have
running, so the hook writes the trace itself.
watchdog already establishes completion when it garbage-collects its work
queue, and we were throwing that away and re-deriving it by polling
Work::isCompleted() -- from a later post-hook and again at dump time, the
latter reaching every live hook through a process-global weak-ptr map.
Backend now carries a completion hook alongside the abort hook, opt-in with a
capability query, and nccl2 fires it per work once, only for COMPLETED, so a
failed or timed-out work stays un-retired and a dump keeps reporting it as
never seen to finish. The backend supplies the duration too, since it is what
knows whether timing was enabled. The sweep, the global hook registry and the
duration-unavailable latch are all deleted; dump_fr_trace is one statement.
Backends without the hook fall back to retiring in the post-hook: no duration
and never "completed", which is honest, since without a push signal we do not
know when the op finished.
Two lock orders this required. The hook cannot be invoked under the work-queue
lock, or every enqueue queues behind whatever the hook waits on -- so
completions are collected under the lock and fired after releasing it. And
detaching cannot hold the hook's own lock: releasing the last ProcessGroup
reference destroys the backend, which joins the watchdog, which may be blocked
on that same lock inside the hook. Removal is published under the lock, then
unregistration and release happen with nothing held.
Consequence for callers: a just-finished op can read as pending for up to one
watchdog tick, because nothing polls at dump time any more.
Tests are split into the commit above this one, to keep each PR under the 2000
LOC review limit. The results quoted below were produced with both applied.
Test Plan:
Hung versus healthy, the property the feature exists for, on a real 2-rank nccl2
run:
14998 ms is exactly the time the peer spent not arriving; the old design reported
0.01-0.06 ms of host wall clock for the same op.
A real watchdog timeout under default settings, where the rank does die:
with stack frames present in the on-disk pickle, and the bounded fallback
verified by forcing TORCH_FR_WAIT_TIMEOUT_DUMP_MILSEC=0.
A real 2-rank run through the torchfrtrace CLI, zero mismatches:
NCCLTraceTest and test_c10d_nan_check are not incidental: the first is the only
coverage of the native _all_gather_base numel check this enables, and the second
covers the other consumer of the HookOpName enum.
lintrunner --revision HEAD: clean.
Authored with the assistance of an AI coding agent.