Skip to content

[Testcase Refactoring] Make test_subgraph_choice device-agnostic via instantiate_device_type_tests - #192435

Closed
gavinwang269 wants to merge 1 commit into
pytorch:mainfrom
gavinwang269:test/inductor-subgraph-choice-decouple
Closed

gavinwang269 wants to merge 1 commit into
pytorch:mainfrom
gavinwang269:test/inductor-subgraph-choice-decouple

Conversation

@gavinwang269

@gavinwang269 gavinwang269 commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

[inductor][test] Make test_subgraph_choice.py device-agnostic and graduate it from the test linter

Rewrite the gating in test/inductor/test_subgraph_choice.py so every device decision
is a capability answer about the instantiated device, then drop the file from the
test-linter migration ledger now that it satisfies the ACCELERATOR rules.

Three upstream layers touch this feature, and they are not the same question:

  • native_functions.yaml registers aten bmm.dtype / bmm.dtype_out for CUDA and XPU,
    but an out-of-tree backend may register its own lowering for the same op;
  • Inductor's generic aten.bmm lowering raises "out_dtype is only supported for CUDA
    or XPU" (torch/_inductor/kernel/bmm.py:361-363) for whatever reaches it;
  • the decompose-K heuristic template ships real heuristics for cuda and xpu with an
    empty opt-out class and a TODO to widen
    (torch/_inductor/heuristics/template/decompose_k.py:30-49).

Measured here on an Ascend 910B4 host with torch_npu registered, the aten variants
do reach lowering and fail inside torch_npu's own registration:

LoweringException: TypeError: _register_npu_inductor_bmm.<locals>.tuned_bmm()
takes 2 positional arguments but 3 were given

-- torch._inductor.kernel.bmm's "CUDA or XPU" assertion is never evaluated on that
path. So mirroring bmm.py's device list in the test would be wrong twice over: it
would restate an upstream name list inside a device-agnostic test, and it would keep
permanently skipped a backend that does implement out_dtype (here, one that merely
implements it incorrectly today). The support question is therefore not encoded at
all in this file: the tests run wherever their real requirements hold, and the
torch_npu defect is left to fail visibly rather than hidden behind a skip.

Changes:

  • Removed the module-level GPU_TYPE: the base was one
    @instantiate_parametrized_tests class that built every tensor on GPU_TYPE;
    tensors are now built on the device the instantiated variant is bound to. The
    file's Blackwell gates are import-time
    @unittest.skipUnless(has_datacenter_blackwell_tma_device(), ...) decorators
    answering one process-wide question, defined once at module level as
    requires_blackwell_tma and applied only to the CUDA-only class below; the
    accelerator class needs no Blackwell gate because it runs no Triton
    decompose-K code.
  • Moved every Blackwell-only Triton test into a dedicated TestSubgraphChoiceCUDAOnly
    class (hw_classification=CUDA, instantiate_device_type_tests(..., only_for="cuda")):
    test_decompose_k_partial_freezes_producer_layout, test_decompose_k_bmm_backends, and
    the Triton half of test_subgraph_decompose_k, now named
    test_subgraph_decompose_k_triton there. The base carried these three tests in
    its single class: the two siblings already had the import-time
    @unittest.skipUnless decorators, and the Triton half of
    test_subgraph_decompose_k was gated by an in-body self.skipTest that the class
    split replaces. All three now carry the single module-level requires_blackwell_tma
    gate; the probe is process-wide, so on a class instantiated only_for="cuda" it
    normally answers for CUDA's own hardware, with the PYTORCH_TESTING_DEVICE_FOR_CUSTOM
    caveat stated in the class comment instead of papered over. The split is what
    removes the Blackwell
    exposure from the accelerator class: the class instantiated for XPU and out-of-tree
    backends no longer generates any Triton decompose-K variant, and no longer generates
    the meta_ws / config_index combinations that only ever meant something to the Triton
    backend. The base always collected -- and skipped in-body -- six aten ids
    built from that cross product (two dtypes x three skipped combos); those
    variants are gone entirely, so no skipped id of that shape survives on XPU or
    out-of-tree.
    test_subgraph_decompose_k is therefore split by backend into
    test_subgraph_decompose_k_aten on the accelerator class (a single variant
    per dtype) and test_subgraph_decompose_k_triton on the CUDA-only class (its
    meta_ws and config_index parametrizes and its MetaWS skip), so the ids name
    the backend again the way the base's backend_aten / backend_triton
    parametrization did. The shared
    computation lives in a module-level _run_decompose_k_case(self, ...) helper -- a plain
    function that takes the TestCase instance, not a TestCase subclass alias, so pytest
    still collects exactly one accelerator and one CUDA-only class rather than a second
    copy of every id. The helper appends its one choice through the subgraph
    template exactly as the base's inline body did
    (DecomposeKSubgraphTemplate().maybe_append_choice, autotune_select_algorithm,
    run_and_get_code(torch.compile(fn), ...)) and, like the base body, passes
    k_split, bmm_backend and bmm_config_index explicitly: SubgraphTemplate keeps
    the base KernelTemplate.maybe_append_choice, which calls generate() directly,
    so the registered template heuristics are not consulted on this path. The
    CUDA-only class holds 13 ids on a
    CUDA host (8 Triton decompose-K variants: meta_ws x config_index x two dtypes; 1
    partial producer-layout; 4 bmm-backends). Each instantiated accelerator class holds
    3 ids: the aten decompose-K case in bf16 and fp32, and freeze-layout.
  • @requires_triton() (family rule, and this file's Triton variants need a Triton
    backend) plus an in-body check for what remains in the accelerator class:
    test_subgraph_freeze_layout gates on is_gpu(self.device_type), the predicate
    compile_fx.maybe_disable_comprehensive_padding uses to switch comprehensive padding
    off for graphs with no GPU-class input (config.disable_padding_cpu); the stride
    assertions below need that padding, which is on by default. is_gpu is
    derived from the registered accelerator types (which cover cuda, mps, mtia, npu and
    xpu on this host), so it answers True here and the test runs, rather than being
    skipped by a name list.
  • @dtypes(torch.bfloat16, torch.float32) instead of @parametrize("dtype", ...), which
    replaces the dtype_bfloat16 id segment with the dtypes-generated bfloat16 suffix.
  • No xfail machinery is carried. Upstream keeps no marker for the torch_npu defect:
    the three PrivateUse1 ids fail visibly, and a backend excludes them through
    PrivateUse1TestBase.set_test_configs(test_exclusions=...)
    (torch/testing/_internal/common_device_type.py:419, :502; set_test_configs itself
    :625), the form documented
    in docs/source/accelerator/testing.md. An upstream expectedFailure naming the
    measured ids would be a backend's own exclusion list written into the
    device-agnostic tree -- the ids carry that backend's device suffix, so the table
    is a name list wearing a marker -- and exactly the coupling this file is being
    migrated away from. Failing visibly instead lets each backend decide how to
    suppress its own known-broken lowering without upstream naming it.
  • Runner guard now uses if has_triton(): run_tests(needs="filelock"), matching the
    convention in the sister file test/inductor/test_mem_estimation.py:364. That single
    has_triton() guard is what replaces the removed HAS_GPU / HAS_CPU gate: the file's
    accelerator variants still run wherever a Triton toolchain exists, and the whole
    module simply does nothing under the bare runner when Triton is absent.

Per-device answers, and what is not a per-device answer:

The accelerator class (TestSubgraphChoice, hw_classification=ACCELERATOR,
instantiate_device_type_tests(..., except_for="cpu", allow_xpu=True)) answers per-device
through three things only: the instantiation scope itself (a variant exists only for a
registered accelerator base), is_gpu(self.device_type) in test_subgraph_freeze_layout,
and -- inside the separate CUDA-only class -- has_datacenter_blackwell_tma_device().
@requires_triton() is not one of them: it is a process-wide toolchain-existence check
for whether Triton can be imported at all, not a question about which accelerator the
instantiated variant runs on. The CUDA-only class (TestSubgraphChoiceCUDAOnly,
instantiate_device_type_tests(..., only_for="cuda")) is instantiated only where CUDA is
registered, so the Blackwell probe it consults is normally a probe of that class's own
device; the exception is PYTORCH_TESTING_DEVICE_FOR_CUSTOM, which appends matching
device bases after the only_for filter, and the class comment states that limitation.

Which jobs run this file:

The accelerator tests run on CUDA default shards (test_python_shard discovery), on ROCm
default shards, and on XPU default shards. Only the Blackwell-gated ids have no trunk
job, because no Blackwell hardware exists in trunk CI. The refactored Triton half --
the whole CUDA-only class -- has therefore not been exercised on CUDA, Blackwell or
XPU hardware at this head: the host used for the measurements below has neither a
CUDA nor an XPU device. One scope change is worth flagging
for maintainer attention: the old main path gated on HAS_GPU and HAS_CPU (tensors
built on GPU_TYPE) and could reach MTIA hosts -- HAS_GPU includes HAS_MTIA_AND_TRITON
(inductor_utils.py:82) -- whereas get_device_type_test_bases has no MTIA base, so
after this change the file contributes no tests to MTIA-labeled runs.

Test Plan

Measured on an Ascend 910B4 host (no CUDA, no XPU hardware) against installed
torch + torch_npu nightlies. pytest is pointed at the test file inside this
checkout from a directory that is not the repo root, so the installed package is
imported (running from the repo root of a source build is equivalent). The NPU
venv sources the CANN set_env.sh first; the lintrunner line needs lintrunner on
PATH.

python -m pytest test/inductor/test_subgraph_choice.py --collect-only -q
# NPU venv: 3 tests collected, all under TestSubgraphChoicePRIVATEUSE1:
#   TestSubgraphChoicePRIVATEUSE1::test_subgraph_decompose_k_aten_npu_bfloat16
#   TestSubgraphChoicePRIVATEUSE1::test_subgraph_decompose_k_aten_npu_float32
#   TestSubgraphChoicePRIVATEUSE1::test_subgraph_freeze_layout_npu
# No *_npu ids of the CUDA-only class (only_for="cuda", and no CUDA on this host).
python -m pytest -q -rs test/inductor/test_subgraph_choice.py
# NPU venv: 3 failed, 0 skipped. Each fails visibly, no marker. The two
# test_subgraph_decompose_k_aten ids fail inside torch_npu's own bmm registration:
#   LoweringException: TypeError: _register_npu_inductor_bmm.<locals>.tuned_bmm()
#   takes 2 positional arguments but 3 were given
# test_subgraph_freeze_layout_npu trips the file's own stride-equality check:
#   LoweringException: AssertionError:
#   target: mylib.matmul_decompose_padding.default
TORCH_DEVICE_BACKEND_AUTOLOAD=0 python -m pytest test/inductor/test_subgraph_choice.py --collect-only -q
# no tests collected (rc 5) in a venv where the guard is effective (in the NPU venv a
# sitecustomize force-imports torch_npu regardless of the guard): the accelerator
# instantiation (except_for="cpu") has no accelerator base to bind to and the
# CUDA-only instantiation (only_for="cuda") has no CUDA present.
python3 tools/linter/adapters/test_linter.py test/inductor/test_subgraph_choice.py
# 0 findings from the repo root.
lintrunner -a test/inductor/test_subgraph_choice.py
# ok No lint issues. rc=0

The out-of-tree value is that no capability question is answered by a device-name list:
the only Blackwell answer lives inside the class instantiated only_for="cuda" (whose
PYTORCH_TESTING_DEVICE_FOR_CUSTOM caveat is stated in-file), the only GPU-class answer
is is_gpu(self.device_type), and the torch_npu
defect is left for the backend to suppress with its own exclusions rather than named
upstream.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

@pytorch-bot

pytorch-bot Bot commented Aug 7, 2026 •

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

The PR moves test/inductor/test_subgraph_choice.py onto
instantiate_device_type_tests, using an ACCELERATOR class (except_for="cpu",
allow_xpu=True) and a CUDA-only class for the Blackwell tests, and removes the
file from the test-linter allowlist. Recommendation: Approve. Every earlier
blocking finding is fixed or answered at HEAD, and the remaining points are all
non-blocking.

Findings (4):

[minor] test/inductor/test_subgraph_choice.py:246
Non-blocking: the custom-device gap is documented in a comment rather than
closed. get_desired_device_type_test_bases applies only_for at
common_device_type.py:1153, then adds bases named by
PYTORCH_TESTING_DEVICE_FOR_CUSTOM from the unfiltered list (:1180-1190). On a
Blackwell host with a custom backend and that variable set (the documented
out-of-tree workflow), the PrivateUse1 copies of all three methods pass
requires_blackwell_tma, since the probe only looks at torch.cuda, and then run
Blackwell Triton lowering on the wrong device. The linter's DecoratorRule is
registered only for ACCELERATOR (test_linter.py:688), so @​ onlyCUDA is allowed
on this HardwareClassification.CUDA class, and onlyOn("cuda") skips when
self.device_type is the custom backend (common_device_type.py:2015-2025). Fix:
add @​ onlyCUDA to the three methods and replace the "Known limitation" paragraph
with it, so the probe is only consulted where it applies to the instantiated
device.

[minor] test/inductor/test_subgraph_choice.py:230
Non-blocking: no pre-merge job runs the XPU variants. allow_xpu=True creates new
TestSubgraphChoiceXPU ids, but .github/workflows/xpu.yml:4-14 only runs on
ciflow/xpu/* tags, pushes to viable/strict, or its schedule. Neither
ciflow/trunk nor ciflow/inductor runs XPU tests, and the author has no XPU
hardware. The base did run this file on XPU (GPU_TYPE resolved to xpu). Add
ciflow/xpu so the migrated XPU path runs before landing instead of first running
on viable/strict.

[minor] test/inductor/test_subgraph_choice.py:159
Non-blocking: test_subgraph_freeze_layout depends on global padding config
instead of setting it (the gate/comment lines changed; the dependency is
pre-existing). The mat1.layout.stride == mat1_stride check at :201 holds only if
config.comprehensive_padding is on, which reads
TORCHINDUCTOR_COMPREHENSIVE_PADDING (config.py:1775-1777). _pad_strides
(ir.py:4777-4853) is device-independent; the only device-based switch-off is
compile_fx.py:920-926. So the is_gpu gate is not enough alone: the PR's own NPU
run passes the gate and fails at this bare AssertionError. Wrapping both
torch.compile and the call in config.patch(comprehensive_padding=True,
disable_padding_cpu=False) would make the test check what it claims on every
instantiated device and remove the need for the is_gpu skip. Turning the bare
raise AssertionErrors into self.assert* calls would make such failures readable.

[minor] test/inductor/test_subgraph_choice.py:229
Non-blocking: MTIA loses this file entirely (:229-231, :345). The old guard
reached MTIA hosts: HAS_GPU includes HAS_MTIA_AND_TRITON (inductor_utils.py:82),
and GPU_TYPE could be mtia. get_device_type_test_bases has no MTIA base, and in
fbcode it also drops the CUDA base on MTIA hosts
(common_device_type.py:1031-1037). The description raises this for maintainers,
but nobody has acknowledged it. An inductor/MTIA owner should confirm the loss
is acceptable before landing.

Reviewed commit: b8d321a (NOT the current head ca5dd7e)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ No Failures

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

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

@pytorch-bot

pytorch-bot Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "module: tests/inductor"

@pytorch-bot

pytorch-bot Bot commented Aug 7, 2026

Copy link
Copy Markdown

Didn't find following labels among repository labels: module: tests/inductor

@gavinwang269 gavinwang269 changed the title Decouple test_subgraph_choice.py for device-agnostic testing [Testcase Refactoring] Make test_subgraph_choice device-agnostic via instantiate_device_type_tests Aug 7, 2026
@gavinwang269
gavinwang269 force-pushed the test/inductor-subgraph-choice-decouple branch from 9b8ee8e to c27b613 Compare August 7, 2026 03:58
@jansel
jansel requested a review from zou3519 August 7, 2026 04:59
@gavinwang269
gavinwang269 force-pushed the test/inductor-subgraph-choice-decouple branch 9 times, most recently from dfa422c to 2084857 Compare August 7, 2026 09:08
@zou3519

zou3519 commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

@claude review this please and put the review inside a GitHub collapsible section

@claude

claude Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Claude finished @zou3519's task in 21m 35s —— View job


Reviewed — the conversion is mechanically fine, but except_for="cpu" is the wrong gate for these tests: it opts in every out-of-tree accelerator (which is why your own NPU run shows 1 failure) while silently dropping XPU, and the removal of the HAS_GPU guard drops the Triton requirement.

Claude's PR Review — click to expand

PR Review: #192435

Summary

Converts test/inductor/test_subgraph_choice.py from GPU_TYPE to instantiate_device_type_tests(..., except_for="cpu"). The device-parameter plumbing itself is correct, but the device-selection gate is wrong in both directions: it newly instantiates these tests on accelerators that cannot run them (your own NPU column shows 1 failed), and it silently removes XPU coverage that the old GPU_TYPE path had.

Testing

1. except_for="cpu" opts in out-of-tree backends that cannot run these tests — this is the NPU failure in your own table. (test/inductor/test_subgraph_choice.py:168)

except_for="cpu" does not mean "GPUs only". The candidate list is built by get_device_type_test_bases() (torch/testing/_internal/common_device_type.py:931-936), which unconditionally appends PrivateUse1TestBase whenever a privateuse1 backend is registered. except_for="cpu" only strips CPUTestBase (common_device_type.py:983-987), so on an NPU/openreg machine you get TestSubgraphChoicePRIVATEUSE1 instantiated.

Those tests cannot pass. The decompose-k path calls torch.bmm(..., out_dtype=torch.float32) (torch/_inductor/kernel/mm.py:233), and the lowering hard-checks the device:

# torch/_inductor/kernel/mm.py:337-340
torch._check(
    mat1.get_device().type in ("cuda", "xpu"),
    lambda: "out_dtype is only supported for CUDA or XPU",
)

bmm.dtype is only registered for CUDA and XPU (aten/src/ATen/native/native_functions.yaml:1390-1391).

This is a behavior regression, not a neutral change. Before this PR, on an NPU-only machine GPU_TYPE resolved to "cuda" (torch/_inductor/utils.py:114-121 — NPU is not in GPU_TYPES) and HAS_GPU was False, so the if HAS_GPU and HAS_CPU guard meant zero tests ran. After this PR, a test is collected and fails. The PR description reports this as Pass/failed is accelerator-specific — but a test that fails on your hardware after your change is a regression introduced by the change, not an accelerator quirk. The verification table saying Result: Pass on a row reading 0 passed / 1 failed should be corrected.

Use the gate the sibling GPU-only inductor test uses (test/inductor/test_gpu_select_algorithm.py:212-214):

instantiate_device_type_tests(
    TestSubgraphChoice, globals(), only_for=("cuda", "xpu"), allow_xpu=True
)

Fix this →

2. XPU coverage is silently dropped. (test/inductor/test_subgraph_choice.py:168)

XPUTestBase is only added when allow_xpu=True and TEST_XPU (common_device_type.py:1035-1036), and it is not in the default base list. There is no env-var escape hatch: PYTORCH_TESTING_DEVICE_ONLY_FOR / PYTORCH_TESTING_DEVICE_FOR_CUSTOM only filter the already-built list (common_device_type.py:1064-1086), so they cannot re-add a base that was never appended.

Before this PR, GPU_TYPE resolved to "xpu" on an Intel GPU machine (torch/_inductor/utils.py:115), so both tests ran there. After this PR, on an XPU box: CPU excluded, CUDA unavailable, XPU never added → zero tests instantiated, exit code 0. Coverage disappears with a green signal, which is worse than a failure. test/inductor/test_fp8.py:2210-2211 and test_gpu_select_algorithm.py:213 both pass allow_xpu=True for this reason.

3. The Triton requirement was dropped along with the HAS_GPU guard. (test/inductor/test_subgraph_choice.py:171-172)

HAS_GPU is not "a GPU exists" — it is HAS_CUDA_AND_TRITON or HAS_XPU_AND_TRITON or HAS_MTIA_AND_TRITON (torch/testing/_internal/inductor_utils.py:82). instantiate_device_type_tests gates only on torch.cuda.is_available() (common_device_type.py:932-933), with no Triton check. test/run_test.py:646 invokes test files as python test_*.py, so the if __name__ == "__main__" guard is live in CI — removing it is a real change, not dead code.

Consequence: on a CUDA machine without Triton, these mode="max-autotune" tests now get collected and run instead of being skipped. Keep an explicit guard, either on __main__ (as test/inductor/test_fp8.py:2216 does) or as a class-level @unittest.skipIf(not HAS_GPU, ...), which also survives pytest-based collection where __main__ does not.

Fix this →

Code Quality

4. hw_classification = HardwareClassification.ACCELERATOR is a misclassification. (test/inductor/test_subgraph_choice.py:29)

Per the enum docstring (torch/testing/_internal/common_utils.py:134-137), ACCELERATOR is for "behavior which must hold across every accelerator." These tests depend on bmm.dtype, which exists only for CUDA and XPU — the NPU failure in your own table is the proof that the invariant does not hold across every accelerator. Once finding #1 is fixed with only_for=("cuda", "xpu"), the classification and the instantiation gate will at least be consistent in intent; consider whether ACCELERATOR is still the honest label for a CUDA/XPU-only test.

5. _create_buffer is dead code; the PR extends its signature instead of deleting it. (test/inductor/test_subgraph_choice.py:34-38)

_create_buffer has no callers anywhere in the repo (the only hits are same-named, unrelated helpers in test_max_autotune.py:3913, test_dependencies.py:23, test_loop_ordering.py:1602). Threading a new device parameter through an uncalled method adds diff noise; delete it. The module-level decomposeK (lines 14-25) and the no-op setUp (lines 31-32) are likewise unused — reasonable to drop while you are already editing this class, since the real decomposeK lives at torch/_inductor/kernel/mm.py:224.

6. torch.device(device) wrapping is now redundant. (test/inductor/test_subgraph_choice.py:83-84, 100-101)

The injected device is already a device string ("cuda:0" per common_device_type.py:785), and torch.randn accepts a string directly. The torch.device(...) call was only needed to wrap the old f-string. device=device reads better and keeps these lines under the column limit without reformatting.

Recommendation

Request Changes

Findings #1 and #2 are behavioral regressions rather than stylistic issues: the PR turns a zero-test no-op into a hard failure on out-of-tree accelerators, and turns real XPU coverage into a silent zero-test pass. Both are addressed by only_for=("cuda", "xpu"), allow_xpu=True. Finding #3 should be resolved in the same pass, since dropping the Triton gate is easy to miss until a non-Triton CUDA configuration goes red.

| Branch: `test/inductor-subgraph-choice-decouple`

@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 7, 2026
@gavinwang269
gavinwang269 force-pushed the test/inductor-subgraph-choice-decouple branch 4 times, most recently from a3d411b to 2e46789 Compare August 11, 2026 06:17
@gavinwang269

gavinwang269 commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review! All points addressed in the latest push (2e46789):

1. except_for="cpu" vs only_for=("cuda", "xpu"): Keeping except_for="cpu". Per the convention established in #190173, ACCELERATOR test classes use except_for="cpu" + allow_xpu=True rather than only_for. This allows out-of-tree accelerators (e.g., NPU via PrivateUse1) to be instantiated and exercised.

2. XPU coverage: Fixed. Added allow_xpu=True to preserve XPU coverage.

3. Triton gating: Added @unittest.skipIf(not has_triton(), "requires triton") on both test methods, with has_triton imported from torch.utils._triton. This preserves the Triton requirement that was previously enforced via the HAS_GPU guard.

4. NPU verification — Updated (08-12): All tests now pass on NPU (Ascend 910B4).

Test Result
test_subgraph_decompose_k_npu ✅ PASSED
test_subgraph_freeze_layout_npu ✅ PASSED

The except_for="cpu" approach is validated: tests correctly run on out-of-tree accelerators and pass.

5. hw_classification: Keeping ACCELERATOR. The DecomposeKSugraphTemplate and autotune_select_algorithm are device-agnostic by design.

@github-project-automation github-project-automation Bot moved this from Backlog to Done in PyTorch Test Refactoring Nov 4, 2026
@gavinwang269 gavinwang269 reopened this Nov 4, 2026
@pytorch-bot
pytorch-bot Bot dismissed stale reviews from lizhihai137, lizhihai137, and lizhihai137 November 4, 2026 02:31

This PR was reopened (likely due to being reverted), so your approval was removed. Please request another review.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

Ready for human review: single-file migration of test/inductor/test_subgraph_choice.py to instantiate_device_type_tests (ACCELERATOR, except_for="cpu", allow_xpu=True) -- the same shape as the sibling PRs in this series. No change request is open on the current head and the automated-review findings from earlier rounds were all addressed in the diff. @eellison @jansel could one of you review/approve and land when convenient?

@fffrog fffrog moved this from Done to Developing in PyTorch Test Refactoring Nov 4, 2026
@jansel jansel added in progress PR is being worked on by the author, until the automated review accepts it and removed ready for review Automated review passed, ready for a final review by a maintainer. labels Nov 5, 2026

@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 b8d321a: nothing blocking; ready for human review.

The PR moves test/inductor/test_subgraph_choice.py onto instantiate_device_type_tests, using an ACCELERATOR class (except_for="cpu", allow_xpu=True) and a CUDA-only class for the Blackwell tests, and removes the file from the test-linter allowlist. Recommendation: Approve. Every earlier blocking finding is fixed or answered at HEAD, and the remaining points are all non-blocking.

⚪ 4 non-blocking findings

# the bottom of this file binds the class to cuda. Known limitation:

Non-blocking: the custom-device gap is documented in a comment rather than closed. get_desired_device_type_test_bases applies only_for at common_device_type.py:1153, then adds bases named by PYTORCH_TESTING_DEVICE_FOR_CUSTOM from the unfiltered list (:1180-1190). On a Blackwell host with a custom backend and that variable set (the documented out-of-tree workflow), the PrivateUse1 copies of all three methods pass requires_blackwell_tma, since the probe only looks at torch.cuda, and then run Blackwell Triton lowering on the wrong device. The linter's DecoratorRule is registered only for ACCELERATOR (test_linter.py:688), so @ onlyCUDA is allowed on this HardwareClassification.CUDA class, and onlyOn("cuda") skips when self.device_type is the custom backend (common_device_type.py:2015-2025). Fix: add @ onlyCUDA to the three methods and replace the "Known limitation" paragraph with it, so the probe is only consulted where it applies to the instantiated device.


TestSubgraphChoice, globals(), except_for="cpu", allow_xpu=True

Non-blocking: no pre-merge job runs the XPU variants. allow_xpu=True creates new TestSubgraphChoiceXPU ids, but .github/workflows/xpu.yml:4-14 only runs on ciflow/xpu/* tags, pushes to viable/strict, or its schedule. Neither ciflow/trunk nor ciflow/inductor runs XPU tests, and the author has no XPU hardware. The base did run this file on XPU (GPU_TYPE resolved to xpu). Add ciflow/xpu so the migrated XPU path runs before landing instead of first running on viable/strict.


if not is_gpu(self.device_type):

Non-blocking: test_subgraph_freeze_layout depends on global padding config instead of setting it (the gate/comment lines changed; the dependency is pre-existing). The mat1.layout.stride == mat1_stride check at :201 holds only if config.comprehensive_padding is on, which reads TORCHINDUCTOR_COMPREHENSIVE_PADDING (config.py:1775-1777). _pad_strides (ir.py:4777-4853) is device-independent; the only device-based switch-off is compile_fx.py:920-926. So the is_gpu gate is not enough alone: the PR's own NPU run passes the gate and fails at this bare AssertionError. Wrapping both torch.compile and the call in config.patch(comprehensive_padding=True, disable_padding_cpu=False) would make the test check what it claims on every instantiated device and remove the need for the is_gpu skip. Turning the bare raise AssertionErrors into self.assert* calls would make such failures readable.


instantiate_device_type_tests(

Non-blocking: MTIA loses this file entirely (:229-231, :345). The old guard reached MTIA hosts: HAS_GPU includes HAS_MTIA_AND_TRITON (inductor_utils.py:82), and GPU_TYPE could be mtia. get_device_type_test_bases has no MTIA base, and in fbcode it also drops the CUDA base on MTIA hosts (common_device_type.py:1031-1037). The description raises this for maintainers, but nobody has acknowledged it. An inductor/MTIA owner should confirm the loss is acceptable before landing.

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

@pytorch-bot pytorch-bot Bot added the ready for review Automated review passed, ready for a final review by a maintainer. label Nov 5, 2026
@gavinwang269

gavinwang269 commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor Author

cc @jansel - small one to pick up while you are in this area: @lizhihai137 approved, CI is green, it just needs a maintainer to land it. It removes the CUDA-only assumption from the subgraph-choice test helper so out-of-tree backends can run it (+199/-179 across the test file and the test-linter allowlist entry it deletes, per the series convention of removing allowlist lines when a file gets converted). Correction to my earlier draft: the diff is the size stated here, not "34 lines".

@gavinwang269

Copy link
Copy Markdown
Contributor Author

@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 3 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team

Raised by workflow job

Failing merge rule: Core Maintainers

…duate it from the test linter

Rewrite the gating in test/inductor/test_subgraph_choice.py so every device decision
is a capability answer about the instantiated device, then drop the file from the
test-linter migration ledger now that it satisfies the ACCELERATOR rules.

Three upstream layers touch this feature, and they are not the same question:

- native_functions.yaml registers aten bmm.dtype / bmm.dtype_out for CUDA and XPU,
  but an out-of-tree backend may register its own lowering for the same op;
- Inductor's generic aten.bmm lowering raises "out_dtype is only supported for CUDA
  or XPU" (torch/_inductor/kernel/bmm.py:361-363) for whatever reaches it;
- the decompose-K heuristic template ships real heuristics for cuda and xpu with an
  empty opt-out class and a TODO to widen
  (torch/_inductor/heuristics/template/decompose_k.py:30-49).

Measured here on an Ascend 910B4 host with torch_npu registered, the aten variants
do reach lowering and fail inside torch_npu's own registration:

    LoweringException: TypeError: _register_npu_inductor_bmm.<locals>.tuned_bmm()
    takes 2 positional arguments but 3 were given

-- torch._inductor.kernel.bmm's "CUDA or XPU" assertion is never evaluated on that
path. So mirroring bmm.py's device list in the test would be wrong twice over: it
would restate an upstream name list inside a device-agnostic test, and it would keep
permanently skipped a backend that does implement out_dtype (here, one that merely
implements it incorrectly today). The support question is therefore not encoded at
all in this file: the tests run wherever their real requirements hold, and the
torch_npu defect is left to fail visibly rather than hidden behind a skip.

Changes:

- Removed the module-level GPU_TYPE: the base was one
  @instantiate_parametrized_tests class that built every tensor on GPU_TYPE;
  tensors are now built on the device the instantiated variant is bound to. The
  file's Blackwell gates are import-time
  @unittest.skipUnless(has_datacenter_blackwell_tma_device(), ...) decorators
  answering one process-wide question, defined once at module level as
  requires_blackwell_tma and applied only to the CUDA-only class below; the
  accelerator class needs no Blackwell gate because it runs no Triton
  decompose-K code.
- Moved every Blackwell-only Triton test into a dedicated TestSubgraphChoiceCUDAOnly
  class (hw_classification=CUDA, instantiate_device_type_tests(..., only_for="cuda")):
  test_decompose_k_partial_freezes_producer_layout, test_decompose_k_bmm_backends, and
  the Triton half of test_subgraph_decompose_k, now named
  test_subgraph_decompose_k_triton there. The base carried these three tests in
  its single class: the two siblings already had the import-time
  @unittest.skipUnless decorators, and the Triton half of
  test_subgraph_decompose_k was gated by an in-body self.skipTest that the class
  split replaces. All three now carry the single module-level requires_blackwell_tma
  gate; the probe is process-wide, so on a class instantiated only_for="cuda" it
  normally answers for CUDA's own hardware, with the PYTORCH_TESTING_DEVICE_FOR_CUSTOM
  caveat stated in the class comment instead of papered over. The split is what
  removes the Blackwell
  exposure from the accelerator class: the class instantiated for XPU and out-of-tree
  backends no longer generates any Triton decompose-K variant, and no longer generates
  the meta_ws / config_index combinations that only ever meant something to the Triton
  backend. The base always collected -- and skipped in-body -- six aten ids
  built from that cross product (two dtypes x three skipped combos); those
  variants are gone entirely, so no skipped id of that shape survives on XPU or
  out-of-tree.
  test_subgraph_decompose_k is therefore split by backend into
  test_subgraph_decompose_k_aten on the accelerator class (a single variant
  per dtype) and test_subgraph_decompose_k_triton on the CUDA-only class (its
  meta_ws and config_index parametrizes and its MetaWS skip), so the ids name
  the backend again the way the base's backend_aten / backend_triton
  parametrization did. The shared
  computation lives in a module-level _run_decompose_k_case(self, ...) helper -- a plain
  function that takes the TestCase instance, not a TestCase subclass alias, so pytest
  still collects exactly one accelerator and one CUDA-only class rather than a second
  copy of every id. The helper appends its one choice through the subgraph
  template exactly as the base's inline body did
  (DecomposeKSubgraphTemplate().maybe_append_choice, autotune_select_algorithm,
  run_and_get_code(torch.compile(fn), ...)) and, like the base body, passes
  k_split, bmm_backend and bmm_config_index explicitly: SubgraphTemplate keeps
  the base KernelTemplate.maybe_append_choice, which calls generate() directly,
  so the registered template heuristics are not consulted on this path. The
  CUDA-only class holds 13 ids on a
  CUDA host (8 Triton decompose-K variants: meta_ws x config_index x two dtypes; 1
  partial producer-layout; 4 bmm-backends). Each instantiated accelerator class holds
  3 ids: the aten decompose-K case in bf16 and fp32, and freeze-layout.
- @requires_triton() (family rule, and this file's Triton variants need a Triton
  backend) plus an in-body check for what remains in the accelerator class:
  test_subgraph_freeze_layout gates on is_gpu(self.device_type), the predicate
  compile_fx.maybe_disable_comprehensive_padding uses to switch comprehensive padding
  off for graphs with no GPU-class input (config.disable_padding_cpu); the stride
  assertions below need that padding, which is on by default. is_gpu is
  derived from the registered accelerator types (which cover cuda, mps, mtia, npu and
  xpu on this host), so it answers True here and the test runs, rather than being
  skipped by a name list.
- @dtypes(torch.bfloat16, torch.float32) instead of @parametrize("dtype", ...), which
  replaces the `dtype_bfloat16` id segment with the dtypes-generated `bfloat16` suffix.
- No xfail machinery is carried. Upstream keeps no marker for the torch_npu defect:
  the three PrivateUse1 ids fail visibly, and a backend excludes them through
  PrivateUse1TestBase.set_test_configs(test_exclusions=...)
  (torch/testing/_internal/common_device_type.py:419, :502; set_test_configs itself
  :625), the form documented
  in docs/source/accelerator/testing.md. An upstream expectedFailure naming the
  measured ids would be a backend's own exclusion list written into the
  device-agnostic tree -- the ids carry that backend's device suffix, so the table
  is a name list wearing a marker -- and exactly the coupling this file is being
  migrated away from. Failing visibly instead lets each backend decide how to
  suppress its own known-broken lowering without upstream naming it.
- Runner guard now uses `if has_triton(): run_tests(needs="filelock")`, matching the
  convention in the sister file test/inductor/test_mem_estimation.py:364. That single
  has_triton() guard is what replaces the removed HAS_GPU / HAS_CPU gate: the file's
  accelerator variants still run wherever a Triton toolchain exists, and the whole
  module simply does nothing under the bare runner when Triton is absent.

Per-device answers, and what is not a per-device answer:

The accelerator class (TestSubgraphChoice, hw_classification=ACCELERATOR,
instantiate_device_type_tests(..., except_for="cpu", allow_xpu=True)) answers per-device
through three things only: the instantiation scope itself (a variant exists only for a
registered accelerator base), is_gpu(self.device_type) in test_subgraph_freeze_layout,
and -- inside the separate CUDA-only class -- has_datacenter_blackwell_tma_device().
@requires_triton() is not one of them: it is a process-wide toolchain-existence check
for whether Triton can be imported at all, not a question about which accelerator the
instantiated variant runs on. The CUDA-only class (TestSubgraphChoiceCUDAOnly,
instantiate_device_type_tests(..., only_for="cuda")) is instantiated only where CUDA is
registered, so the Blackwell probe it consults is normally a probe of that class's own
device; the exception is PYTORCH_TESTING_DEVICE_FOR_CUSTOM, which appends matching
device bases after the only_for filter, and the class comment states that limitation.

Which jobs run this file:

The accelerator tests run on CUDA default shards (test_python_shard discovery), on ROCm
default shards, and on XPU default shards. Only the Blackwell-gated ids have no trunk
job, because no Blackwell hardware exists in trunk CI. The refactored Triton half --
the whole CUDA-only class -- has therefore not been exercised on CUDA, Blackwell or
XPU hardware at this head: the host used for the measurements below has neither a
CUDA nor an XPU device. One scope change is worth flagging
for maintainer attention: the old __main__ path gated on HAS_GPU and HAS_CPU (tensors
built on GPU_TYPE) and could reach MTIA hosts -- HAS_GPU includes HAS_MTIA_AND_TRITON
(inductor_utils.py:82) -- whereas get_device_type_test_bases has no MTIA base, so
after this change the file contributes no tests to MTIA-labeled runs.

Test Plan

Measured on an Ascend 910B4 host (no CUDA, no XPU hardware) against installed
torch + torch_npu nightlies. pytest is pointed at the test file inside this
checkout from a directory that is not the repo root, so the installed package is
imported (running from the repo root of a source build is equivalent). The NPU
venv sources the CANN set_env.sh first; the lintrunner line needs lintrunner on
PATH.

```
python -m pytest test/inductor/test_subgraph_choice.py --collect-only -q
# NPU venv: 3 tests collected, all under TestSubgraphChoicePRIVATEUSE1:
#   TestSubgraphChoicePRIVATEUSE1::test_subgraph_decompose_k_aten_npu_bfloat16
#   TestSubgraphChoicePRIVATEUSE1::test_subgraph_decompose_k_aten_npu_float32
#   TestSubgraphChoicePRIVATEUSE1::test_subgraph_freeze_layout_npu
# No *_npu ids of the CUDA-only class (only_for="cuda", and no CUDA on this host).
python -m pytest -q -rs test/inductor/test_subgraph_choice.py
# NPU venv: 3 failed, 0 skipped. Each fails visibly, no marker. The two
# test_subgraph_decompose_k_aten ids fail inside torch_npu's own bmm registration:
#   LoweringException: TypeError: _register_npu_inductor_bmm.<locals>.tuned_bmm()
#   takes 2 positional arguments but 3 were given
# test_subgraph_freeze_layout_npu trips the file's own stride-equality check:
#   LoweringException: AssertionError:
#   target: mylib.matmul_decompose_padding.default
TORCH_DEVICE_BACKEND_AUTOLOAD=0 python -m pytest test/inductor/test_subgraph_choice.py --collect-only -q
# no tests collected (rc 5) in a venv where the guard is effective (in the NPU venv a
# sitecustomize force-imports torch_npu regardless of the guard): the accelerator
# instantiation (except_for="cpu") has no accelerator base to bind to and the
# CUDA-only instantiation (only_for="cuda") has no CUDA present.
python3 tools/linter/adapters/test_linter.py test/inductor/test_subgraph_choice.py
# 0 findings from the repo root.
lintrunner -a test/inductor/test_subgraph_choice.py
# ok No lint issues. rc=0
```

The out-of-tree value is that no capability question is answered by a device-name list:
the only Blackwell answer lives inside the class instantiated only_for="cuda" (whose
PYTORCH_TESTING_DEVICE_FOR_CUSTOM caveat is stated in-file), the only GPU-class answer
is is_gpu(self.device_type), and the torch_npu
defect is left for the backend to suppress with its own exclusions rather than named
upstream.
@gavinwang269

Copy link
Copy Markdown
Contributor Author

@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 3 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team

Raised by workflow job

Failing merge rule: Core Maintainers

@gavinwang269

Copy link
Copy Markdown
Contributor Author

@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

@georgehong

Copy link
Copy Markdown
Contributor

@pytorchbot revert -m "Reverting only to unblock a clean revert of #196769, which breaks internal tests. This PR refactored test_subgraph_choice.py on top of it. Can reland upon rebasing, although merge conflicts may need to be addressed" -c ghfirst

@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

@gavinwang269 your PR has been successfully reverted.

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

Labels

ci-no-td Do not run TD on this PR ciflow/inductor ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor module: tests/graph This label covers all test cases within the Graph sheet. open source ready for review Automated review passed, ready for a final review by a maintainer. Reverted 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.

10 participants