Skip to content

[MPS] Resolve compile_shader headers the way cpp_extension does - #195295

Closed
BenjaminDEMAILLE wants to merge 1 commit into
pytorch:mainfrom
BenjaminDEMAILLE:mps-compile-shader-torch-path
Closed

BenjaminDEMAILLE wants to merge 1 commit into
pytorch:mainfrom
BenjaminDEMAILLE:mps-compile-shader-torch-path

Conversation

@BenjaminDEMAILLE

@BenjaminDEMAILLE BenjaminDEMAILLE commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

compile_shader resolves its header directory from __file__, while the rest of PyTorch uses get_file_path("torch"). The two diverge under an editable install, where the package is redirected to the checkout but the headers are staged next to the installed distribution, so every #include <c10/metal/...> fails with "file not found" even though the headers are there and cpp_extension finds them.

Regression from #180247, which changed the editable install layout.

Fixes #195293.

Test: on such an install TestMetalLibrary goes from 14 errors to 27 passed / 3 skipped, and the four atomic_add cases pass.

(Description drafted with an AI assistant.)

@pytorch-bot pytorch-bot Bot added the module: mkldnn Related to Intel IDEEP or oneDNN (a.k.a. mkldnn) integration label Aug 29, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/195295

Note: Links to docs will display an error until the docs builds have been completed.

❌ 1 New Failure, 2 Unrelated Failures

As of commit fb027d4 with merge base 68dedf0 (image):

NEW FAILURE - The following job has failed:

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.

`torch.mps.compile_shader` inlines `#include` directives before handing the
source to the Metal compiler, and it derives the search directory from
`Path(__file__).parent.parent / "include"`. Nothing else in PyTorch resolves
headers that way: `torch/utils/cpp_extension.py` uses
`_TORCH_PATH = get_file_path("torch")` and builds `include` from that.

The two agree in a packaged install and diverge under an editable one, where
the `torch` package is redirected to the source checkout while the staged
headers live next to the installed distribution. `torch.__file__` then points
at a directory with no `include` in it, and every `#include <c10/metal/...>`
fails with "file not found" even though the headers are present and C++
extensions build against them without trouble:

```
cpp_extension.include_paths()[0]
  .../site-packages/torch/include                     exists

Path(torch.mps.__file__).parent.parent / "include"
  <checkout>/torch/include                            missing
```

Using the same resolution as `cpp_extension` removes the inconsistency rather
than adding a fallback search path. The import is function-local, matching
`Path` and `_embed_headers` immediately above it, so `torch._utils_internal` is
not pulled in at `torch` import time.

Fixes pytorch#195293.

Test Plan:

```
python -c "
import torch
for h in ('c10/metal/special_math.h', 'c10/metal/atomic.h', 'c10/metal/random.h'):
    torch.mps.compile_shader('#include <%s>' % h)
"
python test/test_mps.py TestMetalLibrary
python test/test_mps.py -k atomic_add
```

All three headers resolve. `TestMetalLibrary` is 27 passed / 3 skipped and the
four `atomic_add` cases pass; before the change 14 of those reported as errors
on this install.

This PR was authored with the help of an AI assistant (Claude).
@BenjaminDEMAILLE
BenjaminDEMAILLE force-pushed the mps-compile-shader-torch-path branch from 67b3320 to fb027d4 Compare August 29, 2026 18:19
@BenjaminDEMAILLE

Copy link
Copy Markdown
Contributor Author

Force-pushed to drop four third_party submodule pointer bumps (cudnn_frontend, ideep, kineto, mimalloc) that my git commit -a swept in from a dirty local checkout. The PR is now the single-file change it was meant to be.

(Drafted with an AI assistant.)

@malfet malfet added topic: bug fixes topic category release notes: mps Release notes category ciflow/mps Run MPS tests (subset of trunk) release notes: devx and removed release notes: mps Release notes category module: mkldnn Related to Intel IDEEP or oneDNN (a.k.a. mkldnn) integration labels Aug 29, 2026
@malfet

malfet commented Aug 29, 2026

Copy link
Copy Markdown
Collaborator

@claude any idea why pytorchbot added module: mkldnn on this PR?

@BenjaminDEMAILLE LGTM, but please edit your PR description but hand and keep it more succinct.

@claude

claude Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

Claude finished @malfet's task in 32s —— View job


Why module: mkldnn got applied

It came from the first push, not the current diff. .github/labeler.yml has:

"module: mkldnn":
- third_party/ideep
- caffe2/ideep/**
...

The original commit on this PR swept in four third_party submodule pointer bumps — cudnn_frontend, ideep, kineto, mimalloc — from a dirty local checkout (see @BenjaminDEMAILLE's comment). third_party/ideep matched that first pattern, so the labeler tagged it module: mkldnn, and pytorch-bot then appended the mkldnn/ideep cc list (@gujinghui @PenghuiCheng @XiaobingSuper ...) to the PR body.

The labeler only adds labels; it never removes them, so the force-push that reduced the PR to the single torch/mps/__init__.py change left both the label and the cc list behind. Both are stale and safe to strip — the current diff touches nothing under third_party/ or caffe2/.

Worth noting module: mps is not in labeler.yml at all, which is why this PR ended up labeled for the one subsystem it doesn't touch and unlabeled for the one it does.
| Branch: mps-compile-shader-torch-path

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 30, 2026
@malfet

malfet commented Aug 30, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -f "Lint + MPS are green"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

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

orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…rch#195295)

`compile_shader` resolves its header directory from `__file__`, while the rest of PyTorch uses `get_file_path("torch")`. The two diverge under an editable install, where the package is redirected to the checkout but the headers are staged next to the installed distribution, so every `#include <c10/metal/...>` fails with "file not found" even though the headers are there and `cpp_extension` finds them.

Regression from pytorch#180247, which changed the editable install layout.

Fixes pytorch#195293.

Test: on such an install `TestMetalLibrary` goes from 14 errors to 27 passed / 3 skipped, and the four `atomic_add` cases pass.

*(Description drafted with an AI assistant.)*

Pull Request resolved: pytorch#195295
Approved by: https://github.com/malfet
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 3, 2026
Two defects in the editable-install path lookups added by pytorch#180247, with one root
cause: both ask a question whose answer a source checkout can forge.

`_load_global_deps` falls back to `importlib.metadata.distribution("torch")` when
libtorch_global_deps is not beside `__file__`. That returns the *first* torch
distribution on sys.path, which need not be the installed one: a checkout
carrying a setuptools-era `torch.egg-info` supplies a nearer match whose
`locate_file` resolves relative to its own parent, so the result does not exist,
the `exists()` guard declines to substitute, and CDLL proceeds with the path it
already knew was missing. `import torch` then fails outright, and because the
OSError is routed through the CUDA-dependency retry it surfaces as an unrelated
dlopen error naming the source tree. Reported as pytorch#195293.

That particular leftover is transitional -- `spin clean` removes it, and a
checkout made after pytorch#180248 will not grow one. The lookup is wrong independently
of it, though: taking the first name match was never the same question as
finding the installed distribution.

`_compute_torch_parent` only consults the distribution when `bin/` is absent
beside the module. `tools/build_libtorch.py` installs into `<repo>/torch` by
design and `docs/libtorch.rst` documents that flow, so a checkout can hold one
while the artifacts that matter live elsewhere -- and the presence test then
keeps the fallback from firing, so `get_file_path("torch")` silently returns the
source tree. That makes every caller conditionally wrong, including the
already-merged pytorch#195295 -- and unlike the egg-info above, this one does not age
out, because it is a supported workflow rather than a leftover.

Both now go through one helper. It asks `distributions(name="torch")` rather
than `distribution("torch")`, so it sees every candidate, and accepts one only
if it is a real installed distribution, its path is absolute, and the file is
there. "Real" is decided on METADATA versus PKG-INFO: pip and scikit-build-core
write the former, a setuptools egg-info the latter. Existence alone is not
enough -- a checkout carrying both a stale egg-info and leftover artifacts
resolves to a path that really is present.

The name filter matters for import cost. `distributions(name="torch")` matches
on distribution directory names and takes 0.08 ms; enumerating and reading every
METADATA to filter by name takes 7.3 ms in a 37-package environment and scales
with it. `_compute_torch_parent` runs at import, so the difference is what makes
consulting the distribution first affordable at all, rather than only on a miss.

`_load_global_deps` now prefers the installed distribution outright rather than
only on a miss. Consulting it only when nothing sits beside `__file__` leaves the
worse half of the bug in place: a checkout that has had an in-tree build still
holds loadable libraries, so the preload succeeds against a stale libtorch and
reports nothing. Measured on a Linux box whose checkout carries ten `.so` files
six weeks older than the install -- unpatched, /proc/self/maps shows the stale
copy mapped; patched, the installed one. For a wheel the two paths are the same
directory, so this changes nothing there.

It also raises when nothing resolves at all, instead of handing CDLL a path it
knows is missing. USE_GLOBAL_DEPS gates the call, and its own comment directs
environments without the library to turn it off, so reaching that point is a real
error and worth naming as one.

The helper is imported defensively. `_utils_internal` is replaced wholesale in
some downstream builds -- its own header says so -- and this call sits on the
import path, so a missing helper degrades to the previous `__file__` behaviour
rather than breaking `import torch`.

Not fixed here: `torch.utils.cmake_prefix_path` computes from `__file__`
directly and is still wrong on an editable install. It was blocked on
`get_file_path` being unreliable; with that fixed the one-line change becomes
viable, and it follows separately.

This commit was authored with the assistance of an AI coding assistant.

Test Plan:

Verified on the live reproducer -- a macOS editable install of viable/strict
(2988f71, scikit-build-core 1.0.3) with a stale `torch.egg-info` left in the
checkout, run from inside that checkout so it lands on sys.path:

```
$ pixi run python -c "import torch"          # before
OSError: dlopen(<checkout>/torch/lib/libtorch_global_deps.dylib ... no such file)

$ git apply editable-fix.patch
$ pixi run python -c "import torch"          # after
imported OK: 2.15.0a0+git2988f71
  torch.__file__       <checkout>/torch/__init__.py
  get_file_path(torch) <site-packages>/torch
  lib lookup           <site-packages>/torch/lib/libtorch_global_deps.dylib

$ git checkout -- torch/__init__.py torch/_utils_internal.py
$ pixi run python -c "import torch"          # control
OSError: dlopen(<checkout>/torch/lib/... no such file)
```

`torch.__file__` staying in the checkout while `get_file_path` moves to
site-packages is the split working as intended. The same run shows
`cmake_prefix_path` still resolving into the checkout, which is the separate
follow-up above.

Four synthetic layouts covered the cases that box cannot show, by executing the
two functions against constructed distribution trees:

| layout | expected | result |
| --- | --- | --- |
| stale egg-info + leftover `torch/bin`, checkout first on sys.path | installed | installed |
| same, site-packages first | installed | installed |
| pure checkout, no installed distribution | checkout | checkout |
| plain wheel install, module beside artifacts | unchanged | unchanged |

Row one is why the METADATA/PKG-INFO test exists: an earlier version filtered
only on absolute-and-exists and returned the checkout there.

That row is not hypothetical. A second Linux box carries both leftovers, and its
real distribution set shows every candidate shape at once:

```
version              kind      isabs  exists  locate_file("torch")
2.14.0a0+git7de45b6  PKG-INFO  False  True    torch
2.14.0a0+git2041bef  METADATA  True   True    <site-packages>/torch
2.14.0a0+git7de45b6  PKG-INFO  True   True    <checkout>/torch
```

The third is absolute, present, and wrong -- existence cannot separate it from
the second, which is why the METADATA/PKG-INFO test is load-bearing rather than
belt-and-braces. The first is a *relative* path that `exists()` only because the
process was started in the checkout, which is what the isabs test is for. On that
box the old heuristic returned the checkout, and its fallback, had the heuristic
let it run, would have returned the bare string `torch`; the new helper returns
site-packages.

Lint:

```
lintrunner torch/__init__.py torch/_utils_internal.py
```
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 3, 2026
…d torch

The cpp_wrapper path in the Metal backend embedded `c10/metal/*.h` from
`Path(__file__).parent.parent.parent / "include"`. Under a redirect-mode
editable install `__file__` is in the source checkout, which has no
`include/`, so header embedding fails.

This is the same defect pytorch#195295 fixed in `torch.mps.compile_shader`, at the
twin call site, and it takes the same form: `get_file_path("torch")`, which
resolves through the installed distribution.

Test Plan:

Not reachable without a Metal device, so this was not exercised end to end.
Checked that the expression now matches the merged fix in
`torch/mps/__init__.py`, that `Path` is still needed by the module, and that
`torch._utils_internal` is import-safe here -- it pulls only `torch`,
`torch.version` and the strobelight profiler, and is already imported during
`torch/__init__.py`.

```
lintrunner -a torch/_inductor/codegen/mps.py
```

Depends on the parent commit: `get_file_path` is only reliable once
`_compute_torch_parent` stops keying on `bin/` existing beside the module.

Authored with the assistance of Claude Code.
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…rch#195295)

`compile_shader` resolves its header directory from `__file__`, while the rest of PyTorch uses `get_file_path("torch")`. The two diverge under an editable install, where the package is redirected to the checkout but the headers are staged next to the installed distribution, so every `#include <c10/metal/...>` fails with "file not found" even though the headers are there and `cpp_extension` finds them.

Regression from pytorch#180247, which changed the editable install layout.

Fixes pytorch#195293.

Test: on such an install `TestMetalLibrary` goes from 14 errors to 27 passed / 3 skipped, and the four `atomic_add` cases pass.

*(Description drafted with an AI assistant.)*

Pull Request resolved: pytorch#195295
Approved by: https://github.com/malfet
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 11, 2026
Two defects in the editable-install path lookups added by pytorch#180247 share one
root cause: both asked a question whose answer a source checkout can forge.
`_load_global_deps` fell back to `importlib.metadata.distribution("torch")`,
which returns the first torch distribution on sys.path; a checkout carrying a
setuptools-era `torch.egg-info` supplies a nearer match whose `locate_file`
resolves into the checkout, the `exists()` guard declines it, and CDLL proceeds
with a path it already knew was missing, so `import torch` fails with an
unrelated-looking dlopen error (pytorch#195293). `_compute_torch_parent` consulted the
distribution only when `bin/` was absent beside the module, and
`tools/build_libtorch.py` installs into `<repo>/torch` by design, so a checkout
that had run it kept the fallback from firing and `get_file_path("torch")`
silently returned the source tree, making every caller conditionally wrong,
including the merged pytorch#195295.

Both now ask the import system where torch is installed, through one helper,
`_installed_torch_dir`, in the order RFC-0060 (pytorch/rfcs#109) prescribes:
the editable loader's `paths` (scikit-build/scikit-build-core#1567; the entry
that is not the checkout and holds `lib/`, since the order is only fixed by
scikit-build/scikit-build-core#1566), then `importlib.util.find_spec("torch._C")
.origin`, the directory `_C` will actually be imported from in every layout and
the anchor `torch/__init__.py` already uses for the Windows DLL directory, then
`__file__` when there is no spec at all (BUILD_LIBTORCH_WHL, a frozen
interpreter). `torch_parent` is two levels above that directory.

Instead of reasoning around leftovers, the helper detects them. In a checkout
whose `_C` resolves elsewhere, an in-tree `_C`, `lib/*.so`, `bin/`, `include/`,
`share/` or a `torch.egg-info` produces a warning that lists the paths and
points at `spin clean`, which removes all of them. A warning rather than an
error: the stale copies are never imported, they only mislead tooling that walks
metadata or `__file__`.

`_load_global_deps` resolves through `get_file_path` like every other consumer
and raises OSError when the library is missing, which is what `ctypes.CDLL`
raised and what `torch.utils.collect_env` catches.

Revision history: the first revision of this change resolved the installed
tree through `importlib.metadata.distributions()` with a METADATA-versus-
PKG-INFO filter, and was reviewed in that form on 2026-09-04. A self-review
found the indirection leaking (a built checkout shadowing a wheel could pair the
wheel's `libtorch_global_deps` with the checkout's `_C`), and the review's
`bin/`-probe finding pointed the same way; the import-system anchor replaces
it. The review reply on the PR maps each of its points to this revision.

Test Plan:

Linux, redirect-mode editable install on qgpu3 (scikit-build-core 1.0.0, whose
loaders have no `paths` attribute, so the `_C` spec path is the one exercised
end to end; the checkout there holds a stale `_C`, 13 in-tree libraries and a
`torch.egg-info`), patch applied then reverted:

```
python test/test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

5 passed; the warning listed all leftovers; `torch_parent` and
`cmake_prefix_path` resolve to site-packages. The loader-`paths` step is pinned
by `test_installed_torch_dir_prefers_the_editable_loader_paths` with a fake
loader, since no released scikit-build-core exposes it yet.

Windows, redirect-mode editable install (MSVC, Ninja, scikit-build-core 1.0.0),
clean checkout, run against the `_C`-spec revision of this commit on 2026-09-07:

```
python test\test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

3 passed, 1 skipped (the global-deps test is a no-op on Windows); no warning;
`cmake_prefix_path` resolves to site-packages with `TorchConfig.cmake` present.

```
spin lint -- torch/_utils_internal.py torch/__init__.py test/test_utils.py
```

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 11, 2026
…d torch

The cpp_wrapper path in the Metal backend embedded `c10/metal/*.h` from
`Path(__file__).parent.parent.parent / "include"`. Under a redirect-mode
editable install `__file__` is in the source checkout, which has no
`include/`, so header embedding fails.

This is the same defect pytorch#195295 fixed in `torch.mps.compile_shader`, at the
twin call site, and it takes the same form: `get_file_path("torch")`, which
resolves through the installed torch.

Test Plan:

Not reachable without a Metal device, so this was not exercised end to end.
Checked that the expression now matches the merged fix in
`torch/mps/__init__.py`, that `Path` is still needed by the module, and that
`torch._utils_internal` is import-safe here -- it pulls only `torch`,
`torch.version` and the strobelight profiler, and is already imported during
`torch/__init__.py`.

```
lintrunner -a torch/_inductor/codegen/mps.py
```

Depends on the parent commit: `get_file_path` is only reliable once
`_compute_torch_parent` anchors on the import system.

Authored with the assistance of Claude Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 23, 2026
Two defects in the editable-install path lookups added by pytorch#180247 share one
root cause: both asked a question whose answer a source checkout can forge.
`_load_global_deps` fell back to `importlib.metadata.distribution("torch")`,
which returns the first torch distribution on sys.path; a checkout carrying a
setuptools-era `torch.egg-info` supplies a nearer match whose `locate_file`
resolves into the checkout, the `exists()` guard declines it, and CDLL proceeds
with a path it already knew was missing, so `import torch` fails with an
unrelated-looking dlopen error (pytorch#195293). `_compute_torch_parent` consulted the
distribution only when `bin/` was absent beside the module, and
`tools/build_libtorch.py` installs into `<repo>/torch` by design, so a checkout
that had run it kept the fallback from firing and `get_file_path("torch")`
silently returned the source tree, making every caller conditionally wrong,
including the merged pytorch#195295.

Both now ask the import system where torch is installed, through one helper,
`_installed_torch_dir`, in the order RFC-0060 (pytorch/rfcs#109) prescribes:
the editable loader's `paths` (scikit-build/scikit-build-core#1567; the entry
that is not the checkout and holds `lib/`, since the order is only fixed by
scikit-build/scikit-build-core#1566), then `importlib.util.find_spec("torch._C")
.origin`, the directory `_C` will actually be imported from in every layout and
the anchor `torch/__init__.py` already uses for the Windows DLL directory, then
`__file__` when there is no spec at all (BUILD_LIBTORCH_WHL, a frozen
interpreter). `torch_parent` is two levels above that directory.

Instead of reasoning around leftovers, the helper detects them. In a checkout
whose `_C` resolves elsewhere, an in-tree `_C`, `lib/*.so`, `bin/`, `include/`,
`share/` or a `torch.egg-info` produces a warning that lists the paths and
points at `spin clean`, which removes all of them. A warning rather than an
error: the stale copies are never imported, they only mislead tooling that walks
metadata or `__file__`.

`_load_global_deps` resolves through `get_file_path` like every other consumer
and raises OSError when the library is missing, which is what `ctypes.CDLL`
raised and what `torch.utils.collect_env` catches.

Revision history: the first revision of this change resolved the installed
tree through `importlib.metadata.distributions()` with a METADATA-versus-
PKG-INFO filter, and was reviewed in that form on 2026-09-04. A self-review
found the indirection leaking (a built checkout shadowing a wheel could pair the
wheel's `libtorch_global_deps` with the checkout's `_C`), and the review's
`bin/`-probe finding pointed the same way; the import-system anchor replaces
it. The review reply on the PR maps each of its points to this revision.

Test Plan:

Linux, redirect-mode editable install on qgpu3 (scikit-build-core 1.0.0, whose
loaders have no `paths` attribute, so the `_C` spec path is the one exercised
end to end; the checkout there holds a stale `_C`, 13 in-tree libraries and a
`torch.egg-info`), patch applied then reverted:

```
python test/test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

5 passed; the warning listed all leftovers; `torch_parent` and
`cmake_prefix_path` resolve to site-packages. The loader-`paths` step is pinned
by `test_installed_torch_dir_prefers_the_editable_loader_paths` with a fake
loader, since no released scikit-build-core exposes it yet.

Windows, redirect-mode editable install (MSVC, Ninja, scikit-build-core 1.0.0),
clean checkout, run against the `_C`-spec revision of this commit on 2026-09-07:

```
python test\test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

3 passed, 1 skipped (the global-deps test is a no-op on Windows); no warning;
`cmake_prefix_path` resolves to site-packages with `TorchConfig.cmake` present.

```
spin lint -- torch/_utils_internal.py torch/__init__.py test/test_utils.py
```

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 23, 2026
…d torch

The cpp_wrapper path in the Metal backend embedded `c10/metal/*.h` from
`Path(__file__).parent.parent.parent / "include"`. Under a redirect-mode
editable install `__file__` is in the source checkout, which has no
`include/`, so header embedding fails.

This is the same defect pytorch#195295 fixed in `torch.mps.compile_shader`, at the
twin call site, and it takes the same form: `get_file_path("torch")`, which
resolves through the installed torch.

Test Plan:

Not reachable without a Metal device, so this was not exercised end to end.
Checked that the expression now matches the merged fix in
`torch/mps/__init__.py`, that `Path` is still needed by the module, and that
`torch._utils_internal` is import-safe here -- it pulls only `torch`,
`torch.version` and the strobelight profiler, and is already imported during
`torch/__init__.py`.

```
lintrunner -a torch/_inductor/codegen/mps.py
```

Depends on the parent commit: `get_file_path` is only reliable once
`_compute_torch_parent` anchors on the import system.

Authored with the assistance of Claude Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
pytorchmergebot pushed a commit that referenced this pull request Sep 23, 2026
…le__` (#195587)

## Summary

Follow-up to #195293, which #195295 closed by fixing the reported symptom. This fixes the path-resolution mechanism underneath it, including a hard `import torch` failure that nothing had reported and a defect that made #195295 itself correct only some of the time, and then applies the mechanism to three call sites that were waiting on it. Fixes #191752.

Redirect-mode editable installs (scikit-build-core) are the first layout where Python sources and CMake-installed artifacts live in different trees: `.py` in the checkout, `include/ lib/ bin/ share/` beside the installed distribution. Two lookups added in #180247 to cope with that ask a question a source checkout can answer wrongly.

**`_load_global_deps`** fell back to `importlib.metadata.distribution("torch")`, which returns the *first* torch distribution on `sys.path`, not necessarily the installed one. A checkout carrying a setuptools-era `torch.egg-info` supplies a nearer match whose `locate_file` resolves into the checkout, the `exists()` guard declines it, and `CDLL` proceeds with the path it already knew was missing. `import torch` fails, and since the `OSError` is routed through the CUDA-dependency retry it surfaces as an unrelated dlopen error naming the source tree.

**`_compute_torch_parent`** only consulted the distribution when `bin/` was absent beside the module. `tools/build_libtorch.py` installs into `<repo>/torch` by design (`docs/libtorch.rst` documents that flow), so a checkout can hold one while the artifacts that matter live elsewhere. The presence test then kept the fallback from firing and `get_file_path("torch")` silently returned the source tree, which made every caller conditionally wrong, including the already-merged #195295.

Both now ask the import system where torch is installed, through one helper, `_installed_torch_dir`, in the order RFC-0060 (pytorch/rfcs#109) prescribes:

1. the editable loader's `paths` (scikit-build/scikit-build-core#1567, in review): the entry that is not the checkout and holds `lib/`. Identity, not `lib/`, is what excludes the checkout, since `torch/lib` is a tracked source directory; the order of `paths` is only fixed by scikit-build/scikit-build-core#1566, hence the probe rather than `paths[0]`;
2. `importlib.util.find_spec("torch._C").origin`, the directory `_C` will actually be imported from in every layout, and the anchor `torch/__init__.py` already uses for the Windows DLL directory. This is the path every released scikit-build-core hits today;
3. `__file__`, only when there is no spec at all (`BUILD_LIBTORCH_WHL`, a frozen interpreter).

Instead of reasoning around leftovers, the helper detects them: in a checkout whose `_C` resolves elsewhere, an in-tree `_C`, `lib/*.so`, `bin/`, `include/`, `share/` or `torch.egg-info` produces a warning listing the paths and pointing at `spin clean`. A warning rather than an error, because the editable finder maps `_C` and every other CMake-installed module by name to the install tree, so the stale copies are never imported; they only mislead tooling that walks metadata or `__file__`.

`_load_global_deps` resolves through `get_file_path` like every other consumer and raises `OSError` when the library is missing, which is what `ctypes.CDLL` raised and what `torch.utils.collect_env` catches.

With `get_file_path` sound, three further commits apply it to call sites that derived an asset path from `__file__`. **`torch.utils.cmake_prefix_path`** computed `share/cmake` with no fallback at all, so `find_package(Torch)` failed against every editable install; it is a public API, documented in `docs/cpp/source/installing.md`, and gets a regression test that asserts `Torch/TorchConfig.cmake` is actually present. **`torch/_inductor/codegen/mps.py`** embedded `c10/metal/*.h` from `Path(__file__).parent.parent.parent / "include"` on the cpp_wrapper path, the twin of the site #195295 fixed. **`torch_openreg`'s `get_pytorch_dir()`** passed `dirname(torch.__file__)` as `-DPYTORCH_INSTALL_DIR`. The last two are taken from #192559 by @guptaishaan.

**Revision history.** The first revision of this PR resolved the installed tree through `importlib.metadata.distributions()` with a METADATA-versus-PKG-INFO filter, and was reviewed in that form on 2026-09-04. A self-review found the indirection leaking (a built checkout shadowing a wheel could pair the wheel's `libtorch_global_deps` with the checkout's `_C`), and the review's `bin/`-probe finding pointed the same way; the import-system anchor replaces it. The reply below the review maps each of its points to the current revision.

**Still not fixed here.** More `__file__`-derived lookups remain, in inductor, in distributed, and in the testing helpers. All are `exists()`-guarded, so they degrade quietly rather than failing, and each wants its own decision. They are inventoried in #195887, together with the sites that were checked and deliberately excluded.

This PR was authored with the assistance of an AI coding assistant.

## Test Plan

**Linux, redirect-mode editable install (scikit-build-core 1.0.0), checkout holding a stale `_C`, 13 in-tree libraries and a `torch.egg-info`**, patch applied then reverted:

```
python test/test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

5 passed against the pushed head. The warning listed all leftovers; `torch_parent` and `cmake_prefix_path` resolve to site-packages. scikit-build-core 1.0.0 has no `__loader__.paths`, so this exercises the `_C`-spec step end to end; the loader-paths step is pinned by `test_installed_torch_dir_prefers_the_editable_loader_paths` with a fake loader, including the case where the checkout appears in `paths` under a symlinked spelling.

**Windows, redirect-mode editable install (MSVC, Ninja, scikit-build-core 1.0.0), clean checkout**, run against the `_C`-spec revision:

```
python test\test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

3 passed, 1 skipped (the global-deps test is a no-op on Windows); no warning; `cmake_prefix_path` resolves to site-packages with `TorchConfig.cmake` present.

**`cmake_prefix_path`** was also checked on a macOS arm64 editable install (scikit-build-core 1.0.3) by configuring a real project, since printing the path proves nothing when the stale value is a well-formed string:

```cmake
cmake_minimum_required(VERSION 3.27)
project(probe LANGUAGES CXX)
find_package(Torch REQUIRED)
message(STATUS "PROBE_OK TORCH_LIBRARIES=${TORCH_LIBRARIES}")
```

configured with `-DCMAKE_PREFIX_PATH=$(python -c 'import torch.utils; print(torch.utils.cmake_prefix_path)')`:

| tree | result |
| --- | --- |
| before | exit 1, "Could not find a package configuration file provided by Torch" |
| after | exit 0, `PROBE_OK`, `TORCH_LIBRARIES` resolved into site-packages |
| reverted | exit 1 again |

The inductor MPS path needs a Metal device and was not exercised; it is the same one-line change as the merged #195295. Building torch_openreg needs a full extension build and was not run; the change substitutes one directory computation for another, and both resolve to `<site-packages>/torch` in a wheel install.

Lint:

```
spin lint -- torch/_utils_internal.py torch/__init__.py torch/utils/__init__.py torch/_inductor/codegen/mps.py test/test_utils.py test/cpp_extensions/open_registration_extension/torch_openreg/setup.py
```

Pull Request resolved: #195587
Approved by: https://github.com/atalman
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 30, 2026
Two defects in the editable-install path lookups added by pytorch#180247 share one
root cause: both asked a question whose answer a source checkout can forge.
`_load_global_deps` fell back to `importlib.metadata.distribution("torch")`,
which returns the first torch distribution on sys.path; a checkout carrying a
setuptools-era `torch.egg-info` supplies a nearer match whose `locate_file`
resolves into the checkout, the `exists()` guard declines it, and CDLL proceeds
with a path it already knew was missing, so `import torch` fails with an
unrelated-looking dlopen error (pytorch#195293). `_compute_torch_parent` consulted the
distribution only when `bin/` was absent beside the module, and
`tools/build_libtorch.py` installs into `<repo>/torch` by design, so a checkout
that had run it kept the fallback from firing and `get_file_path("torch")`
silently returned the source tree, making every caller conditionally wrong,
including the merged pytorch#195295.

Both now ask the import system where torch is installed, through one helper,
`_installed_torch_dir`, in the order RFC-0060 (pytorch/rfcs#109) prescribes:
the editable loader's `paths` (scikit-build/scikit-build-core#1567; the entry
that is not the checkout and holds `lib/`, since the order is only fixed by
scikit-build/scikit-build-core#1566), then `importlib.util.find_spec("torch._C")
.origin`, the directory `_C` will actually be imported from in every layout and
the anchor `torch/__init__.py` already uses for the Windows DLL directory, then
`__file__` when there is no spec at all (BUILD_LIBTORCH_WHL, a frozen
interpreter). `torch_parent` is two levels above that directory.

Instead of reasoning around leftovers, the helper detects them. In a checkout
whose `_C` resolves elsewhere, an in-tree `_C`, `lib/*.so`, `bin/`, `include/`,
`share/` or a `torch.egg-info` produces a warning that lists the paths and
points at `spin clean`, which removes all of them. A warning rather than an
error: the stale copies are never imported, they only mislead tooling that walks
metadata or `__file__`.

`_load_global_deps` resolves through `get_file_path` like every other consumer
and raises OSError when the library is missing, which is what `ctypes.CDLL`
raised and what `torch.utils.collect_env` catches.

Revision history: the first revision of this change resolved the installed
tree through `importlib.metadata.distributions()` with a METADATA-versus-
PKG-INFO filter, and was reviewed in that form on 2026-09-04. A self-review
found the indirection leaking (a built checkout shadowing a wheel could pair the
wheel's `libtorch_global_deps` with the checkout's `_C`), and the review's
`bin/`-probe finding pointed the same way; the import-system anchor replaces
it. The review reply on the PR maps each of its points to this revision.

Test Plan:

Linux, redirect-mode editable install on qgpu3 (scikit-build-core 1.0.0, whose
loaders have no `paths` attribute, so the `_C` spec path is the one exercised
end to end; the checkout there holds a stale `_C`, 13 in-tree libraries and a
`torch.egg-info`), patch applied then reverted:

```
python test/test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

5 passed; the warning listed all leftovers; `torch_parent` and
`cmake_prefix_path` resolve to site-packages. The loader-`paths` step is pinned
by `test_installed_torch_dir_prefers_the_editable_loader_paths` with a fake
loader, since no released scikit-build-core exposes it yet.

Windows, redirect-mode editable install (MSVC, Ninja, scikit-build-core 1.0.0),
clean checkout, run against the `_C`-spec revision of this commit on 2026-09-07:

```
python test\test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

3 passed, 1 skipped (the global-deps test is a no-op on Windows); no warning;
`cmake_prefix_path` resolves to site-packages with `TorchConfig.cmake` present.

```
spin lint -- torch/_utils_internal.py torch/__init__.py test/test_utils.py
```

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 30, 2026
…d torch

The cpp_wrapper path in the Metal backend embedded `c10/metal/*.h` from
`Path(__file__).parent.parent.parent / "include"`. Under a redirect-mode
editable install `__file__` is in the source checkout, which has no
`include/`, so header embedding fails.

This is the same defect pytorch#195295 fixed in `torch.mps.compile_shader`, at the
twin call site, and it takes the same form: `get_file_path("torch")`, which
resolves through the installed torch.

Test Plan:

Not reachable without a Metal device, so this was not exercised end to end.
Checked that the expression now matches the merged fix in
`torch/mps/__init__.py`, that `Path` is still needed by the module, and that
`torch._utils_internal` is import-safe here -- it pulls only `torch`,
`torch.version` and the strobelight profiler, and is already imported during
`torch/__init__.py`.

```
lintrunner -a torch/_inductor/codegen/mps.py
```

Depends on the parent commit: `get_file_path` is only reliable once
`_compute_torch_parent` anchors on the import system.

Authored with the assistance of Claude Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
pytorchmergebot pushed a commit that referenced this pull request Oct 2, 2026
…le__` (#195587)

## Summary

Follow-up to #195293, which #195295 closed by fixing the reported symptom. This fixes the path-resolution mechanism underneath it, including a hard `import torch` failure that nothing had reported and a defect that made #195295 itself correct only some of the time, and then applies the mechanism to three call sites that were waiting on it. Fixes #191752.

Redirect-mode editable installs (scikit-build-core) are the first layout where Python sources and CMake-installed artifacts live in different trees: `.py` in the checkout, `include/ lib/ bin/ share/` beside the installed distribution. Two lookups added in #180247 to cope with that ask a question a source checkout can answer wrongly.

**`_load_global_deps`** fell back to `importlib.metadata.distribution("torch")`, which returns the *first* torch distribution on `sys.path`, not necessarily the installed one. A checkout carrying a setuptools-era `torch.egg-info` supplies a nearer match whose `locate_file` resolves into the checkout, the `exists()` guard declines it, and `CDLL` proceeds with the path it already knew was missing. `import torch` fails, and since the `OSError` is routed through the CUDA-dependency retry it surfaces as an unrelated dlopen error naming the source tree.

**`_compute_torch_parent`** only consulted the distribution when `bin/` was absent beside the module. `tools/build_libtorch.py` installs into `<repo>/torch` by design (`docs/libtorch.rst` documents that flow), so a checkout can hold one while the artifacts that matter live elsewhere. The presence test then kept the fallback from firing and `get_file_path("torch")` silently returned the source tree, which made every caller conditionally wrong, including the already-merged #195295.

Both now ask the import system where torch is installed, through one helper, `_installed_torch_dir`, in the order RFC-0060 (pytorch/rfcs#109) prescribes:

1. the editable loader's `paths` (scikit-build/scikit-build-core#1567, in review): the entry that is not the checkout and holds `lib/`. Identity, not `lib/`, is what excludes the checkout, since `torch/lib` is a tracked source directory; the order of `paths` is only fixed by scikit-build/scikit-build-core#1566, hence the probe rather than `paths[0]`;
2. `importlib.util.find_spec("torch._C").origin`, the directory `_C` will actually be imported from in every layout, and the anchor `torch/__init__.py` already uses for the Windows DLL directory. This is the path every released scikit-build-core hits today;
3. `__file__`, only when there is no spec at all (`BUILD_LIBTORCH_WHL`, a frozen interpreter).

Instead of reasoning around leftovers, the helper detects them: in a checkout whose `_C` resolves elsewhere, an in-tree `_C`, `lib/*.so`, `bin/`, `include/`, `share/` or `torch.egg-info` produces a warning listing the paths and pointing at `spin clean`. A warning rather than an error, because the editable finder maps `_C` and every other CMake-installed module by name to the install tree, so the stale copies are never imported; they only mislead tooling that walks metadata or `__file__`.

`_load_global_deps` resolves through `get_file_path` like every other consumer and raises `OSError` when the library is missing, which is what `ctypes.CDLL` raised and what `torch.utils.collect_env` catches.

With `get_file_path` sound, three further commits apply it to call sites that derived an asset path from `__file__`. **`torch.utils.cmake_prefix_path`** computed `share/cmake` with no fallback at all, so `find_package(Torch)` failed against every editable install; it is a public API, documented in `docs/cpp/source/installing.md`, and gets a regression test that asserts `Torch/TorchConfig.cmake` is actually present. **`torch/_inductor/codegen/mps.py`** embedded `c10/metal/*.h` from `Path(__file__).parent.parent.parent / "include"` on the cpp_wrapper path, the twin of the site #195295 fixed. **`torch_openreg`'s `get_pytorch_dir()`** passed `dirname(torch.__file__)` as `-DPYTORCH_INSTALL_DIR`. The last two are taken from #192559 by @guptaishaan.

**Revision history.** The first revision of this PR resolved the installed tree through `importlib.metadata.distributions()` with a METADATA-versus-PKG-INFO filter, and was reviewed in that form on 2026-09-04. A self-review found the indirection leaking (a built checkout shadowing a wheel could pair the wheel's `libtorch_global_deps` with the checkout's `_C`), and the review's `bin/`-probe finding pointed the same way; the import-system anchor replaces it. The reply below the review maps each of its points to the current revision.

**Still not fixed here.** More `__file__`-derived lookups remain, in inductor, in distributed, and in the testing helpers. All are `exists()`-guarded, so they degrade quietly rather than failing, and each wants its own decision. They are inventoried in #195887, together with the sites that were checked and deliberately excluded.

This PR was authored with the assistance of an AI coding assistant.

## Test Plan

**Linux, redirect-mode editable install (scikit-build-core 1.0.0), checkout holding a stale `_C`, 13 in-tree libraries and a `torch.egg-info`**, patch applied then reverted:

```
python test/test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

5 passed against the pushed head. The warning listed all leftovers; `torch_parent` and `cmake_prefix_path` resolve to site-packages. scikit-build-core 1.0.0 has no `__loader__.paths`, so this exercises the `_C`-spec step end to end; the loader-paths step is pinned by `test_installed_torch_dir_prefers_the_editable_loader_paths` with a fake loader, including the case where the checkout appears in `paths` under a symlinked spelling.

**Windows, redirect-mode editable install (MSVC, Ninja, scikit-build-core 1.0.0), clean checkout**, run against the `_C`-spec revision:

```
python test\test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

3 passed, 1 skipped (the global-deps test is a no-op on Windows); no warning; `cmake_prefix_path` resolves to site-packages with `TorchConfig.cmake` present.

**`cmake_prefix_path`** was also checked on a macOS arm64 editable install (scikit-build-core 1.0.3) by configuring a real project, since printing the path proves nothing when the stale value is a well-formed string:

```cmake
cmake_minimum_required(VERSION 3.27)
project(probe LANGUAGES CXX)
find_package(Torch REQUIRED)
message(STATUS "PROBE_OK TORCH_LIBRARIES=${TORCH_LIBRARIES}")
```

configured with `-DCMAKE_PREFIX_PATH=$(python -c 'import torch.utils; print(torch.utils.cmake_prefix_path)')`:

| tree | result |
| --- | --- |
| before | exit 1, "Could not find a package configuration file provided by Torch" |
| after | exit 0, `PROBE_OK`, `TORCH_LIBRARIES` resolved into site-packages |
| reverted | exit 1 again |

The inductor MPS path needs a Metal device and was not exercised; it is the same one-line change as the merged #195295. Building torch_openreg needs a full extension build and was not run; the change substitutes one directory computation for another, and both resolve to `<site-packages>/torch` in a wheel install.

Lint:

```
spin lint -- torch/_utils_internal.py torch/__init__.py torch/utils/__init__.py torch/_inductor/codegen/mps.py test/test_utils.py test/cpp_extensions/open_registration_extension/torch_openreg/setup.py
```

Pull Request resolved: #195587
Approved by: https://github.com/atalman
zklaus added a commit to zklaus/pytorch that referenced this pull request Oct 5, 2026
Two defects in the editable-install path lookups added by pytorch#180247 share one
root cause: both asked a question whose answer a source checkout can forge.
`_load_global_deps` fell back to `importlib.metadata.distribution("torch")`,
which returns the first torch distribution on sys.path; a checkout carrying a
setuptools-era `torch.egg-info` supplies a nearer match whose `locate_file`
resolves into the checkout, the `exists()` guard declines it, and CDLL proceeds
with a path it already knew was missing, so `import torch` fails with an
unrelated-looking dlopen error (pytorch#195293). `_compute_torch_parent` consulted the
distribution only when `bin/` was absent beside the module, and
`tools/build_libtorch.py` installs into `<repo>/torch` by design, so a checkout
that had run it kept the fallback from firing and `get_file_path("torch")`
silently returned the source tree, making every caller conditionally wrong,
including the merged pytorch#195295.

Both now ask the import system where torch is installed, through one helper,
`_installed_torch_dir`, in the order RFC-0060 (pytorch/rfcs#109) prescribes:
the editable loader's `paths` (scikit-build/scikit-build-core#1567; the entry
that is not the checkout and holds `lib/`, since the order is only fixed by
scikit-build/scikit-build-core#1566), then `importlib.util.find_spec("torch._C")
.origin`, the directory `_C` will actually be imported from in every layout and
the anchor `torch/__init__.py` already uses for the Windows DLL directory, then
`__file__` when there is no spec at all (BUILD_LIBTORCH_WHL, a frozen
interpreter). `torch_parent` is two levels above that directory.

Instead of reasoning around leftovers, the helper detects them. In a checkout
whose `_C` resolves elsewhere, an in-tree `_C`, `lib/*.so`, `bin/`, `include/`,
`share/` or a `torch.egg-info` produces a warning that lists the paths and
points at `spin clean`, which removes all of them. A warning rather than an
error: the stale copies are never imported, they only mislead tooling that walks
metadata or `__file__`.

`_load_global_deps` resolves through `get_file_path` like every other consumer
and raises OSError when the library is missing, which is what `ctypes.CDLL`
raised and what `torch.utils.collect_env` catches.

Revision history: the first revision of this change resolved the installed
tree through `importlib.metadata.distributions()` with a METADATA-versus-
PKG-INFO filter, and was reviewed in that form on 2026-09-04. A self-review
found the indirection leaking (a built checkout shadowing a wheel could pair the
wheel's `libtorch_global_deps` with the checkout's `_C`), and the review's
`bin/`-probe finding pointed the same way; the import-system anchor replaces
it. The review reply on the PR maps each of its points to this revision.

Test Plan:

Linux, redirect-mode editable install on qgpu3 (scikit-build-core 1.0.0, whose
loaders have no `paths` attribute, so the `_C` spec path is the one exercised
end to end; the checkout there holds a stale `_C`, 13 in-tree libraries and a
`torch.egg-info`), patch applied then reverted:

```
python test/test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

5 passed; the warning listed all leftovers; `torch_parent` and
`cmake_prefix_path` resolve to site-packages. The loader-`paths` step is pinned
by `test_installed_torch_dir_prefers_the_editable_loader_paths` with a fake
loader, since no released scikit-build-core exposes it yet.

Windows, redirect-mode editable install (MSVC, Ninja, scikit-build-core 1.0.0),
clean checkout, run against the `_C`-spec revision of this commit on 2026-09-07:

```
python test\test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

3 passed, 1 skipped (the global-deps test is a no-op on Windows); no warning;
`cmake_prefix_path` resolves to site-packages with `TorchConfig.cmake` present.

```
spin lint -- torch/_utils_internal.py torch/__init__.py test/test_utils.py
```

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
zklaus added a commit to zklaus/pytorch that referenced this pull request Oct 5, 2026
…d torch

The cpp_wrapper path in the Metal backend embedded `c10/metal/*.h` from
`Path(__file__).parent.parent.parent / "include"`. Under a redirect-mode
editable install `__file__` is in the source checkout, which has no
`include/`, so header embedding fails.

This is the same defect pytorch#195295 fixed in `torch.mps.compile_shader`, at the
twin call site, and it takes the same form: `get_file_path("torch")`, which
resolves through the installed torch.

Test Plan:

Not reachable without a Metal device, so this was not exercised end to end.
Checked that the expression now matches the merged fix in
`torch/mps/__init__.py`, that `Path` is still needed by the module, and that
`torch._utils_internal` is import-safe here -- it pulls only `torch`,
`torch.version` and the strobelight profiler, and is already imported during
`torch/__init__.py`.

```
lintrunner -a torch/_inductor/codegen/mps.py
```

Depends on the parent commit: `get_file_path` is only reliable once
`_compute_torch_parent` anchors on the import system.

Authored with the assistance of Claude Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…le__` (pytorch#195587)

## Summary

Follow-up to pytorch#195293, which pytorch#195295 closed by fixing the reported symptom. This fixes the path-resolution mechanism underneath it, including a hard `import torch` failure that nothing had reported and a defect that made pytorch#195295 itself correct only some of the time, and then applies the mechanism to three call sites that were waiting on it. Fixes pytorch#191752.

Redirect-mode editable installs (scikit-build-core) are the first layout where Python sources and CMake-installed artifacts live in different trees: `.py` in the checkout, `include/ lib/ bin/ share/` beside the installed distribution. Two lookups added in pytorch#180247 to cope with that ask a question a source checkout can answer wrongly.

**`_load_global_deps`** fell back to `importlib.metadata.distribution("torch")`, which returns the *first* torch distribution on `sys.path`, not necessarily the installed one. A checkout carrying a setuptools-era `torch.egg-info` supplies a nearer match whose `locate_file` resolves into the checkout, the `exists()` guard declines it, and `CDLL` proceeds with the path it already knew was missing. `import torch` fails, and since the `OSError` is routed through the CUDA-dependency retry it surfaces as an unrelated dlopen error naming the source tree.

**`_compute_torch_parent`** only consulted the distribution when `bin/` was absent beside the module. `tools/build_libtorch.py` installs into `<repo>/torch` by design (`docs/libtorch.rst` documents that flow), so a checkout can hold one while the artifacts that matter live elsewhere. The presence test then kept the fallback from firing and `get_file_path("torch")` silently returned the source tree, which made every caller conditionally wrong, including the already-merged pytorch#195295.

Both now ask the import system where torch is installed, through one helper, `_installed_torch_dir`, in the order RFC-0060 (pytorch/rfcs#109) prescribes:

1. the editable loader's `paths` (scikit-build/scikit-build-core#1567, in review): the entry that is not the checkout and holds `lib/`. Identity, not `lib/`, is what excludes the checkout, since `torch/lib` is a tracked source directory; the order of `paths` is only fixed by scikit-build/scikit-build-core#1566, hence the probe rather than `paths[0]`;
2. `importlib.util.find_spec("torch._C").origin`, the directory `_C` will actually be imported from in every layout, and the anchor `torch/__init__.py` already uses for the Windows DLL directory. This is the path every released scikit-build-core hits today;
3. `__file__`, only when there is no spec at all (`BUILD_LIBTORCH_WHL`, a frozen interpreter).

Instead of reasoning around leftovers, the helper detects them: in a checkout whose `_C` resolves elsewhere, an in-tree `_C`, `lib/*.so`, `bin/`, `include/`, `share/` or `torch.egg-info` produces a warning listing the paths and pointing at `spin clean`. A warning rather than an error, because the editable finder maps `_C` and every other CMake-installed module by name to the install tree, so the stale copies are never imported; they only mislead tooling that walks metadata or `__file__`.

`_load_global_deps` resolves through `get_file_path` like every other consumer and raises `OSError` when the library is missing, which is what `ctypes.CDLL` raised and what `torch.utils.collect_env` catches.

With `get_file_path` sound, three further commits apply it to call sites that derived an asset path from `__file__`. **`torch.utils.cmake_prefix_path`** computed `share/cmake` with no fallback at all, so `find_package(Torch)` failed against every editable install; it is a public API, documented in `docs/cpp/source/installing.md`, and gets a regression test that asserts `Torch/TorchConfig.cmake` is actually present. **`torch/_inductor/codegen/mps.py`** embedded `c10/metal/*.h` from `Path(__file__).parent.parent.parent / "include"` on the cpp_wrapper path, the twin of the site pytorch#195295 fixed. **`torch_openreg`'s `get_pytorch_dir()`** passed `dirname(torch.__file__)` as `-DPYTORCH_INSTALL_DIR`. The last two are taken from pytorch#192559 by @guptaishaan.

**Revision history.** The first revision of this PR resolved the installed tree through `importlib.metadata.distributions()` with a METADATA-versus-PKG-INFO filter, and was reviewed in that form on 2026-09-04. A self-review found the indirection leaking (a built checkout shadowing a wheel could pair the wheel's `libtorch_global_deps` with the checkout's `_C`), and the review's `bin/`-probe finding pointed the same way; the import-system anchor replaces it. The reply below the review maps each of its points to the current revision.

**Still not fixed here.** More `__file__`-derived lookups remain, in inductor, in distributed, and in the testing helpers. All are `exists()`-guarded, so they degrade quietly rather than failing, and each wants its own decision. They are inventoried in pytorch#195887, together with the sites that were checked and deliberately excluded.

This PR was authored with the assistance of an AI coding assistant.

## Test Plan

**Linux, redirect-mode editable install (scikit-build-core 1.0.0), checkout holding a stale `_C`, 13 in-tree libraries and a `torch.egg-info`**, patch applied then reverted:

```
python test/test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

5 passed against the pushed head. The warning listed all leftovers; `torch_parent` and `cmake_prefix_path` resolve to site-packages. scikit-build-core 1.0.0 has no `__loader__.paths`, so this exercises the `_C`-spec step end to end; the loader-paths step is pinned by `test_installed_torch_dir_prefers_the_editable_loader_paths` with a fake loader, including the case where the checkout appears in `paths` under a symlinked spelling.

**Windows, redirect-mode editable install (MSVC, Ninja, scikit-build-core 1.0.0), clean checkout**, run against the `_C`-spec revision:

```
python test\test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

3 passed, 1 skipped (the global-deps test is a no-op on Windows); no warning; `cmake_prefix_path` resolves to site-packages with `TorchConfig.cmake` present.

**`cmake_prefix_path`** was also checked on a macOS arm64 editable install (scikit-build-core 1.0.3) by configuring a real project, since printing the path proves nothing when the stale value is a well-formed string:

```cmake
cmake_minimum_required(VERSION 3.27)
project(probe LANGUAGES CXX)
find_package(Torch REQUIRED)
message(STATUS "PROBE_OK TORCH_LIBRARIES=${TORCH_LIBRARIES}")
```

configured with `-DCMAKE_PREFIX_PATH=$(python -c 'import torch.utils; print(torch.utils.cmake_prefix_path)')`:

| tree | result |
| --- | --- |
| before | exit 1, "Could not find a package configuration file provided by Torch" |
| after | exit 0, `PROBE_OK`, `TORCH_LIBRARIES` resolved into site-packages |
| reverted | exit 1 again |

The inductor MPS path needs a Metal device and was not exercised; it is the same one-line change as the merged pytorch#195295. Building torch_openreg needs a full extension build and was not run; the change substitutes one directory computation for another, and both resolve to `<site-packages>/torch` in a wheel install.

Lint:

```
spin lint -- torch/_utils_internal.py torch/__init__.py torch/utils/__init__.py torch/_inductor/codegen/mps.py test/test_utils.py test/cpp_extensions/open_registration_extension/torch_openreg/setup.py
```

Pull Request resolved: pytorch#195587
Approved by: https://github.com/atalman
pytorchmergebot pushed a commit to zklaus/pytorch that referenced this pull request Oct 13, 2026
Two defects in the editable-install path lookups added by pytorch#180247 share one
root cause: both asked a question whose answer a source checkout can forge.
`_load_global_deps` fell back to `importlib.metadata.distribution("torch")`,
which returns the first torch distribution on sys.path; a checkout carrying a
setuptools-era `torch.egg-info` supplies a nearer match whose `locate_file`
resolves into the checkout, the `exists()` guard declines it, and CDLL proceeds
with a path it already knew was missing, so `import torch` fails with an
unrelated-looking dlopen error (pytorch#195293). `_compute_torch_parent` consulted the
distribution only when `bin/` was absent beside the module, and
`tools/build_libtorch.py` installs into `<repo>/torch` by design, so a checkout
that had run it kept the fallback from firing and `get_file_path("torch")`
silently returned the source tree, making every caller conditionally wrong,
including the merged pytorch#195295.

Both now ask the import system where torch is installed, through one helper,
`_installed_torch_dir`, in the order RFC-0060 (pytorch/rfcs#109) prescribes:
the editable loader's `paths` (scikit-build/scikit-build-core#1567; the entry
that is not the checkout and holds `lib/`, since the order is only fixed by
scikit-build/scikit-build-core#1566), then `importlib.util.find_spec("torch._C")
.origin`, the directory `_C` will actually be imported from in every layout and
the anchor `torch/__init__.py` already uses for the Windows DLL directory, then
`__file__` when there is no spec at all (BUILD_LIBTORCH_WHL, a frozen
interpreter). `torch_parent` is two levels above that directory.

Instead of reasoning around leftovers, the helper detects them. In a checkout
whose `_C` resolves elsewhere, an in-tree `_C`, `lib/*.so`, `bin/`, `include/`,
`share/` or a `torch.egg-info` produces a warning that lists the paths and
points at `spin clean`, which removes all of them. A warning rather than an
error: the stale copies are never imported, they only mislead tooling that walks
metadata or `__file__`.

`_load_global_deps` resolves through `get_file_path` like every other consumer
and raises OSError when the library is missing, which is what `ctypes.CDLL`
raised and what `torch.utils.collect_env` catches.

Revision history: the first revision of this change resolved the installed
tree through `importlib.metadata.distributions()` with a METADATA-versus-
PKG-INFO filter, and was reviewed in that form on 2026-09-04. A self-review
found the indirection leaking (a built checkout shadowing a wheel could pair the
wheel's `libtorch_global_deps` with the checkout's `_C`), and the review's
`bin/`-probe finding pointed the same way; the import-system anchor replaces
it. The review reply on the PR maps each of its points to this revision.

Test Plan:

Linux, redirect-mode editable install on qgpu3 (scikit-build-core 1.0.0, whose
loaders have no `paths` attribute, so the `_C` spec path is the one exercised
end to end; the checkout there holds a stale `_C`, 13 in-tree libraries and a
`torch.egg-info`), patch applied then reverted:

```
python test/test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

5 passed; the warning listed all leftovers; `torch_parent` and
`cmake_prefix_path` resolve to site-packages. The loader-`paths` step is pinned
by `test_installed_torch_dir_prefers_the_editable_loader_paths` with a fake
loader, since no released scikit-build-core exposes it yet.

Windows, redirect-mode editable install (MSVC, Ninja, scikit-build-core 1.0.0),
clean checkout, run against the `_C`-spec revision of this commit on 2026-09-07:

```
python test\test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

3 passed, 1 skipped (the global-deps test is a no-op on Windows); no warning;
`cmake_prefix_path` resolves to site-packages with `TorchConfig.cmake` present.

```
spin lint -- torch/_utils_internal.py torch/__init__.py test/test_utils.py
```

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
pytorchmergebot pushed a commit to zklaus/pytorch that referenced this pull request Oct 13, 2026
…d torch

The cpp_wrapper path in the Metal backend embedded `c10/metal/*.h` from
`Path(__file__).parent.parent.parent / "include"`. Under a redirect-mode
editable install `__file__` is in the source checkout, which has no
`include/`, so header embedding fails.

This is the same defect pytorch#195295 fixed in `torch.mps.compile_shader`, at the
twin call site, and it takes the same form: `get_file_path("torch")`, which
resolves through the installed torch.

Test Plan:

Not reachable without a Metal device, so this was not exercised end to end.
Checked that the expression now matches the merged fix in
`torch/mps/__init__.py`, that `Path` is still needed by the module, and that
`torch._utils_internal` is import-safe here -- it pulls only `torch`,
`torch.version` and the strobelight profiler, and is already imported during
`torch/__init__.py`.

```
lintrunner -a torch/_inductor/codegen/mps.py
```

Depends on the parent commit: `get_file_path` is only reliable once
`_compute_torch_parent` anchors on the import system.

Authored with the assistance of Claude Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
pytorchmergebot pushed a commit that referenced this pull request Oct 14, 2026
…le__` (#195587)

## Summary

Follow-up to #195293, which #195295 closed by fixing the reported symptom. This fixes the path-resolution mechanism underneath it, including a hard `import torch` failure that nothing had reported and a defect that made #195295 itself correct only some of the time, and then applies the mechanism to three call sites that were waiting on it. Fixes #191752.

Redirect-mode editable installs (scikit-build-core) are the first layout where Python sources and CMake-installed artifacts live in different trees: `.py` in the checkout, `include/ lib/ bin/ share/` beside the installed distribution. Two lookups added in #180247 to cope with that ask a question a source checkout can answer wrongly.

**`_load_global_deps`** fell back to `importlib.metadata.distribution("torch")`, which returns the *first* torch distribution on `sys.path`, not necessarily the installed one. A checkout carrying a setuptools-era `torch.egg-info` supplies a nearer match whose `locate_file` resolves into the checkout, the `exists()` guard declines it, and `CDLL` proceeds with the path it already knew was missing. `import torch` fails, and since the `OSError` is routed through the CUDA-dependency retry it surfaces as an unrelated dlopen error naming the source tree.

**`_compute_torch_parent`** only consulted the distribution when `bin/` was absent beside the module. `tools/build_libtorch.py` installs into `<repo>/torch` by design (`docs/libtorch.rst` documents that flow), so a checkout can hold one while the artifacts that matter live elsewhere. The presence test then kept the fallback from firing and `get_file_path("torch")` silently returned the source tree, which made every caller conditionally wrong, including the already-merged #195295.

Both now ask the import system where torch is installed, through one helper, `_installed_torch_dir`, in the order RFC-0060 (pytorch/rfcs#109) prescribes:

1. the editable loader's `paths` (scikit-build/scikit-build-core#1567, in review): the entry that is not the checkout and holds `lib/`. Identity, not `lib/`, is what excludes the checkout, since `torch/lib` is a tracked source directory; the order of `paths` is only fixed by scikit-build/scikit-build-core#1566, hence the probe rather than `paths[0]`;
2. `importlib.util.find_spec("torch._C").origin`, the directory `_C` will actually be imported from in every layout, and the anchor `torch/__init__.py` already uses for the Windows DLL directory. This is the path every released scikit-build-core hits today;
3. `__file__`, only when there is no spec at all (`BUILD_LIBTORCH_WHL`, a frozen interpreter).

Instead of reasoning around leftovers, the helper detects them: in a checkout whose `_C` resolves elsewhere, an in-tree `_C`, `lib/*.so`, `bin/`, `include/`, `share/` or `torch.egg-info` produces a warning listing the paths and pointing at `spin clean`. A warning rather than an error, because the editable finder maps `_C` and every other CMake-installed module by name to the install tree, so the stale copies are never imported; they only mislead tooling that walks metadata or `__file__`.

`_load_global_deps` resolves through `get_file_path` like every other consumer and raises `OSError` when the library is missing, which is what `ctypes.CDLL` raised and what `torch.utils.collect_env` catches.

With `get_file_path` sound, three further commits apply it to call sites that derived an asset path from `__file__`. **`torch.utils.cmake_prefix_path`** computed `share/cmake` with no fallback at all, so `find_package(Torch)` failed against every editable install; it is a public API, documented in `docs/cpp/source/installing.md`, and gets a regression test that asserts `Torch/TorchConfig.cmake` is actually present. **`torch/_inductor/codegen/mps.py`** embedded `c10/metal/*.h` from `Path(__file__).parent.parent.parent / "include"` on the cpp_wrapper path, the twin of the site #195295 fixed. **`torch_openreg`'s `get_pytorch_dir()`** passed `dirname(torch.__file__)` as `-DPYTORCH_INSTALL_DIR`. The last two are taken from #192559 by @guptaishaan.

**Revision history.** The first revision of this PR resolved the installed tree through `importlib.metadata.distributions()` with a METADATA-versus-PKG-INFO filter, and was reviewed in that form on 2026-09-04. A self-review found the indirection leaking (a built checkout shadowing a wheel could pair the wheel's `libtorch_global_deps` with the checkout's `_C`), and the review's `bin/`-probe finding pointed the same way; the import-system anchor replaces it. The reply below the review maps each of its points to the current revision.

**Still not fixed here.** More `__file__`-derived lookups remain, in inductor, in distributed, and in the testing helpers. All are `exists()`-guarded, so they degrade quietly rather than failing, and each wants its own decision. They are inventoried in #195887, together with the sites that were checked and deliberately excluded.

This PR was authored with the assistance of an AI coding assistant.

## Test Plan

**Linux, redirect-mode editable install (scikit-build-core 1.0.0), checkout holding a stale `_C`, 13 in-tree libraries and a `torch.egg-info`**, patch applied then reverted:

```
python test/test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

5 passed against the pushed head. The warning listed all leftovers; `torch_parent` and `cmake_prefix_path` resolve to site-packages. scikit-build-core 1.0.0 has no `__loader__.paths`, so this exercises the `_C`-spec step end to end; the loader-paths step is pinned by `test_installed_torch_dir_prefers_the_editable_loader_paths` with a fake loader, including the case where the checkout appears in `paths` under a symlinked spelling.

**Windows, redirect-mode editable install (MSVC, Ninja, scikit-build-core 1.0.0), clean checkout**, run against the `_C`-spec revision:

```
python test\test_utils.py -k TestTorchPathResolution -k test_cmake_prefix_path -v
```

3 passed, 1 skipped (the global-deps test is a no-op on Windows); no warning; `cmake_prefix_path` resolves to site-packages with `TorchConfig.cmake` present.

**`cmake_prefix_path`** was also checked on a macOS arm64 editable install (scikit-build-core 1.0.3) by configuring a real project, since printing the path proves nothing when the stale value is a well-formed string:

```cmake
cmake_minimum_required(VERSION 3.27)
project(probe LANGUAGES CXX)
find_package(Torch REQUIRED)
message(STATUS "PROBE_OK TORCH_LIBRARIES=${TORCH_LIBRARIES}")
```

configured with `-DCMAKE_PREFIX_PATH=$(python -c 'import torch.utils; print(torch.utils.cmake_prefix_path)')`:

| tree | result |
| --- | --- |
| before | exit 1, "Could not find a package configuration file provided by Torch" |
| after | exit 0, `PROBE_OK`, `TORCH_LIBRARIES` resolved into site-packages |
| reverted | exit 1 again |

The inductor MPS path needs a Metal device and was not exercised; it is the same one-line change as the merged #195295. Building torch_openreg needs a full extension build and was not run; the change substitutes one directory computation for another, and both resolve to `<site-packages>/torch` in a wheel install.

Lint:

```
spin lint -- torch/_utils_internal.py torch/__init__.py torch/utils/__init__.py torch/_inductor/codegen/mps.py test/test_utils.py test/cpp_extensions/open_registration_extension/torch_openreg/setup.py
```

Pull Request resolved: #195587
Approved by: https://github.com/atalman
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/mps Run MPS tests (subset of trunk) ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: devx topic: bug fixes topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[MPS] compile_shader cannot resolve c10/metal headers with a scikit-build-core editable install

4 participants