Skip to content

Fix cmake_prefix_path for editable installs - #192559

Draft
guptaishaan wants to merge 1 commit into
pytorch:mainfrom
guptaishaan:fix-191752
Draft

guptaishaan wants to merge 1 commit into
pytorch:mainfrom
guptaishaan:fix-191752

Conversation

@guptaishaan

Copy link
Copy Markdown
Contributor

torch.utils.cmake_prefix_path was derived from torch/utils/init.py's own file. In a scikit-build-core editable install (redirect mode, which is what pyproject.toml configures) the Python modules are redirected to the source checkout while the CMake install tree (bin/, lib/, include/, share/cmake/) ships in the editable wheel and lands in site-packages. The public prefix therefore pointed at a directory that does not exist, and any find_package(Torch) using it failed.

Resolve it through torch._utils_internal.get_file_path instead, which returns the physical package root. torch/utils/cpp_extension.py already uses that helper to locate lib/ and include/ for exactly this reason, so this keeps the two in step; deriving the path from torch._C.file would have worked too, but it would have introduced a second convention and would not be overridable in the FB build environment, where _utils_internal.py is replaced.

OpenReg's setup.py had the same bug at its own call site: it passed -DPYTORCH_INSTALL_DIR=os.path.dirname(torch.file), so its find_package(Torch REQUIRED) failed in an editable install as well. It now uses the same helper.

The new regression test asserts that Torch/TorchConfig.cmake exists under the prefix rather than only that the parent directory does.

Test Plan:

CPU-only Release editable build on Linux x86_64, Python 3.13, gcc 13.4:

USE_CUDA=0 USE_ROCM=0 USE_XPU=0 BUILD_TEST=0 CMAKE_BUILD_TYPE=Release \
MAX_JOBS=96 pip install -e . -v --no-build-isolation

The new test fails before the change (TorchConfig.cmake does not exist under the checkout) and passes after:

python test/test_utils.py TestCppExtensionUtils
python test/test_utils.py
python test/run_test.py --openreg
lintrunner torch/utils/__init__.py test/test_utils.py \
  test/cpp_extensions/open_registration_extension/torch_openreg/setup.py

A minimal find_package(Torch REQUIRED) consumer configured with torch.utils.cmake_prefix_path fails before the change and finds libtorch.so after it.

torch.utils.cmake_prefix_path was derived from torch/utils/__init__.py's
own __file__. In a scikit-build-core editable install (redirect mode,
which is what pyproject.toml configures) the Python modules are
redirected to the source checkout while the CMake install tree (bin/,
lib/, include/, share/cmake/) ships in the editable wheel and lands in
site-packages. The public prefix therefore pointed at a directory that
does not exist, and any find_package(Torch) using it failed.

Resolve it through torch._utils_internal.get_file_path instead, which
returns the physical package root. torch/utils/cpp_extension.py already
uses that helper to locate lib/ and include/ for exactly this reason, so
this keeps the two in step; deriving the path from torch._C.__file__
would have worked too, but it would have introduced a second convention
and would not be overridable in the FB build environment, where
_utils_internal.py is replaced.

OpenReg's setup.py had the same bug at its own call site: it passed
-DPYTORCH_INSTALL_DIR=os.path.dirname(torch.__file__), so its
find_package(Torch REQUIRED) failed in an editable install as well. It
now uses the same helper.

The new regression test asserts that Torch/TorchConfig.cmake exists
under the prefix rather than only that the parent directory does.

Test Plan:

CPU-only Release editable build on Linux x86_64, Python 3.13, gcc 13.4:

```bash
USE_CUDA=0 USE_ROCM=0 USE_XPU=0 BUILD_TEST=0 CMAKE_BUILD_TYPE=Release \
MAX_JOBS=96 pip install -e . -v --no-build-isolation
```

The new test fails before the change (TorchConfig.cmake does not exist
under the checkout) and passes after:

```bash
python test/test_utils.py TestCppExtensionUtils
python test/test_utils.py
python test/run_test.py --openreg
lintrunner torch/utils/__init__.py test/test_utils.py \
  test/cpp_extensions/open_registration_extension/torch_openreg/setup.py
```

A minimal find_package(Torch REQUIRED) consumer configured with
torch.utils.cmake_prefix_path fails before the change and finds
libtorch.so after it.
@pytorch-bot

pytorch-bot Bot commented Aug 7, 2026

Copy link
Copy Markdown

🔗 Helpful Links

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

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

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot

pytorch-bot Bot commented Aug 7, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 3, 2026
The three preceding commits change how torch resolves its installed
artifacts but add no test, so nothing guards the resolution from drifting
back. This asserts that `torch.utils.cmake_prefix_path` actually contains
`Torch/TorchConfig.cmake`, which is the property `find_package(Torch)`
depends on and the one that was broken -- checking the string alone would
not have caught it, since the stale value was a well-formed path.

The test is taken unchanged from pytorch#192559 by @guptaishaan, a draft PR that
fixed `cmake_prefix_path` the same way this stack does. That PR also fixes
`get_pytorch_dir()` in the torch_openreg test extension, which is a third
site with this defect and is not addressed here.

Skipped under fbcode, where the CMake package files are not shipped.

Test Plan:

```
python test/test_utils.py TestCppExtensionUtils.test_cmake_prefix_path
lintrunner -a test/test_utils.py
```

The assertion fails on an editable install without the `cmake_prefix_path`
commit in this stack: the prefix resolves into the source checkout, which
holds no `share/cmake`. Verified by hand on macOS arm64 before that commit
existed, by configuring a real project; see its message.

Co-authored-by: guptaishaan <[email protected]>

Authored with the assistance of Claude Code.
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 3, 2026
`get_pytorch_dir()` derived the directory it passes as
`-DPYTORCH_INSTALL_DIR` from `torch.__file__`, so under a redirect-mode
editable install it pointed at the source checkout, which holds no `lib/`,
`include/` or `share/cmake` for the extension to build against.

Taken unchanged from pytorch#192559 by @guptaishaan, along with the regression test
in the preceding commit. The import stays inside the function, after the
`TORCH_DEVICE_BACKEND_AUTOLOAD` guard, so the circular-import case that
comment describes is unaffected -- importing `torch._utils_internal` still
imports `torch`, just as `import torch` did.

This is the last known site of this defect outside the four listed in the PR
description, all of which are `exists()`-guarded and degrade quietly rather
than failing.

Test Plan:

Not run: building torch_openreg needs a full source build of the extension,
which this checkout has no torch installed to link against. The change is a
substitution of one directory computation for another, both of which resolve
to `<site-packages>/torch` in a wheel install; they differ only for the split
layout, which is the case being fixed.

```
lintrunner -a test/cpp_extensions/open_registration_extension/torch_openreg/setup.py
```

Not affected by the `test_public_bindings` constraint that applies to
`torch.utils` in this stack: `test_public_bindings` only considers APIs whose
`__module__` starts with `torch.`, and this is a standalone setup script.
The import is function-local in any case.

Co-authored-by: guptaishaan <[email protected]>

Authored with the assistance of Claude Code.
@zklaus

zklaus commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

Thanks for this.

cmake_prefix_path is fixed in #195587, though by a different route than here. get_file_path("torch") was itself unreliable: _compute_torch_parent only consulted the installed distribution when bin/ was absent beside the module, and tools/build_libtorch.py installs into <repo>/torch by design, so a checkout could hold one while the artifacts that matter lived elsewhere. The mechanism this PR routes through had to be repaired before it could carry the fix.

Your other two hunks I have taken across unchanged, both with a Co-authored-by:

  • the regression test. Asserting that TorchConfig.cmake is actually present is the right shape -- checking the string alone would not have caught this, since the stale value was a well-formed path.
  • get_pytorch_dir() in torch_openreg/setup.py. That site was not on our own list, so thank you for catching it.

So nothing here is outstanding any more and this can be closed, unless you would rather keep it open for something I have missed.

zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 11, 2026
`cmake_prefix_path` derived its value from `__file__`, which under a
redirect-mode editable install points into the source checkout while
`share/cmake` is installed beside the distribution. The path it returned did
not exist, so `find_package(Torch)` failed against every editable install.
Unlike the other drifted sites this one had no fallback at all, and it is a
public API documented in `docs/cpp/source/installing.md`.

`get_file_path` is imported under a private alias. `torch.utils` defines no
`__all__`, so a plain import would publish `torch.utils.get_file_path` as a
new public API whose `__module__` is `torch._utils_internal`, which
`test_public_bindings` rejects. `import os.path as _osp` became unused and is
dropped; nothing outside this module referenced it.

The regression test asserts that `torch.utils.cmake_prefix_path` actually
contains `Torch/TorchConfig.cmake`, which is the property `find_package(Torch)`
depends on and the one that was broken; checking the string alone would not
have caught it, since the stale value was a well-formed path. It is taken
unchanged from pytorch#192559 by @guptaishaan, a draft PR that fixed
`cmake_prefix_path` the same way. Skipped under fbcode, where the CMake
package files are not shipped.

Test Plan:

Verified against a real editable install on macOS arm64 (scikit-build-core
1.0.3), by configuring an actual project rather than printing the path -- the
old value is a well-formed string, so only a configure distinguishes them.

```
cat > CMakeLists.txt <<'EOF2'
cmake_minimum_required(VERSION 3.27)
project(probe LANGUAGES CXX)
find_package(Torch REQUIRED)
message(STATUS "PROBE_OK TORCH_LIBRARIES=${TORCH_LIBRARIES}")
EOF2
cmake -DCMAKE_PREFIX_PATH="$(python -c 'import torch.utils; print(torch.utils.cmake_prefix_path)')" ..
```

Before: `<checkout>/torch/share/cmake`, which does not exist; cmake exits 1
with "Could not find a package configuration file provided by Torch".
After: `<site-packages>/torch/share/cmake`; cmake exits 0 and prints
PROBE_OK with TORCH_LIBRARIES resolved. Reverting the patch restores the
failure, so the change is causal.

```
python test/test_utils.py TestCppExtensionUtils.test_cmake_prefix_path
lintrunner -a torch/utils/__init__.py test/test_utils.py
python test/test_public_bindings.py TestPublicBindings.test_correct_module_names
```

The test fails on an editable install without this commit: the prefix
resolves into the source checkout, which holds no `share/cmake`.

Co-authored-by: guptaishaan <[email protected]>

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 11, 2026
`get_pytorch_dir()` derived the directory it passes as
`-DPYTORCH_INSTALL_DIR` from `torch.__file__`, so under a redirect-mode
editable install it pointed at the source checkout, which holds no `lib/`,
`include/` or `share/cmake` for the extension to build against. It now goes
through `get_file_path("torch")`, still under `realpath` so the rpaths it
bakes stay symlink-free.

Taken from pytorch#192559 by @guptaishaan. The import stays inside the function,
after the `TORCH_DEVICE_BACKEND_AUTOLOAD` guard, so the circular-import case
that comment describes is unaffected -- importing `torch._utils_internal`
still imports `torch`, just as `import torch` did.

Test Plan:

Not run: building torch_openreg needs a full source build of the extension.
The change substitutes one directory computation for another, both of which
resolve to `<site-packages>/torch` in a wheel install; they differ only for
the split layout, which is the case being fixed.

```
lintrunner -a test/cpp_extensions/open_registration_extension/torch_openreg/setup.py
```

Not affected by the `test_public_bindings` constraint that applies to
`torch.utils` in this stack: it only considers APIs whose `__module__`
starts with `torch.`, and this is a standalone setup script. The import is
function-local in any case.

Co-authored-by: guptaishaan <[email protected]>

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
`cmake_prefix_path` derived its value from `__file__`, which under a
redirect-mode editable install points into the source checkout while
`share/cmake` is installed beside the distribution. The path it returned did
not exist, so `find_package(Torch)` failed against every editable install.
Unlike the other drifted sites this one had no fallback at all, and it is a
public API documented in `docs/cpp/source/installing.md`.

`get_file_path` is imported under a private alias. `torch.utils` defines no
`__all__`, so a plain import would publish `torch.utils.get_file_path` as a
new public API whose `__module__` is `torch._utils_internal`, which
`test_public_bindings` rejects. `import os.path as _osp` became unused and is
dropped; nothing outside this module referenced it.

The regression test asserts that `torch.utils.cmake_prefix_path` actually
contains `Torch/TorchConfig.cmake`, which is the property `find_package(Torch)`
depends on and the one that was broken; checking the string alone would not
have caught it, since the stale value was a well-formed path. It is taken
unchanged from pytorch#192559 by @guptaishaan, a draft PR that fixed
`cmake_prefix_path` the same way. Skipped under fbcode, where the CMake
package files are not shipped.

Test Plan:

Verified against a real editable install on macOS arm64 (scikit-build-core
1.0.3), by configuring an actual project rather than printing the path -- the
old value is a well-formed string, so only a configure distinguishes them.

```
cat > CMakeLists.txt <<'EOF2'
cmake_minimum_required(VERSION 3.27)
project(probe LANGUAGES CXX)
find_package(Torch REQUIRED)
message(STATUS "PROBE_OK TORCH_LIBRARIES=${TORCH_LIBRARIES}")
EOF2
cmake -DCMAKE_PREFIX_PATH="$(python -c 'import torch.utils; print(torch.utils.cmake_prefix_path)')" ..
```

Before: `<checkout>/torch/share/cmake`, which does not exist; cmake exits 1
with "Could not find a package configuration file provided by Torch".
After: `<site-packages>/torch/share/cmake`; cmake exits 0 and prints
PROBE_OK with TORCH_LIBRARIES resolved. Reverting the patch restores the
failure, so the change is causal.

```
python test/test_utils.py TestCppExtensionUtils.test_cmake_prefix_path
lintrunner -a torch/utils/__init__.py test/test_utils.py
python test/test_public_bindings.py TestPublicBindings.test_correct_module_names
```

The test fails on an editable install without this commit: the prefix
resolves into the source checkout, which holds no `share/cmake`.

Co-authored-by: guptaishaan <[email protected]>

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
`get_pytorch_dir()` derived the directory it passes as
`-DPYTORCH_INSTALL_DIR` from `torch.__file__`, so under a redirect-mode
editable install it pointed at the source checkout, which holds no `lib/`,
`include/` or `share/cmake` for the extension to build against. It now goes
through `get_file_path("torch")`, still under `realpath` so the rpaths it
bakes stay symlink-free.

Taken from pytorch#192559 by @guptaishaan. The import stays inside the function,
after the `TORCH_DEVICE_BACKEND_AUTOLOAD` guard, so the circular-import case
that comment describes is unaffected -- importing `torch._utils_internal`
still imports `torch`, just as `import torch` did.

Test Plan:

Not run: building torch_openreg needs a full source build of the extension.
The change substitutes one directory computation for another, both of which
resolve to `<site-packages>/torch` in a wheel install; they differ only for
the split layout, which is the case being fixed.

```
lintrunner -a test/cpp_extensions/open_registration_extension/torch_openreg/setup.py
```

Not affected by the `test_public_bindings` constraint that applies to
`torch.utils` in this stack: it only considers APIs whose `__module__`
starts with `torch.`, and this is a standalone setup script. The import is
function-local in any case.

Co-authored-by: guptaishaan <[email protected]>

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
`cmake_prefix_path` derived its value from `__file__`, which under a
redirect-mode editable install points into the source checkout while
`share/cmake` is installed beside the distribution. The path it returned did
not exist, so `find_package(Torch)` failed against every editable install.
Unlike the other drifted sites this one had no fallback at all, and it is a
public API documented in `docs/cpp/source/installing.md`.

`get_file_path` is imported under a private alias. `torch.utils` defines no
`__all__`, so a plain import would publish `torch.utils.get_file_path` as a
new public API whose `__module__` is `torch._utils_internal`, which
`test_public_bindings` rejects. `import os.path as _osp` became unused and is
dropped; nothing outside this module referenced it.

The regression test asserts that `torch.utils.cmake_prefix_path` actually
contains `Torch/TorchConfig.cmake`, which is the property `find_package(Torch)`
depends on and the one that was broken; checking the string alone would not
have caught it, since the stale value was a well-formed path. It is taken
unchanged from pytorch#192559 by @guptaishaan, a draft PR that fixed
`cmake_prefix_path` the same way. Skipped under fbcode, where the CMake
package files are not shipped.

Test Plan:

Verified against a real editable install on macOS arm64 (scikit-build-core
1.0.3), by configuring an actual project rather than printing the path -- the
old value is a well-formed string, so only a configure distinguishes them.

```
cat > CMakeLists.txt <<'EOF2'
cmake_minimum_required(VERSION 3.27)
project(probe LANGUAGES CXX)
find_package(Torch REQUIRED)
message(STATUS "PROBE_OK TORCH_LIBRARIES=${TORCH_LIBRARIES}")
EOF2
cmake -DCMAKE_PREFIX_PATH="$(python -c 'import torch.utils; print(torch.utils.cmake_prefix_path)')" ..
```

Before: `<checkout>/torch/share/cmake`, which does not exist; cmake exits 1
with "Could not find a package configuration file provided by Torch".
After: `<site-packages>/torch/share/cmake`; cmake exits 0 and prints
PROBE_OK with TORCH_LIBRARIES resolved. Reverting the patch restores the
failure, so the change is causal.

```
python test/test_utils.py TestCppExtensionUtils.test_cmake_prefix_path
lintrunner -a torch/utils/__init__.py test/test_utils.py
python test/test_public_bindings.py TestPublicBindings.test_correct_module_names
```

The test fails on an editable install without this commit: the prefix
resolves into the source checkout, which holds no `share/cmake`.

Co-authored-by: guptaishaan <[email protected]>

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 30, 2026
`get_pytorch_dir()` derived the directory it passes as
`-DPYTORCH_INSTALL_DIR` from `torch.__file__`, so under a redirect-mode
editable install it pointed at the source checkout, which holds no `lib/`,
`include/` or `share/cmake` for the extension to build against. It now goes
through `get_file_path("torch")`, still under `realpath` so the rpaths it
bakes stay symlink-free.

Taken from pytorch#192559 by @guptaishaan. The import stays inside the function,
after the `TORCH_DEVICE_BACKEND_AUTOLOAD` guard, so the circular-import case
that comment describes is unaffected -- importing `torch._utils_internal`
still imports `torch`, just as `import torch` did.

Test Plan:

Not run: building torch_openreg needs a full source build of the extension.
The change substitutes one directory computation for another, both of which
resolve to `<site-packages>/torch` in a wheel install; they differ only for
the split layout, which is the case being fixed.

```
lintrunner -a test/cpp_extensions/open_registration_extension/torch_openreg/setup.py
```

Not affected by the `test_public_bindings` constraint that applies to
`torch.utils` in this stack: it only considers APIs whose `__module__`
starts with `torch.`, and this is a standalone setup script. The import is
function-local in any case.

Co-authored-by: guptaishaan <[email protected]>

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
`cmake_prefix_path` derived its value from `__file__`, which under a
redirect-mode editable install points into the source checkout while
`share/cmake` is installed beside the distribution. The path it returned did
not exist, so `find_package(Torch)` failed against every editable install.
Unlike the other drifted sites this one had no fallback at all, and it is a
public API documented in `docs/cpp/source/installing.md`.

`get_file_path` is imported under a private alias. `torch.utils` defines no
`__all__`, so a plain import would publish `torch.utils.get_file_path` as a
new public API whose `__module__` is `torch._utils_internal`, which
`test_public_bindings` rejects. `import os.path as _osp` became unused and is
dropped; nothing outside this module referenced it.

The regression test asserts that `torch.utils.cmake_prefix_path` actually
contains `Torch/TorchConfig.cmake`, which is the property `find_package(Torch)`
depends on and the one that was broken; checking the string alone would not
have caught it, since the stale value was a well-formed path. It is taken
unchanged from pytorch#192559 by @guptaishaan, a draft PR that fixed
`cmake_prefix_path` the same way. Skipped under fbcode, where the CMake
package files are not shipped.

Test Plan:

Verified against a real editable install on macOS arm64 (scikit-build-core
1.0.3), by configuring an actual project rather than printing the path -- the
old value is a well-formed string, so only a configure distinguishes them.

```
cat > CMakeLists.txt <<'EOF2'
cmake_minimum_required(VERSION 3.27)
project(probe LANGUAGES CXX)
find_package(Torch REQUIRED)
message(STATUS "PROBE_OK TORCH_LIBRARIES=${TORCH_LIBRARIES}")
EOF2
cmake -DCMAKE_PREFIX_PATH="$(python -c 'import torch.utils; print(torch.utils.cmake_prefix_path)')" ..
```

Before: `<checkout>/torch/share/cmake`, which does not exist; cmake exits 1
with "Could not find a package configuration file provided by Torch".
After: `<site-packages>/torch/share/cmake`; cmake exits 0 and prints
PROBE_OK with TORCH_LIBRARIES resolved. Reverting the patch restores the
failure, so the change is causal.

```
python test/test_utils.py TestCppExtensionUtils.test_cmake_prefix_path
lintrunner -a torch/utils/__init__.py test/test_utils.py
python test/test_public_bindings.py TestPublicBindings.test_correct_module_names
```

The test fails on an editable install without this commit: the prefix
resolves into the source checkout, which holds no `share/cmake`.

Co-authored-by: guptaishaan <[email protected]>

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 Oct 5, 2026
`get_pytorch_dir()` derived the directory it passes as
`-DPYTORCH_INSTALL_DIR` from `torch.__file__`, so under a redirect-mode
editable install it pointed at the source checkout, which holds no `lib/`,
`include/` or `share/cmake` for the extension to build against. It now goes
through `get_file_path("torch")`, still under `realpath` so the rpaths it
bakes stay symlink-free.

Taken from pytorch#192559 by @guptaishaan. The import stays inside the function,
after the `TORCH_DEVICE_BACKEND_AUTOLOAD` guard, so the circular-import case
that comment describes is unaffected -- importing `torch._utils_internal`
still imports `torch`, just as `import torch` did.

Test Plan:

Not run: building torch_openreg needs a full source build of the extension.
The change substitutes one directory computation for another, both of which
resolve to `<site-packages>/torch` in a wheel install; they differ only for
the split layout, which is the case being fixed.

```
lintrunner -a test/cpp_extensions/open_registration_extension/torch_openreg/setup.py
```

Not affected by the `test_public_bindings` constraint that applies to
`torch.utils` in this stack: it only considers APIs whose `__module__`
starts with `torch.`, and this is a standalone setup script. The import is
function-local in any case.

Co-authored-by: guptaishaan <[email protected]>

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
`cmake_prefix_path` derived its value from `__file__`, which under a
redirect-mode editable install points into the source checkout while
`share/cmake` is installed beside the distribution. The path it returned did
not exist, so `find_package(Torch)` failed against every editable install.
Unlike the other drifted sites this one had no fallback at all, and it is a
public API documented in `docs/cpp/source/installing.md`.

`get_file_path` is imported under a private alias. `torch.utils` defines no
`__all__`, so a plain import would publish `torch.utils.get_file_path` as a
new public API whose `__module__` is `torch._utils_internal`, which
`test_public_bindings` rejects. `import os.path as _osp` became unused and is
dropped; nothing outside this module referenced it.

The regression test asserts that `torch.utils.cmake_prefix_path` actually
contains `Torch/TorchConfig.cmake`, which is the property `find_package(Torch)`
depends on and the one that was broken; checking the string alone would not
have caught it, since the stale value was a well-formed path. It is taken
unchanged from pytorch#192559 by @guptaishaan, a draft PR that fixed
`cmake_prefix_path` the same way. Skipped under fbcode, where the CMake
package files are not shipped.

Test Plan:

Verified against a real editable install on macOS arm64 (scikit-build-core
1.0.3), by configuring an actual project rather than printing the path -- the
old value is a well-formed string, so only a configure distinguishes them.

```
cat > CMakeLists.txt <<'EOF2'
cmake_minimum_required(VERSION 3.27)
project(probe LANGUAGES CXX)
find_package(Torch REQUIRED)
message(STATUS "PROBE_OK TORCH_LIBRARIES=${TORCH_LIBRARIES}")
EOF2
cmake -DCMAKE_PREFIX_PATH="$(python -c 'import torch.utils; print(torch.utils.cmake_prefix_path)')" ..
```

Before: `<checkout>/torch/share/cmake`, which does not exist; cmake exits 1
with "Could not find a package configuration file provided by Torch".
After: `<site-packages>/torch/share/cmake`; cmake exits 0 and prints
PROBE_OK with TORCH_LIBRARIES resolved. Reverting the patch restores the
failure, so the change is causal.

```
python test/test_utils.py TestCppExtensionUtils.test_cmake_prefix_path
lintrunner -a torch/utils/__init__.py test/test_utils.py
python test/test_public_bindings.py TestPublicBindings.test_correct_module_names
```

The test fails on an editable install without this commit: the prefix
resolves into the source checkout, which holds no `share/cmake`.

Co-authored-by: guptaishaan <[email protected]>

Authored with the assistance of Claude Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
pytorchmergebot pushed a commit to zklaus/pytorch that referenced this pull request Oct 13, 2026
`get_pytorch_dir()` derived the directory it passes as
`-DPYTORCH_INSTALL_DIR` from `torch.__file__`, so under a redirect-mode
editable install it pointed at the source checkout, which holds no `lib/`,
`include/` or `share/cmake` for the extension to build against. It now goes
through `get_file_path("torch")`, still under `realpath` so the rpaths it
bakes stay symlink-free.

Taken from pytorch#192559 by @guptaishaan. The import stays inside the function,
after the `TORCH_DEVICE_BACKEND_AUTOLOAD` guard, so the circular-import case
that comment describes is unaffected -- importing `torch._utils_internal`
still imports `torch`, just as `import torch` did.

Test Plan:

Not run: building torch_openreg needs a full source build of the extension.
The change substitutes one directory computation for another, both of which
resolve to `<site-packages>/torch` in a wheel install; they differ only for
the split layout, which is the case being fixed.

```
lintrunner -a test/cpp_extensions/open_registration_extension/torch_openreg/setup.py
```

Not affected by the `test_public_bindings` constraint that applies to
`torch.utils` in this stack: it only considers APIs whose `__module__`
starts with `torch.`, and this is a standalone setup script. The import is
function-local in any case.

Co-authored-by: guptaishaan <[email protected]>

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
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Nov 3, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants