Skip to content

[native_aot][7/7] build_stage2: relink, patch the wheel, and the build wiring - #194243

Closed
slayton58 wants to merge 21 commits into
gh/slayton58/151/basefrom
gh/slayton58/151/head
Closed

slayton58 wants to merge 21 commits into
gh/slayton58/151/basefrom
gh/slayton58/151/head

Conversation

@slayton58

@slayton58 slayton58 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Human note:

Finally putting everything together. Relink libtorch_cuda, correctly fixup the wheel, and
make sure everything (paths, manifests, etc.) are all aligned and correct.

Claude note:

The driver on top of the verdict, and the CI and dev flows that call it. With
this commit a standard CUDA build ships embedded AOT kernels.

A post-install step, because the kernel builders package-import torch and
scikit-build-core has no post-build hook inside the PEP 517 backend. It
reconfigures before a targeted relink of torch_cuda: the generated file registers
itself in CMAKE_CONFIGURE_DEPENDS only from the reconfigure that first READS it,
and the build.ninja on disk predates this generation -- without that the relink
silently omitted the kernels (417 MiB where 423 ships).

--wheel patches the relinked library and its RECORD entry back into the built
wheel, so test jobs get the kernels rather than a library replaced only on disk;
released wheels get the same before repair_wheel.py, so it goes through patchelf
like any other. It asserts that torch imports, because a kernel-free release wheel
must fail rather than skip -- and the ASan and TSan images cannot import torch
plainly, which is why the CI call is CUDA-guarded.

It assumes the torch it finds installed is the one this tree just built, and
VERIFIES that rather than repairing it: the reconfigure has to report embedding
before anything is relinked, the relinked library has to report its own kernels
before this exits, and a failure past that point says to reinstall. A run that
DECLINES overwrites a native_aot.cmake an earlier one left behind, because the
include is unconditional and the release matrix shares one build tree across eight
interpreters -- so the wheel for an interpreter with no DSL runtime was shipping
the previous interpreter's objects.

caffe2/CMakeLists.txt gets the one include line, EnvVarForwarding.cmake caches
TORCH_NATIVE_AOT so the opt-out survives a reconfigure, and CONTRIBUTING.md states
the skip reasons.

Test Plan:

pytest tools/test/test_native_aot_tools.py

Run at this commit's own tree, in a checkout with no built torch -- which is
what lint.yml's "Test tools" job has. This commit's tests cover patch_wheel's
RECORD and its ZIP64 metadata -- a copied member must not inherit the source's
stale offsets, which pip and unzip accept and uv refuses -- each of main()'s
refusals from the verdict down to a relink that produced no library, the argv and
env contract with both children including the one artifacts directory they share,
and the CI shells and CMake read as text.

PR CI cannot reach the relink at this commit -- no declaration exists yet, so
should_run() reports "nothing declares kernels" in every build job -- so it was
exercised by hand on a clean tree:

rm -rf build && USE_CUDNN=1 USE_CUDA=1 USE_MSLK=1 MAX_JOBS=32 spin develop

Stage 2 exported all four declarations (54 objects + 4 generated sources, 4.0 MiB),
reconfigured, relinked, copied 324 MiB over the installed torch and passed its
embedded-kernel probe. On that build: test/python_native, one file per process, 331
passed; test_ops.py -k "cuda and (topk or scatter_add or index_add)" 115 passed;
test_sort_and_select 207; test_scatter_gather_ops 247; test_indexing 380.

Authored with an AI assistant (Claude Code).

[ghstack-poisoned]
@slayton58
slayton58 requested a review from a team as a code owner August 20, 2026 15:52
@pytorch-bot

pytorch-bot Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 2 Pending, 6 Unclassified Failures

As of commit 4984518 with merge base 67aade5 (image):

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

  • macos-arm64-binary-wheel / wheel-build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    ninja: build stopped: subcommand failed

    AI verdict: AI verdict: infra issue

    The build failed because pyyaml crashed with SIGSEGV (exit code -11) during pip's dependency resolution phase on macOS ARM64. This is an infrastructure/environment issue unrelated to the commit's Python-only changes to native AOT tooling.

    Full reasoning on HUD →

  • windows-binary-wheel / wheel-py3_15-cpu-build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    No files were found with the provided path: C:\actions-runner\_work\_temp/artifacts. No artifacts will be uploaded.

    AI verdict: AI verdict: not related

    The failure is caused by a missing Cython compiler when trying to build NumPy 2.5.1 from source for Python 3.15 on Windows. The suspect commit only modifies files in tools/native_aot/ and tools/test/, which are completely unrelated to the Windows wheel build dependency installation process.

    Full reasoning on HUD →

  • windows-binary-wheel / wheel-py3_15-cuda12_6-build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    No files were found with the provided path: C:\actions-runner\_work\_temp/artifacts. No artifacts will be uploaded.

    AI verdict: AI verdict: not related

    The build fails during NumPy 2.5.1 dependency installation because Cython is missing/broken on the Windows runner, before PyTorch's own build starts. This affects all py3_15 variants (CPU, XPU, CUDA) equally, and the PR's native_aot changes don't touch dependency installation.

    Full reasoning on HUD →

  • windows-binary-wheel / wheel-py3_15-cuda13_0-build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    No files were found with the provided path: C:\actions-runner\_work\_temp/artifacts. No artifacts will be uploaded.

    AI verdict: AI verdict: infra issue

    The build fails because NumPy 2.5.1 cannot be built from source on Python 3.15 Windows — Cython is missing from the CI environment. The suspect commit does not touch any Windows CI scripts, dependency specifications, or workflow files.

    Full reasoning on HUD →

  • windows-binary-wheel / wheel-py3_15-cuda13_2-build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    No files were found with the provided path: C:\actions-runner\_work\_temp/artifacts. No artifacts will be uploaded.

    AI verdict: AI verdict: infra issue

    The build fails because numpy cannot be installed from source on Windows with Python 3.15 — cython/cython3 is not found. This is a CI environment issue unrelated to the suspect commit, which only modifies native_aot tooling files.

    Full reasoning on HUD →

  • windows-binary-wheel / wheel-py3_15-xpu-build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    No files were found with the provided path: C:\actions-runner\_work\_temp/artifacts. No artifacts will be uploaded.

    AI verdict: AI verdict: not related

    The failure is Cython segfaulting (0xC0000005) when pip tries to build NumPy from source on Python 3.15 beta, before the PyTorch build even starts. The suspect commit only modifies native_aot tool files with no connection to dependency installation. The same job succeeded earlier the same day, indicating an external environment change (likely a new Cython/NumPy version incompatible with Python 3.15 beta).

    Full reasoning on HUD →

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

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@slayton58
slayton58 requested a review from albanD August 31, 2026 17:29
slayton58 added a commit that referenced this pull request Aug 31, 2026
…d wiring

Human note:

Finally putting everything together. Relink libtorch_cuda, correctly fixup the wheel, and
make sure everything (paths, manifests, etc.) are all aligned and correct.

Claude note:

The driver on top of the verdict, and the CI and dev flows that call it. With
this commit a standard CUDA build ships embedded AOT kernels.

A post-install step, because the kernel builders package-import torch and
scikit-build-core has no post-build hook inside the PEP 517 backend. It
reconfigures before a targeted relink of torch_cuda: the generated file registers
itself in CMAKE_CONFIGURE_DEPENDS only from the reconfigure that first READS it,
and the build.ninja on disk predates this generation -- without that the relink
silently omitted the kernels (417 MiB where 423 ships).

--wheel patches the relinked library and its RECORD entry back into the built
wheel, so test jobs get the kernels rather than a library replaced only on disk;
released wheels get the same before repair_wheel.py, so it goes through patchelf
like any other. It asserts that torch imports, because a kernel-free release wheel
must fail rather than skip -- and the ASan and TSan images cannot `import torch`
plainly, which is why the CI call is CUDA-guarded.

It assumes the torch it finds installed is the one this tree just built, and
VERIFIES that rather than repairing it: the reconfigure has to report embedding
before anything is relinked, the relinked library has to report its own kernels
before this exits, and a failure past that point says to reinstall. A run that
DECLINES overwrites a native_aot.cmake an earlier one left behind, because the
include is unconditional and the release matrix shares one build tree across eight
interpreters -- so the wheel for an interpreter with no DSL runtime was shipping
the previous interpreter's objects.

caffe2/CMakeLists.txt gets the one include line, EnvVarForwarding.cmake caches
TORCH_NATIVE_AOT so the opt-out survives a reconfigure, and CONTRIBUTING.md states
the skip reasons.

Test Plan:

```
pytest tools/test/test_native_aot_tools.py
```

Run at this commit's own tree, in a checkout with no built torch -- which is
what lint.yml's "Test tools" job has. This commit's tests cover patch_wheel's
RECORD and its ZIP64 metadata -- a copied member must not inherit the source's
stale offsets, which pip and unzip accept and `uv` refuses -- each of main()'s
refusals from the verdict down to a relink that produced no library, the argv and
env contract with both children including the one artifacts directory they share,
and the CI shells and CMake read as text.

PR CI cannot reach the relink at this commit -- no declaration exists yet, so
should_run() reports "nothing declares kernels" in every build job -- so it was
exercised by hand on a clean tree:

```
rm -rf build && USE_CUDNN=1 USE_CUDA=1 USE_MSLK=1 MAX_JOBS=32 spin develop
```

Stage 2 exported all four declarations (54 objects + 4 generated sources, 4.0 MiB),
reconfigured, relinked, copied 324 MiB over the installed torch and passed its
embedded-kernel probe. On that build: test/python_native, one file per process, 331
passed; `test_ops.py -k "cuda and (topk or scatter_add or index_add)"` 115 passed;
test_sort_and_select 207; test_scatter_gather_ops 247; test_indexing 380.

Authored with an AI assistant (Claude Code).

ghstack-source-id: 0991d3b
Pull-Request: #194243
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread tools/native_aot/build_stage2.py Resolved
Comment thread tools/native_aot/build_stage2.py Resolved
Comment thread tools/native_aot/build_stage2.py Resolved
@slayton58 slayton58 added the topic: not user facing topic category label Sep 2, 2026
[ghstack-poisoned]

@albanD albanD 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.

Thanks for the fix.

Comment thread tools/native_aot/build_stage2.py Resolved
Comment thread tools/native_aot/build_stage2.py Resolved
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]

@albanD albanD 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.

Sounds ok

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #195877

1 similar comment
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #195877

pytorchmergebot pushed a commit that referenced this pull request Sep 4, 2026
Human Note:

Not to say this **can't** be supported at some point, but for now it isn't,
so just fail nice and loudly.

Claude:

scikit-build-core's editable.rebuild (also SKBUILD_EDITABLE_REBUILD, or
-C editable.rebuild=true) installs a meta-path finder that runs `cmake --build`
and `cmake --install` on the first `import torch`. Stage 2 cannot work under it:
every probe it makes imports torch in a subprocess, so each one triggers that
build and install -- overwriting the library stage 2 relinked and copied, and
leaving the final embedded-kernels check describing whatever the probe just
built rather than what this script verified.

Detected from sys.meta_path rather than from pyproject.toml or the environment.
The finder is what the torch on this path actually does, and it carries the flag
(rebuild_flag) however the setting arrived. Refused after the opt-out, like every
other refusal here, so TORCH_NATIVE_AOT=0 still exempts it, and after
--print-verdict, so the word the CI shells compare stays RUN or SKIP.

Authored with an AI assistant (Claude Code).

Test Plan:

```
pytest tools/test/test_native_aot_tools.py -k ImportTimeRebuild
```

Covers the flag being read from the installed finder, a finder without it being
left alone, and the opt-out still winning.
Pull Request resolved: #195877
Approved by: https://github.com/albanD
ghstack dependencies: #190896, #194238, #194239, #194240, #194241, #194242, #194243
pytorchmergebot pushed a commit that referenced this pull request Sep 4, 2026
… structured wrappers (#190897)

Human Notes:

Insert the dispatch logic into structure operator's codegen - conditionally call
AOT'd kernels post-META(), and fall back to regular `IMPL()` if nothing
matches.

Claude:

Generates one at::native DispatchStub per declaration
(NativeAotStubs.{h,cpp}) and a consultation between meta() and impl() in
the structured wrapper: if the stub has a registered kernel and it
returns true, op.impl is skipped. Declarations must resolve to exactly
one structured group (qualified names like "gt.Tensor" target one
overload; ambiguous base names are a codegen error).

Cost when no AOT library is loaded (every upstream wheel): the
consultation is a plain bool load (allowNativeAot, like Context's ~67
other user-facing toggles) plus a null-check on the stub pointer --
measured indistinguishable from noise (<0.1us) on covered ops' wrappers;
no behavior change, since an unregistered stub falls through to op.impl.

Adds the Context::allowNativeAot kill switch with
torch._C._set/_get_native_aot_enabled bindings. Default TRUE because the
switch alone is inert: kernels only run when the separately-built AOT
library is loaded, which is the actual opt-in; the switch exists so a
loaded library can be masked at runtime (python_native disabled(),
debugging, A/B).

A declaration may set UNCONDITIONAL = True to say its kernels ARE the
op's implementation rather than a faster route to the same answer. Those
gate on a second, private switch (Context::maskUnconditionalNativeAot)
instead, so the user-facing off switch cannot change what the op
computes. A gate still has to exist rather than being compiled out, or a
numerics test would have no way to obtain stock aten values for such an
op; the only caller is torch._native._unconditional_masked(). Declining
a shape still falls through to op.impl either way -- UNCONDITIONAL
constrains who may switch the path off, not which shapes the kernels
cover. No declaration in this stack sets it; the flag lands here so the
op families that need it (an op with no stock aten equivalent) do not
have to change the codegen later.

Generated output for a tree carrying four declarations -- this commit adds
none, and the stack's only declaration (topk) lands later. NativeAotStubs.h,
one stub per declared (op, key), signature-matched to the structured impl:

```cpp
namespace at::native {

using bmm_aot_fn = bool (*)(const at::Tensor & self, const at::Tensor & mat2, const at::Tensor & out);
DECLARE_DISPATCH(bmm_aot_fn, bmm_aot_stub)
using index_add_aot_fn = bool (*)(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, const at::Scalar & alpha, const at::Tensor & out);
DECLARE_DISPATCH(index_add_aot_fn, index_add_aot_stub)
using scatter_add_aot_fn = bool (*)(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, const at::Tensor & out);
DECLARE_DISPATCH(scatter_add_aot_fn, scatter_add_aot_stub)
using topk_aot_fn = bool (*)(const at::Tensor & self, int64_t k, int64_t dim, bool largest, bool sorted, const at::Tensor & values, const at::Tensor & indices);
DECLARE_DISPATCH(topk_aot_fn, topk_aot_stub)

} // namespace at::native
```

The consultation emitted into the structured wrapper (RegisterCUDA_0.cpp).
Outputs are already allocated and validated by meta(), so an AOT kernel
only fills them and returns true:

```cpp
// native-AOT: the last conjunct is the LAUNCH, not a query -- it runs the
// AOT kernel into the meta()-allocated outputs and returns true if it
// handled the call, false if it declined this shape. && short-circuits, so
// the stub is never called when AOT is switched off or the device is
// unsupported. op.impl below is the ordinary aten kernel, and it runs in
// exactly those three cases: switched off, unsupported device, or declined.
if (!(at::globalContext().allowNativeAot() && at::native::topk_aot_stub.is_device_supported(c10::DeviceType::CUDA) && at::native::topk_aot_stub(c10::DeviceType::CUDA, self, k, dim, largest, sorted, op.outputs_[0], op.outputs_[1]))) { op.impl(self, k, dim, largest, sorted, op.outputs_[0], op.outputs_[1]); }
```

It is emitted once per structured variant, so the functional/out split
shows up as op.outputs_[i] in one and op.maybe_get_output(i) in the
other.

An UNCONDITIONAL declaration gets the same site with the private gate,
and prose that matches it -- the shared comment's "switched off" case
does not exist for such an op, and a comment contradicting its own gate
is worse than none:

```cpp
// native-AOT: the last conjunct is the LAUNCH, not a query -- it runs the
// AOT kernel into the meta()-allocated outputs and returns true if it
// handled the call, false if it declined this shape. && short-circuits, so
// the stub is never called when the device is unsupported. op.impl
// below is the ordinary aten kernel.
// declared UNCONDITIONAL: these kernels are the implementation, so
// torch._native.set_aot_enabled(False) does NOT mask them -- only the
// private reference-computation hatch does. op.impl runs when that hatch
// is set, when the device is unsupported, or when the kernels decline
// this shape.
if (!(!at::globalContext().maskUnconditionalNativeAot() && at::native::topk_aot_stub.is_device_supported(c10::DeviceType::CUDA) && at::native::topk_aot_stub(c10::DeviceType::CUDA, self, k, dim, largest, sorted, op.outputs_[0], op.outputs_[1]))) { op.impl(self, k, dim, largest, sorted, op.outputs_[0], op.outputs_[1]); }
```

The consumer that registers on these stubs is generated by gen_aot_lib
(#194240). One kernel's definition, copied from
build/native_aot/topk/aot_topk_cuda.cpp -- 48 exported points, one launcher
each -- for an sm_100a export:

```cpp
void launch_topk_radix_bf16_n2048_k128_det__sm100a(const at::Tensor& mX, const at::Tensor& mValues, const at::Tensor& mIndices, c10::Stream stream) {
  c10::call_once(topk_radix_bf16_n2048_k128_det__sm100a_loaded, [] { topk_radix_bf16_n2048_k128_det__sm100a_Kernel_Module_Load(&topk_radix_bf16_n2048_k128_det__sm100a_module); });
  topk_radix_bf16_n2048_k128_det__sm100a_Tensor_mX_t mX_s;
  mX_s.data = const_cast<void*>(mX.const_data_ptr());
  mX_s.dynamic_shapes[0] = static_cast<int32_t>(mX.size(0));
  mX_s.dynamic_strides[0] = mX.stride(0);
  [... mValues_s and mIndices_s the same way, writable ...]
  int32_t rc = cute_dsl_topk_radix_bf16_n2048_k128_det__sm100a_wrapper(&topk_radix_bf16_n2048_k128_det__sm100a_module, &mX_s, &mValues_s, &mIndices_s,
                                         c10::cuda::CUDAStream(stream).stream());
  TORCH_CHECK(rc == 0, "topk_radix_bf16_n2048_k128_det__sm100a launch failed with code ", rc);
}
```

and the stub kernel those launchers hang off, which is what registers on the
DispatchStub above -- the arch gate, the declaration's prelude, then one cond
per precompile point:

```cpp
bool topk_cuda_aot_kernel(const at::Tensor & self, int64_t k, int64_t dim, bool largest, bool sorted, const at::Tensor & values, const at::Tensor & indices) {
  const auto* _naot_props = at::cuda::getCurrentDeviceProperties();
  if (!((_naot_props->major == 10 && _naot_props->minor == 0))) return false;
  [... int32 size gate, then cpp_dispatch_prelude() re-indented to this scope ...]
  if (_naot_props->major == 10 && _naot_props->minor == 0) {
    if (self.scalar_type() == at::kBFloat16 && N == 2048 && k == 128 && det) {
      auto self_2d = self.view({M, N});
      [... values_2d, indices_2d ...]
      launch_topk_radix_bf16_n2048_k128_det__sm100a(self_2d, values_2d, indices_2d, at::cuda::getCurrentCUDAStream());
      return true;
    }
    [... 47 more conds ...]
  }
  return false;
}

namespace at::native {
REGISTER_CUDA_DISPATCH(topk_aot_stub, &::topk_cuda_aot_kernel)
} // namespace at::native
```

Ops without a declaration are untouched, and a build with no AOT kernel
library links the stubs with nothing registered, so every call falls
through to op.impl.

Authored with an AI assistant (Claude Code).

Test Plan:

```
PYTHONPATH=$(pwd) pytest tools/test/test_native_aot.py
```
Pull Request resolved: #190897
Approved by: https://github.com/albanD
ghstack dependencies: #190896, #194238, #194239, #194240, #194241, #194242, #194243, #195877
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…d wiring (pytorch#194243)

Human note:

Finally putting everything together. Relink libtorch_cuda, correctly fixup the wheel, and
make sure everything (paths, manifests, etc.) are all aligned and correct.

Claude note:

The driver on top of the verdict, and the CI and dev flows that call it. With
this commit a standard CUDA build ships embedded AOT kernels.

A post-install step, because the kernel builders package-import torch and
scikit-build-core has no post-build hook inside the PEP 517 backend. It
reconfigures before a targeted relink of torch_cuda: the generated file registers
itself in CMAKE_CONFIGURE_DEPENDS only from the reconfigure that first READS it,
and the build.ninja on disk predates this generation -- without that the relink
silently omitted the kernels (417 MiB where 423 ships).

--wheel patches the relinked library and its RECORD entry back into the built
wheel, so test jobs get the kernels rather than a library replaced only on disk;
released wheels get the same before repair_wheel.py, so it goes through patchelf
like any other. It asserts that torch imports, because a kernel-free release wheel
must fail rather than skip -- and the ASan and TSan images cannot `import torch`
plainly, which is why the CI call is CUDA-guarded.

It assumes the torch it finds installed is the one this tree just built, and
VERIFIES that rather than repairing it: the reconfigure has to report embedding
before anything is relinked, the relinked library has to report its own kernels
before this exits, and a failure past that point says to reinstall. A run that
DECLINES overwrites a native_aot.cmake an earlier one left behind, because the
include is unconditional and the release matrix shares one build tree across eight
interpreters -- so the wheel for an interpreter with no DSL runtime was shipping
the previous interpreter's objects.

caffe2/CMakeLists.txt gets the one include line, EnvVarForwarding.cmake caches
TORCH_NATIVE_AOT so the opt-out survives a reconfigure, and CONTRIBUTING.md states
the skip reasons.

Test Plan:

```
pytest tools/test/test_native_aot_tools.py
```

Run at this commit's own tree, in a checkout with no built torch -- which is
what lint.yml's "Test tools" job has. This commit's tests cover patch_wheel's
RECORD and its ZIP64 metadata -- a copied member must not inherit the source's
stale offsets, which pip and unzip accept and `uv` refuses -- each of main()'s
refusals from the verdict down to a relink that produced no library, the argv and
env contract with both children including the one artifacts directory they share,
and the CI shells and CMake read as text.

PR CI cannot reach the relink at this commit -- no declaration exists yet, so
should_run() reports "nothing declares kernels" in every build job -- so it was
exercised by hand on a clean tree:

```
rm -rf build && USE_CUDNN=1 USE_CUDA=1 USE_MSLK=1 MAX_JOBS=32 spin develop
```

Stage 2 exported all four declarations (54 objects + 4 generated sources, 4.0 MiB),
reconfigured, relinked, copied 324 MiB over the installed torch and passed its
embedded-kernel probe. On that build: test/python_native, one file per process, 331
passed; `test_ops.py -k "cuda and (topk or scatter_add or index_add)"` 115 passed;
test_sort_and_select 207; test_scatter_gather_ops 247; test_indexing 380.

Authored with an AI assistant (Claude Code).
Pull Request resolved: pytorch#194243
Approved by: https://github.com/albanD
ghstack dependencies: pytorch#190896, pytorch#194238, pytorch#194239, pytorch#194240, pytorch#194241, pytorch#194242
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
)

Human Note:

Not to say this **can't** be supported at some point, but for now it isn't,
so just fail nice and loudly.

Claude:

scikit-build-core's editable.rebuild (also SKBUILD_EDITABLE_REBUILD, or
-C editable.rebuild=true) installs a meta-path finder that runs `cmake --build`
and `cmake --install` on the first `import torch`. Stage 2 cannot work under it:
every probe it makes imports torch in a subprocess, so each one triggers that
build and install -- overwriting the library stage 2 relinked and copied, and
leaving the final embedded-kernels check describing whatever the probe just
built rather than what this script verified.

Detected from sys.meta_path rather than from pyproject.toml or the environment.
The finder is what the torch on this path actually does, and it carries the flag
(rebuild_flag) however the setting arrived. Refused after the opt-out, like every
other refusal here, so TORCH_NATIVE_AOT=0 still exempts it, and after
--print-verdict, so the word the CI shells compare stays RUN or SKIP.

Authored with an AI assistant (Claude Code).

Test Plan:

```
pytest tools/test/test_native_aot_tools.py -k ImportTimeRebuild
```

Covers the flag being read from the installed finder, a finder without it being
left alone, and the opt-out still winning.
Pull Request resolved: pytorch#195877
Approved by: https://github.com/albanD
ghstack dependencies: pytorch#190896, pytorch#194238, pytorch#194239, pytorch#194240, pytorch#194241, pytorch#194242, pytorch#194243
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
… structured wrappers (pytorch#190897)

Human Notes:

Insert the dispatch logic into structure operator's codegen - conditionally call
AOT'd kernels post-META(), and fall back to regular `IMPL()` if nothing
matches.

Claude:

Generates one at::native DispatchStub per declaration
(NativeAotStubs.{h,cpp}) and a consultation between meta() and impl() in
the structured wrapper: if the stub has a registered kernel and it
returns true, op.impl is skipped. Declarations must resolve to exactly
one structured group (qualified names like "gt.Tensor" target one
overload; ambiguous base names are a codegen error).

Cost when no AOT library is loaded (every upstream wheel): the
consultation is a plain bool load (allowNativeAot, like Context's ~67
other user-facing toggles) plus a null-check on the stub pointer --
measured indistinguishable from noise (<0.1us) on covered ops' wrappers;
no behavior change, since an unregistered stub falls through to op.impl.

Adds the Context::allowNativeAot kill switch with
torch._C._set/_get_native_aot_enabled bindings. Default TRUE because the
switch alone is inert: kernels only run when the separately-built AOT
library is loaded, which is the actual opt-in; the switch exists so a
loaded library can be masked at runtime (python_native disabled(),
debugging, A/B).

A declaration may set UNCONDITIONAL = True to say its kernels ARE the
op's implementation rather than a faster route to the same answer. Those
gate on a second, private switch (Context::maskUnconditionalNativeAot)
instead, so the user-facing off switch cannot change what the op
computes. A gate still has to exist rather than being compiled out, or a
numerics test would have no way to obtain stock aten values for such an
op; the only caller is torch._native._unconditional_masked(). Declining
a shape still falls through to op.impl either way -- UNCONDITIONAL
constrains who may switch the path off, not which shapes the kernels
cover. No declaration in this stack sets it; the flag lands here so the
op families that need it (an op with no stock aten equivalent) do not
have to change the codegen later.

Generated output for a tree carrying four declarations -- this commit adds
none, and the stack's only declaration (topk) lands later. NativeAotStubs.h,
one stub per declared (op, key), signature-matched to the structured impl:

```cpp
namespace at::native {

using bmm_aot_fn = bool (*)(const at::Tensor & self, const at::Tensor & mat2, const at::Tensor & out);
DECLARE_DISPATCH(bmm_aot_fn, bmm_aot_stub)
using index_add_aot_fn = bool (*)(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, const at::Scalar & alpha, const at::Tensor & out);
DECLARE_DISPATCH(index_add_aot_fn, index_add_aot_stub)
using scatter_add_aot_fn = bool (*)(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, const at::Tensor & out);
DECLARE_DISPATCH(scatter_add_aot_fn, scatter_add_aot_stub)
using topk_aot_fn = bool (*)(const at::Tensor & self, int64_t k, int64_t dim, bool largest, bool sorted, const at::Tensor & values, const at::Tensor & indices);
DECLARE_DISPATCH(topk_aot_fn, topk_aot_stub)

} // namespace at::native
```

The consultation emitted into the structured wrapper (RegisterCUDA_0.cpp).
Outputs are already allocated and validated by meta(), so an AOT kernel
only fills them and returns true:

```cpp
// native-AOT: the last conjunct is the LAUNCH, not a query -- it runs the
// AOT kernel into the meta()-allocated outputs and returns true if it
// handled the call, false if it declined this shape. && short-circuits, so
// the stub is never called when AOT is switched off or the device is
// unsupported. op.impl below is the ordinary aten kernel, and it runs in
// exactly those three cases: switched off, unsupported device, or declined.
if (!(at::globalContext().allowNativeAot() && at::native::topk_aot_stub.is_device_supported(c10::DeviceType::CUDA) && at::native::topk_aot_stub(c10::DeviceType::CUDA, self, k, dim, largest, sorted, op.outputs_[0], op.outputs_[1]))) { op.impl(self, k, dim, largest, sorted, op.outputs_[0], op.outputs_[1]); }
```

It is emitted once per structured variant, so the functional/out split
shows up as op.outputs_[i] in one and op.maybe_get_output(i) in the
other.

An UNCONDITIONAL declaration gets the same site with the private gate,
and prose that matches it -- the shared comment's "switched off" case
does not exist for such an op, and a comment contradicting its own gate
is worse than none:

```cpp
// native-AOT: the last conjunct is the LAUNCH, not a query -- it runs the
// AOT kernel into the meta()-allocated outputs and returns true if it
// handled the call, false if it declined this shape. && short-circuits, so
// the stub is never called when the device is unsupported. op.impl
// below is the ordinary aten kernel.
// declared UNCONDITIONAL: these kernels are the implementation, so
// torch._native.set_aot_enabled(False) does NOT mask them -- only the
// private reference-computation hatch does. op.impl runs when that hatch
// is set, when the device is unsupported, or when the kernels decline
// this shape.
if (!(!at::globalContext().maskUnconditionalNativeAot() && at::native::topk_aot_stub.is_device_supported(c10::DeviceType::CUDA) && at::native::topk_aot_stub(c10::DeviceType::CUDA, self, k, dim, largest, sorted, op.outputs_[0], op.outputs_[1]))) { op.impl(self, k, dim, largest, sorted, op.outputs_[0], op.outputs_[1]); }
```

The consumer that registers on these stubs is generated by gen_aot_lib
(pytorch#194240). One kernel's definition, copied from
build/native_aot/topk/aot_topk_cuda.cpp -- 48 exported points, one launcher
each -- for an sm_100a export:

```cpp
void launch_topk_radix_bf16_n2048_k128_det__sm100a(const at::Tensor& mX, const at::Tensor& mValues, const at::Tensor& mIndices, c10::Stream stream) {
  c10::call_once(topk_radix_bf16_n2048_k128_det__sm100a_loaded, [] { topk_radix_bf16_n2048_k128_det__sm100a_Kernel_Module_Load(&topk_radix_bf16_n2048_k128_det__sm100a_module); });
  topk_radix_bf16_n2048_k128_det__sm100a_Tensor_mX_t mX_s;
  mX_s.data = const_cast<void*>(mX.const_data_ptr());
  mX_s.dynamic_shapes[0] = static_cast<int32_t>(mX.size(0));
  mX_s.dynamic_strides[0] = mX.stride(0);
  [... mValues_s and mIndices_s the same way, writable ...]
  int32_t rc = cute_dsl_topk_radix_bf16_n2048_k128_det__sm100a_wrapper(&topk_radix_bf16_n2048_k128_det__sm100a_module, &mX_s, &mValues_s, &mIndices_s,
                                         c10::cuda::CUDAStream(stream).stream());
  TORCH_CHECK(rc == 0, "topk_radix_bf16_n2048_k128_det__sm100a launch failed with code ", rc);
}
```

and the stub kernel those launchers hang off, which is what registers on the
DispatchStub above -- the arch gate, the declaration's prelude, then one cond
per precompile point:

```cpp
bool topk_cuda_aot_kernel(const at::Tensor & self, int64_t k, int64_t dim, bool largest, bool sorted, const at::Tensor & values, const at::Tensor & indices) {
  const auto* _naot_props = at::cuda::getCurrentDeviceProperties();
  if (!((_naot_props->major == 10 && _naot_props->minor == 0))) return false;
  [... int32 size gate, then cpp_dispatch_prelude() re-indented to this scope ...]
  if (_naot_props->major == 10 && _naot_props->minor == 0) {
    if (self.scalar_type() == at::kBFloat16 && N == 2048 && k == 128 && det) {
      auto self_2d = self.view({M, N});
      [... values_2d, indices_2d ...]
      launch_topk_radix_bf16_n2048_k128_det__sm100a(self_2d, values_2d, indices_2d, at::cuda::getCurrentCUDAStream());
      return true;
    }
    [... 47 more conds ...]
  }
  return false;
}

namespace at::native {
REGISTER_CUDA_DISPATCH(topk_aot_stub, &::topk_cuda_aot_kernel)
} // namespace at::native
```

Ops without a declaration are untouched, and a build with no AOT kernel
library links the stubs with nothing registered, so every call falls
through to op.impl.

Authored with an AI assistant (Claude Code).

Test Plan:

```
PYTHONPATH=$(pwd) pytest tools/test/test_native_aot.py
```
Pull Request resolved: pytorch#190897
Approved by: https://github.com/albanD
ghstack dependencies: pytorch#190896, pytorch#194238, pytorch#194239, pytorch#194240, pytorch#194241, pytorch#194242, pytorch#194243, pytorch#195877
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 8, 2026
Document the consolidated CD wheel build tree: the shared stage sequence
(set_desired_python -> build_env_setup -> build_install_deps -> build_wheel
-> repair_wheel, threaded via the --env-out hand-off, with the
Linux-CUDA-only native-AOT stage 2 from pytorch#194243 sitting between build and
repair), the per-platform orchestration and topology (Linux/macOS loop over
DESIRED_PYTHONS on one runner, Windows fans out via the CI matrix), the
shared _common.py helpers, and the dependencies that live outside
.ci/wheel/ -- the generated workflows + templates, the Windows workspace and
shared installers under .ci/pytorch/windows/, and the repo-root build
inputs.

Docs only. `lintrunner .ci/wheel/README.md` is clean; repair-tool and path
claims cross-checked against the scripts.

Authored with assistance from Claude Code.
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 8, 2026
The directory move in "Move Linux CD wheel scripts to .ci/wheel/linux/"
updated every literal `.ci/manywheel` reference, but two callers reach the
Linux build scripts through a *dynamic* path that a string grep never
matched:

- `.github/workflows/_binary-build-linux.yml` runs
  `bash .ci/${{ inputs.PACKAGE_TYPE }}/build.sh` -- with `PACKAGE_TYPE`
  `manywheel`, that resolved to the moved directory, so every Linux
  manywheel binary build (cpu, cuda, rocm, xpu, s390x) failed at
  `docker exec` with `.ci/manywheel/build.sh: No such file or directory`.
- `.ci/libtorch/build.sh` shims to `${SCRIPTPATH}/../manywheel/build.sh`,
  breaking libtorch builds the same way.

`PACKAGE_TYPE` is a semantic label (`manywheel` / `libtorch`), not a
directory, so it is left as-is; instead the reusable workflow remaps the one
type whose scripts moved via a render-time expression
(`manywheel -> wheel/linux`, everything else unchanged), and the libtorch
shim is repointed. The `.ci/${PACKAGE_TYPE}/build.sh` convention otherwise
stands.

Surfaced by a `ciflow/binaries_wheel` run on pytorch#189275; the string-only
reference sweep in the move commit was the gap.

Rebasing onto viable/strict brought a third kind of reference the sweep
could not have seen. pytorch#194243 (native-AOT stage 2) landed tests in
tools/test/test_native_aot_tools.py that open `.ci/manywheel/build.sh` by
literal path, and comments in tools/native_aot/build_stage2.py and
.ci/pytorch/build.sh citing the old paths. The tests would raise
FileNotFoundError after the move; all are repointed here. While there,
torch/cuda/__init__.py's arch-table comment cited
`.ci/manywheel/build_cuda.sh`, a file the Python port had already removed;
it now names the build_env_setup.py the matrix validator actually reads.

```
grep -c "PACKAGE_TYPE == 'manywheel' && 'wheel/linux'" .github/workflows/_binary-build-linux.yml  # 2
grep -c '.ci/${{ inputs.PACKAGE_TYPE }}/build.sh' .github/workflows/_binary-build-linux.yml         # 0
python -c "import yaml; yaml.safe_load(open('.github/workflows/_binary-build-linux.yml'))"
python -m pytest tools/test/test_native_aot_tools.py -k TestCiAndCMakeWiring -q   # 7 passed, 15 subtests
git grep -n -E '\.ci/manywheel/' -- . ':!agent_space'                             # empty
lintrunner .github/workflows/_binary-build-linux.yml .ci/libtorch/build.sh \
    tools/test/test_native_aot_tools.py tools/native_aot/build_stage2.py torch/cuda/__init__.py
```
Re-validated by re-running `ciflow/binaries_wheel` on the PR.

Authored with assistance from Claude Code.
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 11, 2026
Document the consolidated CD wheel build tree: the shared stage sequence
(set_desired_python -> build_env_setup -> build_install_deps -> build_wheel
-> repair_wheel, threaded via the --env-out hand-off, with the
Linux-CUDA-only native-AOT stage 2 from pytorch#194243 sitting between build and
repair), the per-platform orchestration and topology (Linux/macOS loop over
DESIRED_PYTHONS on one runner, Windows fans out via the CI matrix), the
shared _common.py helpers, and the dependencies that live outside
.ci/wheel/ -- the generated workflows + templates, the Windows workspace and
shared installers under .ci/pytorch/windows/, and the repo-root build
inputs.

Docs only. `lintrunner .ci/wheel/README.md` is clean; repair-tool and path
claims cross-checked against the scripts.

Authored with assistance from Claude Code.
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 11, 2026
The directory move in "Move Linux CD wheel scripts to .ci/wheel/linux/"
updated every literal `.ci/manywheel` reference, but two callers reach the
Linux build scripts through a *dynamic* path that a string grep never
matched:

- `.github/workflows/_binary-build-linux.yml` runs
  `bash .ci/${{ inputs.PACKAGE_TYPE }}/build.sh` -- with `PACKAGE_TYPE`
  `manywheel`, that resolved to the moved directory, so every Linux
  manywheel binary build (cpu, cuda, rocm, xpu, s390x) failed at
  `docker exec` with `.ci/manywheel/build.sh: No such file or directory`.
- `.ci/libtorch/build.sh` shims to `${SCRIPTPATH}/../manywheel/build.sh`,
  breaking libtorch builds the same way.

`PACKAGE_TYPE` is a semantic label (`manywheel` / `libtorch`), not a
directory, so it is left as-is; instead the reusable workflow remaps the one
type whose scripts moved via a render-time expression
(`manywheel -> wheel/linux`, everything else unchanged), and the libtorch
shim is repointed. The `.ci/${PACKAGE_TYPE}/build.sh` convention otherwise
stands.

Surfaced by a `ciflow/binaries_wheel` run on pytorch#189275; the string-only
reference sweep in the move commit was the gap.

Rebasing onto viable/strict brought a third kind of reference the sweep
could not have seen. pytorch#194243 (native-AOT stage 2) landed tests in
tools/test/test_native_aot_tools.py that open `.ci/manywheel/build.sh` by
literal path, and comments in tools/native_aot/build_stage2.py and
.ci/pytorch/build.sh citing the old paths. The tests would raise
FileNotFoundError after the move; all are repointed here. While there,
torch/cuda/__init__.py's arch-table comment cited
`.ci/manywheel/build_cuda.sh`, a file the Python port had already removed;
it now names the build_env_setup.py the matrix validator actually reads.

```
grep -c "PACKAGE_TYPE == 'manywheel' && 'wheel/linux'" .github/workflows/_binary-build-linux.yml  # 2
grep -c '.ci/${{ inputs.PACKAGE_TYPE }}/build.sh' .github/workflows/_binary-build-linux.yml         # 0
python -c "import yaml; yaml.safe_load(open('.github/workflows/_binary-build-linux.yml'))"
python -m pytest tools/test/test_native_aot_tools.py -k TestCiAndCMakeWiring -q   # 7 passed, 15 subtests
git grep -n -E '\.ci/manywheel/' -- . ':!agent_space'                             # empty
lintrunner .github/workflows/_binary-build-linux.yml .ci/libtorch/build.sh \
    tools/test/test_native_aot_tools.py tools/native_aot/build_stage2.py torch/cuda/__init__.py
```
Re-validated by re-running `ciflow/binaries_wheel` on the PR.

Authored with assistance from Claude Code.
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 16, 2026
Document the consolidated CD wheel build tree: the shared stage sequence
(set_desired_python -> build_env_setup -> build_install_deps -> build_wheel
-> repair_wheel, threaded via the --env-out hand-off, with the
Linux-CUDA-only native-AOT stage 2 from pytorch#194243 sitting between build and
repair), the per-platform orchestration and topology (Linux/macOS loop over
DESIRED_PYTHONS on one runner, Windows fans out via the CI matrix), the
shared _common.py helpers, and the dependencies that live outside
.ci/wheel/ -- the generated workflows + templates, the Windows workspace and
shared installers under .ci/pytorch/windows/, and the repo-root build
inputs.

Docs only. `lintrunner .ci/wheel/README.md` is clean; repair-tool and path
claims cross-checked against the scripts.

Authored with assistance from Claude Code.
zklaus added a commit to zklaus/pytorch that referenced this pull request Sep 16, 2026
The directory move in "Move Linux CD wheel scripts to .ci/wheel/linux/"
updated every literal `.ci/manywheel` reference, but two callers reach the
Linux build scripts through a *dynamic* path that a string grep never
matched:

- `.github/workflows/_binary-build-linux.yml` runs
  `bash .ci/${{ inputs.PACKAGE_TYPE }}/build.sh` -- with `PACKAGE_TYPE`
  `manywheel`, that resolved to the moved directory, so every Linux
  manywheel binary build (cpu, cuda, rocm, xpu, s390x) failed at
  `docker exec` with `.ci/manywheel/build.sh: No such file or directory`.
- `.ci/libtorch/build.sh` shims to `${SCRIPTPATH}/../manywheel/build.sh`,
  breaking libtorch builds the same way.

`PACKAGE_TYPE` is a semantic label (`manywheel` / `libtorch`), not a
directory, so it is left as-is; instead the reusable workflow remaps the one
type whose scripts moved via a render-time expression
(`manywheel -> wheel/linux`, everything else unchanged), and the libtorch
shim is repointed. The `.ci/${PACKAGE_TYPE}/build.sh` convention otherwise
stands.

Surfaced by a `ciflow/binaries_wheel` run on pytorch#189275; the string-only
reference sweep in the move commit was the gap.

Rebasing onto viable/strict brought a third kind of reference the sweep
could not have seen. pytorch#194243 (native-AOT stage 2) landed tests in
tools/test/test_native_aot_tools.py that open `.ci/manywheel/build.sh` by
literal path, and comments in tools/native_aot/build_stage2.py and
.ci/pytorch/build.sh citing the old paths. The tests would raise
FileNotFoundError after the move; all are repointed here. While there,
torch/cuda/__init__.py's arch-table comment cited
`.ci/manywheel/build_cuda.sh`, a file the Python port had already removed;
it now names the build_env_setup.py the matrix validator actually reads.

```
grep -c "PACKAGE_TYPE == 'manywheel' && 'wheel/linux'" .github/workflows/_binary-build-linux.yml  # 2
grep -c '.ci/${{ inputs.PACKAGE_TYPE }}/build.sh' .github/workflows/_binary-build-linux.yml         # 0
python -c "import yaml; yaml.safe_load(open('.github/workflows/_binary-build-linux.yml'))"
python -m pytest tools/test/test_native_aot_tools.py -k TestCiAndCMakeWiring -q   # 7 passed, 15 subtests
git grep -n -E '\.ci/manywheel/' -- . ':!agent_space'                             # empty
lintrunner .github/workflows/_binary-build-linux.yml .ci/libtorch/build.sh \
    tools/test/test_native_aot_tools.py tools/native_aot/build_stage2.py torch/cuda/__init__.py
```
Re-validated by re-running `ciflow/binaries_wheel` on the PR.

Authored with assistance from Claude Code.
pytorchmergebot pushed a commit to zklaus/pytorch that referenced this pull request Sep 16, 2026
Document the consolidated CD wheel build tree: the shared stage sequence
(set_desired_python -> build_env_setup -> build_install_deps -> build_wheel
-> repair_wheel, threaded via the --env-out hand-off, with the
Linux-CUDA-only native-AOT stage 2 from pytorch#194243 sitting between build and
repair), the per-platform orchestration and topology (Linux/macOS loop over
DESIRED_PYTHONS on one runner, Windows fans out via the CI matrix), the
shared _common.py helpers, and the dependencies that live outside
.ci/wheel/ -- the generated workflows + templates, the Windows workspace and
shared installers under .ci/pytorch/windows/, and the repo-root build
inputs.

Docs only. `lintrunner .ci/wheel/README.md` is clean; repair-tool and path
claims cross-checked against the scripts.

Authored with assistance from Claude Code.
pytorchmergebot pushed a commit to zklaus/pytorch that referenced this pull request Sep 16, 2026
The directory move in "Move Linux CD wheel scripts to .ci/wheel/linux/"
updated every literal `.ci/manywheel` reference, but two callers reach the
Linux build scripts through a *dynamic* path that a string grep never
matched:

- `.github/workflows/_binary-build-linux.yml` runs
  `bash .ci/${{ inputs.PACKAGE_TYPE }}/build.sh` -- with `PACKAGE_TYPE`
  `manywheel`, that resolved to the moved directory, so every Linux
  manywheel binary build (cpu, cuda, rocm, xpu, s390x) failed at
  `docker exec` with `.ci/manywheel/build.sh: No such file or directory`.
- `.ci/libtorch/build.sh` shims to `${SCRIPTPATH}/../manywheel/build.sh`,
  breaking libtorch builds the same way.

`PACKAGE_TYPE` is a semantic label (`manywheel` / `libtorch`), not a
directory, so it is left as-is; instead the reusable workflow remaps the one
type whose scripts moved via a render-time expression
(`manywheel -> wheel/linux`, everything else unchanged), and the libtorch
shim is repointed. The `.ci/${PACKAGE_TYPE}/build.sh` convention otherwise
stands.

Surfaced by a `ciflow/binaries_wheel` run on pytorch#189275; the string-only
reference sweep in the move commit was the gap.

Rebasing onto viable/strict brought a third kind of reference the sweep
could not have seen. pytorch#194243 (native-AOT stage 2) landed tests in
tools/test/test_native_aot_tools.py that open `.ci/manywheel/build.sh` by
literal path, and comments in tools/native_aot/build_stage2.py and
.ci/pytorch/build.sh citing the old paths. The tests would raise
FileNotFoundError after the move; all are repointed here. While there,
torch/cuda/__init__.py's arch-table comment cited
`.ci/manywheel/build_cuda.sh`, a file the Python port had already removed;
it now names the build_env_setup.py the matrix validator actually reads.

```
grep -c "PACKAGE_TYPE == 'manywheel' && 'wheel/linux'" .github/workflows/_binary-build-linux.yml  # 2
grep -c '.ci/${{ inputs.PACKAGE_TYPE }}/build.sh' .github/workflows/_binary-build-linux.yml         # 0
python -c "import yaml; yaml.safe_load(open('.github/workflows/_binary-build-linux.yml'))"
python -m pytest tools/test/test_native_aot_tools.py -k TestCiAndCMakeWiring -q   # 7 passed, 15 subtests
git grep -n -E '\.ci/manywheel/' -- . ':!agent_space'                             # empty
lintrunner .github/workflows/_binary-build-linux.yml .ci/libtorch/build.sh \
    tools/test/test_native_aot_tools.py tools/native_aot/build_stage2.py torch/cuda/__init__.py
```
Re-validated by re-running `ciflow/binaries_wheel` on the PR.

Authored with assistance from Claude Code.
pytorchmergebot pushed a commit that referenced this pull request Sep 16, 2026
…umpy pin (#189275)

## Summary

The three CD wheel-build pipelines (Linux, Windows, macOS) grew as three
independent Python ports and drifted apart: copy-pasted helpers, three
different `numpy` build-pin tables, and different directory homes. This PR
consolidates them under a common `.ci/wheel/` root with a single shared
`_common.py`, and reconciles the numpy pin -- fixing a latent bug where
Linux's greedy `cp31` prefix silently overrode its own numpy default.

A new `.ci/wheel/README.md` documents the resulting layout, the shared stage
sequence (including the Linux-CUDA-only native-AOT stage 2 that #194243
added to the Linux orchestrator), and the dependencies that live outside the
tree.

## Review order

The commits are a deliberate progression -- three mechanical moves first,
then the semantic change, then cleanup:

1. **Move macOS** `.ci/macwheel/` -> `.ci/wheel/mac/` (pure rename + regen).
2. **Move Linux** `.ci/manywheel/` -> `.ci/wheel/linux/` (pure rename + regen).
3. **Move Windows** pipeline -> `.ci/wheel/windows/`. Unlike Linux/macOS,
   `.ci/pytorch/windows/` is a *mixed* dir: only the 5 CD pipeline files
   move; the shared `internal/*.bat` installers and `arm64/` scripts stay
   (non-CD Windows CI uses them). `WIN_CI_DIR` is re-anchored to
   `.ci/pytorch/windows/` so the runtime workspace is byte-for-byte
   unchanged -- only the source files move.
4. **Share `_common.py` + unify numpy** -- the heart of the PR.
5. **Dedup** the `build_env_setup.py` env helpers into `_common.py`.
6. **Add the README.**
7. **Fix the dynamic Linux paths** the string sweep in commit 2 could not
   see (`.ci/${PACKAGE_TYPE}/build.sh`, the libtorch shim) plus, after the
   rebase onto #194243, the native-AOT tests and comments that open
   `.ci/manywheel/build.sh` by literal path.
8. **Fix depth-sensitive paths** inside the moved Linux scripts.
9. **Stop using `PACKAGE_TYPE` as a directory**; drop the dead libtorch shim.
10. **Fall back to an image-provisioned numpy** for a Python with no pin.

## numpy pin reconciliation

The three tables disagreed for almost every Python. Replaced with one
explicit dict + fail-loud (the design macOS already used):

| Python | pin |
|--------|-----|
| 3.10 / 3.11 / 3.12 | `2.0.2` |
| 3.13 | `2.1.2` |
| 3.14 | `2.3.4` |
| 3.15 | `2.5.2` |

Each entry is the oldest numpy *minor* that ships a wheel for that
interpreter, at the newest *patch* of that minor already shipped in
production by one of the platforms, so no numpy bugfix is dropped. Every
Python currently in the CD matrix has an entry; free-threaded builds share
their base version's pin, and numpy publishes `cp31Xt` wheels for every
entry above.

**Build-time pin changes, per platform** (all verified to have a real wheel
on PyPI for every interpreter/platform in the matrix):

| Python | Linux | macOS | Windows |
|---|---|---|---|
| 3.10 / 3.11 / 3.12 | `2.1.0` -> `2.0.2` | -- | -- |
| 3.13 | `2.1.0` -> `2.1.2` | `2.1.0` -> `2.1.2` | -- |
| 3.14 / 3.14t | -- | -- | `2.3.2` -> `2.3.4` |
| 3.15 / 3.15t | -- | -- | -- |

Two of these deserve a reviewer's attention:

- **Linux 3.10-3.12 (`2.1.0` -> `2.0.2`)** undoes the greedy-prefix accident
  and converges Linux onto what Windows and macOS already used. Note this is
  *not* an ABI-floor change: torch never defines `NPY_TARGET_VERSION`, so the
  shipped wheel's runtime numpy requirement is identical across 2.0.x-2.5.x.
- **3.15 / 3.15t** was the one row a single table could not reconcile:
  Windows pinned 2.5.2 (#194618) while Linux and macOS pinned 2.5.1, which
  has no `cp315` wheel and built numpy from source. Upstream has since moved
  Linux (#194741) and macOS (#194734) to 2.5.2 as well, so the unified table
  takes 2.5.2 and this PR changes no 3.15 pin. A side effect of that upstream
  move is that the ROCm cp315 pkg-config workaround (`is_rocm_py315` /
  `prefer_target_python_pkgconfig`, #189722) is now inert; it is deliberately
  left in place here rather than removed in a PR that did not stop
  exercising it.

**s390x keeps its own table, now synced.** `cpu-s390x` is the one Linux arch
that does not run the Python pipeline -- `build.sh` routes it to
`build_cpu.sh` -> `build_common.sh`, which pins numpy in shell. That table
had drifted (`cp31*` -> `2.1.0`, so 3.10-3.13 all got `2.1.0`) and upstream's
"keep in sync" reminder was attached to the table this PR deletes. It is now
updated to match `NUMPY_PINS` entry-for-entry, with a cross-reference in both
files. Absorbing s390x into the Python pipeline proper is a sensible
follow-up -- the image already ships `/opt/python/cpXXX` and
`build_common.sh` already builds via `python -m build` -- but it is a
behavioural port of an arch that only a nightly can validate, so it is
deliberately not bundled here.

Linux's incidental `--pre` is dropped: `install_numpy()` always emits an
exact `numpy==X` pin, and pip's prerelease filtering never narrows an exact
specifier -- including one naming a prerelease, since packaging enables
prereleases automatically when the specifier itself references one.

`install_numpy()` takes passthrough pip args so Windows (#194618) and macOS
(#194734) keep `--no-build-isolation` on the numpy install. cp315 has no
`pyyaml` wheel, so `PIP_PACKAGES` genuinely builds an sdist there and needs
the preinstalled `cython<3.3.0` to reach it (`PIP_CONSTRAINT` cannot -- pip
does not apply it to isolated build environments, which is why #194618
disables isolation instead). numpy resolves to a wheel at the current pin,
which makes those flags inert for that install rather than unnecessary; they
are passed anyway so a future pin without a cp315 wheel stays guarded.

The unpinned-Python fallback checks a snapshot taken when `_common.py` is
imported, not a probe at call time. It has to: on Linux and macOS the stage
installs `requirements-build.txt` -- which lists a bare `numpy` -- before
calling `install_numpy()`, so a call-time probe would always find one and the
fail-loud branch could never fire.

## Note on verification

`ciflow/binaries_wheel` exercises the build half of these pipelines, and is
running on this PR. What it does *not* cover is the nightly-only tail:
upload, the libtorch-extract job, and the s390x path. Those parts are
verified by import/path-math simulation, the numpy table checked against PyPI
wheel availability, and lint.

`install_numpy()`'s fallback is covered by a unit-style check of all three
branches (pinned / unpinned-with-image-numpy / unpinned-without), including
the case that proves the fail-loud branch is reachable -- see the test plan
in the final commit's message.

The two spots most worth a careful eye in review are the Windows
`WIN_CI_DIR` re-anchoring (commit 3) and Linux/macOS adopting the shared
(Windows-superset) `write_env_exports` (commit 5); both are argued to be
behavior-preserving in their commit messages.

Deferred (not a blocker, entangled with the scikit-build-core migration):
switching Linux's `setup.py clean` to `spin clean`, which also needs a
dependency reorder.

## Test plan

```
# helpers resolve from one source; numpy table is the evidence-based one
python - <<'PY'
import importlib.util as u
m=u.module_from_spec(s:=u.spec_from_file_location("_common",".ci/wheel/_common.py")); s.loader.exec_module(m)
assert m.NUMPY_PINS=={"3.10":"2.0.2","3.11":"2.0.2","3.12":"2.0.2","3.13":"2.1.2","3.14":"2.3.4","3.15":"2.5.2"}
assert all(hasattr(m,h) for h in ["retry","pip_install","install_numpy","download","write_env_exports","shell_quote"])
PY
# no stray refs to the old dirs; generated workflows reproduce with no diff
grep -rn -- .ci/macwheel .ci/manywheel .github .ci   # (empty)
python .github/scripts/generate_ci_workflows.py       # no-op
spin lint .ci/wheel/_common.py .ci/wheel/*/build_install_deps.py .ci/wheel/*/build_env_setup.py .ci/wheel/README.md
```

This PR was authored with the assistance of Claude Code.

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

Pull Request resolved: #189275
Approved by: https://github.com/atalman
@github-actions
github-actions Bot deleted the gh/slayton58/151/head branch November 14, 2026 01:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 ciflow/binaries Trigger all binary build and upload jobs on the PR ciflow/inductor Merged topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants