Skip to content

Migrate build system from setuptools to scikit-build-core - #180247

Closed
zklaus wants to merge 76 commits into
gh/zklaus/53/basefrom
gh/zklaus/53/head
Closed

zklaus wants to merge 76 commits into
gh/zklaus/53/basefrom
gh/zklaus/53/head

Conversation

@zklaus

@zklaus zklaus commented Apr 13, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

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
    --toml crashes with AttributeError: 'list' object has no attribute 'items' on a pyproject.toml with an array-of-tables directly under [tool] (e.g. [[tool.dynamic-metadata]]) 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 add device asserts in scatter/gather kernels #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:

  • Wheel size: 193,274,760 B vs Build torch._C extension module and version.py via CMake #180243 193,263,155 B (+0.006 %).
  • 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)
    
  • 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).
  • 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:

  • 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).
  • 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

[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/180247

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

❗ 1 Active SEVs

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

❌ 77 Pending, 1 Unrelated Failure, 2 Unclassified Failures

As of commit 6da30a9 with merge base 2398dc2 (image):

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 job failed but was likely due to flakiness present on trunk:

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

@pytorch-bot pytorch-bot Bot added the release notes: releng release notes category label Apr 13, 2026
zklaus added a commit to zklaus/pytorch that referenced this pull request Apr 13, 2026
Switch the build backend in pyproject.toml from setuptools to
scikit-build-core. This eliminates the need for setup.py to orchestrate
CMake -- scikit-build-core calls CMake directly based on pyproject.toml
configuration.

Key changes:
- pyproject.toml: new build-system, scikit-build config for cmake
  defines, wheel layout, editable mode, and dynamic metadata
- CMakeLists.txt: project name/version from SKBUILD variables with
  fallbacks for standalone cmake invocations
- tools/metadata/version.py and dependencies.py: dynamic metadata
  providers for wheel version (from generate_torch_version) and
  dependencies (base + CUDA/ROCm extras)
- CI scripts: replace "python setup.py clean" with "rm -rf build",
  check for pyproject.toml instead of setup.py, install scikit-build-core
- requirements-build.txt and CI requirements: add scikit-build-core

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


ghstack-source-id: e25794a
Pull-Request: pytorch#180247
@zklaus
zklaus marked this pull request as ready for review April 14, 2026 18:32
@zklaus
zklaus requested review from a team and jeffdaily as code owners April 14, 2026 18:32
@zklaus zklaus added the ciflow/binaries Trigger all binary build and upload jobs on the PR label Apr 14, 2026
zklaus added a commit to zklaus/pytorch that referenced this pull request Apr 15, 2026
Switch the build backend in pyproject.toml from setuptools to
scikit-build-core. This eliminates the need for setup.py to orchestrate
CMake -- scikit-build-core calls CMake directly based on pyproject.toml
configuration.

Key changes:
- pyproject.toml: new build-system, scikit-build config for cmake
  defines, wheel layout, editable mode, and dynamic metadata
- CMakeLists.txt: project name/version from SKBUILD variables with
  fallbacks for standalone cmake invocations
- tools/metadata/version.py and dependencies.py: dynamic metadata
  providers for wheel version (from generate_torch_version) and
  dependencies (base + CUDA/ROCm extras)
- CI scripts: replace "python setup.py clean" with "rm -rf build",
  check for pyproject.toml instead of setup.py, install scikit-build-core
- requirements-build.txt and CI requirements: add scikit-build-core

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


ghstack-source-id: e25794a
Pull-Request: pytorch#180247
zklaus added a commit to zklaus/pytorch that referenced this pull request Apr 17, 2026
Switch the build backend in pyproject.toml from setuptools to
scikit-build-core. This eliminates the need for setup.py to orchestrate
CMake -- scikit-build-core calls CMake directly based on pyproject.toml
configuration.

Key changes:
- pyproject.toml: new build-system, scikit-build config for cmake
  defines, wheel layout, editable mode, and dynamic metadata
- CMakeLists.txt: project name/version from SKBUILD variables with
  fallbacks for standalone cmake invocations
- tools/metadata/version.py and dependencies.py: dynamic metadata
  providers for wheel version (from generate_torch_version) and
  dependencies (base + CUDA/ROCm extras)
- CI scripts: replace "python setup.py clean" with "rm -rf build",
  check for pyproject.toml instead of setup.py, install scikit-build-core
- requirements-build.txt and CI requirements: add scikit-build-core

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


ghstack-source-id: e25794a
Pull-Request: pytorch#180247
[ghstack-poisoned]
scotts added a commit to scotts/kineto that referenced this pull request Jul 22, 2026
Summary:
The profiler CI job builds PyTorch from source, then runs test/profiler/.
Collecting test_cpp_thread.py JIT-compiles a C++ extension and failed with:

  fatal error: torch/csrc/autograd/profiler_kineto.h: No such file or directory

PyTorch migrated its build from setuptools to scikit-build-core
(pytorch/pytorch#180247). Editable installs (pip install -e .) now use
redirect mode: Python modules resolve from the source tree while the
CMake-installed C++ headers under torch/include stay in the build tree.
torch.utils.cpp_extension derives its header search path from the source
tree's torch/include, which the editable install never populates, so no
installed torch header is found. The failure is not specific to
profiler_kineto.h; it is simply the first include in the test.

Drop -e so PyTorch installs as a normal wheel, which stages torch/include
into site-packages where cpp_extension finds it. CI builds once and never
edits the tree, so editable mode bought us nothing here.

Test Plan:
Re-run linux-cpu-pytorch-build-and-test; test/profiler/ collection now
compiles test_cpp_thread.cpp instead of failing on the missing header.

Authored with assistance from an AI agent (Claude Code).
pytorchmergebot pushed a commit that referenced this pull request Jul 22, 2026
…180248)

With the build fully driven by scikit-build-core (#180247), the
setuptools path is dead code. Remove the setuptools build helpers
(build_pytorch_libs, setup_helpers.{cmake,cmake_utils,env}, test_cmake)
and replace setup.py with a small shim that forwards `install` and
`develop` to pip and fails with instructions for everything else.
Retain a minimal build_libtorch.py -- it calls cmake directly and is
still used by the libtorch build path.

## Why a phased sunset instead of outright removal?

pip and `python -m build` never execute setup.py; the only way it still
runs is a direct `python setup.py <cmd>` invocation. For `install` and
`develop` we have redirected to pip since #152276; the shim keeps that
contract intact for two more releases so existing scripts keep working
while they migrate. Every other command (`build`, `bdist_wheel`,
`clean`, `sdist`, ...) used to fall through into the setuptools
machinery this PR deletes; emulating that interface is not worth it
(setuptools itself deprecated it in 2021), so those commands now fail
immediately, printing the replacement commands and the sunset schedule
-- a more helpful failure mode than `can't open file 'setup.py'` while
still surfacing not-yet-migrated callers.

The schedule is stated in the shim header and printed on every
invocation:

- PyTorch 2.14-2.15: `install`/`develop` forward to pip; all other
  commands fail with instructions
- PyTorch 2.16-2.17: all commands fail with instructions
- PyTorch 2.18: setup.py is removed

## Test plan

- [x] **Wheel byte-identical to parent #180247**: empty manifest diff,
  +10 B zip-timestamp noise. Removing the dead setuptools machinery does
  not change wheel content (it is never shipped, and scikit-build-core
  does not use it). The shim cannot change this: nothing installs the
  root setup.py into the wheel.
  ```
  diff <(unzip -Z1 247.whl | sort) <(unzip -Z1 248.whl | sort)   # empty
  ```
- [x] **Shim forwarding**: `install`/`develop` forward to pip with the
  exact #152276 command line, extra arguments are dropped with a
  warning, and pip's exit code is propagated (verified with a stub pip
  that prints its argv and exits 3):
  ```
  python setup.py develop --user   # pip install -v --no-build-isolation -e ., warns about dropped --user
  python setup.py install          # pip install -v --no-build-isolation .
  ```
- [x] **Shim guard**: every other command fails with exit code 1,
  printing the replacement commands and the sunset schedule:
  ```
  python setup.py bdist_wheel
  ```
- [x] **No dangling references** to the removed modules
  (`build_pytorch_libs`, `setup_helpers.{cmake,cmake_utils,env}`,
  `test_cmake`); the remaining `tools/setup_helpers` references point to
  surviving files (`generate_code.py`, `gen_version_header.py`,
  `generate_linker_script.py`).
  ```
  grep -rE 'build_pytorch_libs|setup_helpers\.(cmake|env)' --include='*.py' .
  ```
- [x] **0 build failures** across the matrix -- the removed path was
  genuinely dead.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: #180248
Approved by: https://github.com/albanD, https://github.com/atalman
pytorchmergebot pushed a commit that referenced this pull request Jul 23, 2026
**Problem**

Building a C++ or CUDA extension against a PyTorch installed in editable mode (`pip install -e .`) fails to find any installed torch header. The compile aborts on the first include, e.g.:
```
  fatal error: torch/csrc/autograd/profiler_kineto.h: No such file or directory
```
The recent migration to scikit-build-core changed editable installs so that compiled artifacts (the installed headers, libraries, and binaries) live in the installed package directory instead of the source tree. The C++ extension helper still looked for them under the source tree, which an editable install never populates, so extension builds lose their header and library search paths. Regular wheel installs are unaffected because their package directory and their import location are the same.

**Fix**

The scikit-build-core migration (#180247) already added `_compute_torch_parent` so `get_file_path` resolves to the installed package directory for editable installs, but `torch.utils.cpp_extension` still computed its own root from `dirname(dirname(__file__))`. Resolve `_TORCH_PATH` with `get_file_path("torch")` instead, so `cpp_extension` reuses that same editable-aware logic. `_TORCH_PATH` feeds every include, library, precompiled-header, and hipify path in the module, so this single change fixes all of them; non-editable installs resolve exactly as before.

Authored with assistance from an AI agent (Claude Code).
Pull Request resolved: #190829
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
requirements-build.txt was updated by pytorch#180247 to include additional dependencies for supporting scikit-build-core. This broke my local setup for building PyTorch using uv. This commit updates the dev dependencies.
Pull Request resolved: pytorch#190690
Approved by: https://github.com/Skylion007
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…ytorch#180248)

With the build fully driven by scikit-build-core (pytorch#180247), the
setuptools path is dead code. Remove the setuptools build helpers
(build_pytorch_libs, setup_helpers.{cmake,cmake_utils,env}, test_cmake)
and replace setup.py with a small shim that forwards `install` and
`develop` to pip and fails with instructions for everything else.
Retain a minimal build_libtorch.py -- it calls cmake directly and is
still used by the libtorch build path.

## Why a phased sunset instead of outright removal?

pip and `python -m build` never execute setup.py; the only way it still
runs is a direct `python setup.py <cmd>` invocation. For `install` and
`develop` we have redirected to pip since pytorch#152276; the shim keeps that
contract intact for two more releases so existing scripts keep working
while they migrate. Every other command (`build`, `bdist_wheel`,
`clean`, `sdist`, ...) used to fall through into the setuptools
machinery this PR deletes; emulating that interface is not worth it
(setuptools itself deprecated it in 2021), so those commands now fail
immediately, printing the replacement commands and the sunset schedule
-- a more helpful failure mode than `can't open file 'setup.py'` while
still surfacing not-yet-migrated callers.

The schedule is stated in the shim header and printed on every
invocation:

- PyTorch 2.14-2.15: `install`/`develop` forward to pip; all other
  commands fail with instructions
- PyTorch 2.16-2.17: all commands fail with instructions
- PyTorch 2.18: setup.py is removed

## Test plan

- [x] **Wheel byte-identical to parent pytorch#180247**: empty manifest diff,
  +10 B zip-timestamp noise. Removing the dead setuptools machinery does
  not change wheel content (it is never shipped, and scikit-build-core
  does not use it). The shim cannot change this: nothing installs the
  root setup.py into the wheel.
  ```
  diff <(unzip -Z1 247.whl | sort) <(unzip -Z1 248.whl | sort)   # empty
  ```
- [x] **Shim forwarding**: `install`/`develop` forward to pip with the
  exact pytorch#152276 command line, extra arguments are dropped with a
  warning, and pip's exit code is propagated (verified with a stub pip
  that prints its argv and exits 3):
  ```
  python setup.py develop --user   # pip install -v --no-build-isolation -e ., warns about dropped --user
  python setup.py install          # pip install -v --no-build-isolation .
  ```
- [x] **Shim guard**: every other command fails with exit code 1,
  printing the replacement commands and the sunset schedule:
  ```
  python setup.py bdist_wheel
  ```
- [x] **No dangling references** to the removed modules
  (`build_pytorch_libs`, `setup_helpers.{cmake,cmake_utils,env}`,
  `test_cmake`); the remaining `tools/setup_helpers` references point to
  surviving files (`generate_code.py`, `gen_version_header.py`,
  `generate_linker_script.py`).
  ```
  grep -rE 'build_pytorch_libs|setup_helpers\.(cmake|env)' --include='*.py' .
  ```
- [x] **0 build failures** across the matrix -- the removed path was
  genuinely dead.

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

**Problem**

Building a C++ or CUDA extension against a PyTorch installed in editable mode (`pip install -e .`) fails to find any installed torch header. The compile aborts on the first include, e.g.:
```
  fatal error: torch/csrc/autograd/profiler_kineto.h: No such file or directory
```
The recent migration to scikit-build-core changed editable installs so that compiled artifacts (the installed headers, libraries, and binaries) live in the installed package directory instead of the source tree. The C++ extension helper still looked for them under the source tree, which an editable install never populates, so extension builds lose their header and library search paths. Regular wheel installs are unaffected because their package directory and their import location are the same.

**Fix**

The scikit-build-core migration (pytorch#180247) already added `_compute_torch_parent` so `get_file_path` resolves to the installed package directory for editable installs, but `torch.utils.cpp_extension` still computed its own root from `dirname(dirname(__file__))`. Resolve `_TORCH_PATH` with `get_file_path("torch")` instead, so `cpp_extension` reuses that same editable-aware logic. `_TORCH_PATH` feeds every include, library, precompiled-header, and hipify path in the module, so this single change fixes all of them; non-editable installs resolve exactly as before.

Authored with assistance from an AI agent (Claude Code).
Pull Request resolved: pytorch#190829
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
requirements-build.txt was updated by pytorch#180247 to include additional dependencies for supporting scikit-build-core. This broke my local setup for building PyTorch using uv. This commit updates the dev dependencies.
Pull Request resolved: pytorch#190690
Approved by: https://github.com/Skylion007
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…ytorch#180248)

With the build fully driven by scikit-build-core (pytorch#180247), the
setuptools path is dead code. Remove the setuptools build helpers
(build_pytorch_libs, setup_helpers.{cmake,cmake_utils,env}, test_cmake)
and replace setup.py with a small shim that forwards `install` and
`develop` to pip and fails with instructions for everything else.
Retain a minimal build_libtorch.py -- it calls cmake directly and is
still used by the libtorch build path.

## Why a phased sunset instead of outright removal?

pip and `python -m build` never execute setup.py; the only way it still
runs is a direct `python setup.py <cmd>` invocation. For `install` and
`develop` we have redirected to pip since pytorch#152276; the shim keeps that
contract intact for two more releases so existing scripts keep working
while they migrate. Every other command (`build`, `bdist_wheel`,
`clean`, `sdist`, ...) used to fall through into the setuptools
machinery this PR deletes; emulating that interface is not worth it
(setuptools itself deprecated it in 2021), so those commands now fail
immediately, printing the replacement commands and the sunset schedule
-- a more helpful failure mode than `can't open file 'setup.py'` while
still surfacing not-yet-migrated callers.

The schedule is stated in the shim header and printed on every
invocation:

- PyTorch 2.14-2.15: `install`/`develop` forward to pip; all other
  commands fail with instructions
- PyTorch 2.16-2.17: all commands fail with instructions
- PyTorch 2.18: setup.py is removed

## Test plan

- [x] **Wheel byte-identical to parent pytorch#180247**: empty manifest diff,
  +10 B zip-timestamp noise. Removing the dead setuptools machinery does
  not change wheel content (it is never shipped, and scikit-build-core
  does not use it). The shim cannot change this: nothing installs the
  root setup.py into the wheel.
  ```
  diff <(unzip -Z1 247.whl | sort) <(unzip -Z1 248.whl | sort)   # empty
  ```
- [x] **Shim forwarding**: `install`/`develop` forward to pip with the
  exact pytorch#152276 command line, extra arguments are dropped with a
  warning, and pip's exit code is propagated (verified with a stub pip
  that prints its argv and exits 3):
  ```
  python setup.py develop --user   # pip install -v --no-build-isolation -e ., warns about dropped --user
  python setup.py install          # pip install -v --no-build-isolation .
  ```
- [x] **Shim guard**: every other command fails with exit code 1,
  printing the replacement commands and the sunset schedule:
  ```
  python setup.py bdist_wheel
  ```
- [x] **No dangling references** to the removed modules
  (`build_pytorch_libs`, `setup_helpers.{cmake,cmake_utils,env}`,
  `test_cmake`); the remaining `tools/setup_helpers` references point to
  surviving files (`generate_code.py`, `gen_version_header.py`,
  `generate_linker_script.py`).
  ```
  grep -rE 'build_pytorch_libs|setup_helpers\.(cmake|env)' --include='*.py' .
  ```
- [x] **0 build failures** across the matrix -- the removed path was
  genuinely dead.

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

**Problem**

Building a C++ or CUDA extension against a PyTorch installed in editable mode (`pip install -e .`) fails to find any installed torch header. The compile aborts on the first include, e.g.:
```
  fatal error: torch/csrc/autograd/profiler_kineto.h: No such file or directory
```
The recent migration to scikit-build-core changed editable installs so that compiled artifacts (the installed headers, libraries, and binaries) live in the installed package directory instead of the source tree. The C++ extension helper still looked for them under the source tree, which an editable install never populates, so extension builds lose their header and library search paths. Regular wheel installs are unaffected because their package directory and their import location are the same.

**Fix**

The scikit-build-core migration (pytorch#180247) already added `_compute_torch_parent` so `get_file_path` resolves to the installed package directory for editable installs, but `torch.utils.cpp_extension` still computed its own root from `dirname(dirname(__file__))`. Resolve `_TORCH_PATH` with `get_file_path("torch")` instead, so `cpp_extension` reuses that same editable-aware logic. `_TORCH_PATH` feeds every include, library, precompiled-header, and hipify path in the module, so this single change fixes all of them; non-editable installs resolve exactly as before.

Authored with assistance from an AI agent (Claude Code).
Pull Request resolved: pytorch#190829
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 macOS OpenMP embedding step out of `setup.py::_embed_libomp`
into CMake so the wheel is self-contained under the scikit-build-core
build (pytorchgh-180247) as well as the legacy setuptools path.

`cmake/PostBuildSteps.cmake` installs `libomp.dylib` (and `omp.h` for
Inductor) alongside `libtorch_cpu.dylib`. A small Python helper at
`tools/embed_libomp_macos.py`, invoked via `install(CODE ...)`,
rewrites libtorch_cpu's `LC_LOAD_DYLIB` and `LC_RPATH` so the bundled
libomp is the sole resolution path at runtime; it handles both the
Homebrew (absolute-path load command) and conda (`@rpath` + build-time
rpath) layouts. The `otool` / `install_name_tool` work doesn't
translate cleanly to pure CMake, hence the Python helper.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180239
Approved by: https://github.com/atalman
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/docker ciflow/dynamo Trigger jobs ran periodically on main for dynamo tests ciflow/inductor ciflow/inductor-perf-test-nightly-rocm-mi350 Trigger inductor perf tests on ROCm MI350 ciflow/inductor-rocm-mi200 Trigger "inductor" config CI on ROCm MI200 ciflow/inductor-rocm-mi300 Trigger "inductor" config CI on ROCm MI300/MI325 ciflow/inductor-rocm-mi350 Trigger "inductor" config CI on ROCm MI350 ciflow/periodic Trigger jobs ran periodically on master (periodic.yml) on the PR ciflow/trunk Trigger trunk jobs on your pull request ciflow/xpu Run XPU CI tasks Merged open source release notes: releng release notes category

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

8 participants