Skip to content

[precompile] Serve and load compiled artifacts with a portable Dynamo state - #195288

Closed
bobrenjc93 wants to merge 22 commits into
gh/bobrenjc93/1085/basefrom
gh/bobrenjc93/1085/head
Closed

bobrenjc93 wants to merge 22 commits into
gh/bobrenjc93/1085/basefrom
gh/bobrenjc93/1085/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

This builds out torch._precompile so a torch.compile artifact can be captured
once, persisted, and served later without re-tracing. A precompiled callable
saves two things: the Dynamo state (guards plus the reconstruction code, as an
importable Python module) and the inductor cache bundle. On load, serve is a
pure cache lookup and replay -- it never recompiles -- and dispatches across
saved entries newest-first, honoring the grad-mode the entry was captured under.

Guard serialization keeps only the guards that a served artifact must re-check.
is_input_guard keeps GuardProvenance.INPUT and SYNTHETIC guards (the
dispatch-relevant ones rooted at the traced inputs and shape env, plus any
tracing-internal root a drop policy must never treat as environment) and
_keep_serializable_capture_guards drops GuardProvenance.GLOBAL guards of types
that cannot be serialized; guard minimization then drops, per variant, the
remaining named guards that every recorded example passes without, which the
precompile docs declare an unchecked environment invariant (globals and
context-manager state).

Capture validation for tracer="dynamo". The served bytecode's global loads are
validated at capture: modules the residual bytecode references (a user's
torch/math, or one Dynamo installed under a synthetic name) are recorded as
import sources when they import back to the same object under their name
(torch.ops namespaces and main do not), and any other global it would read
fails capture with the name -- distinguishing a Dynamo-installed helper, which
is a global the user's module never held, from a user global -- instead of a
NameError at serve. Side effects are checked from what Dynamo records for each
compiled code (convert_frame.get_compiled_code_side_effects, collected by a
bytecode hook for the capture session) rather than by pattern-matching the
residual bytecode: a mutation of anything reached through a module global (a
helper's global, an attribute set or deleted on an object a module holds, a
dict or list it holds, a module attribute) would apply the capture-time value
to the SERVING process's objects and is rejected with the path; so is a
mutation of a parameter left at its default, since defaults ship as a pickled
copy the served replay would mutate instead of the object the default names.
Mutations of the call's own argument objects are replayed on the caller's
objects at serve, which the docs state. The storage-overlap probe checks
wrapper tensor subclasses through the tensors they flatten to and rejects the
same inner tensor reached twice, which the guard snapshot cannot express.

Artifacts are pickled, so the loader must be able to import the same symbols the
capture referenced and run a matching torch version, checked before the Dynamo
state is parsed or the cache bundle unpickled; on a code-hash mismatch load()
degrades a dynamo artifact to a cold inductor cache with a warning and rejects a
make_fx artifact with PrecompileError, rather than serving stale compiled code.
load() accepts the cache as bytes, bytearray or memoryview and raises TypeError
for anything else or for mixing in-memory and path arguments (behavior change
versus v2.14.0, where load(code, None) and load(code, "not-bytes") degraded to
JIT with a warning because the envelope read sat inside a broad except).
Artifact files are written atomically (mkstemp in the target directory, fsync,
os.replace, through a symlinked destination) so a crash mid-write cannot leave
a torn artifact.

The tracer is selectable: the default make_fx path and an opt-in dynamo capture
path (documented in the user guide). Stateful capture accumulates variants
across calls and rewrites the artifact after each; a resumed call whose example
Dynamo cannot record (a guard-serialization failure marks the package entry
bypassed, after which no variant is ever recorded again) closes the state and
says so, while a call that failed before Dynamo produced bytecode leaves it
usable. PGO profiles are isolated from serve so a precompiled run does not
pollute an unrelated compile's profile. SECURITY.md covers artifact loading
under "Untrusted models" (load executes the artifact's code and unpickles the
embedded Dynamo state), and the backward doc states the None-versus-zeros
divergence of the undefined-tangent specialization precompile builds on.

Suggested review order: torch/_precompile.py (save/serve/load and the guard
filters), torch/_precompile_driver.py (the driver), torch/_dynamo/pgo.py (the
isolation hook), then the tests and docs.

Test Plan:

python test/test_precompile.py

313 pass; the 23 errored tests are all TritonMissing (this env has no Triton):
the CUDA numerics tests under TestPrecompileNumericsCUDA, the autotune
cache-bundle test and the static-launcher rehydration test. Coverage includes
tensor-subclass round-trip across backend x tracer, config restoration after
dynamo capture, every module-reachable mutation shape and the defaulted-
parameter case, the stateful lifecycle (resume mismatches, a call that raised,
an unrecordable variant closing the state), and the PGO-isolation /
serve-never-recompiles / optimizer-weakref / ambient-config tests.

Authored with an AI assistant.

Co-Authored-By: Claude Fable 5.1 [email protected]

cc @gujinghui @PenghuiCheng @XiaobingSuper @jianyuh @jgong5 @mingfeima @sanchitintel @ashokei @jingxu10 @min-jean-cho @yanbing-j @Guobing-Chen @Xia-Weiwen @snadampal @albanD @voznesenskym @penguinwu @EikanWang @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @azahed98 @xmfan @aditvenk

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 21 New Failures, 2 Cancelled Jobs

As of commit c0eb264 with merge base 3d3d3f4 (image):

NEW FAILURES - The following jobs have failed:

CANCELLED JOBS - The following jobs were cancelled. Please retry:

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

[ghstack-poisoned]
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
[ghstack-poisoned]
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
@pytorch-bot pytorch-bot Bot added module: compiled autograd compiled_autograd module: mkldnn Related to Intel IDEEP or oneDNN (a.k.a. mkldnn) integration labels Aug 30, 2026
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
[ghstack-poisoned]
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
[ghstack-poisoned]
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
[ghstack-poisoned]
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
[ghstack-poisoned]
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 Sep 2, 2026
… state

This builds out torch._precompile so a torch.compile artifact can be captured
once, persisted, and served later without re-tracing. A precompiled callable
saves two things: the Dynamo state (guards plus the reconstruction code, as an
importable Python module) and the inductor cache bundle. On load, serve is a
pure cache lookup and replay -- it never recompiles -- and dispatches across
saved entries newest-first, honoring the grad-mode the entry was captured under.

Guard serialization keeps only the guards that a served artifact must re-check.
is_input_guard keeps GuardProvenance.INPUT guards (the dispatch-relevant ones
rooted at the traced inputs and shape env) and _keep_serializable_capture_guards
drops GuardProvenance.GLOBAL guards of types that cannot be serialized; ambient
and synthetic guards are handled by the same provenance classification
introduced earlier in this stack.

Artifacts are pickled, so the loader must be able to import the same symbols the
capture referenced and run a matching torch version; load() degrades to a cold
inductor cache with a warning on a code-hash mismatch rather than serving stale
compiled code. Artifact files are written atomically (mkstemp in the target
directory, fsync, os.replace) so a crash mid-write cannot leave a torn artifact.

The tracer is selectable: the default make_fx path and an opt-in dynamo capture
path (documented in the user guide). PGO profiles are isolated from serve so a
precompiled run does not pollute an unrelated compile's profile.

Suggested review order: torch/_precompile.py (save/serve/load and the guard
filters), torch/_precompile_driver.py (the driver), torch/_dynamo/pgo.py (the
isolation hook), then the tests and docs.

Test Plan:

```
python test/test_precompile.py
```

293 pass; the 23 errored tests are all TritonMissing (this env has no Triton):
the CUDA numerics tests under TestPrecompileNumericsCUDA and the two autotune
cache-bundle tests. New coverage: tensor-subclass round-trip across
backend x tracer, config restoration after dynamo capture, and the existing
PGO-isolation / serve-never-recompiles / optimizer-weakref / ambient-config
tests.

Authored with an AI assistant.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

ghstack-source-id: 049f074
Pull-Request: #195288
@bobrenjc93 bobrenjc93 changed the title [precompile] Accept multiple example inputs, add a Dynamo capture front-end, and support stateful incremental capture [precompile] Serve and load compiled artifacts with a portable Dynamo state Sep 2, 2026
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
… state

This builds out torch._precompile so a torch.compile artifact can be captured
once, persisted, and served later without re-tracing. A precompiled callable
saves two things: the Dynamo state (guards plus the reconstruction code, as an
importable Python module) and the inductor cache bundle. On load, serve is a
pure cache lookup and replay -- it never recompiles -- and dispatches across
saved entries newest-first, honoring the grad-mode the entry was captured under.

Guard serialization keeps only the guards that a served artifact must re-check.
is_input_guard keeps GuardProvenance.INPUT guards (the dispatch-relevant ones
rooted at the traced inputs and shape env) and _keep_serializable_capture_guards
drops GuardProvenance.GLOBAL guards of types that cannot be serialized; ambient
and synthetic guards are handled by the same provenance classification
introduced earlier in this stack.

Artifacts are pickled, so the loader must be able to import the same symbols the
capture referenced and run a matching torch version; load() degrades to a cold
inductor cache with a warning on a code-hash mismatch rather than serving stale
compiled code. Artifact files are written atomically (mkstemp in the target
directory, fsync, os.replace) so a crash mid-write cannot leave a torn artifact.

The tracer is selectable: the default make_fx path and an opt-in dynamo capture
path (documented in the user guide). PGO profiles are isolated from serve so a
precompiled run does not pollute an unrelated compile's profile.

Suggested review order: torch/_precompile.py (save/serve/load and the guard
filters), torch/_precompile_driver.py (the driver), torch/_dynamo/pgo.py (the
isolation hook), then the tests and docs.

Test Plan:

```
python test/test_precompile.py
```

293 pass; the 23 errored tests are all TritonMissing (this env has no Triton):
the CUDA numerics tests under TestPrecompileNumericsCUDA and the two autotune
cache-bundle tests. New coverage: tensor-subclass round-trip across
backend x tracer, config restoration after dynamo capture, and the existing
PGO-isolation / serve-never-recompiles / optimizer-weakref / ambient-config
tests.

Authored with an AI assistant.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

ghstack-source-id: 049f074
Pull-Request: #195288
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
… state

This builds out torch._precompile so a torch.compile artifact can be captured
once, persisted, and served later without re-tracing. A precompiled callable
saves two things: the Dynamo state (guards plus the reconstruction code, as an
importable Python module) and the inductor cache bundle. On load, serve is a
pure cache lookup and replay -- it never recompiles -- and dispatches across
saved entries newest-first, honoring the grad-mode the entry was captured under.

Guard serialization keeps only the guards that a served artifact must re-check.
is_input_guard keeps GuardProvenance.INPUT guards (the dispatch-relevant ones
rooted at the traced inputs and shape env) and _keep_serializable_capture_guards
drops GuardProvenance.GLOBAL guards of types that cannot be serialized; ambient
and synthetic guards are handled by the same provenance classification
introduced earlier in this stack.

Artifacts are pickled, so the loader must be able to import the same symbols the
capture referenced and run a matching torch version; load() degrades to a cold
inductor cache with a warning on a code-hash mismatch rather than serving stale
compiled code. Artifact files are written atomically (mkstemp in the target
directory, fsync, os.replace) so a crash mid-write cannot leave a torn artifact.

The tracer is selectable: the default make_fx path and an opt-in dynamo capture
path (documented in the user guide). PGO profiles are isolated from serve so a
precompiled run does not pollute an unrelated compile's profile.

Suggested review order: torch/_precompile.py (save/serve/load and the guard
filters), torch/_precompile_driver.py (the driver), torch/_dynamo/pgo.py (the
isolation hook), then the tests and docs.

Test Plan:

```
python test/test_precompile.py
```

293 pass; the 23 errored tests are all TritonMissing (this env has no Triton):
the CUDA numerics tests under TestPrecompileNumericsCUDA and the two autotune
cache-bundle tests. New coverage: tensor-subclass round-trip across
backend x tracer, config restoration after dynamo capture, and the existing
PGO-isolation / serve-never-recompiles / optimizer-weakref / ambient-config
tests.

Authored with an AI assistant.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

ghstack-source-id: 32f0a34
Pull-Request: #195288
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
… state

This builds out torch._precompile so a torch.compile artifact can be captured
once, persisted, and served later without re-tracing. A precompiled callable
saves two things: the Dynamo state (guards plus the reconstruction code, as an
importable Python module) and the inductor cache bundle. On load, serve is a
pure cache lookup and replay -- it never recompiles -- and dispatches across
saved entries newest-first, honoring the grad-mode the entry was captured under.

Guard serialization keeps only the guards that a served artifact must re-check.
is_input_guard keeps GuardProvenance.INPUT guards (the dispatch-relevant ones
rooted at the traced inputs and shape env) and _keep_serializable_capture_guards
drops GuardProvenance.GLOBAL guards of types that cannot be serialized; ambient
and synthetic guards are handled by the same provenance classification
introduced earlier in this stack.

Artifacts are pickled, so the loader must be able to import the same symbols the
capture referenced and run a matching torch version; load() degrades to a cold
inductor cache with a warning on a code-hash mismatch rather than serving stale
compiled code. Artifact files are written atomically (mkstemp in the target
directory, fsync, os.replace) so a crash mid-write cannot leave a torn artifact.

The tracer is selectable: the default make_fx path and an opt-in dynamo capture
path (documented in the user guide). PGO profiles are isolated from serve so a
precompiled run does not pollute an unrelated compile's profile.

Suggested review order: torch/_precompile.py (save/serve/load and the guard
filters), torch/_precompile_driver.py (the driver), torch/_dynamo/pgo.py (the
isolation hook), then the tests and docs.

Test Plan:

```
python test/test_precompile.py
```

293 pass; the 23 errored tests are all TritonMissing (this env has no Triton):
the CUDA numerics tests under TestPrecompileNumericsCUDA and the two autotune
cache-bundle tests. New coverage: tensor-subclass round-trip across
backend x tracer, config restoration after dynamo capture, and the existing
PGO-isolation / serve-never-recompiles / optimizer-weakref / ambient-config
tests.

Authored with an AI assistant.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

ghstack-source-id: 67d59c4
Pull-Request: #195288
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
… state

This builds out torch._precompile so a torch.compile artifact can be captured
once, persisted, and served later without re-tracing. A precompiled callable
saves two things: the Dynamo state (guards plus the reconstruction code, as an
importable Python module) and the inductor cache bundle. On load, serve is a
pure cache lookup and replay -- it never recompiles -- and dispatches across
saved entries newest-first, honoring the grad-mode the entry was captured under.

Guard serialization keeps only the guards that a served artifact must re-check.
is_input_guard keeps GuardProvenance.INPUT guards (the dispatch-relevant ones
rooted at the traced inputs and shape env) and _keep_serializable_capture_guards
drops GuardProvenance.GLOBAL guards of types that cannot be serialized; ambient
and synthetic guards are handled by the same provenance classification
introduced earlier in this stack.

Artifacts are pickled, so the loader must be able to import the same symbols the
capture referenced and run a matching torch version; load() degrades to a cold
inductor cache with a warning on a code-hash mismatch rather than serving stale
compiled code. Artifact files are written atomically (mkstemp in the target
directory, fsync, os.replace) so a crash mid-write cannot leave a torn artifact.

The tracer is selectable: the default make_fx path and an opt-in dynamo capture
path (documented in the user guide). PGO profiles are isolated from serve so a
precompiled run does not pollute an unrelated compile's profile.

Suggested review order: torch/_precompile.py (save/serve/load and the guard
filters), torch/_precompile_driver.py (the driver), torch/_dynamo/pgo.py (the
isolation hook), then the tests and docs.

Test Plan:

```
python test/test_precompile.py
```

293 pass; the 23 errored tests are all TritonMissing (this env has no Triton):
the CUDA numerics tests under TestPrecompileNumericsCUDA and the two autotune
cache-bundle tests. New coverage: tensor-subclass round-trip across
backend x tracer, config restoration after dynamo capture, and the existing
PGO-isolation / serve-never-recompiles / optimizer-weakref / ambient-config
tests.

Authored with an AI assistant.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

Review fixes. The served bytecode's global loads are validated at capture:
modules the residual bytecode references (a user's `torch`/`math`, or a module
Dynamo installed under a synthetic name for `type(x)`) are recorded as import
sources so they resolve in the artifact, and any other global it would read
fails capture with the name instead of a NameError at serve. The storage-overlap
probe checks wrapper tensor subclasses through the tensors they flatten to
(previously any call with two subclass inputs was rejected because a wrapper
owns no storage), with the outer layout checked first so jagged and mkldnn
inputs are still refused. load() rejects mixing any in-memory argument with any
path argument (TypeError, as documented), rejects a non-bytes cache, reads the
artifact as bytes so code_hash cannot be broken by newline normalization, and
checks the artifact's torch/Python version before parsing the Dynamo state or
unpickling the cache bundle. The atomic rewrite writes through a symlinked
destination, closes its fd on a chmod failure, and skips the directory fsync on
Windows (no directory fsync there); cross-process interleaving of the two
renames is documented as out of scope, as is why codecache.write_atomic is not
reused. The no-match error reports how many variants raised during guard
evaluation. SECURITY.md states that loading an artifact executes code; the
per-load warning stays (it is a tested, deliberate choice). Docstrings now
describe the actual locking (Dynamo capture only), the options that apply per
tracer, requires_grad dispatch under no_grad, and the quadratic guard
minimization cost; the doc examples and the layout sentence were corrected, and
`precompile.StateSummary` names the type `state.summary()` returns. The module
globals shared with the standalone training composer are referenced through
its constants.

ghstack-source-id: 4413125
Pull-Request: #195288
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
… state

This builds out torch._precompile so a torch.compile artifact can be captured
once, persisted, and served later without re-tracing. A precompiled callable
saves two things: the Dynamo state (guards plus the reconstruction code, as an
importable Python module) and the inductor cache bundle. On load, serve is a
pure cache lookup and replay -- it never recompiles -- and dispatches across
saved entries newest-first, honoring the grad-mode the entry was captured under.

Guard serialization keeps only the guards that a served artifact must re-check.
is_input_guard keeps GuardProvenance.INPUT guards (the dispatch-relevant ones
rooted at the traced inputs and shape env) and _keep_serializable_capture_guards
drops GuardProvenance.GLOBAL guards of types that cannot be serialized; ambient
and synthetic guards are handled by the same provenance classification
introduced earlier in this stack.

Artifacts are pickled, so the loader must be able to import the same symbols the
capture referenced and run a matching torch version; load() degrades to a cold
inductor cache with a warning on a code-hash mismatch rather than serving stale
compiled code. Artifact files are written atomically (mkstemp in the target
directory, fsync, os.replace) so a crash mid-write cannot leave a torn artifact.

The tracer is selectable: the default make_fx path and an opt-in dynamo capture
path (documented in the user guide). PGO profiles are isolated from serve so a
precompiled run does not pollute an unrelated compile's profile.

Suggested review order: torch/_precompile.py (save/serve/load and the guard
filters), torch/_precompile_driver.py (the driver), torch/_dynamo/pgo.py (the
isolation hook), then the tests and docs.

Test Plan:

```
python test/test_precompile.py
```

293 pass; the 23 errored tests are all TritonMissing (this env has no Triton):
the CUDA numerics tests under TestPrecompileNumericsCUDA and the two autotune
cache-bundle tests. New coverage: tensor-subclass round-trip across
backend x tracer, config restoration after dynamo capture, and the existing
PGO-isolation / serve-never-recompiles / optimizer-weakref / ambient-config
tests.

Authored with an AI assistant.

Follow-up review fixes. A module-valued residual global is recorded as an
import source only if it imports back to the same object under its __name__
(torch.ops namespaces and __main__ do not); otherwise capture fails with the
name instead of a ModuleNotFoundError at serve. The residual bytecode is also
scanned for module-global mutations that an inlined helper's `global` statement
produces (Dynamo replays them as a STORE_ATTR on the imported module, spilled
through a temp local, or as STORE_GLOBAL), since a served artifact would apply
them to the serving process's module; the entry-frame check only saw the
function's own STORE_GLOBALs. Both scans share one bytecode walker, and the
rejection message distinguishes Dynamo-installed helpers (`__gen_rand_values`)
from user globals. The storage-overlap probe rejects the same inner tensor
reached from two distinct wrapper subclasses, which the guard snapshot cannot
express, instead of failing later with a guard mismatch. The version pre-check
skips a malformed line rather than giving up on both. `fn` is
positional-or-keyword again, as shipped in v2.14.0. precompile.StateSummary is
re-homed to torch.compiler like its siblings and documented; load accepts any
bytes-like cache and documents its TypeError/ValueError cases. The guard
minimizer protects SYNTHETIC-rooted guards alongside INPUT. SECURITY.md covers
artifact loading under "Untrusted models", and the backward doc states the
None-versus-zeros divergence instead of claiming an exact eager match.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

Review fixes. The served bytecode's global loads are validated at capture:
modules the residual bytecode references (a user's `torch`/`math`, or a module
Dynamo installed under a synthetic name for `type(x)`) are recorded as import
sources so they resolve in the artifact, and any other global it would read
fails capture with the name instead of a NameError at serve. The storage-overlap
probe checks wrapper tensor subclasses through the tensors they flatten to
(previously any call with two subclass inputs was rejected because a wrapper
owns no storage), with the outer layout checked first so jagged and mkldnn
inputs are still refused. load() rejects mixing any in-memory argument with any
path argument (TypeError, as documented), rejects a non-bytes cache, reads the
artifact as bytes so code_hash cannot be broken by newline normalization, and
checks the artifact's torch/Python version before parsing the Dynamo state or
unpickling the cache bundle. The atomic rewrite writes through a symlinked
destination, closes its fd on a chmod failure, and skips the directory fsync on
Windows (no directory fsync there); cross-process interleaving of the two
renames is documented as out of scope, as is why codecache.write_atomic is not
reused. The no-match error reports how many variants raised during guard
evaluation. SECURITY.md states that loading an artifact executes code; the
per-load warning stays (it is a tested, deliberate choice). Docstrings now
describe the actual locking (Dynamo capture only), the options that apply per
tracer, requires_grad dispatch under no_grad, and the quadratic guard
minimization cost; the doc examples and the layout sentence were corrected, and
`precompile.StateSummary` names the type `state.summary()` returns. The module
globals shared with the standalone training composer are referenced through
its constants.

ghstack-source-id: d4a9e90
Pull-Request: #195288
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 3, 2026
… state

This builds out torch._precompile so a torch.compile artifact can be captured
once, persisted, and served later without re-tracing. A precompiled callable
saves two things: the Dynamo state (guards plus the reconstruction code, as an
importable Python module) and the inductor cache bundle. On load, serve is a
pure cache lookup and replay -- it never recompiles -- and dispatches across
saved entries newest-first, honoring the grad-mode the entry was captured under.

Guard serialization keeps only the guards that a served artifact must re-check.
is_input_guard keeps GuardProvenance.INPUT guards (the dispatch-relevant ones
rooted at the traced inputs and shape env) and _keep_serializable_capture_guards
drops GuardProvenance.GLOBAL guards of types that cannot be serialized; ambient
and synthetic guards are handled by the same provenance classification
introduced earlier in this stack.

Artifacts are pickled, so the loader must be able to import the same symbols the
capture referenced and run a matching torch version; load() degrades to a cold
inductor cache with a warning on a code-hash mismatch rather than serving stale
compiled code. Artifact files are written atomically (mkstemp in the target
directory, fsync, os.replace) so a crash mid-write cannot leave a torn artifact.

The tracer is selectable: the default make_fx path and an opt-in dynamo capture
path (documented in the user guide). PGO profiles are isolated from serve so a
precompiled run does not pollute an unrelated compile's profile.

Suggested review order: torch/_precompile.py (save/serve/load and the guard
filters), torch/_precompile_driver.py (the driver), torch/_dynamo/pgo.py (the
isolation hook), then the tests and docs.

Test Plan:

```
python test/test_precompile.py
```

293 pass; the 23 errored tests are all TritonMissing (this env has no Triton):
the CUDA numerics tests under TestPrecompileNumericsCUDA and the two autotune
cache-bundle tests. New coverage: tensor-subclass round-trip across
backend x tracer, config restoration after dynamo capture, and the existing
PGO-isolation / serve-never-recompiles / optimizer-weakref / ambient-config
tests.

Authored with an AI assistant.

Round-five fixes. The residual-bytecode scan now covers every form Dynamo uses
to replay a mutation of state reached through a module: a STORE_ATTR through
the import alias (directly, via a spilled temp, or via a stack COPY that the
previous state machine lost), and the object_setattr_ignore_descriptor /
object.__setattr__ call Dynamo emits for a user object's attribute, so
`m.CONFIG.value = ...` is rejected at capture instead of serving the
capture-time constant into the serving process; the report names the full
receiver path. A module global is only recorded as an import source if it
resolves to itself under its __name__ and is not __main__ (which resolves to
the serving process's script). Only names shaped like Dynamo's installed
helpers (`__<purpose>_<n>`, callable) get the helper wording; a user's dunder
global gets the generic one. The storage-overlap probe rejects the same inner
tensor twice within one wrapper as well as across wrappers. SECURITY.md and the
load warning describe what load actually does (exec, cache priming, and for
dynamo artifacts the embedded-state unpickle) instead of attributing an
unpickle to the cache bundle.

Follow-up review fixes. A module-valued residual global is recorded as an
import source only if it imports back to the same object under its __name__
(torch.ops namespaces and __main__ do not); otherwise capture fails with the
name instead of a ModuleNotFoundError at serve. The residual bytecode is also
scanned for module-global mutations that an inlined helper's `global` statement
produces (Dynamo replays them as a STORE_ATTR on the imported module, spilled
through a temp local, or as STORE_GLOBAL), since a served artifact would apply
them to the serving process's module; the entry-frame check only saw the
function's own STORE_GLOBALs. Both scans share one bytecode walker, and the
rejection message distinguishes Dynamo-installed helpers (`__gen_rand_values`)
from user globals. The storage-overlap probe rejects the same inner tensor
reached from two distinct wrapper subclasses, which the guard snapshot cannot
express, instead of failing later with a guard mismatch. The version pre-check
skips a malformed line rather than giving up on both. `fn` is
positional-or-keyword again, as shipped in v2.14.0. precompile.StateSummary is
re-homed to torch.compiler like its siblings and documented; load accepts any
bytes-like cache and documents its TypeError/ValueError cases. Behavior change
versus v2.14.0: load(code, None) and load(code, "not-bytes") used to degrade to
JIT with a warning (the envelope read sat inside a broad except); they now
raise TypeError, since a wrong-typed cache is a programming error. The guard
minimizer protects SYNTHETIC-rooted guards alongside INPUT. SECURITY.md covers
artifact loading under "Untrusted models", and the backward doc states the
None-versus-zeros divergence instead of claiming an exact eager match.

Review fixes. The served bytecode's global loads are validated at capture:
modules the residual bytecode references (a user's `torch`/`math`, or a module
Dynamo installed under a synthetic name for `type(x)`) are recorded as import
sources so they resolve in the artifact, and any other global it would read
fails capture with the name instead of a NameError at serve. The storage-overlap
probe checks wrapper tensor subclasses through the tensors they flatten to
(previously any call with two subclass inputs was rejected because a wrapper
owns no storage), with the outer layout checked first so jagged and mkldnn
inputs are still refused. load() rejects mixing any in-memory argument with any
path argument (TypeError, as documented), rejects a non-bytes cache, reads the
artifact as bytes so code_hash cannot be broken by newline normalization, and
checks the artifact's torch/Python version before parsing the Dynamo state or
unpickling the cache bundle. The atomic rewrite writes through a symlinked
destination, closes its fd on a chmod failure, and skips the directory fsync on
Windows (no directory fsync there); cross-process interleaving of the two
renames is documented as out of scope, as is why codecache.write_atomic is not
reused. The no-match error reports how many variants raised during guard
evaluation. SECURITY.md states that loading an artifact executes code; the
per-load warning stays (it is a tested, deliberate choice). Docstrings now
describe the actual locking (Dynamo capture only), the options that apply per
tracer, requires_grad dispatch under no_grad, and the quadratic guard
minimization cost; the doc examples and the layout sentence were corrected, and
`precompile.StateSummary` names the type `state.summary()` returns. The module
globals shared with the standalone training composer are referenced through
its constants.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 96f3e89
Pull-Request: #195288
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 3, 2026
… state

This builds out torch._precompile so a torch.compile artifact can be captured
once, persisted, and served later without re-tracing. A precompiled callable
saves two things: the Dynamo state (guards plus the reconstruction code, as an
importable Python module) and the inductor cache bundle. On load, serve is a
pure cache lookup and replay -- it never recompiles -- and dispatches across
saved entries newest-first, honoring the grad-mode the entry was captured under.

Guard serialization keeps only the guards that a served artifact must re-check.
is_input_guard keeps GuardProvenance.INPUT guards (the dispatch-relevant ones
rooted at the traced inputs and shape env) and _keep_serializable_capture_guards
drops GuardProvenance.GLOBAL guards of types that cannot be serialized; ambient
and synthetic guards are handled by the same provenance classification
introduced earlier in this stack.

Artifacts are pickled, so the loader must be able to import the same symbols the
capture referenced and run a matching torch version; on a code-hash mismatch
load() degrades a dynamo artifact to a cold inductor cache with a warning and
rejects a make_fx artifact with PrecompileError, rather than serving stale
compiled code. Artifact files are written atomically (mkstemp in the target
directory, fsync, os.replace) so a crash mid-write cannot leave a torn artifact.

The tracer is selectable: the default make_fx path and an opt-in dynamo capture
path (documented in the user guide). PGO profiles are isolated from serve so a
precompiled run does not pollute an unrelated compile's profile.

Suggested review order: torch/_precompile.py (save/serve/load and the guard
filters), torch/_precompile_driver.py (the driver), torch/_dynamo/pgo.py (the
isolation hook), then the tests and docs.

Test Plan:

```
python test/test_precompile.py
```

311 pass; the 23 errored tests are all TritonMissing (this env has no Triton):
the CUDA numerics tests under TestPrecompileNumericsCUDA and the two autotune
cache-bundle tests. New coverage: tensor-subclass round-trip across
backend x tracer, config restoration after dynamo capture, and the existing
PGO-isolation / serve-never-recompiles / optimizer-weakref / ambient-config
tests.

Authored with an AI assistant.

Round-six fixes. Module-reachable mutations are no longer detected by
pattern-matching Dynamo's residual bytecode (which missed
object_delattr_ignore_descriptor, subscripted receivers, dict and list
mutation, and depended on 3.12 opcodes: DUP_TOP and LOAD_METHOD on the 3.10 CI
shard would have made the two-globals case pass capture). Dynamo already
records, per compiled code, the sources of the pre-existing objects whose
mutation it replays (convert_frame.get_compiled_code_side_effects); a bytecode
hook registered for the capture session collects them and the artifact build
rejects any not rooted at a call argument, naming the path
(`precompile_test_helpers.OBJS[0]`, `module 'precompile_test_helpers'`). The
Dynamo-installed-helper wording is now decided exactly: a residual global the
user's module never held was installed by Dynamo into the capture's copy of
the globals, so a user's own callable `__helper_2` gets the generic message.
The torch.compiler_api entry for load() names the accepted cache types.

Round-five fixes. The residual-bytecode scan (since replaced, see above)
covered every form Dynamo uses to replay a mutation of state reached through a
module, so `m.CONFIG.value = ...` is rejected at capture instead of serving the
capture-time constant into the serving process; the report names the full
receiver path. A module global is only recorded as an import source if it
resolves to itself under its __name__ and is not __main__ (which resolves to
the serving process's script). The storage-overlap probe rejects the same inner
tensor twice within one wrapper as well as across wrappers. SECURITY.md and the
load warning describe what load actually does (exec, cache priming, and for
dynamo artifacts the embedded-state unpickle) instead of attributing an
unpickle to the cache bundle.

Follow-up review fixes. A module-valued residual global is recorded as an
import source only if it imports back to the same object under its __name__
(torch.ops namespaces and __main__ do not); otherwise capture fails with the
name instead of a ModuleNotFoundError at serve. Module-global mutations that an
inlined helper's `global` statement produces are rejected too, since a served
artifact would apply them to the serving process's module; the entry-frame
check only saw the function's own STORE_GLOBALs. The rejection message
distinguishes Dynamo-installed helpers (`__gen_rand_values`) from user globals.
The storage-overlap probe rejects the same inner tensor
reached from two distinct wrapper subclasses, which the guard snapshot cannot
express, instead of failing later with a guard mismatch. The version pre-check
skips a malformed line rather than giving up on both. `fn` is
positional-or-keyword again, as shipped in v2.14.0. precompile.StateSummary is
re-homed to torch.compiler like its siblings and documented; load accepts any
bytes-like cache and documents its TypeError/ValueError cases. Behavior change
versus v2.14.0: load(code, None) and load(code, "not-bytes") used to degrade to
JIT with a warning (the envelope read sat inside a broad except); they now
raise TypeError, since a wrong-typed cache is a programming error. The guard
minimizer protects SYNTHETIC-rooted guards alongside INPUT. SECURITY.md covers
artifact loading under "Untrusted models", and the backward doc states the
None-versus-zeros divergence instead of claiming an exact eager match.

Review fixes. The served bytecode's global loads are validated at capture:
modules the residual bytecode references (a user's `torch`/`math`, or a module
Dynamo installed under a synthetic name for `type(x)`) are recorded as import
sources so they resolve in the artifact, and any other global it would read
fails capture with the name instead of a NameError at serve. The storage-overlap
probe checks wrapper tensor subclasses through the tensors they flatten to
(previously any call with two subclass inputs was rejected because a wrapper
owns no storage), with the outer layout checked first so jagged and mkldnn
inputs are still refused. load() rejects mixing any in-memory argument with any
path argument (TypeError, as documented), rejects a non-bytes cache, reads the
artifact as bytes so code_hash cannot be broken by newline normalization, and
checks the artifact's torch/Python version before parsing the Dynamo state or
unpickling the cache bundle. The atomic rewrite writes through a symlinked
destination, closes its fd on a chmod failure, and skips the directory fsync on
Windows (no directory fsync there); cross-process interleaving of the two
renames is documented as out of scope, as is why codecache.write_atomic is not
reused. The no-match error reports how many variants raised during guard
evaluation. SECURITY.md states that loading an artifact executes code; the
per-load warning stays (it is a tested, deliberate choice). Docstrings now
describe the actual locking (Dynamo capture only), the options that apply per
tracer, requires_grad dispatch under no_grad, and the quadratic guard
minimization cost; the doc examples and the layout sentence were corrected, and
`precompile.StateSummary` names the type `state.summary()` returns. The module
globals shared with the standalone training composer are referenced through
its constants.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 6e109bd
Pull-Request: #195288
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 3, 2026
… state

This builds out torch._precompile so a torch.compile artifact can be captured
once, persisted, and served later without re-tracing. A precompiled callable
saves two things: the Dynamo state (guards plus the reconstruction code, as an
importable Python module) and the inductor cache bundle. On load, serve is a
pure cache lookup and replay -- it never recompiles -- and dispatches across
saved entries newest-first, honoring the grad-mode the entry was captured under.

Guard serialization keeps only the guards that a served artifact must re-check.
is_input_guard keeps GuardProvenance.INPUT and SYNTHETIC guards (the
dispatch-relevant ones rooted at the traced inputs and shape env, plus any
tracing-internal root a drop policy must never treat as environment) and
_keep_serializable_capture_guards drops GuardProvenance.GLOBAL guards of types
that cannot be serialized; guard minimization then drops, per variant, the
remaining named guards that every recorded example passes without, which the
precompile docs declare an unchecked environment invariant (globals and
context-manager state).

Capture validation for tracer="dynamo". The served bytecode's global loads are
validated at capture: modules the residual bytecode references (a user's
`torch`/`math`, or one Dynamo installed under a synthetic name) are recorded as
import sources when they import back to the same object under their __name__
(torch.ops namespaces and __main__ do not), and any other global it would read
fails capture with the name -- distinguishing a Dynamo-installed helper, which
is a global the user's module never held, from a user global -- instead of a
NameError at serve. Side effects are checked from what Dynamo records for each
compiled code (convert_frame.get_compiled_code_side_effects, collected by a
bytecode hook for the capture session) rather than by pattern-matching the
residual bytecode: a mutation of anything reached through a module global (a
helper's `global`, an attribute set or deleted on an object a module holds, a
dict or list it holds, a module attribute) would apply the capture-time value
to the SERVING process's objects and is rejected with the path; so is a
mutation of a parameter left at its default, since defaults ship as a pickled
copy the served replay would mutate instead of the object the default names.
Mutations of the call's own argument objects are replayed on the caller's
objects at serve, which the docs state. The storage-overlap probe checks
wrapper tensor subclasses through the tensors they flatten to and rejects the
same inner tensor reached twice, which the guard snapshot cannot express.

Artifacts are pickled, so the loader must be able to import the same symbols the
capture referenced and run a matching torch version, checked before the Dynamo
state is parsed or the cache bundle unpickled; on a code-hash mismatch load()
degrades a dynamo artifact to a cold inductor cache with a warning and rejects a
make_fx artifact with PrecompileError, rather than serving stale compiled code.
load() accepts the cache as bytes, bytearray or memoryview and raises TypeError
for anything else or for mixing in-memory and path arguments (behavior change
versus v2.14.0, where load(code, None) and load(code, "not-bytes") degraded to
JIT with a warning because the envelope read sat inside a broad except).
Artifact files are written atomically (mkstemp in the target directory, fsync,
os.replace, through a symlinked destination) so a crash mid-write cannot leave
a torn artifact.

The tracer is selectable: the default make_fx path and an opt-in dynamo capture
path (documented in the user guide). Stateful capture accumulates variants
across calls and rewrites the artifact after each; a resumed call whose example
Dynamo cannot record (a guard-serialization failure marks the package entry
bypassed, after which no variant is ever recorded again) closes the state and
says so, while a call that failed before Dynamo produced bytecode leaves it
usable. PGO profiles are isolated from serve so a precompiled run does not
pollute an unrelated compile's profile. SECURITY.md covers artifact loading
under "Untrusted models" (load executes the artifact's code and unpickles the
embedded Dynamo state), and the backward doc states the None-versus-zeros
divergence of the undefined-tangent specialization precompile builds on.

Suggested review order: torch/_precompile.py (save/serve/load and the guard
filters), torch/_precompile_driver.py (the driver), torch/_dynamo/pgo.py (the
isolation hook), then the tests and docs.

Test Plan:

```
python test/test_precompile.py
```

313 pass; the 23 errored tests are all TritonMissing (this env has no Triton):
the CUDA numerics tests under TestPrecompileNumericsCUDA, the autotune
cache-bundle test and the static-launcher rehydration test. Coverage includes
tensor-subclass round-trip across backend x tracer, config restoration after
dynamo capture, every module-reachable mutation shape and the defaulted-
parameter case, the stateful lifecycle (resume mismatches, a call that raised,
an unrecordable variant closing the state), and the PGO-isolation /
serve-never-recompiles / optimizer-weakref / ambient-config tests.

Authored with an AI assistant.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: f77a5bb
Pull-Request: #195288
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: dynamo"

bobrenjc93 added a commit that referenced this pull request Sep 3, 2026
… state

This builds out torch._precompile so a torch.compile artifact can be captured
once, persisted, and served later without re-tracing. A precompiled callable
saves two things: the Dynamo state (guards plus the reconstruction code, as an
importable Python module) and the inductor cache bundle. On load, serve is a
pure cache lookup and replay -- it never recompiles -- and dispatches across
saved entries newest-first, honoring the grad-mode the entry was captured under.

Guard serialization keeps only the guards that a served artifact must re-check.
is_input_guard keeps GuardProvenance.INPUT and SYNTHETIC guards (the
dispatch-relevant ones rooted at the traced inputs and shape env, plus any
tracing-internal root a drop policy must never treat as environment) and
_keep_serializable_capture_guards drops GuardProvenance.GLOBAL guards of types
that cannot be serialized; guard minimization then drops, per variant, the
remaining named guards that every recorded example passes without, which the
precompile docs declare an unchecked environment invariant (globals and
context-manager state).

Capture validation for tracer="dynamo". The served bytecode's global loads are
validated at capture: modules the residual bytecode references (a user's
`torch`/`math`, or one Dynamo installed under a synthetic name) are recorded as
import sources when they import back to the same object under their __name__
(torch.ops namespaces and __main__ do not), and any other global it would read
fails capture with the name -- distinguishing a Dynamo-installed helper, which
is a global the user's module never held, from a user global -- instead of a
NameError at serve. Side effects are checked from what Dynamo records for each
compiled code (convert_frame.get_compiled_code_side_effects, collected by a
bytecode hook for the capture session) rather than by pattern-matching the
residual bytecode: a mutation of anything reached through a module global (a
helper's `global`, an attribute set or deleted on an object a module holds, a
dict or list it holds, a module attribute) would apply the capture-time value
to the SERVING process's objects and is rejected with the path; so is a
mutation of a parameter left at its default, since defaults ship as a pickled
copy the served replay would mutate instead of the object the default names.
Mutations of the call's own argument objects are replayed on the caller's
objects at serve, which the docs state. The storage-overlap probe checks
wrapper tensor subclasses through the tensors they flatten to and rejects the
same inner tensor reached twice, which the guard snapshot cannot express.

Artifacts are pickled, so the loader must be able to import the same symbols the
capture referenced and run a matching torch version, checked before the Dynamo
state is parsed or the cache bundle unpickled; on a code-hash mismatch load()
degrades a dynamo artifact to a cold inductor cache with a warning and rejects a
make_fx artifact with PrecompileError, rather than serving stale compiled code.
load() accepts the cache as bytes, bytearray or memoryview and raises TypeError
for anything else or for mixing in-memory and path arguments (behavior change
versus v2.14.0, where load(code, None) and load(code, "not-bytes") degraded to
JIT with a warning because the envelope read sat inside a broad except).
Artifact files are written atomically (mkstemp in the target directory, fsync,
os.replace, through a symlinked destination) so a crash mid-write cannot leave
a torn artifact.

The tracer is selectable: the default make_fx path and an opt-in dynamo capture
path (documented in the user guide). Stateful capture accumulates variants
across calls and rewrites the artifact after each; a resumed call whose example
Dynamo cannot record (a guard-serialization failure marks the package entry
bypassed, after which no variant is ever recorded again) closes the state and
says so, while a call that failed before Dynamo produced bytecode leaves it
usable. PGO profiles are isolated from serve so a precompiled run does not
pollute an unrelated compile's profile. SECURITY.md covers artifact loading
under "Untrusted models" (load executes the artifact's code and unpickles the
embedded Dynamo state).

Suggested review order: torch/_precompile.py (save/serve/load and the guard
filters), torch/_precompile_driver.py (the driver), torch/_dynamo/pgo.py (the
isolation hook), then the tests and docs.

Test Plan:

```
python test/test_precompile.py
```

313 pass; the 23 errored tests are all TritonMissing (this env has no Triton):
the CUDA numerics tests under TestPrecompileNumericsCUDA, the autotune
cache-bundle test and the static-launcher rehydration test. Coverage includes
tensor-subclass round-trip across backend x tracer, config restoration after
dynamo capture, every module-reachable mutation shape and the defaulted-
parameter case, the stateful lifecycle (resume mismatches, a call that raised,
an unrecordable variant closing the state), and the PGO-isolation /
serve-never-recompiles / optimizer-weakref / ambient-config tests.

Authored with an AI assistant.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ghstack-source-id: 4d4a66a
Pull-Request: #195288
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Closing in favor of the canonical stack #195353-#195362 (now also #195911-#195929), which carries an equivalent of this change. Final state of this PR's stack is preserved locally for reference.

@bobrenjc93 bobrenjc93 closed this Sep 3, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1085/head branch November 15, 2026 01:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant