Skip to content

Add RFC-0060: PyTorch install layouts - #109

Open
zklaus wants to merge 7 commits into
pytorch:masterfrom
zklaus:rfc-0060-install-layouts
Open

zklaus wants to merge 7 commits into
pytorch:masterfrom
zklaus:rfc-0060-install-layouts

Conversation

@zklaus

@zklaus zklaus commented Sep 10, 2026 •

Copy link
Copy Markdown

Review and tracking issue: pytorch/pytorch#203808

Summary of the RFC (drafted with an AI assistant, reviewed by the author)

PyTorch is installed in one of three layouts. In the wheel the compiled artifacts sit beside the Python sources; in an editable install scikit-build-core's redirect mode splits them; a standalone cmake --install has no Python sources at all. Code that derives paths from __file__ is right in the first layout and wrong in the other two, and none of the three is documented.

The RFC proposes one documentation page that names the three layouts and shows what each puts where, from listings of the shipped 2.14.0 artifacts and of real editable installs; one rule for in-tree code, carried by two helpers anchored on the import system (one for files the code reads, one for directories it hands to external tools); and a lint and an editable-install CI job that keep the rule true.

Status: the location helper landed in pytorch/pytorch#195587 and the editable-install CI job is in review as pytorch/pytorch#203390. The standalone build defaults that an earlier version of this RFC covered are split out and follow as separate PRs.

🤖 Generated with Claude Code

PyTorch is installed in one of three shapes (artifacts beside the Python
sources, split from them, or without them), and the documentation describes
the result of only one of the six commands that produce them. Code that
derives asset paths from __file__ is right in some shapes and wrong in
others, which is how seven call sites broke under editable installs after
the scikit-build-core migration.

The RFC documents the shapes from listings of the shipped 2.14.0 wheels and
libtorch zips and of real editable installs on Linux, macOS and Windows;
states two resolution rules for in-tree code (resources through
importlib.resources behind a thin helper, directories for external tools
through the existing location helper, both anchored on the import system);
proposes one documentation page linked from CONTRIBUTING.md and the C++
docs; and aligns the standalone cmake --install recipe and
tools/build_libtorch.py with the zips through three build defaults.

Opened as a draft for discussion. Authored with assistance from Claude Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
The per-directory table rested on file listings that lived outside the
repository. RFC-0060-assets/artifact-inventory.md now carries the sources,
the per-category counts across the 2.14.0 wheels, libtorch zips and
editable installs, the consumer groups, the provenance of each directory,
the generated Python files, and the CI consumers of the build_libtorch.py
prefix. RFC-0060-assets/list-wheel-contents.py regenerates the wheel and zip
listings for any release from the zip central directories over HTTP range
requests; it reproduces the 2.14.0 listings entry for entry.

The RFC references both and keeps only the facts its rules and proposals
rely on, so it shrinks by about 200 words with nothing dropped.

Authored with assistance from Claude Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@meta-cla meta-cla Bot added the cla signed label Sep 10, 2026
…nd anchor

Sequencing item 1 said the resource helper "lands with the first call site
that reads a file", which reads as if none existed. Six do: model_dump and
the export serde schema check read package data through the functional
importlib.resources API, and the inductor aoti_runtime sources and the two
jinja template directories are read relative to __file__. Every one of
those files is tracked and also CMake-installed, so under the split shape
it exists in both trees with identical bytes, which is why they work today
and why they are the both-trees case the helper's shim orders.

The enforcement sentence and the first metric named only
importlib.resources.files("torch"); the live users call read_text(), so
the lint and the metric now cover every direct importlib.resources call.

torchgen becomes a second anchor with the same two rules. It cannot import
torch, its packaged/ data is mirrored into the install tree only, and its
public get_torchgen_root() still derives from __file__, so it needs its own
copy of the anchor chain. It is listed as a separate sequencing item.

Evidence gathered on a scikit-build-core 1.0.0 redirect editable install.

Written with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
torch/_inductor/codecache.py reads csrc/inductor/aoti_runtime/model.h
relative to __file__ for static-linkage AOTI. That file is the only thing
PackageData.cmake installs under torch/csrc/, so under the split shape the
directory exists in both trees like torch/lib does, and the read is one
more both-trees resource site for the helper to take over.

Written 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
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)
@atalman
atalman marked this pull request as ready for review September 15, 2026 15:10
Comment thread RFC-0060-install-layouts.md Resolved
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)
pytorchmergebot pushed a commit to pytorch/pytorch 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)
pytorchmergebot pushed a commit to pytorch/pytorch 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)
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
Review feedback was that "Proposed Implementation" read as description with
the actual changes scattered through it. The section now opens with a
numbered change list (code, CI, documentation), followed by the three
layouts, the per-directory table, the resolution rule and placement. The
standalone build defaults (recipe BUILD_PYTHON/BUILD_TEST, protobuf_INSTALL,
the tools/build_libtorch.py prefix, the arm64 script, the standalone-layout
CI job) are split out into follow-up PRs that cite the page.

The text is written against scikit-build-core 1.1.1, which ships the
install-first __path__ order and the loader's paths attribute, so the shim
for older releases, its drawback and the __path__-order constraint are
gone. "Shape" is renamed "layout" and the layouts are named by role. The
Vocabulary subsection is dropped (the component taxonomy it relied on was
closed unmerged).

Restructured with an AI assistant; reviewed and edited by the author.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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 pytorch/pytorch 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
4. `torchgen` gets the same two helpers: `torchgen.gen.get_torchgen_root()`
re-anchored, and a resource entry point for `packaged/`.

**CI**

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is fine. We can perhaps go ahead an open a PR for this right now

the rules assume no more than it provides, nothing else decided.


## Resolution

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we remove or fill in the sections to be filled in.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think these sections are intended to document the outcome of the discussion with the project, which is still to come.

Comment thread RFC-0060-install-layouts.md Outdated
## Resolution
(to be filled in)

### Level of Support

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this section is something we want to fill in.

  • What is the update cadence for updating to next version of scikit-build-core ?
  • What is the maintenance model
  • Since we have a CI job running, can we auto update to latest scikit-build-core ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The section here also should be filled in after the community discussion, but I the questions you ask are important, so I have added a new subsection under the proposed implementation section.

atalman's review of 2026-10-27 asked three things: open the CI PR for the
editable-install job, remove or fill the "(to be filled in)" blocks, and
say how the scikit-build-core dependency is kept current (update cadence,
maintenance model, automatic updates).

The maintenance questions are answered in a new subsection, "The build
backend", at the end of Proposed Implementation rather than under Level of
Support: that heading is the 1-to-7 consensus score the process derives the
accepted/draft/shelved label from, so it stays open until the discussion
settles. The subsection states the floor-versus-pin split, the cadence (CI
pin follows each release, floor moves only when PyTorch needs a fix, with
1.1.1 and the just-released 1.1.2 as the two cases), project ownership of
the integration, and a scheduled pin bump in the style of the hash-update
PRs.

The Resolution block keeps what can be filled before a decision: Resolution
reads "open", Next Steps restates the landing order, Tracking issue holds a
placeholder until the pytorch/pytorch issue is filed with the CI PR. Level
of Support, Additional Context and Exceptions are dropped; they only make
sense after the decision, and only two merged RFCs carry them at all.

The landing-order paragraph under Changes is brought up to date: item 2
landed with pytorch/pytorch#195587, the rest of item 3 is tracked in
#195889, #195890 and #195891, and the 1.1.1 floor has been in place since
#200913.

Drafted with an AI assistant; reviewed and edited by the author.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
The Resolution block held a placeholder for the tracking issue. The issue
is now filed as pytorch/pytorch#203808: it asks for review of the proposal
and carries the implementation checklist, so it becomes the tracking issue
if the RFC is accepted.

Drafted with an AI assistant; reviewed by the author.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@atalman atalman added the commenting RFC is open for discussions label Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla signed commenting RFC is open for discussions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants