Skip to content

[Testcase Refactoring] Label test_fsdp_freezing_weights ACCELERATOR and switch to device-type instantiation - #192712

Closed
twthighd wants to merge 1 commit into
pytorch:mainfrom
twthighd:test/decouple-test_fsdp_freezing_weights
Closed

twthighd wants to merge 1 commit into
pytorch:mainfrom
twthighd:test/decouple-test_fsdp_freezing_weights

Conversation

@twthighd

@twthighd twthighd commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Label TestFreezingWeights as ACCELERATOR, switch it from @instantiate_parametrized_tests to instantiate_device_type_tests (no except_for), skip the CPU variant explicitly with @onlyAccelerator, and migrate the test call chain from the module-level device_type constant to the injected device parameter using the type-only form for tensor creation and model placement.

Changes

  • test/distributed/fsdp/test_fsdp_freezing_weights.py:
    • Add hw_classification = HardwareClassification.ACCELERATOR and import HardwareClassification.
    • Switch from @instantiate_parametrized_tests to instantiate_device_type_tests(TestFreezingWeights, globals(), allow_xpu=True) so the class is instantiated as a device-type test, generating per-accelerator variants (including PrivateUse1 out-of-tree backends). No except_for: on machines without an accelerator the only generatable variant is CPU, and excluding it would silently drop the class from collection (0 tests collected, exit code 0); with the bare call the CPU variant is collected and skipped explicitly by the existing device-count guards (review feedback).
    • Decorate test_freezing_weights with @onlyAccelerator (variant-level: raises SkipTest when self.device_type is cpu/meta). Without it, on machines with >= 2 accelerators @skip_if_lt_x_gpu(2) (a global device-count check) would let the CPU variant through, and the test would fail deterministically in the DDP branch — DistributedDataParallel with a CPU module and non-empty device_ids=[self.rank] raises ValueError unconditionally.
    • Migrate test_freezing_weights and _dist_train from the module-level device_type = acc.type if (acc := ...) else "cpu" constant to the injected device parameter. Delete the module-level device_type constant.
    • In _dist_train, derive device_type = torch.device(device).type (type-only, index stripped) and use it for batch.to, model.to, and target.to. The pre-existing device_id=self.rank / device_ids=[self.rank] (int rank) are kept unchanged from main.

Motivation

TestFreezingWeights runs FSDP/DDP device-tensor paths guarded by @skip_if_lt_x_gpu(2) and is not CPU-runnable, so ACCELERATOR is the correct classification; the original @instantiate_parametrized_tests did not generate per-device variants, a classification/mechanism mismatch. The bare instantiate_device_type_tests call keeps the class collectable on machines without an accelerator (the CPU variant is reported as skipped rather than the class disappearing from collection), while @onlyAccelerator keeps the CPU variant from actually running on accelerator machines where the global @skip_if_lt_x_gpu(2) check would let it through. The device parameter migration is required because instantiate_device_type_tests generates per-device variants whose cls.device_type differs, and a module-level constant cannot follow. The type-only form (torch.device(device).type) is required for tensor creation and model placement because the injected device is an indexed string (e.g. "cuda:0"); passing it bare forces all ranks onto device 0 and produces numerical mismatches from the FSDP auto-move path, while the type-only form lets each rank use its current device.

Test Plan

python test/distributed/fsdp/test_fsdp_freezing_weights.py
  • Result: Ran 64 tests ... OK (skipped=32) — 32 parametrized combinations x cpu/accelerator variants; the 32 CPU variants are skipped by @onlyAccelerator, the 32 accelerator variants pass.
  • lintrunner reports no lint issues.

Notes

@pytorch-bot

pytorch-bot Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 6f68747 with merge base 199499c (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Aug 10, 2026
@twthighd

Copy link
Copy Markdown
Contributor Author

@twthighd

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "module: tests/distributed"

@pytorch-bot pytorch-bot Bot added the module: tests/distributed This label covers all test cases within the Distributed sheet. label Aug 10, 2026
@fffrog fffrog moved this to Backlog in PyTorch Test Refactoring Aug 10, 2026
@twthighd
twthighd force-pushed the test/decouple-test_fsdp_freezing_weights branch from 21fa133 to c60d3af Compare August 13, 2026 04:25
@twthighd
twthighd force-pushed the test/decouple-test_fsdp_freezing_weights branch from c60d3af to 3f447f3 Compare August 18, 2026 07:37
@twthighd
twthighd marked this pull request as ready for review August 24, 2026 06:15
kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Aug 26, 2026
kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Aug 26, 2026
@liangel-02
liangel-02 requested a review from fffrog August 26, 2026 15:02
@liangel-02 liangel-02 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 26, 2026

@KarhouTam KarhouTam left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks.
cc @fffrog

@twthighd
twthighd force-pushed the test/decouple-test_fsdp_freezing_weights branch from 3f447f3 to d548c82 Compare September 1, 2026 04:36
kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Sep 7, 2026

@KarhouTam KarhouTam left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please resolve the conflict

@twthighd
twthighd force-pushed the test/decouple-test_fsdp_freezing_weights branch from d548c82 to c875b51 Compare October 8, 2026 07:24
@twthighd

twthighd commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Please resolve the conflict

Conflict resolved

@can-gaa-hou can-gaa-hou left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@twthighd

Copy link
Copy Markdown
Contributor Author

Hi @d4l3k, please help to review this PR, thank you!

@twthighd

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorch-bot

pytorch-bot Bot commented Oct 26, 2026

Copy link
Copy Markdown

-i flag is only allowed for users with write permissions

@twthighd

Copy link
Copy Markdown
Contributor Author

@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

@github-project-automation github-project-automation Bot moved this from Ready for Merge to Done in PyTorch Test Refactoring Oct 26, 2026
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
…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
…devices and label ACCELERATOR classes

Summary:
- Add `hw_classification = HardwareClassification.ACCELERATOR` to both
  `TestFSDPCheckpoint` and `TestFSDPCheckpointSubmodule`, and import
  `HardwareClassification`.
- Switch `TestFSDPCheckpoint` from `@instantiate_parametrized_tests` to
  `instantiate_device_type_tests(..., allow_xpu=True)`, and use the same
  form for `TestFSDPCheckpointSubmodule` (its hard-coded device list was
  already removed in the preceding commit).
- Gate all three test methods with the variant-aware `@onlyAccelerator`
  instead of excluding the CPU variant: the CPU variant is now collected and
  skips cleanly on every host (the guard reads the running variant's
  `device_type`, so CPU-only machines report explicit skips instead of the
  classes being invisible), while accelerator variants run unchanged. Same
  gating form as pytorch#192712 (landed) and pytorch#191905.
- Migrate the test methods off the module-level `device_type` string: every
  method takes the injected `device` parameter, and the bodies create
  tensors, move modules, and pass the FSDP `device_id` with the per-variant
  type-only `self.device_type`; `SequentialModule.__init__` receives the
  device. Delete the module-level `device_type = torch.device(get_devtype())`
  and the `get_devtype` import.
- Replace 4 `TestFSDPCheckpoint.SequentialModule(...)` references in class-1
  test bodies with `self.SequentialModule(...)`. `instantiate_device_type_tests`
  removes the original class name from scope (replaces it with per-device
  variants like `TestFSDPCheckpointPRIVATEUSE1`), so a test body referencing the
  original class name raises `NameError` at runtime. The variants inherit from
  the original class, so `self.SequentialModule` resolves the nested class
  correctly. This was latent until the c10d backend-type lookup for PrivateUse1
  was fixed (pytorch#187650 / out-of-tree accelerator issue pytorch#3947), because workers
  previously exited at `dist.barrier(device_ids=)` before reaching this code.

This aligns both classes' mechanism with their ACCELERATOR classification and
removes the hard-coded device whitelist so any accelerator registered via
`torch.accelerator` is admitted. The device-parameter migration ensures each
per-device variant uses its own device rather than a module-level constant,
which is the correct pattern under `instantiate_device_type_tests`.

Rebase note: upstream has since moved both classes onto the
FSDPTestContinuous base; this is kept, and the type-only device idiom in
test bodies is normalized to self.device_type (equivalent to the previous
torch.device(device).type, and unambiguous under type-only injection).

Verified end to end on an 8-card accelerator backend (the verification host
runs an older torch snapshot; its common_distributed.py carries the
previously-applied verification patches - the skip_if_lt_x_gpu device-agnostic
rewrite and the device-backend registry resolution - plus the worker-side
method-level SkipTest pass-through that current main already has):

python test/distributed/fsdp/test_fsdp_checkpoint.py -v
-> 34 cases collected: 17 accelerator-variant cases pass across both
   classes, and 17 CPU-variant cases (the two generated CPU classes) are
   collected and skipped with the exact reason "onlyAccelerator: doesn't
   run on CPU or meta devices"; 0 errors.
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
twthighd added a commit to twthighd/pytorch that referenced this pull request Oct 30, 2026
…label classes

Summary:
- Split the mixed TestFakePG class: the fake-PG mechanism tests
  (copy semantics, requires_grad propagation, validation errors,
  dispatch tracing) stay in TestFakePG labeled GENERIC, while the
  nine accelerator-path tests (FSDP/TP e2e, functional-collectives
  tracing, split_group) move to a new TestFakePGDevice labeled
  ACCELERATOR.
- TestFakePGDevice is instantiated via instantiate_device_type_tests
  with allow_xpu=True, and the moved methods take the injected device
  parameter instead of the module-level device_type = get_devtype().type
  (deleted).
- Gate the nine methods with the variant-aware @onlyAccelerator instead
  of excluding the CPU variant: the CPU variant is collected and skips
  cleanly on every host (the guard reads the running variant's
  device_type), so CPU-only machines report explicit skips instead of
  the class being invisible, while accelerator variants run unchanged.
  Same gating form as the landed pytorch#192712 and pytorch#191905. @skipIfHpu
  blacklist guards are kept.
- Rebase absorption: keep pytorch#202253's six compile-sync methods in the
  GENERIC TestFakePG (14 expanded cases, parametrizations and gloo
  availability guards intact; their config strings naming cuda/nccl do
  not exercise device-tensor paths) and pytorch#202141's whole-file adjustments
  (fake backend moved to a Python PyBackend, new GENERIC
  debug-wrapper/alias/split-options tests, updated assertion patterns);
  the unittest/unittest.mock imports the new tests use are kept.

This allows the accelerator-path tests to run on any out-of-tree
accelerator variant instead of being skipped wherever HAS_ACCELERATOR
is False, while the device-agnostic fake-PG mechanics stay in a
GENERIC class that runs everywhere.

Verified on an old-snapshot verify host (its C++ fake backend predates
the Python PyBackend move):
- The generated CPU class collects 15 cases, all skipped with the exact
  reason "onlyAccelerator: doesn't run on CPU or meta devices" (OK,
  0 errors).
- A whole-file run is not obtainable there: a newly absorbed GENERIC
  test crashes the old C++ fake backend.
- The PrivateUse1 variant fails there at the fake backend's
  device-type lookup (observed error).

Full-file validation on the rebased stack remains pending. GENERIC/CPU
and accelerator coverage will be checked in the corresponding CI jobs
where selected. PrivateUse1 execution additionally requires pytorch#202363 at
the new registration site, with the backend plugin loaded before fake
registration, and a compatible verification environment; ordinary
CPU/CUDA CI does not cover it.
twthighd added a commit to twthighd/pytorch that referenced this pull request Nov 4, 2026
…devices and label ACCELERATOR classes

Summary:
- Add `hw_classification = HardwareClassification.ACCELERATOR` to both
  `TestFSDPCheckpoint` and `TestFSDPCheckpointSubmodule`, and import
  `HardwareClassification`.
- Switch `TestFSDPCheckpoint` from `@instantiate_parametrized_tests` to
  `instantiate_device_type_tests(..., allow_xpu=True)`, and use the same
  form for `TestFSDPCheckpointSubmodule` (its hard-coded device list was
  already removed in the preceding commit).
- Gate all three test methods with the variant-aware `@onlyAccelerator`
  instead of excluding the CPU variant: the CPU variant is now collected and
  skips cleanly on every host (the guard reads the running variant's
  `device_type`, so CPU-only machines report explicit skips instead of the
  classes being invisible), while accelerator variants run unchanged. Same
  gating form as pytorch#192712 (landed) and pytorch#191905.
- Migrate the test methods off the module-level `device_type` string: every
  method takes the injected `device` parameter, and the bodies create
  tensors, move modules, and pass the FSDP `device_id` with the per-variant
  type-only `self.device_type`; `SequentialModule.__init__` receives the
  device. Delete the module-level `device_type = torch.device(get_devtype())`
  and the `get_devtype` import.
- Replace 4 `TestFSDPCheckpoint.SequentialModule(...)` references in class-1
  test bodies with `self.SequentialModule(...)`. `instantiate_device_type_tests`
  removes the original class name from scope (replaces it with per-device
  variants like `TestFSDPCheckpointPRIVATEUSE1`), so a test body referencing the
  original class name raises `NameError` at runtime. The variants inherit from
  the original class, so `self.SequentialModule` resolves the nested class
  correctly. This was latent until the c10d backend-type lookup for PrivateUse1
  was fixed (pytorch#187650 / out-of-tree accelerator issue pytorch#3947), because workers
  previously exited at `dist.barrier(device_ids=)` before reaching this code.

This aligns both classes' mechanism with their ACCELERATOR classification and
removes the hard-coded device whitelist so any accelerator registered via
`torch.accelerator` is admitted. The device-parameter migration ensures each
per-device variant uses its own device rather than a module-level constant,
which is the correct pattern under `instantiate_device_type_tests`.

Rebase note: upstream has since moved both classes onto the
FSDPTestContinuous base; this is kept, and the type-only device idiom in
test bodies is normalized to self.device_type (equivalent to the previous
torch.device(device).type, and unambiguous under type-only injection).

Verified end to end on an 8-card accelerator backend (the verification host
runs an older torch snapshot; its common_distributed.py carries the
previously-applied verification patches - the skip_if_lt_x_gpu device-agnostic
rewrite and the device-backend registry resolution - plus the worker-side
method-level SkipTest pass-through that current main already has):

python test/distributed/fsdp/test_fsdp_checkpoint.py -v
-> 34 cases collected: 17 accelerator-variant cases pass across both
   classes, and 17 CPU-variant cases (the two generated CPU classes) are
   collected and skipped with the exact reason "onlyAccelerator: doesn't
   run on CPU or meta devices"; 0 errors.
twthighd added a commit to twthighd/pytorch that referenced this pull request Nov 4, 2026
…evel @onlyAccelerator

Summary:
- Drop except_for=("cpu",) from instantiate_device_type_tests and gate the
  test method with @onlyAccelerator instead, so the CPU variant is generated
  and collected on every host and gated at the method level.
- The baseline MultiProcContinuousTest worker loop already forwards a
  method-level unittest.SkipTest to the parent as a skip result, so the CPU
  variant skips cleanly on hosts with enough devices instead of surfacing
  as an exception-in-worker failure.

This aligns the file with the default ACCELERATOR gating form (same form as
the landed test_fsdp_freezing_weights.py, pytorch#192712) and makes the CPU-only
collection visible on CPU-only CI runners instead of suppressed.
pytorchmergebot pushed a commit that referenced this pull request Nov 4, 2026
…devices and label ACCELERATOR classes (#191419)

## Summary

This PR labels `TestFSDPCheckpoint` and `TestFSDPCheckpointSubmodule` as `HardwareClassification.ACCELERATOR`, switches both to `instantiate_device_type_tests(..., allow_xpu=True)` with the variant-aware `@onlyAccelerator` gate on every test method, and completes the device-parameter migration in the test bodies. Rebased onto upstream's migration of both classes onto the `FSDPTestContinuous` base (kept); type-only device access in test bodies uses `self.device_type` (canonical idiom, unambiguous under `DeviceTypeTestBase` injection).

## Changes

- **`test/distributed/fsdp/test_fsdp_checkpoint.py`**:
  - Added `hw_classification = HardwareClassification.ACCELERATOR` to both classes, plus the import. Both classes' `test_*` methods require an accelerator (`@skip_if_lt_x_gpu(2)`, `device` param) and exercise FSDP checkpoint behavior on the device-tensor path.
  - Switched `TestFSDPCheckpoint` from `@instantiate_parametrized_tests` to `instantiate_device_type_tests(..., allow_xpu=True)` (deleting the class decorator avoids the double-expansion trap); `TestFSDPCheckpointSubmodule`'s hard-coded `only_for=("cuda","hpu","xpu")` device list was removed in the preceding commit and it now uses the same form. ACCELERATOR classes must not use `only_for` (landed test linter #190173).
  - All three test methods carry the variant-aware `@onlyAccelerator` (stacked above `@skip_if_lt_x_gpu(2)`): the CPU variant is generated and collected everywhere but skips cleanly with the exact reason `onlyAccelerator: doesn't run on CPU or meta devices` (the guard reads the running variant's `device_type`, unlike availability-based guards), so CPU-only machines report explicit skips instead of the classes being invisible, while accelerator variants run unchanged. Same gating form as #192712 (landed) and #191905.
  - Migrated every test method to the injected `device` parameter: added `device` to both class-1 methods and to `SequentialModule.__init__`, deleted the module-level `device_type` constant and the `get_devtype` import.
  - Replaced 4 `TestFSDPCheckpoint.SequentialModule(...)` references with `self.SequentialModule(...)` — `instantiate_device_type_tests` removes the original class name from scope, so module-level references raise `NameError` at runtime (latent until #187650 fixed the backend-type lookup for PrivateUse1 / out-of-tree accelerator issue #3947, because workers previously exited at `dist.barrier(device_ids=)` first).
  - Device access in test bodies uses `self.device_type` (type-only) for FSDP `device_id` (`fsdp_kwargs`), `.to(...)`, `torch.randn(device=...)`, and `SequentialModule(device=...)`; `SequentialModule.__init__` receives the type-only device from its callers and uses it directly. Type-only `device_id` keeps `_get_device_from_device_id` resolving each rank to its own current device (no single-card degeneration).
- **`tools/linter/adapters/test_linter_allowlist.json`**: removed the single `test/distributed/fsdp/test_fsdp_checkpoint.py` entry — this PR migrates that file to the linter's requirements.

## Motivation

Both classes had no `hw_classification` (silently dropped under `--hw-classification ACCELERATOR` filtering) and used `only_for=("cuda","hpu","xpu")`, excluding PrivateUse1-based out-of-tree accelerators. The module-level `device_type` constant does not change across per-device variants, and an indexed `device` passed bare to FSDP `device_id` silently degenerates multi-rank tests to single-card.

## Test Plan

- FSDP infra routes to the real accelerator backend (not a gloo/CPU false pass): `python -c "from torch.testing._internal.common_fsdp import DEVICE_TYPE, DISTRIBUTED_BACKEND, DEVICE_COUNT; print(...)"` resolves to the verify backend's accelerator type, its native comm backend, and 8 on the verify host.
- End-to-end on an 8-card accelerator backend (the verify host runs an older torch snapshot; its `common_distributed.py` carries the previously documented verification patches plus the worker-side method-level SkipTest pass-through that current main already has):

```
python test/distributed/fsdp/test_fsdp_checkpoint.py -v
# 34 cases collected: 17 accelerator-variant cases pass across both classes;
# 17 CPU-variant cases (the two generated CPU classes) are collected and
# skipped with the exact onlyAccelerator reason; 0 errors.
```

- The earlier revision of this PR (CPU variant excluded at instantiation) verified as `Ran 17 tests, OK (0 errors)`; accelerator-variant behavior is unchanged between the two forms.
- `lintrunner` clean; landed test linter: 0 violations.
- With the entry removed, the TEST_LINTER full re-check passes for the migrated file: `python3 tools/linter/adapters/test_linter.py tools/linter/adapters/test_linter_allowlist.json` (the allowlist-as-argument form lintrunner triggers in CI) — rc=0, zero lint messages for `test/distributed/fsdp/test_fsdp_checkpoint.py`.

## Notes

- The method-level `@onlyAccelerator` form (rather than `except_for=("cpu",)`) keeps the CPU variant in collection so CPU-only hosts report explicit skips instead of the classes silently disappearing. This PR's base already translates a worker-side `unittest.SkipTest` into a skip result, and the trade-off — one extra class-level worker/PG lifecycle per generated CPU class on accelerator hosts, with no change in accelerator-variant execution — was accepted for collection visibility. Same form as #192712 (landed) and #191905.
- This is part of the test case refactoring initiative tracked in #185590.

Pull Request resolved: #191419
Approved by: https://github.com/jialinw77, 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 5, 2026
…devices and label ACCELERATOR classes (pytorch#191419)

## Summary

This PR labels `TestFSDPCheckpoint` and `TestFSDPCheckpointSubmodule` as `HardwareClassification.ACCELERATOR`, switches both to `instantiate_device_type_tests(..., allow_xpu=True)` with the variant-aware `@onlyAccelerator` gate on every test method, and completes the device-parameter migration in the test bodies. Rebased onto upstream's migration of both classes onto the `FSDPTestContinuous` base (kept); type-only device access in test bodies uses `self.device_type` (canonical idiom, unambiguous under `DeviceTypeTestBase` injection).

## Changes

- **`test/distributed/fsdp/test_fsdp_checkpoint.py`**:
  - Added `hw_classification = HardwareClassification.ACCELERATOR` to both classes, plus the import. Both classes' `test_*` methods require an accelerator (`@skip_if_lt_x_gpu(2)`, `device` param) and exercise FSDP checkpoint behavior on the device-tensor path.
  - Switched `TestFSDPCheckpoint` from `@instantiate_parametrized_tests` to `instantiate_device_type_tests(..., allow_xpu=True)` (deleting the class decorator avoids the double-expansion trap); `TestFSDPCheckpointSubmodule`'s hard-coded `only_for=("cuda","hpu","xpu")` device list was removed in the preceding commit and it now uses the same form. ACCELERATOR classes must not use `only_for` (landed test linter pytorch#190173).
  - All three test methods carry the variant-aware `@onlyAccelerator` (stacked above `@skip_if_lt_x_gpu(2)`): the CPU variant is generated and collected everywhere but skips cleanly with the exact reason `onlyAccelerator: doesn't run on CPU or meta devices` (the guard reads the running variant's `device_type`, unlike availability-based guards), so CPU-only machines report explicit skips instead of the classes being invisible, while accelerator variants run unchanged. Same gating form as pytorch#192712 (landed) and pytorch#191905.
  - Migrated every test method to the injected `device` parameter: added `device` to both class-1 methods and to `SequentialModule.__init__`, deleted the module-level `device_type` constant and the `get_devtype` import.
  - Replaced 4 `TestFSDPCheckpoint.SequentialModule(...)` references with `self.SequentialModule(...)` — `instantiate_device_type_tests` removes the original class name from scope, so module-level references raise `NameError` at runtime (latent until pytorch#187650 fixed the backend-type lookup for PrivateUse1 / out-of-tree accelerator issue pytorch#3947, because workers previously exited at `dist.barrier(device_ids=)` first).
  - Device access in test bodies uses `self.device_type` (type-only) for FSDP `device_id` (`fsdp_kwargs`), `.to(...)`, `torch.randn(device=...)`, and `SequentialModule(device=...)`; `SequentialModule.__init__` receives the type-only device from its callers and uses it directly. Type-only `device_id` keeps `_get_device_from_device_id` resolving each rank to its own current device (no single-card degeneration).
- **`tools/linter/adapters/test_linter_allowlist.json`**: removed the single `test/distributed/fsdp/test_fsdp_checkpoint.py` entry — this PR migrates that file to the linter's requirements.

## Motivation

Both classes had no `hw_classification` (silently dropped under `--hw-classification ACCELERATOR` filtering) and used `only_for=("cuda","hpu","xpu")`, excluding PrivateUse1-based out-of-tree accelerators. The module-level `device_type` constant does not change across per-device variants, and an indexed `device` passed bare to FSDP `device_id` silently degenerates multi-rank tests to single-card.

## Test Plan

- FSDP infra routes to the real accelerator backend (not a gloo/CPU false pass): `python -c "from torch.testing._internal.common_fsdp import DEVICE_TYPE, DISTRIBUTED_BACKEND, DEVICE_COUNT; print(...)"` resolves to the verify backend's accelerator type, its native comm backend, and 8 on the verify host.
- End-to-end on an 8-card accelerator backend (the verify host runs an older torch snapshot; its `common_distributed.py` carries the previously documented verification patches plus the worker-side method-level SkipTest pass-through that current main already has):

```
python test/distributed/fsdp/test_fsdp_checkpoint.py -v
# 34 cases collected: 17 accelerator-variant cases pass across both classes;
# 17 CPU-variant cases (the two generated CPU classes) are collected and
# skipped with the exact onlyAccelerator reason; 0 errors.
```

- The earlier revision of this PR (CPU variant excluded at instantiation) verified as `Ran 17 tests, OK (0 errors)`; accelerator-variant behavior is unchanged between the two forms.
- `lintrunner` clean; landed test linter: 0 violations.
- With the entry removed, the TEST_LINTER full re-check passes for the migrated file: `python3 tools/linter/adapters/test_linter.py tools/linter/adapters/test_linter_allowlist.json` (the allowlist-as-argument form lintrunner triggers in CI) — rc=0, zero lint messages for `test/distributed/fsdp/test_fsdp_checkpoint.py`.

## Notes

- The method-level `@onlyAccelerator` form (rather than `except_for=("cpu",)`) keeps the CPU variant in collection so CPU-only hosts report explicit skips instead of the classes silently disappearing. This PR's base already translates a worker-side `unittest.SkipTest` into a skip result, and the trade-off — one extra class-level worker/PG lifecycle per generated CPU class on accelerator hosts, with no change in accelerator-variant execution — was accepted for collection visibility. Same form as pytorch#192712 (landed) and pytorch#191905.
- This is part of the test case refactoring initiative tracked in pytorch#185590.

Pull Request resolved: pytorch#191419
Approved by: https://github.com/jialinw77, https://github.com/can-gaa-hou, https://github.com/d4l3k
twthighd added a commit to twthighd/pytorch that referenced this pull request Nov 9, 2026
…evel @onlyAccelerator

Summary:
- Drop except_for=("cpu",) from instantiate_device_type_tests and gate the
  test method with @onlyAccelerator instead, so the CPU variant is generated
  and collected on every host and gated at the method level.
- The baseline MultiProcContinuousTest worker loop already forwards a
  method-level unittest.SkipTest to the parent as a skip result, so the CPU
  variant skips cleanly on hosts with enough devices instead of surfacing
  as an exception-in-worker failure.

This aligns the file with the default ACCELERATOR gating form (same form as
the landed test_fsdp_freezing_weights.py, pytorch#192712) and makes the CPU-only
collection visible on CPU-only CI runners instead of suppressed.
pytorchmergebot pushed a commit that referenced this pull request Nov 9, 2026
…and switch to device-type instantiation (#192945)

## Summary

Label `TestBackwardPrefetch` as `ACCELERATOR`, switch it to `instantiate_device_type_tests` with method-level `@onlyAccelerator` gating, migrate the test from the module-level `device_type` constant to the per-variant `self.device_type` class attribute, and replace an engine-thread `assertEqual` arity check with a direct `raise AssertionError`.

## Changes

- **`test/distributed/fsdp/test_fsdp_backward_prefetch.py`**:
  - Add `hw_classification = HardwareClassification.ACCELERATOR` and import `HardwareClassification`.
  - Add `instantiate_device_type_tests(TestBackwardPrefetch, globals(), allow_xpu=True)` with a method-level `@onlyAccelerator` gate on the test method (previously plain `FSDPTestContinuous` with no instantiation). The CPU variant is generated and collected on every host and skips cleanly at the method level.
  - The `@onlyAccelerator` decorator sits above the retained `@skip_if_lt_x_gpu(2)`: on CPU-only hosts the multi-card guard skips the CPU variant before the fixture starts, and on accelerator hosts the CPU variant initializes the class fixture and then skips with reason `onlyAccelerator: doesn't run on CPU or meta devices`, returned by the workers as a skip result rather than wrapped in an exception.
  - Migrate from the module-level `device_type = torch.device(getdevtype())` to the per-variant class attribute `self.device_type`; delete the module-level constant and the `getdevtype` import. `_test_backward_prefetch` and `_dist_train` keep their original zero-device-arg signatures — the device type flows from the class attribute rather than a parameter chain, so the framework-injected `device` parameter stays on the test method only.
  - FSDP `device_id`, `nn.Transformer(device=...)`, and `torch.randn(device=...)` use the type-only `self.device_type`: passing the bare injected device (an indexed string, e.g. `"cuda:0"`) to FSDP `device_id` forces all ranks onto device 0 and silently degrades the multi-device test into a single-device run, while the type-only form lets FSDP resolve the per-rank current device.
  - The arity check inside `patched_get_handle_to_prefetch` raises `AssertionError` directly instead of calling `self.assertEqual`: the check runs inside the FSDP backward hook on the autograd engine thread, where the per-thread test state (`DeviceTypeTestBase._tls`) is empty, so an `assertEqual` there fails with `AttributeError` on `rel_tol` instead of reporting the intended arity failure. This keeps the change test-file-only; no `common_device_type.py` modification is needed.
- **`tools/linter/adapters/test_linter_allowlist.json`**: removed the single `test/distributed/fsdp/test_fsdp_backward_prefetch.py` entry — this PR migrates that file to the linter's requirements.

## Motivation

`TestBackwardPrefetch` runs FSDP device-tensor paths guarded by `@skip_if_lt_x_gpu(2)` and is not CPU-runnable, so `ACCELERATOR` is the correct classification; the original class had no instantiation — a classification/mechanism mismatch. The `self.device_type` migration is required because `instantiate_device_type_tests` generates per-device variants whose `cls.device_type` differs and a module-level constant cannot follow. The method-level `@onlyAccelerator` gating (rather than `except_for=("cpu",)`) makes the CPU variant visible in CPU-only CI collection instead of suppressed, matching the landed gating form of `test_fsdp_freezing_weights.py` (#192712, same `FSDPTestContinuous` base).

## Test Plan

- Verified end-to-end on an 8-device out-of-tree accelerator backend with per-rank devices (FSDP `device_id` resolves the per-rank current device):

```bash
python test/distributed/fsdp/test_fsdp_backward_prefetch.py
# Ran 2 tests — OK (skipped=1): the accelerator variant executes the full
# backward-prefetch training and passes; the CPU variant skips with reason
# "onlyAccelerator: doesn't run on CPU or meta devices"
```

- On the same accelerator host, running only the CPU variant (`TestBackwardPrefetchCPU`) shows the class fixture initializing the workers and the process group before the method-level skip is returned as a skip result (`Ran 1 test ... OK (skipped=1)`) — the exact path the old `except_for` form avoided by not generating the CPU variant.
- With the accelerator backend disabled (simulating a CPU-only runner), the CPU variant is collected and skips at the multi-card guard before the fixture starts.
- `lintrunner` reports no lint issues.
- With the entry removed, the TEST_LINTER full re-check passes for the migrated file: `python3 tools/linter/adapters/test_linter.py tools/linter/adapters/test_linter_allowlist.json` — rc=0, zero lint messages for `test/distributed/fsdp/test_fsdp_backward_prefetch.py`.

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

Pull Request resolved: #192945
Approved by: https://github.com/jialinw77, 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
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…devices and label ACCELERATOR classes (pytorch#191419)

## Summary

This PR labels `TestFSDPCheckpoint` and `TestFSDPCheckpointSubmodule` as `HardwareClassification.ACCELERATOR`, switches both to `instantiate_device_type_tests(..., allow_xpu=True)` with the variant-aware `@onlyAccelerator` gate on every test method, and completes the device-parameter migration in the test bodies. Rebased onto upstream's migration of both classes onto the `FSDPTestContinuous` base (kept); type-only device access in test bodies uses `self.device_type` (canonical idiom, unambiguous under `DeviceTypeTestBase` injection).

## Changes

- **`test/distributed/fsdp/test_fsdp_checkpoint.py`**:
  - Added `hw_classification = HardwareClassification.ACCELERATOR` to both classes, plus the import. Both classes' `test_*` methods require an accelerator (`@skip_if_lt_x_gpu(2)`, `device` param) and exercise FSDP checkpoint behavior on the device-tensor path.
  - Switched `TestFSDPCheckpoint` from `@instantiate_parametrized_tests` to `instantiate_device_type_tests(..., allow_xpu=True)` (deleting the class decorator avoids the double-expansion trap); `TestFSDPCheckpointSubmodule`'s hard-coded `only_for=("cuda","hpu","xpu")` device list was removed in the preceding commit and it now uses the same form. ACCELERATOR classes must not use `only_for` (landed test linter pytorch#190173).
  - All three test methods carry the variant-aware `@onlyAccelerator` (stacked above `@skip_if_lt_x_gpu(2)`): the CPU variant is generated and collected everywhere but skips cleanly with the exact reason `onlyAccelerator: doesn't run on CPU or meta devices` (the guard reads the running variant's `device_type`, unlike availability-based guards), so CPU-only machines report explicit skips instead of the classes being invisible, while accelerator variants run unchanged. Same gating form as pytorch#192712 (landed) and pytorch#191905.
  - Migrated every test method to the injected `device` parameter: added `device` to both class-1 methods and to `SequentialModule.__init__`, deleted the module-level `device_type` constant and the `get_devtype` import.
  - Replaced 4 `TestFSDPCheckpoint.SequentialModule(...)` references with `self.SequentialModule(...)` — `instantiate_device_type_tests` removes the original class name from scope, so module-level references raise `NameError` at runtime (latent until pytorch#187650 fixed the backend-type lookup for PrivateUse1 / out-of-tree accelerator issue pytorch#3947, because workers previously exited at `dist.barrier(device_ids=)` first).
  - Device access in test bodies uses `self.device_type` (type-only) for FSDP `device_id` (`fsdp_kwargs`), `.to(...)`, `torch.randn(device=...)`, and `SequentialModule(device=...)`; `SequentialModule.__init__` receives the type-only device from its callers and uses it directly. Type-only `device_id` keeps `_get_device_from_device_id` resolving each rank to its own current device (no single-card degeneration).
- **`tools/linter/adapters/test_linter_allowlist.json`**: removed the single `test/distributed/fsdp/test_fsdp_checkpoint.py` entry — this PR migrates that file to the linter's requirements.

## Motivation

Both classes had no `hw_classification` (silently dropped under `--hw-classification ACCELERATOR` filtering) and used `only_for=("cuda","hpu","xpu")`, excluding PrivateUse1-based out-of-tree accelerators. The module-level `device_type` constant does not change across per-device variants, and an indexed `device` passed bare to FSDP `device_id` silently degenerates multi-rank tests to single-card.

## Test Plan

- FSDP infra routes to the real accelerator backend (not a gloo/CPU false pass): `python -c "from torch.testing._internal.common_fsdp import DEVICE_TYPE, DISTRIBUTED_BACKEND, DEVICE_COUNT; print(...)"` resolves to the verify backend's accelerator type, its native comm backend, and 8 on the verify host.
- End-to-end on an 8-card accelerator backend (the verify host runs an older torch snapshot; its `common_distributed.py` carries the previously documented verification patches plus the worker-side method-level SkipTest pass-through that current main already has):

```
python test/distributed/fsdp/test_fsdp_checkpoint.py -v
# 34 cases collected: 17 accelerator-variant cases pass across both classes;
# 17 CPU-variant cases (the two generated CPU classes) are collected and
# skipped with the exact onlyAccelerator reason; 0 errors.
```

- The earlier revision of this PR (CPU variant excluded at instantiation) verified as `Ran 17 tests, OK (0 errors)`; accelerator-variant behavior is unchanged between the two forms.
- `lintrunner` clean; landed test linter: 0 violations.
- With the entry removed, the TEST_LINTER full re-check passes for the migrated file: `python3 tools/linter/adapters/test_linter.py tools/linter/adapters/test_linter_allowlist.json` (the allowlist-as-argument form lintrunner triggers in CI) — rc=0, zero lint messages for `test/distributed/fsdp/test_fsdp_checkpoint.py`.

## Notes

- The method-level `@onlyAccelerator` form (rather than `except_for=("cpu",)`) keeps the CPU variant in collection so CPU-only hosts report explicit skips instead of the classes silently disappearing. This PR's base already translates a worker-side `unittest.SkipTest` into a skip result, and the trade-off — one extra class-level worker/PG lifecycle per generated CPU class on accelerator hosts, with no change in accelerator-variant execution — was accepted for collection visibility. Same form as pytorch#192712 (landed) and pytorch#191905.
- This is part of the test case refactoring initiative tracked in pytorch#185590.

Pull Request resolved: pytorch#191419
Approved by: https://github.com/jialinw77, 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
…and switch to device-type instantiation (pytorch#192945)

## Summary

Label `TestBackwardPrefetch` as `ACCELERATOR`, switch it to `instantiate_device_type_tests` with method-level `@onlyAccelerator` gating, migrate the test from the module-level `device_type` constant to the per-variant `self.device_type` class attribute, and replace an engine-thread `assertEqual` arity check with a direct `raise AssertionError`.

## Changes

- **`test/distributed/fsdp/test_fsdp_backward_prefetch.py`**:
  - Add `hw_classification = HardwareClassification.ACCELERATOR` and import `HardwareClassification`.
  - Add `instantiate_device_type_tests(TestBackwardPrefetch, globals(), allow_xpu=True)` with a method-level `@onlyAccelerator` gate on the test method (previously plain `FSDPTestContinuous` with no instantiation). The CPU variant is generated and collected on every host and skips cleanly at the method level.
  - The `@onlyAccelerator` decorator sits above the retained `@skip_if_lt_x_gpu(2)`: on CPU-only hosts the multi-card guard skips the CPU variant before the fixture starts, and on accelerator hosts the CPU variant initializes the class fixture and then skips with reason `onlyAccelerator: doesn't run on CPU or meta devices`, returned by the workers as a skip result rather than wrapped in an exception.
  - Migrate from the module-level `device_type = torch.device(getdevtype())` to the per-variant class attribute `self.device_type`; delete the module-level constant and the `getdevtype` import. `_test_backward_prefetch` and `_dist_train` keep their original zero-device-arg signatures — the device type flows from the class attribute rather than a parameter chain, so the framework-injected `device` parameter stays on the test method only.
  - FSDP `device_id`, `nn.Transformer(device=...)`, and `torch.randn(device=...)` use the type-only `self.device_type`: passing the bare injected device (an indexed string, e.g. `"cuda:0"`) to FSDP `device_id` forces all ranks onto device 0 and silently degrades the multi-device test into a single-device run, while the type-only form lets FSDP resolve the per-rank current device.
  - The arity check inside `patched_get_handle_to_prefetch` raises `AssertionError` directly instead of calling `self.assertEqual`: the check runs inside the FSDP backward hook on the autograd engine thread, where the per-thread test state (`DeviceTypeTestBase._tls`) is empty, so an `assertEqual` there fails with `AttributeError` on `rel_tol` instead of reporting the intended arity failure. This keeps the change test-file-only; no `common_device_type.py` modification is needed.
- **`tools/linter/adapters/test_linter_allowlist.json`**: removed the single `test/distributed/fsdp/test_fsdp_backward_prefetch.py` entry — this PR migrates that file to the linter's requirements.

## Motivation

`TestBackwardPrefetch` runs FSDP device-tensor paths guarded by `@skip_if_lt_x_gpu(2)` and is not CPU-runnable, so `ACCELERATOR` is the correct classification; the original class had no instantiation — a classification/mechanism mismatch. The `self.device_type` migration is required because `instantiate_device_type_tests` generates per-device variants whose `cls.device_type` differs and a module-level constant cannot follow. The method-level `@onlyAccelerator` gating (rather than `except_for=("cpu",)`) makes the CPU variant visible in CPU-only CI collection instead of suppressed, matching the landed gating form of `test_fsdp_freezing_weights.py` (pytorch#192712, same `FSDPTestContinuous` base).

## Test Plan

- Verified end-to-end on an 8-device out-of-tree accelerator backend with per-rank devices (FSDP `device_id` resolves the per-rank current device):

```bash
python test/distributed/fsdp/test_fsdp_backward_prefetch.py
# Ran 2 tests — OK (skipped=1): the accelerator variant executes the full
# backward-prefetch training and passes; the CPU variant skips with reason
# "onlyAccelerator: doesn't run on CPU or meta devices"
```

- On the same accelerator host, running only the CPU variant (`TestBackwardPrefetchCPU`) shows the class fixture initializing the workers and the process group before the method-level skip is returned as a skip result (`Ran 1 test ... OK (skipped=1)`) — the exact path the old `except_for` form avoided by not generating the CPU variant.
- With the accelerator backend disabled (simulating a CPU-only runner), the CPU variant is collected and skips at the multi-card guard before the fixture starts.
- `lintrunner` reports no lint issues.
- With the entry removed, the TEST_LINTER full re-check passes for the migrated file: `python3 tools/linter/adapters/test_linter.py tools/linter/adapters/test_linter_allowlist.json` — rc=0, zero lint messages for `test/distributed/fsdp/test_fsdp_backward_prefetch.py`.

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

Pull Request resolved: pytorch#192945
Approved by: https://github.com/jialinw77, https://github.com/can-gaa-hou, https://github.com/d4l3k
twthighd added a commit to twthighd/pytorch that referenced this pull request Nov 23, 2026
…label classes

Summary:
- Split the mixed TestFakePG class: the fake-PG mechanism tests
  (copy semantics, requires_grad propagation, validation errors,
  dispatch tracing) stay in TestFakePG labeled GENERIC, while the
  nine accelerator-path tests (FSDP/TP e2e, functional-collectives
  tracing, split_group) move to a new TestFakePGDevice labeled
  ACCELERATOR.
- TestFakePGDevice is instantiated via instantiate_device_type_tests
  with allow_xpu=True, and the moved methods take the injected device
  parameter instead of the module-level device_type = get_devtype().type
  (deleted).
- Gate the nine methods with the variant-aware @onlyAccelerator instead
  of excluding the CPU variant: the CPU variant is collected and skips
  cleanly on every host (the guard reads the running variant's
  device_type), so CPU-only machines report explicit skips instead of
  the class being invisible, while accelerator variants run unchanged.
  Same gating form as the landed pytorch#192712 and pytorch#191905. @skipIfHpu
  blacklist guards are kept.
- Rebase absorption: keep pytorch#202253's six compile-sync methods in the
  GENERIC TestFakePG (14 expanded cases, parametrizations and gloo
  availability guards intact; their config strings naming cuda/nccl do
  not exercise device-tensor paths) and pytorch#202141's whole-file adjustments
  (fake backend moved to a Python PyBackend, new GENERIC
  debug-wrapper/alias/split-options tests, updated assertion patterns);
  the unittest/unittest.mock imports the new tests use are kept.

This allows the accelerator-path tests to run on any out-of-tree
accelerator variant instead of being skipped wherever HAS_ACCELERATOR
is False, while the device-agnostic fake-PG mechanics stay in a
GENERIC class that runs everywhere.

Verified on an old-snapshot verify host (its C++ fake backend predates
the Python PyBackend move):
- The generated CPU class collects 15 cases, all skipped with the exact
  reason "onlyAccelerator: doesn't run on CPU or meta devices" (OK,
  0 errors).
- A whole-file run is not obtainable there: a newly absorbed GENERIC
  test crashes the old C++ fake backend.
- The PrivateUse1 variant fails there at the fake backend's
  device-type lookup (observed error).

Full-file validation on the rebased stack remains pending. GENERIC/CPU
and accelerator coverage will be checked in the corresponding CI jobs
where selected. PrivateUse1 execution additionally requires pytorch#202363 at
the new registration site, with the backend plugin loaded before fake
registration, and a compatible verification environment; ordinary
CPU/CUDA CI does not cover it.
twthighd added a commit to twthighd/pytorch that referenced this pull request Dec 3, 2026
…label classes

Summary:
- Split the mixed TestFakePG class: the fake-PG mechanism tests
  (copy semantics, requires_grad propagation, validation errors,
  dispatch tracing) stay in TestFakePG labeled GENERIC, while the
  nine accelerator-path tests (FSDP/TP e2e, functional-collectives
  tracing, split_group) move to a new TestFakePGDevice labeled
  ACCELERATOR.
- TestFakePGDevice is instantiated via instantiate_device_type_tests
  with allow_xpu=True, and the moved methods take the injected device
  parameter instead of the module-level device_type = get_devtype().type
  (deleted).
- Gate the nine methods with the variant-aware @onlyAccelerator instead
  of excluding the CPU variant: the CPU variant is collected and skips
  cleanly on every host (the guard reads the running variant's
  device_type), so CPU-only machines report explicit skips instead of
  the class being invisible, while accelerator variants run unchanged.
  Same gating form as the landed pytorch#192712 and pytorch#191905. @skipIfHpu
  blacklist guards are kept.
- Rebase absorption: keep pytorch#202253's six compile-sync methods in the
  GENERIC TestFakePG (14 expanded cases, parametrizations and gloo
  availability guards intact; their config strings naming cuda/nccl do
  not exercise device-tensor paths) and pytorch#202141's whole-file adjustments
  (fake backend moved to a Python PyBackend, new GENERIC
  debug-wrapper/alias/split-options tests, updated assertion patterns);
  the unittest/unittest.mock imports the new tests use are kept.

This allows the accelerator-path tests to run on any out-of-tree
accelerator variant instead of being skipped wherever HAS_ACCELERATOR
is False, while the device-agnostic fake-PG mechanics stay in a
GENERIC class that runs everywhere.

Verified on an old-snapshot verify host (its C++ fake backend predates
the Python PyBackend move):
- The generated CPU class collects 15 cases, all skipped with the exact
  reason "onlyAccelerator: doesn't run on CPU or meta devices" (OK,
  0 errors).
- A whole-file run is not obtainable there: a newly absorbed GENERIC
  test crashes the old C++ fake backend.
- The PrivateUse1 variant fails there at the fake backend's
  device-type lookup (observed error).

Full-file validation on the rebased stack remains pending. GENERIC/CPU
and accelerator coverage will be checked in the corresponding CI jobs
where selected. PrivateUse1 execution additionally requires pytorch#202363 at
the new registration site, with the backend plugin loaded before fake
registration, and a compatible verification environment; ordinary
CPU/CUDA CI does not cover it.
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: tests/distributed This label covers all test cases within the Distributed sheet. module: tests/simple This label covers all the testcase that are very straightforward open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

9 participants