Skip to content

Anchor torch's installed artifacts on the import system, not on __file__ - #195587

Closed
zklaus wants to merge 7 commits into
pytorch:mainfrom
zklaus:fix-editable-install-path-lookups
Closed

zklaus wants to merge 7 commits into
pytorch:mainfrom
zklaus:fix-editable-install-path-lookups

Conversation

@zklaus

@zklaus zklaus commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator

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 (feat(editable): expose search paths on redirect loaders 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 fix(editable): deterministic install-first __path__ order in redirect mode 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_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

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

@pytorch-bot

pytorch-bot Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit c6ead00 with merge base 41b4c95 (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@jansel

jansel commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 49m 6s —— View job


Solid fix with a well-argued rationale, but the bin/ probe it hinges on doesn't exist on Windows, so the fix is inoperative there and the newly added test_cmake_prefix_path would fail on a Windows editable install — details and four other findings below.

Full review: PR #195587

PR Review: #195587

Summary

Replaces two ad-hoc importlib.metadata.distribution("torch") lookups with a single _installed_torch_path() helper that filters candidates on METADATA/absolute/exists, then applies get_file_path to cmake_prefix_path, the inductor MPS header path, and torch_openreg's PYTORCH_INSTALL_DIR. The analysis in the PR body is unusually careful and the METADATA-vs-PKG-INFO discrimination is the right call, but the chosen probe (bin/) is not portable, the new error message gives advice the user cannot act on, and the logic the PR body describes testing across four synthetic layouts ships with no unit test.

Infrastructure

torch/_utils_internal.py:94 — probing bin/ makes the fix a no-op on Windows.

_compute_torch_parent resolves the installed tree by asking for <installed torch>/bin and requiring it to exist. torch/bin/ is not shipped in a default Windows build:

  • torch/CMakeLists.txt:23-27 selects libshm_windows on MSVC, and torch/lib/libshm_windows/CMakeLists.txt installs only into lib/ and include/ — the install(TARGETS torch_shm_manager DESTINATION "bin") at torch/lib/libshm/CMakeLists.txt:74 is on the non-MSVC path only.
  • The other DESTINATION bin producers are all off by default: cmake/public/utils.cmake:242 is reached only under BUILD_BINARY (CMakeLists.txt:332, OFF), the test/cpp/** rules under BUILD_TEST, and CMakeLists.txt:1620 under BUILD_BUNDLE_PTXAS (CMakeLists.txt:523-524, OFF; enabled only for CUDA manywheels at .ci/manywheel/build_env_setup.py:159).

So on a Windows redirect-mode editable install the probe returns None and _compute_torch_parent falls through to os.path.dirname(torch_dir) — the source checkout, which is exactly the wrong answer this PR exists to eliminate. cmake_prefix_path still resolves to <checkout>/torch/share/cmake, find_package(Torch) still fails, and the new test_cmake_prefix_path fails with it.

lib/ is a strictly better anchor: torch/CMakeLists.txt:450 installs torch_python into TORCH_INSTALL_LIB_DIR (default lib, torch/CMakeLists.txt:19-21) on every platform, and the METADATA filter — not the directory name — is what excludes a checkout's leftover .egg-info. Please also state in a comment why the chosen directory is the invariant, since the next person to touch this needs to know the probe is load-bearing.

Fix this →

torch/__init__.py:442 — the error message's remediation is not actionable.

"Set USE_GLOBAL_DEPS=0 to skip this preload." — USE_GLOBAL_DEPS is a hardcoded module constant (torch/_utils_internal.py:334) read at torch/__init__.py:516. There is no os.environ lookup for it anywhere, so a user hitting this error cannot set it; the only lever is replacing _utils_internal.py, which is an fbcode build mechanism, not a user action. Either drop that sentence or point at something that works. (The spin clean half of the message checks out — .gitignore:72 lists torch.egg-info/ and tools/clean.py removes it.)

API Design

torch/_utils_internal.py:69 vs torch/__init__.py:428 — preferring distribution metadata over beside_module can now cross-link two installations.

sorted() is stable, so the METADATA sort only reorders when a PKG-INFO candidate precedes a METADATA one — but that is precisely the mixed case: a checkout carrying a leftover .egg-info and an in-tree build, sitting ahead of a separately pip-installed torch in site-packages. Previously beside_module won whenever it existed, which is self-consistent: torch._C is imported at torch/__init__.py:518 from the same directory as __init__.py, so preloading the library next to __init__.py always matched the extension about to be loaded. Under the new code that pairing is broken — libtorch_global_deps comes from site-packages while _C comes from the checkout, which is an ABI mismatch rather than the stale-library warning the PR body is aiming at.

In redirect mode the PR's preference is the correct one, because scikit-build-core installs _C into SKBUILD_PLATLIB_DIR/torch (torch/CMakeLists.txt:471-476), not beside __init__.py. That is the real invariant worth encoding: the preloaded library must live beside the _C that will be imported, and neither beside_module nor the distribution expresses it directly. importlib.util.find_spec("torch._C") answers it authoritatively without importing the extension, and would be correct in both layouts. At minimum, please say in the comment at torch/__init__.py:412-417 that the distribution is being trusted as a proxy for where _C lives, so the assumption is visible when it next breaks.

Testing

No unit test for _installed_torch_path. The PR body enumerates four synthetic distribution layouts and a three-candidate real environment, and correctly identifies that an earlier revision filtering only on absolute-and-exists returned the wrong tree for the first layout. That is exactly the behavior a test should pin: METADATA beats PKG-INFO, non-absolute is rejected, non-existent is rejected, and ordering is independent of sys.path position. All of it is reachable with a stub object exposing read_text and locate_file plus a patch of importlib.metadata.distributions — no build layout required. Without it, the METADATA filter is a subtle invariant with nothing preventing a future simplification from reintroducing the bug the PR body says it already hit once.

test/test_utils.py:964-967 — the test does not exercise the bug and will fail in at least one shipped configuration. On a plain wheel cmake_prefix_path was already correct, so this asserts the case that never broke; the redirect-mode split layout it is meant to protect is untested. Separately, TorchConfig.cmake is installed at caffe2/CMakeLists.txt:1488-1491, which sits inside the if(NOT BUILD_LIBTORCHLESS) block opened at line 854 and closed at line 2196 (the body is unindented, so this is easy to misread). BUILD_PYTHON_ONLY=1 sets BUILD_LIBTORCHLESS=ON (cmake/EnvVarForwarding.cmake:304-307), so a torch_no_python wheel ships no share/cmake/Torch/ and this assertion fails there. The IS_FBCODE skip does not cover it — moderate confidence on whether that config runs test_utils.py in CI today, but the guard is cheap and the failure mode is confusing.

No regression test for the new RuntimeError path at torch/__init__.py:437-443, which is the one genuinely new behavior in _load_global_deps.

Code Quality

test/cpp_extensions/open_registration_extension/torch_openreg/setup.py:41 — silently drops realpath. The old code was os.path.dirname(os.path.realpath(torch.__file__)); get_file_path builds on os.path.abspath (torch/_utils_internal.py:82), so symlinks are no longer resolved. PYTORCH_INSTALL_DIR feeds target_link_directories (torch_openreg/csrc/CMakeLists.txt:18) and Torch_DIR (CMakeLists.txt:30), where an unresolved symlink can change baked rpaths. If dropping realpath is deliberate, say so; otherwise wrap the call.

Also note the accompanying comment is slightly off: from torch._utils_internal import get_file_path still triggers a full import torch via torch/_utils_internal.py:12, so the TORCH_DEVICE_BACKEND_AUTOLOAD=0 guard above it remains necessary for the reason the original comment gave. The comment reads as if the import were avoided.

torch/_utils_internal.py:76 — os.path.exists where the old code used os.path.isdir. Both call sites (bin, and share/cmake via _compute_torch_parent) are directories; a stray file named bin now satisfies the probe. Use os.path.isdir when the component is known to be a directory, or take a predicate.

torch/_utils_internal.py:52-55 — dead try/except. importlib.metadata is stdlib from 3.8 and pyproject.toml:348 pins requires-python = ">=3.10", so the import cannot fail. The except Exception around it suggests to a reader that it can.

torch/_utils_internal.py:94-96 — roundabout. Resolving <installed>/bin and then stripping two components to get back to the parent is harder to follow than resolving <installed> once and testing the subdirectory. Given _installed_torch_path already accepts zero components, p = _installed_torch_path() followed by an isdir(os.path.join(p, ...)) check reads more directly and makes the returned value's meaning obvious.

Recommendation

Request Changes

The Windows bin/ gap means the fix does not deliver on one of its two stated call sites for a whole platform, and it takes the new test down with it. The missing unit test for _installed_torch_path is the other blocker: the PR body documents that the METADATA filter was added in response to a concrete failure of a simpler predicate, which is the clearest possible argument that the predicate needs a test. The USE_GLOBAL_DEPS=0 advice and the realpath drop are quick corrections. The precedence question under API Design is worth a reply before merge even if the conclusion is that the current behavior is preferred.

| Branch: `fix-editable-install-path-lookups`

@ezyang ezyang added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Sep 10, 2026
@zklaus
zklaus force-pushed the fix-editable-install-path-lookups branch from 1534950 to 5b0d2cf Compare September 11, 2026 14:08
@jansel jansel added the topic: not user facing topic category label Sep 12, 2026
saud5150 added a commit to saud5150/pytorch that referenced this pull request Sep 13, 2026
Fixes pytorch#196233.

## Summary

`cpp_wrapper_mps.py` generated AOTI code that ignored the return codes from:

- `aoti_torch_mps_create_shader_library`
- `aoti_torch_mps_get_kernel_function`

When shader compilation failed, `aoti_torch_mps_create_shader_library` returned an error without initializing `library_handle`. The generated wrapper then passed the null handle to `aoti_torch_mps_get_kernel_function`, causing a SIGSEGV and discarding the original Metal compiler diagnostic.

Wrap both calls with `AOTI_TORCH_ERROR_CODE_CHECK`, matching every other `cpp_wrapper` backend (`cpp_wrapper_cpu.py`, `cpp_wrapper_cpu_array_ref.py`, `cpp_wrapper_gpu.py`) and the hand-written consumer of this same shim API in `test/cpp_extensions/libtorch_agn_2_14_extension/csrc/mps/mps_set_arg_bytes_test.cpp`, which wraps every one of these calls. `cpp_wrapper_mps.py` was the only `cpp_wrapper` backend that did not reference the macro at all.

Also move the shader-library handle into its `unique_ptr` immediately after a successful create call. With the new error check, ownership must be established before the subsequent kernel-function lookup to avoid leaking the library on failure.

Update the `codegen_additional_funcs` docstring to match the generated code.

## Test plan

```bash
python test/inductor/test_mps_basic.py MPSBasicTestsAOTI.test_shader_compile_error_raises
python test/inductor/test_mps_basic.py MPSBasicTestsAOTI.test_kernel_function_lookup_error_raises
python test/inductor/test_mps_basic.py
python test/inductor/test_aot_inductor.py AOTInductorTestABICompatibleMps
spin quicklint
```

### Regression coverage

One test per shim call. Each forces a real failure and asserts the diagnostic
reaches Python; each segfaults without the fix.

- `test_shader_compile_error_raises` injects invalid MSL, so
  `aoti_torch_mps_create_shader_library` fails.
- `test_kernel_function_lookup_error_raises` renames the kernel symbol, so the
  library compiles but `aoti_torch_mps_get_kernel_function` cannot find
  `generated_kernel`. This covers the second call, which the first test never
  reaches because it fails earlier.

Before this change both segfault with no output:

```bash
$ python test/inductor/test_mps_basic.py MPSBasicTestsAOTI.test_shader_compile_error_raises; echo "exit=$?"
exit=139
$ python test/inductor/test_mps_basic.py MPSBasicTestsAOTI.test_kernel_function_lookup_error_raises; echo "exit=$?"
exit=139
```

After:

```bash
$ python test/inductor/test_mps_basic.py MPSBasicTestsAOTI.test_shader_compile_error_raises MPSBasicTestsAOTI.test_kernel_function_lookup_error_raises
..
----------------------------------------------------------------------
Ran 2 tests in 4.642s

OK
```

### Results

| Test | Result |
|---|---|
| `test/inductor/test_mps_basic.py` | 63 run, 63 passed |
| `test/inductor/test_aot_inductor.py` (MPS class) | 386 run: 196 passed, 157 skipped, 33 expected failures |
| `spin quicklint` | Passed |

## Environment

- macOS 15.5, arm64
- Apple M4 Pro
- `2.15.0a0+gitf62c80c`, built from source
- No CUDA available; non-MPS `test_aot_inductor.py` device classes were not run locally

Note: pytorch#195587 currently prevents editable builds from resolving shader `#include`s because `torch/include` is absent. Full-suite results above used a local `torch/include/c10 -> ../../c10` symlink. Without that workaround, Metal shader compilation fails due to the unrelated issue; this PR now reports the shim error rather than segfaulting. The two regression tests pass with or without the workaround.

## BC-breaking?

No. Successful generated code is unchanged; only error handling on failure paths changes.

## Follow-ups

Out of scope for this PR:

- Add return-code checks for other emitted `aoti_torch_mps_*` calls.
- Fix JIT `cpp_wrapper` on MPS, which currently fails on main with `undeclared identifier 'get_mps_lib_0_handle'`.

***

The implementation was prepared with an AI assistant (Claude) and reviewed and validated by the author. The reproduction, negative control, and suite runs were executed locally on the environment above.

Co-Authored-By: Claude Opus 5 <[email protected]>
@zklaus zklaus changed the title Resolve torch's installed artifacts by distribution, not by leftovers Anchor torch's installed artifacts on the import system, not on __file__ Sep 14, 2026
@zklaus

zklaus commented Sep 14, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, @jansel for initiating the review. The precedence point changed the approach, not just the probe, so the present version of this PR is substantially changed from the one that was reviewed. Summarizing those changes with the help of AI:

Mechanism. The distribution lookup is gone. torch_parent is anchored on importlib.util.find_spec("torch._C").origin, the anchor torch/__init__.py already uses for the Windows DLL directory, so assets resolve from the directory _C is imported from and the mixed layout you describe cannot cross-link. _load_global_deps goes through get_file_path like every other consumer. Ahead of the spec, if the editable loader exposes __loader__.paths (scikit-build/scikit-build-core#1567, in review), the helper takes the entry that is not the checkout and holds lib/; no release has that attribute yet. This is the order RFC-0060 (pytorch/rfcs#109) prescribes. No spec (BUILD_LIBTORCH_WHL, frozen builds) falls back to __file__ as before.

Leftover artifacts. Instead of reasoning around stale build output and egg-infos, the helper detects them: in a checkout whose _C resolves elsewhere, any 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, because the editable finder maps CMake-installed modules by name to the install tree; the stale copies are never imported, they only mislead tooling that reads metadata or __file__.

Smaller items. The missing-library case raises OSError, which is what CDLL raised and what collect_env catches; the message no longer mentions USE_GLOBAL_DEPS. realpath is back in the openreg setup and its comment no longer suggests the import avoids import torch. The bin/ probe, isdir, the dead try and the unit test for _installed_torch_path are moot: that code is gone, and its replacement has its own tests.

Tests. test_cmake_prefix_path stays. New tests pin that torch_parent follows the extension module, that the loader-paths step picks the install tree even when the checkout appears under a symlinked spelling (a checkout has a tracked torch/lib, so identity excludes it, not lib/), that the stale-artifact detector finds exactly the expected paths, and that the OSError fires. Run on a Linux redirect-mode editable install against the pushed head, and on Windows against the _C-spec revision, where the warning stayed silent on a clean checkout. Agreed that test_cmake_prefix_path asserts a case a wheel never broke; it bites on editable installs, which is where it ran and where #195888 will run it. On BUILD_LIBTORCHLESS: that build installs no TorchConfig.cmake, but there is no Python-visible flag for it and no CI job runs test_utils.py that way, so I left the test unguarded rather than add a speculative skip.

pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
…er (#196634)

Fixes #196233.

## Summary

`cpp_wrapper_mps.py` generated AOTI code that ignored the return codes from:

- `aoti_torch_mps_create_shader_library`
- `aoti_torch_mps_get_kernel_function`

When shader compilation failed, `aoti_torch_mps_create_shader_library` returned an error without initializing `library_handle`. The generated wrapper then passed the null handle to `aoti_torch_mps_get_kernel_function`, causing a SIGSEGV and discarding the original Metal compiler diagnostic.

Wrap both calls with `AOTI_TORCH_ERROR_CODE_CHECK`, matching every other `cpp_wrapper` backend (`cpp_wrapper_cpu.py`, `cpp_wrapper_cpu_array_ref.py`, `cpp_wrapper_gpu.py`) and the hand-written consumer of this same shim API in `test/cpp_extensions/libtorch_agn_2_14_extension/csrc/mps/mps_set_arg_bytes_test.cpp`, which wraps every one of these calls. `cpp_wrapper_mps.py` was the only `cpp_wrapper` backend that did not reference the macro at all.

Also move the shader-library handle into its `unique_ptr` immediately after a successful create call. With the new error check, ownership must be established before the subsequent kernel-function lookup to avoid leaking the library on failure.

Update the `codegen_additional_funcs` docstring to match the generated code.

## Test plan

```bash
python test/inductor/test_mps_basic.py MPSBasicTestsAOTI.test_shader_compile_error_raises
python test/inductor/test_mps_basic.py MPSBasicTestsAOTI.test_kernel_function_lookup_error_raises
python test/inductor/test_mps_basic.py
python test/inductor/test_aot_inductor.py AOTInductorTestABICompatibleMps
spin quicklint
```

### Regression coverage

One test per shim call. Each forces a real failure and asserts the diagnostic
reaches Python; each segfaults without the fix.

- `test_shader_compile_error_raises` injects invalid MSL, so
  `aoti_torch_mps_create_shader_library` fails.
- `test_kernel_function_lookup_error_raises` renames the kernel symbol, so the
  library compiles but `aoti_torch_mps_get_kernel_function` cannot find
  `generated_kernel`. This covers the second call, which the first test never
  reaches because it fails earlier.

Before this change both segfault with no output:

```bash
$ python test/inductor/test_mps_basic.py MPSBasicTestsAOTI.test_shader_compile_error_raises; echo "exit=$?"
exit=139
$ python test/inductor/test_mps_basic.py MPSBasicTestsAOTI.test_kernel_function_lookup_error_raises; echo "exit=$?"
exit=139
```

After:

```bash
$ python test/inductor/test_mps_basic.py MPSBasicTestsAOTI.test_shader_compile_error_raises MPSBasicTestsAOTI.test_kernel_function_lookup_error_raises
..
----------------------------------------------------------------------
Ran 2 tests in 4.642s

OK
```

### Results

| Test | Result |
|---|---|
| `test/inductor/test_mps_basic.py` | 63 run, 63 passed |
| `test/inductor/test_aot_inductor.py` (MPS class) | 386 run: 196 passed, 157 skipped, 33 expected failures |
| `spin quicklint` | Passed |

## Environment

- macOS 15.5, arm64
- Apple M4 Pro
- `2.15.0a0+gitf62c80c`, built from source
- No CUDA available; non-MPS `test_aot_inductor.py` device classes were not run locally

Note: #195587 currently prevents editable builds from resolving shader `#include`s because `torch/include` is absent. Full-suite results above used a local `torch/include/c10 -> ../../c10` symlink. Without that workaround, Metal shader compilation fails due to the unrelated issue; this PR now reports the shim error rather than segfaulting. The two regression tests pass with or without the workaround.

## BC-breaking?

No. Successful generated code is unchanged; only error handling on failure paths changes.

## Follow-ups

Out of scope for this PR:

- Add return-code checks for other emitted `aoti_torch_mps_*` calls.
- Fix JIT `cpp_wrapper` on MPS, which currently fails on main with `undeclared identifier 'get_mps_lib_0_handle'`.

***

The implementation was prepared with an AI assistant (Claude) and reviewed and validated by the author. The reproduction, negative control, and suite runs were executed locally on the environment above.

Pull Request resolved: #196634
Approved by: https://github.com/malfet

Co-authored-by: Claude Opus 5 <[email protected]>
Comment thread test/test_utils.py Resolved

@atalman atalman left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

lgtm

…h raises

The first landing of this PR was reverted because torch.utils computed
cmake_prefix_path through get_file_path at import time, and the internal
_utils_internal override raises OSError for a resource it does not ship,
so `import torch.utils` failed there. The OSS get_file_path never raises,
which is why CI and the editable-install tests were green.

cmake_prefix_path now goes through a small resolver that tries
get_file_path and, on OSError, returns the historical __file__-derived
path, the exact expression the module used before this PR. The other
import-time user of the anchor, _load_global_deps, is gated on
USE_GLOBAL_DEPS, which the internal override turns off, and the mps and
openreg call sites are not import-time, so no other site needs the guard.

A test mocks a raising get_file_path and checks that the resolver returns
the fallback path.

Authored with an AI assistant; the diff was reviewed by hand.

Test Plan:

On an editable install (the two files overlaid onto the installed tree):

```
python -c "import torch.utils; print(torch.utils.cmake_prefix_path)"
python -m pytest test/test_utils.py -k falls_back_when_get_file_path_raises
spin quicklint
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)
The second landing was reverted for the same reason as the first: inside
Meta, `torch._utils_internal.get_file_path` raises when `torch/share/cmake`
is not packaged, and `import torch.utils` called it at import time. The
fallback added after the first revert caught OSError, which is what the
revert comment named; the internal analysis of the second revert shows the
exception is a ValueError. The exception type belongs to that build
system, so the fallback no longer names one: any failure of the lookup
yields the historical `__file__`-derived path and the import succeeds.
The OSS get_file_path is a path join over an import-time constant and
cannot raise, so nothing is masked there.

The test now exercises both an OSError and a ValueError.

Authored with an AI assistant; the diff was reviewed by hand.

Test Plan:

On an editable install, with the two files overlaid on the installed tree:

```
python -c "import torch.utils; print(torch.utils.cmake_prefix_path)"
python -m pytest test/test_utils.py -k falls_back_when_get_file_path_raises -v
spin quicklint
```

Both subtests pass. With the previous `except OSError` restored, the
ValueError subtest fails.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased fix-editable-install-path-lookups onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout fix-editable-install-path-lookups && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the fix-editable-install-path-lookups branch from 575c2b7 to c6ead00 Compare October 13, 2026 15:12
@zklaus

zklaus commented Oct 14, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -f "The torchtitan-test break is unrelated (see #200511) and meta internal import status confirmed green with @atalman offline."

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

zklaus added a commit to zklaus/pytorch that referenced this pull request Oct 14, 2026
…rsistent tree

The build-system floor moves from 1.0 to 1.1.1, together with the CI pins
(.ci/docker/requirements-ci.txt, the Windows installer scripts, the riscv
cross image), so this rebuilds the Docker images. Two features of the new
release are switched on at the same time; the Import-Name metadata (PEP 794)
that 1.1 can also emit is left for a follow-up, since it raises the wheels'
Metadata-Version to 2.5 and deserves its own compatibility check.

Editable installs now use editable.rebuild-dir = "build/install/{wheel_tag}"
with rebuild = false. The compiled artifacts are installed into a persistent
tree under build/ and the editable wheel shrinks to the redirect. Before,
every `pip install -e .` zipped the whole install tree into a wheel that pip
unpacked and discarded, several GB and about five minutes on a debug build
(pytorch#196619). The tree is keyed by wheel tag so editable installs for several
interpreters can share one checkout, and `spin clean` removes it with the
rest of build/. Rebuild-on-import stays off; torch.__loader__.rebuild()
refreshes the tree on demand. CONTRIBUTING.md describes the new location.

The sdist build sets sdist.resolve-symlinks = "error", so a symlink among the
included files fails the build by name instead of being silently copied.
Every tracked symlink is handled explicitly: seven are excluded
(.dockerignore, the three AGENTS.md links, XNNPACK's xngen alias, the
cudnn_frontend .claude directory link that the old default duplicated, and a
flatbuffers test fixture), and docs/requirements.txt is force-included from
its target in .ci. The release workflow used to make that replacement in the
working tree before both of its archives were built; it now does so only on
the staged copy that becomes the plain tarball, so the PEP 517 sdist is built
from the pristine checkout and the local `python -m build --sdist` and the
release sdist are produced the same way. The sdist member list changes by
exactly those eight entries.

1.1.0 and 1.1.1 also carry the nested-.gitignore walk fix (pytorch#194945,
scikit-build/scikit-build-core#1542), repository-boundary handling for ignore
rules (scikit-build-core#1585, pytorch#1594) and the deterministic, install-first
__path__ with a public __loader__.paths for redirect-mode packages (pytorch#1566,
pytorch#1567), which the resolution helpers from pytorch#195587 use.

Not in this change: the blanket third_party/** include block in sdist.include
stays. Without it, 1.1.1 drops 389 more tracked files, among them cpuinfo's
deps/clog sources and PeachPy's instruction tables that NNPACK's code
generation imports, so retiring it needs targeted includes and a
build-from-sdist test of its own.

Requires pytorch#195587: before it, get_file_path found the editable install tree
through the distribution's location under site-packages; with rebuild-dir
that tree moves to build/install/<wheel tag>/, where only the import-system
anchor finds it.

Fixes pytorch#194945. Fixes pytorch#196619.

Test Plan

On top of main at the pytorch#195587 merge (7402bdb) with scikit-build-core
1.1.1, CPU-only Release build on Linux, Python 3.10:

```
python -m build --sdist --no-isolation
python -m pip wheel . -v --no-build-isolation --no-deps -w /tmp/wheel
python -m pip install -e . -v --no-build-isolation
python -m pytest test/test_utils.py -k "PathResolution or cmake_prefix_path or get_file_path"
spin lint
```

The sdist builds with the symlink check on; of the six tracked symlinks only
docs/requirements.txt appears among its members, as a regular file copied
from its .ci target. The editable install takes 22 s from an existing
build directory, puts the artifacts under
build/install/cp310-cp310-linux_x86_64/ with nothing but the redirect in
site-packages; `import torch` from outside the checkout loads _C from that
tree, torch.__loader__.paths lists it first, and torch.utils.cmake_prefix_path
resolves into it with TorchConfig.cmake present. The six path-resolution
tests pass against that editable install.

Authored with an AI assistant; the diff was reviewed by hand.

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

The build-system floor moves from 1.0 to 1.1.1, together with the CI pins
(.ci/docker/requirements-ci.txt, the Windows installer scripts, the riscv
cross image), so this rebuilds the Docker images. Two features of the new
release are switched on at the same time; the Import-Name metadata (PEP 794)
that 1.1 can also emit is left for a follow-up, since it raises the wheels'
Metadata-Version to 2.5 and deserves its own compatibility check.

Editable installs now use editable.rebuild-dir = "build/install/{wheel_tag}"
with rebuild = false. The compiled artifacts are installed into a persistent
tree under build/ and the editable wheel shrinks to the redirect. Before,
every `pip install -e .` zipped the whole install tree into a wheel that pip
unpacked and discarded, several GB and about five minutes on a debug build
(pytorch#196619). The tree is keyed by wheel tag so editable installs for several
interpreters can share one checkout, and `spin clean` removes it with the
rest of build/. Rebuild-on-import stays off; torch.__loader__.rebuild()
refreshes the tree on demand. CONTRIBUTING.md describes the new location.

The tree is keyed by wheel tag only: scikit-build-core formats rebuild-dir
with the same keys as build-dir and has no `{build_dir}` key, so a second
build tree selected through `SKBUILD_BUILD_DIR` (another CUDA toolkit, a Debug
build) shares `build/install/<wheel tag>/` with the first and the last
editable install wins. Setting `SKBUILD_EDITABLE_REBUILD_DIR` to a directory
under that build tree keeps them apart; CONTRIBUTING.md says so. The proper
fix is a `{build_dir}` template key upstream, which we will ask for
separately.

The sdist build sets sdist.resolve-symlinks = "error", so a symlink among the
included files fails the build by name instead of being silently copied.
Every tracked symlink is handled explicitly: seven are excluded
(.dockerignore, the three AGENTS.md links, XNNPACK's xngen alias, the
cudnn_frontend .claude directory link that the old default duplicated, and a
flatbuffers test fixture), and docs/requirements.txt is force-included from
its target in .ci. The release workflow used to make that replacement in the
working tree before both of its archives were built; it now does so only on
the staged copy that becomes the plain tarball, so the PEP 517 sdist is built
from the pristine checkout and the local `python -m build --sdist` and the
release sdist are produced the same way. The sdist member list changes by
exactly those eight entries.

1.1.0 and 1.1.1 also carry the nested-.gitignore walk fix (pytorch#194945,
scikit-build/scikit-build-core#1542), repository-boundary handling for ignore
rules (scikit-build-core#1585, pytorch#1594) and the deterministic, install-first
__path__ with a public __loader__.paths for redirect-mode packages (pytorch#1566,

Not in this change: the blanket third_party/** include block in sdist.include
stays. Without it, 1.1.1 drops 389 more tracked files, among them cpuinfo's
deps/clog sources and PeachPy's instruction tables that NNPACK's code
generation imports, so retiring it needs targeted includes and a
build-from-sdist test of its own.

Requires pytorch#195587: before it, get_file_path found the editable install tree
through the distribution's location under site-packages; with rebuild-dir
that tree moves to build/install/<wheel tag>/, where only the import-system
anchor finds it.

Fixes pytorch#194945. Fixes pytorch#196619.

Test Plan

On top of main at the pytorch#195587 merge (7402bdb) with scikit-build-core
1.1.1, CPU-only Release build on Linux, Python 3.10:

```
python -m build --sdist --no-isolation
python -m pip wheel . -v --no-build-isolation --no-deps -w /tmp/wheel
python -m pip install -e . -v --no-build-isolation
python -m pytest test/test_utils.py -k "PathResolution or cmake_prefix_path or get_file_path"
spin lint
```

The sdist builds with the symlink check on; of the six tracked symlinks only
docs/requirements.txt appears among its members, as a regular file copied
from its .ci target. The editable install takes 22 s from an existing
build directory, puts the artifacts under
build/install/cp310-cp310-linux_x86_64/ with nothing but the redirect in
site-packages; `import torch` from outside the checkout loads _C from that
tree, torch.__loader__.paths lists it first, and torch.utils.cmake_prefix_path
resolves into it with TorchConfig.cmake present. The six path-resolution
tests pass against that editable install.

Authored with an AI assistant; the diff was reviewed by hand.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
pytorchmergebot pushed a commit that referenced this pull request Oct 22, 2026
Go through the following checklist
- [x] Passes lint (`spin fixlint`)
- [x] ~Added/updated tests~
- [x] Updated documentation (if applicable)
- [x] ~Included benchmark results (for PRs impacting perf)~

---

## Linked issue or supporting maintainer

<!-- Keep the one line that applies and delete the others. Link an issue labeled "actionable", or name the maintainer who agreed to this change beforehand. PRs with neither will be automatically closed, unless the author has write access to the repo. -->

Fixes #194945. Fixes #196619.

## BC-breaking?

<!-- If this change breaks backward compatibility, describe the impact and migration path. Otherwise, write "No". -->
No. Wheels and sdists are produced with the same contents and metadata as before (the sdist loses eight symlinks that nothing consumes; docs/requirements.txt has the same content). For developers, an editable install now keeps its compiled artifacts in build/install/<wheel tag>/ instead of site-packages, so deleting build/ removes them, and code that located the install tree through the distribution's site-packages path has to use the import-system anchor from #195587 instead (in-tree code already does). Building from source needs scikit-build-core 1.1.1, available on PyPI and conda-forge.

## Summary (human written only)

<!-- Point to the issue for relevant design discussion. If not discussed there (rare), add up to one paragraph. Overly verbose descriptions will be considered spam. -->

This PR raises the floor for scikit-build-core from 1.0 to 1.1.1, which is a release that includes a number of improvements that target issues specifically surfaced from Pytorch.

## Agent details (if applicable)

<!-- You can add here the details from your agent related to this PR. -->

The build-system floor moves from 1.0 to 1.1.1, together with the CI pins (.ci/docker/requirements-ci.txt, the Windows installer scripts, the riscv cross image), so this rebuilds the Docker images. Two features of the new release are switched on at the same time; the Import-Name metadata (PEP 794) that 1.1 can also emit is left for a follow-up, since it raises the wheels' Metadata-Version to 2.5 and deserves its own compatibility check.

Editable installs now use editable.rebuild-dir = "build/install/{wheel_tag}" with rebuild = false. The compiled artifacts are installed into a persistent tree under build/ and the editable wheel shrinks to the redirect. Before, every `pip install -e .` zipped the whole install tree into a wheel that pip unpacked and discarded, several GB and about five minutes on a debug build (#196619). The tree is keyed by wheel tag so editable installs for several interpreters can share one checkout, and `spin clean` removes it with the rest of build/. Rebuild-on-import stays off; torch.__loader__.rebuild() refreshes the tree on demand. CONTRIBUTING.md describes the new location.
The tree is keyed by wheel tag only: scikit-build-core formats rebuild-dir with the same keys as build-dir and has no `{build_dir}` key, so a second build tree selected through `SKBUILD_BUILD_DIR` (another CUDA toolkit, a Debug build) shares `build/install/<wheel tag>/` with the first and the last editable install wins. Setting `SKBUILD_EDITABLE_REBUILD_DIR` to a directory under that build tree keeps them apart; CONTRIBUTING.md says so. The proper fix is a `{build_dir}` template key upstream, which we will ask for separately.

The sdist build sets sdist.resolve-symlinks = "error", so a symlink among the included files fails the build by name instead of being silently copied. Every tracked symlink is handled explicitly: seven are excluded (.dockerignore, the three AGENTS.md links, XNNPACK's xngen alias, the cudnn_frontend .claude directory link that the old default duplicated, and a flatbuffers test fixture), and docs/requirements.txt is force-included from its target in .ci. The release workflow used to make that replacement in the working tree before both of its archives were built; it now does so only on the staged copy that becomes the plain tarball, so the PEP 517 sdist is built from the pristine checkout and the local `python -m build --sdist` and the release sdist are produced the same way. The sdist member list changes by exactly those eight entries.

1.1.0 and 1.1.1 also carry the nested-.gitignore walk fix (#194945, scikit-build/scikit-build-core#1542), repository-boundary handling for ignore rules (scikit-build-core#1585, #1594) and the deterministic, install-first __path__ with a public __loader__.paths for redirect-mode packages (#1566, #1567), which the resolution helpers from #195587 use.

Not in this change: the blanket third_party/** include block in sdist.include stays. Without it, 1.1.1 drops 389 more tracked files, among them cpuinfo's deps/clog sources and PeachPy's instruction tables that NNPACK's code generation imports, so retiring it needs targeted includes and a build-from-sdist test of its own.

Requires #195587: before it, get_file_path found the editable install tree through the distribution's location under site-packages; with rebuild-dir that tree moves to build/install/<wheel tag>/, where only the import-system anchor finds it.

### Test Plan

On top of main at the #195587 merge (7402bdb) with scikit-build-core 1.1.1, CPU-only Release build on Linux, Python 3.10:

```
python -m build --sdist --no-isolation
python -m pip wheel . -v --no-build-isolation --no-deps -w /tmp/wheel
python -m pip install -e . -v --no-build-isolation
python -m pytest test/test_utils.py -k "PathResolution or cmake_prefix_path or get_file_path"
spin lint
```

The sdist builds with the symlink check on; of the six tracked symlinks only docs/requirements.txt appears among its members, as a regular file copied from its .ci target. The editable install takes 22 s from an existing build directory, puts the artifacts under
build/install/cp310-cp310-linux_x86_64/ with nothing but the redirect in site-packages; `import torch` from outside the checkout loads _C from that tree, torch.__loader__.paths lists it first, and torch.utils.cmake_prefix_path resolves into it with TorchConfig.cmake present. The six path-resolution tests pass against that editable install.

Authored with an AI assistant; the diff was reviewed by hand.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: #200913
Approved by: https://github.com/Skylion007, https://github.com/benjaminglass1, https://github.com/atalman
zklaus added a commit to zklaus/rfcs that referenced this pull request Nov 3, 2026
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)
zklaus added a commit to zklaus/pytorch that referenced this pull request Nov 13, 2026
## Linked issue or supporting maintainer

Part of pytorch#195891

## BC-breaking?

No

## Summary (human written only)

This PR removes instances of legacy `__file__` based lookups in tests in favor of the modern importlib based alternatives that are compatible with editable installs in redirect mode.

## Agent details (if applicable)

Under a redirect-mode editable install, `torch.__file__` points into the source tree while `lib/`, `include/`, `share/cmake` and the dist-info are installed elsewhere. Several test-side lookups derived these locations from `__file__` and so looked in the source tree, where they do not exist or where only stale leftovers of an earlier build exist.

`find_library_location` now asks `torch._utils_internal.get_file_path`, which is anchored on the import system (pytorch#195587), before falling back to `build/lib`. `test_xpu` finds the include directory the same way, and `test_aot_inductor_package` passes `torch.utils.cmake_prefix_path` as `CMAKE_PREFIX_PATH` instead of the package directory. `test_license` locates the dist-info through `importlib.metadata`, since it is distribution metadata rather than a file inside the package; a stale `torch.egg-info` on `sys.path` also counts as a "torch" distribution, so only dist-info directories are kept.

The editable CI job already runs `test_fx` and `test_license`. Until now `test_fx` found the torchbind test library only through the `build/lib` fallback and `test_license` skipped its dist-info test, so both start exercising the installed layout with this change. The job also prints sccache stats through `print_sccache_stats` like the other jobs.

An alternative for `test_license` was `get_file_path("torch", "..")`, but that assumes the dist-info is a sibling of the installed package files, which is the assumption this change removes elsewhere.

Tracked in pytorch#195887.

### Test Plan

Editable install of this commit on Linux x86_64, Python 3.12, CPU-only, with `BUILD_TEST=1` so that the torchbind test library is built. The checkout also held a stale `torch/lib/libtorchbind_test.so` and a stale `torch.egg-info` from earlier builds.

```
pip install -e . -v --no-build-isolation
cd test
python -m pytest test_license.py -q -rs
python -m pytest test_fx.py -q
```

`test_license.py`: 13 passed, none skipped. `test_fx.py`: 840 passed, 5 xfailed. `find_library_location("libtorchbind_test.so")` returns the copy in the install tree, not the stale one in the checkout.

The CMake-based tests in `test_aot_inductor_package.py` require CUDA 12.8 and were skipped on this machine. As a substitute, a minimal project calling `find_package(Torch REQUIRED)` configures with `-DCMAKE_PREFIX_PATH` set to `torch.utils.cmake_prefix_path` and fails with the previous value, the package directory in the checkout. `test_xpu_header_installed` was not run (no XPU).

```
lintrunner -a --take PYFMT,RUFF,FLAKE8,SHELLCHECK .ci/pytorch/test.sh test/inductor/test_aot_inductor_package.py test/test_license.py test/test_xpu.py torch/testing/_internal/common_utils.py
```

Authored with the help of an AI assistant (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
zklaus added a commit to zklaus/pytorch that referenced this pull request Nov 13, 2026
## Linked issue or supporting maintainer

Fixes pytorch#195891

## BC-breaking?

No

## Summary (human written only)

This PR removes instances of legacy `__file__` based lookups in tests in favor of the modern importlib based alternatives that are compatible with editable installs in redirect mode.

## Agent details (if applicable)

Under a redirect-mode editable install, `torch.__file__` points into the source tree while `lib/`, `include/`, `share/cmake` and the dist-info are installed elsewhere. Several test-side lookups derived these locations from `__file__` and so looked in the source tree, where they do not exist or where only stale leftovers of an earlier build exist.

`find_library_location` now asks `torch._utils_internal.get_file_path`, which is anchored on the import system (pytorch#195587), before falling back to `build/lib`. `test_xpu` finds the include directory the same way, and `test_aot_inductor_package` passes `torch.utils.cmake_prefix_path` as `CMAKE_PREFIX_PATH` instead of the package directory. `test_license` locates the dist-info through `importlib.metadata`, since it is distribution metadata rather than a file inside the package; a stale `torch.egg-info` on `sys.path` also counts as a "torch" distribution, so only dist-info directories are kept.

The editable CI job already runs `test_fx` and `test_license`. Until now `test_fx` found the torchbind test library only through the `build/lib` fallback and `test_license` skipped its dist-info test, so both start exercising the installed layout with this change. The job also prints sccache stats through `print_sccache_stats` like the other jobs.

On the nightly schedule `filter_test_configs.py` turns every test config, this one included, into a rerun-disabled-tests run. `run_test.py` never fails in that mode, so the editable rebuild there could only repeat the build and layout checks that the job already runs on every PR. `test_editable` now returns early when `PYTORCH_TEST_RERUN_DISABLED_TESTS=1`.

An alternative for `test_license` was `get_file_path("torch", "..")`, but that assumes the dist-info is a sibling of the installed package files, which is the assumption this change removes elsewhere.

Tracked in pytorch#195887.

### Test Plan

Editable install of this commit on Linux x86_64, Python 3.12, CPU-only, with `BUILD_TEST=1` so that the torchbind test library is built. The checkout also held a stale `torch/lib/libtorchbind_test.so` and a stale `torch.egg-info` from earlier builds.

```
pip install -e . -v --no-build-isolation
cd test
python -m pytest test_license.py -q -rs
python -m pytest test_fx.py -q
```

`test_license.py`: 13 passed, none skipped. `test_fx.py`: 840 passed, 5 xfailed. `find_library_location("libtorchbind_test.so")` returns the copy in the install tree, not the stale one in the checkout.

The CMake-based tests in `test_aot_inductor_package.py` require CUDA 12.8 and were skipped on this machine. As a substitute, a minimal project calling `find_package(Torch REQUIRED)` configures with `-DCMAKE_PREFIX_PATH` set to `torch.utils.cmake_prefix_path` and fails with the previous value, the package directory in the checkout. `test_xpu_header_installed` was not run (no XPU).

The early return for rerun-disabled-tests mode was not run; it takes effect only on the nightly schedule. `bash -n .ci/pytorch/test.sh` and shellcheck pass.

```
lintrunner -a --take PYFMT,RUFF,FLAKE8,SHELLCHECK .ci/pytorch/test.sh test/inductor/test_aot_inductor_package.py test/test_license.py test/test_xpu.py torch/testing/_internal/common_utils.py
```

Authored with the help of an AI assistant (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
zklaus added a commit to zklaus/pytorch that referenced this pull request Nov 17, 2026
## Linked issue or supporting maintainer

Fixes pytorch#195891

## BC-breaking?

No

## Summary (human written only)

This PR removes instances of legacy `__file__` based lookups in tests in favor of the modern importlib based alternatives that are compatible with editable installs in redirect mode.

## Agent details (if applicable)

Under a redirect-mode editable install, `torch.__file__` points into the source tree while `lib/`, `include/`, `share/cmake` and the dist-info are installed elsewhere. Several test-side lookups derived these locations from `__file__` and so looked in the source tree, where they do not exist or where only stale leftovers of an earlier build exist.

`find_library_location` now asks `torch._utils_internal.get_file_path`, which is anchored on the import system (pytorch#195587), before falling back to `build/lib`. `test_xpu` finds the include directory the same way, and `test_aot_inductor_package` passes `torch.utils.cmake_prefix_path` as `CMAKE_PREFIX_PATH` instead of the package directory. `test_license` locates the dist-info through `importlib.metadata`, since it is distribution metadata rather than a file inside the package; a stale `torch.egg-info` on `sys.path` also counts as a "torch" distribution, so only dist-info directories are kept. The matches are de-duplicated by real path, because `sys.path` can reach one site-packages directory twice through a symlink such as `lib64 -> lib`.

The editable CI job already runs `test_fx` and `test_license`. Until now `test_fx` found the torchbind test library only through the `build/lib` fallback and `test_license` skipped its dist-info test, so both start exercising the installed layout with this change. The job also prints sccache stats through `print_sccache_stats` like the other jobs.

An alternative for `test_license` was `get_file_path("torch", "..")`, but that assumes the dist-info is a sibling of the installed package files, which is the assumption this change removes elsewhere.

Tracked in pytorch#195887.

### Test Plan

Editable install of this commit on Linux x86_64, Python 3.12, CPU-only, with `BUILD_TEST=1` so that the torchbind test library is built. The checkout also held a stale `torch/lib/libtorchbind_test.so` and a stale `torch.egg-info` from earlier builds.

```
pip install -e . -v --no-build-isolation
cd test
python -m pytest test_license.py -q -rs
python -m pytest test_fx.py -q
```

`test_license.py`: 13 passed, none skipped. `test_fx.py`: 840 passed, 5 xfailed. `find_library_location("libtorchbind_test.so")` returns the copy in the install tree, not the stale one in the checkout.

`test_license.py` and the CMake-based tests were rerun for the final revision on a second machine: Linux x86_64, Python 3.12, CUDA 12.9 editable install of viable/strict bafda5b built with `BUILD_TEST=0`, with the test and helper changes of this commit applied on top.

```
cd test
python -m pytest test_license.py -q -rs
PYTHONPATH=<symlink to site-packages> python -m pytest test_license.py -q -rs -k distinfo
python -m pytest inductor/test_aot_inductor_package.py -q -rA -k "compile_after_package or compile_standalone or compile_with_exporter"
```

`test_license.py`: 13 passed, none skipped. With site-packages also on `sys.path` through a symlink, `importlib.metadata` reports two locations for torch, one dist-info directory remains after de-duplication and the dist-info test passes.

`test_aot_inductor_package.py` (triton 3.9.0): the 11 selected tests pass, 5 in `TestAOTInductorPackageCpp_cpu` and 6 in `TestAOTInductorPackageCpp_cuda`. Without this commit the same 11 fail in `cmake ..` at `find_package(Torch)`. `test_fx.py` was not rerun there (no torchbind test library with `BUILD_TEST=0`); the helper it uses is unchanged since the run above. `test_xpu_header_installed` was not run (no XPU).

In CI the editable job builds with `BUILD_TEST` on and installs `libtorchbind_test.so` into `build/install/<wheel tag>/torch/lib`, which is where `test_fx` now finds it. The build artifact that the job unpacks also provides `build/lib/libtorchbind_test.so`, so the fallback would still find a copy there.

`bash -n .ci/pytorch/test.sh` and shellcheck pass.

```
lintrunner -a --take PYFMT,RUFF,FLAKE8,SHELLCHECK .ci/pytorch/test.sh test/inductor/test_aot_inductor_package.py test/test_license.py test/test_xpu.py torch/testing/_internal/common_utils.py
```

Authored with the help of an AI assistant (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
zklaus added a commit to zklaus/pytorch that referenced this pull request Nov 18, 2026
## Linked issue or supporting maintainer

Fixes pytorch#195891

## BC-breaking?

No

## Summary (human written only)

This PR removes instances of legacy `__file__` based lookups in tests in favor of the modern importlib based alternatives that are compatible with editable installs in redirect mode.

## Agent details (if applicable)

Under a redirect-mode editable install, `torch.__file__` points into the source tree while `lib/`, `include/`, `share/cmake` and the dist-info are installed elsewhere. Several test-side lookups derived these locations from `__file__` and so looked in the source tree, where they do not exist or where only stale leftovers of an earlier build exist.

`find_library_location` now asks `torch._utils_internal.get_file_path`, which is anchored on the import system (pytorch#195587), before falling back to `build/lib`. `test_xpu` finds the include directory the same way, and `test_aot_inductor_package` passes `torch.utils.cmake_prefix_path` as `CMAKE_PREFIX_PATH` instead of the package directory. `test_license` locates the dist-info through `importlib.metadata`, since it is distribution metadata rather than a file inside the package; a stale `torch.egg-info` on `sys.path` also counts as a "torch" distribution, so only dist-info directories are kept. The matches are de-duplicated by real path, because `sys.path` can reach one site-packages directory twice through a symlink such as `lib64 -> lib`.

The editable CI job already runs `test_fx` and `test_license`. Until now `test_fx` found the torchbind test library only through the `build/lib` fallback and `test_license` skipped its dist-info test, so both start exercising the installed layout with this change. The job also prints sccache stats through `print_sccache_stats` like the other jobs.

An alternative for `test_license` was `get_file_path("torch", "..")`, but that assumes the dist-info is a sibling of the installed package files, which is the assumption this change removes elsewhere.

Tracked in pytorch#195887.

### Test Plan

Editable install of this commit on Linux x86_64, Python 3.12, CPU-only, with `BUILD_TEST=1` so that the torchbind test library is built. The checkout also held a stale `torch/lib/libtorchbind_test.so` and a stale `torch.egg-info` from earlier builds.

```
pip install -e . -v --no-build-isolation
cd test
python -m pytest test_license.py -q -rs
python -m pytest test_fx.py -q
```

`test_license.py`: 13 passed, none skipped. `test_fx.py`: 840 passed, 5 xfailed. `find_library_location("libtorchbind_test.so")` returns the copy in the install tree, not the stale one in the checkout.

`test_license.py` and the CMake-based tests were rerun for the final revision on a second machine: Linux x86_64, Python 3.12, CUDA 12.9 editable install of viable/strict bafda5b built with `BUILD_TEST=0`, with the test and helper changes of this commit applied on top.

```
cd test
python -m pytest test_license.py -q -rs
PYTHONPATH=<symlink to site-packages> python -m pytest test_license.py -q -rs -k distinfo
python -m pytest inductor/test_aot_inductor_package.py -q -rA -k "compile_after_package or compile_standalone or compile_with_exporter"
```

`test_license.py`: 13 passed, none skipped. With site-packages also on `sys.path` through a symlink, `importlib.metadata` reports two locations for torch, one dist-info directory remains after de-duplication and the dist-info test passes.

`test_aot_inductor_package.py` (triton 3.9.0): the 11 selected tests pass, 5 in `TestAOTInductorPackageCpp_cpu` and 6 in `TestAOTInductorPackageCpp_cuda`. Without this commit the same 11 fail in `cmake ..` at `find_package(Torch)`. `test_fx.py` was not rerun there (no torchbind test library with `BUILD_TEST=0`); the helper it uses is unchanged since the run above. `test_xpu_header_installed` was not run (no XPU).

In CI the editable job builds with `BUILD_TEST` on and installs `libtorchbind_test.so` into `build/install/<wheel tag>/torch/lib`, which is where `test_fx` now finds it. The build artifact that the job unpacks also provides `build/lib/libtorchbind_test.so`, so the fallback would still find a copy there.

`bash -n .ci/pytorch/test.sh` and shellcheck pass.

```
lintrunner -a --take PYFMT,RUFF,FLAKE8,SHELLCHECK .ci/pytorch/test.sh test/inductor/test_aot_inductor_package.py test/test_license.py test/test_xpu.py torch/testing/_internal/common_utils.py
```

Authored with the help of an AI assistant (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
pytorchmergebot pushed a commit to zklaus/pytorch that referenced this pull request Dec 1, 2026
## Linked issue or supporting maintainer

Fixes pytorch#195891

## BC-breaking?

No

## Summary (human written only)

This PR removes instances of legacy `__file__` based lookups in tests in favor of the modern importlib based alternatives that are compatible with editable installs in redirect mode.

## Agent details (if applicable)

Under a redirect-mode editable install, `torch.__file__` points into the source tree while `lib/`, `include/`, `share/cmake` and the dist-info are installed elsewhere. Several test-side lookups derived these locations from `__file__` and so looked in the source tree, where they do not exist or where only stale leftovers of an earlier build exist.

`find_library_location` now asks `torch._utils_internal.get_file_path`, which is anchored on the import system (pytorch#195587), before falling back to `build/lib`. `test_xpu` finds the include directory the same way, and `test_aot_inductor_package` passes `torch.utils.cmake_prefix_path` as `CMAKE_PREFIX_PATH` instead of the package directory. `test_license` locates the dist-info through `importlib.metadata`, since it is distribution metadata rather than a file inside the package; a stale `torch.egg-info` on `sys.path` also counts as a "torch" distribution, so only dist-info directories are kept. The matches are de-duplicated by real path, because `sys.path` can reach one site-packages directory twice through a symlink such as `lib64 -> lib`.

The editable CI job already runs `test_fx` and `test_license`. Until now `test_fx` found the torchbind test library only through the `build/lib` fallback and `test_license` skipped its dist-info test, so both start exercising the installed layout with this change. The job also prints sccache stats through `print_sccache_stats` like the other jobs.

An alternative for `test_license` was `get_file_path("torch", "..")`, but that assumes the dist-info is a sibling of the installed package files, which is the assumption this change removes elsewhere.

Tracked in pytorch#195887.

### Test Plan

Editable install of this commit on Linux x86_64, Python 3.12, CPU-only, with `BUILD_TEST=1` so that the torchbind test library is built. The checkout also held a stale `torch/lib/libtorchbind_test.so` and a stale `torch.egg-info` from earlier builds.

```
pip install -e . -v --no-build-isolation
cd test
python -m pytest test_license.py -q -rs
python -m pytest test_fx.py -q
```

`test_license.py`: 13 passed, none skipped. `test_fx.py`: 840 passed, 5 xfailed. `find_library_location("libtorchbind_test.so")` returns the copy in the install tree, not the stale one in the checkout.

`test_license.py` and the CMake-based tests were rerun for the final revision on a second machine: Linux x86_64, Python 3.12, CUDA 12.9 editable install of viable/strict bafda5b built with `BUILD_TEST=0`, with the test and helper changes of this commit applied on top.

```
cd test
python -m pytest test_license.py -q -rs
PYTHONPATH=<symlink to site-packages> python -m pytest test_license.py -q -rs -k distinfo
python -m pytest inductor/test_aot_inductor_package.py -q -rA -k "compile_after_package or compile_standalone or compile_with_exporter"
```

`test_license.py`: 13 passed, none skipped. With site-packages also on `sys.path` through a symlink, `importlib.metadata` reports two locations for torch, one dist-info directory remains after de-duplication and the dist-info test passes.

`test_aot_inductor_package.py` (triton 3.9.0): the 11 selected tests pass, 5 in `TestAOTInductorPackageCpp_cpu` and 6 in `TestAOTInductorPackageCpp_cuda`. Without this commit the same 11 fail in `cmake ..` at `find_package(Torch)`. `test_fx.py` was not rerun there (no torchbind test library with `BUILD_TEST=0`); the helper it uses is unchanged since the run above. `test_xpu_header_installed` was not run (no XPU).

In CI the editable job builds with `BUILD_TEST` on and installs `libtorchbind_test.so` into `build/install/<wheel tag>/torch/lib`, which is where `test_fx` now finds it. The build artifact that the job unpacks also provides `build/lib/libtorchbind_test.so`, so the fallback would still find a copy there.

`bash -n .ci/pytorch/test.sh` and shellcheck pass.

```
lintrunner -a --take PYFMT,RUFF,FLAKE8,SHELLCHECK .ci/pytorch/test.sh test/inductor/test_aot_inductor_package.py test/test_license.py test/test_xpu.py torch/testing/_internal/common_utils.py
```

Authored with the help of an AI assistant (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
pytorchmergebot pushed a commit to zklaus/pytorch that referenced this pull request Dec 1, 2026
## Linked issue or supporting maintainer

Part of pytorch#195889

## BC-breaking?

No

## Summary (human written only)

This PR replaces resource lookups in inductor and inductor tests that are based on the legacy `__file__` mechanism with the modern importlib based lookup via `torch._utils_internal.get_file_path`. This is necessary to make things work with editable installs in redirect mode that came in with our move to scikit-build-core.

## Agent details (if applicable)

Under a redirect-mode editable install, `torch.__file__` points into the source checkout while `bin/`, `include/` and `lib/` are installed beside the compiled extension. Three inductor lookups derived those directories from `__file__` and so pointed into the checkout:

- `runtime/compile_tasks.py`: the bundled `bin/ptxas` was not found, so `TRITON_PTXAS_PATH` stayed unset and Triton fell back to its own ptxas.
- `codegen/cpp_wrapper_cpu.py`: an out-of-tree backend's extended `c_shim_<device>.h` was not found and silently not included.
- `cpu_vec_isa.py`: the `lib` directory prepended to `LD_LIBRARY_PATH` for the vec-ISA probe did not exist, so the probe always took the slower `import torch` retry.

All three now start from `torch._utils_internal.get_file_path("torch")`, which is anchored on the import system (pytorch#195587). Two tests in `test_codecache.py` that pinned the old `lib` path move with it.

`get_file_path` is called with the single component `"torch"` and the rest is joined with `os.path`, the form `torch/utils/cpp_extension.py` and `codegen/mps.py` already use. Two of the three files looked up are optional, and a build system that replaces `get_file_path` may raise for a resource it does not ship (see `_resolve_cmake_prefix_path` in `torch/utils/__init__.py`); the single-component form keeps the existing `exists()` checks in charge of that case. The alternative was the multi-component form wrapped in `try/except` at each site.

The fourth site named in the issue, the `include` lookup through `_TORCH_PATH` in `cpp_builder.py`, is not changed. It is only used by `build_fbcode_re`, the remote-build path, which an editable install does not reach, and `_TORCH_PATH` also feeds the linker script path and the code hash, where the source tree is the right answer.

Tracked in pytorch#195887.

### Test Plan

Applied on top of an editable install on Linux x86_64, Python 3.12, CPU-only, in a checkout with no leftovers of earlier in-tree builds (no libraries in `torch/lib`). The changes are pure Python, so no rebuild was needed.

```
cd test
python -m pytest inductor/test_codecache.py -q -rs -k TestVecISACheckBuild
python -m pytest inductor/test_aot_inductor.py -q -k "AOTInductorTestABICompatibleCpu and (test_simple or test_add)"
```

`TestVecISACheckBuild` before the change: 3 passed, 1 skipped ("libc10.so not found in torch lib dir"), and the first `LD_LIBRARY_PATH` entry of `VecISA._build_probe_env()` is `torch/lib` in the checkout, which holds no libraries. `test_build_probe_env_prepends_torch_lib_dir_to_loader_path` passes there only because it asserted the same `__file__`-derived path as the code. After the change: 4 passed, and the entry is `torch/lib` of the install tree.

AOT inductor selection after the change: 8 passed. A `torch.compile` call with `cpp_wrapper=True` runs.

Not exercised: the ptxas lookup (needs a CUDA build with `BUILD_BUNDLE_PTXAS=1`) and the extended shim header (needs an out-of-tree backend).

```
lintrunner -a --take PYFMT,RUFF,FLAKE8 test/inductor/test_codecache.py torch/_inductor/codegen/cpp_wrapper_cpu.py torch/_inductor/cpu_vec_isa.py torch/_inductor/runtime/compile_tasks.py
```

Authored with the help of an AI assistant (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
pytorchmergebot pushed a commit to zklaus/pytorch that referenced this pull request Dec 1, 2026
## Linked issue or supporting maintainer

Fixes pytorch#195890

## BC-breaking?

No

## Summary (human written only)

This PR replaces the legacy `__file__` based lookup of the RPATH source `libtorch_nvshmem.so` with a modern importlib based version via our `get_file_path` helper, which is necessary for editable installs in redirect mode.

## Agent details (if applicable)

`NvshmemLibFinder.find_device_library` builds a list of directories to search for the NVSHMEM device library. Its last step reads the RPATH of torch's own `libtorch_nvshmem.so` and adds those directories, which is how an NVSHMEM that lives outside site-packages and the system directories is found. It located that library through `os.path.dirname(torch.__file__)`. Under a redirect-mode editable install that is the source checkout, where there is no `lib/libtorch_nvshmem.so`, so the step was silently skipped.

The lookup now starts from `torch._utils_internal.get_file_path("torch")`, which is anchored on the import system (pytorch#195587). The change only restores that last step: the `NVSHMEM_LIB_DIR` override, the NVSHMEM wheel directory and the system directories are searched as before and in the same order, so the question raised in the issue, whether falling through to a system NVSHMEM is intended, is not affected.

`get_file_path` is called with the single component `"torch"`, as in `torch/utils/cpp_extension.py`, and the rest is joined with `os.path`.

Tracked in pytorch#195887.

### Test Plan

Editable install on Linux x86_64, Python 3.12, CUDA 12.9, built with `NVSHMEM_HOME` pointing at an NVSHMEM 3.7.2 tree outside site-packages. `libtorch_nvshmem.so` is in the install tree only, and its RPATH contains the NVSHMEM `lib` directory.

```
python -c "from torch.distributed._symmetric_memory._nvshmem_triton import NvshmemLibFinder; NvshmemLibFinder.find_device_library()"
```

Before the change the directories searched are the wheel directory and the three system directories. After the change the list also contains the RPATH entries of `libtorch_nvshmem.so`, including the NVSHMEM `lib` directory.

The call still ends in "NVSHMEM device library not found" on this setup, for an unrelated reason: it looks for `libnvshmem_device.bc`, and the NVSHMEM 3.7.2 wheel ships per-architecture files (`libnvshmem_device_sm_NN.bc`) instead. No GPU test was run; the function only inspects files.

```
lintrunner -a --take PYFMT,RUFF,FLAKE8 torch/distributed/_symmetric_memory/_nvshmem_triton.py
```

Authored with the help of an AI assistant (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
pytorchmergebot pushed a commit that referenced this pull request Dec 1, 2026
## Linked issue or supporting maintainer

Part of #195889

## BC-breaking?

No

## Summary (human written only)

This PR replaces resource lookups in inductor and inductor tests that are based on the legacy `__file__` mechanism with the modern importlib based lookup via `torch._utils_internal.get_file_path`. This is necessary to make things work with editable installs in redirect mode that came in with our move to scikit-build-core.

## Agent details (if applicable)

Under a redirect-mode editable install, `torch.__file__` points into the source checkout while `bin/`, `include/` and `lib/` are installed beside the compiled extension. Three inductor lookups derived those directories from `__file__` and so pointed into the checkout:

- `runtime/compile_tasks.py`: the bundled `bin/ptxas` was not found, so `TRITON_PTXAS_PATH` stayed unset and Triton fell back to its own ptxas.
- `codegen/cpp_wrapper_cpu.py`: an out-of-tree backend's extended `c_shim_<device>.h` was not found and silently not included.
- `cpu_vec_isa.py`: the `lib` directory prepended to `LD_LIBRARY_PATH` for the vec-ISA probe did not exist, so the probe always took the slower `import torch` retry.

All three now start from `torch._utils_internal.get_file_path("torch")`, which is anchored on the import system (#195587). Two tests in `test_codecache.py` that pinned the old `lib` path move with it.

`get_file_path` is called with the single component `"torch"` and the rest is joined with `os.path`, the form `torch/utils/cpp_extension.py` and `codegen/mps.py` already use. Two of the three files looked up are optional, and a build system that replaces `get_file_path` may raise for a resource it does not ship (see `_resolve_cmake_prefix_path` in `torch/utils/__init__.py`); the single-component form keeps the existing `exists()` checks in charge of that case. The alternative was the multi-component form wrapped in `try/except` at each site.

The fourth site named in the issue, the `include` lookup through `_TORCH_PATH` in `cpp_builder.py`, is not changed. It is only used by `build_fbcode_re`, the remote-build path, which an editable install does not reach, and `_TORCH_PATH` also feeds the linker script path and the code hash, where the source tree is the right answer.

Tracked in #195887.

### Test Plan

Applied on top of an editable install on Linux x86_64, Python 3.12, CPU-only, in a checkout with no leftovers of earlier in-tree builds (no libraries in `torch/lib`). The changes are pure Python, so no rebuild was needed.

```
cd test
python -m pytest inductor/test_codecache.py -q -rs -k TestVecISACheckBuild
python -m pytest inductor/test_aot_inductor.py -q -k "AOTInductorTestABICompatibleCpu and (test_simple or test_add)"
```

`TestVecISACheckBuild` before the change: 3 passed, 1 skipped ("libc10.so not found in torch lib dir"), and the first `LD_LIBRARY_PATH` entry of `VecISA._build_probe_env()` is `torch/lib` in the checkout, which holds no libraries. `test_build_probe_env_prepends_torch_lib_dir_to_loader_path` passes there only because it asserted the same `__file__`-derived path as the code. After the change: 4 passed, and the entry is `torch/lib` of the install tree.

AOT inductor selection after the change: 8 passed. A `torch.compile` call with `cpp_wrapper=True` runs.

Not exercised: the ptxas lookup (needs a CUDA build with `BUILD_BUNDLE_PTXAS=1`) and the extended shim header (needs an out-of-tree backend).

```
lintrunner -a --take PYFMT,RUFF,FLAKE8 test/inductor/test_codecache.py torch/_inductor/codegen/cpp_wrapper_cpu.py torch/_inductor/cpu_vec_isa.py torch/_inductor/runtime/compile_tasks.py
```

Authored with the help of an AI assistant (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #204789
Approved by: https://github.com/atalman
pytorchmergebot pushed a commit that referenced this pull request Dec 2, 2026
## Linked issue or supporting maintainer

Fixes #195890

## BC-breaking?

No

## Summary (human written only)

This PR replaces the legacy `__file__` based lookup of the RPATH source `libtorch_nvshmem.so` with a modern importlib based version via our `get_file_path` helper, which is necessary for editable installs in redirect mode.

## Agent details (if applicable)

`NvshmemLibFinder.find_device_library` builds a list of directories to search for the NVSHMEM device library. Its last step reads the RPATH of torch's own `libtorch_nvshmem.so` and adds those directories, which is how an NVSHMEM that lives outside site-packages and the system directories is found. It located that library through `os.path.dirname(torch.__file__)`. Under a redirect-mode editable install that is the source checkout, where there is no `lib/libtorch_nvshmem.so`, so the step was silently skipped.

The lookup now starts from `torch._utils_internal.get_file_path("torch")`, which is anchored on the import system (#195587). The change only restores that last step: the `NVSHMEM_LIB_DIR` override, the NVSHMEM wheel directory and the system directories are searched as before and in the same order, so the question raised in the issue, whether falling through to a system NVSHMEM is intended, is not affected.

`get_file_path` is called with the single component `"torch"`, as in `torch/utils/cpp_extension.py`, and the rest is joined with `os.path`.

Tracked in #195887.

### Test Plan

Editable install on Linux x86_64, Python 3.12, CUDA 12.9, built with `NVSHMEM_HOME` pointing at an NVSHMEM 3.7.2 tree outside site-packages. `libtorch_nvshmem.so` is in the install tree only, and its RPATH contains the NVSHMEM `lib` directory.

```
python -c "from torch.distributed._symmetric_memory._nvshmem_triton import NvshmemLibFinder; NvshmemLibFinder.find_device_library()"
```

Before the change the directories searched are the wheel directory and the three system directories. After the change the list also contains the RPATH entries of `libtorch_nvshmem.so`, including the NVSHMEM `lib` directory.

The call still ends in "NVSHMEM device library not found" on this setup, for an unrelated reason: it looks for `libnvshmem_device.bc`, and the NVSHMEM 3.7.2 wheel ships per-architecture files (`libnvshmem_device_sm_NN.bc`) instead. No GPU test was run; the function only inspects files.

```
lintrunner -a --take PYFMT,RUFF,FLAKE8 torch/distributed/_symmetric_memory/_nvshmem_triton.py
```

Authored with the help of an AI assistant (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: #204804
Approved by: https://github.com/atalman
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/inductor ciflow/mps Run MPS tests (subset of trunk) ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source Reverted topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[AI-assisted] Editable installs expose an invalid CMake prefix path

8 participants