Skip to content

[Inductor] Add backend hooks for C++ wrapper routing and device properties - #190615

Closed
srhust wants to merge 2 commits into
pytorch:mainfrom
srhust:inductor/device-identity-from-interface
Closed

srhust wants to merge 2 commits into
pytorch:mainfrom
srhust:inductor/device-identity-from-interface

Conversation

@srhust

@srhust srhust commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add backend extension points for C++ wrapper routing and device-property
metadata so out-of-tree accelerator backends can participate in these Inductor
paths without hardcoding their device names in core.

Changes

  • Add DeviceOpOverrides.uses_gpu_cpp_wrapper() with a default of False.
    CUDA and XPU override it to True, preserving the existing C++ wrapper
    routing behavior for in-tree backends.
  • Use uses_gpu_cpp_wrapper() in both GraphLowering C++ wrapper decisions:
    the two-pass wrapper-codegen gate and the device selection used for JIT
    wrapper compilation.
  • Treat unregistered devices conservatively as not using the GPU-style C++
    wrapper path.
  • Add DeviceInterface.get_multi_processor_count(). The default implementation
    reads the standard multi_processor_count device-property field and asks
    backends with a different representation to override the method.
  • Preserve the existing XPU behavior through gpu_subslice_count and the
    existing MTIA value of 64.
  • Make DeviceProperties.create() obtain the compute-unit count through
    DeviceInterface.get_multi_processor_count().

Motivation

Two Inductor paths currently encode backend-specific assumptions directly in
core: C++ wrapper routing recognizes CUDA/XPU by device name, and
DeviceProperties.create() contains device-specific handling for compute-unit
metadata.

For an out-of-tree backend, these differences are properties of the backend
rather than properties of Inductor itself. DeviceOpOverrides already owns
backend-specific codegen behavior, while DeviceInterface already owns
backend device properties.

Exposing the two decisions through those existing contracts lets registered
backends provide their behavior directly without adding out-of-tree device
names or property layouts to Inductor core.

Test Plan

  • CI: python test/inductor/test_device_identity.py
  • Added device-independent tests for get_multi_processor_count():
    standard-property behavior, missing-property error handling, the XPU
    gpu_subslice_count override, and the MTIA fixed value.
  • Added a DeviceProperties.create() test using a fake DeviceInterface to
    verify that the compute-unit count is obtained through the interface
    contract.
  • Added C++ wrapper-routing tests covering CUDA/XPU opt-in, CPU/MPS default
    behavior, an out-of-tree DeviceOpOverrides opt-in, the default
    out-of-tree behavior, and an unregistered device.
  • The tests use fake interfaces / registered overrides and mocks where needed,
    so the new coverage does not require accelerator hardware.

Notes

  • uses_gpu_cpp_wrapper() is a backend codegen capability rather than a
    general device-classification predicate. Both relevant GraphLowering
    call sites use the same capability.
  • The default behavior of both extension points is conservative:
    DeviceOpOverrides does not opt into GPU-style wrapper routing, while
    DeviceInterface.get_multi_processor_count() uses the standard device
    property when available.
  • Existing CUDA/XPU C++ wrapper routing and XPU/MTIA compute-unit behavior are
    preserved.

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

@pytorch-bot

pytorch-bot Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit 1d9ff4d with merge base ad4f58f (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@linux-foundation-easycla

linux-foundation-easycla Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: srhust / name: srhust (d2e140e)

@pytorch-bot

pytorch-bot Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

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

@pytorch-bot

pytorch-bot Bot commented Jul 21, 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/inductor
  • 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.

@srhust

srhust commented Jul 21, 2026

Copy link
Copy Markdown
Contributor Author

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.

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Jul 21, 2026
@srhust
srhust force-pushed the inductor/device-identity-from-interface branch 4 times, most recently from 663aa76 to 4030681 Compare July 21, 2026 09:41
@soulitzer
soulitzer requested review from eellison and jansel July 21, 2026 21:51
@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 21, 2026
@srhust
srhust force-pushed the inductor/device-identity-from-interface branch from 4030681 to 0291319 Compare July 22, 2026 07:34
@jansel

jansel commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 14m 34s —— View job


PR Review: #190615

Summary

Routes Inductor's device identity/capability predicates (is_gpu, has_triton, device_need_guard, DeviceProperties.create) through the DeviceInterface contract instead of hardcoded device-name lists, so out-of-tree PrivateUse1 backends can opt in. The design is sound and the in-tree mappings look faithful, but there are a few correctness concerns and a doc/comment that doesn't match the code.

Full review details

Code Quality

  • torch/_inductor/utils.py:107-111 — the comment contradicts the code. The comment says GPU_TYPES is "a late-binding compatibility shim backed by the private _gpu_types()", but GPU_TYPES is still a plain hardcoded literal ["cuda", "mps", "xpu", "mtia"] — it is not backed by _gpu_types() in any way. A PrivateUse1 backend that opts into is_gpu() will be picked up by is_gpu()/_gpu_types()/get_gpu_type() but will not appear in GPU_TYPES, so the two live call-sites that still iterate GPU_TYPES (torch/_inductor/fx_passes/freezing_patterns.py:131 and torch/testing/_internal/inductor_utils.py:100) silently exclude that backend. Either make GPU_TYPES actually delegate (e.g. a module-__getattr__ / lazy proxy that calls _gpu_types()) or reword the comment to state plainly that it remains a static list and is a divergence risk. As written the comment is misleading. Fix this →

  • torch/_dynamo/device_interface.py:160,261,296 and hints.py:202, test line 48 — non-ASCII characters in newly added comments/docstrings. CLAUDE.md requires ASCII-only in new comments. The box-drawing chars (──), em dash (—), and arrows (→) violate this. Replace with ASCII (#---, -, ->).

Testing

  • test/inductor/test_device_identity.py — the tests are almost entirely tautological / smoke tests and do not verify the behavioral equivalence the PR claims. Most assert only isinstance(result, bool) or don't-crash (test_has_triton_discovers_registered_device, test_returns_string, test_create_for_cpu). The PR description claims "behavior equivalence verified over the in-tree device matrix... old vs new all match" — but no test encodes that. The one genuinely new behavior worth locking down — that a registered PrivateUse1 interface flows through device_need_guard, has_triton, and get_gpu_type (not just is_gpu) — is not tested. test_privateuse1_gpu_after_opt_in only exercises is_gpu. Add a test registering an interface that declares is_gpu()=True + a real Stream override and assert device_need_guard(...)==True, plus one asserting get_gpu_type() disambiguation actually returns the PrivateUse1 type when it coexists with cuda.

  • get_gpu_type() disambiguation path is untested. The new PrivateUse1-first branch (utils.py:138-146) using torch.accelerator.current_accelerator() is the riskiest new logic (see below) and has zero coverage. It only runs when len(avail_gpus) != 1, which the CI machines won't hit, so it will ship unexercised.

API Design / Correctness

  • get_gpu_type() semantics changed silently (utils.py:133-147). The old code asserted "at most 1 available GPU type" and returned "cuda" on zero. The new code, when len(avail_gpus) != 1 (i.e. zero or 2+), consults torch.accelerator.current_accelerator(). In the >1 case this is a genuine behavior change — previously a hard error, now a silent pick. That's probably the intent, but if current_accelerator() returns something not in avail_gpus (or a non-GPU), it falls through to avail_gpus[0] whose ordering depends on dict-registration order of get_registered_device_interfaces() — nondeterministic-ish and unasserted. Worth a comment documenting the chosen precedence, and guarding that the accelerator is actually among the available GPU types before returning it.

  • has_triton() CUDA path now bypasses the Worker device-properties cache (_triton.py + CudaInterface.is_triton_capable). The old cuda_extra_check used device_interface.Worker.get_device_properties().major >= 7 — the Worker API exists specifically so compile subprocess workers (post-fork, no CUDA init) can read cached properties. The new path calls iface.is_triton_capable(), and CudaInterface.is_triton_capable calls torch.cuda.get_device_properties(device).major directly. has_triton() is invoked from torch/_inductor/runtime/autotune_cache.py:70, which runs in runtime/worker contexts. If has_triton() is ever evaluated (cache cold) inside a forked worker that can't touch the CUDA driver, this is a regression vs. the Worker-cached path. Please confirm has_triton() is only ever first-computed in the main process, or route the capability check through Worker. (Medium confidence — depends on where the functools.cache gets warmed.)

Backward Compatibility

  • DeviceProperties.create now hard-fails for a registered non-GPU backend that lacks multi_processor_count (hints.py:206). The old ladder had try/except AttributeError and only the default branch re-raised; the base-class get_multi_processor_count does get_device_properties(device).multi_processor_count with no fallback. Behavior for cuda/xpu/mtia/mps/cpu is preserved (each supplies the field or overrides), so in-tree is fine, but any out-of-tree interface that previously reached DeviceProperties.create and relied on the old except AttributeError: raise getting a clearer failure now just gets a bare AttributeError. Minor, but the base default silently assumes the standard field exists — a targeted error message ("interface must override get_multi_processor_count") would be friendlier.

Recommendation

Request Changes — primarily the misleading GPU_TYPES comment vs. the two remaining GPU_TYPES call-sites (a real divergence bug for PrivateUse1 backends, which is the PR's whole motivation), the ASCII-only comment violations, and the thin/tautological test coverage that doesn't lock down the equivalence or the new get_gpu_type/device_need_guard PrivateUse1 flow. The has_triton Worker-cache question should be confirmed before merge.
· branch inductor/device-identity-from-interface

@srhust
srhust force-pushed the inductor/device-identity-from-interface branch from 0291319 to 9f54a03 Compare July 23, 2026 01:40
@jansel

jansel commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes again

@claude

claude Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 4m 19s —— View job


PR Review: #190615 (re-review)

Routes Inductor's device identity/capability predicates through the DeviceInterface contract. Since the last review, most findings were addressed: the GPU_TYPES comment now honestly states it stays static and names the un-migrated call-sites; get_gpu_type() now guards that the accelerator is GPU-class and present before returning it; non-ASCII comment chars are gone; CpuInterface.is_triton_capable guards the triton import; and has_triton/get_multi_processor_count carry justification comments. A few items remain.

Full review details

Code Quality

  • torch/_inductor/utils.py:107-113 — the shim comment omits a third live call-site. It names freezing_patterns.py and inductor_utils.py as the call-sites that still iterate GPU_TYPES and will exclude PrivateUse1 backends, but misses torch/testing/_internal/common_device_type.py:1560 (skipGPUIf/skipCUDAIf-style base passing device_type=GPU_TYPES). Since the comment is explicitly enumerating the divergence risk, it should be complete. Either list all three or reword to "several call-sites (grep GPU_TYPES)". Fix this →

Testing

  • get_gpu_type() coexistence path (utils.py:139-147) is still effectively untested. test_privateuse1_discovered_by_get_gpu_type only asserts membership in _gpu_types(); it never calls get_gpu_type() in a state where len(avail_gpus) != 1, so the new torch.accelerator.current_accelerator() disambiguation branch — the riskiest new logic — ships unexercised. The branch is testable without hardware: register two fake interfaces that both report is_available()==True and is_gpu()==True, patch torch.accelerator.current_accelerator() to return one of them, and assert get_gpu_type() returns it. Please add that.

  • test_has_triton_discovers_registered_device asserts only isinstance(result, bool). It doesn't lock down the new registry-walk behavior (it would pass against the old hardcoded-dict implementation too). Consider registering a fake interface with is_triton_capable()==True and a no-op raise_if_triton_unavailable, then asserting has_triton() returns True — that is the actual new discovery path.

Correctness

  • has_triton() CUDA path bypasses the Worker device-properties cache. The new CudaInterface.is_triton_capable (device_interface.py:321) calls torch.cuda.get_device_properties(device).major directly, whereas the old cuda_extra_check used Worker.get_device_properties(). The added comment (device_interface.py:319-323) argues this is safe because has_triton() is @functools.cache'd and warmed in the main process before any worker fork. That reasoning is only sound if the cache is guaranteed warm pre-fork — has_triton() is called from autotune_cache.py:70, which runs in worker contexts. If a worker is ever the first to evaluate has_triton() cold (cache not inherited across the fork, or a spawn-start-method pool), this touches the CUDA driver in a subprocess that may not have initialized CUDA. Worth confirming the warm-before-fork invariant holds for all worker start methods, or routing the capability probe through Worker to be safe. (Medium confidence.)

  • get_gpu_type() >1-GPU fallthrough ordering (utils.py:147). When two GPU types coexist and the accelerator isn't among them, the return is avail_gpus[0], whose order derives from get_registered_device_interfaces() dict-insertion order. This is non-obvious; a one-line comment noting the fallthrough is best-effort/registration-ordered would help. Minor.

Recommendation

Request Changes (soft) — the substantive prior findings are resolved. Remaining blockers are test coverage for the two genuinely-new paths (get_gpu_type coexistence disambiguation and has_triton registry discovery), which currently ship unexercised. The has_triton Worker-cache invariant should be confirmed, and the GPU_TYPES comment completed. None of these require design changes.
· branch inductor/device-identity-from-interface

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

address automated feedback from claude

@srhust
srhust force-pushed the inductor/device-identity-from-interface branch from 9f54a03 to 79b6b8e Compare July 24, 2026 15:27
@srhust

srhust commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor Author

@jansel Could you please rerun the failed CI job?
linux-jammy-cuda13.2-cudnn9-py3.10-clang18 / build failed during Initialize containers with ErrImagePull / ImagePullBackOff, before the build or tests started. This appears to be an infrastructure failure.

@jansel

jansel commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased inductor/device-identity-from-interface onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout inductor/device-identity-from-interface && git pull --rebase)

@FuDdd

FuDdd commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorch-bot

pytorch-bot Bot commented Aug 25, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

@jansel

jansel commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

@claude review again, update your reland safety analysis based on the above discussion and the new code

@claude

claude Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 11m 22s —— View job


PR Review: #190615 — re-review + updated reland-safety analysis

  • Read the current diff (git diff ad4f58f7...HEAD)
  • Verify the getattr fallbacks for MTIA/XPU were applied
  • Verify the _uses_gpu_cpp_wrapper device set is exactly {cuda, xpu}
  • Review the new test_device_backend_hooks.py coverage
  • Re-assess reland risk against the posted root-cause analysis

Bottom line: all three of my pre-merge conditions are now met, and the diff is a provable in-tree no-op for every registered device. Reland risk drops to low — the only remaining item worth doing before merge is an fbcode grep for name collisions, which is a check rather than a code change.

Full review details

What changed since the last pass

Every substantive item from my previous two reviews and from metamate's follow-up has been addressed:

Prior finding Status
MTIA hardcoded 64 unconditionally (the one behavioral delta) Fixed — getattr(cls.get_device_properties(device), "multi_processor_count", 64) (device_interface.py:395-400)
XPU dropped the multi_processor_count-first precedence Fixed — getattr(props, "multi_processor_count", None) or props.gpu_subslice_count (device_interface.py:488-490)
_uses_gpu_cpp_wrapper wedged into graph.py Fixed — moved to common.py:718-721, next to get_device_op_overrides
except KeyError swallowing errors from the 5-module import chain Fixed — now device_op_overrides_dict.get(device) after an explicit _initialize_device_op_overrides()
uses_gpu_cpp_wrapper name invites the MPS/MTIA trap Addressed via docstring (common.py:328-336), which now names MPS and MTIA explicitly as CppWrapperGpu users that must still return False. Not renamed, but the trap is documented at the definition site — acceptable.
No CI-enforced {"cuda","xpu"} invariant Fixed — test_builtin_devices (test_device_backend_hooks.py:96-101)
No cpu_backend="triton" regression test Fixed — test_cpu_triton_does_not_use_gpu_cpp_wrapper (line 103-106)
test_mtia_override pinned only the constant Fixed — both branches asserted via side_effect (lines 50-60), same for XPU (38-48)
Filename didn't describe contents / collided with #190326 Fixed — renamed to test_device_backend_hooks.py

Verification I did rather than took on faith

The getattr fallbacks are provably equivalent to the old ladder. The old code (hints.py, pre-PR) read props from device_interface.get_device_properties(device) and the new overrides read from cls.get_device_properties(device) — the same source, so the case analysis is complete:

  • MTIA in OSS: torch.mtia.get_device_properties is annotated dict[str, Any] (torch/mtia/__init__.py:285) and a dict has no such attribute → 64, matching the old except AttributeError branch.
  • MTIA internally, if getDeviceProperties returns an object exposing the field → both old and new read the real value. This is the case that previously worried me, and the getattr closes it without needing internal visibility.
  • XPU: Module.cpp:355 exposes only gpu_subslice_count, so getattr(..., None) is None → gpu_subslice_count, matching old behavior exactly.
  • CUDA/HIP: CudaInterface.get_device_properties = staticmethod(torch.cuda.get_device_properties) (device_interface.py:277), field present, base implementation reads it. Note this is the same non-Worker path the old hints.py used, so there is no Worker-cache regression here — my concern from an earlier round genuinely does not apply to this diff.
  • CPU / MPS / TPU: CpuDeviceProperties (516-517), MPSProperties (614), TPUProperties (656) all carry multi_processor_count → base implementation, unchanged.

The _uses_gpu_cpp_wrapper True set is exactly {"cuda", "xpu"}. I enumerated every registration reachable from _initialize_device_op_overrides (common.py:688-708): mps, mtia, cuda, tpu (via CpuDeviceOpOverrides), cpu, xpu. Only CUDADeviceOpOverrides (cuda/device_op_overrides.py:19) and XPUDeviceOpOverrides (xpu/device_op_overrides.py:12) override the method; MTIADeviceOpOverrides and MPSDeviceOpOverrides do not. "meta" and unregistered devices hit .get() → None → False, identical to device in ["cuda","xpu"]. Both call sites (graph.py:2599, graph.py:2909) substitute the identical predicate for the identical literal.

The two failure modes named in the root-cause analysis are structurally excluded, not incidentally avoided. mtia returns the default False and stays on the single-pass path. cpu under cpu_backend="triton" returns False because the predicate never consults config.cpu_backend at all — unlike ir.is_triton, which does (ir.py:456-459). That is the important distinction: the new gate cannot follow the config in the way that caused the revert, and test_cpu_triton_does_not_use_gpu_cpp_wrapper pins exactly that. This is the analysis's own preferred remedy (option 2: dedicated opt-in capability, default False, only CUDA/XPU opting in), with the only deviation being that it lives on DeviceOpOverrides rather than DeviceInterface — the better home, since it is a codegen capability.

Remaining comments (all minor, none blocking)

1. getattr(...) or props.gpu_subslice_count treats 0 as absent (device_interface.py:490). or falls through on any falsy value, so a properties object reporting multi_processor_count = 0 would silently use gpu_subslice_count, where the old ladder returned 0. Unreachable today (XPU has no such field) and arguably the more useful behavior, but is None would be exact:

mp_count = getattr(props, "multi_processor_count", None)
return props.gpu_subslice_count if mp_count is None else mp_count

Fix this →

2. Stray blank line in graph.py (line 148). The diff adds a second blank line between perf_hint_log = ... and aten = torch.ops.aten. Pure noise in an otherwise tight diff — worth dropping so the graph.py hunk is only the two gate substitutions plus the import.

3. test_builtin_devices is sensitive to registry pollution from other test files. It asserts an exact set over the process-global device_op_overrides_dict. That is the right invariant and I'd keep it, but note test_extension_backend.py:129 and test_triton_extension_backend.py:120 register additional devices in the same process if the shard runs them together. Both use CpuDeviceOpOverrides (which returns False), so the assertion holds today — it just means a future extension test that opts in would fail this file rather than its own. Acceptable tradeoff; flagging so a future failure isn't mysterious.

4. device_op_overrides_dict.pop(name, None) bypasses device_op_overrides_lock that register_device_op_overrides holds (common.py:684-685). Harmless single-threaded, just asymmetric with the registration it undoes.

5. hints.py:201-202 fetches props, then the base get_multi_processor_count fetches it again. Harmless — create is functools.cache'd and torch.cuda.get_device_properties is itself cheap/cached. Noting only so it's deliberate.

6. Design note, unchanged. The docstring now warns backend authors off the MPS/MTIA trap, which was my main ask. I'd still mildly prefer a behavioral name (needs_two_pass_aoti_codegen), since a name that contradicts the registry for half the devices it classifies is a durable readability cost and the docstring only helps readers who open common.py. Non-blocking, and reasonable to defer.

Updated reland-risk assessment

Risk: low. Compared to my last assessment ("low with two small additions"), both additions landed. Concretely:

What the reland now consists of, behaviorally: nothing. Every in-tree device produces identical values and takes identical code paths. The new surface is two default-off, opt-in extension points plus one test file. That is a materially smaller blast radius than the reverted version, which contained the is_gpu/GPU_TYPES/get_gpu_type/device_need_guard rework, the has_triton() registry walk, and the ir.is_triton-keyed has_gpu gate that the analysis identifies as the cause.

The identified root cause is eliminated and CI-fenced. Previously my confidence rested on my own registration-by-registration walk. Now test_builtin_devices encodes the {"cuda","xpu"} invariant as an assertion, and test_cpu_triton_does_not_use_gpu_cpp_wrapper encodes the exact cpu_backend="triton" widening from the analysis. A future change that re-introduces the trap fails CI on a Linux machine with no accelerator — which is precisely the signal that was missing when the reverted version went in green.

The hints.py hypothesis is now closed too. The analysis explains graph.py and is silent on hints.py, so the compute-unit change had not been exonerated — it was simply no longer needed as an explanation. With the getattr fallbacks, it is equivalent regardless of what the out-of-tree getDeviceProperties() returns, so that hypothesis no longer needs the internal signal to rule out. This is why the two lines were worth insisting on.

Residual risks, ranked:

  1. fbcode name collision — the only item I'd still check before merging. DeviceInterface.get_multi_processor_count and DeviceOpOverrides.uses_gpu_cpp_wrapper are new names on two base classes that internal backends subclass. hints.py:202 calls device_interface.get_multi_processor_count(device) positionally, so an internal subclass that already defines that name with an incompatible signature (e.g. a no-arg staticmethod) raises TypeError on a name nothing called before. Low probability, near-zero cost to check, and — importantly — it is a failure mode visible only internally, i.e. the same class of thing that produced the first revert. A grep for both names over internal DeviceInterface / DeviceOpOverrides subclasses closes it.
  2. The extension point still invites a backend into the configuration that broke. Routing a non-cubin Triton-scheduled accelerator through the two-pass path is what produced the stride/kernel-metadata mismatch; opting in is now a one-line change for any backend. The docstring warning mitigates this and is the reason I'm not treating it as blocking, but the failure mode is now out-of-tree rather than eliminated.
  3. Unknown-unknowns from the original revert. Still no internal task or trace was ever shared. The analysis is a mechanism-level reconstruction, not a quoted failure, so a small chance remains that the internal signal was something neither of us has considered. What bounds this: with the current diff there is no in-tree behavioral change at all, so any such cause would have to live in the two new API names — i.e. risk item 1.

My recommendation: approve, and reland after the fbcode grep. I would no longer hold on the internal task. The scope reduction (2026-08-19) independently removed the exact line the analysis (2026-08-20) fingers, the remaining diff's in-tree behavior is verifiable without internal access and I verified it, and the two new tests convert that verification from a review claim into a CI invariant. If a second ghfirst revert did occur, the surface to bisect is now two method names rather than a device-classification rework — a much cheaper failure.

Recommendation: Approve. All three pre-merge conditions from my last pass are met — the getattr fallbacks make MTIA/XPU provable no-ops, the {"cuda","xpu"} set assertion and the cpu_backend="triton" repro now fence the exact widening that caused the internal revert, and _uses_gpu_cpp_wrapper moved to common.py with the narrow .get() lookup. The diff no longer changes behavior for any in-tree device; its only new surface is two default-off extension points. I'd still run the fbcode grep for pre-existing get_multi_processor_count / uses_gpu_cpp_wrapper definitions on subclasses before merging, since that is now the sole remaining internal-only failure mode. Items 1-6 above are cleanups, not blockers.
· branch inductor/device-identity-from-interface

@jansel

jansel commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

@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

orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…ytorch#190615)

Summary
Route Inductor's device identity, capability classification, and AOTI codegen
device selection through the DeviceInterface contract, so out-of-tree
PrivateUse1 accelerator backends are recognized as GPU-class, Triton-capable,
and guard-emitting without monkeypatching upstream module-level state.

Changes
DeviceInterface contract (`torch/_dynamo
Add is_gpu() (default False), exposes_streams() (derived from Stream
slot override), and get_multi_processor_count() (default reads standard
field multi_processor_count) capability bits to the base class
Declare the bits for all 6 in-tree backend,
CpuInterface.is_triton_capable() to check "cpu" in triton.backends.backends
instead of unconditionally returning True
Device identity predicates (torch/_inductor/utils.py)
is_gpu() queries get_interface_for_device(device).is_gpu() instead of
testing membership in the hardcoded GPU_TYPES list
device_need_guard() becomes is_gpu() ∧ exposes_streams(), eliminating
the handwritten != "mps" special case
get_gpu_type() removes the assert len(a crash and adds a PrivateUse1-first disambiguation rule matching the C++ getAccelerator()` priority
Add private _gpu_types() for enumeration
Triton routing (torch/utils/_triton.py)
has_triton() walks get_registered_device_interfaces(), queries
is_triton_capable() first then validates the backend is actually built
via raise_if_triton_unavailable(), replacing the hardcoded
triton_supported_devices dict
Skip "device:index" entries; only catch RuntimeError so that
GPUTooOldForTriton is never leaked for sub-capable devices
Changes
DeviceInterface contract (`torch/_dynamo
Add is_gpu() (default False), exposes_streams() (derived from Stream
slot override), and get_multi_processor_count() (default reads standard
field multi_processor_count) capability bits to the base class

Declare the bits for all 6 in-tree backends (CUDA/XPU/MTIA/MPS/CPU/TPU),
each precisely reproducing current behavior
Fix CpuInterface.is_triton_capable() to check "cpu" in triton.backends.backends
instead of unconditionally returning True
Device identity predicates (torch/_inductor/utils.py)
is_gpu() queries get_interface_for_deviof testing membership in the hardcoded GPU_TYPES` list
device_need_guard() becomes is_gpu() ∧ exposes_streams(), eliminating
the handwritten != "mps" special case
get_gpu_type() removes the assert len(avail_gpus) <= 1 coexistence
crash and adds a PrivateUse1-first disambiguation rule matching the C++
getAccelerator() priority
Add private _gpu_types() for enumeration, backed by the registry
Triton routing (torch/utils/_triton.py
has_triton() walks get_registered_device_interfaces(), queries
is_triton_capable() first then validates the backend is actually built
via raise_if_triton_unavailable(), repla
triton_supported_devices dict
Skip "device:index" entries; only catch RuntimeError so that
GPUTooOldForTriton is never leaked for s
Codegen / AOTI device selection (torch/_inductor/graph.py)
cpp_wrapper two-pass gate (line 2511): `["
JIT compile device selection (line 2819): ("cuda","xpu") → is_gpu(d)
Device properties (torch/_inductor/runtime/hints.py)
Collapse DeviceProperties.create's multi_processor_count device-name
ladder (try default → xpu: gpu_subslice_count → mtia: 64) into the
single contract call device_interface.get_multi_processor_count(device)
Tests (test/inductor/test_device_identity.py)
14 new tests covering: base defaults, in-tree backend declarations,
is_gpu() predicate behavior, device_nee has_triton()registry discovery,get_gpu_type()` disambiguation,
and PrivateUse1 opt-in scenarios
Motivation
Inductor's lowest-level device predicates (is_gpu, has_triton,
device_need_guard, DeviceProperties.creat hardcoded device-name lists instead of consulting the existing DeviceInterfacecontract. An out-of-tree P already registered a completeDeviceInterfacewas still classified as non-GPU and no-guard, and could only work around it by mutating upstream module-level state at import time. Routing these predicates through the contract lets any registered backend participate through its ownDeviceInterface` — zero upstream module-state mutation required.

Test Plan
CI: python test/inductor/test_device_identity.py (14 new device-agnostic
unit tests — no hardware dependency)
Behavior equivalence verified over the in-tree device matrix
(cuda/xpu/mtia/mps/cpu/tpu): old vs new fo
device_need_guard(), has_triton(), get_gpu_type(),
DeviceProperties.create() — all match
A PrivateUse1 backend declaring is_gpu()=True / is_triton_capable()=True
is now correctly classified as GPU, Triton-capable, and guard-emitting
CUDA behavior is byte-for-byte unchanged
Notes
Related RFC: DeviceInterface registry support for PrivateUse1 backends
in torch.compile (4 classes, 9 hardcoded
"device identity and capability" class)
GPU_TYPES is retained as a late-binding compatibility shim and can be
removed once all call-sites have migrated

Pull Request resolved: pytorch#190615
Approved by: https://github.com/jansel, https://github.com/JiasenTian
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…rties (pytorch#190615)

## Summary

Add backend extension points for C++ wrapper routing and device-property
metadata so out-of-tree accelerator backends can participate in these Inductor
paths without hardcoding their device names in core.

## Changes

- Add `DeviceOpOverrides.uses_gpu_cpp_wrapper()` with a default of `False`.
  CUDA and XPU override it to `True`, preserving the existing C++ wrapper
  routing behavior for in-tree backends.
- Use `uses_gpu_cpp_wrapper()` in both `GraphLowering` C++ wrapper decisions:
  the two-pass wrapper-codegen gate and the device selection used for JIT
  wrapper compilation.
- Treat unregistered devices conservatively as not using the GPU-style C++
  wrapper path.
- Add `DeviceInterface.get_multi_processor_count()`. The default implementation
  reads the standard `multi_processor_count` device-property field and asks
  backends with a different representation to override the method.
- Preserve the existing XPU behavior through `gpu_subslice_count` and the
  existing MTIA value of `64`.
- Make `DeviceProperties.create()` obtain the compute-unit count through
  `DeviceInterface.get_multi_processor_count()`.

## Motivation

Two Inductor paths currently encode backend-specific assumptions directly in
core: C++ wrapper routing recognizes CUDA/XPU by device name, and
`DeviceProperties.create()` contains device-specific handling for compute-unit
metadata.

For an out-of-tree backend, these differences are properties of the backend
rather than properties of Inductor itself. `DeviceOpOverrides` already owns
backend-specific codegen behavior, while `DeviceInterface` already owns
backend device properties.

Exposing the two decisions through those existing contracts lets registered
backends provide their behavior directly without adding out-of-tree device
names or property layouts to Inductor core.

## Test Plan

- CI: `python test/inductor/test_device_identity.py`
- Added device-independent tests for `get_multi_processor_count()`:
  standard-property behavior, missing-property error handling, the XPU
  `gpu_subslice_count` override, and the MTIA fixed value.
- Added a `DeviceProperties.create()` test using a fake `DeviceInterface` to
  verify that the compute-unit count is obtained through the interface
  contract.
- Added C++ wrapper-routing tests covering CUDA/XPU opt-in, CPU/MPS default
  behavior, an out-of-tree `DeviceOpOverrides` opt-in, the default
  out-of-tree behavior, and an unregistered device.
- The tests use fake interfaces / registered overrides and mocks where needed,
  so the new coverage does not require accelerator hardware.

## Notes

- `uses_gpu_cpp_wrapper()` is a backend codegen capability rather than a
  general device-classification predicate. Both relevant `GraphLowering`
  call sites use the same capability.
- The default behavior of both extension points is conservative:
  `DeviceOpOverrides` does not opt into GPU-style wrapper routing, while
  `DeviceInterface.get_multi_processor_count()` uses the standard device
  property when available.
- Existing CUDA/XPU C++ wrapper routing and XPU/MTIA compute-unit behavior are
  preserved.

Pull Request resolved: pytorch#190615
Approved by: https://github.com/jansel
copybara-service Bot pushed a commit to google-pytorch/torch_tpu that referenced this pull request Sep 3, 2026
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`.

Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`.

This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior.

This method was introduced in PyTorch with:
- pytorch/pytorch#190615

Generated from cl/975497299

PiperOrigin-RevId: 975497299
copybara-service Bot pushed a commit to google-pytorch/torch_tpu that referenced this pull request Sep 3, 2026
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`.

Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`.

This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior.

This method was introduced in PyTorch with:
- pytorch/pytorch#190615

Generated from cl/975497299

PiperOrigin-RevId: 975497299
copybara-service Bot pushed a commit to google-pytorch/torch_tpu that referenced this pull request Sep 3, 2026
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`.

Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`.

This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior.

This method was introduced in PyTorch with:
- pytorch/pytorch#190615

Generated from cl/975497299

PiperOrigin-RevId: 975497299
copybara-service Bot pushed a commit to google-pytorch/torch_tpu that referenced this pull request Sep 3, 2026
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`.

Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`.

This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior.

This method was introduced in PyTorch with:
- pytorch/pytorch#190615

Generated from cl/975497299

PiperOrigin-RevId: 975497299
copybara-service Bot pushed a commit to google-pytorch/torch_tpu that referenced this pull request Sep 4, 2026
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`.

Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`.

This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior.

This method was introduced in PyTorch with:
- pytorch/pytorch#190615

Generated from cl/975497299

PiperOrigin-RevId: 975497299
copybara-service Bot pushed a commit to google-pytorch/torch_tpu that referenced this pull request Sep 4, 2026
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`.

Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`.

This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior.

This method was introduced in PyTorch with:
- pytorch/pytorch#190615

Generated from cl/975497299

PiperOrigin-RevId: 975497299
copybara-service Bot pushed a commit to google-pytorch/torch_tpu that referenced this pull request Sep 5, 2026
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`.

Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`.

This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior.

This method was introduced in PyTorch with:
- pytorch/pytorch#190615

Generated from cl/976571851

PiperOrigin-RevId: 976571851
huangjingwei pushed a commit to Ascend/pytorch that referenced this pull request Sep 9, 2026
Co-authored-by: srhust<[email protected]>



# message auto-generated for no-merge-commit merge:
!43791 merge cleanup/remove-gpu-monkey-patches into master

refactor(inductor): remove upstreamed NPU compatibility patches

Created-by: srhust
Commit-by: srhust
Merged-by: ascend-robot
Description: # 【合入来源】

关联 issue: https://gitcode.com/Ascend/pytorch/issues/3634

- [ ] 需求
- [ ] 问题单
- [x] issue/工单
- [x] 重构优化
- [ ] 资料更新

# 〖修改方案〗

基于 PyTorch upstream 提供的 PrivateUse1 / out-of-tree backend 扩展机制,
将 NPU Inductor 中原有的设备相关 monkey patch 迁移到
`DeviceOpOverrides`、`DeviceInterface` 等统一 backend extension points。

同时将 PyTorch 版本差异收敛到 `torch_npu/_compat` 层:
业务代码不直接进行版本判断,统一通过 compat 接口访问对应能力。

兼容策略:

- `torch < 2.15`:保留原有 legacy patch / mapping 行为。
- `torch >= 2.15`:使用 PyTorch upstream 提供的统一 backend extension points。
- 当最低支持 PyTorch 版本提升至 2.15 及以上后,可删除对应 legacy compat 实现。

具体修改如下。

1. 接入 C++ wrapper routing 扩展能力
   - 在 `NewNPUDeviceOpOverrides` 中实现:
     ```python
     def uses_gpu_cpp_wrapper(self) -> bool:
         return True
     ```
   - 通过 PyTorch `DeviceOpOverrides.uses_gpu_cpp_wrapper()` 向
     `GraphLowering` 提供 NPU C++ wrapper routing capability。
   - `torch < 2.15` 通过 `_compat` 保留原
     `patch_codegen_with_cpp_wrapper` 行为。
   - 对应 upstream:pytorch/pytorch#190615。

2. 接入 device compute-unit 查询能力
   - 在 `NpuInterface` 中实现:
     ```python
     @classmethod
     def get_multi_processor_count(cls, device=None) -> int:
         return cls.get_device_properties(device).vector_core_num
     ```
   - 通过 PyTorch `DeviceInterface.get_multi_processor_count()` 向
     `DeviceProperties.create()` 提供 NPU compute-unit 数量。
   - `torch < 2.15` 通过 `_compat` 保留原
     `patch_create_device_properties` 行为。
   - 对应 upstream:pytorch/pytorch#190615。

3. 接入 AOTI / C++ wrapper ATen DeviceType 扩展能力
   - 在 `NewNPUDeviceOpOverrides` 中实现:
     ```python
     def aten_device_type(self) -> str:
         return "at::kPrivateUse1"
     ```
   - 通过 PyTorch `DeviceOpOverrides.aten_device_type()` 提供 NPU
     ATen DeviceType 映射。
   - 新增 `_compat.inductor.device_to_aten()` 统一接口:
     - `torch >= 2.15` 调用 PyTorch upstream `device_to_aten()`;
     - `torch < 2.15` 继续使用 legacy `DEVICE_TO_ATEN` mapping。
   - `cpp_wrapper_npu.py` 统一通过 `_compat` 接口获取 ATen DeviceType,
     不直接依赖不同 PyTorch 版本下的内部实现。
   - 对应 upstream:pytorch/pytorch#193904。

4. 接入 CodeCache system metadata 扩展能力
   - 在 `NpuInterface` 中实现:
     ```python
     @classmethod
     def get_cache_system_info(cls):
         try:
             device_properties = get_device_properties_npu(current_device())
         except (AssertionError, RuntimeError):
             return None

         return {
             "name": device_properties.name,
             "cann": torch.version.cann,
         }
     ```
   - 通过 PyTorch `DeviceInterface.get_cache_system_info()` 向
     `CacheBase.get_system()` 提供 NPU device name 和 CANN version。
   - 保证 NPU backend metadata 参与统一的 CodeCache system key
     及 cache hash 生成。
   - `torch < 2.15` 通过 `_compat` 保留原
     `patch_cache_base_get_system` 行为。
   - 对应 upstream:pytorch/pytorch#193908。

5. 收敛版本兼容逻辑
   - 新增 `torch_npu/_compat/inductor.py`,统一管理上述 Inductor
     版本兼容逻辑。
   - 业务实现优先调用 `_compat` 层提供的统一接口,不在业务模块中
     分散进行 PyTorch 版本判断。
   - `CURRENT_VERSION >= (2, 15)` 使用 upstream contract;
     旧版本继续保持原有 PTA 行为。
   - 删除/收敛已由 upstream extension point 替代的版本相关
     monkey patch 实现。

6. 同步测试及模块注册信息
   - 增加 NPU C++ wrapper routing capability 测试。
   - 增加 NPU ATen DeviceType / `device_to_aten` 测试。
   - 增加 NPU compute-unit 查询测试。
   - 更新 CodeCache 测试,覆盖 NPU device metadata、CANN version
     及 cache hash。
   - 覆盖 `<2.15` legacy compat 与 `>=2.15` upstream contract
     的版本分支。
   - 同步更新 `test_public_bindings.py`,使 public bindings 检查与
     当前 Inductor 模块结构保持一致。

# 〖资料变更〗

不涉及。

# 〖接口变更〗

不涉及客户可见接口变更。

内部实现使用 PyTorch upstream 提供的以下 backend extension points:

- `DeviceOpOverrides.uses_gpu_cpp_wrapper()`
- `DeviceInterface.get_multi_processor_count()`
- `DeviceOpOverrides.aten_device_type()`
- `DeviceInterface.get_cache_system_info()`

PTA 内部新增 `_compat` 统一适配层,用于隔离不同 PyTorch 版本下
Inductor backend contract 的差异,不新增客户可见 API。

# 〖功能验证〗

新增/更新以下 UT:

1. `test/_inductor/test_npu_device.py`
   - 验证 `NewNPUDeviceOpOverrides.uses_gpu_cpp_wrapper()` 返回 `True`。
   - 验证 `NewNPUDeviceOpOverrides.aten_device_type()` 返回
     `at::kPrivateUse1`。
   - 验证 NPU ATen DeviceType 可通过统一 `device_to_aten()` 接口获取。

2. `test/utils/test_dynamo_device.py`
   - 验证 `NpuInterface.get_multi_processor_count()` 从
     `vector_core_num` 获取 NPU compute-unit 数量。

3. `test/_inductor/test_codecache.py`
   - 验证
     `CacheBase.get_system()["device_interfaces"]["npu"]`
     包含 NPU device name 和 CANN version。
   - 验证 NPU backend metadata 参与 CodeCache system hash 生成。

4. `test/npu/test_public_bindings.py`
   - 验证 public bindings 配置与当前 Inductor 模块结构保持一致。

兼容性验证:

- `torch < 2.15` 使用 legacy compat 实现。
- `torch >= 2.15` 使用 PyTorch upstream backend extension points。
- compat 版本判断通过 PTA version compatibility checker 约束。

静态检查:

- `git diff --check` 通过。
- `python -m compileall` 通过。

# 〖CheckList〗

- [x] 代码注释完备,正确记录错误日志
- [x] 代码实现进行了返回值、空指针等校验
- [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等
- [x] PR持续集成流水线(CI)执行通过,代码检查无异常

See merge request: Ascend/pytorch!43791
bogdanu added a commit to bogdanu/pytorch that referenced this pull request Oct 7, 2026
Adds a regression test for the behavior changed and then reverted in pytorch#190615.
pytorchmergebot pushed a commit to huangfei1199/pytorch that referenced this pull request Oct 8, 2026
## Summary
Replace the hardcoded torch.xpu/torch.cuda if-chain in
flex_decoding.get_split_k with a query against the kernel's target device
through the DeviceInterface capability (pytorch#190615), so the SM count that feeds
the SPLIT_KV heuristic is sourced from whichever device the decode kernel
actually targets instead of ambient xpu/cuda detection. Existing behavior is
preserved for single-device cuda and xpu environments (same SM count, same
SPLIT_KV); mixed-backend machines now route correctly, and backends with no
registered interface get a clear error instead of crashing inside CUDA device
property initialization.

## Changes
torch/_inductor/kernel/flex/flex_decoding.py: get_split_k now takes the kernel
target device as a required keyword argument (`device: torch.device`) and
resolves its SM count via get_interface_for_device(device), then
interface.get_multi_processor_count(device). The lazy import of
torch._dynamo.device_interface keeps the dynamo dependency off this module's
load path (matching the style of other decoupling sites). The split_k formula
(num_SM // bh * 2, floored to 1) is unchanged -- only the source of num_SM
moves from a hardcoded device string / is_available() probe to the device's
own registered interface. The single call site (create_flex_decoding_kernel)
now reads `device = query.get_device()` (the surrounding code already queried
query.get_device().type two lines above) and passes it through, which also
fixes a latent multi-card inaccuracy where the old code used the default
"xpu"/"cuda" device instead of the kernel's actual device index.

## Motivation
get_split_k feeds SPLIT_KV, which sizes the decode KV intermediate buffer
(buf_ACC_shape). The original if-chain asked the ambient environment
("is xpu available?") rather than "which device is this kernel for": on a
machine with both xpu and cuda, every cuda decode kernel wrongly took the xpu
branch; on a machine with neither (mtia-only, cpu-triton), the code crashed
inside torch.cuda device-property initialization with no path to a usable
value; tpu and out-of-tree accelerators had no legal path at all. The
DeviceInterface registry already exposes get_multi_processor_count (added in
pytorch#190615, already consumed by hints.py): cuda reads the standard
multi_processor_count field, xpu overrides with gpu_subslice_count, mtia
defaults to 64. Routing get_split_k through the same contract lets each
backend report its own SM count for the device the kernel actually targets,
and surfaces a clear AttributeError ("must override") for a backend whose
interface has not yet been adapted -- pointing the backend author at the one
method to override -- instead of an opaque CUDA init failure.

## Test Plan
CI: python -m pytest -q test/inductor/test_flex_attention.py
CI: python test/inductor/test_flex_attention.py
CI: lintrunner -a torch/_inductor/kernel/flex/flex_decoding.py

Verified on GPU (cuda): flex decode end-to-end passes (the device matrix
tests cover the SPLIT_KV-shaped buffer indirectly).
Verified on CPU: pytest 2 passed, 582 skipped, 0 failed; python direct run
584 tests, OK (skipped=582). Same result in NPU mode and CPU mode.
Verified on an Ascend NPU container: pytest 2 passed, 582 skipped, 0 failed
in both NPU mode and CPU mode; the mainline get_split_k path is not reached
on NPU (torch_npu overrides the flex decode lowering), so this confirms
non-regression and import/collection integrity. lintrunner reports 0
violations on the changed file.

No new tests added: the existing decode end-to-end device matrix tests
already cover SPLIT_KV indirectly (a changed value resizes buf_ACC_shape and
turns the test red), and the must-override contract get_split_k now relies on
is already tested by test_device_backend_hooks.py::TestMultiProcessorCount
::test_missing_standard_property (pytorch#190615). A standalone unit test for the
formula / routing would be zero-increment over that coverage, so it is
omitted to keep the PR a minimal source-only diff.

## Notes
Behavior preservation: for any single-device cuda or xpu CI environment the
SM count is identical to before (cuda reads the same multi_processor_count
field; xpu's override returns the same gpu_subslice_count), so SPLIT_KV is
unchanged and the formula is untouched. The behavioral changes are all on
paths the old code could not handle correctly:
- On a mixed xpu+cuda machine, a cuda decode kernel now reads
  multi_processor_count instead of wrongly taking the xpu branch. This is a
  bug fix; single-device CI is structurally unaffected.
- On an mtia-only / no-xpu-no-cuda machine, the previous CUDA-init crash
  becomes a usable value (mtia default 64).
- For an out-of-tree DeviceInterface that has not yet overridden
  get_multi_processor_count, the previous opaque crash becomes a clear
  AttributeError("must override") pointing at the method to implement;
  once the backend overrides it (returning its SM count), the decode
  heuristic works without a mainline patch.
Part of the hardware decoupling effort: remove hardcoded device lists so
backends register capability through their DeviceInterface instead.
Authored with an AI assistant (Claude).
pytorchmergebot pushed a commit to huangfei1199/pytorch that referenced this pull request Oct 8, 2026
## Summary
Replace the hardcoded torch.xpu/torch.cuda if-chain in
flex_decoding.get_split_k with a query against the kernel's target device
through the DeviceInterface capability (pytorch#190615), so the SM count that feeds
the SPLIT_KV heuristic is sourced from whichever device the decode kernel
actually targets instead of ambient xpu/cuda detection. Existing behavior is
preserved for single-device cuda and xpu environments (same SM count, same
SPLIT_KV); mixed-backend machines now route correctly, and backends with no
registered interface get a clear error instead of crashing inside CUDA device
property initialization.

## Changes
torch/_inductor/kernel/flex/flex_decoding.py: get_split_k now takes the kernel
target device as a required keyword argument (`device: torch.device`) and
resolves its SM count via get_interface_for_device(device), then
interface.get_multi_processor_count(device). The lazy import of
torch._dynamo.device_interface keeps the dynamo dependency off this module's
load path (matching the style of other decoupling sites). The split_k formula
(num_SM // bh * 2, floored to 1) is unchanged -- only the source of num_SM
moves from a hardcoded device string / is_available() probe to the device's
own registered interface. The single call site (create_flex_decoding_kernel)
now reads `device = query.get_device()` (the surrounding code already queried
query.get_device().type two lines above) and passes it through, which also
fixes a latent multi-card inaccuracy where the old code used the default
"xpu"/"cuda" device instead of the kernel's actual device index.

## Motivation
get_split_k feeds SPLIT_KV, which sizes the decode KV intermediate buffer
(buf_ACC_shape). The original if-chain asked the ambient environment
("is xpu available?") rather than "which device is this kernel for": on a
machine with both xpu and cuda, every cuda decode kernel wrongly took the xpu
branch; on a machine with neither (mtia-only, cpu-triton), the code crashed
inside torch.cuda device-property initialization with no path to a usable
value; tpu and out-of-tree accelerators had no legal path at all. The
DeviceInterface registry already exposes get_multi_processor_count (added in
pytorch#190615, already consumed by hints.py): cuda reads the standard
multi_processor_count field, xpu overrides with gpu_subslice_count, mtia
defaults to 64. Routing get_split_k through the same contract lets each
backend report its own SM count for the device the kernel actually targets,
and surfaces a clear AttributeError ("must override") for a backend whose
interface has not yet been adapted -- pointing the backend author at the one
method to override -- instead of an opaque CUDA init failure.

## Test Plan
CI: python -m pytest -q test/inductor/test_flex_attention.py
CI: python test/inductor/test_flex_attention.py
CI: lintrunner -a torch/_inductor/kernel/flex/flex_decoding.py

Verified on GPU (cuda): flex decode end-to-end passes (the device matrix
tests cover the SPLIT_KV-shaped buffer indirectly).
Verified on CPU: pytest 2 passed, 582 skipped, 0 failed; python direct run
584 tests, OK (skipped=582). Same result in NPU mode and CPU mode.
Verified on an Ascend NPU container: pytest 2 passed, 582 skipped, 0 failed
in both NPU mode and CPU mode; the mainline get_split_k path is not reached
on NPU (torch_npu overrides the flex decode lowering), so this confirms
non-regression and import/collection integrity. lintrunner reports 0
violations on the changed file.

No new tests added: the existing decode end-to-end device matrix tests
already cover SPLIT_KV indirectly (a changed value resizes buf_ACC_shape and
turns the test red), and the must-override contract get_split_k now relies on
is already tested by test_device_backend_hooks.py::TestMultiProcessorCount
::test_missing_standard_property (pytorch#190615). A standalone unit test for the
formula / routing would be zero-increment over that coverage, so it is
omitted to keep the PR a minimal source-only diff.

## Notes
Behavior preservation: for any single-device cuda or xpu CI environment the
SM count is identical to before (cuda reads the same multi_processor_count
field; xpu's override returns the same gpu_subslice_count), so SPLIT_KV is
unchanged and the formula is untouched. The behavioral changes are all on
paths the old code could not handle correctly:
- On a mixed xpu+cuda machine, a cuda decode kernel now reads
  multi_processor_count instead of wrongly taking the xpu branch. This is a
  bug fix; single-device CI is structurally unaffected.
- On an mtia-only / no-xpu-no-cuda machine, the previous CUDA-init crash
  becomes a usable value (mtia default 64).
- For an out-of-tree DeviceInterface that has not yet overridden
  get_multi_processor_count, the previous opaque crash becomes a clear
  AttributeError("must override") pointing at the method to implement;
  once the backend overrides it (returning its SM count), the decode
  heuristic works without a mainline patch.
Part of the hardware decoupling effort: remove hardcoded device lists so
backends register capability through their DeviceInterface instead.
Authored with an AI assistant (Claude).
pytorchmergebot pushed a commit that referenced this pull request Oct 9, 2026
…ce (#196736)

## Summary
Replace the hardcoded torch.xpu/torch.cuda if-chain in flex_decoding.get_split_k with a query against the kernel's target device through the DeviceInterface capability (#190615), so the SM count that feeds the SPLIT_KV heuristic is sourced from whichever device the decode kernel actually targets instead of ambient xpu/cuda detection. Existing behavior is preserved for single-device cuda and xpu environments (same SM count, same SPLIT_KV); mixed-backend machines now route correctly, and backends with no registered interface get a clear error instead of crashing inside CUDA device property initialization.

## Changes
torch/_inductor/kernel/flex/flex_decoding.py: get_split_k now takes the kernel target device as a required keyword argument (`device: torch.device`) and resolves its SM count via get_interface_for_device(device), then interface.get_multi_processor_count(device). The lazy import of torch._dynamo.device_interface keeps the dynamo dependency off this module's load path (matching the style of other decoupling sites). The split_k formula (num_SM // bh * 2, floored to 1) is unchanged -- only the source of num_SM moves from a hardcoded device string / is_available() probe to the device's own registered interface. The single call site (create_flex_decoding_kernel) now reads `device = query.get_device()` (the surrounding code already queried query.get_device().type two lines above) and passes it through, which also fixes a latent multi-card inaccuracy where the old code used the default "xpu"/"cuda" device instead of the kernel's actual device index.

## Motivation
get_split_k feeds SPLIT_KV, which sizes the decode KV intermediate buffer (buf_ACC_shape). The original if-chain asked the ambient environment ("is xpu available?") rather than "which device is this kernel for": on a machine with both xpu and cuda, every cuda decode kernel wrongly took the xpu branch; on a machine with neither (mtia-only, cpu-triton), the code crashed inside torch.cuda device-property initialization with no path to a usable value; tpu and out-of-tree accelerators had no legal path at all. The DeviceInterface registry already exposes get_multi_processor_count (added in #190615, already consumed by hints.py): cuda reads the standard multi_processor_count field, xpu overrides with gpu_subslice_count, mtia defaults to 64. Routing get_split_k through the same contract lets each backend report its own SM count for the device the kernel actually targets, and surfaces a clear AttributeError ("must override") for a backend whose interface has not yet been adapted -- pointing the backend author at the one method to override -- instead of an opaque CUDA init failure.

## Test Plan
CI: python -m pytest -q test/inductor/test_flex_attention.py CI: python test/inductor/test_flex_attention.py
CI: lintrunner -a torch/_inductor/kernel/flex/flex_decoding.py

Verified on GPU (cuda): flex decode end-to-end passes (the device matrix tests cover the SPLIT_KV-shaped buffer indirectly). Verified on CPU: pytest 2 passed, 582 skipped, 0 failed; python direct run 584 tests, OK (skipped=582). Same result in NPU mode and CPU mode. Verified on an Ascend NPU container: pytest 2 passed, 582 skipped, 0 failed in both NPU mode and CPU mode; the mainline get_split_k path is not reached on NPU (torch_npu overrides the flex decode lowering), so this confirms non-regression and import/collection integrity. lintrunner reports 0 violations on the changed file.

No new tests added: the existing decode end-to-end device matrix tests already cover SPLIT_KV indirectly (a changed value resizes buf_ACC_shape and turns the test red), and the must-override contract get_split_k now relies on is already tested by test_device_backend_hooks.py::TestMultiProcessorCount ::test_missing_standard_property (#190615). A standalone unit test for the formula / routing would be zero-increment over that coverage, so it is omitted to keep the PR a minimal source-only diff.

## Notes
Behavior preservation: for any single-device cuda or xpu CI environment the SM count is identical to before (cuda reads the same multi_processor_count field; xpu's override returns the same gpu_subslice_count), so SPLIT_KV is unchanged and the formula is untouched. The behavioral changes are all on paths the old code could not handle correctly:
- On a mixed xpu+cuda machine, a cuda decode kernel now reads multi_processor_count instead of wrongly taking the xpu branch. This is a bug fix; single-device CI is structurally unaffected.
- On an mtia-only / no-xpu-no-cuda machine, the previous CUDA-init crash becomes a usable value (mtia default 64).
- For an out-of-tree DeviceInterface that has not yet overridden get_multi_processor_count, the previous opaque crash becomes a clear AttributeError("must override") pointing at the method to implement; once the backend overrides it (returning its SM count), the decode heuristic works without a mainline patch. Part of the hardware decoupling effort: remove hardcoded device lists so backends register capability through their DeviceInterface instead. Authored with an AI assistant (Claude).

Pull Request resolved: #196736
Approved by: https://github.com/jansel, https://github.com/drisspg
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…ce (pytorch#196736)

## Summary
Replace the hardcoded torch.xpu/torch.cuda if-chain in flex_decoding.get_split_k with a query against the kernel's target device through the DeviceInterface capability (pytorch#190615), so the SM count that feeds the SPLIT_KV heuristic is sourced from whichever device the decode kernel actually targets instead of ambient xpu/cuda detection. Existing behavior is preserved for single-device cuda and xpu environments (same SM count, same SPLIT_KV); mixed-backend machines now route correctly, and backends with no registered interface get a clear error instead of crashing inside CUDA device property initialization.

## Changes
torch/_inductor/kernel/flex/flex_decoding.py: get_split_k now takes the kernel target device as a required keyword argument (`device: torch.device`) and resolves its SM count via get_interface_for_device(device), then interface.get_multi_processor_count(device). The lazy import of torch._dynamo.device_interface keeps the dynamo dependency off this module's load path (matching the style of other decoupling sites). The split_k formula (num_SM // bh * 2, floored to 1) is unchanged -- only the source of num_SM moves from a hardcoded device string / is_available() probe to the device's own registered interface. The single call site (create_flex_decoding_kernel) now reads `device = query.get_device()` (the surrounding code already queried query.get_device().type two lines above) and passes it through, which also fixes a latent multi-card inaccuracy where the old code used the default "xpu"/"cuda" device instead of the kernel's actual device index.

## Motivation
get_split_k feeds SPLIT_KV, which sizes the decode KV intermediate buffer (buf_ACC_shape). The original if-chain asked the ambient environment ("is xpu available?") rather than "which device is this kernel for": on a machine with both xpu and cuda, every cuda decode kernel wrongly took the xpu branch; on a machine with neither (mtia-only, cpu-triton), the code crashed inside torch.cuda device-property initialization with no path to a usable value; tpu and out-of-tree accelerators had no legal path at all. The DeviceInterface registry already exposes get_multi_processor_count (added in pytorch#190615, already consumed by hints.py): cuda reads the standard multi_processor_count field, xpu overrides with gpu_subslice_count, mtia defaults to 64. Routing get_split_k through the same contract lets each backend report its own SM count for the device the kernel actually targets, and surfaces a clear AttributeError ("must override") for a backend whose interface has not yet been adapted -- pointing the backend author at the one method to override -- instead of an opaque CUDA init failure.

## Test Plan
CI: python -m pytest -q test/inductor/test_flex_attention.py CI: python test/inductor/test_flex_attention.py
CI: lintrunner -a torch/_inductor/kernel/flex/flex_decoding.py

Verified on GPU (cuda): flex decode end-to-end passes (the device matrix tests cover the SPLIT_KV-shaped buffer indirectly). Verified on CPU: pytest 2 passed, 582 skipped, 0 failed; python direct run 584 tests, OK (skipped=582). Same result in NPU mode and CPU mode. Verified on an Ascend NPU container: pytest 2 passed, 582 skipped, 0 failed in both NPU mode and CPU mode; the mainline get_split_k path is not reached on NPU (torch_npu overrides the flex decode lowering), so this confirms non-regression and import/collection integrity. lintrunner reports 0 violations on the changed file.

No new tests added: the existing decode end-to-end device matrix tests already cover SPLIT_KV indirectly (a changed value resizes buf_ACC_shape and turns the test red), and the must-override contract get_split_k now relies on is already tested by test_device_backend_hooks.py::TestMultiProcessorCount ::test_missing_standard_property (pytorch#190615). A standalone unit test for the formula / routing would be zero-increment over that coverage, so it is omitted to keep the PR a minimal source-only diff.

## Notes
Behavior preservation: for any single-device cuda or xpu CI environment the SM count is identical to before (cuda reads the same multi_processor_count field; xpu's override returns the same gpu_subslice_count), so SPLIT_KV is unchanged and the formula is untouched. The behavioral changes are all on paths the old code could not handle correctly:
- On a mixed xpu+cuda machine, a cuda decode kernel now reads multi_processor_count instead of wrongly taking the xpu branch. This is a bug fix; single-device CI is structurally unaffected.
- On an mtia-only / no-xpu-no-cuda machine, the previous CUDA-init crash becomes a usable value (mtia default 64).
- For an out-of-tree DeviceInterface that has not yet overridden get_multi_processor_count, the previous opaque crash becomes a clear AttributeError("must override") pointing at the method to implement; once the backend overrides it (returning its SM count), the decode heuristic works without a mainline patch. Part of the hardware decoupling effort: remove hardcoded device lists so backends register capability through their DeviceInterface instead. Authored with an AI assistant (Claude).

Pull Request resolved: pytorch#196736
Approved by: https://github.com/jansel, https://github.com/drisspg
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/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo module: inductor open source 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

None yet

Development

Successfully merging this pull request may close these issues.

9 participants