Repository navigation
Conversation
🔗 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 FailuresAs of commit 6f68747 with merge base 199499c ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
Contributor
Author
Contributor
Author
|
@pytorchbot label "module: tests/distributed" |
twthighd
force-pushed
the
test/decouple-test_fsdp_freezing_weights
branch
from
August 13, 2026 04:25
21fa133 to
c60d3af
Compare
twthighd
force-pushed
the
test/decouple-test_fsdp_freezing_weights
branch
from
August 18, 2026 07:37
c60d3af to
3f447f3
Compare
twthighd
marked this pull request as ready for review
August 24, 2026 06:15
jialinw77
approved these changes
Aug 25, 2026
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
5 tasks done
KarhouTam
approved these changes
Aug 29, 2026
fffrog
requested changes
Aug 29, 2026
twthighd
force-pushed
the
test/decouple-test_fsdp_freezing_weights
branch
from
September 1, 2026 04:36
3f447f3 to
d548c82
Compare
kerer-ai
pushed a commit
to kerer-ai/pytorch-nv
that referenced
this pull request
Sep 7, 2026
KarhouTam
reviewed
Oct 8, 2026
KarhouTam
left a comment
Collaborator
There was a problem hiding this comment.
Please resolve the conflict
twthighd
force-pushed
the
test/decouple-test_fsdp_freezing_weights
branch
from
October 8, 2026 07:24
d548c82 to
c875b51
Compare
Contributor
Author
Conflict resolved |
Contributor
Author
|
Hi @d4l3k, please help to review this PR, thank you! |
Contributor
Author
|
@pytorchbot merge -i |
|
|
Contributor
Author
|
@pytorchbot merge |
Collaborator
Merge startedYour 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 |
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Label
TestFreezingWeightsasACCELERATOR, switch it from@instantiate_parametrized_teststoinstantiate_device_type_tests(noexcept_for), skip the CPU variant explicitly with@onlyAccelerator, and migrate the test call chain from the module-leveldevice_typeconstant to the injecteddeviceparameter using the type-only form for tensor creation and model placement.Changes
test/distributed/fsdp/test_fsdp_freezing_weights.py:hw_classification = HardwareClassification.ACCELERATORand importHardwareClassification.@instantiate_parametrized_teststoinstantiate_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). Noexcept_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).test_freezing_weightswith@onlyAccelerator(variant-level: raisesSkipTestwhenself.device_typeis 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 —DistributedDataParallelwith a CPU module and non-emptydevice_ids=[self.rank]raisesValueErrorunconditionally.test_freezing_weightsand_dist_trainfrom the module-leveldevice_type = acc.type if (acc := ...) else "cpu"constant to the injecteddeviceparameter. Delete the module-leveldevice_typeconstant._dist_train, derivedevice_type = torch.device(device).type(type-only, index stripped) and use it forbatch.to,model.to, andtarget.to. The pre-existingdevice_id=self.rank/device_ids=[self.rank](int rank) are kept unchanged from main.Motivation
TestFreezingWeightsruns FSDP/DDP device-tensor paths guarded by@skip_if_lt_x_gpu(2)and is not CPU-runnable, soACCELERATORis the correct classification; the original@instantiate_parametrized_testsdid not generate per-device variants, a classification/mechanism mismatch. The bareinstantiate_device_type_testscall keeps the class collectable on machines without an accelerator (the CPU variant is reported as skipped rather than the class disappearing from collection), while@onlyAcceleratorkeeps the CPU variant from actually running on accelerator machines where the global@skip_if_lt_x_gpu(2)check would let it through. Thedeviceparameter migration is required becauseinstantiate_device_type_testsgenerates per-device variants whosecls.device_typediffers, 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 injecteddeviceis 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
common_fsdp.pyaccelerator branch from [Testcase Refactoring] Make FSDP tests device-agnostic for out-of-tree backends #187650 applied):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.lintrunnerreports no lint issues.Notes
skip_if_lt_x_gpudevice decoupling (letting that helper recognize out-of-tree accelerators) is tracked by [Testcase Refactoring] Make FSDP tests device-agnostic for out-of-tree backends #187650 — an independent framework-level change tocommon_distributed.py, orthogonal to this PR. This PR keeps@skip_if_lt_x_gpu(2)unchanged.FSDPTestbase class to truly run on an out-of-tree accelerator (rather than falling back to a CPU/gloo path), thecommon_fsdp.pydevice/backend selection also needs the accelerator branch that [Testcase Refactoring] Make FSDP tests device-agnostic for out-of-tree backends #187650 adds. That is a framework-level change tracked by [Testcase Refactoring] Make FSDP tests device-agnostic for out-of-tree backends #187650, separate from this PR.