Skip to content

Compute libnvrtc shorthash with CMake file(SHA256) instead of Python - #189386

Closed
zklaus wants to merge 2 commits into
pytorch:mainfrom
zklaus:cuda-nvrtc-shorthash-native
Closed

zklaus wants to merge 2 commits into
pytorch:mainfrom
zklaus:cuda-nvrtc-shorthash-native

Conversation

@zklaus

@zklaus zklaus commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

Summary

The NVRTC "shorthash" (first 8 hex chars of the sha256 of libnvrtc.so) was
computed by spawning the Python interpreter to run a hashlib one-liner, which
required a local find_package(Python COMPONENTS Interpreter) inside
cmake/public/cuda.cmake. CMake has provided file(SHA256) since 3.x, so this
can be done natively with no interpreter and no subprocess:

file(SHA256 "${CUDA_NVRTC_LIB}" _cuda_nvrtc_sha256)
string(SUBSTRING "${_cuda_nvrtc_sha256}" 0 8 CUDA_NVRTC_SHORTHASH)

Besides being simpler and faster, this removes the only find_package(Python)
that runs after Python is first resolved at the top level. That re-find silently
unsets and recomputes Python_SOABI (FindPython does so on every invocation),
which is a footgun for any code that sets Python_SOABI to work around
FindPython limitations. cuda.cmake is also a public, installed module
re-included by downstream find_package(Torch) via Caffe2Config.cmake, so
dropping the Python dependency there is a small correctness win too.

file(SHA256) hard-errors on an unreadable file where the old code fell back to
"XXXXXXXX", but the enclosing guard already requires CUDA_NVRTC_LIB to be a
resolved library path, so the file exists.

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

Test Plan

Verified CMake's file(SHA256) + string(SUBSTRING 0 8) is byte-identical to
the previous Python hashlib hexdigest()[:8] on the same input (both print
8fafd5d4). Only reached on CUDA builds (guarded by USE_CUDA and
CUDA_NVRTC_LIB); end-to-end validation is a CUDA configure logging the expected
shorthash is <8 hex>.

The NVRTC "shorthash" (first 8 hex chars of the sha256 of libnvrtc.so) was
computed by spawning the Python interpreter to run a hashlib one-liner, which
required a local find_package(Python COMPONENTS Interpreter) inside
cmake/public/cuda.cmake. CMake has provided file(SHA256) since 3.x, so this can
be done natively with no interpreter and no subprocess.

Besides being simpler and faster, this removes the only find_package(Python)
that runs after Python is first resolved at the top level. That re-find silently
unsets and recomputes Python_SOABI (FindPython does so on every invocation),
which is a footgun for any code that sets Python_SOABI to work around FindPython
limitations. cuda.cmake is also a public, installed module re-included by
downstream find_package(Torch) via Caffe2Config.cmake, so dropping the Python
dependency there is a small correctness win too.

file(SHA256) hard-errors on an unreadable file where the old code fell back to
"XXXXXXXX", but the enclosing guard already requires CUDA_NVRTC_LIB to be a
resolved library path, so the file exists.

Authored with assistance from Claude Code.

Test Plan:
Verified CMake's file(SHA256) + string(SUBSTRING 0 8) is byte-identical to the
previous Python hashlib hexdigest()[:8] on the same input:

```
# both print 8fafd5d4 for the same file
cmake -P hashtest.cmake        # file(SHA256) -> substring 0 8
python -c "import hashlib; ... hexdigest()[:8]"
```

Only reached on CUDA builds (guarded by USE_CUDA and CUDA_NVRTC_LIB); end-to-end
validation is a CUDA configure logging the expected "shorthash is <8 hex>".
@pytorch-bot

pytorch-bot Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ No Failures

As of commit 7f10122 with merge base d07e3d5 (image):
💚 Looks good so far! There are no failures yet. 💚

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

Copilot AI left a comment

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.

Pull request overview

This PR updates PyTorch’s CUDA CMake module to compute the NVRTC “shorthash” using native CMake hashing instead of spawning a Python interpreter, reducing configuration-time dependencies and avoiding a late find_package(Python ...) in a public installed CMake module.

Changes:

  • Replace execute_process(${Python_EXECUTABLE} -c "hashlib...") with file(SHA256 ...) + string(SUBSTRING ...) to compute CUDA_NVRTC_SHORTHASH.
  • Always emit a status message with the computed shorthash when it is computed.

Comment thread cmake/public/cuda.cmake
Comment on lines 133 to +136
if(CUDA_NVRTC_LIB AND NOT CUDA_NVRTC_SHORTHASH)
find_package(Python COMPONENTS Interpreter)
execute_process(
COMMAND "${Python_EXECUTABLE}" -c
"import hashlib;hash=hashlib.sha256();hash.update(open('${CUDA_NVRTC_LIB}','rb').read());print(hash.hexdigest()[:8])"
RESULT_VARIABLE _retval
OUTPUT_VARIABLE CUDA_NVRTC_SHORTHASH)
if(NOT _retval EQUAL 0)
message(WARNING "Failed to compute shorthash for libnvrtc.so")
set(CUDA_NVRTC_SHORTHASH "XXXXXXXX")
else()
string(STRIP "${CUDA_NVRTC_SHORTHASH}" CUDA_NVRTC_SHORTHASH)
message(STATUS "${CUDA_NVRTC_LIB} shorthash is ${CUDA_NVRTC_SHORTHASH}")
endif()
file(SHA256 "${CUDA_NVRTC_LIB}" _cuda_nvrtc_sha256)
string(SUBSTRING "${_cuda_nvrtc_sha256}" 0 8 CUDA_NVRTC_SHORTHASH)
message(STATUS "${CUDA_NVRTC_LIB} shorthash is ${CUDA_NVRTC_SHORTHASH}")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This is true, however, note that this whole block is inside a if(CUDA_NVRTC_LIB...) guard, which means that CUDA_NVRTC_LIB here is definitively intended to be available, hence this behavior is imho reasonable.

The old codes fallback was likely more intended to deal with the rare situations where Python could not be found or used for one reason or another, not to allow continuing when the desired library could not be found or used.

Comment thread cmake/public/cuda.cmake Resolved
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
@zklaus

zklaus commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jul 14, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
…ytorch#189386)

## Summary

The NVRTC "shorthash" (first 8 hex chars of the sha256 of `libnvrtc.so`) was
computed by spawning the Python interpreter to run a `hashlib` one-liner, which
required a local `find_package(Python COMPONENTS Interpreter)` inside
`cmake/public/cuda.cmake`. CMake has provided `file(SHA256)` since 3.x, so this
can be done natively with no interpreter and no subprocess:

```cmake
file(SHA256 "${CUDA_NVRTC_LIB}" _cuda_nvrtc_sha256)
string(SUBSTRING "${_cuda_nvrtc_sha256}" 0 8 CUDA_NVRTC_SHORTHASH)
```

Besides being simpler and faster, this removes the only `find_package(Python)`
that runs after Python is first resolved at the top level. That re-find silently
unsets and recomputes `Python_SOABI` (FindPython does so on every invocation),
which is a footgun for any code that sets `Python_SOABI` to work around
FindPython limitations. `cuda.cmake` is also a public, installed module
re-included by downstream `find_package(Torch)` via `Caffe2Config.cmake`, so
dropping the Python dependency there is a small correctness win too.

`file(SHA256)` hard-errors on an unreadable file where the old code fell back to
`"XXXXXXXX"`, but the enclosing guard already requires `CUDA_NVRTC_LIB` to be a
resolved library path, so the file exists.

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

## Test Plan

Verified CMake's `file(SHA256)` + `string(SUBSTRING 0 8)` is byte-identical to
the previous Python `hashlib` `hexdigest()[:8]` on the same input (both print
`8fafd5d4`). Only reached on CUDA builds (guarded by `USE_CUDA` and
`CUDA_NVRTC_LIB`); end-to-end validation is a CUDA configure logging the expected
`shorthash is <8 hex>`.

Pull Request resolved: pytorch#189386
Approved by: https://github.com/Skylion007

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
DamJanusz pushed a commit to DamJanusz/pytorch that referenced this pull request Jul 21, 2026
…ytorch#189386)

## Summary

The NVRTC "shorthash" (first 8 hex chars of the sha256 of `libnvrtc.so`) was
computed by spawning the Python interpreter to run a `hashlib` one-liner, which
required a local `find_package(Python COMPONENTS Interpreter)` inside
`cmake/public/cuda.cmake`. CMake has provided `file(SHA256)` since 3.x, so this
can be done natively with no interpreter and no subprocess:

```cmake
file(SHA256 "${CUDA_NVRTC_LIB}" _cuda_nvrtc_sha256)
string(SUBSTRING "${_cuda_nvrtc_sha256}" 0 8 CUDA_NVRTC_SHORTHASH)
```

Besides being simpler and faster, this removes the only `find_package(Python)`
that runs after Python is first resolved at the top level. That re-find silently
unsets and recomputes `Python_SOABI` (FindPython does so on every invocation),
which is a footgun for any code that sets `Python_SOABI` to work around
FindPython limitations. `cuda.cmake` is also a public, installed module
re-included by downstream `find_package(Torch)` via `Caffe2Config.cmake`, so
dropping the Python dependency there is a small correctness win too.

`file(SHA256)` hard-errors on an unreadable file where the old code fell back to
`"XXXXXXXX"`, but the enclosing guard already requires `CUDA_NVRTC_LIB` to be a
resolved library path, so the file exists.

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

## Test Plan

Verified CMake's `file(SHA256)` + `string(SUBSTRING 0 8)` is byte-identical to
the previous Python `hashlib` `hexdigest()[:8]` on the same input (both print
`8fafd5d4`). Only reached on CUDA builds (guarded by `USE_CUDA` and
`CUDA_NVRTC_LIB`); end-to-end validation is a CUDA configure logging the expected
`shorthash is <8 hex>`.

Pull Request resolved: pytorch#189386
Approved by: https://github.com/Skylion007

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…ytorch#189386)

## Summary

The NVRTC "shorthash" (first 8 hex chars of the sha256 of `libnvrtc.so`) was
computed by spawning the Python interpreter to run a `hashlib` one-liner, which
required a local `find_package(Python COMPONENTS Interpreter)` inside
`cmake/public/cuda.cmake`. CMake has provided `file(SHA256)` since 3.x, so this
can be done natively with no interpreter and no subprocess:

```cmake
file(SHA256 "${CUDA_NVRTC_LIB}" _cuda_nvrtc_sha256)
string(SUBSTRING "${_cuda_nvrtc_sha256}" 0 8 CUDA_NVRTC_SHORTHASH)
```

Besides being simpler and faster, this removes the only `find_package(Python)`
that runs after Python is first resolved at the top level. That re-find silently
unsets and recomputes `Python_SOABI` (FindPython does so on every invocation),
which is a footgun for any code that sets `Python_SOABI` to work around
FindPython limitations. `cuda.cmake` is also a public, installed module
re-included by downstream `find_package(Torch)` via `Caffe2Config.cmake`, so
dropping the Python dependency there is a small correctness win too.

`file(SHA256)` hard-errors on an unreadable file where the old code fell back to
`"XXXXXXXX"`, but the enclosing guard already requires `CUDA_NVRTC_LIB` to be a
resolved library path, so the file exists.

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

## Test Plan

Verified CMake's `file(SHA256)` + `string(SUBSTRING 0 8)` is byte-identical to
the previous Python `hashlib` `hexdigest()[:8]` on the same input (both print
`8fafd5d4`). Only reached on CUDA builds (guarded by `USE_CUDA` and
`CUDA_NVRTC_LIB`); end-to-end validation is a CUDA configure logging the expected
`shorthash is <8 hex>`.

Pull Request resolved: pytorch#189386
Approved by: https://github.com/Skylion007

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ytorch#189386)

## Summary

The NVRTC "shorthash" (first 8 hex chars of the sha256 of `libnvrtc.so`) was
computed by spawning the Python interpreter to run a `hashlib` one-liner, which
required a local `find_package(Python COMPONENTS Interpreter)` inside
`cmake/public/cuda.cmake`. CMake has provided `file(SHA256)` since 3.x, so this
can be done natively with no interpreter and no subprocess:

```cmake
file(SHA256 "${CUDA_NVRTC_LIB}" _cuda_nvrtc_sha256)
string(SUBSTRING "${_cuda_nvrtc_sha256}" 0 8 CUDA_NVRTC_SHORTHASH)
```

Besides being simpler and faster, this removes the only `find_package(Python)`
that runs after Python is first resolved at the top level. That re-find silently
unsets and recomputes `Python_SOABI` (FindPython does so on every invocation),
which is a footgun for any code that sets `Python_SOABI` to work around
FindPython limitations. `cuda.cmake` is also a public, installed module
re-included by downstream `find_package(Torch)` via `Caffe2Config.cmake`, so
dropping the Python dependency there is a small correctness win too.

`file(SHA256)` hard-errors on an unreadable file where the old code fell back to
`"XXXXXXXX"`, but the enclosing guard already requires `CUDA_NVRTC_LIB` to be a
resolved library path, so the file exists.

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

## Test Plan

Verified CMake's `file(SHA256)` + `string(SUBSTRING 0 8)` is byte-identical to
the previous Python `hashlib` `hexdigest()[:8]` on the same input (both print
`8fafd5d4`). Only reached on CUDA builds (guarded by `USE_CUDA` and
`CUDA_NVRTC_LIB`); end-to-end validation is a CUDA configure logging the expected
`shorthash is <8 hex>`.

Pull Request resolved: pytorch#189386
Approved by: https://github.com/Skylion007

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
pytorchmergebot pushed a commit that referenced this pull request Aug 28, 2026
…d suffix (#189388)

## Summary

Since #180243 the `torch._C` extension is built by CMake via
`Python_add_library(_C MODULE WITH_SOABI ...)`. `WITH_SOABI` names the module
using `Python_SOABI`, which CMake's FindPython only computes by running the
interpreter **when not cross-compiling**: under `CMAKE_CROSSCOMPILING` the query
is skipped unless `CMAKE_CROSSCOMPILING_EMULATOR` is set (policy `CMP0190`), so
`Python_SOABI` is left empty and `WITH_SOABI` silently emits an untagged `_C.so`.

That breaks cross builds: the extension is installed under a name the target
interpreter will not import, so `import torch._C` fails. This is the conda-forge
linux-aarch64 failure in
[pytorch-cpu-feedstock#526](conda-forge/pytorch-cpu-feedstock#526).

When this was first diagnosed the symptom was different: `setup.py` collected the
extension via `package_data = f"_C{sysconfig.get_config_var('EXT_SUFFIX')}"`, the
untagged name did not match, and `_C` was dropped from the wheel entirely.
#180248 has since removed `setup.py`, and `_C` is now collected by
`install(TARGETS _C ...)`, so it ships under the wrong name rather than going
missing. Either way the target cannot import it.

#190003 has since widened which builds hit this. It forwards `CMAKE_SYSTEM_NAME`
and `CMAKE_SYSTEM_PROCESSOR` from the environment before `project()`, which is
exactly what puts CMake into cross-compile mode, so a cross setup that passes
them that way now takes the empty-`Python_SOABI` path too. Such a build
previously stayed in native mode -- `CMAKE_CROSSCOMPILING` false, `Python_SOABI`
computed normally -- and so never produced an untagged module. That makes this
the completion of #190003 rather than a conda-forge-only concern.

CMake's sanctioned cross path (`CMP0190` + an emulator) assumes the target
interpreter is run under qemu/wine. That does not fit conda-forge's crossenv,
where the interpreter is a build-native binary that reports the target's config
and is directly runnable -- no emulator. So when `Python_SOABI` is empty while
cross-compiling, we query `SOABI` from the interpreter (which crossenv answers
with the target's value) and set it once, right where FindPython resolves the
`Development.Module` component. Every downstream `WITH_SOABI` consumer (`_C`, and
the CUDA-only `_nccl_ep`) then gets the correct suffix, and `WITH_SOABI` still
composes the platform-specific filename.

The override deliberately only fills an **empty** `Python_SOABI`. A non-empty
value is authoritative and left untouched: with an emulator FindPython ran the
target interpreter to compute it, whereas this bare invocation would run the
wrong interpreter (or fail to exec the target binary), so it must not
second-guess a value FindPython already produced.

It sets `Python_SOABI` centrally rather than overriding each target's `SUFFIX`
because FindPython recomputes `Python_SOABI` on every `find_package(Python)`, so
a manual value only survives if nothing re-finds Python afterwards. That now
holds unconditionally: since #189386 replaced the libnvrtc shorthash with
`file(SHA256)`, no `find_package(Python)` runs after this one at all.

An alternative considered was passing `-DPython_SOABI=...`; FindPython unsets and
recomputes the variable on each find, so a command-line value is not honored.

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

## Test Plan

### Cross-build validation (real linux-aarch64 crossenv)

Validated against a genuine conda-forge-style cross environment: cross compilers
plus a `linux-aarch64` target prefix, joined by `crossenv`, so `Python_EXECUTABLE`
is an interpreter that **runs on x86_64 but reports the target's config**
(SOABI `cpython-312-aarch64-linux-gnu`, platform `linux-aarch64`) -- the setup
this fix is written for.

```
mamba create -p $ROOT/build-env -c conda-forge python=3.12 crossenv cmake ninja \
      gcc_linux-aarch64 gxx_linux-aarch64 sysroot_linux-aarch64
conda create -p $ROOT/target-env --platform linux-aarch64 -c conda-forge python=3.12 numpy
export PATH="$ROOT/build-env/bin:$PATH"
$ROOT/build-env/bin/python -m crossenv \
  --sysconfigdata-file $ROOT/target-env/lib/python3.12/_sysconfigdata_aarch64_conda_linux_gnu.py \
  --cc aarch64-conda-linux-gnu-gcc --cxx aarch64-conda-linux-gnu-c++ \
  --ar aarch64-conda-linux-gnu-ar \
  --sysroot $ROOT/build-env/aarch64-conda-linux-gnu/sysroot \
  $ROOT/target-env/bin/python $ROOT/cross-venv
```

PyTorch itself was then configured twice with that interpreter, the two runs
differing **only** in `cmake/Dependencies.cmake`:

```
cmake -S . -B $B -G Ninja \
  -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64 \
  -DCMAKE_C_COMPILER=aarch64-conda-linux-gnu-gcc \
  -DCMAKE_CXX_COMPILER=aarch64-conda-linux-gnu-c++ \
  -DCMAKE_SYSROOT=$ROOT/build-env/aarch64-conda-linux-gnu/sysroot \
  -DPython_EXECUTABLE=$ROOT/cross-venv/cross/bin/python \
  -DPython_INCLUDE_DIR=$ROOT/target-env/include/python3.12 \
  -DUSE_CUDA=0 -DUSE_DISTRIBUTED=0 -DBUILD_TEST=0 -DUSE_MKLDNN=0 \
  -DUSE_NUMPY=0 -DUSE_OPENMP=0 -DUSE_KINETO=0 -DBLAS=Eigen
```

Both configures succeed; the resulting `_C` target in the generated build system:

| | `_C` output in `build.ninja` |
| --- | --- |
| without this patch (current `viable/strict`) | `torch/_C.so` -- untagged, the reported bug |
| with this patch | `torch/_C.cpython-312-aarch64-linux-gnu.so` |

The configure log shows the override firing with
`cpython-312-aarch64-linux-gnu`. This also exercises the central-override design
end to end: the value survives from the override in `Dependencies.cmake` all the
way to target generation, with no later `find_package(Python)` resetting it.

Scope: this covers configure and the generated build system, where the module
name is decided. A full aarch64 compile was not run, and the box has no
`qemu-user`, so importing an aarch64 artifact there was not possible; end-to-end
execution remains the conda-forge build below.

### Supporting checks

In a standalone FindPython project: (a) a non-empty `Python_SOABI` is preserved
and only an empty one takes the override path, and (b) setting `Python_SOABI`
before the `Python_add_library` calls (no intervening `find_package`) drives the
suffix of every `WITH_SOABI` module:

```cmake
set(Python_SOABI "cpython-312-aarch64-linux-gnu")
Python_add_library(_C MODULE WITH_SOABI stub.c)        # -> _C.cpython-312-aarch64-linux-gnu.so
Python_add_library(_nccl_ep MODULE WITH_SOABI stub.c)  # -> _nccl_ep.cpython-312-aarch64-linux-gnu.so
```

Native builds are unchanged: the `CMAKE_CROSSCOMPILING` guard is not taken and
FindPython's `Python_SOABI` already equals `EXT_SUFFIX` there.

The #190003 interaction was checked separately (cmake 3.28.3), since it governs
*which* builds reach the empty-`SOABI` condition in the first place:

```
# native, no toolchain vars
cmake -S . -B b1
# -> CMAKE_CROSSCOMPILING=FALSE  Python_SOABI=cpython-310-x86_64-linux-gnu

# toolchain vars in the environment, WITHOUT #190003's forwarding block
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b4
# -> CMAKE_CROSSCOMPILING=FALSE  Python_SOABI=cpython-310-x86_64-linux-gnu

# same, WITH the forwarding block (current main)
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b2
# -> CMAKE_CROSSCOMPILING=TRUE   Python_SOABI=''

# -D flags (the conda-forge CMAKE_ARGS path)
cmake -S . -B b3 -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64
# -> CMAKE_CROSSCOMPILING=TRUE   Python_SOABI=''
```

macOS is unaffected: `CMAKE_OSX_ARCHITECTURES=x86_64` on an arm64 host leaves
`CMAKE_CROSSCOMPILING` false, and macOS SOABI (`cpython-3XY-darwin`) carries no
architecture component, so no arch-mismatched module name can arise there.

End-to-end validation is a conda-forge linux-aarch64 build
([pytorch-cpu-feedstock#526](conda-forge/pytorch-cpu-feedstock#526))
confirming `_C.cpython-3XY-aarch64-linux-gnu.so` is installed and
`import torch._C` succeeds.

Pull Request resolved: #189388
Approved by: https://github.com/isuruf, https://github.com/jeffdaily
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…d suffix (pytorch#189388)

## Summary

Since pytorch#180243 the `torch._C` extension is built by CMake via
`Python_add_library(_C MODULE WITH_SOABI ...)`. `WITH_SOABI` names the module
using `Python_SOABI`, which CMake's FindPython only computes by running the
interpreter **when not cross-compiling**: under `CMAKE_CROSSCOMPILING` the query
is skipped unless `CMAKE_CROSSCOMPILING_EMULATOR` is set (policy `CMP0190`), so
`Python_SOABI` is left empty and `WITH_SOABI` silently emits an untagged `_C.so`.

That breaks cross builds: the extension is installed under a name the target
interpreter will not import, so `import torch._C` fails. This is the conda-forge
linux-aarch64 failure in
[pytorch-cpu-feedstock#526](conda-forge/pytorch-cpu-feedstock#526).

When this was first diagnosed the symptom was different: `setup.py` collected the
extension via `package_data = f"_C{sysconfig.get_config_var('EXT_SUFFIX')}"`, the
untagged name did not match, and `_C` was dropped from the wheel entirely.
pytorch#180248 has since removed `setup.py`, and `_C` is now collected by
`install(TARGETS _C ...)`, so it ships under the wrong name rather than going
missing. Either way the target cannot import it.

pytorch#190003 has since widened which builds hit this. It forwards `CMAKE_SYSTEM_NAME`
and `CMAKE_SYSTEM_PROCESSOR` from the environment before `project()`, which is
exactly what puts CMake into cross-compile mode, so a cross setup that passes
them that way now takes the empty-`Python_SOABI` path too. Such a build
previously stayed in native mode -- `CMAKE_CROSSCOMPILING` false, `Python_SOABI`
computed normally -- and so never produced an untagged module. That makes this
the completion of pytorch#190003 rather than a conda-forge-only concern.

CMake's sanctioned cross path (`CMP0190` + an emulator) assumes the target
interpreter is run under qemu/wine. That does not fit conda-forge's crossenv,
where the interpreter is a build-native binary that reports the target's config
and is directly runnable -- no emulator. So when `Python_SOABI` is empty while
cross-compiling, we query `SOABI` from the interpreter (which crossenv answers
with the target's value) and set it once, right where FindPython resolves the
`Development.Module` component. Every downstream `WITH_SOABI` consumer (`_C`, and
the CUDA-only `_nccl_ep`) then gets the correct suffix, and `WITH_SOABI` still
composes the platform-specific filename.

The override deliberately only fills an **empty** `Python_SOABI`. A non-empty
value is authoritative and left untouched: with an emulator FindPython ran the
target interpreter to compute it, whereas this bare invocation would run the
wrong interpreter (or fail to exec the target binary), so it must not
second-guess a value FindPython already produced.

It sets `Python_SOABI` centrally rather than overriding each target's `SUFFIX`
because FindPython recomputes `Python_SOABI` on every `find_package(Python)`, so
a manual value only survives if nothing re-finds Python afterwards. That now
holds unconditionally: since pytorch#189386 replaced the libnvrtc shorthash with
`file(SHA256)`, no `find_package(Python)` runs after this one at all.

An alternative considered was passing `-DPython_SOABI=...`; FindPython unsets and
recomputes the variable on each find, so a command-line value is not honored.

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

## Test Plan

### Cross-build validation (real linux-aarch64 crossenv)

Validated against a genuine conda-forge-style cross environment: cross compilers
plus a `linux-aarch64` target prefix, joined by `crossenv`, so `Python_EXECUTABLE`
is an interpreter that **runs on x86_64 but reports the target's config**
(SOABI `cpython-312-aarch64-linux-gnu`, platform `linux-aarch64`) -- the setup
this fix is written for.

```
mamba create -p $ROOT/build-env -c conda-forge python=3.12 crossenv cmake ninja \
      gcc_linux-aarch64 gxx_linux-aarch64 sysroot_linux-aarch64
conda create -p $ROOT/target-env --platform linux-aarch64 -c conda-forge python=3.12 numpy
export PATH="$ROOT/build-env/bin:$PATH"
$ROOT/build-env/bin/python -m crossenv \
  --sysconfigdata-file $ROOT/target-env/lib/python3.12/_sysconfigdata_aarch64_conda_linux_gnu.py \
  --cc aarch64-conda-linux-gnu-gcc --cxx aarch64-conda-linux-gnu-c++ \
  --ar aarch64-conda-linux-gnu-ar \
  --sysroot $ROOT/build-env/aarch64-conda-linux-gnu/sysroot \
  $ROOT/target-env/bin/python $ROOT/cross-venv
```

PyTorch itself was then configured twice with that interpreter, the two runs
differing **only** in `cmake/Dependencies.cmake`:

```
cmake -S . -B $B -G Ninja \
  -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64 \
  -DCMAKE_C_COMPILER=aarch64-conda-linux-gnu-gcc \
  -DCMAKE_CXX_COMPILER=aarch64-conda-linux-gnu-c++ \
  -DCMAKE_SYSROOT=$ROOT/build-env/aarch64-conda-linux-gnu/sysroot \
  -DPython_EXECUTABLE=$ROOT/cross-venv/cross/bin/python \
  -DPython_INCLUDE_DIR=$ROOT/target-env/include/python3.12 \
  -DUSE_CUDA=0 -DUSE_DISTRIBUTED=0 -DBUILD_TEST=0 -DUSE_MKLDNN=0 \
  -DUSE_NUMPY=0 -DUSE_OPENMP=0 -DUSE_KINETO=0 -DBLAS=Eigen
```

Both configures succeed; the resulting `_C` target in the generated build system:

| | `_C` output in `build.ninja` |
| --- | --- |
| without this patch (current `viable/strict`) | `torch/_C.so` -- untagged, the reported bug |
| with this patch | `torch/_C.cpython-312-aarch64-linux-gnu.so` |

The configure log shows the override firing with
`cpython-312-aarch64-linux-gnu`. This also exercises the central-override design
end to end: the value survives from the override in `Dependencies.cmake` all the
way to target generation, with no later `find_package(Python)` resetting it.

Scope: this covers configure and the generated build system, where the module
name is decided. A full aarch64 compile was not run, and the box has no
`qemu-user`, so importing an aarch64 artifact there was not possible; end-to-end
execution remains the conda-forge build below.

### Supporting checks

In a standalone FindPython project: (a) a non-empty `Python_SOABI` is preserved
and only an empty one takes the override path, and (b) setting `Python_SOABI`
before the `Python_add_library` calls (no intervening `find_package`) drives the
suffix of every `WITH_SOABI` module:

```cmake
set(Python_SOABI "cpython-312-aarch64-linux-gnu")
Python_add_library(_C MODULE WITH_SOABI stub.c)        # -> _C.cpython-312-aarch64-linux-gnu.so
Python_add_library(_nccl_ep MODULE WITH_SOABI stub.c)  # -> _nccl_ep.cpython-312-aarch64-linux-gnu.so
```

Native builds are unchanged: the `CMAKE_CROSSCOMPILING` guard is not taken and
FindPython's `Python_SOABI` already equals `EXT_SUFFIX` there.

The pytorch#190003 interaction was checked separately (cmake 3.28.3), since it governs
*which* builds reach the empty-`SOABI` condition in the first place:

```
# native, no toolchain vars
cmake -S . -B b1
# -> CMAKE_CROSSCOMPILING=FALSE  Python_SOABI=cpython-310-x86_64-linux-gnu

# toolchain vars in the environment, WITHOUT pytorch#190003's forwarding block
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b4
# -> CMAKE_CROSSCOMPILING=FALSE  Python_SOABI=cpython-310-x86_64-linux-gnu

# same, WITH the forwarding block (current main)
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b2
# -> CMAKE_CROSSCOMPILING=TRUE   Python_SOABI=''

# -D flags (the conda-forge CMAKE_ARGS path)
cmake -S . -B b3 -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64
# -> CMAKE_CROSSCOMPILING=TRUE   Python_SOABI=''
```

macOS is unaffected: `CMAKE_OSX_ARCHITECTURES=x86_64` on an arm64 host leaves
`CMAKE_CROSSCOMPILING` false, and macOS SOABI (`cpython-3XY-darwin`) carries no
architecture component, so no arch-mismatched module name can arise there.

End-to-end validation is a conda-forge linux-aarch64 build
([pytorch-cpu-feedstock#526](conda-forge/pytorch-cpu-feedstock#526))
confirming `_C.cpython-3XY-aarch64-linux-gnu.so` is installed and
`import torch._C` succeeds.

Pull Request resolved: pytorch#189388
Approved by: https://github.com/isuruf, https://github.com/jeffdaily
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…d suffix (pytorch#189388)

## Summary

Since pytorch#180243 the `torch._C` extension is built by CMake via
`Python_add_library(_C MODULE WITH_SOABI ...)`. `WITH_SOABI` names the module
using `Python_SOABI`, which CMake's FindPython only computes by running the
interpreter **when not cross-compiling**: under `CMAKE_CROSSCOMPILING` the query
is skipped unless `CMAKE_CROSSCOMPILING_EMULATOR` is set (policy `CMP0190`), so
`Python_SOABI` is left empty and `WITH_SOABI` silently emits an untagged `_C.so`.

That breaks cross builds: the extension is installed under a name the target
interpreter will not import, so `import torch._C` fails. This is the conda-forge
linux-aarch64 failure in
[pytorch-cpu-feedstock#526](conda-forge/pytorch-cpu-feedstock#526).

When this was first diagnosed the symptom was different: `setup.py` collected the
extension via `package_data = f"_C{sysconfig.get_config_var('EXT_SUFFIX')}"`, the
untagged name did not match, and `_C` was dropped from the wheel entirely.
pytorch#180248 has since removed `setup.py`, and `_C` is now collected by
`install(TARGETS _C ...)`, so it ships under the wrong name rather than going
missing. Either way the target cannot import it.

pytorch#190003 has since widened which builds hit this. It forwards `CMAKE_SYSTEM_NAME`
and `CMAKE_SYSTEM_PROCESSOR` from the environment before `project()`, which is
exactly what puts CMake into cross-compile mode, so a cross setup that passes
them that way now takes the empty-`Python_SOABI` path too. Such a build
previously stayed in native mode -- `CMAKE_CROSSCOMPILING` false, `Python_SOABI`
computed normally -- and so never produced an untagged module. That makes this
the completion of pytorch#190003 rather than a conda-forge-only concern.

CMake's sanctioned cross path (`CMP0190` + an emulator) assumes the target
interpreter is run under qemu/wine. That does not fit conda-forge's crossenv,
where the interpreter is a build-native binary that reports the target's config
and is directly runnable -- no emulator. So when `Python_SOABI` is empty while
cross-compiling, we query `SOABI` from the interpreter (which crossenv answers
with the target's value) and set it once, right where FindPython resolves the
`Development.Module` component. Every downstream `WITH_SOABI` consumer (`_C`, and
the CUDA-only `_nccl_ep`) then gets the correct suffix, and `WITH_SOABI` still
composes the platform-specific filename.

The override deliberately only fills an **empty** `Python_SOABI`. A non-empty
value is authoritative and left untouched: with an emulator FindPython ran the
target interpreter to compute it, whereas this bare invocation would run the
wrong interpreter (or fail to exec the target binary), so it must not
second-guess a value FindPython already produced.

It sets `Python_SOABI` centrally rather than overriding each target's `SUFFIX`
because FindPython recomputes `Python_SOABI` on every `find_package(Python)`, so
a manual value only survives if nothing re-finds Python afterwards. That now
holds unconditionally: since pytorch#189386 replaced the libnvrtc shorthash with
`file(SHA256)`, no `find_package(Python)` runs after this one at all.

An alternative considered was passing `-DPython_SOABI=...`; FindPython unsets and
recomputes the variable on each find, so a command-line value is not honored.

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

## Test Plan

### Cross-build validation (real linux-aarch64 crossenv)

Validated against a genuine conda-forge-style cross environment: cross compilers
plus a `linux-aarch64` target prefix, joined by `crossenv`, so `Python_EXECUTABLE`
is an interpreter that **runs on x86_64 but reports the target's config**
(SOABI `cpython-312-aarch64-linux-gnu`, platform `linux-aarch64`) -- the setup
this fix is written for.

```
mamba create -p $ROOT/build-env -c conda-forge python=3.12 crossenv cmake ninja \
      gcc_linux-aarch64 gxx_linux-aarch64 sysroot_linux-aarch64
conda create -p $ROOT/target-env --platform linux-aarch64 -c conda-forge python=3.12 numpy
export PATH="$ROOT/build-env/bin:$PATH"
$ROOT/build-env/bin/python -m crossenv \
  --sysconfigdata-file $ROOT/target-env/lib/python3.12/_sysconfigdata_aarch64_conda_linux_gnu.py \
  --cc aarch64-conda-linux-gnu-gcc --cxx aarch64-conda-linux-gnu-c++ \
  --ar aarch64-conda-linux-gnu-ar \
  --sysroot $ROOT/build-env/aarch64-conda-linux-gnu/sysroot \
  $ROOT/target-env/bin/python $ROOT/cross-venv
```

PyTorch itself was then configured twice with that interpreter, the two runs
differing **only** in `cmake/Dependencies.cmake`:

```
cmake -S . -B $B -G Ninja \
  -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64 \
  -DCMAKE_C_COMPILER=aarch64-conda-linux-gnu-gcc \
  -DCMAKE_CXX_COMPILER=aarch64-conda-linux-gnu-c++ \
  -DCMAKE_SYSROOT=$ROOT/build-env/aarch64-conda-linux-gnu/sysroot \
  -DPython_EXECUTABLE=$ROOT/cross-venv/cross/bin/python \
  -DPython_INCLUDE_DIR=$ROOT/target-env/include/python3.12 \
  -DUSE_CUDA=0 -DUSE_DISTRIBUTED=0 -DBUILD_TEST=0 -DUSE_MKLDNN=0 \
  -DUSE_NUMPY=0 -DUSE_OPENMP=0 -DUSE_KINETO=0 -DBLAS=Eigen
```

Both configures succeed; the resulting `_C` target in the generated build system:

| | `_C` output in `build.ninja` |
| --- | --- |
| without this patch (current `viable/strict`) | `torch/_C.so` -- untagged, the reported bug |
| with this patch | `torch/_C.cpython-312-aarch64-linux-gnu.so` |

The configure log shows the override firing with
`cpython-312-aarch64-linux-gnu`. This also exercises the central-override design
end to end: the value survives from the override in `Dependencies.cmake` all the
way to target generation, with no later `find_package(Python)` resetting it.

Scope: this covers configure and the generated build system, where the module
name is decided. A full aarch64 compile was not run, and the box has no
`qemu-user`, so importing an aarch64 artifact there was not possible; end-to-end
execution remains the conda-forge build below.

### Supporting checks

In a standalone FindPython project: (a) a non-empty `Python_SOABI` is preserved
and only an empty one takes the override path, and (b) setting `Python_SOABI`
before the `Python_add_library` calls (no intervening `find_package`) drives the
suffix of every `WITH_SOABI` module:

```cmake
set(Python_SOABI "cpython-312-aarch64-linux-gnu")
Python_add_library(_C MODULE WITH_SOABI stub.c)        # -> _C.cpython-312-aarch64-linux-gnu.so
Python_add_library(_nccl_ep MODULE WITH_SOABI stub.c)  # -> _nccl_ep.cpython-312-aarch64-linux-gnu.so
```

Native builds are unchanged: the `CMAKE_CROSSCOMPILING` guard is not taken and
FindPython's `Python_SOABI` already equals `EXT_SUFFIX` there.

The pytorch#190003 interaction was checked separately (cmake 3.28.3), since it governs
*which* builds reach the empty-`SOABI` condition in the first place:

```
# native, no toolchain vars
cmake -S . -B b1
# -> CMAKE_CROSSCOMPILING=FALSE  Python_SOABI=cpython-310-x86_64-linux-gnu

# toolchain vars in the environment, WITHOUT pytorch#190003's forwarding block
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b4
# -> CMAKE_CROSSCOMPILING=FALSE  Python_SOABI=cpython-310-x86_64-linux-gnu

# same, WITH the forwarding block (current main)
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b2
# -> CMAKE_CROSSCOMPILING=TRUE   Python_SOABI=''

# -D flags (the conda-forge CMAKE_ARGS path)
cmake -S . -B b3 -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64
# -> CMAKE_CROSSCOMPILING=TRUE   Python_SOABI=''
```

macOS is unaffected: `CMAKE_OSX_ARCHITECTURES=x86_64` on an arm64 host leaves
`CMAKE_CROSSCOMPILING` false, and macOS SOABI (`cpython-3XY-darwin`) carries no
architecture component, so no arch-mismatched module name can arise there.

End-to-end validation is a conda-forge linux-aarch64 build
([pytorch-cpu-feedstock#526](conda-forge/pytorch-cpu-feedstock#526))
confirming `_C.cpython-3XY-aarch64-linux-gnu.so` is installed and
`import torch._C` succeeds.

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

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged open source topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants