Skip to content

[precompile] Add torch.compiler.precompile.accumulate - #195362

Closed
bobrenjc93 wants to merge 29 commits into
gh/bobrenjc93/1102/basefrom
gh/bobrenjc93/1102/head
Closed

bobrenjc93 wants to merge 29 commits into
gh/bobrenjc93/1102/basefrom
gh/bobrenjc93/1102/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

precompile() makes its example calls itself, back to back, which is wrong
whenever the calls are not independent: a training step whose inputs come off
a queue the enclosing loop advances cannot be called twice in a row.
accumulate(fn, *, artifact_path, cache_path, ...) inverts that. It returns an
AccumulatingCapture the caller calls exactly like fn; each call runs for real,
folds whatever it newly exercised into a resumable PrecompileSession, renders
everything captured so far through snapshot_artifact() and rewrites the two
named files with _write_artifact, so they are a complete loadable artifact
after every call and a job that dies partway leaves a working one. Calls are
serialized on an RLock. A call whose fn raises leaves the capture open; a
refusal from the artifact gates is final -- the step already ran, so the
PrecompileError carries its return value as result, the capture closes
(the files keep the last artifact that passed) and later calls fail fast; an
OSError from the rewrite also carries the result but leaves the capture open.
The lock is reentrant because that close happens inside call, so a call
made from inside fn is refused as a recursive re-entry. close() retires the
session through the same drain handshake as exit.

load() takes the two files back with load(artifact_path=..., cache_path=...),
exclusive with the in-memory pair, since that is how the files this writes
are read; the hunk map placed that with the public-surface commit above, but
the accumulate tests need it here.

Test Plan:

python test/test_precompile.py -k precompile_accumulate
python test/test_public_bindings.py -k correct_module_names
python test/test_precompile.py

Authored with an AI assistant.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 1 Unrelated Failure

As of commit 3455e15 with merge base 1ad121e (image):

NEW FAILURE - The following job has failed:

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

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

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

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…cs, and add stateful incremental capture

This distills the hardening iterations that sit above the dynamo-tracer
front-end in the stack at #195284 into one reviewable unit. The front-end
establishes the capture/serve contract and the PR below this one fixes the
guard-drop policy; this PR is the rest of what it took to make the contract
hold on real models: guard rebuilds that fail loudly instead of drifting,
artifact install/serve that survives a hostile host process, diagnostics that
name the actual problem when something cannot ship -- and one new public API,
torch.compiler.precompile.accumulate, a stateful incremental capture the
caller drives one call at a time, whose named files are a complete loadable
artifact after every call.

The suggested review order follows the data:

1. Guard rebuilds (torch/_dynamo/guards.py, precompile_package.py): a guard
   that cannot be rebuilt at load is dropped (and actually removed from the
   artifact) with a report, instead of the whole artifact being refused; a
   guard that rebuilds into a DIFFERENT check than the one validated is
   reported rather than silently trusted; a precompiled frame's guard tree is
   built twice, not three times.

2. Guard state pickling (guards.py): the pickle keeps a guard's own subject
   out of the value pruning, shares user_stack objects, re-reduces _Missing
   compactly, carries a tensor's guard-traversed Python attributes and a
   wrapper subclass's requires_grad, and makes the bound-method reducer a
   fixed point over its own output. Dimension markings register where they
   are read.

3. Artifact lifecycle (torch/_precompile.py, _precompile_driver.py,
   package.py): an installed artifact is prepared once at load and consumed
   by install; serving runs from a private copy of the artifact's dynamo
   state; a served frame's user globals win over the artifact's own; an
   installed entry gets back the defaults its code object lost; an artifact
   installed on a guarded object no longer loses the frame. Load checks the
   artifact against its host and a standalone artifact's inlined source
   before trusting either, and reads the TORCH_VERSION the artifact already
   carries. The package stops shipping every inlined module's whole source,
   resolves code defined under property/cached_property, and revalidates a
   memoized module-by-file hit before handing it back.

4. Capture fidelity (precompile_package.py, precompile_context.py): capture
   observes the calls the CALLER makes rather than calls precompile makes,
   lets the example call keep the gradients it produced (without the tracer
   accumulating into them), records a backend for a graph the compiler
   short-circuited, and stops requiring AOTAutogradCache to key a graph
   before recording it. precompile writes the artifact to caller-provided
   paths and hands back what the examples returned; accumulate() builds on
   exactly that pair of behaviours.

5. Diagnostics: the risky-drop report leads with the guards that can change
   a shape, a missing compiled backend reports the recorded/total split, and
   serve-time recompiles, guard misses, bypassed entry frames and empty
   captures each say specifically what happened.

Review fixes folded in at this level: the HASATTR guard builder now registers
the attribute value with the guard tree (unregistered, serialization pruned a
tensor attribute nothing else referenced and the rebuilt HASATTR silently
INVERTED to no-hasattr, routing attr-less inputs into the attr-present
graph); a retained-grad non-leaf's .grad survives the pickle (the "always
None anyway" rationale is wrong for retains_grad, which torch.optim permits
on params, and a guard chaining through the dropped grad failed the load);
and the exception path of PrecompileSession.__enter__ drains in-flight calls
before erasing its cache region, as __exit__ already did, so a concurrent
resumable-session call cannot be left compiling against a destroyed entry.

The provenance of every change here is an individual reviewed commit in the
#195284 stack; this PR carries their squashed net effect on top of the
guard-policy PR below. The capture-once redesign, the never-drop policy for
shape/value/type-pinning guards, and the unpicklable-value diagnostics
formerly in this PR moved down into that PR, where their machinery lands.

Test Plan:

```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_recompile_ux.py
```

Authored with an AI assistant.

ghstack-source-id: 477b381
Pull-Request: #195362
@bobrenjc93 bobrenjc93 changed the title [precompile] Harden guard serialization, artifact lifecycle, and diagnostics for the dynamo tracer [precompile] Harden guard rebuilds, artifact lifecycle, and diagnostics, and add stateful incremental capture Aug 30, 2026
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…cs, and add stateful incremental capture

This distills the hardening iterations that sit above the dynamo-tracer
front-end in the stack at #195284 into one reviewable unit. The front-end
establishes the capture/serve contract and the PR below this one fixes the
guard-drop policy; this PR is the rest of what it took to make the contract
hold on real models: guard rebuilds that fail loudly instead of drifting,
artifact install/serve that survives a hostile host process, diagnostics that
name the actual problem when something cannot ship -- and one new public API,
torch.compiler.precompile.accumulate, a stateful incremental capture the
caller drives one call at a time, whose named files are a complete loadable
artifact after every call.

The suggested review order follows the data:

1. Guard rebuilds (torch/_dynamo/guards.py, precompile_package.py): a guard
   that cannot be rebuilt at load is dropped (and actually removed from the
   artifact) with a report, instead of the whole artifact being refused; a
   guard that rebuilds into a DIFFERENT check than the one validated is
   reported rather than silently trusted; a precompiled frame's guard tree is
   built twice, not three times.

2. Guard state pickling (guards.py): the pickle keeps a guard's own subject
   out of the value pruning, shares user_stack objects, re-reduces _Missing
   compactly, carries a tensor's guard-traversed Python attributes and a
   wrapper subclass's requires_grad, and makes the bound-method reducer a
   fixed point over its own output. Dimension markings register where they
   are read.

3. Artifact lifecycle (torch/_precompile.py, _precompile_driver.py,
   package.py): an installed artifact is prepared once at load and consumed
   by install; serving runs from a private copy of the artifact's dynamo
   state; a served frame's user globals win over the artifact's own; an
   installed entry gets back the defaults its code object lost; an artifact
   installed on a guarded object no longer loses the frame. Load checks the
   artifact against its host and a standalone artifact's inlined source
   before trusting either, and reads the TORCH_VERSION the artifact already
   carries. The package stops shipping every inlined module's whole source,
   resolves code defined under property/cached_property, and revalidates a
   memoized module-by-file hit before handing it back.

4. Capture fidelity (precompile_package.py, precompile_context.py): capture
   observes the calls the CALLER makes rather than calls precompile makes,
   lets the example call keep the gradients it produced (without the tracer
   accumulating into them), records a backend for a graph the compiler
   short-circuited, and stops requiring AOTAutogradCache to key a graph
   before recording it. precompile writes the artifact to caller-provided
   paths and hands back what the examples returned; accumulate() builds on
   exactly that pair of behaviours.

5. Diagnostics: the risky-drop report leads with the guards that can change
   a shape, a missing compiled backend reports the recorded/total split, and
   serve-time recompiles, guard misses, bypassed entry frames and empty
   captures each say specifically what happened.

Review fixes folded in at this level: the HASATTR guard builder now registers
the attribute value with the guard tree (unregistered, serialization pruned a
tensor attribute nothing else referenced and the rebuilt HASATTR silently
INVERTED to no-hasattr, routing attr-less inputs into the attr-present
graph); a retained-grad non-leaf's .grad survives the pickle (the "always
None anyway" rationale is wrong for retains_grad, which torch.optim permits
on params, and a guard chaining through the dropped grad failed the load);
and the exception path of PrecompileSession.__enter__ drains in-flight calls
before erasing its cache region, as __exit__ already did, so a concurrent
resumable-session call cannot be left compiling against a destroyed entry.

The provenance of every change here is an individual reviewed commit in the
#195284 stack; this PR carries their squashed net effect on top of the
guard-policy PR below. The capture-once redesign, the never-drop policy for
shape/value/type-pinning guards, and the unpicklable-value diagnostics
formerly in this PR moved down into that PR, where their machinery lands.

Test Plan:

```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_recompile_ux.py
```

Authored with an AI assistant.

ghstack-source-id: 477b381
Pull-Request: #195362
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…cs, and add stateful incremental capture

This distills the hardening iterations that sit above the dynamo-tracer
front-end in the stack at #195284 into one reviewable unit. The front-end
establishes the capture/serve contract and the PR below this one fixes the
guard-drop policy; this PR is the rest of what it took to make the contract
hold on real models: guard rebuilds that fail loudly instead of drifting,
artifact install/serve that survives a hostile host process, diagnostics that
name the actual problem when something cannot ship -- and one new public API,
torch.compiler.precompile.accumulate, a stateful incremental capture the
caller drives one call at a time, whose named files are a complete loadable
artifact after every call.

The suggested review order follows the data:

1. Guard rebuilds (torch/_dynamo/guards.py, precompile_package.py): a guard
   that cannot be rebuilt at load is dropped (and actually removed from the
   artifact) with a report, instead of the whole artifact being refused; a
   guard that rebuilds into a DIFFERENT check than the one validated is
   reported rather than silently trusted; a precompiled frame's guard tree is
   built twice, not three times.

2. Guard state pickling (guards.py): the pickle keeps a guard's own subject
   out of the value pruning, shares user_stack objects, re-reduces _Missing
   compactly, carries a tensor's guard-traversed Python attributes and a
   wrapper subclass's requires_grad, and makes the bound-method reducer a
   fixed point over its own output. Dimension markings register where they
   are read.

3. Artifact lifecycle (torch/_precompile.py, _precompile_driver.py,
   package.py): an installed artifact is prepared once at load and consumed
   by install; serving runs from a private copy of the artifact's dynamo
   state; a served frame's user globals win over the artifact's own; an
   installed entry gets back the defaults its code object lost; an artifact
   installed on a guarded object no longer loses the frame. Load checks the
   artifact against its host and a standalone artifact's inlined source
   before trusting either, and reads the TORCH_VERSION the artifact already
   carries. The package stops shipping every inlined module's whole source,
   resolves code defined under property/cached_property, and revalidates a
   memoized module-by-file hit before handing it back.

4. Capture fidelity (precompile_package.py, precompile_context.py): capture
   observes the calls the CALLER makes rather than calls precompile makes,
   lets the example call keep the gradients it produced (without the tracer
   accumulating into them), records a backend for a graph the compiler
   short-circuited, and stops requiring AOTAutogradCache to key a graph
   before recording it. precompile writes the artifact to caller-provided
   paths and hands back what the examples returned; accumulate() builds on
   exactly that pair of behaviours.

5. Diagnostics: the risky-drop report leads with the guards that can change
   a shape, a missing compiled backend reports the recorded/total split, and
   serve-time recompiles, guard misses, bypassed entry frames and empty
   captures each say specifically what happened.

Review fixes folded in at this level: the HASATTR guard builder now registers
the attribute value with the guard tree (unregistered, serialization pruned a
tensor attribute nothing else referenced and the rebuilt HASATTR silently
INVERTED to no-hasattr, routing attr-less inputs into the attr-present
graph); a retained-grad non-leaf's .grad survives the pickle (the "always
None anyway" rationale is wrong for retains_grad, which torch.optim permits
on params, and a guard chaining through the dropped grad failed the load);
and the exception path of PrecompileSession.__enter__ drains in-flight calls
before erasing its cache region, as __exit__ already did, so a concurrent
resumable-session call cannot be left compiling against a destroyed entry.

The provenance of every change here is an individual reviewed commit in the
guard-policy PR below. The capture-once redesign, the never-drop policy for
shape/value/type-pinning guards, and the unpicklable-value diagnostics
formerly in this PR moved down into that PR, where their machinery lands.

Second review round, folded in at this level: the HASATTR guard-tree
registration is narrowed to TENSOR bases -- the inversion it fixes exists only
where _carried_tensor_attributes drops the attribute, and registering on
nn.Module/user-object bases dragged possibly-unpicklable hasattr-only values
into the pickle, turning serializable frames into bypasses. The __enter__
exception path now drains in-flight calls BEFORE any teardown (matching
__exit__) and runs the region cleanup in a finally, so an interrupt raised
out of the drain's wait cannot leak the compile region; _call's redundant
local pgo import (between the active-call increment and its try/finally) is
gone. The TYPE_MATCH/HASATTR never-drop entries and their covering test moved
DOWN into the guard-policy PR below, where that policy lands, so this PR's
"moved down" accounting is now accurate; guard-state unpickling in the
re-serialization pass sits inside the PackageError-converting try (from the
PR below) and this PR's rebuildability collection builds on it.

Test Plan:

```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_recompile_ux.py
```

Authored with an AI assistant.

ghstack-source-id: 17d9f65
Pull-Request: #195362
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…cs, and add stateful incremental capture

This distills the hardening iterations that sit above the dynamo-tracer
front-end in the stack at #195284 into one reviewable unit. The front-end
establishes the capture/serve contract and the PR below this one fixes the
guard-drop policy; this PR is the rest of what it took to make the contract
hold on real models: guard rebuilds that fail loudly instead of drifting,
artifact install/serve that survives a hostile host process, diagnostics that
name the actual problem when something cannot ship -- and one new public API,
torch.compiler.precompile.accumulate, a stateful incremental capture the
caller drives one call at a time, whose named files are a complete loadable
artifact after every call.

The suggested review order follows the data:

1. Guard rebuilds (torch/_dynamo/guards.py, precompile_package.py): a guard
   that cannot be rebuilt at load is dropped (and actually removed from the
   artifact) with a report, instead of the whole artifact being refused; a
   guard that rebuilds into a DIFFERENT check than the one validated is
   reported rather than silently trusted; a precompiled frame's guard tree is
   built twice, not three times.

2. Guard state pickling (guards.py): the pickle keeps a guard's own subject
   out of the value pruning, shares user_stack objects, re-reduces _Missing
   compactly, carries a tensor's guard-traversed Python attributes and a
   wrapper subclass's requires_grad, and makes the bound-method reducer a
   fixed point over its own output. Dimension markings register where they
   are read.

3. Artifact lifecycle (torch/_precompile.py, _precompile_driver.py,
   package.py): an installed artifact is prepared once at load and consumed
   by install; serving runs from a private copy of the artifact's dynamo
   state; a served frame's user globals win over the artifact's own; an
   installed entry gets back the defaults its code object lost; an artifact
   installed on a guarded object no longer loses the frame. Load checks the
   artifact against its host and a standalone artifact's inlined source
   before trusting either, and reads the TORCH_VERSION the artifact already
   carries. The package stops shipping every inlined module's whole source,
   resolves code defined under property/cached_property, and revalidates a
   memoized module-by-file hit before handing it back.

4. Capture fidelity (precompile_package.py, precompile_context.py): capture
   observes the calls the CALLER makes rather than calls precompile makes,
   lets the example call keep the gradients it produced (without the tracer
   accumulating into them), records a backend for a graph the compiler
   short-circuited, and stops requiring AOTAutogradCache to key a graph
   before recording it. precompile writes the artifact to caller-provided
   paths and hands back what the examples returned; accumulate() builds on
   exactly that pair of behaviours.

5. Diagnostics: the risky-drop report leads with the guards that can change
   a shape, a missing compiled backend reports the recorded/total split, and
   serve-time recompiles, guard misses, bypassed entry frames and empty
   captures each say specifically what happened.

Review fixes folded in at this level: the HASATTR guard builder now registers
the attribute value with the guard tree (unregistered, serialization pruned a
tensor attribute nothing else referenced and the rebuilt HASATTR silently
INVERTED to no-hasattr, routing attr-less inputs into the attr-present
graph); a retained-grad non-leaf's .grad survives the pickle (the "always
None anyway" rationale is wrong for retains_grad, which torch.optim permits
on params, and a guard chaining through the dropped grad failed the load);
and the exception path of PrecompileSession.__enter__ drains in-flight calls
before erasing its cache region, as __exit__ already did, so a concurrent
resumable-session call cannot be left compiling against a destroyed entry.

The provenance of every change here is an individual reviewed commit in the
guard-policy PR below. The capture-once redesign, the never-drop policy for
shape/value/type-pinning guards, and the unpicklable-value diagnostics
formerly in this PR moved down into that PR, where their machinery lands.

Second review round, folded in at this level: the HASATTR guard-tree
registration is narrowed to TENSOR bases -- the inversion it fixes exists only
where _carried_tensor_attributes drops the attribute, and registering on
nn.Module/user-object bases dragged possibly-unpicklable hasattr-only values
into the pickle, turning serializable frames into bypasses. The __enter__
exception path now drains in-flight calls BEFORE any teardown (matching
__exit__) and runs the region cleanup in a finally, so an interrupt raised
out of the drain's wait cannot leak the compile region; _call's redundant
local pgo import (between the active-call increment and its try/finally) is
gone. The TYPE_MATCH/HASATTR never-drop entries and their covering test moved
DOWN into the guard-policy PR below, where that policy lands, so this PR's
"moved down" accounting is now accurate; guard-state unpickling in the
re-serialization pass sits inside the PackageError-converting try (from the
PR below) and this PR's rebuildability collection builds on it.

Test Plan:

```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_recompile_ux.py
```

Authored with an AI assistant.

ghstack-source-id: 17d9f65
Pull-Request: #195362
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 31, 2026
…cs, and add stateful incremental capture

This distills the hardening iterations that sit above the dynamo-tracer
front-end in the stack at #195284 into one reviewable unit. The front-end
establishes the capture/serve contract and the PR below this one fixes the
guard-drop policy; this PR is the rest of what it took to make the contract
hold on real models: guard rebuilds that fail loudly instead of drifting,
artifact install/serve that survives a hostile host process, diagnostics that
name the actual problem when something cannot ship -- and one new public API,
torch.compiler.precompile.accumulate, a stateful incremental capture the
caller drives one call at a time, whose named files are a complete loadable
artifact after every call.

The suggested review order follows the data:

1. Guard rebuilds (torch/_dynamo/guards.py, precompile_package.py): a guard
   that cannot be rebuilt at load is dropped (and actually removed from the
   artifact) with a report, instead of the whole artifact being refused; a
   guard that rebuilds into a DIFFERENT check than the one validated is
   reported rather than silently trusted; a precompiled frame's guard tree is
   built twice, not three times.

2. Guard state pickling (guards.py): the pickle keeps a guard's own subject
   out of the value pruning, shares user_stack objects, re-reduces _Missing
   compactly, carries a tensor's guard-traversed Python attributes and a
   wrapper subclass's requires_grad, and makes the bound-method reducer a
   fixed point over its own output. Dimension markings register where they
   are read.

3. Artifact lifecycle (torch/_precompile.py, _precompile_driver.py,
   package.py): an installed artifact is prepared once at load and consumed
   by install; serving runs from a private copy of the artifact's dynamo
   state; a served frame's user globals win over the artifact's own; an
   installed entry gets back the defaults its code object lost; an artifact
   installed on a guarded object no longer loses the frame. Load checks the
   artifact against its host and a standalone artifact's inlined source
   before trusting either, and reads the TORCH_VERSION the artifact already
   carries. The package stops shipping every inlined module's whole source,
   resolves code defined under property/cached_property, and revalidates a
   memoized module-by-file hit before handing it back.

4. Capture fidelity (precompile_package.py, precompile_context.py): capture
   observes the calls the CALLER makes rather than calls precompile makes,
   lets the example call keep the gradients it produced (without the tracer
   accumulating into them), records a backend for a graph the compiler
   short-circuited, and stops requiring AOTAutogradCache to key a graph
   before recording it. precompile writes the artifact to caller-provided
   paths and hands back what the examples returned; accumulate() builds on
   exactly that pair of behaviours.

5. Diagnostics: the risky-drop report leads with the guards that can change
   a shape, a missing compiled backend reports the recorded/total split, and
   serve-time recompiles, guard misses, bypassed entry frames and empty
   captures each say specifically what happened.

Review fixes folded in at this level: the HASATTR guard builder now registers
the attribute value with the guard tree (unregistered, serialization pruned a
tensor attribute nothing else referenced and the rebuilt HASATTR silently
INVERTED to no-hasattr, routing attr-less inputs into the attr-present
graph); a retained-grad non-leaf's .grad survives the pickle (the "always
None anyway" rationale is wrong for retains_grad, which torch.optim permits
on params, and a guard chaining through the dropped grad failed the load);
and the exception path of PrecompileSession.__enter__ drains in-flight calls
before erasing its cache region, as __exit__ already did, so a concurrent
resumable-session call cannot be left compiling against a destroyed entry.

The provenance of every change here is an individual reviewed commit in the
guard-policy PR below. The capture-once redesign, the never-drop policy for
shape/value/type-pinning guards, and the unpicklable-value diagnostics
formerly in this PR moved down into that PR, where their machinery lands.

Second review round, folded in at this level: the HASATTR guard-tree
registration is narrowed to TENSOR bases -- the inversion it fixes exists only
where _carried_tensor_attributes drops the attribute, and registering on
nn.Module/user-object bases dragged possibly-unpicklable hasattr-only values
into the pickle, turning serializable frames into bypasses. The __enter__
exception path now drains in-flight calls BEFORE any teardown (matching
__exit__) and runs the region cleanup in a finally, so an interrupt raised
out of the drain's wait cannot leak the compile region; _call's redundant
local pgo import (between the active-call increment and its try/finally) is
gone. The TYPE_MATCH/HASATTR never-drop entries and their covering test moved
DOWN into the guard-policy PR below, where that policy lands, so this PR's
"moved down" accounting is now accurate; guard-state unpickling in the
re-serialization pass sits inside the PackageError-converting try (from the
PR below) and this PR's rebuildability collection builds on it.

Test Plan:

```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_recompile_ux.py
```

Authored with an AI assistant.

ghstack-source-id: b39f950
Pull-Request: #195362
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 31, 2026
…cs, and add stateful incremental capture

This distills the hardening iterations that sit above the dynamo-tracer
front-end in the stack at #195284 into one reviewable unit. The front-end
establishes the capture/serve contract and the PR below this one fixes the
guard-drop policy; this PR is the rest of what it took to make the contract
hold on real models: guard rebuilds that fail loudly instead of drifting,
artifact install/serve that survives a hostile host process, diagnostics that
name the actual problem when something cannot ship -- and one new public API,
torch.compiler.precompile.accumulate, a stateful incremental capture the
caller drives one call at a time, whose named files are a complete loadable
artifact after every call.

The suggested review order follows the data:

1. Guard rebuilds (torch/_dynamo/guards.py, precompile_package.py): a guard
   that cannot be rebuilt at load is dropped (and actually removed from the
   artifact) with a report, instead of the whole artifact being refused; a
   guard that rebuilds into a DIFFERENT check than the one validated is
   reported rather than silently trusted; a precompiled frame's guard tree is
   built twice, not three times.

2. Guard state pickling (guards.py): the pickle keeps a guard's own subject
   out of the value pruning, shares user_stack objects, re-reduces _Missing
   compactly, carries a tensor's guard-traversed Python attributes and a
   wrapper subclass's requires_grad, and makes the bound-method reducer a
   fixed point over its own output. Dimension markings register where they
   are read.

3. Artifact lifecycle (torch/_precompile.py, _precompile_driver.py,
   package.py): an installed artifact is prepared once at load and consumed
   by install; serving runs from a private copy of the artifact's dynamo
   state; a served frame's user globals win over the artifact's own; an
   installed entry gets back the defaults its code object lost; an artifact
   installed on a guarded object no longer loses the frame. Load checks the
   artifact against its host and a standalone artifact's inlined source
   before trusting either, and reads the TORCH_VERSION the artifact already
   carries. The package stops shipping every inlined module's whole source,
   resolves code defined under property/cached_property, and revalidates a
   memoized module-by-file hit before handing it back.

4. Capture fidelity (precompile_package.py, precompile_context.py): capture
   observes the calls the CALLER makes rather than calls precompile makes,
   lets the example call keep the gradients it produced (without the tracer
   accumulating into them), records a backend for a graph the compiler
   short-circuited, and stops requiring AOTAutogradCache to key a graph
   before recording it. precompile writes the artifact to caller-provided
   paths and hands back what the examples returned; accumulate() builds on
   exactly that pair of behaviours.

5. Diagnostics: the risky-drop report leads with the guards that can change
   a shape, a missing compiled backend reports the recorded/total split, and
   serve-time recompiles, guard misses, bypassed entry frames and empty
   captures each say specifically what happened.

Review fixes folded in at this level: the HASATTR guard builder now registers
the attribute value with the guard tree (unregistered, serialization pruned a
tensor attribute nothing else referenced and the rebuilt HASATTR silently
INVERTED to no-hasattr, routing attr-less inputs into the attr-present
graph); a retained-grad non-leaf's .grad survives the pickle (the "always
None anyway" rationale is wrong for retains_grad, which torch.optim permits
on params, and a guard chaining through the dropped grad failed the load);
and the exception path of PrecompileSession.__enter__ drains in-flight calls
before erasing its cache region, as __exit__ already did, so a concurrent
resumable-session call cannot be left compiling against a destroyed entry.

The provenance of every change here is an individual reviewed commit in the
guard-policy PR below. The capture-once redesign, the never-drop policy for
shape/value/type-pinning guards, and the unpicklable-value diagnostics
formerly in this PR moved down into that PR, where their machinery lands.

Second review round, folded in at this level: the HASATTR guard-tree
registration is narrowed to TENSOR bases -- the inversion it fixes exists only
where _carried_tensor_attributes drops the attribute, and registering on
nn.Module/user-object bases dragged possibly-unpicklable hasattr-only values
into the pickle, turning serializable frames into bypasses. The __enter__
exception path now drains in-flight calls BEFORE any teardown (matching
__exit__) and runs the region cleanup in a finally, so an interrupt raised
out of the drain's wait cannot leak the compile region; _call's redundant
local pgo import (between the active-call increment and its try/finally) is
gone. The TYPE_MATCH/HASATTR never-drop entries and their covering test moved
DOWN into the guard-policy PR below, where that policy lands, so this PR's
"moved down" accounting is now accurate; guard-state unpickling in the
re-serialization pass sits inside the PackageError-converting try (from the
PR below) and this PR's rebuildability collection builds on it.

Test Plan:

```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_recompile_ux.py
```

Authored with an AI assistant.

ghstack-source-id: 2ce02df
Pull-Request: #195362
@bobrenjc93 bobrenjc93 added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 31, 2026
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 31, 2026
…cs, and add stateful incremental capture

This distills the hardening iterations that sit above the dynamo-tracer
front-end in the stack at #195284 into one reviewable unit. The front-end
establishes the capture/serve contract and the PR below this one fixes the
guard-drop policy; this PR is the rest of what it took to make the contract
hold on real models: guard rebuilds that fail loudly instead of drifting,
artifact install/serve that survives a hostile host process, diagnostics that
name the actual problem when something cannot ship -- and one new public API,
torch.compiler.precompile.accumulate, a stateful incremental capture the
caller drives one call at a time, whose named files are a complete loadable
artifact after every call.

The suggested review order follows the data:

1. Guard rebuilds (torch/_dynamo/guards.py, precompile_package.py): a guard
   that cannot be rebuilt at load is dropped (and actually removed from the
   artifact) with a report, instead of the whole artifact being refused; a
   guard that rebuilds into a DIFFERENT check than the one validated is
   reported rather than silently trusted; a precompiled frame's guard tree is
   built twice, not three times.

2. Guard state pickling (guards.py): the pickle keeps a guard's own subject
   out of the value pruning, shares user_stack objects, re-reduces _Missing
   compactly, carries a tensor's guard-traversed Python attributes and a
   wrapper subclass's requires_grad, and makes the bound-method reducer a
   fixed point over its own output. Dimension markings register where they
   are read.

3. Artifact lifecycle (torch/_precompile.py, _precompile_driver.py,
   package.py): an installed artifact is prepared once at load and consumed
   by install; serving runs from a private copy of the artifact's dynamo
   state; a served frame's user globals win over the artifact's own; an
   installed entry gets back the defaults its code object lost; an artifact
   installed on a guarded object no longer loses the frame. Load checks the
   artifact against its host and a standalone artifact's inlined source
   before trusting either, and reads the TORCH_VERSION the artifact already
   carries. The package stops shipping every inlined module's whole source,
   resolves code defined under property/cached_property, and revalidates a
   memoized module-by-file hit before handing it back.

4. Capture fidelity (precompile_package.py, precompile_context.py): capture
   observes the calls the CALLER makes rather than calls precompile makes,
   lets the example call keep the gradients it produced (without the tracer
   accumulating into them), records a backend for a graph the compiler
   short-circuited, and stops requiring AOTAutogradCache to key a graph
   before recording it. precompile writes the artifact to caller-provided
   paths and hands back what the examples returned; accumulate() builds on
   exactly that pair of behaviours.

5. Diagnostics: the risky-drop report leads with the guards that can change
   a shape, a missing compiled backend reports the recorded/total split, and
   serve-time recompiles, guard misses, bypassed entry frames and empty
   captures each say specifically what happened.

Review fixes folded in at this level: the HASATTR guard builder now registers
the attribute value with the guard tree (unregistered, serialization pruned a
tensor attribute nothing else referenced and the rebuilt HASATTR silently
INVERTED to no-hasattr, routing attr-less inputs into the attr-present
graph); a retained-grad non-leaf's .grad survives the pickle (the "always
None anyway" rationale is wrong for retains_grad, which torch.optim permits
on params, and a guard chaining through the dropped grad failed the load);
and the exception path of PrecompileSession.__enter__ drains in-flight calls
before erasing its cache region, as __exit__ already did, so a concurrent
resumable-session call cannot be left compiling against a destroyed entry.

The provenance of every change here is an individual reviewed commit in the
guard-policy PR below. The capture-once redesign, the never-drop policy for
shape/value/type-pinning guards, and the unpicklable-value diagnostics
formerly in this PR moved down into that PR, where their machinery lands.

Second review round, folded in at this level: the HASATTR guard-tree
registration is narrowed to TENSOR bases -- the inversion it fixes exists only
where _carried_tensor_attributes drops the attribute, and registering on
nn.Module/user-object bases dragged possibly-unpicklable hasattr-only values
into the pickle, turning serializable frames into bypasses. The __enter__
exception path now drains in-flight calls BEFORE any teardown (matching
__exit__) and runs the region cleanup in a finally, so an interrupt raised
out of the drain's wait cannot leak the compile region; _call's redundant
local pgo import (between the active-call increment and its try/finally) is
gone. The TYPE_MATCH/HASATTR never-drop entries and their covering test moved
DOWN into the guard-policy PR below, where that policy lands, so this PR's
"moved down" accounting is now accurate; guard-state unpickling in the
re-serialization pass sits inside the PackageError-converting try (from the
PR below) and this PR's rebuildability collection builds on it.

CI round 3: re-centered benchmarks/dynamo/pr_time_benchmarks/expected_results.csv
with the values the trunk pr_time_benchmarks job printed. The gate tripped as
a WIN (add_loop_eager_dynamic -10.01% vs the +/-10% window) -- baseline drift
against this stack's Aug 28 base, not an effect of this diff -- and the
harness's own failure message instructs updating every printed row.

Test Plan:

```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_recompile_ux.py
```

Authored with an AI assistant.

ghstack-source-id: b8f5502
Pull-Request: #195362
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 changed the title [precompile] Harden guard rebuilds, artifact lifecycle, and diagnostics, and add stateful incremental capture [precompile] Add torch.compiler.precompile.accumulate Sep 4, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 4, 2026
precompile() makes its example calls itself, back to back, which is wrong
whenever the calls are not independent: a training step whose inputs come off
a queue the enclosing loop advances cannot be called twice in a row.
accumulate(fn, *, artifact_path, cache_path, ...) inverts that. It returns an
AccumulatingCapture the caller calls exactly like fn; each call runs for real,
folds whatever it newly exercised into a resumable PrecompileSession, renders
everything captured so far through snapshot_artifact() and rewrites the two
named files with _write_artifact, so they are a complete loadable artifact
after every call and a job that dies partway leaves a working one. Calls are
serialized on an RLock. A call whose fn raises leaves the capture open; a
refusal from the artifact gates is final -- the step already ran, so the
PrecompileError carries its return value as ``result``, the capture closes
(the files keep the last artifact that passed) and later calls fail fast; an
OSError from the rewrite also carries the result but leaves the capture open.
The lock is reentrant because that close happens inside __call__, so a call
made from inside fn is refused as a recursive re-entry. close() retires the
session through the same drain handshake as __exit__.

load() takes the two files back with load(artifact_path=..., cache_path=...),
exclusive with the in-memory pair, since that is how the files this writes
are read; the hunk map placed that with the public-surface commit above, but
the accumulate tests need it here.

Test Plan:

```
python test/test_precompile.py -k precompile_accumulate
python test/test_public_bindings.py -k correct_module_names
python test/test_precompile.py
```

Authored with an AI assistant.

ghstack-source-id: 687e338
Pull-Request: #195362
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

/easycla

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

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request module: dynamo release notes: dynamo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant