Skip to content

Support non-builtin constexpr objects in user Triton kernels - #189692

Closed
AnthonyBarbier wants to merge 17 commits into
pytorch:mainfrom
graphcore:anthonyb/triton_constexpr
Closed

AnthonyBarbier wants to merge 17 commits into
pytorch:mainfrom
graphcore:anthonyb/triton_constexpr

Conversation

@AnthonyBarbier

@AnthonyBarbier AnthonyBarbier commented Jul 13, 2026 •

Copy link
Copy Markdown
Collaborator

Fix Inductor codegen for user-defined Triton kernels that pass non-builtin Python objects as tl.constexpr values.

When such constants are serialized with constructor-style repr output, for example UserDefinedTritonKernelConfig(offset=2), generated kernel source and launcher code need the corresponding class in scope.

This change imports the constant class into generated kernel source and makes it available in the generated launcher exec scope.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

Fix Inductor codegen for user-defined Triton kernels that pass non-builtin Python objects as `tl.constexpr` values.

When such constants are serialized with constructor-style `repr` output, for example `UserDefinedTritonKernelConfig(offset=2)`, generated kernel source and launcher code need the corresponding class in scope. This change imports the constant class into generated kernel
source and makes it available in the generated launcher exec scope.
@pytorch-bot

pytorch-bot Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (4 Unrelated Failures)

As of commit f942d0c with merge base 1859e8b (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

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

@albanD
albanD requested review from eellison and zou3519 July 13, 2026 15:42
@albanD albanD added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 13, 2026
@jansel

jansel commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 8m 38s —— View job


PR Review: #189692

One-sentence summary: The change correctly makes non-builtin tl.constexpr classes importable in generated kernel source and launcher scope, but the detection heuristic is fragile, duplicated across two files, and misses nested/same-name cases — I'd request changes before merge.

Full review details

Summary

Fixes Inductor codegen for user-defined Triton kernels passing non-builtin objects (e.g. a dataclass) as tl.constexpr, whose repr() is baked into generated code (via triton_meta={triton_meta!r} at wrapper.py:3573) and therefore needs the class in scope. The mechanism is reasonable, but the detection logic has correctness gaps and is copy-pasted.

Code Quality

  • Duplicated detection logic. The same block — type(value) → __name__/__module__ → != "builtins" → repr(value).startswith(f"{type_name}(") — is duplicated in torch/_inductor/codegen/wrapper.py:3550-3564 and torch/_inductor/runtime/triton_heuristics.py:3143-3155. The two copies already diverge (wrapper dedups on (module, name); heuristics uses setdefault). This must be factored into one shared helper so the heuristic can't drift between the kernel-source path and the launcher-scope path.

Testing

  • Only the happy path is covered. The single test uses a module-top-level frozen dataclass. None of the failure/edge modes below are exercised. At minimum add a test for a class defined in __main__ / non-importable scope (see below), since that is the common way users define these config objects and it changes from a NameError to an ImportError with no fallback.

Correctness / robustness

  • Non-importable modules crash at launch. importlib.import_module(type_module) (triton_heuristics.py:3154) and from {type_module} import ... (wrapper.py:3562) will raise ImportError if the class lives in __main__, a nested/local scope, or a dynamically-created module. Users very commonly define small constexpr-config classes at script top level (__main__). There is no try/except or fallback, so this replaces the old NameError with an equally-fatal ImportError. Consider guarding and degrading gracefully (or at least emitting a clear diagnostic).

  • Nested non-builtin values are not handled. The loop only inspects the top-level constant's type. A value like Config(inner=Inner(2)) has repr Config(inner=Inner(2)); only Config is imported, so the baked-in code referencing Inner fails. The repr-round-trip assumption is transitive but the import logic is not.

  • __qualname__ vs __name__ mismatch for nested classes. Dataclass __repr__ uses self.__class__.__qualname__, so a nested class reprs as Outer.Inner(x=1), while type_name is __name__ = Inner. The guard repr(value).startswith(f"{type_name}(") is then False, silently skipping the import — and from module import Inner wouldn't resolve a nested class anyway. Result: silent miss then a codegen failure.

  • Same-name classes from different modules resolve inconsistently. If two constants have types with the same __name__ from different modules, wrapper.py emits both from A import Foo and from B import Foo (last wins in kernel source), while triton_heuristics.py's setdefault keeps the first. The kernel source and the launcher scope can then bind Foo to different classes.

  • startswith(f"{type_name}(") is a weak round-trip proxy. It neither guarantees eval(repr(value)) reconstructs the object (Python makes no such promise) nor rules out false positives (a class whose repr cosmetically starts with Name( but whose constructor signature differs). The whole approach hinges on repr being eval-able; that assumption should be documented and, ideally, the detection tied to something stronger (e.g. an explicit opt-in / registration) rather than a string prefix.

Recommendation

Request Changes

Main blockers: de-duplicate the detection into a shared helper, and handle the non-importable-module / nested-value / nested-class cases (or explicitly document + fail loudly with a clear message). The happy-path test should be expanded to cover at least the __main__/non-importable case.

(branch: `anthonyb/triton_constexpr`)

- Factored the constexpr type detection/import logic into shared get_importable_constexpr_types() in torch/_inductor/utils.py:152.
- Updated both wrapper kernel-source imports and launcher-scope imports to use the shared helper.
- Added recursive handling for nested containers/dataclasses and nested classes.
- Added clear ImportError failures for local / __main__ / conflicting import cases.
- Expanded tests with nested constexpr config coverage and local-class failure coverage.
- Added importable test config classes in test/inductor/triton_constexpr_configs.py.
@albanD

albanD commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator

@jansel any follow up?

@jansel

jansel commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

@claude review this again, are the prior issues fixed?

@claude

claude Bot commented Aug 15, 2026

Copy link
Copy Markdown

Claude Code is working…

I'll analyze this and get back to you.

View job run

@jansel

jansel commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

@claude review this again, are the prior issues fixed?

@jansel
jansel requested a review from oulgen August 16, 2026 00:21
@claude

claude Bot commented Aug 16, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 19m 18s —— View job


Re-review of #189692

One-sentence summary: All four structural issues from my previous review are addressed (logic de-duplicated into get_importable_constexpr_types, nested values traversed, __qualname__ handled, non-importable and same-name cases now raise clear errors), but the new shared helper in torch/_inductor/utils.py has three correctness bugs of its own — most notably it raises a spurious ImportError for two different nested classes under the same outer class.

Full review details

Prior findings — status

Prior finding Status
Duplicated detection logic across wrapper.py / triton_heuristics.py Fixed — single get_importable_constexpr_types in torch/_inductor/utils.py:233, consumed at wrapper.py:3669 and triton_heuristics.py:3228. The two call sites now share one policy.
Non-importable module (__main__ / <locals>) silently becomes ImportError at launch Fixed — detected up front at utils.py:197-202 with an actionable message ("Define constexpr config classes at module scope in an importable module"), and covered by test_importable_constexpr_types_local_class_error.
Nested non-builtin values not handled Fixed for dataclasses and containers — recursion at utils.py:219-230, covered by test_importable_constexpr_types_nested_values and the end-to-end kernel test. See gap below re: non-dataclass objects.
__qualname__ vs __name__ mismatch for nested classes Fixed for the dataclass case — qualname is recorded and the root name is imported (utils.py:203), so NS.Nested(offset=2) in the baked repr resolves. But the __name__ fallback branch is now unsound; see finding 2.
Same-name classes from different modules bind inconsistently Fixed — now a hard ImportError (utils.py:205-212) instead of a silent divergence between kernel source and launcher scope.
startswith(f"{type_name}(") is a weak eval-round-trip proxy Not addressed — still the detection mechanism, and get_importable_constexpr_types has no docstring stating the assumption. Acceptable as a heuristic, but see nit below.

New issues in the shared helper

1. Spurious ImportError for two distinct nested classes under the same root. utils.py:203-212 keys result by root_name but rejects on existing.qualname != type_qualname. Two sibling nested classes need only one import, yet they collide:

# Both need only `from mod import NS` — this raises today.
Config(a=NS.A(1), b=NS.B(2))
# ImportError: ... conflicting imports for NS: mod.NS.A and mod.NS.B

The genuine conflict is two different roots with the same name, so the check should compare (module, root_name), not (module, qualname). Fix this →

2. The __name__ fallback in _constexpr_type_repr_prefix detects a value but then imports the wrong name. utils.py:173 accepts a match on either __qualname__ or bare __name__. Dataclasses always repr with __qualname__, but hand-written __repr__s (and attrs/pydantic) commonly use type(self).__name__. In that case the repr baked into the kernel is Nested(offset=2) while the emitted import is from mod import NS — so the generated code hits a NameError on Nested, i.e. exactly the bug this PR fixes, just not fixed for that shape. The function already computes which prefix matched but the caller discards it (... is not None at utils.py:195); that return value is the information needed to bind the correct name (or to reject the case with a clear error). Fix this →

3. Traversal over-reports, turning working code into a hard failure. utils.py:220 iterates dataclasses.fields(value) unconditionally, including fields declared field(repr=False) (and init=False). Those values never appear in the baked repr, so no import is needed — but if such a field holds a __main__-defined or locally-defined object, utils.py:197 now raises ImportError and fails compilation for a kernel that previously worked. Skipping not f.repr fields matches the repr-round-trip premise the whole helper rests on.

4. Recursion gaps. Two shapes still slip through:

  • Plain set is missing from utils.py:228 (list, tuple, OrderedSet, frozenset). A set constexpr inlines its elements into the repr, so nested types inside it go unimported.
  • Nested traversal is dataclass-only. attrs/pydantic config objects (a natural fit for this feature, and just as repr-round-trippable) are detected at top level but not descended into, so finding 3 from my prior review still applies to them.

Testing

Coverage is much better — a nested-value unit test, a local-class error test, and an end-to-end compiled-kernel test. Remaining gaps:

  • No test for the sibling-nested-classes case (finding 1) or the __name__-repr case (finding 2).
  • test_user_defined_triton_kernel_non_builtin_constexpr is gated on HAS_GPU_AND_TRITON or (HAS_CPU and has_triton_package()) and falls back to device="cpu" (test_codegen_triton.py:809). Launching a user-defined Triton kernel on CPU tensors is unusual; since CI is green either it genuinely works or the branch is never taken. Can you confirm this actually executed on a CPU-only job rather than silently skipping? If it can't run on CPU, plain @requires_gpu (as test_triton_kernels.py uses throughout) would be clearer than a fallback that looks exercised but isn't.

Nits

  • test/inductor/triton_constexpr_configs.py:5 defines UserDefinedTritonKernelConfig, which nothing references — dead code, drop it.
  • get_importable_constexpr_types is a new public util resting on a non-obvious contract (the constant's repr must be constructor-style and eval-able in the generated module). One line of docstring stating that would save the next reader a trip through _constexpr_type_repr_prefix.
  • wrapper.py:3673-3675 emits from {module} import {Root} as {Root}; the self-alias is redundant in generated code that is never linted.

Recommendation

Request changes (minor) — the structural rework is the right shape and the previous blockers are genuinely resolved. Findings 1 and 3 are behavior regressions relative to no-op for valid programs, and finding 2 leaves a common repr shape broken; all three are small, local fixes in _collect_importable_constexpr_types.

(branch: `anthonyb/triton_constexpr`)

@AnthonyBarbier

Copy link
Copy Markdown
Collaborator Author

@claude review this again, are the prior issues fixed?

@claude

claude Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

Claude finished @AnthonyBarbier's task in 27m 52s —— View job


Re-review of #189692

One-sentence summary: All four findings from my last round are fixed and well-tested, but the PR now makes dataclasses a first-class tl.constexpr shape without teaching _sanitize_for_repr about them, so a dataclass holding an Enum field emits MyConfig(mode=<Mode.FAST: 1>) into the kernel source and fails to compile.

Full review details

Prior findings — status

Prior finding (round 2) Status
1. Spurious ImportError for sibling nested classes (NS.A + NS.B) Fixed — conflict check now compares (module, root_name) at utils.py:241-244, with the rationale in a comment at utils.py:239-240. Covered by test_importable_constexpr_types_sibling_nested_classes.
2. __name__ fallback detects a value but imports the wrong name Fixed — _constexpr_type_repr_prefix now returns the matched prefix and the caller compares it against __qualname__ (utils.py:229-236), raising a clear error for the bare-name-of-a-nested-class case instead of silently emitting an import that won't resolve. Covered by test_importable_constexpr_types_bare_nested_class_repr.
3. Traversal over-reports field(repr=False), turning working code into a hard failure Fixed — if not field.repr: continue at utils.py:258-259, covered by test_importable_constexpr_types_skip_hidden_dataclass_field (which deliberately hides a local class to prove no spurious ImportError).
4a. Plain set missing from container recursion Fixed — utils.py:279, covered by test_importable_constexpr_types_set.
4b. attrs/pydantic objects detected but not descended into Fixed — __attrs_attrs__ and __repr_args__ branches at utils.py:263-274, covered by test_importable_constexpr_types_repr_protocols. Nice touch reading the metadata protocols rather than taking a runtime dep on attrs/pydantic.

I also checked the two things I flagged as structural in round 2 and they hold up: get_importable_constexpr_types is the single policy for both consumers (wrapper.py:3779, triton_heuristics.py:3265), and importing it from ..utils into runtime/triton_heuristics.py is not a new layering violation — that module already imported six names from ..utils on main.

New issue

1. _sanitize_for_repr doesn't recurse into dataclasses, so an Enum field inside a constexpr dataclass produces invalid Python. This is a feature interaction that only becomes reachable because of this PR.

_sanitize_for_repr (wrapper.py:120-135) recurses into dict, list, tuple/namedtuple, and rewrites Enum -> .value. It returns any other object unchanged (wrapper.py:135) — including dataclass instances. So for:

class Mode(IntEnum):
    FAST = 1

@dataclasses.dataclass(frozen=True)
class MyConfig:
    mode: Mode

get_importable_constexpr_types correctly sees MyConfig(mode=<Mode.FAST: 1>), matches the MyConfig( prefix, and even recurses into the mode field (utils.py:256-262) — but the text actually baked into the kernel at wrapper.py:3796 is repr(_sanitize_for_repr(triton_meta)), and the Enum inside the dataclass was never rewritten. The generated source gets <Mode.FAST: 1>, which is a SyntaxError, not a NameError — no import can rescue it.

The ordering makes this concrete: get_importable_constexpr_types runs on the unsanitized constants at wrapper.py:3779-3781, then sanitized_triton_meta = _sanitize_for_repr(triton_meta) at wrapper.py:3790. The two passes disagree about what the repr will contain. The repo already treats bare Enum constexprs as a supported shape (test_enum_constexpr_in_user_defined_triton_kernel, test_codegen_triton.py:948), and an enum field inside a config dataclass is the natural next thing a user writes — so this is worth closing rather than leaving as a latent trap.

Fix is to teach _sanitize_for_repr to rebuild dataclasses (dataclasses.replace, or type(obj)(**{f.name: _sanitize_for_repr(...)}) for init fields), and to add a test with an enum-valued field. Note the two functions rest on the same contract, so they should ideally traverse via one shared walk rather than two divergent ones. Fix this →

2. set traversal makes the emitted import order nondeterministic. utils.py:279 iterates a set/frozenset directly, and result is an insertion-ordered dict whose order becomes the order of the from ... import ... lines at wrapper.py:3782-3785. Set iteration order for elements with string-derived hashes varies with PYTHONHASHSEED, so two processes compiling the identical graph can emit textually different kernel source and miss each other's cache entries. Sorting the traversal of unordered containers (or sorting result before returning) removes the variance.

Still unaddressed from round 2

  • Dead code. UserDefinedTritonKernelConfig (test/inductor/triton_constexpr_configs.py:5) has no references anywhere in torch/ or test/ — I re-grepped. Drop it.
  • No docstring on get_importable_constexpr_types (utils.py:284). This is the one place the whole design's contract lives — "the constant's repr must be constructor-style, use the type's __qualname__, and be eval-able in the generated module" — and a reader currently has to reverse-engineer it from _constexpr_type_repr_prefix. One or two lines.
  • wrapper.py:3784 self-alias. import {Root} as {Root} is a re-export marker for type checkers; generated code is neither linted nor type-checked, so it's just noise.
  • CPU gating of the e2e test. test_user_defined_triton_kernel_non_builtin_constexpr is still gated on HAS_GPU_AND_TRITON or (HAS_CPU and has_triton_package()) and falls back to device="cpu" (test_codegen_triton.py:828-831, 868). I asked last round whether this branch genuinely executes on a CPU-only job; still unanswered. If a user-defined Triton kernel can't actually launch on CPU tensors, plain @requires_gpu is honest, whereas the fallback reads as covered when it isn't.

Minor

  • _AttrsField.repr (triton_constexpr_configs.py:40) shadows the builtin. It's mirroring the attrs field API so it's defensible, but repr_enabled is already the ctor arg name — worth keeping consistent.
  • getattr(field, "repr", True) is not False (utils.py:267) reads as a typo for a truthiness check. It isn't — attrs permits repr=<callable>, which must be treated as enabled — but that's exactly the kind of non-obvious invariant that earns a short comment.

Recommendation

Request changes (minor) — every round-2 finding is genuinely fixed and the test suite now covers each one, so the helper itself is in good shape. Finding 1 is the only blocker: it's a compile-time SyntaxError on a shape users will hit immediately, and it's a small change to _sanitize_for_repr plus one test.

(branch: `anthonyb/triton_constexpr`)

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_models_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8)

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

Restack of #195044 onto main (via viable/strict), self-contained: the old
base was a snapshot of a since-abandoned stack, so this commit now FOLDS IN
the prerequisite layer that lived there (the compile_to_python extensions in
to_standalone_python.py, the backward-retrace machinery in graph_compile.py
/ runtime_wrappers.py / schemas.py, compiled_autograd and standalone_compile
support, and their tests), on top of the two typed-guard commits below it in
this stack. Review order: the prerequisite layer first (it is the bulk),
then torch/_precompile.py / _precompile_driver.py (the feature), then the
trunk reconciliation and fixes below.

Two reconciliations with trunk made during the restack:

- #189692 (non-builtin constexpr support for user Triton kernels) landed on
  trunk in parallel and overlapped this stack's constexpr rendering. The
  merge keeps trunk's get_importable_constexpr_types/get_constexpr_repr_children
  machinery in _inductor/utils.py and its launcher-side type imports in
  triton_heuristics.py (all of #189692's unit tests still pass), while this
  stack's rendering (_constexpr_source/_render_constexpr_mappings, which
  also emits importable-type references and feeds the autotune-cache
  matching) takes the wrapper.py kernel-emission sites; trunk's
  _sanitize_for_repr lost its only caller there and is removed along with
  its tests.

- Two latent bugs in the folded retrace machinery, previously masked by the
  old base and visible as CI failures (test_pow_backward_dynamic_symint_
  exponent, test_gan_repro_trying_to_backward_through_the_graph_a_second_
  time): the backward-time retrace re-ran the joint trace WITHOUT the
  compile-time ambient environment, so factory ops materialized real
  tensors inside fake tracing ("Please convert all Tensors to
  FakeTensors"). The retrace now enters the same contexts create_aot_state
  uses (fake mode from the recorded args, single-threaded autograd,
  preserved RNG, PhiloxStateTracker, saved-tensor hooks disabled). The
  folded runtime_wrappers.py was also missing _dealias_marked_returns,
  which its own folded tests reference; it is included with its call sites.

The feature itself is unchanged from #195044 (see that PR for the eleven
review rounds): example_inputs= tuples with the positional form kept for
compatibility; tracer="dynamo" capturing guarded specializations and
recompilations (automatic dynamic across examples, newest-first dispatch at
load); training=True with readable Inductor forward/backward source bridged
by an emitted autograd.Function; precompile.stateful for crash-safe
incremental capture from a caller-owned loop; environment guards dropped by
provenance with input guards retained; loud rejections for graph breaks,
closures, nn.Module / numpy arguments, overlapping storage, and
tensor-reachable globals.

Supersedes #195044.

Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 92 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/functorch/test_aotdispatch.py               # 3837 tests; 1 error = pre-existing trunk test needing LAPACK (absent in this local build), 55 expected failures
python test/inductor/test_compiled_autograd.py          # OK
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK (was failing)
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK (was failing)
python test/dynamo/test_guard_serialization.py          # 61 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/inductor/test_triton_heuristics.py          # OK (5 skipped)
python test/dynamo/test_backward_higher_order_ops.py    # OK
lintrunner <touched files>                              # ok
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: bec0fe1
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

Restack of #195044 onto main (via viable/strict), self-contained: the old
base was a snapshot of a since-abandoned stack, so this commit now FOLDS IN
the prerequisite layer that lived there (the compile_to_python extensions in
to_standalone_python.py, the backward-retrace machinery in graph_compile.py
/ runtime_wrappers.py / schemas.py, compiled_autograd and standalone_compile
support, and their tests), on top of the two typed-guard commits below it in
this stack. Review order: the prerequisite layer first (it is the bulk),
then torch/_precompile.py / _precompile_driver.py (the feature), then the
trunk reconciliation and fixes below.

Two reconciliations with trunk made during the restack:

- #189692 (non-builtin constexpr support for user Triton kernels) landed on
  trunk in parallel and overlapped this stack's constexpr rendering. The
  merge keeps trunk's get_importable_constexpr_types/get_constexpr_repr_children
  machinery in _inductor/utils.py and its launcher-side type imports in
  triton_heuristics.py (all of #189692's unit tests still pass), while this
  stack's rendering (_constexpr_source/_render_constexpr_mappings, which
  also emits importable-type references and feeds the autotune-cache
  matching) takes the wrapper.py kernel-emission sites; trunk's
  _sanitize_for_repr lost its only caller there and is removed along with
  its tests.

- Two latent bugs in the folded retrace machinery, previously masked by the
  old base and visible as CI failures (test_pow_backward_dynamic_symint_
  exponent, test_gan_repro_trying_to_backward_through_the_graph_a_second_
  time): the backward-time retrace re-ran the joint trace WITHOUT the
  compile-time ambient environment, so factory ops materialized real
  tensors inside fake tracing ("Please convert all Tensors to
  FakeTensors"). The retrace now enters the same contexts create_aot_state
  uses (fake mode from the recorded args, single-threaded autograd,
  preserved RNG, PhiloxStateTracker, saved-tensor hooks disabled). The
  folded runtime_wrappers.py was also missing _dealias_marked_returns,
  which its own folded tests reference; it is included with its call sites.

The feature itself is unchanged from #195044 (see that PR for the eleven
review rounds): example_inputs= tuples with the positional form kept for
compatibility; tracer="dynamo" capturing guarded specializations and
recompilations (automatic dynamic across examples, newest-first dispatch at
load); training=True with readable Inductor forward/backward source bridged
by an emitted autograd.Function; precompile.stateful for crash-safe
incremental capture from a caller-owned loop; environment guards dropped by
provenance with input guards retained; loud rejections for graph breaks,
closures, nn.Module / numpy arguments, overlapping storage, and
tensor-reachable globals.

Supersedes #195044.

Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 92 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/functorch/test_aotdispatch.py               # 3837 tests; 1 error = pre-existing trunk test needing LAPACK (absent in this local build), 55 expected failures
python test/inductor/test_compiled_autograd.py          # OK
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK (was failing)
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK (was failing)
python test/dynamo/test_guard_serialization.py          # 61 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/inductor/test_triton_heuristics.py          # OK (5 skipped)
python test/dynamo/test_backward_higher_order_ops.py    # OK
lintrunner <touched files>                              # ok
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: bec0fe1
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

Restack of #195044 onto main (via viable/strict), self-contained: the old
base was a snapshot of a since-abandoned stack, so this commit FOLDS IN the
prerequisite layer that lived there (the compile_to_python extensions in
to_standalone_python.py, the undefined-tangent/backward-retrace machinery in
graph_compile.py / runtime_wrappers.py / schemas.py, compiled_autograd and
standalone_compile support, and their tests), on top of the two typed-guard
commits below it in this stack. Review order: the prerequisite layer first
(it is the bulk), then torch/_precompile.py / _precompile_driver.py (the
feature), then the reconciliations and hardening below.

The folded undefined-tangent machinery is now OPT-IN
(torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
False): ordinary torch.compile keeps the zero-materialization backward
behavior, and precompile enables the flag during training capture. Emitted
training artifacts bake the enabled behavior at emission time and never
consult ambient config at load. A contract test pins that a default-config
partial backward never invokes the machinery and matches eager.

A workflow review round (8 finders, 3-lens adversarial verification per
finding, all empirically reproduced) hardened the machinery behind the flag:
the backward-time retrace now snapshots the compile-time autocast state and
falls back to the structural path on mismatch (an AMP forward with a partial
backward previously recompiled the backward under the caller's autocast
state and crashed or silently changed dtypes); the retrace runs the inductor
partitioner inside V.set_fake_mode and is wrapped in a warn-and-fall-back
exception guard (dropout graphs previously hard-crashed in
replace_random_passes); clearing bw_donated_idxs now also invalidates
donation-compiled specialized backwards (a stale donated variant could
bypass the retain_graph guard and corrupt gradients); the structural
specializer's pruned-zero folds require meta-matching fx.Node survivors
(custom backwards like g1+1 previously emitted a Python int gradient); and
masking a backward output to None now requires it to be PROVABLY zero
(affine custom backwards previously lost nonzero gradients silently) --
provably-safe-but-unprovable cases now materialize zero grads instead of
None, and the two subclass fallback tests accept either outcome. Each fix
carries a fail-first regression test.

Two reconciliations with trunk made during the restack: #189692 (non-builtin
constexpr support) is preserved -- constructor-repr rendering for importable
dataclass/attrs/pydantic-like constexpr configs now lives as a branch of
this stack's _constexpr_source_impl (rendered source is eval-verified to
rebuild the exact type before acceptance), while trunk's launcher-side
type-import loop is removed (the launcher binds constant objects directly;
the loop's validation spuriously rejected class-nested namedtuples and
name-shadowing types) and trunk's _sanitize_for_repr (whose only caller was
the replaced emission site) is removed with its tests; the previously
vacuous e2e test now compiles the kernel via @triton_op with fullgraph=True
and asserts the rendered constructor source. Second, two latent retrace bugs
previously masked by the old base were fixed (ambient-environment contexts
at backward-time retrace; the ported _dealias_marked_returns), and the
DTensor sharding-prop cache test isolation fix works around a pre-existing
trunk hazard (stale DeviceMesh across pg re-init).

The feature itself is unchanged from #195044 (see that PR for its review
history): example_inputs= tuples with the positional form kept for
compatibility; tracer="dynamo" capturing guarded specializations and
recompilations (automatic dynamic across examples, newest-first dispatch at
load); training=True with readable Inductor forward/backward source bridged
by an emitted autograd.Function; precompile.stateful for crash-safe
incremental capture from a caller-owned loop; environment guards dropped by
provenance with input guards retained; loud rejections for graph breaks,
closures, nn.Module / numpy arguments, overlapping storage, and
tensor-reachable globals.

Supersedes #195044.

Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 97 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: 1f52f73
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

Restack of #195044 onto main (via viable/strict), self-contained: the old
base was a snapshot of a since-abandoned stack, so this commit FOLDS IN the
prerequisite layer that lived there (the compile_to_python extensions in
to_standalone_python.py, the undefined-tangent/backward-retrace machinery in
graph_compile.py / runtime_wrappers.py / schemas.py, compiled_autograd and
standalone_compile support, and their tests), on top of the two typed-guard
commits below it in this stack. Review order: the prerequisite layer first
(it is the bulk), then torch/_precompile.py / _precompile_driver.py (the
feature), then the reconciliations and hardening below.

The folded undefined-tangent machinery is now OPT-IN
(torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
False): ordinary torch.compile keeps the zero-materialization backward
behavior, and precompile enables the flag during training capture. Emitted
training artifacts bake the enabled behavior at emission time and never
consult ambient config at load. A contract test pins that a default-config
partial backward never invokes the machinery and matches eager.

A workflow review round (8 finders, 3-lens adversarial verification per
finding, all empirically reproduced) hardened the machinery behind the flag:
the backward-time retrace now snapshots the compile-time autocast state and
falls back to the structural path on mismatch (an AMP forward with a partial
backward previously recompiled the backward under the caller's autocast
state and crashed or silently changed dtypes); the retrace runs the inductor
partitioner inside V.set_fake_mode and is wrapped in a warn-and-fall-back
exception guard (dropout graphs previously hard-crashed in
replace_random_passes); clearing bw_donated_idxs now also invalidates
donation-compiled specialized backwards (a stale donated variant could
bypass the retain_graph guard and corrupt gradients); the structural
specializer's pruned-zero folds require meta-matching fx.Node survivors
(custom backwards like g1+1 previously emitted a Python int gradient); and
masking a backward output to None now requires it to be PROVABLY zero
(affine custom backwards previously lost nonzero gradients silently) --
provably-safe-but-unprovable cases now materialize zero grads instead of
None, and the two subclass fallback tests accept either outcome. Each fix
carries a fail-first regression test.

Two reconciliations with trunk made during the restack: #189692 (non-builtin
constexpr support) is preserved -- constructor-repr rendering for importable
dataclass/attrs/pydantic-like constexpr configs now lives as a branch of
this stack's _constexpr_source_impl (rendered source is eval-verified to
rebuild the exact type before acceptance), while trunk's launcher-side
type-import loop is removed (the launcher binds constant objects directly;
the loop's validation spuriously rejected class-nested namedtuples and
name-shadowing types) and trunk's _sanitize_for_repr (whose only caller was
the replaced emission site) is removed with its tests; the previously
vacuous e2e test now compiles the kernel via @triton_op with fullgraph=True
and asserts the rendered constructor source. Second, two latent retrace bugs
previously masked by the old base were fixed (ambient-environment contexts
at backward-time retrace; the ported _dealias_marked_returns), and the
DTensor sharding-prop cache test isolation fix works around a pre-existing
trunk hazard (stale DeviceMesh across pg re-init).

The feature itself is unchanged from #195044 (see that PR for its review
history): example_inputs= tuples with the positional form kept for
compatibility; tracer="dynamo" capturing guarded specializations and
recompilations (automatic dynamic across examples, newest-first dispatch at
load); training=True with readable Inductor forward/backward source bridged
by an emitted autograd.Function; precompile.stateful for crash-safe
incremental capture from a caller-owned loop; environment guards dropped by
provenance with input guards retained; loud rejections for graph breaks,
closures, nn.Module / numpy arguments, overlapping storage, and
tensor-reachable globals.

Supersedes #195044.

Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 97 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: 1f52f73
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

Restack of #195044 onto main (via viable/strict), self-contained: the old
base was a snapshot of a since-abandoned stack, so this commit FOLDS IN the
prerequisite layer that lived there (the compile_to_python extensions in
to_standalone_python.py, the undefined-tangent/backward-retrace machinery in
graph_compile.py / runtime_wrappers.py / schemas.py, compiled_autograd and
standalone_compile support, and their tests), on top of the two typed-guard
commits below it in this stack. Review order: the prerequisite layer first
(it is the bulk), then torch/_precompile.py / _precompile_driver.py (the
feature), then the reconciliations and hardening below.

The folded undefined-tangent machinery is now OPT-IN
(torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
False): ordinary torch.compile keeps the zero-materialization backward
behavior, and precompile enables the flag during training capture. Emitted
training artifacts bake the enabled behavior at emission time and never
consult ambient config at load. A contract test pins that a default-config
partial backward never invokes the machinery and matches eager.

A workflow review round (8 finders, 3-lens adversarial verification per
finding, all empirically reproduced) hardened the machinery behind the flag:
the backward-time retrace now snapshots the compile-time autocast state and
falls back to the structural path on mismatch (an AMP forward with a partial
backward previously recompiled the backward under the caller's autocast
state and crashed or silently changed dtypes); the retrace runs the inductor
partitioner inside V.set_fake_mode and is wrapped in a warn-and-fall-back
exception guard (dropout graphs previously hard-crashed in
replace_random_passes); clearing bw_donated_idxs now also invalidates
donation-compiled specialized backwards (a stale donated variant could
bypass the retain_graph guard and corrupt gradients); the structural
specializer's pruned-zero folds require meta-matching fx.Node survivors
(custom backwards like g1+1 previously emitted a Python int gradient); and
masking a backward output to None now requires it to be PROVABLY zero
(affine custom backwards previously lost nonzero gradients silently) --
provably-safe-but-unprovable cases now materialize zero grads instead of
None, and the two subclass fallback tests accept either outcome. Each fix
carries a fail-first regression test.

Two reconciliations with trunk made during the restack: #189692 (non-builtin
constexpr support) is preserved -- constructor-repr rendering for importable
dataclass/attrs/pydantic-like constexpr configs now lives as a branch of
this stack's _constexpr_source_impl (rendered source is eval-verified to
rebuild the exact type before acceptance), while trunk's launcher-side
type-import loop is removed (the launcher binds constant objects directly;
the loop's validation spuriously rejected class-nested namedtuples and
name-shadowing types) and trunk's _sanitize_for_repr (whose only caller was
the replaced emission site) is removed with its tests; the previously
vacuous e2e test now compiles the kernel via @triton_op with fullgraph=True
and asserts the rendered constructor source. Second, two latent retrace bugs
previously masked by the old base were fixed (ambient-environment contexts
at backward-time retrace; the ported _dealias_marked_returns), and the
DTensor sharding-prop cache test isolation fix works around a pre-existing
trunk hazard (stale DeviceMesh across pg re-init).

The feature itself is unchanged from #195044 (see that PR for its review
history): example_inputs= tuples with the positional form kept for
compatibility; tracer="dynamo" capturing guarded specializations and
recompilations (automatic dynamic across examples, newest-first dispatch at
load); training=True with readable Inductor forward/backward source bridged
by an emitted autograd.Function; precompile.stateful for crash-safe
incremental capture from a caller-owned loop; environment guards dropped by
provenance with input guards retained; loud rejections for graph breaks,
closures, nn.Module / numpy arguments, overlapping storage, and
tensor-reachable globals.

CI-portability fixes from the first trunk-based CI round: the emitted
training artifact's RNG tracker is now written as a constructor call instead
of a pickled object (its itertools.count default is unpicklable on Python >=
3.14); the dedup training test is skipped under dynamo-wrapped testing
(compiled autograd deliberately rejects the artifact's boxed backward); and
the fresh-process artifact test is skipped under crossref (the mode is part
of the captured environment, so the plain subprocess correctly fails the
environment-invariant contract). The PR carries skip-pr-sanity-checks for
the 2000-LOC limit.

Supersedes #195044.

Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 97 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: 2bf4c63
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

Restack of #195044 onto main (via viable/strict), self-contained: the old
base was a snapshot of a since-abandoned stack, so this commit FOLDS IN the
prerequisite layer that lived there (the compile_to_python extensions in
to_standalone_python.py, the undefined-tangent/backward-retrace machinery in
graph_compile.py / runtime_wrappers.py / schemas.py, compiled_autograd and
standalone_compile support, and their tests), on top of the two typed-guard
commits below it in this stack. Review order: the prerequisite layer first
(it is the bulk), then torch/_precompile.py / _precompile_driver.py (the
feature), then the reconciliations and hardening below.

The folded undefined-tangent machinery is now OPT-IN
(torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
False): ordinary torch.compile keeps the zero-materialization backward
behavior, and precompile enables the flag during training capture. Emitted
training artifacts bake the enabled behavior at emission time and never
consult ambient config at load. A contract test pins that a default-config
partial backward never invokes the machinery and matches eager.

A workflow review round (8 finders, 3-lens adversarial verification per
finding, all empirically reproduced) hardened the machinery behind the flag:
the backward-time retrace now snapshots the compile-time autocast state and
falls back to the structural path on mismatch (an AMP forward with a partial
backward previously recompiled the backward under the caller's autocast
state and crashed or silently changed dtypes); the retrace runs the inductor
partitioner inside V.set_fake_mode and is wrapped in a warn-and-fall-back
exception guard (dropout graphs previously hard-crashed in
replace_random_passes); clearing bw_donated_idxs now also invalidates
donation-compiled specialized backwards (a stale donated variant could
bypass the retain_graph guard and corrupt gradients); the structural
specializer's pruned-zero folds require meta-matching fx.Node survivors
(custom backwards like g1+1 previously emitted a Python int gradient); and
masking a backward output to None now requires it to be PROVABLY zero
(affine custom backwards previously lost nonzero gradients silently) --
provably-safe-but-unprovable cases now materialize zero grads instead of
None, and the two subclass fallback tests accept either outcome. Each fix
carries a fail-first regression test.

Two reconciliations with trunk made during the restack: #189692 (non-builtin
constexpr support) is preserved -- constructor-repr rendering for importable
dataclass/attrs/pydantic-like constexpr configs now lives as a branch of
this stack's _constexpr_source_impl (rendered source is eval-verified to
rebuild the exact type before acceptance), while trunk's launcher-side
type-import loop is removed (the launcher binds constant objects directly;
the loop's validation spuriously rejected class-nested namedtuples and
name-shadowing types) and trunk's _sanitize_for_repr (whose only caller was
the replaced emission site) is removed with its tests; the previously
vacuous e2e test now compiles the kernel via @triton_op with fullgraph=True
and asserts the rendered constructor source. Second, two latent retrace bugs
previously masked by the old base were fixed (ambient-environment contexts
at backward-time retrace; the ported _dealias_marked_returns), and the
DTensor sharding-prop cache test isolation fix works around a pre-existing
trunk hazard (stale DeviceMesh across pg re-init).

The feature itself is unchanged from #195044 (see that PR for its review
history): example_inputs= tuples with the positional form kept for
compatibility; tracer="dynamo" capturing guarded specializations and
recompilations (automatic dynamic across examples, newest-first dispatch at
load); training=True with readable Inductor forward/backward source bridged
by an emitted autograd.Function; precompile.stateful for crash-safe
incremental capture from a caller-owned loop; environment guards dropped by
provenance with input guards retained; loud rejections for graph breaks,
closures, nn.Module / numpy arguments, overlapping storage, and
tensor-reachable globals.

CI-portability fixes from the first trunk-based CI round: the emitted
training artifact's RNG tracker is now written as a constructor call instead
of a pickled object (its itertools.count default is unpicklable on Python >=
3.14); the dedup training test is skipped under dynamo-wrapped testing
(compiled autograd deliberately rejects the artifact's boxed backward); and
the fresh-process artifact test is skipped under crossref (the mode is part
of the captured environment, so the plain subprocess correctly fails the
environment-invariant contract). The PR carries skip-pr-sanity-checks for
the 2000-LOC limit.

Supersedes #195044.

Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 97 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: 2bf4c63
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

torch.compiler.precompile lowers a whole computation ahead of time to a
self-contained, runnable Python source string plus a binary acceleration
cache, and reloads it with precompile.load -- no compiler in the serving
process, no weights baked into the artifact, and the artifact is auditable
text rather than an opaque binary. Until now it captured exactly one
execution through make_fx: control flow and shapes were specialized to a
single example call. This PR generalizes the API to a SET of observed calls
and adds a Dynamo capture front-end:

- example_inputs= takes a sequence of positional-argument tuples (the
  existing positional form keeps working as a single example call; make_fx
  remains the default tracer and requires exactly one tuple).

- tracer="dynamo" executes every example tuple under Dynamo and captures
  each guarded specialization and recompilation it produces, including the
  automatically dynamic graphs that appear when a dimension varies across
  examples (one isolated capture session with a private PGO record, so the
  result is deterministic regardless of process history). At serve time the
  artifact dispatches among the captured variants by guard check, newest
  variant first, and never compiles: a call no variant covers raises.
  Guards derived from explicit inputs are retained for dispatch, classified
  by their typed provenance (the commit below in this stack); guards on the
  Python environment may be dropped, since the environment is a declared
  caller invariant. Unsupported inputs are rejected loudly at capture:
  graph breaks, closures, nn.Module / numpy arguments, tensor inputs with
  overlapping storage, tensor-reachable globals, and global-mutating
  functions.

- training=True (dynamo + inductor) captures differentiable graphs: each
  compiled segment carries readable Inductor source for its AOTAutograd
  forward and backward, bridged by an emitted torch.autograd.Function, so
  served outputs retain grad_fn and backward() runs the precompiled
  kernels. Backward variants are specialized to the output-tangent patterns
  observed during capture (the all-tangents-defined pattern is always
  covered); an unseen pattern fails instead of compiling at runtime.

- precompile.stateful captures incrementally from a loop the caller owns
  (e.g. a pipelined train step that precompile cannot drive itself): every
  call runs its example tuples for real, accumulates newly exercised
  variants into an opaque resumable state, and atomically rewrites an
  always-loadable artifact/cache pair on disk, so a job that dies mid-loop
  keeps a working artifact for the batches it saw.

Supporting machinery introduced by this PR, and why it is safe for everyone
else:

- compile_to_python (to_standalone_python.py) renders AOTAutograd
  forward/backward pairs as standalone Python source, with values emitted as
  auditable source expressions rather than pickle blobs (training artifacts
  bake their behavior at emission time and never consult ambient config at
  load).

- An undefined-tangent backward-specialization layer in AOTAutograd
  (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a
  variant specialized to which output tangents are undefined, retracing or
  structurally pruning the backward per observed pattern. It is OPT-IN:
  torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
  False, ordinary torch.compile keeps the existing zero-materialization
  backward behavior (a contract test pins this), and precompile enables the
  flag only during training capture. Behind the flag the layer reconciles
  autocast state at retrace time, runs the partitioner inside inductor's
  virtualized context with a fall-back exception guard, invalidates
  specialized backwards when donation state changes, and only prunes
  gradients it can prove are zero -- each property carried by a fail-first
  regression test.

- User-defined Triton kernel constexprs render as importable, eval-verified
  source (enums, containers, torch.Size, and constructor-repr'able
  dataclass/attrs/pydantic-style configs), with autotune-cache matching that
  round-trips tuple-valued config kwargs type-faithfully and an async-compile
  fallback when a worker cannot import a constexpr's module.

Suggested review order: to_standalone_python.py and the runtime_wrappers.py
/ graph_compile.py layer first (the bulk), then torch/_precompile.py and
torch/_precompile_driver.py (the API, the capture pipeline, and the emitted
serve-time driver), then the inductor constexpr/autotune changes, then
tests and docs.

Supersedes #195044. Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 97 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: 2bf4c63
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

torch.compiler.precompile lowers a whole computation ahead of time to a
self-contained, runnable Python source string plus a binary acceleration
cache, and reloads it with precompile.load -- no compiler in the serving
process, no weights baked into the artifact, and the artifact is auditable
text rather than an opaque binary. Until now it captured exactly one
execution through make_fx: control flow and shapes were specialized to a
single example call. This PR generalizes the API to a SET of observed calls
and adds a Dynamo capture front-end:

- example_inputs= takes a sequence of positional-argument tuples (the
  existing positional form keeps working as a single example call; make_fx
  remains the default tracer and requires exactly one tuple).

- tracer="dynamo" executes every example tuple under Dynamo and captures
  each guarded specialization and recompilation it produces, including the
  automatically dynamic graphs that appear when a dimension varies across
  examples (one isolated capture session with a private PGO record, so the
  result is deterministic regardless of process history). At serve time the
  artifact dispatches among the captured variants by guard check, newest
  variant first, and never compiles: a call no variant covers raises.
  Guards derived from explicit inputs are retained for dispatch, classified
  by their typed provenance (the commit below in this stack); guards on the
  Python environment may be dropped, since the environment is a declared
  caller invariant. Unsupported inputs are rejected loudly at capture:
  graph breaks, closures, nn.Module / numpy arguments, tensor inputs with
  overlapping storage, tensor-reachable globals, and global-mutating
  functions.

- With the inductor backend, differentiability is inferred per captured
  graph exactly as torch.compile infers it: capture runs grad-enabled, and a
  graph whose inputs require grad is compiled differentiable (no-grad inputs
  stay inference graphs; requires_grad is guarded per input, so a flipped
  input fails dispatch loudly; the eager backend always captures inference).
  For each differentiable graph, each
  compiled segment carries readable Inductor source for its AOTAutograd
  forward and backward, bridged by an emitted torch.autograd.Function, so
  served outputs retain grad_fn and backward() runs the precompiled
  kernels. Backward variants are specialized to the output-tangent patterns
  observed during capture (the all-tangents-defined pattern is always
  covered); an unseen pattern fails instead of compiling at runtime.

- precompile.stateful captures incrementally from a loop the caller owns
  (e.g. a pipelined train step that precompile cannot drive itself): every
  call runs its example tuples for real, accumulates newly exercised
  variants into an opaque resumable state, and atomically rewrites an
  always-loadable artifact/cache pair on disk, so a job that dies mid-loop
  keeps a working artifact for the batches it saw.

Supporting machinery introduced by this PR, and why it is safe for everyone
else:

- compile_to_python (to_standalone_python.py) renders AOTAutograd
  forward/backward pairs as standalone Python source, with values emitted as
  auditable source expressions rather than pickle blobs (training artifacts
  bake their behavior at emission time and never consult ambient config at
  load).

- An undefined-tangent backward-specialization layer in AOTAutograd
  (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a
  variant specialized to which output tangents are undefined, retracing or
  structurally pruning the backward per observed pattern. It is OPT-IN:
  torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
  False, ordinary torch.compile keeps the existing zero-materialization
  backward behavior (a contract test pins this), and precompile enables the
  flag only during dynamo-inductor capture. Behind the flag the layer reconciles
  autocast state at retrace time, runs the partitioner inside inductor's
  virtualized context with a fall-back exception guard, invalidates
  specialized backwards when donation state changes, and only prunes
  gradients it can prove are zero -- each property carried by a fail-first
  regression test.

- User-defined Triton kernel constexprs render as importable, eval-verified
  source (enums, containers, torch.Size, and constructor-repr'able
  dataclass/attrs/pydantic-style configs), with autotune-cache matching that
  round-trips tuple-valued config kwargs type-faithfully and an async-compile
  fallback when a worker cannot import a constexpr's module.

Suggested review order: to_standalone_python.py and the runtime_wrappers.py
/ graph_compile.py layer first (the bulk), then torch/_precompile.py and
torch/_precompile_driver.py (the API, the capture pipeline, and the emitted
serve-time driver), then the inductor constexpr/autotune changes, then
tests and docs.

Supersedes #195044. Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 97 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: 99c13fb
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

torch.compiler.precompile lowers a whole computation ahead of time to a
self-contained, runnable Python source string plus a binary acceleration
cache, and reloads it with precompile.load -- no compiler in the serving
process, no weights baked into the artifact, and the artifact is auditable
text rather than an opaque binary. Until now it captured exactly one
execution through make_fx: control flow and shapes were specialized to a
single example call. This PR generalizes the API to a SET of observed calls
and adds a Dynamo capture front-end:

- example_inputs= takes a sequence of positional-argument tuples (the
  existing positional form keeps working as a single example call; make_fx
  remains the default tracer and requires exactly one tuple).

- tracer="dynamo" executes every example tuple under Dynamo and captures
  each guarded specialization and recompilation it produces, including the
  automatically dynamic graphs that appear when a dimension varies across
  examples (one isolated capture session with a private PGO record, so the
  result is deterministic regardless of process history). At serve time the
  artifact dispatches among the captured variants by guard check, newest
  variant first, and never compiles: a call no variant covers raises.
  Guards derived from explicit inputs are retained for dispatch, classified
  by their typed provenance (the commit below in this stack); guards on the
  Python environment may be dropped, since the environment is a declared
  caller invariant. Unsupported inputs are rejected loudly at capture:
  graph breaks, closures, nn.Module / numpy arguments, tensor inputs with
  overlapping storage, tensor-reachable globals, and global-mutating
  functions.

- With the inductor backend, differentiability is inferred per captured
  graph exactly as torch.compile infers it: capture runs grad-enabled, and a
  graph whose inputs require grad is compiled differentiable (no-grad inputs
  stay inference graphs; requires_grad is guarded per input, so a flipped
  input fails dispatch loudly; the eager backend always captures inference).
  For each differentiable graph, each
  compiled segment carries readable Inductor source for its AOTAutograd
  forward and backward, bridged by an emitted torch.autograd.Function, so
  served outputs retain grad_fn and backward() runs the precompiled
  kernels. Backward variants are specialized to the output-tangent patterns
  observed during capture (the all-tangents-defined pattern is always
  covered); an unseen pattern fails instead of compiling at runtime.

- precompile.stateful captures incrementally from a loop the caller owns
  (e.g. a pipelined train step that precompile cannot drive itself): every
  call runs its example tuples for real, accumulates newly exercised
  variants into an opaque resumable state, and atomically rewrites an
  always-loadable artifact/cache pair on disk, so a job that dies mid-loop
  keeps a working artifact for the batches it saw.

Supporting machinery introduced by this PR, and why it is safe for everyone
else:

- compile_to_python (to_standalone_python.py) renders AOTAutograd
  forward/backward pairs as standalone Python source, with values emitted as
  auditable source expressions rather than pickle blobs (training artifacts
  bake their behavior at emission time and never consult ambient config at
  load).

- An undefined-tangent backward-specialization layer in AOTAutograd
  (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a
  variant specialized to which output tangents are undefined, retracing or
  structurally pruning the backward per observed pattern. It is OPT-IN:
  torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
  False, ordinary torch.compile keeps the existing zero-materialization
  backward behavior (a contract test pins this), and precompile enables the
  flag only during dynamo-inductor capture. Behind the flag the layer reconciles
  autocast state at retrace time, runs the partitioner inside inductor's
  virtualized context with a fall-back exception guard, invalidates
  specialized backwards when donation state changes, and only prunes
  gradients it can prove are zero -- each property carried by a fail-first
  regression test.

- User-defined Triton kernel constexprs render as importable, eval-verified
  source (enums, containers, torch.Size, and constructor-repr'able
  dataclass/attrs/pydantic-style configs), with autotune-cache matching that
  round-trips tuple-valued config kwargs type-faithfully and an async-compile
  fallback when a worker cannot import a constexpr's module.

Suggested review order: to_standalone_python.py and the runtime_wrappers.py
/ graph_compile.py layer first (the bulk), then torch/_precompile.py and
torch/_precompile_driver.py (the API, the capture pipeline, and the emitted
serve-time driver), then the inductor constexpr/autotune changes, then
tests and docs.

Supersedes #195044. Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 97 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: 99c13fb
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

torch.compiler.precompile lowers a whole computation ahead of time to a
self-contained, runnable Python source string plus a binary acceleration
cache, and reloads it with precompile.load -- no compiler in the serving
process, no weights baked into the artifact, and the artifact is auditable
text rather than an opaque binary. Until now it captured exactly one
execution through make_fx: control flow and shapes were specialized to a
single example call. This PR generalizes the API to a SET of observed calls
and adds a Dynamo capture front-end:

- example_inputs= takes a sequence of positional-argument tuples (the
  existing positional form keeps working as a single example call; make_fx
  remains the default tracer and requires exactly one tuple).

- tracer="dynamo" executes every example tuple under Dynamo and captures
  each guarded specialization and recompilation it produces, including the
  automatically dynamic graphs that appear when a dimension varies across
  examples (one isolated capture session with a private PGO record, so the
  result is deterministic regardless of process history). At serve time the
  artifact dispatches among the captured variants by guard check, newest
  variant first, and never compiles: a call no variant covers raises.
  Guards derived from explicit inputs are retained for dispatch, classified
  by their typed provenance (the commit below in this stack); guards on the
  Python environment may be dropped, since the environment is a declared
  caller invariant. Unsupported inputs are rejected loudly at capture:
  graph breaks, closures, nn.Module / numpy arguments, tensor inputs with
  overlapping storage, tensor-reachable globals, and global-mutating
  functions.

- Differentiability is inferred per captured graph exactly as torch.compile
  infers it: capture runs grad-enabled, and a graph whose inputs require
  grad is differentiable (no-grad inputs stay inference graphs;
  requires_grad is guarded per input, so a flipped input fails dispatch
  loudly). On the inductor backend the backward is precompiled; on the eager
  backend it is live eager autograd through the emitted ops -- neither
  captured nor specialized, like torch.compile(backend="eager"). For each
  inductor differentiable graph, each
  compiled segment carries readable Inductor source for its AOTAutograd
  forward and backward, bridged by an emitted torch.autograd.Function, so
  served outputs retain grad_fn and backward() runs the precompiled
  kernels. Backward variants are specialized to the output-tangent patterns
  observed during capture (the all-tangents-defined pattern is always
  covered); an unseen pattern fails instead of compiling at runtime.

- precompile.stateful captures incrementally from a loop the caller owns
  (e.g. a pipelined train step that precompile cannot drive itself): every
  call runs its example tuples for real, accumulates newly exercised
  variants into an opaque resumable state, and atomically rewrites an
  always-loadable artifact/cache pair on disk, so a job that dies mid-loop
  keeps a working artifact for the batches it saw.

Supporting machinery introduced by this PR, and why it is safe for everyone
else:

- compile_to_python (to_standalone_python.py) renders AOTAutograd
  forward/backward pairs as standalone Python source, with values emitted as
  auditable source expressions rather than pickle blobs (training artifacts
  bake their behavior at emission time and never consult ambient config at
  load).

- An undefined-tangent backward-specialization layer in AOTAutograd
  (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a
  variant specialized to which output tangents are undefined, retracing or
  structurally pruning the backward per observed pattern. It is OPT-IN:
  torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
  False, ordinary torch.compile keeps the existing zero-materialization
  backward behavior (a contract test pins this), and precompile enables the
  flag only during dynamo-inductor capture. Behind the flag the layer reconciles
  autocast state at retrace time, runs the partitioner inside inductor's
  virtualized context with a fall-back exception guard, invalidates
  specialized backwards when donation state changes, and only prunes
  gradients it can prove are zero -- each property carried by a fail-first
  regression test.

- User-defined Triton kernel constexprs render as importable, eval-verified
  source (enums, containers, torch.Size, and constructor-repr'able
  dataclass/attrs/pydantic-style configs), with autotune-cache matching that
  round-trips tuple-valued config kwargs type-faithfully and an async-compile
  fallback when a worker cannot import a constexpr's module.

Suggested review order: to_standalone_python.py and the runtime_wrappers.py
/ graph_compile.py layer first (the bulk), then torch/_precompile.py and
torch/_precompile_driver.py (the API, the capture pipeline, and the emitted
serve-time driver), then the inductor constexpr/autotune changes, then
tests and docs.

Supersedes #195044. Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 97 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: af74acd
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

torch.compiler.precompile lowers a whole computation ahead of time to a
self-contained, runnable Python source string plus a binary acceleration
cache, and reloads it with precompile.load -- no compiler in the serving
process, no weights baked into the artifact, and the artifact is auditable
text rather than an opaque binary. Until now it captured exactly one
execution through make_fx: control flow and shapes were specialized to a
single example call. This PR generalizes the API to a SET of observed calls
and adds a Dynamo capture front-end:

- example_inputs= takes a sequence of positional-argument tuples (the
  existing positional form keeps working as a single example call; make_fx
  remains the default tracer and requires exactly one tuple).

- tracer="dynamo" executes every example tuple under Dynamo and captures
  each guarded specialization and recompilation it produces, including the
  automatically dynamic graphs that appear when a dimension varies across
  examples (one isolated capture session with a private PGO record, so the
  result is deterministic regardless of process history). At serve time the
  artifact dispatches among the captured variants by guard check, newest
  variant first, and never compiles: a call no variant covers raises.
  Guards derived from explicit inputs are retained for dispatch, classified
  by their typed provenance (the commit below in this stack); guards on the
  Python environment may be dropped, since the environment is a declared
  caller invariant. Unsupported inputs are rejected loudly at capture:
  graph breaks, closures, nn.Module / numpy arguments, tensor inputs with
  overlapping storage, tensor-reachable globals, and global-mutating
  functions.

- Differentiability is inferred per captured graph exactly as torch.compile
  infers it: capture runs grad-enabled, and a graph whose inputs require
  grad is differentiable (no-grad inputs stay inference graphs;
  requires_grad is guarded per input, so a flipped input fails dispatch
  loudly). On the inductor backend the backward is precompiled; on the eager
  backend it is live eager autograd through the emitted ops -- neither
  captured nor specialized, like torch.compile(backend="eager"). For each
  inductor differentiable graph, each
  compiled segment carries readable Inductor source for its AOTAutograd
  forward and backward, bridged by an emitted torch.autograd.Function, so
  served outputs retain grad_fn and backward() runs the precompiled
  kernels. Backward variants are specialized to the output-tangent patterns
  observed during capture (the all-tangents-defined pattern is always
  covered); an unseen pattern fails instead of compiling at runtime.

- precompile.stateful captures incrementally from a loop the caller owns
  (e.g. a pipelined train step that precompile cannot drive itself): every
  call runs its example tuples for real, accumulates newly exercised
  variants into an opaque resumable state, and atomically rewrites an
  always-loadable artifact/cache pair on disk, so a job that dies mid-loop
  keeps a working artifact for the batches it saw.

Supporting machinery introduced by this PR, and why it is safe for everyone
else:

- compile_to_python (to_standalone_python.py) renders AOTAutograd
  forward/backward pairs as standalone Python source, with values emitted as
  auditable source expressions rather than pickle blobs (training artifacts
  bake their behavior at emission time and never consult ambient config at
  load).

- An undefined-tangent backward-specialization layer in AOTAutograd
  (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a
  variant specialized to which output tangents are undefined, retracing or
  structurally pruning the backward per observed pattern. It is OPT-IN:
  torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
  False, ordinary torch.compile keeps the existing zero-materialization
  backward behavior (a contract test pins this), and precompile enables the
  flag only during dynamo-inductor capture. Behind the flag the layer reconciles
  autocast state at retrace time, runs the partitioner inside inductor's
  virtualized context with a fall-back exception guard, invalidates
  specialized backwards when donation state changes, and only prunes
  gradients it can prove are zero -- each property carried by a fail-first
  regression test.

- User-defined Triton kernel constexprs render as importable, eval-verified
  source (enums, containers, torch.Size, and constructor-repr'able
  dataclass/attrs/pydantic-style configs), with autotune-cache matching that
  round-trips tuple-valued config kwargs type-faithfully and an async-compile
  fallback when a worker cannot import a constexpr's module.

Suggested review order: to_standalone_python.py and the runtime_wrappers.py
/ graph_compile.py layer first (the bulk), then torch/_precompile.py and
torch/_precompile_driver.py (the API, the capture pipeline, and the emitted
serve-time driver), then the inductor constexpr/autotune changes, then
tests and docs.

Supersedes #195044. Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 97 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: af74acd
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

torch.compiler.precompile lowers a whole computation ahead of time to a
self-contained, runnable Python source string plus a binary acceleration
cache, and reloads it with precompile.load -- no compiler in the serving
process, no weights baked into the artifact, and the artifact is auditable
text rather than an opaque binary. Until now it captured exactly one
execution through make_fx: control flow and shapes were specialized to a
single example call. This PR generalizes the API to a SET of observed calls
and adds a Dynamo capture front-end:

- example_inputs= takes a sequence of positional-argument tuples (the
  existing positional form keeps working as a single example call; make_fx
  remains the default tracer and requires exactly one tuple).

- tracer="dynamo" executes every example tuple under Dynamo and captures
  each guarded specialization and recompilation it produces, including the
  automatically dynamic graphs that appear when a dimension varies across
  examples (one isolated capture session with a private PGO record, so the
  result is deterministic regardless of process history). At serve time the
  artifact dispatches among the captured variants by guard check, newest
  variant first, and never compiles: a call no variant covers raises.
  Guards derived from explicit inputs are retained for dispatch, classified
  by their typed provenance (the commit below in this stack); guards on the
  Python environment may be dropped, since the environment is a declared
  caller invariant. Unsupported inputs are rejected loudly at capture:
  graph breaks, closures, nn.Module / numpy arguments, tensor inputs with
  overlapping storage, tensor-reachable globals, and global-mutating
  functions.

- Differentiability is inferred per captured graph exactly as torch.compile
  infers it: capture runs grad-enabled, and a graph whose inputs require
  grad is differentiable (no-grad inputs stay inference graphs;
  requires_grad is guarded per input, so a flipped input fails dispatch
  loudly). On the inductor backend the backward is precompiled; on the eager
  backend it is live eager autograd through the emitted ops -- neither
  captured nor specialized, like torch.compile(backend="eager"). For each
  inductor differentiable graph, each
  compiled segment carries readable Inductor source for its AOTAutograd
  forward and backward, bridged by an emitted torch.autograd.Function, so
  served outputs retain grad_fn and backward() runs the precompiled
  kernels. Backward variants are specialized to the output-tangent patterns
  observed during capture (the all-tangents-defined pattern is always
  covered); an unseen pattern fails instead of compiling at runtime.

- precompile.stateful captures incrementally from a loop the caller owns
  (e.g. a pipelined train step that precompile cannot drive itself): every
  call runs its example tuples for real, accumulates newly exercised
  variants into an opaque resumable state, and atomically rewrites an
  always-loadable artifact/cache pair on disk, so a job that dies mid-loop
  keeps a working artifact for the batches it saw.

Supporting machinery introduced by this PR, and why it is safe for everyone
else:

- compile_to_python (to_standalone_python.py) renders AOTAutograd
  forward/backward pairs as standalone Python source, with values emitted as
  auditable source expressions rather than pickle blobs (training artifacts
  bake their behavior at emission time and never consult ambient config at
  load).

- An undefined-tangent backward-specialization layer in AOTAutograd
  (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a
  variant specialized to which output tangents are undefined, retracing or
  structurally pruning the backward per observed pattern. It is OPT-IN:
  torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
  False, ordinary torch.compile keeps the existing zero-materialization
  backward behavior (a contract test pins this), and precompile enables the
  flag only during dynamo-inductor capture. Behind the flag the layer reconciles
  autocast state at retrace time, runs the partitioner inside inductor's
  virtualized context with a fall-back exception guard, invalidates
  specialized backwards when donation state changes, and only prunes
  gradients it can prove are zero -- each property carried by a fail-first
  regression test.

- User-defined Triton kernel constexprs render as importable, eval-verified
  source (enums, containers, torch.Size, and constructor-repr'able
  dataclass/attrs/pydantic-style configs), with autotune-cache matching that
  round-trips tuple-valued config kwargs type-faithfully and an async-compile
  fallback when a worker cannot import a constexpr's module.

Suggested review order: to_standalone_python.py and the runtime_wrappers.py
/ graph_compile.py layer first (the bulk), then torch/_precompile.py and
torch/_precompile_driver.py (the API, the capture pipeline, and the emitted
serve-time driver), then the inductor constexpr/autotune changes, then
tests and docs.

Supersedes #195044. Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 97 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: 55e2e88
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…nt-end, and support stateful incremental capture

torch.compiler.precompile lowers a whole computation ahead of time to a
self-contained, runnable Python source string plus a binary acceleration
cache, and reloads it with precompile.load -- no compiler in the serving
process, no weights baked into the artifact, and the artifact is auditable
text rather than an opaque binary. Until now it captured exactly one
execution through make_fx: control flow and shapes were specialized to a
single example call. This PR generalizes the API to a SET of observed calls
and adds a Dynamo capture front-end:

- example_inputs= takes a sequence of positional-argument tuples (the
  existing positional form keeps working as a single example call; make_fx
  remains the default tracer and requires exactly one tuple).

- tracer="dynamo" executes every example tuple under Dynamo and captures
  each guarded specialization and recompilation it produces, including the
  automatically dynamic graphs that appear when a dimension varies across
  examples (one isolated capture session with a private PGO record, so the
  result is deterministic regardless of process history). At serve time the
  artifact dispatches among the captured variants by guard check, newest
  variant first, and never compiles: a call no variant covers raises.
  Guards derived from explicit inputs are retained for dispatch, classified
  by their typed provenance (the commit below in this stack); guards on the
  Python environment may be dropped, since the environment is a declared
  caller invariant. Unsupported inputs are rejected loudly at capture:
  graph breaks, closures, nn.Module / numpy arguments, tensor inputs with
  overlapping storage, tensor-reachable globals, and global-mutating
  functions.

- Differentiability is inferred per captured graph exactly as torch.compile
  infers it: capture runs grad-enabled, and a graph whose inputs require
  grad is differentiable (no-grad inputs stay inference graphs;
  requires_grad is guarded per input, so a flipped input fails dispatch
  loudly). On the inductor backend the backward is precompiled; on the eager
  backend it is live eager autograd through the emitted ops -- neither
  captured nor specialized, like torch.compile(backend="eager"). For each
  inductor differentiable graph, each
  compiled segment carries readable Inductor source for its AOTAutograd
  forward and backward, bridged by an emitted torch.autograd.Function, so
  served outputs retain grad_fn and backward() runs the precompiled
  kernels. Backward variants are specialized to the output-tangent patterns
  observed during capture (the all-tangents-defined pattern is always
  covered); an unseen pattern fails instead of compiling at runtime.

- precompile.stateful captures incrementally from a loop the caller owns
  (e.g. a pipelined train step that precompile cannot drive itself): every
  call runs its example tuples for real, accumulates newly exercised
  variants into an opaque resumable state, and atomically rewrites an
  always-loadable artifact/cache pair on disk, so a job that dies mid-loop
  keeps a working artifact for the batches it saw.

Supporting machinery introduced by this PR, and why it is safe for everyone
else:

- compile_to_python (to_standalone_python.py) renders AOTAutograd
  forward/backward pairs as standalone Python source, with values emitted as
  auditable source expressions rather than pickle blobs (training artifacts
  bake their behavior at emission time and never consult ambient config at
  load).

- An undefined-tangent backward-specialization layer in AOTAutograd
  (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a
  variant specialized to which output tangents are undefined, retracing or
  structurally pruning the backward per observed pattern. It is OPT-IN:
  torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
  False, ordinary torch.compile keeps the existing zero-materialization
  backward behavior (a contract test pins this), and precompile enables the
  flag only during dynamo-inductor capture. Behind the flag the layer reconciles
  autocast state at retrace time, runs the partitioner inside inductor's
  virtualized context with a fall-back exception guard, invalidates
  specialized backwards when donation state changes, and only prunes
  gradients it can prove are zero -- each property carried by a fail-first
  regression test.

- User-defined Triton kernel constexprs render as importable, eval-verified
  source (enums, containers, torch.Size, and constructor-repr'able
  dataclass/attrs/pydantic-style configs), with autotune-cache matching that
  round-trips tuple-valued config kwargs type-faithfully and an async-compile
  fallback when a worker cannot import a constexpr's module.

Suggested review order: to_standalone_python.py and the runtime_wrappers.py
/ graph_compile.py layer first (the bulk), then torch/_precompile.py and
torch/_precompile_driver.py (the API, the capture pipeline, and the emitted
serve-time driver), then the inductor constexpr/autotune changes, then
tests and docs.

Supersedes #195044. Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 97 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: 5c7b5c3
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 31, 2026
…nt-end, and support stateful incremental capture

torch.compiler.precompile lowers a whole computation ahead of time to a
self-contained, runnable Python source string plus a binary acceleration
cache, and reloads it with precompile.load -- no compiler in the serving
process, no weights baked into the artifact, and the artifact is auditable
text rather than an opaque binary. Until now it captured exactly one
execution through make_fx: control flow and shapes were specialized to a
single example call. This PR generalizes the API to a SET of observed calls
and adds a Dynamo capture front-end:

- example_inputs= takes a sequence of positional-argument tuples (the
  existing positional form keeps working as a single example call; make_fx
  remains the default tracer and requires exactly one tuple).

- tracer="dynamo" executes every example tuple under Dynamo and captures
  each guarded specialization and recompilation it produces, including the
  automatically dynamic graphs that appear when a dimension varies across
  examples (one isolated capture session with a private PGO record, so the
  result is deterministic regardless of process history). At serve time the
  artifact dispatches among the captured variants by guard check, newest
  variant first, and never compiles: a call no variant covers raises.
  Guards derived from explicit inputs are retained for dispatch, classified
  by their typed provenance (the commit below in this stack); guards on the
  Python environment may be dropped, since the environment is a declared
  caller invariant. Unsupported inputs are rejected loudly at capture:
  graph breaks, closures, nn.Module / numpy arguments, tensor inputs with
  overlapping storage, tensor-reachable globals, and global-mutating
  functions.

- Differentiability is inferred per captured graph exactly as torch.compile
  infers it: capture runs grad-enabled, and a graph whose inputs require
  grad is differentiable (no-grad inputs stay inference graphs;
  requires_grad is guarded per input, so a flipped input fails dispatch
  loudly). On the inductor backend the backward is precompiled; on the eager
  backend it is live eager autograd through the emitted ops -- neither
  captured nor specialized, like torch.compile(backend="eager"). For each
  inductor differentiable graph, each
  compiled segment carries readable Inductor source for its AOTAutograd
  forward and backward, bridged by an emitted torch.autograd.Function, so
  served outputs retain grad_fn and backward() runs the precompiled
  kernels. Backward variants are specialized to the output-tangent patterns
  observed during capture (the all-tangents-defined pattern is always
  covered); an unseen pattern fails instead of compiling at runtime.
  Serving follows the ambient grad mode like eager: under torch.no_grad()
  freshly created outputs are returned detached (passthrough inputs
  untouched), and torch.inference_mode() is rejected with a clear error.

- precompile.stateful captures incrementally from a loop the caller owns
  (e.g. a pipelined train step that precompile cannot drive itself): every
  call runs its example tuples for real, accumulates newly exercised
  variants into an opaque resumable state, and atomically rewrites an
  always-loadable artifact/cache pair on disk, so a job that dies mid-loop
  keeps a working artifact for the batches it saw.

Supporting machinery introduced by this PR, and why it is safe for everyone
else:

- compile_to_python (to_standalone_python.py) renders AOTAutograd
  forward/backward pairs as standalone Python source, with values emitted as
  auditable source expressions rather than pickle blobs (training artifacts
  bake their behavior at emission time and never consult ambient config at
  load).

- An undefined-tangent backward-specialization layer in AOTAutograd
  (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a
  variant specialized to which output tangents are undefined, retracing or
  structurally pruning the backward per observed pattern. It is OPT-IN:
  torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
  False, ordinary torch.compile keeps the existing zero-materialization
  backward behavior (a contract test pins this), and precompile enables the
  flag only during dynamo-inductor capture. Behind the flag the layer reconciles
  autocast state at retrace time, runs the partitioner inside inductor's
  virtualized context with a fall-back exception guard, invalidates
  specialized backwards when donation state changes, and only prunes
  gradients it can prove are zero -- each property carried by a fail-first
  regression test.

- User-defined Triton kernel constexprs render as importable, eval-verified
  source (enums, containers, torch.Size, and constructor-repr'able
  dataclass/attrs/pydantic-style configs), with autotune-cache matching that
  round-trips tuple-valued config kwargs type-faithfully and an async-compile
  fallback when a worker cannot import a constexpr's module.

Suggested review order: to_standalone_python.py and the runtime_wrappers.py
/ graph_compile.py layer first (the bulk), then torch/_precompile.py and
torch/_precompile_driver.py (the API, the capture pipeline, and the emitted
serve-time driver), then the inductor constexpr/autotune changes, then
tests and docs.

Supersedes #195044. Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 297 tests, OK
python test/inductor/test_codegen_triton.py             # 102 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 64 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3873 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: b1ceae8
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Sep 1, 2026
…nt-end, and support stateful incremental capture

torch.compiler.precompile lowers a whole computation ahead of time to a
self-contained, runnable Python source string plus a binary acceleration
cache, and reloads it with precompile.load -- no compiler in the serving
process, no weights baked into the artifact, and the artifact is auditable
text rather than an opaque binary. Until now it captured exactly one
execution through make_fx: control flow and shapes were specialized to a
single example call. This PR generalizes the API to a SET of observed calls
and adds a Dynamo capture front-end:

- example_inputs= takes a sequence of positional-argument tuples (the
  existing positional form keeps working as a single example call; make_fx
  remains the default tracer and requires exactly one tuple).

- tracer="dynamo" executes every example tuple under Dynamo and captures
  each guarded specialization and recompilation it produces, including the
  automatically dynamic graphs that appear when a dimension varies across
  examples (one isolated capture session with a private PGO record, so the
  result is deterministic regardless of process history). At serve time the
  artifact dispatches among the captured variants by guard check, newest
  variant first, and never compiles: a call no variant covers raises.
  Guards derived from explicit inputs are retained for dispatch, classified
  by their typed provenance (the commit below in this stack); guards on the
  Python environment may be dropped, since the environment is a declared
  caller invariant. Unsupported inputs are rejected loudly at capture:
  graph breaks, closures, nn.Module / numpy arguments, tensor inputs with
  overlapping storage, tensor-reachable globals, and global-mutating
  functions.

- Differentiability is inferred per captured graph exactly as torch.compile
  infers it: capture runs grad-enabled, and a graph whose inputs require
  grad is differentiable (no-grad inputs stay inference graphs;
  requires_grad is guarded per input, so a flipped input fails dispatch
  loudly). On the inductor backend the backward is precompiled; on the eager
  backend it is live eager autograd through the emitted ops -- neither
  captured nor specialized, like torch.compile(backend="eager"). For each
  inductor differentiable graph, each
  compiled segment carries readable Inductor source for its AOTAutograd
  forward and backward, bridged by an emitted torch.autograd.Function, so
  served outputs retain grad_fn and backward() runs the precompiled
  kernels. Backward variants are specialized to the output-tangent patterns
  observed during capture (the all-tangents-defined pattern is always
  covered); an unseen pattern fails instead of compiling at runtime.
  Serving follows the ambient grad mode like eager: under torch.no_grad()
  freshly created outputs are returned detached (passthrough inputs
  untouched), and torch.inference_mode() is rejected with a clear error.

- precompile.stateful captures incrementally from a loop the caller owns
  (e.g. a pipelined train step that precompile cannot drive itself): every
  call runs its example tuples for real, accumulates newly exercised
  variants into an opaque resumable state, and atomically rewrites an
  always-loadable artifact/cache pair on disk, so a job that dies mid-loop
  keeps a working artifact for the batches it saw.

Supporting machinery introduced by this PR, and why it is safe for everyone
else:

- compile_to_python (to_standalone_python.py) renders AOTAutograd
  forward/backward pairs as standalone Python source, with values emitted as
  auditable source expressions rather than pickle blobs (training artifacts
  bake their behavior at emission time and never consult ambient config at
  load).

- An undefined-tangent backward-specialization layer in AOTAutograd
  (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a
  variant specialized to which output tangents are undefined, retracing or
  structurally pruning the backward per observed pattern. It is OPT-IN:
  torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
  False, ordinary torch.compile keeps the existing zero-materialization
  backward behavior (a contract test pins this), and precompile enables the
  flag only during dynamo-inductor capture. Behind the flag the layer reconciles
  autocast state at retrace time, runs the partitioner inside inductor's
  virtualized context with a fall-back exception guard, invalidates
  specialized backwards when donation state changes, and only prunes
  gradients it can prove are zero -- each property carried by a fail-first
  regression test.

- User-defined Triton kernel constexprs render as importable, eval-verified
  source (enums, containers, torch.Size, and constructor-repr'able
  dataclass/attrs/pydantic-style configs), with autotune-cache matching that
  round-trips tuple-valued config kwargs type-faithfully and an async-compile
  fallback when a worker cannot import a constexpr's module.

- BC note for user-defined Triton kernels (independent of precompile): a
  plain-Enum constexpr previously reached the generated source value-unwrapped
  (Mode.A with value 1 was baked as the literal 1); it now bakes the real
  member, matching direct eager triton launches. A kernel written against the
  unwrapped behavior (e.g. branching on MODE == 1) sees plain-Enum __eq__
  semantics and selects a different branch, and a plain Enum defined in
  __main__ or a local scope now raises a clear error where value-unwrapping
  previously compiled. Both are deliberate fidelity fixes, pinned by
  test_plain_enum_constexpr_in_user_defined_triton_kernel and
  test_constexpr_source_declines_main_module_enum.

Suggested review order: to_standalone_python.py and the runtime_wrappers.py
/ graph_compile.py layer first (the bulk), then torch/_precompile.py and
torch/_precompile_driver.py (the API, the capture pipeline, and the emitted
serve-time driver), then the inductor constexpr/autotune changes, then
tests and docs.

Supersedes #195044. Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 301 tests, OK
python test/inductor/test_codegen_triton.py             # 102 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 65 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3873 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 66 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
python test/dynamo/test_pgo.py                          # 12 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: ae6fc34
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Sep 1, 2026
…nt-end, and support stateful incremental capture

torch.compiler.precompile lowers a whole computation ahead of time to a
self-contained, runnable Python source string plus a binary acceleration
cache, and reloads it with precompile.load -- no compiler in the serving
process, no weights baked into the artifact, and the artifact is auditable
text rather than an opaque binary. Until now it captured exactly one
execution through make_fx: control flow and shapes were specialized to a
single example call. This PR generalizes the API to a SET of observed calls
and adds a Dynamo capture front-end:

- example_inputs= takes a sequence of positional-argument tuples (the
  existing positional form keeps working as a single example call; make_fx
  remains the default tracer and requires exactly one tuple).

- tracer="dynamo" executes every example tuple under Dynamo and captures
  each guarded specialization and recompilation it produces, including the
  automatically dynamic graphs that appear when a dimension varies across
  examples (one isolated capture session with a private PGO record, so the
  result is deterministic regardless of process history). At serve time the
  artifact dispatches among the captured variants by guard check, newest
  variant first, and never compiles: a call no variant covers raises.
  Guards derived from explicit inputs are retained for dispatch, classified
  by their typed provenance (the commit below in this stack); guards on the
  Python environment may be dropped, since the environment is a declared
  caller invariant. Unsupported inputs are rejected loudly at capture:
  graph breaks, closures, nn.Module / numpy arguments, tensor inputs with
  overlapping storage, tensor-reachable globals, and global-mutating
  functions.

- Differentiability is inferred per captured graph exactly as torch.compile
  infers it: capture runs grad-enabled, and a graph whose inputs require
  grad is differentiable (no-grad inputs stay inference graphs;
  requires_grad is guarded per input, so a flipped input fails dispatch
  loudly). On the inductor backend the backward is precompiled; on the eager
  backend it is live eager autograd through the emitted ops -- neither
  captured nor specialized, like torch.compile(backend="eager"). For each
  inductor differentiable graph, each
  compiled segment carries readable Inductor source for its AOTAutograd
  forward and backward, bridged by an emitted torch.autograd.Function, so
  served outputs retain grad_fn and backward() runs the precompiled
  kernels. Backward variants are specialized to the output-tangent patterns
  observed during capture (the all-tangents-defined pattern is always
  covered); an unseen pattern fails instead of compiling at runtime.
  Serving follows the ambient grad mode like eager: under torch.no_grad()
  freshly created outputs are returned detached (passthrough inputs
  untouched), and torch.inference_mode() is rejected with a clear error.

- precompile.stateful captures incrementally from a loop the caller owns
  (e.g. a pipelined train step that precompile cannot drive itself): every
  call runs its example tuples for real, accumulates newly exercised
  variants into an opaque resumable state, and atomically rewrites an
  always-loadable artifact/cache pair on disk, so a job that dies mid-loop
  keeps a working artifact for the batches it saw.

Supporting machinery introduced by this PR, and why it is safe for everyone
else:

- compile_to_python (to_standalone_python.py) renders AOTAutograd
  forward/backward pairs as standalone Python source, with values emitted as
  auditable source expressions rather than pickle blobs (training artifacts
  bake their behavior at emission time and never consult ambient config at
  load).

- An undefined-tangent backward-specialization layer in AOTAutograd
  (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a
  variant specialized to which output tangents are undefined, retracing or
  structurally pruning the backward per observed pattern. It is OPT-IN:
  torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
  False, ordinary torch.compile keeps the existing zero-materialization
  backward behavior (a contract test pins this), and precompile enables the
  flag only during dynamo-inductor capture. Behind the flag the layer reconciles
  autocast state at retrace time, runs the partitioner inside inductor's
  virtualized context with a fall-back exception guard, invalidates
  specialized backwards when donation state changes, and only prunes
  gradients it can prove are zero -- each property carried by a fail-first
  regression test.

- User-defined Triton kernel constexprs render as importable, eval-verified
  source (enums, containers, torch.Size, and constructor-repr'able
  dataclass/attrs/pydantic-style configs), with autotune-cache matching that
  round-trips tuple-valued config kwargs type-faithfully and an async-compile
  fallback when a worker cannot import a constexpr's module.

- BC note for user-defined Triton kernels (independent of precompile): a
  plain-Enum constexpr previously reached the generated source value-unwrapped
  (Mode.A with value 1 was baked as the literal 1); it now bakes the real
  member, matching direct eager triton launches. A kernel written against the
  unwrapped behavior (e.g. branching on MODE == 1) sees plain-Enum __eq__
  semantics and selects a different branch, and a plain Enum defined in
  __main__ or a local scope now raises a clear error where value-unwrapping
  previously compiled. Both are deliberate fidelity fixes, pinned by
  test_plain_enum_constexpr_in_user_defined_triton_kernel and
  test_constexpr_source_declines_main_module_enum.

Suggested review order: to_standalone_python.py and the runtime_wrappers.py
/ graph_compile.py layer first (the bulk), then torch/_precompile.py and
torch/_precompile_driver.py (the API, the capture pipeline, and the emitted
serve-time driver), then the inductor constexpr/autotune changes, then
tests and docs.

Supersedes #195044. Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 301 tests, OK
python test/inductor/test_codegen_triton.py             # 102 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 65 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3873 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 66 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
python test/dynamo/test_pgo.py                          # 12 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: b2f1c7a
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
…nt-end, and support stateful incremental capture

torch.compiler.precompile lowers a whole computation ahead of time to a
self-contained, runnable Python source string plus a binary acceleration
cache, and reloads it with precompile.load -- no compiler in the serving
process, no weights baked into the artifact, and the artifact is auditable
text rather than an opaque binary. Until now it captured exactly one
execution through make_fx: control flow and shapes were specialized to a
single example call. This PR generalizes the API to a SET of observed calls
and adds a Dynamo capture front-end:

- example_inputs= takes a sequence of positional-argument tuples (the
  existing positional form keeps working as a single example call; make_fx
  remains the default tracer and requires exactly one tuple).

- tracer="dynamo" executes every example tuple under Dynamo and captures
  each guarded specialization and recompilation it produces, including the
  automatically dynamic graphs that appear when a dimension varies across
  examples (one isolated capture session with a private PGO record, so the
  result is deterministic regardless of process history). At serve time the
  artifact dispatches among the captured variants by guard check, newest
  variant first, and never compiles: a call no variant covers raises.
  Guards derived from explicit inputs are retained for dispatch, classified
  by their typed provenance (the commit below in this stack); guards on the
  Python environment may be dropped, since the environment is a declared
  caller invariant. Unsupported inputs are rejected loudly at capture:
  graph breaks, closures, nn.Module / numpy arguments, tensor inputs with
  overlapping storage, tensor-reachable globals, and global-mutating
  functions.

- Differentiability is inferred per captured graph exactly as torch.compile
  infers it: capture runs grad-enabled, and a graph whose inputs require
  grad is differentiable (no-grad inputs stay inference graphs;
  requires_grad is guarded per input, so a flipped input fails dispatch
  loudly). On the inductor backend the backward is precompiled; on the eager
  backend it is live eager autograd through the emitted ops -- neither
  captured nor specialized, like torch.compile(backend="eager"). For each
  inductor differentiable graph, each
  compiled segment carries readable Inductor source for its AOTAutograd
  forward and backward, bridged by an emitted torch.autograd.Function, so
  served outputs retain grad_fn and backward() runs the precompiled
  kernels. Backward variants are specialized to the output-tangent patterns
  observed during capture (the all-tangents-defined pattern is always
  covered); an unseen pattern fails instead of compiling at runtime.
  Serving follows the ambient grad mode like eager: under torch.no_grad()
  freshly created outputs are returned detached (passthrough inputs
  untouched), and torch.inference_mode() is rejected with a clear error.

- precompile.stateful captures incrementally from a loop the caller owns
  (e.g. a pipelined train step that precompile cannot drive itself): every
  call runs its example tuples for real, accumulates newly exercised
  variants into an opaque resumable state, and atomically rewrites an
  always-loadable artifact/cache pair on disk, so a job that dies mid-loop
  keeps a working artifact for the batches it saw.

Supporting machinery introduced by this PR, and why it is safe for everyone
else:

- compile_to_python (to_standalone_python.py) renders AOTAutograd
  forward/backward pairs as standalone Python source, with values emitted as
  auditable source expressions rather than pickle blobs (training artifacts
  bake their behavior at emission time and never consult ambient config at
  load).

- An undefined-tangent backward-specialization layer in AOTAutograd
  (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a
  variant specialized to which output tangents are undefined, retracing or
  structurally pruning the backward per observed pattern. It is OPT-IN:
  torch._functorch.config.aot_autograd_prune_unused_outputs defaults to
  False, ordinary torch.compile keeps the existing zero-materialization
  backward behavior (a contract test pins this), and precompile enables the
  flag only during dynamo-inductor capture. Behind the flag the layer reconciles
  autocast state at retrace time, runs the partitioner inside inductor's
  virtualized context with a fall-back exception guard, invalidates
  specialized backwards when donation state changes, and only prunes
  gradients it can prove are zero -- each property carried by a fail-first
  regression test.

- User-defined Triton kernel constexprs render as importable, eval-verified
  source (enums, containers, torch.Size, and constructor-repr'able
  dataclass/attrs/pydantic-style configs), with autotune-cache matching that
  round-trips tuple-valued config kwargs type-faithfully and an async-compile
  fallback when a worker cannot import a constexpr's module.

- BC note for user-defined Triton kernels (independent of precompile): a
  plain-Enum constexpr previously reached the generated source value-unwrapped
  (Mode.A with value 1 was baked as the literal 1); it now bakes the real
  member, matching direct eager triton launches. A kernel written against the
  unwrapped behavior (e.g. branching on MODE == 1) sees plain-Enum __eq__
  semantics and selects a different branch, and a plain Enum defined in
  __main__ or a local scope now raises a clear error where value-unwrapping
  previously compiled. Both are deliberate fidelity fixes, pinned by
  test_plain_enum_constexpr_in_user_defined_triton_kernel and
  test_constexpr_source_declines_main_module_enum.

Suggested review order: to_standalone_python.py and the runtime_wrappers.py
/ graph_compile.py layer first (the bulk), then torch/_precompile.py and
torch/_precompile_driver.py (the API, the capture pipeline, and the emitted
serve-time driver), then the inductor constexpr/autotune changes, then
tests and docs.

Supersedes #195044. Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 301 tests, OK
python test/inductor/test_codegen_triton.py             # 102 tests, OK (2 skipped; includes all #189692 tests)
python test/functorch/test_compile_to_python.py         # 65 tests, OK
python test/inductor/test_compile_to_python.py          # 19 tests, OK
python test/functorch/test_aotdispatch.py               # 3873 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build)
python test/inductor/test_compiled_autograd.py TestCompiledAutograd  # 150 tests, OK (2 expected failures)
python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu   # OK
python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time  # OK
python test/dynamo/test_guard_serialization.py          # 66 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 8 tests, OK
python test/dynamo/test_backward_higher_order_ops.py    # 7 tests, OK
python test/dynamo/test_pgo.py                          # 12 tests, OK
lintrunner <all changed files>                          # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>

ghstack-source-id: 972d7af
Pull-Request: #195288
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…#189692)

Fix Inductor codegen for user-defined Triton kernels that pass non-builtin Python objects as `tl.constexpr` values.

When such constants are serialized with constructor-style `repr` output, for example `UserDefinedTritonKernelConfig(offset=2)`, generated kernel source and launcher code need the corresponding class in scope.

This change imports the constant class into generated kernel source and makes it available in the generated launcher exec scope.

Pull Request resolved: pytorch#189692
Approved by: https://github.com/jansel
pytorchmergebot pushed a commit that referenced this pull request Sep 2, 2026
Forward fix for D117882973 (#189692), which broke
`fbcode//caffe2/test/inductor:codegen_triton` at listing time.

That diff added a new helper module `triton_constexpr_configs.py` next to
`test_codegen_triton.py` and imported it with two OSS-only fallbacks:

```
try:
    from triton_constexpr_configs import ...          # test/inductor on sys.path
except ImportError:
    from test.inductor.triton_constexpr_configs import ...   # pytorch repo root on sys.path
```

The file itself is packaged fine internally -- `:inductor_test_lib` uses
`srcs = glob(["*.py"])`, so no BUCK change is needed -- but inside the PAR it
resolves under the fbcode base module as
`caffe2.test.inductor.triton_constexpr_configs`. Neither branch matches, so
both raised `ModuleNotFoundError` and the whole module failed to import,
taking down all 22 tests in the suite, not just the new ones:

```
ModuleNotFoundError: No module named 'triton_constexpr_configs'
During handling of the above exception, another exception occurred:
ModuleNotFoundError: No module named 'test.inductor'
```

Switch to the relative-first pattern already used elsewhere in this directory
(`test_codecache.py`, `test_ck_backend.py`). The relative import resolves
against whatever package the test module actually lives in, so it covers all
three run modes: the fbcode PAR (`caffe2.test.inductor`), OSS pytest from the
repo root (`test.inductor`), and `python test/inductor/test_codegen_triton.py`
(no package, falls through to the bare import).

This also matters beyond the import statement itself. The new
`get_importable_constexpr_types` emits `from {type.__module__} import ...`
into the generated Triton kernel source, so the helper module has to be
reachable under its real package name for
`test_user_defined_triton_kernel_non_builtin_constexpr` to compile and run.

`xplat/caffe2` is updated to keep it in sync with `fbcode/caffe2`.

Differential Revision: [D118378564](https://our.internmc.facebook.com/intern/diff/D118378564/)

Pull Request resolved: #195663
Approved by: https://github.com/pytorchgreenlight
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…#189692)

Fix Inductor codegen for user-defined Triton kernels that pass non-builtin Python objects as `tl.constexpr` values.

When such constants are serialized with constructor-style `repr` output, for example `UserDefinedTritonKernelConfig(offset=2)`, generated kernel source and launcher code need the corresponding class in scope.

This change imports the constant class into generated kernel source and makes it available in the generated launcher exec scope.

Pull Request resolved: pytorch#189692
Approved by: https://github.com/jansel
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…ch#195663)

Forward fix for D117882973 (pytorch#189692), which broke
`fbcode//caffe2/test/inductor:codegen_triton` at listing time.

That diff added a new helper module `triton_constexpr_configs.py` next to
`test_codegen_triton.py` and imported it with two OSS-only fallbacks:

```
try:
    from triton_constexpr_configs import ...          # test/inductor on sys.path
except ImportError:
    from test.inductor.triton_constexpr_configs import ...   # pytorch repo root on sys.path
```

The file itself is packaged fine internally -- `:inductor_test_lib` uses
`srcs = glob(["*.py"])`, so no BUCK change is needed -- but inside the PAR it
resolves under the fbcode base module as
`caffe2.test.inductor.triton_constexpr_configs`. Neither branch matches, so
both raised `ModuleNotFoundError` and the whole module failed to import,
taking down all 22 tests in the suite, not just the new ones:

```
ModuleNotFoundError: No module named 'triton_constexpr_configs'
During handling of the above exception, another exception occurred:
ModuleNotFoundError: No module named 'test.inductor'
```

Switch to the relative-first pattern already used elsewhere in this directory
(`test_codecache.py`, `test_ck_backend.py`). The relative import resolves
against whatever package the test module actually lives in, so it covers all
three run modes: the fbcode PAR (`caffe2.test.inductor`), OSS pytest from the
repo root (`test.inductor`), and `python test/inductor/test_codegen_triton.py`
(no package, falls through to the bare import).

This also matters beyond the import statement itself. The new
`get_importable_constexpr_types` emits `from {type.__module__} import ...`
into the generated Triton kernel source, so the helper module has to be
reachable under its real package name for
`test_user_defined_triton_kernel_non_builtin_constexpr` to compile and run.

`xplat/caffe2` is updated to keep it in sync with `fbcode/caffe2`.

Differential Revision: [D118378564](https://our.internmc.facebook.com/intern/diff/D118378564/)

Pull Request resolved: pytorch#195663
Approved by: https://github.com/pytorchgreenlight
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source release notes: inductor triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants