Skip to content

Improve cpp_extension and drop setuptools runtime requirement - #180707

Closed
zklaus wants to merge 8 commits into
pytorch:mainfrom
zklaus:cpp-extension-skbuild
Closed

zklaus wants to merge 8 commits into
pytorch:mainfrom
zklaus:cpp-extension-skbuild

Conversation

@zklaus

@zklaus zklaus commented Apr 17, 2026

Copy link
Copy Markdown
Collaborator

This implements the changes proposed in #180624, clarifying the different facets of torch.utils.cpp_extension and removing setuptools as a runtime requirement.

Depends on the stack #177641--#180250.

Closes #180624.

zklaus added 7 commits April 17, 2026 12:49
Authored with Claude.
Authored with Claude.
__init__ now imports directly from _discovery and _jit, and resolves
BuildExtension / CppExtension / CUDAExtension / SyclExtension lazily
from the setuptools submodule via __getattr__. As a result,
``import torch.utils.cpp_extension`` no longer pulls in setuptools
unless one of those adapters is actually used. The _impl.py shrinking
bucket is now empty and gets deleted.

Authored with Claude.
Each case runs in a fresh subprocess so that sys.modules state bleeding in
from other tests can't mask a regression. The assertion set is: plain
import of torch.utils.cpp_extension must not load the setuptools adapter
submodule; accessing JIT/discovery names (load, include_paths, CUDA_HOME,
...) must not load it either; first access to any of BuildExtension /
CppExtension / CUDAExtension / SyclExtension must load it and cache the
resolved attribute on the package.

Authored with Claude.
torch.utils.cpp_extension no longer pulls in setuptools at import time
(the setuptools-dependent adapters are resolved lazily via
cpp_extension.__getattr__). A full scan of torch/ confirms no other
runtime code path imports setuptools — remaining references are either
lazy per-call imports in _jit.py or Windows-only paths in
cpp_extension/setuptools.py, which only runs when an adapter is
accessed. setuptools is still kept as a build-time and dev dependency
(requirements-build.txt, pyproject.toml [dependency-groups].dev) for
anyone actually using BuildExtension or building from source.

Authored with Claude.
@pytorch-bot

pytorch-bot Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 12 New Failures

As of commit a031069 with merge base 6433e6f (image):

NEW FAILURES - The following jobs have failed:

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

@pytorch-bot

pytorch-bot Bot commented Apr 17, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

The Windows-only ``_get_vc_env`` helper in _jit.py reached into
``setuptools._distutils._msvccompiler`` (a private, underscored API)
to locate Visual Studio and capture the vcvarsall environment, and
``_run_ninja_build`` used ``distutils.util.get_platform`` to pick the
right vcvarsall arch. Both were the last setuptools imports anywhere
in the cpp_extension package.

Replace with a first-party implementation that calls ``vswhere.exe``
and ``vcvarsall.bat`` directly. ``sysconfig.get_platform`` returns the
same strings ``distutils.util.get_platform`` did, so ``PLAT_TO_VCVARS``
is unchanged. The ``DISTUTILS_USE_SDK`` escape hatch is preserved.

Extend test_cpp_extensions_imports.py with a static AST check that
walks the three non-adapter modules (__init__, _discovery, _jit) and
asserts none of them import setuptools, so a future refactor that
re-introduces a setuptools dependency outside the adapter submodule
trips immediately.

Authored with Claude.
zklaus added a commit to zklaus/pytorch that referenced this pull request May 28, 2026
…u path)

First commit in the Windows CD-workflow Python-script refactor, mirroring
the Linux split landed in pytorchgh-182409. Introduces the env-handoff scaffold:
build_env_setup.py emits `export KEY=VALUE` lines into an --env-out file
that the parent bash wrapper sources, so build flags from this script
reach the eventual `python -m build` subprocess.

vcvarsall discovery and env capture mirror torch.utils.cpp_extension._jit
._get_vc_env (pytorchgh-180707) -- vswhere.exe with %VS15VCVARSALL% fallback,
`cmd /u /c` for UTF-16LE output, then diffing against the current env so
only variables vcvarsall actually changed flow through.

Only the cpu branch is implemented; cuda and xpu fail loudly until they
land in follow-up commits. The new script is not yet wired into
binary_windows_build.sh -- the legacy .bat chain remains live until the
full Python pipeline (install_deps, wheel, entry-point) is in place.

Authored by Claude.
zklaus added a commit to zklaus/pytorch that referenced this pull request Jun 8, 2026
…u path)

First commit in the Windows CD-workflow Python-script refactor, mirroring
the Linux split landed in pytorchgh-182409. Introduces the env-handoff scaffold:
build_env_setup.py emits `export KEY=VALUE` lines into an --env-out file
that the parent bash wrapper sources, so build flags from this script
reach the eventual `python -m build` subprocess.

vcvarsall discovery and env capture mirror torch.utils.cpp_extension._jit
._get_vc_env (pytorchgh-180707) -- vswhere.exe with %VS15VCVARSALL% fallback,
`cmd /u /c` for UTF-16LE output, then diffing against the current env so
only variables vcvarsall actually changed flow through.

Only the cpu branch is implemented; cuda and xpu fail loudly until they
land in follow-up commits. The new script is not yet wired into
binary_windows_build.sh -- the legacy .bat chain remains live until the
full Python pipeline (install_deps, wheel, entry-point) is in place.

Authored by Claude.
zklaus added a commit to zklaus/pytorch that referenced this pull request Jun 14, 2026
…u path)

First commit in the Windows CD-workflow Python-script refactor, mirroring
the Linux split landed in pytorchgh-182409. Introduces the env-handoff scaffold:
build_env_setup.py emits `export KEY=VALUE` lines into an --env-out file
that the parent bash wrapper sources, so build flags from this script
reach the eventual `python -m build` subprocess.

vcvarsall discovery and env capture mirror torch.utils.cpp_extension._jit
._get_vc_env (pytorchgh-180707) -- vswhere.exe with %VS15VCVARSALL% fallback,
`cmd /u /c` for UTF-16LE output, then diffing against the current env so
only variables vcvarsall actually changed flow through.

Only the cpu branch is implemented; cuda and xpu fail loudly until they
land in follow-up commits. The new script is not yet wired into
binary_windows_build.sh -- the legacy .bat chain remains live until the
full Python pipeline (install_deps, wheel, entry-point) is in place.

Authored by Claude.
zklaus added a commit to zklaus/pytorch that referenced this pull request Jun 15, 2026
…u path)

First commit in the Windows CD-workflow Python-script refactor, mirroring
the Linux split landed in pytorchgh-182409. Introduces the env-handoff scaffold:
build_env_setup.py emits `export KEY=VALUE` lines into an --env-out file
that the parent bash wrapper sources, so build flags from this script
reach the eventual `python -m build` subprocess.

vcvarsall discovery and env capture mirror torch.utils.cpp_extension._jit
._get_vc_env (pytorchgh-180707) -- vswhere.exe with %VS15VCVARSALL% fallback,
`cmd /u /c` for UTF-16LE output, then diffing against the current env so
only variables vcvarsall actually changed flow through.

Only the cpu branch is implemented; cuda and xpu fail loudly until they
land in follow-up commits. The new script is not yet wired into
binary_windows_build.sh -- the legacy .bat chain remains live until the
full Python pipeline (install_deps, wheel, entry-point) is in place.

Authored by Claude.
zklaus added a commit to zklaus/pytorch that referenced this pull request Jun 16, 2026
…u path)

First commit in the Windows CD-workflow Python-script refactor, mirroring
the Linux split landed in pytorchgh-182409. Introduces the env-handoff scaffold:
build_env_setup.py emits `export KEY=VALUE` lines into an --env-out file
that the parent bash wrapper sources, so build flags from this script
reach the eventual `python -m build` subprocess.

vcvarsall discovery and env capture mirror torch.utils.cpp_extension._jit
._get_vc_env (pytorchgh-180707) -- vswhere.exe with %VS15VCVARSALL% fallback,
`cmd /u /c` for UTF-16LE output, then diffing against the current env so
only variables vcvarsall actually changed flow through.

Only the cpu branch is implemented; cuda and xpu fail loudly until they
land in follow-up commits. The new script is not yet wired into
binary_windows_build.sh -- the legacy .bat chain remains live until the
full Python pipeline (install_deps, wheel, entry-point) is in place.

Authored by Claude.
pytorchmergebot pushed a commit that referenced this pull request Jun 16, 2026
## Summary

Port the Windows x86_64 wheel CD build off the legacy `.bat` chain onto a
Python pipeline, mirroring the Linux split landed in #182409. CPU, CUDA, and
XPU wheel builds now run through a small set of Python scripts instead of the
`build_pytorch.bat -> cpu/cuda/xpu.bat -> internal/setup.bat` chain.

The new entry chain on x86_64 wheel builds:

```
binary_windows_build.sh
  -> windows/internal/vc_install_helper.bat   (ensure VS2022 BuildTools)
  -> windows/set_desired_python.sh            (install Python.org Python)
  -> python windows/build_env_setup.py        (vcvarsall + CUDA/XPU env + MAGMA + sccache)
  -> python windows/build_install_deps.py     (pip deps + libuv)
  -> python windows/build_wheel.py            (python -m build --wheel)
```

The three Python steps are driven through the interpreter
`set_desired_python.sh` selected (exported as `DESIRED_PYTHON_EXE`), not a
bare `python`, so the wheel ABI tag and pip build deps track
`DESIRED_PYTHON` for free-threaded builds (see Build-correctness fixes).

vcvarsall env capture mirrors `torch.utils.cpp_extension._jit._get_vc_env`
from #180707 (vswhere discovery, `cmd /u /c` for UTF-16LE output, diff
against current env so additions layer on top).

`internal/cuda_install.bat`, `internal/xpu_install.bat`, and
`internal/vc_install_helper.bat` are kept as Python/bash-invoked installers --
same pragmatic precedent as the Linux refactor (`install_cuda.sh` etc.).
Heavy installer logic stays in bash/cmd; orchestration moves to Python.
`set_desired_python.sh` inlines what `internal/install_python.bat` did (the
`bash -> cmd /c` boundary was unreliable for the python.org installer), so
the wheel path no longer invokes `install_python.bat`.

## Removing the legacy bat chain

The x86_64 wheel build was the last consumer of the legacy
`build_pytorch.bat -> {cpu,cuda,xpu}.bat -> internal/setup.bat` chain, so
porting it to the Python pipeline lets that chain go. This PR deletes:

- `build_pytorch.bat`, `cpu/cuda/xpu.bat`, `setup_build.bat`, and
  `internal/{build_wheels,check_deps,check_nvtx,check_opts,clean,clone,
  cuda_config,init,setup}.bat`.

These are now orphaned -- nothing in the tree invokes them. The only
remaining mentions are provenance comments in the new Python scripts (e.g.
"Mirrors the MAGMA block in the legacy build_pytorch.bat"), plus the separate
`arm64/build_pytorch.bat` and `win-test-helpers/build_pytorch.bat`, which are
different files left untouched.

Note on debug libtorch: upstream has already stopped shipping the Windows
debug libtorch builds and removed their nightly workflows, and this branch is
rebased on top of that -- so it carries no `.github/workflows` or
`generate_ci_workflows.py` changes. (Earlier revisions of this PR removed
those workflows here; those commits were dropped in the rebase once the
upstream removal landed.) The release path is unaffected: release libtorch is
still produced by extraction from the release wheel
(`extract_libtorch_from_wheel.py`, the same mechanism as on Linux), and those
wheels are now built by this Python pipeline.

## Build-correctness fixes (surfaced by the wheel smoke tests)

With the builds green, the `wheel-*-test` smoke jobs ran and caught two gaps
the legacy bat chain had handled implicitly:

- **Free-threaded wheels (`DESIRED_PYTHON=3.14t`).** A free-threaded
  python.org install ships both `python.exe` and `python3.14t.exe` under the
  same prefix, so a bare `python` resolved to the regular interpreter and
  `python -m build` produced a `cp314` wheel that the `cp314t` test job
  rejected ("not a supported wheel on this platform"). Fix: export the
  selected interpreter as `DESIRED_PYTHON_EXE` and drive all three pipeline
  steps through it, so deps and the wheel ABI tag match `DESIRED_PYTHON`.
- **XPU MKL availability.** `CMAKE_PREFIX_PATH` was assigned
  `<sys.prefix>/Library` (the pip `mkl-static`/`mkl-include` prefix) before
  the per-device setup ran, and the XPU oneAPI `vars.bat` then overwrote it
  with its own value -- so the XPU build configured BLAS as Eigen and
  `torch.backends.mkl.is_available()` was False (the smoke test asserts on
  it). cpu/cuda were unaffected because nothing else touches
  `CMAKE_PREFIX_PATH` there. Fix: set `CMAKE_PREFIX_PATH` after the device
  dispatch and prepend the MKL prefix to whatever the device contributed, so
  both the pip MKL and the oneAPI compiler prefix stay on the search path.

## Python patch pinning

`set_desired_python.sh` selects the python.org installer from an explicit
per-minor patch table (e.g. 3.13 -> 3.13.14) rather than the `.0` patch the
legacy `install_python.bat` used. The `.0` pin froze each minor on its
oldest, CVE-laden release; floating to the newest installer was rejected
because python.org serves source-only (no-installer) releases for
security-only minors, which would require scraping the release index and
HEAD-probing candidates on every build. Security-only minors (3.10-3.12) are
pinned to their last release that shipped a Windows installer; bugfix minors
(3.13, 3.14) point at the current newest installer and are bumped here in
review. The table must stay in sync with the matrix in
`generated-windows-binary-wheel-nightly.yml`.

## Divergences from the Linux template (#182409)

Where this PR deviates from the Linux pipeline, why:

- **No `repair_wheel.py` step.** Windows DLL discovery uses PATH /
  `AddDllDirectory` rather than RPATH, so there's nothing for patchelf to
  do. CUDA DLLs already ship inside `torch/lib/`. Wheel-content diff against
  the latest published nightly cpu wheel confirms parity: identical DLL set
  in `torch/lib/`.
- **`set_desired_python.sh` installs Python from python.org** rather than
  picking from a baked image (the Windows CI AMI doesn't ship Pythons
  preinstalled).
- **`build_env_setup.py` downloads MAGMA / sccache / randomtemp** during the
  build rather than baking them into a Docker image. (These downloads now go
  through `urllib` with default TLS verification, replacing the legacy
  `curl -k` which disabled cert checking.)
- **MKL comes from pip** (`mkl-static` / `mkl-include`), put on
  `CMAKE_PREFIX_PATH` via the `<sys.prefix>/Library` prefix, rather than the
  legacy `check_opts.bat` `LIB`/`MKLProductDir` system-MKL prepend.
- **No cuda-aarch64 / rocm / cpu-cxx11-abi branches** (not applicable on
  Windows).
- **`build_install_deps.py` hardcodes the pip dep list** (matches what
  `setup_build.bat` did) rather than reading `requirements*.txt` like Linux.
  Migrating to `requirements*.txt` is a worthwhile follow-up but out of scope
  here.

The binary-build env knobs the legacy chain set are preserved in
`COMMON_BUILD_ENV` (`PYTORCH_BINARY_BUILD`, `TH_BINARY_BUILD`, `BUILD_TEST=0`,
`INSTALL_TEST=0`, `MSSdk`, `DISTUTILS_USE_SDK`).

## Out of scope

- `windows-arm64` wheels (separate `arm64/build_pytorch.bat` chain,
  untouched).
- Windows pull-CI build (uses a separate `win-test-helpers/build_pytorch.bat`,
  untouched).
- `cpu-s390x` (Linux only).

## Test plan

Builds are green across the full x86_64 wheel matrix:

- [x] x86_64 cpu wheel build x Python 3.10-3.14 + 3.14t
- [x] x86_64 cuda wheel build (12.6, 13.0, 13.2) x the same Python set
- [x] x86_64 xpu wheel build x the same Python set
- [x] Wheel content verified equivalent to the published nightly cpu wheel
      (same DLL set in `torch/lib/`)
- [x] sccache enabled on CPU + CUDA host compilation; server lifecycle
      confirmed via build logs
- [x] cpu / cuda smoke tests (`wheel-*-test`) green
- [x] windows-arm64 wheel + libtorch builds unaffected (path goes through
      `arm64/build_pytorch.bat`, untouched)

Smoke-test status for the two build-correctness fixes above (free-threaded
ABI tag, XPU MKL) is being re-validated on the current head; the prior run
caught both at the `wheel-*-test` stage and the fixes target exactly those
failures.

Earlier-run note (resolved): the `cuda13_0` / `cuda13_2` wheel builds had
failed at the cuDNN download step because the
`cudnn-...-9.23.1.3_cuda13-archive.zip` object was briefly missing from
`ossci-windows` (uploaded ~19 min after the build fetched it). It is present
and valid now and the cuda13 builds are green; unrelated to this PR.

## Follow-ups (deferred, captured separately)

- **Migrate `build_install_deps.py` to read `requirements*.txt`** rather than
  hardcoded `PIP_PACKAGES`, matching the Linux pattern.
- Remaining self-review cleanup items: `CMAKE_GENERATOR` explicit for
  CPU/XPU, env-handoff fragilities, PATH conversion guard, numpy pin for a
  future Python 3.15, and bumping the python patch table / keeping it in sync
  with the wheel matrix.

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

Pull Request resolved: #184407
Approved by: https://github.com/atalman
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Jun 16, 2026
@zklaus zklaus removed the Stale label Jun 16, 2026
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…184407)

## Summary

Port the Windows x86_64 wheel CD build off the legacy `.bat` chain onto a
Python pipeline, mirroring the Linux split landed in pytorch#182409. CPU, CUDA, and
XPU wheel builds now run through a small set of Python scripts instead of the
`build_pytorch.bat -> cpu/cuda/xpu.bat -> internal/setup.bat` chain.

The new entry chain on x86_64 wheel builds:

```
binary_windows_build.sh
  -> windows/internal/vc_install_helper.bat   (ensure VS2022 BuildTools)
  -> windows/set_desired_python.sh            (install Python.org Python)
  -> python windows/build_env_setup.py        (vcvarsall + CUDA/XPU env + MAGMA + sccache)
  -> python windows/build_install_deps.py     (pip deps + libuv)
  -> python windows/build_wheel.py            (python -m build --wheel)
```

The three Python steps are driven through the interpreter
`set_desired_python.sh` selected (exported as `DESIRED_PYTHON_EXE`), not a
bare `python`, so the wheel ABI tag and pip build deps track
`DESIRED_PYTHON` for free-threaded builds (see Build-correctness fixes).

vcvarsall env capture mirrors `torch.utils.cpp_extension._jit._get_vc_env`
from pytorch#180707 (vswhere discovery, `cmd /u /c` for UTF-16LE output, diff
against current env so additions layer on top).

`internal/cuda_install.bat`, `internal/xpu_install.bat`, and
`internal/vc_install_helper.bat` are kept as Python/bash-invoked installers --
same pragmatic precedent as the Linux refactor (`install_cuda.sh` etc.).
Heavy installer logic stays in bash/cmd; orchestration moves to Python.
`set_desired_python.sh` inlines what `internal/install_python.bat` did (the
`bash -> cmd /c` boundary was unreliable for the python.org installer), so
the wheel path no longer invokes `install_python.bat`.

## Removing the legacy bat chain

The x86_64 wheel build was the last consumer of the legacy
`build_pytorch.bat -> {cpu,cuda,xpu}.bat -> internal/setup.bat` chain, so
porting it to the Python pipeline lets that chain go. This PR deletes:

- `build_pytorch.bat`, `cpu/cuda/xpu.bat`, `setup_build.bat`, and
  `internal/{build_wheels,check_deps,check_nvtx,check_opts,clean,clone,
  cuda_config,init,setup}.bat`.

These are now orphaned -- nothing in the tree invokes them. The only
remaining mentions are provenance comments in the new Python scripts (e.g.
"Mirrors the MAGMA block in the legacy build_pytorch.bat"), plus the separate
`arm64/build_pytorch.bat` and `win-test-helpers/build_pytorch.bat`, which are
different files left untouched.

Note on debug libtorch: upstream has already stopped shipping the Windows
debug libtorch builds and removed their nightly workflows, and this branch is
rebased on top of that -- so it carries no `.github/workflows` or
`generate_ci_workflows.py` changes. (Earlier revisions of this PR removed
those workflows here; those commits were dropped in the rebase once the
upstream removal landed.) The release path is unaffected: release libtorch is
still produced by extraction from the release wheel
(`extract_libtorch_from_wheel.py`, the same mechanism as on Linux), and those
wheels are now built by this Python pipeline.

## Build-correctness fixes (surfaced by the wheel smoke tests)

With the builds green, the `wheel-*-test` smoke jobs ran and caught two gaps
the legacy bat chain had handled implicitly:

- **Free-threaded wheels (`DESIRED_PYTHON=3.14t`).** A free-threaded
  python.org install ships both `python.exe` and `python3.14t.exe` under the
  same prefix, so a bare `python` resolved to the regular interpreter and
  `python -m build` produced a `cp314` wheel that the `cp314t` test job
  rejected ("not a supported wheel on this platform"). Fix: export the
  selected interpreter as `DESIRED_PYTHON_EXE` and drive all three pipeline
  steps through it, so deps and the wheel ABI tag match `DESIRED_PYTHON`.
- **XPU MKL availability.** `CMAKE_PREFIX_PATH` was assigned
  `<sys.prefix>/Library` (the pip `mkl-static`/`mkl-include` prefix) before
  the per-device setup ran, and the XPU oneAPI `vars.bat` then overwrote it
  with its own value -- so the XPU build configured BLAS as Eigen and
  `torch.backends.mkl.is_available()` was False (the smoke test asserts on
  it). cpu/cuda were unaffected because nothing else touches
  `CMAKE_PREFIX_PATH` there. Fix: set `CMAKE_PREFIX_PATH` after the device
  dispatch and prepend the MKL prefix to whatever the device contributed, so
  both the pip MKL and the oneAPI compiler prefix stay on the search path.

## Python patch pinning

`set_desired_python.sh` selects the python.org installer from an explicit
per-minor patch table (e.g. 3.13 -> 3.13.14) rather than the `.0` patch the
legacy `install_python.bat` used. The `.0` pin froze each minor on its
oldest, CVE-laden release; floating to the newest installer was rejected
because python.org serves source-only (no-installer) releases for
security-only minors, which would require scraping the release index and
HEAD-probing candidates on every build. Security-only minors (3.10-3.12) are
pinned to their last release that shipped a Windows installer; bugfix minors
(3.13, 3.14) point at the current newest installer and are bumped here in
review. The table must stay in sync with the matrix in
`generated-windows-binary-wheel-nightly.yml`.

## Divergences from the Linux template (pytorch#182409)

Where this PR deviates from the Linux pipeline, why:

- **No `repair_wheel.py` step.** Windows DLL discovery uses PATH /
  `AddDllDirectory` rather than RPATH, so there's nothing for patchelf to
  do. CUDA DLLs already ship inside `torch/lib/`. Wheel-content diff against
  the latest published nightly cpu wheel confirms parity: identical DLL set
  in `torch/lib/`.
- **`set_desired_python.sh` installs Python from python.org** rather than
  picking from a baked image (the Windows CI AMI doesn't ship Pythons
  preinstalled).
- **`build_env_setup.py` downloads MAGMA / sccache / randomtemp** during the
  build rather than baking them into a Docker image. (These downloads now go
  through `urllib` with default TLS verification, replacing the legacy
  `curl -k` which disabled cert checking.)
- **MKL comes from pip** (`mkl-static` / `mkl-include`), put on
  `CMAKE_PREFIX_PATH` via the `<sys.prefix>/Library` prefix, rather than the
  legacy `check_opts.bat` `LIB`/`MKLProductDir` system-MKL prepend.
- **No cuda-aarch64 / rocm / cpu-cxx11-abi branches** (not applicable on
  Windows).
- **`build_install_deps.py` hardcodes the pip dep list** (matches what
  `setup_build.bat` did) rather than reading `requirements*.txt` like Linux.
  Migrating to `requirements*.txt` is a worthwhile follow-up but out of scope
  here.

The binary-build env knobs the legacy chain set are preserved in
`COMMON_BUILD_ENV` (`PYTORCH_BINARY_BUILD`, `TH_BINARY_BUILD`, `BUILD_TEST=0`,
`INSTALL_TEST=0`, `MSSdk`, `DISTUTILS_USE_SDK`).

## Out of scope

- `windows-arm64` wheels (separate `arm64/build_pytorch.bat` chain,
  untouched).
- Windows pull-CI build (uses a separate `win-test-helpers/build_pytorch.bat`,
  untouched).
- `cpu-s390x` (Linux only).

## Test plan

Builds are green across the full x86_64 wheel matrix:

- [x] x86_64 cpu wheel build x Python 3.10-3.14 + 3.14t
- [x] x86_64 cuda wheel build (12.6, 13.0, 13.2) x the same Python set
- [x] x86_64 xpu wheel build x the same Python set
- [x] Wheel content verified equivalent to the published nightly cpu wheel
      (same DLL set in `torch/lib/`)
- [x] sccache enabled on CPU + CUDA host compilation; server lifecycle
      confirmed via build logs
- [x] cpu / cuda smoke tests (`wheel-*-test`) green
- [x] windows-arm64 wheel + libtorch builds unaffected (path goes through
      `arm64/build_pytorch.bat`, untouched)

Smoke-test status for the two build-correctness fixes above (free-threaded
ABI tag, XPU MKL) is being re-validated on the current head; the prior run
caught both at the `wheel-*-test` stage and the fixes target exactly those
failures.

Earlier-run note (resolved): the `cuda13_0` / `cuda13_2` wheel builds had
failed at the cuDNN download step because the
`cudnn-...-9.23.1.3_cuda13-archive.zip` object was briefly missing from
`ossci-windows` (uploaded ~19 min after the build fetched it). It is present
and valid now and the cuda13 builds are green; unrelated to this PR.

## Follow-ups (deferred, captured separately)

- **Migrate `build_install_deps.py` to read `requirements*.txt`** rather than
  hardcoded `PIP_PACKAGES`, matching the Linux pattern.
- Remaining self-review cleanup items: `CMAKE_GENERATOR` explicit for
  CPU/XPU, env-handoff fragilities, PATH conversion guard, numpy pin for a
  future Python 3.15, and bumping the python patch table / keeping it in sync
  with the wheel matrix.

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

Pull Request resolved: pytorch#184407
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
…184407)

## Summary

Port the Windows x86_64 wheel CD build off the legacy `.bat` chain onto a
Python pipeline, mirroring the Linux split landed in pytorch#182409. CPU, CUDA, and
XPU wheel builds now run through a small set of Python scripts instead of the
`build_pytorch.bat -> cpu/cuda/xpu.bat -> internal/setup.bat` chain.

The new entry chain on x86_64 wheel builds:

```
binary_windows_build.sh
  -> windows/internal/vc_install_helper.bat   (ensure VS2022 BuildTools)
  -> windows/set_desired_python.sh            (install Python.org Python)
  -> python windows/build_env_setup.py        (vcvarsall + CUDA/XPU env + MAGMA + sccache)
  -> python windows/build_install_deps.py     (pip deps + libuv)
  -> python windows/build_wheel.py            (python -m build --wheel)
```

The three Python steps are driven through the interpreter
`set_desired_python.sh` selected (exported as `DESIRED_PYTHON_EXE`), not a
bare `python`, so the wheel ABI tag and pip build deps track
`DESIRED_PYTHON` for free-threaded builds (see Build-correctness fixes).

vcvarsall env capture mirrors `torch.utils.cpp_extension._jit._get_vc_env`
from pytorch#180707 (vswhere discovery, `cmd /u /c` for UTF-16LE output, diff
against current env so additions layer on top).

`internal/cuda_install.bat`, `internal/xpu_install.bat`, and
`internal/vc_install_helper.bat` are kept as Python/bash-invoked installers --
same pragmatic precedent as the Linux refactor (`install_cuda.sh` etc.).
Heavy installer logic stays in bash/cmd; orchestration moves to Python.
`set_desired_python.sh` inlines what `internal/install_python.bat` did (the
`bash -> cmd /c` boundary was unreliable for the python.org installer), so
the wheel path no longer invokes `install_python.bat`.

## Removing the legacy bat chain

The x86_64 wheel build was the last consumer of the legacy
`build_pytorch.bat -> {cpu,cuda,xpu}.bat -> internal/setup.bat` chain, so
porting it to the Python pipeline lets that chain go. This PR deletes:

- `build_pytorch.bat`, `cpu/cuda/xpu.bat`, `setup_build.bat`, and
  `internal/{build_wheels,check_deps,check_nvtx,check_opts,clean,clone,
  cuda_config,init,setup}.bat`.

These are now orphaned -- nothing in the tree invokes them. The only
remaining mentions are provenance comments in the new Python scripts (e.g.
"Mirrors the MAGMA block in the legacy build_pytorch.bat"), plus the separate
`arm64/build_pytorch.bat` and `win-test-helpers/build_pytorch.bat`, which are
different files left untouched.

Note on debug libtorch: upstream has already stopped shipping the Windows
debug libtorch builds and removed their nightly workflows, and this branch is
rebased on top of that -- so it carries no `.github/workflows` or
`generate_ci_workflows.py` changes. (Earlier revisions of this PR removed
those workflows here; those commits were dropped in the rebase once the
upstream removal landed.) The release path is unaffected: release libtorch is
still produced by extraction from the release wheel
(`extract_libtorch_from_wheel.py`, the same mechanism as on Linux), and those
wheels are now built by this Python pipeline.

## Build-correctness fixes (surfaced by the wheel smoke tests)

With the builds green, the `wheel-*-test` smoke jobs ran and caught two gaps
the legacy bat chain had handled implicitly:

- **Free-threaded wheels (`DESIRED_PYTHON=3.14t`).** A free-threaded
  python.org install ships both `python.exe` and `python3.14t.exe` under the
  same prefix, so a bare `python` resolved to the regular interpreter and
  `python -m build` produced a `cp314` wheel that the `cp314t` test job
  rejected ("not a supported wheel on this platform"). Fix: export the
  selected interpreter as `DESIRED_PYTHON_EXE` and drive all three pipeline
  steps through it, so deps and the wheel ABI tag match `DESIRED_PYTHON`.
- **XPU MKL availability.** `CMAKE_PREFIX_PATH` was assigned
  `<sys.prefix>/Library` (the pip `mkl-static`/`mkl-include` prefix) before
  the per-device setup ran, and the XPU oneAPI `vars.bat` then overwrote it
  with its own value -- so the XPU build configured BLAS as Eigen and
  `torch.backends.mkl.is_available()` was False (the smoke test asserts on
  it). cpu/cuda were unaffected because nothing else touches
  `CMAKE_PREFIX_PATH` there. Fix: set `CMAKE_PREFIX_PATH` after the device
  dispatch and prepend the MKL prefix to whatever the device contributed, so
  both the pip MKL and the oneAPI compiler prefix stay on the search path.

## Python patch pinning

`set_desired_python.sh` selects the python.org installer from an explicit
per-minor patch table (e.g. 3.13 -> 3.13.14) rather than the `.0` patch the
legacy `install_python.bat` used. The `.0` pin froze each minor on its
oldest, CVE-laden release; floating to the newest installer was rejected
because python.org serves source-only (no-installer) releases for
security-only minors, which would require scraping the release index and
HEAD-probing candidates on every build. Security-only minors (3.10-3.12) are
pinned to their last release that shipped a Windows installer; bugfix minors
(3.13, 3.14) point at the current newest installer and are bumped here in
review. The table must stay in sync with the matrix in
`generated-windows-binary-wheel-nightly.yml`.

## Divergences from the Linux template (pytorch#182409)

Where this PR deviates from the Linux pipeline, why:

- **No `repair_wheel.py` step.** Windows DLL discovery uses PATH /
  `AddDllDirectory` rather than RPATH, so there's nothing for patchelf to
  do. CUDA DLLs already ship inside `torch/lib/`. Wheel-content diff against
  the latest published nightly cpu wheel confirms parity: identical DLL set
  in `torch/lib/`.
- **`set_desired_python.sh` installs Python from python.org** rather than
  picking from a baked image (the Windows CI AMI doesn't ship Pythons
  preinstalled).
- **`build_env_setup.py` downloads MAGMA / sccache / randomtemp** during the
  build rather than baking them into a Docker image. (These downloads now go
  through `urllib` with default TLS verification, replacing the legacy
  `curl -k` which disabled cert checking.)
- **MKL comes from pip** (`mkl-static` / `mkl-include`), put on
  `CMAKE_PREFIX_PATH` via the `<sys.prefix>/Library` prefix, rather than the
  legacy `check_opts.bat` `LIB`/`MKLProductDir` system-MKL prepend.
- **No cuda-aarch64 / rocm / cpu-cxx11-abi branches** (not applicable on
  Windows).
- **`build_install_deps.py` hardcodes the pip dep list** (matches what
  `setup_build.bat` did) rather than reading `requirements*.txt` like Linux.
  Migrating to `requirements*.txt` is a worthwhile follow-up but out of scope
  here.

The binary-build env knobs the legacy chain set are preserved in
`COMMON_BUILD_ENV` (`PYTORCH_BINARY_BUILD`, `TH_BINARY_BUILD`, `BUILD_TEST=0`,
`INSTALL_TEST=0`, `MSSdk`, `DISTUTILS_USE_SDK`).

## Out of scope

- `windows-arm64` wheels (separate `arm64/build_pytorch.bat` chain,
  untouched).
- Windows pull-CI build (uses a separate `win-test-helpers/build_pytorch.bat`,
  untouched).
- `cpu-s390x` (Linux only).

## Test plan

Builds are green across the full x86_64 wheel matrix:

- [x] x86_64 cpu wheel build x Python 3.10-3.14 + 3.14t
- [x] x86_64 cuda wheel build (12.6, 13.0, 13.2) x the same Python set
- [x] x86_64 xpu wheel build x the same Python set
- [x] Wheel content verified equivalent to the published nightly cpu wheel
      (same DLL set in `torch/lib/`)
- [x] sccache enabled on CPU + CUDA host compilation; server lifecycle
      confirmed via build logs
- [x] cpu / cuda smoke tests (`wheel-*-test`) green
- [x] windows-arm64 wheel + libtorch builds unaffected (path goes through
      `arm64/build_pytorch.bat`, untouched)

Smoke-test status for the two build-correctness fixes above (free-threaded
ABI tag, XPU MKL) is being re-validated on the current head; the prior run
caught both at the `wheel-*-test` stage and the fixes target exactly those
failures.

Earlier-run note (resolved): the `cuda13_0` / `cuda13_2` wheel builds had
failed at the cuDNN download step because the
`cudnn-...-9.23.1.3_cuda13-archive.zip` object was briefly missing from
`ossci-windows` (uploaded ~19 min after the build fetched it). It is present
and valid now and the cuda13 builds are green; unrelated to this PR.

## Follow-ups (deferred, captured separately)

- **Migrate `build_install_deps.py` to read `requirements*.txt`** rather than
  hardcoded `PIP_PACKAGES`, matching the Linux pattern.
- Remaining self-review cleanup items: `CMAKE_GENERATOR` explicit for
  CPU/XPU, env-handoff fragilities, PATH conversion guard, numpy pin for a
  future Python 3.15, and bumping the python patch table / keeping it in sync
  with the wheel matrix.

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

Pull Request resolved: pytorch#184407
Approved by: https://github.com/atalman
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Aug 16, 2026
@github-actions github-actions Bot closed this Sep 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Decouple torch.utils.cpp_extension from setuptools and align with the scikit-build-core build backend

2 participants