Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/190615
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (1 Unrelated Failure)As of commit 1d9ff4d with merge base ad4f58f ( BROKEN TRUNK - The following job failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
|
|
|
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" |
663aa76 to
4030681
Compare
4030681 to
0291319
Compare
|
@claude review these changes |
|
Claude finished @jansel's task in 14m 34s —— View job PR Review: #190615SummaryRoutes Inductor's device identity/capability predicates ( Full review detailsCode Quality
Testing
API Design / Correctness
Backward Compatibility
RecommendationRequest Changes — primarily the misleading |
0291319 to
9f54a03
Compare
|
@claude review these changes again |
|
Claude finished @jansel's task in 4m 19s —— View job PR Review: #190615 (re-review)Routes Inductor's device identity/capability predicates through the Full review detailsCode Quality
Testing
Correctness
RecommendationRequest Changes (soft) — the substantive prior findings are resolved. Remaining blockers are test coverage for the two genuinely-new paths ( |
jansel
left a comment
There was a problem hiding this comment.
address automated feedback from claude
9f54a03 to
79b6b8e
Compare
|
@jansel Could you please rerun the failed CI job? |
|
@pytorchbot rebase |
|
@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here |
|
Successfully rebased |
|
@pytorchbot merge |
|
This PR needs to be approved by an authorized maintainer before merge. |
|
@claude review again, update your reland safety analysis based on the above discussion and the new code |
|
Claude finished @jansel's task in 11m 22s —— View job PR Review: #190615 — re-review + updated reland-safety analysis
Bottom line: all three of my pre-merge conditions are now met, and the diff is a provable in-tree no-op for every registered device. Reland risk drops to low — the only remaining item worth doing before merge is an fbcode grep for name collisions, which is a check rather than a code change. Full review detailsWhat changed since the last passEvery substantive item from my previous two reviews and from metamate's follow-up has been addressed:
Verification I did rather than took on faithThe
The The two failure modes named in the root-cause analysis are structurally excluded, not incidentally avoided. Remaining comments (all minor, none blocking)1. mp_count = getattr(props, "multi_processor_count", None)
return props.gpu_subslice_count if mp_count is None else mp_count2. Stray blank line in 3. 4. 5. 6. Design note, unchanged. The docstring now warns backend authors off the MPS/MTIA trap, which was my main ask. I'd still mildly prefer a behavioral name ( Updated reland-risk assessmentRisk: low. Compared to my last assessment ("low with two small additions"), both additions landed. Concretely: What the reland now consists of, behaviorally: nothing. Every in-tree device produces identical values and takes identical code paths. The new surface is two default-off, opt-in extension points plus one test file. That is a materially smaller blast radius than the reverted version, which contained the The identified root cause is eliminated and CI-fenced. Previously my confidence rested on my own registration-by-registration walk. Now The Residual risks, ranked:
My recommendation: approve, and reland after the fbcode grep. I would no longer hold on the internal task. The scope reduction (2026-08-19) independently removed the exact line the analysis (2026-08-20) fingers, the remaining diff's in-tree behavior is verifiable without internal access and I verified it, and the two new tests convert that verification from a review claim into a CI invariant. If a second Recommendation: Approve. All three pre-merge conditions from my last pass are met — the |
|
@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#190615) Summary Route Inductor's device identity, capability classification, and AOTI codegen device selection through the DeviceInterface contract, so out-of-tree PrivateUse1 accelerator backends are recognized as GPU-class, Triton-capable, and guard-emitting without monkeypatching upstream module-level state. Changes DeviceInterface contract (`torch/_dynamo Add is_gpu() (default False), exposes_streams() (derived from Stream slot override), and get_multi_processor_count() (default reads standard field multi_processor_count) capability bits to the base class Declare the bits for all 6 in-tree backend, CpuInterface.is_triton_capable() to check "cpu" in triton.backends.backends instead of unconditionally returning True Device identity predicates (torch/_inductor/utils.py) is_gpu() queries get_interface_for_device(device).is_gpu() instead of testing membership in the hardcoded GPU_TYPES list device_need_guard() becomes is_gpu() ∧ exposes_streams(), eliminating the handwritten != "mps" special case get_gpu_type() removes the assert len(a crash and adds a PrivateUse1-first disambiguation rule matching the C++ getAccelerator()` priority Add private _gpu_types() for enumeration Triton routing (torch/utils/_triton.py) has_triton() walks get_registered_device_interfaces(), queries is_triton_capable() first then validates the backend is actually built via raise_if_triton_unavailable(), replacing the hardcoded triton_supported_devices dict Skip "device:index" entries; only catch RuntimeError so that GPUTooOldForTriton is never leaked for sub-capable devices Changes DeviceInterface contract (`torch/_dynamo Add is_gpu() (default False), exposes_streams() (derived from Stream slot override), and get_multi_processor_count() (default reads standard field multi_processor_count) capability bits to the base class Declare the bits for all 6 in-tree backends (CUDA/XPU/MTIA/MPS/CPU/TPU), each precisely reproducing current behavior Fix CpuInterface.is_triton_capable() to check "cpu" in triton.backends.backends instead of unconditionally returning True Device identity predicates (torch/_inductor/utils.py) is_gpu() queries get_interface_for_deviof testing membership in the hardcoded GPU_TYPES` list device_need_guard() becomes is_gpu() ∧ exposes_streams(), eliminating the handwritten != "mps" special case get_gpu_type() removes the assert len(avail_gpus) <= 1 coexistence crash and adds a PrivateUse1-first disambiguation rule matching the C++ getAccelerator() priority Add private _gpu_types() for enumeration, backed by the registry Triton routing (torch/utils/_triton.py has_triton() walks get_registered_device_interfaces(), queries is_triton_capable() first then validates the backend is actually built via raise_if_triton_unavailable(), repla triton_supported_devices dict Skip "device:index" entries; only catch RuntimeError so that GPUTooOldForTriton is never leaked for s Codegen / AOTI device selection (torch/_inductor/graph.py) cpp_wrapper two-pass gate (line 2511): `[" JIT compile device selection (line 2819): ("cuda","xpu") → is_gpu(d) Device properties (torch/_inductor/runtime/hints.py) Collapse DeviceProperties.create's multi_processor_count device-name ladder (try default → xpu: gpu_subslice_count → mtia: 64) into the single contract call device_interface.get_multi_processor_count(device) Tests (test/inductor/test_device_identity.py) 14 new tests covering: base defaults, in-tree backend declarations, is_gpu() predicate behavior, device_nee has_triton()registry discovery,get_gpu_type()` disambiguation, and PrivateUse1 opt-in scenarios Motivation Inductor's lowest-level device predicates (is_gpu, has_triton, device_need_guard, DeviceProperties.creat hardcoded device-name lists instead of consulting the existing DeviceInterfacecontract. An out-of-tree P already registered a completeDeviceInterfacewas still classified as non-GPU and no-guard, and could only work around it by mutating upstream module-level state at import time. Routing these predicates through the contract lets any registered backend participate through its ownDeviceInterface` — zero upstream module-state mutation required. Test Plan CI: python test/inductor/test_device_identity.py (14 new device-agnostic unit tests — no hardware dependency) Behavior equivalence verified over the in-tree device matrix (cuda/xpu/mtia/mps/cpu/tpu): old vs new fo device_need_guard(), has_triton(), get_gpu_type(), DeviceProperties.create() — all match A PrivateUse1 backend declaring is_gpu()=True / is_triton_capable()=True is now correctly classified as GPU, Triton-capable, and guard-emitting CUDA behavior is byte-for-byte unchanged Notes Related RFC: DeviceInterface registry support for PrivateUse1 backends in torch.compile (4 classes, 9 hardcoded "device identity and capability" class) GPU_TYPES is retained as a late-binding compatibility shim and can be removed once all call-sites have migrated Pull Request resolved: pytorch#190615 Approved by: https://github.com/jansel, https://github.com/JiasenTian
…bility (pytorch#190615)" This reverts commit 80216c6. Reverted pytorch#190615 on behalf of https://github.com/atalman due to reverted internally ([comment](pytorch#190615 (comment)))
…rties (pytorch#190615) ## Summary Add backend extension points for C++ wrapper routing and device-property metadata so out-of-tree accelerator backends can participate in these Inductor paths without hardcoding their device names in core. ## Changes - Add `DeviceOpOverrides.uses_gpu_cpp_wrapper()` with a default of `False`. CUDA and XPU override it to `True`, preserving the existing C++ wrapper routing behavior for in-tree backends. - Use `uses_gpu_cpp_wrapper()` in both `GraphLowering` C++ wrapper decisions: the two-pass wrapper-codegen gate and the device selection used for JIT wrapper compilation. - Treat unregistered devices conservatively as not using the GPU-style C++ wrapper path. - Add `DeviceInterface.get_multi_processor_count()`. The default implementation reads the standard `multi_processor_count` device-property field and asks backends with a different representation to override the method. - Preserve the existing XPU behavior through `gpu_subslice_count` and the existing MTIA value of `64`. - Make `DeviceProperties.create()` obtain the compute-unit count through `DeviceInterface.get_multi_processor_count()`. ## Motivation Two Inductor paths currently encode backend-specific assumptions directly in core: C++ wrapper routing recognizes CUDA/XPU by device name, and `DeviceProperties.create()` contains device-specific handling for compute-unit metadata. For an out-of-tree backend, these differences are properties of the backend rather than properties of Inductor itself. `DeviceOpOverrides` already owns backend-specific codegen behavior, while `DeviceInterface` already owns backend device properties. Exposing the two decisions through those existing contracts lets registered backends provide their behavior directly without adding out-of-tree device names or property layouts to Inductor core. ## Test Plan - CI: `python test/inductor/test_device_identity.py` - Added device-independent tests for `get_multi_processor_count()`: standard-property behavior, missing-property error handling, the XPU `gpu_subslice_count` override, and the MTIA fixed value. - Added a `DeviceProperties.create()` test using a fake `DeviceInterface` to verify that the compute-unit count is obtained through the interface contract. - Added C++ wrapper-routing tests covering CUDA/XPU opt-in, CPU/MPS default behavior, an out-of-tree `DeviceOpOverrides` opt-in, the default out-of-tree behavior, and an unregistered device. - The tests use fake interfaces / registered overrides and mocks where needed, so the new coverage does not require accelerator hardware. ## Notes - `uses_gpu_cpp_wrapper()` is a backend codegen capability rather than a general device-classification predicate. Both relevant `GraphLowering` call sites use the same capability. - The default behavior of both extension points is conservative: `DeviceOpOverrides` does not opt into GPU-style wrapper routing, while `DeviceInterface.get_multi_processor_count()` uses the standard device property when available. - Existing CUDA/XPU C++ wrapper routing and XPU/MTIA compute-unit behavior are preserved. Pull Request resolved: pytorch#190615 Approved by: https://github.com/jansel
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`. Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`. This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior. This method was introduced in PyTorch with: - pytorch/pytorch#190615 Generated from cl/975497299 PiperOrigin-RevId: 975497299
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`. Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`. This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior. This method was introduced in PyTorch with: - pytorch/pytorch#190615 Generated from cl/975497299 PiperOrigin-RevId: 975497299
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`. Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`. This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior. This method was introduced in PyTorch with: - pytorch/pytorch#190615 Generated from cl/975497299 PiperOrigin-RevId: 975497299
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`. Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`. This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior. This method was introduced in PyTorch with: - pytorch/pytorch#190615 Generated from cl/975497299 PiperOrigin-RevId: 975497299
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`. Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`. This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior. This method was introduced in PyTorch with: - pytorch/pytorch#190615 Generated from cl/975497299 PiperOrigin-RevId: 975497299
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`. Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`. This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior. This method was introduced in PyTorch with: - pytorch/pytorch#190615 Generated from cl/975497299 PiperOrigin-RevId: 975497299
Implements `get_multi_processor_count` on `_DeviceModule` and exposes it via `torch.tpu`. Upstream PyTorch updated `DeviceInterface` and Inductor device property queries (`torch._inductor.runtime.hints.DeviceProperties.create`) to invoke `device_interface.get_multi_processor_count(device)` rather than reading `multi_processor_count` directly from device properties. Without this method on the registered TPU device interface, Inductor lowering fails with `AttributeError: module 'torch.tpu' has no attribute 'get_multi_processor_count'`. This method queries `multi_processor_count` from `get_device_properties(device)` and defaults to 1 if properties are uninitialized or unavailable, matching PyTorch's default `DeviceInterface` behavior. This method was introduced in PyTorch with: - pytorch/pytorch#190615 Generated from cl/976571851 PiperOrigin-RevId: 976571851
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
Adds a regression test for the behavior changed and then reverted in pytorch#190615.
## Summary Replace the hardcoded torch.xpu/torch.cuda if-chain in flex_decoding.get_split_k with a query against the kernel's target device through the DeviceInterface capability (pytorch#190615), so the SM count that feeds the SPLIT_KV heuristic is sourced from whichever device the decode kernel actually targets instead of ambient xpu/cuda detection. Existing behavior is preserved for single-device cuda and xpu environments (same SM count, same SPLIT_KV); mixed-backend machines now route correctly, and backends with no registered interface get a clear error instead of crashing inside CUDA device property initialization. ## Changes torch/_inductor/kernel/flex/flex_decoding.py: get_split_k now takes the kernel target device as a required keyword argument (`device: torch.device`) and resolves its SM count via get_interface_for_device(device), then interface.get_multi_processor_count(device). The lazy import of torch._dynamo.device_interface keeps the dynamo dependency off this module's load path (matching the style of other decoupling sites). The split_k formula (num_SM // bh * 2, floored to 1) is unchanged -- only the source of num_SM moves from a hardcoded device string / is_available() probe to the device's own registered interface. The single call site (create_flex_decoding_kernel) now reads `device = query.get_device()` (the surrounding code already queried query.get_device().type two lines above) and passes it through, which also fixes a latent multi-card inaccuracy where the old code used the default "xpu"/"cuda" device instead of the kernel's actual device index. ## Motivation get_split_k feeds SPLIT_KV, which sizes the decode KV intermediate buffer (buf_ACC_shape). The original if-chain asked the ambient environment ("is xpu available?") rather than "which device is this kernel for": on a machine with both xpu and cuda, every cuda decode kernel wrongly took the xpu branch; on a machine with neither (mtia-only, cpu-triton), the code crashed inside torch.cuda device-property initialization with no path to a usable value; tpu and out-of-tree accelerators had no legal path at all. The DeviceInterface registry already exposes get_multi_processor_count (added in pytorch#190615, already consumed by hints.py): cuda reads the standard multi_processor_count field, xpu overrides with gpu_subslice_count, mtia defaults to 64. Routing get_split_k through the same contract lets each backend report its own SM count for the device the kernel actually targets, and surfaces a clear AttributeError ("must override") for a backend whose interface has not yet been adapted -- pointing the backend author at the one method to override -- instead of an opaque CUDA init failure. ## Test Plan CI: python -m pytest -q test/inductor/test_flex_attention.py CI: python test/inductor/test_flex_attention.py CI: lintrunner -a torch/_inductor/kernel/flex/flex_decoding.py Verified on GPU (cuda): flex decode end-to-end passes (the device matrix tests cover the SPLIT_KV-shaped buffer indirectly). Verified on CPU: pytest 2 passed, 582 skipped, 0 failed; python direct run 584 tests, OK (skipped=582). Same result in NPU mode and CPU mode. Verified on an Ascend NPU container: pytest 2 passed, 582 skipped, 0 failed in both NPU mode and CPU mode; the mainline get_split_k path is not reached on NPU (torch_npu overrides the flex decode lowering), so this confirms non-regression and import/collection integrity. lintrunner reports 0 violations on the changed file. No new tests added: the existing decode end-to-end device matrix tests already cover SPLIT_KV indirectly (a changed value resizes buf_ACC_shape and turns the test red), and the must-override contract get_split_k now relies on is already tested by test_device_backend_hooks.py::TestMultiProcessorCount ::test_missing_standard_property (pytorch#190615). A standalone unit test for the formula / routing would be zero-increment over that coverage, so it is omitted to keep the PR a minimal source-only diff. ## Notes Behavior preservation: for any single-device cuda or xpu CI environment the SM count is identical to before (cuda reads the same multi_processor_count field; xpu's override returns the same gpu_subslice_count), so SPLIT_KV is unchanged and the formula is untouched. The behavioral changes are all on paths the old code could not handle correctly: - On a mixed xpu+cuda machine, a cuda decode kernel now reads multi_processor_count instead of wrongly taking the xpu branch. This is a bug fix; single-device CI is structurally unaffected. - On an mtia-only / no-xpu-no-cuda machine, the previous CUDA-init crash becomes a usable value (mtia default 64). - For an out-of-tree DeviceInterface that has not yet overridden get_multi_processor_count, the previous opaque crash becomes a clear AttributeError("must override") pointing at the method to implement; once the backend overrides it (returning its SM count), the decode heuristic works without a mainline patch. Part of the hardware decoupling effort: remove hardcoded device lists so backends register capability through their DeviceInterface instead. Authored with an AI assistant (Claude).
## Summary Replace the hardcoded torch.xpu/torch.cuda if-chain in flex_decoding.get_split_k with a query against the kernel's target device through the DeviceInterface capability (pytorch#190615), so the SM count that feeds the SPLIT_KV heuristic is sourced from whichever device the decode kernel actually targets instead of ambient xpu/cuda detection. Existing behavior is preserved for single-device cuda and xpu environments (same SM count, same SPLIT_KV); mixed-backend machines now route correctly, and backends with no registered interface get a clear error instead of crashing inside CUDA device property initialization. ## Changes torch/_inductor/kernel/flex/flex_decoding.py: get_split_k now takes the kernel target device as a required keyword argument (`device: torch.device`) and resolves its SM count via get_interface_for_device(device), then interface.get_multi_processor_count(device). The lazy import of torch._dynamo.device_interface keeps the dynamo dependency off this module's load path (matching the style of other decoupling sites). The split_k formula (num_SM // bh * 2, floored to 1) is unchanged -- only the source of num_SM moves from a hardcoded device string / is_available() probe to the device's own registered interface. The single call site (create_flex_decoding_kernel) now reads `device = query.get_device()` (the surrounding code already queried query.get_device().type two lines above) and passes it through, which also fixes a latent multi-card inaccuracy where the old code used the default "xpu"/"cuda" device instead of the kernel's actual device index. ## Motivation get_split_k feeds SPLIT_KV, which sizes the decode KV intermediate buffer (buf_ACC_shape). The original if-chain asked the ambient environment ("is xpu available?") rather than "which device is this kernel for": on a machine with both xpu and cuda, every cuda decode kernel wrongly took the xpu branch; on a machine with neither (mtia-only, cpu-triton), the code crashed inside torch.cuda device-property initialization with no path to a usable value; tpu and out-of-tree accelerators had no legal path at all. The DeviceInterface registry already exposes get_multi_processor_count (added in pytorch#190615, already consumed by hints.py): cuda reads the standard multi_processor_count field, xpu overrides with gpu_subslice_count, mtia defaults to 64. Routing get_split_k through the same contract lets each backend report its own SM count for the device the kernel actually targets, and surfaces a clear AttributeError ("must override") for a backend whose interface has not yet been adapted -- pointing the backend author at the one method to override -- instead of an opaque CUDA init failure. ## Test Plan CI: python -m pytest -q test/inductor/test_flex_attention.py CI: python test/inductor/test_flex_attention.py CI: lintrunner -a torch/_inductor/kernel/flex/flex_decoding.py Verified on GPU (cuda): flex decode end-to-end passes (the device matrix tests cover the SPLIT_KV-shaped buffer indirectly). Verified on CPU: pytest 2 passed, 582 skipped, 0 failed; python direct run 584 tests, OK (skipped=582). Same result in NPU mode and CPU mode. Verified on an Ascend NPU container: pytest 2 passed, 582 skipped, 0 failed in both NPU mode and CPU mode; the mainline get_split_k path is not reached on NPU (torch_npu overrides the flex decode lowering), so this confirms non-regression and import/collection integrity. lintrunner reports 0 violations on the changed file. No new tests added: the existing decode end-to-end device matrix tests already cover SPLIT_KV indirectly (a changed value resizes buf_ACC_shape and turns the test red), and the must-override contract get_split_k now relies on is already tested by test_device_backend_hooks.py::TestMultiProcessorCount ::test_missing_standard_property (pytorch#190615). A standalone unit test for the formula / routing would be zero-increment over that coverage, so it is omitted to keep the PR a minimal source-only diff. ## Notes Behavior preservation: for any single-device cuda or xpu CI environment the SM count is identical to before (cuda reads the same multi_processor_count field; xpu's override returns the same gpu_subslice_count), so SPLIT_KV is unchanged and the formula is untouched. The behavioral changes are all on paths the old code could not handle correctly: - On a mixed xpu+cuda machine, a cuda decode kernel now reads multi_processor_count instead of wrongly taking the xpu branch. This is a bug fix; single-device CI is structurally unaffected. - On an mtia-only / no-xpu-no-cuda machine, the previous CUDA-init crash becomes a usable value (mtia default 64). - For an out-of-tree DeviceInterface that has not yet overridden get_multi_processor_count, the previous opaque crash becomes a clear AttributeError("must override") pointing at the method to implement; once the backend overrides it (returning its SM count), the decode heuristic works without a mainline patch. Part of the hardware decoupling effort: remove hardcoded device lists so backends register capability through their DeviceInterface instead. Authored with an AI assistant (Claude).
…ce (#196736) ## Summary Replace the hardcoded torch.xpu/torch.cuda if-chain in flex_decoding.get_split_k with a query against the kernel's target device through the DeviceInterface capability (#190615), so the SM count that feeds the SPLIT_KV heuristic is sourced from whichever device the decode kernel actually targets instead of ambient xpu/cuda detection. Existing behavior is preserved for single-device cuda and xpu environments (same SM count, same SPLIT_KV); mixed-backend machines now route correctly, and backends with no registered interface get a clear error instead of crashing inside CUDA device property initialization. ## Changes torch/_inductor/kernel/flex/flex_decoding.py: get_split_k now takes the kernel target device as a required keyword argument (`device: torch.device`) and resolves its SM count via get_interface_for_device(device), then interface.get_multi_processor_count(device). The lazy import of torch._dynamo.device_interface keeps the dynamo dependency off this module's load path (matching the style of other decoupling sites). The split_k formula (num_SM // bh * 2, floored to 1) is unchanged -- only the source of num_SM moves from a hardcoded device string / is_available() probe to the device's own registered interface. The single call site (create_flex_decoding_kernel) now reads `device = query.get_device()` (the surrounding code already queried query.get_device().type two lines above) and passes it through, which also fixes a latent multi-card inaccuracy where the old code used the default "xpu"/"cuda" device instead of the kernel's actual device index. ## Motivation get_split_k feeds SPLIT_KV, which sizes the decode KV intermediate buffer (buf_ACC_shape). The original if-chain asked the ambient environment ("is xpu available?") rather than "which device is this kernel for": on a machine with both xpu and cuda, every cuda decode kernel wrongly took the xpu branch; on a machine with neither (mtia-only, cpu-triton), the code crashed inside torch.cuda device-property initialization with no path to a usable value; tpu and out-of-tree accelerators had no legal path at all. The DeviceInterface registry already exposes get_multi_processor_count (added in #190615, already consumed by hints.py): cuda reads the standard multi_processor_count field, xpu overrides with gpu_subslice_count, mtia defaults to 64. Routing get_split_k through the same contract lets each backend report its own SM count for the device the kernel actually targets, and surfaces a clear AttributeError ("must override") for a backend whose interface has not yet been adapted -- pointing the backend author at the one method to override -- instead of an opaque CUDA init failure. ## Test Plan CI: python -m pytest -q test/inductor/test_flex_attention.py CI: python test/inductor/test_flex_attention.py CI: lintrunner -a torch/_inductor/kernel/flex/flex_decoding.py Verified on GPU (cuda): flex decode end-to-end passes (the device matrix tests cover the SPLIT_KV-shaped buffer indirectly). Verified on CPU: pytest 2 passed, 582 skipped, 0 failed; python direct run 584 tests, OK (skipped=582). Same result in NPU mode and CPU mode. Verified on an Ascend NPU container: pytest 2 passed, 582 skipped, 0 failed in both NPU mode and CPU mode; the mainline get_split_k path is not reached on NPU (torch_npu overrides the flex decode lowering), so this confirms non-regression and import/collection integrity. lintrunner reports 0 violations on the changed file. No new tests added: the existing decode end-to-end device matrix tests already cover SPLIT_KV indirectly (a changed value resizes buf_ACC_shape and turns the test red), and the must-override contract get_split_k now relies on is already tested by test_device_backend_hooks.py::TestMultiProcessorCount ::test_missing_standard_property (#190615). A standalone unit test for the formula / routing would be zero-increment over that coverage, so it is omitted to keep the PR a minimal source-only diff. ## Notes Behavior preservation: for any single-device cuda or xpu CI environment the SM count is identical to before (cuda reads the same multi_processor_count field; xpu's override returns the same gpu_subslice_count), so SPLIT_KV is unchanged and the formula is untouched. The behavioral changes are all on paths the old code could not handle correctly: - On a mixed xpu+cuda machine, a cuda decode kernel now reads multi_processor_count instead of wrongly taking the xpu branch. This is a bug fix; single-device CI is structurally unaffected. - On an mtia-only / no-xpu-no-cuda machine, the previous CUDA-init crash becomes a usable value (mtia default 64). - For an out-of-tree DeviceInterface that has not yet overridden get_multi_processor_count, the previous opaque crash becomes a clear AttributeError("must override") pointing at the method to implement; once the backend overrides it (returning its SM count), the decode heuristic works without a mainline patch. Part of the hardware decoupling effort: remove hardcoded device lists so backends register capability through their DeviceInterface instead. Authored with an AI assistant (Claude). Pull Request resolved: #196736 Approved by: https://github.com/jansel, https://github.com/drisspg
…ce (pytorch#196736) ## Summary Replace the hardcoded torch.xpu/torch.cuda if-chain in flex_decoding.get_split_k with a query against the kernel's target device through the DeviceInterface capability (pytorch#190615), so the SM count that feeds the SPLIT_KV heuristic is sourced from whichever device the decode kernel actually targets instead of ambient xpu/cuda detection. Existing behavior is preserved for single-device cuda and xpu environments (same SM count, same SPLIT_KV); mixed-backend machines now route correctly, and backends with no registered interface get a clear error instead of crashing inside CUDA device property initialization. ## Changes torch/_inductor/kernel/flex/flex_decoding.py: get_split_k now takes the kernel target device as a required keyword argument (`device: torch.device`) and resolves its SM count via get_interface_for_device(device), then interface.get_multi_processor_count(device). The lazy import of torch._dynamo.device_interface keeps the dynamo dependency off this module's load path (matching the style of other decoupling sites). The split_k formula (num_SM // bh * 2, floored to 1) is unchanged -- only the source of num_SM moves from a hardcoded device string / is_available() probe to the device's own registered interface. The single call site (create_flex_decoding_kernel) now reads `device = query.get_device()` (the surrounding code already queried query.get_device().type two lines above) and passes it through, which also fixes a latent multi-card inaccuracy where the old code used the default "xpu"/"cuda" device instead of the kernel's actual device index. ## Motivation get_split_k feeds SPLIT_KV, which sizes the decode KV intermediate buffer (buf_ACC_shape). The original if-chain asked the ambient environment ("is xpu available?") rather than "which device is this kernel for": on a machine with both xpu and cuda, every cuda decode kernel wrongly took the xpu branch; on a machine with neither (mtia-only, cpu-triton), the code crashed inside torch.cuda device-property initialization with no path to a usable value; tpu and out-of-tree accelerators had no legal path at all. The DeviceInterface registry already exposes get_multi_processor_count (added in pytorch#190615, already consumed by hints.py): cuda reads the standard multi_processor_count field, xpu overrides with gpu_subslice_count, mtia defaults to 64. Routing get_split_k through the same contract lets each backend report its own SM count for the device the kernel actually targets, and surfaces a clear AttributeError ("must override") for a backend whose interface has not yet been adapted -- pointing the backend author at the one method to override -- instead of an opaque CUDA init failure. ## Test Plan CI: python -m pytest -q test/inductor/test_flex_attention.py CI: python test/inductor/test_flex_attention.py CI: lintrunner -a torch/_inductor/kernel/flex/flex_decoding.py Verified on GPU (cuda): flex decode end-to-end passes (the device matrix tests cover the SPLIT_KV-shaped buffer indirectly). Verified on CPU: pytest 2 passed, 582 skipped, 0 failed; python direct run 584 tests, OK (skipped=582). Same result in NPU mode and CPU mode. Verified on an Ascend NPU container: pytest 2 passed, 582 skipped, 0 failed in both NPU mode and CPU mode; the mainline get_split_k path is not reached on NPU (torch_npu overrides the flex decode lowering), so this confirms non-regression and import/collection integrity. lintrunner reports 0 violations on the changed file. No new tests added: the existing decode end-to-end device matrix tests already cover SPLIT_KV indirectly (a changed value resizes buf_ACC_shape and turns the test red), and the must-override contract get_split_k now relies on is already tested by test_device_backend_hooks.py::TestMultiProcessorCount ::test_missing_standard_property (pytorch#190615). A standalone unit test for the formula / routing would be zero-increment over that coverage, so it is omitted to keep the PR a minimal source-only diff. ## Notes Behavior preservation: for any single-device cuda or xpu CI environment the SM count is identical to before (cuda reads the same multi_processor_count field; xpu's override returns the same gpu_subslice_count), so SPLIT_KV is unchanged and the formula is untouched. The behavioral changes are all on paths the old code could not handle correctly: - On a mixed xpu+cuda machine, a cuda decode kernel now reads multi_processor_count instead of wrongly taking the xpu branch. This is a bug fix; single-device CI is structurally unaffected. - On an mtia-only / no-xpu-no-cuda machine, the previous CUDA-init crash becomes a usable value (mtia default 64). - For an out-of-tree DeviceInterface that has not yet overridden get_multi_processor_count, the previous opaque crash becomes a clear AttributeError("must override") pointing at the method to implement; once the backend overrides it (returning its SM count), the decode heuristic works without a mainline patch. Part of the hardware decoupling effort: remove hardcoded device lists so backends register capability through their DeviceInterface instead. Authored with an AI assistant (Claude). Pull Request resolved: pytorch#196736 Approved by: https://github.com/jansel, https://github.com/drisspg
Summary
Add backend extension points for C++ wrapper routing and device-property
metadata so out-of-tree accelerator backends can participate in these Inductor
paths without hardcoding their device names in core.
Changes
DeviceOpOverrides.uses_gpu_cpp_wrapper()with a default ofFalse.CUDA and XPU override it to
True, preserving the existing C++ wrapperrouting behavior for in-tree backends.
uses_gpu_cpp_wrapper()in bothGraphLoweringC++ wrapper decisions:the two-pass wrapper-codegen gate and the device selection used for JIT
wrapper compilation.
wrapper path.
DeviceInterface.get_multi_processor_count(). The default implementationreads the standard
multi_processor_countdevice-property field and asksbackends with a different representation to override the method.
gpu_subslice_countand theexisting MTIA value of
64.DeviceProperties.create()obtain the compute-unit count throughDeviceInterface.get_multi_processor_count().Motivation
Two Inductor paths currently encode backend-specific assumptions directly in
core: C++ wrapper routing recognizes CUDA/XPU by device name, and
DeviceProperties.create()contains device-specific handling for compute-unitmetadata.
For an out-of-tree backend, these differences are properties of the backend
rather than properties of Inductor itself.
DeviceOpOverridesalready ownsbackend-specific codegen behavior, while
DeviceInterfacealready ownsbackend device properties.
Exposing the two decisions through those existing contracts lets registered
backends provide their behavior directly without adding out-of-tree device
names or property layouts to Inductor core.
Test Plan
python test/inductor/test_device_identity.pyget_multi_processor_count():standard-property behavior, missing-property error handling, the XPU
gpu_subslice_countoverride, and the MTIA fixed value.DeviceProperties.create()test using a fakeDeviceInterfacetoverify that the compute-unit count is obtained through the interface
contract.
behavior, an out-of-tree
DeviceOpOverridesopt-in, the defaultout-of-tree behavior, and an unregistered device.
so the new coverage does not require accelerator hardware.
Notes
uses_gpu_cpp_wrapper()is a backend codegen capability rather than ageneral device-classification predicate. Both relevant
GraphLoweringcall sites use the same capability.
DeviceOpOverridesdoes not opt into GPU-style wrapper routing, whileDeviceInterface.get_multi_processor_count()uses the standard deviceproperty when available.
preserved.
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @azahed98