Skip to content

[Testcase Refactoring] Refactor test_dtensor_pp_unit_tests with instantiate_device_type_tests and hw-classification label - #192051

Open
PlatformLC wants to merge 7 commits into
pytorch:mainfrom
PlatformLC:test/test_dtensor_pp_unit_tests
Open

PlatformLC wants to merge 7 commits into
pytorch:mainfrom
PlatformLC:test/test_dtensor_pp_unit_tests

Conversation

@PlatformLC

@PlatformLC PlatformLC commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Refactor test_dtensor_pp_unit_tests.py with instantiate_device_type_tests and a hardware-classification label, so the multi-process TestDTensorPPUnitTests runs as per-device variants (including out-of-tree PrivateUse1 accelerators) instead of relying on module-level device/backend globals.

Changes

  • test/distributed/pipelining/test_dtensor_pp_unit_tests.py:
    • TestDTensorPPUnitTests now instantiates via instantiate_device_type_tests(..., except_for=["cpu"], allow_xpu=True) and is classified HardwareClassification.ACCELERATOR. The framework auto-discovers the registered PrivateUse1 backend and generates a per-device variant; previously the class was a plain MultiProcContinuousTest subclass with module-level device_type/backend globals, so it never produced a PrivateUse1 variant. The classification is metadata: it only filters tests when --hw-classification is passed; normal discovery/execution is unchanged.
    • Every test method takes the framework-injected device parameter and uses it: the per-rank device comes from rank_device = self._rank_device(device) (the injected device is the rank-0 primary device; each spawned worker rebinds it to its own rank), init_pg(rank_device) sets the device index, so the binding follows the same backend family the process group backend was derived from (rather than the process's current accelerator), and _make_mesh(device)derives the mesh's device type from the parameter.backend_strlikewise derives the per-device default backend from thedevice argument the framework passes (dist.get_default_backend_for_device); no self.device_type` reads remain.
    • Removed the module-level device_type/backend globals, the device/device_type properties they backed, and the @requires_accelerator_dist_backend(["nccl", "xccl"]) decorator on the _requires_multi_gpu helper — the backend availability check lives in MultiProcContinuousTest._ensure_processes_spawned via c10d.is_backend_available, so the decorator is redundant and its explicit list excluded PrivateUse1's backend. The helper's @skip_but_pass_in_sandcastle_if(not TEST_MULTIACCELERATOR, ...) skip gate is kept (its message loses the backend prefix along with the globals).
    • init_pg uses torch.accelerator.set_device_index (device-agnostic) instead of the old cuda-only branch.
  • tools/linter/adapters/test_linter_allowlist.json: dropped this file's entry; it is classified and passes the test linter rules.

Motivation

Part of the test-case refactoring initiative tracked in #185590, decoupling tests from hardcoded device assumptions so out-of-tree accelerators can run the suite. This file switches to instantiate_device_type_tests (per-device variants) and is classified so the suite can filter it by hardware category.

Notes

@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/192051

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

⚠️ 4 Awaiting Approval

As of commit 7003d6a with merge base 1c51a45 (image):

AWAITING APPROVAL - The following workflows need approval before CI can run:

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

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

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).
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).
@PlatformLC
PlatformLC force-pushed the test/test_dtensor_pp_unit_tests branch from b22e893 to 5699585 Compare August 7, 2026 08:50
@fffrog fffrog moved this to Backlog in PyTorch Test Refactoring Aug 7, 2026

@jishuangfeng jishuangfeng left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Clean refactoring. Migration to instantiate_device_type_tests is correct, _resolved_device_type() properly handles the PrivateUse1 subprocess case, and init_pg switching to the unified torch.accelerator API is sound. The device set extends from cuda/xpu to include PrivateUse1, which is reasonable.
LGTM.

li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Aug 10, 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 Aug 10, 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 Aug 10, 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 Aug 10, 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 Aug 10, 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 Aug 10, 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).
@PlatformLC
PlatformLC force-pushed the test/test_dtensor_pp_unit_tests branch from 8955c05 to 792aff3 Compare August 13, 2026 01:21
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Aug 13, 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).
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Aug 13, 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 Aug 13, 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 Aug 13, 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).

@jishuangfeng jishuangfeng left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Injects device param into all 19 ACCELERATOR methods; _rank_device(device) is equivalent to the removed @Property device; no residual self.device references. Behavior-preserving.
LGTM.

@jishuangfeng jishuangfeng left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code looks good. Good to merge. Replacing torch.cuda.set_device with torch.accelerator.set_device_index in init_pg is a correct generalization that also fixes the latent bug where XPU ranks never had set_device called. The removed @requires_accelerator_dist_backend is still backed by _ensure_processes_spawned for nccl/xccl — no regression. All 19 methods genuinely use the device param; no pure-logic method is misclassified into ACCELERATOR.
LGTM.

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
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Sep 10, 2026
…ice resolution

Addresses the /pr-review feedback on pytorch#192208:

1. `backend_str()` no longer falls back to the module-level
   `DISTRIBUTED_BACKEND` constant from `common_fsdp`. That constant is computed
   at import time from the host's TEST_CUDA/TEST_HPU/TEST_XPU flags, so on a
   mixed host it can return e.g. "nccl" for an HPU variant. Instead, a
   `ValueError` from `get_default_backend_for_device()` now raises a
   `unittest.SkipTest` naming the device, so a variant with no registered
   default collective backend is skipped rather than run on the wrong transport.

2. Drop `_resolved_device_type()` and its six call sites. Verified on Ascend NPU
   that `PrivateUse1TestBase.setUpClass` already resolves `device_type` from
   "privateuse1" to the backend name (e.g. "npu") before any test body runs, so
   the `privateuse1` branch was dead code. Call sites now read `self.device_type`
   directly.

3. Trim the base-class docstring and remove the cross-PR `pytorch#192051` reference.

4. Add missing `import unittest`.
li-lizhe added a commit to li-lizhe/pytorch that referenced this pull request Sep 10, 2026
…ice resolution

Addresses the /pr-review feedback on pytorch#192208:

1. `backend_str()` no longer falls back to the module-level
   `DISTRIBUTED_BACKEND` constant from `common_fsdp`. That constant is computed
   at import time from the host's TEST_CUDA/TEST_HPU/TEST_XPU flags, so on a
   mixed host it can return e.g. "nccl" for an HPU variant. Instead, a
   `ValueError` from `get_default_backend_for_device()` now raises a
   `unittest.SkipTest` naming the device, so a variant with no registered
   default collective backend is skipped rather than run on the wrong transport.

2. Drop `_resolved_device_type()` and its six call sites. Verified on Ascend NPU
   that `PrivateUse1TestBase.setUpClass` already resolves `device_type` from
   "privateuse1" to the backend name (e.g. "npu") before any test body runs, so
   the `privateuse1` branch was dead code. Call sites now read `self.device_type`
   directly.

3. Trim the base-class docstring and remove the cross-PR `pytorch#192051` reference.

4. Add missing `import unittest`.
@PlatformLC
PlatformLC marked this pull request as ready for review September 15, 2026 00:54
@liangel-02
liangel-02 requested a review from fffrog September 18, 2026 15:49
@liangel-02 liangel-02 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Sep 18, 2026
@PlatformLC

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "no-stale"

@pytorch-bot pytorch-bot Bot added the no-stale label Oct 19, 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).
…e_type_tests and add hw-classification in test_dtensor_pp_unit_tests

Enable TestDTensorPPUnitTests on out-of-tree PrivateUse1 accelerators
by switching it to
instantiate_device_type_tests(only_for=["cuda","xpu","privateuse1"],
allow_xpu=True); the framework auto-discovers the registered PrivateUse1
backend and generates a per-device variant.

Classify TestDTensorPPUnitTests as ACCELERATOR (device-exercising,
multi-process).

Drop @requires_accelerator_dist_backend from the _requires_multi_gpu
helper. The backend availability check is centralized in
MultiProcContinuousTest._ensure_processes_spawned via
c10d.is_backend_available (provided by pytorch#192044), making the decorator's
gate redundant.

Add a DTensorPPTestBase intermediate base holding backend_str. It is
defined on the base (not on TestDTensorPPUnitTests) so
instantiate_device_type_tests inherits rather than ports it -- a ported
classmethod is bound to the generic class and cannot see the generated
variant's device_type. backend_str delegates to a _resolved_device_type
helper that resolves the generic "privateuse1" token to the registered
backend name, since MultiProcContinuousTest subprocesses run tests without
calling setUpClass (where PrivateUse1TestBase would otherwise resolve it).

Switch init_pg to torch.accelerator.set_device_index and resolve the
device type per-variant in _make_mesh.

Test Plan:
```
python test/distributed/pipelining/test_dtensor_pp_unit_tests.py -v --hw-classification ACCELERATOR
```
--hw-classification ACCELERATOR selects the device-exercising tests;
--hw-classification GENERIC/CPU filter the ACCELERATOR class out (Ran 0).
…nit_tests ACCELERATOR methods

Per the ACCELERATOR classification rule from pytorch#190173 (instantiated methods
must take and use the framework-injected `device` param), add `device` to the
19 test methods and a `_rank_device(device)` helper that resolves the per-rank
`torch.device` from the injected primary device (`{type}:0`) and `self.rank`.
`init_pg` and `_make_dtensor` now take `device`; placement uses `rank_device`;
the per-variant `device` @Property (type derived from `cls.device_type`) is
removed. Behavior-preserving (the injected device type matches `cls.device_type`
per variant).

Test Plan:
  python test/distributed/pipelining/test_dtensor_pp_unit_tests.py -v --hw-classification ACCELERATOR
  # --hw-classification ACCELERATOR selects the tests; GENERIC/CPU filter them out (Ran 0)
… test_dtensor_pp_unit_tests

The device-param threading (prior commit) makes instantiate_test_helper
call _init_and_get_primary_device at class-construction time, whose
try/except fallback calls setUpClass; PrivateUse1TestBase.setUpClass
resolves cls.device_type to the concrete backend name, re-run in spawn
workers via module re-import. So _resolved_device_type's "privateuse1"
fallback is dead -- backend_str/_make_mesh read cls.device_type /
self.device_type directly. The module-level device_type/backend globals
were only used in the _requires_multi_gpu skip message; drop them and use
a plain string. Addresses review feedback.

Test Plan:
python test/distributed/pipelining/test_dtensor_pp_unit_tests.py -v
cls.device_type is concrete at the call sites; behavior unchanged.
…d_str(device) API

MultiProcContinuousTest.backend_str now receives the device argument from
the framework; accept it in the override.

Test Plan:
python3 tools/linter/adapters/test_linter.py test/distributed/pipelining/test_dtensor_pp_unit_tests.py
…er allowlist

The file is classified in this branch (single ACCELERATOR class with
instantiate_device_type_tests and device-parametrized test methods), so
it no longer needs the allowlist exemption.

Test Plan:
python3 tools/linter/adapters/test_linter.py test/distributed/pipelining/test_dtensor_pp_unit_tests.py
…ests

The intermediate base existed so backend_str stayed inherited: methods
copied from the generic class by instantiate_device_type_tests bind to
it, so a classmethod there could not see the generated class's
device_type. The framework now passes the device into backend_str, and
the override derives the device type from that argument, so the binding
no longer matters and the base has no remaining purpose.

Test Plan:
python3 tools/linter/adapters/test_linter.py test/distributed/pipelining/test_dtensor_pp_unit_tests.py
… _make_mesh

_make_mesh read self.device_type to pick the mesh's device; derive it
from the framework-injected device argument instead, so every helper in
the file (backend_str, _rank_device, _make_mesh) uniformly derives the
device type from the injected device parameter.

Test Plan:
python3 tools/linter/adapters/test_linter.py test/distributed/pipelining/test_dtensor_pp_unit_tests.py
@PlatformLC
PlatformLC force-pushed the test/test_dtensor_pp_unit_tests branch from 0ae2f38 to 7003d6a Compare December 2, 2026 07:47
@PlatformLC
PlatformLC force-pushed the test/test_dtensor_pp_unit_tests branch from 86e2938 to 7003d6a Compare December 2, 2026 08:17
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).
@skip_but_pass_in_sandcastle_if(
not TEST_MULTIACCELERATOR, f"{backend} test requires 4+ GPUs"
)
@skip_but_pass_in_sandcastle_if(not TEST_MULTIACCELERATOR, "Test requires 4+ GPUs")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I’d check the device count for each generated variant before starting its workers.

AI-assisted verification at 7003d6a9de. The decorator evaluates TEST_MULTIACCELERATOR at import time, using the process’s current accelerator. With NPU current, one simulated NPU and eight CUDA devices, all 19 CUDA cases were marked skipped. Swapping the counts admitted all 19 CUDA cases, and the fixture requested a one-rank NCCL run for the CUDA variant I traced. This decision is already made before the worker reaches the rank-binding code discussed in the other thread. Could the parent check the required count on the variant’s own device module and skip it there when that backend has too few devices?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hmm, any example for such check ?

This branch has not been deployed

No deployments
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. no-stale open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

Status: Backlog

Development

Successfully merging this pull request may close these issues.

5 participants