Repository navigation
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194242
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 2e3c7ee with merge base 67aade5 ( 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]
Human note: Determine which builds should actually make AOT objects, and that they are setup to do so (runtimes etc.). Needs to handle a lot of variables here - explicit opt-outs, cuda versions, python versions, runtime DSL versions, etc. Claude note: Only the verdict: should_run() and the probes it is built from. No CLI and nothing that runs a step, so this commit is the list of reasons a build declines to ship AOT kernels, each one a test. should_run declines for nine reasons and reports every one, because a silent skip is a wheel that quietly underperforms. The CUDA 13 floor is a cost decision rather than a capability one: 12.x builds top out at sm_90 and every 13.x config builds sm_90 too, so a 12.x export is a strict subset of what the 13.x wheels ship -- and the CI shells install the ~180 MB of DSL wheels only when the verdict says RUN. The verdict cannot demand what it is being asked about. require_runtimes is separate and runs only once stage 2 is committed; when should_run raised for a missing runtime, stdout was empty, the shell skipped the install, and the real run then failed on the runtimes it was meant to request. Everything torch-related is answered out of process and outside the repo root: `python -c` puts the cwd on sys.path, so from the root every probe answered about the SOURCE torch/ tree instead of the installed wheel. Diagnostics go to stderr, which is what lets the next commit put a machine-read word on stdout. 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 each of the nine reasons should_run() declines and the text it reports for each, a probe that cannot be spawned at all degrading to a skip rather than a traceback, the probe diagnostics, the opt-out read exactly as CMake reads it (the environment, else the cache), and the dialect-runtime archive matched to this build's CUDA major. Authored with an AI assistant (Claude Code). ghstack-source-id: cc080b4 Pull-Request: #194242
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
| * After: stage 2 exports and embeds, runtimes required to progress, failures | ||
| fail the build. | ||
|
|
||
| TORCH_NATIVE_AOT=0 opts out at any point. |
There was a problem hiding this comment.
What does this mean? Don't we mostly expect this flag to be kept constant during the build phases?
There was a problem hiding this comment.
Yes, we expect it to constant across all phases of the build - but it is checked at every entry-point (verdict-probe, stage-2 run and created cmake).
There is a theoretical error point here from changing TORCH_NATIVE_AOT from 1 to 0 partway through the build, but this should only ever be possible to expose through a manual cmake call -- spin {develop,install} or pip install -e would configure unconditionally and re-generate the cmake files correctly. Because this relies on behaviour that's outside of usual usage (cmake --build build directly) I haven't closed that gap.
| * TORCH_CUDA_ARCH_LIST names no exportable arch (export.EXPORTABLE_ARCHES); | ||
| with it unset, on-device export runs if a supported GPU is present | ||
|
|
||
| Two different processes, gated by skip list. |
There was a problem hiding this comment.
Overloaded term :D not OS processes, but using "modes" instead of "processes" anyway.
|
|
||
| Two different processes, gated by skip list. | ||
|
|
||
| * Before: No stage-2, normal wheel without AOT artifacts |
There was a problem hiding this comment.
But aren't these primed to receive the registration from AOT?
There was a problem hiding this comment.
They are - the hooks will be compiled in, but if the artefacts for the kernels aren't present in the final library, we'll fall through into the regular ATen .impl(...)
[ghstack-poisoned]
albanD
left a comment
There was a problem hiding this comment.
Ok ok
I think there is more wordsmithing we might want to do, but maybe that can wait for the top of the stack
|
Starting merge as part of PR stack under #195877 |
1 similar comment
|
Starting merge as part of PR stack under #195877 |
…d wiring (#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: #194243 Approved by: https://github.com/albanD ghstack dependencies: #190896, #194238, #194239, #194240, #194241, #194242
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
… 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
Human note: Determine which builds should actually make AOT objects, and that they are setup to do so (runtimes etc.). Needs to handle a lot of variables here - explicit opt-outs, cuda versions, python versions, runtime DSL versions, etc. Claude note: Only the verdict: should_run() and the probes it is built from. No CLI and nothing that runs a step, so this commit is the list of reasons a build declines to ship AOT kernels, each one a test. should_run declines for nine reasons and reports every one, because a silent skip is a wheel that quietly underperforms. The CUDA 13 floor is a cost decision rather than a capability one: 12.x builds top out at sm_90 and every 13.x config builds sm_90 too, so a 12.x export is a strict subset of what the 13.x wheels ship -- and the CI shells install the ~180 MB of DSL wheels only when the verdict says RUN. The verdict cannot demand what it is being asked about. require_runtimes is separate and runs only once stage 2 is committed; when should_run raised for a missing runtime, stdout was empty, the shell skipped the install, and the real run then failed on the runtimes it was meant to request. Everything torch-related is answered out of process and outside the repo root: `python -c` puts the cwd on sys.path, so from the root every probe answered about the SOURCE torch/ tree instead of the installed wheel. Diagnostics go to stderr, which is what lets the next commit put a machine-read word on stdout. 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 each of the nine reasons should_run() declines and the text it reports for each, a probe that cannot be spawned at all degrading to a skip rather than a traceback, the probe diagnostics, the opt-out read exactly as CMake reads it (the environment, else the cache), and the dialect-runtime archive matched to this build's CUDA major. Authored with an AI assistant (Claude Code). Pull Request resolved: pytorch#194242 Approved by: https://github.com/albanD ghstack dependencies: pytorch#190896, pytorch#194238, pytorch#194239, pytorch#194240, pytorch#194241
…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
) 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
… 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
Stack from ghstack (oldest at bottom):
Human note:
Determine which builds should actually make AOT objects, and that they are setup to
do so (runtimes etc.). Needs to handle a lot of variables here - explicit opt-outs,
cuda versions, python versions, runtime DSL versions, etc.
Claude note:
Only the verdict: should_run() and the probes it is built from. No CLI and
nothing that runs a step, so this commit is the list of reasons a build declines to
ship AOT kernels, each one a test.
should_run declines for nine reasons and reports every one, because a silent skip
is a wheel that quietly underperforms. The CUDA 13 floor is a cost decision rather
than a capability one: 12.x builds top out at sm_90 and every 13.x config builds
sm_90 too, so a 12.x export is a strict subset of what the 13.x wheels ship -- and
the CI shells install the ~180 MB of DSL wheels only when the verdict says RUN.
The verdict cannot demand what it is being asked about. require_runtimes is
separate and runs only once stage 2 is committed; when should_run raised for a
missing runtime, stdout was empty, the shell skipped the install, and the real run
then failed on the runtimes it was meant to request.
Everything torch-related is answered out of process and outside the repo root:
python -cputs the cwd on sys.path, so from the root every probe answered aboutthe SOURCE torch/ tree instead of the installed wheel. Diagnostics go to stderr,
which is what lets the next commit put a machine-read word on stdout.
Test Plan:
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 each of the
nine reasons should_run() declines and the text it reports for each, a probe that
cannot be spawned at all degrading to a skip rather than a traceback, the probe
diagnostics, the opt-out read exactly as CMake reads it (the environment, else
the cache), and the dialect-runtime archive matched to this build's CUDA major.
Authored with an AI assistant (Claude Code).