Skip to content

[fix]: derive is_gpu()/device_need_guard() from DeviceInterface - #190326

Closed
05mengmeizi wants to merge 4 commits into
pytorch:mainfrom
05mengmeizi:main_guard
Closed

05mengmeizi wants to merge 4 commits into
pytorch:mainfrom
05mengmeizi:main_guard

Conversation

@05mengmeizi

@05mengmeizi 05mengmeizi commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

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
    DeviceInterfaces 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.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @azahed98

@pytorch-bot

pytorch-bot Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

🔗 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 (image):

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.

@linux-foundation-easycla

linux-foundation-easycla Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: 05mengmeizi / name: s50057208 (f0fa257)

@pytorch-bot

pytorch-bot Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Jul 17, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@janeyx99 janeyx99 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 17, 2026
@05mengmeizi
05mengmeizi marked this pull request as draft July 20, 2026 07:23
@05mengmeizi
05mengmeizi force-pushed the main_guard branch 3 times, most recently from 07874fe to 084759f Compare July 22, 2026 07:42
@05mengmeizi
05mengmeizi marked this pull request as ready for review July 23, 2026 01:25
@jansel

jansel commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 4m 11s —— View job


Reviewed the changes. One meaningful perf/design concern in the hot is_gpu() path and one latent bug for the out-of-tree backends this PR targets; details below.

PR Review: #190326 — full details

Summary

Routes Inductor's GPU classification through DeviceInterface so out-of-tree PrivateUse1 backends can opt into GPU treatment. The DeviceInterface additions and device_need_guard() rewrite are clean, but is_gpu() doesn't actually use the direct interface lookup the description claims, and the now-dynamic GPU_TYPES breaks an existing consumer for out-of-tree device names.

Code Quality / Performance

  • torch/_inductor/utils.py:3487-3488 — is_gpu() still does a full-registry scan, contradicting the PR description. The body is unchanged: return device in GPU_TYPES. With GPU_TYPES now a _GpuTypes instance, every membership test calls _gpu_types(), which iterates the entire registry and invokes .is_gpu() on each entry — rebuilt on every call, with no caching. is_gpu() is called throughout the scheduler fusion hot paths (scheduler.py:197, 1463, 1883, 2257, 5164, 8856, 8870, 9528, 10040), so this is a compile-time regression versus the old O(1) list membership. The PR description says "is_gpu() now queries get_interface_for_device(device).is_gpu()" — that is both faster (O(1) dict lookup) and matches the stated design, but the code does not do it. Recommend:
    def is_gpu(device: str | None) -> bool:
        if device is None:
            return False
        from torch._dynamo.device_interface import get_interface_for_device
        try:
            return get_interface_for_device(device).is_gpu()
        except NotImplementedError:
            return False
    Fix this →

Backward Compatibility / Correctness

  • torch/_inductor/fx_passes/freezing_patterns.py:130-132 — dynamic GPU_TYPES can now break getattr(torch, gpu). This consumer does getattr(torch, gpu).is_available() while iterating GPU_TYPES. Previously GPU_TYPES was the fixed ["cuda","mps","xpu","mtia"], so getattr(torch, gpu) always resolved. Now _gpu_types() returns any registered device name whose interface reports is_gpu(), including an out-of-tree "npu" — the exact case this PR enables. getattr(torch, "npu") will raise AttributeError if that submodule isn't present, turning the feature this PR adds into a crash in an unrelated pass. This should route availability through the interface too, e.g. get_interface_for_device(gpu).is_available(). Please audit any other GPU_TYPES consumers for the same getattr(torch, ...) assumption.
    Fix this →

  • torch/_inductor/utils.py:get_gpu_type() — silent behavior change from assertion to disambiguation. The old code raised AssertionError when more than one GPU type was available; the new code silently picks via current_accelerator() (falling back to avail_gpus[0]). This is defensible and matches the PR's intent, but it's a real behavior change for in-tree multi-backend builds (e.g. cuda + xpu both available) that previously failed loudly. Confirm this is intended and worth a note in the description, since it's not just an out-of-tree concern.

Testing

  • CI shows lint failures on test/inductor/test_utils.py (lintrunner-noclang-partial, lintrunner-pyrefly-partial). Run lintrunner -a on the file and push the fix.
  • No test covers the freezing_patterns.py / getattr(torch, gpu) interaction above — the new TestDeviceClassification mocks _gpu_types but doesn't exercise a real consumer with an out-of-tree name. Worth a test that registers a fake "npu"-style interface and confirms nothing that iterates GPU_TYPES crashes.

Recommendation

Request Changes — the is_gpu() hot-path scan (does not match the described design) and the freezing_patterns.py getattr crash for out-of-tree names should be addressed before merge. The DeviceInterface/device_need_guard() core is solid.

@05mengmeizi

Copy link
Copy Markdown
Contributor Author

Claude finished @jansel's task in 4m 11s —— View job

Reviewed the changes. One meaningful perf/design concern in the hot is_gpu() path and one latent bug for the out-of-tree backends this PR targets; details below.

PR Review: #190326 — full details

Thanks for the thorough review

freezing_patterns.py getattr(torch, gpu) — great catch, and it's a real crash for exactly the out-of-tree case this PR targets. Fixed by routing availability through the registry: get_interface_for_device(gpu).is_available(). I audited the other GPU_TYPES consumers (common_device_type.py, inductor_utils.py) — they only iterate / do membership tests, so no other getattr(torch, ...) assumption exists. Added a regression test (test_gpu_types_consumer_resolves_out_of_tree_via_registry) that registers a fake out-of-tree interface and drives the freezing_patterns-style consumer.

is_gpu() staying device in GPU_TYPES — this is intentional; I've updated the PR description (the earlier wording was stale). get_registered_device_interfaces() is just device_interfaces.items() over the fixed set of registered backends (a handful), so membership is effectively constant-time rather than a scan over any data-sized structure. Keeping it as device in GPU_TYPES also preserves exact prior semantics — e.g. is_gpu("cuda:0") stays False, whereas a direct get_interface_for_device(...).is_gpu() would flip it to True. Happy to memoize _gpu_types() if you'd prefer to make the constant-time guarantee explicit.

get_gpu_type() assertion → disambiguation — intended; the old AssertionError on >1 available GPU type is replaced by current_accelerator()-based disambiguation, with single-GPU builds unchanged.

Lint — the noclang (PYFMT) failure is fixed and pushed.

@jansel

jansel commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes again

@claude

claude Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 9m 35s —— View job


Re-reviewed. The freezing_patterns.py fix is correct, but the same getattr(torch, gpu) crash still exists in torch/testing/_internal/inductor_utils.py:96-99 (so the audit claim in the last reply doesn't hold), and the new regression test re-implements the consumer inline rather than calling it, so it would still pass if the fix were reverted.

PR Review: #190326 — full details

PR Review: #190326

Summary

Routes Inductor's GPU classification through DeviceInterface so out-of-tree PrivateUse1 backends can opt into GPU treatment. The freezing_patterns.py fix from the last round is correct, but a second getattr(torch, gpu)-over-GPU_TYPES site was missed, the new regression test does not exercise the code it protects, and @functools.cache on get_gpu_type() now caches a value derived from a registry the PR explicitly wants backends to mutate late.

Backward Compatibility / Correctness

  • torch/testing/_internal/inductor_utils.py:96-99 — the same getattr(torch, gpu) bug the PR just fixed still exists here, at module import time.

    HAS_MULTIGPU = any(
        getattr(torch, gpu).is_available() and getattr(torch, gpu).device_count() >= 2
        for gpu in GPU_TYPES
    )

    This is module scope, not inside a function. Once an out-of-tree backend registers a GPU-class DeviceInterface under a name with no matching torch.<name> submodule — the exact scenario this PR enables — importing torch.testing._internal.inductor_utils raises AttributeError, taking down the entire Inductor test-support module. The reply to the previous review stated that common_device_type.py and inductor_utils.py "only iterate / do membership tests, so no other getattr(torch, ...) assumption exists"; that is not the case for these lines. Route both calls through get_interface_for_device(gpu) (.is_available() / .device_count()), matching the fix already applied in freezing_patterns.py.
    Fix this →

  • torch/_inductor/utils.py:151 — @functools.cache on get_gpu_type() conflicts with the PR's own premise of late registration. torch/testing/_internal/inductor_utils.py:94 calls GPU_TYPE = get_gpu_type() at module scope. If a backend registers its DeviceInterface after that import, the cached value is permanently wrong for the process — the same "frozen at import time" failure mode the PR set out to remove, just relocated from the list literal to the cache. The new tests need get_gpu_type.cache_clear() in setUp/tearDown and again inside three individual tests (test/inductor/test_utils.py:1183, 1188, 1270, 1279, 1294), which is direct evidence the cache and the dynamic registry are in tension. Either invalidate the cache in register_interface_for_device(), or key it on a registry generation counter.

  • torch/_inductor/utils.py:174 — return avail_gpus[0] is order-dependent and the order is not stable across processes. _gpu_types() derives its order from device_interfaces.items() (insertion order of torch/_dynamo/device_interface.py:647). In-tree names are inserted deterministically by init_device_reg(), but an out-of-tree backend inserts whenever its module happens to be imported. A parent process and a forked compile worker can therefore see [cuda, npu] vs [npu, cuda] and silently disagree on get_gpu_type(). This last-resort branch should not be a positional pick — prefer a stable rule (e.g. "cuda" if "cuda" in avail_gpus else sorted(avail_gpus)[0]) and emit a warning, since reaching it means current_accelerator() disagreed with every available GPU type.

Performance

  • torch/_inductor/utils.py:118-148 — every is_gpu() call now allocates a list and runs a filtered scan of the registry. is_gpu() remains device in GPU_TYPES, and _GpuTypes.__contains__ calls _gpu_types(), which rebuilds the list on every invocation. There are 43 is_gpu() call sites across 10 Inductor files, several in pairwise fusion loops (scheduler.py:197 via BaseSchedulerNode.is_gpu() at scheduler.py:1461, plus scheduler.py:1883, 2257, 5164), so this runs O(nodes²) times per compile where it was previously O(1) list membership. The registry is small, but the per-call list allocation is not free at that call frequency. The offer to memoize _gpu_types() in the last reply is the right fix and should be taken — cache it and invalidate in register_interface_for_device() so it stays live and constant-time. That also resolves the get_gpu_type cache issue above with the same mechanism.
    Fix this →

  • _gpu_types() forces device-registry initialization on any membership test. get_registered_device_interfaces() calls init_device_reg() (torch/_dynamo/device_interface.py:669-693), which invokes torch.cuda.device_count(), torch.xpu.device_count() and torch.mtia.device_count(). The old list literal had no side effects at all, so "cuda" in GPU_TYPES was previously free of any runtime probing. This now happens from HAS_MULTIGPU at import of inductor_utils (see above) and from any early is_gpu() call. Worth confirming this does not perturb pre-fork state in torch/_inductor/async_compile.py's pre_fork_setup(), which does not currently clear these caches.

Testing

  • test/inductor/test_utils.py:1246-1264 — test_gpu_types_consumer_resolves_out_of_tree_via_registry does not test the fix. The test body re-implements addmm_patterns_init()'s generator expression inline (for gpu in inductor_utils.GPU_TYPES if di.get_interface_for_device(gpu).is_available()) instead of calling addmm_patterns_init(). Reverting torch/_inductor/fx_passes/freezing_patterns.py:132-135 back to getattr(torch, gpu).is_available() leaves this test green, so it provides no regression protection. It should call the real function (or at minimum assert against the production symbol), and the comment "Mirrors freezing_patterns.addmm_patterns_init()'s device pick" is itself an admission that the test is a copy that can drift.
    Fix this →

  • No test covers the inductor_utils.HAS_MULTIGPU import-time path. Once fixed, add coverage that a registered out-of-tree GPU name does not break the availability/device-count lookup, otherwise this class of bug recurs the next time a GPU_TYPES consumer is added.

API Design

  • torch/_dynamo/device_interface.py:169-173 — exposes_streams() infers a capability instead of declaring one, unlike is_gpu(). The PR adds is_gpu() as an explicit opt-in bit but derives stream capability from cls.Stream is not DeviceInterface.Stream. A backend that implements current_stream/get_raw_stream/set_stream but does not shadow the nested Stream class is silently classified as guard-less, which suppresses codegen_device_guard_enter for it — a silent-wrong-codegen failure mode rather than a loud one. Given the PR's stated goal of making the contract explicit for out-of-tree backends, this should either be an explicit overridable bit alongside is_gpu(), or the docstring must state that shadowing Stream is a required part of the contract for guard generation.

  • _GpuTypes implements only __iter__ / __contains__ / __repr__. bool(GPU_TYPES) is now unconditionally True where the old list was falsy when empty, and len() / indexing / == against a list all fail or silently misbehave. Nothing in-tree relies on these today, but since GPU_TYPES is imported by torch/testing/_internal/* it is de facto reachable by out-of-tree test suites. Adding __len__ and __eq__ is cheap and removes the sharp edge; at minimum note the removed behaviors in the class docstring.

Code Quality

  • The new comment volume in torch/_inductor/utils.py:107-141 (module-level comment plus two multi-line docstrings for a 6-line helper and a 3-method view class) runs against CLAUDE.md's "minimize comments; be concise". The why worth keeping is the circular-import ordering constraint and the ":" not in name filter; the rest restates the code.

Recommendation

Request Changes — three blocking items: the unfixed getattr(torch, gpu) at torch/testing/_internal/inductor_utils.py:96-99 (crashes at import for exactly the backends this PR enables), the regression test that does not exercise the fixed code path, and the @functools.cache/_gpu_types() interaction (both a correctness hazard for late registration and the hot-path allocation). The DeviceInterface additions and the device_need_guard() rewrite are otherwise sound.

| Branch: `main_guard`

gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Jul 28, 2026
…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
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Jul 28, 2026
…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
gavinwang269 added a commit to gavinwang269/pytorch that referenced this pull request Jul 29, 2026
…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 |
@anijain2305

Copy link
Copy Markdown
Contributor

@claude review this change for import-time side effects — it caused a post-merge
regression on trunk and I'd like a second opinion on the right fix.

What broke

test_xpu.py::TestXpu::test_no_xpu_device_query_on_inductor_import (and the
test_xpu_expandable_segments.py variant) went red on the xpu workflow
starting 2026-09-03:

AssertionError: String comparison failed: '1' != '0'   # test/test_xpu.py:558

The test counts calls to torch._C._xpu_getDeviceCount while doing
import torch._inductor.lowering, and now sees 1 instead of 0.

Green→red boundary is tight: 4fbf3a4d17e (08:51:49Z) green, first red on the
run after f936aaaee23 (this PR, 08:53:25Z) landed. The next commit,
df2e8e5b317, is an MPS-metal-only change and is not implicated.

This was subsequently masked by a DISABLED issue (#195878, Platforms: xpu),
so the smoke_xpu job is green again — but the underlying behavior change is
still on main, and nothing has been fixed.

The chain

On current main:

  • torch/_inductor/utils.py:206 — GPU_TYPES: list[str] = _gpu_types() now runs
    at module scope
  • _gpu_types() (torch/_inductor/utils.py:115) calls
    get_registered_device_interfaces()
  • that triggers init_device_reg() (torch/_dynamo/device_interface.py:796),
    which calls torch.cuda.device_count(), torch.xpu.device_count(), and
    MtiaInterface.device_count()

So importing inductor now probes every device backend. The PR description
acknowledges this ("Importing torch._inductor.utils now triggers
init_device_reg() (lightweight device_count() probes) at import; previously
this happened on the first registry access") — the question is whether the two
consequences below were intended.

Two things I'd like the review to focus on

1. Fork-poisoning when NVML discovery fails. torch.cuda.device_count()
documents "will NOT poison fork if NVML discovery succeeds", but when
_device_count_nvml() returns < 0 it falls back to
torch._C._cuda_getDeviceCount() (torch/cuda/__init__.py:1285-1293), which
initializes the CUDA driver. On hosts/containers without working NVML, merely
importing inductor would then poison fork, where previously a process might
never reach the first registry access. To be clear: this is reasoned from
reading the code, not something I observed in CI
— please confirm or refute
it rather than assuming it.

2. The registry is now frozen at inductor-import time. The comment above
GPU_TYPES states "Registering after this module is imported is not supported."
That means an out-of-tree backend (NPU, privateuse1) registering its
DeviceInterface after inductor has been imported silently won't appear in
GPU_TYPES, and is_gpu() will return False for it. Given the ongoing
accelerator-generalization / OOT-backend work in this repo, is the
autoload-ordering assumption ("autoloaded backends register during import torch, explicit ones at their package import") safe in practice — e.g. for
import torch_npu issued after something has already pulled in inductor?

What I'm unsure about

A narrow patch looks hard: caching once at import is the PR's central design
decision, and GPU_TYPES is consumed as a plain list[str] in many places, so
lazifying it via a module __getattr__ isn't obviously safe. I'd like the
review to say which of these is right:

  • restore laziness behind an accessor and update the call sites,
  • keep the eager snapshot but make the scan itself side-effect-free (i.e. avoid
    device_count() during registration, registering the bare interfaces without
    enumerating indexed aliases),
  • or revert and redo.

Also worth checking whether the indexed-alias enumeration (cuda:0, xpu:0, …)
in init_device_reg() needs to happen at registration time at all, since that
is the only reason device_count() is called there.

@claude

claude Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

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.

  • Read the landed change on main and confirm the import chain
  • Verify claim 1: fork-poisoning when NVML discovery fails
  • Verify claim 2: registry frozen at inductor-import time / OOT ordering
  • Check whether indexed-alias enumeration needs device_count() at registration
  • Recommend a fix direction
Full analysis — import-time side effects, fork-poisoning, and the right fix

The chain, confirmed

Your trace is correct and I verified every hop against the tree:

  • torch/_inductor/utils.py:206 — GPU_TYPES: list[str] = _gpu_types() at module scope
  • _gpu_types() (:116-127) → get_registered_device_interfaces() (device_interface.py:790-793)
  • which calls init_device_reg() (:796-816), whose only expensive work is the three enumeration loops: torch.cuda.device_count() (:799), torch.xpu.device_count() (:803), MtiaInterface.device_count() (:809)
  • and torch/testing/_internal/common_device_type.py:20 does a top-level from torch._inductor.utils import GPU_TYPES, so the probe reaches ~every device-generic test file, not just Inductor.

The XPU failure is a straightforward consequence: test_no_xpu_device_query_on_inductor_import counts torch._C._xpu_getDeviceCount calls during import torch._inductor.lowering and asserts 0. torch.xpu.device_count() (torch/xpu/__init__.py:262-284) only avoids that C call when _device_count_zes() returns >= 0, which requires the pyzes module to import and Level Zero Sysman to enumerate successfully (:128-153). On the CI runner it evidently does not, so line 278 falls through to torch._C._xpu_getDeviceCount() and the count becomes 1. The test is measuring exactly the property this PR removed, and it is not a flake.

Worth noting: the assertion that fired is rc[-2] == "0", i.e. the device-query assertion, not rc[-1] == "False" (torch.xpu.is_initialized()). So on that host the probe did not fully initialize XPU — but see below, that is not the part that matters for fork.

Claim 1: fork-poisoning — confirmed, and it is broader than you described

Your 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());
}

torch/csrc/xpu/Module.cpp:95-104 is byte-for-byte the same shape for at::kXPU. And register_fork_handler_for_device_init (torch/csrc/utils/device_lazy_init.cpp:76-95) installs a pthread_atfork child handler that, for every device type that has ever been registered, calls set_device_in_bad_fork(dt, true) and set_requires_device_init(dt, true) (CUDA/XPU/HPU/MTIA/PrivateUse1 are all lazy-init-supported, device_lazy_init.h:32-40).

So the sequence is:

  1. import torch._inductor.utils (or anything importing common_device_type) → torch.xpu.device_count()
  2. zes/NVML discovery fails → falls through to torch._C._xpu_getDeviceCount()
  3. register_fork_handler_for_device_init(at::kXPU) runs → at_fork_registered[XPU] = true
  4. any subsequent fork() → the child is marked in-bad-fork for XPU
  5. the child calling torch.xpu._lazy_init() gets RuntimeError: Cannot re-initialize XPU in forked subprocess (torch/xpu/__init__.py:353-357; CUDA analogue at torch/cuda/__init__.py:590-592)

The reason rc[-1] stayed "False" in the XPU test is that is_initialized() tracks _initialized, which device_count() never sets — but at_fork_registered is set. The fork-poisoning flag and the initialization flag are independent, and only the latter is what the test's second assertion observes. That is why this looked survivable and isn't.

For CUDA specifically, the fallback trigger is _device_count_nvml() < 0 (torch/cuda/__init__.py:1288-1293), which happens when _raw_device_uuid_nvml() returns None, _raw_device_count_nvml() fails, or an OSError escapes (:1223-1245) — i.e. containers without libnvidia-ml.so, MIG-only CUDA_VISIBLE_DEVICES, or ROCm hosts where _device_count_amdsmi() fails. test_cuda_nvml_based_avail.py:64-82 already asserts precisely this: with _device_count_nvml patched to -1, a forked child is in bad fork. So the failure mode is already an established, tested property of the codebase — this PR just moved its trigger to import.

This is the part I'd treat as blocking regardless of the XPU test. torch.testing._internal.common_device_type is imported by fork-using suites (test_multiprocessing.py, test_dataloader.py both import it), and torch/_inductor/async_compile.py's pre_fork_setup() does not clear or pre-empt any of this.

Claim 2: registry frozen at import — confirmed as a real hole, but not the urgent one

The register_interface_for_device() docstring (device_interface.py:760-771) asserts registration always precedes inductor import. That holds for the two paths it names (autoload at the end of import torch; explicit import torch_npu at the top of a user script), but it is not an invariant the code can enforce, and there are in-tree counterexamples of late registration:

  • test/inductor/test_triton_extension_backend.py:121 calls register_interface_for_device("privateuseone", DeviceInterface) inside a test body — long after inductor is imported. It happens to work because that path uses get_interface_for_device() (still live) rather than GPU_TYPES, but it shows late registration is a shape that exists.
  • Any library that does import torch_npu lazily, or after something (a framework, a torch.compile call, an unrelated torch.testing import) has already pulled in inductor, silently gets is_gpu("npu") == False and no diagnostic. Failure mode is "GPU codegen quietly off", which is the worst kind.

I'd note the PR's own test acknowledges this: test_gpu_types_is_an_import_time_snapshot (test/inductor/test_utils.py:1394-1406) pins the frozen behavior as intended. That's honest, but it makes the contract a documentation-only guarantee for exactly the OOT-backend population the PR is written to serve.

That said — I would not re-lazify to fix this. See below.

The indexed-alias question — the enumeration is dead code

You asked the right question, and the answer is yes: device_count() is called only to enumerate cuda:{i} / xpu:{i} / mtia:{i} aliases, and nothing reads them.

I checked every consumer of the registry:

Consumer Indexed entries
_gpu_types() (utils.py:126) explicitly filtered: ":" not in name
codecache.py:365-366 explicitly filtered: if ":" in name: continue
_triton.py:249 explicitly filtered: if ":" in name
async_compile.py:115 iterates all — indexed entries are duplicate CudaInterface objects, so this just does redundant Worker.get_device_properties() calls
variables/builder.py:4221,4234,4247, variables/torch.py:1743, variables/user_defined.py:418 build sets of .Stream/.Event/current_stream classes — indexed entries contribute the same class objects, i.e. no-ops into a set
get_interface_for_device() call sites all 42 in-tree call sites pass an unindexed type (device.type, V.graph.device_type, gpu_type, "cuda"). I grepped for any "cuda:0"-style or f-string-interpolated lookup and found none, in torch/ or test/.

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 init_device_reg() touches a device runtime at all.

(MtiaInterface.device_count() at :809 is already guarded by the wrapper added in this PR at :450-454, so MTIA is the one arm that is currently safe — but it is safe by a special case, and deleting the loop makes the guard unnecessary.)

Recommendation: option 2, plus a narrowing of the snapshot claim

Do not revert, and do not re-lazify. Concretely:

(a) Delete the three enumeration loops in init_device_reg() (device_interface.py:798-814), leaving:

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 = True

This makes init_device_reg() — and therefore the GPU_TYPES scan, and therefore importing inductor — completely free of device runtime calls, which restores the pre-PR property the XPU test encodes. It fixes the fork-poisoning exposure at its root rather than at one call site, and it fixes CUDA and XPU and MTIA together rather than one at a time. It also keeps the PR's central design decision (eager snapshot, plain list[str], is_gpu() back to list.__contains__) fully intact, which is what makes it a narrow patch rather than a redesign.

If you want belt-and-braces for the indexed aliases: make get_interface_for_device() strip the index (device.split(":")[0]) before lookup. That is strictly more capable than the enumeration was — it works for any ordinal, including ones beyond device_count() — and costs one line. But I'd land the deletion first and treat that as optional, since no in-tree caller needs it.

(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 (torch._C._cuda_getDeviceCount call count during import torch._inductor.lowering) would be cheap and would close the symmetric hole.

(c) Narrow the snapshot contract, or accept it explicitly. With (a) landed, _gpu_types() becomes cheap enough that re-deriving it is not a performance question anymore — the round-2/3 objections to laziness were about the cost of the scan and the cache-invalidation machinery, both of which evaporate once the scan is a dict comprehension over six entries. So there is a coherent middle path if you want claim 2 fixed too:

  • keep GPU_TYPES as the eager snapshot for the ~4 consumers that want a list[str] (common_device_type.py:1698, freezing_patterns.py:128, inductor_utils.py:101, get_gpu_type()), and
  • change is_gpu() (utils.py:3832) — the one hot, semantically-important predicate — to a direct registry query instead of device in GPU_TYPES. That is O(1) and live, so a late-registering NPU is classified correctly even though GPU_TYPES is stale. Note this needs the ":" not in device filter preserved to keep is_gpu("cuda:0") == False, which is what test_in_tree_gpu_types_unchanged pins.

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 register_interface_for_device() docstring should at least be strengthened from "is not supported" to naming the concrete failure (is_gpu() silently returns False; no error is raised), and ideally the OOT-backend RFC should carry the constraint.

Why not the other two options:

  • Restore laziness behind an accessor: this reintroduces exactly what rounds 2-3 of this PR's review spent three iterations deleting — the _GpuTypes proxy, the functools.cache, the sys.modules-based invalidation hook from dynamo into inductor, and the dict.items() thread-safety window. The eager snapshot was the right call; the bug is not the snapshot, it's what the scan touches.
  • Revert and redo: the PR's core (the is_gpu()/exposes_streams() capability bits, device_need_guard() derived from stream exposure rather than != "mps", _device_is_available() unification) is sound and unrelated to the regression. A three-line deletion in init_device_reg() fixes the observed failure; a revert throws away six rounds of review for a bug that is not in the design.

One thing I could not verify

I read code only — this environment has no built PyTorch, so I did not run test/test_xpu.py, and I could not empirically confirm the CUDA fork-poisoning path (it needs a host where NVML discovery fails). The mechanism is verified by reading Module.cpp + device_lazy_init.cpp, and test_cuda_nvml_based_avail.py::test_cuda_is_available already asserts the nvml_avail=False → in_bad_fork=True half of it, so I'm confident in the reasoning — but the observation is still inferential, matching your own caveat.

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 pthread_atfork handler is registered unconditionally on entry to the C getDeviceCount binding, so reaching it is sufficient — the driver need not initialize). The indexed-alias enumeration in init_device_reg() is the sole reason device_count() is called there, and nothing in-tree reads those aliases, so deleting the three loops makes the eager snapshot side-effect-free without touching the PR's design. Recommend option 2 + re-enabling the disabled XPU tests, and treating the frozen-registry issue as a separate, narrower change to is_gpu().
| Branch: main_guard

@anijain2305

Copy link
Copy Markdown
Contributor

@pytorchbot merge -m "test_no_xpu_device_query_on_inductor_import and fork poisoning" -c nosignal

@pytorch-bot

pytorch-bot Bot commented Sep 4, 2026

Copy link
Copy Markdown

❌ 🤖 pytorchbot command failed:

@pytorchbot: error: unrecognized arguments: -m test_no_xpu_device_query_on_inductor_import and fork poisoning -c nosignal

usage: @pytorchbot [-h]
                   
                   {merge,revert,rebase,label,drci,lint,fix-lint,apply-lint,cherry-pick}
                   ...

Try @pytorchbot --help for more info.

@anijain2305

Copy link
Copy Markdown
Contributor

@pytorchbot revert -m "test_no_xpu_device_query_on_inductor_import and fork poisoning" -c nosignal

@anijain2305

Copy link
Copy Markdown
Contributor

@05mengmeizi Sorry, we have to revert the PR. Please look at this message - #190326 (comment)

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a revert job. Check the current status here.
Questions? Feedback? Please reach out to the PyTorch DevX Team

pytorchmergebot added a commit that referenced this pull request Sep 4, 2026
…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)))
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@05mengmeizi your PR has been successfully reverted.

@pytorch-bot
pytorch-bot Bot dismissed jansel’s stale review September 4, 2026 06:52

This PR was reopened (likely due to being reverted), so your approval was removed. Please request another review.

@05mengmeizi

Copy link
Copy Markdown
Contributor Author

@claude review this change for import-time side effects — it caused a post-merge请审查这一变更可能带来的进口时副作用——它导致了合并后的问题。 regression on trunk and I'd like a second opinion on the right fix.我打算采取回归疗法,希望能找到正确的解决方案。

What broke  是什么导致了问题的发生?

test_xpu.py::TestXpu::test_no_xpu_device_query_on_inductor_import (and the   test_xpu.py::TestXpu::test_no_xpu_device_query_on_inductor_import (以及)其他…… test_xpu_expandable_segments.py variant) went red on the xpu workflow在 xpu 工作流程中, test_xpu_expandable_segments.py 变体变成了红色 starting 2026-09-03:  从 2026 年 9 月 3 日开始:

AssertionError: String comparison failed: '1' != '0'   # test/test_xpu.py:558

The test counts calls to torch._C._xpu_getDeviceCount while doing在执行过程中,该测试共处理了 0 个调用,目标地址为 torch._C._xpu_getDeviceCount 。 import torch._inductor.lowering, and now sees 1 instead of 0. import torch._inductor.lowering ,现在显示的不是 0 而是 1。

Green→red boundary is tight: 4fbf3a4d17e (08:51:49Z) green, first red on the绿色与红色的边界非常清晰: 4fbf3a4d17e (08:51:49Z) 先出现绿色,然后才出现红色。 run after f936aaaee23 (this PR, 08:53:25Z) landed. The next commit,正在处理 f936aaaee23 的提交(此 PR,时间 08:53:25Z)。下一个提交任务…… df2e8e5b317, is an MPS-metal-only change and is not implicated. df2e8e5b317 ,是一个仅适用于金属环境的修改,与任何问题无关。

This was subsequently masked by a DISABLED issue (#195878, Platforms: xpu),这个问题随后被一个“已禁用”的问题所掩盖了( #195878 , Platforms: xpu )。 so the smoke_xpu job is green again — but the underlying behavior change is所以, smoke_xpu 的工作又变得“绿色”了——不过,其背后的行为模式其实已经发生了改变。 still on main, and nothing has been fixed.仍然停留在 main 状态,没有任何问题得到解决。

The chain  这条链条

On current main:  当前时间: main

  • torch/_inductor/utils.py:206 — GPU_TYPES: list[str] = _gpu_types() now runs torch/_inductor/utils.py:206 – GPU_TYPES: list[str] = _gpu_types() 现在可以运行了
    at module scope  在模块范围内
  • _gpu_types() (torch/_inductor/utils.py:115) calls _gpu_types() ( torch/_inductor/utils.py:115 ) 正在调用
    get_registered_device_interfaces()
  • that triggers init_device_reg() (torch/_dynamo/device_interface.py:796),这将触发 init_device_reg() ( torch/_dynamo/device_interface.py:796 ),
    which calls torch.cuda.device_count(), torch.xpu.device_count(), and调用了 torch.cuda.device_count() 、 torch.xpu.device_count() 以及
    MtiaInterface.device_count()

So importing inductor now probes every device backend. The PR description因此,现在在导入电感器时,会检查每个设备的后端代码。相关的问题描述如下: acknowledges this ("Importing torch._inductor.utils now triggers已确认这一点(“现在导入 torch._inductor.utils 会触发操作”) init_device_reg() (lightweight device_count() probes) at import; previously init_device_reg() (轻量级 device_count() 探针)在导入阶段被使用;之前已经使用过 this happened on the first registry access") — the question is whether the two这种情况发生在第一次注册访问时——问题是,这两者之间是否真的存在关联。 consequences below were intended.这些后果正是人们所期望的。

Two things I'd like the review to focus on

我希望这篇评论能重点关注两件事。
1. Fork-poisoning when NVML discovery fails. torch.cuda.device_count()1. 当 NVML 发现功能失效时,会导致“叉子中毒”问题。 torch.cuda.device_count() documents "will NOT poison fork if NVML discovery succeeds", but when文件《如果 NVML 的发现成功,就不会出现‘毒叉’问题》中提到,但当……时候才会发生这种情况。 _device_count_nvml() returns < 0 it falls back to _device_count_nvml() 返回 < 0 否则就回退到 torch._C._cuda_getDeviceCount() (torch/cuda/__init__.py:1285-1293), which torch._C._cuda_getDeviceCount() ( torch/cuda/__init__.py:1285-1293 ),也就是 initializes the CUDA driver. On hosts/containers without working NVML, merely初始化 CUDA 驱动程序。对于没有运行 NVML 功能的主机/容器来说,只需执行此操作即可。 importing inductor would then poison fork, where previously a process might进口的电感器最终会被丢弃,而在此之前,这些电感器或许还能被使用。 never reach the first registry access. To be clear: this is reasoned from永远无法到达第一个注册表项。需要明确的是:这是基于某种理由而做出的判断。 reading the code, not something I observed in CI — please confirm or refute阅读了这段代码,这不是我在集成测试中观察到的现象——请确认或反驳这一点。 it rather than assuming it.与其假设它存在,不如实际去确认它。

2. The registry is now frozen at inductor-import time. The comment above2. 现在注册表在 inductor-import 时间被冻结了。上面的评论是这么说的。 GPU_TYPES states "Registering after this module is imported is not supported." GPU_TYPES 表示“在导入此模块之后进行注册是不被支持的”。 That means an out-of-tree backend (NPU, privateuse1) registering its这意味着有一个非树状结构的后端(NPU、privateuse1)正在注册其…… DeviceInterface after inductor has been imported silently won't appear in DeviceInterface 在电感被静默导入之后,它将不会再次出现。 GPU_TYPES, and is_gpu() will return False for it. Given the ongoing GPU_TYPES ,而 is_gpu() 会返回 False。鉴于当前的情况…… accelerator-generalization / OOT-backend work in this repo, is the在这个仓库中,加速器-泛化/OOT 后端相关工作包括…… autoload-ordering assumption ("autoloaded backends register during import torch, explicit ones at their package import") safe in practice — e.g. for自动加载排序假设(“在 import torch 期间,所有自动加载的后端都会被注册到系统中,而具体的注册位置则取决于它们的包导入方式”)在实践中是安全的——例如,对于…… import torch_npu issued after something has already pulled in inductor? import torch_npu 是在某些事情已经吸引了感应器之后才发布的吗?

What I'm unsure about

我不太确定的地方是什么……
A narrow patch looks hard: caching once at import is the PR's central design这一小块区域看起来很难处理:在导入时进行一次缓存操作就是该项目的核心设计。 decision, and GPU_TYPES is consumed as a plain list[str] in many places, so决策过程,而 GPU_TYPES 在许多地方被当作普通的 list[str] 来使用,因此 lazifying it via a module __getattr__ isn't obviously safe. I'd like the通过模块 __getattr__ 来使它变得懒惰化显然并不安全。我希望不要这样做。 review to say which of these is right:请评论一下,指出其中哪一个是正确的:

  • restore laziness behind an accessor and update the call sites,在访问器之后恢复惰性行为,并更新调用点。
  • keep the eager snapshot but make the scan itself side-effect-free (i.e. avoid保留高效的快照功能,但让扫描过程本身不产生副作用(即避免……)
    device_count() during registration, registering the bare interfaces without在注册过程中,没有对裸接口进行注册。
    enumerating indexed aliases),列举索引化别名),
  • or revert and redo.或者重新进行操作。

Also worth checking whether the indexed-alias enumeration (cuda:0, xpu:0, …)同样值得检查的是那些已索引化的别名枚举方式( cuda:0 、 xpu:0 等)。 in init_device_reg() needs to happen at registration time at all, since that在 init_device_reg() 中,所有事情都需要在注册时完成,因为…… is the only reason device_count() is called there.这就是 device_count() 被派往那个地方的唯一原因。

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.
The branch is pushed and CI should be green. Please re-enable the XPU test when landing.

@05mengmeizi
05mengmeizi requested a review from jansel September 7, 2026 03:00
@05mengmeizi

Copy link
Copy Markdown
Contributor Author

@jansel @anijain2305 I have fixed the issue that caused the error. Please check it again if you could. Thank you.

kerer-ai pushed a commit to kerer-ai/pytorch-nv that referenced this pull request Sep 7, 2026
@jansel

jansel commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

@claude is this safe to reland? Has the reason for the revert been fixed? Give a confidence level.

@claude

claude Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

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.

  • Read the new fix commit (46b3f0f6)
  • Verify init_device_reg() no longer performs any device probe
  • Verify no other import-time path re-introduces _xpu_getDeviceCount / fork-poisoning
  • Verify deleting the indexed aliases is behavior-preserving in-tree
  • Verdict + confidence level

One thing to do at merge time: the XPU guard tests are still masked by DISABLED issue #195878 (Platforms: xpu). Nothing in this PR re-enables them, so if you land as-is the only mechanical check that inductor import does not probe devices stays off. Close #195878 (or drop the Platforms: xpu line) as part of landing.

Reland assessment #190326 — full verification

The fix

46b3f0f6 deletes the three indexed-alias enumeration loops from init_device_reg(), leaving (torch/_dynamo/device_interface.py:796-805):

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 = True

That is exactly option 2 from the previous round, and it removes the only device-runtime call in the function. register_interface_for_device() itself just does a dict store plus UserDefinedClassVariable._in_graph_classes.cache_clear() — no device touch. So:

  • _gpu_types() (torch/_inductor/utils.py:116-127) → get_registered_device_interfaces() → init_device_reg() is now probe-free.
  • GPU_TYPES: list[str] = _gpu_types() at utils.py:206 therefore no longer touches any device runtime at import.
  • The whole chain that broke test_no_xpu_device_query_on_inductor_import — import torch._inductor.lowering → torch._inductor.utils → _gpu_types() → torch.xpu.device_count() → torch._C._xpu_getDeviceCount() → register_fork_handler_for_device_init(at::kXPU) — is severed at the third hop.

I also checked that nothing else in the import torch._inductor.lowering path re-introduces a probe. torch/_dynamo/device_interface.py has no module-scope device calls (the staticmethod(torch.cuda.device_count) bindings are attribute references, and the new MtiaInterface.device_count wrapper likewise is only defined, not called). lowering.py:3737,3742 call torch.xpu._is_compiled() / torch.mtia._is_compiled(), which are torch._C._has_xpu and a registry Has() query — neither queries a device nor latches hooks, and both predate this PR. And get_gpu_type() is not called at inductor-utils import; it is only called at import of torch.testing._internal.inductor_utils, which is not in the test's import path.

Fork-poisoning is closed for the wide fan-out path. The concern was torch/testing/_internal/common_device_type.py:20 (from torch._inductor.utils import GPU_TYPES), which fans out to ~215 test files including fork-sensitive ones. That import is now side-effect-free again, restoring the pre-PR property. The remaining module-scope probes in torch/testing/_internal/inductor_utils.py (GPU_TYPE = get_gpu_type() → _device_is_available() → torch.xpu.is_available()) do reach device_count(), but that file already called torch.cuda.is_available() / torch.xpu.is_available() / torch.mtia.is_available() at module scope before this PR (pre-PR lines 72-78), so this PR adds no new exposure there.

Deleting the indexed aliases: behavior-preserving in-tree

I re-audited every registry consumer against the current tree:

Consumer Effect of removal
_gpu_types() (utils.py:126) filters ":" not in name — no change
codecache.py:365 filters if ":" in name: continue — no change
torch/utils/_triton.py:249 filters if ":" in name — no change
async_compile.caching_device_properties (:115) indexed entries were the same interface class, so this was doing N+1 redundant calls. Worker.get_device_properties(None) caches props for all ordinals (device_interface.py:325-329, range(device_count())), so pre_fork_setup() still warms the full cache
variables/builder.py:4211,4224,4237, variables/torch.py:1743, variables/user_defined.py:418 build lists/sets of Stream/Event/current_stream class objects; duplicates collapsed already
get_interface_for_device() all 28 in-tree torch/ call sites and all 42 test/ call sites pass an unindexed type (device.type, V.graph.device_type, GPU_TYPE, gpu_type, "cuda"), and the function strips .type from any torch.device it is handed. I grepped for f-string/"cuda:0"-style lookups and found none

The one real BC delta: get_interface_for_device("cuda:0") as a literal string now raises NotImplementedError instead of resolving. Nothing in-tree does this, and passing torch.device("cuda:0") still works (index stripped). If you want to be belt-and-braces, device.split(":")[0] in get_interface_for_device() is a one-liner that is strictly more capable than the enumeration was (works for ordinals beyond device_count() too) — but it is not needed to land.

Also note the indexed-alias filters in codecache.py / _triton.py / _gpu_types() are now dead in-tree. Leave them: an out-of-tree backend can still register indexed names, and test_gpu_types_filters_indexed_and_non_gpu / test_indexed_device_name_skipped register "fakegpu:0" / "fake:0" explicitly, so the filters stay covered.

Rest of the PR: unchanged and still sound

Re-verified the in-tree equivalence by inspection: init_device_reg() registers cuda/xpu/mtia/cpu/mps/tpu; only the four GPU classes override is_gpu(), so _gpu_types() = ["cuda","xpu","mtia","mps"] (order differs from the old literal, which put mps second — harmless, and get_gpu_type() is now explicitly order-independent). MpsInterface defines no Stream, so exposes_streams() is False and device_need_guard("mps") stays False, reproducing the removed != "mps" case via the real reason. test_in_tree_gpu_types_unchanged (test/inductor/test_utils.py:1481-1490) pins all of that, including is_gpu("cuda:0") == False. is_gpu() is plain list.__contains__ on a 4-element global, so no hot-path cost. The MTIA device_count() guard (device_interface.py:450-454) is now belt-and-braces for the import path but still load-bearing for _is_multigpu and autotune_process.py:356, so keep it.

Confidence: high (~85%)

What I verified by reading code: the exact chain that produced '1' != '0' is severed, no remaining import-time device probe exists on the torch._inductor.lowering path, and the alias deletion is inert for every in-tree consumer.

What keeps it at 85% rather than higher:

  1. I could not run anything — no built PyTorch in this environment. The check I'd want is python test/test_xpu.py -k test_no_xpu_device_query_on_inductor_import on an XPU runner, plus python test/test_cpp_extensions_mtia_backend.py and python test/inductor/test_utils.py TestDeviceClassification.
  2. The guard test is disabled, so CI green on smoke_xpu is not evidence this time. That is why re-enabling it is a landing condition rather than a nice-to-have — with it live, a re-regression fails within one commit, as it did before.
  3. Two carried-over advisories, neither a reland blocker: GPU_TYPES is still bound at utils.py:206 after the torch._dynamo import block at 174-192 while get_gpu_type() at 147 reads it (latent NameError only — I re-traced the block and nothing reaches it); and the frozen-registry / late-import torch_npu hole is still a documentation-only guarantee, which is worth a separate narrowing of is_gpu() rather than anything here.

The current CI failure is torchtitan-test / torchtitan_models_integration, which Dr. CI attributes to the merge base (broken trunk), not this PR.

| Branch: `main_guard`

@jansel

jansel commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo module: inductor open source release notes: inductor Reverted triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants