Skip to content

Fix missing stream synchronization in the threaded process group - #195281

Closed
albmalamd wants to merge 2 commits into
pytorch:mainfrom
albmalamd:fix_upstream_threaded_pg_stream_ordering
Closed

albmalamd wants to merge 2 commits into
pytorch:mainfrom
albmalamd:fix_upstream_threaded_pg_stream_ordering

Conversation

@albmalamd

Copy link
Copy Markdown
Contributor

Summary:

Threaded PG performs the data movement for all ranks on rank 0's thread, hence on rank 0's current stream. The current stream is thread-local, so a collective issued from a side stream is unordered w.r.t. rank 0's copies: rank 0 can read a rank's input before its copy-in has run, and a rank can read its output before rank 0 has written it. FSDP2 hits this on every collective because

FSDPCommContext.lazy_init gives each rank private all-gather and reduce-scatter streams. The host-side ordering in Collective.join was already correct, which is why the race went unnoticed for so long: it resolves favourably on NVIDIA CI and loses on ROCm, where it surfaces as check_sharded_parity gradient mismatches and diverging losses in the FSDP2 and replicate tests (ROCM-28104).

A real backend is stream-ordered w.r.t. the stream that issued the collective, and Collective.join now provides the same guarantee using events: every non-root rank records an event on the stream it issued from, rank 0 waits on those events before copying and records one afterwards, and the other ranks wait on that. The path is a no-op for CPU tensors. test_collectives_issued_from_side_stream covers the same ordering without involving FSDP.

Reproduction:

The affected tests pass by luck on a fast enough GPU, so delay the producing side. In test_param_registration_after_forward, right before model(inp):

if self.rank != 0:
    device_sleep(device_type.type, int(50 * get_cycles_per_ms(device_type.type)))

FSDP2's side streams wait on the rank's compute stream, so the sleep holds back the collective's inputs while rank 0 runs ahead. Without this change the test fails with 9/36 elements mismatched; with it, it passes. test_to_float64_after_init reproduces the same way with the sleep at the top of the training loop.

Summary:

Threaded PG performs the data movement for all ranks on rank 0's thread, hence
on rank 0's current stream. The current stream is thread-local, so a collective
issued from a side stream is unordered w.r.t. rank 0's copies: rank 0 can read a
rank's input before its copy-in has run, and a rank can read its output before
rank 0 has written it. FSDP2 hits this on every collective because

FSDPCommContext.lazy_init gives each rank private all-gather and reduce-scatter
streams. The host-side ordering in Collective.join was already correct, which is
why the race went unnoticed for so long: it resolves favourably on NVIDIA CI and
loses on ROCm, where it surfaces as check_sharded_parity gradient mismatches and
diverging losses in the FSDP2 and replicate tests (ROCM-28104).

A real backend is stream-ordered w.r.t. the stream that issued the collective,
and Collective.join now provides the same guarantee using events: every non-root
rank records an event on the stream it issued from, rank 0 waits on those events
before copying and records one afterwards, and the other ranks wait on that. The
path is a no-op for CPU tensors. test_collectives_issued_from_side_stream covers
the same ordering without involving FSDP.

Reproduction:

The affected tests pass by luck on a fast enough GPU, so delay the producing
side. In test_param_registration_after_forward, right before model(inp):

    if self.rank != 0:
        device_sleep(device_type.type, int(50 * get_cycles_per_ms(device_type.type)))

FSDP2's side streams wait on the rank's compute stream, so the sleep holds back
the collective's inputs while rank 0 runs ahead. Without this change the test
fails with 9/36 elements mismatched; with it, it passes. test_to_float64_after_init
reproduces the same way with the sleep at the top of the training loop.
@pytorch-bot

pytorch-bot Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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 83ad6f2 with merge base 3c844ed (image):

BROKEN TRUNK - The following job 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.

@jithunnair-amd jithunnair-amd added ciflow/trunk Trigger trunk jobs on your pull request ciflow/periodic-rocm-mi350 Trigger "distributed_4gpu" config (only runs distributed tests that need >2GPUs) CI on ROCm MI350 ciflow/periodic-rocm-mi300 Trigger "distributed" config CI on ROCm MI300/MI325 ciflow/periodic-rocm-mi200 Trigger "distributed" config CI on ROCm MI200 labels Aug 29, 2026
@pytorch-bot

This comment was marked as resolved.

@jeffdaily jeffdaily removed the ciflow/periodic-rocm-mi350 Trigger "distributed_4gpu" config (only runs distributed tests that need >2GPUs) CI on ROCm MI350 label Sep 1, 2026
Follow-up to the preceding commit. The synchronization semantics it introduced are unchanged; this is cleanup plus one test-robustness fix.

Each rank's accelerator device set is now computed once in Collective.join and stashed in self._devices, and the leader derives its post-work event set from the union of those rather than running a second pytree walk over every rank's data. Threaded PG backs a large share of the DTensor and FSDP2 test suites and this path runs on every collective, including the CPU-only ones where it can never produce an event, so halving the traversals is worth the extra field. The event containers are plain lists throughout instead of a mix of tuples and lists, and the reason rank 0 records no input event of its own (its copies already run on the stream that produced its data) is now stated in the Note rather than left implicit in a bare `rank > 0`.

In the new test, get_cycles_per_ms is lru_cached and was being called concurrently by all four rank threads. Four calibration sleeps contended on the device, each thread measured roughly four times the true elapsed time, and whichever thread won the cache stored the under-measured value for the rest of the process; the intended 200 ms delay shrank to something closer to 50 ms. One rank now calibrates behind a barrier. The test also drops the redundant explicit device index to match the rest of the file, and switches to all_gather_single / reduce_scatter_single because the *_into_tensor / *_tensor spellings are deprecated and were emitting FutureWarnings from brand new code.

Pooling events to avoid creating and destroying world_size + 1 of them per collective was considered and rejected. The leader's post-work event could be re-recorded by its next collective before a slow rank has enqueued its wait, and if the leader switched streams in between, waiting on that recording would no longer imply the earlier work had completed. The churn is the safer trade.

Test Plan:

The regression test still discriminates. On 4x gfx90a, with torch/testing/_internal/distributed/multi_threaded_pg.py reverted to its pre-fix state it fails with 8/32 mismatched elements, and passes with the fix in place:

```
python test/distributed/test_multi_threaded_pg.py -k test_collectives_issued_from_side_stream
```

Full file, 23 passed:

```
python test/distributed/test_multi_threaded_pg.py
```

The FSDP2 threaded-PG tests named in the PR description (test_param_registration_after_forward, test_to_float64_after_init) live here; 45 passed, 2 skipped:

```
python test/distributed/_composable/fsdp/test_fully_shard_init.py
```

Broader threaded-PG consumer; 9 errors, byte-identical to the same run against an unmodified tree (they are the real-backend multi-GPU cases, unrelated):

```
python test/distributed/test_functional_api.py
```

Authored with assistance from Claude Code.
@pytorch-bot

pytorch-bot Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@jeffdaily

Copy link
Copy Markdown
Collaborator

Thanks for tracking this down, the diagnosis is right. I traced every Collective.work() implementation, including the cross-device .to() paths in AllReduce and ReduceScatter that launch on the source device's current stream, and the per-device event set covers all of them.

Rather than leave you a list of small items I pushed a follow-up commit (83ad6f2) directly to the branch. The synchronization semantics are unchanged; it is cleanup plus one test-robustness fix. Squash it, rework it, or tell me to drop it, whichever you prefer.

The one that matters. get_cycles_per_ms() is lru_cached and was being called from inside the test body, which MultiThreadedTestCase runs concurrently on all four rank threads. Its calibration times ten _sleep(1_000_000) launches, so four concurrent calibrations serialize on the device: each thread measures roughly 4x the true elapsed time, computes a proportionally smaller cycles/ms, and whichever thread wins the cache stores that under-measured value for the rest of the process. The intended 200 ms delay shrinks to something closer to 50 ms. Every other in-tree caller of this helper is multi-process, so this is a new usage pattern. Rank 0 now calibrates behind a dist.barrier() and the others read the cache.

Hot-path cost. Threaded PG backs a large share of the DTensor and FSDP2 suites, and join() runs on every collective including the CPU-only ones where it can never produce an event. Each rank's device set is now computed once in join() and stashed in self._devices, and the leader unions those instead of running a second pytree walk over every rank's data.

Readability. The event containers are plain lists throughout instead of a mix of tuples and lists, and the reason rank 0 records no input event of its own (its copies already run on the stream that produced its data) is now stated in the Note rather than left implicit in the bare rank > 0.

Test. Dropped the explicit device index 0 to match the rest of the file, and switched to all_gather_single / reduce_scatter_single since the *_into_tensor / *_tensor spellings are deprecated and were emitting FutureWarnings from brand new code.

I considered pooling events to avoid creating and destroying world_size + 1 of them per collective, and decided against it: the leader's post-work event could be re-recorded by its next collective before a slow rank has enqueued its wait, and if the leader switched streams in between, waiting on that recording would no longer imply the earlier work had completed. The churn is the safer trade.

On 4x gfx90a, verified the regression test still discriminates. With multi_threaded_pg.py reverted to its pre-fix state it fails with 8/32 mismatched elements, and passes with the fix:

python test/distributed/test_multi_threaded_pg.py -k test_collectives_issued_from_side_stream

Full file 23 passed; test_fully_shard_init.py (where test_param_registration_after_forward and test_to_float64_after_init live) 45 passed, 2 skipped; test_functional_api.py 9 errors, an identical set to the same run against an unmodified tree, all real-backend multi-GPU cases unrelated to this change.

python test/distributed/test_multi_threaded_pg.py
python test/distributed/_composable/fsdp/test_fully_shard_init.py
python test/distributed/test_functional_api.py

Two things left before this can land: it needs a release notes: or topic: not user facing label, and it is still marked draft.

This comment was drafted with an AI assistant (Claude Code).

@jeffdaily
jeffdaily marked this pull request as ready for review September 1, 2026 21:39
@jeffdaily jeffdaily added the topic: not user facing topic category label Sep 1, 2026
@jeffdaily

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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: periodic-rocm-mi200 / linux-jammy-rocm-py3.10-mi200 / test (distributed, 2, 3, linux.rocm.gpu.mi210.2, module:rocm, oncall:distributed)

Details for Dev Infra team Raised by workflow job

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

Same periodic-rocm-mi200 failure on the merge base.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: periodic-rocm-mi200 / linux-jammy-rocm-py3.10-mi200 / test (distributed, 2, 3, linux.rocm.gpu.mi210.2, module:rocm, oncall:distributed)

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

jeffdaily added a commit to ROCm/pytorch that referenced this pull request Sep 2, 2026
…cess group (pytorch#195281) (#3612)

Fix missing stream synchronization in the threaded process group
(pytorch#195281)

## Summary:

Threaded PG performs the data movement for all ranks on rank 0's thread,
hence on rank 0's current stream. The current stream is thread-local, so
a collective issued from a side stream is unordered w.r.t. rank 0's
copies: rank 0 can read a rank's input before its copy-in has run, and a
rank can read its output before rank 0 has written it. FSDP2 hits this
on every collective because

FSDPCommContext.lazy_init gives each rank private all-gather and
reduce-scatter streams. The host-side ordering in Collective.join was
already correct, which is why the race went unnoticed for so long: it
resolves favourably on NVIDIA CI and loses on ROCm, where it surfaces as
check_sharded_parity gradient mismatches and diverging losses in the
FSDP2 and replicate tests (ROCM-28104).

A real backend is stream-ordered w.r.t. the stream that issued the
collective, and Collective.join now provides the same guarantee using
events: every non-root rank records an event on the stream it issued
from, rank 0 waits on those events before copying and records one
afterwards, and the other ranks wait on that. The path is a no-op for
CPU tensors. test_collectives_issued_from_side_stream covers the same
ordering without involving FSDP.

## Reproduction:

The affected tests pass by luck on a fast enough GPU, so delay the
producing side. In test_param_registration_after_forward, right before
model(inp):

    if self.rank != 0:
device_sleep(device_type.type, int(50 *
get_cycles_per_ms(device_type.type)))

FSDP2's side streams wait on the rank's compute stream, so the sleep
holds back the collective's inputs while rank 0 runs ahead. Without this
change the test fails with 9/36 elements mismatched; with it, it passes.
test_to_float64_after_init reproduces the same way with the sleep at the
top of the training loop. Pull Request resolved:
pytorch#195281 Approved by:
https://github.com/jeffdaily


(cherry picked from commit d8cc87a)

Co-authored-by: Jeff Daily <[email protected]>
rocm-repo-management-api-6 Bot added a commit to ROCm/pytorch that referenced this pull request Sep 2, 2026
rocm-repo-management-api-6 Bot added a commit to ROCm/pytorch that referenced this pull request Sep 3, 2026
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…orch#195281)

## Summary:

Threaded PG performs the data movement for all ranks on rank 0's thread, hence on rank 0's current stream. The current stream is thread-local, so a collective issued from a side stream is unordered w.r.t. rank 0's copies: rank 0 can read a rank's input before its copy-in has run, and a rank can read its output before rank 0 has written it. FSDP2 hits this on every collective because

FSDPCommContext.lazy_init gives each rank private all-gather and reduce-scatter streams. The host-side ordering in Collective.join was already correct, which is why the race went unnoticed for so long: it resolves favourably on NVIDIA CI and loses on ROCm, where it surfaces as check_sharded_parity gradient mismatches and diverging losses in the FSDP2 and replicate tests (ROCM-28104).

A real backend is stream-ordered w.r.t. the stream that issued the collective, and Collective.join now provides the same guarantee using events: every non-root rank records an event on the stream it issued from, rank 0 waits on those events before copying and records one afterwards, and the other ranks wait on that. The path is a no-op for CPU tensors. test_collectives_issued_from_side_stream covers the same ordering without involving FSDP.

## Reproduction:

The affected tests pass by luck on a fast enough GPU, so delay the producing side. In test_param_registration_after_forward, right before model(inp):

    if self.rank != 0:
        device_sleep(device_type.type, int(50 * get_cycles_per_ms(device_type.type)))

FSDP2's side streams wait on the rank's compute stream, so the sleep holds back the collective's inputs while rank 0 runs ahead. Without this change the test fails with 9/36 elements mismatched; with it, it passes. test_to_float64_after_init reproduces the same way with the sleep at the top of the training loop.
Pull Request resolved: pytorch#195281
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>
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.
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…#197827)

TestFullyShardCollectiveOps._test_all_gather exercises foreach_all_gather directly with its own copy-in and all-gather streams. Its reshard_after_forward=8 leg calls fsdp_param_group._to_sharded_post_forward(), which clones each parameter's post-forward chunk on the current stream, and then immediately runs foreach_all_gather, whose copy-in kernel reads those clones on all_gather_copy_in_stream. Nothing orders the two: real FSDP records _reshard_after_forward_event in reshard() and makes both all-gather streams wait on it in unshard(), but the test drives the helpers by hand and skips that step, and the pool streams are non-blocking with respect to the current stream. When the clones have not landed yet, whole 8-rank post-forward groups all-gather stale chunks (fresh zeros or recycled memory), which is the k/8-chunk mismatch pattern in the DISABLED issue's CI logs (12.5 and 25 percent of elements, always at the post-forward assertEqual, never at the first leg, whose preceding full_tensor() comparison drains the current stream). On this host the test failed 3 of 25 and 8 of 25 fresh runs under CPU and GPU contention; a deliberate stall on the current stream after the reshard makes it fail every time on an idle GPU, and the event ordering makes that pass.

Make both all-gather streams wait for the current stream right after _to_sharded_post_forward(), the same ordering unshard() provides. The reduce-scatter tests in the class already go through unshard()/reshard() and foreach_reduce's own wait_stream, which is why they never failed. The threaded process group is not involved: the earlier #195281 event fix did not change this signature.

Fixes #195655

Test Plan:

On a ROCm 10.0 gfx950 host, with stress-ng (64 CPU workers, 4 VM workers) and a GEMM co-tenant process on the same GPU, the unfixed test failed 3 of 25 fresh-process runs (8 of 25 on a two-GPU set); with the fix:

    for i in $(seq 25); do PYTHONPATH=test:test/distributed python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py -k test_all_gather_fp32; done
    # 1 passed, in each of the 25 fresh processes under the same contention
    for i in $(seq 10); do PYTHONPATH=test:test/distributed python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py -k "test_all_gather_fp32 or test_reduce_scatter"; done
    # 3 passed, 1 skipped, in each of the 10 fresh processes on an idle GPU

This PR was authored with the assistance of an AI agent (Claude). The analysis and test results were verified by hand.

Pull Request resolved: #197827
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>
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.
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/periodic-rocm-mi200 Trigger "distributed" config CI on ROCm MI200 ciflow/periodic-rocm-mi300 Trigger "distributed" config CI on ROCm MI300/MI325 ciflow/trunk Trigger trunk jobs on your pull request Merged open source topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants