Repository navigation
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/190897
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (2 Unrelated Failures)As of commit 4fdbc22 with merge base 78fa18d ( CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
… structured wrappers
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 relaxed atomic load (allowNativeAot) 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).
Authored with an AI assistant (Claude Code).
Test Plan:
```
python tools/test/test_native_aot.py
```
ghstack-source-id: ecfdb2c
Pull-Request: #190897
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
MatthiasKohl
left a comment
There was a problem hiding this comment.
LGTM, just a question about torchgen
[ghstack-poisoned]
[ghstack-poisoned]
… 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
…, embedded detection, disabled() masking
Human Notes:
Optimization of "is-this-covered-by-AOT" check by allowing a C++
implementation to be defined.
Allow control of AOT'd kernels at runtime where appropriate:
* If this is a sparsely-populated optimization (i.e. AOT covers
a few specific cases, and expects to fall back otherwise, allow opt-out
* If this is intended to have 100% coverage and be the only valid
implementation, do **not** allow opt-out
Claude:
torch/_native/aot_manifest.py loads declarations into coverage
objects; the eager router checks coverage once per call ahead of its
cond chain, so covered calls decline the JIT route and fall through
to the aten wrapper's stub. When the AOT library ships a cpp_covers
predicate (torch.ops._native_aot.covers_<id>), coverage prefers it
over the Python matching.
AOT kernels are always linked into libtorch_cuda (no separate
library): _native_aot_embedded() detects them in-process via the
_native_aot covers-op namespace. Two distinct off states, deliberately
different:
* Artifacts ABSENT (stage 2 never ran): coverage still declines
covered calls, the stub has no kernel, and they land on STOCK aten.
Artifact presence is static per process and coverage is a
declaration-time statement ("these points ship AOT"), not a runtime
probe; checking per call would tax every covered call for a
transient packaging condition. The correctness contract holds
(stock aten serves), only the acceleration source changes; tested
explicitly (test_covered_call_correct_without_aot_lib).
* Context switch OFF (set_aot_enabled(False), also flipped by
TORCH_DISABLE_NATIVE_AOT=1 and masked by
python_native.<dsl>.disabled()): coverage itself returns False, so
covered calls KEEP their JIT route rather than declining into a
stub that will not fire -- masking must not silently lose both
accelerated routes (test_masked_switch_restores_jit_coverage).
Inside disabled() the JIT layer is off too, so those blocks still
see stock aten end to end.
Unconditional overrides sit outside both of those, on both routes. An
override whose declaration says its kernels ARE the op's implementation
is exempt from every user-facing filter (registry.check_enabled) -- the
same rule the generated C++ gate follows in #190897 -- so
set_aot_enabled(False) and disabled() cannot change what such an op
computes. The one thing that reaches them is the private
_set_mask_unconditional() behind torch._native._unconditional_masked(),
which exists so a numerics test can still obtain stock aten values: a
reference silently computed through the override under test is worse
than no reference. It rebuilds every router rather than only setting the
flag, because check_enabled runs while a graph is being registered, not
per call -- so flipping the flag alone would leave the already-installed
routers in place and the mask would appear to do nothing.
Authored with an AI assistant (Claude Code).
Test Plan:
```
python test/python_native/test_aot_manifest.py
python test/python_native/test_registry.py
```
ghstack-source-id: 32881b4
Pull-Request: #190898
|
@pytorchbot revert -m "breaks internal build" |
|
❌ 🤖 pytorchbot command failed: Try |
|
@pytorchbot revert -m "breaks internal build" -c ghfirst |
|
@pytorchbot successfully started a revert job. Check the current status here. |
|
@slayton58 your PR has been successfully reverted. |
…Stubs in structured wrappers (#190897)" This reverts commit 818c104. Reverted #190897 on behalf of https://github.com/slayton58 due to breaks internal build ([comment](#190897 (comment)))
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
… structured wrappers (pytorch#190897) Human Notes: Fix an internal build issue due to `NativeAotStubs.h` being unconditionally included, but not actually generated in the build. Guard against that. 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. Re-land. This landed once and was backed out in dfe5500 because it broke an internal build: the generated CUDA registration TU included <ATen/NativeAotStubs.h> unconditionally, and that build does not generate the header. Fixed here rather than in a follow-up, so the re-land cannot reproduce what it was reverted for: gen_registration_headers takes has_native_aot, which gen.py derives from the manifests it already groups per dispatch key, so a tree that declares nothing -- or a build that opts out with --native-aot-ops-dir= -- gets the registration TU it had before native-AOT existed. Everything else is unchanged from what was reverted. The test asserts the generated RegisterCUDA text rather than the header helper's return value: a unit test of the helper alone still passes with has_native_aot=True hardcoded at the call site, which was checked by mutating it. 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
…, embedded detection, disabled() masking (#190898) Human Notes: Optimization of "is-this-covered-by-AOT" check by allowing a C++ implementation to be defined. Allow control of AOT'd kernels at runtime where appropriate: * If this is a sparsely-populated optimization (i.e. AOT covers a few specific cases, and expects to fall back otherwise, allow opt-out * If this is intended to have 100% coverage and be the only valid implementation, do **not** allow opt-out Claude: torch/_native/aot_manifest.py loads declarations into coverage objects; the eager router checks coverage once per call ahead of its cond chain, so covered calls decline the JIT route and fall through to the aten wrapper's stub. When the AOT library ships a cpp_covers predicate (torch.ops._native_aot.covers_<id>), coverage prefers it over the Python matching. AOT kernels are always linked into libtorch_cuda (no separate library): _native_aot_embedded() detects them in-process via the _native_aot covers-op namespace. Two distinct off states, deliberately different: * Artifacts ABSENT (stage 2 never ran): coverage still declines covered calls, the stub has no kernel, and they land on STOCK aten. Artifact presence is static per process and coverage is a declaration-time statement ("these points ship AOT"), not a runtime probe; checking per call would tax every covered call for a transient packaging condition. The correctness contract holds (stock aten serves), only the acceleration source changes; tested explicitly (test_covered_call_correct_without_aot_lib). * Context switch OFF (set_aot_enabled(False), also flipped by TORCH_DISABLE_NATIVE_AOT=1 and masked by python_native.<dsl>.disabled()): coverage itself returns False, so covered calls KEEP their JIT route rather than declining into a stub that will not fire -- masking must not silently lose both accelerated routes (test_masked_switch_restores_jit_coverage). Inside disabled() the JIT layer is off too, so those blocks still see stock aten end to end. Unconditional overrides sit outside both of those, on both routes. An override whose declaration says its kernels ARE the op's implementation is exempt from every user-facing filter (registry.check_enabled) -- the same rule the generated C++ gate follows in #190897 -- so set_aot_enabled(False) and disabled() cannot change what such an op computes. The one thing that reaches them is the private _set_mask_unconditional() behind torch._native._unconditional_masked(), which exists so a numerics test can still obtain stock aten values: a reference silently computed through the override under test is worse than no reference. It rebuilds every router rather than only setting the flag, because check_enabled runs while a graph is being registered, not per call -- so flipping the flag alone would leave the already-installed routers in place and the mask would appear to do nothing. Authored with an AI assistant (Claude Code). Test Plan: ``` python test/python_native/test_aot_manifest.py python test/python_native/test_registry.py ``` Pull Request resolved: #190898 Approved by: https://github.com/MatthiasKohl, https://github.com/ngimel
Stack from ghstack (oldest at bottom):
Human Notes:
Fix an internal build issue due to
NativeAotStubs.hbeing unconditionally included,but not actually generated in the build. Guard against that.
Insert the dispatch logic into structure operator's codegen - conditionally call
AOT'd kernels post-META(), and fall back to regular
IMPL()if nothingmatches.
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:
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:
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:
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:
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:
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.
Re-land. This landed once and was backed out in dfe5500 because it broke an
internal build: the generated CUDA registration TU included
<ATen/NativeAotStubs.h> unconditionally, and that build does not generate the
header. Fixed here rather than in a follow-up, so the re-land cannot reproduce
what it was reverted for: gen_registration_headers takes has_native_aot, which
gen.py derives from the manifests it already groups per dispatch key, so a tree
that declares nothing -- or a build that opts out with --native-aot-ops-dir= --
gets the registration TU it had before native-AOT existed. Everything else is
unchanged from what was reverted.
The test asserts the generated RegisterCUDA text rather than the header helper's
return value: a unit test of the helper alone still passes with
has_native_aot=True hardcoded at the call site, which was checked by mutating it.
Authored with an AI assistant (Claude Code).
Test Plan:
cc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @aditew01