Skip to content

[native_aot] runtime: router-level AOT coverage, C++ covers fast path, embedded detection, disabled() masking - #190898

Closed
slayton58 wants to merge 67 commits into
gh/slayton58/115/basefrom
gh/slayton58/115/head
Closed

slayton58 wants to merge 67 commits into
gh/slayton58/115/basefrom
gh/slayton58/115/head

Conversation

@slayton58

@slayton58 slayton58 commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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), 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..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-poisoned]
@pytorch-bot

pytorch-bot Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 06d02a9 with merge base 81deebd (image):
💚 Looks good so far! There are no failures yet. 💚

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

[ghstack-poisoned]
@slayton58 slayton58 changed the title [native_aot] runtime: router-level AOT coverage, C++ covers fast path, AOT-lib load, disabled() masking [native_aot] runtime: router-level AOT coverage, C++ covers fast path, embedded detection, disabled() masking Jul 23, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
slayton58 added a commit that referenced this pull request Jul 24, 2026
…, embedded detection, disabled() masking

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.

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: dc40d29
Pull-Request: #190898
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@slayton58 slayton58 added the ciflow/trunk Trigger trunk jobs on your pull request label Jul 28, 2026
[ghstack-poisoned]
[ghstack-poisoned]

@MatthiasKohl MatthiasKohl left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

[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.

codegen sounds ok. But it would be good for someone else to weigh on the coverage logic

Comment thread torch/_native/__init__.py Outdated
return embedded


_native_aot_embedded()

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.

Why force this to happen?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

_native_aot_embedded() was reading & setting the opt-out, that's now moved to a dedicated _apply_env_opt_out() method.

Comment thread torch/_native/__init__.py Outdated
except Exception:
embedded = False
if embedded and os.getenv("TORCH_DISABLE_NATIVE_AOT") == "1":
torch._C._set_native_aot_enabled(False)

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.

Ho this is sneaky!
I would separate the two things: a function to check if it is in the build (that is cached). And code that runs on import reading the config.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done - _native_aot_embedded() is the cached "is it in the build", config read is in _apply_env_opt_out, read at module-import time.

Comment thread torch/_native/__init__.py Outdated


def set_aot_enabled(enabled: bool) -> None:
"""Toggle at::globalContext().allowNativeAot(), the switch every generated stub

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.

We should have a python-centric view of the world in these docs.
A user reading this shouldn't be expected to know the C++ details.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done here and other methods that were analogous.

Comment thread torch/_native/registry.py Outdated
# Masks unconditional overrides, which the user-facing filters cannot reach. The
# only supported flip is torch._native._unconditional_masked(), which lets a test
# compute stock-aten reference values for an op whose override IS the implementation.
_mask_unconditional = False

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.

What is this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This was module-level state tracking the masking of unconditional overrides -- places where the override was intended to cover all cases (i.e. never fallback to ATen), but a debug hook was available to let ATen cover anyway (with the risk of bad things happening if no other implementation existed/was valid -- hence the private, undocumented nature of it).

Removed, API goes directly through the torch._C._get_native_aot_unconditional_masked method.

@slayton58 slayton58 added the topic: not user facing topic category label Sep 3, 2026
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread tools/native_aot/build_stage2.py Outdated
if sep and not line.startswith("#") and ":" in key:
name, _, kind = key.partition(":")
entries[name] = (f"{kind}={value}", doc)
name, _, _kind = key.partition(":")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Note: This is because cmake is changing the type of variables after they've been used, example:

First configure (what stage-2 snapshots):

  //Use XCCL
  USE_XCCL:BOOL=OFF

And after stage-2's reconfigure:

USE_XCCL:INTERNAL=OFF

This was being reported as a change in config, and loud-failing. We care about the values being the same, not the types -- we could verify that types == same || INTERNAL, but I don't think that buys us much.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
slayton58 added a commit that referenced this pull request Sep 8, 2026
…, 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
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #190899

2 similar comments
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #190899

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #190899

pytorchmergebot pushed a commit that referenced this pull request Sep 9, 2026
…he check (#196070)

Human Notes:

Bug fixes discovered as part of #190899 CI runs:

* Cmake changes the TYPE of variables if inactive, and mark them `INTERNAL`,
so we can't directly compare both type & value. Instead just check value.
* cuteDSL `.compile` takes the current host CPU arch, which may not be compatible
with all machines -- notable AVX512 was present on the builder, not on H100 runner,
causing failures. Moved to a conservative arch.

Claude:

Two stage-2 defects that only bite once a declaration exists, so they land ahead
of the first one (#190899).

The exported objects targeted the BUILD machine's CPU. CuTeDSL compiles the host
stubs in an export_to_c object for the native host unless cute.compile is given a
--host-target, so a builder with AVX512 emits AVX512 module loaders and every
launch of those kernels faults on a host without it. Reproduced by running the
wheel the B200 build job produced on an AVX2-only box: SIGILL inside
topk_radix_f32_n4096_k64_nondet__sm90a_cuda_load_to_device, and the H100 test job
in #190899 fails with the same signature. Which instructions appear depends on
the builder, so the same commit is portable or not depending on which runner took
the job.

The pin is the baseline aten itself targets: torch compiles general code for the
compiler default and keeps AVX2 and AVX512 in runtime-dispatched capability
copies (CPU_CAPABILITY_FLAGS in cmake/Codegen.cmake), which a kernel's module
loader cannot do. It reaches only the host half of the object, so device SASS is
unchanged and the JIT route cannot diverge from it; a declaration naming its own
--host-target still wins. toolchains.py is inside the sidecars' source closure,
so artifacts exported before this change re-export rather than keeping their
host-specific loaders.

Second, the reconfigure's cache comparison read an entry's TYPE as part of its
value. cmake_dependent_option re-declares a settled option as CACHE INTERNAL on
the second configure -- USE_XCCL:BOOL=OFF becomes USE_XCCL:INTERNAL=OFF -- so
stage 2 refused its own reconfigure as configuration drift and failed the build.
Only the value is compared now, which leaves the check's purpose intact: a
changed value, or an entry EnvVarForwarding newly FORCEs, is still drift.

Authored with an AI assistant (Claude Code).

Test Plan:

```
pytest tools/test/test_native_aot_tools.py -k "pins_the_host_isa or retyped_by_the_reconfigure or RelinkNeverStrands"
```

Each new test was checked against the unfixed code: dropping the pin, letting it
override a declaration's own, and putting the TYPE back into the compared value
all fail it. The pin was also confirmed end to end -- objdump of a real exported
object carries no ymm or zmm registers where it previously had 16 ymm
references.
Pull Request resolved: #196070
Approved by: https://github.com/ngimel
ghstack dependencies: #190898
pytorchmergebot pushed a commit that referenced this pull request Sep 9, 2026
…e2e tests (#190899)

Human Notes:

Finally do a thing! Add `topk` as an AOT-provided override in libtorch_cuda.

Claude:

Declares a 48-point grid (fp32/bf16 x N{2048..16384} x K{64,128,256}
x both determinism modes) over the radix-select kernel. The det
specialization (stable prefix-sum gather + lex (ord, -idx) sort) is
bit-exact vs aten including tie resolution, so det-mode calls are
served AOT too; the dispatch chain keys on
deterministicAlgorithms(). The kernel gains
in_dtype and index_dtype compile parameters; the AOT route writes
int64 indices directly (no widening copy). build(spec) lives beside
the JIT wrappers, so both routes compile the same class. fp16 and
off-grid shapes keep their JIT eligibility, as do calls the prelude
declines: a non-last dim, largest/sorted false, sub-full-wave M, or a
base pointer less aligned than the kernels were compiled for.

ARCHS is stated rather than defaulted, and covers Hopper as well as
Blackwell: measured on an H100, the AOT kernels beat aten on 48/48 of
the grid, median 2.16x (min 1.26x at M=4096/N=2048, max 2.99x at
M=256/N=4096 fp32). Both spellings of each capability are listed --
archs_from_cuda_arch_list maps 9.0 and 9.0a to different nvcc targets,
and a wheel built with the plain list would otherwise export trees
generation then filters out.

CI: a native_aot test config (test.sh) asserts the wheel actually
embeds the kernels -- a silently artifact-free wheel would make every
routing test vacuously pass on the JIT/aten fallbacks -- then runs the
python_native suites. One build+test pair per capability in
native-aot.yml: cuda-arch-list 9.0a tested on linux.aws.h100 and
10.0a on linux.dgx.b200, both built on a GPU-less builder
(path-triggered + nightly). test_uncovered_fp32_served_by_jit_layer
skips below sm_100, since the JIT topk override is gated there while
these AOT kernels are not. This lands with the first op so the AOT path
is exercised in CI from this commit onward.

Authored with an AI assistant (Claude Code).

Test Plan:

```
.venv/bin/python test/python_native/test_native_aot.py
# incl. det-mode routing + bit-exact-with-ties tests
# (test_deterministic_mode_routes_to_aot_bit_exact,
#  test_deterministic_ties_bit_exact)
.venv/bin/python test/python_native/test_topk_radix_kernel.py
.venv/bin/python test/python_native/test_topk_cutedsl.py
```

On an H100, against the kernels a `spin develop` embedded:

```
.venv/bin/python test/python_native/test_native_aot.py    # 11 tests, 1 skipped
.venv/bin/python test/python_native/test_aot_manifest.py  # 18 tests
.venv/bin/python test/python_native/test_registry.py      # 35 tests
```
Pull Request resolved: #190899
Approved by: https://github.com/MatthiasKohl, https://github.com/ngimel
ghstack dependencies: #190898, #196070
@github-actions
github-actions Bot deleted the gh/slayton58/115/head branch November 16, 2026 01:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 ciflow/inductor ciflow/trunk Trigger trunk jobs on your pull request Merged topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants