Skip to content

[guards] Reconstruct fqn-mismatched functions when a guard is rooted at them - #195353

Closed
bobrenjc93 wants to merge 52 commits into
gh/bobrenjc93/1093/basefrom
gh/bobrenjc93/1093/head
Closed

bobrenjc93 wants to merge 52 commits into
gh/bobrenjc93/1093/basefrom
gh/bobrenjc93/1093/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Enabler for the precompile PR at the top of this stack.

GuardsStatePickler looks a function up by __module__ and __qualname__ and
substitutes a _Missing sentinel when that resolves elsewhere; every
functools.wraps wrapper and module-level lambda is such a mismatch. For a
function a guard is rooted at, load_guard_manager then evaluates the source
against the sentinel and the load fails.

A function in guard_tree_values is now pickled by value and rebuilt from its
code object, sharing one reconstruction with the <locals> branch in the
new FunctionPicklerBase (package.py); the AOT pickler is rebuilt on that
same base in the follow-up commit above this one.
The rebuilt function restores __name__, __module__, __doc__,
__kwdefaults__, __dict__ and the signature containers' shape, since a rebaked EQUALS_MATCH
reads them. Only values a guard references are carried; the rest become shared
_Missing sentinels, and a function whose __globals__ no guard reads gets
import_module(__module__).__dict__ at load. Everything beyond the
FunctionType() arguments travels as pickle state so self-referential values
do not recurse; an empty cell is rebuilt empty; a bound method whose function
does not resolve back is carried explicitly.

pickle_guards_state maps any exception -- including a RecursionError
from a deep or non-memoizing guard value -- to PackageError, and the bypass
now works: convert_frame checks the output
graph's package, which bypass_package clears, and a bypassed entry drops its
backend ids and guarded codes.

Test Plan:

python test/dynamo/test_guard_serialization.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py -k gone_at_load -k recursing -k lambda -k bound_method -k copied_doc
python test/dynamo/test_guard_serialization.py -k fqn_mismatched_function_prunes

The new tests mutate each restored attribute on the live function and assert
the loaded guard rejects it, and pin empty and None-valued cells, lambda and
bound-method roots, a module gone at load, the recursion-overflow-to-PackageError conversion, and
a non-strict bypass.

Authored with an AI assistant.

FAQ

Q: The bound-method branch in reducer_override emits a value that reduces back
to the same branch on a second pass; it reads like a no-op that could be
dropped. Why keep it?

A: It is load-bearing. The guard policy serializes guard state twice, and by
the second pass a method's receiver has already been degraded to the _Missing
sentinel. Emitting the binding unconditionally makes the branch a fixed point:
its own output reduces to itself, so the second pass is stable. Dropping it
would let the method degrade to _Missing on the second pass, re-pinning that
method's TYPE_MATCH to the sentinel, and the loaded artifact would then never
match a live receiver. The branch fires for every method reached during the
dump, so it is exercised, not dead.

Q: The delta ships some testing nits: a bare assertRaises(RecursionError)
where the file's convention is assertRaisesRegex; no assertIsNot pinning the
per-call {} identity split; no guard-side round-trip for __type_params__;
and the bound-method seeding loop is never exercised. Why not close these?

A: Triaged individually. The RecursionError case is the one place a regex adds
nothing: RecursionError carries CPython's "maximum recursion depth exceeded"
boilerplate, not a message this code authors, so assertRaisesRegex would pin
interpreter text rather than our contract; the sibling PackageError test regexes
precisely because it has an authored message. The {}-identity split is
deliberate and, as the comment at _unpickle_fn_from_snapshot now records,
unobservable -- no serialized guard reads __globals__ identity -- so an
assertIsNot would lock in behavior nothing depends on. The
__annotations__ round-trip WAS reachable here -- a guard reading an annotation
value rebakes a TYPE_MATCH on the __annotations__ dict plus an ID_MATCH on the
value type, both of which the by-value reconstruction must restore -- so it is
now folded in as the annotations subtest of
test_guard_rooted_at_fqn_mismatched_function, which mutates the restored
__annotations__ and asserts the loaded guard rejects it. The earlier claim
that annotations are "a verbatim assignment the runtime never evaluates" was an
AOT-path argument that does not hold on the guard path. __type_params__
remains genuine test debt. Every 3.12+ function already exercises the branch
with the empty tuple; a non-empty value needs PEP 695 syntax (3.12+), which this
test file cannot contain while it must parse on 3.10/3.11, so the test needs an
exec'd source and is deferred for the 2000-line gate. The pruned case matters: a
def f[T] TypeVar is not picklable by reference. The pre-dump bound-method seeding loop was
redundant for every reachable case and is now removed: get_guard_manager_from_source
seeds func where every guarded method is known, and the in-reducer write stays
as the belt-and-suspenders no-op described below.

Q: The bound-method seed gates on id(leaf) in guard_tree_values, which is
id-based; bound methods are ephemeral, so when the registered instance differs
from the pytree leaf the seed silently does not happen. And the in-reducer write
at guards.py is dead for every case the pre-dump loop covers. Fix both?

A: The id-based gate is correct for every case with coverage today; the failure
mode it misses (a fresh MethodType materialized by builder.get differing
from the pytree leaf) is a latent gap, and an equality fallback on
(__func__, __self__) is the right hardening but is not exercised by any
current test, so it is deferred rather than added blind. The in-reducer write is
a deliberate belt-and-suspenders no-op: it cannot fire for the covered cases and
is harmless for the rest; it is annotated as such rather than deleted so the two
registration sites stay symmetric.

Q: The Note's claim that "a guard never calls the rebuilt function" is not
strictly true -- WeakRefCallSource._name_template is "{0}()", so builder.get
would call the value. Shouldn't the claim be softened?

A: Latent and not currently reachable: no guard reconstructed on this path is
rooted at a WeakRefCallSource over a reconstructed function. The comment on the
shared _unpickle_fn_from_module already scopes the "reads attributes without
calling it" claim to the guard-serialization path and spells out that the shared
AOT path does call it (surfacing an empty scope as a call-time NameError); the
WeakRefCallSource corner is the same "if a future guard shape calls it" caveat
and is noted here rather than complicating the inline comment.

Q: Now that a guard-serialization bypass actually saves a package, a bypassed
frame that also graph-breaks saves a live resume-function entry beside the
bypassed parent. Does the next process die on load with "Name '_resume_at..'
already exists in scope" once the bypassed parent recompiles?

A: Not at the stack head. #195911 renames every installed resume function to a
per-install token-suffixed name, so the name the package owns
(_resume_at) is disjoint from the plain
_resume_at_ a recompiling bypassed parent regenerates. The
install-owned global and the regenerated one no longer share a name, so
install() binding entry.function_names above the if entry.bypassed: continue
cannot collide with CleanupHook.create. The underlying "install()-owned global
vs. a later recompile" overlap is pre-existing -- the named-parameters bypass at
output_graph.py reaches it too -- and is orthogonal to this commit.

Q: bypass_current_entry clears the bypassed entry's backend_ids and
guarded_codes, but never removes the inlined-source contribution that same
entry made to the package-global _source_info during an earlier successful
compile of the same code object (the entry is keyed by code object and reused
across recompiles). cache_entry() serializes _source_info whole, so at load
initialize() raises "Source code changes detected" for a helper only the now-
empty bypassed entry ever inlined, and eval_frame discards the ENTIRE package.
Shouldn't a bypassed entry stop contributing checksummed sources?

A: The _cached_backends half of this is fixed here: bypass now pops the entry's
compiled backends from the package-global cache before clearing backend_ids, so
a dead GraphModule is no longer stranded under an id no entry references. The
_source_info half is a real but narrower gap and is deferred deliberately.
_source_info has no per-entry attribution -- it is a package-global set that
add_inlined_source accumulates across every non-bypassed compile, and a loaded
artifact carries only that flattened blob with no per-entry breakdown, so
recomputing it from the live non-bypassed entries at cache_entry() time would
silently drop the sources a load-then-resave package legitimately inherited. The
honest fix is per-entry inlined-source attribution carried in the artifact
format, so a bypassed entry's uniquely-owned sources drop out while sources a
live entry still shares stay -- a serialization-format change, tracked
separately. Its only observable consequence is a SAFE over-invalidation: a
package whose sole referencer of an edited helper was bypassed is discarded and
recompiled cold, never a wrong result or a crash, which is why the format change
is deferred rather than rushed in here.

Q: _unpickle_fn_from_module swallows any import failure into f_globals = {} for
both the guard-serialization and AOT paths, so an AOT load succeeds and then
NameErrors from arbitrary call depth at first call, instead of failing cleanly
at load time with a ModuleNotFoundError. Why not stash the failed module name,
or have the AOT subclass re-raise?

A: The reducer is shared with the guard-serialization path, which reads
attributes off the rebuilt function without ever calling it and must tolerate an
exec-created or transformers_modules.* module that only existed in sys.modules
at save time. A single swallow keeps that path robust; the AOT path documents
the residual first-call NameError as a known limitation. Re-raising on the AOT
subclass would break the guard path's tolerance, so it is not done here.
Stashing the unresolved module name in the reduce state so the eventual
NameError can be attributed to the missing module is a cheap future improvement
and is tracked separately.

Q: The new hasattr(cls, "__getattr__") clause in the bound-method reducer
(package.py) makes the explicit (func, self) reduce fire for EVERY nn.Module
method -- nn.Module defines getattr -- not just the getattr proxy the
comment describes. Isn't that far wider than documented, and shouldn't it use
inspect.getattr_static(cls, name) to narrow it?

A: Revised: the reducer now asks the class MRO first. inspect.getattr_static(cls, name) is func -- which never runs a user __getattr__ -- means the name is
class-served, so the method returns to pickle's default getattr(self, name) at
load and its __func__ stays the class attribute; any other name on an INSTANCE
receiver (an instance-dict monkeypatch, a slot, a __getattr__ proxy, a property)
is carried as (func, self) explicitly and never probed -- probing runs user
code, can recurse, and a property hands back the bare function (the reducer used
to probe there and reloaded such a method as a plain function). Only a type
receiver (a classmethod) is still probed. The earlier coarse hasattr(cls, "__getattr__")
gate was correct for the guard path but, once the AOT pickler adopted the shared
reducer (#196454), it rebuilt every <locals> nn.Module method by value -- an
unpicklable default then failed the save and the reloaded __func__ was no
longer the class attribute -- so the MRO check is a correctness fix there, not
an optimization. A decorated forward (the MRO serves the wrapper, not
__wrapped__) still takes the explicit path. (The sibling guards.py edge runs no user __getattr__ either: it reads
dict through object.getattribute -- a type-level __dict__ property
is still invoked (pickle itself stopped doing so in 3.11, where
object.__getstate__ reads the slot directly) and only its AttributeError is
absorbed; a class that makes __dict__ a raising property is out of scope, as
it is for vars() -- and no longer touches
annotations at all, so the two halves of the commit do not take opposite positions on
running user code.)

Q: pr-sanity-checks is red -- this commit is 2228 LOC, over the 2000-line gate.
Shouldn't it be split?

A: Done. The AOT-pickler half -- rebuilding AOTCompilePickler on the shared
FunctionPicklerBase, the _dumps_cleanly prune, and the __doc__/__kwdefaults__
split -- moved to the follow-up commit above this one, bringing this commit under
the gate. The two halves split cleanly along a file seam (aot_compile.py and its
test move out; package.py's shared base, guards.py, convert_frame.py and the guard
tests stay), and the combined tree is unchanged. What remains here is one cohesive
unit: the fqn-mismatch guard reconstruction plus the guard-tree pruning that makes
the reconstructed guards serializable, with their tests. The bulk of the remaining
delta is new guard-serialization test cases, not new control flow.

Q: isinstance(source, AttrSource) misses GenericAttrSource, whose member also
lives in obj.__dict__. Is that a third whole-container shape the edge repair
should cover?

A: Not a reachable one. GenericAttrSource is produced only by SuperVariable
handling object.__getattribute__ (variables/misc.py), and the verbatim-__dict__
hazard exists only for a receiver that is itself a function -- the only object
_reduce_function prunes. Dynamo cannot trace object.__getattribute__(fn, name)
or super(FunctionType, fn).__getattribute__(name) on a function receiver: both
raise an observed exception during tracing and the frame is skipped, so no guard
is ever rooted through such a source on a function. Adding the type would be dead
code; the test-pinned AttrSource shape is the one that exists.

Q: getattr(base_example_value, "__dict__", None) runs a user __getattr__ on a
__slots__ receiver, and a non-AttributeError raised there escapes guard
creation as an InternalTorchDynamoError -- outside the pickle_guards_state
bypass. Real bug?

A: Yes -- fixed. The mapping edge now reads __dict__ through
object.__getattribute__ and treats AttributeError as "no instance dict", so no
user __getattr__ or __getattribute__ runs on that path (a class-level
__dict__ property is still invoked, and only its AttributeError absorbed;
pickle itself stopped reading __dict__ through the attribute protocol in 3.11). The read is package.py's _instance_dict, shared
with the bound-method reducer's receiver probe here and with #195912's
whole-object pruner, whose hasattr(obj, "__dict__") gate had the same hole;
test_attribute_guard_on_a_slotted_receiver_runs_no_user_getattr compiles the
reviewer's slotted receiver end to end under caching_precompile. Reproduced with a slotted class whose __getattr__
raises RuntimeError under caching_precompile: before, the compile failed with an
internal error; after, the frame compiles and the guard state serializes.

Q: The __annotations__ append in the same block should be deleted: reading it
directly forces PEP 649 evaluation on 3.14 (NameError for a TYPE_CHECKING-only
name), on <3.14 getattr(cls, "__annotations__", None) materializes an empty dict
INTO the class/module __dict__, and the edge it records is keyed on the
annotation dict while pointing at the attribute VALUE, which is not an element of
that dict. And the annotations subtest is already covered.

A: All correct -- the append is gone. A guard that reads an annotation value is
rooted at DictGetItemSource(AttrSource(fn, "__annotations__"), name), whose
base_example_value IS the annotations dict, so the generic edge at the top of
the block already records exactly the right container->element edge; the
annotations subtest of test_guard_rooted_at_fqn_mismatched_function exercises
that path and still passes with the append removed. Only the __dict__ half of
the repair remains, and the comments and the _keep_container_verbatim docstring
no longer name __annotations__ as a repaired shape.

Q: FunctionPicklerBase's docstring says the reducers are "shared by
GuardsStatePickler and AOTCompilePickler" and a comment describes what "the
shared AOT path" does, but at this commit the base has one subclass and the
resolve=True branch of _read_raw_annotations has no caller.

A: Fixed by moving the AOT-only parts up. The docstring and the _build_function
comment now describe the one subclass this commit has and say the AOT pickler is
rebuilt on the base in the commit above (#196454), which also rewords them back
to the shared form; the resolve= keyword and its Format.VALUE branch moved to
#196454 with their only caller. The combined tree is unchanged.

Q: _reduce_bound_method probes getattr(method.__self__, "__dict__", None)
BEFORE the hasattr(cls, "__getattr__") exemption, so a slotted receiver whose
__getattr__ recurses raises RecursionError out of the probe -- landing in the
bypass instead of the (func, self) reduce the comment promises.

A: Fixed. The receiver probe reads __dict__ through object.__getattribute__
(AttributeError -> no instance dict) so a user __getattr__ never runs there, and
the slotted __getattr__ proxy now takes the intended explicit-binding reduce.

Q: The description says a bypassed entry drops its compiled backends from
_cached_backends, but at this commit bypass_current_entry only clears
backend_ids and guarded_codes; the pop lives in #195913.

A: Fixed by moving those lines down into this commit (they were byte-identical to
#195913's, whose diff shrinks by the same lines). add_backend_id runs during
call_user_compiler, before build_guards can trigger the bypass, so the entry's
backend is already cached when it is bypassed and the pop is needed here.

Q: test_fqn_mismatched_function_prunes_an_unpicklable_called_default and
..._a_verbatim_dict_read compile a module and assert nothing; a bypass would
pass them.

A: Fixed. Both now clear PrecompileContext, compile, and assert the single dynamo
entry save_to_dynamo_cache() reports carries a non-empty backend_ids -- a
bypassed frame has none -- so a regression to carrying the container verbatim
(a PackageError bypass under non-strict precompile) fails the test.

Q: The RecursionError bypass message ("guard state exceeded the recursion limit
while pickling") names no frame; shouldn't it say WHERE?

A: Deliberately not by walking the object graph -- that recurses again on an
already-exhausted stack, as the comment says. The frame is still identifiable:
the PackageError is turned into a bypass by bypass_package, whose
"Detected a package bypass" log record is emitted inside that frame's compile and
carries its CompileId prefix, so the log context names the frame. (The
strict_precompile raise on that path had a pre-existing uninterpolated %s;
this commit fixes that one-liner while touching the area.)

Q: The Note in GuardsStatePickler says "a registered CONTAINER is carried
verbatim rather than pruned per element", contradicting _keep_container_verbatim,
and the convert_frame comment says the bypass fires when guards "could not be
serialized" although output_graph.py's named-parameters bypass reaches it too.

A: Both comments corrected: the Note now says a registered plain container is
carried verbatim UNLESS a guard is rooted at one of its elements through it, and
the convert_frame comment names both bypass producers.

Q: Per-value pruning can silently and permanently kill a whole-container value
guard, and the shape is ordinary code: if self.fn.__defaults__ == (2.0, 1.0)
(EQUALS_MATCH on the tuple, no per-element source) plus self.fn(x, b=5.0) (a
DefaultsSource edge for a) makes _keep_container_verbatim prune b to
_Missing, the EQUALS_MATCH is rebaked from the pruned tuple at load, and every
call recompiles forever with a healthy-looking package. The docstring's "coexist by
construction" claim does not hold.

A: Confirmed (reproduced: reloaded __defaults__ == (2.0, _Missing(...)),
fail_on_recompile trips) and fixed by tracking the missing fact rather than
documenting it: EQUALS_MATCH records the id of the value it bakes
(GuardBuilder.guard_tree_verbatim, save path only; CONSTANT_MATCH delegates
there for tuples -- a dict is never value-baked, its comparison decomposes into
per-key guards whose values register in guard_tree_values -- while
SEQUENCE_LENGTH/DICT_KEYS/TYPE_MATCH/ID_MATCH bake no contents and need nothing), and _keep_container_verbatim keeps such a
container verbatim before consulting the child edges. The two cases now really are
disjoint: a container some guard bakes whole is carried verbatim (an unpicklable
sibling there is a loud bypass, and cannot occur for a literal tuple anyway), and
only a container nothing reads by value prunes per value. The __dict__ per-value
path is unaffected because a whole-__dict__ read installs no EQUALS_MATCH. The
regression is pinned at zero cost: GuardedDefaultsTupleModule.forward now also
calls self.fn(x, b=5.0), so test_nested_function_preserves_a_guarded_defaults_tuple
fails without the fix and passes with it.

Q: The pre-dump loop in pickle_guards_state that seeds a guarded bound
method's __func__ looks like a no-op: the only writer that puts a bound method
into guard_tree_values is get_guard_manager_from_source, which seeds __func__
in the same statement under the same save_guards gate.

A: Correct, and measured (across the whole serialization suite the loop would
have seeded zero functions), so it is deleted; the source-site seed is the
load-bearing one and the in-reducer write remains as the belt-and-suspenders
no-op an earlier FAQ describes.

Q: The two full-compile container-edge tests assert only that the frame was
captured (backend_ids non-empty), which cannot distinguish "serialized fine" from
"serialized fine but the guard never matches again" -- exactly the silent failure
mode the Note warns about.

A: Both now capture, save, reset, reload through the transparent cache and serve
under fail_on_recompile (_assert_reloads_and_still_matches), so a rebaked
guard that no longer matches fails the test; the blocker shape above is pinned by
the defaults-tuple test the same way.

Q: __doc__ is pruned unconditionally, so a plain-str docstring is dropped and
a docstring-less function comes back with a truthy _Missing instead of None.

A: Fixed: a str or None __doc__ is kept (it always pickles); only a
reassigned non-str object is pruned. Nothing on the guard path reads __doc__
unless a guard is rooted there, in which case _keep already kept it, so this is
fidelity, not correctness.

Q: guard_tree_verbatim is a set[int] while guard_tree_values is a dict that
pins the objects its ids came from; an EQUALS_MATCH id(val) of a freshly built
value could dangle and be recycled onto an unrelated container.

A: Made a dict[int, Any] for uniformity (zero cost). The hazard was latent
rather than live: GuardBuilder.get memoizes every source's value in
src_get_value_cache, so the val EQUALS_MATCH records is the same object
get_guard_manager_from_source stores in guard_tree_values, pinned for the whole
pickle_guards_state call (measured over both suites: all 61 recorded ids resolve
to live, identical objects). Pinning it directly removes the reliance on that
invariant.

Q: bypass_current_entry() in the bypass test runs before any backend is
registered, so the new _cached_backends pop loop iterates zero times and nothing
pins it.

A: The test now registers a backend id under the code context first, bypasses,
and asserts cached_backends is empty.

Q: "A dict/tuple SUBCLASS is always verbatim" reads unconditional, but the
_keep gate above it means an unkept subclass prunes per value and comes back as
a plain dict/tuple.

A: Docstring corrected to "a KEPT dict/tuple subclass is always verbatim"; an
unkept container has no guard rooted at it (edges are keyed on values that
_keep holds), so its type is nobody's business.

Q: The fqn-resolution walk (module + qualname, rebuild by value when it does not
round back) lives only in the guard pickler; the AOT pickler dispatches on the
<locals> marker alone, so a functools.wraps wrapper of a module-level function
diverges between the two.

A: Lifted into FunctionPicklerBase._fqn_resolves here and used by the guard
pickler; #196454 switches the AOT dispatch to it, which is the "shared so a fix
cannot be missed" promise of the base class. (pickle_guards_state also gained the
guard_tree_verbatim argument this round; #195912's hand-built builder namespace
in its path test is updated to carry it.)

Q: For an instance receiver whose class serves the name through a property (or
any descriptor that is not the function itself), the reducer's getattr(self, name) probe runs the descriptor and can return the bare function, so func is inner says "class-served" and the method reloads as a plain function.

A: Real; fixed. The reducer no longer probes an instance receiver at all: an
instance-dict entry is carried explicitly, a getattr_static hit on the class is
class-served, and anything else on an instance (slot, __getattr__ proxy,
property, other descriptor) is carried as (func, self) explicitly. Only a type
receiver (a classmethod bound to its class) is still probed.
test_bound_method_on_an_instance_served_name_is_not_probed covers the three
receiver kinds in one subTest loop and asserts the property was never read.

Q: _globals_snapshot prunes __builtins__ to the sentinel, so a function the
rebuilt function creates at call time cannot resolve builtins through
__globals__.

A: The affected shape is narrow -- only a guard-pickler function whose
__globals__ a guard reads AND which is later called takes the snapshot path;
the AOT pickler passes no snapshot and loads its functions through the real
module dict -- but the hardening is free, so the snapshot now carries the
builtins module for __builtins__ instead of pruning it.

Q: third_party/kineto is bumped in this commit.

A: A stale gitlink from rebasing across main's kineto bump (#196015 -> #196325),
not an intended change; reset to the base's commit here, which is the only commit
in the stack that touched it.

Q: BUILTIN_MATCH now checks isinstance(source.index, str); is that this
commit's change?

A: No. That line is on origin/main, on this commit's parent and on the PR base
branch (introduced by #196370, "Type source keys and region hashes as object");
git diff <parent> <this commit> -- torch/_dynamo/guards.py has no hunk touching
used_builtin_vars. The comparison was against a stale base.

Q: test_a_whole_tuple_guard_keeps_defaults_verbatim passes no
guard_tree_verbatim, so it exercises the absent-edge branch, not the record the
name promises.

A: Fixed: the fixture now passes a child edge (which alone would prune the
sibling) together with the verbatim record, so the test fails without
_keep_container_verbatim's record check.

Q: _unpickle_fn_from_module imports fn.__module__ for the rebuilt function's
scope, but functools.wraps copies __module__ from the wrappee, so a wrapper
defined in another module is rebuilt against the wrong globals.

A: Fixed here (the base class owns the reducer): the no-snapshot reduce now
carries both fn.__module__ (for the rebuilt function's __module__) and the
compile scope, fn.__globals__["__name__"], which is what gets imported for
__globals__. A function whose __module__ is None still has a scope. The
guard path never calls a rebuilt function, so the AOT pickler (#196454, which
does) carries the test: test_aot_compile_rebuilt_wrapper_keeps_its_own_module_scope.

Q: snapshot["__builtins__"] = builtins inserts the key unconditionally, so a
snapshot can be one entry longer than the dict it mirrors.

A: Fixed: the insert is gated on the key being present in the live dict. A
function built with types.FunctionType(code, {}) has no __builtins__ and
CPython resolves its nested functions' builtins from the interpreter, so an
absent key needs no replacement, and a DICT_KEYS_MATCH/SEQUENCE_LENGTH
guard on such a __globals__ sees the live shape.
test_snapshot_globals_function_preserves_module now asserts the reloaded
__globals__["__builtins__"] is the module.

Q: _instance_dict's docstring claims more than the read guarantees, and the
bound-method seeding "loop-only shape" (a raw function as a separate unguarded
leaf) has no test.

A: Docstring corrected (a user __getattr__/__getattribute__ never runs; a
type-level __dict__ property does, and only its AttributeError is absorbed).
test_guard_rooted_at_fqn_mismatched_bound_method now also passes the raw
function as an unguarded leaf, which the pre-dump missing_values pass would
prune if the source-site seed did not keep it whole.

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Aug 30, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit be43fcc with merge base 9d5a710 (image):
💚 Looks good so far! There are no failures yet. 💚

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

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
…at them

One of the enabler fixes the precompile PR at the top of this stack needs. That PR
serializes a Dynamo guard tree per captured variant and rebuilds it at load;
this is what stops the rebuild from failing on ordinary library code.

A serialized guard set cannot be loaded if any guard's source walks through a
function whose qualname does not resolve back to it. `GuardsStatePickler` looks
the function up by `__module__` and `__qualname__` and substitutes a `_Missing`
sentinel when that finds something else. For a function nothing depends on that
is correct. For one a guard is rooted at, evaluating the source against the
sentinel raises while the guard manager is still being built, and the whole load
fails.

Any `functools.wraps` decorator produces the mismatch, since the wrapper copies
the wrapped function's `__module__` and `__qualname__` while living in the
decorator's file. That makes this ordinary rather than exotic: it is why a
transformers model cannot be loaded from a compile package at all today.

The sentinel stays for functions no guard needs. A function in
`guard_tree_values` is pickled by value instead, rebuilt from its code object
through the same path the `<locals>` branch already used. Most of the diff is
what reaching that path from the fqn branch turned out to require, and the
reason it is so much is that the reconstruction is directly observable:
`load_guard_manager` re-runs guard construction against the deserialized scope,
so an EQUALS_MATCH constant is rebaked by reading the rebuilt function. Any
attribute the reconstruction gets wrong does not fail the load, it produces a
guard that never passes again. `__name__` (the old code passed `__qualname__`
there), `__module__` (`FunctionType` derives it from the globals it is handed,
which for the snapshot branch is empty), `__kwdefaults__`, `__dict__`, and the
length and keys of the signature containers are all load-bearing for that
reason, and each has a round-trip test that mutates the live function and
asserts the loaded guard rejects it.

Rebuilding drags along whatever the function holds, and carrying all of it would
let an unpicklable neighbour fail a package that never needed it. So the policy
is to carry only what some guard tree node references and to prune the rest to
sentinels -- the inverse of pickling the function wholesale, which is simpler but
regresses the failure mode this PR exists to remove. Pruning is shape-preserving
for the signature (a rebaked guard reads the container's length and keys) but not
for `__dict__`, which holds whatever a decorator happened to stash. The module
scope is snapshotted once per module dict, so N functions from one module cost
one copy of the scope rather than N.

Everything a rebuilt function holds beyond what `FunctionType()` needs -- its
defaults, kwdefaults, attributes and the module scope -- travels as pickle state
rather than as a reduce argument, and so do a cell's contents. pickle memoizes an
object only after saving its reduce arguments, so a value that reaches back to
the function being reduced recurses until RecursionError. That is not a corner
case: `wrapped = deco(base)` at module level puts the wrapper in its own
globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching
decorator stashes `wrapper` in its own `__dict__`. Only the globals were handled
that way at first; the closure and `__dict__` cases were found in review, and
since RecursionError was not among the exceptions `pickle_guards_state` mapped to
`PackageError`, they escaped compilation as InternalTorchDynamoError. State is
applied after memoization, so all of these now resolve to the pickle already
built.

An empty cell -- a free variable only assigned on a path that did not run -- has
no contents to read, and reading them raised `ValueError` out of the pickler.
Such a cell is now rebuilt empty.

`AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had
the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped
`__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the
shared pieces -- how a code object, cell, module, bound method and function are
rebuilt -- now live in `FunctionPicklerBase` in package.py. Each pickler keeps
its own dispatch and decides what a function carries: the guard pickler prunes
to what a guard reads, the AOT one prunes nothing because the runtime env has to
run the function.

`pickle_guards_state` turned only AttributeError into `PackageError`; anything
else `dump` raised -- TypeError for an unpicklable value, PicklingError, the
RecursionError above -- escaped as InternalTorchDynamoError. Every such failure
means some guarded value cannot be serialized, which is exactly what
`PackageError` is for: a bypass for non-strict callers and an error under
`strict_precompile`, with the cause chained. So `dump` now maps any Exception to
`PackageError`, and a test pins that with a guarded value whose own `__reduce__`
raises.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
```

Each behavior above was also checked by blunting one aspect of the
reconstruction at a time and confirming a named test fails: cells or function
attributes carried as reduce arguments again, an empty cell read unguarded, and
`__module__` not restored each fail exactly one of the new tests.

Authored with an AI assistant.

ghstack-source-id: 8924927
Pull-Request: #195353
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
…at them

One of the enabler fixes the precompile PR at the top of this stack needs. That PR
serializes a Dynamo guard tree per captured variant and rebuilds it at load;
this is what stops the rebuild from failing on ordinary library code.

A serialized guard set cannot be loaded if any guard's source walks through a
function whose qualname does not resolve back to it. `GuardsStatePickler` looks
the function up by `__module__` and `__qualname__` and substitutes a `_Missing`
sentinel when that finds something else. For a function nothing depends on that
is correct. For one a guard is rooted at, evaluating the source against the
sentinel raises while the guard manager is still being built, and the whole load
fails.

Any `functools.wraps` decorator produces the mismatch, since the wrapper copies
the wrapped function's `__module__` and `__qualname__` while living in the
decorator's file. That makes this ordinary rather than exotic: it is why a
transformers model cannot be loaded from a compile package at all today.

The sentinel stays for functions no guard needs. A function in
`guard_tree_values` is pickled by value instead, rebuilt from its code object
through the same path the `<locals>` branch already used. Most of the diff is
what reaching that path from the fqn branch turned out to require, and the
reason it is so much is that the reconstruction is directly observable:
`load_guard_manager` re-runs guard construction against the deserialized scope,
so an EQUALS_MATCH constant is rebaked by reading the rebuilt function. Any
attribute the reconstruction gets wrong does not fail the load, it produces a
guard that never passes again. `__name__` (the old code passed `__qualname__`
there), `__module__` (`FunctionType` derives it from the globals it is handed,
which for the snapshot branch is empty), `__kwdefaults__`, `__dict__`, and the
length and keys of the signature containers are all load-bearing for that
reason, and each has a round-trip test that mutates the live function and
asserts the loaded guard rejects it.

Rebuilding drags along whatever the function holds, and carrying all of it would
let an unpicklable neighbour fail a package that never needed it. So the policy
is to carry only what some guard tree node references and to prune the rest to
sentinels -- the inverse of pickling the function wholesale, which is simpler but
regresses the failure mode this PR exists to remove. Pruning is shape-preserving
for the signature (a rebaked guard reads the container's length and keys) but not
for `__dict__`, which holds whatever a decorator happened to stash. The module
scope is snapshotted once per module dict, so N functions from one module cost
one copy of the scope rather than N.

Everything a rebuilt function holds beyond what `FunctionType()` needs -- its
defaults, kwdefaults, attributes and the module scope -- travels as pickle state
rather than as a reduce argument, and so do a cell's contents. pickle memoizes an
object only after saving its reduce arguments, so a value that reaches back to
the function being reduced recurses until RecursionError. That is not a corner
case: `wrapped = deco(base)` at module level puts the wrapper in its own
globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching
decorator stashes `wrapper` in its own `__dict__`. Only the globals were handled
that way at first; the closure and `__dict__` cases were found in review, and
since RecursionError was not among the exceptions `pickle_guards_state` mapped to
`PackageError`, they escaped compilation as InternalTorchDynamoError. State is
applied after memoization, so all of these now resolve to the pickle already
built.

An empty cell -- a free variable only assigned on a path that did not run -- has
no contents to read, and reading them raised `ValueError` out of the pickler.
Such a cell is now rebuilt empty.

`AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had
the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped
`__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the
shared pieces -- how a code object, cell, module, bound method and function are
rebuilt -- now live in `FunctionPicklerBase` in package.py. Each pickler keeps
its own dispatch and decides what a function carries: the guard pickler prunes
to what a guard reads, the AOT one prunes nothing because the runtime env has to
run the function.

`pickle_guards_state` turned only AttributeError into `PackageError`; anything
else `dump` raised -- TypeError for an unpicklable value, PicklingError, the
RecursionError above -- escaped as InternalTorchDynamoError. Every such failure
means some guarded value cannot be serialized, which is exactly what
`PackageError` is for: a bypass for non-strict callers and an error under
`strict_precompile`, with the cause chained. So `dump` now maps any Exception to
`PackageError`, and a test pins that with a guarded value whose own `__reduce__`
raises.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
```

Each behavior above was also checked by blunting one aspect of the
reconstruction at a time and confirming a named test fails: cells or function
attributes carried as reduce arguments again, an empty cell read unguarded, and
`__module__` not restored each fail exactly one of the new tests.

Authored with an AI assistant.

ghstack-source-id: 8924927
Pull-Request: #195353
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
…at them

One of the enabler fixes the precompile PR at the top of this stack needs. That PR
serializes a Dynamo guard tree per captured variant and rebuilds it at load;
this is what stops the rebuild from failing on ordinary library code.

A serialized guard set cannot be loaded if any guard's source walks through a
function whose qualname does not resolve back to it. `GuardsStatePickler` looks
the function up by `__module__` and `__qualname__` and substitutes a `_Missing`
sentinel when that finds something else. For a function nothing depends on that
is correct. For one a guard is rooted at, evaluating the source against the
sentinel raises while the guard manager is still being built, and the whole load
fails.

Any `functools.wraps` decorator produces the mismatch, since the wrapper copies
the wrapped function's `__module__` and `__qualname__` while living in the
decorator's file. That makes this ordinary rather than exotic: it is why a
transformers model cannot be loaded from a compile package at all today.

The sentinel stays for functions no guard needs. A function in
`guard_tree_values` is pickled by value instead, rebuilt from its code object
the way the `<locals>` branch already did; both branches now share one
reconstruction, so a `<locals>` function also gets the fixes below and is pruned
the same way (it used to carry its defaults and closure verbatim, so one
unpicklable neighbour failed the package). Most of the diff is what that
reconstruction turned out to require, and the reason it is so much is that it
is directly observable: `load_guard_manager` re-runs guard construction against
the deserialized scope, so an EQUALS_MATCH constant is rebaked by reading the
rebuilt function. Any attribute the reconstruction gets wrong does not fail the
load, it produces a guard that never passes again. `__name__` (the old code
passed `__qualname__` there), `__module__` (`FunctionType` derives it from the
globals it is handed, which for the snapshot branch is empty), `__kwdefaults__`,
`__dict__`, and the length and keys of the signature containers are all
load-bearing for that reason. Each of `__name__`, `__module__`, a `__dict__`
attribute, a default's value and the defaults' length, a kwdefault's value and
the kwdefaults' keys, a global's value and the globals' key set has a
capture-driven test that mutates the live function and asserts the loaded guard
rejects it.

Rebuilding drags along whatever the function holds, and carrying all of it would
let an unpicklable neighbour fail a package that never needed it. So the policy
is to carry only what some guard tree node references and to prune the rest to
sentinels -- the inverse of pickling the function wholesale, which is simpler but
regresses the failure mode this PR exists to remove. Pruning is shape-preserving
for the signature (a rebaked guard reads the container's length and keys) but not
for `__dict__`, which holds whatever a decorator happened to stash. The module
scope is snapshotted once per module dict, so N functions from one module cost
one copy of the scope rather than N.

Everything a rebuilt function holds beyond what `FunctionType()` needs -- its
defaults, kwdefaults, attributes and the module scope -- travels as pickle state
rather than as a reduce argument, and so do a cell's contents. pickle memoizes an
object only after saving its reduce arguments, so a value that reaches back to
the function being reduced recurses until RecursionError. That is not a corner
case: `wrapped = deco(base)` at module level puts the wrapper in its own
globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching
decorator stashes `wrapper` in its own `__dict__`. State is applied after
memoization, so all of these resolve to the pickle already built. A cell's
contents are wrapped in a 1-tuple on the way: pickle skips the state step when
the state object is None, and `scale = None` is an ordinary closure variable
that must not come back as an empty cell.

An empty cell -- a free variable only assigned on a path that did not run -- has
no contents to read, and reading them raised `ValueError` out of the pickler.
Such a cell is now rebuilt empty.

`AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had
the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped
`__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the
shared pieces -- how a code object, cell, module, bound method and function are
rebuilt -- now live in `FunctionPicklerBase` in package.py, which both picklers
already depend on for `SerializedCode`. Each pickler keeps its own dispatch and
decides what a function carries: the guard pickler prunes to what a guard reads,
the AOT one prunes nothing because the runtime env has to run the function. The
old pickle targets `_unpickle_nested_function`, `_unpickle_cell` and
`_apply_function_globals` are gone; artifacts are gated on an exact
`torch.__version__` match before any guard bytes are unpickled, so no saved
artifact can reference them.

`pickle_guards_state` turned only AttributeError into `PackageError`; anything
else `dump` raised -- TypeError for an unpicklable value, PicklingError -- escaped
as InternalTorchDynamoError. Every such failure means some guarded value cannot
be serialized, which is exactly what `PackageError` is for: a bypass for
non-strict callers and an error under `strict_precompile`, with the cause
chained. So `dump` now maps any Exception to `PackageError`, except
RecursionError, which means a cycle the reducers did not route through state and
should stay loud. The bypass itself did not work end to end: `bypass_package`
clears the package on the output graph, but convert_frame checked the package
it had been handed and then asserted on the missing guards state. It now checks
the output graph's, and a non-strict caching_precompile test compiles a frame
whose guarded default refuses to pickle and asserts it runs with a bypass and no
cache entry.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
```

Each behavior above was also checked by blunting one aspect of the fix at a
time and confirming a named test fails: cells or function attributes carried as
reduce arguments again, a cell's contents as bare state, an empty cell read
unguarded, `__module__` not restored, and convert_frame checking the package it
was handed.

Authored with an AI assistant.

ghstack-source-id: 0d7df67
Pull-Request: #195353
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
…at them

One of the enabler fixes the precompile PR at the top of this stack needs. That PR
serializes a Dynamo guard tree per captured variant and rebuilds it at load;
this is what stops the rebuild from failing on ordinary library code.

A serialized guard set cannot be loaded if any guard's source walks through a
function whose qualname does not resolve back to it. `GuardsStatePickler` looks
the function up by `__module__` and `__qualname__` and substitutes a `_Missing`
sentinel when that finds something else. For a function nothing depends on that
is correct. For one a guard is rooted at, evaluating the source against the
sentinel raises while the guard manager is still being built, and the whole load
fails.

Any `functools.wraps` decorator produces the mismatch, since the wrapper copies
the wrapped function's `__module__` and `__qualname__` while living in the
decorator's file. That makes this ordinary rather than exotic: it is why a
transformers model cannot be loaded from a compile package at all today.

The sentinel stays for functions no guard needs. A function in
`guard_tree_values` is pickled by value instead, rebuilt from its code object
the way the `<locals>` branch already did; both branches now share one
reconstruction, so a `<locals>` function also gets the fixes below and is pruned
the same way (it used to carry its defaults and closure verbatim, so one
unpicklable neighbour failed the package). Most of the diff is what that
reconstruction turned out to require, and the reason it is so much is that it
is directly observable: `load_guard_manager` re-runs guard construction against
the deserialized scope, so an EQUALS_MATCH constant is rebaked by reading the
rebuilt function. Any attribute the reconstruction gets wrong does not fail the
load, it produces a guard that never passes again. `__name__` (the old code
passed `__qualname__` there), `__module__` (`FunctionType` derives it from the
globals it is handed, which for the snapshot branch is empty), `__kwdefaults__`,
`__dict__`, and the length and keys of the signature containers are all
load-bearing for that reason. Each of `__name__`, `__module__`, a `__dict__`
attribute, a default's value and the defaults' length, a kwdefault's value and
the kwdefaults' keys, a global's value and the globals' key set has a
capture-driven test that mutates the live function and asserts the loaded guard
rejects it.

Rebuilding drags along whatever the function holds, and carrying all of it would
let an unpicklable neighbour fail a package that never needed it. So the policy
is to carry only what some guard tree node references and to prune the rest to
sentinels -- the inverse of pickling the function wholesale, which is simpler but
regresses the failure mode this PR exists to remove. Pruning is shape-preserving
for the signature (a rebaked guard reads the container's length and keys) but not
for `__dict__`, which holds whatever a decorator happened to stash. The module
scope is snapshotted once per module dict, so N functions from one module cost
one copy of the scope rather than N.

Everything a rebuilt function holds beyond what `FunctionType()` needs -- its
defaults, kwdefaults, attributes and the module scope -- travels as pickle state
rather than as a reduce argument, and so do a cell's contents. pickle memoizes an
object only after saving its reduce arguments, so a value that reaches back to
the function being reduced recurses until RecursionError. That is not a corner
case: `wrapped = deco(base)` at module level puts the wrapper in its own
globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching
decorator stashes `wrapper` in its own `__dict__`. State is applied after
memoization, so all of these resolve to the pickle already built. A cell's
contents are wrapped in a 1-tuple on the way: pickle skips the state step when
the state object is None, and `scale = None` is an ordinary closure variable
that must not come back as an empty cell.

An empty cell -- a free variable only assigned on a path that did not run -- has
no contents to read, and reading them raised `ValueError` out of the pickler.
Such a cell is now rebuilt empty.

`AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had
the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped
`__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the
shared pieces -- how a code object, cell, module, bound method and function are
rebuilt -- now live in `FunctionPicklerBase` in package.py, which both picklers
already depend on for `SerializedCode`. Each pickler keeps its own dispatch and
decides what a function carries: the guard pickler prunes to what a guard reads,
the AOT one prunes nothing because the runtime env has to run the function. The
old pickle targets `_unpickle_nested_function`, `_unpickle_cell` and
`_apply_function_globals` are gone; artifacts are gated on an exact
`torch.__version__` match before any guard bytes are unpickled, so no saved
artifact can reference them.

`pickle_guards_state` turned only AttributeError into `PackageError`; anything
else `dump` raised -- TypeError for an unpicklable value, PicklingError -- escaped
as InternalTorchDynamoError. Every such failure means some guarded value cannot
be serialized, which is exactly what `PackageError` is for: a bypass for
non-strict callers and an error under `strict_precompile`, with the cause
chained. So `dump` now maps any Exception to `PackageError`, except
RecursionError, which means a cycle the reducers did not route through state and
should stay loud. The bypass itself did not work end to end: `bypass_package`
clears the package on the output graph, but convert_frame checked the package
it had been handed and then asserted on the missing guards state. It now checks
the output graph's, and a non-strict caching_precompile test compiles a frame
whose guarded default refuses to pickle and asserts it runs with a bypass and no
cache entry.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
```

Each behavior above was also checked by blunting one aspect of the fix at a
time and confirming a named test fails: cells or function attributes carried as
reduce arguments again, a cell's contents as bare state, an empty cell read
unguarded, `__module__` not restored, and convert_frame checking the package it
was handed.

Authored with an AI assistant.

ghstack-source-id: 0d7df67
Pull-Request: #195353
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
…at them

One of the enabler fixes the precompile PR at the top of this stack needs. That PR
serializes a Dynamo guard tree per captured variant and rebuilds it at load;
this is what stops the rebuild from failing on ordinary library code.

A serialized guard set cannot be loaded if any guard's source walks through a
function whose qualname does not resolve back to it. `GuardsStatePickler` looks
the function up by `__module__` and `__qualname__` and substitutes a `_Missing`
sentinel when that finds something else. For a function nothing depends on that
is correct. For one a guard is rooted at, evaluating the source against the
sentinel raises while the guard manager is still being built, and the whole load
fails.

Any `functools.wraps` decorator produces the mismatch, since the wrapper copies
the wrapped function's `__module__` and `__qualname__` while living in the
decorator's file. That makes this ordinary rather than exotic: it is why a
transformers model cannot be loaded from a compile package at all today.

The sentinel stays for a module-level function no guard needs. A function in
`guard_tree_values` is pickled by value instead, rebuilt from its code object
the way the `<locals>` branch already did; both branches now share one
reconstruction, so a `<locals>` function also gets the fixes below and is pruned
the same way (it used to carry its defaults and closure verbatim, so one
unpicklable neighbour failed the package). Most of the diff is what that
reconstruction turned out to require, and the reason it is so much is that it
is directly observable: `load_guard_manager` re-runs guard construction against
the deserialized scope, so an EQUALS_MATCH constant is rebaked by reading the
rebuilt function. Any attribute the reconstruction gets wrong does not fail the
load, it produces a guard that never passes again. `__name__` (the old code
passed `__qualname__` there), `__module__` (`FunctionType` derives it from the
globals it is handed, which for the snapshot branch is empty), `__kwdefaults__`,
`__dict__`, and the length and keys of the signature containers are all
load-bearing for that reason. Each of `__name__`, `__module__`, a `__dict__`
attribute, a default's value and the defaults' length, a kwdefault's value and
the presence of its key, a global's value and the globals' length has a
capture-driven test that mutates the live function and asserts the loaded guard
rejects it; an empty and a None-valued closure cell round-trip through a capture
as well.

Rebuilding drags along whatever the function holds, and carrying all of it would
let an unpicklable neighbour fail a package that never needed it. So the policy
is to carry only what some guard tree node references and to prune the rest to
sentinels -- the inverse of pickling the function wholesale, which is simpler but
regresses the failure mode this PR exists to remove. Pruning is shape-preserving
for the signature (a rebaked guard reads the container's length and keys) but not
for `__dict__`, which holds whatever a decorator happened to stash. Pruned values
share one `_Missing` per reason, so a snapshot of a large module costs one
sentinel rather than thousands, and the module scope is snapshotted once per
module dict, so N functions from one module cost one copy of the scope rather
than N. A rebuilt function whose `__globals__` no guard reads is instead given
`import_module(__module__).__dict__`, which for a `functools.wraps` wrapper is
the wrapped function's module; only a guard that walks `__globals__` forces the
snapshot.

Everything a rebuilt function holds beyond what `FunctionType()` needs -- its
defaults, kwdefaults, attributes and the module scope -- travels as pickle state
rather than as a reduce argument, and so do a cell's contents. pickle memoizes an
object only after saving its reduce arguments, so a value that reaches back to
the function being reduced recurses until RecursionError. That is not a corner
case: `wrapped = deco(base)` at module level puts the wrapper in its own
globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching
decorator stashes `wrapper` in its own `__dict__`. State is applied after
memoization, so all of these resolve to the pickle already built. A cell's
contents are wrapped in a 1-tuple on the way: pickle skips the state step when
the state object is None, and `scale = None` is an ordinary closure variable
that must not come back as an empty cell.

An empty cell -- a free variable only assigned on a path that did not run -- has
no contents to read, and reading them raised `ValueError` out of the pickler.
Such a cell is now rebuilt empty.

`AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had
the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped
`__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the
shared pieces -- how a code object, cell, module, bound method and function are
rebuilt -- now live in `FunctionPicklerBase` in package.py, which both picklers
already depend on for `SerializedCode`. Each pickler keeps its own dispatch and
decides what a function carries: the guard pickler prunes to what a guard reads,
the AOT one prunes nothing because the runtime env has to run the function. The
pickle targets `_unpickle_nested_function` and `_unpickle_cell` are gone and the
AOT `_unpickle_module` is renamed `_unpickle_python_module`. Precompile
artifacts are gated on an exact `torch.__version__` match before any guard bytes
are unpickled, and an `aot_compile` artifact from another version was never
loadable (its version check runs after the outer unpickle, as before), so no
loadable artifact references the old names.

`pickle_guards_state` turned only AttributeError into `PackageError`; anything
else `dump` raised -- TypeError for an unpicklable value, PicklingError -- escaped
as InternalTorchDynamoError. Every such failure means some guarded value cannot
be serialized, which is exactly what `PackageError` is for: a bypass for
non-strict callers and an error under `strict_precompile`, with the cause
chained. So `dump` now maps any Exception to `PackageError`, except
RecursionError, which means a cycle the reducers did not route through state and
should stay loud. The bypass itself did not work end to end: `bypass_package`
clears the package on the output graph, but convert_frame checked the package
it had been handed and then asserted on the missing guards state. It now checks
the output graph's. A bypassed entry also drops the backend ids it already
registered and accepts no new ones, since it is never installed and its backends
would otherwise be serialized for nothing. A non-strict caching_precompile test
compiles a frame whose guarded default refuses to pickle and asserts it runs
with a bypass, saves with no backend, and installs nothing on reload.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
```

Each behavior above was also checked by blunting one aspect of the fix at a
time and confirming a named test fails: cells or function attributes carried as
reduce arguments again, a cell's contents as bare state, an empty cell read
unguarded, `__module__` not restored, convert_frame checking the package it
was handed, and a bypassed entry keeping its backend ids.

Authored with an AI assistant.

ghstack-source-id: f4a0551
Pull-Request: #195353
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
…at them

One of the enabler fixes the precompile PR at the top of this stack needs. That PR
serializes a Dynamo guard tree per captured variant and rebuilds it at load;
this is what stops the rebuild from failing on ordinary library code.

A serialized guard set cannot be loaded if any guard's source walks through a
function whose qualname does not resolve back to it. `GuardsStatePickler` looks
the function up by `__module__` and `__qualname__` and substitutes a `_Missing`
sentinel when that finds something else. For a function nothing depends on that
is correct. For one a guard is rooted at, evaluating the source against the
sentinel raises while the guard manager is still being built, and the whole load
fails.

Any `functools.wraps` decorator produces the mismatch, since the wrapper copies
the wrapped function's `__module__` and `__qualname__` while living in the
decorator's file. That makes this ordinary rather than exotic: it is why a
transformers model cannot be loaded from a compile package at all today.

The sentinel stays for a module-level function no guard needs. A function in
`guard_tree_values` is pickled by value instead, rebuilt from its code object
the way the `<locals>` branch already did; both branches now share one
reconstruction, so a `<locals>` function also gets the fixes below and is pruned
the same way (it used to carry its defaults and closure verbatim, so one
unpicklable neighbour failed the package). Most of the diff is what that
reconstruction turned out to require, and the reason it is so much is that it
is directly observable: `load_guard_manager` re-runs guard construction against
the deserialized scope, so an EQUALS_MATCH constant is rebaked by reading the
rebuilt function. Any attribute the reconstruction gets wrong does not fail the
load, it produces a guard that never passes again. `__name__` (the old code
passed `__qualname__` there), `__module__` (`FunctionType` derives it from the
globals it is handed, which for the snapshot branch is empty), `__kwdefaults__`,
`__dict__`, and the length and keys of the signature containers are all
load-bearing for that reason. Each of `__name__`, `__module__`, a `__dict__`
attribute, a default's value and the defaults' length, a kwdefault's value and
the presence of its key, a global's value and the globals' length has a
capture-driven test that mutates the live function and asserts the loaded guard
rejects it; an empty and a None-valued closure cell round-trip through a capture
as well.

Rebuilding drags along whatever the function holds, and carrying all of it would
let an unpicklable neighbour fail a package that never needed it. So the policy
is to carry only what some guard tree node references and to prune the rest to
sentinels -- the inverse of pickling the function wholesale, which is simpler but
regresses the failure mode this PR exists to remove. Pruning is shape-preserving
for the signature (a rebaked guard reads the container's length and keys) but not
for `__dict__`, which holds whatever a decorator happened to stash. Pruned values
share one `_Missing` per reason, so a snapshot of a large module costs one
sentinel rather than thousands, and the module scope is snapshotted once per
module dict, so N functions from one module cost one copy of the scope rather
than N. A rebuilt function whose `__globals__` no guard reads is instead given
`import_module(__module__).__dict__`, which for a `functools.wraps` wrapper is
the wrapped function's module; only a guard that walks `__globals__` forces the
snapshot.

Everything a rebuilt function holds beyond what `FunctionType()` needs -- its
defaults, kwdefaults, attributes and the module scope -- travels as pickle state
rather than as a reduce argument, and so do a cell's contents. pickle memoizes an
object only after saving its reduce arguments, so a value that reaches back to
the function being reduced recurses until RecursionError. That is not a corner
case: `wrapped = deco(base)` at module level puts the wrapper in its own
globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching
decorator stashes `wrapper` in its own `__dict__`. State is applied after
memoization, so all of these resolve to the pickle already built. A cell's
contents are wrapped in a 1-tuple on the way: pickle skips the state step when
the state object is None, and `scale = None` is an ordinary closure variable
that must not come back as an empty cell.

An empty cell -- a free variable only assigned on a path that did not run -- has
no contents to read, and reading them raised `ValueError` out of the pickler.
Such a cell is now rebuilt empty.

`AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had
the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped
`__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the
shared pieces -- how a code object, cell, module, bound method and function are
rebuilt -- now live in `FunctionPicklerBase` in package.py, which both picklers
already depend on for `SerializedCode`. Each pickler keeps its own dispatch and
decides what a function carries: the guard pickler prunes to what a guard reads,
the AOT one prunes nothing because the runtime env has to run the function. The
pickle targets `_unpickle_nested_function` and `_unpickle_cell` are gone and the
AOT `_unpickle_module` is renamed `_unpickle_python_module`. Precompile
artifacts are gated on an exact `torch.__version__` match before any guard bytes
are unpickled, and an `aot_compile` artifact from another version was never
loadable (its version check runs after the outer unpickle, as before), so no
loadable artifact references the old names.

`pickle_guards_state` turned only AttributeError into `PackageError`; anything
else `dump` raised -- TypeError for an unpicklable value, PicklingError -- escaped
as InternalTorchDynamoError. Every such failure means some guarded value cannot
be serialized, which is exactly what `PackageError` is for: a bypass for
non-strict callers and an error under `strict_precompile`, with the cause
chained. So `dump` now maps any Exception to `PackageError`, except
RecursionError, which means a cycle the reducers did not route through state and
should stay loud. The bypass itself did not work end to end: `bypass_package`
clears the package on the output graph, but convert_frame checked the package
it had been handed and then asserted on the missing guards state. It now checks
the output graph's. A bypassed entry also drops the backend ids it already
registered and accepts no new ones, since it is never installed and its backends
would otherwise be serialized for nothing. A non-strict caching_precompile test
compiles a frame whose guarded default refuses to pickle and asserts it runs
with a bypass, saves with no backend, and installs nothing on reload.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
```

Each behavior above was also checked by blunting one aspect of the fix at a
time and confirming a named test fails: cells or function attributes carried as
reduce arguments again, a cell's contents as bare state, an empty cell read
unguarded, `__module__` not restored, convert_frame checking the package it
was handed, and a bypassed entry keeping its backend ids.

Authored with an AI assistant.

ghstack-source-id: f4a0551
Pull-Request: #195353
@bobrenjc93 bobrenjc93 added the topic: not user facing topic category label Sep 2, 2026
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 2, 2026
…at them

One of the enabler fixes the precompile PR at the top of this stack needs. That PR
serializes a Dynamo guard tree per captured variant and rebuilds it at load;
this is what stops the rebuild from failing on ordinary library code.

A serialized guard set cannot be loaded if any guard's source walks through a
function whose qualname does not resolve back to it. `GuardsStatePickler` looks
the function up by `__module__` and `__qualname__` and substitutes a `_Missing`
sentinel when that finds something else. For a function nothing depends on that
is correct. For one a guard is rooted at, evaluating the source against the
sentinel raises while the guard manager is still being built, and the whole load
fails.

Any `functools.wraps` decorator produces the mismatch, since the wrapper copies
the wrapped function's `__module__` and `__qualname__` while living in the
decorator's file. That makes this ordinary rather than exotic: it is why a
transformers model cannot be loaded from a compile package at all today.

The sentinel stays for a module-level function no guard needs. A function in
`guard_tree_values` is pickled by value instead, rebuilt from its code object
the way the `<locals>` branch already did; both branches now share one
reconstruction, so a `<locals>` function also gets the fixes below and is pruned
the same way (it used to carry its defaults and closure verbatim, so one
unpicklable neighbour failed the package). Most of the diff is what that
reconstruction turned out to require, and the reason it is so much is that it
is directly observable: `load_guard_manager` re-runs guard construction against
the deserialized scope, so an EQUALS_MATCH constant is rebaked by reading the
rebuilt function. Any attribute the reconstruction gets wrong does not fail the
load, it produces a guard that never passes again. `__name__` (the old code
passed `__qualname__` there), `__module__` (`FunctionType` derives it from the
globals it is handed, which for the snapshot branch is empty), `__kwdefaults__`,
`__dict__`, and the length and keys of the signature containers are all
load-bearing for that reason. Each of `__name__`, `__module__`, a `__dict__`
attribute, a default's value and the defaults' length, a kwdefault's value and
the presence of its key, a global's value and the globals' length has a
capture-driven test that mutates the live function and asserts the loaded guard
rejects it; an empty and a None-valued closure cell round-trip through a capture
as well.

Rebuilding drags along whatever the function holds, and carrying all of it would
let an unpicklable neighbour fail a package that never needed it. So the policy
is to carry only what some guard tree node references and to prune the rest to
sentinels -- the inverse of pickling the function wholesale, which is simpler but
regresses the failure mode this PR exists to remove. Pruning is shape-preserving
for the signature (a rebaked guard reads the container's length and keys) but not
for `__dict__`, which holds whatever a decorator happened to stash. Pruned values
share one `_Missing` per reason, so a snapshot of a large module costs one
sentinel rather than thousands, and the module scope is snapshotted once per
module dict, so N functions from one module cost one copy of the scope rather
than N. A rebuilt function whose `__globals__` no guard reads is instead given
`import_module(__module__).__dict__`, which for a `functools.wraps` wrapper is
the wrapped function's module; only a guard that walks `__globals__` forces the
snapshot.

Everything a rebuilt function holds beyond what `FunctionType()` needs -- its
defaults, kwdefaults, attributes and the module scope -- travels as pickle state
rather than as a reduce argument, and so do a cell's contents. pickle memoizes an
object only after saving its reduce arguments, so a value that reaches back to
the function being reduced recurses until RecursionError. That is not a corner
case: `wrapped = deco(base)` at module level puts the wrapper in its own
globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching
decorator stashes `wrapper` in its own `__dict__`. State is applied after
memoization, so all of these resolve to the pickle already built. A cell's
contents are wrapped in a 1-tuple on the way: pickle skips the state step when
the state object is None, and `scale = None` is an ordinary closure variable
that must not come back as an empty cell.

An empty cell -- a free variable only assigned on a path that did not run -- has
no contents to read, and reading them raised `ValueError` out of the pickler.
Such a cell is now rebuilt empty.

`AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had
the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped
`__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the
shared pieces -- how a code object, cell, module, bound method and function are
rebuilt -- now live in `FunctionPicklerBase` in package.py, which both picklers
already depend on for `SerializedCode`. Each pickler keeps its own dispatch and
decides what a function carries: the guard pickler prunes to what a guard reads,
the AOT one prunes nothing because the runtime env has to run the function. The
pickle targets `_unpickle_nested_function` and `_unpickle_cell` are gone and the
AOT `_unpickle_module` is renamed `_unpickle_python_module`. Precompile
artifacts are gated on an exact `torch.__version__` match before any guard bytes
are unpickled, and an `aot_compile` artifact from another version was never
loadable (its version check runs after the outer unpickle, as before), so no
loadable artifact references the old names; such an artifact whose runtime env
holds a cell or nested function now fails inside that unpickle with an
AttributeError on the old name rather than with the version error. Carrying a
nested function's `__dict__` also means a helper holding an unpicklable
attribute, a lock say, now fails `aot_compile` at save where it used to
serialize with the attribute silently dropped.

`pickle_guards_state` turned only AttributeError into `PackageError`; anything
else `dump` raised -- TypeError for an unpicklable value, PicklingError -- escaped
as InternalTorchDynamoError. Every such failure means some guarded value cannot
be serialized, which is exactly what `PackageError` is for: a bypass for
non-strict callers and an error under `strict_precompile`, with the cause
chained. So `dump` now maps any Exception to `PackageError`, except
RecursionError, which means a cycle the reducers did not route through state and
should stay loud. The bypass itself did not work end to end: `bypass_package`
clears the package on the output graph, but convert_frame checked the package
it had been handed and then asserted on the missing guards state. It now checks
the output graph's. A bypassed entry also drops the backend ids and guarded
codes it already registered and accepts no new backends, since it is never
installed and they would otherwise be serialized for nothing. A non-strict
caching_precompile test compiles a frame whose guarded default refuses to
pickle and asserts it runs with a bypass, saves an entry with no backend, and
installs nothing when the cache is reloaded.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_aot_compile.py
python test/dynamo/test_package.py
```

Each behavior above was also checked by blunting one aspect of the fix at a
time and confirming a named test fails: cells or function attributes carried as
reduce arguments again, a cell's contents as bare state, an empty cell read
unguarded, `__module__` not restored, convert_frame checking the package it
was handed, and a bypassed entry keeping its backend ids.

Authored with an AI assistant.

ghstack-source-id: f14e3ee
Pull-Request: #195353
Comment thread torch/_dynamo/guards.py Resolved
Comment thread torch/_dynamo/guards.py Resolved
Comment thread torch/_dynamo/package.py Resolved
Comment thread torch/_dynamo/package.py Resolved
Comment thread torch/_dynamo/package.py Resolved
Comment thread test/dynamo/test_guard_serialization.py Resolved
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

PR Review: #195353

  • Scope the delta since the last reviewed head (f2a60b3d)
  • Read the source changes
  • Verify the fixes claimed in the new review replies
  • Audit for fresh issues
  • Fact-check and post

View job run | Branch: gh/bobrenjc93/1093/head

[ghstack-poisoned]
Comment thread torch/_dynamo/guards.py Resolved
Comment thread torch/_dynamo/guards.py Resolved
Comment thread test/dynamo/test_guard_serialization.py Resolved
Comment thread torch/_dynamo/guards.py Resolved
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 51m 48s —— View job


PR Review: #195353

Re-review at head 1131d9ac: the guard_tree_verbatim mechanism is the right fix for the blocker I raised last round — I traced it and it makes the verbatim/prune decision on the actual question ("does a guard bake this container by value") rather than inferring it from child edges. I have no correctness objection. Two things to flag: the merge commit introduces a third_party/kineto submodule bump that neither parent nor origin/main carries, and the docstring/FAQ justify the new mechanism partly through a dict path that cannot exist (dict is not in EQUALS_MATCH's ok_types).

Full review details
  • Scope the delta since the last reviewed head (f2a60b3d)
  • Read the source changes
  • Verify the fixes claimed in the new review replies
  • Audit for fresh issues
  • Fact-check and post

What changed since f2a60b3d

 test/dynamo/test_guard_serialization.py | 142 +++++++++++-------
 torch/_dynamo/convert_frame.py          |  ... (base update)
 torch/_dynamo/guards.py                 | 177 +++++++++-------------
 torch/_dynamo/output_graph.py           |  ...
 torch/_dynamo/package.py                |  67 +++++----

Resolved

The EQUALS_MATCH blocker (BR/BE) — fixed, and fixed on the right predicate. GuardBuilder.EQUALS_MATCH now records id(val) in guard_tree_verbatim (guards.py:2901-2902, save-path only), and _keep_container_verbatim (:4386-4388) consults that before the child edges. I traced the whole chain and it holds: the two cases are now genuinely disjoint, the ids are strongly referenced for the pickler's lifetime (src_get_value_cache at :1353 plus guard_tree_values, so no id-reuse hazard on a set that holds only ints), and the double build_guards (:4905 / :4928) cannot poison it since the first pass runs with save_guards=False. GuardedDefaultsTupleModule.forward now also calls self.fn(x, b=5.0) (test_guard_serialization.py:429), so test_nested_function_preserves_a_guarded_defaults_tuple genuinely fails without the fix: the DefaultsSource binding of a records {id(2.0)} on the tuple while 1.0 is registered by nothing, so the pre-fix code reloaded (2.0, _Missing). Zero added LOC for the regression pin — good call.

The pre-dump bound-method seeding loop — deleted, correctly. The seed now lives at the source site (guards.py:1724-1727), which runs during guard-tree construction and therefore cannot lose to pickle traversal or to the frozen missing_values. Your measurement (zero functions seeded across the suite) matches what I read; the in-reducer write at :4665-4670 is annotated as the belt-and-suspenders no-op.

The two full-compile container-edge tests — fixed. _assert_reloads_and_still_matches (:1605-1618) captures, saves, resets, reloads through the transparent cache and serves under fail_on_recompile, so a rebaked guard that no longer matches now fails the test. That closes the "cannot distinguish serialized-fine from serialized-but-never-matches" gap.

The __doc__ prune — fixed. type(doc) is not str keeps a str or None verbatim (:4486-4489), so a docstring-less function comes back with None rather than a truthy _Missing. Using type() is str rather than isinstance is the right choice here, since a <locals> str subclass would not pickle.

_cached_backends pop — verified safe. I checked whether popping from the package-global cache when one entry is bypassed can strand a backend another live entry needs. It cannot: make_compiled_fn_name → unique_id(COMPILED_FN_PREFIX, with_uuid=True) (bytecode_transformation.py:1983, :2000) draws from a global monotonic counter plus a UUID, _codes is a 1:1 code→entry map (package.py:884), and resume functions get their own entries with their own empty backend_ids. The .pop(..., None) is also KeyError-safe. Moving those two lines down from #195913 is correct given add_backend_id runs in call_user_compiler, before build_guards can bypass.

output_graph.py:2591 — the uninterpolated %s is fixed. PackageError(f"Detected a package bypass: {reason}") now produces a readable str(e), which matters because that is the one PackageError the new type(e).__name__ prefix at guards.py:4812 could not help.

_instance_dict and the slotted-proxy reduce — both land. The mapping edge (guards.py:1759-1764) and _reduce_bound_method's receiver probe (package.py:~310) now share one non-executing read, and inspect.getattr_static replaced the hasattr for the slots clause. test_bound_method_on_a_slotted_getattr_proxy_is_not_probed and test_attribute_guard_on_a_slotted_receiver_runs_no_user_getattr pin both halves. See C for the one residual.

Infrastructure

BT. The merge commit introduces a third_party/kineto bump that neither parent nor origin/main carries (third_party/kineto)

$ git rev-parse de4e0e4f:third_party/kineto   # prior PR head
84e5ca9e8dc1a27abd174f1305bd8e0e400239ea
$ git rev-parse e990a8dc:third_party/kineto   # base update
84e5ca9e8dc1a27abd174f1305bd8e0e400239ea
$ git rev-parse origin/main:third_party/kineto  # tip 0c26744a, 2026-09-09 18:57
84e5ca9e8dc1a27abd174f1305bd8e0e400239ea
$ git rev-parse HEAD:third_party/kineto        # 1131d9ac, the merge
8b682abf0e4dd2bec66a92397a097b1a14cd95e0

So 8b682abf appears in neither parent of the merge and is not what main is on — the merge commit itself is where it enters. git log --all --oneline -- third_party/kineto finds no commit in this checkout that bumps to it. It shows in this PR's changed-files list, so it is currently part of what the PR proposes to merge, in a PR whose subject is guard serialization.

Worth noting the adjacent file is not the reason: git diff e990a8dc HEAD -- torch/csrc/profiler/kineto_metadata.cpp is empty (the typed-metadata change at origin/main's tip came in via the base update and is already on the base), so nothing in this PR needs the newer kineto. Almost certainly a merge-resolution artifact rather than intent — same shape as the cudnn_frontend bump that rode along and was reverted several rounds ago — but it needs reverting to 84e5ca9e before merge, since a submodule pointer that no branch carries is not something a reviewer can evaluate. Fix this →

Code Quality

BU. The verbatim mechanism's dict half cannot fire, but the docstring and the FAQ justify it as though it can (torch/_dynamo/guards.py:4370-4392)

The docstring says a plain dict/tuple "is verbatim when a guard bakes it whole (guard_tree_verbatim: EQUALS_MATCH...)", and the FAQ says "CONSTANT_MATCH delegates there for tuples/dicts". For a tuple that is right. For a dict it is not reachable:

  • dict is absent from EQUALS_MATCH's ok_types (:2922-2937) and from common_constant_types (utils.py:2968-2987), so a dict reaching EQUALS_MATCH hits raise AssertionError(f"Unexpected type {type(val)}") at :2968.
  • CONSTANT_MATCH (:3019-3028) delegates a dict to EQUALS_MATCH, i.e. into that assertion — so it cannot be a live path either.
  • ConstantVariable.create cannot hold a dict (constant.py, is_base_literal requires type(obj) in common_constant_types), so a dict never becomes a constant to be baked in the first place.

So guard_tree_verbatim can only ever contain a tuple id among containers, and type(container) is dict always falls through to the child-edge branch. That matters for the __kwdefaults__ half of GuardedDefaultsTupleModule: self.fn.__kwdefaults__ == {"c": 3.0} is protected not by the verbatim set but by the per-key decomposition, which registers each compared value so _prune returns it verbatim. The reasoning is sound; the stated mechanism is the wrong one, and a future reader adding dict to ok_types would be building on a branch nobody has exercised. One clause naming the real reason ("a dict is never value-baked — EQUALS_MATCH excludes it; a dict comparison decomposes into per-key guards that register their values") makes the whole docstring verifiable.

BV. _instance_dict's claim covers __getattr__ but not a __dict__ data descriptor (torch/_dynamo/package.py:114-121)

"obj.dict read through the plain slot, so a user __getattr__ on a __slots__ receiver never runs"

object.__getattribute__ does not consult __getattr__, which is the fix — but it does resolve and invoke type-level data descriptors, so a class defining __dict__ as a property (or any custom getset) still runs user code here, and a non-AttributeError raised there still escapes guard creation as an InternalTorchDynamoError, outside the pickle_guards_state bypass. That is the same failure class the helper was written to close, reached through a descriptor instead of __getattr__.

Exotic, and I would not ask for code — but the helper is now shared by three call sites (this file's bound-method probe, the guards mapping edge at :1760, and #195912's whole-object pruner per your reply), so the scope of its guarantee is load-bearing across the stack. Say "no __getattr__ runs" rather than "no user code runs", and note the except AttributeError is the only failure it absorbs.

BW. The BUILTIN_MATCH change is an unrelated drive-by with no stated motivation (torch/_dynamo/guards.py:3152-3157)

source = guard.originating_source
if isinstance(source, DictGetItemSource) and isinstance(source.index, str):

I chased what the new isinstance(source.index, str) guard buys. used_builtin_vars is declared OrderedSet[str] (:4854) and consumed at :5147 as if k in self.used_builtin_vars over global_scope[builtins_dict_name].items() — builtins keys are always strings, so a non-str index that used to be added silently never matched anything. DictGetItemSource.index can be a ConstDictKeySource or any literal (source.py), but the only installer of BUILTIN_MATCH I found builds DictGetItemSource(builtins_source, argval) from co_names (symbolic_convert.py:2571), which is always a str. So this is defensive hardening for a shape that is at most a harmless no-op, not a fix for a crash or an incorrectness.

That is fine on its own merits, but it is in a commit whose stated scope is fqn-mismatch function reconstruction, it has no test, and the PR is one line under the size gate. Either add a clause saying what it prevents (a non-str index polluting a set[str]) or move it out — as written the next reader cannot tell whether it was load-bearing for something in this PR.

Testing

BX. test_a_whole_tuple_guard_keeps_defaults_verbatim does not model a whole-tuple guard (test/dynamo/test_guard_serialization.py:1066-1080)

The test's name and its comment ("A __defaults__ tuple under a whole-tuple guard") describe the guard_tree_verbatim mechanism, but the test constructs GuardsStatePickler(gtv, {}, {}, buf) with no guard_tree_verbatim and no guard_tree_children — so it takes the absent-edge branch at :4392-4397, not the verbatim branch at :4386-4388. grep -n "guard_tree_verbatim" test/ returns nothing: the branch that fixes the blocker has no unit test, and the only coverage is test_nested_function_preserves_a_guarded_defaults_tuple end to end.

Both halves are worth pinning separately, because they fail differently: the child-edge branch protects against a coincidentally _keep element forcing a prune, while the verbatim branch protects against a legitimately recorded edge forcing one. Passing guard_tree_verbatim={id(d)} and guard_tree_children={id(d): {id(d[0])}} to the existing fixture is a two-line addition that would fail without :4386-4388 — and it makes the current test's name true.

Unchanged coverage gaps, all acknowledged in the FAQ:

  • __type_params__ has no coverage on the guard side. guards.py:4477-4483 and package.py:~247 never run with a non-None value, and both _keep_container_verbatim branches on that slot are untested. Tracked as 3.14-gated, though the branch is reachable from 3.12.
  • The bound-method seeding loop-only shape (a raw function as a separate unguarded pytree leaf) still has no test; with the pre-dump loop deleted, the source-site seed at :1724-1727 is the single mechanism, so a test there would be cheaper than before.
  • test_attribute_guard_on_a_slotted_receiver_runs_no_user_getattr pins that no user code runs, but on a __slots__ receiver _instance_dict returns None, so the mapping edge is never recorded — the test does not exercise the edge itself, only the read. That matches its name; noting it so it is not miscounted as edge coverage.

CI

10 runs, 6 green (both Lint, BC Lint, TSan, docs-build, ghstack mergeability), 4 pending (pull, trunk, inductor, torchtitan-test), 0 failures. pr-sanity-checks passes at 1999 LOC (1926 + 73) — one line under the 2000 gate, so any further test addition here needs offsetting; keep_defaults_element (:474-481) is still byte-identical to keep_default_value (:398-405), which is ~8 lines. No test shard has reported yet, so neither the rewritten reload tests nor the two new slotted-receiver tests are confirmed in CI.

Recommendation

Approve with nits. The guard_tree_verbatim fix resolves my last blocking finding on the right predicate, with a zero-cost regression pin, and the four other fixes this round all verified clean. The one thing that must be dealt with before merge is BT: the merge commit carries a third_party/kineto pointer that neither parent nor main has, which is not something this PR should be proposing. BU and BV are two comment claims that overstate what the code does — both one clause, and BU matters because it describes a branch nobody can reach as the reason the mechanism is safe. BW is an unexplained unrelated change, BX is a two-line test that would make the new branch's name true. Carried-forward test debt (__type_params__, the seeding loop-only shape) remains tracked in the FAQ with reasoning I find defensible.

Verification note: Python execution and a built torch are unavailable here (3.12.3 only). BT rests on git rev-parse against both merge parents and origin/main. BU was independently verified against guards.py:2922-2968, :3019-3028, utils.py:2968-2987 and constant.py. The _cached_backends and BUILTIN_MATCH conclusions came from independent source reads of bytecode_transformation.py:1983/:2000, package.py:884/:1089-1099, and guards.py:4854/:5147. Nothing was reproduced.

| Branch: `gh/bobrenjc93/1093/head`

[ghstack-poisoned]
Comment thread torch/_dynamo/guards.py Resolved
Comment thread test/dynamo/test_package.py Resolved
Comment thread torch/_dynamo/guards.py Resolved
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

PR Review: #195353

  • Scope the delta since the last reviewed head (1131d9ac)
  • Read the source changes
  • Verify the fixes claimed in the new review replies
  • Re-check the third_party/kineto submodule pointer (BT)
  • Audit for fresh issues + fact-check
  • Post review

View job run | Branch: gh/bobrenjc93/1093/head

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude please re-review: round-39 fixes are in (all inline threads addressed; FAQ updated in the description).

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 6m 43s —— View job


PR Review: #195353

Re-review at head 42b8dae5: BT is fixed — the third_party/kineto pointer is back to 84e5ca9e, matching both merge parents and origin/main, and the PR diff is 6 dynamo files again. BU, BW and BX are all resolved, and BW was my error: the BUILTIN_MATCH change has zero hunks in the PR diff, so it came from the base as the FAQ says. I have no correctness objection. One new nit: the __builtins__ hardening inserts the key unconditionally, which can lengthen a snapshot relative to the live dict.

Full review details
  • Scope the delta since the last reviewed head (1131d9ac)
  • Re-check the third_party/kineto submodule pointer (BT)
  • Verify the fixes claimed in the round-39 inline replies (BU, BV, BW, BX)
  • Audit for fresh issues + fact-check
  • Post review

What changed since 1131d9ac

 test/dynamo/test_guard_serialization.py |  83 ++++++++++-------
 test/dynamo/test_package.py             |   2 +
 torch/_dynamo/guards.py                 |  40 ++++-----
 torch/_dynamo/package.py                | 101 ++++++++++----------

Resolved

BT (the stray third_party/kineto bump) — fixed.

1131d9ac  8b682abf0e4dd2bec66a92397a097b1a14cd95e0   <- prior head
37e16d46  84e5ca9e8dc1a27abd174f1305bd8e0e400239ea   <- base update (parent)
HEAD      84e5ca9e8dc1a27abd174f1305bd8e0e400239ea
main      84e5ca9e8dc1a27abd174f1305bd8e0e400239ea

git diff origin/gh/bobrenjc93/1093/base...HEAD --stat is now exactly the 6 dynamo files, no submodule entry. Confirmed.

BW — my finding was wrong, and I withdraw it. git diff origin/gh/bobrenjc93/1093/base...HEAD -- torch/_dynamo/guards.py | grep -c used_builtin_vars returns 0, so isinstance(source.index, str) is on the base, not introduced here. The FAQ's diagnosis is right: I was comparing against a stale base after the base update landed. Nothing for you to do.

BU (the docstring justified the verbatim rule through a dict path that cannot fire) — fixed correctly. _keep_container_verbatim's docstring (guards.py:4370-4381) no longer claims a dict is value-baked, and the FAQ now states the real mechanism: CONSTANT_MATCH delegates to EQUALS_MATCH for tuples, while a dict is never value-baked and its comparison decomposes into per-key guards whose values register in guard_tree_values. I re-verified the delegation at :3017-3026 — bool/None/CodeType split off first, everything else including a tuple goes to EQUALS_MATCH, and dict is absent from ok_types so it cannot arrive there. The docstring is now checkable end to end.

BX (the verbatim test exercised the absent-edge branch, not the record) — fixed. test_a_whole_tuple_guard_keeps_defaults_verbatim (test_guard_serialization.py:1065-1083) now passes guard_tree_children={id(d): {id(d[1])}} and guard_tree_verbatim={id(d): d}, so the child edge alone would prune the sibling and only the verbatim record keeps it whole. That means the test fails without :4387-4388 — which is what the name promised and what was missing. The sibling test_an_element_guarded_through_its_container_still_prunes_siblings (:1085-1101) is the control for the other branch.

guard_tree_verbatim is now dict[int, Any] (:1388, :2900), so the ids it records are pinned by the same structure that holds them. Your measurement (all recorded ids resolve to live identical objects via src_get_value_cache) matches what I read, so this was latent rather than live — but pinning directly removes the reliance on that invariant, at zero cost. Good.

_fqn_resolves lifted to the base class (package.py:257-266) — traced and correct. The "<locals>" in fn.__qualname__ early-out is redundant at the guard call site (guards.py:4649 already dispatched on it) but makes the helper self-contained for the AOT subclass, which is the point of putting it on the base. A non-str __module__ and a module absent from sys.modules both fall to False cleanly (sys.modules.get → None → getattr(None, ..., None) → None is not fn).

The scope split in _unpickle_fn_from_module (package.py:186-213, :347-350) is the right fix for the functools.wraps case: fn.__module__ still drives the rebuilt function's __module__ (so a guard rooted there rebakes the wrappee's value, matching live), while fn.__globals__["__name__"] is what gets imported for the scope. A function whose __module__ is None now still gets a scope, which the previous form could not express.

_reduce_bound_method's MRO-first restructure (package.py:297-329) — traced all four receiver kinds. An instance-dict entry short-circuits to the explicit reduce; getattr_static(cls, name) is func proves the name is class-served and returns None (pickle's default getattr); any other name on an instance takes the explicit reduce without probing; only a type receiver reaches the getattr probe, and for a classmethod that resolves back through __func__ correctly. test_bound_method_on_an_instance_served_name_is_not_probed (:1339-1351) covers all three instance kinds in one subTest loop and asserts PropertyProxy.calls == 0, which is the assertion that pins "never probed" rather than merely "round-trips". That is the strongest form of this test so far.

The _cached_backends pop test (test_package.py:139-142) now registers a backend id under the code context before bypassing and asserts cached_backends == {}, so the pop loop iterates at least once. Previously it ran zero times.

keep_defaults_element deduped — DecoratedDefaultsElementForwardModule now decorates with the existing keep_default_value, removing the byte-identical fixture I'd flagged for several rounds.

Code Quality

BY. snapshot["__builtins__"] = builtins inserts the key unconditionally, so a snapshot can be one entry longer than the dict it mirrors (torch/_dynamo/guards.py:4405-4407)

The hardening itself is right — a function the rebuilt one creates at call time resolves builtins through __globals__, and a sentinel there would break it. But the assignment is unconditional rather than a replacement, so if f_globals has no __builtins__ the snapshot gains a key the live dict does not have.

That matters because __globals__ is length- and keys-guardable, and this file already tests it: keep_globals_length (test_guard_serialization.py:163-166) reads len(func.__globals__), which installs SEQUENCE_LENGTH derived from DICT_KEYS_MATCH (test_fqn_mismatched_function_rejects_a_new_global, :1455-1468). For a real module dict the key is always present — CPython inserts it during module execution — so the existing test is unaffected and both sides agree. The divergent shape is a function built against a dict that never went through exec/module init (types.FunctionType(code, {}), or a <locals> function whose scope was hand-assembled), whose __globals__ a guard both keeps and reads by length: the snapshot rebakes len + 1 and the guard fails forever, silently.

I could not construct a reachable instance — _globals_snapshot only runs when _keep(obj.__globals__), and every path I traced that registers __globals__ roots it at a genuine module dict. So this is a latent narrowing, not a live defect. Gating it (if "__builtins__" in f_globals:) keeps the hardening and removes the shape entirely, for one line. Worth noting the same guard makes the intent clearer too: the point is "do not sentinel the builtins that were there", not "add builtins". Fix this →

BZ. _instance_dict's docstring claims more than the read guarantees (torch/_dynamo/package.py:114-121)

"obj.dict read through the plain slot, so a user __getattr__ on a __slots__ receiver never runs"

Accurate as written for __getattr__, and the FAQ now records the residual explicitly ("a type-level __dict__ data descriptor is still invoked, as it is by pickle itself"). The remaining gap is only that the docstring doesn't say it: object.__getattribute__ skips __getattr__ but still resolves and invokes type-level data descriptors, so a class exposing __dict__ as a property runs user code here, and a non-AttributeError raised there escapes as an InternalTorchDynamoError outside the pickle_guards_state bypass.

I'm not asking for code — the FAQ's "as pickle itself does" framing is the right disposition, and the helper is now shared by three call sites across the stack (the bound-method receiver probe, the guards mapping edge at :1760, and #195912's whole-object pruner), so the scope of its guarantee is what future callers will read. Half a clause naming the descriptor case, and that the except AttributeError is the only failure it absorbs.

Cosmetic: a line-wrap artifact in the reworded FunctionPicklerBase docstring (package.py:127-131). The edit left "...is rebuilt on this base next. Both rebuild the same kinds of objects" broken mid-clause with a short trailing line, unlike the rest of the paragraph. spin fixlint won't catch it since it's inside a string.

Testing

The delta's own changes are covered — BX's test now fails without the mechanism it names, and the merged test_bound_method_on_an_instance_served_name_is_not_probed covers three receiver kinds plus the never-probed assertion in fewer lines than the two tests it replaces. Remaining gaps are unchanged and all acknowledged in the FAQ:

  • __type_params__ has no guard-side coverage. guards.py:4478-4483 and package.py:252-253 never run with a non-None value, and both _keep_container_verbatim branches on that slot are untested. Tracked as 3.14-gated, though the branch is reachable from 3.12.
  • The bound-method seeding loop-only shape (a raw function as a separate unguarded pytree leaf) has no test. With the pre-dump loop now deleted, the source-site seed at guards.py:1724-1727 is the single load-bearing mechanism, so a test there would be cheaper than when there were three sites.
  • No test exercises the new __builtins__ snapshot entry — nothing asserts the reloaded __globals__["__builtins__"] is the module rather than a sentinel, so a regression to pruning it is invisible. One assertIs on the existing globals-snapshot test would cover it and would also have caught BY.
  • The 3.14-gated _read_raw_annotations FORWARDREF branch cannot be exercised here (this environment has 3.12.3 and no built torch), so confirm CI's 3.14 dynamo_wrapped shards specifically rather than treating overall-green as confirmation.

CI

15 runs: 3 green (Lint, BC Lint, ghstack mergeability), 7 pending (pull, trunk, inductor, TSan, docs-build, torchtitan-test, a second Lint), 5 cancelled by the newer push, 0 failures. pr-sanity-checks passes — 1917 + 74 = 1991 LOC, 9 under the gate. That margin is thin enough that any further test addition here needs offsetting; the keep_defaults_element dedup this round is what bought it, so the easy win is spent.

No test shard has reported yet, so neither the reworked pickler-level tests nor the test_package.py bypass assertion is confirmed in CI. pull is the one to watch.

Recommendation

Approve. Everything I flagged last round is resolved, including one finding (BW) that was mine to withdraw — the BUILTIN_MATCH line is genuinely on the base and the FAQ's stale-base diagnosis is correct. The guard_tree_verbatim dict, the scope/__module__ split, the MRO-first bound-method reducer and the two test fixes all verified clean under tracing. BY is a one-line gate on a latent shape I could not make reachable but which the file's own globals-length guard makes theoretically live; BZ and the docstring wrap are comment polish. The remaining test debt (__type_params__, the seeding loop-only shape) is tracked in the FAQ with reasoning I find defensible, and none of it is a correctness objection.

Verification note: Python execution and a built torch are unavailable in this environment (3.12.3 only). This pass rests on git rev-parse against both merge parents and origin/main for BT; git diff origin/gh/bobrenjc93/1093/base...HEAD -- torch/_dynamo/guards.py for BW; and reading guards.py:1380-1395/:1740-1770/:2890-2905/:3017-3026/:4200-4230/:4340-4500/:4640-4660/:4770, package.py:110-362/:1050-1070, and the two test files. Nothing was reproduced.

| Branch: `gh/bobrenjc93/1093/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude please re-review: round-40 fixes are in (every finding from the last review is fixed or answered in the description's FAQ).

@claude

claude Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 46m 22s —— View job


PR Review: #195353

Re-review at head be43fcc9: both round-40 changes land — the __builtins__ insert is now gated on the key's presence (BY), and _instance_dict's docstring now names the type-level-__dict__-descriptor residual (BZ), which is exactly the scope correction I asked for. I have no correctness objection. Two things worth a look: the __builtins__ substitution is still type-infaithful (an imported module's __builtins__ is builtins.__dict__, a dict, not the module) and the assertion added this round pins that; and the bound-method test's new unguarded leaf is dropped by local_scope pruning, so it does not exercise the shape the description says it does.

Full review details
  • Scope the delta since the last reviewed head (42b8dae5)
  • Read the source changes in the 6 PR files
  • Verify the round-40 fixes (BY, BZ, docstring wrap)
  • Audit for fresh issues + fact-check
  • Post review

What changed since 42b8dae5

 test/dynamo/test_guard_serialization.py | 12 +++++++-----
 torch/_dynamo/guards.py                 |  3 ++-
 torch/_dynamo/package.py                | 16 ++++++++--------

(git diff 42b8dae5..HEAD is wider because the base moved; the PR's own delta is the three files above.)

Resolved

BY (__builtins__ inserted unconditionally, lengthening the snapshot) — gated. guards.py:4407-4408 is now if "__builtins__" in f_globals:, so the snapshot's key set always matches the live dict's. That closes the length half: keep_globals_length (test_guard_serialization.py:163-166) reads len(func.__globals__), which installs SEQUENCE_LENGTH derived from DICT_KEYS_MATCH, and a function built with types.FunctionType(code, {}) no longer gets a phantom key. See CA for the half that remains.

BZ (_instance_dict's guarantee overstated) — corrected precisely. package.py:114-117 now says a user __getattr__/__getattribute__ never runs, that a type-level __dict__ property still does, and that only its AttributeError is absorbed. That is the right scope for a helper now shared by three call sites across the stack (the bound-method receiver probe, the mapping edge at guards.py:1757-1762, and #195912's whole-object pruner).

The FunctionPicklerBase docstring wrap — fixed. package.py:128-134 reflows cleanly.

The third_party/kineto pointer is clean. HEAD:third_party/kineto, origin/main:third_party/kineto and the base all report 84e5ca9e8dc1a27abd174f1305bd8e0e400239ea. The PR diff is the 6 dynamo files, nothing else.

Code Quality

CA. The __builtins__ substitution stores the module where an imported module really holds builtins.__dict__, and the new assertion pins that (torch/_dynamo/guards.py:4405-4408, test/dynamo/test_guard_serialization.py:1175)

The gate fixed the key set; the value is still not the live one's type. Per the CPython language reference (shipped locally at /usr/lib/python3.12/pydoc_data/topics.py:6257-6269): "By default, when in the __main__ module, __builtins__ is the built-in module builtins; when in any other module, __builtins__ is an alias for the dictionary of the builtins module itself." Import runs exec(code, module.__dict__) into a dict with no __builtins__, so _PyEval_BuiltinsFromGlobals inserts interp->builtins — documented as "Dictionary of the builtins module" (/usr/include/python3.12/internal/pycore_interp.h:135-136). So for every function whose __globals__ can reach _globals_snapshot in production — the function must come from a real module for its globals to be a module dict — the live entry is a dict and :4408 writes a ModuleType.

That is observable, through the same shape this file already tests. fn.__globals__ is a PyMemberDef/member_descriptor, so getattr resolves it via MemberDescriptorVariable.tp_descr_get_impl (variables/functions.py:4893-4930), which builds with AttrSource(fn, "__globals__"); VariableBuilder._wrap then takes the dict branch at variables/builder.py:1214-1215 (install_guards(TYPE_MATCH)) and wraps each value lazily under DictGetItemSource at :1253. keep_global (test_guard_serialization.py:153-160) exercises exactly that chain with a different key. For __builtins__ the value is itself a dict, so realizing it installs TYPE_MATCH on it. load_guard_manager re-runs the builder against the deserialized objects, so builder.get reads the snapshot's module and TYPE_MATCH bakes t = types.ModuleType (guards.py:2436) — and ModuleType.__qualname__ == ModuleType.__name__, so the _unserializable trip at :2438-2441 never fires and nothing surfaces at load. At check time the live value is a dict: permanent silent cache miss.

I could not construct a reachable user program for this — it needs traced code that subscripts an fqn-mismatched function's __globals__ with "__builtins__" specifically, which is exotic — so this is a latent narrowing, not a live defect, and the same class as the length issue BY just closed. Two reasons it is still worth the one line:

  • The stated rationale does not require the module. The comment says a function the rebuilt one creates at call time reads its builtins from __globals__. PyFunctionObject has a dedicated func_builtins slot filled once at construction from _PyEval_BuiltinsFromGlobals (/usr/include/python3.12/cpython/funcobject.h:11-19), so only a nested function made at MAKE_FUNCTION time re-reads the entry — and per the spec line above that accepts a module or a dict. builtins.__dict__ satisfies the rationale identically while preserving the type; mirroring the live entry (builtins if isinstance(f_globals["__builtins__"], types.ModuleType) else builtins.__dict__) is exact.
  • The new assertion locks the divergence in. assertIs(out.__globals__["__builtins__"], sys.modules["builtins"]) (:1175) passes regardless of what the live dict held, because :4408 always writes the module — so it pins the substitution rather than the fidelity, and a later type-faithful fix would have to change the test. An assertIs(out.__globals__["__builtins__"], g["__builtins__"]) would assert the property that matters and would be robust to how the test module was loaded (__main__ under run_tests, an imported module under collection).

Fix this →

Testing

CB. The bound-method test's new unguarded leaf is pruned out of local_scope before the pass it is meant to exercise (test/dynamo/test_guard_serialization.py:1682-1703)

The comment and the FAQ both say the raw function now travels "as an unguarded leaf, which only the source-site seed can keep whole", i.e. that the pre-dump missing_values pass would prune it. Traced through, inner never reaches that pass:

  • serialize_guards rebuilds the state with local_scope filtered to used_local_vars | additional_used_local_vars (guards.py:5144-5150), and it is that pruned state that becomes GuardsState at :5169 and is handed to pickle_guards_state.
  • used_local_vars is populated only by prune_variable(guard.originating_source) over the post-filter sorted_guards (:5103-5112; the filter is applied at :4918-4920). The test's guard_filter_fn keeps only EQUALS_MATCH-derived guards, and g is never loaded in fn's body — so its LazyVariableTracker is never realized, no guard is rooted at L['g'], and additional_used_local_vars is fed only by the aliasing path at :3283.
  • So g is gone from local_scope before pytree.tree_leaves runs at :4751, and inner never lands in missing_values at :4764.

Independently, the in-reducer seed at :4664-4668 already covers this case: _keep(bound) is True (the source-site registration at :1720 put the method in guard_tree_values for L['f']), so guard_tree_values[id(inner)] is set before pickle saves the reduce args, and inner reaches :4658 with its id present. The missing_values check at :4514 — the only thing that would outrank that seed — is never consulted for it.

The test should still pass, so this is a claim/coverage mismatch rather than a broken test. To actually reach the loop-only shape the raw function has to survive local_scope pruning, which means a kept guard must be rooted at it (or at a container holding it) — e.g. root a second EQUALS_MATCH at g in the traced body, or reach the function through a guarded container. Otherwise the comment at :1685-1686 should say the leaf is pruned and the in-reducer seed is what covers this, so the next reader does not treat this as the loop-only regression test.

Unchanged gaps, all acknowledged in the FAQ:

  • __type_params__ has no guard-side coverage. guards.py:4479-4485 and package.py:252-253 never run with a non-None value, and both _keep_container_verbatim branches on that slot are untested.
  • The bound-method loop-only shape still has no test, per CB.
  • The 3.14 _read_raw_annotations FORWARDREF branch cannot be exercised here (3.12.3, no built torch), so confirm CI's 3.14 dynamo_wrapped shards specifically rather than treating overall-green as confirmation.

Also still open (comment accuracy only)

  • The Note at guards.py:4356-4375 still states the container rule as "A registered CONTAINER is carried verbatim rather than pruned per element", which several rounds have narrowed and which _keep_container_verbatim's docstring 30 lines below (:4370-4381, correctly reworded this round to "a KEPT dict/tuple SUBCLASS") now qualifies in both directions. A reader hits the Note first, and it is still the natural place to record what "registered" means — guard_tree_values is written only at :1720, for values on a walked source chain — which is the misreading behind my withdrawn AO.
  • convert_frame.py:1966-1969: the comment attributes the bypass to "this entry's guards could not be serialized", but bypass_package has a second caller (output_graph.py, the graph-has-named-parameters bypass), so that is one of two reasons. Half a clause.
  • The RecursionError arm at guards.py:4793-4801 raises a fixed string with no interpolation, while the except Exception two lines down was improved to f"{type(e).__name__}: {e}". The comment correctly explains why walking the graph is skipped, but sys.getrecursionlimit() or the guard's source name are both available without recursing.
  • E / L — the per-call {} globals identity split (documented at package.py:207-210); the AttributeError-before-version-message ordering in deserialize (now a follow-up-commit concern). Both recorded as intentional.

CI

15 runs: 3 green (Lint, BC Lint, ghstack mergeability), 7 pending (pull, trunk, inductor, TSan, docs-build, torchtitan-test, a second Lint), 5 cancelled by the newer push, 0 failures. pr-sanity-checks passes — 1920 + 74 = 1994 LOC, 6 under the gate. That margin is now thin enough that any further test addition here needs offsetting, and the keep_defaults_element dedup that bought the last round's headroom is already spent. No test shard has reported yet.

Recommendation

Approve. Both round-40 changes are correct and the _instance_dict docstring is now scoped to what the read actually guarantees. CA is the value half of the same __builtins__ issue the gate fixed — type-infaithful for every imported module, reachable only through exotic traced code, and one line to make exact; the assertion added this round pins the substitution rather than the fidelity, so it is worth changing alongside. CB is a claim/coverage mismatch: the new unguarded leaf is filtered out of local_scope at guards.py:5144-5150 before the pass it is meant to reach, so either root a guard at it or reword the comment. Neither is a correctness objection.

Verification note: Python execution and a built torch are unavailable in this environment (3.12.3 only). CA rests on /usr/lib/python3.12/pydoc_data/topics.py:6257-6269, /usr/include/python3.12/cpython/funcobject.h:11-19, /usr/include/python3.12/internal/pycore_interp.h:135-136, plus variables/functions.py:4893-4930, variables/builder.py:1214-1256 and guards.py:2425-2454. CB rests on guards.py:4742-4772, :5087-5150, :4508-4520, :4650-4669 and the test harness at test_guard_serialization.py:899-1017. Nothing was reproduced.

| Branch: `gh/bobrenjc93/1093/head`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant