Skip to content

[Testcase Refactoring] Make with_comms backend dynamically resolved for out-of-tree accelerators - #192417

Closed
youlituao wants to merge 2 commits into
pytorch:mainfrom
youlituao:test/with_comms
Closed

youlituao wants to merge 2 commits into
pytorch:mainfrom
youlituao:test/with_comms

Conversation

@youlituao

@youlituao youlituao commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The with_comms decorator in ShardedTensorTestBase hardcodes
backend="nccl" as the default. This causes test variants for non-NCCL
accelerator backends (e.g. PrivateUse1 backends using HCCL) to be
skipped at the wrapper level, because
backend != dist.get_default_backend_for_device(acc).

This PR changes the default from "nccl" to None, and resolves the
backend dynamically in the wrapper via a single lookup:
dist.get_default_backend_for_device(self.device_type) (where
self.device_type is set by instantiate_device_type_tests, with a
getattr fallback to "cpu" for classes not using it).

get_default_backend_for_device queries Backend.default_device_backend_map
("cpu": GLOO, "cuda": NCCL, "xpu": XCCL, "mps": GLOO, plus
out-of-tree entries registered via register_backend(..., devices=[...])),
so each device variant gets its own backend:

  • CPU variant → gloo
  • CUDA → nccl
  • XPU → xccl
  • PrivateUse1 (e.g. NPU, renamed via rename_privateuse1_backend) → hccl

Resolving from self.device_type (the variant's own device) rather than
torch.accelerator.current_accelerator() (the host's accelerator) ensures
per-device test variants get the correct backend even on cross-device hosts.
For example, a CPU variant on an NPU host resolves to gloo instead of the
host's hccl (which would cause ProcessGroupHCCL::scatter to receive a
CPU tensor when an NPU tensor is expected); likewise a cuda variant on an
NPU-only host resolves to nccl and is correctly skipped, rather than being
mis-resolved to hccl.

The accelerator-backend skip check uses resolved_backend != "gloo" +
dist.is_backend_available() instead of a hard-coded backend list, so
new accelerator backends are automatically supported without modifying
the check.

Changes

  • Changed with_comms(func=None, init_rpc=True, backend="nccl") to
    with_comms(func=None, init_rpc=True, backend=None).
  • Added dynamic resolution logic in the wrapper: when backend is None,
    resolve via a single lookup
    dist.get_default_backend_for_device(device_type), where device_type
    is obtained from getattr(self, "device_type", "cpu") (the "cpu"
    default ensures backward compatibility with classes not using
    instantiate_device_type_tests).
  • Replaced if resolved_backend in ["nccl", "xccl", "hccl"]: with
    if resolved_backend != "gloo":, and added
    dist.is_backend_available(resolved_backend) check to skip tests when
    the backend is not compiled/available. New accelerator backends are
    automatically supported without modifying the check.
  • Moved torch.accelerator.current_accelerator() call into the
    accelerator-backend branch (only needed when resolved_backend is not
    "gloo"), avoiding unnecessary accelerator initialization for CPU
    variants.
  • Updated all references from backend to resolved_backend in the
    skip-check and init_comms call.

Before vs After

Scenario Before (hardcoded) After (this PR)
CPU variant, no accelerator nccl → skip ✗ gloo ✓
CPU variant, NPU present on host nccl → skip ✗ gloo ✓
PrivateUse1 variant, NPU present nccl → skip ✗ hccl ✓
CUDA variant, CUDA present nccl ✓ nccl ✓
Explicit backend="gloo" gloo ✓ gloo ✓
Backend not compiled (e.g. xccl) N/A (not in list) is_backend_available → skip ✓

Not changed

  • Callers that explicitly pass backend= are unaffected (backward
    compatible).
  • The skip logic for accelerator backends is preserved — tests are still
    skipped if the backend is not available, does not match the current
    accelerator, or if device count is insufficient.
  • init_pg is not modified (already handles dynamic device binding via
    torch.accelerator.set_device_index).

Test plan

  • Backend resolution verified on an out-of-tree accelerator backend
    (PrivateUse1, torch_npu 2.13.0+git45fbeae on PyTorch 2.13.0a0+gitfad7424,
    Ascend 910B3, NPU host):
    • device_type="npu" → backend resolved to hccl ✅
    • device_type="cpu" (with NPU present on host) → backend resolved to
      gloo ✅ (previously mis-resolved to the host's hccl)
    • get_default_backend_for_device("cpu") returns "gloo" as expected,
      confirming the single-lookup approach is equivalent to the removed
      device_type == "cpu" special-case.
  • Note: test_sharded_tensor_reshard.py does not call
    instantiate_device_type_tests, so TestReshard has no per-device
    variants (e.g. TestReshardCPU/TestReshardNPU); device_type falls
    back to the "cpu" default. The per-device variant paths were verified
    via mock test classes (FakeNPUTest / FakeCPUTest) that set
    device_type and assert the backend passed to init_comms.
  • Note: The test methods in test_sharded_tensor_reshard.py are decorated
    with @requires_nccl(), which skips them on hosts where NCCL is not
    compiled (independent of this PR). Replacing @requires_nccl() with a
    capability-based decorator is tracked as a separate follow-up.
  • TODO: Run other ShardedTensor test files that use with_comms to
    confirm no regressions.

@pytorch-bot

pytorch-bot Bot commented Aug 7, 2026

Copy link
Copy Markdown

🔗 Helpful Links

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

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

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

@pytorch-bot pytorch-bot Bot added the release notes: distributed (sharded) release notes category label Aug 7, 2026
@youlituao

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "module: tests/distributed"

else:
resolved_backend = backend

if resolved_backend in ["nccl", "xccl", "hccl"]:

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 change to the default backend to fix out-of-tree accelerators is reasonable, but it still retains a hard-coded check(backend in ["nccl", "xccl", "hccl"]). It is recommended to consider using c10d.is_backend_available() instead.

@youlituao youlituao Aug 14, 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.

Thanks for the feedback! You're right — the hard-coded ["nccl", "xccl", "hccl"] list is not ideal since it requires updating whenever a new accelerator backend is added.

I've updated the PR to replace the hard-coded list with dist.is_backend_available():

Before:

if resolved_backend in ["nccl", "xccl", "hccl"]:
    if (
        acc is None
        or resolved_backend != dist.get_default_backend_for_device(acc)
        or torch.accelerator.device_count() < self.world_size
    ):
        sys.exit(TEST_SKIPS[f"multi-gpu-{self.world_size}"].exit_code)

After:

if resolved_backend != "gloo":
    if not dist.is_backend_available(resolved_backend):
        sys.exit(TEST_SKIPS["backend_unavailable"].exit_code)
    acc = torch.accelerator.current_accelerator()
    if (
        acc is None
        or resolved_backend != dist.get_default_backend_for_device(acc)
        or torch.accelerator.device_count() < self.world_size
    ):
        sys.exit(TEST_SKIPS[f"multi-gpu-{self.world_size}"].exit_code)

This way, new accelerator backends are automatically supported without modifying the check. The resolved_backend != "gloo" condition preserves the original intent: gloo (CPU backend) does not require an accelerator, so the device-count and accelerator-match checks are skipped for it.

Additionally, I addressed another issue discovered during testing: when instantiate_device_type_tests generates per-device test variants (e.g., TestReshardCPU, TestReshardPRIVATEUSE1), using torch.accelerator.current_accelerator() to resolve the backend causes the CPU variant to incorrectly use the host accelerator's backend (e.g., hccl) instead of gloo. The fix uses self.device_type (set by instantiate_device_type_tests) to determine the correct backend per variant.

Verified on NPU (Ascend 910B3):

  • TestReshardPRIVATEUSE1: correctly resolves to hccl, 2 tests pass (OK)
  • TestReshardCPU: correctly resolves to gloo (no longer attempts hccl)

youlituao added a commit to youlituao/pytorch that referenced this pull request Aug 14, 2026
…ty gating

Summary:
- Replace @requires_nccl() with @requires_capabilities(Capability.distributed.backend)
- Replace .cuda(self.rank) with .to(device)
- Replace hardcoded placement with dynamic device_type
- Add hw_classification = HardwareClassification.ACCELERATOR
- Add instantiate_device_type_tests for device-variant generation

Part of pytorch#185590.
Depends on: pytorch#187650, pytorch#190528, pytorch#191919, pytorch#192417, pytorch#193080
youlituao added a commit to youlituao/pytorch that referenced this pull request Aug 14, 2026
…ty gating

Summary:
- Replace @requires_nccl() with @requires_capabilities(Capability.distributed.backend)
- Replace .cuda(self.rank) with .to(device)
- Replace hardcoded placement with dynamic device_type
- Add hw_classification = HardwareClassification.ACCELERATOR
- Add instantiate_device_type_tests for device-variant generation

Part of pytorch#185590.
Depends on: pytorch#187650, pytorch#190528, pytorch#191919, pytorch#192417, pytorch#193080
…of-tree accelerators

- Change default from backend="nccl" to backend=None (dynamic resolution)
- Use self.device_type to determine correct backend per test variant
- Replace hard-coded ["nccl", "xccl", "hccl"] with dist.is_backend_available()
- CPU variants correctly use gloo even when accelerator is present on host

Verified on NPU (Ascend 910B3):
- TestReshardPRIVATEUSE1: correctly resolves to hccl, 2 tests pass
- TestReshardCPU: correctly resolves to gloo

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

Reasonable refactoring, @fffrog please review.

# present on the host.
device_type = getattr(self, "device_type", "cpu")
if backend is None:
if device_type == "cpu":

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.

If the device type is correct, there is no need to add the judgment if device_type == "cpu": resolved_backend = "gloo". get_default_backend_for_device is capable of returning the corresponding backend for the cpu device‑type.

@youlituao youlituao Aug 19, 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.

Thanks for the review. Updated in the latest push and verified locally.

Change: Simplified the resolution to a single lookup as you suggested:

device_type = getattr(self, "device_type", "cpu")
if backend is None:
    resolved_backend = dist.get_default_backend_for_device(device_type)
else:
    resolved_backend = backend

get_default_backend_for_device("cpu") returns "gloo" via Backend.default_device_backend_map ("cpu": GLOO), so the explicit device_type == "cpu" branch was redundant. This also drops the current_accelerator() call and the else "gloo" fallback from the resolution path — the downstream skip check (acc is None / resolved_backend != get_default_backend_for_device(acc)) already covers those cases.

As a side benefit, resolving from device_type (the variant's own device) rather than current_accelerator() (the host's accelerator) is more correct on cross-device hosts: each variant gets its own backend instead of inheriting the host's. For example, a cuda variant on an NPU-only host now resolves to nccl and is correctly skipped, rather than being mis-resolved to hccl.

Note: get_default_backend_for_device raises ValueError for an unregistered device_type, but this doesn't introduce a new failure mode — the previous code queried the same map via current_accelerator(). Out-of-tree backends register themselves into default_device_backend_map via register_backend(..., devices=[...]), which both approaches rely on.

Local verification (PrivateUse1, torch_npu 2.13.0, Ascend 910B3, NPU host):

device_type="npu" → backend resolved to hccl ✅
device_type="cpu" (with NPU present on host) → backend resolved to gloo ✅
get_default_backend_for_device("cpu") returns "gloo" as expected, confirming the simplified lookup is equivalent to the removed explicit branch.

…vice

get_default_backend_for_device(device_type) already maps "cpu" -> "gloo"
via Backend.default_device_backend_map, so the explicit device_type == "cpu"
branch is redundant. Drop it along with the current_accelerator() fallback
in the resolution path; the downstream skip check already covers the
no-accelerator / backend-mismatch cases.

Resolving from device_type (the variant's device) rather than
current_accelerator() (the host's accelerator) is also more correct on
cross-device hosts: each variant gets its own backend instead of the host
accelerator's backend.

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

The default value has been changed from NCCL to GLOO, and this modification is not recommended.

@drisspg
drisspg requested a review from fffrog August 19, 2026 18:48
@drisspg drisspg added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 19, 2026
@youlituao youlituao closed this Aug 21, 2026
@github-project-automation github-project-automation Bot moved this from Backlog to Done in PyTorch Test Refactoring Aug 21, 2026
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 release notes: distributed (sharded) release notes category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants