Skip to content

[native_aot][2/7] export: arch identity and compiler versions in the sidecar - #194238

Closed
slayton58 wants to merge 8 commits into
gh/slayton58/146/basefrom
gh/slayton58/146/head
Closed

slayton58 wants to merge 8 commits into
gh/slayton58/146/basefrom
gh/slayton58/146/head

Conversation

@slayton58

@slayton58 slayton58 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Human note:

There are lots of potential footguns in the process - compile w/one compiler, link
with another, perform linking w/one set of archs, but generated a different set, etc.

Encode all pertinent info into the sidecar so both sides of the contract know what's
happening.

Claude note:

The sidecar is all generation reads about an artifact, so this commit fixes what
it records -- the arch the kernels were really compiled for, and the compiler that
built them. The artifact layout is next.

_effective_arch is the single resolver (explicit --arch, then a toolchain's env
var, then the device), so a tree can never disagree with its own sidecars. An arch
env var without --arch is now refused: it is per-kind, and a tree named sm_90a
held a sidecar recording the detected sm_100. Prefixes gain an arch tag, because
every exported C symbol derives from the prefix and two arches sharing one are
duplicate definitions at link time.

The layout that belongs with that tag lands in the next commit, which nests
unconditionally. Until it does, a single-arch export still writes flat into
--out-dir, so two hand runs with different --arch values accumulate both trees
where the arch-free prefix overwrote -- stated in the module docstring as well.
No build path calls export before [7/7], so nothing exercises it.

The compiler is recorded because no file on disk names it: the DSL version appears
in nothing the source closure hashes, so upgrading the wheel invalidated nothing
and a tree quietly mixed artifacts from two compilers. torch._vendor joins the
closure for the same bug one level down -- the vendored packages hold real kernel
bodies. Sidecar reads are schema-first throughout, so a renamed field re-exports
instead of raising a bare KeyError naming no file.

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 arch
resolution and the arch-tagged prefixes, the refusal of a per-kind arch env
var with no --arch, recorded-versus-installed compiler versions, and the
source closure covering vendored kernel bodies, schema-first sidecar reads
re-exporting instead of raising, and the arch-conditional spelling winning
where a declaration claims both.

Authored with an AI assistant (Claude Code).

[ghstack-poisoned]
@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/194238

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

✅ No Failures

As of commit 5b77491 with merge base 67aade5 (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]
[ghstack-poisoned]
[ghstack-poisoned]
@slayton58

Copy link
Copy Markdown
Contributor Author

@claude review this pr

@claude

claude Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Claude finished @slayton58's task in 17m 46s —— View job


Review done: the sidecar changes are well-motivated, but arch-tagging the prefix silently removed the overwrite that kept a flat --out-dir single-arch, and the on-device path now records an arch the declaration may disown — plus a mislabeled test class, two assertions that are vacuous exactly where CI runs them, and several docstrings that describe call sites and layout behavior the code doesn't have.

Full review of PR #194238

PR Review: #194238

Summary

Records the arch the kernels were really compiled for and the compiler that built them into the export sidecar, adds torch._vendor to the source closure, and makes sidecar reads schema-first. Two behavioral findings (arch-tagged prefixes vs. the flat layout; on-device arch vs. declaration ARCHS), three test defects, one unbumped schema version, and a cluster of docstrings that describe code that isn't there.

Infrastructure

  • tools/native_aot/export.py:309-315 — arch-tagging the prefix removes the overwrite that kept a flat --out-dir single-arch, and nothing replaces it. Sequential single-arch runs into one --out-dir still use the flat <out-root>/<decl_id>/ layout (_collect_jobs:344,363 — multi = len(archs) > 1). Trace --arch sm_100 --out-dir D then --arch sm_100a --out-dir D:

    1. _job_needed correctly returns True for run 2 (arch differs at :528).
    2. Run 2 no longer clobbers run 1 — it writes k__sm100a.{o,h,json} alongside run 1's k__sm100.*. Before this PR the prefix was arch-free, so run 2 overwrote run 1 and the flat tree stayed single-arch by construction.
    3. _check_no_orphan_artifacts:434-440 cannot catch it: the stale test is purely sidecar["spec"] not in live, and both sidecars record the same spec. Artifacts that have a sidecar are never checked for arch relevance.

    Net: a flat --out-dir now silently accumulates two arch variants of one spec point, and both would generate launchers claiming the same hardware (sm_100/sm_100a share a capability). The _job_needed docstring rewrite at :504-513 asserts "Per-arch directories stop two arches colliding in one tree" — that is exactly false for the single-arch flat path, which is the path the deleted docstring text was specifically about. Either nest unconditionally (see the docstring finding below, which claims you already do) or teach the orphan scan to reject a sidecar whose arch is not this run's.

  • tools/native_aot/export.py:322 + :353-359 — the on-device path can now record an arch the declaration disowns. _collect_jobs:358 deliberately skips arch filtering when arch is None ("the builder machine is the target by construction"), but the sidecar now records the detected arch rather than null. On an sm_90 builder with a declaration whose ARCHS = ("sm_100a",), export writes prefix k__sm90 and "arch": "sm_90" — a positive claim the declaration explicitly disowns, where before the PR it claimed nothing. torchgen/native_aot_decl.py:127-131 documents this as the precise bug cc_of was made shared to prevent ("a declaration pinning ('sm_100a',) disowned the 'sm_100' its own on-device export produced"). _claimed_spelling looks like the intended reconciliation, but it is never called — either filter the on-device job against archs_of(d) by capability, or route the detected arch through _claimed_spelling before it reaches the prefix and the sidecar.

API Design

  • tools/native_aot/export.py:93 — SIDECAR_VERSION was not bumped, though the comment at :90-92 says to bump it "on any change to the sidecar layout". This PR adds a runtimes field, changes arch from "explicit-or-None" to device-detected, and changes the prefix naming scheme. The runtimes field is not a substitute backstop: runtimes_current's all-"absent" early return at :482-483 fires before the comparison, so on a machine with no DSL wheels an old sidecar lacking runtimes is judged current. What actually saves the tree today is incidental — export.py hashes itself via the glob at :170, and this PR edits export.py, so every pre-PR sidecar's closure is stale. Any future sidecar-semantics change that doesn't touch tools/native_aot/*.py slips through. Fix this →

Testing

  • tools/test/test_native_aot_tools.py:1199-1202 — new test class carries a copy-pasted comment from an unrelated class. This PR adds class TestReadOnlyInputs whose comment reads "read_only tensor args must go through const_data_ptr in every toolchain's launcher". Nothing in the class touches read-only args — it holds the four source-closure staleness tests moved out of the deleted TestSourceStaleness. Both the name and the 3-line comment are wrong for the ~130 lines they head. Rename to something like TestSourceClosure. Fix this →

  • tools/test/test_native_aot_tools.py:1221-1230 — test_closure_excludes_the_consumer_tools is vacuous. It asserts assertNotIn on gen_aot_lib.py and build_stage2.py, but neither file exists in tools/native_aot/ (the directory holds only __init__.py, cutedsl_warmup.py, decl.py, export.py, toolchains.py). The glob at export.py:170 can never yield them, so the test passes with _CLOSURE_EXCLUDED = () and guards nothing. Either drop it until the consumers land, or write the fixture files into a temp _HERE so the filter is actually exercised.

  • tools/test/test_native_aot_tools.py:435-440 — the two new runtimes assertions in test_export_prefix_is_arch_qualified are vacuous, one of them precisely in the environment CI uses. assertEqual(written["runtimes"], export.runtime_versions("cutedsl")) runs inside mock.patch.object(toolchains, "get_toolchain", return_value=fake), and runtime_versions resolves its dists through get_toolchain (export.py:459) — so both sides of the equality go through the same patched object and the field's content is never checked. And assertTrue(export.runtimes_current(written)) at :440 returns True via the all-"absent" ignorance arm (export.py:482-483) in the lint image, where nvidia-cutlass-dsl is not installed — i.e. it cannot fail where the suite actually runs. The sibling test at :485-488 documents exactly this hazard and patches runtime_versions to dodge it; apply the same treatment here.

  • export.py:205 — _detected_arch's except Exception arm is untested. Only the is_available() is False path is covered (test file :572-588). See the Code Quality note on that arm below.

  • _claimed_spelling has three dedicated tests (:1470-1486) for a function with no production caller. Tests for dead code pin a contract nothing consumes.

Code Quality

  • export.py:45-46 — the new module docstring contradicts the code. "Every arch nests under <out-dir>/<arch>/" is false: :344,363 nest only when len(archs) > 1. Three places still state the real behavior — _collect_jobs's own docstring (:339-342), the --arch help string (:621), and test_multi_arch_jobs_nest_per_arch (test file :639-665), which asserts the single-arch job lands at <out>/fakeop directly. If nesting unconditionally is the intent (it would fix the flat-tree finding above), change the code and those three sites; otherwise revert the docstring.

  • export.py:225-227,232-236 — _effective_arch's docstring describes a call site that does not exist. "ONE resolver for both the sidecar and the directory name" and "tc is omitted when choosing a directory, before any builder (and so kind) exists": the only production callers are :312 (export_point) and :528 (_job_needed), and both pass tc. Directory naming at :363 uses the raw arch string from the archs list and never calls _effective_arch. The tc=None default is exercised only by tests (test_native_aot_tools.py:328,361,363,368,378), so the paragraph documents an invariant nothing establishes.

  • export.py:262-269 — _claimed_spelling is dead code. No caller anywhere in tools/, torchgen/, torch/, cmake, or setup.py. Its docstring's "matching the generator's tie-break" has no referent either; gen_aot_lib exists only as prose in comments. Land it with the caller that needs it (see the on-device/ARCHS finding, which is arguably that caller), not ahead of it.

  • export.py:196-198 vs :585-590 — two comments in the same file disagree about the gate. The new one says "the gate compares major.minor, which both spellings share"; the pre-existing EXPORTABLE_ARCHES comment says "_arch_gate compares only the CUDA major", and bases the deliberate sm_103 exclusion on it. native_aot_decl.cc_of returns (major, minor), which favors the new comment — meaning the sm_103 rationale at :585-590 is now stale and should be corrected in the same PR that establishes the contrary claim.

  • tools/native_aot/toolchains.py:52-55 and :109-113 — stale after this PR. Both still say ARCH_ENV_VAR is the var "this kind reads when no arch is passed explicitly" and that "export._effective_arch resolves it so the sidecar records the arch actually compiled for". It is now refused, not resolved. Not in the diff, but made wrong by it.

  • export.py:245-258 — the env-var refusal fires from a nondeterministic place. main() (:594-673) validates only --jobs and TORCH_CUDA_ARCH_LIST; nothing checks ARCH_ENV_VAR up front. The first call is _job_needed:528, but only inside the sidecar loop (:518), so on a clean out_dir the loop body never runs and the error instead surfaces from export_point:312 — inside a forkserver worker, re-raised through fut.result():668 as a remote-traceback wrapper. So whether the user gets a clean message or a worker crash mid-export depends on whether a sidecar already happens to exist. Resolve once in main() before _collect_jobs. Fix this →

  • export.py:251,254-257 — error message wording and the example value. With one var set it renders arch variable(s) CUTE_DSL_ARCH=sm_90a are set but --arch is not. They are per-toolchain... — "are set"/"They are" is wrong for a single variable. And sorted(named.items())[0][1] is the value of the alphabetically-first name, which is legible only after decoding the tuple index; named[min(named)] says the same thing. With two vars set (the case tested at test_native_aot_tools.py:350-356) the suggestion silently drops one value even though --arch is nargs="*".

  • export.py:478,491-492 — the "SCHEMA FIRST" principle isn't applied consistently to its own neighbors. After the new guard at :525 proves both version and kind, sources_current's own version check (:491-492) is unreachable from production, while runtimes_current still defaults a field the caller guaranteed (sidecar.get("kind", "cutedsl") at :478). Pick one: either both helpers assume a validated sidecar, or the guard is redundant.

  • export.py:199-206 — _detected_arch swallows every exception. A CUDA-present-but-broken driver (or a transient init failure) returns None, and export_point:313 then skips the prefix tag and writes "arch": null. Given the PR's premise is that both sides of the contract should know what's happening, a probe that finds CUDA and then fails should be loud at probe time rather than deferred to a generation-time rejection that names no cause. Narrowing the except to the import and is_available() — letting a get_device_capability() failure propagate — would do it.

  • test_native_aot_tools.py:45-68 — _no_ambient_arch returns an already-entered ExitStack. It applies its patches at call time rather than at with time, so a call site that constructs it but never enters the with (e.g. an exception raised while evaluating a later context manager in the same parenthesised with) leaks the os.environ patch and the _detected_arch mock for the rest of the process — and _effective_arch's new behavior depends on both. A @contextmanager generator would make entry and patching coincide.

  • Test comments are changelog rather than documentation. :393-397, :441-448, :482-488, :1295-1297 narrate what previously "left the suite green" or "the first version of this test"; _no_ambient_arch's docstring is 12 lines and ends in PR history ("patching only the device left six of them failing"). Per CLAUDE.md ("minimize comments; code should be self-explanatory"), these should state the invariant and drop the history.

Recommendation

Request Changes

The two Infrastructure findings are behavioral and specific to this diff: the flat-layout duplicate-artifact window opened by arch-tagged prefixes, and the on-device sidecar now asserting an arch the declaration may disown. Both are the kind of "tree quietly disagrees with itself" bug the PR exists to close. On the test side, the mislabeled class and the two vacuous runtimes assertions matter because the compiler-version check is the PR's headline feature and its writer-side assertions currently cannot fail in CI. The unbumped SIDECAR_VERSION and the docstring/comment cluster are cheap to clear in the same pass.

Note: I could not execute pytest tools/test/test_native_aot_tools.py in this environment (command not permitted), so all findings come from reading the code rather than from a failing test.

· branch [`gh/slayton58/146/head`](https://github.com/pytorch/pytorch/tree/gh/slayton58/146/head)

@slayton58

Copy link
Copy Markdown
Contributor Author

Addressing pertinent claude review bits:

Flat out-dir: This is only extant in this commit, it's move to full nested-dir in [3/7] - effectively an artifact of the seam-splitting used to make this set of commits more reviewable -- will not fix here.

On-device sidecar: Reconciliation described is handled in [3/7]

Runtime assertions: Disproved via. mutation

Sidecar change = version bump: Deliberately done, there are zero consumers, so there's nothing to protect via. bumping.

minor nits: fixed.

[ghstack-poisoned]
[ghstack-poisoned]
@slayton58
slayton58 requested a review from albanD August 27, 2026 14:29
Comment thread tools/native_aot/export.py Resolved
Comment thread tools/native_aot/export.py Resolved
Comment thread tools/native_aot/export.py Resolved
Comment thread tools/native_aot/export.py Resolved
Comment thread tools/test/test_native_aot_tools.py Resolved
[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.

Ok!
Thanks for the answers

slayton58 added a commit that referenced this pull request Aug 31, 2026
…sidecar

Human note:

There are lots of potential footguns in the process - compile w/one compiler, link
with another, perform linking w/one set of archs, but generated a different set, etc.

Encode all pertinent info into the sidecar so both sides of the contract know what's
happening.

Claude note:

The sidecar is all generation reads about an artifact, so this commit fixes what
it records -- the arch the kernels were really compiled for, and the compiler that
built them. The artifact layout is next.

_effective_arch is the single resolver (explicit --arch, then a toolchain's env
var, then the device), so a tree can never disagree with its own sidecars. An arch
env var without --arch is now refused: it is per-kind, and a tree named sm_90a
held a sidecar recording the detected sm_100. Prefixes gain an arch tag, because
every exported C symbol derives from the prefix and two arches sharing one are
duplicate definitions at link time.

The layout that belongs with that tag lands in the next commit, which nests
unconditionally. Until it does, a single-arch export still writes flat into
--out-dir, so two hand runs with different --arch values accumulate both trees
where the arch-free prefix overwrote -- stated in the module docstring as well.
No build path calls export before [7/7], so nothing exercises it.

The compiler is recorded because no file on disk names it: the DSL version appears
in nothing the source closure hashes, so upgrading the wheel invalidated nothing
and a tree quietly mixed artifacts from two compilers. torch._vendor joins the
closure for the same bug one level down -- the vendored packages hold real kernel
bodies. Sidecar reads are schema-first throughout, so a renamed field re-exports
instead of raising a bare KeyError naming no file.

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 arch
resolution and the arch-tagged prefixes, the refusal of a per-kind arch env
var with no --arch, recorded-versus-installed compiler versions, and the
source closure covering vendored kernel bodies, schema-first sidecar reads
re-exporting instead of raising, and the arch-conditional spelling winning
where a declaration claims both.

Authored with an AI assistant (Claude Code).

ghstack-source-id: c8084bc
Pull-Request: #194238
Comment thread tools/native_aot/export.py Resolved
[ghstack-poisoned]
slayton58 added a commit that referenced this pull request Sep 1, 2026
…sidecar

Human note:

There are lots of potential footguns in the process - compile w/one compiler, link
with another, perform linking w/one set of archs, but generated a different set, etc.

Encode all pertinent info into the sidecar so both sides of the contract know what's
happening.

Claude note:

The sidecar is all generation reads about an artifact, so this commit fixes what
it records -- the arch the kernels were really compiled for, and the compiler that
built them. The artifact layout is next.

_effective_arch is the single resolver (explicit --arch, then a toolchain's env
var, then the device), so a tree can never disagree with its own sidecars. An arch
env var without --arch is now refused: it is per-kind, and a tree named sm_90a
held a sidecar recording the detected sm_100. Prefixes gain an arch tag, because
every exported C symbol derives from the prefix and two arches sharing one are
duplicate definitions at link time.

The layout that belongs with that tag lands in the next commit, which nests
unconditionally. Until it does, a single-arch export still writes flat into
--out-dir, so two hand runs with different --arch values accumulate both trees
where the arch-free prefix overwrote -- stated in the module docstring as well.
No build path calls export before [7/7], so nothing exercises it.

The compiler is recorded because no file on disk names it: the DSL version appears
in nothing the source closure hashes, so upgrading the wheel invalidated nothing
and a tree quietly mixed artifacts from two compilers. torch._vendor joins the
closure for the same bug one level down -- the vendored packages hold real kernel
bodies. Sidecar reads are schema-first throughout, so a renamed field re-exports
instead of raising a bare KeyError naming no file.

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 arch
resolution and the arch-tagged prefixes, the refusal of a per-kind arch env
var with no --arch, recorded-versus-installed compiler versions, and the
source closure covering vendored kernel bodies, schema-first sidecar reads
re-exporting instead of raising, and the arch-conditional spelling winning
where a declaration claims both.

Authored with an AI assistant (Claude Code).

ghstack-source-id: 2e3dd1b
Pull-Request: #194238
@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
…g, CLI (#194239)

Human note:

Setup directory structure for 1+ architectures to be consistent. Setup ordering for
similar but distinct architectures (sm100 vs. sm100a for instance).

Claude note:

Where artifacts go, what an inconsistent tree means, and which arch lists the
automatic path accepts.

One layout whatever the arch count, <out-dir>/<arch>/<decl_id>/. The old shape
depended on how many arches were requested, so switching between one and several
left the other shape behind and one arch then appeared twice for a declaration. A
declaration matching no requested arch is now reported by name: with several
declarations the result is partial but looks healthy.

The orphan scan splits by how recoverable each case is. Artifacts no sidecar
claims are an export that died before writing one: reported, never fatal, since
nothing links them -- as a refusal it turned one failed compile in a 48-point grid
into a hand-delete that --force could not clear either, and it called every
interrupted first export of a new arch a corrupt tree, which is the shape a fresh
one always has. A sidecar recording a spec the grid no longer holds stays fatal:
nothing prunes it, and it makes an artifact nothing will launch look exported.

TORCH_CUDA_ARCH_LIST collapses to one arch per capability. "10.0;10.0a" is one
piece of hardware, and exporting both shipped the loser inside libtorch_cuda with
no launcher (54 objects, 3.5 MiB measured) -- the common case for CUDA 13.x
manywheel lists.

EXPORTABLE_ARCHES gains Hopper (sm_90, sm_90a), so a release list naming 9.0
exports for it instead of skipping. That is one more full set of kernels in every
CUDA 13.x wheel and in the H100 build jobs (topk's grid is 48 points), and past
this filter the DSL runtimes stop being optional: an H100 box without the
cutlass-dsl wheel now fails stage 2 where it used to skip, as a B200 box already
did. No CI job exercises AOT kernels on Hopper: the one functional AOT job in this
stack runs on B200 and arrives with the first declaration, so the coverage here
is the tools suite alone.

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 the per-arch
layout, the CLI's arch resolution (--arch, TORCH_CUDA_ARCH_LIST, on-device),
unclaimed artifacts being reported and never fatal -- including the fresh tree
whose first export died -- a sidecar for a dropped grid point staying fatal, and
the arch-list collapse to one spelling per capability.

Authored with an AI assistant (Claude Code).
Pull Request resolved: #194239
Approved by: https://github.com/albanD
ghstack dependencies: #190896, #194238
pytorchmergebot pushed a commit that referenced this pull request Sep 4, 2026
Human note:

Real work! Generate launchers and conditional gating functions in C++ for embedding.

Claude note:

The first half of the generator: a declaration plus its sidecars become the C++
ATen links. Source production only -- the CLI and the emitted CMake are next, so
this reads as "what is generated and why".

gen_op emits one .cpp per declaration: a marshalling launcher per kernel (from the
sidecar kind's Toolchain, so the guard chain is toolchain-blind), an early-out over
the shipped capabilities, then one cond chain per capability ending in `return
false` so the op falls through to aten.

The same declaration also emits a covers() predicate, so the router can ask
whether the AOT path applies without entering it. Its signature comes from
torchgen's structured introspection rather than being written out per op, which is
what makes it the signature aten will really call -- including for an op whose meta
function precomputes arguments.

Two gates are generated rather than written per declaration. The device gate
compares exact major.minor, because sm_103 reports major 10: a major-only gate
offered it sm_100 artifacts and the module load then failed instead of declining,
with no retry. The size gate exists because a kind whose exported ABI narrows
shapes to int32 cannot be handed a dim past INT32_MAX; it is per-kind and
per-argument, the width being a property of that ABI rather than of aten.

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 the emitted
launchers and per-capability cond chains, the device gate comparing exact
major.minor, the shipped-versus-declared arch selector, the covers() predicate's
signature and the device it reads, and the int32 size gate being per-kind and
per-argument.

Authored with an AI assistant (Claude Code).
Pull Request resolved: #194240
Approved by: https://github.com/albanD
ghstack dependencies: #190896, #194238, #194239
pytorchmergebot pushed a commit that referenced this pull request Sep 4, 2026
…eration ordering (#194241)

Human note:

Driver script for generation -- controls how the previous commits are put together
into one cohesive thing. Generates the cmake for libtorch_cuda relinking.

Claude note:

The generator gains a driver, and with it the build integration the previous
commit left out.

native_aot.cmake is not data for CMake to parse -- it IS the CMake calls, so
caffe2/CMakeLists.txt is a single include(... OPTIONAL). An earlier version put
~370 lines of parsing and comparison in CMake, none of it reachable by a test. The
link options are emitted in one exact spelling because each part is load-bearing:
target_link_options de-duplicates, so bare -Xlinker tokens collapse and the link
fails; LINKER: expands to -Wl, which the driver splits on commas; SHELL: splits its
own value on spaces.

Ordering is the correctness argument. The old file is deleted first, sources are
buffered until every declaration has passed its refusals, and the new file is
written atomically and last, so its CONTENT is the only evidence a generation
finished. export.py joins that rule here, invalidating the previous generation
before touching an artifact and on every refusal -- artifacts are direct link
inputs in build.ninja, so an interrupted export plus an ordinary `cmake --build`
relinked a library mixing two source revisions. Invalidation OVERWRITES the
include with its nothing-to-embed form rather than deleting it: CMake registers an
include()d file as a configure dependency only if it existed at configure time, so
a deleted one made the next generation invisible to `cmake --build` and the
kernels stayed out of the library however many times it was rebuilt.

The version script localizes the objects' _mlir_* entry points, which export_to_c
gives default visibility and which would otherwise join torch_cuda's public ABI. A
static torch_cuda cannot take it at all, because CMake silently discards
target_link_options for an archive -- the script would evaporate while appearing to
be applied -- so the verdict in the next commit refuses such a build outright.

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 the emitted
CMake calls and the opt-out among them, every version-script pattern being
anchored on a kernel prefix and the `local:` directive itself, the delete-first /
buffer-sources / write-last ordering and the atomic write, invalidation leaving an
include a later generation is still seen through, generation scoped to this
build's arch list, and the sidecar-field and orphan-artifact refusals.

Authored with an AI assistant (Claude Code).
Pull Request resolved: #194241
Approved by: https://github.com/albanD
ghstack dependencies: #190896, #194238, #194239, #194240
pytorchmergebot pushed a commit that referenced this pull request Sep 4, 2026
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: #194242
Approved by: https://github.com/albanD
ghstack dependencies: #190896, #194238, #194239, #194240, #194241
pytorchmergebot pushed a commit that referenced this pull request Sep 4, 2026
…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
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
…sidecar (pytorch#194238)

Human note:

There are lots of potential footguns in the process - compile w/one compiler, link
with another, perform linking w/one set of archs, but generated a different set, etc.

Encode all pertinent info into the sidecar so both sides of the contract know what's
happening.

Claude note:

The sidecar is all generation reads about an artifact, so this commit fixes what
it records -- the arch the kernels were really compiled for, and the compiler that
built them. The artifact layout is next.

_effective_arch is the single resolver (explicit --arch, then a toolchain's env
var, then the device), so a tree can never disagree with its own sidecars. An arch
env var without --arch is now refused: it is per-kind, and a tree named sm_90a
held a sidecar recording the detected sm_100. Prefixes gain an arch tag, because
every exported C symbol derives from the prefix and two arches sharing one are
duplicate definitions at link time.

The layout that belongs with that tag lands in the next commit, which nests
unconditionally. Until it does, a single-arch export still writes flat into
--out-dir, so two hand runs with different --arch values accumulate both trees
where the arch-free prefix overwrote -- stated in the module docstring as well.
No build path calls export before [7/7], so nothing exercises it.

The compiler is recorded because no file on disk names it: the DSL version appears
in nothing the source closure hashes, so upgrading the wheel invalidated nothing
and a tree quietly mixed artifacts from two compilers. torch._vendor joins the
closure for the same bug one level down -- the vendored packages hold real kernel
bodies. Sidecar reads are schema-first throughout, so a renamed field re-exports
instead of raising a bare KeyError naming no file.

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 arch
resolution and the arch-tagged prefixes, the refusal of a per-kind arch env
var with no --arch, recorded-versus-installed compiler versions, and the
source closure covering vendored kernel bodies, schema-first sidecar reads
re-exporting instead of raising, and the arch-conditional spelling winning
where a declaration claims both.

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

Human note:

Setup directory structure for 1+ architectures to be consistent. Setup ordering for
similar but distinct architectures (sm100 vs. sm100a for instance).

Claude note:

Where artifacts go, what an inconsistent tree means, and which arch lists the
automatic path accepts.

One layout whatever the arch count, <out-dir>/<arch>/<decl_id>/. The old shape
depended on how many arches were requested, so switching between one and several
left the other shape behind and one arch then appeared twice for a declaration. A
declaration matching no requested arch is now reported by name: with several
declarations the result is partial but looks healthy.

The orphan scan splits by how recoverable each case is. Artifacts no sidecar
claims are an export that died before writing one: reported, never fatal, since
nothing links them -- as a refusal it turned one failed compile in a 48-point grid
into a hand-delete that --force could not clear either, and it called every
interrupted first export of a new arch a corrupt tree, which is the shape a fresh
one always has. A sidecar recording a spec the grid no longer holds stays fatal:
nothing prunes it, and it makes an artifact nothing will launch look exported.

TORCH_CUDA_ARCH_LIST collapses to one arch per capability. "10.0;10.0a" is one
piece of hardware, and exporting both shipped the loser inside libtorch_cuda with
no launcher (54 objects, 3.5 MiB measured) -- the common case for CUDA 13.x
manywheel lists.

EXPORTABLE_ARCHES gains Hopper (sm_90, sm_90a), so a release list naming 9.0
exports for it instead of skipping. That is one more full set of kernels in every
CUDA 13.x wheel and in the H100 build jobs (topk's grid is 48 points), and past
this filter the DSL runtimes stop being optional: an H100 box without the
cutlass-dsl wheel now fails stage 2 where it used to skip, as a B200 box already
did. No CI job exercises AOT kernels on Hopper: the one functional AOT job in this
stack runs on B200 and arrives with the first declaration, so the coverage here
is the tools suite alone.

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 the per-arch
layout, the CLI's arch resolution (--arch, TORCH_CUDA_ARCH_LIST, on-device),
unclaimed artifacts being reported and never fatal -- including the fresh tree
whose first export died -- a sidecar for a dropped grid point staying fatal, and
the arch-list collapse to one spelling per capability.

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

Human note:

Real work! Generate launchers and conditional gating functions in C++ for embedding.

Claude note:

The first half of the generator: a declaration plus its sidecars become the C++
ATen links. Source production only -- the CLI and the emitted CMake are next, so
this reads as "what is generated and why".

gen_op emits one .cpp per declaration: a marshalling launcher per kernel (from the
sidecar kind's Toolchain, so the guard chain is toolchain-blind), an early-out over
the shipped capabilities, then one cond chain per capability ending in `return
false` so the op falls through to aten.

The same declaration also emits a covers() predicate, so the router can ask
whether the AOT path applies without entering it. Its signature comes from
torchgen's structured introspection rather than being written out per op, which is
what makes it the signature aten will really call -- including for an op whose meta
function precomputes arguments.

Two gates are generated rather than written per declaration. The device gate
compares exact major.minor, because sm_103 reports major 10: a major-only gate
offered it sm_100 artifacts and the module load then failed instead of declining,
with no retry. The size gate exists because a kind whose exported ABI narrows
shapes to int32 cannot be handed a dim past INT32_MAX; it is per-kind and
per-argument, the width being a property of that ABI rather than of aten.

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 the emitted
launchers and per-capability cond chains, the device gate comparing exact
major.minor, the shipped-versus-declared arch selector, the covers() predicate's
signature and the device it reads, and the int32 size gate being per-kind and
per-argument.

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

Human note:

Driver script for generation -- controls how the previous commits are put together
into one cohesive thing. Generates the cmake for libtorch_cuda relinking.

Claude note:

The generator gains a driver, and with it the build integration the previous
commit left out.

native_aot.cmake is not data for CMake to parse -- it IS the CMake calls, so
caffe2/CMakeLists.txt is a single include(... OPTIONAL). An earlier version put
~370 lines of parsing and comparison in CMake, none of it reachable by a test. The
link options are emitted in one exact spelling because each part is load-bearing:
target_link_options de-duplicates, so bare -Xlinker tokens collapse and the link
fails; LINKER: expands to -Wl, which the driver splits on commas; SHELL: splits its
own value on spaces.

Ordering is the correctness argument. The old file is deleted first, sources are
buffered until every declaration has passed its refusals, and the new file is
written atomically and last, so its CONTENT is the only evidence a generation
finished. export.py joins that rule here, invalidating the previous generation
before touching an artifact and on every refusal -- artifacts are direct link
inputs in build.ninja, so an interrupted export plus an ordinary `cmake --build`
relinked a library mixing two source revisions. Invalidation OVERWRITES the
include with its nothing-to-embed form rather than deleting it: CMake registers an
include()d file as a configure dependency only if it existed at configure time, so
a deleted one made the next generation invisible to `cmake --build` and the
kernels stayed out of the library however many times it was rebuilt.

The version script localizes the objects' _mlir_* entry points, which export_to_c
gives default visibility and which would otherwise join torch_cuda's public ABI. A
static torch_cuda cannot take it at all, because CMake silently discards
target_link_options for an archive -- the script would evaporate while appearing to
be applied -- so the verdict in the next commit refuses such a build outright.

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 the emitted
CMake calls and the opt-out among them, every version-script pattern being
anchored on a kernel prefix and the `local:` directive itself, the delete-first /
buffer-sources / write-last ordering and the atomic write, invalidation leaving an
include a later generation is still seen through, generation scoped to this
build's arch list, and the sidecar-field and orphan-artifact refusals.

Authored with an AI assistant (Claude Code).
Pull Request resolved: pytorch#194241
Approved by: https://github.com/albanD
ghstack dependencies: pytorch#190896, pytorch#194238, pytorch#194239, pytorch#194240
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
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
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
@github-actions
github-actions Bot deleted the gh/slayton58/146/head branch November 13, 2026 01:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants