Repository navigation
Conversation
🔗 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 ( 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. |
|
|
|
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. |
|
@pytorchbot label "topic: not user facing" |
|
@claude review these changes |
|
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 Full reviewPR Review: #193908SummaryAdds an optional API Design
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 —
The docstring pushes this onto implementers instead (
The
Code Quality
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;
Testing
Missing coverage for the two issues above: no test that an unavailable interface is skipped, and no test that a raising
Documentation
RecommendationRequest Changes The |
aorenste
left a comment
There was a problem hiding this comment.
(Reviewed by me, assisted by AI)
[blocker] My agent says:
test_device_interface_cache_system_info_raisescovers the hook throwing, but not the hook returning metadata that cannot be serialized -- which is the case that actually escapesget_system()(see the inline comment oncodecache.py). Same template, with aFakeDeviceInterfacereturning e.g.{"v": {1, 2}}, asserting the warning fires anddevice_interfacesstays out of the key. Worth adding a{}-returning case in the same pass, since{}andNonedo 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/gcnArchNameplustorch.version.cuda/hipis aCudaInterface.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_propertiescall incodecache.pyis the CUDA one at line 339 andtorch.version.xpuappears 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.
|
@aorenste , The changes have been updated . Could you take another look when you have a moment? |
aorenste
left a comment
There was a problem hiding this comment.
(Reviewed by me, assisted by AI)
|
@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 |
…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
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
Allow registered
DeviceInterfaceimplementations to contribute stabledevice 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 runtimeinformation in Inductor.
Changes
DeviceInterface.get_cache_system_info(), returning optional stable,JSON-serializable metadata for the code cache key.
Noneopts out while an empty dict stillparticipates in the cache key.
CacheBase.get_system()to collect metadata from registered andavailable device interfaces.
cuda:0when collecting metadata soeach backend contributes only once.
non-dict or non-JSON-serializable metadata is warned about and skipped
instead of breaking unrelated compilation.
validation isolated so a broken third-party backend cannot break CPU-only
compilation.
device probing is unavailable.
Motivation
CacheBase.get_system()currently derives cache-invalidating systeminformation 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
DeviceInterfacekeeps backend-specific systemmetadata behind the existing device abstraction and avoids requiring
out-of-tree backends to replace
CacheBase.get_system()or duplicate itscache hashing logic.
The default
DeviceInterface.get_cache_system_info()implementation returnsNone, so backends opt in explicitly.Because
CacheBase.get_system()is cached, the interface must be registeredbefore the hook is first sampled.
Test Plan
Added or updated coverage for:
DeviceInterface.get_cache_system_info()returningNone.additional metadata.
fake:0.cache metadata.
than as an opt-out.
contract.
unavailable.
Follow-up work
This PR intentionally does not migrate the existing CUDA/HIP-specific fields
in
CacheBase.get_system()intoCudaInterface.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 ofthe 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
changes the previous non-CUDA cache payload and therefore causes a one-time
cache invalidation for those environments.
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @azahed98