Skip to content

[precompile] Accept multiple example inputs, add a Dynamo capture front-end, and support stateful incremental capture - #195044

Closed
bobrenjc93 wants to merge 25 commits into
gh/bobrenjc93/997/basefrom
precompile-dynamo-tracer-v2
Closed

bobrenjc93 wants to merge 25 commits into
gh/bobrenjc93/997/basefrom
precompile-dynamo-tracer-v2

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

torch.compiler.precompile lowers a whole computation to a self-contained, runnable
Python source string plus a binary acceleration cache. Until now it captured exactly one
execution through make_fx: control flow and shapes were specialized to a single example
call, and the artifact served exactly that specialization.

This PR generalizes the API to a set of observed calls, adds a Dynamo capture
front-end that turns them into a multi-variant artifact, and adds a stateful form for
capturing incrementally from a loop the caller owns:

examples = [(torch.randn(2, 4),), (torch.randn(3, 4),)]
python_code, cache = torch.compiler.precompile(fn, example_inputs=examples, tracer="dynamo")
f = torch.compiler.precompile.load(python_code, cache)
out = f(torch.randn(7, 4))   # served by the captured dynamic variant
  • example_inputs= takes a sequence of positional-argument tuples. The existing
    positional form (precompile(fn, model, x)) 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. At serve time the
    artifact dispatches among the captured variants by guard check, newest variant
    first (matching live Dynamo's recompilation order, so an input matching both an
    early static variant and a later dynamic one is served by the dynamic one).
  • 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 ordinary
    all-tangents-defined pattern is always covered.
  • recompile_limit= (dynamo only) caps the captured variants per capture; the
    one-shot default is torch._dynamo.config.recompile_limit or the example count plus
    one, whichever is larger, and the stateful default is
    max(torch._dynamo.config.recompile_limit, 256).
  • dynamic= (dynamo only) is forwarded to Dynamo; None keeps the automatic
    dynamic-shape policy, and it rides in the stateful consistency check.

Stateful capture

Some capture regions can only be exercised from the caller's own loop (e.g. a pipelined
train step whose batch deque only advances between iterations), so precompile cannot
drive the examples itself. The sibling entry point precompile.stateful (dynamo
tracer implied) accumulates one call per example batch:

state = None
try:
    for batch in batches:                  # the caller's loop, not precompile's
        [result], state = torch.compiler.precompile.stateful(
            step, example_inputs=[(batch,)], state=state,
            artifact_path="step.py", cache_path="step.cache",
            training=True, recompile_limit=256,
        )
        # result is this call's real step output; backward it, step the optimizer, etc.
finally:
    if state is not None:
        state.close()                      # release the capture session

Every call runs its example tuples for real, adds whatever guarded variants they newly
exercise to the returned opaque state, atomically rewrites both files, and returns
(results, state): results is always a list with one entry per example tuple of the
call (never unwrapped, so a fn that itself returns a list is unambiguous). There is no session object and no finalize step: the files on disk
are always a loadable artifact for everything captured so far, so a job that dies
mid-loop keeps a working artifact for the batches it saw. state=None starts fresh; a
returned state resumes, and a resumed call whose fn, backend, training,
recompile_limit, or dynamic disagrees with the state raises instead of producing a
mixed artifact. A call whose guards all hit adds nothing. Every example of a call is
bind-checked against the fn's signature before any is recorded or run, so a
wrong-arity example raises with nothing recorded, and a step that raises after Dynamo
compiled its variant (a data-dependent runtime error) leaves a resumable state: later
calls keep capturing, and the variant the failed step left behind serves its shape.
Guard minimization re-runs its full
rebuild-and-recheck over every example seen so far on each rewrite (repeated work, not
wrong work) against pre-execution snapshots of the examples (tensor data by reference,
tensor metadata frozen), so a step may freely mutate its container inputs and its
tensor inputs in place, and the state carries one isolate-recompiles bucket and one PGO record
across calls, so a dimension that varies between calls recompiles into a symbolic graph
exactly as it would within one call. The state is process-local and not
serializable; call state.close() when done capturing to release the session
(Dynamo's recompile-logging registry otherwise pins it until
torch._dynamo.reset(); a state garbage collected without close() logs a warning).
A tangent mask whose deferred compile fails is dropped
from that rewrite with a warning instead of poisoning every later rebuild, and a
rebuild that cannot render the accumulated capture says so while the last
successfully written files stay valid. state.summary() reports what the current
artifact carries (calls, examples, variants, graphs, dynamic graphs, and the
environment guards minimization dropped from at least one variant -- also embedded
in the artifact as a _DROPPED_GUARDS section), and precompile.load(artifact_path=..., cache_path=...)
reloads the on-disk pair directly. Writes fsync both halves, rename back to back,
and clean their temp files up on failure, so a failed or interrupted rewrite leaves
the previous pair loadable -- and a pair whose halves mismatch (a crash landed between
the two renames) still loads: the dynamo loader treats a backend- or code_hash-
mismatched cache -- or a missing cache file, the first-rewrite crash window -- as cold
with a warning, since python_code is fully self-contained. make_fx artifacts keep
the strict pairing check.

Contract

  1. The Python environment (globals, context managers, similar state) is identical at
    precompile time and runtime. This is an unchecked caller invariant: environment
    changes after capture can silently run code specialized for the old state.
  2. Only explicit graph inputs participate in dispatch. Guards derived from inputs are
    retained and serialized; guards that only cover the environment are minimized away
    when dropping them provably preserves how every capture example dispatches.
  3. The artifact never invokes Dynamo and never compiles while serving. A call that fails
    every retained guard set raises PrecompileError instead of recompiling.

Compiled graphs and kernels remain plain Python source in the artifact; only Dynamo's
guard trees and transformed code objects, which have no source form, are stored as
opaque inline data, pinned to the producing Python minor and torch versions (a
mismatch raises a clean PrecompileError at load, not an unpickling error). Loading a
corrupt or stale cache degrades to JIT-from-source with correct numerics, never a
crash. No weights or example-tensor data are embedded (guard-state tensors serialize
as meta tensors, and tensors reachable through object-valued function defaults are
rejected like direct tensor defaults).

Implementation notes

  • Capture drives torch._dynamo.optimize with a CompilePackage, isolated recompile
    buckets, an isolated PGO code-state (new ContextVar override in torch/_dynamo/pgo.py),
    copied fn globals, and full cleanup of installed frames. Repeated captures do not
    perturb, and are not perturbed by, unrelated torch.compile state in the process.
  • Stateful capture reuses the same pieces without the teardown: the state owns the
    cloned capture fn (its installed code caches stay live between calls), the
    CompilePackage new variants accumulate into, and the optimize wrapper whose
    isolate bucket keeps earlier variants visible to later calls. Config patches are
    entered per call and exited before returning, so nothing leaks into the caller's
    loop, and training snapshots compose non-destructively
    (finalize_training(keep_capture=True)) so real backwards run between calls keep
    recording tangent masks.
  • _filter_dynamo_guards greedily drops environment guards while re-checking every
    capture example against the rebuilt guard manager; input-derived guards, AOT guards,
    and dict key-order guards are never candidates. Measured capture overhead is
    sub-second up to ~100 droppable guards.
  • Fixes a latent Dynamo guards-serialization bug the stateful flow exposes on its
    second call (and any capture whose example tensor already carries .grad):
    GuardsStatePickler serialized a guarded tensor's .grad as a _Missing
    placeholder that load_guards_state could not assign back; the grad now serializes
    as a meta tensor like its owner, registered upfront before pickling so the fix is
    independent of pickle memoization order (a grad reachable earlier through an
    unguarded container leaf would otherwise still memoize as _Missing).
  • Both tracers share one error surface: rejected inputs (closures, nn.Module args --
    including nested inside containers, tensor-valued or unpicklable function defaults --
    including tensors inside object attributes and slot values, globals whose object
    graph contains a tensor -- conservatively, spanning containers, instance state, slot
    values, class attributes, user modules, and user functions (their defaults, closure
    cells, attributes, and the globals their own code loads -- an inlined helper can
    carry state the root fn's bytecode never names; bound methods and functools.partial
    are walked too), since every tensor must be an explicit input; the class/module-attribute widening applies to both global scans (tensor
    reachability and input aliasing -- an input aliased through a global class or module
    attribute would have its identity guard dropped as environment and silently serve
    the capture-time branch), value-guarded process-wide singletons (dtypes, layouts,
    memory formats -- but not devices, whose equality is not identity) are exempt from
    the aliasing rejection, as are enum members (Dynamo puts an unserializable ID_MATCH
    on every used enum argument, so those fail capture loudly regardless; the exemption
    enables unused pass-through enums), and the expensive environment walk runs once per
    capture/state with only the per-call id intersection repeated on stateful resumes --
    the alias and tensor-global rejections are therefore checked at state creation, and
    a post-creation environment change is a contract violation that is not re-detected;
    the aliasing check covers pytree-leaf inputs (a container input's own identity
    dissolves into its leaves),
    while an argument is still judged only by what it carries
    (its __dict__ and slot values), not by unrelated attributes of its type, functions
    that mutate
    globals -- the artifact could not reproduce the side effect, distinct tensor inputs
    that share or overlap storage -- deliberately storage-granular (non-overlapping
    views of one buffer included) because AOTAutograd's synthetic-base mutation handling
    keys on shared storage and its StorageOverlap guards have no serialized form; both
    capture and the loaded artifact reject them while passing the same
    tensor object twice stays supported; sparse inputs surface Dynamo's own rejection
    and any other non-strided layout (e.g. jagged, which Dynamo accepts but whose
    aliasing the artifact cannot verify) is refused at capture and at serve, callable
    inputs needing identity
    guards, graph breaks, decompositions) raise typed errors with actionable messages,
    and wrong-arity calls on a loaded artifact raise PrecompileError like the make_fx
    drivers do. _load_dynamo_state gives tests and tooling an AST-based accessor to the
    artifact's opaque section instead of line matching.
  • Inductor's user-defined Triton constexpr rendering is rewritten (_constexpr_source)
    to emit importable references (e.g. module.Enum['NAME']) with collision-free import
    aliases, replacing the lossy _sanitize_for_repr; launcher constants that cannot be
    spelled as literals are bound into the launcher scope instead of repr'd. This is a
    deliberate behavior change for torch.compile user Triton kernels
    : values the old
    path silently baked as .value now raise a clear error when they cannot be
    reconstructed importably -- plain Enums defined in __main__, Flag composites
    (A | B), and NaN constexprs. OrderedSet constexprs reconstruct exactly (type and
    insertion order); any other set subclass declines rather than emitting
    hash-order-nondeterministic or constructor-assuming source, and the rendered
    placeholders stay local to the emitted source (the
    returned/cached kernel metas keep real values -- exercised end to end by a
    cpp_wrapper/AOTI enum-constexpr test). The autotune cache normalizes Enum
    config kwargs to their underlying values for its JSON payloads
    (_json_config_value, recursing through lists and dicts the same way the
    cacheable check does), skips caching configs whose kwargs do not survive a JSON
    round-trip -- whether the unstable value is an Enum's payload, a bare tuple, or a
    non-finite float -- (re-autotune instead of warm-loading a degraded value, with a
    warning naming the cache entry), re-autotunes when Enum unwrapping makes two
    candidate configs match the same cached payload, and
    found_by_coordesc is only stamped when coordinate descent actually runs for the
    kernel, so user-autotuned Enum configs match candidates on warm loads instead of
    being reconstructed with raw values. The importable-reference imports execute in
    async-compile subprocess workers, whose PYTHONPATH snapshot can predate a runtime
    sys.path addition; a worker ModuleNotFoundError on exactly these generated
    imports now falls back to an in-process compile with a warning (codegen already
    validated the import in the parent) instead of failing the compile.

Not yet supported (rejected with clear errors): graph breaks, closures, nn.Module
arguments, numpy array/scalar arguments, decompositions with the dynamo tracer. Graph-break support lands next in
the stack; the stateful entry point is the mechanics those entries plug into.

API note: stateful capture began as a mode of precompile itself (keyed on passing
the paths) and was split into the sibling entry point precompile.stateful after
review: both modes returned 2-tuples, so calling the wrong mode failed silently at
unpack time, and the return annotation was an unhelpful union naming a private class.
The modes still share every capture semantic and differ only in delivery. This history
is recorded in the docstring.

Test plan

On a from-source build (H100, triton 3.7, Python 3.12):

python test/test_precompile.py                    # 267 tests, OK
python test/inductor/test_codegen_triton.py       # 70 tests, OK (2 skipped)
python test/functorch/test_compile_to_python.py   # 62 tests, OK
python test/dynamo/test_guard_serialization.py    # 63 tests, OK (1 skipped)
python test/dynamo/test_package.py                # 64 tests, OK
python test/inductor/test_triton_heuristics.py    # 58 tests, OK (4 skipped)
python test/inductor/test_coordinate_descent_tuner.py  # 14 tests, OK
lintrunner <touched files>                        # ok No lint issues.

Coverage includes every rejection path (tensor-reaching globals -- including class-
attribute, module-attribute, slot-value, and slotted-class-attribute tensors, each as
a subTest; global-mutating functions; overlapping-storage inputs at capture AND at
serve -- previously a mutating variant could silently serve wrong results on
overlapping views; wrong-arity stateful examples -- rejected without poisoning the
state, including a mixed good/bad batch recording nothing; inputs aliased through a
global class or user-module attribute; dtype, layout, and memory-format inputs shared
with a referenced config class capturing and serving both variants (the singleton
exemption), plus enum semantics (unused pass-through serves, used enum fails loudly
on its identity guard) and a pin that the environment scan is computed once per
stateful state; nn.Module and
tensor payloads carried in
argument/default slots; jagged-layout inputs at capture and serve with sparse inputs
surfacing Dynamo's own diagnostics; and a regression test that
an argument whose class carries an nn.Module attribute still captures and serves),
cache robustness (corrupt bundle, weights_only
envelope, code/cache mismatch degrading for dynamo and rejecting for make_fx,
truncated artifact, torch/Python version mismatches via the public error), fresh-
subprocess runs of inference and training artifacts under TORCHDYNAMO_DISABLE=1
(the artifact keeps working with the compiler hard-disabled) plus the public
cache-primed load() path with a frame-counter assertion proving serving compiles
no frame (child env sanitized so an ambient TORCHDYNAMO_DISABLE cannot void it), a
sentinel scan proving no tensor bytes land in the artifact,
device-generic CPU/CUDA numerics for the dynamic and training paths, capture-time
environment specialization (changing a minimized-away global after capture), and the
stateful loop: accumulate/rewrite with a guard-hit third call pinning the variant
count, training with real backwards between calls, resume-mismatch errors (including
training=), a step that raises after its variant compiled (state keeps capturing), a
populated-.grad example capture pinning the guards-serialization fix (fails on the
parent commit with TypeError: ... got grad of type _Missing), partial-backward
mask-0 coverage across rewrites, close() releasing the recompile-logging pin, the
failed-mask snapshot fallback, and up-front rejection when Dynamo is disabled.
Later review rounds added: tensors and aliases carried through helper functions
(defaults and inlined-global reads); overlapping storage inside custom-object
arguments at capture and at serve; container-mutating steps capturing correctly
one-shot and stateful; the always-a-list stateful return; UTF-8 artifact writes and
failed-rename temp cleanup; missing-cache and backend-tag load degrades; the
stateful recompile-limit advice; an unrenderable resumed rebuild keeping the last
files loadable; the unclosed-state GC warning; garbage/tampered python_code
rejections; the PackageError translation; the cache-prime failure fallback; PGO
isolation pinned; grad-pickling order-dependence regression tests in
test_guard_serialization.py; container-of-Enum autotune save/load, ambiguous
warm-load re-autotune, escape-bearing constexprs end to end; and the generated
constexpr import exercised in a real subprocess compile worker, plus its
deterministic missing-module fallback. New
tests were verified load-bearing by stashing their fix and watching them fail.

🤖 Generated with Claude Code

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 14 New Failures, 1 Unrelated Failure

As of commit 3f5d7ed with merge base ab5fb26 (image):

NEW FAILURES - The following jobs have failed:

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

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

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

@bobrenjc93 bobrenjc93 changed the title [precompile] dynamo tracer v2: #194113 + review fixes and error-surface tests [precompile] Accept multiple example inputs and add a Dynamo capture front-end to torch.compiler.precompile Aug 27, 2026
@bobrenjc93
bobrenjc93 force-pushed the precompile-dynamo-tracer-v2 branch from 3e63ccc to 7b8a2be Compare August 27, 2026 21:28
…ests

Alternative to the top commit of #194113 (same ghstack base, same feature
set) that applies the fixes and coverage from its code review. Review the
diff against #194113's head in this order: the guard-minimization loop in
_filter_dynamo_guards, then the error-surface changes (driver arity errors,
defaults picklability, AssertionError translation), then the test additions.

Root causes fixed:

- _filter_dynamo_guards iterated three guard-record lists but its try_drop
  refused two of them unconditionally, leaving unreachable trial-list
  branches; minimization now explicitly walks only kept_guards.
- The identity-guard AssertionError translation string-matched a message
  that only exists as "check_fn.guards_state must not be None" in
  torch/_dynamo/convert_frame.py; the two sides now share the
  GUARDS_STATE_NONE_MESSAGE constant defined in convert_frame.py.
- An unpicklable function default (e.g. a lambda) failed inside the
  artifact-state pickle and was misreported as a guards/bytecode
  serialization failure; defaults are now probed up front with an accurate
  message.
- Wrong-arity calls on a loaded dynamo artifact leaked a raw TypeError from
  signature.bind while make_fx artifacts raise PrecompileError; the dynamo
  dispatcher now matches the make_fx error surface (keyword calls stay
  TypeError on both tracers, documented).
- _CompileToPythonState's docstring claimed finalize removes the live
  compiler hook; the caller does that cleanup, and the docstring now states
  the actual read/finalize/cleanup contract.
- _SourceLiteral gained __eq__/__hash__ so cached rendered constexpr configs
  compare by source instead of identity; the driver's hand-rolled closure
  cell builder became types.CellType.

A second review round (of this PR's own diff) fixed:

- The tensor-default check only walked containers, unlike its sibling
  input-alias walk, so a picklable object default holding a tensor slipped
  past both the tensor check and the pickle probe and embedded real tensor
  bytes inside _DYNAMO_STATE, violating the no-tensor-data contract. Both
  traversals are now one predicate-driven `reaches` walk that also descends
  object __dict__.
- The nn.Module rejection only checked top-level example arguments; a module
  nested in a container was silently accepted into an unvalidated capture
  path. The check now uses the same `reaches` walk.
- A non-interchangeable Enum in an autotune triton.Config reaches the
  runtime as a real Enum member (the constexpr rendering rewrite made that
  path work at all), but AutotuneCache.save JSON-encodes config kwargs and
  raised TypeError whenever there was more than one config and the
  (default-on) local autotune cache. Save and the cached-config match now
  normalize Enum members to their underlying values (_json_config_value).
- _constexpr_source_impl matched OrderedSet but not builtin set (OrderedSet
  is not a set subclass), leaving builtin sets to render via repr in
  nondeterministic hash order; both now render sorted and deterministic.
- Hardening: _parse_artifact_metadata requires the dynamo driver globals so
  a truncated dynamo artifact fails load with a clean PrecompileError
  instead of a NameError from exec; _convert_constant falls back to binding
  the object on any literal_eval exception (repr of an unhashable-key dict
  raises TypeError, not just SyntaxError/ValueError); _passthrough_source
  renders nonfinite floats as float('inf')/float('nan') instead of invalid
  bare inf/nan; the THREADING docstring states that capture-time global
  config patches are visible to concurrent torch.compile calls on other
  threads.

A third review round (of the updated head) fixed:

- autotune_to_one_config stamped found_by_coordesc from the global
  coordinate_descent_tuning flag with no eligibility gate, while coordesc
  itself never runs for USER_AUTOTUNE/TEMPLATE/FIXED kernels
  (_should_coordesc_tune). A warm cache load seeing that flag skips
  candidate matching and reconstructs the Config from the JSON payload,
  which hands a user kernel raw values where it expects Enum constexprs.
  The stamp is now gated on _should_coordesc_tune; coordesc's own save
  path (which runs after coordesc actually refines a config) still stamps
  True.
- The three tests importing torch.distributed.fsdp TrainingState now skip
  when distributed is unavailable: on USE_DISTRIBUTED=0 builds the import
  chain fails at torch._C._distributed_c10d
  (fsdp/_common_utils -> _flat_param -> testing fake_pg).

New coverage: every dynamo-tracer rejection path (non-function fn, closure
cells, nn.Module example args -- top-level and nested in a container,
decompositions, eager get_attr, unpicklable defaults, tensors hidden inside
object defaults, unserializable identity guards), dynamo cache robustness
(corrupt bundle degrades to JIT with correct numerics, weights_only
envelope, code/cache mismatch, truncated artifact), fresh-process runs of
the inference artifact, a _load_dynamo_state AST accessor replacing the
test helper's brittle line-prefix parse of _DYNAMO_STATE plus direct unit
tests for it and for _filter_dynamo_guards' unmatched-variant invariant,
the dynamo numeric tests moved into the device-generic
TestPrecompileNumerics, plain-Enum autotune configs end to end (codegen +
autotune-cache save) plus a unit test of the cached-config Enum match, set
and empty-set constexpr rendering, and nonfinite-float passthrough
rendering.

This PR was authored by an AI assistant (Claude Code) at the stack owner's
direction, from the plan derived from the review of #194113; every change
was verified on a from-source build.

Test Plan:

On a from-source editable build of this branch (H100, triton 3.7, py3.12):

```
.venv/bin/python test/test_precompile.py
# Ran 216 tests ... OK

.venv/bin/python test/inductor/test_codegen_triton.py
# Ran 54 tests ... OK (skipped=2)

.venv/bin/python test/functorch/test_compile_to_python.py
# Ran 62 tests ... OK

lintrunner torch/_precompile.py torch/_dynamo/convert_frame.py \
  torch/_inductor/codegen/wrapper.py \
  torch/_inductor/runtime/triton_heuristics.py \
  torch/_inductor/runtime/autotune_cache.py \
  torch/_inductor/standalone_compile.py \
  test/test_precompile.py test/inductor/test_codegen_triton.py \
  test/functorch/test_compile_to_python.py
# ok No lint issues.
```

The new autotune-cache test was verified load-bearing: with the
autotune_cache.py fix stashed, test_plain_enum_constexpr_in_autotune_config
fails with "TypeError: Object of type TrainingState is not JSON
serializable". The embedded-tensor and nested-module repros were likewise
confirmed to fail before the fixes and raise typed errors after, and
test_user_autotune_cache_not_stamped_coordesc fails without the
found_by_coordesc gate and passes with it.
test/inductor/test_coordinate_descent_tuner.py stays OK, pinning that
coordesc-eligible kernels are unaffected by the gate.

Plus a 17-check behavioral harness (rejection paths, artifact hygiene
including a no-tensor-bytes-in-artifact scan, environment-drift semantics,
CPU/CUDA training numerics, guard-minimization timing): 17/17 pass.

Co-Authored-By: Claude Fable 5 <[email protected]>
@bobrenjc93
bobrenjc93 force-pushed the precompile-dynamo-tracer-v2 branch from 7b8a2be to f790258 Compare August 27, 2026 22:45
@bobrenjc93 bobrenjc93 changed the title [precompile] Accept multiple example inputs and add a Dynamo capture front-end to torch.compiler.precompile [precompile] Accept multiple example inputs, add a Dynamo capture front-end, and support stateful incremental capture Aug 27, 2026
…act on every call

Adds a stateful form of torch.compiler.precompile for capture regions that
can only be exercised from a loop the caller owns (e.g. a pipelined train
step whose batch deque only advances between iterations, so precompile
cannot drive the examples itself):

    state = None
    for batch in batches:
        result, state = torch.compiler.precompile(
            step, example_inputs=[(batch,)], state=state,
            artifact_path="step.py", cache_path="step.cache",
            tracer="dynamo", training=True, recompile_limit=256,
        )

Passing artifact_path/cache_path (dynamo tracer only) switches the return
to (this call's example result(s), opaque state). Every call runs its
examples for real, accumulates whatever guarded variants they newly
exercise into the state, atomically rewrites both files, and leaves them
always loadable -- a job that dies mid-loop keeps a working artifact for
everything captured so far. state=None starts fresh; a returned state
resumes, and a resumed call whose fn, backend, training, or
recompile_limit disagrees with the state raises instead of producing a
mixed artifact. A call whose guards all hit adds nothing. There is no
session object and no finalize step.

Review the change in this order:

1. torch/_precompile.py: _precompile_dynamo is split into reusable pieces
   (_validate_dynamo_capture, _make_dynamo_capture_target,
   _dynamo_capture_context, _translate_dynamo_capture_errors,
   _make_dynamo_capture_optimizer, _build_dynamo_artifact,
   _teardown_dynamo_capture); the one-shot driver's behavior is unchanged
   apart from the new optional recompile_limit override.
2. _PrecompileDynamoState and _precompile_dynamo_stateful: the state owns
   the cloned capture fn (installed code caches stay live between calls),
   the CompilePackage new variants accumulate into, the optimize wrapper --
   whose isolate-recompiles bucket is what keeps earlier variants visible
   to later calls -- the isolated PGO record (so a dimension that varies
   across calls recompiles into a symbolic graph exactly as it would within
   one call), and every example tuple seen so far, because guard
   minimization re-checks all of them on every rebuild (the full
   rebuild-and-recheck path runs per call; it is repeated work, not wrong
   work). Config patches are entered per call and exited before returning,
   so nothing leaks into the caller's loop.
3. _DynamoPythonBackend.finalize_training(keep_capture=True): a training
   snapshot that composes the backward variants recorded so far (finalize
   is a pure compose) while leaving the live variant-compiler hook
   installed, so real backwards run by the caller between calls keep
   recording new tangent masks.
4. torch/_dynamo/guards.py: fixes a latent guards-serialization bug the
   stateful flow exposes on its second call (and any one-shot capture whose
   example tensor already carries .grad). GuardsStatePickler serializes a
   guarded tensor's .grad alongside it, but the grad tensor is not in
   guard_tree_values, so it pickled as a _Missing placeholder that
   _unpickle_tensor cannot assign back (TypeError at load_guards_state).
   The reducer now registers the grad in guard_tree_values so it serializes
   as a meta tensor like its owner.

A review round on this commit's own diff fixed four issues, each with a
test verified to fail before its fix:

- Training snapshots dropped the ordinary all-tangents-defined backward
  (mask 0) once any partial backward had run between calls: _finalize's
  [0] fallback applies only when NO masks were observed, so a rewritten
  artifact could no longer serve a full backward that the previous
  artifact served. finalize_training now always unions mask 0 into the
  snapshot.
- Abandoned states leaked the whole capture session process-wide: Dynamo's
  recompile logging strong-keys the capture code object in the
  module-level guard_failures registry, transitively pinning the copied fn
  globals (and anything they reference). _PrecompileDynamoState.close()
  releases the session (teardown now also pops guard_failures and the
  cached_backends entry); a closed state cannot be resumed.
- A tangent mask whose deferred compile fails is recorded before compiling,
  so it poisoned every later rebuild; snapshot finalize now drops such
  masks with a warning (serving that pattern then fails like any
  unobserved pattern), and a resumed call whose rebuild fails says the
  state cannot make further progress instead of implying it can.
- The artifact/cache pair was written artifact-first, leaving a
  code_hash-mismatched pair on disk if the process died during the cache
  write; both temp files are now written before two back-to-back renames.

Smaller hardening from the same round: _dynamo_capture_context patches
caching_precompile off so capture-internal packages stay out of the global
PrecompileContext; a disabled Dynamo (TORCHDYNAMO_DISABLE) is rejected up
front with a clear PrecompileError instead of failing later with a
misleading one; the guards.py grad fix also pops the grad from the
pickler's missing_values so a grad that doubles as an unguarded local
still serializes.

Not included, called out for reviewers: keep_example_grads is unnecessary
on this path (the dynamo tracer never touches example grads; every call is
a real step whose outputs the caller backwards through), and
require_no_risky_drops belongs to guard-policy machinery that is not part
of this PR. nn.Module example arguments and graph breaks remain rejected,
so a full pipelined train step still needs the upcoming stack entries;
this PR delivers the entry-point mechanics.

This PR was authored with an AI assistant (Claude Code); every change was
verified on a from-source build.

Test Plan:

```
.venv/bin/python test/test_precompile.py
# Ran 225 tests ... OK  (new: stateful accumulate/rewrite with a guard-hit
# third call pinning VARIANT_COUNT, stateful training with backward between
# calls, stateful validation errors, recompile_limit kwarg, a
# populated-.grad example capture pinning the guards.py fix, partial-
# backward mask-0 coverage, close() releasing the guard_failures pin,
# failed-mask snapshot fallback, and the disabled-Dynamo rejection)

.venv/bin/python test/dynamo/test_guard_serialization.py   # OK
.venv/bin/python test/dynamo/test_package.py               # OK
.venv/bin/python test/functorch/test_compile_to_python.py  # Ran 62 tests ... OK

lintrunner torch/_precompile.py torch/_dynamo/guards.py \
  test/test_precompile.py docs/source/torch.compiler_api.md \
  docs/source/user_guide/torch_compiler/torch.compiler.md
# ok No lint issues.
```

The populated-grad repro fails on the parent commit with "TypeError:
assigned grad expected to be a Tensor or None but got grad of type
_Missing" and passes with the guards.py fix.

Co-Authored-By: Claude Fable 5 <[email protected]>
@bobrenjc93
bobrenjc93 force-pushed the precompile-dynamo-tracer-v2 branch from c3bde18 to d265afb Compare August 28, 2026 01:22
#195070)

A comparison against the ghstack implementation ending at #195070 (the
accumulate() session shape of the same caller-owned-loop feature) surfaced
several ideas worth having regardless of API shape. This ports the ones
that fit this stack's foundation:

- _write_dynamo_artifact_files now creates parent directories, fsyncs both
  temp files before the back-to-back renames, and unlinks its temp files
  when a write fails, so a failed rewrite leaves the previous pair and no
  litter (their _write_artifact's exact discipline, with their flaky-open
  crash test ported alongside).
- Guard-drop observability: _filter_dynamo_guards reports the (guard type,
  source) pairs it minimized away, aggregated and deduplicated across
  variants (a listed pair was dropped from at least one variant's dispatch
  and may remain checked in others -- the artifact comment, docstrings, and
  a two-variant test pin that reading); they are embedded in the artifact
  as a _DROPPED_GUARDS section and surfaced through the new
  state.summary() -> PrecompileStateSummary (calls, examples, variants,
  graphs, dynamic graphs, dropped guards), the counterpart of their
  summary()/POLICY_DROPPED_GUARDS reporting.
- dynamic= is now a real kwarg (forwarded to torch._dynamo.optimize, None
  keeps the automatic policy) and rides in the stateful consistency check
  alongside backend/training/recompile_limit, closing the one field of the
  original ask's requirement 4 that had nothing to check.
- precompile.load(artifact_path=..., cache_path=...) reads the pair a
  stateful capture wrote, mirroring their path-based load.
- The stateful default recompile_limit is now
  max(torch._dynamo.config.recompile_limit, 256): accumulating captures
  outgrow the example-count default immediately (their accumulate defaults
  to 256 outright).
- A raised call no longer being able to freeze the loop is now pinned by a
  test (a graph-breaking call fails loudly; the next good call captures and
  rewrites), matching their survives-a-call-that-raised semantics, which
  this implementation already had but never proved.

Deliberately NOT ported, called out for reviewers: nn.Module arguments,
graph breaks/multi-frame artifacts, kwargs/ExampleInput, and serve-time
compilation are foundation-level features of that stack's 63-PR base, not
ideas this diff can absorb; and serving-compiles-on-miss is a contract
decision (this stack's artifacts deliberately raise instead).

This PR was authored with an AI assistant (Claude Code); every change was
verified on a from-source build.

Test Plan:

```
.venv/bin/python test/test_precompile.py
# Ran 230 tests ... OK  (new: summary()/dropped-guards reporting, dynamic=
# kwarg incl. resume mismatch, path-based load validation, writer crash
# cleanup, survives-a-raised-call)

lintrunner torch/_precompile.py test/test_precompile.py \
  docs/source/torch.compiler_api.md
# ok No lint issues.
```

The dropped-guards test pins the exact minimized pairs
(EQUALS_MATCH/CONSTANT_MATCH on a module-global constant) in both the
summary and the artifact text; the writer test ports #195070's flaky-open
scenario and asserts the previous pair survives with no .tmp litter.

Co-Authored-By: Claude Fable 5 <[email protected]>
@bobrenjc93
bobrenjc93 force-pushed the precompile-dynamo-tracer-v2 branch from 05e9e61 to a3a84b3 Compare August 28, 2026 03:06
bobrenjc93 and others added 5 commits August 28, 2026 04:23
…ful capture, contain constexpr rendering

Follow-ups from review of #195044. Start reviewing in torch/_precompile.py:
_validate_dynamo_capture regains two rejections that the tracer
simplification dropped while the PR description still promised them. Both
share a root cause: capture runs against a copy of fn.__globals__ and the
artifact serves from its own namespace, so a referenced tensor-valued global
captured fine and then served a raw NameError, and a `global X; X = ...`
mutation was silently discarded at both capture and serve time. Both now
raise PrecompileError up front.

Next the stateful loop: Dynamo installs a guarded variant at frame entry but
the example was only recorded after the step returned, so a step raising
after a successful recompile (a data-dependent runtime error) left a variant
matching no recorded example and every later rebuild failed guard
minimization (reproduced with an out-of-bounds gather under dynamic=False).
Examples are now recorded before they run. The state also gains a warn-only
weakref finalizer for the forgotten-close() leak, and close() sets its flag
under the compile lock.

Then load(): the two-rename rewrite window could leave a code_hash-mismatched
pair that load() hard-rejected, contradicting the "always loadable" contract;
for dynamo artifacts (whose python_code is fully self-contained) that
mismatch now degrades to a cold cache with a warning, while make_fx keeps the
strict pairing check. The torch-version stamp returns
(_DYNAMO_TORCH_VERSION, checked in the driver before unpickling) so a foreign
build fails with a clean PrecompileError instead of an arbitrary unpickling
error, and the dead python_module state key is gone.

Finally the Inductor containment fixes: set-subclass constexprs (OrderedSet)
reconstruct their exact type in iteration order or decline instead of
silently degrading to a sorted builtin set; the rendered _SourceLiteral
placeholders stay local to the emitted source instead of leaking into the
returned/cached kernel metas (whose consumers compare by equality, which
_SourceLiteral never satisfies against real values); the autotune cache skips
configs whose Enum kwargs do not survive a JSON round-trip (a tuple value
came back as a list, matched nothing, and the reconstruct fallthrough baked
the degraded list into the kernel on warm start -- now it re-autotunes); and
the NaN constexpr rejection explains itself.

Docs/description drift is fixed alongside (recompile_limit defaults, version
pinning, the restored rejections), and tests cover each fix: the review also
showed the torch-global guard-filter test could pass vacuously, the
recompile-limit test depended on the ambient config default, stateful tests
leaked their session pin, and several assertions pinned formatting rather
than behavior; those are corrected, subprocess serve tests now run under
TORCHDYNAMO_DISABLE=1, and the public cache-primed load() path gets a cold
fresh-subprocess test.

Authored with an AI assistant (Claude Code); all changes reviewed and tested
locally.

Test plan:

```
python test/test_precompile.py                         # Ran 237 tests ... OK
python test/inductor/test_codegen_triton.py            # Ran 55 tests ... OK (skipped=2)
python test/inductor/test_triton_heuristics.py         # OK (skipped=4)
python test/inductor/test_coordinate_descent_tuner.py  # Ran 14 tests ... OK
python test/functorch/test_compile_to_python.py        # Ran 62 tests ... OK
lintrunner <touched files>                             # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>
…e-record, broader tensor-global scan

Adversarial verification of the previous review-fix commit surfaced one
regression it introduced, one demonstrated correctness hole, and several
fixes narrower than documented. Start reviewing in torch/_precompile.py.

The stateful loop's record-before-run fix regressed wrong-arity calls: an
example that does not bind to the fn's signature raised TypeError from the
call but stayed recorded, and guard minimization signature.bind()s every
recorded example on every rebuild, so one caller arity mistake poisoned the
state permanently. The loop now probes the bind first and records only
bindable examples.

Distinct tensor inputs sharing or overlapping storage could serve silently
wrong results: their AOT StorageOverlap relation has no serialized form (the
artifact's aotautograd_guards are empty), so a mutating variant captured on
non-overlapping inputs computed the wrong thing on overlapping views where
plain torch.compile raises. Capture now rejects overlapping example inputs
and the emitted driver rejects overlapping runtime inputs; passing the same
tensor object more than once remains supported (identity aliasing has
serialized dynamo guards, covered by the existing relational-guards test).

The tensor-global rejection missed tensors held as class attributes and as
attributes of user modules because the reachability walk stopped at types and
modules; it now traverses non-library classes (through the MRO), non-library
modules, and instance types, and its error message states the deliberately
conservative rule (a global is rejected when any tensor is reachable from
it). The walk is also gated to run once per stateful state instead of on
every resumed call, since the programming model declares the environment
invariant.

In torch/_inductor, the set-subclass constexpr branch emitted
hash-order-nondeterministic source for non-OrderedSet subclasses and
constructor-crashing source for subclasses without an iterable constructor;
only OrderedSet (known order semantics, list constructor) now reconstructs,
and every other subclass declines to the actionable render error. The
autotune-cache JSON-cacheable predicate now checks value stability for all
kwargs rather than only Enum payloads, closing the same warm-load divergence
for bare tuple kwargs, and save() skipping is directly unit-tested. A
cpp_wrapper/AOTI enum-constexpr test covers the meta-consuming path that had
no coverage.

Test-quality fixes from the same verification: the over-recompile-limit test
was vacuous (automatic dynamic folded 9 examples into 2 variants; it now pins
dynamic=False and VARIANT_COUNT = 9), the TORCHDYNAMO_DISABLE subprocess
comments overclaimed (the env var silently no-ops dynamo, so the no-compile
property is now pinned by a frame-counter assertion in the load subprocess
test instead), and the state-key assertion returns to an exact set as a
deliberate format pin. load()'s docstring and the module notes now describe
the dynamo code_hash degrade carve-out, and the stateful return-type design
decision is recorded in the docstring and PR description.

Authored with an AI assistant (Claude Code); all changes reviewed and tested
locally.

Test plan:

```
python test/test_precompile.py                         # Ran 240 tests ... OK
python test/inductor/test_codegen_triton.py            # Ran 57 tests ... OK (skipped=2)
python test/inductor/test_triton_heuristics.py         # OK (skipped=4)
python test/inductor/test_coordinate_descent_tuner.py  # OK
lintrunner <touched files>                             # ok No lint issues.
```

The overlap fix was verified against the review's reproducer (previously:
silent wrong results / raw AssertionError; now: PrecompileError at capture
and at serve), and the wrong-arity fix against its reproducer (previously:
state permanently poisoned; now: raises without recording, later calls keep
capturing).

Co-Authored-By: Claude Fable 5 <[email protected]>
…e the slots hole, batch-probe binds

Adversarial verification of the second-round commit found its widened
reachability walker leaked into the wrong check, missed one shape it was
built for, and paired a false claim with the new bind probe. Start in
torch/_precompile.py.

The walker widening (classes, modules, instance types) was meant for the
tensor-global scan but reaches() is shared, so the per-argument nn.Module
check began rejecting arguments whose CLASS carries an nn.Module attribute
the fn never touches -- a regression of previously-working captures with an
inaccurate message. The widening is now opt-in (follow_types=True), used
only by the tensor-global scan; argument, default, and alias checks keep
judging values by what they carry. At the same time the widened walk itself
missed __dict__-less instances entirely (the hasattr gate returned before
the instance-to-type step), so a slotted global whose class attribute or
slot value is a tensor still captured and served a raw NameError; the
instance branch now reads slot values through their member descriptors and
always falls through to the type when following types.

The bind probe ran per example inside the run loop, so a batch of
[good, bad] examples recorded and ran the good one while the error claimed
"The state is unchanged." All examples of a call are now probed before any
is recorded or run, and the message says exactly that.

The storage-overlap check keeps its storage granularity as a recorded
decision rather than an accident: AOTAutograd's synthetic-base mutation
handling keys on shared storage, not element overlap, so relaxing to
element ranges would readmit the silent-wrong-results hole for mutating
fns captured on same-storage disjoint views. Comments in both copies and
the PR description now say so. Around it: non-strided layouts skip the
check so Dynamo surfaces its own clearer sparse diagnostics, calls with
fewer than two tensors short-circuit (the check was the largest new
per-call term for small models), the data_ptr()==0 exclusion is explained,
and the driver hoists its pytree import out of the per-call path.

autotune_cache's _json_stable_value now also declines non-finite floats
(NaN never ==-matches its cached entry and json.dumps emits non-strict
tokens strict-JSON remote caches reject).

Test fixes from the same review: the tensor-global loop runs each fn as a
subTest (a failure now names the case), the OrderedSubSet decline is pinned
against a fully importable subclass (the previous local class declined via
its qualname, so the type gate was untested), and the frame-counter
subprocess strips TORCHDYNAMO_DISABLE from the child env and asserts dynamo
is enabled, so an ambient variable cannot void the no-compile assertion.

Authored with an AI assistant (Claude Code); all changes reviewed and
tested locally.

Test plan:

```
python test/test_precompile.py                         # Ran 241 tests ... OK
python test/inductor/test_codegen_triton.py            # Ran 57 tests ... OK (skipped=2)
python test/inductor/test_triton_heuristics.py         # OK (skipped=4)
python test/inductor/test_coordinate_descent_tuner.py  # OK
lintrunner <touched files>                             # ok No lint issues.
```

The nn.Module-class-attribute regression and both slotted holes are pinned
by new tests that fail on the parent commit; the mixed good/bad batch case
asserts via summary() that nothing was recorded.

Co-Authored-By: Claude Fable 5 <[email protected]>
…y slot values as instance state, reject exotic layouts

Adversarial verification of the third-round commit demonstrated that its
follow_types scoping, added to stop the argument check from judging values
by their types, also de-scoped the input-alias scan -- and that reopened a
silent-wrong-result: an input aliased through a global class attribute
(Holder.payload is p) or a user-module attribute captured fine, guard
minimization classified the identity guard as environment and dropped it,
and serving with a non-aliasing input returned the capture-time branch.
The alias scan is a scan of globals, exactly like the tensor-global scan,
so it now passes follow_types=True; per-argument checks keep the narrow
walk. Verified against the review's reproducer (now rejected at capture)
and pinned by tests for both alias shapes.

Slot values were gated behind follow_types, which contradicted the
scoping's own rationale: slots are instance state -- what the object
carries -- so a box holding an nn.Module in a slot captured where the
identical __dict__ box was rejected, and a tensor in a slotted default
slipped past the defaults check. The slot walk now runs for every caller;
only the type traversal remains gated. A literal fast-path keeps the
per-argument cost flat for scalar-heavy inputs.

The overlap check's non-strided skip claimed Dynamo would reject those
layouts with better diagnostics; true for sparse, false for jagged --
Dynamo accepts NJT inputs, so the skip silently admitted an input surface
whose aliasing the artifact cannot verify (previously rejected loudly via
the storage probe error). The skip now names the sparse layouts
explicitly; every other non-strided layout is refused at capture and at
serve, independent of tensor count.

Authored with an AI assistant (Claude Code); all changes reviewed and
tested locally.

Test plan:

```
python test/test_precompile.py                # Ran 246 tests ... OK
python test/inductor/test_codegen_triton.py   # Ran 57 tests ... OK (skipped=2)
lintrunner <touched files>                    # ok No lint issues.
```

The alias regression is pinned by tests that fail on the parent commit
(the class-attr case silently captures there); the slot-value tests and
the jagged capture/serve rejections likewise fail on the parent.

Co-Authored-By: Claude Fable 5 <[email protected]>
… state, exempt value-guarded singletons

Adversarial verification of the fourth-round commit measured its re-widened
alias scan at 28ms of validation per stateful resume for a fn that merely
references numpy (5.7x total call latency), and demonstrated that the
id-based aliasing rejection falsely bans a sound pattern: torch.float32
passed as an input while also living on a referenced config class, with an
error whose remedy cannot be followed since the singleton inherently lives
on the class.

The expensive half of the alias walk -- enumerating every object id
reachable from each referenced global -- is input-independent, so
validation now splits into a narrow per-argument walker (containers,
__dict__, slot values) and a wide environment collector that runs once per
capture, returns {global -> (reachable ids, tensor reached)}, and is cached
on the stateful state; resumed calls only intersect the cached ids with the
current example's leaf ids. This also folds the tensor-global and alias
scans into one walk for one-shot captures. Measured: a numpy-referencing
stateful resume is back to 5.6ms median from 34.1ms.

The aliasing rejection now exempts process-wide singletons whose guards are
value-based and whose pickles return the same object -- torch.dtype,
torch.layout, torch.memory_format, and enum members -- because sharing one
with the environment carries no identity hazard (an enum input that
genuinely needs an identity guard still fails later with Dynamo's accurate
cannot-serialize error). torch.device is deliberately not exempt: equal
devices need not be identical, so an `is` branch could silently flip. The
dtype-config pattern is pinned by a regression test serving both dtype
variants, and the docs now describe the aliasing rejection, the singleton
exemption, and the non-strided layout policy, which they previously
omitted entirely.

Authored with an AI assistant (Claude Code); all changes reviewed and
tested locally.

Test plan:

```
python test/test_precompile.py   # Ran 247 tests ... OK
lintrunner <touched files>       # ok No lint issues.
python agent_space/perf_resume2.py  # median resume: 5.6ms (was 34.1ms)
```

Known pre-existing edge surfaced while probing (unchanged by this commit,
reproduced on the parent): stateful capture with dynamic=True and a varying
int argument can fail loudly at rebuild with "guard filtering changed
captured example dispatch".

Co-Authored-By: Claude Fable 5 <[email protected]>
bobrenjc93 and others added 4 commits August 29, 2026 00:09
…recompile.stateful, fall back when a worker cannot import a constexpr module

Adopts the remaining review recommendations. Review torch/_precompile.py
first, then the async-compile fallback, then the test restructuring.

precompile.stateful: stateful capture was a mode of precompile() keyed on
passing artifact_path/cache_path, and both modes returned 2-tuples -- so
calling the wrong mode failed silently at unpack time and the return
annotation was a union naming a private class. It is now a sibling entry
point, precompile.stateful(fn, *, example_inputs, artifact_path, cache_path,
state=None, backend, training, recompile_limit, dynamic), mirroring how load
already lives on the namespace object. The dynamo tracer is implied, the
capture semantics are unchanged (the entry point forwards to the same
internals), and precompile() no longer accepts state/artifact_path/cache_path
at all, so mixing the modes is a TypeError instead of a silent misparse. The
reference docs get a dedicated precompile.stateful entry and the docstrings
record the split and its rationale.

Worker constexpr imports: the importable-reference rendering emits
`import user_module as __inductor_constexpr_module_N` into generated kernel
source, which async-compile subprocess workers exec; the worker pool bakes
PYTHONPATH at spawn, so a module the parent can import (added to sys.path
after the warm pool spawned) raised ModuleNotFoundError in the worker and
hard-failed the compile -- there was no per-kernel fallback. AsyncCompile's
get_result now detects a worker ModuleNotFoundError that names exactly one of
these generated imports and falls back to an in-process compile with a
warning (codegen already validated the import in the parent, so the fallback
always succeeds); any other worker failure re-raises as before. The serial
branch and the fallback share one extracted _compile_triton_in_process.
Covered by a positive test that proves the import really executes in a real
subprocess worker and a deterministic negative test (module added to sys.path
after pool spawn) that pins the fallback.

Test restructuring: the constexpr mega-test is split into eight focused
methods (subTest where cases are homogeneous), and its live-module mutation
is now mock.patch.object; every assertion survived verbatim.

Test Plan:

```
python test/test_precompile.py                          # 267 tests, OK
python test/inductor/test_codegen_triton.py             # 70 tests, OK (2 skipped)
python test/dynamo/test_guard_serialization.py          # 63 tests, OK (1 skipped)
lintrunner <touched files>                              # ok No lint issues.
```

The new worker tests were verified load-bearing by stashing the async_compile
fix and watching the fallback test fail.

Authored with an AI assistant.

Co-Authored-By: Claude Fable 5 <[email protected]>
… and duplicate-config warm loads, exempt interpreter singletons from the alias scan

Fixes three regressions the previous two fix commits introduced, all
reproduced end to end before fixing, plus the smaller review items from the
same pass. Review the two inductor regressions first, then the alias-scan
exemptions, then the load/message/doc polish.

torch.Size constexprs: the container-subclass decline policy (eighth round)
switched _constexpr_constant to exact-type checks and made
_constexpr_source_impl decline tuple subclasses, which turned the ordinary
pattern k[grid](out, SHAPE=x.shape) into a hard RuntimeError -- eager and the
pre-decline code both worked (Size coerced to a plain tuple, which is exact
for it: no _fields, iteration and __eq__ inherited). torch.Size is now
special-cased to coerce in both functions; every other subclass decline is
unchanged.

Duplicate-config warm loads: the seventh round made _load_cached_autotuning
return None whenever more than one candidate config matched the cached
payload, to stop Enum-vs-raw ambiguity from baking a raw value. That guard
also caught value-identical multi-matches -- duplicate configs (legal in
Triton and common in generated user_autotune lists) and subset-kwargs
candidates -- silently re-autotuning them on every cold process forever. The
guard is now scoped to actual unwrapping ambiguity: re-autotune only when
some matching kwarg changes under _json_config_value (plain Enums; IntEnum
and str-mixin members ==-match their unwrapped values and are safe);
value-identical multi-matches fall through to reconstruction as they did
before the guard existed.

Interpreter singletons: the deep alias id set (seventh round) walked
example inputs into (), Ellipsis, and NotImplemented -- CPython process-wide
singletons that Dynamo value-guards -- so a helper default like dims=() plus
a caller passing () anywhere in an example raised a misleading "aliases the
Python environment" error for a legitimate call. They join the exempt set,
as do functions, classes, and modules an argument merely carries (the enum
rationale: a USED reference gets an unserializable identity guard and fails
loudly; an unused one never influences dispatch).

Smaller items from the same review pass: load(python_code, b"") warns before
degrading to JIT again (the empty in-memory cache previously warned via the
envelope-parse failure; the seventh round's `if cache` guard silenced it); a
FRESH stateful call that hits the recompile limit gets the plain
pass-a-larger-limit advice since it self-closes and never returns its state
(close()-and-recapture only fits resumed calls); the constexpr-import worker
fallback memoizes its kernel so re-entrant .result() calls neither recompile
nor re-warn; the missing-cache-file degrade is documented as
tracer-independent (it runs before the tracer is known); the GC-warning test
releases its session via addCleanup so an assertion failure cannot leak the
pinned session into the suite; and the guard-serialization tuple harness now
requires every requested guard type to match, so the ordering tests cannot
silently degrade if dict-local guard emission changes.

Every new test was verified load-bearing by stashing its fix and watching it
fail. Authored with an AI assistant; each regression was reproduced at the
prior commit before fixing.

Test Plan:

```
python test/test_precompile.py                          # 271 tests, OK
python test/inductor/test_codegen_triton.py             # 73 tests, OK (2 skipped)
python test/inductor/test_triton_heuristics.py          # 58 tests, OK (4 skipped)
python test/dynamo/test_guard_serialization.py          # 63 tests, OK (1 skipped)
lintrunner <touched files>                              # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>
…ds, freeze snapshot metadata, serve newest variant first

Fixes four reproduced correctness bugs from this round's review, hardens the
load path, and restores autotune caching for tuple config kwargs. Review the
guard-classification fix first (it is the only silent-wrong-numerics bug),
then the snapshot and dispatch-order changes, then the load/driver hardening,
and the inductor pair last.

Input-guard classification: guard minimization classified a guard as
input-derived by string prefix on its rendered name ("L['x']", "L['x'].",
"L['x']["), but many input-rooted Dynamo sources render as call expressions
(___tuple_iterator_getitem(L['it'], 0), ___from_numpy(L['x']), type(L['x']),
list(dict.keys(L['d']))[0], ...). Those were misclassified as environment
guards, and dropping one always succeeds against the examples that produced
the variant, so the artifact silently served the capture-time specialization
for calls whose values differ (an iterator input reproduced this end to end:
different item values returned the baked constants with no error).
Classification now walks the guard's originating_source base chain to its
root and keeps everything rooted at a LocalSource of a bound parameter.

Snapshot metadata freezing: recorded example tensors were kept by reference
on the rationale that guards check metadata, not data -- which is exactly
what in-place METADATA mutation (resize_, transpose_, requires_grad_)
breaks. One such mutation, by the step fn or the caller between stateful
calls, permanently poisoned the state: every later rebuild failed its
"variant does not match any example" re-check. Snapshots now record
metadata-frozen storage aliases (as_strided views built under no_grad, one
per unique tensor through the shared deepcopy memo, so identity and aliasing
relations are preserved and no data is copied); a tensor that cannot be
re-aliased falls back to the old by-reference recording.

Newest-first dispatch: the artifact's variants were emitted in chronological
guarded_codes order while live Dynamo checks recompilations LRU-front-first,
so an input matching both an early static variant and a later dynamic one
(the automatic-dynamic revisit pattern) was served by a different graph than
capture used -- benign for inference, but with training=True the tangent
masks live on the backend that actually served capture, so replaying the
exact capture sequence could raise "unseen tangent pattern". Variants are
now emitted newest-first, matching what live dispatch served.

Capture-environment fixes: the capture context patches suppress_errors=False
(eval_frame asserts it is off whenever fail_on_recompile_limit_hit is on, so
a process-level TORCHDYNAMO_SUPPRESS_ERRORS=1 failed every capture with that
raw assertion -- and suppressing would silently build artifacts from
uncaptured runs anyway), and numpy.ndarray example inputs are rejected up
front with a convert-to-tensor message (their ___from_numpy TENSOR_MATCH
guard construction dies inside the save-guards path as an
InternalTorchDynamoError).

Load/driver hardening: load() emits the untrusted-input warning BEFORE
unpickling the cache rather than after (the warning previously fired only
once the risk had been taken); a non-literal metadata assignment raises
PrecompileError instead of ast's raw ValueError; the emitted driver runs its
Python/torch version checks before importing torch._dynamo.package (a
foreign build now fails with the version message, not a raw ImportError) and
installs the builtins dict under its per-compile key like the mainline
CompilePackage loader (defense in depth: a retained builtins-routed guard
would otherwise silently fail every call); the write-failure comment now
describes the second-rename window accurately.

Inductor: tuple-valued autotune config kwargs are cacheable again -- the
eighth-round JSON-round-trip guard skipped them entirely (permanent
cold-start re-autotune plus a warning on every save). _json_config_value now
serializes tuples as lists so candidate matching compares the shape
json.loads hands back, and a unique match returns the original Config object
with its tuple types intact; reconstruction (which would bake a list) is
refused whenever some candidate kwarg degrades under the round-trip. The
constexpr worker-import fallback also catches the raw ModuleNotFoundError
that spawn/fork worker pools re-raise (previously only the subprocess pool's
SubprocException), closing the gap against the codegen comment that promised
the fallback.

Tests: regression tests for each fix above (each verified load-bearing
against the unfixed library), stateful argument-validation and
positional-form-with-dynamo coverage, make_fx path-form load coverage, CPU
coverage for the ninth-round torch.Size constexpr fix, bytearray and
_SourceLiteral unit tests, a caches-disabled skip guard for the coordesc
stamp test, timeouts on the fresh-process subprocess tests, and @parametrize
/ subTest / mock.patch.dict / TEST_CUDA cleanups in test_precompile.py.

Authored with an AI assistant; every behavior fix was reproduced at the
prior commit before fixing and re-verified after.

Test Plan:

```
python test/test_precompile.py                          # 286 tests, OK
python test/inductor/test_codegen_triton.py             # 81 tests, OK (2 skipped)
python test/inductor/test_triton_heuristics.py          # 58 tests, OK (4 skipped)
python test/dynamo/test_guard_serialization.py          # 63 tests, OK (1 skipped)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
lintrunner <touched files>                              # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>
…pe and grad, reject numpy scalars

Fixes two capture regressions the tenth round's metadata-frozen snapshots
introduced, both reproduced A/B against the prior commit before fixing, plus
the smaller items from the same review pass. Review the snapshot fix first,
then the numpy widening, then the autotune guard move.

Snapshot type and grad: _freeze_tensor_metadata built its storage alias with
as_strided, which on an nn.Parameter (or any _disabled_torch_function_impl
subclass) SUCCEEDS but decays to a plain Tensor -- so the except-fallback
never fired, and TENSOR_MATCH's exact-pytype check failed the guard re-check
on every recorded example ("captured a variant that does not match any
example input") for the advertised parameters-as-inputs pattern. The alias
was also a fresh leaf built under no_grad, so its .grad was None while the
original carried one, failing the GradSource-rooted guards of an
optimizer-style step that reads x.grad -- exactly the in-place-update
pattern the stateful docstring promises. The alias now restores the input's
exact type via as_subclass and carries .grad by reference (gated on
is_leaf/retains_grad to avoid the non-leaf access warning); anything that
cannot re-alias still falls back to live recording.

numpy scalars: the tenth round's up-front numpy rejection only matched
ndarray, but numpy scalars (numpy.generic, e.g. np.float64) route through
the same ___from_numpy guard path and died with a raw internal TypeError
from guard-tree loading -- the exact error class the rejection claims to
preclude. The isinstance now covers numpy.generic and the message says how
to convert either form.

Autotune degradation guard: the tuple-caching fix's pre-reconstruction scan
lived only in the non-coordesc branch, so a coordesc-stamped entry for a
tuple-kwarg config would reconstruct a list-typed constexpr. Unreachable
today (coordesc-eligible kernels have int-only kwargs), but the scan now
runs before reconstruction on both branches so that stays true by
construction if coordesc eligibility ever widens.

Smaller items from the same pass: the three test comments still attributing
the untrusted-input warning to _make_inlined_forward now describe load()'s
warn-before-cache-processing behavior; the emitted-driver builtins-install
assertion is annotated as a presence-only pin (the guarded path is
unreachable via public capture, so there is no behavioral load path to
assert against); and the raw-ModuleNotFoundError fallback test clears the
process-global CompiledTritonKernels cache it would otherwise leave a
Mock-holding future in.

Every new test was verified load-bearing: the Parameter and grad-step
scenarios fail with PrecompileError on the tenth-round snapshot code, and
the numpy-scalar case raised the internal TypeError rather than the asserted
NotImplementedError before the widening. Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/inductor/test_codegen_triton.py             # 81 tests, OK (2 skipped)
python test/inductor/test_triton_heuristics.py          # 58 tests, OK (4 skipped)
lintrunner <touched files>                              # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>
bobrenjc93 added a commit that referenced this pull request Aug 29, 2026
…nt-end, and support stateful incremental capture

Restack of #195044 (unchanged in behavior, eleven review rounds included) on
top of the two new typed-guard-machinery commits below it in this stack,
which replace the parts of the original PR that re-derived information Dynamo
already has:

- Guard classification during minimization now uses Guard.provenance (the
  typed, fail-closed classification added below) instead of walking source
  chains by hand; the environment-vs-input decision cannot drift from
  Dynamo's own source taxonomy.
- The unserializable-identity-guard error surface now consumes the typed
  GuardSerializationError chained through convert_frame's PackageError
  instead of string-matching an AssertionError message, and the resulting
  PrecompileError names the exact guard (type and source) that blocked
  serialization. The convert_frame message-constant hack from the original
  PR is gone.

Summary of the feature (see the original PR for the full history):
torch.compiler.precompile lowers a whole computation to a self-contained,
runnable Python source string plus a binary acceleration cache. This PR
generalizes the API to a set of observed calls (example_inputs= tuples; the
positional form remains as a single example call), adds a tracer="dynamo"
front-end that executes every example tuple and captures each guarded
specialization and recompilation it produces (including automatic-dynamic
graphs when a dimension varies across examples, served newest-first by guard
check at load), supports training=True (dynamo + inductor: readable Inductor
source for AOTAutograd forward and backward bridged by an emitted
torch.autograd.Function, backward variants specialized to observed
output-tangent patterns), and adds precompile.stateful for capturing
incrementally from a loop the caller owns: every call runs its example
tuples for real, accumulates newly exercised guarded variants into an opaque
resumable state, atomically rewrites an always-loadable artifact/cache pair
on disk, and returns the call's real results. Guards derived from explicit
inputs are retained for dispatch; guards on the Python environment may be
dropped (the environment is a declared caller invariant). Rejections are
loud: graph breaks, closures, nn.Module / numpy array / numpy scalar
arguments, overlapping tensor inputs, tensor-reachable globals, and
global-mutating functions all fail with clear errors.

Supersedes #195044.

Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 7 tests, OK
python test/inductor/test_codegen_triton.py             # 81 tests, OK (2 skipped)
python test/inductor/test_triton_heuristics.py          # 58 tests, OK (4 skipped)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
lintrunner <touched files>                              # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>
ghstack-source-id: 7f94f93
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 29, 2026
…nt-end, and support stateful incremental capture

Restack of #195044 (unchanged in behavior, eleven review rounds included) on
top of the two new typed-guard-machinery commits below it in this stack,
which replace the parts of the original PR that re-derived information Dynamo
already has:

- Guard classification during minimization now uses Guard.provenance (the
  typed, fail-closed classification added below) instead of walking source
  chains by hand; the environment-vs-input decision cannot drift from
  Dynamo's own source taxonomy.
- The unserializable-identity-guard error surface now consumes the typed
  GuardSerializationError chained through convert_frame's PackageError
  instead of string-matching an AssertionError message, and the resulting
  PrecompileError names the exact guard (type and source) that blocked
  serialization. The convert_frame message-constant hack from the original
  PR is gone.

Summary of the feature (see the original PR for the full history):
torch.compiler.precompile lowers a whole computation to a self-contained,
runnable Python source string plus a binary acceleration cache. This PR
generalizes the API to a set of observed calls (example_inputs= tuples; the
positional form remains as a single example call), adds a tracer="dynamo"
front-end that executes every example tuple and captures each guarded
specialization and recompilation it produces (including automatic-dynamic
graphs when a dimension varies across examples, served newest-first by guard
check at load), supports training=True (dynamo + inductor: readable Inductor
source for AOTAutograd forward and backward bridged by an emitted
torch.autograd.Function, backward variants specialized to observed
output-tangent patterns), and adds precompile.stateful for capturing
incrementally from a loop the caller owns: every call runs its example
tuples for real, accumulates newly exercised guarded variants into an opaque
resumable state, atomically rewrites an always-loadable artifact/cache pair
on disk, and returns the call's real results. Guards derived from explicit
inputs are retained for dispatch; guards on the Python environment may be
dropped (the environment is a declared caller invariant). Rejections are
loud: graph breaks, closures, nn.Module / numpy array / numpy scalar
arguments, overlapping tensor inputs, tensor-reachable globals, and
global-mutating functions all fail with clear errors.

Supersedes #195044.

Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 7 tests, OK
python test/inductor/test_codegen_triton.py             # 81 tests, OK (2 skipped)
python test/inductor/test_triton_heuristics.py          # 58 tests, OK (4 skipped)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
lintrunner <touched files>                              # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>
ghstack-source-id: 7f94f93
Pull-Request: #195288
bobrenjc93 added a commit that referenced this pull request Aug 29, 2026
…nt-end, and support stateful incremental capture

Restack of #195044 (unchanged in behavior, eleven review rounds included) on
top of the two new typed-guard-machinery commits below it in this stack,
which replace the parts of the original PR that re-derived information Dynamo
already has:

- Guard classification during minimization now uses Guard.provenance (the
  typed, fail-closed classification added below) instead of walking source
  chains by hand; the environment-vs-input decision cannot drift from
  Dynamo's own source taxonomy.
- The unserializable-identity-guard error surface now consumes the typed
  GuardSerializationError chained through convert_frame's PackageError
  instead of string-matching an AssertionError message, and the resulting
  PrecompileError names the exact guard (type and source) that blocked
  serialization. The convert_frame message-constant hack from the original
  PR is gone.

Summary of the feature (see the original PR for the full history):
torch.compiler.precompile lowers a whole computation to a self-contained,
runnable Python source string plus a binary acceleration cache. This PR
generalizes the API to a set of observed calls (example_inputs= tuples; the
positional form remains as a single example call), adds a tracer="dynamo"
front-end that executes every example tuple and captures each guarded
specialization and recompilation it produces (including automatic-dynamic
graphs when a dimension varies across examples, served newest-first by guard
check at load), supports training=True (dynamo + inductor: readable Inductor
source for AOTAutograd forward and backward bridged by an emitted
torch.autograd.Function, backward variants specialized to observed
output-tangent patterns), and adds precompile.stateful for capturing
incrementally from a loop the caller owns: every call runs its example
tuples for real, accumulates newly exercised guarded variants into an opaque
resumable state, atomically rewrites an always-loadable artifact/cache pair
on disk, and returns the call's real results. Guards derived from explicit
inputs are retained for dispatch; guards on the Python environment may be
dropped (the environment is a declared caller invariant). Rejections are
loud: graph breaks, closures, nn.Module / numpy array / numpy scalar
arguments, overlapping tensor inputs, tensor-reachable globals, and
global-mutating functions all fail with clear errors.

Supersedes #195044.

Authored with an AI assistant.

Test Plan:

```
python test/test_precompile.py                          # 288 tests, OK
python test/dynamo/test_guard_serialization.py          # 64 tests, OK (1 skipped)
python test/dynamo/test_sources.py                      # 7 tests, OK
python test/inductor/test_codegen_triton.py             # 81 tests, OK (2 skipped)
python test/inductor/test_triton_heuristics.py          # 58 tests, OK (4 skipped)
python test/functorch/test_compile_to_python.py         # 62 tests, OK
lintrunner <touched files>                              # ok No lint issues.
```

Co-Authored-By: Claude Fable 5 <[email protected]>
ghstack-source-id: 7f94f93
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 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
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Precompile surface superseded by #195360/#195362; the aot_autograd and inductor pieces are carried by #195689 and #195687. Closing this squash branch.

@bobrenjc93 bobrenjc93 closed this Sep 3, 2026
@github-actions
github-actions Bot deleted the precompile-dynamo-tracer-v2 branch November 11, 2026 01:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant