Skip to content

[c10d] Fix threaded-PG teardown crash on pg_flight_recorder_hooks - #196786

Closed
pablo-garay wants to merge 1 commit into
pytorch:mainfrom
ROCm:jeffdaily/threaded-pg-flight-recorder-hooks
Closed

pablo-garay wants to merge 1 commit into
pytorch:mainfrom
ROCm:jeffdaily/threaded-pg-flight-recorder-hooks

Conversation

@pablo-garay

@pablo-garay pablo-garay commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

_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.

cc @awgu @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @pragupta @msaroufim @dcci @aditvenk @weifengpy @kapilsh

`_World` grew a `pg_flight_recorder_hooks` dict in pytorch#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'
```

`destroy_process_group()` clears world state in a fixed order and the failing line is third from the end, so the groups do get shut down but `_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, so it only ever showed up as warning spam in FSDP, DTensor and `_composable` logs.

The fix mirrors `pg_flight_recorder_hooks` on `ThreadLocalWorld`. `pg_config_info` had drifted out of the mirror as well and has its own live failure, since `ExecutionTraceObserver._record_pg_config()` reads it whenever distributed is initialized; it is derived entirely from already-mirrored state, so `ThreadLocalWorld` reuses `_World`'s property object rather than duplicating its body. An alternative would have been to make `destroy_process_group()` tolerate a missing attribute, but that hides the drift instead of fixing it and leaves the next added field to break the same way. `WorldData`'s fields now default-construct so that adding one can no longer silently shift the positional constructor.

Test Plan:

All runs on a 4x MI250X (gfx90a) host, ROCm 7.14, built from this branch. Both new tests fail on `main` (`FAILED (failures=1, errors=1)`) and pass with the fix:

```
python test/distributed/test_multi_threaded_pg.py TestThreadLocalWorld -v
python test/distributed/test_multi_threaded_pg.py -v
```

The four `distributed/_composable/fsdp` files whose CI logs carried the warning, 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"
```

Wider threaded-PG coverage, same 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"
```

All green. `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/destroy still reports an empty hook dict, a populated `pg_config_info`, and `group_count == 0` after teardown. `spin quicklint` is clean on both changed files.

Authored with Claude.
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196786

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (1 Unrelated Failure)

As of commit 4617a65 with merge base f66e97e (image):

FLAKY - The following job failed but was likely due to flakiness present on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@jithunnair-amd jithunnair-amd added oncall: distributed Add this issue/PR to distributed oncall triage queue module: c10d Issues/PRs related to collective communications and process groups release notes: distributed (c10d) release notes category topic: not user facing topic category ciflow/trunk Trigger trunk jobs on your pull request labels Sep 11, 2026
@pytorch-bot pytorch-bot Bot removed the oncall: distributed Add this issue/PR to distributed oncall triage queue label Sep 11, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026

Copy link
Copy Markdown

The label oncall: distributed is only applicable to issues and has been removed. Please only use this label on issues.

@jithunnair-amd jithunnair-amd added the oncall: distributed Add this issue/PR to distributed oncall triage queue label Sep 11, 2026
@pytorch-bot pytorch-bot Bot removed the oncall: distributed Add this issue/PR to distributed oncall triage queue label Sep 11, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026

Copy link
Copy Markdown

The label oncall: distributed is only applicable to issues and has been removed. Please only use this label on issues.

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

twthighd added a commit to twthighd/pytorch that referenced this pull request Sep 18, 2026
…nt tests in test_multi_threaded_pg

Summary:
- Label `TestCollectivesWithWrapper` and `TestCollectivesWithBaseClass`
  with `hw_classification = HardwareClassification.GENERIC` (device-agnostic
  threaded-collective logic on CPU tensors).
- Move `test_bwd_sees_fwd_pg` (requires an accelerator, asserts
  collective+autograd correctness on a device-tensor path) out of
  `TestCollectivesWithBaseClass` into a new parallel
  `TestCollectivesWithBaseClassDevice(MultiThreadedTestCase)` class
  labeled `hw_classification = HardwareClassification.ACCELERATOR`.
- While resolving conflicts against upstream main, migrate the
  newly-landed `test_collectives_issued_from_side_stream` (pytorch#195281) into
  `TestCollectivesWithBaseClassDevice` too: it exercises side-stream
  synchronization on device tensors and read the module-level `device_type`
  constant this PR deletes, so it now takes a `device` parameter and derives
  the device module / `device_sleep` / `get_cycles_per_ms` helpers from
  `self.device_type`; its `@skip_if_lt_x_gpu(1)` is dropped for the same
  reason as `test_bwd_sees_fwd_pg`'s (see below).
- Label the newly-landed `TestThreadLocalWorld` (pytorch#196786, pure world-state
  mirror/teardown logic, no device participation) as `GENERIC` so every
  collected class in the file carries a `hw_classification`.
- Extract a shared `_TestCollectivesBase(MultiThreadedTestCase)` fixture
  base holding `world_size`/`setUp`/`tearDown` (the `TORCH_DIST_INIT_BARRIER`
  env setup plus `_spawn_threads`), and have both `TestCollectivesWithBaseClass`
  and `TestCollectivesWithBaseClassDevice` inherit it. The base has no
  `test_*` methods, so unittest does not collect it and `--hw-classification`
  filtering does not scan it; no `hw_classification` label is needed on it.
- Both device-dependent methods take a `device` parameter and the
  `TestCollectivesWithBaseClassDevice` class is instantiated via
  `instantiate_device_type_tests(..., except_for=("cpu",), allow_xpu=True)`.
  The `except_for=("cpu",)` excludes the CPU variant at instantiation time,
  so on an accelerator host only the accelerator variant is generated and
  runs with `device=<accelerator>` -- matching the original single-run
  behavior (`device_type = acc.type if (acc :=
  torch.accelerator.current_accelerator()) else "cpu"`), while opening the
  class to other accelerator variants beyond CUDA. Neither method carries
  `@skip_if_lt_x_gpu(1)`: the pure-CPU-host skip it provided is now handled
  by `except_for=("cpu",)` (no variant generated on a CPU-only host), so the
  decorator would be redundant. Keeping it would also re-introduce the issue
  raised in review: on a GPU host `@skip_if_lt_x_gpu(1)` only checks
  accelerator *availability*, not whether the current variant is an
  accelerator, so a CPU variant (had one been generated) would run with
  `device="cpu"` instead of being skipped.

This allows the 17 CPU threaded-collective methods to be collected as
GENERIC under `--hw-classification` filtering while the two
accelerator-dependent methods run on-device via an injected `device`
parameter, instead of mislabeling the mixed class or relying on a
module-level device string. The split plus fixture-base pattern keeps each
class classification unambiguous and aligns the ACCELERATOR class with the
TEST_LINTER direction (PR pytorch#190173): instantiated, `device` param on every
`test_*`, no `only_for`.

This is part of the test case refactoring initiative tracked in pytorch#185590.
twthighd added a commit to twthighd/pytorch that referenced this pull request Oct 27, 2026
…evice

Summary:
- TestCollectivesWithBaseClassDevice runs each test in freshly spawned rank
  threads, and the thread-local current device of a new thread starts at
  the default index 0, while the instantiate framework injects an indexed
  device string resolved in the main thread. test_collectives_issued_from_
  side_stream built its tensors from self.device_type and its side stream
  from bare Stream()/current_stream(), and test_bwd_sees_fwd_pg relies on
  the threaded PG moving data on rank 0's current stream - all resolving to
  the thread's current device rather than the injected one, so on a
  non-default primary device the variants would silently exercise the wrong
  card or split tensors and streams across cards.
- Bind each rank thread with torch.accelerator.set_device_index(device) at
  the top of both tests, pass the injected device explicitly to every
  tensor and to Stream()/current_stream(), and derive the device module
  from the injected device. get_cycles_per_ms/device_sleep keep the
  type-only self.device_type argument - they are device-type helpers, and
  their sleep kernel now lands on the bound device.

Verified on an 8-card accelerator backend: the full file collects 25 tests
(23 GENERIC + 2 ACCELERATOR) and the classification filters collect 23 and
2 respectively; with the primary device set to a non-default index, the
injected device carries that index and all four rank threads move from
current device 0 to the injected index while test_bwd_sees_fwd_pg passes
on the accelerator variant. The two TestThreadLocalWorld failures seen on
the verify host were baseline lag (the host snapshot predates pytorch#196786's
pg_flight_recorder_hooks; syncing the matching pure-Python infra file
turned both green). test_collectives_issued_from_side_stream cannot
execute there: the backend module's _sleep entry point exists but the
Sleep operator is not installed in that backend's operator package (error
161001), so its execution stays with CUDA/XPU CI while its device binding
is exercised by the non-default-index probe above.

This allows the rank threads to run on the variant's own device instead of
silently defaulting to the default card.
twthighd added a commit to twthighd/pytorch that referenced this pull request Oct 28, 2026
…evice

Summary:
- TestCollectivesWithBaseClassDevice runs each test in freshly spawned rank
  threads, and the thread-local current device of a new thread starts at
  the default index 0, while the instantiate framework injects an indexed
  device string resolved in the main thread. test_collectives_issued_from_
  side_stream built its tensors from self.device_type and its side stream
  from bare Stream()/current_stream(), and test_bwd_sees_fwd_pg relies on
  the threaded PG moving data on rank 0's current stream - all resolving to
  the thread's current device rather than the injected one, so on a
  non-default primary device the variants would silently exercise the wrong
  card or split tensors and streams across cards.
- Bind each rank thread with torch.accelerator.set_device_index(device) at
  the top of both tests, pass the injected device explicitly to every
  tensor and to Stream()/current_stream(), and derive the device module
  from the injected device. get_cycles_per_ms/device_sleep keep the
  type-only self.device_type argument - they are device-type helpers, and
  their sleep kernel now lands on the bound device.
- Drop except_for=("cpu",) from the instantiation and gate both tests with
  method-level @onlyAccelerator instead: the CPU variant is now collected
  and skips cleanly (onlyAccelerator checks the variant's device_type,
  unlike the removed @skip_if_lt_x_gpu(1) which checked only global
  accelerator availability and would let a CPU variant run with
  device="cpu" on accelerator hosts). Same gating form as the landed
  pytorch#192712.

Verified on an 8-card accelerator backend: the full file collects 27 tests
(23 GENERIC, 2 accelerator-variant, and 2 CPU-variant; each CPU variant is
collected, initializes the threaded fixture, and reports a clean skip with
the onlyAccelerator reason) and test_bwd_sees_fwd_pg passes on the
accelerator variant; with the primary device set to a non-default index,
the injected device carries that index and all four rank threads move from
current device 0 to the injected index. The two TestThreadLocalWorld
failures seen on the verify host were baseline lag (the host snapshot
predates pytorch#196786's pg_flight_recorder_hooks; syncing the matching
pure-Python infra file turned both green). test_collectives_issued_from_
side_stream cannot execute there: the backend module's _sleep entry point
exists but the Sleep operator is not installed in that backend's operator
package (error 161001), so its execution stays with CUDA/XPU CI while its
device binding is exercised by the non-default-index probe above.

This allows the rank threads to run on the variant's own device instead of
silently defaulting to the default card, and keeps the CPU variants
visible as explicit skips on CPU-only hosts.
twthighd added a commit to twthighd/pytorch that referenced this pull request Oct 30, 2026
…nt tests in test_multi_threaded_pg

Summary:
- Label `TestCollectivesWithWrapper` and `TestCollectivesWithBaseClass`
  with `hw_classification = HardwareClassification.GENERIC` (device-agnostic
  threaded-collective logic on CPU tensors).
- Move `test_bwd_sees_fwd_pg` (requires an accelerator, asserts
  collective+autograd correctness on a device-tensor path) out of
  `TestCollectivesWithBaseClass` into a new parallel
  `TestCollectivesWithBaseClassDevice(MultiThreadedTestCase)` class
  labeled `hw_classification = HardwareClassification.ACCELERATOR`.
- While resolving conflicts against upstream main, migrate the
  newly-landed `test_collectives_issued_from_side_stream` (pytorch#195281) into
  `TestCollectivesWithBaseClassDevice` too: it exercises side-stream
  synchronization on device tensors and read the module-level `device_type`
  constant this PR deletes, so it now takes a `device` parameter and derives
  the device module / `device_sleep` / `get_cycles_per_ms` helpers from
  `self.device_type`; its `@skip_if_lt_x_gpu(1)` is dropped for the same
  reason as `test_bwd_sees_fwd_pg`'s (see below).
- Label the newly-landed `TestThreadLocalWorld` (pytorch#196786, pure world-state
  mirror/teardown logic, no device participation) as `GENERIC` so every
  collected class in the file carries a `hw_classification`.
- Extract a shared `_TestCollectivesBase(MultiThreadedTestCase)` fixture
  base holding `world_size`/`setUp`/`tearDown` (the `TORCH_DIST_INIT_BARRIER`
  env setup plus `_spawn_threads`), and have both `TestCollectivesWithBaseClass`
  and `TestCollectivesWithBaseClassDevice` inherit it. The base has no
  `test_*` methods, so unittest does not collect it and `--hw-classification`
  filtering does not scan it; no `hw_classification` label is needed on it.
- Both device-dependent methods take a `device` parameter and the
  `TestCollectivesWithBaseClassDevice` class is instantiated via
  `instantiate_device_type_tests(..., except_for=("cpu",), allow_xpu=True)`.
  The `except_for=("cpu",)` excludes the CPU variant at instantiation time,
  so on an accelerator host only the accelerator variant is generated and
  runs with `device=<accelerator>` -- matching the original single-run
  behavior (`device_type = acc.type if (acc :=
  torch.accelerator.current_accelerator()) else "cpu"`), while opening the
  class to other accelerator variants beyond CUDA. Neither method carries
  `@skip_if_lt_x_gpu(1)`: the pure-CPU-host skip it provided is now handled
  by `except_for=("cpu",)` (no variant generated on a CPU-only host), so the
  decorator would be redundant. Keeping it would also re-introduce the issue
  raised in review: on a GPU host `@skip_if_lt_x_gpu(1)` only checks
  accelerator *availability*, not whether the current variant is an
  accelerator, so a CPU variant (had one been generated) would run with
  `device="cpu"` instead of being skipped.

This allows the 17 CPU threaded-collective methods to be collected as
GENERIC under `--hw-classification` filtering while the two
accelerator-dependent methods run on-device via an injected `device`
parameter, instead of mislabeling the mixed class or relying on a
module-level device string. The split plus fixture-base pattern keeps each
class classification unambiguous and aligns the ACCELERATOR class with the
TEST_LINTER direction (PR pytorch#190173): instantiated, `device` param on every
`test_*`, no `only_for`.

This is part of the test case refactoring initiative tracked in pytorch#185590.
twthighd added a commit to twthighd/pytorch that referenced this pull request Oct 30, 2026
…evice

Summary:
- TestCollectivesWithBaseClassDevice runs each test in freshly spawned rank
  threads, and the thread-local current device of a new thread starts at
  the default index 0, while the instantiate framework injects an indexed
  device string resolved in the main thread. test_collectives_issued_from_
  side_stream built its tensors from self.device_type and its side stream
  from bare Stream()/current_stream(), and test_bwd_sees_fwd_pg relies on
  the threaded PG moving data on rank 0's current stream - all resolving to
  the thread's current device rather than the injected one, so on a
  non-default primary device the variants would silently exercise the wrong
  card or split tensors and streams across cards.
- Bind each rank thread with torch.accelerator.set_device_index(device) at
  the top of both tests, pass the injected device explicitly to every
  tensor and to Stream()/current_stream(), and derive the device module
  from the injected device. get_cycles_per_ms/device_sleep keep the
  type-only self.device_type argument - they are device-type helpers, and
  their sleep kernel now lands on the bound device.
- Drop except_for=("cpu",) from the instantiation and gate both tests with
  method-level @onlyAccelerator instead: the CPU variant is now collected
  and skips cleanly (onlyAccelerator checks the variant's device_type,
  unlike the removed @skip_if_lt_x_gpu(1) which checked only global
  accelerator availability and would let a CPU variant run with
  device="cpu" on accelerator hosts). Same gating form as the landed
  pytorch#192712.

Verified on an 8-card accelerator backend: the full file collects 27 tests
(23 GENERIC, 2 accelerator-variant, and 2 CPU-variant; each CPU variant is
collected, initializes the threaded fixture, and reports a clean skip with
the onlyAccelerator reason) and test_bwd_sees_fwd_pg passes on the
accelerator variant; with the primary device set to a non-default index,
the injected device carries that index and all four rank threads move from
current device 0 to the injected index. The two TestThreadLocalWorld
failures seen on the verify host were baseline lag (the host snapshot
predates pytorch#196786's pg_flight_recorder_hooks; syncing the matching
pure-Python infra file turned both green). test_collectives_issued_from_
side_stream cannot execute there: the backend module's _sleep entry point
exists but the Sleep operator is not installed in that backend's operator
package (error 161001), so its execution stays with CUDA/XPU CI while its
device binding is exercised by the non-default-index probe above.

This allows the rank threads to run on the variant's own device instead of
silently defaulting to the default card, and keeps the CPU variants
visible as explicit skips on CPU-only hosts.
pytorchmergebot pushed a commit that referenced this pull request Oct 30, 2026
…nt test in test_multi_threaded_pg (#191905)

## Summary

Split the device-dependent tests out of the mixed TestCollectivesWithBaseClass into a dedicated ACCELERATOR class instantiated via instantiate_device_type_tests, and label the CPU-only collective classes GENERIC, so the threaded-collective tests are correctly classified under --hw-classification filtering and run on-device via an injected device parameter instead of a module-level device string.

## Changes

- **`test/distributed/test_multi_threaded_pg.py`**:
  - Labeled `TestCollectivesWithWrapper` and `TestCollectivesWithBaseClass` with `hw_classification = HardwareClassification.GENERIC` (device-agnostic threaded-collective logic on CPU tensors).
  - Moved `test_bwd_sees_fwd_pg` (requires an accelerator; asserts that autograd backward runs in the same thread as forward and can still see the process group on a device tensor) out of `TestCollectivesWithBaseClass` into a new parallel `TestCollectivesWithBaseClassDevice` class labeled `hw_classification = HardwareClassification.ACCELERATOR`.
  - During the rebase onto main, `test_collectives_issued_from_side_stream` (added upstream in #195281, reading the module-level device string this PR deletes) moved into the ACCELERATOR class as well, with the same `device` parameter and helpers derived from the variant's `self.device_type`.
  - Extracted a shared `_TestCollectivesBase(MultiThreadedTestCase)` fixture base holding `world_size` / `setUp` / `tearDown` (the `TORCH_DIST_INIT_BARRIER` env setup plus `_spawn_threads`); both `TestCollectivesWithBaseClass` and `TestCollectivesWithBaseClassDevice` inherit it. The base has no `test_*` methods, so unittest does not collect it and `--hw-classification` filtering does not scan it; no `hw_classification` label is needed on it.
  - Both ACCELERATOR methods take a `device` parameter, and `TestCollectivesWithBaseClassDevice` is instantiated via `instantiate_device_type_tests(..., allow_xpu=True)`. The `device` is injected per-variant rather than read from a module-level device string.
  - Removed the module-level `device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu"` string and the pre-existing `@skip_if_lt_x_gpu(1)` decorator on `test_bwd_sees_fwd_pg` (plus its `skip_if_lt_x_gpu` import). Both tests carry the variant-aware `@onlyAccelerator` gate instead: the CPU variant is generated but skips cleanly on every host (the guard reads the running variant's `device_type`), while accelerator variants run on-device with the injected `device`. On a CPU-only host the two tests are now collected and report explicit skips instead of the class being invisible. Same gating shape as the landed #192712.
  - Rank threads are bound to the injected device: `MultiThreadedTestCase` runs each test in freshly spawned threads whose thread-local current device starts at the default index, while the injected device string is resolved in the main thread at class-creation time. Both tests now call `torch.accelerator.set_device_index(device)` up front, `test_collectives_issued_from_side_stream` passes the injected device to its tensors and to `Stream()`/`current_stream()` explicitly, and the type-only helpers (`get_cycles_per_ms`, `device_sleep`) keep `self.device_type` — their sleep kernel now lands on the bound device.

## Motivation

`TestCollectivesWithBaseClass` was a mixed class: CPU threaded-collective methods plus accelerator-dependent methods (`test_bwd_sees_fwd_pg`, and later `test_collectives_issued_from_side_stream`). Under `--hw-classification` filtering such a mixed class cannot be classified unambiguously, and the accelerator method resolved its device from a module-level string (`device_type = acc.type if ...`) rather than the per-variant `device` parameter injected by `instantiate_device_type_tests` — so non-default device variants would use the wrong device. Splitting the class by hardware dependency and instantiating the ACCELERATOR class with an injected `device` parameter makes the classification unambiguous and aligns with the TEST_LINTER direction (PR #190173): instantiated, `device` param on every `test_*`, no `only_for`.

The gating resolves the review divergence concern without hiding the CPU variant from collection: `@onlyAccelerator` reads the running variant's `device_type` (unlike `@skip_if_lt_x_gpu(1)`, which checked only global accelerator availability and would let a CPU variant run with `device="cpu"` on accelerator hosts), so the CPU variant is collected and skips everywhere while accelerator variants keep the original on-device execution.

## Test Plan

Verified on an 8-device accelerator backend with the threaded reference PG:

```bash
python test/distributed/test_multi_threaded_pg.py
# Ran 27 tests — 24 ok, 2 skipped, 1 error. The two skips are the CPU-variant
# methods reporting "onlyAccelerator: doesn't run on CPU or meta devices"
# after the threaded fixture initializes; test_bwd_sees_fwd_pg passes
# on-device on the accelerator variant. The one error is
# test_collectives_issued_from_side_stream on the accelerator variant: the
# backend's _sleep entry point exists but the Sleep operator is not
# installed in its operator package (error 161001), so that test's execution
# stays with CUDA/XPU CI. After syncing the verify host's older pure-Python
# test-infra file (its snapshot predates #196786), the two TestThreadLocalWorld
# tests pass.

python test/distributed/test_multi_threaded_pg.py --hw-classification GENERIC
# OK — total=27, passed=23, unclassified=0, mismatched=4

python test/distributed/test_multi_threaded_pg.py --hw-classification ACCELERATOR
# total=27, passed=4, unclassified=0, mismatched=23 (errors=1, skipped=2:
# the environmental Sleep error and the two CPU-variant skips)
```

Non-default device index: with the primary device set to a non-default index before collection, the injected device carries that index, and each of the four rank threads' current device moves from the default card to the injected index (threads start on the default card; the binding lands them on the variant's device) while test_bwd_sees_fwd_pg passes on the accelerator variant. `lintrunner` reports no lint issues.

## Notes

- This is part of the test case refactoring initiative tracked in #185590.

Pull Request resolved: #191905
Approved by: https://github.com/jishuangfeng, https://github.com/jialinw77, https://github.com/KarhouTam, https://github.com/can-gaa-hou, https://github.com/d4l3k
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…nt test in test_multi_threaded_pg (pytorch#191905)

## Summary

Split the device-dependent tests out of the mixed TestCollectivesWithBaseClass into a dedicated ACCELERATOR class instantiated via instantiate_device_type_tests, and label the CPU-only collective classes GENERIC, so the threaded-collective tests are correctly classified under --hw-classification filtering and run on-device via an injected device parameter instead of a module-level device string.

## Changes

- **`test/distributed/test_multi_threaded_pg.py`**:
  - Labeled `TestCollectivesWithWrapper` and `TestCollectivesWithBaseClass` with `hw_classification = HardwareClassification.GENERIC` (device-agnostic threaded-collective logic on CPU tensors).
  - Moved `test_bwd_sees_fwd_pg` (requires an accelerator; asserts that autograd backward runs in the same thread as forward and can still see the process group on a device tensor) out of `TestCollectivesWithBaseClass` into a new parallel `TestCollectivesWithBaseClassDevice` class labeled `hw_classification = HardwareClassification.ACCELERATOR`.
  - During the rebase onto main, `test_collectives_issued_from_side_stream` (added upstream in pytorch#195281, reading the module-level device string this PR deletes) moved into the ACCELERATOR class as well, with the same `device` parameter and helpers derived from the variant's `self.device_type`.
  - Extracted a shared `_TestCollectivesBase(MultiThreadedTestCase)` fixture base holding `world_size` / `setUp` / `tearDown` (the `TORCH_DIST_INIT_BARRIER` env setup plus `_spawn_threads`); both `TestCollectivesWithBaseClass` and `TestCollectivesWithBaseClassDevice` inherit it. The base has no `test_*` methods, so unittest does not collect it and `--hw-classification` filtering does not scan it; no `hw_classification` label is needed on it.
  - Both ACCELERATOR methods take a `device` parameter, and `TestCollectivesWithBaseClassDevice` is instantiated via `instantiate_device_type_tests(..., allow_xpu=True)`. The `device` is injected per-variant rather than read from a module-level device string.
  - Removed the module-level `device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu"` string and the pre-existing `@skip_if_lt_x_gpu(1)` decorator on `test_bwd_sees_fwd_pg` (plus its `skip_if_lt_x_gpu` import). Both tests carry the variant-aware `@onlyAccelerator` gate instead: the CPU variant is generated but skips cleanly on every host (the guard reads the running variant's `device_type`), while accelerator variants run on-device with the injected `device`. On a CPU-only host the two tests are now collected and report explicit skips instead of the class being invisible. Same gating shape as the landed pytorch#192712.
  - Rank threads are bound to the injected device: `MultiThreadedTestCase` runs each test in freshly spawned threads whose thread-local current device starts at the default index, while the injected device string is resolved in the main thread at class-creation time. Both tests now call `torch.accelerator.set_device_index(device)` up front, `test_collectives_issued_from_side_stream` passes the injected device to its tensors and to `Stream()`/`current_stream()` explicitly, and the type-only helpers (`get_cycles_per_ms`, `device_sleep`) keep `self.device_type` — their sleep kernel now lands on the bound device.

## Motivation

`TestCollectivesWithBaseClass` was a mixed class: CPU threaded-collective methods plus accelerator-dependent methods (`test_bwd_sees_fwd_pg`, and later `test_collectives_issued_from_side_stream`). Under `--hw-classification` filtering such a mixed class cannot be classified unambiguously, and the accelerator method resolved its device from a module-level string (`device_type = acc.type if ...`) rather than the per-variant `device` parameter injected by `instantiate_device_type_tests` — so non-default device variants would use the wrong device. Splitting the class by hardware dependency and instantiating the ACCELERATOR class with an injected `device` parameter makes the classification unambiguous and aligns with the TEST_LINTER direction (PR pytorch#190173): instantiated, `device` param on every `test_*`, no `only_for`.

The gating resolves the review divergence concern without hiding the CPU variant from collection: `@onlyAccelerator` reads the running variant's `device_type` (unlike `@skip_if_lt_x_gpu(1)`, which checked only global accelerator availability and would let a CPU variant run with `device="cpu"` on accelerator hosts), so the CPU variant is collected and skips everywhere while accelerator variants keep the original on-device execution.

## Test Plan

Verified on an 8-device accelerator backend with the threaded reference PG:

```bash
python test/distributed/test_multi_threaded_pg.py
# Ran 27 tests — 24 ok, 2 skipped, 1 error. The two skips are the CPU-variant
# methods reporting "onlyAccelerator: doesn't run on CPU or meta devices"
# after the threaded fixture initializes; test_bwd_sees_fwd_pg passes
# on-device on the accelerator variant. The one error is
# test_collectives_issued_from_side_stream on the accelerator variant: the
# backend's _sleep entry point exists but the Sleep operator is not
# installed in its operator package (error 161001), so that test's execution
# stays with CUDA/XPU CI. After syncing the verify host's older pure-Python
# test-infra file (its snapshot predates pytorch#196786), the two TestThreadLocalWorld
# tests pass.

python test/distributed/test_multi_threaded_pg.py --hw-classification GENERIC
# OK — total=27, passed=23, unclassified=0, mismatched=4

python test/distributed/test_multi_threaded_pg.py --hw-classification ACCELERATOR
# total=27, passed=4, unclassified=0, mismatched=23 (errors=1, skipped=2:
# the environmental Sleep error and the two CPU-variant skips)
```

Non-default device index: with the primary device set to a non-default index before collection, the injected device carries that index, and each of the four rank threads' current device moves from the default card to the injected index (threads start on the default card; the binding lands them on the variant's device) while test_bwd_sees_fwd_pg passes on the accelerator variant. `lintrunner` reports no lint issues.

## Notes

- This is part of the test case refactoring initiative tracked in pytorch#185590.

Pull Request resolved: pytorch#191905
Approved by: https://github.com/jishuangfeng, https://github.com/jialinw77, https://github.com/KarhouTam, https://github.com/can-gaa-hou, https://github.com/d4l3k
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…nt test in test_multi_threaded_pg (pytorch#191905)

## Summary

Split the device-dependent tests out of the mixed TestCollectivesWithBaseClass into a dedicated ACCELERATOR class instantiated via instantiate_device_type_tests, and label the CPU-only collective classes GENERIC, so the threaded-collective tests are correctly classified under --hw-classification filtering and run on-device via an injected device parameter instead of a module-level device string.

## Changes

- **`test/distributed/test_multi_threaded_pg.py`**:
  - Labeled `TestCollectivesWithWrapper` and `TestCollectivesWithBaseClass` with `hw_classification = HardwareClassification.GENERIC` (device-agnostic threaded-collective logic on CPU tensors).
  - Moved `test_bwd_sees_fwd_pg` (requires an accelerator; asserts that autograd backward runs in the same thread as forward and can still see the process group on a device tensor) out of `TestCollectivesWithBaseClass` into a new parallel `TestCollectivesWithBaseClassDevice` class labeled `hw_classification = HardwareClassification.ACCELERATOR`.
  - During the rebase onto main, `test_collectives_issued_from_side_stream` (added upstream in pytorch#195281, reading the module-level device string this PR deletes) moved into the ACCELERATOR class as well, with the same `device` parameter and helpers derived from the variant's `self.device_type`.
  - Extracted a shared `_TestCollectivesBase(MultiThreadedTestCase)` fixture base holding `world_size` / `setUp` / `tearDown` (the `TORCH_DIST_INIT_BARRIER` env setup plus `_spawn_threads`); both `TestCollectivesWithBaseClass` and `TestCollectivesWithBaseClassDevice` inherit it. The base has no `test_*` methods, so unittest does not collect it and `--hw-classification` filtering does not scan it; no `hw_classification` label is needed on it.
  - Both ACCELERATOR methods take a `device` parameter, and `TestCollectivesWithBaseClassDevice` is instantiated via `instantiate_device_type_tests(..., allow_xpu=True)`. The `device` is injected per-variant rather than read from a module-level device string.
  - Removed the module-level `device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu"` string and the pre-existing `@skip_if_lt_x_gpu(1)` decorator on `test_bwd_sees_fwd_pg` (plus its `skip_if_lt_x_gpu` import). Both tests carry the variant-aware `@onlyAccelerator` gate instead: the CPU variant is generated but skips cleanly on every host (the guard reads the running variant's `device_type`), while accelerator variants run on-device with the injected `device`. On a CPU-only host the two tests are now collected and report explicit skips instead of the class being invisible. Same gating shape as the landed pytorch#192712.
  - Rank threads are bound to the injected device: `MultiThreadedTestCase` runs each test in freshly spawned threads whose thread-local current device starts at the default index, while the injected device string is resolved in the main thread at class-creation time. Both tests now call `torch.accelerator.set_device_index(device)` up front, `test_collectives_issued_from_side_stream` passes the injected device to its tensors and to `Stream()`/`current_stream()` explicitly, and the type-only helpers (`get_cycles_per_ms`, `device_sleep`) keep `self.device_type` — their sleep kernel now lands on the bound device.

## Motivation

`TestCollectivesWithBaseClass` was a mixed class: CPU threaded-collective methods plus accelerator-dependent methods (`test_bwd_sees_fwd_pg`, and later `test_collectives_issued_from_side_stream`). Under `--hw-classification` filtering such a mixed class cannot be classified unambiguously, and the accelerator method resolved its device from a module-level string (`device_type = acc.type if ...`) rather than the per-variant `device` parameter injected by `instantiate_device_type_tests` — so non-default device variants would use the wrong device. Splitting the class by hardware dependency and instantiating the ACCELERATOR class with an injected `device` parameter makes the classification unambiguous and aligns with the TEST_LINTER direction (PR pytorch#190173): instantiated, `device` param on every `test_*`, no `only_for`.

The gating resolves the review divergence concern without hiding the CPU variant from collection: `@onlyAccelerator` reads the running variant's `device_type` (unlike `@skip_if_lt_x_gpu(1)`, which checked only global accelerator availability and would let a CPU variant run with `device="cpu"` on accelerator hosts), so the CPU variant is collected and skips everywhere while accelerator variants keep the original on-device execution.

## Test Plan

Verified on an 8-device accelerator backend with the threaded reference PG:

```bash
python test/distributed/test_multi_threaded_pg.py
# Ran 27 tests — 24 ok, 2 skipped, 1 error. The two skips are the CPU-variant
# methods reporting "onlyAccelerator: doesn't run on CPU or meta devices"
# after the threaded fixture initializes; test_bwd_sees_fwd_pg passes
# on-device on the accelerator variant. The one error is
# test_collectives_issued_from_side_stream on the accelerator variant: the
# backend's _sleep entry point exists but the Sleep operator is not
# installed in its operator package (error 161001), so that test's execution
# stays with CUDA/XPU CI. After syncing the verify host's older pure-Python
# test-infra file (its snapshot predates pytorch#196786), the two TestThreadLocalWorld
# tests pass.

python test/distributed/test_multi_threaded_pg.py --hw-classification GENERIC
# OK — total=27, passed=23, unclassified=0, mismatched=4

python test/distributed/test_multi_threaded_pg.py --hw-classification ACCELERATOR
# total=27, passed=4, unclassified=0, mismatched=23 (errors=1, skipped=2:
# the environmental Sleep error and the two CPU-variant skips)
```

Non-default device index: with the primary device set to a non-default index before collection, the injected device carries that index, and each of the four rank threads' current device moves from the default card to the injected index (threads start on the default card; the binding lands them on the variant's device) while test_bwd_sees_fwd_pg passes on the accelerator variant. `lintrunner` reports no lint issues.

## Notes

- This is part of the test case refactoring initiative tracked in pytorch#185590.

Pull Request resolved: pytorch#191905
Approved by: https://github.com/jishuangfeng, https://github.com/jialinw77, https://github.com/KarhouTam, https://github.com/can-gaa-hou, https://github.com/d4l3k
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged module: c10d Issues/PRs related to collective communications and process groups open source release notes: distributed (c10d) release notes category topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants