Repository navigation
Conversation
🔗 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 ( 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. |
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
|
@claude review these changes |
|
Claude finished @jansel's task in 15m 13s —— View job Reviewed — the refactor is directionally right, but the new Full reviewPR Review: #193904SummaryRoutes AOTI/C++ wrapper device-type mapping through API Design
device_str = device_to_aten(device.type)[5:].lower() # remove "at::k"Previously the values fed to Fix one of:
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. Nothing actually prevents the monkeypatching this PR exists to eliminate. Split error contract in
Additionally, TestingThe one added assertion is a tautology. The advertised failure path is untested. The PR body states: "backends that do not provide a mapping fail explicitly instead of defaulting to Nothing verifies the generated C++, so the Test Plan's "end-to-end" claim does not hold. The existing FileCheck at FileCheck().check("void").check(load_expr).check("extension_device").run(code)None of those three tokens depend on the ATen device mapping — Test helper placement. Code Quality
It is also placed first in the class, ahead of
Backward Compatibility
Relatedly, MTIA registers a backend with RecommendationRequest 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 Separately, CI reports a PYFMT lint failure on the changed files — |
|
|
||
| # TPU uses Pallas for codegen and only needs no-op overrides | ||
| register_device_op_overrides("tpu", CpuDeviceOpOverrides()) | ||
| register_device_op_overrides("tpu", NoOpDeviceOpOverrides()) |
There was a problem hiding this comment.
Is it better to keep CpuDeviceOpOverrides rather than using a new NoOpDeviceOpOverrides?
There was a problem hiding this comment.
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.
|
@jansel The changes have been updated . Could you take another look when you have a moment? |
|
@claude review again |
|
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 Full reviewSummarySecond pass on #193904 (commits Previous round's blocking items — all resolved:
Comments1. 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 raise RuntimeError(f"No ATen device type mapping for {device_type}") from excThat message doesn't name the fix, and it's byte-identical for the two distinct causes (no registered 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 excWorth 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. 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 3. 4. Loop-based tests should use 5. The two failure-path tests permanently pollute the global override registry. self.addCleanup(device_op_overrides_dict.pop, device, None)6. Catching 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 8. 9. Nit: RecommendationApprove — 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 |
4a37509 to
e41f7f1
Compare
e41f7f1 to
a3271bc
Compare
|
@pytorchbot merge |
Merge startedYour 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 |
…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
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
Summary
Route AOTI/C++ wrapper ATen device type mapping through
DeviceOpOverridesas the authoritative per-device contract.This removes the mutable global
DEVICE_TO_ATENmapping and lets bothin-tree and out-of-tree backends provide their ATen device type through
the existing device codegen extension point.
Changes
DeviceOpOverrides.aten_device_type()as the per-device contract forC++ ATen device type mapping.
DEVICE_TO_ATENmapping.metaas an explicit special case because it has no registeredDeviceOpOverrides.identity so TPU continues to use no-op overrides without inheriting the
CPU ATen device type.
device_to_aten().DEVICE_TO_ATEN["extension_device"]mutation from theextension backend test.
invalid mappings, and unsupported TPU/MTIA mappings.
Motivation
AOTI/C++ wrapper codegen previously looked up device types through the
hardcoded mutable
DEVICE_TO_ATENmapping.That forced out-of-tree backends to mutate Inductor module state even when
they already registered a
DeviceOpOverridesimplementation. It also lefttwo 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
DeviceOpOverridesas the authoritative backend-specific source keepsATen device identity with the existing per-device codegen contract and
removes the need for backends to mutate Inductor globals.
Test Plan
types.
at::kPrivateUse1through its registered
DeviceOpOverrides.fail explicitly.
backend's mapping.
device code without mutating a global mapping.
Out-of-tree backend migration
Out-of-tree backends that previously populated
cpp_utils.DEVICE_TO_ATENshould instead implement
aten_device_type()on their registeredDeviceOpOverrides. The returned value must use theat::k...form, forexample
at::kPrivateUse1.Notes
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo