Repository navigation
[precompile] Keep the guards whose loss changes the answer - #195284
Closed
bobrenjc93 wants to merge 4 commits into
Closed
bobrenjc93 wants to merge 4 commits into
bobrenjc93 wants to merge 4 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/195284
Note: Links to docs will display an error until the docs builds have been completed. ❌ 13 New Failures, 1 Unrelated FailureAs of commit 4b56d06 with merge base 1b4e490 ( NEW FAILURES - The following jobs have failed:
BROKEN TRUNK - The following job failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This was referenced Aug 29, 2026
Closed
Closed
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 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
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
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
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: 629dd04 Pull-Request: #195362
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 4 (post-rebase): trunk gained test_opaque_obj_v2.test_guard_pickle_subclass_with_opaque_inner_attr, which unpacks GuardsStatePickler.reducer_override(tensor) as a 2-tuple; this PR's tensor reduce legitimately carries guard-traversed attributes in the pickle STATE slot, so the test now unpacks the (func, args) head explicitly -- and additionally asserts the full pickle round-trips, which is the contract the regression test exists for. 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: 7393adf Pull-Request: #195362
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 4 (post-rebase): trunk gained test_opaque_obj_v2.test_guard_pickle_subclass_with_opaque_inner_attr, which unpacks GuardsStatePickler.reducer_override(tensor) as a 2-tuple; this PR's tensor reduce legitimately carries guard-traversed attributes in the pickle STATE slot, so the test now unpacks the (func, args) head explicitly -- and additionally asserts the full pickle round-trips, which is the contract the regression test exists for. Third review round, five fixes: - snapshot_artifact() now calls refuse_unserializable() like artifact() and save(): it is a serialization boundary, and an accumulating capture whose CPU codegen target drifted mid-loop was still writing an artifact mixing native code for two ISA targets. Tested by injecting drift between accumulate() calls. - AccumulatingCapture.close() no longer reaches into three session privates with no drain: the session now owns a retire() that performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. A two-thread test pins that close() parks until the in-flight call finishes. - Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) now reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections, and the drop warning no longer understate what was removed. - The driver's torch-build lock and the INLINED_SOURCES drift check raise the PrecompileError the docs promise instead of bare ValueErrors, and the drift check treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError; a module the bytecode actually needs still fails loudly in the import_sources loop. The drift test now also covers the module-absent serve. - The bypassed-entry diagnostic in _reject_uninstallable_entry was unreachable for its documented scenario: _multigraph_frames DROPS bypassed codes, so a bypassed entry arrived as "no entry frame" and hit the silent early return. It now fires from the empty-frames state too, and its test constructs the state production actually produces instead of one it never can. CI round 5 (post-rebase): trunk gained test_opaque_obj_v2.test_guard_pickle_subclass_with_opaque_inner_attr, which unpacks GuardsStatePickler.reducer_override(tensor) as a 2-tuple; this PR's tensor reduce legitimately carries guard-traversed attributes in the pickle STATE slot, so the test now unpacks the (func, args) head explicitly -- and additionally asserts the full pickle round-trips, which is the contract the regression test exists for. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.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: b289774 Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 1, 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 4 (post-rebase): trunk gained test_opaque_obj_v2.test_guard_pickle_subclass_with_opaque_inner_attr, which unpacks GuardsStatePickler.reducer_override(tensor) as a 2-tuple; this PR's tensor reduce legitimately carries guard-traversed attributes in the pickle STATE slot, so the test now unpacks the (func, args) head explicitly -- and additionally asserts the full pickle round-trips, which is the contract the regression test exists for. Third review round, five fixes: - snapshot_artifact() now calls refuse_unserializable() like artifact() and save(): it is a serialization boundary, and an accumulating capture whose CPU codegen target drifted mid-loop was still writing an artifact mixing native code for two ISA targets. Tested by injecting drift between accumulate() calls. - AccumulatingCapture.close() no longer reaches into three session privates with no drain: the session now owns a retire() that performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. A two-thread test pins that close() parks until the in-flight call finishes. - Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) now reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections, and the drop warning no longer understate what was removed. - The driver's torch-build lock and the INLINED_SOURCES drift check raise the PrecompileError the docs promise instead of bare ValueErrors, and the drift check treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError; a module the bytecode actually needs still fails loudly in the import_sources loop. The drift test now also covers the module-absent serve. - The bypassed-entry diagnostic in _reject_uninstallable_entry was unreachable for its documented scenario: _multigraph_frames DROPS bypassed codes, so a bypassed entry arrived as "no entry frame" and hit the silent early return. It now fires from the empty-frames state too, and its test constructs the state production actually produces instead of one it never can. CI round 5 (post-rebase): trunk gained test_opaque_obj_v2.test_guard_pickle_subclass_with_opaque_inner_attr, which unpacks GuardsStatePickler.reducer_override(tensor) as a 2-tuple; this PR's tensor reduce legitimately carries guard-traversed attributes in the pickle STATE slot, so the test now unpacks the (func, args) head explicitly -- and additionally asserts the full pickle round-trips, which is the contract the regression test exists for. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.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: 62a3481 Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. Explicit capture is signalled to CheckFunctionManager as ``explicit_capture`` (set on every package the session, serve_cache_entry and prepare_cache_entry build) rather than inferred from a serialization filter being present, and an explicit capture without a serialization filter is an assertion. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a tempfile.mkstemp scratch file beside its target (so two writers targeting one path never share a scratch name and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: bbf8f91 Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. Explicit capture is signalled to CheckFunctionManager as ``explicit_capture`` (set on every package the session, serve_cache_entry and prepare_cache_entry build) rather than inferred from a serialization filter being present, and an explicit capture without a serialization filter is an assertion. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a tempfile.mkstemp scratch file beside its target (so two writers targeting one path never share a scratch name and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: bbf8f91 Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two CheckFunctionManager rebuilds the guard-policy pass performs pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a tempfile.mkstemp scratch file beside its target (so two writers targeting one path never share a scratch name and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; ``_InstalledArtifact.unload()`` takes a backend artifact out of the process registry only if it is the object this install recorded, since keys are content hashes an ambient caching_precompile run of the same graph can share; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: 2ecefe1 Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 2026
…the answer
The dynamo tracer below this PR learned its guard-drop policy from a throwaway
probe capture: run every example once to see which guards discriminate, reset,
run them all again keeping only those. A capture is not free of side effects,
so that design is wrong twice over -- a training step's gradients accumulate
across BOTH passes (doubling every .grad the example produced), and a region
that mutates state (BatchNorm running stats, a step counter) is guarded on
values the discarded pass had already advanced past. Capture now runs ONCE and
the policy is applied on the way out, by re-serializing each frame's guards
from the pickle the capture already made (PrecompileSession._apply_guard_policy).
The re-serialization pass unpickles the capture's guard state inside the try
that converts failures to PackageError, so an unpicklable value surfaces as the
diagnostic below rather than a raw pickle error.
The policy itself is tightened to never drop a guard whose loss changes an
answer, rather than dropping everything that held invariant across the
examples, and its classification is fail-closed. The ONLY guard types the
invariance policy may drop are the explicit _INVARIANT_DROPPABLE_GUARD_TYPES:
identity guards, which the default filter drops anyway as unserializable, and
process-wide compiler state. Everything that pins semantics is kept
unconditionally: shape-bearing guards survive a single-example capture (with
one example nothing can discriminate, so the old rule dropped even the guard
that checks the runtime tensor looks like the captured one at all); TYPE_MATCH
and HASATTR, without which a graph traced for one class was reproducibly served
to another; and every guard that pins a Python fact about a value or a
container's contents -- BOOL_MATCH, CONSTANT_SUBCLASS_MATCH, NONE_MATCH,
NOT_NONE_MATCH, DICT_CONTAINS, DICT_NOT_CONTAINS, DICT_KEYS_MATCH,
MAPPING_KEYS_CHECK, NOT_PRESENT_IN_GENERIC_DICT, SET_CONTAINS, SET_NOT_CONTAINS,
TUPLE_ITERATOR_LEN, RANGE_ITERATOR_MATCH, COUNT_ITERATOR_MATCH. Each of those
is a branch the graph specialized on, so dropping it serves the captured
branch to the other side, silently. The membership guards matter because a
module-owned dict (``self.opts = {}``) is environment-rooted, which is exactly
where the policy used to drop them: ``M({"flag": 1})`` was answered with
``M({})``'s branch, no error, at the default gates. A guard type in none of the
three sets -- i.e. anything added to GuardBuilder after this -- is KEPT until
someone classifies it, and test_guard_policy_classification_is_total pins that
the sets are a disjoint, phantom-free cover of GuardBuilder's guard-producing
methods (it caught and removed a "SYMBOL_MATCH" entry that named no method;
symbolic shapes are protected through SHAPE_ENV in the unmodelled set).
A custom guard_filter_fn composes with that default instead of replacing it,
so it can drop more guards, never fewer, and the risk accounting follows: the
identity drops the default makes anyway are judged as they always are, and
only a drop the custom filter ADDED beyond the default counts as risky by
construction, because nothing here can say what the caller gave up. Previously
every drop under a custom filter was flagged risky, which made the report
useless for the common case of a filter that only drops more.
Policy-dropped facts are re-marked enforced=False in _guard_sets instead of
deleted, so the invariants report -- whose header promises a dropped line is
"a precondition NOTHING checks" -- lists them; 738 of 1207 slots on the example
model used to vanish from the file.
``require_complete`` now also refuses a capture that compiled no graph at all.
allow_empty_graphs keeps a frame that compiled nothing as one guarded code, so
guarded_codes alone cannot tell a real capture from one whose whole body sits
behind torch._dynamo.disable; such a capture carries no compiled compute, so
``summary.complete`` says so and the artifact refuses with "compiled no graph"
unless require_complete=False.
The serialization machinery underneath gets the correctness fixes this
exposed. Value pruning applies to any guarded object rather than only
nn.Module and exempts interned values (id()-keyed pruning cannot scope a
value the interpreter shares, so registering torch.float32 as missing
poisoned every other reference to it). A Guard's export bookkeeping
(code_list/guard_types, EXTENDED per build) is no longer pickled.
_SourceGraphModule's __deepcopy__ deep-copies its parameter/buffer containers
instead of sharing their tensors between "deep" copies, and its __reduce__
snapshots the instance's own parameters/buffers/submodules (re-blobbing live
sub-GraphModules) rather than pickling the shared _src whose body aliases the
ORIGINAL's containers -- a deepcopy used to pickle the original's
since-mutated tensors. An eager backend's graph is carried through the
artifact without re-tracing at load, and a bypassed entry frame reports the
real reason, counting only the entry's own bypassed codes so an unrelated
bypassed helper no longer relabels a thin-wrapper entry as a bypass.
``pickle_guards_state`` catches ``Exception`` broadly, and that now includes
the RecursionError and AssertionError it used to let through as "our bug".
They are not ours to claim: GradScaler.__getstate__ asserts when pickled
mid-iteration, tensor subclasses assert in __tensor_flatten__, a reducer can
recurse through a user object graph, and any user assert in a __reduce__ or a
property lands here. Propagating those turns a serialization limitation into
a hard torch.compile failure for a program that has nothing wrong with it.
The caller turns the resulting PackageError into a package bypass, or
re-raises it under strict_precompile, and the message names the original
exception type plus the path to the offending value, because a type alone
("cannot pickle 'generator' object") is not actionable in a model with a
thousand-frame guard tree.
Review order: start with _apply_guard_policy and the capture-once change in
torch/_precompile.py and precompile_package.py; then the survives()/pruning
policy and the three guard-type sets in precompile_package.py; then the
GuardsStatePickler changes in guards.py; the diagnostics last. This PR
carries, squashed, the contiguous segment of the #195284 stack between the
standalone-source composition below and the hardening PR above (including the
diagnostic repairs that segment needs to be green: the whole-state search and
identity attribution), so the hardening PR above shrinks by the same content.
Test Plan:
```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
```
test_capture_runs_each_example_once pins the capture-once contract with a
region that counts its own calls; test_capture_does_not_double_the_gradients_it_accumulates
and test_a_mutating_module_is_guarded_on_what_the_capture_saw pin the two
consequences the probe design got wrong. test_shape_guards_survive_a_single_example
rejects four out-of-domain calls that the old policy served;
test_a_different_class_is_refused_not_served covers TYPE_MATCH;
test_a_dict_membership_guard_is_never_dropped and
test_a_module_owned_dict_membership_guard_is_never_dropped cover the
membership guards on a local and on a module-owned dict, the latter also
asserting DICT_NOT_CONTAINS is absent from POLICY_DROPPED_GUARDS.
test_an_empty_capture_is_not_complete covers the compiled-no-graph refusal.
The unpicklable-value tests assert the diagnostic names the actual value and
its path, including a function default
(test_unpicklable_function_default_names_the_path), and a round-trip test pins
live AND pickled isolation of _SourceGraphModule copies.
Authored with an AI assistant.
ghstack-source-id: e779d5d
Pull-Request: #195371
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two CheckFunctionManager rebuilds the guard-policy pass performs pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a tempfile.mkstemp scratch file beside its target (so two writers targeting one path never share a scratch name and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; ``_InstalledArtifact.unload()`` takes a backend artifact out of the process registry only if it is the object this install recorded, since keys are content hashes an ambient caching_precompile run of the same graph can share; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: 2ecefe1 Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two CheckFunctionManager rebuilds the guard-policy pass performs pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; ``_InstalledArtifact`` remembers which backend keys the process registry already held before it served, puts those objects back once install has consumed its own (the driver's _serve records and overwrites unconditionally), and ``unload()`` takes out only the keys this install added and only while they still hold the object it recorded, since keys are content hashes an ambient caching_precompile run of the same graph can share; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: bc96b7a Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two CheckFunctionManager rebuilds the guard-policy pass performs pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; ``_InstalledArtifact`` remembers which backend keys the process registry already held before it served, puts those objects back once install has consumed its own (the driver's _serve records and overwrites unconditionally), and ``unload()`` takes out only the keys this install added and only while they still hold the object it recorded, since keys are content hashes an ambient caching_precompile run of the same graph can share; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: bc96b7a Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two CheckFunctionManager rebuilds the guard-policy pass performs pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; the emitted driver's ``_serve`` records a backend only under a key the process registry does not already hold, and ``_InstalledArtifact.unload()`` takes out only the keys this install added and only while they still hold the object it recorded, since keys are content hashes that an ambient caching_precompile run of the same graph, or a second handle on the same artifact, shares; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: ce11fa9 Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two CheckFunctionManager rebuilds the guard-policy pass performs pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; the emitted driver's ``_serve`` records a backend only under a key the process registry does not already hold, and ``_InstalledArtifact.unload()`` takes out only the keys this install added and only while they still hold the object it recorded, since keys are content hashes that an ambient caching_precompile run of the same graph, or a second handle on the same artifact, shares; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: ce11fa9 Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 2026
…the answer
The dynamo tracer below this PR learned its guard-drop policy from a throwaway
probe capture: run every example once to see which guards discriminate, reset,
run them all again keeping only those. A capture is not free of side effects,
so that design is wrong twice over -- a training step's gradients accumulate
across BOTH passes (doubling every .grad the example produced), and a region
that mutates state (BatchNorm running stats, a step counter) is guarded on
values the discarded pass had already advanced past. Capture now runs ONCE and
the policy is applied on the way out, by re-serializing each frame's guards
from the pickle the capture already made (PrecompileSession._apply_guard_policy).
The re-serialization pass unpickles the capture's guard state inside the try
that converts failures to PackageError, so an unpicklable value surfaces as the
diagnostic below rather than a raw pickle error.
The policy itself is tightened to never drop a guard whose loss changes an
answer, rather than dropping everything that held invariant across the
examples, and its classification is fail-closed. The ONLY guard types the
invariance policy may drop are the explicit _INVARIANT_DROPPABLE_GUARD_TYPES:
identity guards, which the default filter drops anyway as unserializable, and
process-wide compiler state. Everything that pins semantics is kept
unconditionally: shape-bearing guards survive a single-example capture (with
one example nothing can discriminate, so the old rule dropped even the guard
that checks the runtime tensor looks like the captured one at all); TYPE_MATCH
and HASATTR, without which a graph traced for one class was reproducibly served
to another; and every guard that pins a Python fact about a value or a
container's contents -- BOOL_MATCH, CONSTANT_SUBCLASS_MATCH, NONE_MATCH,
NOT_NONE_MATCH, DICT_CONTAINS, DICT_NOT_CONTAINS, DICT_KEYS_MATCH,
MAPPING_KEYS_CHECK, NOT_PRESENT_IN_GENERIC_DICT, SET_CONTAINS, SET_NOT_CONTAINS,
TUPLE_ITERATOR_LEN, RANGE_ITERATOR_MATCH, COUNT_ITERATOR_MATCH. Each of those
is a branch the graph specialized on, so dropping it serves the captured
branch to the other side, silently. The membership guards matter because a
module-owned dict (``self.opts = {}``) is environment-rooted, which is exactly
where the policy used to drop them: ``M({"flag": 1})`` was answered with
``M({})``'s branch, no error, at the default gates. A guard type in none of the
three sets -- i.e. anything added to GuardBuilder after this -- is KEPT until
someone classifies it, and test_guard_policy_classification_is_total pins that
the sets are a disjoint, phantom-free cover of GuardBuilder's guard-producing
methods (it caught and removed a "SYMBOL_MATCH" entry that named no method;
symbolic shapes are protected through SHAPE_ENV in the unmodelled set).
A custom guard_filter_fn composes with that default instead of replacing it,
so it can drop more guards, never fewer, and the risk accounting follows: the
identity drops the default makes anyway are judged as they always are, and
only a drop the custom filter ADDED beyond the default counts as risky by
construction, because nothing here can say what the caller gave up. Previously
every drop under a custom filter was flagged risky, which made the report
useless for the common case of a filter that only drops more.
Policy-dropped facts are re-marked enforced=False in _guard_sets instead of
deleted, so the invariants report -- whose header promises a dropped line is
"a precondition NOTHING checks" -- lists them; 738 of 1207 slots on the example
model used to vanish from the file.
``require_complete`` now also refuses a capture that compiled no graph at all.
allow_empty_graphs keeps a frame that compiled nothing as one guarded code, so
guarded_codes alone cannot tell a real capture from one whose whole body sits
behind torch._dynamo.disable; such a capture carries no compiled compute, so
``summary.complete`` says so and the artifact refuses with "compiled no graph"
unless require_complete=False.
The serialization machinery underneath gets the correctness fixes this
exposed. Value pruning applies to any guarded object rather than only
nn.Module and exempts interned values (id()-keyed pruning cannot scope a
value the interpreter shares, so registering torch.float32 as missing
poisoned every other reference to it). A Guard's export bookkeeping
(code_list/guard_types, EXTENDED per build) is no longer pickled.
_SourceGraphModule's __deepcopy__ deep-copies its parameter/buffer containers
instead of sharing their tensors between "deep" copies, and its __reduce__
snapshots the instance's own parameters/buffers/submodules (re-blobbing live
sub-GraphModules) rather than pickling the shared _src whose body aliases the
ORIGINAL's containers -- a deepcopy used to pickle the original's
since-mutated tensors. An eager backend's graph is carried through the
artifact without re-tracing at load, and a bypassed entry frame reports the
real reason, counting only the entry's own bypassed codes so an unrelated
bypassed helper no longer relabels a thin-wrapper entry as a bypass.
``pickle_guards_state`` catches ``Exception`` broadly, and that now includes
the RecursionError and AssertionError it used to let through as "our bug".
They are not ours to claim: GradScaler.__getstate__ asserts when pickled
mid-iteration, tensor subclasses assert in __tensor_flatten__, a reducer can
recurse through a user object graph, and any user assert in a __reduce__ or a
property lands here. Propagating those turns a serialization limitation into
a hard torch.compile failure for a program that has nothing wrong with it.
The caller turns the resulting PackageError into a package bypass, or
re-raises it under strict_precompile, and the message names the original
exception type plus the path to the offending value, because a type alone
("cannot pickle 'generator' object") is not actionable in a model with a
thousand-frame guard tree.
Review order: start with _apply_guard_policy and the capture-once change in
torch/_precompile.py and precompile_package.py; then the survives()/pruning
policy and the three guard-type sets in precompile_package.py; then the
GuardsStatePickler changes in guards.py; the diagnostics last. This PR
carries, squashed, the contiguous segment of the #195284 stack between the
standalone-source composition below and the hardening PR above (including the
diagnostic repairs that segment needs to be green: the whole-state search and
identity attribution), so the hardening PR above shrinks by the same content.
The policy pass rebuilds each frame's guards through CheckFunctionManager with
``explicit_capture=True``, the flag the tracer commit introduced: the
serialization filter that applies the policy runs only for an explicit
capture, so without it the pass would keep every guard and drop nothing.
Test Plan:
```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
```
test_capture_runs_each_example_once pins the capture-once contract with a
region that counts its own calls; test_capture_does_not_double_the_gradients_it_accumulates
and test_a_mutating_module_is_guarded_on_what_the_capture_saw pin the two
consequences the probe design got wrong. test_shape_guards_survive_a_single_example
rejects four out-of-domain calls that the old policy served;
test_a_different_class_is_refused_not_served covers TYPE_MATCH;
test_a_dict_membership_guard_is_never_dropped and
test_a_module_owned_dict_membership_guard_is_never_dropped cover the
membership guards on a local and on a module-owned dict, the latter also
asserting DICT_NOT_CONTAINS is absent from POLICY_DROPPED_GUARDS.
test_an_empty_capture_is_not_complete covers the compiled-no-graph refusal.
The unpicklable-value tests assert the diagnostic names the actual value and
its path, including a function default
(test_unpicklable_function_default_names_the_path), and a round-trip test pins
live AND pickled isolation of _SourceGraphModule copies.
Authored with an AI assistant.
ghstack-source-id: be6a956
Pull-Request: #195371
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two probe rebuild the guard-policy pass now performs, and the package prepare_cache_entry builds, pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; the emitted driver's ``_serve`` records a backend only under a key the process registry does not already hold, and ``_InstalledArtifact.unload()`` takes out only the keys this install added and only while they still hold the object it recorded. Backend keys are per-capture uuids, so the only other holder of one is a second handle on the same artifact; an earlier version restored that holder's entry through record_artifact, which deep-copies, so the holder's own identity check never matched again and its keys leaked on unload; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: efb7edf Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two probe rebuild the guard-policy pass now performs, and the package prepare_cache_entry builds, pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; the emitted driver's ``_serve`` records a backend only under a key the process registry does not already hold, and ``_InstalledArtifact.unload()`` takes out only the keys this install added and only while they still hold the object it recorded. Backend keys are per-capture uuids, so the only other holder of one is a second handle on the same artifact; an earlier version restored that holder's entry through record_artifact, which deep-copies, so the holder's own identity check never matched again and its keys leaked on unload; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: efb7edf Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two probe rebuild the guard-policy pass now performs, and the package prepare_cache_entry builds, pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; the emitted driver's ``_serve`` records a backend only under a key the process registry does not already hold, and ``_InstalledArtifact.unload()`` takes out only the keys this install added and only while they still hold the object it recorded. Backend keys are per-capture uuids, so the only other holder of one is a second handle on the same artifact; an earlier version restored that holder's entry through record_artifact, which deep-copies, so the holder's own identity check never matched again and its keys leaked on unload; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: efb7edf Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 2, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two probe rebuild the guard-policy pass now performs, and the package prepare_cache_entry builds, pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; the emitted driver's ``_serve`` records a backend only under a key the process registry does not already hold, and ``_InstalledArtifact.unload()`` takes out only the keys this install added and only while they still hold the object it recorded. Backend keys are per-capture uuids, so the only other holder of one is a second handle on the same artifact; an earlier version restored that holder's entry through record_artifact, which deep-copies, so the holder's own identity check never matched again and its keys leaked on unload; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: efb7edf Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 3, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two probe rebuild the guard-policy pass now performs, and the package prepare_cache_entry builds, pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; the emitted driver's ``_serve`` records a backend only under a key the process registry does not already hold, and ``_InstalledArtifact.unload()`` takes out only the keys this install added and only while they still hold the object it recorded. Backend keys are per-capture uuids, so the only other holder of one is a second handle on the same artifact; an earlier version restored that holder's entry through record_artifact, which deep-copies, so the holder's own identity check never matched again and its keys leaked on unload; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: af9f477 Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 3, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two probe rebuild the guard-policy pass now performs, and the package prepare_cache_entry builds, pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; the emitted driver's ``_serve`` records a backend only under a key the process registry does not already hold, and ``_InstalledArtifact.unload()`` takes out only the keys this install added and only while they still hold the object it recorded. Backend keys are per-capture uuids, so the only other holder of one is a second handle on the same artifact; an earlier version restored that holder's entry through record_artifact, which deep-copies, so the holder's own identity check never matched again and its keys leaked on unload; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: 3365a14 Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 3, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and ``tracer="dynamo"`` (now its default), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. This is a breaking change against main, where the documented ``torch.compiler.precompile(...)`` returned the ``(python_code, cache)`` pair; the API is a prototype and no release carries it, so there is no deprecation cycle, and an old-style call fails loudly (positional examples with a pointed TypeError, a missing path with a ValueError naming ``precompile.artifact``). The whole surface is marked as a prototype API. A ``_reject_positional_examples`` check keeps the pointed TypeError for the retired positional spelling on both forms. 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. Companion guards that drop_failed_guards removes inside _reserialize_without's rebuild (the HASATTR paired with a dropped base.attr subject) reach _record_unrebuildable and _record_dropped_code, so summary().risky_dropped_guards, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning do not understate what was removed. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The two probe rebuild the guard-policy pass now performs, and the package prepare_cache_entry builds, pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, documents all eight rules under which reducer_override substitutes _Missing and mirrors the five a bound method's receiver can plausibly hit, now including a type in ``_get_unsupported_types()``. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. 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. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem) and renames both into place only after both are fsynced. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. The lock is reentrant because that close happens inside __call__. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly, and no longer overrides its __module__. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; the emitted driver's ``_serve`` records a backend only under a key the process registry does not already hold, and ``_InstalledArtifact.unload()`` takes out only the keys this install added and only while they still hold the object it recorded. Backend keys are per-capture uuids, so the only other holder of one is a second handle on the same artifact; an earlier version restored that holder's entry through record_artifact, which deep-copies, so the holder's own identity check never matched again and its keys leaked on unload; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py ``` test_precompile_public_result_types pins the three return types (precompile -> list, artifact -> the pair, PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture and reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: c4ec4cb Pull-Request: #195362
bobrenjc93
added a commit
that referenced
this pull request
Sep 3, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and traces with dynamo (passing ``tracer=`` or ``decompositions=`` to it is a TypeError naming ``precompile.artifact``), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented; it never had a positional spelling, so a positional example there is a pointed TypeError. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. The 2.14 release shipped and documented ``precompile(fn, *example_inputs, backend="inductor", tracer="make_fx", decompositions=None) -> (python_code, cache)``, so that spelling is kept for one release: the one example call passed positionally still returns the pair, as ``precompile.artifact`` with ``example_inputs=[example_inputs]`` and the make_fx default, behind a FutureWarning that names the replacement; combining it with ``example_inputs`` or the paths is a TypeError. What changed for the keyword form against main is the return type (the results list rather than the pair), the two required paths, and the tracer (dynamo only). The whole surface is marked as a prototype API. 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. Each CheckFunctionManager builds a precompiled frame's guard tree twice, not three times; per frame variant the public path builds three managers -- the live one, the policy rebuild, and _validated's rebuild of the pickle that ships -- for five build_guards calls, and the test pins both numbers. Drift is measured on that last tree, the one the serving machine builds, rather than on the policy rebuild's runtime tree: the latter still holds the failed guards' HASATTR companions, whose inverted rebuild was reported as drift although it never ships. A guard that drop_failed_guards removes -- the unrebuildable one and the HASATTR paired with its base.attr subject -- leaves the serialized set before any filter entry is built, so it never reached the filters' recording; its rendered check is recorded in _record_unrebuildable instead, where it still has its code_list, so summary().risky_dropped_guards, summary().dropped_guard_code, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning agree on what was removed, and the warning fires once per (guard type, source) rather than once per Guard object per rebuild. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The probe rebuilds the guard-policy pass performs pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards; package.py's load_guard_manager passes it too, for every CompilePackage install including ordinary caching_precompile loads, which removes one redundant build there and changes no guard. The gradient snapshot a default capture takes reads .grad only off leaves and retained-grad tensors, visiting each argument once, so a non-leaf example input no longer produces two "not a leaf Tensor" warnings per capture. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, mirrors every rule under which reducer_override substitutes _Missing, in its order -- a precompile handle, missing_values, a returned _Missing, an unreached tensor or nn.Module, a PyCapsule, an unsupported type, and a function whose qualified name resolves elsewhere -- and its docstring lists them. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. The package stops shipping every inlined module's whole source, resolves code defined under property/cached_property (a class attribute whose function or descriptor carries a different name is skipped, so the definition's own name resolves it), and revalidates a memoized module-by-file hit before handing it back. Neither driver rebuilds closure cells for the entry: capture refuses a closure entry, so _entry_binding carries defaults only. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem), renames both into place only after both are fsynced, and moves the previous artifact aside first so that if the second rename fails the previous pair is put back rather than leaving a new .py beside the old cache, which load refuses on code_hash. Every entry that takes the path pair refuses one file named for both halves, which used to overwrite the source with cache bytes. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. A rewrite that fails with an OSError also carries the result but leaves the capture open, and the files are the previous call's pair. The lock is reentrant because that close happens inside __call__; a call made from inside fn therefore reaches __call__ with the lock held, and is refused as a recursive re-entry rather than as a concurrent one. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly. Nothing reachable through the precompile singleton has its __module__ rewritten any more: ExampleInput, AccumulatingCapture, PrecompileSummary, FrameInvariants and GuardFact (the last three now hang off the singleton, where the docs place them) report the module that defines them, so pickle resolves them and inspect.getsource finds them; only PrecompileError and PrecompiledCallable, the two names in torch.compiler.__all__, report torch.compiler, set on the class. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results; the 2.14 positional spelling and its FutureWarning, and the ValueError/TypeError cases), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back, with PrecompileSummary, FrameInvariants and GuardFact documented under precompile.*) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; the emitted driver's ``_serve`` records a backend only under a key the process registry does not already hold, and ``_InstalledArtifact.unload()`` takes out only the keys this install added and only while they still hold the object it recorded. Backend keys are per-capture uuids, so the only other holder of one is a second handle on the same artifact; an earlier version restored that holder's entry through record_artifact, which deep-copies, so the holder's own identity check never matched again and its keys leaked on unload; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_precompile_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py python test/test_public_bindings.py -k correct_module_names ``` test_precompile_public_result_types pins the three return types (precompile -> list, or the pair for the 2.14 positional spelling; artifact -> the pair; PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_2_14_positional_call_still_returns_the_pair runs the exact call from the 2.14 docs under assertWarns(FutureWarning), loads the result with precompile.load(python_code, cache), and pins the TypeErrors for tracer=/decompositions= without positional examples and for mixing the two spellings. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_keeps_the_last_artifact_when_the_rewrite_fails fails the cache rename and asserts the previous pair is intact and loadable with the OSError as the cause; test_precompile_artifact_paths_must_name_two_files covers the same-file refusal on all three entries; test_precompile_accumulate_refuses_recursive_re_entry pins the recursion message. test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture while an observer thread checks that every snapshot of the files taken with no rewrite in progress is a matched code_hash pair, then reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_guard_drift_is_reported injects a real drift -- the reconstructed scope is edited so an EQUALS_MATCH rebakes to a constant no live build made -- and asserts the default gate refuses it; test_unrebuildable_guards_reach_the_dropped_code_report fails a TENSOR_MATCH rebuild and asserts DROPPED_GUARD_CODE and summary().dropped_guard_code name the dropped check, that the dropped companion is not reported as drift, and that the HASATTR warning fires once. test_grad_snapshot_reads_grad_only_off_leaves asserts a non-leaf example input produces no "not a leaf" warning. test_capture_builds_each_guard_tree_twice_not_three_times pins two builds per manager and five per variant. test_precompile_attribute_classes_keep_a_truthful_module pins pickle and inspect.getsource on ExampleInput. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: 43fb11c Pull-Request: #195362
Contributor
Author
bobrenjc93
added a commit
that referenced
this pull request
Sep 3, 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 public surface is settled here as three entry points, each with one return type. ``torch.compiler.precompile(fn, *, example_inputs, artifact_path, cache_path, ...)`` requires both paths and traces with dynamo (passing ``tracer=`` or ``decompositions=`` to it is a TypeError naming ``precompile.artifact``), writes the artifact to disk, and ALWAYS returns the list of what the example calls returned, in order -- a real capture's artifact runs to hundreds of megabytes of source, so it is kept out of memory, and the results are how a training capture over real batches hands its losses on without a second forward. A make_fx trace runs ``fn`` under proxy tensors and has no results to give, so it is refused BEFORE ``fn`` runs rather than handing back an empty list after it. ``precompile.artifact(fn, *, example_inputs, ...)`` is the in-memory ``(python_code, cache)`` pair for both tracers (default make_fx, ``decompositions`` accepted) and is where the shared contract is documented; it never had a positional spelling, so a positional example there is a pointed TypeError. The alternative -- one call whose return type depends on whether the paths were passed -- is what was there before, and a return type that changes with the arguments is exactly the kind of thing a caller gets wrong silently; both forms share a private ``_capture``. ``precompile.accumulate`` is the third. The 2.14 release shipped and documented ``precompile(fn, *example_inputs, backend="inductor", tracer="make_fx", decompositions=None) -> (python_code, cache)``, so that spelling is kept for one release: the one example call passed positionally still returns the pair, as ``precompile.artifact`` with ``example_inputs=[example_inputs]`` and the make_fx default, behind a FutureWarning that names the replacement; combining it with ``example_inputs`` or the paths is a TypeError. What changed for the keyword form against main is the return type (the results list rather than the pair), the two required paths, and the tracer (dynamo only). The whole surface is marked as a prototype API. 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. Each CheckFunctionManager builds a precompiled frame's guard tree twice, not three times; per frame variant the public path builds three managers -- the live one, the policy rebuild, and _validated's rebuild of the pickle that ships -- for five build_guards calls, and the test pins both numbers. Drift is measured on that last tree, the one the serving machine builds, rather than on the policy rebuild's runtime tree: the latter still holds the failed guards' HASATTR companions, whose inverted rebuild was reported as drift although it never ships. A guard that drop_failed_guards removes -- the unrebuildable one and the HASATTR paired with its base.attr subject -- leaves the serialized set before any filter entry is built, so it never reached the filters' recording; its rendered check is recorded in _record_unrebuildable instead, where it still has its code_list, so summary().risky_dropped_guards, summary().dropped_guard_code, the artifact's RISKY/DROPPED_GUARD_CODE sections and the drop warning agree on what was removed, and the warning fires once per (guard type, source) rather than once per Guard object per rebuild. The HASATTR guard builder registers the attribute value with the guard tree for TENSOR bases: 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; it is narrowed to tensor bases because that inversion 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 drift check's live-leaf recording (_LIVE_LEAF_GUARDS) is a ContextVar rather than a module global, installed per capture call by PrecompileSession._call into the session's cycle set, so a torch.compile on another thread neither records into a capture's set nor clobbers a second session's on exit; _quiet silences guard-failure logging with a per-thread logging filter rather than logger.disabled, which is process-wide and took a concurrent torch.compile's guard-failure log down with it. The probe rebuilds the guard-policy pass performs pass the ``explicit_capture`` flag that the tracer commit below introduced, so they are treated like the capture that produced the guards; package.py's load_guard_manager passes it too, for every CompilePackage install including ordinary caching_precompile loads, which removes one redundant build there and changes no guard. The gradient snapshot a default capture takes reads .grad only off leaves and retained-grad tensors, visiting each argument once, so a non-leaf example input no longer produces two "not a leaf Tensor" warnings per capture. 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 in the pickle STATE slot and a wrapper subclass's requires_grad, keeps a retained-grad non-leaf's .grad (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 makes the bound-method reducer a fixed point over its own output. Dimension markings register where they are read. test_opaque_obj_v2's test_guard_pickle_subclass_with_opaque_inner_attr unpacked reducer_override(tensor) as a 2-tuple; it now unpacks the (func, args) head explicitly and asserts the full pickle round-trips, which is the contract that regression test exists for. When a guard value cannot be pickled the diagnostic now finds the value. It searches the whole guard state, attributes the failure by identity rather than type name, and names the attribute path where the value lives. ``_offending_value_path`` descends into a function's ``__defaults__``, ``__kwdefaults__`` and closure cells -- a function a guard is rooted at is pickled by value, so a default some guard reads travels with it, and the walk used to stop at the function with no path at all -- and one object whose attribute read raises (a ``__dict__`` property that throws, a proxy) no longer ends the whole walk. ``GuardsStatePickler._reduces_to_missing``, which a reducer that has to know its own output asks rather than reading the value, mirrors every rule under which reducer_override substitutes _Missing, in its order -- a precompile handle, missing_values, a returned _Missing, an unreached tensor or nn.Module, a PyCapsule, an unsupported type, and a function whose qualified name resolves elsewhere -- and its docstring lists them. 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. The installed driver checks the same locks the standalone driver does -- _DYNAMO_PYTHON_VERSION and TORCH_VERSION -- and raises the documented PrecompileError, since it unmarshals bytecode and unpickles Dynamo internals and a cross-build artifact otherwise failed wherever its blob happened to break first; the INLINED_SOURCES drift check likewise raises PrecompileError, and treats an absent or source-less (.pyc-only) module as UNVERIFIABLE -- skipped -- rather than rejecting a working artifact with a raw ModuleNotFoundError/OSError, while a module the bytecode actually needs still fails loudly in the import_sources loop. The package stops shipping every inlined module's whole source, resolves code defined under property/cached_property (a class attribute whose function or descriptor carries a different name is skipped, so the definition's own name resolves it), and revalidates a memoized module-by-file hit before handing it back. Neither driver rebuilds closure cells for the entry: capture refuses a closure entry, so _entry_binding carries defaults only. _write_artifact writes each half through a uniquely named scratch file beside its target (pid and a uuid in the name, so two writers targeting one path never share a scratch file and the rename stays on one filesystem), renames both into place only after both are fsynced, and moves the previous artifact aside first so that if the second rename fails the previous pair is put back rather than leaving a new .py beside the old cache, which load refuses on code_hash. Every entry that takes the path pair refuses one file named for both halves, which used to overwrite the source with cache bytes. 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. Every serialization boundary -- artifact(), save() and snapshot_artifact() -- calls refuse_unserializable(), so an accumulating capture whose CPU codegen target drifted mid-loop no longer writes an artifact mixing native code for two ISA targets. The session's __enter__ exception path drains in-flight calls BEFORE any teardown (matching __exit__) and runs the region cleanup in a finally, so a concurrent resumable-session call cannot be left compiling against a destroyed entry and an interrupt raised out of the drain's wait cannot leak the compile region; re-entering an active session raises PackageError. accumulate() builds on exactly that pair of behaviours. 5. The accumulating capture (torch/_precompile.py): calls are serialized on an RLock, so a second thread calling the capture waits for the first call to finish, artifact rewrite included, and the files on disk are one whole artifact at every instant. A call whose fn raises propagates the error and leaves the capture open. A refusal from the artifact gates (require_*) is different and final: the gate runs AFTER the step, whose gradients have moved and whose result exists, and the refusal is about the accumulated capture, which every later render would repeat -- so the capture closes (the files keep the last artifact that passed), the PrecompileError carries the step's return value as ``result``, and every later call raises without running. Leaving the capture open instead would train and raise again on every step. A rewrite that fails with an OSError also carries the result but leaves the capture open, and the files are the previous call's pair. The lock is reentrant because that close happens inside __call__; a call made from inside fn therefore reaches __call__ with the lock held, and is refused as a recursive re-entry rather than as a concurrent one. close() goes through the session's retire(), which performs the same _closing/_active_calls handshake as __exit__ before tearing the region down, so a capture call in flight on another thread cannot be left compiling against a destroyed cache entry. AccumulatingCapture is documented as returned by accumulate() and not constructed directly. Nothing reachable through the precompile singleton has its __module__ rewritten any more: ExampleInput, AccumulatingCapture, PrecompileSummary, FrameInvariants and GuardFact (the last three now hang off the singleton, where the docs place them) report the module that defines them, so pickle resolves them and inspect.getsource finds them; only PrecompileError and PrecompiledCallable, the two names in torch.compiler.__all__, report torch.compiler, set on the class. 6. 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. The bypassed-entry diagnostic in _reject_uninstallable_entry fires from the empty-frames state, which is what production actually produces (_multigraph_frames DROPS bypassed codes, so a bypassed entry arrives as "no entry frame" rather than as a bypassed frame). The docs describe exactly this surface: precompile (paths required, dynamo only, returns the results; the 2.14 positional spelling and its FutureWarning, and the ValueError/TypeError cases), precompile.artifact (the pair, both tracers, the full parameter contract), accumulate (the gate-refusal and threading behaviour, what summary()/invariants()/calls()/close() give back, with PrecompileSummary, FrameInvariants and GuardFact documented under precompile.*) and load (pair or paths, exclusive), with prototype warnings on each. 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 (TYPE_MATCH and HASATTR included, with their covering test) and the unpicklable-value diagnostics formerly in this PR live in that PR, where their machinery lands; this PR's rebuildability collection builds on its PackageError-converting re-serialization pass. Smaller corrections from review: artifact files are written to a uniquely named sibling temp file with a plain ``open`` and then ``os.replace``d, so the result honours the umask (``tempfile.mkstemp`` made them 0600, unreadable by other users of a shared artifact directory); the live-leaf-guard recording test runs its worker in an explicit fresh ``contextvars.Context`` because a free-threaded Python 3.14 thread inherits its parent's context by default; ``PrecompileError.result`` is documented; the emitted driver's ``_serve`` records a backend only under a key the process registry does not already hold, and ``_InstalledArtifact.unload()`` takes out only the keys this install added and only while they still hold the object it recorded. Backend keys are per-capture uuids, so the only other holder of one is a second handle on the same artifact; an earlier version restored that holder's entry through record_artifact, which deep-copies, so the holder's own identity check never matched again and its keys leaked on unload; and the ``torch.compiler`` and ``precompile_package`` docstrings describe ``precompile(...)`` versus ``precompile.artifact(...)`` as they now are. Test Plan: ``` python test/test_precompile.py python test/test_opaque_obj_v2.py python test/dynamo/test_package.py python test/dynamo/test_precompile_package.py python test/dynamo/test_guard_serialization.py python test/dynamo/test_recompile_ux.py python test/test_public_bindings.py -k correct_module_names ``` test_precompile_public_result_types pins the three return types (precompile -> list, or the pair for the 2.14 positional spelling; artifact -> the pair; PrecompileSession.artifact -> the pair) and that precompile, artifact, accumulate and PrecompileSession.artifact all default require_no_risky_drops=True and require_no_dropped_guards=False. test_precompile_2_14_positional_call_still_returns_the_pair runs the exact call from the 2.14 docs under assertWarns(FutureWarning), loads the result with precompile.load(python_code, cache), and pins the TypeErrors for tracer=/decompositions= without positional examples and for mixing the two spellings. test_precompile_accumulate_gate_refusal_closes_the_capture asserts the result rides on the error, the next call fails fast, and nothing was written; test_precompile_accumulate_keeps_the_last_artifact_when_the_rewrite_fails fails the cache rename and asserts the previous pair is intact and loadable with the OSError as the cause; test_precompile_artifact_paths_must_name_two_files covers the same-file refusal on all three entries; test_precompile_accumulate_refuses_recursive_re_entry pins the recursion message. test_precompile_accumulate_serializes_concurrent_calls drives two threads through one capture while an observer thread checks that every snapshot of the files taken with no rewrite in progress is a matched code_hash pair, then reloads the result. A two-thread test pins that close() parks until an in-flight call finishes; drift injected between accumulate() calls pins the snapshot_artifact refusal. test_guard_drift_is_reported injects a real drift -- the reconstructed scope is edited so an EQUALS_MATCH rebakes to a constant no live build made -- and asserts the default gate refuses it; test_unrebuildable_guards_reach_the_dropped_code_report fails a TENSOR_MATCH rebuild and asserts DROPPED_GUARD_CODE and summary().dropped_guard_code name the dropped check, that the dropped companion is not reported as drift, and that the HASATTR warning fires once. test_grad_snapshot_reads_grad_only_off_leaves asserts a non-leaf example input produces no "not a leaf" warning. test_capture_builds_each_guard_tree_twice_not_three_times pins two builds per manager and five per variant. test_precompile_attribute_classes_keep_a_truthful_module pins pickle and inspect.getsource on ExampleInput. test_live_guard_leaf_recording_is_thread_scoped pins the ContextVar; test_installed_artifact_refuses_a_foreign_torch_build pins the installed driver's TORCH_VERSION lock; the drift test covers the module-absent serve and cleans up the module it imports and the global it rebinds. The bypassed-entry test constructs the state production actually produces. Authored with an AI assistant. ghstack-source-id: 07cbcc1 Pull-Request: #195362
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Three holes in the invariant-guard policy, each of which serves a wrong answer
rather than refusing, and the first two on the DEFAULT gates.
The policy drops a slot that held identically in every captured variant, on the
stated contract that the environment is fixed and every variation is in the
inputs. varying_guard_slots over a SINGLE variant is empty by construction --
one variant cannot disagree with itself -- so a one-shot precompile() drops
every droppable slot in the artifact. That is why both of the first two
reproduce with no gate relaxed.
HASATTR was not in the never-drop set. hasattr is a branch, so dropping it
serves the captured side to a caller on the other one. Captured with the
attribute and served without it, a
x * 2.0/x * 100.0branch returns 2.0where eager returns 100.0, RISKY_DROPPED_GUARDS is empty, and nothing raises.
It belongs beside CONSTANT_MATCH and EQUALS_MATCH, which are in the set for
exactly this reason: they pin a Python value the graph specialized on, and
shapes at least crash inside a kernel where these do not.
survives() judged only the top-level guard type. default_guard_filter_fn reads
derived_guard_types and this did not, but one Guard emits several checks -- a
DICT_KEYS_MATCH emits the SEQUENCE_LENGTH for the same dict -- and apply_filter
removes whole Guards. So the length check went out with its parent, and
d["a"] * len(d)captured on a two-key dict answers a four-key dict with thetwo-key result.
And on the accumulating path the gates ran before the policy pass.
snapshot_artifact called _gated_summary and only then _policy_filtered_codes,
so require_no_risky_drops judged the PREVIOUS render's numbers -- nothing at
all on the first call. A capture that renders once therefore wrote
POLICY_DROPPED_GUARDS = [] into the artifact while that same pass had dropped
ten slots. The existing regression test makes two calls, so it read the lagged
value and passed.
And the general form of the first one, which is the better fix and which a
reviewer pushed back for. Blanket-protecting a guard type is a blocklist: it
closes HASATTR and leaves every other type whose drop is silently wrong open.
The premise the policy rests on already names the right rule -- "the environment
is fixed and every variation is in the inputs" -- so classify a slot by what it
is ROOTED at rather than by whether it was observed to vary. Environment is the
module structure, the process globals, the global interpreter state and the
shape env; a local holding anything else is data the caller passed in, and the
contract does not license dropping guards on it.
Module-rooted is decided by VALUE, not by the name starting with "self".
precompile's own calling convention passes the model in as an argument, so on
the public API the module structure hangs off a local like
model, and aname-prefix rule would keep all of it -- 35 of 38 dropped slots in the test
model. Keying on isinstance(value, nn.Module) covers both that and the
self-rooted shape an inner frame sees.It costs almost nothing, which is the point: on a six-block model the drop count
and the rendered artifact are byte-identical with and without it, because the
bulk of a real model's invariant guards genuinely are module structure. On the
reporting model it was measured at roughly 60 of 7,575 slots retained.
HASATTR stays in the never-drop set as well. The root rule is the general
answer, but that one type's failure is a silently wrong branch and it has
already bitten once.
And two things a reviewer asked for on top, neither of which is a correctness
change.
Every dropped slot now carries what it actually checked, as DROPPED_GUARD_CODE
in the artifact and PrecompileSummary.dropped_guard_code. A slot is identified
by its type and its SOURCE, and for some types that is not enough to judge the
drop: a dropped ('HASATTR', "counts['pixel']") may be the benign companion of a
kept TENSOR_MATCH on the same source, or the only thing standing between the
artifact and an optional attribute going missing, and those want very different
reactions from whoever is auditing it. The rendered check names the attribute
and tells them apart. Reported alongside the three lists rather than folded into
them, so the slot tuples stay the identity the policy compares on.
_parse_artifact_metadata reads it, and POLICY_DROPPED_GUARDS, as OPTIONAL keys,
so an auditor gets them back as data and artifacts predating them still load.
Not every dropped slot renders a check -- EMPTY_NN_MODULE_HOOKS_DICT installs
nothing under the default skip_nnmodule_hook_guards, and the global-state guards
are checked in C++ against no source -- so those appear in the drop lists with
no entry here rather than with an empty one.
And a comment on the facts-pruning loop saying why it is still classified by
observed variance: a GuardFact carries no source object, so it cannot be
root-classified. It is not a correctness gap on either path -- keep_only is
computed before the loop, so the pruning cannot feed itself, and the method
never runs on the accumulating path, where close() retires the session without
going through exit. It costs reporting fidelity in invariants(), nothing
more. Written down because the next reader will have the same worry.
Test Plan:
Six new tests. Three, one per hole, each assert the served artifact REFUSES the
call it cannot answer rather than answering it wrongly. The first two capture
under fully default gates on purpose -- that is the claim -- and both return the
captured branch's numbers without this change. The third renders exactly once
and asserts the artifact does not write an empty POLICY_DROPPED_GUARDS.
Two more cover the root rule from both sides: an input-rooted slot of a type no
never-drop list covers (NOT_PRESENT_IN_GENERIC_DICT on a class attribute) is no
longer dropped, and a module-heavy capture still prunes every slot it used to,
so the fix did not buy correctness by keeping everything.
One more asserts every dropped slot carries a non-empty check and that each is
one of the slots the three lists report.
Nothing regressed: the whole suite passes, so no test was relying on these
going out.
Reported by a reviewer running the stack against a production model; the
reproductions here are theirs, reduced to the public API.
Authored with the assistance of an AI coding agent.