Skip to content

[Testcase Refactoring] Make FSDP tests device-agnostic for out-of-tree backends - #187650

Closed
lixing-he wants to merge 9 commits into
pytorch:mainfrom
lixing-he:test/add-skip-if-lt-x-devices
Closed

lixing-he wants to merge 9 commits into
pytorch:mainfrom
lixing-he:test/add-skip-if-lt-x-devices

Conversation

@lixing-he

@lixing-he lixing-he commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Makes the FSDP test infrastructure in common_fsdp.py device-agnostic so it works
for any accelerator supported by torch.accelerator (CUDA, XPU, HPU, and
PrivateUse1-based out-of-tree backends such as NPU).

  • DEVICE_TYPE / DISTRIBUTED_BACKEND / DEVICE_COUNT are now derived from
    torch.accelerator.current_accelerator() instead of being hard-coded per
    TEST_CUDA / TEST_HPU / TEST_XPU, using the backend registered in
    Backend.default_device_backend_map for the accelerator type.
  • The three set_device_index calls (FSDPTestMixin / FSDPTest /
    FSDPTestContinuous) now gate on torch.accelerator.is_available() instead of
    TEST_CUDA or TEST_XPU, so HPU is treated like any other accelerator.

Test Plan

  • Verified on CPU and across multiple accelerator types:
    • python test/distributed/_composable/fsdp/test_fully_shard_autograd.py
    • python test/distributed/_composable/fsdp/test_fully_shard_clip_grad_norm_.py
    • python test/distributed/_composable/fsdp/test_fully_shard_comm.py
    • python test/distributed/_composable/fsdp/test_fully_shard_compile.py
    • python test/distributed/_composable/fsdp/test_fully_shard_dtensor.py
    • python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
    • python test/distributed/_composable/fsdp/test_fully_shard_frozen.py
    • python test/distributed/_composable/fsdp/test_fully_shard_grad_scaler.py
    • python test/distributed/_composable/fsdp/test_fully_shard_ignore_params.py
    • python test/distributed/_composable/fsdp/test_fully_shard_init.py
    • python test/distributed/_composable/fsdp/test_fully_shard_logging.py
    • python test/distributed/_composable/fsdp/test_fully_shard_memory.py
    • python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
    • python test/distributed/_composable/fsdp/test_fully_shard_overlap.py
    • python test/distributed/_composable/fsdp/test_fully_shard_state.py
    • python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py
    • python test/distributed/_composable/fsdp/test_fully_shard_training.py

@pytorch-bot

pytorch-bot Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure

As of commit b3468b1 with merge base 6b1f3af (image):

NEW FAILURE - The following job has failed:

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

@pytorch-bot pytorch-bot Bot added the release notes: distributed (fsdp) release notes category label Jun 18, 2026
@linux-foundation-easycla

linux-foundation-easycla Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

@lixing-he
lixing-he force-pushed the test/add-skip-if-lt-x-devices branch from 628b95d to 8f79852 Compare July 2, 2026 02:03
PlatformLC added a commit to PlatformLC/pytorch that referenced this pull request Jul 15, 2026
The 4 multi-process tests in `ComposabilityTest` were skipped on
out-of-tree PrivateUse1 accelerators: `@skip_if_lt_x_gpu(8)` and
`at_least_x_gpu(8)` only check cuda/hpu/xpu, not PrivateUse1.

Replace `@skip_if_lt_x_gpu(8)` with `@skip_if_lt_x_devices(8)` (the
device-agnostic decorator from pytorch#187650), and
`not at_least_x_gpu(8)` with `not at_least_x_device(8)` (the device-agnostic
helper from the separate `at_least_x_device` framework PR), and "GPUs" ->
"accelerators" in the skip message. Pattern B
(`requires_accelerator_dist_backend()`, already no-args) and the
`torch.accelerator.set_device_index` init_pg are unchanged.

Depends on pytorch#187650 (`skip_if_lt_x_devices`) and the
`at_least_x_device` framework helper (separate PR); rebase onto main
after they merge.

Test Plan:
```
python test/distributed/_composable/test_composability/test_pp_composability.py -v
```
Verified on a PrivateUse1 host (8 devices, world_size 8): the tests now
run (previously skipped by `skip_if_lt_x_gpu`); each test passes in
isolation.
PlatformLC added a commit to PlatformLC/pytorch that referenced this pull request Jul 15, 2026
The 4 multi-process tests in `ComposabilityTest` were skipped on
out-of-tree PrivateUse1 accelerators: `@skip_if_lt_x_gpu(8)` and
`at_least_x_gpu(8)` only check cuda/hpu/xpu, not PrivateUse1.

- Add `at_least_x_device(x)` to `common_distributed.py` (device-agnostic
  replacement for `at_least_x_gpu`, using `torch.accelerator.device_count()`)
  and use `not at_least_x_device(8)` in the `@skip_but_pass_in_sandcastle_if`
  guard.
- Replace `@skip_if_lt_x_gpu(8)` with `@skip_if_lt_x_devices(8)` (the
  device-agnostic decorator from pytorch#187650), and "GPUs" ->
  "accelerators" in the skip message.
- Pattern B (`requires_accelerator_dist_backend()`, already no-args) and the
  `torch.accelerator.set_device_index` init_pg are unchanged.

Depends on pytorch#187650 (`skip_if_lt_x_devices`); rebase onto main
after it merges.

Test Plan:
```
python test/distributed/_composable/test_composability/test_pp_composability.py -v
```
Verified on a PrivateUse1 host (8 devices, world_size 8): the tests now
run (previously skipped by `skip_if_lt_x_gpu`); each test passes in
isolation.
@lixing-he lixing-he changed the title [Pytorch Test] Add skip_if_lt_x_devices and migrate FSDP autograd tests to be device-agnostic [Test] Make skip_if_lt_x_gpu hardware-agnostic and FSDP tests device-agnostic for out-of-tree backends Jul 16, 2026
PlatformLC added a commit to PlatformLC/pytorch that referenced this pull request Jul 16, 2026
- Change @requires_accelerator_dist_backend() to
  @requires_accelerator_dist_backend(ACCELERATOR_DIST_BACKENDS + ["privateuse1"])
  on all 4 tests. Originally used () (no-args, default list), now references
  ACCELERATOR_DIST_BACKENDS constant and appends "privateuse1" locally.
- Replace @skip_if_lt_x_gpu(8) with @skip_if_lt_x_devices(8) (from pytorch#187650).
- Replace at_least_x_gpu(8) with at_least_x_device(8) and "GPUs" -> "accelerators".
Depends on the framework change in the preceding commit (from pytorch#190153).

Test Plan:
```
python test/distributed/_composable/test_composability/test_pp_composability.py -v
```
Verified on a PrivateUse1 host (8 devices): test_pp_and_dcp passes.
On a CPU-only host all tests are skipped.
PlatformLC added a commit to PlatformLC/pytorch that referenced this pull request Jul 16, 2026
- Change `@requires_accelerator_dist_backend()` to
  `@requires_accelerator_dist_backend(ACCELERATOR_DIST_BACKENDS + ["privateuse1"])`
  on all 4 tests. The list was originally `()` (no-args, default), so it
  now references the `ACCELERATOR_DIST_BACKENDS` constant and appends
  `"privateuse1"` locally — the framework constant itself is unchanged.
- Replace `@skip_if_lt_x_gpu(8)` with `@skip_if_lt_x_devices(8)` (from pytorch#187650).
- Replace `at_least_x_gpu(8)` with `at_least_x_device(8)` (added to
  `common_distributed.py` in this commit) and the skip message
  `"8+ GPUs"` -> `"8+ accelerators"`.

Depends on the framework change in the preceding commit (from pytorch#190153).

Test Plan:
```
python test/distributed/_composable/test_composability/test_pp_composability.py -v
```
Verified on a PrivateUse1 host (8 devices): test_pp_and_dcp passes.
On a CPU-only host all tests are skipped.
@lixing-he
lixing-he marked this pull request as ready for review July 17, 2026 03:56
@janeyx99
janeyx99 requested review from fffrog and weifengpy July 17, 2026 22:05
@lixing-he

Copy link
Copy Markdown
Contributor Author

Hi @weifengpy, could you take a look at this PR and approve it if it looks
good to you? It refactors away the previously hard-coded cuda/hpu/xpu logic
in the FSDP test infra. fffrog has already reviewed and approved it, and CI
is green. Thanks!

@can-gaa-hou

Copy link
Copy Markdown
Collaborator

@claude review this pr with pr review skill

@claude

claude Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Claude finished @can-gaa-hou's task in 24m 40s —— View job


PyTorch PR review complete — the hpu:0 -> hpu change in DEVICE_TYPE breaks the HPU DDP reference path in the same file, and get_default_backend_for_device will raise at import time for accelerators whose backend is not in Backend.default_device_backend_map (HPU, PrivateUse1 before plugin import).

Full review

PR Review: #187650

Summary

Replaces the hard-coded TEST_CUDA/TEST_HPU/TEST_XPU cascade in common_fsdp.py with torch.accelerator-derived DEVICE_TYPE/DISTRIBUTED_BACKEND/DEVICE_COUNT. Two blocking correctness problems: HPU's DEVICE_TYPE silently loses its device index and breaks the DDP reference path a few hundred lines below, and get_default_backend_for_device raises at import time for any accelerator missing from Backend.default_device_backend_map.

Backward Compatibility

  • torch/testing/_internal/common_fsdp.py:79 — HPU DEVICE_TYPE drops the index and breaks _test_fsdp_parity. acc.type is "hpu", whereas the old code set "hpu:0". That value is still consumed at common_fsdp.py:1403-1406:

    if TEST_HPU:
        ref_model = DDP(model, device_ids=[DEVICE_TYPE], output_device=DEVICE_TYPE)

    In DDP.__init__ (torch/nn/parallel/distributed.py:950) this becomes [_get_device_index("hpu", True)]. _get_device_index (torch/_utils.py:898-922) sees torch.device("hpu").index is None, falls through to _get_current_device_index(), which routes to _get_available_device_type() (torch/_utils.py:819-833) — that function checks cuda / mps / xpu / mtia / privateuse1 and has no hpu branch, so it returns None. Result: self.device_ids == [None], and at torch/nn/parallel/distributed.py:1474-1477 that list is handed to Logger::set_construction_data_and_log, whose binding takes const std::vector<int>& (torch/csrc/distributed/c10d/logger.cpp:170-176) — pybind11 raises TypeError on the None element. With the old "hpu:0", _get_device_index returned 0 and this path worked.

    Since the whole point of the change is to stop special-casing HPU, the right fix is to also drop the TEST_HPU branch at 1403-1406 so HPU takes the DDP(model, device_ids=[rank], output_device=rank) path like every other accelerator. That also removes the last TEST_HPU use in the file. Fix this →

  • torch/testing/_internal/common_fsdp.py:77-83 — MPS builds change branch. MPS is in the compile-time accelerator list (aten/src/ATen/DeviceAccelerator.cpp:47), so on an Apple Silicon build with USE_DISTRIBUTED=1 this now yields DEVICE_TYPE="mps", DISTRIBUTED_BACKEND="gloo" (from distributed_c10d.py:513), DEVICE_COUNT=1, where previously it fell through to "cpu"/"gloo"/1. Gloo's declared capability is ["cpu", "cuda"] (distributed_c10d.py:517), so tests would move models onto MPS and then collective on a backend that does not support MPS tensors. Lower confidence, since USE_DISTRIBUTED defaults off on macOS and common_fsdp imports torch.distributed._composable unconditionally — but if MPS is not an intended target here, the branch should exclude it explicitly rather than by accident.

Infrastructure

  • torch/testing/_internal/common_fsdp.py:82 — get_default_backend_for_device turns a missing backend into an import-time crash. It raises ValueError: Default backend not registered for device : ... (torch/distributed/distributed_c10d.py:2213-2215) when acc.type is absent from Backend.default_device_backend_map, which ships with only cpu/cuda/xpu/mps (distributed_c10d.py:509-514). hpu is not there — it only appears in backend_capability[FAKE] (line 522), which is a capability list, not the default map. The entry-point loader Backend._ensure_backend_registered is only reached from init_process_group/new_group paths (lines 996, 1047, 1098, 1102, 2007, 2992, 6836) and is not called by get_default_backend_for_device, so nothing populates the map before this module-level statement runs. On an HPU host, importing common_fsdp therefore fails outright — a collection error for every FSDP test file rather than a skip.

    The same fragility applies to the PrivateUse1/NPU case this PR is aimed at: it works only if import torch_npu (which calls Backend.register_backend(..., devices=["npu"]), distributed_c10d.py:642-648) happens before common_fsdp is imported. That import-order dependency is invisible at the call site and deserves either a try/except ValueError fallback that leaves DISTRIBUTED_BACKEND unset-but-importable, or an explicit comment stating the ordering requirement.

  • torch/testing/_internal/common_fsdp.py:80-81 — the comment misstates the failure mode. "If no backend is registered, the accelerator's companion plugin is missing or broken" is wrong for HPU (no in-tree registration exists at all) and misleading for PrivateUse1 (the plugin may be perfectly fine but simply imported after this module). Reword to state the actual contract: the accelerator's backend must be registered in Backend.default_device_backend_map before this module is imported.

Testing

  • No test accompanies the two behavior changes that CI cannot reach. Upstream CI covers CUDA and ROCm, where acc.type == "cuda" and the old and new code agree — so the entire delta of this PR (HPU losing its index, HPU's DEVICE_COUNT moving from a hard-coded 4 to torch.accelerator.device_count(), the ValueError path, MPS) is unexercised. The PR body lists 17 FSDP test files as "verified across multiple accelerator types" but does not say which accelerators, and the HPU DDP break above indicates HPU was not among them. At minimum, state concretely which accelerators the listed commands were run on. A cheap unit-level guard would be a test asserting DEVICE_TYPE has no : and that torch.device(DEVICE_TYPE).index is None, which would have caught the HPU regression on any backend.

Code Quality

  • torch/testing/_internal/common_fsdp.py:72-75 — this block is now entirely dead and should be deleted. Both arms of the new if/else assign DEVICE_COUNT, so neither min(4, max(2, torch.cuda.device_count())) nor the = 4 default can survive. Before this PR the block was live for HPU (the elif TEST_HPU arm did not set DEVICE_COUNT); it no longer is. Note this also silently changes HPU's world_size from a fixed 4 to the runtime device count, which is a behavior change worth calling out in the PR description rather than leaving as a side effect of dead-code retention. Removing the block also makes the TEST_WITH_ROCM import at line 66 unused. Fix this →

  • torch/testing/_internal/common_fsdp.py:78 — acc leaks as a module-level global. torch.testing._internal.common_fsdp.acc is now importable and shadows nothing meaningful. The established idiom in this exact directory is the walrus form, e.g. common_distributed.py:1734 and common_utils.py:1745. Prefer if (acc := torch.accelerator.current_accelerator()) is not None: as the guard, which also drops the redundant is_available()-then-current_accelerator() double call and makes the non-None-ness of acc locally provable (relevant because torch/testing/_internal is excluded from mypy per mypy.ini:49, so acc.type on an Optional[torch.device] is not type-checked here).

Recommendation

Request Changes

The HPU DDP(device_ids=[DEVICE_TYPE]) breakage and the import-time ValueError are both hard failures on HPU hosts, and neither is covered by any test. The dead TEST_WITH_ROCM block and the acc global are small but should be cleaned up in the same pass. The overall direction — deriving these constants from torch.accelerator — is right; the remaining work is finishing the HPU de-special-casing rather than half-removing it.

| Branch: `test/add-skip-if-lt-x-devices`

@lixing-he

Copy link
Copy Markdown
Contributor Author

@can-gaa-hou Thanks for running the review! Regarding the HPU point:

The hpu:0 → hpu change of DEVICE_TYPE here is intentional and was already discussed with @fffrog during the earlier review rounds. fffrog explicitly asked us to stop special-casing HPU and to treat it like other standard accelerators (see comment):

I knew, but I still think we should Regard hpu as an accelerator that will follow the thing other standard accelerator will do.

He then suggested the current form (DEVICE_TYPE = acc.type) in a follow-up comment and approved the PR with it in place. So we'd prefer to keep DEVICE_TYPE = acc.type (no device index, consistent with cuda/xpu) rather than reintroducing the hpu:0 special case.

@fffrog fffrog 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.

SGTM

Comment thread torch/testing/_internal/common_fsdp.py Outdated
Comment on lines 1404 to 1406

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 append index here

Comment thread torch/testing/_internal/common_fsdp.py Outdated
DEVICE_COUNT = torch.xpu.device_count()
if torch.accelerator.is_available():
acc = torch.accelerator.current_accelerator()
DEVICE_TYPE = acc.type

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.

We should add special logic for MPS here to keep BC

@lixing-he

Copy link
Copy Markdown
Contributor Author

@fffrog Fixed per Claude's review comments — removed the TEST_WITH_ROCM special case, added the MPS fallback, and fixed the HPU DDP device_ids. Tests passed. Please re-review. Thanks!

@KarhouTam

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 0 checks:

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / linux-jammy-cuda13.0-py3.10-gcc11 / test (default, 13, 14, mt-l-x86aavx2-29-113-l4)

Details for Dev Infra team Raised by workflow job

@KarhouTam

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: trunk / linux-jammy-cuda13.0-py3.10-gcc11 / test (default, 13, 14, mt-l-x86aavx2-29-113-l4)

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

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. open source release notes: distributed (fsdp) release notes 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.