Skip to content

[CD] Refactor Windows wheel build scripts (Python pipeline) - #184407

Closed
zklaus wants to merge 27 commits into
pytorch:mainfrom
zklaus:cd-windows-python-scripts
Closed

zklaus wants to merge 27 commits into
pytorch:mainfrom
zklaus:cd-windows-python-scripts

Conversation

@zklaus

@zklaus zklaus commented May 19, 2026 •

Copy link
Copy Markdown
Collaborator

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:

  • x86_64 cpu wheel build x Python 3.10-3.14 + 3.14t
  • x86_64 cuda wheel build (12.6, 13.0, 13.2) x the same Python set
  • x86_64 xpu wheel build x the same Python set
  • Wheel content verified equivalent to the published nightly cpu wheel
    (same DLL set in torch/lib/)
  • sccache enabled on CPU + CUDA host compilation; server lifecycle
    confirmed via build logs
  • cpu / cuda smoke tests (wheel-*-test) green
  • 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.

@pytorch-bot

pytorch-bot Bot commented May 19, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 32 Pending, 1 Unclassified Failure

As of commit d32561f with merge base cb69512 (image):

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

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

@zklaus zklaus added the ciflow/binaries Trigger all binary build and upload jobs on the PR label May 19, 2026
@zklaus
zklaus force-pushed the cd-windows-python-scripts branch from 0810573 to de1a234 Compare May 28, 2026 14:46
@zklaus
zklaus marked this pull request as ready for review June 1, 2026 16:21
@zklaus
zklaus requested a review from a team as a code owner June 1, 2026 16:21
@zklaus
zklaus requested a review from atalman June 1, 2026 16:21
@jbschlosser jbschlosser added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jun 1, 2026
@zklaus
zklaus force-pushed the cd-windows-python-scripts branch from 744759b to 84cbbec Compare June 8, 2026 15:12
@pytorch-bot pytorch-bot Bot added the release notes: releng release notes category label Jun 8, 2026
@zklaus
zklaus force-pushed the cd-windows-python-scripts branch from 3249be8 to c17c204 Compare June 14, 2026 16:00

@atalman atalman left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

lgtm

@zklaus
zklaus force-pushed the cd-windows-python-scripts branch from f3e1b73 to fe28989 Compare June 15, 2026 18:09
zklaus added 17 commits June 16, 2026 07:58
…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.
Windows analog of .ci/manywheel/build_install_deps.py from pytorchgh-182409.
Replaces the pip-install + libuv-extract portion of the legacy
setup_build.bat: per-Python numpy pin, the fixed build-time pip set
(cmake, pyyaml, mkl-include/static, boto3, requests, ninja,
typing_extensions, setuptools==78.1.1, scikit-build-core), spin clean,
and libuv tarball extraction into the running Python's prefix. Emits
libuv_ROOT via --env-out so the parent bash wrapper picks it up.

Package list stays hardcoded for parity with setup_build.bat; the
requirements unification work (pytorchgh-183913) will centralize this later.
Not yet wired into binary_windows_build.sh.

Authored by Claude.
Ports the CUDA half of the legacy cuda.bat + cuda_config.bat + check_nvtx
plus the MAGMA/sccache/randomtemp sections of build_pytorch.bat into a
single setup_cuda() that returns the env dict for the wheel build:

  - install_cuda_toolkit() shells out to internal/cuda_install.bat,
    keeping the heavy installer as a .bat (same precedent as Linux's
    install_cuda.sh handoff in build_env_setup.py)
  - find_cuda_path() resolves CUDA_PATH_V<ver> / standard install
  - find_nvtoolsext() mirrors check_nvtx.bat
  - install_magma() curl + 7z extracts the pre-built MAGMA archive
  - install_sccache_binaries() downloads sccache, sccache-cl, randomtemp
  - setup_nvcc_wrapper() writes the randomtemp+sccache nvcc.bat shim
    and returns the CMAKE_CUDA_COMPILER / CUDA_NVCC_EXECUTABLE wiring

TORCH_CUDA_ARCH_LIST is kept in lockstep with cuda_config.bat's
CUDA_ARCH_LIST values. The DISTUTILS_USE_SDK short-circuit in
capture_vcvars_env (carried over from cpp_extension._jit._get_vc_env)
is dropped: CI always runs vcvarsall and we set DISTUTILS_USE_SDK
unconditionally in COMMON_BUILD_ENV.

main() also now updates os.environ with the GPU env before capturing
vcvarsall so the latter's PATH/LIB extensions layer on top rather than
shadowing CUDA's additions.

XPU branch and wiring into binary_windows_build.sh still pending.

Authored by Claude.
Ports xpu.bat + xpu_install.bat into setup_xpu():
  - install_xpu_bundle() shells out to internal/xpu_install.bat for the
    Intel Deep Learning Essentials installer
  - source_oneapi_vars() chains the compiler + ocloc vars.bat scripts in
    one cmd invocation and captures the env diff (Windows analog of
    Linux's source_oneapi_env helper)
  - Sets USE_CUDA=0, USE_ONEMKL=1, XPU_BUNDLE_ROOT, plus VS2022INSTALLDIR
    aliased from VS15INSTALLDIR for downstream tools that look there

Factors out _capture_cmd_env() shared by the vcvarsall and oneAPI capture
paths -- same UTF-16LE / cmd /u /c / diff-against-current-env logic.

main() now dispatches cpu/cuda/xpu cleanly; any other GPU_ARCH_TYPE
errors out. Wiring into binary_windows_build.sh is the next commit.

Authored by Claude.
build_wheel.py is the wheel-build stage proper: invokes
`python -m build --wheel --no-isolation` once the GPU env (set by
build_env_setup.py), pip deps (set by build_install_deps.py), and
vcvarsall env have all been sourced into the parent bash wrapper.

set_desired_python.sh is the Windows analog of
.ci/manywheel/set_desired_python.sh: the Linux variant just prepends a
manylinux-image-shipped /opt/python/cpXY/bin to PATH, but Windows AMIs
don't bake Pythons in, so the script runs internal/install_python.bat
(with retry) and exports PATH for the installed interpreter. Source it
rather than exec, so the PATH update reaches the caller.

Also marks build_env_setup.py and build_install_deps.py executable.

Authored by Claude.
x86_64 wheel builds now flow through the new
set_desired_python.sh -> build_env_setup.py -> build_install_deps.py
-> build_wheel.py chain instead of the legacy
internal/build_wheels.bat -> build_pytorch.bat -> {cpu,cuda,xpu}.bat
-> internal/setup.bat dispatch.

The GPU_ARCH_TYPE (cpu/cuda/xpu) selector is derived from DESIRED_CUDA
and exported for build_env_setup.py to dispatch on. The bash wrapper
sources two intermediate ENV_FILEs (one from env_setup, one from
install_deps) so build flags, libuv_ROOT, and vcvarsall's PATH/LIB
reach the eventual `python -m build` subprocess.

windows-arm64 wheels, libtorch zip artifacts, and cpu-s390x are
intentionally left on the legacy bat chain in this PR -- same scoping
discipline as pytorchgh-182409 on the Linux side.

Authored by Claude.
…line

With the new build_env_setup.py / build_install_deps.py / build_wheel.py
chain wired into binary_windows_build.sh, the x86_64 wheel build no
longer goes through the .bat orchestration. Drop the now-dead files:

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

Kept as installers invoked from the new pipeline:
  internal/install_python.bat      (from set_desired_python.sh)
  internal/cuda_install.bat        (from build_env_setup.py)
  internal/xpu_install.bat         (from build_env_setup.py)
  internal/vc_install_helper.bat   (from binary_windows_build.sh)
  internal/vs2022_install.ps1      (from vc_install_helper.bat)

Also adds the missing vc_install_helper.bat invocation that
internal/build_wheels.bat used to provide -- ensures VS2022 BuildTools
are present before vcvarsall is consulted by build_env_setup.py.

windows-arm64 wheels, libtorch zips, and the test scripts
(smoke_test, static_lib_test, win-test-helpers/...) are untouched.

Authored by Claude.
The 2026-05-19 CI on this branch failed every Windows wheel-build job
with `python: command not found` at binary_windows_build.sh line 60.
Root cause: install_python.bat never ran.

set_desired_python.sh invokes the installer with

    (cd "$WIN_CI_DIR" && cmd /c "internal\install_python.bat")

The bash `cd` inside the `(...)` subshell does not propagate to the cmd
child's Windows CWD on the MSYS/Git-Bash + Windows runner combo. cmd
starts with CWD inherited from the outer bash (`.ci/pytorch`), looks for
the relative path `internal\install_python.bat` from there, finds no
file, and exits in ~9 ms with no useful diagnostic. The subsequent
`source` continues happily, the PATH export lists a Python dir that does
not exist, and the next `python` invocation in binary_windows_build.sh
hits PATH-not-found.

Fix: convert WIN_CI_DIR to a Windows path with cygpath and `cd /d`
inside cmd before invoking the bat, so cmd's CWD is unambiguous and
install_python.bat's `%CD%\Python` TargetDir resolves correctly. Add a
post-loop sanity check that the binary actually landed, so a future
silent failure surfaces here with a clear message instead of as
`python: command not found` two screens later.

Test Plan:
Can only be validated by the Windows binary-build matrix on CI; the
runner-specific MSYS/cmd CWD-inheritance behavior is not reproducible
on Linux. Push and re-run `wheel-py3_10-cpu-build` (and a CUDA + XPU
job) on the rebased branch; expect the build step to proceed past
binary_windows_build.sh:60 instead of dying at exit code 127.

Authored by Claude.
The previous attempt invoked `internal\install_python.bat` from bash via
`cmd /c "cd /d \"$WIN_CI_DIR_W\" && internal\install_python.bat"`. CI on
the prior push validated that the cmd-CWD form was being used (and that
the sanity check pinned the next failure cleanly) but install_python.bat
still ran for ~9 ms with no output: cmd silently swallowed the command
line, almost certainly because of bash-side argv quoting interacting
poorly with the embedded double quotes around the Windows-style path
when CreateProcess re-concatenates the argv for cmd.

Eliminate the boundary entirely. The .bat only does a curl + run the
python.org .exe installer + pip-upgrade; that translates to bash
directly. The installer .exe runs natively under Git Bash (CreateProcess
on a .exe needs no shell), so we can pass the TargetDir via a
cygpath-converted Windows path without any cmd-side quote handling.

`internal\install_python.bat` is left in place — it is still consumed by
smoke_test.bat and .github/scripts/windows/build_triton.bat in
cmd-native contexts where the original chain works as designed.

Test Plan:
Same caveat as the previous fix attempt: validates only on the Windows
binary-build CI matrix; the MSYS argv-quoting behavior is not
reproducible on Linux. The added sanity check (`if [[ ! -x
$PYDIR/$PYTHON_EXE_NAME ]]`) ensures a future install-step regression
fails loudly here with a meaningful message instead of as `python:
command not found` two screens later.

Authored by Claude.
The previous iteration inlined the python.org installer call directly
from bash, removing the bash->cmd boundary that had caused
install_python.bat to silently no-op. CI on that change confirmed the
.exe was being launched and the cmd-CWD/argv-quoting trouble was gone,
but every wheel-build job then hung in set_desired_python.sh for the
full 6-hour GHA job timeout. Runner cleanup found two leftover
python-amd64.exe processes alive, pinpointing the cause: the python.org
wrapper .exe returns to its parent while the underlying install
continues asynchronously in child processes. Bash's wait() only blocks
for the immediate child, so when the wrapper returns we proceed while
the actual install is still running, and subsequent steps that touch
TargetDir contend with installer-held resources.

PowerShell's `Start-Process -Wait` waits for the process *and its
descendants* (the documented behavior). That matches the semantics
`start /wait` had in the legacy cmd-native chain and unblocks bash
cleanly once the install is fully done. We launch via PowerShell with
the arguments passed as a comma-separated array so each option reaches
the installer as a distinct argument, and propagate the installer's
exit code through PowerShell's exit so the retry loop still observes
failure.

Test Plan:
Same caveat as the previous two attempts: only validated by the
Windows binary-build CI matrix. Push and re-run a representative
wheel-py3_10-cpu-build; expect the install step to complete in seconds
rather than hanging for 6 hours, with the subsequent
build_env_setup.py / build_install_deps.py / build_wheel.py chain
producing actual compile output.

Authored by Claude.
The PowerShell Start-Process fix in the previous commit unblocked the
install hang, and `python ./windows/build_env_setup.py` now actually
runs. But every wheel-build job then fails ~2 s later when bash sources
the env-out file:

  ++ export 'BASH_FUNC_retry%%=() { $* || (sleep 1 && $*) || ... }'
  /tmp/tmp.BBvOGWqSmv: line 7: export:
    `BASH_FUNC_retry%%=...': not a valid identifier

Bash serializes `export -f retry` (defined in binary_populate_env.sh) as
the env variable `BASH_FUNC_retry%%=() { ... }`. That leaks into the
Python interpreter's `os.environ`, and from there into the env diff
captured by `_capture_cmd_env` (cmd's `set` output picks it up). The
identifier contains `%`, which bash refuses to re-export when sourcing
the env file.

Filter the env-out lines down to keys that match `[A-Za-z_][A-Za-z0-9_]*`
in both `build_env_setup.py` (the primary site, since it does the
os.environ-diffed capture) and `build_install_deps.py` (defense in depth;
it only writes a single hand-constructed key today, but anything that
later flows through write_env_exports gets the same protection).

Test Plan:
Only validated by Windows binary-build CI. Push and re-run a
representative wheel-py3_10-cpu-build; expect the source of the env
file to succeed and the chain to reach build_install_deps.py /
build_wheel.py with real compile output to follow.

Authored by Claude.
After the env-key filter cleared `BASH_FUNC_retry%%` from the env file,
build_env_setup.py now runs cleanly and write_env_exports lays down the
vcvarsall-captured env. But sourcing that file leaves bash with a
Windows-form PATH (`;`-separated, `C:\...\bin\HostX64\x64;...`), so the
next `python ./windows/build_install_deps.py` invocation dies with exit
127 — bash splits PATH on `:`, gets one bogus directory, and the lookup
fails.

The Windows form is unavoidable on the way in: when bash launches
python.exe, MSYS auto-translates PATH from POSIX to Windows form for
the child, and cmd's `set` therefore echoes Windows form too. Convert
back via `cygpath -up` (the established translator already used in
.ci/pytorch/win-build.sh and win-test.sh) when writing PATH to the env
file so the parent bash sees a usable POSIX list.

Gated on `;` actually being present in the captured value, so a future
caller that hands us a pre-converted POSIX PATH won't get double-
translated. Other path-like vars (INCLUDE, LIB, LIBPATH, ...) are left
in Windows form because the MSVC tools that consume them expect that.

Test Plan:
Only validated by the Windows binary-build CI matrix. Push and re-run
a representative wheel-py3_10-cpu-build; expect build_install_deps.py
to actually run (pip-install cmake/ninja/numpy etc.) and the chain to
reach build_wheel.py with real compile output.

Authored by Claude.
build_install_deps.py now calls 'spin clean' but spin isn't preinstalled
on the python.org Python we deploy in set_desired_python.sh. Match the
Linux-side pin used in .ci/docker/requirements-ci.txt.
spin discovers its config from the CWD's pyproject.toml; the bash
caller invokes build_install_deps.py from .ci/pytorch/ so spin can't
find pyproject.toml. Pass cwd=PYTORCH_ROOT explicitly.
oneAPI's compiler/vars.bat probes VS<year>INSTALLDIR to locate the host
MSVC toolchain and aborts (without exporting any of the env we need)
when neither is set. In the legacy cmd-native chain, check_deps.bat ran
its vswhere pass before xpu.bat and stashed the result in VS15INSTALLDIR
for xpu.bat to alias as VS2022INSTALLDIR. Our Python port discovered
vcvarsall lazily inside main() after the dispatch, so the XPU branch
ran with neither var set and hit the same vars.bat early-exit.

Hoist find_vcvarsall() above the GPU dispatch and pass the derived VS
install root into setup_xpu so it can populate both VS15INSTALLDIR and
VS2022INSTALLDIR before sourcing oneAPI.
The Windows pip-installed MKL lands under <PythonPrefix>\Library, and
without CMAKE_PREFIX_PATH pointing there, CMake's BLAS lookup falls
through to general BLAS and finds nothing. CPU wheels don't notice
because aten/src/ATen/CMakeLists.txt's MSVC TH_BINARY_BUILD branch
appends ${BLAS_LIBRARIES} only to ATen_CUDA_DEPENDENCY_LIBS; an empty
list-variable serializes as the literal token "NOTFOUND" in the CUDA
link line, surfacing as "LNK1181: cannot open input file 'NOTFOUND.lib'"
when building torch_cuda.dll.

Legacy build_pytorch.bat set "CMAKE_PREFIX_PATH=%CD%\Python\Library\;%PATH%";
Python's sys.prefix gives the same install root, so derive it from there.
The Python pipeline only wired sccache into the CUDA branch, so the
USE_SCCACHE=1 / SCCACHE_BUCKET env that binary_windows_build.sh exports
went unused on every CPU wheel build (6 Python versions per cycle).
CPU compiles ran without cache and rebuilt every TU from scratch.

The legacy check_opts.bat set CC/CXX=sccache cl whenever sccache.exe
was on PATH and USE_SCCACHE!=0. Mirror that: extract host-compiler
sccache install into setup_sccache(), call it from both the CPU and
CUDA branches, and gate on USE_SCCACHE=0 so XPU (which sets
USE_SCCACHE=0 in binary_windows_build.sh) and any future debug
override correctly bypass the cache.

randomtemp moves into setup_nvcc_wrapper because it's only useful
when wrapping nvcc; CPU never invokes the NVCC wrapper, so there's
no reason to download randomtemp on CPU builds.
zklaus added 8 commits June 16, 2026 08:02
shell_quote, write_env_exports, _BASH_IDENT_RE, _to_posix_path_list,
and download were duplicated across build_env_setup.py and
build_install_deps.py. Worse, build_install_deps.py's write_env_exports
lacked the cygpath -up PATH conversion that build_env_setup.py grew --
so any future caller adding a PATH-bearing var to build_install_deps's
env-out would have hit the same exit-127 failure the conversion was
introduced to fix.

Move the shared pieces to .ci/pytorch/windows/_common.py and import
from both sites. Side benefit: build_install_deps.py's writer now has
the PATH conversion too, closing the divergence.
Reviewers comparing the new Windows pipeline to the Linux template
(pytorchgh-182409) will notice the missing repair_wheel.py step. Spelled out
why it isn't needed on Windows so the asymmetry doesn't read as an
oversight: DLL discovery doesn't use RPATH, and CUDA DLLs already
land in torch/lib/ during the build.

Wheel-content diff against the latest published nightly cpu wheel
confirms parity: identical DLL set (9 DLLs, 13 libs) in torch/lib/.
Three RUFF warnings flagged by CI lint that lintrunner's auto-fix
caught (and that my local lintrunner missed due to stale init):

- _common.py: move 'from pathlib import Path' under TYPE_CHECKING
  (TC003: Path is only referenced from type annotations; method
  calls on path objects don't need the name).
- build_env_setup.py / build_install_deps.py: drop the defensive
  '# noqa: E402' on the post-sys.path.insert imports (RUF100:
  E402 isn't enabled in the project's ruff config, so the noqa
  was a no-op).
The legacy Windows CD wheel path set BUILD_TEST=0 in internal/setup.bat's
:pytorch branch (added by pytorchgh-182123) so the C++ test binaries are not
compiled during binary wheel builds. The Python pipeline that replaced
that bat chain carried INSTALL_TEST=0 but dropped BUILD_TEST=0, so every
Windows CD wheel build was recompiling the test executables for no
reason. Restore it in COMMON_BUILD_ENV, matching the Linux sibling
.ci/manywheel/build_env_setup.py.

BUILD_TEST and INSTALL_TEST are distinct: INSTALL_TEST controls whether
test binaries are bundled into the wheel; BUILD_TEST controls whether
they are compiled at all. Both belong in the binary-build env.

Test Plan:
- lintrunner -a (clean).
- Surfaced by a port-fidelity diff of the deleted setup.bat against the
  new COMMON_BUILD_ENV; BUILD_TEST=0 was present on the legacy :pytorch
  branch (setup.bat:90) and absent from the Python pipeline.

Authored with assistance from Claude.
set_desired_python.sh special-cased the literal "3.14t", so any other
free-threaded variant (e.g. a future "3.15t") would fall through to the
default branch, build a non-existent installer URL, and install a
non-free-threaded interpreter under the wrong exe name. Derive the base
version by stripping a trailing "t" and key the freethreaded installer
option and exe name off the suffix, so a single branch covers every
t-variant. The legacy internal/install_python.bat had the same 3.14t
hardcoding; this generalizes it.

The .0 patch pin is kept deliberately (it mirrors the legacy
install_python.bat for reproducible installs) and is now documented.

For the current matrix (3.10-3.14 plus 3.14t) the generated URLs and exe
names are byte-identical to before, so this is a no-op for today's jobs
and only unblocks future free-threaded versions.

Test Plan:

```
bash -n .ci/pytorch/windows/set_desired_python.sh
```

Verified the base-stripping by hand for 3.13/3.14/3.14t/3.15t: 3.14t
resolves to the same URL and python3.14t.exe as the old hardcoded branch,
and 3.15t now resolves correctly instead of 404ing.

Authored with assistance from Claude.
install_libuv returned python_prefix/Library unconditionally. If the
ossci-windows libuv tarball layout ever changes so that the extract
produces no Library/ tree, libuv_ROOT would point at a nonexistent
directory and the failure would surface much later as a confusing
"libuv not found" during the cmake configure. Fail fast at extract time
with a message that names the expected path and the likely cause.

Test Plan:

```
python -m py_compile .ci/pytorch/windows/build_install_deps.py
```

Authored with assistance from Claude.
The bash wrapper (binary_windows_build.sh) always exports GPU_ARCH_TYPE
as one of cpu/cuda/xpu before invoking build_env_setup.py, so the
DESIRED_CUDA fallback and the cu*-to-cuda remap were unreachable. Read
GPU_ARCH_TYPE directly with a cpu default for standalone invocation and
document the wrapper contract.

Test Plan:

```
python -m py_compile .ci/pytorch/windows/build_env_setup.py
```

Authored with assistance from Claude.
set_desired_python.sh pinned the patch level to ".0", which freezes each
minor on its oldest release and ships known CVEs for the life of the
minor. That pin was introduced by pytorchgh-151035 when it swapped conda (whose
`python=3.X` floated to the newest channel patch) for the python.org
installer.

Replace it with an explicit per-minor patch table. This keeps installs
reproducible (a given commit always resolves the same interpreter) while
letting us move off the oldest patch deliberately in review. Floating to
the newest installer was considered and rejected: python.org serves
source-only releases for security-only minors (e.g. 3.10.20 has no
amd64.exe), so floating requires scraping the release index and
HEAD-probing candidates newest-first, which makes every build depend on
that listing and fires request bursts that python.org rate-limits.

The security-only minors (3.10-3.12) are pinned to their last release
that shipped a Windows installer; the bugfix minors (3.13, 3.14) point at
the current newest installer and carry a comment to bump them here. The
table must stay in sync with the matrix in
generated-windows-binary-wheel-nightly.yml.

Test Plan:

```
bash -n .ci/pytorch/windows/set_desired_python.sh
lintrunner -a .ci/pytorch/windows/set_desired_python.sh
```

Verified each pinned installer exists (HTTP 200) and that the source-only
successors 404, confirming the security-only pins are the last available:

```
3.10.11 200 / 3.10.12+ source-only
3.11.9  200 / 3.11.10 404
3.12.10 200 / 3.12.11 404
3.13.14 200 (current bugfix latest)
3.14.6  200 (current bugfix latest)
```

Authored with assistance from Claude.
@zklaus
zklaus force-pushed the cd-windows-python-scripts branch from fe28989 to 80cae4e Compare June 16, 2026 07:28
zklaus added 2 commits June 16, 2026 13:37
The free-threaded wheel jobs (DESIRED_PYTHON=3.14t) failed their smoke
test with "torch-...-cp314-cp314-win_amd64.whl is not a supported wheel
on this platform": the build produced a regular cp314 wheel, but the test
job runs under python3.14t (cp314t ABI) and rejects it.

Root cause: a free-threaded python.org install ships both python.exe and
python3.14t.exe under the same prefix. binary_windows_build.sh invoked the
pipeline (build_env_setup.py / build_install_deps.py / build_wheel.py) via
a bare `python`, which resolves to the regular python.exe, so `python -m
build` produced a non-free-threaded wheel and the pip build deps landed in
the wrong interpreter. Because python.exe exists, this failed silently
into the wrong ABI rather than erroring.

set_desired_python.sh already knew the right exe (PYTHON_EXE_NAME); export
it as DESIRED_PYTHON_EXE and drive all three pipeline steps through it so
deps and the wheel ABI tag track DESIRED_PYTHON. Non-free-threaded builds
are unchanged (the exe is plain python.exe).

Test Plan:

```
bash -n .ci/pytorch/windows/set_desired_python.sh
bash -n .ci/pytorch/binary_windows_build.sh
lintrunner -a .ci/pytorch/windows/set_desired_python.sh .ci/pytorch/binary_windows_build.sh
```

Verified against the failing run: the py3_14t build emitted a cp314 wheel
(job log) which the cp314t test rejected; routing the build through
python3.14t.exe produces a cp314t wheel. Needs a CD re-run to confirm
green end to end.

Authored with assistance from Claude.
The xpu wheel jobs failed their smoke test at "Checking that MKL is
available" (torch.backends.mkl.is_available() == False). The xpu build
configured BLAS as Eigen -- the cmake log shows "Trying to find preferred
BLAS backend of choice: MKL ... MKL could not be found. Defaulting to
Eigen", with mkl_intel_lp64 not found.

Root cause: CMAKE_PREFIX_PATH was assigned <sys.prefix>/Library (where pip
mkl-static/mkl-include land) before the per-device setup ran. The XPU
oneAPI vars.bat sets its own CMAKE_PREFIX_PATH, and `env_out.update(
setup_xpu(...))` then overwrote the Library entry, so the xpu build lost
the MKL prefix entirely. cpu/cuda were unaffected because nothing else
touches CMAKE_PREFIX_PATH there, which is why only xpu failed.

Move the assignment after the device dispatch and prepend the MKL prefix
to whatever the device setup contributed, so both the pip MKL and the
oneAPI compiler prefix stay on the search path.

Test Plan:

```
python -m py_compile .ci/pytorch/windows/build_env_setup.py
lintrunner -a .ci/pytorch/windows/build_env_setup.py
```

Confirmed from the failing run's build logs: cpu CMAKE_PREFIX_PATH ended
in ...\Python\Library (MKL found); xpu ended in
...\oneAPI\compiler\latest (Library dropped, MKL not found). Needs a CD
re-run to confirm the xpu smoke test passes.

Authored with assistance from Claude.
@atalman

atalman commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator

@pytorchmergebot merge -f "all looks good"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

zklaus added a commit to zklaus/pytorch that referenced this pull request Jun 23, 2026
Port the macOS arm64 CD wheel build from the monolithic build_wheel.sh to
the same staged Python pipeline used for Linux (pytorch#182409) and Windows
(pytorch#184407): build_env_setup.py emits the macOS build flags to an env file,
build_install_deps.py installs the pinned build/runtime deps (and libomp
when not staged), build_wheel.py runs `python -m build`, and repair_wheel.py
delocates the wheel in place. A per-Python build.sh owns the stage contract;
build_all_macos_wheels.sh selects the interpreter and loops.

Delocation moves into the per-Python build (repair_wheel.py) instead of a
separate workflow step, so the template drops the "Delocate all wheels" step
and the generated workflow is regenerated to match.

build_wheel.sh and delocate_wheels.sh are removed: the former's wheel path is
superseded by the Python modules and its BUILD_PYTHONLESS/libtorch branch was
dead code (macOS ships no libtorch package; libtorch is built on Linux via
.ci/libtorch/), and the latter's logic now lives in repair_wheel.py.

Review in pipeline order: build.sh (the contract) first, then the four stage
modules, then build_all_macos_wheels.sh and the workflow template.

Test Plan:
Static checks only so far (no macOS runner in this environment):

```
python3 -m py_compile .ci/wheel/*.py
bash -n .ci/wheel/build.sh .ci/wheel/build_all_macos_wheels.sh
python3 .github/scripts/generate_ci_workflows.py   # regen, clean diff
lintrunner .ci/wheel/*.py .ci/wheel/*.sh \
    .github/templates/macos_binary_build_workflow.yml.j2 \
    .github/workflows/generated-macos-arm64-binary-wheel-nightly.yml
```

End-to-end validation on a macOS arm64 runner (the nightly wheel matrix) is
pending and will be exercised via ciflow/binaries.

Authored with assistance from Claude Code.
zklaus added a commit to zklaus/pytorch that referenced this pull request Jun 30, 2026
Port the macOS arm64 CD wheel build from the monolithic build_wheel.sh to
the same staged Python pipeline used for Linux (pytorch#182409) and Windows
(pytorch#184407): build_env_setup.py emits the macOS build flags to an env file,
build_install_deps.py installs the pinned build/runtime deps (and libomp
when not staged), build_wheel.py runs `python -m build`, and repair_wheel.py
delocates the wheel in place. A per-Python build.sh owns the stage contract;
build_all_macos_wheels.sh selects the interpreter and loops.

Delocation moves into the per-Python build (repair_wheel.py) instead of a
separate workflow step, so the template drops the "Delocate all wheels" step
and the generated workflow is regenerated to match.

build_wheel.sh and delocate_wheels.sh are removed: the former's wheel path is
superseded by the Python modules and its BUILD_PYTHONLESS/libtorch branch was
dead code (macOS ships no libtorch package; libtorch is built on Linux via
.ci/libtorch/), and the latter's logic now lives in repair_wheel.py.

Review in pipeline order: build.sh (the contract) first, then the four stage
modules, then build_all_macos_wheels.sh and the workflow template.

Test Plan:
Static checks only so far (no macOS runner in this environment):

```
python3 -m py_compile .ci/wheel/*.py
bash -n .ci/wheel/build.sh .ci/wheel/build_all_macos_wheels.sh
python3 .github/scripts/generate_ci_workflows.py   # regen, clean diff
lintrunner .ci/wheel/*.py .ci/wheel/*.sh \
    .github/templates/macos_binary_build_workflow.yml.j2 \
    .github/workflows/generated-macos-arm64-binary-wheel-nightly.yml
```

End-to-end validation on a macOS arm64 runner (the nightly wheel matrix) is
pending and will be exercised via ciflow/binaries.

Authored with assistance from Claude Code.
pytorchmergebot pushed a commit that referenced this pull request Jul 1, 2026
## Summary

Refactors the macOS arm64 CD wheel build from the monolithic `build_wheel.sh` into the same staged Python pipeline already adopted for Linux (#182409) and Windows (#184407). This is the third and final platform, bringing macOS in line with the cross-platform structure.

Following the Linux template, the build is split into four single-responsibility modules under `.ci/macwheel/`, driven by a per-Python `build.sh` orchestrator that owns the stage contract:

- `build_env_setup.py` — emits the macOS build flags (`USE_DISTRIBUTED`, deployment target, Metal/CoreML, libomp prefix) to an `--env-out` file the orchestrator sources
- `build_install_deps.py` — pinned build/runtime deps + numpy pin; libomp via Homebrew when not staged
- `build_wheel.py` — sets the arm64 host platform / `ARCHFLAGS` and runs `python -m build --wheel --no-isolation`
- `repair_wheel.py` — delocates the wheel in place (the macOS analog of Linux's `auditwheel`/patchelf; Windows needs no repair)

`build_all_macos_wheels.sh` selects each interpreter and loops, reusing the ABI-free `libtorch_cpu` across Python versions via `SKIP_SETUP_CLEAN` (same incremental-build trick as Linux).

### Notable points

- **macOS is arm64-only.** Main builds no Intel-Mac wheels (the matrix emits only `macos-arm64`), so the pipeline is arm64-only by design — and the dead `x86_64`/`BUILD_PYTHONLESS` libtorch branches in the old `build_wheel.sh` are removed. macOS still ships a libtorch artifact, but it is *extracted from the finished wheel* by a later workflow job (`.ci/libtorch/extract_libtorch_from_wheel.py`), not produced by a separate `BUILD_PYTHONLESS` build.
- **Delocation moves inline** into the per-Python build (`repair_wheel.py`), so the workflow drops its separate "Delocate all wheels" step.
- **Directory renamed** `.ci/wheel/` → `.ci/macwheel/`, parallel to Linux's `.ci/manywheel/` (the old name was too generic for a macOS-only build).
- `build_install_deps.py` uses **`spin clean`** rather than `setup.py clean`, matching Windows and surviving the eventual `setup.py` removal.

### Review order

1. `build.sh` (the stage contract), then the four stage modules
2. `build_all_macos_wheels.sh` and the workflow template
3. The second commit is a pure rename + `spin clean` switch

## Test Plan

Static + structural checks locally:

```
python3 -m py_compile .ci/macwheel/*.py
bash -n .ci/macwheel/build.sh .ci/macwheel/build_all_macos_wheels.sh
python3 .github/scripts/generate_ci_workflows.py   # only the macOS workflow changes
lintrunner .ci/macwheel/* .github/templates/macos_binary_build_workflow.yml.j2
```

A from-source build on a dev Mac exercised the pipeline through environment setup, dependency install, CMake configure, and compilation, confirming the orchestration contract (venv handoff, `--env-out` sourcing, `python -m build` invocation). End-to-end wheel production + delocation is validated by this PR's `ciflow/binaries` run on the `macos-arm64` runner.

Opening as a draft for a first round of CI.

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

Pull Request resolved: #187944
Approved by: https://github.com/atalman
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
vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
…#187944)

## Summary

Refactors the macOS arm64 CD wheel build from the monolithic `build_wheel.sh` into the same staged Python pipeline already adopted for Linux (pytorch#182409) and Windows (pytorch#184407). This is the third and final platform, bringing macOS in line with the cross-platform structure.

Following the Linux template, the build is split into four single-responsibility modules under `.ci/macwheel/`, driven by a per-Python `build.sh` orchestrator that owns the stage contract:

- `build_env_setup.py` — emits the macOS build flags (`USE_DISTRIBUTED`, deployment target, Metal/CoreML, libomp prefix) to an `--env-out` file the orchestrator sources
- `build_install_deps.py` — pinned build/runtime deps + numpy pin; libomp via Homebrew when not staged
- `build_wheel.py` — sets the arm64 host platform / `ARCHFLAGS` and runs `python -m build --wheel --no-isolation`
- `repair_wheel.py` — delocates the wheel in place (the macOS analog of Linux's `auditwheel`/patchelf; Windows needs no repair)

`build_all_macos_wheels.sh` selects each interpreter and loops, reusing the ABI-free `libtorch_cpu` across Python versions via `SKIP_SETUP_CLEAN` (same incremental-build trick as Linux).

### Notable points

- **macOS is arm64-only.** Main builds no Intel-Mac wheels (the matrix emits only `macos-arm64`), so the pipeline is arm64-only by design — and the dead `x86_64`/`BUILD_PYTHONLESS` libtorch branches in the old `build_wheel.sh` are removed. macOS still ships a libtorch artifact, but it is *extracted from the finished wheel* by a later workflow job (`.ci/libtorch/extract_libtorch_from_wheel.py`), not produced by a separate `BUILD_PYTHONLESS` build.
- **Delocation moves inline** into the per-Python build (`repair_wheel.py`), so the workflow drops its separate "Delocate all wheels" step.
- **Directory renamed** `.ci/wheel/` → `.ci/macwheel/`, parallel to Linux's `.ci/manywheel/` (the old name was too generic for a macOS-only build).
- `build_install_deps.py` uses **`spin clean`** rather than `setup.py clean`, matching Windows and surviving the eventual `setup.py` removal.

### Review order

1. `build.sh` (the stage contract), then the four stage modules
2. `build_all_macos_wheels.sh` and the workflow template
3. The second commit is a pure rename + `spin clean` switch

## Test Plan

Static + structural checks locally:

```
python3 -m py_compile .ci/macwheel/*.py
bash -n .ci/macwheel/build.sh .ci/macwheel/build_all_macos_wheels.sh
python3 .github/scripts/generate_ci_workflows.py   # only the macOS workflow changes
lintrunner .ci/macwheel/* .github/templates/macos_binary_build_workflow.yml.j2
```

A from-source build on a dev Mac exercised the pipeline through environment setup, dependency install, CMake configure, and compilation, confirming the orchestration contract (venv handoff, `--env-out` sourcing, `python -m build` invocation). End-to-end wheel production + delocation is validated by this PR's `ciflow/binaries` run on the `macos-arm64` runner.

Opening as a draft for a first round of CI.

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

Pull Request resolved: pytorch#187944
Approved by: https://github.com/atalman
DamJanusz pushed a commit to DamJanusz/pytorch that referenced this pull request Jul 21, 2026
…#187944)

## Summary

Refactors the macOS arm64 CD wheel build from the monolithic `build_wheel.sh` into the same staged Python pipeline already adopted for Linux (pytorch#182409) and Windows (pytorch#184407). This is the third and final platform, bringing macOS in line with the cross-platform structure.

Following the Linux template, the build is split into four single-responsibility modules under `.ci/macwheel/`, driven by a per-Python `build.sh` orchestrator that owns the stage contract:

- `build_env_setup.py` — emits the macOS build flags (`USE_DISTRIBUTED`, deployment target, Metal/CoreML, libomp prefix) to an `--env-out` file the orchestrator sources
- `build_install_deps.py` — pinned build/runtime deps + numpy pin; libomp via Homebrew when not staged
- `build_wheel.py` — sets the arm64 host platform / `ARCHFLAGS` and runs `python -m build --wheel --no-isolation`
- `repair_wheel.py` — delocates the wheel in place (the macOS analog of Linux's `auditwheel`/patchelf; Windows needs no repair)

`build_all_macos_wheels.sh` selects each interpreter and loops, reusing the ABI-free `libtorch_cpu` across Python versions via `SKIP_SETUP_CLEAN` (same incremental-build trick as Linux).

### Notable points

- **macOS is arm64-only.** Main builds no Intel-Mac wheels (the matrix emits only `macos-arm64`), so the pipeline is arm64-only by design — and the dead `x86_64`/`BUILD_PYTHONLESS` libtorch branches in the old `build_wheel.sh` are removed. macOS still ships a libtorch artifact, but it is *extracted from the finished wheel* by a later workflow job (`.ci/libtorch/extract_libtorch_from_wheel.py`), not produced by a separate `BUILD_PYTHONLESS` build.
- **Delocation moves inline** into the per-Python build (`repair_wheel.py`), so the workflow drops its separate "Delocate all wheels" step.
- **Directory renamed** `.ci/wheel/` → `.ci/macwheel/`, parallel to Linux's `.ci/manywheel/` (the old name was too generic for a macOS-only build).
- `build_install_deps.py` uses **`spin clean`** rather than `setup.py clean`, matching Windows and surviving the eventual `setup.py` removal.

### Review order

1. `build.sh` (the stage contract), then the four stage modules
2. `build_all_macos_wheels.sh` and the workflow template
3. The second commit is a pure rename + `spin clean` switch

## Test Plan

Static + structural checks locally:

```
python3 -m py_compile .ci/macwheel/*.py
bash -n .ci/macwheel/build.sh .ci/macwheel/build_all_macos_wheels.sh
python3 .github/scripts/generate_ci_workflows.py   # only the macOS workflow changes
lintrunner .ci/macwheel/* .github/templates/macos_binary_build_workflow.yml.j2
```

A from-source build on a dev Mac exercised the pipeline through environment setup, dependency install, CMake configure, and compilation, confirming the orchestration contract (venv handoff, `--env-out` sourcing, `python -m build` invocation). End-to-end wheel production + delocation is validated by this PR's `ciflow/binaries` run on the `macos-arm64` runner.

Opening as a draft for a first round of CI.

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

Pull Request resolved: pytorch#187944
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
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…#187944)

## Summary

Refactors the macOS arm64 CD wheel build from the monolithic `build_wheel.sh` into the same staged Python pipeline already adopted for Linux (pytorch#182409) and Windows (pytorch#184407). This is the third and final platform, bringing macOS in line with the cross-platform structure.

Following the Linux template, the build is split into four single-responsibility modules under `.ci/macwheel/`, driven by a per-Python `build.sh` orchestrator that owns the stage contract:

- `build_env_setup.py` — emits the macOS build flags (`USE_DISTRIBUTED`, deployment target, Metal/CoreML, libomp prefix) to an `--env-out` file the orchestrator sources
- `build_install_deps.py` — pinned build/runtime deps + numpy pin; libomp via Homebrew when not staged
- `build_wheel.py` — sets the arm64 host platform / `ARCHFLAGS` and runs `python -m build --wheel --no-isolation`
- `repair_wheel.py` — delocates the wheel in place (the macOS analog of Linux's `auditwheel`/patchelf; Windows needs no repair)

`build_all_macos_wheels.sh` selects each interpreter and loops, reusing the ABI-free `libtorch_cpu` across Python versions via `SKIP_SETUP_CLEAN` (same incremental-build trick as Linux).

### Notable points

- **macOS is arm64-only.** Main builds no Intel-Mac wheels (the matrix emits only `macos-arm64`), so the pipeline is arm64-only by design — and the dead `x86_64`/`BUILD_PYTHONLESS` libtorch branches in the old `build_wheel.sh` are removed. macOS still ships a libtorch artifact, but it is *extracted from the finished wheel* by a later workflow job (`.ci/libtorch/extract_libtorch_from_wheel.py`), not produced by a separate `BUILD_PYTHONLESS` build.
- **Delocation moves inline** into the per-Python build (`repair_wheel.py`), so the workflow drops its separate "Delocate all wheels" step.
- **Directory renamed** `.ci/wheel/` → `.ci/macwheel/`, parallel to Linux's `.ci/manywheel/` (the old name was too generic for a macOS-only build).
- `build_install_deps.py` uses **`spin clean`** rather than `setup.py clean`, matching Windows and surviving the eventual `setup.py` removal.

### Review order

1. `build.sh` (the stage contract), then the four stage modules
2. `build_all_macos_wheels.sh` and the workflow template
3. The second commit is a pure rename + `spin clean` switch

## Test Plan

Static + structural checks locally:

```
python3 -m py_compile .ci/macwheel/*.py
bash -n .ci/macwheel/build.sh .ci/macwheel/build_all_macos_wheels.sh
python3 .github/scripts/generate_ci_workflows.py   # only the macOS workflow changes
lintrunner .ci/macwheel/* .github/templates/macos_binary_build_workflow.yml.j2
```

A from-source build on a dev Mac exercised the pipeline through environment setup, dependency install, CMake configure, and compilation, confirming the orchestration contract (venv handoff, `--env-out` sourcing, `python -m build` invocation). End-to-end wheel production + delocation is validated by this PR's `ciflow/binaries` run on the `macos-arm64` runner.

Opening as a draft for a first round of CI.

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

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

Labels

ciflow/binaries Trigger all binary build and upload jobs on the PR Merged open source release notes: releng release notes category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants