Skip to content

[Inductor] Let DeviceInterface contribute CodeCache system metadata - #193908

Closed
srhust wants to merge 5 commits into
pytorch:mainfrom
srhust:upstream/inductor-device-interface-cache-system-info
Closed

srhust wants to merge 5 commits into
pytorch:mainfrom
srhust:upstream/inductor-device-interface-cache-system-info

Conversation

@srhust

@srhust srhust commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Allow registered DeviceInterface implementations to contribute stable
device and runtime metadata to the Inductor CodeCache system key.

This lets out-of-tree backends participate in cache invalidation without
replacing CacheBase.get_system() or hardcoding backend-specific runtime
information in Inductor.

Changes

  • Add DeviceInterface.get_cache_system_info(), returning optional stable,
    JSON-serializable metadata for the code cache key.
  • Define the hook contract so None opts out while an empty dict still
    participates in the cache key.
  • Extend CacheBase.get_system() to collect metadata from registered and
    available device interfaces.
  • Skip indexed device aliases such as cuda:0 when collecting metadata so
    each backend contributes only once.
  • Validate contributed metadata before adding it to the cache key:
    non-dict or non-JSON-serializable metadata is warned about and skipped
    instead of breaking unrelated compilation.
  • Keep interface availability checks, metadata collection, and metadata
    validation isolated so a broken third-party backend cannot break CPU-only
    compilation.
  • Preserve Triton version information in the system cache key even when CUDA
    device probing is unavailable.
  • Continue collecting out-of-tree backend metadata when CUDA is unavailable.

Motivation

CacheBase.get_system() currently derives cache-invalidating system
information primarily from CUDA/HIP device properties and runtime versions.

Out-of-tree backends that need their own device or runtime version to
invalidate generated or autotuned code therefore have no backend-owned
extension point for contributing that information.

Providing this through DeviceInterface keeps backend-specific system
metadata behind the existing device abstraction and avoids requiring
out-of-tree backends to replace CacheBase.get_system() or duplicate its
cache hashing logic.

The default DeviceInterface.get_cache_system_info() implementation returns
None, so backends opt in explicitly.

Because CacheBase.get_system() is cached, the interface must be registered
before the hook is first sampled.

Test Plan

Added or updated coverage for:

  • The default DeviceInterface.get_cache_system_info() returning None.
  • Preserving existing CUDA system cache input when no interface contributes
    additional metadata.
  • Including registered interface metadata in the system cache key.
  • Changing interface metadata changing the resulting system hash.
  • Ignoring indexed device aliases such as fake:0.
  • Skipping unavailable device interfaces.
  • Continuing compilation when a device interface raises while contributing
    cache metadata.
  • Treating an empty metadata dict as participating in the cache key rather
    than as an opt-out.
  • Rejecting non-JSON-serializable metadata without propagating the failure.
  • Rejecting JSON-serializable non-dict metadata that violates the hook
    contract.
  • Collecting interface metadata when CUDA is unavailable.
  • Preserving Triton version information in the cache key when CUDA is
    unavailable.

Follow-up work

This PR intentionally does not migrate the existing CUDA/HIP-specific fields
in CacheBase.get_system() into CudaInterface.get_cache_system_info().

That migration would change the existing serialized cache payload shape and
invalidate existing on-disk caches, so it should be handled separately rather
than combined with introducing this extension point.

XpuInterface.get_cache_system_info() is a natural first in-tree adopter of
the new hook because XPU currently does not contribute equivalent device or
runtime metadata to this system cache key. Unlike moving the existing
CUDA/HIP fields, adding XPU metadata would introduce new cache-key information
rather than relocate existing fields.

Notes

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

Copy link
Copy Markdown

🔗 Helpful Links

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

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 a2f761b with merge base 2472115 (image):

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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.

@srhust

srhust commented Aug 18, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Aug 18, 2026
@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 review from aorenste and bobrenjc93 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 16m 51s —— View job


Reviewed at @jansel's request — the extension point itself is reasonable and mirrors the existing get_device_information() precedent, but I'd hold off on approving: get_cache_system_info() is called on every registered interface without an is_available() gate (unlike the two other places that iterate this registry), which makes the Inductor system cache key depend on which backend modules happen to be imported, and the new call sites sit outside the try/except that protects the rest of get_system().

Full review

PR Review: #193908

Summary

Adds an optional DeviceInterface.get_cache_system_info() hook and folds its result into the Inductor CacheBase.get_system() cache key so out-of-tree backends can invalidate generated code on runtime/driver changes. Two correctness/design problems in get_system() (unavailable-device metadata polluting the key, and unguarded exceptions), plus a cast that drops the SystemInfo type check and some avoidable duplication.

API Design

torch/_inductor/codecache.py:370-375 — no is_available() gate; the cache key becomes import-order dependent.

device_interface_info = {
    name: info
    for name, interface in get_registered_device_interfaces()
    if ":" not in name
    if (info := interface.get_cache_system_info()) is not None
}

Both other consumers of this registry gate on availability before calling into the interface — torch/utils/_triton.py:227-233 (if not (device_interface.is_available() and ...): continue) and torch/_inductor/async_compile.py:115-117 (if device_interface.is_available()). This one does not, so:

  • A CPU-only compile on a host that merely has an out-of-tree backend installed picks up that backend's runtime version in its system hash. Bumping a driver for a device the graph never touches invalidates every cached CPU artifact.
  • Two processes on the same machine — one that did import torch_npu, one that didn't — compute different system hashes for an identical graph. Since get_system()["hash"] is the local cache directory name (get_local_cache_path, line 387) and feeds FxGraphHashDetails.system_info (line 1666), this splits the cache and halves hit rates rather than invalidating anything meaningfully.

The docstring pushes this onto implementers instead (without unnecessarily initializing hardware), which makes correctness a per-backend convention rather than something the framework enforces. Gating on interface.is_available() here matches the established pattern and also resolves the "don't initialize hardware" concern for the common case. Fix this →

torch/_inductor/codecache.py:370-375 — unguarded third-party call breaks all compilation.

The try/except (AssertionError, RuntimeError) above covers only the CUDA/HIP block; the registry iteration and every get_cache_system_info() call are outside it. An out-of-tree implementation that raises (probing a driver, reading a device file, an uninitialized runtime) propagates out of get_system() and takes down every torch.compile call in the process, including CPU-only ones that have nothing to do with that backend. Since this hook exists specifically to be implemented by code PyTorch doesn't control, and its contribution is a cache-key optimization, a failure should degrade to "no metadata from this backend" rather than a hard error. Fix this →

torch/_dynamo/device_interface.py:135 — tuple[Any, ...] is not JSON-round-trippable. The docstring promises "JSON-serializable" metadata, and system is written to disk via update_local_cache → json.dumps (line 404). A tuple serializes to a JSON array and reads back as a list, so the in-memory and on-disk forms of device_interfaces differ in type. Nothing compares them today (get_local_cache only reads local_cache["cache"]), so this is latent rather than broken — but dict[str, Any] | None, or at minimum a JSON-native container, states the contract more honestly and gives backends a place to name their fields. If tuple is deliberate, the docstring should say the tuple is positional and order-stable, since the hash depends on element order.

Code Quality

torch/_inductor/codecache.py:354-365, 376-381 — hash_input and system are built as two copies of the same data.

hash_input.update({"device": device_info, "version": version_info})
system.update({"device": device_info, "version": version_info})
...
if device_interface_info:
    hash_input["device_interfaces"] = device_interface_info
    system["device_interfaces"] = device_interface_info
system["hash"] = SYSTEM_CACHE_KEY_STRATEGY.key_from_json(hash_input)

The two dicts are identical by construction; system is just hash_input plus "hash". Keeping them as separate mutable variables means every future field has to be added in two places or the hash silently stops covering it. Building one dict and deriving the other at the return (return {**hash_input, "hash": ...}) removes the duplication and the four-line .update({...}) blocks the reformat is fighting with.

torch/_inductor/codecache.py:381 — cast(SystemInfo, system) gives up the type check the old code had. Previously both returns were SystemInfo-shaped dict literals, so adding a key not declared in SystemInfo (line 169) was a type error. Now system is a bare dict[str, Any] and the cast asserts conformance the checker can no longer verify — the new device_interfaces field is exactly the kind of addition that used to be caught. Constructing the SystemInfo at the return keeps the annotation load-bearing.

torch/_inductor/codecache.py:372-374 — stacked comprehension if clauses. Two consecutive if clauses plus a walrus in one comprehension is dense for what is a filter-and-collect loop; an explicit for loop reads better here and is where the is_available() gate and per-interface error handling from above would naturally live.

Testing

test/inductor/test_codecache.py:238-241, 305-308 — MagicMock strategy doesn't match the real key_from_json signature. side_effect = lambda value: json.dumps(value, sort_keys=True) accepts only one positional arg, but the real CacheKeyStrategy.key_from_json (torch/_inductor/cache_key.py:73) is (value, *, sort_keys=True). If get_system() ever passes sort_keys= explicitly the fake raises TypeError instead of exercising the code. The test immediately above (test_cache_base_get_system_uses_system_strategy, line 183-190) already defines a FakeStrategy with the full signature that also records sort_keys — reusing that pattern keeps the file internally consistent and preserves the sort_keys assertion, which matters here because the hash's stability against registration order depends on it.

test/inductor/test_codecache.py:226-297 — one test asserting five behaviors, with assertions outside the try. first and second are assigned inside the with/try but asserted after the finally (lines 287-297). If any earlier assertion in the block fails, the trailing lines raise UnboundLocalError and that becomes the reported failure instead of the real one. The PR description lists these as five distinct cases (default None, CUDA input preserved, metadata included, hash changes, indexed alias ignored) — splitting them, or at least moving the assertions inside the block, makes failures point at the right thing. The assertIsNone(DeviceInterface.get_cache_system_info()) on line 227 in particular has nothing to do with the rest of the test.

Missing coverage for the two issues above: no test that an unavailable interface is skipped, and no test that a raising get_cache_system_info() doesn't take down get_system(). Both should land with the fixes.

test/inductor/test_codecache.py:288-297 — the combined case is never asserted at the hash-input level. The test checks first["device_interfaces"] and that first["hash"] != second["hash"], but never asserts that key_from_json received both device/version and device_interfaces in the same payload. Given the whole point is that interface metadata composes with the existing CUDA info rather than replacing it, asserting key_from_json.call_args.args[0] for that combined case (as the CUDA-less test already does on line 331-334) would be the load-bearing check.

Documentation

DeviceInterface has no reference documentation anywhere in docs/ — the accelerator integration guides cover the C++ PrivateUse1HooksInterface but not this Python-level registry — so there's no existing page to update. Worth noting only because this hook is useless unless out-of-tree backends know it exists; the RFC (#189137) may be the right place to note the discoverability gap.

Recommendation

Request Changes

The is_available() gate and the unguarded third-party call are the blockers — as written, an installed-but-unused backend can fragment the cache for unrelated CPU compiles, and a misbehaving one can break compilation process-wide. The cast/duplication cleanup and the test restructuring are smaller but should ride along. CI is also red on lintrunner for test/inductor/test_codecache.py (PYFMT only — three over-wrapped calls at lines ~242, ~277, ~328); lintrunner -a clears it.

| Branch: `upstream/inductor-device-interface-cache-system-info`

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

(Reviewed by me, assisted by AI)

[blocker] My agent says:

test_device_interface_cache_system_info_raises covers the hook throwing, but not the hook returning metadata that cannot be serialized -- which is the case that actually escapes get_system() (see the inline comment on codecache.py). Same template, with a FakeDeviceInterface returning e.g. {"v": {1, 2}}, asserting the warning fires and device_interfaces stays out of the key. Worth adding a {}-returning case in the same pass, since {} and None do not produce the same hash.

[cleanup] Follow-up scope worth naming in the description. As it stands the hook ships with zero in-tree users -- get_cache_system_info is overridden nowhere outside the test fakes -- so the production path is only ever exercised by mocks:

  • The CUDA/HIP block in get_system() is the special case this hook generalizes: device_properties.name/gcnArchName plus torch.version.cuda/hip is a CudaInterface.get_cache_system_info(). Relocating it changes the payload shape and invalidates every on-disk cache, so it cannot ride along here -- but with no stated plan, CUDA stays permanently special-cased and this becomes a second, parallel mechanism rather than the one mechanism.
  • XPU and MTIA contribute nothing today. The only get_device_properties call in codecache.py is the CUDA one at line 339 and torch.version.xpu appears nowhere in the file, so an XPU host's system key carries no device or runtime information at all. XpuInterface.get_cache_system_info() is the natural first in-tree user and, unlike CUDA, adds a key rather than relocating one.

Comment thread torch/_inductor/codecache.py Resolved
Comment thread torch/_dynamo/device_interface.py Resolved
Comment thread torch/_inductor/codecache.py Resolved
Comment thread torch/_dynamo/device_interface.py Resolved
Comment thread torch/_inductor/codecache.py Resolved
Comment thread torch/_inductor/codecache.py Resolved
Comment thread torch/_inductor/codecache.py Resolved
Comment thread torch/_inductor/codecache.py Resolved
@srhust
srhust requested a review from aorenste August 24, 2026 08:05
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 1, 2026

Copy link
Copy Markdown
Contributor Author

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

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

(Reviewed by me, assisted by AI)

Comment thread torch/_inductor/codecache.py Resolved
Comment thread torch/_dynamo/device_interface.py Resolved
Comment thread test/inductor/test_codecache.py Resolved
Comment thread torch/_inductor/codecache.py Resolved
@srhust

srhust commented Sep 2, 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 2, 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
…ytorch#193908)

## Summary

Allow registered `DeviceInterface` implementations to contribute stable
device and runtime metadata to the Inductor CodeCache system key.

This lets out-of-tree backends participate in cache invalidation without
replacing `CacheBase.get_system()` or hardcoding backend-specific runtime
information in Inductor.

## Changes

- Add `DeviceInterface.get_cache_system_info()`, returning optional stable,
  JSON-serializable metadata for the code cache key.
- Define the hook contract so `None` opts out while an empty dict still
  participates in the cache key.
- Extend `CacheBase.get_system()` to collect metadata from registered and
  available device interfaces.
- Skip indexed device aliases such as `cuda:0` when collecting metadata so
  each backend contributes only once.
- Validate contributed metadata before adding it to the cache key:
  non-dict or non-JSON-serializable metadata is warned about and skipped
  instead of breaking unrelated compilation.
- Keep interface availability checks, metadata collection, and metadata
  validation isolated so a broken third-party backend cannot break CPU-only
  compilation.
- Preserve Triton version information in the system cache key even when CUDA
  device probing is unavailable.
- Continue collecting out-of-tree backend metadata when CUDA is unavailable.

## Motivation

`CacheBase.get_system()` currently derives cache-invalidating system
information primarily from CUDA/HIP device properties and runtime versions.

Out-of-tree backends that need their own device or runtime version to
invalidate generated or autotuned code therefore have no backend-owned
extension point for contributing that information.

Providing this through `DeviceInterface` keeps backend-specific system
metadata behind the existing device abstraction and avoids requiring
out-of-tree backends to replace `CacheBase.get_system()` or duplicate its
cache hashing logic.

The default `DeviceInterface.get_cache_system_info()` implementation returns
`None`, so backends opt in explicitly.

Because `CacheBase.get_system()` is cached, the interface must be registered
before the hook is first sampled.

## Test Plan

Added or updated coverage for:

- The default `DeviceInterface.get_cache_system_info()` returning `None`.
- Preserving existing CUDA system cache input when no interface contributes
  additional metadata.
- Including registered interface metadata in the system cache key.
- Changing interface metadata changing the resulting system hash.
- Ignoring indexed device aliases such as `fake:0`.
- Skipping unavailable device interfaces.
- Continuing compilation when a device interface raises while contributing
  cache metadata.
- Treating an empty metadata dict as participating in the cache key rather
  than as an opt-out.
- Rejecting non-JSON-serializable metadata without propagating the failure.
- Rejecting JSON-serializable non-dict metadata that violates the hook
  contract.
- Collecting interface metadata when CUDA is unavailable.
- Preserving Triton version information in the cache key when CUDA is
  unavailable.

## Follow-up work

This PR intentionally does not migrate the existing CUDA/HIP-specific fields
in `CacheBase.get_system()` into `CudaInterface.get_cache_system_info()`.

That migration would change the existing serialized cache payload shape and
invalidate existing on-disk caches, so it should be handled separately rather
than combined with introducing this extension point.

`XpuInterface.get_cache_system_info()` is a natural first in-tree adopter of
the new hook because XPU currently does not contribute equivalent device or
runtime metadata to this system cache key. Unlike moving the existing
CUDA/HIP fields, adding XPU metadata would introduce new cache-key information
rather than relocate existing fields.

## Notes

- Preserving Triton version information when CUDA probing is unavailable
  changes the previous non-CUDA cache payload and therefore causes a one-time
  cache invalidation for those environments.
- Related RFC: pytorch#189137.

Pull Request resolved: pytorch#193908
Approved by: https://github.com/aorenste, https://github.com/FuDdd
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: dynamo module: inductor open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants