Skip to content

[Testcase Refactoring] Let out-of-tree PrivateUse1 backends register their own capabilities - #192043

Closed
shichuanliujie9527 wants to merge 1 commit into
pytorch:mainfrom
shichuanliujie9527:test/privateuse1-capability-registry
Closed

shichuanliujie9527 wants to merge 1 commit into
pytorch:mainfrom
shichuanliujie9527:test/privateuse1-capability-registry

Conversation

@shichuanliujie9527

@shichuanliujie9527 shichuanliujie9527 commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A small registry so out-of-tree PrivateUse1 backends
can each declare their own supported capabilities without editing
PrivateUse1TestBase._capabilities() directly.

Motivation

PrivateUse1TestBase is shared by every out-of-tree backend. If each backend
team overrides _capabilities() on this single class directly, every team's PR
touches the exact same method body, and independent PRs from different backend
teams will routinely conflict with each other on merge. This is a base-class
file, and different backends should be able to contribute independently.

register_privateuse1_capabilities(provider) lets each backend append its own
capability provider at module import time, typically from that backend's own
test-support module, and _capabilities() merges every registered provider's
map. No two backends' contributions live in the same edited region, so PRs from
different backend teams do not collide.

Usage

from torch.testing._internal.common_device_type import (
    Capability,
    register_privateuse1_capabilities,
)

register_privateuse1_capabilities(lambda: {
    Capability.dtype.bf16: lambda: True,
})

Changes

  • torch/testing/_internal/common_device_type.py:
    • add _PRIVATEUSE1_CAPABILITY_PROVIDERS and
      register_privateuse1_capabilities();
    • give PrivateUse1TestBase a _capabilities() override that merges every
      registered provider into the same flat {capability: predicate} map the
      in-tree bases (CPUTestBase, CUDATestBase, XPUTestBase) return, so
      get_capabilities() can call each value directly.

Providers are merged in registration order, so a provider registered later wins
on a key an earlier one already declared.

Test Plan

No functional change for existing backends: with no provider registered,
PrivateUse1TestBase._capabilities() returns exactly what the base
DeviceTypeTestBase._capabilities() returns today, so every existing
@requires_capabilities outcome is unchanged.

The TestCapabilityGating suite in
test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_testing.py
temporarily replaces PrivateUse1TestBase._capabilities to test gating with
a fixed capability map. That suite does not exercise provider registration
or the order in which provider maps are merged.

Related

Part of #185590.

@pytorch-bot

pytorch-bot Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 3195fd5 with merge base cf8577d (image):
💚 Looks good so far! There are no failures yet. 💚

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

@shichuanliujie9527

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "module: tests/distributed"

@pytorch-bot pytorch-bot Bot added the module: tests/distributed This label covers all test cases within the Distributed sheet. label Aug 4, 2026
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Aug 5, 2026
… gating

Refactor TestTPFSDPIntegration to the device-agnostic pattern from the
testcase-refactoring initiative (pytorch#185590) so it runs on out-of-tree
PrivateUse1 backends (NPU) without patching common_fsdp module globals.

Introduce TPFSDPIntegrationTestBase(FSDPTestContinuous) that resolves the
device and backend at runtime: _resolved_device_type() resolves the
generic "privateuse1" token to the registered backend name, backend_str
goes through dist.get_default_backend_for_device (npu->hccl, cuda->nccl,
no hardcoding), and world_size is accelerator-aware. This mirrors
DTensorPPTestBase in pytorch#192051. Tag the class
HardwareClassification.ACCELERATOR, since all three methods run
multi-device FSDP+TP collectives on an accelerator.

Replace @skip_if_lt_x_gpu(4) with @requires_world_size(4) plus
@requires_capabilities(Capability.distributed.backend/dtensor/fsdp), the
same gates pytorch#192045 uses for the FSDP+DTensor path. Drop the module-level
device_type global and point its six call sites at
self._resolved_device_type(); the nested TestModel captures the resolved
device via closure. Switch instantiate_parametrized_tests to
instantiate_device_type_tests(only_for=["cuda","xpu","privateuse1"],
allow_xpu=True) so per-device variants are generated and registered
PrivateUse1 backends are auto-discovered. No torch_npu or backend-specific
import is introduced; backend capability registration is handled
separately via register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#190846 (Capability/
requires_capabilities) and pytorch#191919 (Capability.distributed namespace +
generalized requires_world_size), not on main yet, so opened as draft
until they land (same as pytorch#192045/pytorch#192046). NPU runtime additionally
needs pytorch#192043 (register_privateuse1_capabilities) plus the backend's
distributed.* registration in the torch_npu repo.

The full capability-gated form was validated end-to-end on 4x Ascend
910B4 (privateuse1=npu) by porting the foundation mechanism onto a
local checkout (the foundation PRs do not apply cleanly to the older
base). With NPU registering distributed.backend/dtensor/fsdp as
supported, instantiate_device_type_tests generates the
TestTPFSDPIntegrationPRIVATEUSE1 variant and all three tests pass:

  python test/distributed/fsdp/test_fsdp_tp_integration.py
  # Testing class TestTPFSDPIntegrationPRIVATEUSE1 on 4 npu
  # Ran 3 tests ... OK

This exercises the FSDPTestContinuous x PrivateUse1TestBase MRO and the
@requires_capabilities / @requires_world_size gates on a multiprocess
test, both previously open risks for this test type.

Authored with the assistance of an AI assistant (Claude Code).

Co-Authored-By: Claude <[email protected]>
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Aug 5, 2026
… gating

Refactor TestTPFSDPIntegration to the device-agnostic pattern from the
testcase-refactoring initiative (pytorch#185590) so it runs on out-of-tree
PrivateUse1 backends (NPU) without patching common_fsdp module globals.

Introduce TPFSDPIntegrationTestBase(FSDPTestContinuous) that resolves the
device and backend at runtime: _resolved_device_type() resolves the
generic "privateuse1" token to the registered backend name, backend_str
goes through dist.get_default_backend_for_device (npu->hccl, cuda->nccl,
no hardcoding), and world_size is accelerator-aware. This mirrors
DTensorPPTestBase in pytorch#192051. Tag the class
HardwareClassification.ACCELERATOR, since all three methods run
multi-device FSDP+TP collectives on an accelerator.

Replace @skip_if_lt_x_gpu(4) with @requires_world_size(4) plus
@requires_capabilities(Capability.distributed.backend/dtensor/fsdp), the
same gates pytorch#192045 uses for the FSDP+DTensor path. Drop the module-level
device_type global and point its six call sites at
self._resolved_device_type(); the nested TestModel captures the resolved
device via closure. Switch instantiate_parametrized_tests to
instantiate_device_type_tests(only_for=["cuda","xpu","privateuse1"],
allow_xpu=True) so per-device variants are generated and registered
PrivateUse1 backends are auto-discovered. No torch_npu or backend-specific
import is introduced; backend capability registration is handled
separately via register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#190846 (Capability/
requires_capabilities) and pytorch#191919 (Capability.distributed namespace +
generalized requires_world_size), not on main yet, so opened as draft
until they land (same as pytorch#192045/pytorch#192046). NPU runtime additionally
needs pytorch#192043 (register_privateuse1_capabilities) plus the backend's
distributed.* registration in the torch_npu repo.

The full capability-gated form was validated end-to-end on 4x Ascend
910B4 (privateuse1=npu) by porting the foundation mechanism onto a
local checkout (the foundation PRs do not apply cleanly to the older
base). With NPU registering distributed.backend/dtensor/fsdp as
supported, instantiate_device_type_tests generates the
TestTPFSDPIntegrationPRIVATEUSE1 variant and all three tests pass:

  python test/distributed/fsdp/test_fsdp_tp_integration.py
  # Testing class TestTPFSDPIntegrationPRIVATEUSE1 on 4 npu
  # Ran 3 tests ... OK

This exercises the FSDPTestContinuous x PrivateUse1TestBase MRO and the
@requires_capabilities / @requires_world_size gates on a multiprocess
test, both previously open risks for this test type.

Authored with the assistance of an AI assistant (Claude Code).
@jbschlosser jbschlosser added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 5, 2026
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Aug 6, 2026
… gating

Refactor TestTPFSDPIntegration to the device-agnostic pattern from the
testcase-refactoring initiative (pytorch#185590) so it runs on out-of-tree
PrivateUse1 backends (NPU) without patching common_fsdp module globals.

Introduce TPFSDPIntegrationTestBase(FSDPTestContinuous) that resolves the
device and backend at runtime: _resolved_device_type() resolves the
generic "privateuse1" token to the registered backend name, backend_str
goes through dist.get_default_backend_for_device (npu->hccl, cuda->nccl,
no hardcoding), and world_size is accelerator-aware. This mirrors
DTensorPPTestBase in pytorch#192051. Tag the class
HardwareClassification.ACCELERATOR, since all three methods run
multi-device FSDP+TP collectives on an accelerator.

Replace @skip_if_lt_x_gpu(4) with @requires_world_size(4) plus
@requires_capabilities(Capability.distributed.backend/dtensor/fsdp), the
same gates pytorch#192045 uses for the FSDP+DTensor path. Drop the module-level
device_type global and point its six call sites at
self._resolved_device_type(); the nested TestModel captures the resolved
device via closure. Switch instantiate_parametrized_tests to
instantiate_device_type_tests(except_for="cpu",
allow_xpu=True) so per-device variants are generated and registered
PrivateUse1 backends are auto-discovered. No torch_npu or backend-specific
import is introduced; backend capability registration is handled
separately via register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#190846 (Capability/
requires_capabilities) and pytorch#191919 (Capability.distributed namespace +
generalized requires_world_size), not on main yet, so opened as draft
until they land (same as pytorch#192045/pytorch#192046). NPU runtime additionally
needs pytorch#192043 (register_privateuse1_capabilities) plus the backend's
distributed.* registration in the torch_npu repo.

The full capability-gated form was validated end-to-end on 4x Ascend
910B4 (privateuse1=npu) by porting the foundation mechanism onto a
local checkout (the foundation PRs do not apply cleanly to the older
base). With NPU registering distributed.backend/dtensor/fsdp as
supported, instantiate_device_type_tests generates the
TestTPFSDPIntegrationPRIVATEUSE1 variant and all three tests pass:

  python test/distributed/fsdp/test_fsdp_tp_integration.py
  # Testing class TestTPFSDPIntegrationPRIVATEUSE1 on 4 npu
  # Ran 3 tests ... OK

This exercises the FSDPTestContinuous x PrivateUse1TestBase MRO and the
@requires_capabilities / @requires_world_size gates on a multiprocess
test, both previously open risks for this test type.

Authored with the assistance of an AI assistant (Claude Code).
@shichuanliujie9527

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

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

Copy link
Copy Markdown
Contributor Author

@orangeH25 @fffrog This extends the _capabilities() mechanism from #190846 with a registry, so that out-of-tree PrivateUse1 backends can each declare capabilities without editing the same method body — otherwise every backend team's PR conflicts on that one region. Would appreciate your view on whether this fits the direction you're taking the API.

The branch is cut from #190846's head, so its changes show up in the combined diff. This PR's own change is 28 lines: 3825dc2

…their own capabilities

PrivateUse1TestBase is shared by every out-of-tree backend, so having each
backend override _capabilities() on that one class makes unrelated backends'
PRs conflict on the same method body. register_privateuse1_capabilities() lets
each backend append its own provider at import time, and
PrivateUse1TestBase._capabilities() merges them.

Rebased onto main now that pytorch#190846 has landed. The branch was originally cut
from an intermediate pytorch#190846 commit whose _capabilities() contract was
dict[type, dict[str, Callable[[], bool]]], and the merge nested each provider's
entries under a namespace key. The contract that landed is a flat
dict[str, Callable[[], bool]]: every in-tree base returns
{Capability.dtype.fp8: lambda: ..., ...} and get_capabilities() calls bool(fn())
on each value, so the nested merge would have put a dict where a callable is
expected. Providers are now merged flat, in registration order.

This no longer depends on pytorch#191919. The registry needs no capability namespace of
its own, so the usage example refers to an existing one.
@shichuanliujie9527
shichuanliujie9527 force-pushed the test/privateuse1-capability-registry branch from b4a5d77 to 3195fd5 Compare August 25, 2026 02:27
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
kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Sep 7, 2026
@shichuanliujie9527

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot

pytorch-bot Bot commented Sep 15, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

@shichuanliujie9527

Copy link
Copy Markdown
Contributor Author

@fffrog Could you please review and approve this PR if it looks good? The merge bot requires approval from an authorized maintainer. Thanks.

pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…agnostic (#192694)

`requires_world_size` is the world-size gate that capability-gated FSDP test migrations (e.g. #192208 and the `test_fsdp_*` series) are migrating **to** from `skip_if_lt_x_gpu`. It hardcodes `torch.cuda.device_count()`, so on any non-CUDA accelerator (XPU/HPU/PrivateUse1) every `@requires_world_size(n)` test is skipped even when devices are present.

Generalizes the skip to `torch.accelerator.current_accelerator(check_available=True)` + `torch.get_device_module(acc.type).device_count()`, mirroring `skip_if_lt_x_gpu`'s generalization in #187650. Without this, #187650 alone does not unblock the migrated tests because they call `requires_world_size`, not `skip_if_lt_x_gpu`; #187650 generalized the old function while the migrations target the new one.

Sibling to #187650. Independent of the capability foundation PRs #190846/#191919/#192043 (this changes `common_distributed.requires_world_size`, they change `common_device_type.py`).

## Test plan
Validated on Ascend 910B (PrivateUse1, `torch.accelerator.device_count()=4`): `@requires_world_size(2)` tests run instead of being skipped ("requires 2 accelerators, found 4"); the 6 capability-gated `test_fsdp_*` files pass on 4-card NPU (56 tests, 0 failures). Container-side shims of the foundation PRs (#190846/#191919) were applied only to provide the Capability/requires_capabilities imports (not yet on main); this change is independent of those.

Pull Request resolved: #192694
Approved by: https://github.com/wjlFlyer, https://github.com/fffrog
pytorchmergebot pushed a commit that referenced this pull request Oct 21, 2026
…test base classes (#194992)

## Motivation

Device-instantiated subclasses of `ShardedTensorTestBase` already receive
`device_type`, but a bare `@with_comms` still selects the fixed `"nccl"` default.
Use the device's registered default backend for these subclasses while retaining
the existing decorator argument for callers that have not yet adopted
`instantiate_device_type_tests`.

## Changes

Only `torch/testing/_internal/distributed/_shard/sharded_tensor/__init__.py`
changes:

- Add `backend(self, device)`, using the existing `dist` import to call
  `dist.get_default_backend_for_device(device)`.
- In `with_comms`, resolve the backend from `self.device_type` when it is
  present and non-`None`; otherwise use the decorator's `backend` argument.
- Store the result in `backend_name`, avoiding shadowing the outer decorator
  argument, and use it for both the device-count check and `init_comms`.
- When an accelerator is available and the selected backend is not Gloo,
  skip if there are fewer devices than `world_size`. Remove the
  `current_accelerator()` probe and the comparison against its default backend.

The `"nccl"` defaults of `with_comms`, `init_comms`, and `init_pg` remain.
Existing backend availability checks, rank binding, RPC initialization, and
cleanup methods are unchanged. There are no changes to `common_distributed.py`.

## Behavior

| Caller | Backend selection |
| --- | --- |
| Device-instantiated class | Registered default for `self.device_type`; this takes precedence over the decorator argument |
| Legacy class without `device_type` | Decorator argument, defaulting to `"nccl"` |
| Direct `init_pg` / `init_comms` call | Explicit argument, or the unchanged `"nccl"` default |

## Validation

- Patch replay, Python syntax, PYFMT, and Ruff checks passed.
- Isolated wrapper checks covered legacy defaults, explicit Gloo, CPU/NPU
  backend selection, reuse of the same closure, RPC flag forwarding, and
  the insufficient-device skip.
- Ran the existing DCP caching test from #192324 on two NPU devices with HCCL:
  `TestDistributedStateDictSaveLoadWithCachingNPU.test_read_write_shard_tensor_npu`
  in `test/distributed/checkpoint/test_file_system_checkpoint.py`.

| Compared version | Selected | Passed | Failed / errors / skipped | Exit code |
| --- | --- | --- | --- | --- |
| Implementation before the latest import cleanup | 1 | 1 | 0 / 0 / 0 | 0 |
| Previous PR implementation (control run) | 1 | 1 | 0 / 0 / 0 | 0 |

The unmodified business test completed two save/load rounds, data equality
checks, and process-group destruction. Parent and worker imports were verified.
The run reused an existing PyTorch/torch_npu binary environment with isolated
test-helper sources and device-test capability support from #191919 and #192043.

The final review cleanup reuses `dist.get_default_backend_for_device` instead
of importing `distributed_c10d` separately; both names refer to the same function.
That two-line cleanup passed patch replay, syntax, PYFMT, and Ruff checks.
The device test was run before this import-only cleanup.

Pull Request resolved: #194992
Approved by: https://github.com/JamesD18, https://github.com/fffrog
pytorchmergebot pushed a commit that referenced this pull request Oct 23, 2026
…test base classes (#194992)

## Motivation

Device-instantiated subclasses of `ShardedTensorTestBase` already receive
`device_type`, but a bare `@with_comms` still selects the fixed `"nccl"` default.
Use the device's registered default backend for these subclasses while retaining
the existing decorator argument for callers that have not yet adopted
`instantiate_device_type_tests`.

## Changes

Only `torch/testing/_internal/distributed/_shard/sharded_tensor/__init__.py`
changes:

- Add `backend(self, device)`, using the existing `dist` import to call
  `dist.get_default_backend_for_device(device)`.
- In `with_comms`, resolve the backend from `self.device_type` when it is
  present and non-`None`; otherwise use the decorator's `backend` argument.
- Store the result in `backend_name`, avoiding shadowing the outer decorator
  argument, and use it for both the device-count check and `init_comms`.
- When an accelerator is available and the selected backend is not Gloo,
  skip if there are fewer devices than `world_size`. Remove the
  `current_accelerator()` probe and the comparison against its default backend.

The `"nccl"` defaults of `with_comms`, `init_comms`, and `init_pg` remain.
Existing backend availability checks, rank binding, RPC initialization, and
cleanup methods are unchanged. There are no changes to `common_distributed.py`.

## Behavior

| Caller | Backend selection |
| --- | --- |
| Device-instantiated class | Registered default for `self.device_type`; this takes precedence over the decorator argument |
| Legacy class without `device_type` | Decorator argument, defaulting to `"nccl"` |
| Direct `init_pg` / `init_comms` call | Explicit argument, or the unchanged `"nccl"` default |

## Validation

- Patch replay, Python syntax, PYFMT, and Ruff checks passed.
- Isolated wrapper checks covered legacy defaults, explicit Gloo, CPU/NPU
  backend selection, reuse of the same closure, RPC flag forwarding, and
  the insufficient-device skip.
- Ran the existing DCP caching test from #192324 on two NPU devices with HCCL:
  `TestDistributedStateDictSaveLoadWithCachingNPU.test_read_write_shard_tensor_npu`
  in `test/distributed/checkpoint/test_file_system_checkpoint.py`.

| Compared version | Selected | Passed | Failed / errors / skipped | Exit code |
| --- | --- | --- | --- | --- |
| Implementation before the latest import cleanup | 1 | 1 | 0 / 0 / 0 | 0 |
| Previous PR implementation (control run) | 1 | 1 | 0 / 0 / 0 | 0 |

The unmodified business test completed two save/load rounds, data equality
checks, and process-group destruction. Parent and worker imports were verified.
The run reused an existing PyTorch/torch_npu binary environment with isolated
test-helper sources and device-test capability support from #191919 and #192043.

The final review cleanup reuses `dist.get_default_backend_for_device` instead
of importing `distributed_c10d` separately; both names refer to the same function.
That two-line cleanup passed patch replay, syntax, PYFMT, and Ruff checks.
The device test was run before this import-only cleanup.

Pull Request resolved: #194992
Approved by: https://github.com/fffrog
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Nov 14, 2026
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Nov 16, 2026
… gating

Refactor TestFlattenParams to the device-agnostic pattern from the
testcase-refactoring initiative (pytorch#185590) so it runs on out-of-tree
PrivateUse1 backends (NPU) without patching common_fsdp module globals.

Introduce FlattenParamsTestBase(FSDPTestContinuous) that resolves the
device and backend at runtime: _resolved_device_type() resolves the
generic "privateuse1" token to the registered backend name, backend_str
goes through dist.get_default_backend_for_device (npu->hccl, cuda->nccl,
no hardcoding), and world_size stays clamped to 1 (these are flattening
logic / subroutine checks that do not require multiple ranks). Mirrors
DTensorPPTestBase in pytorch#192051: the intermediate base holds backend_str so
the device-specific generated class inherits it rather than ports it (a
ported classmethod cannot see the variant's device_type). Tag the class
HardwareClassification.ACCELERATOR since the device-touching methods
construct FSDP on an accelerator.

Replace the in-method device resolution in _get_default_config
(acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu",
which returns "cpu" when torch_npu is not imported) with
torch.device(self._resolved_device_type()) so the FlatParamHandle config
uses the instantiate-injected device. Replace @skip_if_lt_x_gpu(1) on the
six device-touching methods with @requires_world_size(1) plus
@requires_capabilities(Capability.distributed.backend/fsdp) (flatten is
pure FSDP, no DTensor). The metadata-only methods (test_flat_param_shard_*
and test_numel_*/test_flatten_nothing) stay ungated; they are pure logic
and run on every device variant including cpu. Switch
instantiate_parametrized_tests to instantiate_device_type_tests(except_for
="cpu", allow_xpu=True) so per-device variants are generated and
registered PrivateUse1 backends are auto-discovered; instantiate_test
still processes the @parametrize on test_flat_param_shard_metadata_with_
memory_format. No torch_npu or backend-specific import is introduced;
backend capability registration is handled separately via
register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#191919 (provides Capability.distributed
+ requires_capabilities + runtime gate; not on main yet). NPU run reproducible
with non-merge runtime prerequisites pytorch#187650 (common_fsdp/common_distributed
hardware-agnostic generalization) and pytorch#192694 (requires_world_size
generalization); these are NOT merge dependencies. pytorch#190846 is a competing
capability design (Capability.lib/dtype) this file does not use; pytorch#192043 is
not required to run (capabilities stay no-op without it).

  python -m ruff check test/distributed/fsdp/test_fsdp_flatten_params.py  # All checks passed
  python -m py_compile test/distributed/fsdp/test_fsdp_flatten_params.py  # OK

Authored with the assistance of an AI assistant (Claude Code).
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Nov 16, 2026
…lity gating

Refactor TestFSDPWithDeviceMeshAndDTensor to the device-agnostic pattern
from the testcase-refactoring initiative (pytorch#185590) so it runs on
out-of-tree PrivateUse1 backends (NPU) without patching common_fsdp /
common_dtensor module globals.

Introduce FSDPDTensorStateDictTestBase(DTensorContinuousTestBase) that
resolves the device and backend at runtime: _resolved_device_type()
resolves the generic "privateuse1" token to the registered backend name,
backend_str goes through dist.get_default_backend_for_device
(npu->hccl, cuda->nccl, no hardcoding), and world_size is
accelerator-aware (min(4, device_count()), capped at 4 because
test_raises_warning_or_errors needs a 2-dim mesh). Mirrors
TPFSDPIntegrationTestBase / DTensorPPTestBase in pytorch#192051: the
intermediate base holds backend_str so the device-specific generated
class inherits it rather than ports it (a ported classmethod cannot see
the variant's device_type). Tag the class
HardwareClassification.ACCELERATOR since all five methods run multi-rank
DTensor/FSDP collectives on an accelerator.

Replace @skip_if_lt_x_gpu(2) on the four 2-rank tests
(test_fsdp_init_with_device_mesh,
test_dtensor_sharded_tensor_state_dict_identical,
test_dtensor_sharded_optim_load_state_dict,
test_dtensor_sharded_model_load_state_dict) and @skip_if_lt_x_gpu(4) on
test_raises_warning_or_errors with @requires_world_size(N) plus
@requires_capabilities(Capability.distributed.backend/dtensor/fsdp)
(this is a DTensor+FSDP path, so the dtensor capability is included).
@with_comms / @with_comms() is preserved on all five (DTensor comms init,
not a CUDA whitelist gate). Drop the module-level
device_type = torch.device(get_devtype()) global and replace its usages:
init_device_mesh now takes self._resolved_device_type() (string) and the
dummy model is moved with .to(self._resolved_device_type()). Thread a
device parameter through TestDummyModel.get_input and
TestDummyModelUneven.get_input (previously hardcoded via the module
global) and update all call sites to pass self._resolved_device_type().
Switch the instantiate call from only_for=("cuda","hpu","xpu") to
except_for="cpu", allow_xpu=True so registered PrivateUse1 backends are
auto-discovered. No torch_npu or backend-specific import is introduced;
backend capability registration is handled separately via
register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#191919 (provides Capability.distributed
+ requires_capabilities + runtime gate; not on main yet). NPU run reproducible
with non-merge runtime prerequisites pytorch#187650 (common_fsdp/common_distributed
hardware-agnostic generalization) and pytorch#192694 (requires_world_size
generalization); these are NOT merge dependencies. pytorch#190846 is a competing
capability design (Capability.lib/dtype) this file does not use; pytorch#192043 is
not required to run (capabilities stay no-op without it).

  python -m ruff check test/distributed/fsdp/test_fsdp_dtensor_state_dict.py  # All checks passed
  python -m py_compile test/distributed/fsdp/test_fsdp_dtensor_state_dict.py  # OK

Authored with the assistance of an AI assistant (Claude Code).
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Nov 16, 2026
Refactor TestCommunication and TestExplicitUnshard to the device-agnostic
pattern from the testcase-refactoring initiative (pytorch#185590) so they run on
out-of-tree PrivateUse1 backends (NPU) without patching common_fsdp
module globals. Both classes inherit FSDPTestContinuous, so they share
one intermediate base.

Introduce FSDPCommTestBase(FSDPTestContinuous) that resolves the device
and backend at runtime: _resolved_device_type() resolves the generic
"privateuse1" token to the registered backend name, backend_str goes
through dist.get_default_backend_for_device (npu->hccl, cuda->nccl, no
hardcoding), and world_size is accelerator-aware (min(2, device_count())).
Mirrors DTensorPPTestBase in pytorch#192051 and the sibling ExecOrderTestBase/
FineTuneTestBase: the intermediate base holds backend_str so the
device-specific generated class inherits it rather than ports it (a
ported classmethod cannot see the variant's device_type). Tag the class
HardwareClassification.ACCELERATOR since all three methods run multi-rank
FSDP/DDP collectives on an accelerator. TestExplicitUnshard's redundant
world_size override is removed since the shared base now provides the
identical value.

Replace @skip_if_lt_x_gpu(2) on the three tests (test_communication,
test_unshard_async, test_unshard_after_backward) with
@requires_world_size(2) plus
@requires_capabilities(Capability.distributed.backend/fsdp) (comm is pure
FSDP+DDP, no DTensor path). Drop the module-level
device_type = torch.device(get_devtype()) global and capture
device_type = torch.device(self._resolved_device_type()) at the top of
each of the three methods, so the method bodies keep their exact
device-object semantics (.to, device_id=, device_ids=, get_input). The
init helper _init_model drops its unused device parameter and uses
self._resolved_device_type() for device_id. The nested nn.Module classes
defined inside test_unshard_async / test_unshard_after_backward
(ReduceModule/MLPs/ReduceModel; nn.Sequential/nn.Linear) close over the
enclosing method's local device_type rather than self._resolved_device_type(),
because their self is the nn.Module, not the test instance (mirrors
test_fsdp_tp_integration). device_ids=[self.rank] is left as-is (rank-based).
Switch both instantiate_device_type_tests calls from
only_for=("cuda","hpu","xpu") to except_for="cpu", allow_xpu=True so
registered PrivateUse1 backends are auto-discovered. No torch_npu or
backend-specific import is introduced; backend capability registration is
handled separately via register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#191919 (provides Capability.distributed
+ requires_capabilities + runtime gate; not on main yet). NPU run reproducible
with non-merge runtime prerequisites pytorch#187650 (common_fsdp/common_distributed
hardware-agnostic generalization) and pytorch#192694 (requires_world_size
generalization); these are NOT merge dependencies. pytorch#190846 is a competing
capability design (Capability.lib/dtype) this file does not use; pytorch#192043 is
not required to run (capabilities stay no-op without it).

  python -m ruff check test/distributed/fsdp/test_fsdp_comm.py  # All checks passed
  python -m py_compile test/distributed/fsdp/test_fsdp_comm.py  # OK

Authored with the assistance of an AI assistant (Claude Code).
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Nov 16, 2026
Refactor TestFSDPExecOrder to the device-agnostic pattern from the
testcase-refactoring initiative (pytorch#185590) so it runs on out-of-tree
PrivateUse1 backends (NPU) without patching common_fsdp module globals.

Introduce ExecOrderTestBase(FSDPTestContinuous) that resolves the device
and backend at runtime: _resolved_device_type() resolves the generic
"privateuse1" token to the registered backend name, backend_str goes
through dist.get_default_backend_for_device (npu->hccl, cuda->nccl, no
hardcoding), and world_size is accelerator-aware (min(2, device_count())).
Mirrors DTensorPPTestBase in pytorch#192051 and the sibling FineTuneTestBase/
FlattenParamsTestBase: the intermediate base holds backend_str so the
device-specific generated class inherits it rather than ports it (a ported
classmethod cannot see the variant's device_type). Tag the class
HardwareClassification.ACCELERATOR since all three methods run multi-device
FSDP collectives on an accelerator.

Replace @skip_if_lt_x_gpu(2) on the three test methods
(test_invalid_first_iter_order, test_invalid_later_iter_order,
test_train_eval) with @requires_world_size(2) plus
@requires_capabilities(Capability.distributed.backend/fsdp) (exec_order is
pure FSDP, no DTensor path). Drop the module-level
device_type = torch.device(get_devtype()) global and capture
device_type = torch.device(self._resolved_device_type()) at the top of each
of the three methods that referenced it, so the method bodies keep their
exact device-object semantics (.to, device_id=, get_input, get_loss).
Switch the instantiate call from only_for=("cuda","hpu","xpu") to
except_for="cpu", allow_xpu=True so registered PrivateUse1 backends are
auto-discovered. No torch_npu or backend-specific import is introduced;
backend capability registration is handled separately via
register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#191919 (provides Capability.distributed
+ requires_capabilities + runtime gate; not on main yet). NPU run reproducible
with non-merge runtime prerequisites pytorch#187650 (common_fsdp/common_distributed
hardware-agnostic generalization) and pytorch#192694 (requires_world_size
generalization); these are NOT merge dependencies. pytorch#190846 is a competing
capability design (Capability.lib/dtype) this file does not use; pytorch#192043 is
not required to run (capabilities stay no-op without it).

  python -m ruff check test/distributed/fsdp/test_fsdp_exec_order.py  # All checks passed
  python -m py_compile test/distributed/fsdp/test_fsdp_exec_order.py  # OK

Authored with the assistance of an AI assistant (Claude Code).
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Nov 16, 2026
Refactor TestFSDPFineTune to the device-agnostic pattern from the
testcase-refactoring initiative (pytorch#185590) so it runs on out-of-tree
PrivateUse1 backends (NPU) without patching common_fsdp module globals.

Introduce FineTuneTestBase(FSDPTestContinuous) that resolves the device
and backend at runtime: _resolved_device_type() resolves the generic
"privateuse1" token to the registered backend name, backend_str goes
through dist.get_default_backend_for_device (npu->hccl, cuda->nccl, no
hardcoding), and world_size is accelerator-aware (min(2, device_count())).
This mirrors DTensorPPTestBase in pytorch#192051: the intermediate base holds
backend_str so the device-specific generated class inherits it rather than
ports it (a ported classmethod cannot see the variant's device_type). Tag
the class HardwareClassification.ACCELERATOR since all methods run
multi-device FSDP collectives on an accelerator.

Replace @skip_if_lt_x_gpu(2) with @requires_world_size(2) plus
@requires_capabilities(Capability.distributed.backend/fsdp) (fine-tune is
pure FSDP+DDP, no DTensor path). Drop the module-level device_type global
(a torch.device from get_devtype()) and capture
device_type = torch.device(self._resolved_device_type()) at the top of each
of the four _test_* methods that referenced it, so the method bodies keep
their exact device-object semantics (.to, device_id=, device_ids=,
device=). In _test_parity_with_ddp, replace the module-level TEST_CUDA
tolerance check with self._resolved_device_type() == "cuda" so a
multi-accelerator host picks tolerance by the test's actual device variant
rather than host CUDA availability; drop the now-stale TEST_CUDA import.
Switch the instantiate call from only_for=("cuda","hpu","xpu")
to except_for="cpu", allow_xpu=True so registered PrivateUse1 backends are
auto-discovered. No torch_npu or backend-specific import is introduced;
backend capability registration is handled separately via
register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#191919 (provides Capability.distributed
+ requires_capabilities + runtime gate; not on main yet). NPU run reproducible
with non-merge runtime prerequisites pytorch#187650 (common_fsdp/common_distributed
hardware-agnostic generalization) and pytorch#192694 (requires_world_size
generalization); these are NOT merge dependencies. pytorch#190846 is a competing
capability design (Capability.lib/dtype) this file does not use; pytorch#192043 is
not required to run (capabilities stay no-op without it).

  python -m ruff check test/distributed/fsdp/test_fsdp_fine_tune.py  # All checks passed
  python -m py_compile test/distributed/fsdp/test_fsdp_fine_tune.py  # OK

Authored with the assistance of an AI assistant (Claude Code).
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Dec 2, 2026
Refactor TestFSDPFineTune to the device-agnostic pattern from the
testcase-refactoring initiative (pytorch#185590) so it runs on out-of-tree
PrivateUse1 backends (NPU) without patching common_fsdp module globals.

Introduce FineTuneTestBase(FSDPTestContinuous) that resolves the device
and backend at runtime: _resolved_device_type() resolves the generic
"privateuse1" token to the registered backend name, backend_str goes
through dist.get_default_backend_for_device (npu->hccl, cuda->nccl, no
hardcoding), and world_size is accelerator-aware (min(2, device_count())).
This mirrors DTensorPPTestBase in pytorch#192051: the intermediate base holds
backend_str so the device-specific generated class inherits it rather than
ports it (a ported classmethod cannot see the variant's device_type). Tag
the class HardwareClassification.ACCELERATOR since all methods run
multi-device FSDP collectives on an accelerator.

Replace @skip_if_lt_x_gpu(2) with @requires_world_size(2) plus
@requires_capabilities(Capability.distributed.backend/fsdp) (fine-tune is
pure FSDP+DDP, no DTensor path). Drop the module-level device_type global
(a torch.device from get_devtype()) and capture
device_type = torch.device(self._resolved_device_type()) at the top of each
of the four _test_* methods that referenced it, so the method bodies keep
their exact device-object semantics (.to, device_id=, device_ids=,
device=). In _test_parity_with_ddp, replace the module-level TEST_CUDA
tolerance check with self._resolved_device_type() == "cuda" so a
multi-accelerator host picks tolerance by the test's actual device variant
rather than host CUDA availability; drop the now-stale TEST_CUDA import.
Switch the instantiate call from only_for=("cuda","hpu","xpu")
to except_for="cpu", allow_xpu=True so registered PrivateUse1 backends are
auto-discovered. No torch_npu or backend-specific import is introduced;
backend capability registration is handled separately via
register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#191919 (provides Capability.distributed
+ requires_capabilities + runtime gate; not on main yet). NPU run reproducible
with non-merge runtime prerequisites pytorch#187650 (common_fsdp/common_distributed
hardware-agnostic generalization) and pytorch#192694 (requires_world_size
generalization); these are NOT merge dependencies. pytorch#190846 is a competing
capability design (Capability.lib/dtype) this file does not use; pytorch#192043 is
not required to run (capabilities stay no-op without it).

  python -m ruff check test/distributed/fsdp/test_fsdp_fine_tune.py  # All checks passed
  python -m py_compile test/distributed/fsdp/test_fsdp_fine_tune.py  # OK

Authored with the assistance of an AI assistant (Claude Code).
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Dec 2, 2026
… gating

Refactor TestFlattenParams to the device-agnostic pattern from the
testcase-refactoring initiative (pytorch#185590) so it runs on out-of-tree
PrivateUse1 backends (NPU) without patching common_fsdp module globals.

Introduce FlattenParamsTestBase(FSDPTestContinuous) that resolves the
device and backend at runtime: _resolved_device_type() resolves the
generic "privateuse1" token to the registered backend name, backend_str
goes through dist.get_default_backend_for_device (npu->hccl, cuda->nccl,
no hardcoding), and world_size stays clamped to 1 (these are flattening
logic / subroutine checks that do not require multiple ranks). Mirrors
DTensorPPTestBase in pytorch#192051: the intermediate base holds backend_str so
the device-specific generated class inherits it rather than ports it (a
ported classmethod cannot see the variant's device_type). Tag the class
HardwareClassification.ACCELERATOR since the device-touching methods
construct FSDP on an accelerator.

Replace the in-method device resolution in _get_default_config
(acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu",
which returns "cpu" when torch_npu is not imported) with
torch.device(self._resolved_device_type()) so the FlatParamHandle config
uses the instantiate-injected device. Replace @skip_if_lt_x_gpu(1) on the
six device-touching methods with @requires_world_size(1) plus
@requires_capabilities(Capability.distributed.backend/fsdp) (flatten is
pure FSDP, no DTensor). The metadata-only methods (test_flat_param_shard_*
and test_numel_*/test_flatten_nothing) stay ungated; they are pure logic
and run on every device variant including cpu. Switch
instantiate_parametrized_tests to instantiate_device_type_tests(except_for
="cpu", allow_xpu=True) so per-device variants are generated and
registered PrivateUse1 backends are auto-discovered; instantiate_test
still processes the @parametrize on test_flat_param_shard_metadata_with_
memory_format. No torch_npu or backend-specific import is introduced;
backend capability registration is handled separately via
register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#191919 (provides Capability.distributed
+ requires_capabilities + runtime gate; not on main yet). NPU run reproducible
with non-merge runtime prerequisites pytorch#187650 (common_fsdp/common_distributed
hardware-agnostic generalization) and pytorch#192694 (requires_world_size
generalization); these are NOT merge dependencies. pytorch#190846 is a competing
capability design (Capability.lib/dtype) this file does not use; pytorch#192043 is
not required to run (capabilities stay no-op without it).

  python -m ruff check test/distributed/fsdp/test_fsdp_flatten_params.py  # All checks passed
  python -m py_compile test/distributed/fsdp/test_fsdp_flatten_params.py  # OK

Authored with the assistance of an AI assistant (Claude Code).
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Dec 2, 2026
Refactor TestFSDPExecOrder to the device-agnostic pattern from the
testcase-refactoring initiative (pytorch#185590) so it runs on out-of-tree
PrivateUse1 backends (NPU) without patching common_fsdp module globals.

Introduce ExecOrderTestBase(FSDPTestContinuous) that resolves the device
and backend at runtime: _resolved_device_type() resolves the generic
"privateuse1" token to the registered backend name, backend_str goes
through dist.get_default_backend_for_device (npu->hccl, cuda->nccl, no
hardcoding), and world_size is accelerator-aware (min(2, device_count())).
Mirrors DTensorPPTestBase in pytorch#192051 and the sibling FineTuneTestBase/
FlattenParamsTestBase: the intermediate base holds backend_str so the
device-specific generated class inherits it rather than ports it (a ported
classmethod cannot see the variant's device_type). Tag the class
HardwareClassification.ACCELERATOR since all three methods run multi-device
FSDP collectives on an accelerator.

Replace @skip_if_lt_x_gpu(2) on the three test methods
(test_invalid_first_iter_order, test_invalid_later_iter_order,
test_train_eval) with @requires_world_size(2) plus
@requires_capabilities(Capability.distributed.backend/fsdp) (exec_order is
pure FSDP, no DTensor path). Drop the module-level
device_type = torch.device(get_devtype()) global and capture
device_type = torch.device(self._resolved_device_type()) at the top of each
of the three methods that referenced it, so the method bodies keep their
exact device-object semantics (.to, device_id=, get_input, get_loss).
Switch the instantiate call from only_for=("cuda","hpu","xpu") to
except_for="cpu", allow_xpu=True so registered PrivateUse1 backends are
auto-discovered. No torch_npu or backend-specific import is introduced;
backend capability registration is handled separately via
register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#191919 (provides Capability.distributed
+ requires_capabilities + runtime gate; not on main yet). NPU run reproducible
with non-merge runtime prerequisites pytorch#187650 (common_fsdp/common_distributed
hardware-agnostic generalization) and pytorch#192694 (requires_world_size
generalization); these are NOT merge dependencies. pytorch#190846 is a competing
capability design (Capability.lib/dtype) this file does not use; pytorch#192043 is
not required to run (capabilities stay no-op without it).

  python -m ruff check test/distributed/fsdp/test_fsdp_exec_order.py  # All checks passed
  python -m py_compile test/distributed/fsdp/test_fsdp_exec_order.py  # OK

Authored with the assistance of an AI assistant (Claude Code).
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Dec 2, 2026
…lity gating

Refactor TestFSDPWithDeviceMeshAndDTensor to the device-agnostic pattern
from the testcase-refactoring initiative (pytorch#185590) so it runs on
out-of-tree PrivateUse1 backends (NPU) without patching common_fsdp /
common_dtensor module globals.

Introduce FSDPDTensorStateDictTestBase(DTensorContinuousTestBase) that
resolves the device and backend at runtime: _resolved_device_type()
resolves the generic "privateuse1" token to the registered backend name,
backend_str goes through dist.get_default_backend_for_device
(npu->hccl, cuda->nccl, no hardcoding), and world_size is
accelerator-aware (min(4, device_count()), capped at 4 because
test_raises_warning_or_errors needs a 2-dim mesh). Mirrors
TPFSDPIntegrationTestBase / DTensorPPTestBase in pytorch#192051: the
intermediate base holds backend_str so the device-specific generated
class inherits it rather than ports it (a ported classmethod cannot see
the variant's device_type). Tag the class
HardwareClassification.ACCELERATOR since all five methods run multi-rank
DTensor/FSDP collectives on an accelerator.

Replace @skip_if_lt_x_gpu(2) on the four 2-rank tests
(test_fsdp_init_with_device_mesh,
test_dtensor_sharded_tensor_state_dict_identical,
test_dtensor_sharded_optim_load_state_dict,
test_dtensor_sharded_model_load_state_dict) and @skip_if_lt_x_gpu(4) on
test_raises_warning_or_errors with @requires_world_size(N) plus
@requires_capabilities(Capability.distributed.backend/dtensor/fsdp)
(this is a DTensor+FSDP path, so the dtensor capability is included).
@with_comms / @with_comms() is preserved on all five (DTensor comms init,
not a CUDA whitelist gate). Drop the module-level
device_type = torch.device(get_devtype()) global and replace its usages:
init_device_mesh now takes self._resolved_device_type() (string) and the
dummy model is moved with .to(self._resolved_device_type()). Thread a
device parameter through TestDummyModel.get_input and
TestDummyModelUneven.get_input (previously hardcoded via the module
global) and update all call sites to pass self._resolved_device_type().
Switch the instantiate call from only_for=("cuda","hpu","xpu") to
except_for="cpu", allow_xpu=True so registered PrivateUse1 backends are
auto-discovered. No torch_npu or backend-specific import is introduced;
backend capability registration is handled separately via
register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#191919 (provides Capability.distributed
+ requires_capabilities + runtime gate; not on main yet). NPU run reproducible
with non-merge runtime prerequisites pytorch#187650 (common_fsdp/common_distributed
hardware-agnostic generalization) and pytorch#192694 (requires_world_size
generalization); these are NOT merge dependencies. pytorch#190846 is a competing
capability design (Capability.lib/dtype) this file does not use; pytorch#192043 is
not required to run (capabilities stay no-op without it).

  python -m ruff check test/distributed/fsdp/test_fsdp_dtensor_state_dict.py  # All checks passed
  python -m py_compile test/distributed/fsdp/test_fsdp_dtensor_state_dict.py  # OK

Authored with the assistance of an AI assistant (Claude Code).
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Dec 2, 2026
Refactor TestCommunication and TestExplicitUnshard to the device-agnostic
pattern from the testcase-refactoring initiative (pytorch#185590) so they run on
out-of-tree PrivateUse1 backends (NPU) without patching common_fsdp
module globals. Both classes inherit FSDPTestContinuous, so they share
one intermediate base.

Introduce FSDPCommTestBase(FSDPTestContinuous) that resolves the device
and backend at runtime: _resolved_device_type() resolves the generic
"privateuse1" token to the registered backend name, backend_str goes
through dist.get_default_backend_for_device (npu->hccl, cuda->nccl, no
hardcoding), and world_size is accelerator-aware (min(2, device_count())).
Mirrors DTensorPPTestBase in pytorch#192051 and the sibling ExecOrderTestBase/
FineTuneTestBase: the intermediate base holds backend_str so the
device-specific generated class inherits it rather than ports it (a
ported classmethod cannot see the variant's device_type). Tag the class
HardwareClassification.ACCELERATOR since all three methods run multi-rank
FSDP/DDP collectives on an accelerator. TestExplicitUnshard's redundant
world_size override is removed since the shared base now provides the
identical value.

Replace @skip_if_lt_x_gpu(2) on the three tests (test_communication,
test_unshard_async, test_unshard_after_backward) with
@requires_world_size(2) plus
@requires_capabilities(Capability.distributed.backend/fsdp) (comm is pure
FSDP+DDP, no DTensor path). Drop the module-level
device_type = torch.device(get_devtype()) global and capture
device_type = torch.device(self._resolved_device_type()) at the top of
each of the three methods, so the method bodies keep their exact
device-object semantics (.to, device_id=, device_ids=, get_input). The
init helper _init_model drops its unused device parameter and uses
self._resolved_device_type() for device_id. The nested nn.Module classes
defined inside test_unshard_async / test_unshard_after_backward
(ReduceModule/MLPs/ReduceModel; nn.Sequential/nn.Linear) close over the
enclosing method's local device_type rather than self._resolved_device_type(),
because their self is the nn.Module, not the test instance (mirrors
test_fsdp_tp_integration). device_ids=[self.rank] is left as-is (rank-based).
Switch both instantiate_device_type_tests calls from
only_for=("cuda","hpu","xpu") to except_for="cpu", allow_xpu=True so
registered PrivateUse1 backends are auto-discovered. No torch_npu or
backend-specific import is introduced; backend capability registration is
handled separately via register_privateuse1_capabilities (pytorch#192043).

Test Plan:
The capability-gated form depends on pytorch#191919 (provides Capability.distributed
+ requires_capabilities + runtime gate; not on main yet). NPU run reproducible
with non-merge runtime prerequisites pytorch#187650 (common_fsdp/common_distributed
hardware-agnostic generalization) and pytorch#192694 (requires_world_size
generalization); these are NOT merge dependencies. pytorch#190846 is a competing
capability design (Capability.lib/dtype) this file does not use; pytorch#192043 is
not required to run (capabilities stay no-op without it).

  python -m ruff check test/distributed/fsdp/test_fsdp_comm.py  # All checks passed
  python -m py_compile test/distributed/fsdp/test_fsdp_comm.py  # OK

Authored with the assistance of an AI assistant (Claude Code).

@KarhouTam KarhouTam left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Adds a process-global registry so out-of-tree PrivateUse1 backends can contribute capability maps to PrivateUse1TestBase._capabilities() without editing the shared method body; the merge itself is sound and no provider leaves existing @requires_capabilities outcomes unchanged. The new API is undocumented and untyped beyond a bare dict, the registry has no deregistration path and so leaks across tests, and its merge/ordering behavior has no test.

Findings (3):

  • [Major/api-design] torch/testing/_internal/common_device_type.py:985: Type the provider as returning dict[str, Callable[[], bool]] and document it: get_capabilities() calls every value, so a provider returning plain bools fails with a bare TypeError far from the registration site.
    fix: Annotate as Callable[[], dict[str, Callable[[], bool]]] and add a docstring stating that keys are Capability.* identifiers, values are zero-argument predicates evaluated by get_capabilities(), and registration is process-global.
  • [Major/code-quality] torch/testing/_internal/common_device_type.py:982: This registry can only grow: with no deregistration or idempotency guard, a provider registered by a test or by a module imported twice silently changes capability gating for every test that runs afterwards.
    fix: Return a deregistration callback (or expose a context manager) so tests can restore the previous state, and make registration idempotent per provider.
  • [Major/testing] torch/testing/_internal/common_device_type.py:996: Nothing here is exercised by a test: TestCapabilityGating replaces PrivateUse1TestBase._capabilities wholesale, so registration, merging and the documented 'later provider wins' order are never run.
    fix: Add a case to test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_testing.py that registers a provider, asserts the merged map and last-wins order, then deregisters.

Generated by my agent. Reviewed by the user.

_PRIVATEUSE1_CAPABILITY_PROVIDERS: list[Callable[[], dict]] = []


def register_privateuse1_capabilities(provider: Callable[[], dict]) -> None:

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.

Type the provider as returning dict[str, Callable[[], bool]] and document it: get_capabilities() calls every value, so a provider returning plain bools fails with a bare TypeError far from the registration site.

#
# `_capabilities()` merges every registered provider's map, so a provider
# registered later wins on a key an earlier one already declared.
_PRIVATEUSE1_CAPABILITY_PROVIDERS: list[Callable[[], dict]] = []

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.

This registry can only grow: with no deregistration or idempotency guard, a provider registered by a test or by a module imported twice silently changes capability gating for every test that runs afterwards.

bypass_device_restrictions = False

@classmethod
def _capabilities(cls):

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.

Nothing here is exercised by a test: TestCapabilityGating replaces PrivateUse1TestBase._capabilities wholesale, so registration, merging and the documented 'later provider wins' order are never run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

module: tests/distributed This label covers all test cases within the Distributed sheet. open source Stale topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants