Skip to content

[Testcase Refactoring] Split test_fake_pg by hardware dependency and label classes - #194716

Open
twthighd wants to merge 4 commits into
pytorch:mainfrom
twthighd:test/decouple-test_fake_pg
Open

twthighd wants to merge 4 commits into
pytorch:mainfrom
twthighd:test/decouple-test_fake_pg

Conversation

@twthighd

@twthighd twthighd commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Split the mixed TestFakePG class in test/distributed/test_fake_pg.py by hardware dependency: the fake-PG mechanism tests (copy semantics, requires_grad propagation, validation errors, dispatch tracing, compile-sync interactions) stay in TestFakePG labeled GENERIC, while the nine accelerator-path tests (FSDP/TP e2e, functional-collectives tracing, split_group) move to a new TestFakePGDevice labeled ACCELERATOR and are instantiated via instantiate_device_type_tests, replacing the module-level device resolution and the HAS_ACCELERATOR enumeration gate.

Changes

  • test/distributed/test_fake_pg.py:
    • TestFakePG (GENERIC, 68 fake-PG mechanism tests): keeps @instantiate_parametrized_tests, now labeled hw_classification = HardwareClassification.GENERIC.
    • New TestFakePGDevice (ACCELERATOR, 9 methods: test_construct_fsdp, test_fsdp_fake_e2e, test_fake_pg_tracing, test_fsdp_tp_fake_e2e, and the five test_split_group* tests): hw_classification = HardwareClassification.ACCELERATOR + instantiate_device_type_tests(TestFakePGDevice, globals(), allow_xpu=True). Every moved method takes the injected device parameter and consumes it: tensor and module placement use device=device, and the type-only forms derive the type from it via torch.device(device).type — device_id=torch.device(torch.device(device).type, 0), the per-rank device strings in test_split_group, the backend-filter assertion, and the init_device_mesh/_get_backend arguments. No self.device_type remains in the file; the module-level device_type = get_devtype().type global is deleted. @skipIfHpu blacklist guards are kept as-is.
    • Gating: the nine dropped @unittest.skipIf(not HAS_ACCELERATOR, "No accelerator") guards are replaced by nine bare method-level @onlyAccelerator decorators. The CPU variant stays collected on every host and skips with the explicit reason onlyAccelerator: doesn't run on CPU or meta devices (the guard is evaluated per device variant), instead of the variant being invisible on CPU-only machines; accelerator variants run unchanged. This stops relying on HAS_ACCELERATOR = TEST_CUDA or TEST_HPU or TEST_XPU, an enumeration that excludes out-of-tree accelerators, and matches the gating form of the landed [Testcase Refactoring] Label test_fsdp_freezing_weights ACCELERATOR and switch to device-type instantiation #192712 and [Testcase Refactoring] Add hw_classification and split device-dependent test in test_multi_threaded_pg #191905.
    • allow_xpu=True restores the XPU variant: the pre-split code resolved the current accelerator dynamically, so XPU hosts ran these nine tests; without the flag XPUTestBase never enters the base set and the variant would silently not be generated (0 collected instead of 15 expanded cases).
    • Rebase absorption: [dynamo] Build the compile sync group on the fake backend over a fake world #202253's six compile-sync methods stay in the GENERIC TestFakePG (14 expanded cases, parametrizations and gloo availability guards intact — their config strings naming cuda/nccl do not exercise device-tensor paths); [c10d] Move FakeProcessGroup from C++ to a Python PyBackend #202141's whole-file adjustments are kept (fake backend moved to a Python PyBackend, new GENERIC debug-wrapper/alias/split-options tests, updated assertion patterns). The unittest/unittest.mock imports those absorbed tests use are kept; HAS_ACCELERATOR/get_devtype and the module-level device_type are removed.
  • torch/distributed/_backends/fake.py: _register_fake_backend registers the fake backend with the four built-in device types and then appends the loaded PrivateUse1 device type to the fake backend's device capability, so the device is covered by backend="fake" groups without "fake" becoming its default backend in Backend.default_device_backend_map.
  • tools/linter/adapters/test_linter_allowlist.json: removed the single test/distributed/test_fake_pg.py entry — this PR migrates that file to the linter's requirements.

Motivation

TestFakePG was a mixed class: the mechanism tests exercise fake-PG behavior that is device-agnostic (CPU tensors, single-process fake process group — copy semantics, autograd safety, error validation), while 9 tests place parameters and collectives on the current accelerator. A mixed class cannot be labeled correctly, and the 9 accelerator tests were gated by HAS_ACCELERATOR, a hard-coded TEST_CUDA or TEST_HPU or TEST_XPU enumeration — so on an out-of-tree accelerator (PrivateUse1) that registers via Backend.register_backend, all nine were silently skipped even with 8 devices available: zero coverage of the FSDP/TP/split_group paths on those backends.

Under the split, the mechanism tests run everywhere (GENERIC), and the accelerator tests run on every accelerator variant the framework generates — including out-of-tree backends — with admission expressed by the variant-aware @onlyAccelerator guard rather than a device-name enumeration, and with the CPU variant explicitly visible as skips instead of absent.

Fake backend device list. torch/distributed/_backends/fake.py registers the fake backend with ["cpu", "cuda", "hpu", "xpu"] and, when hasattr(torch, privateuse1) is true, appends the loaded out-of-tree backend's device type to the fake backend's device capability (Backend.backend_capability["fake"]). BackendConfig("fake") then resolves that device to FakeProcessGroup for an explicitly requested fake group instead of raising No backend type associated with device type <device>, while the device's entry in Backend.default_device_backend_map is left as is: a default process group on that device still resolves to the backend the device registered, or reports that none is registered.

Test Plan

Static gates: lintrunner -a reports no lint issues; the hw-classification/TEST_LINTER scan reports no findings.

  • On an out-of-tree accelerator host (device module loaded, its communication backend registered at import), with this PR's test_fake_pg.py and _register_fake_backend applied over main:
python test/distributed/test_fake_pg.py                                    # Ran 155 tests — OK (skipped=15)
python test/distributed/test_fake_pg.py --hw-classification ACCELERATOR    # Ran 30 tests — OK (skipped=15)
python test/distributed/test_fake_pg.py --hw-classification GENERIC        # Ran 125 tests — OK
python test/distributed/test_c10d_common.py BackendEntryPointTest -v      # Ran 14 tests — OK

The ACCELERATOR group is the 15 accelerator-variant cases of TestFakePGDevice (pass) and the 15 CPU variants (skip with the onlyAccelerator message); those CPU variants are the 15 skips in the full run. On main the same file gives Ran 140 tests — OK (skipped=15) with the accelerator tests skipped as No accelerator, and --hw-classification ACCELERATOR collects 0 tests. BackendEntryPointTest was run with device-module autoload disabled: with the device module autoloaded, test_fake_backend_registration fails the same way on main in that environment (the fake backend module is already imported after import torch).

  • Registration lookups, with a temporary probe that runs _register_fake_backend against an isolated copy of the backend registry: with the device module loaded and no backend registered for the device, BackendConfig("fake") covers the device and get_default_backend_for_device() raises ValueError; with the device's backend registered before or after the fake backend, the default lookup returns that backend; with the device module not loaded, the fake capability is the four built-in device types; a second call lists the device once. dist.init_process_group(backend="fake") followed by dist.get_backend_impl(pg, torch.device(<device>)) returns a FakeProcessGroup, and the default map entry for the device is unchanged by the registration.
  • TEST_LINTER full re-check on the migrated file passes (see below).
  • With the entry removed, the TEST_LINTER full re-check passes for the migrated file: python3 tools/linter/adapters/test_linter.py tools/linter/adapters/test_linter_allowlist.json (the allowlist-as-argument form lintrunner triggers in CI) — rc=0, zero lint messages for test/distributed/test_fake_pg.py.

Notes

@pytorch-bot

pytorch-bot Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⚠️ 4 Awaiting Approval

As of commit c6418d1 with merge base 5fa1bea (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 25, 2026
@twthighd

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 25, 2026
@fffrog fffrog moved this to Backlog in PyTorch Test Refactoring Aug 25, 2026
Comment thread test/distributed/test_fake_pg.py Outdated
@unittest.skipIf(not HAS_ACCELERATOR, "No accelerator")
def test_split_group_store_not_retained(self):
def test_split_group_store_not_retained(self, device):
device_type = torch.device(device).type

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Refer to : #191456

device parameter is str type, so could we use device_id=device rather than
device_id=torch.device(device).type?

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 the review! The device_id here doesn't accept a plain string — init_process_group's signature is torch.device | int | None, and the runtime sanity check accesses device_id.type directly, so device_id=device (a str) would raise AttributeError: 'str' object has no attribute 'type'. It also requires an explicit index (device_id.index is None → ValueError), so the type-only form used for FSDP device_id doesn't apply here.

@twthighd
twthighd force-pushed the test/decouple-test_fake_pg branch 2 times, most recently from 09076b2 to 4d272ca Compare October 21, 2026 06:35
@twthighd
twthighd marked this pull request as ready for review October 26, 2026 01:58
@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot missing actionable issue A PR without a linked actionable issue or maintainer sponsor triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Oct 26, 2026
@twthighd
twthighd force-pushed the test/decouple-test_fake_pg branch 3 times, most recently from 0dda7eb to 5ad6438 Compare October 30, 2026 09:05
@twthighd
twthighd marked this pull request as draft October 31, 2026 02:26
@twthighd
twthighd marked this pull request as ready for review October 31, 2026 06:26

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

I’m reviewing these hardware-decoupling changes to catch recurring test issues early and avoid repeated review requests. The inline analysis below was prepared with Codex.

Comment thread test/distributed/test_fake_pg.py Outdated
def test_construct_fsdp(self, device):
store = FakeStore()
dist.init_process_group(backend="fake", rank=0, world_size=2, store=store)
FSDP(nn.Linear(2, 3, device=self.device_type))

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.

Codex static review. test_construct_fsdp() accepts the harness's device, but this tensor placement only uses the class's unindexed self.device_type. Could we pass device here so the FSDP construction actually exercises the selected device? The same unused-argument pattern occurs in the nearby FSDP and tracing tests; this is separate from the init_process_group(device_id=...) argument-type discussion.

@twthighd twthighd Nov 23, 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.

Fixed in the rebased head: all nine TestFakePGDevice methods now consume the harness-injected device instead of reading the class's unindexed self.device_type — tensor placement uses device=device, and type strings (per-rank device strings in test_split_group, the backend-filter assertion, init_device_mesh/_get_backend lookups) are derived via torch.device(device).type. The module-level device_type = get_devtype().type global is deleted. An AST audit of the nine methods shows each body loads device (1-4 references), with zero self.device_type remaining in the file.

@twthighd
twthighd force-pushed the test/decouple-test_fake_pg branch from 738c811 to 29efc6b Compare November 23, 2026 07:32
@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Nov 23, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

pg.all_gather_single_coalesced(outputs, [torch.ones(2)])


class TestFakePGDevice(TestCase):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think maybe you don't need to create a new class for thess accelerator only test cases. Just replace the former skip for no accelerator to @onlyAccelerator is good to me.

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.

The decorator swap is what the PR does — each of the nine tests carries @onlyAccelerator — but they need a class of their own for it to work. @onlyAccelerator reads self.device_type, which only exists on the classes that instantiate_device_type_tests generates; on a plain TestCase it raises AttributeError: ... has no attribute 'device_type' (checked on both a bare test and one with a device parameter). The nine tests also need the framework-injected device, and TestFakePG is a plain TestCase with 68 device-agnostic methods that has to stay GENERIC and uninstantiated — the linter forbids instantiating a GENERIC class or giving its tests a device parameter — so they cannot take the decorator in place. This is the same shape as test_draft_export.py on main: TestDraftExport (GENERIC) plus TestDraftExportDevice (ACCELERATOR, method-level @onlyAccelerator). Happy to rename or move the class if the concern is its name or its position in the file.

@KarhouTam KarhouTam left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

You are right — @onlyAccelerator reads self.device_type, which only exists on classes generated by instantiate_device_type_tests, so the nine tests do need their own instantiated class for the decorator swap to work. My comment was wrong; nothing to change. Approving, and the pending workflows are approved so CI can run.

Generated by my agent. Reviewed by the user.

Comment thread torch/distributed/_backends/fake.py Outdated
devices = ["cpu", "cuda", "hpu", "xpu"]
privateuse1 = torch._C._get_privateuse1_backend_name()
if hasattr(torch, privateuse1):
devices.append(privateuse1)

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 keep explicit fake process groups available to PrivateUse1 without making fake the default backend for that device.

AI-assisted review at 29efc6b. With a PrivateUse1 device module loaded and no distributed backend registered for it, I ran the registration and lookup code in isolation. On the base, the default-backend lookup still raised after registering fake. On this revision it returned "fake". register_backend also populates default_device_backend_map for new entries in devices. Could we preserve the previous default lookup while adding support for an explicitly requested fake group, and cover both lookups in a regression test?

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.

_register_fake_backend now registers fake with the four built-in device types first and then appends the loaded PrivateUse1 device type to Backend.backend_capability["fake"], so only the capability table gains the device and default_device_backend_map is not written for it. I re-checked both lookups with a temporary probe that runs the registrar against an isolated copy of the registry: with the device module loaded and no backend registered for the device, BackendConfig("fake") covers the device and get_default_backend_for_device() raises as on the base; with the device's backend registered before or after fake, the default lookup returns that backend; with the module not loaded the capability is unchanged; an explicit backend="fake" group resolves the device to FakeProcessGroup. On an out-of-tree accelerator host BackendEntryPointTest (14 tests) and test_fake_pg.py (155 tests, 15 accelerator-variant cases pass) pass with the same outcome as before the change. I did not add a regression test in this round because this PR is part of a test-case refactoring initiative that stays within the existing tests — is the verification above acceptable, or would you like the regression test added here?

…label classes

Summary:
- Split the mixed TestFakePG class: the fake-PG mechanism tests
  (copy semantics, requires_grad propagation, validation errors,
  dispatch tracing) stay in TestFakePG labeled GENERIC, while the
  nine accelerator-path tests (FSDP/TP e2e, functional-collectives
  tracing, split_group) move to a new TestFakePGDevice labeled
  ACCELERATOR.
- TestFakePGDevice is instantiated via instantiate_device_type_tests
  with allow_xpu=True, and the moved methods take the injected device
  parameter instead of the module-level device_type = get_devtype().type
  (deleted).
- Gate the nine methods with the variant-aware @onlyAccelerator instead
  of excluding the CPU variant: the CPU variant is collected and skips
  cleanly on every host (the guard reads the running variant's
  device_type), so CPU-only machines report explicit skips instead of
  the class being invisible, while accelerator variants run unchanged.
  Same gating form as the landed pytorch#192712 and pytorch#191905. @skipIfHpu
  blacklist guards are kept.
- Rebase absorption: keep pytorch#202253's six compile-sync methods in the
  GENERIC TestFakePG (14 expanded cases, parametrizations and gloo
  availability guards intact; their config strings naming cuda/nccl do
  not exercise device-tensor paths) and pytorch#202141's whole-file adjustments
  (fake backend moved to a Python PyBackend, new GENERIC
  debug-wrapper/alias/split-options tests, updated assertion patterns);
  the unittest/unittest.mock imports the new tests use are kept.

This allows the accelerator-path tests to run on any out-of-tree
accelerator variant instead of being skipped wherever HAS_ACCELERATOR
is False, while the device-agnostic fake-PG mechanics stay in a
GENERIC class that runs everywhere.

Verified on an old-snapshot verify host (its C++ fake backend predates
the Python PyBackend move):
- The generated CPU class collects 15 cases, all skipped with the exact
  reason "onlyAccelerator: doesn't run on CPU or meta devices" (OK,
  0 errors).
- A whole-file run is not obtainable there: a newly absorbed GENERIC
  test crashes the old C++ fake backend.
- The PrivateUse1 variant fails there at the fake backend's
  device-type lookup (observed error).

Full-file validation on the rebased stack remains pending. GENERIC/CPU
and accelerator coverage will be checked in the corresponding CI jobs
where selected. PrivateUse1 execution additionally requires pytorch#202363 at
the new registration site, with the backend plugin loaded before fake
registration, and a compatible verification environment; ordinary
CPU/CUDA CI does not cover it.
…wlist

Summary:
- This PR migrates test/distributed/test_fake_pg.py to the TEST_LINTER's
  requirements (hw_classification on every test class plus the per-classification
  structure rules), and the file currently sits in test_linter_allowlist.json.
  Drop its one-line entry in the same PR: the allowlist is a regenerated snapshot
  of non-compliant files, and a migration landing without the deletion leaves a
  silently-stale exemption (canonical: pytorch#191905 needed the follow-up pytorch#202866).

This lets the linter enforce its requirements on future changes to this file
as part of the same change, instead of a separate cleanup PR later.
…ice list

Summary:
- _register_fake_backend() registers the fake backend with a fixed device
  list ("cpu", "cuda", "hpu", "xpu"), so a fake world cannot serve an
  out-of-tree backend loaded through PrivateUse1: a device-qualified
  backend query after init_process_group(backend="fake") raises
  "No backend type associated with device type PrivateUse1". Build the
  device list when the registrar is invoked and append the renamed
  PrivateUse1 backend when its module is loaded, gated on module presence
  with no hardware query.
- The registrar is invoked through lazy backend loading or the
  compatibility shim in torch/testing/_internal/distributed/fake_pg.py;
  the PrivateUse1 module must be loaded before registration, and loading
  it later does not automatically refresh an existing fake registration.
- register_backend's precedence rules keep real backends safe: fake does
  not overwrite the default device map entry of an already-registered
  real backend, and a real backend registered later replaces fake in the
  default device map.

This allows device-type-instantiated fake-PG tests to generate and run
out-of-tree accelerator variants instead of failing at the device-qualified
backend query, while CPU-only environments keep the original registration
behavior.

This is part of the test case refactoring initiative tracked in pytorch#185590.
…making it the default backend

Summary:
- Register the fake backend with its four built-in device types, then append the loaded PrivateUse1 device type to the fake backend's device capability.
- BackendConfig("fake") resolves that device to FakeProcessGroup for an explicitly requested fake group, as before.
- The device's entry in Backend.default_device_backend_map is no longer written, so the default lookup returns the backend the device registered, or raises the "Default backend not registered" error when it registered none.

Passing the device through `register_backend(devices=...)` also filled the device's entry in the default map, which made "fake" the default communication backend for the device whenever its own backend was not registered yet, including for a default `init_process_group()` call. Appending to the capability table after registration keeps the explicit-group support needed by the split test class without that side effect.

This branch was previously deployed

1 inactive (outdated) deployment
bedrock — 738c8110 Deployed Oct 31, 2026 by twthighd
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 ciflow/torchtitan Run TorchTitan integration tests missing actionable issue A PR without a linked actionable issue or maintainer sponsor 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.

5 participants