Skip to content

[Testcase Refactoring] Migrate test_fsdp_tp_integration to device-agnostic collection and hw-classification - #192208

Open
li-lizhe wants to merge 6 commits into
pytorch:mainfrom
li-lizhe:testcase-refactor-fsdp-tp-integration
Open

li-lizhe wants to merge 6 commits into
pytorch:mainfrom
li-lizhe:testcase-refactor-fsdp-tp-integration

Conversation

@li-lizhe

@li-lizhe li-lizhe commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

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

Changes

  • Introduce TPFSDPIntegrationTestBase(FSDPTestContinuous) holding _resolved_device_type() (resolves the generic privateuse1 token to the registered backend name), backend_str (via dist.get_default_backend_for_device, resolving each device to its registered default backend without hardcoding), and an accelerator-aware world_size property. Follows the existing intermediate-base pattern used elsewhere in the testcase-refactoring series.
  • Tag the class hw_classification = HardwareClassification.ACCELERATOR — all three methods exercise multi-device FSDP x TP collectives on an accelerator.
  • Replace @skip_if_lt_x_gpu(4) with @requires_world_size(4).
  • Remove the module-level device_type global; its 6 call sites use self._resolved_device_type(). The nested TestModel captures the resolved device via closure (its self is the nn.Module, not the test instance).
  • Drop instantiate_parametrized_tests for instantiate_device_type_tests(except_for="cpu", allow_xpu=True) so the framework generates per-device variants for every accelerator (cuda/hpu/xpu/privateuse1) and auto-discovers registered PrivateUse1 backends.

Motivation

skip_if_lt_x_gpu and common_fsdp's DEVICE_TYPE / DEVICE_COUNT / DISTRIBUTED_BACKEND globals only recognize cuda/hpu/xpu, so on any other accelerator backend these tests were silently skipped (or required hacking the framework globals to run). instantiate_device_type_tests + _resolved_device_type make the test device-agnostic so out-of-tree PrivateUse1 backends are picked up automatically.

Capability gating

The @requires_capabilities(...) gates are deliberately not part of this revision. The
capability-gate mechanism is still being settled upstream, and referencing its namespace here
would make this file fail to import on main. The change is otherwise complete: the
device-agnostic base, the accelerator-aware world_size/backend_str, the
except_for="cpu" instantiation, and the HardwareClassification.ACCELERATOR tag are all in
place. Once the mechanism lands, the gates can be
added as a small follow-up on top of this file (one decorator per test, no other edit), so
nothing here needs to be reverted for that.

Test Plan

Device-agnostic collection verified on 2x Ascend 910B4 (torch 2.15.0.dev, torch_npu same build):
instantiate_device_type_tests(..., except_for="cpu") generates TestTPFSDPIntegrationPRIVATEUSE1
and all three methods are discovered and executed, instead of the pre-change behaviour where
instantiate_parametrized_tests produced no accelerator variant at all.

Note on the host used: its installed torch build predates the requires_world_size
hardware-agnostic generalization now on main, so that decorator still read
torch.cuda.device_count() (0 on this host) and skipped the tests. Restoring the current main
semantics for that one line was enough for the tests to be discovered and executed.

Related

Part of #185590.


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

@pytorch-bot

pytorch-bot Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⚠️ 4 Awaiting Approval

As of commit 6e9d185 with merge base a868b61 (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 5, 2026
@linux-foundation-easycla

linux-foundation-easycla Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

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

  • ✅ login: li-lizhe / name: lizhe.li (e0a07eb)

@li-lizhe
li-lizhe force-pushed the testcase-refactor-fsdp-tp-integration branch from 5629bd6 to e0a07eb Compare August 5, 2026 09:39
@li-lizhe
li-lizhe marked this pull request as draft August 5, 2026 09:44
@li-lizhe
li-lizhe force-pushed the testcase-refactor-fsdp-tp-integration branch from e0a07eb to f9491a2 Compare August 6, 2026 01:42
@li-lizhe

li-lizhe commented Aug 6, 2026

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 6, 2026
@fffrog fffrog moved this to Backlog in PyTorch Test Refactoring Aug 7, 2026
@li-lizhe
li-lizhe marked this pull request as ready for review August 10, 2026 02:07
@zou3519 zou3519 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 10, 2026
@li-lizhe
li-lizhe force-pushed the testcase-refactor-fsdp-tp-integration branch from f9491a2 to 7b01c96 Compare August 13, 2026 03:33
instantiate_device_type_tests(
TestTPFSDPIntegration,
globals(),
except_for="cpu",

@jialinw77 jialinw77 Aug 15, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The original device_type in this file is defined as:

device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu"

which means current test class could work on cpu device. So please confirm again whether we should exclude cpu here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

device_type in current test class mainly used in init_device_mesh, and device mesh supprots cpu device.


@property
def world_size(self) -> int:
return min(4, _get_device_module(self.device_type).device_count())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

In original logic, world_size whose value is DEVICE_COUNT is defined as min(4, max(2, torch.cuda.device_count())) only for ROCM device. So please check whether is right to always return min(4, _get_device_module(self.device_type).device_count()).

@li-lizhe

li-lizhe commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review! Pushed f9742ddd addressing both points.

1. world_size clamp (L119)

Got it — looked back at the original implementation and the clamp is now dropped. The min(4, ...) only ever lived in the ROCm branch, and that branch is dead code: in common_fsdp.py, if TEST_WITH_ROCM: DEVICE_COUNT = min(4, max(2, torch.cuda.device_count())) (L72) is immediately overwritten by the subsequent if TEST_CUDA: DEVICE_COUNT = torch.cuda.device_count() block (L79), and TEST_CUDA = torch.cuda.is_available() is true on ROCm (HIP runs through the cuda compat surface). So the original test already ran cuda/ROCm at full device_count(), and the uniform min(4, _get_device_module(...).device_count()) I had added was actually a regression clamping them back down to 4. world_size now returns _get_device_module(self.device_type).device_count(), restoring the original per-device semantics (cuda/ROCm/XPU full count). @requires_world_size(4) stays as the floor gate.

2. except_for="cpu" (L534)

Removed. The CPU variant is now generated (not excluded) and skipped at runtime by @requires_capabilities(Capability.distributed.backend, .dtensor, .fsdp) (CPUTestBase in #191919 declares distributed.fsdp as False). The multiprocess harness already propagates SkipTest cleanly on main. Verified on CPU: the test class is generated and the case skips cleanly.

@li-lizhe
li-lizhe force-pushed the testcase-refactor-fsdp-tp-integration branch from 5d95581 to 73751a9 Compare August 17, 2026 14:54
kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Aug 20, 2026
@@ -477,7 +532,12 @@ def assert_local_shard_across_ranks(local_tensor, group, check_equal=True):
assert_local_shard_across_ranks(local_buf, dp_group, check_equal=True)


instantiate_parametrized_tests(TestTPFSDPIntegration)
instantiate_device_type_tests(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The test method has annotation of requires_world_size, we need except cpu in instantiate_device_type_tests.

@li-lizhe li-lizhe Aug 25, 2026 •

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.

Done — added except_for="cpu" in commit 087146a, consistent with the other migrated files in this series. The CPU variants are no longer instantiated.

kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Aug 26, 2026
@li-lizhe

li-lizhe commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review! Replying to each point below.

1. Capability.distributed namespace (Minor)

Capability / requires_capabilities come from #190846, and the distributed namespace from #191919 — both listed under Dependencies, and this PR only lands after they do (as noted in the PR description). With the dependency patches applied, the file runs end-to-end (verified on a 4-card accelerator host).

2. @requires_world_size(4) on XPU (Major)

Addressed by dependency #192694 (listed under Dependencies): it generalizes the device count from torch.cuda.device_count() to torch.accelerator, so non-CUDA variants are no longer skipped. Verified with #192694 applied: the gate passes and all 3 tests run.

3. Unused device params in the test_fsdp_tp_* methods (Minor) — kept for signature uniformity

instantiate_device_type_tests injects device into every method that declares it, and all device-generic tests in these files keep that standard signature, so the param stays. The body deliberately ignores it in favor of self._resolved_device_type() / self.rank: the pre-refactor code used the index-less module-level device_type = torch.device(get_devtype()), while the injected device can carry a primary-device index (e.g. cuda:0), so resolving the device type in the body preserves the old behavior.

@can-gaa-hou

Copy link
Copy Markdown
Collaborator

@claude review this pr with pr review skill

@claude

claude Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Claude finished @can-gaa-hou's task in 23m 38s —— View job


Reviewed with the /pr-review skill — the migration is structurally right, but the backend_str fallback can hand the wrong collective backend to init_process_group, and as written the file cannot import on current main.

Full PR review — #192208

PR Review: #192208

Summary

Migrates TestTPFSDPIntegration from skip_if_lt_x_gpu + a module-level device_type global to capability gating plus instantiate_device_type_tests, via a new TPFSDPIntegrationTestBase. One correctness defect in backend_str, one landing-order hazard that makes the new gates inert on non-CUDA hosts, and some avoidable indirection.

Infrastructure

1. backend_str()'s except ValueError fallback is device-blind and can select the wrong transport — test_fsdp_tp_integration.py:113-122

except ValueError:
    return DISTRIBUTED_BACKEND

DISTRIBUTED_BACKEND is a module-level constant in common_fsdp.py:76-90, computed once at import time from an if TEST_CUDA / elif TEST_HPU / elif TEST_XPU / else chain. It is a function of what the host has, not of cls.device_type — so it cannot be a correct fallback for a per-device generated class:

  • Backend.default_device_backend_map (distributed_c10d.py:507-512) holds only cpu/cuda/xpu/mps, so get_default_backend_for_device("hpu") raises ValueError and the fallback fires. On a host with both CUDA and HPU, TEST_CUDA wins the if chain, so DISTRIBUTED_BACKEND == "nccl" and the generated ...HPU class initializes an NCCL process group. The inline comment's claim that this yields "hccl" on HPU only holds when CUDA is absent.
  • On a PrivateUse1-only host whose vendor has not registered a default backend, all three TEST_* flags are false, so the fallback silently returns "gloo" for an accelerator variant.

This is not a clean skip: the return value flows to dist.init_process_group(backend=...) via _init_pg, so collectives run on the wrong transport (or fail with an opaque init error) instead of the suite reporting "no backend registered for this device". Since the whole point of this PR is to stop leaning on common_fsdp's host-global triple, importing DISTRIBUTED_BACKEND reintroduces exactly the coupling being removed. Prefer letting the ValueError propagate as a unittest.SkipTest naming the device, or resolving the fallback from cls.device_type rather than from a global. Fix this →

2. The file cannot import on current main, and the new gates are inert on non-CUDA accelerators

Capability and requires_capabilities do not exist anywhere under torch/ in this checkout — the from torch.testing._internal.common_device_type import Capability, ..., requires_capabilities at lines 28-32 is an ImportError today, so the file collects as zero tests. The PR body documents this and keeps the PR in draft, which is the right call; flagging it because it means CI cannot validate any of this, and the only end-to-end evidence is a hand-adapted out-of-tree run.

Compounding it: requires_world_size does exist (common_distributed.py:338-357) but still gates on torch.cuda.device_count(). So once the Capability dependencies land but #192694 has not, every generated variant on an XPU / HPU / PrivateUse1 host skips with requires 4 GPUs, found 0. @skip_if_lt_x_gpu(4) at least consulted common_fsdp's device-count global. Please make #192694 land before or with this PR rather than after, otherwise the migration ships as dead tests on exactly the backends it is meant to enable.

Separately, @requires_world_size(4) is only a skip gate here — nothing in MultiProcContinuousTest reads _required_world_size (the sole consumer of get_required_world_size is test/distributed/test_c10d_nccl.py:384). The spawned rank count comes entirely from the world_size property. That matches pre-refactor behavior, but the decorator's own docstring ("the test harness can read this attribute to set the number of ranks to spawn") does not apply on this code path, so don't rely on it as anything but a floor.

Code Quality

3. _resolved_device_type()'s privateuse1 branch looks like dead code — lines 106-111

PrivateUse1TestBase.setUpClass already does the same resolution (common_device_type.py:902):

cls.device_type = torch._C._get_privateuse1_backend_name()

instantiate_device_type_tests wires that into the generated class's setUpClass at common_device_type.py:1135, and the generated class carries no device_type of its own, so it inherits the resolved name. _ensure_processes_spawned — and therefore every test body — runs from setUp (common_distributed.py:2138), strictly after setUpClass. By the time any of the six call sites execute, cls.device_type is already "openreg"/"npu"/etc. and dt == "privateuse1" is never true.

If that holds, the helper and its six call sites are pure indirection and self.device_type reads correctly on its own. Worth confirming on the validation host before removing, since it is the load-bearing assumption of the whole base class. (Moderate confidence — reasoning is from the setup ordering above, not from an executed run.)

4. world_size reads raw self.device_type while every other site reads self._resolved_device_type() — line 124-126

@property
def world_size(self) -> int:
    return _get_device_module(self.device_type).device_count()

Given #3 this is currently fine, but it is the one place that would break loudly (_get_device_module raises RuntimeError on an unknown token, torch/_utils.py:1026-1033) if the resolution ordering ever changed. Pick one accessor and use it everywhere: either both raw, or both resolved. Also consider torch.get_device_module — _get_world_size in the base already uses the public spelling (common_distributed.py:2033), and _get_device_module is lru_cached on a mutable-ish device string.

5. The injected device argument is discarded in all three tests — lines 282, 416, 479

The prior discussion settled on keeping the parameter for signature uniformity, which is fine. But the body then re-derives what the framework already computed; torch.device(device).type gives the index-free device type directly and is what the "an injected device may carry an index" objection actually calls for. Using it would also shrink the surface described in #3.

6. Base-class docstring — lines 92-102

Eleven lines of docstring for a three-member class, and it hard-codes PR #192051 / a comparison to DTensorPPTestBase. Per CLAUDE.md, comments should carry non-obvious global context; cross-PR references rot as soon as that PR merges and is renamed. Trim to the one genuinely non-local fact (why the hooks are overridden at all) and drop the PR number.

Note that this class also stays in globals() after instantiate_device_type_tests deletes the template (common_device_type.py:1108), so unittest collects it as a zero-test TestCase. Harmless today only because it has no test_* methods — if one is ever added to the base, its self.device_type resolves to FSDPTestContinuous.device_type, which is a @classmethod (common_fsdp.py:1623-1625), and _get_device_module(<bound method>) would raise.

Testing

No new coverage is expected for a refactor, and the three test bodies are behavior-preserving. The gap is verification rather than test count: with Capability absent from main, nothing in CI exercises this file, and the recorded validation ran against a manually back-ported foundation on a non-main base. Once the dependencies land, please re-run on a 4-GPU CUDA runner and post the generated class list, so it is on record that TestTPFSDPIntegrationCUDA is actually collected rather than silently filtered by except_for / hw_classification.

Recommendation

Request Changes

Finding 1 is a real correctness defect and should be fixed regardless of landing order. Finding 2 is a sequencing constraint: merging before #192694 converts three CUDA-only tests into three tests that skip everywhere except CUDA, which is a net coverage loss versus skip_if_lt_x_gpu. Findings 3-6 are cleanups that would meaningfully shrink the diff.

· branch `testcase-refactor-fsdp-tp-integration`

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

li-lizhe commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @can-gaa-hou — all feedback is now addressed in commit cc5306e. Point-by-point:

Finding 1 — backend_str() fallback (correctness): agreed, fixed.
Removed the DISTRIBUTED_BACKEND fallback entirely. backend_str() now:

@classmethod
def backend_str(cls) -> str:
    try:
        return dist.get_default_backend_for_device(cls.device_type)
    except ValueError as e:
        raise unittest.SkipTest(
            f"no default distributed backend registered for device {cls.device_type}: {e}"
        ) from e

A ValueError now surfaces as a unittest.SkipTest naming the device, instead of silently returning a host-global backend that may be the wrong transport on a mixed host. The DISTRIBUTED_BACKEND import is dropped.

Finding 2 — dependency ordering: acknowledged. The PR body already documents that Capability/requires_capabilities and the requires_world_size generalization must land first. I confirmed Capability now exists on main (it imports successfully on our checkout), and the plan remains to land this after #192694.

Finding 3 — _resolved_device_type() dead code: confirmed and removed.
Verified on a PrivateUse1 accelerator host (torch 2.14 + vendor extension): PrivateUse1TestBase.setUpClass (common_device_type.py:1156) resolves cls.device_type from "privateuse1" to the vendor backend name via torch._C._get_privateuse1_backend_name() before any setUp/test body runs. So the dt == "privateuse1" branch was unreachable. Removed the helper and its six call sites; they now read self.device_type directly. <<<

Finding 4 — world_size accessor consistency: resolved as part of finding 3 — everything now reads self.device_type uniformly (no mixed accessor).

Finding 5 — discarded device parameter: keeping it for signature uniformity, as settled in the earlier discussion; the bodies still resolve the device type from self.device_type which carries the correct per-variant value.

Finding 6 — base-class docstring: trimmed from eleven lines to the one non-local fact (why the intermediate base holds backend_str), and dropped the #192051 cross-reference.

Verification: on a PrivateUse1 accelerator host, get_default_backend_for_device(<device>) resolves to the backend registered by the vendor extension, so that variant initializes its own process group instead of skipping; cuda→nccl, cpu→gloo unchanged. The file parses cleanly. Once the capability-gating dependencies are on main, this should collect the generated classes correctly. <<<

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
li-lizhe force-pushed the testcase-refactor-fsdp-tp-integration branch from cc5306e to 54b6c46 Compare September 10, 2026 07:08
@li-lizhe

Copy link
Copy Markdown
Contributor Author

Update on commit 54b6c46 — I reconsidered direction: kept _resolved_device_type() and unified all call sites to use it, rather than removing it.

Rationale: Finding 3 confirmed the privateuse1 branch is dead code on any host where setUpClass runs, but _resolved_device_type() is still a useful safety layer and the more conservative direction given claude's "moderate confidence" qualifier. Now:

  • backend_str() — uses cls._resolved_device_type() ✅
  • world_size — uses self._resolved_device_type() (was the one site reading raw self.device_type) ✅
  • All 5 call sites in test bodies — use self._resolved_device_type() ✅

The DISTRIBUTED_BACKEND fallback is still replaced with unittest.SkipTest (Finding 1), and the other cleanups (docstring, import) are unchanged.

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
@li-lizhe
li-lizhe force-pushed the testcase-refactor-fsdp-tp-integration branch from 66d3dce to 6336a8b Compare October 21, 2026 03:11
@li-lizhe li-lizhe changed the title [Testcase Refactoring] Migrate test_fsdp_tp_integration.py to capability gating and hw-classification [Testcase Refactoring] Migrate test_fsdp_tp_integration to device-agnostic collection and hw-classification Oct 21, 2026
@li-lizhe

Copy link
Copy Markdown
Contributor Author

@weifengpy @fduwjj It’s been a few days since this PR was opened. Could you please take a look when you have time?

return dt

@classmethod
def backend_str(cls) -> str:

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 like this override to accept the device argument that the current test harness passes when it starts the workers.

AI-assisted review. I tested the clean merge of afc9d37aed with main at accceec6ad. The shared fixture calls cls.backend_str(device), but this override takes only cls. All three FSDP/TP tests raised TypeError before spawning a worker in a controlled four-device setup. The PR head with its original fixture and main on its own both reached the spawn request. Could the override accept device and use it when choosing the backend?

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.

Thanks for catching the harness signature mismatch. backend_str now accepts the device argument supplied by the harness and uses it when selecting the default backend.

li-lizhe and others added 5 commits December 2, 2026 17:15
…agnostic collection

Rebuild the change on top of current main, which added the cached _get_dp_tp_mesh
helper to this file, and drop the capability-gate reference that is not on main yet.

Keeps: the device-agnostic base, the accelerator-aware world_size / backend_str,
the HardwareClassification.ACCELERATOR tag, and instantiate_device_type_tests
(except_for="cpu") so non-CUDA accelerator variants are generated.
…ration

- Move hw_classification onto the class that defines the test methods;
  the linter only reads that class body, so the copy on the intermediate
  base was invisible (TEST_LINTER [hw_classification]).
- Derive the device type from the collected `device` parameter so the tests
  use the device they are handed (ACCELERATOR rule).
- Drop the file from test_linter_allowlist.json, as REVIEW.md Rule 7 asks.
_get_dp_tp_mesh now takes the device type instead of reading it off the
class, so every test that builds the mesh exercises the device it is
handed. The mesh is still built once and cached, preserving the /dev/shm
budget fix from pytorch#200632.

The cached mesh keeps this honest only because all variants of this class
target one device type per run; the type assertion is implicit in the
call.
``MultiProcessTestCase.backend_str`` takes ``device`` and the fixtures call it
as ``cls.backend_str(device_type)``. The override here declared only ``cls``,
so every device variant raised ``TypeError`` before the workers were spawned.
Accept the argument and use it to pick the backend.
Resolve backend and rank devices from the instantiated variant rather than
using the host-default accelerator. Use the injected device for FSDP
initialization and model construction.

Test Plan:

```
lintrunner -a --take TEST_LINTER,RUFF,PYFMT,FLAKE8,NEWLINE,TABS,SPACES <target> tools/linter/adapters/test_linter_allowlist.json
```

A5x NPU tests passed for this PR (torch 2.16 + torch_npu 2.16,
with main's backend_str(device) fixture contract).

Authored with the assistance of an AI assistant (Claude Code).
@li-lizhe
li-lizhe force-pushed the testcase-refactor-fsdp-tp-integration branch from 2e36292 to bf31750 Compare December 2, 2026 12:00
DeviceTypeTestBase already resolves PrivateUse1 for instantiated variants. Keep the variant-specific backend and rank initialization, and remove stale base-class documentation.

Test Plan:

lintrunner -a --take TEST_LINTER,RUFF,PYFMT,FLAKE8,NEWLINE,TABS,SPACES test/distributed/fsdp/test_fsdp_tp_integration.py tools/linter/adapters/test_linter_allowlist.json
A5x torch 2.16 + torch_npu 2.16 compatibility run of the NPU variant.

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

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

7 participants