Repository navigation
[fix]: derive is_gpu()/device_need_guard() from DeviceInterface - #190326
05mengmeizi wants to merge 4 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/190326
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (4 Unrelated Failures)As of commit 46b3f0f 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. |
07874fe to
084759f
Compare
|
@claude review these changes |
|
Claude finished @jansel's task in 4m 11s —— View job Reviewed the changes. One meaningful perf/design concern in the hot PR Review: #190326 — full detailsSummaryRoutes Inductor's GPU classification through Code Quality / Performance
Backward Compatibility / Correctness
Testing
RecommendationRequest Changes — the |
Thanks for the thorough review
Lint — the |
|
@claude review these changes again |
|
Claude finished @jansel's task in 9m 35s —— View job Re-reviewed. The PR Review: #190326 — full detailsPR Review: #190326SummaryRoutes Inductor's GPU classification through Backward Compatibility / Correctness
Performance
Testing
API Design
Code Quality
RecommendationRequest Changes — three blocking items: the unfixed |
…r NPU Summary: - Add is_gpu()/exposes_streams() to DeviceInterface base class for dynamic GPU type discovery - Change GPU_TYPES from hardcoded list to dynamic _GpuTypes class using is_gpu() - Update HAS_GPU to use GPU_TYPES instead of hardcoded CUDA/XPU - Add npu to GPU_BENCHMARK_DEVICE_TYPES - Replace @requires_cuda with @skipIf(not HAS_GPU) in test_compiler_bisector This allows out-of-tree accelerators (e.g. NPU) to be recognized as GPU devices, enabling test_compiler_bisector to run on non-CUDA hardware. Related to pytorch#190326 (is_gpu() dynamic query) and pytorch#185590 (test classification). Labels: module:tests/dynamo
…r NPU Summary: - Add is_gpu()/exposes_streams() to DeviceInterface base class for dynamic GPU type discovery - Change GPU_TYPES from hardcoded list to dynamic _GpuTypes class using is_gpu() - Add npu to GPU_BENCHMARK_DEVICE_TYPES - Remove redundant @requires_cuda from test_cudagraph_bisect_max (class-level @skipIf already covers) This allows out-of-tree accelerators (e.g. NPU) to be recognized as GPU devices, enabling test_compiler_bisector to run on non-CUDA hardware. Related to pytorch#190326 (is_gpu() dynamic query) and pytorch#185590 (test classification). Labels: module:tests/dynamo
…iler_bisector ## Summary Remove the redundant `@requires_cuda` decorator from `test_cudagraph_bisect_max` in `test/dynamo/test_compiler_bisector.py`. The class-level `@unittest.skipIf(not HAS_GPU, "requires GPU and Triton")` already guards all tests in the class, making the method-level `@requires_cuda` redundant. ## Changes - **`test/dynamo/test_compiler_bisector.py`**: Remove `from torch.testing._internal.common_utils import requires_cuda` and `@requires_cuda` decorator on `test_cudagraph_bisect_max` (2 lines deleted, 0 lines added) ## Motivation The `@requires_cuda` decorator was added when the file was created, because `cudagraph_trees.py` hardcoded `torch.cuda.CUDAGraph()` and only CUDA supported cudagraph at that time. The class-level guard `@unittest.skipIf(not HAS_GPU, "requires GPU and Triton")` uses `HAS_GPU`, which checks `GPU_TYPES` (a registry-derived set of device types whose `DeviceInterface.is_gpu()` returns `True`). This is the device-agnostic mechanism proposed in pytorch#189138 (RFC: PrivateUse1 backends as first-class citizens in `torch.compile`) and implemented in pytorch#190326 (`is_gpu()` / `_GpuTypes` dynamic discovery). Any out-of-tree accelerator that registers a `DeviceInterface` with `is_gpu() = True` is automatically recognized, and `HAS_GPU` reflects it without monkeypatching. With this mechanism in place, `@requires_cuda` (which checks `torch.cuda.is_available()` only) is overly restrictive and redundant: the class-level `@skipIf(not HAS_GPU)` already provides the correct guard for all GPU-class accelerators, including out-of-tree backends. ## Test Plan Verified on Ascend 910B4 (A3) with CANN 9.1.0-beta.1, torch 2.13.0a0, torch_npu 2.13.0: Note: Verification was performed with the full local patch stack, including pytorch#190326 changes + `HAS_GPU` fix + backend-specific patches. ```bash CI=1 LANG=C.UTF-8 LC_ALL=C.UTF-8 \ TRITON_BACKEND=torch_npu TORCHINDUCTOR_COMPILE_THREADS=1 \ python -m pytest test/dynamo/test_compiler_bisector.py -v --tb=short ``` Result: **9 passed, 2 failed** (test_rng and test_emulate_precision_casts fail due to accelerator-specific hardware behavior differences, not compilation errors). This change has no impact on existing CPU/CUDA test results (CPU verified, CUDA by code inspection: only removing a redundant decorator). The 2 failures are caused by accelerator-specific hardware behavior differences and will be addressed in follow-up work. ## Notes - `test_rng`: RNG uses eager fallback (no Philox), so `do_bisect` returns `None`. The assertion `out.backend == "inductor"` fails because `out` is `None`. - `test_emulate_precision_casts`: bfloat16 lowering goes through the `lowerings` subsystem rather than the `emulate_precision_casts` pass, so the bisector locates a different subsystem. The assertion `'lowerings' != 'inductor_emulate_precision_casts'` fails. - Both failures stem from accelerator-specific hardware behavior (RNG implementation and bfloat16 lowering path) and are not related to this change. - **Depends on pytorch#190326** for `HAS_GPU` to correctly identify non-CUDA accelerators as GPU devices. Note: pytorch#190326 provides the `is_gpu()`/`_GpuTypes` mechanism but does not modify `HAS_GPU` itself: an additional change to `inductor_utils.py` (`HAS_GPU = any(... GPU_TYPES)`) is also needed (not covered by pytorch#190326). - Related: pytorch#185590 (test classification), pytorch#174469 (restrictive decorator RFC), pytorch#189138 (PrivateUse1 RFC) ## Verification Report ### Verification Results | Hardware | Cases | Passed | Failed | Skipped | Result | |----------|-------|--------|--------|---------|--------| | CPU (no GPU) | 11 | 0 | 0 | 11 | Pass (no GPU available, all skipped by `@skipIf(not HAS_GPU)`) | | A3 (Ascend 910B4) | 11 | 9 | 2 | 0 | Pass (2 known accelerator-specific failures) | | A2 (Ascend 310B) | - | - | - | - | Not verified | | A5 (Ascend 910C) | - | - | - | - | Not verified | ### Environment | Item | Version | |------|---------| | CANN | 9.1.0-beta.1 | | PyTorch | 2.13.0a0+gitcf30153 | | torch_npu | 2.13.0 | | triton-ascend | 3.5.0 | | Python | 3.13.14 | ### Failed Cases Detail | Test | Error | Root Cause | |------|-------|------------| | test_rng | AttributeError: 'NoneType' has no attribute 'backend' | Accelerator RNG uses eager fallback, do_bisect returns None (no issue to bisect) | | test_emulate_precision_casts | AssertionError: 'lowerings' != 'inductor_emulate_precision_casts' | Accelerator bfloat16 lowering goes through lowerings, not emulate_precision_casts pass |
|
@claude review this change for import-time side effects — it caused a post-merge What broke
The test counts calls to Green→red boundary is tight: This was subsequently masked by a DISABLED issue (#195878, The chainOn current
So importing inductor now probes every device backend. The PR description Two things I'd like the review to focus on1. Fork-poisoning when NVML discovery fails. 2. The registry is now frozen at inductor-import time. The comment above What I'm unsure aboutA narrow patch looks hard: caching once at import is the PR's central design
Also worth checking whether the indexed-alias enumeration ( |
|
Claude finished @anijain2305's task in 19m 2s —— View job Reviewed the import-time side effects. The XPU failure is real and caused by this change; my recommendation is option 2 (keep the eager snapshot, make the scan side-effect-free), and the indexed-alias enumeration is dead weight that can just be deleted.
Full analysis — import-time side effects, fork-poisoning, and the right fixThe chain, confirmedYour trace is correct and I verified every hop against the tree:
The XPU failure is a straightforward consequence: Worth noting: the assertion that fired is Claim 1: fork-poisoning — confirmed, and it is broader than you describedYour reasoning is right, and the actual mechanism is worse than "initializes the CUDA driver": the fork handler is registered unconditionally at the top of the C binding, before any device call, so reaching the C function at all is sufficient — the driver does not need to succeed. // torch/csrc/cuda/Module.cpp:142-150
PyObject* THCPModule_getDeviceCount_wrap(PyObject* self, PyObject* noargs) {
// Note: This is distinct from initExtension because a stub cuda
// implementation has some working functions (e.g. device_count) but cannot
// fully initialize.
torch::utils::register_fork_handler_for_device_init(at::kCUDA); // <-- unconditional
return THPUtils_packUInt64(at::cuda::device_count());
}
So the sequence is:
The reason For CUDA specifically, the fallback trigger is This is the part I'd treat as blocking regardless of the XPU test. Claim 2: registry frozen at import — confirmed as a real hole, but not the urgent oneThe
I'd note the PR's own test acknowledges this: That said — I would not re-lazify to fix this. See below. The indexed-alias question — the enumeration is dead codeYou asked the right question, and the answer is yes: I checked every consumer of the registry:
So the three loops produce entries that are either filtered out, or collapse into a set, or are looked up by nobody. Deleting them is a behavior-preserving change for everything in-tree, and it removes the only reason ( Recommendation: option 2, plus a narrowing of the snapshot claimDo not revert, and do not re-lazify. Concretely: (a) Delete the three enumeration loops in def init_device_reg() -> None:
global _device_initialized
register_interface_for_device("cuda", CudaInterface)
register_interface_for_device("xpu", XpuInterface)
register_interface_for_device("mtia", MtiaInterface)
register_interface_for_device("cpu", CpuInterface)
register_interface_for_device("mps", MpsInterface)
register_interface_for_device("tpu", TpuInterface)
_device_initialized = TrueThis makes If you want belt-and-braces for the indexed aliases: make (b) Re-enable the XPU tests and remove the DISABLED entry (#195878) as part of the fix, so the guard is live again. The test is load-bearing: it is the only mechanical check in the repo that inductor import does not probe devices, and it caught this within one commit. Adding the CUDA analogue ( (c) Narrow the snapshot contract, or accept it explicitly. With (a) landed,
I'd land (a) + (b) first as the regression fix and treat (c) as a separate change, since it has its own semantics to argue about. If (c) is out of scope, the Why not the other two options:
One thing I could not verifyI read code only — this environment has no built PyTorch, so I did not run Summary: the XPU failure is genuine and caused by this change; your fork-poisoning concern is confirmed and the mechanism is actually broader than you described (the |
|
@pytorchbot merge -m "test_no_xpu_device_query_on_inductor_import and fork poisoning" -c nosignal |
|
❌ 🤖 pytorchbot command failed: Try |
|
@pytorchbot revert -m "test_no_xpu_device_query_on_inductor_import and fork poisoning" -c nosignal |
|
@05mengmeizi Sorry, we have to revert the PR. Please look at this message - #190326 (comment) |
|
@pytorchbot successfully started a revert job. Check the current status here. |
…ce (#190326)" This reverts commit f936aaa. Reverted #190326 on behalf of https://github.com/anijain2305 due to test_no_xpu_device_query_on_inductor_import and fork poisoning ([comment](#190326 (comment)))
|
@05mengmeizi your PR has been successfully reverted. |
This PR was reopened (likely due to being reverted), so your approval was removed. Please request another review.
…o fix import-time device probes"
Thanks for the detailed analysis @anijain2305. I've applied the fix: deleted the three indexed-alias enumeration loops from init_device_reg() (for i in range(torch.xxx.device_count())). As confirmed by your analysis, no in-tree consumer reads the indexed entries — they are either filtered out by ":" not in name, collapse into a set, or are never looked up by the 42 get_interface_for_device() call sites. This makes init_device_reg() entirely free of device runtime calls, so importing inductor no longer triggers torch._C._xpu_getDeviceCount() or the fork-poisoning path. |
|
@jansel @anijain2305 I have fixed the issue that caused the error. Please check it again if you could. Thank you. |
|
@claude is this safe to reland? Has the reason for the revert been fixed? Give a confidence level. |
|
Claude finished @jansel's task in 16m 5s —— View job Yes — safe to reland. The revert cause is fixed at the root. Confidence: high (~85%), with one merge-time action.
One thing to do at merge time: the XPU guard tests are still masked by DISABLED issue #195878 ( Reland assessment #190326 — full verificationThe fix
def init_device_reg() -> None:
global _device_initialized
register_interface_for_device("cuda", CudaInterface)
register_interface_for_device("xpu", XpuInterface)
register_interface_for_device("mtia", MtiaInterface)
register_interface_for_device("cpu", CpuInterface)
register_interface_for_device("mps", MpsInterface)
register_interface_for_device("tpu", TpuInterface)
_device_initialized = TrueThat is exactly option 2 from the previous round, and it removes the only device-runtime call in the function.
I also checked that nothing else in the Fork-poisoning is closed for the wide fan-out path. The concern was Deleting the indexed aliases: behavior-preserving in-treeI re-audited every registry consumer against the current tree:
The one real BC delta: Also note the indexed-alias filters in Rest of the PR: unchanged and still soundRe-verified the in-tree equivalence by inspection: Confidence: high (~85%)What I verified by reading code: the exact chain that produced What keeps it at 85% rather than higher:
The current CI failure is |
|
@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 |
…rch#190326) ## Summary Route Inductor's device classification through the `DeviceInterface` contract so out-of-tree PrivateUse1 accelerator backends (e.g. NPU) are recognized as GPUs (for device guards, GPU-type enumeration and disambiguation) without monkeypatching module-level lists. ## Changes **`torch/_dynamo/device_interface.py`** - Add two capability bits to `DeviceInterface`: `is_gpu()` (staticmethod, default `False`) and `exposes_streams()` (classmethod, `True` iff a subclass overrides the base `Stream` sentinel slot). - Declare `is_gpu() = True` on `CudaInterface`, `MtiaInterface`, `XpuInterface` and `MpsInterface` (`Cpu`/`Tpu` inherit `False`). - Document the registration-ordering contract on `register_interface_for_device()` (see Notes). **`torch/_inductor/utils.py`** - Replace the hardcoded `GPU_TYPES = ["cuda", "mps", "xpu", "mtia"]` with a registry-derived snapshot: `_gpu_types()` enumerates the registered `DeviceInterface`s whose `is_gpu()` is `True` (skipping indexed aliases such as `cuda:0`), and `GPU_TYPES: list[str] = _gpu_types()` is computed exactly once, when this module is imported. `GPU_TYPES` stays a plain `list[str]`, so `is_gpu(device)` (`device in GPU_TYPES`) and every other consumer keep the same type, read cost and access patterns as with the old literal; only the contents now come from the registry. - Add `_device_is_available(device)`: a tolerant availability probe shared by the three consumers below. Partially-implemented out-of-tree interfaces (base-class methods raise `NotImplementedError`) and unregistered device types count as unavailable instead of propagating an exception out of registry-driven code, some of which runs at module import time. - Rewrite `get_gpu_type()`: probe availability through the helper; with more than one GPU type available, disambiguate via `torch.accelerator.current_accelerator()` and otherwise fall back to a stable pick (prefer `cuda`, else lexicographically smallest) with a warning, instead of asserting at most one GPU type can exist. - Rewrite `device_need_guard()` to `is_gpu(device) and get_interface_for_device(device).exposes_streams()`, removing the hardcoded `!= "mps"` special case. **`torch/_inductor/fx_passes/freezing_patterns.py`** - Extract `_addmm_pattern_device()` and resolve availability through `_device_is_available()` instead of `getattr(torch, gpu).is_available()`, which raises `AttributeError` for backends that register an interface but expose no `torch.<name>` module - the exact case this PR enables. **`torch/testing/_internal/inductor_utils.py`** - Compute `HAS_MULTIGPU` via a new `_is_multigpu()` that resolves through the registry, fixing the same `getattr(torch, gpu)` crash at module scope and tolerating partially-implemented interfaces. (The import reordering and reformatting in this file are enforced by ruff-format/usort on any PR that touches it.) ## Motivation `is_gpu()` tested membership in a hardcoded `GPU_TYPES = ["cuda","mps","xpu","mtia"]`, `get_gpu_type()` enumerated the same frozen list and asserted at most one GPU type could ever be available, and `device_need_guard()` special-cased the string `"mps"`. An out-of-tree backend that registers a full `DeviceInterface` (e.g. a PrivateUse1 `"npu"`) was still classified as non-GPU / no-guard and was absent from GPU-type enumeration, and could only work around it by mutating upstream module-level state at import time. Routing these predicates through the existing contract lets any registered backend opt in via its own `DeviceInterface`, provided it registers before inductor is imported (which holds by construction; see Notes). ## Test Plan - CI: `python test/inductor/test_utils.py TestDeviceClassification` - Added `TestDeviceClassification` (16 cases) to `test/inductor/test_utils.py`. Tests register throwaway fake `DeviceInterface` subclasses - no GPU or compilation required. Coverage: - `is_gpu()` safe default on the base class, and `exposes_streams()` sentinel comparison (the base `Stream` is a sentinel class, not `None`; comparing against `None` would wrongly classify MPS-style backends as stream-capable). - `is_gpu(device)` for `None` / unregistered / registered devices. - `device_need_guard` derivation for GPU+stream / GPU-no-stream / non-GPU / unknown device. - `_gpu_types` filtering of indexed (`cuda:0`) and non-GPU entries. - The snapshot contract itself: registering after `GPU_TYPES` is computed is not reflected (negative test; a fresh `_gpu_types()` scan does see the new backend, the snapshot and `get_gpu_type()` - re-evaluated after `cache_clear()` - do not). - Real-consumer regression tests: `_addmm_pattern_device()` and `_is_multigpu()` driven against a fake out-of-tree backend with no `torch.<name>` module, including a fixture that omits `is_available()` entirely (base raises `NotImplementedError`). - `get_gpu_type` single-available / none-available (falls back to `cuda` before consulting the accelerator) / multi-GPU disambiguation via `current_accelerator()` / partially-implemented interface skipped / stable sorted fallback when the accelerator names none of the candidates (fed in reverse order to prove the pick is sorted, not positional; warning pinned with `assertLogs`). ## Notes - **`GPU_TYPES` is scanned exactly once, at `torch._inductor.utils` import.** An earlier iteration made it a live view that re-derived the list on every read, which then required caching, invalidation hooks and concurrency handling. Scanning once is sound because registration always precedes that import: in-tree backends are registered by `init_device_reg()` inside the scan itself, and out-of-tree backends register at package import - either autoloaded at the end of `import torch` (`TORCH_DEVICE_BACKEND_AUTOLOAD`, on by default) or via an explicit `import torch_npu`-style import - both of which precede any import of inductor, in the main process and in spawned workers alike. Registering later is unsupported, documented on `register_interface_for_device()`, and pinned by a negative test. - Preserves in-tree behavior: the derived list contains exactly `cuda/xpu/mtia/mps` (`cpu`/`tpu` stay non-GPU), and `MpsInterface` is a GPU but exposes no `Stream`, so `device_need_guard("mps")` stays `False` - reproducing the removed `!= "mps"` case via the real reason (no stream) rather than a device name. - **Behavior change (relaxation):** with more than one GPU type available, `get_gpu_type()` no longer raises `AssertionError`; it disambiguates via the current accelerator and otherwise makes a stable pick and logs a warning. Single-GPU and no-GPU results are unchanged. - Importing `torch._inductor.utils` now triggers `init_device_reg()` (lightweight `device_count()` probes) at import; previously this happened on the first registry access. - Related RFC: `DeviceInterface` registry support for PrivateUse1 backends in `torch.compile`. Pull Request resolved: pytorch#190326 Approved by: https://github.com/jansel
Summary
Route Inductor's device classification through the
DeviceInterfacecontract soout-of-tree PrivateUse1 accelerator backends (e.g. NPU) are recognized as GPUs
(for device guards, GPU-type enumeration and disambiguation) without
monkeypatching module-level lists.
Changes
torch/_dynamo/device_interface.pyDeviceInterface:is_gpu()(staticmethod, defaultFalse) andexposes_streams()(classmethod,Trueiff a subclass overridesthe base
Streamsentinel slot).is_gpu() = TrueonCudaInterface,MtiaInterface,XpuInterfaceand
MpsInterface(Cpu/TpuinheritFalse).register_interface_for_device()(see Notes).torch/_inductor/utils.pyGPU_TYPES = ["cuda", "mps", "xpu", "mtia"]with aregistry-derived snapshot:
_gpu_types()enumerates the registeredDeviceInterfaces whoseis_gpu()isTrue(skipping indexed aliases suchas
cuda:0), andGPU_TYPES: list[str] = _gpu_types()is computed exactlyonce, when this module is imported.
GPU_TYPESstays a plainlist[str],so
is_gpu(device)(device in GPU_TYPES) and every other consumer keep thesame type, read cost and access patterns as with the old literal; only the
contents now come from the registry.
_device_is_available(device): a tolerant availability probe shared bythe three consumers below. Partially-implemented out-of-tree interfaces
(base-class methods raise
NotImplementedError) and unregistered devicetypes count as unavailable instead of propagating an exception out of
registry-driven code, some of which runs at module import time.
get_gpu_type(): probe availability through the helper; with morethan one GPU type available, disambiguate via
torch.accelerator.current_accelerator()and otherwise fall back to astable pick (prefer
cuda, else lexicographically smallest) with a warning,instead of asserting at most one GPU type can exist.
device_need_guard()tois_gpu(device) and get_interface_for_device(device).exposes_streams(),removing the hardcoded
!= "mps"special case.torch/_inductor/fx_passes/freezing_patterns.py_addmm_pattern_device()and resolve availability through_device_is_available()instead ofgetattr(torch, gpu).is_available(),which raises
AttributeErrorfor backends that register an interface butexpose no
torch.<name>module - the exact case this PR enables.torch/testing/_internal/inductor_utils.pyHAS_MULTIGPUvia a new_is_multigpu()that resolves through theregistry, fixing the same
getattr(torch, gpu)crash at module scope andtolerating partially-implemented interfaces. (The import reordering and
reformatting in this file are enforced by ruff-format/usort on any PR that
touches it.)
Motivation
is_gpu()tested membership in a hardcodedGPU_TYPES = ["cuda","mps","xpu","mtia"],get_gpu_type()enumerated the samefrozen list and asserted at most one GPU type could ever be available, and
device_need_guard()special-cased the string"mps". An out-of-tree backendthat registers a full
DeviceInterface(e.g. a PrivateUse1"npu") was stillclassified as non-GPU / no-guard and was absent from GPU-type enumeration, and
could only work around it by mutating upstream module-level state at import
time. Routing these predicates through the existing contract lets any
registered backend opt in via its own
DeviceInterface, provided it registersbefore inductor is imported (which holds by construction; see Notes).
Test Plan
python test/inductor/test_utils.py TestDeviceClassificationTestDeviceClassification(16 cases) totest/inductor/test_utils.py.Tests register throwaway fake
DeviceInterfacesubclasses - no GPU orcompilation required. Coverage:
is_gpu()safe default on the base class, andexposes_streams()sentinelcomparison (the base
Streamis a sentinel class, notNone; comparingagainst
Nonewould wrongly classify MPS-style backends asstream-capable).
is_gpu(device)forNone/ unregistered / registered devices.device_need_guardderivation for GPU+stream / GPU-no-stream / non-GPU /unknown device.
_gpu_typesfiltering of indexed (cuda:0) and non-GPU entries.GPU_TYPESis computed isnot reflected (negative test; a fresh
_gpu_types()scan does see the newbackend, the snapshot and
get_gpu_type()- re-evaluated aftercache_clear()- do not)._addmm_pattern_device()and_is_multigpu()driven against a fake out-of-tree backend with notorch.<name>module, including a fixture that omitsis_available()entirely (base raises
NotImplementedError).get_gpu_typesingle-available / none-available (falls back tocudabefore consulting the accelerator) / multi-GPU disambiguation via
current_accelerator()/ partially-implemented interface skipped / stablesorted fallback when the accelerator names none of the candidates (fed in
reverse order to prove the pick is sorted, not positional; warning pinned
with
assertLogs).Notes
GPU_TYPESis scanned exactly once, attorch._inductor.utilsimport.An earlier iteration made it a live view that re-derived the list on every
read, which then required caching, invalidation hooks and concurrency
handling. Scanning once is sound because registration always precedes that
import: in-tree backends are registered by
init_device_reg()inside thescan itself, and out-of-tree backends register at package import - either
autoloaded at the end of
import torch(TORCH_DEVICE_BACKEND_AUTOLOAD,on by default) or via an explicit
import torch_npu-style import - both ofwhich precede any import of inductor, in the main process and in spawned
workers alike. Registering later is unsupported, documented on
register_interface_for_device(), and pinned by a negative test.cuda/xpu/mtia/mps(cpu/tpustay non-GPU), andMpsInterfaceis a GPUbut exposes no
Stream, sodevice_need_guard("mps")staysFalse-reproducing the removed
!= "mps"case via the real reason (no stream)rather than a device name.
get_gpu_type()no longer raisesAssertionError; it disambiguates via thecurrent accelerator and otherwise makes a stable pick and logs a warning.
Single-GPU and no-GPU results are unchanged.
torch._inductor.utilsnow triggersinit_device_reg()(lightweight
device_count()probes) at import; previously this happened onthe first registry access.
DeviceInterfaceregistry support for PrivateUse1 backends intorch.compile.cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @azahed98