Skip to content

[Test Refactoring] Standardizing the definition format for device_type and backend_str for distributed test-related files - #205504

Closed
fffrog wants to merge 10 commits into
gh/fffrog/177/basefrom
gh/fffrog/177/head
Closed

fffrog wants to merge 10 commits into
gh/fffrog/177/basefrom
gh/fffrog/177/head

Conversation

@fffrog

@fffrog fffrog commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

This PR focuses on standardizing the usage of device_type and backend_str across distributed test-related files. This is a prerequisite for refactoring these files to use instantiate_device_type_tests.
In addition, none of the changes involve any logic modifications. They were made with the assistance of Claude Code.

Note:

All changes have been reviewed line by line by a human.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

The PR makes `MultiProcContinuousTest.device_type` (and the subclasses that
override it) a `property`, changes `backend_str(cls)` to `backend_str(cls,
device)` across the distributed test bases and tests, and replaces
`DTensorTestBase.backend` with a `backend_str` classmethod. Recommendation:
Approve. Every point the review raises is non-blocking, but it asks for the
multi-GPU distributed CI jobs to run before landing and for the PR description
to be updated.

Findings (8):

[minor] torch/testing/_internal/common_distributed.py:1904
Duplicated device resolution (non-blocking). `device = cls.device_type; if
isinstance(device, property): device = device.fget(cls)` appears nine times:
`common_distributed.py` at 1903, 1949, 2116 and 2309, plus
`test_ddp_hooks.py:66`, `test_schedule_multiproc.py:1960`,
`test_c10d_ops_nccl.py:78`, `test_c10d_nccl2.py:1492` and
`test_zero_redundancy_optimizer.py:97`. `test_c10d_window.py:52` calls
`.fget(cls)` with no guard. One classmethod helper next to `_get_world_size`
(`common_distributed.py:2066-2088`, which already uses `inspect.getattr_static`)
would replace all of them.

[minor] test/distributed/test_c10d_ops_nccl.py:73
Overrides ignore the new `device` argument (non-blocking), which works against
the stated goal of moving to `instantiate_device_type_tests`. These overrides
use module globals or `_get_device_type(cls.world_size)` instead:
`test_c10d_ops_nccl.py:73`, `test_fsdp_model_state.py:27`,
`test_fsdp_optim_state.py:58`, `test_hsdp_checkpoint.py:80`,
`test_state_dict_stager.py:1013`. `test_e2e_save_and_load.py:437` overwrites the
argument. In `test_zero_redundancy_optimizer.py`, the `device_type` property
(79-83) and the `device` property (85-87) return the same global, and `_init_pg`
resolves the device at 97-99 and then rebinds it at 103. Line 91 of that file
keeps a hand-written `{"cuda": "nccl", ...}` map instead of using
`dist.get_default_backend_for_device`.

[minor] torch/testing/_internal/distributed/_tensor/common_dtensor.py:710
Duplicate `backend_str` bodies (non-blocking).
`DTensorContinuousTestBase.backend_str` (`common_dtensor.py:709-711`) and
`DTensorTestBase.backend_str` (`:800-802`) are identical and could be defined
once in `DTensorTestMixin`. `DeviceTypeTestBase.distributed_backend`
(`common_device_type.py:542-549`) already does the same mapping for the
`instantiate_device_type_tests` classes this PR prepares for. The PR should say
how the two hooks will be reconciled.

[minor]
test/distributed/_composable/test_composability/test_2d_composability.py:430
Unused variable and unexplained deletions (non-blocking). `curr_backend` at
`test_2d_composability.py:73` is now unused. The deleted "need gloo for cpu
offload" `backend` overrides (classes at 430 and 671 at HEAD) were dead code on
`DTensorContinuousTestBase`, but the description doesn't say so.

[minor] test/distributed/tensor/test_dtensor_testbase.py:37
Test no longer exercises the real path (non-blocking).
`test_dtensor_testbase.py:35-39` and `:46-47` pass the instance property
`Fixture().device_type` into `backend_str`, which is now just
`get_default_backend_for_device(device)`. So the test only checks that
dictionary-style mapping. It does not cover the path the harness actually runs,
`Fixture.device_type.fget(Fixture)` (`common_distributed.py:2116-2121`). Use
that call in the test.

(3 more not shown, see the review run)

Reviewed commit: 351fc26 (NOT the current head a190441)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

⏳ No Failures, 2 Pending

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

🟡 GREEN LIGHT - PR was reverted - re-landing requires human review:

Green Light will not review this PR again, on this or any later commit; re-landing it needs a human approval.

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

@pytorch-bot pytorch-bot Bot added the ciflow/dtensor Run DTensor specific tests label Nov 18, 2026
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 18, 2026
@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Nov 18, 2026
@pytorch-bot pytorch-bot Bot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 18, 2026
[ghstack-poisoned]
[ghstack-poisoned]
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Nov 18, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

@github-actions
github-actions Bot dismissed stale reviews from themself November 18, 2026 15:00

Withdrawn: the automated review of 8d0e916 found nothing blocking.

[ghstack-poisoned]

@github-actions github-actions Bot left a comment

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.

Automated review of 351fc26: nothing blocking; ready for human review.

The PR makes MultiProcContinuousTest.device_type (and the subclasses that override it) a property, changes backend_str(cls) to backend_str(cls, device) across the distributed test bases and tests, and replaces DTensorTestBase.backend with a backend_str classmethod. Recommendation: Approve. Every point the review raises is non-blocking, but it asks for the multi-GPU distributed CI jobs to run before landing and for the PR description to be updated.

⚪ 8 non-blocking findings

if isinstance(device, property):

Duplicated device resolution (non-blocking). device = cls.device_type; if isinstance(device, property): device = device.fget(cls) appears nine times: common_distributed.py at 1903, 1949, 2116 and 2309, plus test_ddp_hooks.py:66, test_schedule_multiproc.py:1960, test_c10d_ops_nccl.py:78, test_c10d_nccl2.py:1492 and test_zero_redundancy_optimizer.py:97. test_c10d_window.py:52 calls .fget(cls) with no guard. One classmethod helper next to _get_world_size (common_distributed.py:2066-2088, which already uses inspect.getattr_static) would replace all of them.


def backend_str(cls, device) -> str:

Overrides ignore the new device argument (non-blocking), which works against the stated goal of moving to instantiate_device_type_tests. These overrides use module globals or _get_device_type(cls.world_size) instead: test_c10d_ops_nccl.py:73, test_fsdp_model_state.py:27, test_fsdp_optim_state.py:58, test_hsdp_checkpoint.py:80, test_state_dict_stager.py:1013. test_e2e_save_and_load.py:437 overwrites the argument. In test_zero_redundancy_optimizer.py, the device_type property (79-83) and the device property (85-87) return the same global, and _init_pg resolves the device at 97-99 and then rebinds it at 103. Line 91 of that file keeps a hand-written {"cuda": "nccl", ...} map instead of using dist.get_default_backend_for_device.


def backend_str(cls, device) -> str:

Duplicate backend_str bodies (non-blocking). DTensorContinuousTestBase.backend_str (common_dtensor.py:709-711) and DTensorTestBase.backend_str (:800-802) are identical and could be defined once in DTensorTestMixin. DeviceTypeTestBase.distributed_backend (common_device_type.py:542-549) already does the same mapping for the instantiate_device_type_tests classes this PR prepares for. The PR should say how the two hooks will be reconciled.


class TestFullyShard2DStateDict(DTensorContinuousTestBase):

Unused variable and unexplained deletions (non-blocking). curr_backend at test_2d_composability.py:73 is now unused. The deleted "need gloo for cpu offload" backend overrides (classes at 430 and 671 at HEAD) were dead code on DTensorContinuousTestBase, but the description doesn't say so.


Fixture.backend_str(Fixture().device_type),

Test no longer exercises the real path (non-blocking). test_dtensor_testbase.py:35-39 and :46-47 pass the instance property Fixture().device_type into backend_str, which is now just get_default_backend_for_device(device). So the test only checks that dictionary-style mapping. It does not cover the path the harness actually runs, Fixture.device_type.fget(Fixture) (common_distributed.py:2116-2121). Use that call in the test.


device_type = cls.device_type

Message regexes are newly enforced but not verified in CI (non-blocking). TestCase.assertRaisesRegex (common_utils.py:5475) skips the message check when self.device_type is not a native device. Before this PR, self.device_type was a bound classmethod, so every MultiProcContinuousTest and FSDPTestContinuous subclass silently skipped the check. Now it is "cuda", so the messages are checked. Two of those regexes depend on runtime behaviour: test_c10d_nccl2.py:1271 (NCCL (AllReduce|error)) and :2560 (does not support symmetric). The only CI label is ciflow/dtensor, so run the multi-GPU distributed jobs before landing. The description's claim that "no logic has been modified" is inaccurate and should be updated.


def backend_str(cls, device) -> str | None:

The new contract is undocumented (non-blocking). The backend_str docstring (common_distributed.py:1868-1874) doesn't describe device (a device-type string). The rule that a device_type override may read only class-level state, because it is evaluated as fget(cls), appears only in the comment at 2118-2120. The comment at 2112-2115 still calls the property form "legacy", although it is now the standard form.


def init_pg(self, eager_init, backend: str | None = None) -> None:

Old-style out-of-tree subclasses break (non-blocking; private API, potentially breaking). List these breaks in the PR description so out-of-tree backend maintainers can migrate: (1) init_pg (common_dtensor.py:804-806) silently ignores a DTensorTestBase subclass that still overrides backend. This is the worst case, because nothing fails. (2) A zero-argument backend_str(cls) override raises TypeError at common_distributed.py:1907, :1952 and :2128. (3) Because the classmethod branch was removed, an @ classmethod device_type override now reaches _get_world_size (:2124) and backend_str as a bound method.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

@fffrog fffrog changed the title [Test Refactoring] Standardizing the definition format for device_type and backend_str [Test Refactoring] Standardizing the definition format for device_type and backend_str for distribute-related test files. Nov 18, 2026
@fffrog fffrog changed the title [Test Refactoring] Standardizing the definition format for device_type and backend_str for distribute-related test files. [Test Refactoring] Standardizing the definition format for device_type and backend_str for distributed test-related files Nov 18, 2026
@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 18, 2026
@izaitsevfb

Copy link
Copy Markdown
Contributor

✴️ iz2: (AI-generated)
@pytorchbot revert -m "Land race with D132952445 (export #205548): both change test/distributed/test_c10d_nccl2.py, so neither the export nor this PR's internal import applies. Reverting so the export can merge; this PR needs a rebase and reland." -c landrace

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a revert job. Check the current status here.
Questions? Feedback? Please reach out to the PyTorch DevX Team

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@fffrog your PR has been successfully reverted.

pytorchmergebot added a commit that referenced this pull request Nov 20, 2026
…evice_type` and `backend_str` for distributed test-related files (#205504)"

This reverts commit 9e983c5.

Reverted #205504 on behalf of https://github.com/izaitsevfb due to Land race with D132952445 (export #205548): both change test/distributed/test_c10d_nccl2.py, so neither the export nor this PR's internal import applies. Reverting so the export can merge; this PR needs a rebase and reland. ([comment](#205504 (comment)))
@izaitsevfb

Copy link
Copy Markdown
Contributor

✴️ iz2: (AI-generated) @fffrog sorry for the churn: this was reverted for a land race, not a test failure. A Meta-internal change (#205548) landed at the same time and moved ProcessGroupNCCLLegacyCommPtrTest and ProcessGroupNCCLLegacyNonblockingTest out of test/distributed/test_c10d_nccl2.py, and this PR edits both classes, so neither change applied on top of the other. Once #205548 is on main, could you rebase onto it and reland? After the rebase this PR no longer needs to touch those two classes.

@fffrog

fffrog commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

@izaitsevfb

Sure, thank you for detailed explanation, and I will try to land this PR again bacause the #205548 was on main already.

@fffrog fffrog moved this from Done to Ready for Merge in PyTorch Test Refactoring Nov 22, 2026
[ghstack-poisoned]
@fffrog

fffrog commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

Well, hopefully there won’t be any merge conflicts this time.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@github-project-automation github-project-automation Bot moved this from Ready for Merge to Done in PyTorch Test Refactoring Nov 22, 2026
acisseJZhong added a commit to pytorch/torchtitan that referenced this pull request Nov 24, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

Fix failing CI test.

## Agent details (AI-generated, to be reviewed by @acisseJZhong)

> AI-generated by an AI agent on behalf of @acisseJZhong.
>
> **Why.** [GPU Unit
Tests](https://github.com/pytorch/torchtitan/actions/workflows/unit_test_gpu.yaml?query=branch%3Amain)
has failed on main since 2026-11-23, in two multi-GPU tests:
>
> | Test | Failure | Cause |
> | --- | --- | --- |
> |
`TestDistMuonCpuOffload::test_accelerator_ns_device_matches_gpu_resident_run`
| `No backend type associated with device type cpu` |
pytorch/pytorch#205504 (nightlies from 2026-11-23) renamed the
`DTensorTestBase` backend hook from `backend` to `backend_str`. The
test's `backend` property is now ignored, so the PG is NCCL-only and the
CPU `all_gather` in `_validate_bucket_plans_across_ranks` fails. First
red run (#6285) has no DistMuon change. |
> | `TestAdamCPUOffloadedMoments::test_rounded_pinned_memory_raises`
(new in #5881) | 300 s timeout | The first `_build` result is dropped,
so its exact-size pinned blocks can go back to the host allocator cache
and get reused by the second build, which then sees no rounding and does
not raise. When this happens on one rank only (rank 0 locally:
`AssertionError: ValueError not raised`), the other rank waits in
`destroy_pg`'s barrier and the test hangs. |
>
> **What changed.** Test-only:
> - `test_dist_muon.py`: pass the backend through
`@with_comms(backend="cpu:gloo,cuda:nccl")`, which works with PyTorch
before and after #205504, instead of overriding the hook.
> - `test_adam_cpu_offloaded_moments.py`: keep the first build alive so
the second build has to allocate new, rounded blocks.
>
> **Testing** (torch 2.16.0.dev20261123+cu132, 2x H100):
> ```
> pytest
tests/unit_tests/gpu/components/optim/test_adam_cpu_offloaded_moments.py
\
>
"tests/unit_tests/gpu/distributed/flex_shard/test_dist_muon.py::TestDistMuonCpuOffload"
> ```
> Before: both tests fail (the Adam test hung in 3/3 runs). After: 4
passed in 5/5 runs.
> `pytest tests/unit_tests/gpu -m multi_gpu` on 8x H100: these two pass.
The 5 other local failures are unrelated: they need FA3
(`flash_attn_interface`), which is not installed locally and not
selected on the A10G CI runners.
>
> **Not changed.** Several CPU tests still override `backend` (returning
`"gloo"`). Those overrides are now dead code, but they don't change
behavior on CPU runners, so they are left for a separate cleanup.
zhaiyaxing001 added a commit to zhaiyaxing001/pytorch that referenced this pull request Nov 27, 2026
 base API (backend_str(device), device_type property), drop main-removed C10dTorchCommsTestBase
zhaiyaxing001 added a commit to zhaiyaxing001/pytorch that referenced this pull request Nov 27, 2026
…e API, drop main-removed C10dTorchCommsTestBase
zhaiyaxing001 added a commit to zhaiyaxing001/pytorch that referenced this pull request Dec 3, 2026
…conflict

The bot rebase onto viable/strict hit a content conflict when replaying the first PR commit over upstream changes to test_replicate_with_fsdp.py and common_distributed.py. Merging main (5cda694) resolves it as a whole-branch three-way merge: common_distributed.py only takes the upstream symm-mem ROCm arch tweak, and the MultiProcContinuousForInstantiateTest class kept from pytorch#195000 (closed without merge) stays compatible with the upstream MultiProcContinuousTest base, whose backend_str now takes the device argument per pytorch#205504.
zhaiyaxing001 added a commit to zhaiyaxing001/pytorch that referenced this pull request Dec 3, 2026
… rationale

pytorch#195000 closed in favor of pytorch#205504: main's MultiProcContinuousTest already normalizes device_type across the forms instantiate_device_type_tests injects and calls backend_str(cls, device), so the bridging subclass is redundant. Test classes now inherit the upstream base directly and override backend_str in the standardized per-class form, resolving the deterministic backend with dist.get_default_backend_for_device. The zero-caller current_device property is dropped with the subclass, leaving torch/testing/_internal/common_distributed.py identical to main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triaged This is a label only to be used by the auto triage bot ci-no-td Do not run TD on this PR ciflow/dtensor Run DTensor specific tests ciflow/trunk Trigger trunk jobs on your pull request GL/superseded GreenLight review is superseded by changes Merged open source ready for review Automated review passed, ready for a final review by a maintainer. release notes: distributed (checkpoint) release notes: distributed (fsdp) release notes category Reverted triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

5 participants