Skip to content

[dynamo] Restore a rebuilt function's attributes and prune what no guard reads - #196476

Closed
bobrenjc93 wants to merge 10 commits into
gh/bobrenjc93/1141/basefrom
gh/bobrenjc93/1141/head
Closed

bobrenjc93 wants to merge 10 commits into
gh/bobrenjc93/1141/basefrom
gh/bobrenjc93/1141/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

types.FunctionType(code, ...) takes __doc__ from the code object, leaves
__annotations__ and __type_params__ empty, and starts with an empty
__dict__ and no __kwdefaults__.
functools.wraps overwrote all of these on the live function, and a guard
rooted at a wrapper reads them: an EQUALS_MATCH on func.scale_flag,
func.__doc__ or func.__kwdefaults__["scale"], an ID_MATCH on an annotation
value. Rebuilt from the code object alone those read None or empty, the guard
rebakes against that at load, and it fails forever with no load error (or the
load raises, for an attribute that is gone). So __kwdefaults__, __dict__,
__doc__, __annotations__ and __type_params__ now travel in the pickle
state next to the defaults, applied after memoization so wrapper.me = wrapper terminates.

Carrying them verbatim would trade one failure for another: everything the
function holds comes along, and one unpicklable, unguarded neighbour -- a
threading.Lock a decorator stashed in __dict__, a local class in an
annotation, a TypeVar in the __type_params__ that wraps copies off any
PEP 695 generic, an unrelated default -- fails the dump and silently bypasses
a package that never needed the value. Only values some guard tree node
references (_keep, identity in guard_tree_values) are carried; the rest
are replaced IN PLACE by a _Missing sentinel, one per reason, so the
signature's shape (defaults length, kwdefaults keys, __dict__ key set)
survives for a guard that reads structure rather than values. Always-picklable
constants (None, bool/int/float/complex/str/bytes, Ellipsis, NotImplemented,
torch.dtype/device/layout/memory_format) are always carried: they cannot fail
the dump, and pruning them would make the rebuilt state depend on whether some
unrelated guard happened to register the interned value. That is deliberately
not dynamo's whole common_constant_types, which includes torch.finfo and
torch.iinfo, and those do not pickle. A registered CONTAINER (a guard on the __defaults__ tuple
itself, as bind_args installs for any called function with a positional
default) is carried verbatim, since a whole-container EQUALS_MATCH rebakes its
constant from the reconstructed function at load; the follow-up that decides
per container whether a guard reads its values comes two commits up. Until
then any guard whose source walks THROUGH a container registers it -- an
unread positional default of a CALLED function (bind_args installs a length
guard on __defaults__), f.__dict__["tag"], f.__defaults__[0],
f.__kwdefaults__["k"], f.__annotations__["x"] -- so an unpicklable sibling
in that container still fails the dump; only a plain attribute read
(f.tag) prunes. The name_beside_unpicklable_default subtest exercises the
pickler only because the test harness's guard filter drops the bind_args
guard. A cell whose contents are kept (or empty) passes through unchanged so
two functions closing over one variable still share it after reload; a
pruned cell is memoized by the original cell's identity for the same reason. __dict__ is assigned before
__type_params__: on Python < 3.12 both live in __dict__, and the reducer's
pruned tuple has to win over the copy inside the carried dict.

Restore and prune land together because either alone regresses its parent:
verbatim restore fails the dump for every generic function and every local
function with an unpicklable attribute, and pruning needs the restore
plumbing. Annotations are read with _read_raw_annotations, which on 3.14+
asks for the FORWARDREF format so a TYPE_CHECKING-only name does not raise
during the dump; it returns a copy, with a proxy only for names that do not
resolve, and the copy is pruned per value like any other unkept container.

Test Plan:

python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k prunes -k sentinels -k type_params -k kwdefaults -k attribute -k annotations -k reaches_itself -k copied_doc -k a_lambda -k name_beside -k with_an_empty_cell -k dict_key_set -k guarded_defaults_tuple -k package_error -k pruned -k reaching_itself

Sixteen of the twenty new tests matched by the second command fail or error on
the previous commit (the command also matches two pre-existing package_error
tests); the two that pass there pin that _prune_cell tolerates an empty cell
and that a kept default is carried rather than pruned. A manually assigned __type_params__ round-trips on
every version, exercising the __dict__-before-__type_params__ order on
3.10/3.11 where both hold it.

Authored with an AI assistant.

FAQ

Q: There is no test for the 3.14 annotationlib FORWARDREF branch of
_read_raw_annotations.

A: The 3.14 path differs only in how the annotations are READ; what comes
back is a fresh dict whose values go through the same version-independent
_prune as any other unguarded non-literal, which the unpicklable-annotation
test covers. On 3.14.7, FORWARDREF does not raise for a TYPE_CHECKING-only
name and returns a new dict each call, so the proxy can never be identity-kept
and is always sentinelled. There is no 3.14 torch build here to run a gated
test against, so it is deferred rather than shipped unverified.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ No Failures, 1 Pending

As of commit 97cafd7 with merge base 32d114b (image):
💚 Looks good so far! There are no failures yet. 💚

GREEN LIGHT - PR approved to be merged without human review:

  • Correctness
    • _apply_function_state unpacks exactly the 6-element state tuple _reduce_function builds at package.py:346, and keyword order matches the call at guards.py:4420
    • fn.__dict__ is assigned before fn.__type_params__ (package.py:232-234) so the reducer's pruned tuple wins on <3.12 where both live in __dict__
    • Pruning is shape-preserving: _prune maps tuples/dicts in place and _prune_cell returns a cell per cell, so defaults length, kwdefaults keys and __dict__ key set survive
  • Pruning safety
    • get_guard_manager_from_source records example_value for every source and recurses on source.base (guards.py:1718-1732), so any value a guard reads is in guard_tree_values and is kept by _keep
    • A whole-container guard registers the container itself, e.g. bind_args installs SEQUENCE_LENGTH on AttrSource(fn, "__defaults__") (variables/functions.py:270-277), which the verbatim gates at guards.py:4381/4386 honor
    • _prune_cell returns an empty cell untouched on ValueError and memoizes pruned cells by the original cell id, so shared cells stay shared
  • Blast radius
    • FunctionPicklerBase has one subclass (GuardsStatePickler) and _reduce_function one caller (guards.py:4420); both are updated in this diff
    • The pickle state shape changed, but SystemInfo.check_compatibility rejects any artifact whose torch_version differs (package.py:684-687), so no stale artifact reaches the new unpickler
  • Tests
    • Twenty new tests in test/dynamo/test_guard_serialization.py cover each restored field plus pruning of defaults, kwdefaults, __dict__, annotations, __doc__ and __type_params__
    • test_reduce_prunes_in_place_beside_a_kept_default and test_reduce_keeps_the_function_dict_key_set pin the shape-preservation invariant the pruning rests on
    • Two existing tests' guard_tree_values were adapted to register cell contents rather than the cell, matching _prune_cell's predicate rather than weakening an assertion
  • Safety
    • No CI, release or auth plumbing touched; the only exec is a hardcoded PEP 695 literal inside a version-gated test, and no secret or credential appears in the diff

reason: clean
Reviewed commit: 97cafd7

Inference job

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

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Reviewing this PR

  • Gather context (diff vs base, read changed files)
  • Run PyTorch PR review checks
  • Post review

View job run · branch gh/bobrenjc93/1141/head

[ghstack-poisoned]
@bobrenjc93 bobrenjc93 changed the title [dynamo] Prune what no guard reads from a function rebuilt by value [dynamo] Restore a rebuilt function's attributes and prune what no guard reads Sep 9, 2026
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 added the topic: not user facing topic category label Sep 9, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Updated (this PR now also carries the attribute restore folded from #196475). From that review: pruning is real here, the dead resolve=True branch is gone, _reduce_function's keyword order matches the state tuple, the class docstring lists every field that travels as state, the ForwardRef comment says the proxy may not pickle rather than that it cannot, and __type_params__ is tested both for a PEP 695 generic and for a manually assigned tuple (which exercises the __dict__-first ordering on 3.10/3.11). A 3.14 annotationlib test is answered in the FAQ in the description.

@claude

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

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


The restore-and-prune split is sound and well covered by tests; I found no correctness bugs, only two consistency issues in _prune/_prune_cell and a couple of test-hygiene nits.

Full review of #196476

PR Review: #196476

Summary

Restores __kwdefaults__/__dict__/__doc__/__annotations__/__type_params__ onto a by-value-rebuilt function and prunes every value no guard tree node references to a _Missing sentinel. I verified the load-order claim about __dict__-before-__type_params__ (/usr/include/python3.12/cpython/funcobject.h:39-44 confirms func_doc, func_annotations, func_typeparams are real struct slots on 3.12+, so the fn.__dict__ = attributes at package.py:224 does not clobber the __doc__/__annotations__ writes above it, and only __type_params__ needs the after-__dict__ ordering on <3.12), and I confirmed the container-verbatim invariant is real for __defaults__ (wrap_listlike's whole-tuple CONSTANT_MATCH registers no per-element source). I found no correctness bugs. Two consistency issues in the pruning predicates and two test nits below.

Code Quality

  • torch/_dynamo/guards.py:4328-4346 — _prune_cell omits the literal carve-out that _prune applies ten lines above. _prune (:4320-4326) carries None/bool/int/float/str/bytes unconditionally, justified in its own comment as "A literal always pickles, so carrying it costs nothing and keeps the rebuilt state deterministic: an interned literal would otherwise be kept only when some unrelated guard happens to register it." _prune_cell has no such branch, so an unguarded cell holding None or 3.0 becomes types.CellType(_Missing(...)) while the identical literal as a positional default is carried verbatim. The rationale applies more strongly to cells, not less: _prune_cell's self._keep(contents) test is exactly the id-based accident the comment says the carve-out exists to eliminate. The modified test_reduce_keeps_a_none_valued_cell (test/dynamo/test_guard_serialization.py:1037-1055) is direct evidence — it now has to pass {id(cell): cell} for a None cell to survive, where a None default survives with no guard_tree_values entry at all. I checked the obvious refutation and it does not hold: cell-content guards go through CellContentsSource and are ordinary serializable guards, not CLOSURE_MATCH (which guards a function by __code__ id and is in UNSUPPORTED_SERIALIZATION_GUARD_TYPES at guards.py:4938), so there is no alternate guarding mechanism that makes sentinelling a cell literal necessary. Apply the carve-out to contents. Fix this →

  • torch/_dynamo/guards.py:4324 — the 5-type whitelist does not deliver the determinism its comment claims. Other always-picklable, process-wide interned singletons are omitted: torch.dtype (interned by dtype_registry in torch/csrc/DynamicTypes.cpp), torch.layout, torch.memory_format, Ellipsis, NotImplemented. All reduce cleanly and none is intercepted by reducer_override. So whether an unguarded def f(x, dtype=torch.float32) default survives the round trip depends on whether some unrelated guard elsewhere in the same compile happened to register that singleton — the exact accident the comment says it is preventing. Consequence is artifact non-determinism, not miscompilation (a sentinelled value is unreachable by construction, since get_guard_manager_from_source at :1706-1732 registers every intermediate on a guard's source chain). One caveat if you widen it: torch._dynamo.utils.is_safe_constant (utils.py:2996) is not a safe drop-in, because it admits arbitrary type and enum.Enum, which would let a <locals> class through and defeat the PackageError at :4591. The narrow fix is to add the specific interned singletons, not to reuse the whole predicate.

  • torch/_dynamo/guards.py:4381 — the annotations verbatim gate is unreachable on 3.14+, and its safety on every version rests on an unstated invariant. annotationlib.get_annotations returns a fresh dict, so self._keep(raw_annotations) can never be true there; the code comment at :4379 notes the fresh dict but frames it as "always pruned" rather than "this branch is dead." It is benign today only because no whole-dict value guard exists — dict is absent from EQUALS_MATCH's ok_types (:2875-2890, where ok_mutable_types = (list, set)), so every dict-container guard bakes type/length/keys only, which the pruning comprehension preserves in place. That is the load-bearing fact and it is not written down anywhere near the gate. Worth one line, since the __defaults__ tuple case (where the invariant genuinely bites) is documented at length in the Note but the reason the dict siblings are safe is not.

Testing

  • test/dynamo/test_guard_serialization.py:1155-1170 — test_function_reaching_itself_through_its_dict only exercises the verbatim branch. It passes gtv = {id(w): w, id(w.__dict__): w.__dict__}, so _keep(obj.__dict__) is true and attributes is obj.__dict__ itself. The interesting path is the other one: with id(w.__dict__) dropped, id(w) is still registered, so _prune(w, ...) keeps w and the cycle runs through a rebuilt dict instead of the carried one — that is where a _prune/memoization ordering mistake would show up, and the assertion out.me is out would still be the check. Dropping the id(w.__dict__) entry (or adding a second subtest without it) covers both.

  • test/dynamo/test_guard_serialization.py:1148-1160 — test_reduce_sentinels_an_unpicklable_doc passes {id(int): int} as guard_tree_values, which nothing in that test reads. It looks copy-pasted from test_reduce_sentinels_an_unpicklable_annotation directly above, where the int entry is load-bearing (it is what makes the kept-vs-sentinelled contrast). Here it is noise that suggests the doc test also has a kept value when it does not; {} is the honest input.

Recommendation

Approve

The restore and the prune genuinely have to land together — I confirmed verbatim restore would fail the dump for every PEP 695 generic (a TypeVar in __type_params__ does not pickle, and functools.wraps copies __type_params__ onto every wrapper of a generic), so neither half is separable. Test coverage is thorough for the new behavior, the shape-preserving in-place sentinel choice is right, and the two container invariants that matter (__defaults__ verbatim, __dict__ key set) each have a dedicated test. The _prune_cell carve-out is the one I would fix before landing since it is a live inconsistency between adjacent predicates rather than a style preference; the rest can ride in a follow-up.

Note: I could not execute Python or run the test suite in this environment (python3 <script> and pip are outside my allowed tools here), so the CPython slot-vs-__dict__ conclusions come from reading /usr/include/python3.12/cpython/funcobject.h and the funcobject.c getset behavior rather than from running the probes I wrote. The <3.12 half of the __type_params__ ordering claim in particular is unverified empirically — this checkout only has a 3.12 interpreter.

· branch `gh/bobrenjc93/1141/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Round-2 review follow-up: the literal check is one helper (_is_literal) used by both _prune and _prune_cell, and a cell's contents alone decide whether it passes through (any guard that reads them registers them, so the extra _keep(cell) early return only widened the failure surface). Comments corrected: FunctionType() takes only __doc__ from the code object; the 3.14 FORWARDREF read evaluates what it can and returns a copy. The message states the full limitation before the container rule lands (any guard walking THROUGH a container registers it), and the defaults-tuple test's comment says what it can and cannot discriminate.

@claude

@claude

claude Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 14m 32s —— View job


The three round-2 fixes are correct and I confirmed the _prune_cell rationale independently, but the _keep(cell) removal left dead guard_tree_values entries in two tests and one comment still describes the removed mechanism.

Full review of #196476 (round 2)

PR Review: #196476

Summary

Restores __kwdefaults__/__dict__/__doc__/__annotations__/__type_params__ onto a by-value-rebuilt function and prunes every value no guard reads to a _Missing sentinel. All three round-2 changes land as described, and I verified the two load-bearing claims behind the _prune_cell simplification independently (see below). The remaining findings are stale test inputs and comments left behind by that simplification, plus two round-1 items that were not addressed.

On the _prune_cell change, which is the substantive one: the removal of the if self._keep(cell): return cell early return is correct, and I confirmed the premise rather than taking it on the description's word. get_guard_manager_from_source (guards.py:1717-1719) registers example_value for every source on a chain and recurses on source.base, and the only source path to a cell's value is CellContentsSource(GetItemSource(ClosureSource(...), i)) (variables/functions.py:857-860), so any guard that reads contents registers the contents object — the cell's own registration is redundant. I also checked the one alternate mechanism that could have made this unsafe: CLOSURE_MATCH (guards.py:3091) guards a function by __code__ identity, not cell contents, and is in UNSUPPORTED_SERIALIZATION_GUARD_TYPES (guards.py:4954), so it is not on this path. Separately, the missing verbatim gate on __closure__ (guards.py:4373-4378) is genuinely unreachable, not an oversight: types.CellType is absent from EQUALS_MATCH's ok_types (guards.py:2877-2892), so a whole-cell or whole-__closure__-tuple value guard cannot be installed and there is no rebaked constant for pruning to invalidate. The inline comment says exactly this.

Code Quality

  • torch/_dynamo/guards.py:4336-4354 — removing _keep(cell) left dead inputs in two tests, and one comment now describes a mechanism that no longer exists. Nothing consults _keep() on a cell object anywhere in the file after this change (I grepped), so a {id(cell): cell} entry in guard_tree_values is inert. Three call sites registered a cell; one was updated, two were not:

    • test/dynamo/test_guard_serialization.py:1038-1056 (test_reduce_keeps_a_none_valued_cell) passes {id(cell): cell} and its comment reads "The cell is guarded here so it is carried; an unguarded one is pruned to a sentinel-holding cell." That is no longer why it is carried — _is_literal(None) is True at :4345, so the cell survives whether or not it is registered, and the test would pass identically with {}. The comment asserts a contrast the test no longer demonstrates.
    • test/dynamo/test_guard_serialization.py:1058-1075 (test_reduce_preserves_a_self_referential_cell) passes {id(fn): fn, id(cell): cell}; the cell is carried via _keep(contents) because the contents is fn, so the id(cell) half is dead.
    • test/dynamo/test_guard_serialization.py:974 was correctly updated from id(cell) to id(cell.cell_contents). Applying the same edit to the other two, and dropping the stale clause at :1040-1041, keeps the tests testing the predicate that actually exists. Fix this →
  • torch/_dynamo/guards.py:4324-4329 — the _is_literal whitelist is narrower than the determinism guarantee its comment states, and extracting it into a named helper makes that contract shared rather than local. The comment justifies the carve-out as keeping the rebuilt state deterministic, "an interned literal would otherwise be kept only when some unrelated guard happens to register it." Several always-picklable, process-wide interned values are omitted: complex, torch.dtype, torch.layout, torch.memory_format, torch.device, Ellipsis, NotImplemented. All of these are in common_constant_types (torch/_dynamo/utils.py:2957-2981) and therefore in EQUALS_MATCH's ok_types (guards.py:2877-2892), and none is intercepted by reducer_override. So whether an unguarded def f(x, dtype=torch.float32) default survives the round trip still depends on whether an unrelated guard in the same compile registered that singleton — the exact accident the comment claims to have eliminated. Consequence is artifact non-determinism, not miscompilation. I raised this in round 1 and it is unaddressed; it now matters slightly more because two predicates share the helper. If you widen it, do not reach for torch._dynamo.utils.is_safe_constant (utils.py:2996): it admits arbitrary type and enum.Enum, which would let a <locals> class through and defeat the PackageError at guards.py:1031.

  • torch/_dynamo/package.py:216-218 — the corrected comment introduces a new inaccuracy on 3.13+. "they are MAKE_FUNCTION operands" was true through 3.12, but 3.13 reduced MAKE_FUNCTION to the code object alone and moved the rest to SET_FUNCTION_ATTRIBUTE — dynamo models both (symbolic_convert.py:5047-5065, and the 3.13 note at symbolic_convert.py:4237). The load-bearing half of the sentence (FunctionType() leaves them empty) is right on every version; the parenthetical explaining why is not. Since this comment was rewritten specifically for accuracy this round, worth saying "they are set by the caller after MAKE_FUNCTION" or dropping the parenthetical.

Testing

  • test/dynamo/test_guard_serialization.py:1460-1464 — the new comment points at a test that does not exist, and its stated reason for the harness's blind spot is not the operative one. Two separate problems in one comment block:

    1. test_whole_defaults_equals_match_survives_a_called_default is nowhere in the repo — I grepped test/ and torch/ and ran git log -S across every commit reachable from HEAD, and the only occurrence is the reference itself at :1464. It presumably lands in the follow-up two commits up that the description mentions. A comment directing a reader to a test they cannot find is worse than no reference; either drop it or say "a follow-up in this stack adds one."
    2. "This harness registers every element it compares" is not what makes this test unable to discriminate. GuardedDefaultsTupleModule.forward (:364-369) compares against (2.0, 1.0) and {"c": 3.0} — all float — and _is_literal (guards.py:4324) carries floats unconditionally, so the elements survive whether or not any guard registers them and whether or not the container is kept verbatim. That is the reason the test cannot tell a whole-container guard from a per-element one, and it is version-independent and easy to state. The previous wording ("A guard on the container itself registers no per-element source") made the opposite claim about registration; I could not confirm either registration story without running dynamo, which is why I would anchor the comment on _is_literal instead — that part is checkable by reading. Using a non-literal default in this module (an Inputs instance, as test_reduce_prunes_in_place_beside_a_kept_default does at :1105-1129) would let the test actually discriminate. Fix this →
  • Two round-1 test items are still open (neither is claimed fixed in the update note, so flagging only for the record): test_reduce_sentinels_an_unpicklable_doc (:1149-1161) still passes {id(int): int}, which nothing in that test reads — it is copy-paste from the annotation test above where the int entry is load-bearing, and {} is the honest input. And test_function_reaching_itself_through_its_dict (:1163-1174) still passes {id(w): w, id(w.__dict__): w.__dict__}, so it only exercises the verbatim __dict__ branch; dropping the id(w.__dict__) entry routes the out.me is out cycle through a rebuilt dict, which is where a _prune/memoization ordering mistake would actually show up.

Recommendation

Approve

The three fixes the update note claims are all present and correct, and the one with real behavioral weight — dropping _keep(cell) so a cell's contents alone decide — I verified against the guard-tree registration path and the CLOSURE_MATCH alternative rather than accepting the rationale. Every finding above is a stale comment or a dead test input, i.e. artifacts of that simplification rather than defects in it. The cell-registration cleanup (first finding) is the one I would do before landing, since two tests currently document a predicate that no longer exists; the dangling test reference is a one-line edit and the rest can ride in the follow-up.

Note: I could not run the test suite or execute Python in this environment (no built torch here), so all conclusions come from reading the source — guards.py, package.py, variables/functions.py, utils.py — rather than from running the probes. The _prune_cell and __closure__ reachability conclusions in the Summary were each cross-checked by an independent pass over the guard-source and ok_types code.

· branch `gh/bobrenjc93/1141/head`

… check, root-verdict caching, scope-first reduce tuple, load-bearing tests

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #196481

…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]

@aorenste aorenste left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Reviewed by me, assisted by AI)

[cleanup] My agent says:

Nothing exercises the 3.14 fallback in _read_raw_annotations. Every annotation in the new tests is either an assigned dict (fn.__annotations__ = {...}) or a name that resolves (def gen[T](x: T)), and for both of those annotationlib.get_annotations(..., FORWARDREF) returns from _get_dunder_annotations at the top of the FORWARDREF branch and never reaches _get_and_call_annotate -- the fake-globals path the helper exists for. The description defers a gated test for lack of a local 3.14 torch build, but CI has one and already runs this file on it: pull / linux-jammy-py3.14-clang21 / test (default, 2, 10) (job 103306525705) ran dynamo/test_guard_serialization under /opt/python-3.14-venv/bin/python on this head. A @unittest.skipIf(sys.version_info < (3, 14)) test with a TYPE_CHECKING-only annotation would be verified there rather than shipped unverified.

[cleanup] My agent says:

Pre-existing rather than introduced here, but this change widens it from one attribute to five: AOTCompilePickler still carries its own by-value function reducer (torch/_dynamo/aot_compile.py:106-151) that passes only __defaults__. That gap is not hypothetical on that side, because an AOT-rebuilt function is CALLED after load rather than read for attributes, so a dropped __kwdefaults__ is a TypeError at call time instead of a guard miss. Round-tripping

def make():
    def helper(x, *, scale=2.0):
        return x * scale
    helper.tag = "attr"
    def fn(x):
        return helper(x, scale=3.0) + 1, helper
    return fn, helper

through save_compiled_function / torch.compiler.load_compiled_function on main hands the caller back a helper with __kwdefaults__ is None and __dict__ == {}, and calling it raises TypeError: make.<locals>.helper() missing 1 required keyword-only argument: 'scale'. (_unpickle_nested_function also passes qualname into types.FunctionType's name parameter, so __name__ comes back as make.<locals>.helper.) Worth a tracking issue alongside the docstring note.


Merging is self-service: comment @pytorchbot merge and the bot lands it once required checks pass. Merging your Change | Bot commands

Comment thread torch/_dynamo/package.py
if sys.version_info >= (3, 14):
import annotationlib

return annotationlib.get_annotations(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[cleanup] My agent says:

Guard the call -- on 3.14 it can raise out of the dump, which is the silent package bypass the surrounding pruning exists to prevent:

            try:
                return annotationlib.get_annotations(
                    obj, format=annotationlib.Format.FORWARDREF
                )
            except Exception:
                return {}

FORWARDREF's rescue is not "catch NameError", it is a rerun under an empty _StringifierDict where every name lookup yields a proxy -- so it also absorbs an AttributeError off a real module, a raising __class_getitem__, and a raising call. What it cannot absorb is a sub-expression with no name in it, and that final result = func(Format.VALUE_WITH_FAKE_GLOBALS) (Lib/annotationlib.py:829 on 3.14.4) is the one call in the chain with no except around it. Checked on CPython 3.14.4, each of these propagates straight out of get_annotations(f, Format.FORWARDREF):

def f(x: f"{Missing}"):  TypeError: Cannot stringify annotation containing string formatting
def f(x: "abc".nope):    AttributeError
def f(x: ()[0]):         IndexError

Narrow, but it is the one unguarded read left in the reducer.

),
subtest(
("EQUALS_MATCH", DecoratedUnpicklableDefaultForwardModule, ("__name__", "x")),
name="name_beside_unpicklable_default",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[cleanup] My agent says:

The subtest name reads as "an unpicklable positional default beside a guarded __name__ gets pruned", which is not true of a real compile: per the description this only passes because _test_serialization's guard_filter_fn drops the bind_args __defaults__ guard that would otherwise register the tuple and force it to be carried verbatim. Every other new test here states that kind of caveat inline; this one needs it too.

    subtest(
        # Prunes only because the harness's guard_filter_fn drops the
        # bind_args __defaults__ guard; in a real compile that guard
        # registers the tuple and the unpicklable default fails the dump.
        ("EQUALS_MATCH", DecoratedUnpicklableDefaultForwardModule, ("__name__", "x")),
        name="name_beside_unpicklable_default",
    ),

Comment thread torch/_dynamo/guards.py
"""Identity match; an interned value that collides is kept, harmlessly."""
return id(value) in self.guard_tree_values

def _missing(self, reason: str) -> _Missing:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[cleanup] torch.utils._functools.cache_method is the in-tree @functools.cache for methods -- per-instance dict, does not pin self -- and dynamo already uses it at symbolic_convert.py:2415 and :2552, both for caches scoped to a single translator.

    @cache_method
    def _missing(self, reason: str) -> _Missing:
        """One sentinel per reason; a pruned container shares them."""
        return _Missing(reason)

self._missing_cache then drops out of __init__.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Thanks; fixed forward in #196767 at the top of the stack (the tuple rule reads the recording alone, __builtins__ is always the module in a snapshot, the 3.14 FORWARDREF read is guarded with a 3.14-gated test, _missing uses cache_method, and the test/comment items are folded). The AOT reducer gap is closed by #196685 and the commits above it in this stack.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #196481

pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
#196478)

Every function carries a pointer to the module dict it was defined in,
`fn.__globals__`, and its body looks up every non-local name there.
`functools.wraps` makes a wrapper lie about which dict that is:

```python
# decorators.py
SCALE = 2

def scaled(func):
    @functools.wraps(func)
    def wrapper(self, x):
        return func(self, x) * SCALE   # looked up in wrapper.__globals__
    return wrapper

# model.py
class M(torch.nn.Module):
    @scaled
    def forward(self, x):
        return x + 1

>>> M.forward.__module__
'model'          # copied from the wrapped function by wraps
>>> M.forward.__globals__ is sys.modules['decorators'].__dict__
True             # where wrapper was actually defined
```

The previous commit rebuilds such a function from its code object and, at
load, hands `types.FunctionType` the only scope it recorded:
`import_module(fn.__module__).__dict__`, here the `model` dict (#196684, above,
imports the compile scope instead, which removes this particular KeyError but
not the two reasons below). Tracing `wrapper` read `SCALE`, so Dynamo guards
through the function's globals:

```python
L['self'].forward.__func__.__globals__['SCALE'] == 2
```

Rebuilding the guard manager at load walks that path on the rebuilt function
and gets `model.__dict__['SCALE']`, a `KeyError`, so the whole package fails to
load. Two things an import can never provide even when it lands on the right
module: the guard must be baked from the value the compile SAW, not whatever
the live module dict holds in the loading process (an import would silently
accept a changed global), and a decorator module that only lived in
`sys.modules` at save has no dict to import at all.

When `fn.__globals__` is itself in `guard_tree_values` (some guard read
through it), carry a snapshot of the dict the function was actually defined
in instead of importing by name, pruned per value like the other containers:

```python
{"__name__": "decorators", "SCALE": 2, "scaled": _Missing(...), "functools": _Missing(...), "__builtins__": builtins}
```

The function is built directly over that dict at load, so
`wrapper.__globals__['SCALE']` is 2 and the guard bakes correctly. A function
whose globals no guard reads keeps the import fallback.

`__builtins__` cannot be a sentinel: `FunctionType` reads
`scope['__builtins__']` at creation to wire up `len`, `isinstance` and the
rest, so a pruned entry becomes the real `builtins` module (pickled by
reference) while a kept one, the builtins dict a guard read through, stays
verbatim; the key set is unchanged.

The snapshot is built once per module dict and memoized by identity, so two
wrappers from the same decorator file share ONE scope after load, as before
saving, and pickle records a reference rather than a copy for the second. It
travels as a reduce ARGUMENT, not as pickle state. A wrapper defined at module
scope is an entry in its own module dict, so pickle reaches it while the
snapshot is still being filled in; `fn.__globals__.update(snapshot)` applied
as state would copy whatever had loaded by then, an empty dict for that
function, and a guard through its globals would KeyError again. Passing the
dict to the constructor gives the function the one shared object and pickle
keeps filling it in afterwards, which is fine because a function reads
`__globals__` lazily at call time. The snapshot's entry for the function
itself closes the cycle through pickle's recursive-object fallback, the same
mechanism a cell closing over its own function relies on; the pure-Python
pickler applies the state on both passes (the C pickler drops the outer one
after the memo fetch), so every write in `_apply_function_state` is
idempotent. The one-`_Missing`-per-reason cache from the pruning commit keeps a
pruned module dict from carrying thousands of distinct sentinels.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k test_guard_through_globals_of_a_wrapper_from_another_module -k test_functions_sharing_a_module_dict_share_the_rebuilt_scope -k test_snapshot_globals_share_one_missing_sentinel -k fqn_mismatched_function_module
```

The two-module test wraps `torch._dynamo.testing.reset_rng_state` from this
test module and guards through the wrapper's `__globals__`; with the snapshot
replaced by the import fallback it errors with `KeyError` at load (at this
commit; #196684 above changes the fallback and this test then pins the
snapshot only through the save-time-value test). The save-time-value test
mutates the guarded global between dump and load and checks the rebuilt
wrapper still sees the saved value in a dict that is not the live one; with
the import fallback it sees the mutated value. The shared-scope test pickles
two module-scope wrappers with their module dict and requires both to load
over one complete scope; with the snapshot applied as state the nested one
loads with `{}`. The preserves-module test pickles that wrapper with its
globals and checks `__module__` is the wrappee's module while the scope's
`__name__` is this module's; without the `__module__` restore it comes back
None, since the wrapper is built while its own snapshot is still loading. The
shared-sentinel and built-once tests fail or error on the previous commit
(the latter reads an attribute this commit adds). The remaining snapshot tests
(preserved/rejected globals, module-scope wrappers) pass on the previous
commit too, since their fixtures live in one importable module.

Authored with an AI assistant.

FAQ

Q: The snapshot freezes the module dict's key set at save time, including the
names Dynamo installed into that dict during the compile (`__compiled_fn_N`,
`__builtins_dict___N`, ...). Can a guard on the dict's shape, such as
`len(func.__globals__)`, miss forever in another process?

A: A guard on a module dict's key set is fragile by construction, with or
without this change: Dynamo writes into module dicts, the names it writes
differ between the saving and the loading process, and `install()` reinstalls
only the ones the installed entries need. Before this change the constant was
rebaked from the live module dict at load, which already contained a different
set of installed names than at save. The snapshot does not make that shape
guard portable, and it is not meant to; it makes the VALUES a guard reads
through `__globals__` come back as they were saved, which is what the
motivating wrapper case needs. Filtering Dynamo's names out of the snapshot
would not help, since the live dict at check time contains them.

Q: No test loads a snapshot in a fresh process.

A: The pickler-level and harness tests pin the two properties the change owns
(the shared scope and the values it carries) and the on-disk round trip is
covered by test_package's reload tests for the package as a whole. A
cross-process test would only add the shape-guard question above, which is
answered by design rather than by this change.

Pull Request resolved: #196478
Approved by: https://github.com/pytorchgreenlight, https://github.com/aorenste
ghstack dependencies: #196505, #196470, #196471, #196472, #196473, #196474, #196476
pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
…ard reads its values (#196479)

The pruning commit carries a rebuilt function's `__defaults__`,
`__kwdefaults__`, `__dict__` and `__annotations__` with every value a guard
did not read replaced by a `_Missing` sentinel:

```python
def scaled(func):
    @functools.wraps(func)
    def wrapper(self, x, scale=2.0, junk=threading.Lock()):
        return func(self, x) * scale
    wrapper.tag = "v1"
    wrapper._cache = threading.Lock()
    return wrapper

wrapper.__defaults__  ->  (2.0, _Missing)      # 2.0 is a literal, the Lock is not
wrapper.__dict__      ->  {"tag": "v1", "_cache": _Missing, "__wrapped__": ...}
```

The lock is never pickled, the shape survives, and a guard on `func.tag` or
`len(func.__defaults__)` bakes correctly at load.

It carved out one exception: a guard that compares a container as a whole,
`func.__defaults__ == (2.0, (1, 2))`, rebakes its constant from the
reconstructed function at load, so a tuple that came back as `(2.0, _Missing)`
would miss forever with no error. The commit therefore carried a container
verbatim whenever the container itself was in `guard_tree_values`. That is
the wrong signal, both ways.

Registration does not mean a value guard. The builder records every object a
source path walks through, and two very common guards register the tuple
without caring about its values:

```python
# 1. Calling any function with a positional default: bind_args installs a
#    SEQUENCE_LENGTH on __defaults__ so the parameter-to-default mapping holds.
mod.forward(x)              # len(L['mod'].forward.__func__.__defaults__) == 2

# 2. Reading one element: the source path passes through the tuple.
if wrapper.__defaults__[0] > 1.0: ...
```

Both survive per-value pruning, yet the old rule forced the whole tuple
verbatim, the dump tried to pickle the lock, and the package bypassed. A
CALLED function with an unread unpicklable default, the common shape, was
still broken end to end; the harness-level subtest passed only because
`_test_serialization`'s guard filter drops the `bind_args` guard.

The inverse rule fails too. A whole-tuple equality and a per-element guard
coexist in ordinary code:

```python
def forward(self, x, scale=2.0, shape=(1, 2)): ...
mod.forward(x)                                     # binds scale through the tuple
assert mod.forward.__defaults__ == (2.0, (1, 2))   # EQUALS_MATCH on the whole tuple
```

Prune here because an element is guarded through the tuple and the equality
guard rebakes against `(2.0, _Missing)`.

So record the decision where it is made. `EQUALS_MATCH` is the one guard whose
constant depends on every element (CONSTANT_MATCH lowers to it), so it now
records every plain tuple it reads whole, keyed by id and holding the value so
the id cannot be reused:

```python
def EQUALS_MATCH(self, guard, ...):
    val = self.get(guard)
    if self.save_guards and type(val) is tuple:
        self.value_guarded_containers[id(val)] = val
```

The pickler receives that map as a required argument (omitting it would
silently prune every container) and `_keep_container_verbatim` carries a plain
tuple whole only when it is in it:

| Guard installed on `__defaults__`        | Old rule                   | New rule                  |
|------------------------------------------|----------------------------|---------------------------|
| `len(...) == 2` from a call              | verbatim, Lock fails dump  | pruned, `(2.0, _Missing)` |
| `[0] > 1.0`                              | verbatim, Lock fails dump  | pruned, element kept      |
| `== (2.0, (1, 2))`                       | verbatim                   | verbatim                  |
| both of the last two                     | verbatim                   | verbatim                  |

The single path that installs such a guard is `wrap_listlike`'s CONSTANT_MATCH
on an all-literal tuple under an unspecialized nn.Module source, which also
leaves the elements sourceless, so it is exactly the shape with no
per-element registration to keep them. A plain dict is never carried
verbatim: a whole-dict comparison lowers to DICT_KEYS_MATCH plus per-value
guards, and EQUALS_MATCH's own allowlist rejects a plain dict, so the
recording is tuple-only. A dict/tuple subclass stays verbatim whenever kept,
since the guard reading that slot needs its type to survive and a subclass
instance cannot be rebuilt element by element. No per-source edge recording is
needed, so nothing here reads `__annotations__` off arbitrary objects (which
on 3.14 would force PEP 649 evaluation and NameError out of guard building).

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k prunes -k pruned_per_value -k stays_verbatim -k keeps_defaults_verbatim -k whole_defaults_equals
```

The compile-path tests go through `_roundtrip_through_precompile`: a real
`torch.compile` under `caching_precompile`, save, `torch._dynamo.reset`,
reload, and a hit under `fail_on_recompile`; the test base class now clears
`DynamoCache` and `PrecompileContext` in setUp and tearDown so those tests
leave no state behind. Seven of the thirteen tests
matched by the second command fail on the previous commit's rule (six with
`PackageError: cannot pickle '_thread.lock' object` / `unrelated default
cannot pickle`, the per-value unit test on its assertion). Of the other six,
the whole-defaults equality test passes there and fails against a rule that
prunes whenever an element is guarded through the tuple; the whole-tuple
verbatim and container-subclass tests pin the two carve-outs against a
prune-everything rule; and three are pre-existing tests swept in by `-k
prunes`.

Authored with an AI assistant.

Pull Request resolved: #196479
Approved by: https://github.com/pytorchgreenlight, https://github.com/aorenste
ghstack dependencies: #196505, #196470, #196471, #196472, #196473, #196474, #196476, #196478
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…t of snapshots, guard the 3.14 annotation read

Follow-up to the reviews of #196476, #196478 and #196479.

`_keep_container_verbatim` decided a plain tuple in two steps: is it in
`guard_tree_values`, and is it in `value_guarded_containers`. The second alone
is the rule; the first held because `EQUALS_MATCH` registers the value it
reads, a separate invariant whose failure would be the silent forever-miss the
rule exists to prevent. The tuple case now reads the recording alone:

```python
if type(container) is tuple:
    return id(container) in self.value_guarded_containers
if type(container) is dict:
    return False
return self._keep(container)
```

A globals snapshot kept `__builtins__` "as read" when some guard had registered
it and replaced it with the `builtins` module only when pruned. For an imported
module `f_globals["__builtins__"]` IS `builtins.__dict__`, the dict every
compile that guards a builtin registers, so the kept branch was the common one
and each snapshot carried all of builtins (about 6 KB, 155 keys) next to the
filtered copy `G` already holds; the two are distinct objects, so pickle does
not share them. The entry is now always the module, pickled by reference.
`FunctionType` accepts either.

`_read_raw_annotations` asked `annotationlib` for FORWARDREF annotations on
3.14 unguarded. FORWARDREF reruns the annotate function with every NAME lookup
proxied, so it absorbs a missing name, a raising attribute or a raising call,
but a sub-expression with no name in it still raises out of it:

```python
def f(x: f"{Missing}"):   # TypeError: Cannot stringify annotation containing string formatting
def f(x: ()[0]):          # IndexError
```

That would fail the dump for a slot the prune exists to make optional; the
read now returns an empty set instead. The 3.14 path had no test at all, since
every annotation in the suite either was an assigned dict or resolved; a
3.14-gated test now pins that a TYPE_CHECKING-only name comes back as a pruned
proxy and the f-string case drops the set (CI runs this file on 3.14; there is
no local 3.14 build).

`_missing` uses `torch.utils._functools.cache_method`, the in-tree per-method
cache that does not pin `self`, in place of a hand-rolled dict.

Test and comment cleanups: the guarded-defaults test names the full-compile
round trip that can tell a whole-container guard from a per-element one instead
of forward-referencing it; the two snapshot tests capture the module dict's key
set BEFORE the dump, since a `CleanupHook` for a traced code object can drop a
`__builtins_dict___N` key out of the live dict during the load; the
`name_beside_unpicklable_default` subtest says it prunes only because the
harness drops the `bind_args` guard; the pickler `__init__` comment no longer
claims omitting the recording prunes every container.

One #196476 comment is not a change here: the AOT pickler's own by-value
reducer carried only `__defaults__` at that commit, so an AOT-rebuilt helper
lost `__kwdefaults__` and `__dict__` and its `__name__` was the qualname.
#196685 and the commits above it move that pickler onto the shared base, which
is where those are fixed in this stack.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k snapshot -k verbatim -k type_checking_only
python test/dynamo/test_aot_compile.py -k Pickler
python test/dynamo/test_package.py
```

The two snapshot tests, the verbatim-rule tests and the `__builtins__` change
pass on the previous commit as well (the rule and the module are behaviourally
the same for every recorded tuple and every imported module); the
TYPE_CHECKING test is 3.14-only and runs in CI.

Authored with an AI assistant.


ghstack-source-id: a071f27
Pull-Request: #196767
pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
… pruned (#196481)

A bound method is two objects, a function and a receiver, and a guard on it
can depend on the function without ever registering it:

```python
def target(self, x):
    return x

@functools.wraps(target)      # copies target's __module__ and __qualname__
def wrapper(self, x):
    return x * 3

class Recv:
    pass

class M(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.cb = types.MethodType(wrapper, Recv())

    def forward(self, x):
        if self.cb.__name__ == "target":
            x = x + 1
        return x * 2
```

Guards are not strings Dynamo evals. They are a tree of guard managers, one
node per value, and the edge from a parent node to a child is an ACCESSOR: the
one step that gets from the parent's value to the child's ("look up key `cb`",
"read attribute `__name__`"). The checks themselves (TYPE_MATCH, EQUALS_MATCH)
hang off the node whose value they test, and a check walks the tree top down:
fetch `self` from the frame's locals, take its `__dict__`, look up `cb` in it,
getattr `__name__`, compare. A method has no `__name__` of its own; Python
forwards `method.__name__` to `method.__func__.__name__`. The tree does not see
that hop, so the guard hangs directly off the method's node (TORCH_LOGS=guards):

```python
L['self']              accessed_by FrameLocalsGuardAccessor('self')  # the module
  L['self'].__dict__   accessed_by GetGenericDictGuardAccessor      # nn.Module attrs live here
    L['self'].cb       accessed_by DictGetItemGuardAccessor('cb')   # the bound method
      L['self'].cb.__name__  accessed_by GetAttrGuardAccessor(__name__)
        EQUALS_MATCH: == 'target'
```

Two earlier rules meet here. `_reduce_bound_method` saves a method whose name
does not resolve back on the receiver (`Recv` has no `cb`) explicitly as the
pair `(func, receiver)`, so pickle goes on to serialize `wrapper` as a value.
The fqn-mismatch rule then rebuilds a function from its code object if it is
in `guard_tree_values` and replaces it with `_Missing("fqn mismatch")` if not.
The builder registers the value of each node it builds through
`get_guard_manager_from_source` (the `__dict__` node is created inline by
`get_generic_dict_manager` and is not registered, which changes nothing here):

```python
L['self']              -> the module         registered
L['self'].__dict__     -> the module's dict  not registered (inline node)
L['self'].cb           -> the bound method   registered
L['self'].cb.__name__  -> 'target'           registered
wrapper                                      NOT registered
```

The function is consulted only by CPython's attribute forwarding while the
`GetAttrGuardAccessor(__name__)` accessor runs, never as a node's value. So the
function the guard depends on is exactly what the pruning rule sees as
untouched. At load the tree is rebuilt by walking the same four steps on the
reconstructed locals to re-derive each node's value, and the last step does:

```python
method = types.MethodType(_Missing("fqn mismatch"), Recv())
method.__name__     # AttributeError while the guard manager is rebuilt
```

The seed cannot live in the reducer. Pickle memoizes every object the first
time it meets it, and it walks the module `__dict__` in insertion order:

```python
self.other = wrapper                          # plain attribute, inserted first
self.cb = types.MethodType(wrapper, Recv())
```

Pickle reaches `wrapper` through `other`, writes the sentinel and memoizes
that by identity; when the reducer later sees `cb` and registers the function,
pickle only emits a back-reference to the sentinel already written. A seed in
`pickle_guards_state`'s leaf loop is no better, since a method inside an
attribute is not a leaf of the local scope.

Register the method's `__func__` where the method's own guard manager is
built, in `GuardBuilder.get_guard_manager_from_source`. Every method anywhere
in the guard tree passes there before anything is pickled, and guard state is
pickled exactly once per builder, so that single seed covers every path pickle
can take to the function:

```python
example_value = self.get(source)
self.guard_tree_values[id(example_value)] = example_value
if self.save_guards and inspect.ismethod(example_value):
    func = example_value.__func__
    if inspect.isfunction(func):
        self.guard_tree_values[id(func)] = func
```

Only a plain function is seeded: `MethodType` accepts any callable, and a
`functools.partial` or builtin `__func__` cannot be rebuilt by value, so
seeding it would just make `_prune` carry it verbatim wherever else it
appears.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py -k test_guard_rooted_at_fqn_mismatched_bound_method
python test/dynamo/test_package.py -k test_bound_method_name_guard_survives_func_reached_first
```

Both targeted tests error on the previous commit. The test_package test drives
a full `caching_precompile` save and reload with the function reached first,
under `fail_on_recompile`, then renames the function's `__name__` and checks
the reloaded guard rejects (a `fail_on_recompile` RuntimeError), so it pins
that the guard really reads the rebuilt function rather than that nothing
crashed.

Authored with an AI assistant.

Pull Request resolved: #196481
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196505, #196470, #196471, #196472, #196473, #196474, #196476, #196478, #196479
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…t of snapshots, guard the 3.14 annotation read

Follow-up to the reviews of #196476, #196478 and #196479.

`_keep_container_verbatim` decided a plain tuple in two steps: is it in
`guard_tree_values`, and is it in `value_guarded_containers`. The second alone
is the rule; the first held because `EQUALS_MATCH` registers the value it
reads, a separate invariant whose failure would be the silent forever-miss the
rule exists to prevent. The tuple case now reads the recording alone:

```python
if type(container) is tuple:
    return id(container) in self.value_guarded_containers
if type(container) is dict:
    return False
return self._keep(container)
```

A globals snapshot kept `__builtins__` "as read" when some guard had registered
it and replaced it with the `builtins` module only when pruned. For an imported
module `f_globals["__builtins__"]` IS `builtins.__dict__`, the dict every
compile that guards a builtin registers, so the kept branch was the common one
and each snapshot carried all of builtins (about 6 KB, 155 keys) next to the
filtered copy `G` already holds; the two are distinct objects, so pickle does
not share them. The entry is now always the module, pickled by reference.
`FunctionType` accepts either.

`_read_raw_annotations` asked `annotationlib` for FORWARDREF annotations on
3.14 unguarded. FORWARDREF reruns the annotate function with every NAME lookup
proxied, so it absorbs a missing name, a raising attribute or a raising call,
but a sub-expression with no name in it still raises out of it:

```python
def f(x: f"{Missing}"):   # TypeError: Cannot stringify annotation containing string formatting
def f(x: ()[0]):          # IndexError
```

That would fail the dump for a slot the prune exists to make optional; the
read now returns an empty set instead. The 3.14 path had no test at all, since
every annotation in the suite either was an assigned dict or resolved; a
3.14-gated test now pins that a TYPE_CHECKING-only name comes back as a pruned
proxy and the f-string case drops the set (CI runs this file on 3.14; there is
no local 3.14 build).

`_missing` uses `torch.utils._functools.cache_method`, the in-tree per-method
cache that does not pin `self`, in place of a hand-rolled dict.

Test and comment cleanups: the guarded-defaults test names the full-compile
round trip that can tell a whole-container guard from a per-element one instead
of forward-referencing it; the two snapshot tests capture the module dict's key
set BEFORE the dump, since a `CleanupHook` for a traced code object can drop a
`__builtins_dict___N` key out of the live dict during the load; the
`name_beside_unpicklable_default` subtest says it prunes only because the
harness drops the `bind_args` guard; the pickler `__init__` comment no longer
claims omitting the recording prunes every container.

One #196476 comment is not a change here: the AOT pickler's own by-value
reducer carried only `__defaults__` at that commit, so an AOT-rebuilt helper
lost `__kwdefaults__` and `__dict__` and its `__name__` was the qualname.
#196685 and the commits above it move that pickler onto the shared base, which
is where those are fixed in this stack.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k snapshot -k verbatim -k type_checking_only
python test/dynamo/test_aot_compile.py -k Pickler
python test/dynamo/test_package.py
```

The two snapshot tests, the verbatim-rule tests and the `__builtins__` change
pass on the previous commit as well (the rule and the module are behaviourally
the same for every recorded tuple and every imported module); the
TYPE_CHECKING test is 3.14-only and runs in CI.

Authored with an AI assistant.


ghstack-source-id: 3992d8d
Pull-Request: #196767
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…t of snapshots, guard the 3.14 annotation read

Follow-up to the reviews of #196476, #196478 and #196479.

`_keep_container_verbatim` decided a plain tuple in two steps: is it in
`guard_tree_values`, and is it in `value_guarded_containers`. The second alone
is the rule; the first held because `EQUALS_MATCH` registers the value it
reads, a separate invariant whose failure would be the silent forever-miss the
rule exists to prevent. The tuple case now reads the recording alone:

```python
if type(container) is tuple:
    return id(container) in self.value_guarded_containers
if type(container) is dict:
    return False
return self._keep(container)
```

A globals snapshot kept `__builtins__` "as read" when some guard had registered
it and replaced it with the `builtins` module only when pruned. For an imported
module `f_globals["__builtins__"]` IS `builtins.__dict__`, the dict every
compile that guards a builtin registers, so the kept branch was the common one
and each snapshot carried all of builtins (about 6 KB, 155 keys) next to the
filtered copy `G` already holds; the two are distinct objects, so pickle does
not share them. The entry is now the module, pickled by reference, whenever
the dict has one; a hand-built globals dict without the key stays without it,
since `FunctionType` falls back to the loading frame's builtins and a guard on
the dict's shape must see the same keys. `FunctionType` accepts either value.
The slot is exempt from the keep contract, and the saving is for a
cross-module snapshot: a snapshot of the traced module's own dict carries
`builtins.__dict__` anyway under `__builtins_dict___N`.

`_read_raw_annotations` asked `annotationlib` for FORWARDREF annotations on
3.14 unguarded. FORWARDREF reruns the annotate function with every NAME lookup
proxied, so it absorbs a missing name, a raising attribute or a raising call,
but a sub-expression with no name in it still raises out of it:

```python
def f(x: f"{Missing}"):   # TypeError: Cannot stringify annotation containing string formatting
def f(x: ()[0]):          # IndexError
```

That would fail the dump for a slot the prune exists to make optional; the
read now returns an empty set instead, with a debug log naming the code
object. Dropping the whole set cannot silently break a guard: a guard rooted at
`fn.__annotations__` evaluated them at trace time (the VALUE format, cached on
the function), so a read that raises at dump time is one no guard performed. The 3.14 path had no test at all, since
every annotation in the suite either was an assigned dict or resolved; a
3.14-gated test now pins that a TYPE_CHECKING-only name comes back as a pruned
proxy and the f-string case drops the set (CI runs this file on 3.14; there is
no local 3.14 build).

`_missing` uses `torch.utils._functools.cache_method`, the in-tree per-method
cache that does not pin `self`, in place of a hand-rolled dict.

Test and comment cleanups: the guarded-defaults test names the full-compile
round trip that can tell a whole-container guard from a per-element one instead
of forward-referencing it; the two snapshot tests capture the module dict's key
set BEFORE the dump, since a `CleanupHook` for a traced code object can drop a
`__builtins_dict___N` key out of the live dict during the load; the
`name_beside_unpicklable_default` subtest says it prunes only because the
harness drops the `bind_args` guard; the pickler `__init__` comment no longer
claims omitting the recording prunes every container.

One #196476 comment is not a change here: the AOT pickler's own by-value
reducer carried only `__defaults__` at that commit, so an AOT-rebuilt helper
lost `__kwdefaults__` and `__dict__` and its `__name__` was the qualname.
#196685 and the commits above it move that pickler onto the shared base, which
is where those are fixed in this stack.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k snapshot -k verbatim -k type_checking_only -k without_builtins
python test/dynamo/test_aot_compile.py -k Pickler
python test/dynamo/test_package.py
```

The preserves-module snapshot test now also asserts the rebuilt scope's
`__builtins__` is the module, and a new test builds a function over a globals
dict without the key and checks the snapshot does not add one; the
verbatim-rule tests pass on the previous commit as well (the rule is
behaviourally the same for every recorded tuple); the TYPE_CHECKING test is
3.14-only and runs in CI.

Authored with an AI assistant.

ghstack-source-id: 184947b
Pull-Request: #196767
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…t of snapshots, guard the 3.14 annotation read

Follow-up to the reviews of #196476, #196478 and #196479.

`_keep_container_verbatim` decided a plain tuple in two steps: is it in
`guard_tree_values`, and is it in `value_guarded_containers`. The second alone
is the rule; the first held because `EQUALS_MATCH` registers the value it
reads, a separate invariant whose failure would be the silent forever-miss the
rule exists to prevent. The tuple case now reads the recording alone:

```python
if type(container) is tuple:
    return id(container) in self.value_guarded_containers
if type(container) is dict:
    return False
return self._keep(container)
```

A globals snapshot kept `__builtins__` "as read" when some guard had registered
it and replaced it with the `builtins` module only when pruned. For an imported
module `f_globals["__builtins__"]` IS `builtins.__dict__`, the dict every
compile that guards a builtin registers, so the kept branch was the common one
and each snapshot carried all of builtins (about 6 KB, 155 keys) next to the
filtered copy `G` already holds; the two are distinct objects, so pickle does
not share them. The entry is now the module, pickled by reference, whenever
the dict has one; a hand-built globals dict without the key stays without it,
since `FunctionType` falls back to the loading frame's builtins and a guard on
the dict's shape must see the same keys. `FunctionType` accepts either value.
The slot is exempt from the keep contract, and the saving is for a
cross-module snapshot: a snapshot of the traced module's own dict carries
`builtins.__dict__` anyway under `__builtins_dict___N`.

`_read_raw_annotations` asked `annotationlib` for FORWARDREF annotations on
3.14 unguarded. FORWARDREF reruns the annotate function with every NAME lookup
proxied, so it absorbs a missing name, a raising attribute or a raising call,
but a sub-expression with no name in it still raises out of it:

```python
def f(x: f"{Missing}"):   # TypeError: Cannot stringify annotation containing string formatting
def f(x: ()[0]):          # IndexError
```

That would fail the dump for a slot the prune exists to make optional; the
read now returns an empty set instead, with a debug log naming the code
object. Dropping the whole set cannot silently break a guard: a guard rooted at
`fn.__annotations__` evaluated them at trace time (the VALUE format, cached on
the function), so a read that raises at dump time is one no guard performed. The 3.14 path had no test at all, since
every annotation in the suite either was an assigned dict or resolved; a
3.14-gated test now pins that a TYPE_CHECKING-only name comes back as a pruned
proxy and the f-string case drops the set (CI runs this file on 3.14; there is
no local 3.14 build).

`_missing` uses `torch.utils._functools.cache_method`, the in-tree per-method
cache that does not pin `self`, in place of a hand-rolled dict.

Test and comment cleanups: the guarded-defaults test names the full-compile
round trip that can tell a whole-container guard from a per-element one instead
of forward-referencing it; the two snapshot tests capture the module dict's key
set BEFORE the dump, since a `CleanupHook` for a traced code object can drop a
`__builtins_dict___N` key out of the live dict during the load; the
`name_beside_unpicklable_default` subtest says it prunes only because the
harness drops the `bind_args` guard; the pickler `__init__` comment no longer
claims omitting the recording prunes every container.

One #196476 comment is not a change here: the AOT pickler's own by-value
reducer carried only `__defaults__` at that commit, so an AOT-rebuilt helper
lost `__kwdefaults__` and `__dict__` and its `__name__` was the qualname.
#196685 and the commits above it move that pickler onto the shared base, which
is where those are fixed in this stack.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k snapshot -k verbatim -k type_checking_only -k without_builtins
python test/dynamo/test_aot_compile.py -k Pickler
python test/dynamo/test_package.py
```

The preserves-module snapshot test now also asserts the rebuilt scope's
`__builtins__` is the module, and a new test builds a function over a globals
dict without the key and checks the snapshot does not add one; the
verbatim-rule tests pass on the previous commit as well (the rule is
behaviourally the same for every recorded tuple); the TYPE_CHECKING test is
3.14-only and runs in CI.

Authored with an AI assistant.

ghstack-source-id: 1303c5d
Pull-Request: #196767
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…t of snapshots, guard the 3.14 annotation read

Follow-up to the reviews of #196476, #196478 and #196479.

`_keep_container_verbatim` decided a plain tuple in two steps: is it in
`guard_tree_values`, and is it in `value_guarded_containers`. The second alone
is the rule; the first held because `EQUALS_MATCH` registers the value it
reads, a separate invariant whose failure would be the silent forever-miss the
rule exists to prevent. The tuple case now reads the recording alone:

```python
if type(container) is tuple:
    return id(container) in self.value_guarded_containers
if type(container) is dict:
    return False
return self._keep(container)
```

A globals snapshot kept `__builtins__` "as read" when some guard had registered
it and replaced it with the `builtins` module only when pruned. For an imported
module `f_globals["__builtins__"]` IS `builtins.__dict__`, the dict every
compile that guards a builtin registers, so the kept branch was the common one
and each snapshot carried all of builtins (about 6 KB, 155 keys) next to the
filtered copy `G` already holds; the two are distinct objects, so pickle does
not share them. The entry is now the module, pickled by reference, whenever
the dict has one; a hand-built globals dict without the key stays without it,
since `FunctionType` falls back to the loading frame's builtins and a guard on
the dict's shape must see the same keys. `FunctionType` accepts either value.
The slot is exempt from the keep contract, and the saving is for a
cross-module snapshot: a snapshot of the traced module's own dict carries
`builtins.__dict__` anyway under `__builtins_dict___N`.

`_read_raw_annotations` asked `annotationlib` for FORWARDREF annotations on
3.14 unguarded. FORWARDREF reruns the annotate function with every NAME lookup
proxied, so it absorbs a missing name, a raising attribute or a raising call,
but a sub-expression with no name in it still raises out of it:

```python
def f(x: f"{Missing}"):   # TypeError: Cannot stringify annotation containing string formatting
def f(x: ()[0]):          # IndexError
```

That would fail the dump for a slot the prune exists to make optional; the
read now returns an empty set instead, with a debug log naming the code
object. The guard covers the FORWARDREF read only: the AOT caller's
`evaluate=True` read is left raising, since it logs its own drop with the
reason it saw. Dropping the whole set cannot silently break a guard: a guard rooted at
`fn.__annotations__` evaluated them at trace time (the VALUE format, cached on
the function), so a read that raises at dump time is one no guard performed. The 3.14 path had no test at all, since
every annotation in the suite either was an assigned dict or resolved; a
3.14-gated test now pins that a TYPE_CHECKING-only name comes back as a pruned
proxy and the f-string case drops the set (CI runs this file on 3.14; there is
no local 3.14 build).

`_missing` uses `torch.utils._functools.cache_method`, the in-tree per-method
cache that does not pin `self`, in place of a hand-rolled dict.

Test and comment cleanups: the guarded-defaults test names the full-compile
round trip that can tell a whole-container guard from a per-element one instead
of forward-referencing it; the two snapshot tests capture the module dict's key
set BEFORE the dump, since a `CleanupHook` for a traced code object can drop a
`__builtins_dict___N` key out of the live dict during the load; the
`name_beside_unpicklable_default` subtest says it prunes only because the
harness drops the `bind_args` guard; the pickler `__init__` comment no longer
claims omitting the recording prunes every container.

One #196476 comment is not a change here: the AOT pickler's own by-value
reducer carried only `__defaults__` at that commit, so an AOT-rebuilt helper
lost `__kwdefaults__` and `__dict__` and its `__name__` was the qualname.
#196685 and the commits above it move that pickler onto the shared base, which
is where those are fixed in this stack.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k snapshot -k verbatim -k type_checking_only -k without_builtins
python test/dynamo/test_aot_compile.py -k Pickler
python test/dynamo/test_package.py
```

The preserves-module snapshot test now also asserts the rebuilt scope's
`__builtins__` is the module, and a new test builds a function over a globals
dict without the key and checks the snapshot does not add one; the
verbatim-rule tests pass on the previous commit as well (the rule is
behaviourally the same for every recorded tuple); the TYPE_CHECKING test is
3.14-only and runs in CI.

Authored with an AI assistant.

ghstack-source-id: 9fb6e95
Pull-Request: #196767
pytorchmergebot pushed a commit that referenced this pull request Sep 12, 2026
…y, pin the dict-served case (#196764)

Follow-up to the reviews of #196473 and #196474.

`_reduce_bound_method` read `func.__name__` before its `try`. `getattr` with a
default swallows only AttributeError, and `__func__` is an arbitrary callable
by the reducer's own premise, so a proxy that raises anything else escaped the
reducer while the receiver-side probe two lines down was already guarded:

```python
class ProxyFunc:
    def __getattr__(self, name):
        raise RuntimeError(f"proxy has no {name}")

pickler._reduce_bound_method(types.MethodType(ProxyFunc(), Plain()))
# before: RuntimeError: proxy has no __name__
# now:    (_unpickle_bound_method, (ProxyFunc(), Plain()))
```

The read moves inside the `try`, after the `__getattr__` gate (which takes the
pair without probing `func` at all), where `explicit` is already built for the
`except` to return.

The `__dict__` half of the per-instance condition had no test: `SlottedByName`
has no instance dict, so the slot test lands on the `getattr_static` half, and
ablating the `__dict__` clause left the suite green while the shape it exists
for broke at load:

```python
obj = Plain()
obj.global_add = types.MethodType(global_add, obj)
# with the clause:    loads back as MethodType(global_add, Plain)
# without the clause: AttributeError: 'Plain' object has no attribute 'global_add'
```

Pinned now, and the comment says which receivers reach that clause: one that
HAS an instance dict, which a pure-slots receiver does not (a slotted subclass
of a non-slotted base has both, and either clause gives the same answer), and a
class defining `__getattr__` (every nn.Module) takes the pair before it either
way.

Two tests from #196474 were not pinning what they said. The shared-closure-cell
test used a `<locals>` pair, whose branch returns before the `guard_tree_values`
gate, so the dict it built was inert and the test passed on the parent; it now
uses two module-level `functools.wraps` wrappers sharing one cell, which only
the gate carries. The module-method test's comment described the `<locals>`
rebuild bug from the commit that fixed it; the comment is gone and the test
asserts the rebuilt function's `__name__` is `forward`, which is a record of
what the rebuild carries rather than a regression guard (the name path is
pinned by `test_rebuilt_locals_function_keeps_its_name`), so the comment now
points at the call as the assertion that catches the placeholder.

Type nits from the same reviews: `object` instead of `Any` for the resolution
walk and both rebuilt scopes; the bound-method reducer returns its real shape,
`tuple[Callable[..., Any], tuple[Any, ...]] | None`; the state tuple stays
`Any`, since its elements are assigned to typed function slots and the checker
rejects `object` there.

One #196474 comment is not a code change here: at that commit the by-value
payload carried every closure cell and default unconditionally, so a `wraps`
wrapper capturing a lock no guard read failed the dump. #196476, two commits
above it, prunes each cell and default through the same `guard_tree_values`
test, and that is where the prune lives in this stack.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k bound_method -k shared_closure_cell
python test/dynamo/test_aot_compile.py -k Pickler
```

The proxy test fails on the previous commit with the RuntimeError above. Its
second case pins the ORDERING rather than the `try`: the receiver is a proxy
whose class defines `__getattr__`, so the gate takes the pair and the name is
never asked for, which the fixture records; moving the read back above the gate
fails that assertion while the rest of the test stays green. The
monkeypatched-method test fails against the `__dict__` clause ablated. The
shared-cell test fails when the fqn-mismatched pair is not in
`guard_tree_values` (both prune to `_Missing`), which the old `<locals>` pair
could not show.

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #196764
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688, #196691, #196692, #196693, #196756
pytorchmergebot pushed a commit that referenced this pull request Sep 14, 2026
…t of snapshots, guard the 3.14 annotation read (#196767)

Follow-up to the reviews of #196476, #196478 and #196479.

`_keep_container_verbatim` decided a plain tuple in two steps: is it in
`guard_tree_values`, and is it in `value_guarded_containers`. The second alone
is the rule; the first held because `EQUALS_MATCH` registers the value it
reads, a separate invariant whose failure would be the silent forever-miss the
rule exists to prevent. The tuple case now reads the recording alone:

```python
if type(container) is tuple:
    return id(container) in self.value_guarded_containers
if type(container) is dict:
    return False
return self._keep(container)
```

That is a behaviour change for the case the two invariants disagree on: a
recorded tuple with no tree entry was pruned per value and is now carried
whole. A test builds exactly that state, and it fails on the previous commit.

A globals snapshot kept `__builtins__` "as read" when some guard had registered
it and replaced it with the `builtins` module only when pruned. For an imported
module `f_globals["__builtins__"]` IS `builtins.__dict__`, and a traced
module's own dict binds that same object a second time under the
`__builtins_dict___N` Dynamo installs; that dict is the one a saved
BUILTIN_MATCH guard registers, so wherever one is saved the kept branch was
taken and the snapshot carried all of builtins (about 6 KB) next to
the filtered copy `G` already holds. The live builtins dict is now exempt from
the keep contract by value rather than by name, so every slot holding it -- the
alias included -- travels as a reference resolved in the loading process rather
than as a copy, one shared `_LiveBuiltins` standing for it so a second slot in
the same scope is a pickle memo reference rather than a second reduce. On a
scope carrying both keys that takes the dump from 6781 bytes to 729; a
cross-module snapshot, which has only `__builtins__`, goes from 6758 to 706.
The slot stays a dict, since a guard may have walked through it and rebakes
against whatever it holds at load. A dict without the key stays without
one, since `FunctionType` falls back to the loading frame's builtins and a
guard on the dict's shape must see the same keys; `FunctionType` accepts either
value. The key set is the module dict's at save time, names Dynamo installed
into it included, so such a guard is only as portable as those names.

The snapshot loop iterated the live module dict. A `CleanupHook` pops the name
it owns, and it fires from a weakref callback (`CleanupManager` holds a
`weakref.ref` per traced code object, whose callback runs the hooks attached to
it), so a code object collected during the dump pops a `__compiled_fn_N` or
`__builtins_dict___N` key mid-loop and the next iteration raises `RuntimeError:
dictionary changed size during iteration`. The loop now walks a copy,
`dict(f_globals)`, which also makes the sentence above literally true: the key
set is the one the loop entered with, not whatever survived to its end.
The rarity is not the loop's own doing -- measured with `gc.callbacks`,
snapshotting a scope of 80 `nn.Linear`s runs 82 iterations and takes zero
automatic collections at the default gen-0 threshold (zero at 300, one at 10),
since it allocates almost nothing GC-tracked. What decides whether a callback
lands inside the loop is where the process-wide gen-0 counter already stood when
the dump began. Scanning that offset with default thresholds and no forced
collection, 1 of 200 positions raises against the live dict, and 0 of 200 once
the loop walks a copy; being a flake rather than a reproducible failure is why
the test forces the hook to fire from the loop's first `_prune` call instead of
waiting for a collection. The copy is `dict(f_globals)` rather than
`list(f_globals.items())`: at a gen-0 threshold of 1, where a callback popping a
key raises out of a live `for k, v in d.items()` loop in all 50 trials, neither
spelling raises once, and the dict copy is shorter and materializes no N-entry
list of 2-tuples.

The 6 KB is a snapshot's cost, and `_reduce_function_by_value` builds a snapshot
only for a function whose own `__globals__` is registered too. A plain
`CompilePackage` compile
(`torch._dynamo.optimize("eager", package=CompilePackage(fn))`) applies no guard
filter and keeps that BUILTIN_MATCH, so building its manager registers the dict
the guard reads through -- but the traced function's module dict is not
registered there, so no snapshot is built at all. Reading a global through a
function's `__globals__` does register that dict, and it also guards the
function itself with a CLOSURE_MATCH, which `serialize_guards` refuses
outright, so with no filter at all an artifact built that way bypasses rather
than saving. The 6 KB is paid where a caller-supplied `guard_filter_fn` drops
that function guard and keeps the BUILTIN_MATCH: there the parent embedded the
whole dict and the exemption hands back a reference instead. Both high-level
entry points filter the BUILTIN_MATCH away instead -- `aot_compile`'s default
`guard_filter_fn` drops every `is_global` entry and the alias's BUILTIN_MATCH is
one, and `caching_precompile=True` drops it as ID_MATCH-derived -- so under them
nothing registers `builtins.__dict__` and the parent embedded no copy of it: it
pruned the alias slot to a sentinel and replaced `__builtins__` with the
builtins module. There the exemption instead hands those slots back the live
dict, 772 bytes to 729 on the same scope, which the same rebake argument covers.

On 3.14 the guard pickler read FORWARDREF annotations unguarded, so whatever
that read raised failed the dump. FORWARDREF reruns the annotate function, but
only NAME lookups are proxied -- the rest of the expression runs for real, so
whatever that real work raises comes out:

```python
def f(x: f"{Missing}"):    # TypeError: the proxy refuses __format__
def f(x: ()[0]):           # IndexError: no proxy is involved at all
def f(x: "%s" % Missing):  # reads fine -- it is the operation, not the name
```

That would fail the dump for a slot the prune exists to make optional, so
`_reduce_function_by_value` drops the whole set instead, with a debug log naming
the code object by `co_qualname` where the runtime has one and by `co_name` on
3.10. That log line repeats the AOT pickler's `_pickleable_annotations` one
rather than sharing it: the two handlers differ in policy (that one swallows a
RecursionError too, and afterwards drops unpicklable values key by key instead
of sentinelling them) and each logs under its own module's logger, which is what
tells the two drops apart in a `TORCH_LOGS` run, so what is left to share is a
format string. The handler sits at that caller
rather than inside the shared
`_read_raw_annotations`, which stays a pure reader raising for either format:
the other caller, the AOT pickler's `evaluate=True` one, already handles its own
read (it logs the reason it saw), so a keyword that selects a format does not
also select an error policy. A RecursionError is re-raised rather than dropped:
it is the dump's own limit, which `pickle_guards_state` reports as a bypass, not
a property of the annotation, and swallowing it would drop a set that reads fine
at any other depth. Dropping the whole set cannot silently break a guard: a
guard rooted at `fn.__annotations__` evaluated them at trace time (the VALUE
format, cached on the function), so a read that raises at dump time is one no
guard performed. The 3.14 path had no test at all, since every annotation in the
suite either was an assigned dict or resolved; a 3.14-gated test now pins that
the TYPE_CHECKING-only name is genuinely unreadable outside the FORWARDREF read
-- a direct `__annotations__` read raises `NameError`, a premise pruning to a
sentinel cannot tell from a resolved class -- and that the f-string case drops
the set (CI runs this file on 3.14; there is no local 3.14 build).

Test and comment cleanups: the guarded-defaults test names the full-compile
round trip that can tell a whole-container guard from a per-element one instead
of forward-referencing it; the two snapshot tests assert on names their
module cannot lose instead of comparing whole key sets against a live module
dict a `CleanupHook` can pop from; the
`name_beside_unpicklable_default` subtest now says why the default prunes,
which is that `bind_args` guards `__defaults__` with SEQUENCE_LENGTH and only
`EQUALS_MATCH` records a tuple in `value_guarded_containers`, so a length guard
survives per-value pruning; the pickler `__init__` comment no longer claims
omitting the recording prunes every container; the snapshot comment names both
regimes whose guard filter drops the alias's BUILTIN_MATCH; and the annotations
comment says what the keep branch there is for, which is a dict SUBCLASS assigned
onto `__annotations__` that a guard registered (an exact dict is never carried
whole on any version, and on 3.14 the read hands back a copy, so neither is a
subclass one) -- the branch stays, since deleting it would prune that mapping
per value and rebuild it as a plain dict. The snapshot comment also says what
the exemption costs, which is that a guard walking the slot rebakes against the
loading process's builtins rather than the binding the compile saw; and the two
builtins tests pin the reference identity alone, since a copy cannot be `is` the
live dict, while an absolute byte bound over a stream whose size depends on the
pickle protocol and the per-version `SerializedCode` payload adds nothing to it.

Kept as one commit rather than split three ways along the paragraphs above (the
tuple rule, the builtins exemption, the annotation guard are independent and
each carries its own test): this is the bottom PR of an already-submitted
pickler stack, so splitting it rebases and renumbers every PR above it; what
that buys is a finer bisect over three changes that already sit in disjoint
functions and cannot interact.

One #196476 comment is not a change here: the AOT pickler's own by-value
reducer carried only `__defaults__` at that commit, so an AOT-rebuilt helper
lost `__kwdefaults__` and `__dict__` and its `__name__` was the qualname.
#196685 and the commits between it and this one moved that pickler onto the
shared base, which is where those are already fixed.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k test_snapshot_survives_a_cleanup_hook_pop_during_the_loop
python test/dynamo/test_guard_serialization.py -k snapshot -k verbatim -k alias -k unresolvable_annotation -k raising_annotation_read -k without_builtins -k length_guarded -k name_beside_unpicklable_default
python test/dynamo/test_aot_compile.py -k Pickler
python test/dynamo/test_package.py
```

The preserves-module snapshot test asserts the rebuilt scope's `__builtins__`
comes back as whatever the live dict held (the module when this file runs as
`__main__`, the builtins dict when it is imported), and another pins the alias
slot: with the exemption keyed on the name that slot arrives as a copy of the
whole builtins dict, not the live dict. Six of the seven new tests fail on the
previous commit: that alias one,
`test_snapshot_of_an_unguarded_builtins_dict_stays_a_dict`,
`test_a_recorded_tuple_is_kept_verbatim_without_a_tree_entry` (the behaviour
change above), `test_a_raising_annotation_read_drops_the_set_but_not_a_recursion_error`
(the parent's read is unguarded and nothing on its save path catches it),
`test_snapshot_survives_a_cleanup_hook_pop_during_the_loop` (the parent builds
the snapshot as a comprehension over the same live dict) and, on a 3.14 shard,
`test_reduce_prunes_an_unresolvable_annotation_and_drops_a_raising_one`
via its f-string case. Only
`test_snapshot_of_a_scope_without_builtins_stays_without` passes there, and is
kept for the contract the exemption must not break: a scope that has no
`__builtins__` does not gain one. The TYPE_CHECKING test is 3.14-only and runs
in CI, while the raising-read test patches the read itself, so the drop, its log
and the RecursionError re-raise are covered on every shard, 3.10 included.

Authored with an AI assistant.

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

## FAQ

> **FAQ: why is this not three commits (tuple rule / builtins exemption / 3.14
> annotation guard)?** The three changes are independent, each already carries its
> own test, and the message's paragraphs are the seam -- but #196767 is the
> pre-existing bottom PR of the pickler stack, not part of the #195354 re-slice
> this round is doing. Splitting it renumbers and rebases every PR above it, and
> what that buys is a finer bisect over three behaviour changes that already sit in
> disjoint functions (`_keep_container_verbatim`, `_globals_snapshot`, the
> annotation read in `_reduce_function_by_value`) and cannot interact. The commit
> message keeps the three-way structure so a bisect landing here can tell which
> behaviour it is.

> **FAQ: isn't the `_keep_container_verbatim(raw_annotations)` keep branch dead code
> now?** No, only on 3.14. Below 3.14 the read hands back `fn.__annotations__`
> itself, and CPython lets that be a `dict` subclass; a subclass instance falls past
> the `type(container) is dict` rule to the identity check, so a guard-registered
> one is still carried whole (verified: it round-trips as the subclass, while
> unregistered it comes back a plain dict of sentinels). Deleting the call would
> silently change that case, so the call stays and the comment now states exactly
> when it fires instead of the misleading 3.14-specific parenthetical it replaced.

> **FAQ: the review asked for "FORWARDREF raises for an operation the proxy will
> not represent". Why does the comment say something else?** Because that is not
> the rule either, and the comment now has to be right in both directions. On
> 3.14.7 the discriminator is `_Stringifier.__format__`, which
> `annotationlib.py:520` raises from outright, not string formatting as a class:
> `f"{Missing}"` and `f"{Missing:>10}"` raise, while `f"{Missing!r}"`,
> `f"{Missing!s}"`, `f"{Missing=}"`, `"%s" % Missing` and `str(Missing)` all read
> fine and give `{'x': 'Missing'}` -- those convert to `str` before the format
> opcode, so the proxy's `__str__`/`__repr__` answers. And the proxy is not the
> only way out: `()[0]`, `1/0` and `{}["k"]` raise with no proxy involved at all,
> and `"".join([Missing])` raises from a real callee rejecting the proxy (`expected
> str instance, _Stringifier found`). One sentence covers all three: only NAME
> lookups are proxied, and the rest of the expression runs for real. That is what
> the comment now says, and it is why `[Missing][0]` -- an expression with real
> work that does not fail -- still reads back a `ForwardRef`.

> **FAQ: the review says the `expected_keys` assertions can flake in either
> direction. Isn't a `list()` at the capture the matching fix?** No, on both
> counts. `CleanupHook.__call__` only ever `pop`s and nothing on the dump path
> installs a name into a traced module dict, so the snapshot can only ever come
> back a subset of the captured key set -- one direction, not two. And a `list()`
> would not close it, because the hole is not inside an iteration: it is the gap
> between `expected_keys = set(g)` and the dump, on a dict that is this test
> module's live globals. That capture is itself a third exposure the finding did
> not name -- `set(g)` iterates the live dict, so a hook firing during that
> statement raises `RuntimeError` from the test body. Both tests therefore stop
> comparing whole key sets and assert `assertIn` on names their module cannot
> lose, which is what each was pinning (the module's own state arrived; the shared
> scope is not the half-loaded copy) without depending on a key Dynamo owns.

> **FAQ: Was `list(f_globals.items())` really exposed to a `CleanupHook` pop,
> and is that what `dict(f_globals)` fixes?**
>
> Measured on 3.12.14 with `gc.set_threshold(1, 1, 1)` and a `gc.callbacks`
> entry that pops a key out of a 5000-entry dict: a live
> `for k, v in d.items()` loop that allocates per step raises
> `RuntimeError: dictionary changed size during iteration` in all 50 trials,
> while `list(d.items())` and `dict(d)` each raise in 0 of 50 -- both see one
> or two collections during the call, but those land at a bytecode boundary
> outside the C-level copy rather than between two iterator steps. The window
> inside `list()` therefore did not reproduce on this interpreter, and the
> change is not a bug fix: the loop walks `dict(f_globals)` because it is the
> shorter spelling and materializes no N-entry list of 2-tuples, and the
> comment above it now claims only what the measurement supports, which is
> that iterating the LIVE dict while pruning is what raises.

> **FAQ: the annotation on `raw_annotations: dict[str, Any] = {}` is redundant
> and sits on the fallback rebinding -- the `try` binding two statements up
> already comes from `_read_raw_annotations`, declared `-> dict[str, Any]`, so
> drop it and leave `raw_annotations = {}`.** Declined: dropping it turns
> PYREFLY red. `pyrefly.toml:143-146` switches `implicit-any` on for
> `torch/_dynamo/**`, and pyrefly types each binding on its own rather than
> joining the branches, so a bare empty literal is an error regardless of what
> the other branch binds. Measured with pyrefly 0.58.0, the version pinned in
> `tools/linter/adapters/pyrefly_linter.py`, on a standalone reduction of
> exactly this shape (a `-> dict[str, Any]` callee in the `try`, a bare `= {}`
> in the `except`): `Cannot infer type of empty container; it will be treated
> as containing Any [implicit-any]` on the fallback line without the
> annotation, and clean with it. The callee's declared return type does not
> reach the `except` branch -- only a declaration gives `{}` a contextual type
> -- and `torch/_dynamo/guards.py` is otherwise clean today (`pyrefly check
> --config pyrefly.toml torch/_dynamo/guards.py` reports 0 errors, 28
> suppressed), so this would be a new error on a line the PR touches. The one
> variant that also measures clean is moving the annotation up onto the `try`
> binding; it was not taken because there it merely restates the callee's
> declared return type, whereas on the fallback it is the only binding pyrefly
> cannot infer.

> **FAQ: the review says the 3.14 test's fixture rots "if that name ever gets
> defined at this module's scope". Doesn't the new `NameError` assertion pin a
> premise that a stray `TYPE_CHECKING` import could already break?** No -- that
> particular vector cannot reach the fixture, and the assertion went in anyway
> because the rest of the finding is right. `inner` is built by `exec` into a fresh
> namespace, `ns = {"__name__": __name__}`
> (`test/dynamo/test_guard_serialization.py:1767`), so the annotate function's
> globals are `ns` and not this module's: measured on 3.14.7 with `class
> OnlyUnderTypeChecking` defined at the module scope of the running file,
> `inner.__annotate__.__globals__ is ns` is `True`, `"OnlyUnderTypeChecking" in ns`
> is `False`, and the direct read still raises `NameError: name
> 'OnlyUnderTypeChecking' is not defined`. The reachable rot is an edit to that
> seed dict or to the `exec` string. What does hold is the non-discrimination:
> every unguarded annotation prunes to a sentinel (`torch/_dynamo/guards.py:4535`
> over `_prune` at `:4380-4383`, which keeps only a literal or a guard-registered
> value), so measured on 3.12.14 a fully RESOLVED class annotation comes back
> `_Missing` as well, and the assertion at `:1787` could not tell a proxy from a
> resolved class. One line can: `inner.__annotations__` raising `NameError` before
> the dump, which is the exact premise `_read_raw_annotations` cites for asking for
> the FORWARDREF format at all (`torch/_dynamo/package.py:320-322`). It passes on
> the fixture as written and fails loudly on the seeded namespace.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #196767
Approved by: https://github.com/pytorchgreenlight
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1141/head branch November 18, 2026 01:46
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 Merged module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants