Skip to content

[Inductor] Route AOTI device type through DeviceOpOverrides - #193904

Closed
srhust wants to merge 7 commits into
pytorch:mainfrom
srhust:upstream/inductor-device-overrides-aten-device-type
Closed

srhust wants to merge 7 commits into
pytorch:mainfrom
srhust:upstream/inductor-device-overrides-aten-device-type

Conversation

@srhust

@srhust srhust commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Route AOTI/C++ wrapper ATen device type mapping through
DeviceOpOverrides as the authoritative per-device contract.

This removes the mutable global DEVICE_TO_ATEN mapping and lets both
in-tree and out-of-tree backends provide their ATen device type through
the existing device codegen extension point.

Changes

  • Add DeviceOpOverrides.aten_device_type() as the per-device contract for
    C++ ATen device type mapping.
  • Implement the mapping in the CPU, CUDA, XPU, and MPS device overrides.
  • Remove the global DEVICE_TO_ATEN mapping.
  • Keep meta as an explicit special case because it has no registered
    DeviceOpOverrides.
  • Separate the generic no-op override behavior from CPU-specific device
    identity so TPU continues to use no-op overrides without inheriting the
    CPU ATen device type.
  • Route AOTI/C++ wrapper device type generation through device_to_aten().
  • Remove the manual DEVICE_TO_ATEN["extension_device"] mutation from the
    extension backend test.
  • Add coverage for built-in mappings, out-of-tree mappings, missing and
    invalid mappings, and unsupported TPU/MTIA mappings.

Motivation

AOTI/C++ wrapper codegen previously looked up device types through the
hardcoded mutable DEVICE_TO_ATEN mapping.

That forced out-of-tree backends to mutate Inductor module state even when
they already registered a DeviceOpOverrides implementation. It also left
two competing mechanisms once an override hook was added: built-in devices
continued to use the global mapping while only out-of-tree devices used the
new hook.

Using DeviceOpOverrides as the authoritative backend-specific source keeps
ATen device identity with the existing per-device codegen contract and
removes the need for backends to mutate Inductor globals.

Test Plan

  • Verify CPU, CUDA, XPU, MPS, and meta resolve to their existing ATen device
    types.
  • Verify an out-of-tree extension backend resolves to at::kPrivateUse1
    through its registered DeviceOpOverrides.
  • Verify unregistered devices and overrides without an ATen device mapping
    fail explicitly.
  • Verify invalid override return values fail with a clear error.
  • Verify TPU and MTIA remain unsupported instead of inheriting another
    backend's mapping.
  • Existing extension C++ wrapper coverage continues to exercise generated
    device code without mutating a global mapping.

Out-of-tree backend migration

Out-of-tree backends that previously populated cpp_utils.DEVICE_TO_ATEN
should instead implement aten_device_type() on their registered
DeviceOpOverrides. The returned value must use the at::k... form, for
example at::kPrivateUse1.

Notes

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 18, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (3 Unrelated Failures)

As of commit a3271bc with merge base d7a82dc (image):

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

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

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

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

@pytorch-bot

pytorch-bot Bot commented Aug 18, 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 Aug 18, 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.

@zou3519 zou3519 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 18, 2026
@zou3519
zou3519 requested a review from eellison August 18, 2026 13:39
@jansel

jansel commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 15m 13s —— View job


Reviewed — the refactor is directionally right, but the new aten_device_type() extension point has an undocumented at::k string-format contract that is enforced only by a [5:] slice, and the failure path the PR body advertises is untested.

Full review

PR Review: #193904

Summary

Routes AOTI/C++ wrapper device-type mapping through DeviceOpOverrides.aten_device_type() so out-of-tree PrivateUse1 backends no longer monkeypatch cpp_utils.DEVICE_TO_ATEN. The mechanism works for the happy path, but the new public extension point returns a string that is silently required to begin with at::k (enforced only by a [5:] slice), the error contract is split across two exception types, and neither the advertised failure mode nor the generated C++ is actually asserted in tests.

API Design

aten_device_type() has an unvalidated string-format contract. torch/_inductor/codegen/cpp_wrapper_cpu.py:2370:

device_str = device_to_aten(device.type)[5:].lower()  # remove "at::k"

Previously the values fed to [5:] were a closed set of five in-tree constants, so the slice was safe by construction. Now the value comes from an arbitrary out-of-tree implementation of a documented-as-public method whose docstring says only "Return the C++ ATen DeviceType expression for this device." A backend author who reasonably returns "c10::DeviceType::PrivateUse1" — which is also a valid C++ ATen DeviceType expression — gets [5:].lower() → "devicetype::privateuse1", which flows into used_cached_devices and is emitted as CACHE_TORCH_DEVICE(devicetype::privateuse1) (cpp_wrapper_cpu.py:1511-1512). The failure surfaces as an opaque C++ compile error inside generated code with no Python-side diagnostic.

Fix one of:

  1. Document the required at::k prefix in the docstring and validate it in device_to_aten(), raising a clear error naming the offending override class; or
  2. Have the override return the bare lowercase token ("privateuse1") and let Inductor construct both at::kPrivateUse1 and the cache identifier from it — this removes the string surgery entirely.

Option 2 is cleaner given the two call sites need different forms of the same value. Fix this →

The extension point is dead code for every in-tree device. device_to_aten() checks DEVICE_TO_ATEN first (cpp_utils.py:92-94), so aten_device_type() is only ever consulted for devices absent from that table. CpuDeviceOpOverrides, CUDADeviceOpOverrides, XPUDeviceOpOverrides, and MPSDeviceOpOverrides do not implement it, and if they did it would be silently ignored. That is a confusing contract for the very audience this method is written for: the docstring presents itself as authoritative while being consulted only as a fallback. Either implement aten_device_type() on the four in-tree overrides and consult overrides first (leaving DEVICE_TO_ATEN holding only meta, which has no registered DeviceOpOverrides at all), or rename the method and docstring to state plainly that it is an out-of-tree-only fallback.

Nothing actually prevents the monkeypatching this PR exists to eliminate. DEVICE_TO_ATEN stays public and mutable, and because it is consulted first, a monkeypatch still wins over a registered override. If the goal is to make DeviceOpOverrides the contract, rename it _DEVICE_TO_ATEN so the previous pattern is visibly unsupported.

Split error contract in device_to_aten() (cpp_utils.py:98-102). Two different exception types for what is one user-facing failure — "this device has no ATen mapping":

  • device has no registered DeviceOpOverrides → KeyError
  • device has one but did not implement the method → NotImplementedError

Additionally, KeyError renders its message with embedded quotes (KeyError: 'No ATen device type mapping for ...'), which reads poorly compared to the AssertionError it replaces, and from None discards the fact that the root cause was a missing backend registration. Prefer a single RuntimeError for both, and drop from None so the missing-registration cause survives.

Testing

The one added assertion is a tautology. test/inductor/test_extension_backend.py:137-140 asserts device_to_aten("extension_device") == "at::kPrivateUse1" immediately after registering an override whose entire body is return "at::kPrivateUse1". It confirms the dict lookup misses and the override is reachable, and nothing more. In particular it does not exercise the [5:].lower() transformation, which is where the actual codegen risk lives.

The advertised failure path is untested. The PR body states: "backends that do not provide a mapping fail explicitly instead of defaulting to at::kPrivateUse1." That is a behavioral guarantee with no test. Add a case registering an override that omits aten_device_type() and assert the resulting error.

Nothing verifies the generated C++, so the Test Plan's "end-to-end" claim does not hold. The existing FileCheck at test_extension_backend.py:180-182 is:

FileCheck().check("void").check(load_expr).check("extension_device").run(code)

None of those three tokens depend on the ATen device mapping — "extension_device" matches kernel naming, not the device type. If [5:] were off by one, or an override returned a malformed prefix, this test would still pass and the breakage would only appear at C++ compile time. Since cpp_wrapper_flag=True already captures the wrapper source, add a .check("cached_torch_device_type_privateuse1") (or assert CACHE_TORCH_DEVICE(privateuse1) appears) under that branch. This is the regression test that makes the refactor safe. Fix this →

Test helper placement. ExtensionDeviceOpOverrides is defined at module scope (test_extension_backend.py:47-49), ~90 lines from its single use at line 135, and above the try: from . import test_torchinductor block that can sys.exit(0). Move it adjacent to the test, or alongside the other extension backend pieces in extension_backends/cpp/extension_codegen_backend.py where ExtensionScheduling and ExtensionCppWrapperCodegen already live — a backend author copying this test as a template will look there.

Code Quality

aten_device_type() breaks the surrounding class's conventions (common.py:328-332). Every other method on DeviceOpOverrides is a bare raise NotImplementedError with no docstring and no message (common.py:334-405, including the closely analogous cpp_kernel_type / cpp_device_ptr / cpp_stream_type). The new method adds both a docstring and an f-string message. Per CLAUDE.md ("match existing code style and architectural patterns"), either follow the bare form or — if the docstring is genuinely load-bearing here, which it is, since this method needs to document its at::k format requirement — say so and keep it, but drop the redundant custom message since the traceback already names the class.

It is also placed first in the class, ahead of import_get_raw_stream_as, rather than grouped with the other C++-codegen methods (cpp_kernel_type, cpp_device_ptr, cpp_stream_type at common.py:386-396) that it belongs with semantically.

device_to_aten() splits a contiguous block of constant tables. cpp_utils.py has DTYPE_TO_CPP / DTYPE_TO_ATEN / DEVICE_TO_ATEN / LAYOUT_TO_ATEN / DEVICE_TO_INT as one run of mappings; the new function at lines 92-102 wedges between DEVICE_TO_ATEN and LAYOUT_TO_ATEN. Move it below DEVICE_TO_INT (line 111) so the tables stay together.

Backward Compatibility

codegen_device() changes its failure mode from AssertionError("<dev> not found in DEVICE_TO_ATEN") to KeyError/NotImplementedError. I found no callers catching the old type, so this is not a break in practice, but note it for anyone with out-of-tree error handling.

Relatedly, MTIA registers a backend with CppWrapperGpu (common.py:633-640), which subclasses CppWrapperCpu, and MTIADeviceOpOverrides does not implement aten_device_type(). "mtia" was already absent from DEVICE_TO_ATEN, so this path raised before and raises now — no regression, and there is no aoti_torch_device_type_mtia() shim for it to target anyway. Flagging only because this PR is the natural place to note the gap rather than leave it implicit.

Recommendation

Request Changes

The design is the right one and I would like to see it land. Blocking items are the untested failure path plus the absence of any assertion on generated C++ (a refactor whose whole risk is a string transformation should have a test covering that transformation), and the unvalidated at::k format contract on a newly public extension point. The API-design points about ordering and DEVICE_TO_ATEN mutability are worth resolving now, while there are no out-of-tree implementations to break.

Separately, CI reports a PYFMT lint failure on the changed files — lintrunner -a should clear it.

| Branch: `upstream/inductor-device-overrides-aten-device-type`


# TPU uses Pallas for codegen and only needs no-op overrides
register_device_op_overrides("tpu", CpuDeviceOpOverrides())
register_device_op_overrides("tpu", NoOpDeviceOpOverrides())

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.

Is it better to keep CpuDeviceOpOverrides rather than using a new NoOpDeviceOpOverrides?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

TPU previously reused CpuDeviceOpOverrides as a no-op implementation; the existing comment also says that TPU only needs no-op overrides. At that point, the ATen device mapping lived separately in DEVICE_TO_ATEN, which had no TPU entry.

With this PR, CpuDeviceOpOverrides now owns the CPU-specific at::kCPU identity. Continuing to register it for TPU would therefore make device_to_aten("tpu") incorrectly resolve to at::kCPU.

NoOpDeviceOpOverrides separates the existing generic no-op behavior from CPU-specific device identity, so TPU can continue using the former without inheriting the latter.

kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Aug 26, 2026
kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Aug 26, 2026
@srhust

srhust commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

@jansel The changes have been updated . Could you take another look when you have a moment?

@jansel

jansel commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 16m 52s —— View job


Re-reviewed — all four blocking items from my last pass are addressed (global removed, unified RuntimeError, prefix validated, generated C++ now asserted); what's left is a set of non-blocking cleanups, the most useful being to make the error message double as the migration hint for out-of-tree backends that were monkeypatching DEVICE_TO_ATEN.

Full review

Summary

Second pass on #193904 (commits c6959a31..4a37509b). The PR now deletes cpp_utils.DEVICE_TO_ATEN entirely and makes DeviceOpOverrides.aten_device_type() the single source of truth, with meta as the one hardcoded special case. I verified DEVICE_TO_ATEN has no remaining references anywhere in the tree, and that all four in-tree overrides (cpu, cuda, xpu, mps) now implement the method.

Previous round's blocking items — all resolved:

Item Status
Unvalidated at::k contract Fixed — validated in cpp_utils.py:108-117, documented in common.py:392-397
Extension point was dead code / DEVICE_TO_ATEN won over overrides Fixed — table deleted, overrides consulted unconditionally
Split KeyError/NotImplementedError contract Fixed — single RuntimeError, from exc preserves cause
Untested failure path Fixed — test_missing_aten_device_type, test_invalid_aten_device_type
No assertion on generated C++ Fixed — assertIn("CACHE_TORCH_DEVICE(privateuse1);", code) at test_extension_backend.py:227
PYFMT lint Fixed (a593be17)

NoOpDeviceOpOverrides is also the right answer to @FuDdd's question — keeping CpuDeviceOpOverrides for TPU would have made device_to_aten("tpu") silently resolve to at::kCPU. I confirmed nothing does isinstance(..., CpuDeviceOpOverrides), so the split is safe.

Comments

1. The error message is the migration path for out-of-tree backends — make it say what to do. This PR removes a module-global that out-of-tree backends were mutating, so any backend currently doing DEVICE_TO_ATEN["mydev"] = "at::kPrivateUse1" goes from working to hard-failing on upgrade. Their entire diagnostic will be cpp_utils.py:98-106:

raise RuntimeError(f"No ATen device type mapping for {device_type}") from exc

That message doesn't name the fix, and it's byte-identical for the two distinct causes (no registered DeviceOpOverrides at all vs. registered but not implementing the method) — which is exactly the distinction a backend author needs. Suggest keeping the shared prefix (so the existing assertRaisesRegex still matches) and appending cause-specific guidance:

except KeyError as exc:
    raise RuntimeError(
        f"No ATen device type mapping for {device_type}: no DeviceOpOverrides "
        f"is registered. Call register_device_op_overrides({device_type!r}, ...)."
    ) from exc
...
except NotImplementedError as exc:
    raise RuntimeError(
        f"No ATen device type mapping for {device_type}: "
        f"{type(overrides).__name__} does not implement aten_device_type()."
    ) from exc

Worth a line in the PR description too, since this is a behavior break for existing out-of-tree backends rather than a pure refactor. Fix this →

2. Validation checks the prefix but not that the result is a legal C++ identifier. cpp_utils.py:108-117 accepts anything starting with at::k and longer than 5 chars, but the value flows into codegen_device (cpp_wrapper_cpu.py:2370) → used_cached_devices → CACHE_TORCH_DEVICE({device}) (cpp_wrapper_cpu.py:1512), which token-pastes into cached_torch_device_type_##device. So "at::kFoo Bar" passes validation and emits uncompilable C++. Tightening to a single condition also collapses the current three-clause check:

suffix = aten_device_type.removeprefix("at::k") if isinstance(aten_device_type, str) else ""
if not suffix.isidentifier():
    raise RuntimeError(...)

Note the real contract is narrower still: only six aoti_torch_device_type_* shims exist (shim.h:61-66 — cpu, cuda, meta, xpu, mps, privateuse1), so anything else compiles-fails regardless. Not asking you to hardcode that list, but .isidentifier() is a cheap upgrade that turns a C++ compile error into a Python one.

3. NoOpDeviceOpOverrides living in cpu_device_op_overrides.py makes TPU registration import a CPU-named module. common.py:698 now does from .cpu_device_op_overrides import NoOpDeviceOpOverrides purely to register TPU. The class is device-agnostic by construction — that's the whole point of the split — so common.py next to DeviceOpOverrides is its natural home, leaving cpu_device_op_overrides.py with just CPU. Would also remove the mild oddity of the test file importing a generic base from the cpu module (test_extension_backend.py:37-40).

4. Loop-based tests should use @parametrize. CLAUDE.md: "For tests over multiple inputs, use the @parametrize decorator." test_builtin_device_types (test_extension_backend.py:80-88) and test_unsupported_device_types (:106-109) both hand-roll loops, so a single failing device reports as one opaque failure and hides the rest. DeviceToAtenTests would need adding to the instantiate_parametrized_tests call at :256.

5. The two failure-path tests permanently pollute the global override registry. test_missing_aten_device_type and test_invalid_aten_device_type call register_device_op_overrides (:96, :102) with no teardown, so missing_aten_device_type and invalid_aten_device_type stay in device_op_overrides_dict for the rest of the process. Nothing iterates that dict today so there's no live breakage, but it's cheap to be clean:

self.addCleanup(device_op_overrides_dict.pop, device, None)

6. Catching NotImplementedError around the call can swallow an unrelated failure. cpp_utils.py:103-106 treats any NotImplementedError escaping overrides.aten_device_type() as "not implemented", including one raised from deeper inside a backend's own implementation. Comparing against the base method is unambiguous:

if type(overrides).aten_device_type is DeviceOpOverrides.aten_device_type:
    raise RuntimeError(...)

Minor — the current form is fine in practice since real implementations are one-liners — but flagging since the whole point of this hook is third-party code you don't control.

7. Add a one-line comment for the meta special case. cpp_utils.py:93-94 returns at::kMeta before consulting overrides, and the reason (meta has no registered DeviceOpOverrides) is only in the PR description. That's exactly the non-obvious, can't-infer-locally kind of fact CLAUDE.md wants a comment for.

8. test_unsupported_device_types asserting mtia raises is a forward-looking lock. MTIADeviceOpOverrides (mtia/device_op_overrides.py) doesn't implement aten_device_type(), and MTIA registers CppWrapperGpu (a CppWrapperCpu subclass), so MTIA + AOTI raises. That matches pre-PR behavior ("mtia" was never in DEVICE_TO_ATEN) and there's no aoti_torch_device_type_mtia() shim to target, so no regression. But whoever adds MTIA support now has to find and delete this assertion. Fine if intentional — a brief comment saying "no aoti_torch_device_type_mtia shim exists yet; delete this when one is added" would save them the archaeology.

9. Nit: MissingAtenDeviceTypeOverrides (:55-56) subclasses NoOpDeviceOpOverrides only to inherit nothing relevant — the test just needs some override lacking aten_device_type. Subclassing DeviceOpOverrides directly would express that and drop the extra import.

Recommendation

Approve — none of the above is blocking, and #1 is the only one I'd push for before merge since it's user-facing for the exact audience this PR is written for. The design is now clean: one authoritative per-device contract, no mutable global, validated boundary, and a test that actually exercises the string transformation.

CI is green apart from the torchtitan-test broken-trunk failure Dr. CI already attributes to merge base 4863ab71.

| Branch: `upstream/inductor-device-overrides-aten-device-type`

@srhust
srhust force-pushed the upstream/inductor-device-overrides-aten-device-type branch from 4a37509 to e41f7f1 Compare September 3, 2026 03:50
@srhust
srhust force-pushed the upstream/inductor-device-overrides-aten-device-type branch from e41f7f1 to a3271bc Compare September 3, 2026 06:40
@srhust

srhust commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 4, 2026
@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

Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…193904)

## Summary

Route AOTI/C++ wrapper ATen device type mapping through
`DeviceOpOverrides` as the authoritative per-device contract.

This removes the mutable global `DEVICE_TO_ATEN` mapping and lets both
in-tree and out-of-tree backends provide their ATen device type through
the existing device codegen extension point.

## Changes

- Add `DeviceOpOverrides.aten_device_type()` as the per-device contract for
  C++ ATen device type mapping.
- Implement the mapping in the CPU, CUDA, XPU, and MPS device overrides.
- Remove the global `DEVICE_TO_ATEN` mapping.
- Keep `meta` as an explicit special case because it has no registered
  `DeviceOpOverrides`.
- Separate the generic no-op override behavior from CPU-specific device
  identity so TPU continues to use no-op overrides without inheriting the
  CPU ATen device type.
- Route AOTI/C++ wrapper device type generation through `device_to_aten()`.
- Remove the manual `DEVICE_TO_ATEN["extension_device"]` mutation from the
  extension backend test.
- Add coverage for built-in mappings, out-of-tree mappings, missing and
  invalid mappings, and unsupported TPU/MTIA mappings.

## Motivation

AOTI/C++ wrapper codegen previously looked up device types through the
hardcoded mutable `DEVICE_TO_ATEN` mapping.

That forced out-of-tree backends to mutate Inductor module state even when
they already registered a `DeviceOpOverrides` implementation. It also left
two competing mechanisms once an override hook was added: built-in devices
continued to use the global mapping while only out-of-tree devices used the
new hook.

Using `DeviceOpOverrides` as the authoritative backend-specific source keeps
ATen device identity with the existing per-device codegen contract and
removes the need for backends to mutate Inductor globals.

## Test Plan

- Verify CPU, CUDA, XPU, MPS, and meta resolve to their existing ATen device
  types.
- Verify an out-of-tree extension backend resolves to `at::kPrivateUse1`
  through its registered `DeviceOpOverrides`.
- Verify unregistered devices and overrides without an ATen device mapping
  fail explicitly.
- Verify invalid override return values fail with a clear error.
- Verify TPU and MTIA remain unsupported instead of inheriting another
  backend's mapping.
- Existing extension C++ wrapper coverage continues to exercise generated
  device code without mutating a global mapping.

## Out-of-tree backend migration

Out-of-tree backends that previously populated `cpp_utils.DEVICE_TO_ATEN`
should instead implement `aten_device_type()` on their registered
`DeviceOpOverrides`. The returned value must use the `at::k...` form, for
example `at::kPrivateUse1`.

## Notes

- Related RFC: pytorch#189137.

Pull Request resolved: pytorch#193904
Approved by: https://github.com/FuDdd, https://github.com/jansel
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source release notes: inductor (aoti) 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.

6 participants