Skip to content

[Test] Add capability-based test skip mechanism - #190846

Closed
orangeH25 wants to merge 9 commits into
pytorch:mainfrom
orangeH25:test/capability/1
Closed

orangeH25 wants to merge 9 commits into
pytorch:mainfrom
orangeH25:test/capability/1

Conversation

@orangeH25

@orangeH25 orangeH25 commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Introduce a capability-based test skip mechanism that allows tests to declare required capabilities, including dtype support, feature availability, and library dependencies (e.g. FP8, Flash Attention, and Triton). The mechanism queries the current device capabilities at runtime and automatically skips tests when requirements are not satisfied.

Motivation

Centralize device capability checks

Currently, hardware and feature capability checks are scattered across the test infrastructure. Modules such as common_cuda.py and common_utils.py expose a large number of hardware- and feature-specific global capability flags that tests import directly and combine with decorators.

Examples include:

  • SM version checks (SM*OrLater, IS_SM*)
  • Feature support flags (PLATFORM_SUPPORTS_FP8, PLATFORM_SUPPORTS_FLASH_ATTENTION)
  • Library availability checks (TEST_CUDNN, has_triton())

There are currently ~50 such global capability flags across the test infrastructure, making capability checks difficult to maintain and requiring tests to manually import and compose backend-specific conditions.

Centralizing capability resolution in DeviceTypeTestBase allows existing backend-specific capability checks to be aggregated and exposed through a uniform interface. Tests no longer need to directly import and combine scattered global flags or backend-specific conditions.

Enable capability reporting for OOT backends

Most existing capability checks are implemented with built-in backend assumptions. For example:

def evaluate_platform_supports_bf16():
    if torch.version.cuda:
        return SM80OrLater
    elif torch.version.hip:
        return True
    elif TEST_XPU:
        return True
    return False

These checks cannot be directly reused by out-of-tree (OOT) backends.

With the capability-based test mechanism, OOT backends can provide their own capability implementations by overriding or monkey-patching capability queries through PrivateUse1TestBase. For example:

PrivateUse1TestBase._capabilities = classmethod(
    lambda cls: {
        Capability.dtype: {Capability.dtype.fp8: lambda: False},
        Capability.lib: {Capability.lib.triton: lambda: True},
    }
)

Design

Structured capability namespace

A Capability class with nested namespaces groups related capabilities, so tests reference Capability.dtype.fp8] instead of bare strings:

class Capability:
    class dtype:
        fp8 = "dtype.fp8"
        bf16 = "dtype.bf16"

    class lib:
        triton = "lib.triton"

    class attention:
        flash_attention = "attention.flash_attention"
        mem_efficient_attention = "attention.mem_efficient_attention"

Capability Registry

Add get_capabilities() and _capabilities() classmethods to DeviceTypeTestBase, where get_capabilities() caches capability information provided by backend-specific _capabilities() hooks.

class DeviceTypeTestBase(TestCase):
    @classmethod
    @cache()
    def get_capabilities(cls) -> dict[str, bool]:
        return {
            k: fn() for sub in cls._capabilities().values() for k, fn in sub.items()
        }

    @classmethod
    def _capabilities(cls) -> dict[type, dict[str, Callable[[], bool]]]:
        return {}

Each DeviceTypeTestBase subclass defines its own capabilities map, for example:

class CUDATestBase(DeviceTypeTestBase):
    @classmethod
    def _capabilities(cls):
        return {
            Capability.dtype: {
                Capability.dtype.fp8: lambda: PLATFORM_SUPPORTS_FP8,
                Capability.dtype.bf16: lambda: SM80OrLater,
            },
            Capability.lib: {
                Capability.lib.triton: lambda: has_triton(),
            },
            Capability.attention: {
                Capability.attention.flash_attention: lambda: PLATFORM_SUPPORTS_FLASH_ATTENTION,
                Capability.attention.mem_efficient_attention: lambda: PLATFORM_SUPPORTS_MEM_EFF_ATTENTION,
            },
        }

Declaring Requirements

Add @requires_capability decorator (call get_capabilities() at runtime) to skip tests when required capabilities are unavailable at runtime, for example:

@requires_capabilities(Capability.lib.triton, Capability.dtype.fp8)
def test_foo(self, device): ...

Changes

  • Add get_capabilities() and _capabilities() classmethods to DeviceTypeTestBase, where get_capabilities() caches capability information provided by backend-specific _capabilities() hooks.
  • Add initial _capabilities() implementations for CUDATestBase, CPUTestBase, and XPUTestBase to provide backend-specific capability queries. The initial set of capabilities covers those required by test_flop_counter.py and can be extended incrementally as more tests migrate.
  • Add @requires_capability decorator to skip tests when required capabilities are unavailable at runtime.
  • Add OpenReg tests to verify capability gating behavior.

Test Plan

pytest test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_testing.py -vvv

  • 16 passed, 8 skipped, 2 xfailed in 0.23s
test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_testing.py::TestCapabilityGatingOPENREG::test_capability_combined_openreg SKIPPED [0.0008s] (Unsupported capabilities:
test.cap_unsupported; Missing capabilities: test.cap_missing)                                                                                                                                                    [ 84%] 
test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_testing.py::TestCapabilityGatingOPENREG::test_capability_missing_openreg SKIPPED [0.0008s] (Missing capabilities: test.cap_missing)     [ 88%] 
test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_testing.py::TestCapabilityGatingOPENREG::test_capability_supported_openreg PASSED [0.0008s]                                             [ 92%] 
test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_testing.py::TestCapabilityGatingOPENREG::test_capability_unsupported_openreg SKIPPED [0.0008s] (Unsupported capabilities:
test.cap_unsupported)                                                                                                                                                                                            [ 96%]

Note

This PR introduces an initial set of capabilities. The capability registry is designed to grow incrementally as additional tests adopt @requires_capability and introduce new backend capability requirements.

@orangeH25
orangeH25 requested a review from mruberry as a code owner July 23, 2026 03:42
@pytorch-bot

pytorch-bot Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit 3c955b4 with merge base f616cd4 (image):

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

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

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

Overal look ok to me, thank you for updates.

Comment thread test/test_flop_counter.py Resolved
@fffrog fffrog moved this from Backlog to Ready for Review(Initial) in PyTorch Test Refactoring Jul 23, 2026
@albanD albanD added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 24, 2026
@orangeH25
orangeH25 force-pushed the test/capability/1 branch from 1361bb5 to 597a3bd Compare July 27, 2026 12:19
twthighd added a commit to twthighd/pytorch that referenced this pull request Aug 4, 2026
…nt test in test_multi_threaded_pg

Summary:
- Label `TestCollectivesWithWrapper` and `TestCollectivesWithBaseClass`
  with `hw_classification = HardwareClassification.GENERIC` (device-agnostic
  threaded-collective logic on CPU tensors).
- Move `test_bwd_sees_fwd_pg` (requires an accelerator, asserts
  collective+autograd correctness on a device-tensor path) out of
  `TestCollectivesWithBaseClass` into a new parallel
  `TestCollectivesWithBaseClassDevice(MultiThreadedTestCase)` class
  labeled `hw_classification = HardwareClassification.ACCELERATOR`,
  replicating `world_size`/`setUp`/`tearDown`.
- `test_bwd_sees_fwd_pg` takes a `device` parameter and the class is
  instantiated via `instantiate_device_type_tests(..., except_for=("cpu",),
  allow_xpu=True)`, so the method runs on the current accelerator device
  variant (e.g. privateuse1) with the device injected by the framework
  rather than a module-level device string. `except_for=("cpu",)` excludes
  the CPU variant since this test requires an accelerator
  (`@skip_if_lt_x_gpu(1)`). This makes the class a `DeviceTypeTestBase`
  subclass, ready for capability-based gating (PR pytorch#190846) when it lands.

This follows the convention that every TestCase subclass carries a
hw_classification label. The split avoids mislabeling the mixed class:
17 CPU threaded methods are GENERIC, the single accelerator-dependent
method is ACCELERATOR.
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).

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

Nice job, thank you.

Additionally:

Could the changes to test_flop_counter.py be split into a separate PR, focusing solely on the implementation of basic functionality?

@orangeH25 orangeH25 changed the title [Test] Add capability-based test skip mechanism and refactor test_flop_counter.py [Test] Add capability-based test skip mechanism Aug 6, 2026

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

SGTM, thank you.

cc @albanD @jbschlosser

@fffrog fffrog moved this from Ready for Review(Initial) to Ready for Review(Definitive) in PyTorch Test Refactoring Aug 6, 2026
@fffrog
fffrog requested a review from albanD August 6, 2026 08:14

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

Sounds good!
Let's be careful on not skipping tests by mistakes!

@fffrog

fffrog commented Aug 19, 2026

Copy link
Copy Markdown
Collaborator

Let's be careful on not skipping tests by mistakes!

Thank you, we will be careful. :D

@fffrog

fffrog commented Aug 19, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: This PR needs a release notes: label
If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

Details for Dev Infra team Raised by workflow job

@fffrog

fffrog commented Aug 19, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot label "topic: not user facing"

@fffrog

fffrog commented Aug 19, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged 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: Done

Development

Successfully merging this pull request may close these issues.

7 participants