Skip to content

Build torch._C extension module and version.py via CMake - #180243

Closed
zklaus wants to merge 41 commits into
gh/zklaus/49/basefrom
gh/zklaus/49/head
Closed

zklaus wants to merge 41 commits into
gh/zklaus/49/basefrom
gh/zklaus/49/head

Conversation

@zklaus

@zklaus zklaus commented Apr 13, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Move the build of the torch._C Python extension and the install of
torch/version.py from setup.py into torch/CMakeLists.txt, so
both the existing setuptools backend and the upcoming
scikit-build-core backend (#180247) go through the same code path.
The new Python_add_library(_C MODULE WITH_SOABI ...) target builds
the same torch/csrc/stub.c and installs at the wheel root (mapped to
torch/ by wheel.install-dir); setup.py's Extension("torch._C", ...) block and its companion extra_compile_args /
extra_link_args / make_relative_rpath_args plumbing are removed.
version.py is gitignored, so it is installed explicitly via
install(FILES ... DESTINATION ".") rather than relying on Python
package collection.

Adds a BinaryDistribution class in setup.py that forces
has_ext_modules=True so bdist_wheel uses the binary layout
(package_data + data_files only) instead of the purelib layout, which
would otherwise dump CMake's build/lib/ tree -- including test
artifacts -- into the wheel root. package_data collects the
CMake-built extension via the interpreter's exact module name
(f"_C{sysconfig.get_config_var('EXT_SUFFIX')}") rather than a _C*
glob, so a build/ dir reused across Python versions cannot leak
other ABIs' _C modules into the wheel.

Windows handling: the manual setup.py copy of _C.lib from
build_temp to build_lib is replaced by the _C target's
ARCHIVE DESTINATION "lib". For MSVC, the linker is told where to
find pythonXX.lib via /LIBPATH (Python headers use #pragma comment(lib, "pythonXX") which expects a bare-name lookup); for
Windows venvs, FindPython's library search path is extended with
sys.base_prefix/libs since the import library lives in the base
install, not the venv. nnapi_backend gains
TORCH_PYTHON_LINK_FLAGS so it picks up the same MSVC linker
options as torch_python.

Test plan

Verification is via artifact-content comparison against the parent
(#180242). Expectation: the wheel must be content-equivalent modulo
the one file the PR rebuilds (torch/_C.cpython-*.so), which must
remain functionally identical (same exports, same imports, same
rpath).

  • No regression in artifact sizes across every manywheel /
    libtorch artifact (sub-0.001 % to 0.001 % delta, zip-timestamp
    noise consistent across artifacts this PR can't directly affect):

    artifact parent (Install libaotriton_v2.so via cmake install for wheel packaging #180242) this PR (Build torch._C extension module and version.py via CMake #180243) delta
    manywheel-py3_12-rocm7_2 6,153,280,701 6,153,275,144 -5,557 (-0.000%)
    manywheel-py3_12-rocm7_1 5,788,503,789 5,788,499,957 -3,832 (-0.000%)
    manywheel-py3_12-cuda12_6 841,797,521 841,797,813 +292 (+0.000%)
    manywheel-py3_12-cuda13_2 624,213,880 624,212,127 -1,753 (-0.000%)
    manywheel-py3_12-cpu 189,248,452 189,248,117 -335 (-0.000%)
    manywheel-py3_12-xpu 778,712,445 778,711,285 -1,160 (-0.000%)
    libtorch-rocm7_2-shared-with-deps-release 12,117,315,856 12,117,314,539 -1,317 (-0.000%)
    libtorch-cpu-shared-with-deps-release 257,626,615 257,624,612 -2,003 (-0.001%)
  • Wheel manifest equivalence vs parent
    (manywheel-py3_12-rocm7_2): both wheels contain 26,779 entries;
    filename diff is empty -- no files added or removed. Confirms the
    BinaryDistribution layout fix worked (no build/lib/ spillage
    into the wheel root).

  • Per-file size diff: exactly one file changed.

    torch/_C.cpython-312-x86_64-linux-gnu.so   22,960  ->  15,720   (-7,240)
    

    Every other one of 26,778 files is byte-identical in size. That is
    precisely the file the PR rebuilds via CMake.

  • torch._C is functionally equivalent between parent and PR.
    Extracted both .so files and compared:

    • Defined symbols: zero-line diff.
    • Undefined symbols (imports from libtorch_python): zero-line
      diff.
    • RPATH: identical ($ORIGIN:$ORIGIN/lib).
    • NEEDED: 180242's .so includes a redundant
      libpthread.so.0 (merged into libc.so.6 since glibc 2.34); the
      CMake build drops it. The size shrinkage matches the cleaner
      NEEDED + tighter section layout from the CMake toolchain.
  • torch/version.py is present in both wheels at 339 bytes,
    byte-identical except for the expected git_version SHA (each
    commit has its own). __version__, debug, cuda, hip, rocm,
    xpu fields all match -- the CMake-driven generation produces the
    same output as the setuptools path.

  • Exactly one _C ABI per wheel. On a fresh multi-ABI
    manywheel-cpu-build (build_all.sh builds all CPython ABIs in one
    checkout), each wheel ships only its own torch/_C.cpython-XY.so.
    An earlier greedy _C*.so package_data glob leaked stale per-ABI
    stubs (a cp312 wheel carried cp310/cp311/cp312); pinning to the
    exact EXT_SUFFIX fixes it.

    unzip -l manywheel-py3_13-cpu.whl | grep 'torch/_C\.cpython'
    # -> only torch/_C.cpython-313-x86_64-linux-gnu.so
    

Coverage notes

  • NNAPI MSVC link-flag fix and Windows venv pythonXX.lib
    discovery fix
    are not exercised by the ROCm-Linux artifacts
    above. They are exercised by the Windows pull-CI (where NNAPI
    builds run and venv-based discovery is relevant); the green Windows
    CI is the evidence for those.
  • ROCm wheels are Linux-only by build matrix
    (.github/scripts/generate_binary_build_matrix.py:130-135,
    supported_platforms=["Linux"]).

Co-Generated with Claude Code

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Apr 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 7 New Failures, 7 Unrelated Failures, 8 Unclassified Failures

As of commit f811044 with merge base 34424f2 (image):

NEW FAILURES - The following jobs have failed:

UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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

zklaus added a commit to zklaus/pytorch that referenced this pull request Apr 13, 2026
Move the torch._C extension module build and version.py installation
into CMake, add Windows import library handling, and fix linking for
NNAPI backend and Windows platforms.

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


ghstack-source-id: d12a88a
Pull-Request: pytorch#180243
@zklaus
zklaus marked this pull request as ready for review April 14, 2026 18:32
@zklaus zklaus added ciflow/binaries Trigger all binary build and upload jobs on the PR release notes: releng release notes category labels Apr 14, 2026
zklaus added a commit to zklaus/pytorch that referenced this pull request Apr 15, 2026
Move the torch._C extension module build and version.py installation
into CMake, add Windows import library handling, and fix linking for
NNAPI backend and Windows platforms.

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


ghstack-source-id: d12a88a
Pull-Request: pytorch#180243
zklaus added a commit to zklaus/pytorch that referenced this pull request Apr 17, 2026
Move the torch._C extension module build and version.py installation
into CMake, add Windows import library handling, and fix linking for
NNAPI backend and Windows platforms.

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


ghstack-source-id: d12a88a
Pull-Request: pytorch#180243
zklaus added 3 commits April 20, 2026 13:41
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread torch/CMakeLists.txt
# forwards to torch_python. This was historically built by setuptools;
# building it here lets both setuptools and scikit-build-core use the
# same code path.
if(BUILD_PYTHON AND NOT BUILD_LIBTORCH_WHL)

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.

Nit: I don't think we really care about BUILD_LIBTORCH_WHL anymore, but sure, no harm in checking this

@malfet

malfet commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 22 checks: pull / linux-jammy-py3.14-clang18 / test (crossref, 2, 2, linux.2xlarge), pull / linux-jammy-py3.14-clang18 / test (dynamo_wrapped, 3, 3, linux.2xlarge), pull / linux-jammy-py3.14t-clang18 / test (crossref, 1, 2, linux.2xlarge), pull / linux-jammy-py3.10-clang18 / test (crossref, 1, 2, linux.2xlarge), pull / linux-jammy-py3.10-clang18 / test (dynamo_wrapped, 3, 3, linux.2xlarge), trunk / linux-jammy-rocm-py3.10-mi355 / test (default, 8, 10, linux.rocm.gpu.gfx950.1, unstable), trunk / linux-jammy-rocm-py3.10-mi355 / test (distributed, 4, 4, linux.rocm.gpu.gfx950.2), trunk / linux-jammy-rocm-py3.10-mi355 / test (default, 9, 10, linux.rocm.gpu.gfx950.1, unstable), linux-binary-manywheel / manywheel-cuda-cu126-build, linux-binary-manywheel / manywheel-cuda-cu132-build, linux-binary-manywheel / manywheel-cuda-cu130-build, linux-binary-manywheel / libtorch-cuda12_6-shared-with-deps-release-extract, linux-binary-manywheel / libtorch-cuda13_0-shared-with-deps-release-extract, linux-binary-manywheel / libtorch-cuda13_2-shared-with-deps-release-extract, linux-aarch64-binary-manywheel / manywheel-py3_15t-cuda-aarch64-12_6-test / test, linux-aarch64-binary-manywheel / manywheel-py3_15-cpu-aarch64-test / test, linux-aarch64-binary-manywheel / manywheel-py3_15-cuda-aarch64-13_0-test / test, linux-aarch64-binary-manywheel / manywheel-py3_15-cuda-aarch64-12_6-test / test, linux-aarch64-binary-manywheel / manywheel-py3_15t-cuda-aarch64-13_2-test / test, linux-aarch64-binary-manywheel / manywheel-py3_15t-cpu-aarch64-test / test, linux-aarch64-binary-manywheel / manywheel-py3_15t-cuda-aarch64-13_0-test / test, linux-aarch64-binary-manywheel / manywheel-py3_15-cuda-aarch64-13_2-test / test

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 Jun 16, 2026
Switch pyproject.toml's build backend from setuptools to
scikit-build-core, which invokes CMake directly instead of having
setup.py orchestrate it. This PR makes only the backend swap; the
now-unused setuptools code is removed separately in pytorch#180248, so this
diff stays focused and is revertible on its own.

Where to look, in order of importance:
- pyproject.toml: the new [build-system], the scikit-build-core config
  (cmake defines, wheel layout, editable mode), and the dynamic-metadata
  hooks. This is the heart of the change.
- tools/metadata/{version,dependencies}.py: the providers backing those
  hooks -- wheel version (from generate_torch_version) and dependencies
  (base + CUDA/ROCm extras).
- CMakeLists.txt: project name/version now come from SKBUILD_* with
  fallbacks so a standalone `cmake` invocation still works.
The remainder is mechanical: CI scripts swap `python setup.py clean` for
`python -m spin clean` and probe for pyproject.toml instead of setup.py,
and the build-requirement files gain scikit-build-core.

## Test plan

Verified the scikit-build-core wheel is content-equivalent to the
setuptools build (pytorch#180243), on fresh cp312 CPU artifacts.

- [x] **Wheel size**: 193,274,760 B vs pytorch#180243 193,263,155 B (+0.006 %);
  scikit-build-core does not bloat the wheel.
- [x] **Manifest diff**: adds only 6 license files
  (`torch/_vendor/{packaging,quack}/LICENSE*`, two dist-info `COPYING`)
  and removes the setuptools-specific `top_level.txt`; 0 `.md`, no
  layout spillage.
  ```
  diff <(unzip -Z1 243.whl | sort) <(unzip -Z1 247.whl | sort)
  ```
- [x] **`version.py`** matches except `git_version`; **METADATA**
  Name / Version / Requires-Dist / Requires-Python identical (only the
  intentional extra `License-File` entries).
- [x] **`torch._C`**: exactly one `_C.cpython-312.so` (the target-based
  `install(TARGETS _C)` is immune to the multi-ABI glob issue fixed in
  pytorch#180243).
- [x] **aotriton (ROCm7.2)**: full payload present -- `libaotriton_v2.so`
  (+ versioned), two headers, and 10,612 `aotriton.images/` kernel
  files across 6 AMD arches.
  ```
  unzip -l rocm7_2.whl | grep -c 'aotriton.images/'
  ```
- [x] **Build time**: no regression; manywheel builds are faster (e.g.
  ROCm ~6h08m -> ~3h45m). The gain is packaging, not compilation: both
  do the identical compile set (no sccache), but setuptools copies the
  whole package tree into `build/lib` and re-adds every file to the
  wheel per ABI, which scikit-build-core's direct cmake-install assembly
  skips.
- [x] **CI** green apart from four unrelated failure classes (onnx
  `test_rotary_embedding_opcheck` pytorch#183713, xpu `tbb==2023.0.0` dep,
  py3.15 bleeding-edge, OSDC `ImagePullBackOff` infra).

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

ghstack-source-id: d407ded
Pull-Request: pytorch#180247
@github-actions
github-actions Bot deleted the gh/zklaus/49/head branch July 5, 2026 02:25
zklaus added a commit to zklaus/pytorch that referenced this pull request Jul 7, 2026
Switch pyproject.toml's build backend from setuptools to
scikit-build-core (>= 1.0), which invokes CMake directly instead of
having setup.py orchestrate it. This PR makes the backend swap plus the
1.0-native configuration it enables; the now-unused setuptools code is
removed separately in pytorch#180248, so this diff stays focused and is
revertible on its own.

Where to look, in order of importance:
- pyproject.toml: the new [build-system], the scikit-build-core config
  (the [tool.scikit-build.env] table, cmake defines, wheel layout,
  editable mode), and the dynamic-metadata hooks. This is the heart of
  the change.
- tools/metadata/{version,dependencies}.py: the providers backing those
  hooks -- wheel version (from generate_torch_version) and dependencies
  (base + CUDA/ROCm extras).
- CMakeLists.txt: project name/version now come from SKBUILD_* with
  fallbacks so a standalone `cmake` invocation still works.
- torch/__init__.py, torch/_utils_internal.py: import-time shims that
  keep editable installs working under the new backend. scikit-build-core's
  redirect finder resolves the extension module itself (`import torch._C`);
  the shims only cover the places PyTorch locates native artifacts by hand,
  off `__file__`, which the import system never sees: the `ctypes.CDLL`
  preload of libtorch_global_deps, the Windows `os.add_dll_directory` for
  `_C`'s dependent DLLs, and the `bin/` data-file path. Redirect mode is the
  first layout to split the Python sources (checkout) from the compiled
  artifacts (install tree); in wheel and `setup.py develop` installs they
  sat together, so those `dirname(__file__)` lookups happened to be right.
- CONTRIBUTING.md: documents the editable-install flow, including
  scikit-build-core's optional rebuild-on-import (SKBUILD_EDITABLE_REBUILD),
  which stays off by default.
The remainder is mechanical: CI scripts swap `python setup.py clean` for
`python -m spin clean` and probe for pyproject.toml instead of setup.py,
and the build-requirement files gain scikit-build-core.

The configuration uses the scikit-build-core 1.0 feature set, which keeps
several PyTorch-specific workarounds out of the tree:
- MAX_JOBS -> CMAKE_BUILD_PARALLEL_LEVEL is aliased in the
  [tool.scikit-build.env] table (added upstream in scikit-build-core#1377
  for exactly this), so no custom PEP 517 wrapper backend is needed -- the
  backend is plain scikit_build_core.build.
- Dynamic version/dependencies use the stable [[tool.dynamic-metadata]]
  table (no experimental flag); the dependencies provider marks deps
  Dynamic in the sdist via a dynamic_wheel hook.
- Build type comes from the environment: 1.0 honors CMAKE_BUILD_TYPE
  natively, so only the DEBUG / REL_WITH_DEB_INFO env-var overrides remain.
- Per-image Linux compiler handling is CC/CXX = { env = ... } in the env
  table, which opts out of scikit-build-core's sysconfig-compiler injection
  (documented behavior since pytorch#1377) and lets CMake detect the compiler from
  PATH -- what green setup.py builds always did -- replacing two per-image
  cmake.define overrides.
- The Windows Ninja generator is cmake.define.CMAKE_GENERATOR in a win32
  override (1.0's generator-resolution chain honors it), so pyproject is the
  single source of truth and a plain editable Windows build gets Ninja too;
  the CI scripts no longer export CMAKE_GENERATOR.

The build-system floor and requirements-build.txt are scikit-build-core
>= 1.0; minimum-version pins the schema to that floor; and the CI pin
(.ci/docker/requirements-ci.txt) plus the Windows build-dep installers are
== 1.0.0. scikit-build-core 1.0.0 released 2026-07-06.

## Test plan

Wheel content-equivalent to the setuptools build (pytorch#180243), fresh cp312
CPU artifacts:
- [x] **Wheel size**: 193,274,760 B vs pytorch#180243 193,263,155 B (+0.006 %).
- [x] **Manifest diff**: adds only 6 license files and removes the
  setuptools-specific `top_level.txt`; no layout spillage.
  ```
  diff <(unzip -Z1 243.whl | sort) <(unzip -Z1 247.whl | sort)
  ```
- [x] **METADATA / version.py** identical bar `git_version` and the extra
  License-File entries; exactly one `_C.cpython-312.so`; aotriton payload
  intact (10,612 `aotriton.images/` kernels across 6 arches).
- [x] **Build time**: no regression; manywheel builds faster (the gain is
  packaging, not compilation).

Clean-build + editable import against the released scikit-build-core 1.0.0:
- [x] Linux (qgpu3, CUDA op), macOS (qmac, MPS), Windows (win11 VM): fresh
  `pip install -e . --no-build-isolation` builds and `import torch`
  resolves the CMake-built native artifacts from the install location. The
  Windows run also confirmed the Ninja generator comes purely from
  pyproject (no CMAKE_GENERATOR env var; build.ninja present, no .sln).
- [x] lintrunner -a clean (two pre-existing torch.bcomplex32 PYREFLY errors
  in torch/storage.py + torch/testing/_creation.py are on trunk, untouched).

Re-validated on this PR's CI (carries ciflow/trunk): the dropped per-image
Linux compiler overrides, exercised by the anaconda (conda-gcc11,
compiler_compat) and aarch64 image builds -- the two cases those overrides
originally fixed.

Based on a patch by Henry Schreiner (scikit-build-core maintainer); the env
table (scikit-build-core#1377) was added upstream specifically to let
PyTorch delete its wrapper backend.

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

ghstack-source-id: 4354dfc
Pull-Request: pytorch#180247
zklaus added a commit to zklaus/pytorch that referenced this pull request Jul 9, 2026
…d suffix

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 packaging on cross builds: setup.py collects the extension via
package_data = f"_C{sysconfig.get_config_var('EXT_SUFFIX')}", i.e. the target
suffix (_C.cpython-3XY-aarch64-linux-gnu.so). The untagged name does not match,
so _C is dropped from the wheel and import torch._C fails. This is the
conda-forge linux-aarch64 failure in pytorch-cpu-feedstock pytorch#526.

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 rather than relying on WITH_SOABI's
computation, when cross-compiling we query SOABI from the interpreter (which
crossenv answers with the target's value) and set Python_SOABI 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 is guarded
on a non-empty result, so a genuine emulator-based cross-build -- where this bare
invocation cannot run the target interpreter -- keeps FindPython's already-correct
value.

This overrides Python_SOABI centrally rather than 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 holds here: the
last find is in this file, the override runs right after it, and the only later
use of FindPython -- cmake/public/cuda.cmake, re-included from torch/CMakeLists.txt
under USE_CUDA to hash libnvrtc -- is short-circuited on that second entry by the
already-computed CUDA_NVRTC_SHORTHASH. So the override is not threatened by a
lingering find_package and lands independently.

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

Authored with assistance from Claude Code.

Test Plan:
Confirmed in a standalone FindPython project that setting Python_SOABI before the
Python_add_library calls (with no intervening find_package) drives the suffix of
every WITH_SOABI module:

```
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
```

This equals f"_C{EXT_SUFFIX}" since EXT_SUFFIX == "." + SOABI + shared-module
suffix on Linux/macOS targets. Native builds are unchanged (the CMAKE_CROSSCOMPILING
guard is not taken; FindPython's Python_SOABI already equals EXT_SUFFIX there).
End-to-end validation is a conda-forge linux-aarch64 build (pytorch-cpu-feedstock
pytorch#526) confirming _C.cpython-3XY-aarch64-linux-gnu.so lands in the wheel and
import torch._C succeeds.
zklaus added a commit to zklaus/pytorch that referenced this pull request Jul 9, 2026
…d suffix

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 packaging on cross builds: setup.py collects the extension via
package_data = f"_C{sysconfig.get_config_var('EXT_SUFFIX')}", i.e. the target
suffix (_C.cpython-3XY-aarch64-linux-gnu.so). The untagged name does not match,
so _C is dropped from the wheel and import torch._C fails. This is the
conda-forge linux-aarch64 failure in pytorch-cpu-feedstock pytorch#526.

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. The empty case is both unambiguous and the
actual failure observed (an untagged _C.so).

This overrides Python_SOABI centrally rather than 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 holds here: the
last find is in this file, the override runs right after it, and the only later
use of FindPython -- cmake/public/cuda.cmake, re-included from torch/CMakeLists.txt
under USE_CUDA to hash libnvrtc -- is short-circuited on that second entry by the
already-computed CUDA_NVRTC_SHORTHASH. So the override is not threatened by a
lingering find_package and lands independently.

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

Authored with assistance from Claude Code.

Test Plan:
Confirmed in a standalone FindPython project that (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:

```
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
```

This equals f"_C{EXT_SUFFIX}" since EXT_SUFFIX == "." + SOABI + shared-module
suffix on Linux/macOS targets. Native builds are unchanged (the CMAKE_CROSSCOMPILING
guard is not taken; FindPython's Python_SOABI already equals EXT_SUFFIX there).
End-to-end validation is a conda-forge linux-aarch64 build (pytorch-cpu-feedstock
pytorch#526) confirming _C.cpython-3XY-aarch64-linux-gnu.so lands in the wheel and
import torch._C succeeds.
zklaus added a commit to zklaus/pytorch that referenced this pull request Jul 9, 2026
…d suffix

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 packaging on cross builds: setup.py collects the extension via
package_data = f"_C{sysconfig.get_config_var('EXT_SUFFIX')}", i.e. the target
suffix (_C.cpython-3XY-aarch64-linux-gnu.so). The untagged name does not match,
so _C is dropped from the wheel and import torch._C fails. This is the
conda-forge linux-aarch64 failure in pytorch-cpu-feedstock pytorch#526.

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. The empty case is both unambiguous and the
actual failure observed (an untagged _C.so).

This overrides Python_SOABI centrally rather than 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 holds here: the
last find is in this file, the override runs right after it, and the only later
use of FindPython -- cmake/public/cuda.cmake, re-included from torch/CMakeLists.txt
under USE_CUDA to hash libnvrtc -- is short-circuited on that second entry by the
already-computed CUDA_NVRTC_SHORTHASH. So the override is not threatened by a
lingering find_package and lands independently.

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

Authored with assistance from Claude Code.

Test Plan:
Confirmed in a standalone FindPython project that (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:

```
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
```

This equals f"_C{EXT_SUFFIX}" since EXT_SUFFIX == "." + SOABI + shared-module
suffix on Linux/macOS targets. Native builds are unchanged (the CMAKE_CROSSCOMPILING
guard is not taken; FindPython's Python_SOABI already equals EXT_SUFFIX there).
End-to-end validation is a conda-forge linux-aarch64 build (pytorch-cpu-feedstock
pytorch#526) confirming _C.cpython-3XY-aarch64-linux-gnu.so lands in the wheel and
import torch._C succeeds.
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
)

Move the build of the `torch._C` Python extension and the install of
`torch/version.py` from `setup.py` into `torch/CMakeLists.txt`, so
both the existing setuptools backend and the upcoming
scikit-build-core backend (pytorch#180247) go through the same code path.
The new `Python_add_library(_C MODULE WITH_SOABI ...)` target builds
the same `torch/csrc/stub.c` and installs at the wheel root (mapped to
`torch/` by `wheel.install-dir`); `setup.py`'s `Extension("torch._C",
...)` block and its companion `extra_compile_args` /
`extra_link_args` / `make_relative_rpath_args` plumbing are removed.
`version.py` is gitignored, so it is installed explicitly via
`install(FILES ... DESTINATION ".")` rather than relying on Python
package collection.

Adds a `BinaryDistribution` class in `setup.py` that forces
`has_ext_modules=True` so `bdist_wheel` uses the binary layout
(package_data + data_files only) instead of the purelib layout, which
would otherwise dump CMake's `build/lib/` tree -- including test
artifacts -- into the wheel root. `package_data` collects the
CMake-built extension via the interpreter's exact module name
(`f"_C{sysconfig.get_config_var('EXT_SUFFIX')}"`) rather than a `_C*`
glob, so a `build/` dir reused across Python versions cannot leak
other ABIs' `_C` modules into the wheel.

Windows handling: the manual `setup.py` copy of `_C.lib` from
`build_temp` to `build_lib` is replaced by the `_C` target's
`ARCHIVE DESTINATION "lib"`. For MSVC, the linker is told where to
find `pythonXX.lib` via `/LIBPATH` (Python headers use `#pragma
comment(lib, "pythonXX")` which expects a bare-name lookup); for
Windows venvs, FindPython's library search path is extended with
`sys.base_prefix/libs` since the import library lives in the base
install, not the venv. `nnapi_backend` gains
`TORCH_PYTHON_LINK_FLAGS` so it picks up the same MSVC linker
options as `torch_python`.

## Test plan

Verification is via artifact-content comparison against the parent
(pytorch#180242). Expectation: the wheel must be content-equivalent modulo
the one file the PR rebuilds (`torch/_C.cpython-*.so`), which must
remain functionally identical (same exports, same imports, same
rpath).

- [x] **No regression in artifact sizes** across every manywheel /
  libtorch artifact (sub-0.001 % to 0.001 % delta, zip-timestamp
  noise consistent across artifacts this PR can't directly affect):

  | artifact | parent (pytorch#180242) | this PR (pytorch#180243) | delta |
  | --- | ---: | ---: | ---: |
  | manywheel-py3_12-rocm7_2 | 6,153,280,701 | 6,153,275,144 | -5,557 (-0.000%) |
  | manywheel-py3_12-rocm7_1 | 5,788,503,789 | 5,788,499,957 | -3,832 (-0.000%) |
  | manywheel-py3_12-cuda12_6 | 841,797,521 | 841,797,813 | +292 (+0.000%) |
  | manywheel-py3_12-cuda13_2 | 624,213,880 | 624,212,127 | -1,753 (-0.000%) |
  | manywheel-py3_12-cpu | 189,248,452 | 189,248,117 | -335 (-0.000%) |
  | manywheel-py3_12-xpu | 778,712,445 | 778,711,285 | -1,160 (-0.000%) |
  | libtorch-rocm7_2-shared-with-deps-release | 12,117,315,856 | 12,117,314,539 | -1,317 (-0.000%) |
  | libtorch-cpu-shared-with-deps-release | 257,626,615 | 257,624,612 | -2,003 (-0.001%) |

- [x] **Wheel manifest equivalence vs parent**
  (`manywheel-py3_12-rocm7_2`): both wheels contain **26,779 entries**;
  filename diff is empty -- no files added or removed. Confirms the
  `BinaryDistribution` layout fix worked (no `build/lib/` spillage
  into the wheel root).

- [x] **Per-file size diff: exactly one file changed.**
  ```
  torch/_C.cpython-312-x86_64-linux-gnu.so   22,960  ->  15,720   (-7,240)
  ```
  Every other one of 26,778 files is byte-identical in size. That is
  precisely the file the PR rebuilds via CMake.

- [x] **`torch._C` is functionally equivalent** between parent and PR.
  Extracted both `.so` files and compared:
  - **Defined symbols**: zero-line diff.
  - **Undefined symbols** (imports from `libtorch_python`): zero-line
    diff.
  - **RPATH**: identical (`$ORIGIN:$ORIGIN/lib`).
  - **NEEDED**: 180242's `.so` includes a redundant
    `libpthread.so.0` (merged into `libc.so.6` since glibc 2.34); the
    CMake build drops it. The size shrinkage matches the cleaner
    NEEDED + tighter section layout from the CMake toolchain.

- [x] **`torch/version.py`** is present in both wheels at 339 bytes,
  byte-identical except for the expected `git_version` SHA (each
  commit has its own). `__version__`, `debug`, `cuda`, `hip`, `rocm`,
  `xpu` fields all match -- the CMake-driven generation produces the
  same output as the setuptools path.

- [x] **Exactly one `_C` ABI per wheel.** On a fresh multi-ABI
  `manywheel-cpu-build` (build_all.sh builds all CPython ABIs in one
  checkout), each wheel ships only its own `torch/_C.cpython-XY.so`.
  An earlier greedy `_C*.so` `package_data` glob leaked stale per-ABI
  stubs (a cp312 wheel carried cp310/cp311/cp312); pinning to the
  exact `EXT_SUFFIX` fixes it.
  ```
  unzip -l manywheel-py3_13-cpu.whl | grep 'torch/_C\.cpython'
  # -> only torch/_C.cpython-313-x86_64-linux-gnu.so
  ```

### Coverage notes

- **NNAPI MSVC link-flag fix** and **Windows venv `pythonXX.lib`
  discovery fix** are not exercised by the ROCm-Linux artifacts
  above. They are exercised by the Windows pull-CI (where NNAPI
  builds run and venv-based discovery is relevant); the green Windows
  CI is the evidence for those.
- ROCm wheels are Linux-only by build matrix
  (`.github/scripts/generate_binary_build_matrix.py:130-135`,
  `supported_platforms=["Linux"]`).

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180243
Approved by: https://github.com/malfet
pytorchmergebot pushed a commit that referenced this pull request Jul 21, 2026
Switch pyproject.toml's build backend from setuptools to
scikit-build-core (>= 1.0), which invokes CMake directly instead of
having setup.py orchestrate it. This PR makes the backend swap plus the
1.0-native configuration it enables; the now-unused setuptools code is
removed separately in #180248, so this diff stays focused and is
revertible on its own.

Where to look, in order of importance:
- pyproject.toml: the new [build-system], the scikit-build-core config
  (the [tool.scikit-build.env] table, cmake defines, wheel layout,
  editable mode), and the dynamic-metadata hooks. This is the heart of
  the change.
- tools/metadata/{version,dependencies}.py: the providers backing those
  hooks -- wheel version (from generate_torch_version) and dependencies
  (base + CUDA/ROCm extras).
- CMakeLists.txt: project name/version now come from SKBUILD_* with
  fallbacks so a standalone `cmake` invocation still works.
- torch/__init__.py, torch/_utils_internal.py: import-time shims that
  keep editable installs working under the new backend. scikit-build-core's
  redirect finder resolves the extension module itself (`import torch._C`);
  the shims only cover the places PyTorch locates native artifacts by hand,
  off `__file__`, which the import system never sees: the `ctypes.CDLL`
  preload of libtorch_global_deps, the Windows `os.add_dll_directory` for
  `_C`'s dependent DLLs, and the `bin/` data-file path. Redirect mode is the
  first layout to split the Python sources (checkout) from the compiled
  artifacts (install tree); in wheel and `setup.py develop` installs they
  sat together, so those `dirname(__file__)` lookups happened to be right.
- CONTRIBUTING.md: documents the editable-install flow, including
  scikit-build-core's optional rebuild-on-import (SKBUILD_EDITABLE_REBUILD),
  which stays off by default.
- tools/linter/adapters/codespell_linter.py: works around a codespell bug (it
  crashes reading a pyproject.toml with an array-of-tables under [tool], which
  our new [[tool.dynamic-metadata]] introduces) by pointing codespell at the
  dictionary directly instead of `--toml pyproject.toml`. Reported upstream as
  codespell-project/codespell#3969.
The remainder is mechanical: CI scripts swap `python setup.py clean` for
`python -m spin clean` and probe for pyproject.toml instead of setup.py,
and the build-requirement files gain scikit-build-core.

The configuration uses the scikit-build-core 1.0 feature set, which keeps
several PyTorch-specific workarounds out of the tree:
- MAX_JOBS -> CMAKE_BUILD_PARALLEL_LEVEL is aliased in the
  [tool.scikit-build.env] table (added upstream in scikit-build-core#1377
  for exactly this), so no custom PEP 517 wrapper backend is needed -- the
  backend is plain scikit_build_core.build.
- Dynamic version/dependencies use the stable [[tool.dynamic-metadata]]
  table (no experimental flag); the dependencies provider marks deps
  Dynamic in the sdist via a dynamic_wheel hook.
- Build type comes from the environment: 1.0 honors CMAKE_BUILD_TYPE
  natively, so only the DEBUG / REL_WITH_DEB_INFO env-var overrides remain.
- Per-image Linux compiler handling is CC/CXX = { env = ... } in the env
  table, which opts out of scikit-build-core's sysconfig-compiler injection
  (documented behavior since #1377) and lets CMake detect the compiler from
  PATH -- what green setup.py builds always did -- replacing two per-image
  cmake.define overrides.
- The Windows Ninja generator is cmake.define.CMAKE_GENERATOR in a win32
  override (1.0's generator-resolution chain honors it), so pyproject is the
  single source of truth and a plain editable Windows build gets Ninja too;
  the CI scripts no longer export CMAKE_GENERATOR.

The build-system floor and requirements-build.txt are scikit-build-core
>= 1.0; minimum-version pins the schema to that floor; and the CI pin
(.ci/docker/requirements-ci.txt) plus the Windows build-dep installers are
== 1.0.0. scikit-build-core 1.0.0 released 2026-07-06.

## Test plan

Wheel content-equivalent to the setuptools build (#180243), fresh cp312
CPU artifacts:
- [x] **Wheel size**: 193,274,760 B vs #180243 193,263,155 B (+0.006 %).
- [x] **Manifest diff**: adds only 6 license files and removes the
  setuptools-specific `top_level.txt`; no layout spillage.
  ```
  diff <(unzip -Z1 243.whl | sort) <(unzip -Z1 247.whl | sort)
  ```
- [x] **METADATA / version.py** identical bar `git_version` and the extra
  License-File entries; exactly one `_C.cpython-312.so`; aotriton payload
  intact (10,612 `aotriton.images/` kernels across 6 arches).
- [x] **Build time**: no regression; manywheel builds faster (the gain is
  packaging, not compilation).

Clean-build + editable import against the released scikit-build-core 1.0.0:
- [x] Linux (qgpu3, CUDA op), macOS (qmac, MPS), Windows (win11 VM): fresh
  `pip install -e . --no-build-isolation` builds and `import torch`
  resolves the CMake-built native artifacts from the install location. The
  Windows run also confirmed the Ninja generator comes purely from
  pyproject (no CMAKE_GENERATOR env var; build.ninja present, no .sln).
- [x] lintrunner -a clean (two pre-existing torch.bcomplex32 PYREFLY errors
  in torch/storage.py + torch/testing/_creation.py are on trunk, untouched).

Re-validated on this PR's CI (carries ciflow/trunk): the dropped per-image
Linux compiler overrides, exercised by the anaconda (conda-gcc11,
compiler_compat) and aarch64 image builds -- the two cases those overrides
originally fixed.

Based on a patch by Henry Schreiner (scikit-build-core maintainer); the env
table (scikit-build-core#1377) was added upstream specifically to let
PyTorch delete its wrapper backend.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: #180247
Approved by: https://github.com/atalman, https://github.com/albanD
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…0247)

Switch pyproject.toml's build backend from setuptools to
scikit-build-core (>= 1.0), which invokes CMake directly instead of
having setup.py orchestrate it. This PR makes the backend swap plus the
1.0-native configuration it enables; the now-unused setuptools code is
removed separately in pytorch#180248, so this diff stays focused and is
revertible on its own.

Where to look, in order of importance:
- pyproject.toml: the new [build-system], the scikit-build-core config
  (the [tool.scikit-build.env] table, cmake defines, wheel layout,
  editable mode), and the dynamic-metadata hooks. This is the heart of
  the change.
- tools/metadata/{version,dependencies}.py: the providers backing those
  hooks -- wheel version (from generate_torch_version) and dependencies
  (base + CUDA/ROCm extras).
- CMakeLists.txt: project name/version now come from SKBUILD_* with
  fallbacks so a standalone `cmake` invocation still works.
- torch/__init__.py, torch/_utils_internal.py: import-time shims that
  keep editable installs working under the new backend. scikit-build-core's
  redirect finder resolves the extension module itself (`import torch._C`);
  the shims only cover the places PyTorch locates native artifacts by hand,
  off `__file__`, which the import system never sees: the `ctypes.CDLL`
  preload of libtorch_global_deps, the Windows `os.add_dll_directory` for
  `_C`'s dependent DLLs, and the `bin/` data-file path. Redirect mode is the
  first layout to split the Python sources (checkout) from the compiled
  artifacts (install tree); in wheel and `setup.py develop` installs they
  sat together, so those `dirname(__file__)` lookups happened to be right.
- CONTRIBUTING.md: documents the editable-install flow, including
  scikit-build-core's optional rebuild-on-import (SKBUILD_EDITABLE_REBUILD),
  which stays off by default.
- tools/linter/adapters/codespell_linter.py: works around a codespell bug (it
  crashes reading a pyproject.toml with an array-of-tables under [tool], which
  our new [[tool.dynamic-metadata]] introduces) by pointing codespell at the
  dictionary directly instead of `--toml pyproject.toml`. Reported upstream as
  codespell-project/codespell#3969.
The remainder is mechanical: CI scripts swap `python setup.py clean` for
`python -m spin clean` and probe for pyproject.toml instead of setup.py,
and the build-requirement files gain scikit-build-core.

The configuration uses the scikit-build-core 1.0 feature set, which keeps
several PyTorch-specific workarounds out of the tree:
- MAX_JOBS -> CMAKE_BUILD_PARALLEL_LEVEL is aliased in the
  [tool.scikit-build.env] table (added upstream in scikit-build-core#1377
  for exactly this), so no custom PEP 517 wrapper backend is needed -- the
  backend is plain scikit_build_core.build.
- Dynamic version/dependencies use the stable [[tool.dynamic-metadata]]
  table (no experimental flag); the dependencies provider marks deps
  Dynamic in the sdist via a dynamic_wheel hook.
- Build type comes from the environment: 1.0 honors CMAKE_BUILD_TYPE
  natively, so only the DEBUG / REL_WITH_DEB_INFO env-var overrides remain.
- Per-image Linux compiler handling is CC/CXX = { env = ... } in the env
  table, which opts out of scikit-build-core's sysconfig-compiler injection
  (documented behavior since pytorch#1377) and lets CMake detect the compiler from
  PATH -- what green setup.py builds always did -- replacing two per-image
  cmake.define overrides.
- The Windows Ninja generator is cmake.define.CMAKE_GENERATOR in a win32
  override (1.0's generator-resolution chain honors it), so pyproject is the
  single source of truth and a plain editable Windows build gets Ninja too;
  the CI scripts no longer export CMAKE_GENERATOR.

The build-system floor and requirements-build.txt are scikit-build-core
>= 1.0; minimum-version pins the schema to that floor; and the CI pin
(.ci/docker/requirements-ci.txt) plus the Windows build-dep installers are
== 1.0.0. scikit-build-core 1.0.0 released 2026-07-06.

## Test plan

Wheel content-equivalent to the setuptools build (pytorch#180243), fresh cp312
CPU artifacts:
- [x] **Wheel size**: 193,274,760 B vs pytorch#180243 193,263,155 B (+0.006 %).
- [x] **Manifest diff**: adds only 6 license files and removes the
  setuptools-specific `top_level.txt`; no layout spillage.
  ```
  diff <(unzip -Z1 243.whl | sort) <(unzip -Z1 247.whl | sort)
  ```
- [x] **METADATA / version.py** identical bar `git_version` and the extra
  License-File entries; exactly one `_C.cpython-312.so`; aotriton payload
  intact (10,612 `aotriton.images/` kernels across 6 arches).
- [x] **Build time**: no regression; manywheel builds faster (the gain is
  packaging, not compilation).

Clean-build + editable import against the released scikit-build-core 1.0.0:
- [x] Linux (qgpu3, CUDA op), macOS (qmac, MPS), Windows (win11 VM): fresh
  `pip install -e . --no-build-isolation` builds and `import torch`
  resolves the CMake-built native artifacts from the install location. The
  Windows run also confirmed the Ninja generator comes purely from
  pyproject (no CMAKE_GENERATOR env var; build.ninja present, no .sln).
- [x] lintrunner -a clean (two pre-existing torch.bcomplex32 PYREFLY errors
  in torch/storage.py + torch/testing/_creation.py are on trunk, untouched).

Re-validated on this PR's CI (carries ciflow/trunk): the dropped per-image
Linux compiler overrides, exercised by the anaconda (conda-gcc11,
compiler_compat) and aarch64 image builds -- the two cases those overrides
originally fixed.

Based on a patch by Henry Schreiner (scikit-build-core maintainer); the env
table (scikit-build-core#1377) was added upstream specifically to let
PyTorch delete its wrapper backend.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180247
Approved by: https://github.com/atalman, https://github.com/albanD
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…0247)

Switch pyproject.toml's build backend from setuptools to
scikit-build-core (>= 1.0), which invokes CMake directly instead of
having setup.py orchestrate it. This PR makes the backend swap plus the
1.0-native configuration it enables; the now-unused setuptools code is
removed separately in pytorch#180248, so this diff stays focused and is
revertible on its own.

Where to look, in order of importance:
- pyproject.toml: the new [build-system], the scikit-build-core config
  (the [tool.scikit-build.env] table, cmake defines, wheel layout,
  editable mode), and the dynamic-metadata hooks. This is the heart of
  the change.
- tools/metadata/{version,dependencies}.py: the providers backing those
  hooks -- wheel version (from generate_torch_version) and dependencies
  (base + CUDA/ROCm extras).
- CMakeLists.txt: project name/version now come from SKBUILD_* with
  fallbacks so a standalone `cmake` invocation still works.
- torch/__init__.py, torch/_utils_internal.py: import-time shims that
  keep editable installs working under the new backend. scikit-build-core's
  redirect finder resolves the extension module itself (`import torch._C`);
  the shims only cover the places PyTorch locates native artifacts by hand,
  off `__file__`, which the import system never sees: the `ctypes.CDLL`
  preload of libtorch_global_deps, the Windows `os.add_dll_directory` for
  `_C`'s dependent DLLs, and the `bin/` data-file path. Redirect mode is the
  first layout to split the Python sources (checkout) from the compiled
  artifacts (install tree); in wheel and `setup.py develop` installs they
  sat together, so those `dirname(__file__)` lookups happened to be right.
- CONTRIBUTING.md: documents the editable-install flow, including
  scikit-build-core's optional rebuild-on-import (SKBUILD_EDITABLE_REBUILD),
  which stays off by default.
- tools/linter/adapters/codespell_linter.py: works around a codespell bug (it
  crashes reading a pyproject.toml with an array-of-tables under [tool], which
  our new [[tool.dynamic-metadata]] introduces) by pointing codespell at the
  dictionary directly instead of `--toml pyproject.toml`. Reported upstream as
  codespell-project/codespell#3969.
The remainder is mechanical: CI scripts swap `python setup.py clean` for
`python -m spin clean` and probe for pyproject.toml instead of setup.py,
and the build-requirement files gain scikit-build-core.

The configuration uses the scikit-build-core 1.0 feature set, which keeps
several PyTorch-specific workarounds out of the tree:
- MAX_JOBS -> CMAKE_BUILD_PARALLEL_LEVEL is aliased in the
  [tool.scikit-build.env] table (added upstream in scikit-build-core#1377
  for exactly this), so no custom PEP 517 wrapper backend is needed -- the
  backend is plain scikit_build_core.build.
- Dynamic version/dependencies use the stable [[tool.dynamic-metadata]]
  table (no experimental flag); the dependencies provider marks deps
  Dynamic in the sdist via a dynamic_wheel hook.
- Build type comes from the environment: 1.0 honors CMAKE_BUILD_TYPE
  natively, so only the DEBUG / REL_WITH_DEB_INFO env-var overrides remain.
- Per-image Linux compiler handling is CC/CXX = { env = ... } in the env
  table, which opts out of scikit-build-core's sysconfig-compiler injection
  (documented behavior since pytorch#1377) and lets CMake detect the compiler from
  PATH -- what green setup.py builds always did -- replacing two per-image
  cmake.define overrides.
- The Windows Ninja generator is cmake.define.CMAKE_GENERATOR in a win32
  override (1.0's generator-resolution chain honors it), so pyproject is the
  single source of truth and a plain editable Windows build gets Ninja too;
  the CI scripts no longer export CMAKE_GENERATOR.

The build-system floor and requirements-build.txt are scikit-build-core
>= 1.0; minimum-version pins the schema to that floor; and the CI pin
(.ci/docker/requirements-ci.txt) plus the Windows build-dep installers are
== 1.0.0. scikit-build-core 1.0.0 released 2026-07-06.

## Test plan

Wheel content-equivalent to the setuptools build (pytorch#180243), fresh cp312
CPU artifacts:
- [x] **Wheel size**: 193,274,760 B vs pytorch#180243 193,263,155 B (+0.006 %).
- [x] **Manifest diff**: adds only 6 license files and removes the
  setuptools-specific `top_level.txt`; no layout spillage.
  ```
  diff <(unzip -Z1 243.whl | sort) <(unzip -Z1 247.whl | sort)
  ```
- [x] **METADATA / version.py** identical bar `git_version` and the extra
  License-File entries; exactly one `_C.cpython-312.so`; aotriton payload
  intact (10,612 `aotriton.images/` kernels across 6 arches).
- [x] **Build time**: no regression; manywheel builds faster (the gain is
  packaging, not compilation).

Clean-build + editable import against the released scikit-build-core 1.0.0:
- [x] Linux (qgpu3, CUDA op), macOS (qmac, MPS), Windows (win11 VM): fresh
  `pip install -e . --no-build-isolation` builds and `import torch`
  resolves the CMake-built native artifacts from the install location. The
  Windows run also confirmed the Ninja generator comes purely from
  pyproject (no CMAKE_GENERATOR env var; build.ninja present, no .sln).
- [x] lintrunner -a clean (two pre-existing torch.bcomplex32 PYREFLY errors
  in torch/storage.py + torch/testing/_creation.py are on trunk, untouched).

Re-validated on this PR's CI (carries ciflow/trunk): the dropped per-image
Linux compiler overrides, exercised by the anaconda (conda-gcc11,
compiler_compat) and aarch64 image builds -- the two cases those overrides
originally fixed.

Based on a patch by Henry Schreiner (scikit-build-core maintainer); the env
table (scikit-build-core#1377) was added upstream specifically to let
PyTorch delete its wrapper backend.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180247
Approved by: https://github.com/atalman, https://github.com/albanD
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
)

Move the build of the `torch._C` Python extension and the install of
`torch/version.py` from `setup.py` into `torch/CMakeLists.txt`, so
both the existing setuptools backend and the upcoming
scikit-build-core backend (pytorch#180247) go through the same code path.
The new `Python_add_library(_C MODULE WITH_SOABI ...)` target builds
the same `torch/csrc/stub.c` and installs at the wheel root (mapped to
`torch/` by `wheel.install-dir`); `setup.py`'s `Extension("torch._C",
...)` block and its companion `extra_compile_args` /
`extra_link_args` / `make_relative_rpath_args` plumbing are removed.
`version.py` is gitignored, so it is installed explicitly via
`install(FILES ... DESTINATION ".")` rather than relying on Python
package collection.

Adds a `BinaryDistribution` class in `setup.py` that forces
`has_ext_modules=True` so `bdist_wheel` uses the binary layout
(package_data + data_files only) instead of the purelib layout, which
would otherwise dump CMake's `build/lib/` tree -- including test
artifacts -- into the wheel root. `package_data` collects the
CMake-built extension via the interpreter's exact module name
(`f"_C{sysconfig.get_config_var('EXT_SUFFIX')}"`) rather than a `_C*`
glob, so a `build/` dir reused across Python versions cannot leak
other ABIs' `_C` modules into the wheel.

Windows handling: the manual `setup.py` copy of `_C.lib` from
`build_temp` to `build_lib` is replaced by the `_C` target's
`ARCHIVE DESTINATION "lib"`. For MSVC, the linker is told where to
find `pythonXX.lib` via `/LIBPATH` (Python headers use `#pragma
comment(lib, "pythonXX")` which expects a bare-name lookup); for
Windows venvs, FindPython's library search path is extended with
`sys.base_prefix/libs` since the import library lives in the base
install, not the venv. `nnapi_backend` gains
`TORCH_PYTHON_LINK_FLAGS` so it picks up the same MSVC linker
options as `torch_python`.

## Test plan

Verification is via artifact-content comparison against the parent
(pytorch#180242). Expectation: the wheel must be content-equivalent modulo
the one file the PR rebuilds (`torch/_C.cpython-*.so`), which must
remain functionally identical (same exports, same imports, same
rpath).

- [x] **No regression in artifact sizes** across every manywheel /
  libtorch artifact (sub-0.001 % to 0.001 % delta, zip-timestamp
  noise consistent across artifacts this PR can't directly affect):

  | artifact | parent (pytorch#180242) | this PR (pytorch#180243) | delta |
  | --- | ---: | ---: | ---: |
  | manywheel-py3_12-rocm7_2 | 6,153,280,701 | 6,153,275,144 | -5,557 (-0.000%) |
  | manywheel-py3_12-rocm7_1 | 5,788,503,789 | 5,788,499,957 | -3,832 (-0.000%) |
  | manywheel-py3_12-cuda12_6 | 841,797,521 | 841,797,813 | +292 (+0.000%) |
  | manywheel-py3_12-cuda13_2 | 624,213,880 | 624,212,127 | -1,753 (-0.000%) |
  | manywheel-py3_12-cpu | 189,248,452 | 189,248,117 | -335 (-0.000%) |
  | manywheel-py3_12-xpu | 778,712,445 | 778,711,285 | -1,160 (-0.000%) |
  | libtorch-rocm7_2-shared-with-deps-release | 12,117,315,856 | 12,117,314,539 | -1,317 (-0.000%) |
  | libtorch-cpu-shared-with-deps-release | 257,626,615 | 257,624,612 | -2,003 (-0.001%) |

- [x] **Wheel manifest equivalence vs parent**
  (`manywheel-py3_12-rocm7_2`): both wheels contain **26,779 entries**;
  filename diff is empty -- no files added or removed. Confirms the
  `BinaryDistribution` layout fix worked (no `build/lib/` spillage
  into the wheel root).

- [x] **Per-file size diff: exactly one file changed.**
  ```
  torch/_C.cpython-312-x86_64-linux-gnu.so   22,960  ->  15,720   (-7,240)
  ```
  Every other one of 26,778 files is byte-identical in size. That is
  precisely the file the PR rebuilds via CMake.

- [x] **`torch._C` is functionally equivalent** between parent and PR.
  Extracted both `.so` files and compared:
  - **Defined symbols**: zero-line diff.
  - **Undefined symbols** (imports from `libtorch_python`): zero-line
    diff.
  - **RPATH**: identical (`$ORIGIN:$ORIGIN/lib`).
  - **NEEDED**: 180242's `.so` includes a redundant
    `libpthread.so.0` (merged into `libc.so.6` since glibc 2.34); the
    CMake build drops it. The size shrinkage matches the cleaner
    NEEDED + tighter section layout from the CMake toolchain.

- [x] **`torch/version.py`** is present in both wheels at 339 bytes,
  byte-identical except for the expected `git_version` SHA (each
  commit has its own). `__version__`, `debug`, `cuda`, `hip`, `rocm`,
  `xpu` fields all match -- the CMake-driven generation produces the
  same output as the setuptools path.

- [x] **Exactly one `_C` ABI per wheel.** On a fresh multi-ABI
  `manywheel-cpu-build` (build_all.sh builds all CPython ABIs in one
  checkout), each wheel ships only its own `torch/_C.cpython-XY.so`.
  An earlier greedy `_C*.so` `package_data` glob leaked stale per-ABI
  stubs (a cp312 wheel carried cp310/cp311/cp312); pinning to the
  exact `EXT_SUFFIX` fixes it.
  ```
  unzip -l manywheel-py3_13-cpu.whl | grep 'torch/_C\.cpython'
  # -> only torch/_C.cpython-313-x86_64-linux-gnu.so
  ```

### Coverage notes

- **NNAPI MSVC link-flag fix** and **Windows venv `pythonXX.lib`
  discovery fix** are not exercised by the ROCm-Linux artifacts
  above. They are exercised by the Windows pull-CI (where NNAPI
  builds run and venv-based discovery is relevant); the green Windows
  CI is the evidence for those.
- ROCm wheels are Linux-only by build matrix
  (`.github/scripts/generate_binary_build_matrix.py:130-135`,
  `supported_platforms=["Linux"]`).

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180243
Approved by: https://github.com/malfet
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…0247)

Switch pyproject.toml's build backend from setuptools to
scikit-build-core (>= 1.0), which invokes CMake directly instead of
having setup.py orchestrate it. This PR makes the backend swap plus the
1.0-native configuration it enables; the now-unused setuptools code is
removed separately in pytorch#180248, so this diff stays focused and is
revertible on its own.

Where to look, in order of importance:
- pyproject.toml: the new [build-system], the scikit-build-core config
  (the [tool.scikit-build.env] table, cmake defines, wheel layout,
  editable mode), and the dynamic-metadata hooks. This is the heart of
  the change.
- tools/metadata/{version,dependencies}.py: the providers backing those
  hooks -- wheel version (from generate_torch_version) and dependencies
  (base + CUDA/ROCm extras).
- CMakeLists.txt: project name/version now come from SKBUILD_* with
  fallbacks so a standalone `cmake` invocation still works.
- torch/__init__.py, torch/_utils_internal.py: import-time shims that
  keep editable installs working under the new backend. scikit-build-core's
  redirect finder resolves the extension module itself (`import torch._C`);
  the shims only cover the places PyTorch locates native artifacts by hand,
  off `__file__`, which the import system never sees: the `ctypes.CDLL`
  preload of libtorch_global_deps, the Windows `os.add_dll_directory` for
  `_C`'s dependent DLLs, and the `bin/` data-file path. Redirect mode is the
  first layout to split the Python sources (checkout) from the compiled
  artifacts (install tree); in wheel and `setup.py develop` installs they
  sat together, so those `dirname(__file__)` lookups happened to be right.
- CONTRIBUTING.md: documents the editable-install flow, including
  scikit-build-core's optional rebuild-on-import (SKBUILD_EDITABLE_REBUILD),
  which stays off by default.
- tools/linter/adapters/codespell_linter.py: works around a codespell bug (it
  crashes reading a pyproject.toml with an array-of-tables under [tool], which
  our new [[tool.dynamic-metadata]] introduces) by pointing codespell at the
  dictionary directly instead of `--toml pyproject.toml`. Reported upstream as
  codespell-project/codespell#3969.
The remainder is mechanical: CI scripts swap `python setup.py clean` for
`python -m spin clean` and probe for pyproject.toml instead of setup.py,
and the build-requirement files gain scikit-build-core.

The configuration uses the scikit-build-core 1.0 feature set, which keeps
several PyTorch-specific workarounds out of the tree:
- MAX_JOBS -> CMAKE_BUILD_PARALLEL_LEVEL is aliased in the
  [tool.scikit-build.env] table (added upstream in scikit-build-core#1377
  for exactly this), so no custom PEP 517 wrapper backend is needed -- the
  backend is plain scikit_build_core.build.
- Dynamic version/dependencies use the stable [[tool.dynamic-metadata]]
  table (no experimental flag); the dependencies provider marks deps
  Dynamic in the sdist via a dynamic_wheel hook.
- Build type comes from the environment: 1.0 honors CMAKE_BUILD_TYPE
  natively, so only the DEBUG / REL_WITH_DEB_INFO env-var overrides remain.
- Per-image Linux compiler handling is CC/CXX = { env = ... } in the env
  table, which opts out of scikit-build-core's sysconfig-compiler injection
  (documented behavior since pytorch#1377) and lets CMake detect the compiler from
  PATH -- what green setup.py builds always did -- replacing two per-image
  cmake.define overrides.
- The Windows Ninja generator is cmake.define.CMAKE_GENERATOR in a win32
  override (1.0's generator-resolution chain honors it), so pyproject is the
  single source of truth and a plain editable Windows build gets Ninja too;
  the CI scripts no longer export CMAKE_GENERATOR.

The build-system floor and requirements-build.txt are scikit-build-core
>= 1.0; minimum-version pins the schema to that floor; and the CI pin
(.ci/docker/requirements-ci.txt) plus the Windows build-dep installers are
== 1.0.0. scikit-build-core 1.0.0 released 2026-07-06.

## Test plan

Wheel content-equivalent to the setuptools build (pytorch#180243), fresh cp312
CPU artifacts:
- [x] **Wheel size**: 193,274,760 B vs pytorch#180243 193,263,155 B (+0.006 %).
- [x] **Manifest diff**: adds only 6 license files and removes the
  setuptools-specific `top_level.txt`; no layout spillage.
  ```
  diff <(unzip -Z1 243.whl | sort) <(unzip -Z1 247.whl | sort)
  ```
- [x] **METADATA / version.py** identical bar `git_version` and the extra
  License-File entries; exactly one `_C.cpython-312.so`; aotriton payload
  intact (10,612 `aotriton.images/` kernels across 6 arches).
- [x] **Build time**: no regression; manywheel builds faster (the gain is
  packaging, not compilation).

Clean-build + editable import against the released scikit-build-core 1.0.0:
- [x] Linux (qgpu3, CUDA op), macOS (qmac, MPS), Windows (win11 VM): fresh
  `pip install -e . --no-build-isolation` builds and `import torch`
  resolves the CMake-built native artifacts from the install location. The
  Windows run also confirmed the Ninja generator comes purely from
  pyproject (no CMAKE_GENERATOR env var; build.ninja present, no .sln).
- [x] lintrunner -a clean (two pre-existing torch.bcomplex32 PYREFLY errors
  in torch/storage.py + torch/testing/_creation.py are on trunk, untouched).

Re-validated on this PR's CI (carries ciflow/trunk): the dropped per-image
Linux compiler overrides, exercised by the anaconda (conda-gcc11,
compiler_compat) and aarch64 image builds -- the two cases those overrides
originally fixed.

Based on a patch by Henry Schreiner (scikit-build-core maintainer); the env
table (scikit-build-core#1377) was added upstream specifically to let
PyTorch delete its wrapper backend.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180247
Approved by: https://github.com/atalman, https://github.com/albanD
MelindaTan pushed a commit to MelindaTan/pytorch that referenced this pull request Jul 31, 2026
…0247)

Switch pyproject.toml's build backend from setuptools to
scikit-build-core (>= 1.0), which invokes CMake directly instead of
having setup.py orchestrate it. This PR makes the backend swap plus the
1.0-native configuration it enables; the now-unused setuptools code is
removed separately in pytorch#180248, so this diff stays focused and is
revertible on its own.

Where to look, in order of importance:
- pyproject.toml: the new [build-system], the scikit-build-core config
  (the [tool.scikit-build.env] table, cmake defines, wheel layout,
  editable mode), and the dynamic-metadata hooks. This is the heart of
  the change.
- tools/metadata/{version,dependencies}.py: the providers backing those
  hooks -- wheel version (from generate_torch_version) and dependencies
  (base + CUDA/ROCm extras).
- CMakeLists.txt: project name/version now come from SKBUILD_* with
  fallbacks so a standalone `cmake` invocation still works.
- torch/__init__.py, torch/_utils_internal.py: import-time shims that
  keep editable installs working under the new backend. scikit-build-core's
  redirect finder resolves the extension module itself (`import torch._C`);
  the shims only cover the places PyTorch locates native artifacts by hand,
  off `__file__`, which the import system never sees: the `ctypes.CDLL`
  preload of libtorch_global_deps, the Windows `os.add_dll_directory` for
  `_C`'s dependent DLLs, and the `bin/` data-file path. Redirect mode is the
  first layout to split the Python sources (checkout) from the compiled
  artifacts (install tree); in wheel and `setup.py develop` installs they
  sat together, so those `dirname(__file__)` lookups happened to be right.
- CONTRIBUTING.md: documents the editable-install flow, including
  scikit-build-core's optional rebuild-on-import (SKBUILD_EDITABLE_REBUILD),
  which stays off by default.
- tools/linter/adapters/codespell_linter.py: works around a codespell bug (it
  crashes reading a pyproject.toml with an array-of-tables under [tool], which
  our new [[tool.dynamic-metadata]] introduces) by pointing codespell at the
  dictionary directly instead of `--toml pyproject.toml`. Reported upstream as
  codespell-project/codespell#3969.
The remainder is mechanical: CI scripts swap `python setup.py clean` for
`python -m spin clean` and probe for pyproject.toml instead of setup.py,
and the build-requirement files gain scikit-build-core.

The configuration uses the scikit-build-core 1.0 feature set, which keeps
several PyTorch-specific workarounds out of the tree:
- MAX_JOBS -> CMAKE_BUILD_PARALLEL_LEVEL is aliased in the
  [tool.scikit-build.env] table (added upstream in scikit-build-core#1377
  for exactly this), so no custom PEP 517 wrapper backend is needed -- the
  backend is plain scikit_build_core.build.
- Dynamic version/dependencies use the stable [[tool.dynamic-metadata]]
  table (no experimental flag); the dependencies provider marks deps
  Dynamic in the sdist via a dynamic_wheel hook.
- Build type comes from the environment: 1.0 honors CMAKE_BUILD_TYPE
  natively, so only the DEBUG / REL_WITH_DEB_INFO env-var overrides remain.
- Per-image Linux compiler handling is CC/CXX = { env = ... } in the env
  table, which opts out of scikit-build-core's sysconfig-compiler injection
  (documented behavior since pytorch#1377) and lets CMake detect the compiler from
  PATH -- what green setup.py builds always did -- replacing two per-image
  cmake.define overrides.
- The Windows Ninja generator is cmake.define.CMAKE_GENERATOR in a win32
  override (1.0's generator-resolution chain honors it), so pyproject is the
  single source of truth and a plain editable Windows build gets Ninja too;
  the CI scripts no longer export CMAKE_GENERATOR.

The build-system floor and requirements-build.txt are scikit-build-core
>= 1.0; minimum-version pins the schema to that floor; and the CI pin
(.ci/docker/requirements-ci.txt) plus the Windows build-dep installers are
== 1.0.0. scikit-build-core 1.0.0 released 2026-07-06.

## Test plan

Wheel content-equivalent to the setuptools build (pytorch#180243), fresh cp312
CPU artifacts:
- [x] **Wheel size**: 193,274,760 B vs pytorch#180243 193,263,155 B (+0.006 %).
- [x] **Manifest diff**: adds only 6 license files and removes the
  setuptools-specific `top_level.txt`; no layout spillage.
  ```
  diff <(unzip -Z1 243.whl | sort) <(unzip -Z1 247.whl | sort)
  ```
- [x] **METADATA / version.py** identical bar `git_version` and the extra
  License-File entries; exactly one `_C.cpython-312.so`; aotriton payload
  intact (10,612 `aotriton.images/` kernels across 6 arches).
- [x] **Build time**: no regression; manywheel builds faster (the gain is
  packaging, not compilation).

Clean-build + editable import against the released scikit-build-core 1.0.0:
- [x] Linux (qgpu3, CUDA op), macOS (qmac, MPS), Windows (win11 VM): fresh
  `pip install -e . --no-build-isolation` builds and `import torch`
  resolves the CMake-built native artifacts from the install location. The
  Windows run also confirmed the Ninja generator comes purely from
  pyproject (no CMAKE_GENERATOR env var; build.ninja present, no .sln).
- [x] lintrunner -a clean (two pre-existing torch.bcomplex32 PYREFLY errors
  in torch/storage.py + torch/testing/_creation.py are on trunk, untouched).

Re-validated on this PR's CI (carries ciflow/trunk): the dropped per-image
Linux compiler overrides, exercised by the anaconda (conda-gcc11,
compiler_compat) and aarch64 image builds -- the two cases those overrides
originally fixed.

Based on a patch by Henry Schreiner (scikit-build-core maintainer); the env
table (scikit-build-core#1377) was added upstream specifically to let
PyTorch delete its wrapper backend.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180247
Approved by: https://github.com/atalman, https://github.com/albanD
zklaus added a commit to zklaus/pytorch that referenced this pull request Aug 18, 2026
…d suffix

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 pytorch#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 collected by install(TARGETS _C ...) in
torch/CMakeLists.txt, so it now 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(), so a cross
setup that passes them that way now genuinely enters cross-compile mode. Such a
build previously stayed in native mode -- CMAKE_CROSSCOMPILING FALSE, and
FindPython computed Python_SOABI normally -- and so never produced an untagged
module. It now takes the empty-SOABI path as well, which makes this fix the
completion of that one 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. The empty case is both unambiguous and the
actual failure observed (an untagged _C.so).

This overrides Python_SOABI centrally rather than 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 holds here: the
last find is in this file, the override runs right after it, and the only later
use of FindPython -- cmake/public/cuda.cmake, re-included from torch/CMakeLists.txt
under USE_CUDA to hash libnvrtc -- is short-circuited on that second entry by the
already-computed CUDA_NVRTC_SHORTHASH. So the override is not threatened by a
lingering find_package and lands independently.

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

Authored with assistance from Claude Code.

Test Plan:
Confirmed in a standalone FindPython project that (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:

```
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
```

This equals f"_C{EXT_SUFFIX}" since EXT_SUFFIX == "." + SOABI + shared-module
suffix on Linux/macOS targets. Native builds are unchanged (the CMAKE_CROSSCOMPILING
guard is not taken; FindPython's Python_SOABI already equals EXT_SUFFIX there).

The pytorch#190003 interaction was checked separately on the same standalone project
(cmake 3.28.3), reproducing the empty-SOABI condition from both directions:

```
# native, no toolchain vars
cmake -S . -B b1                                   # CROSSCOMPILING=FALSE  SOABI=cpython-310-x86_64-linux-gnu
# env vars WITHOUT the pytorch#190003 forwarding block (pre-pytorch#190003 behaviour)
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b4
                                                   # CROSSCOMPILING=FALSE  SOABI=cpython-310-x86_64-linux-gnu
# env vars WITH the forwarding block (post-pytorch#190003)
CMAKE_SYSTEM_NAME=Linux CMAKE_SYSTEM_PROCESSOR=aarch64 cmake -S . -B b2
                                                   # CROSSCOMPILING=TRUE   SOABI=''
# -D flags (the conda-forge CMAKE_ARGS path)
cmake -S . -B b3 -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=aarch64
                                                   # CROSSCOMPILING=TRUE   SOABI=''
```

End-to-end validation is a conda-forge linux-aarch64 build
(pytorch-cpu-feedstock pytorch#526), where import torch._C succeeds.
zklaus added a commit to zklaus/pytorch that referenced this pull request Aug 18, 2026
_C is a CMake MODULE library, and MODULE targets do not produce a Windows import
library -- nothing links against a Python extension module. The ARCHIVE clause on
its install(TARGETS) rule therefore installs nothing, and the comment above it
described a torch/lib/_C.lib that has not shipped since pytorch#180243 removed it as
unconsumed.

Removing it also drops the one prefix-relative destination left in this rule,
which sat next to two absolute ones: the ARCHIVE path was resolved through
CMAKE_INSTALL_PREFIX while RUNTIME and LIBRARY addressed SKBUILD_PLATLIB_DIR
directly. That mixture is exactly what the first commit in this branch removes
everywhere else.

Authored with assistance from Claude Code.

Test Plan:
Confirmed against the 2026-08-18 Windows nightlies that no import library for _C
is produced, by reading each wheel's zip central directory (no full download):

```
torch-2.15.0.dev20260818+cpu-cp312-cp312-win_amd64.whl    _C.lib absent, 13 .lib files
torch-2.15.0.dev20260818+cu126-cp312-cp312-win_amd64.whl  _C.lib absent, 16 .lib files
torch-2.15.0.dev20260818+xpu-cp312-cp312-win_amd64.whl    _C.lib absent, 15 .lib files
```

Every .lib in those wheels is a genuine C++ import library (c10.lib, torch.lib,
torch_cpu.lib, torch_python.lib, sleef.lib, ...); _C ships only as
torch/_C.cp312-win_amd64.pyd. So this rule was already a no-op on the one
platform that could have exercised it, and wheel contents are unchanged.

Lint:

```
lintrunner -a torch/CMakeLists.txt
```
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
zklaus added a commit to zklaus/pytorch that referenced this pull request Aug 28, 2026
_C is a CMake MODULE library, and MODULE targets do not produce a Windows import
library -- nothing links against a Python extension module. The ARCHIVE clause on
its install(TARGETS) rule therefore installs nothing, and the comment above it
described a torch/lib/_C.lib that has not shipped since pytorch#180243 removed it as
unconsumed.

Removing it also drops the one prefix-relative destination left in this rule,
which sat next to two absolute ones: the ARCHIVE path was resolved through
CMAKE_INSTALL_PREFIX while RUNTIME and LIBRARY addressed SKBUILD_PLATLIB_DIR
directly. That mixture is exactly what the first commit in this branch removes
everywhere else.

Authored with assistance from Claude Code.

Test Plan:
Confirmed against the 2026-08-18 Windows nightlies that no import library for _C
is produced, by reading each wheel's zip central directory (no full download):

```
torch-2.15.0.dev20260818+cpu-cp312-cp312-win_amd64.whl    _C.lib absent, 13 .lib files
torch-2.15.0.dev20260818+cu126-cp312-cp312-win_amd64.whl  _C.lib absent, 16 .lib files
torch-2.15.0.dev20260818+xpu-cp312-cp312-win_amd64.whl    _C.lib absent, 15 .lib files
```

Every .lib in those wheels is a genuine C++ import library (c10.lib, torch.lib,
torch_cpu.lib, torch_python.lib, sleef.lib, ...); _C ships only as
torch/_C.cp312-win_amd64.pyd. So this rule was already a no-op on the one
platform that could have exercised it, and wheel contents are unchanged.

Lint:

```
lintrunner -a torch/CMakeLists.txt
```
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/binaries Trigger all binary build and upload jobs on the PR ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: releng release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants