Skip to content

[dynamo] Carry a rebuilt function's container verbatim only when a guard reads its values - #196479

Closed
bobrenjc93 wants to merge 11 commits into
gh/bobrenjc93/1144/basefrom
gh/bobrenjc93/1144/head
Closed

bobrenjc93 wants to merge 11 commits into
gh/bobrenjc93/1144/basefrom
gh/bobrenjc93/1144/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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:

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:

# 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:

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:

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.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[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/196479

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

✅ No Failures

As of commit eaa2c98 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 of the new rule
    • _keep_container_verbatim (torch/_dynamo/guards.py:4379) narrows verbatim carry to _keep plus an EQUALS_MATCH-recorded plain tuple; every other function container is pruned per value.
    • I read all 37 register_guard_check_spec get_metadata_fns in guards.py; the ones reachable on a plain container key on length (_sequence_length), keys (DICT_KEYS_MATCH/MAPPING_KEYS_CHECK), type or a literal key, all of which survive per-value pruning.
    • CONSTANT_MATCH (guards.py:2984) delegates a non-bool non-None tuple to EQUALS_MATCH, so the recording at guards.py:2866 also covers wrap_listlike's CONSTANT_MATCH branch at variables/builder.py:2455.
  • Recording is save-path only and cannot go stale
    • guards.py:2866 gates on self.save_guards, and the pre-filter build passes save_guards=False (guards.py:4907), so a filtered-out guard leaves no entry behind.
    • build_guards constructs a fresh GuardBuilder per pass (guards.py:5204), and pickle_guards_state reads builder.value_guarded_containers off the same builder serialize_guards is handed (guards.py:4774, guards.py:5175).
    • The map holds the value, not just the id (guards.py:1392), so a recorded id cannot be reused while the builder lives.
  • Test coverage in both directions
    • Four _roundtrip_through_precompile tests (test/dynamo/test_guard_serialization.py:2046-2073) do a real torch.compile, save, torch._dynamo.reset, reload and require a hit under fail_on_recompile, with strict_precompile on for the class (test_guard_serialization.py:1697).
    • test_whole_defaults_equals_match_survives_a_called_default pins the verbatim carve-out while test_a_length_guarded_tuple_is_pruned_per_value and test_a_container_subclass_stays_verbatim pin the pruning side, so neither an over- nor under-carrying rule passes.
    • DynamoCache/PrecompileContext clears moved into TestGuardSerializationBase.setUp/tearDown (test_guard_serialization.py:987-996), matching TestPackage (test/dynamo/test_package.py:82-83) and running inside the fresh_cache() scope super().setUp() opens.
  • Scope
    • Non-test change is confined to torch/_dynamo/guards.py: one builder dict, one _keep_container_verbatim helper, and threading a fourth required positional into GuardsStatePickler; no public API or documented behavior changes.
    • All 24 GuardsStatePickler(...) call sites are updated to the new arity and every remaining one is in a test file, so a caller omitting the map is a TypeError rather than a silent prune-everything.

reason: clean
Reviewed commit: eaa2c98

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 PR #196479

  • Load PyTorch /pr-review guidelines
  • Read the diff vs origin/gh/bobrenjc93/1144/base
  • Analyze torch/_dynamo/guards.py changes
  • Analyze test coverage
  • Post review

View job run

[ghstack-poisoned]
@bobrenjc93 bobrenjc93 changed the title [dynamo] Prune a kept container per value when a guard is rooted at an element through it [dynamo] Carry a rebuilt function's container verbatim only when a guard reads its values 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 supersedes #196480; every finding of that review is resolved structurally by the redesign: no per-source edges, no __annotations__ read, one recording point in EQUALS_MATCH, tests that reload and require a hit). value_guarded_containers now holds the value by id so an id cannot be reused while the builder is alive.

@claude

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 44m 24s —— View job


Reviewed the redesign: no correctness defect found in the new rule, but the dict half of the recording predicate is unreachable, and two test comments still describe the superseded per-source-edge design from #196480.

PR Review: #196479 — details

Summary

Moves the "carry a rebuilt function's container verbatim" decision from "the container is in guard_tree_values" to "an EQUALS_MATCH read the container whole," recorded at GuardBuilder.EQUALS_MATCH into a new value_guarded_containers map keyed by id. I audited every @register_guard_check_spec guard's get_metadata_fn for the load-bearing assumption (that every non-EQUALS_MATCH guard reachable on a plain dict/tuple reads only length/keys/type, and so survives per-value pruning) and found no violation — SEQUENCE_LENGTH returns _sequence_length, DICT_KEYS_MATCH returns dict.keys, MAPPING_KEYS_CHECK returns .keys(), TYPE_MATCH returns type, and the rest are either tensor/global-state guards or in UNSUPPORTED_SERIALIZATION_GUARD_TYPES. The design is sound and strictly better than the base commit's registration test. The problems below are documentation accuracy and test hygiene.

Code Quality

  • torch/_dynamo/guards.py:2861 — if self.save_guards and type(val) in (dict, tuple): — the dict arm is unreachable. EQUALS_MATCH asserts its own allowlist a few lines down (guards.py:2923-2928): ok_types is built from common_constant_types | {type, tuple, frozenset, slice, range, dict_keys, torch.Size, ...} plus ok_mutable_types = (list, set). dict is in none of them, is not in pytree.CONSTANT_NODES, and is_opaque_constant_type rejects builtins — so a plain dict reaching EQUALS_MATCH (directly or via CONSTANT_MATCH, guards.py:2988) raises AssertionError(f"Unexpected type {type(val)}") before it could ever be consulted. The consequence is not a bug but it is the rule: no plain dict is ever carried verbatim now, for any of __kwdefaults__ / __dict__ / __annotations__. That happens to be correct, because a whole-dict comparison lowers to DICT_KEYS_MATCH plus a per-value EQUALS_MATCH on each DefaultsSource / AttrSource (variables/dicts.py:854 → polyfills/__init__.py:316 → variables/dicts.py:426), and every value a guard reads is registered in guard_tree_values and therefore kept. But the code and prose assert a symmetry that does not exist. Either drop dict from the tuple literal, or keep it and say why it can't fire; and state the dict rule as a fact in the Note rather than leaving a reader to infer it. Fix this →

  • torch/_dynamo/guards.py:4315-4322 and 4342-4358 — the Note and the _keep_container_verbatim docstring also overstate how broadly the tuple arm fires. The only path that installs a whole-tuple EQUALS_MATCH is wrap_listlike's CONSTANT_MATCH branch (variables/builder.py:2441-2447), gated on istype(value, tuple) and all(ConstantVariable.is_literal(item) ...) and self.source.guard_source.is_unspecialized_nn_module(). WholeDefaultsEqualsModule satisfies it only because impl hangs off an nn.Module; the same f.__defaults__ == (2.0, (1, 2)) on a module-level function goes element-wise through _seq_richcompare (variables/lists.py:395-440) and installs nothing on the tuple. Naming that one trigger in the docstring would stop a future reader from assuming whole-container equality generally lands here.

  • torch/_dynamo/guards.py:4171 — value_guarded_containers is a keyword-only param defaulting to None with or {}, while its three siblings (guard_tree_values, empty_values, missing_values) are required positionals. The docstring justifies it as "Absent for the pickler-level unit tests," i.e. production shape bent for test convenience. The failure mode of a call site omitting it is silent (prune everything → permanent cache miss), not a crash, which is exactly the class of bug this PR exists to eliminate. Since the ~20 existing GuardsStatePickler(gtv, {}, {}, buf) call sites are all in tests, making it a fourth required positional and updating them is mechanical and removes the footgun.

Testing

  • test/dynamo/test_guard_serialization.py:495-499 and 1959-1964 — both comments describe the superseded design from [dynamo] Record the container edge on __defaults__ and instance mappings, not just the base object #196480, not this one. The first says "The generic edge keys on the function, not its __dict__, so without the mapping edge the verbatim dict drags func.cache in"; the second says "The container->element edge is recorded on the source, not the element's value... Gating the edge on value is not None would carry the tuple verbatim." There are no per-source edges in this PR — the decision is one id() lookup in value_guarded_containers. Both tests remain worth keeping (the whole-dict-read shape and the cfg=None shape are real), but the rationale needs rewriting against the rule that actually ships, or the next reader will go looking for edge-recording code that does not exist. Fix this →

  • test/dynamo/test_guard_serialization.py:1912-1932 — _roundtrip_through_precompile mutates process-global state (DynamoCache, PrecompileContext) inline and never restores it: it clears both before the compile, clears PrecompileContext again mid-way, and leaves DynamoCache populated on exit. TestPackage handles the same globals in setUp (test/dynamo/test_package.py:71-76), and TestGuardSerialization's setUp does not. Four tests now call this helper, so cross-test leakage into the rest of the file is order-dependent and will be painful to debug when it bites. Move the clears into setUp/tearDown on the class.

Recommendation

Approve once the comment corrections land. The mechanism itself is right, the end-to-end coverage is genuinely stronger than the base commit's (the _roundtrip_through_precompile tests would fail loudly under fail_on_recompile if the tuple were wrongly pruned, so the recording line is exercised for real and not only through the hand-constructed value_guarded_containers in test_a_whole_tuple_guard_keeps_defaults_verbatim), and I could not construct a serializable guard that reads a plain container's element values without going through EQUALS_MATCH. The blocking-ish items are the two stale comments, which document a design that was replaced.

Note: this checkout has no built torch and python was not runnable, so I could not empirically confirm which guard fires for WholeDefaultsEqualsModule; the wrap_listlike/CONSTANT_MATCH path above is from static reading and should be sanity-checked against a TORCH_LOGS=guards run.

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

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Round-2 review follow-up: comments that still described the removed edge mechanism (a nonexistent 'DunderDict' guard, 'generic/mapping edge') are rewritten to what the guards actually are (a TYPE_MATCH registers the dict; the None default stays because it is a literal), test_fqn_mismatched_function_prunes_a_verbatim_dict_read is renamed ..._prunes_a_type_guarded_dict, and the message's negative-test count is corrected.

@claude

@claude

claude Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 20m 23s —— View job


Re-reviewed the round-2 follow-ups

  • Load PyTorch /pr-review guidelines
  • Read the current diff vs origin/gh/bobrenjc93/1144/base
  • Verify the round-2 follow-ups (rewritten comments, rename, corrected count)
  • Check remaining round-2 findings (unreachable dict arm, kwarg default, global-state leakage)
  • Post review

The rewritten comments now match the code — I independently traced each guard they name and all three claims hold — but the dict half of the recording predicate is still dead, and the value_guarded_containers kwarg default and _roundtrip_through_precompile's global-state mutation are unaddressed from round 2.

PR Review: #196479 (round 3) — details

Summary

Verification pass on the comment rewrites. I re-traced each guard the new comments name, from the bytecode-level VT path down to GuardBuilder, and all three rewritten claims are correct — including the two I could not confirm statically last round. What remains are the three items from round 2 that were not touched.

Verified: the rewritten comments are accurate

  • test_guard_serialization.py:494-496 (keep_whole_dict_attribute) — correct. type(func.__dict__) reaches BuiltinVariable.call_type (variables/builtin.py:2820-2844), which builds dict under TypeSource(AttrSource(fn, "__dict__")); dict is a class so install_guards(CLASS_MATCH) fires (variables/builder.py:2024), and id_match_unchecked rewrites a TypeSource-rooted guard into TYPE_MATCH on source.base (guards.py:2634-2638) — i.e. TYPE_MATCH on the __dict__ itself, which registers the mapping via get_guard_manager_from_source (guards.py:1722-1724). DunderDictVariable no-ops its keys/contains guards (variables/dicts.py:1765-1771), so nothing else lands on the dict. The old "DunderDict guard keeps the mapping verbatim" wording is gone and the replacement names the guard that actually fires.

  • test_guard_serialization.py:520-522 (WholeDefaultsEqualsModule) — correct, and the test is not vacuous. I was wrong to be unsure about the is_unspecialized_nn_module() gate last round: ChainedSource.guard_source delegates to its base (torch/_guards.py:1482-1484), so AttrSource(AttrSource(UnspecializedNNModuleSource(LocalSource("self")), "impl"), "__defaults__") carries LOCAL_UNSPECIALIZED_NN_MODULE all the way down. ConstantVariable.is_literal recurses into the nested (1, 2) (variables/constant.py:212-221), so wrap_listlike's gate at variables/builder.py:2441-2447 is satisfied and CONSTANT_MATCH → EQUALS_MATCH fires on the whole tuple, hitting the new recording line. Crucially, that branch returns TupleVariable([ConstantVariable.create(item) ...]) with sourceless items, so the subsequent == installs no per-element guards and (1, 2) never enters guard_tree_values; since a nested tuple is not a _is_literal (guards.py:4343), it would be pruned to _Missing without the verbatim carry. The test genuinely exercises guards.py:2863.

  • test_guard_serialization.py:1983-1985 (..._prunes_a_none_valued_guarded_default) — correct, including the filter. func.__defaults__[0] is None, which lands in wrap_literal's else branch (variables/builder.py:2916) and installs CONSTANT_MATCH; GuardFilterEntry.guard_type is guard.create_fn_name() (guards.py:4710), which is the constructed create_fn's name — "CONSTANT_MATCH" — not the NONE_MATCH it delegates to. So the harness filter keeps it. EQUALS_MATCH is never reached (guards.py:2985-2986), nothing is recorded, the tuple is pruned per value, and the None survives as a literal. Comment matches.

  • test_guard_serialization.py:461-462 (GuardedDefaultsTupleModule) and 1883-1887 — also accurate; the __kwdefaults__ half really is keys-plus-per-element rather than a whole-dict EQUALS_MATCH, and the note that the harness "registers every element it compares, so it cannot tell whether a whole-container guard survives pruning" is the right caveat to leave next to it.

Code Quality

  • torch/_dynamo/guards.py:2863 — the dict arm is still unreachable, and this round's own test comment now proves why. EQUALS_MATCH's allowlist assertion (guards.py:2925-2930) admits tuple, frozenset, dict_keys, torch.Size, list, set, common_constant_types (utils.py:2957-2981), pytree constant classes and opaque constant types — plain dict is in none, is not in CONSTANT_NODES, and is_opaque_constant_type rejects builtins. A plain dict raises before the recording could matter, and the builder that recorded it is discarded with the failed build (guards.py:5228, no handler), so no stale entry can survive. The reason is exactly what you now document at test_guard_serialization.py:461-462: a whole-dict comparison lowers to DICT_KEYS_MATCH plus per-value guards, never a whole-dict EQUALS_MATCH. Net effect: no plain dict is ever carried verbatim, for any of __kwdefaults__ / __dict__ / __annotations__. That is correct behavior, but the predicate should say so — make it type(val) is tuple, and state the dict rule as a fact in the Note (guards.py:4319-4326) and the _keep_container_verbatim docstring (guards.py:4353-4365) instead of implying dict/tuple symmetry. Fix this →

  • torch/_dynamo/guards.py:4353-4365 — the docstring still does not name the single path that installs a whole-tuple EQUALS_MATCH, and tracing it turned up the invariant that actually makes the rule sound. The only trigger is wrap_listlike's CONSTANT_MATCH branch (variables/builder.py:2441-2447), gated on istype(value, tuple) and all(ConstantVariable.is_literal(item) ...) and self.source.guard_source.is_unspecialized_nn_module(). That gate is also what makes the items sourceless, so the whole-container guard fires precisely in the case where no per-element sources exist to keep the elements. The mirror case confirms it: the same g.__defaults__ == (2.0, (1, 2)) on a module-level g fails the gate, decomposes through _seq_richcompare (variables/lists.py:377-440) over GetItemSource-backed lazies, and registers every element and the nested tuple in guard_tree_values (guards.py:1736), so per-value pruning keeps them anyway. Stating that — "whole-container EQUALS_MATCH is exactly the shape with no per-element sources" — is what stops a future reader from assuming whole-container equality generally lands here, and explains why both branches are safe.

  • torch/_dynamo/guards.py:4173 — unaddressed from round 2. value_guarded_containers is keyword-only with None + or {} while its three siblings are required positionals, justified as "Absent for the pickler-level unit tests" — production shape bent for test convenience. A call site that omits it prunes everything, which is a silent permanent cache miss rather than a crash: the exact failure class this PR exists to remove. The ~20 GuardsStatePickler(gtv, {}, {}, buf) sites are all tests; making it a fourth required positional is mechanical.

Testing

  • test/dynamo/test_guard_serialization.py:1929-1951 — unaddressed from round 2. _roundtrip_through_precompile mutates process-global state (DynamoCache.clear(), PrecompileContext.clear()) inline and never restores it, leaving DynamoCache populated on exit. TestPackage does this in setUp (test/dynamo/test_package.py:71-76); TestGuardSerializationBase.setUp (line 962) does not. Four tests call this helper now, so leakage into the rest of the file is order-dependent. Move the clears into setUp/tearDown.

  • The PR message's revised negative-test count ("seven of the thirteen") is not something I can verify — this checkout has no built torch, so I could not run either command. Worth a local confirmation before merge, since the claim is what establishes the tests are load-bearing.

Recommendation

Approve once the dict arm is narrowed and the docstring names its trigger. Both are documentation-and-one-token changes; the mechanism is correct as it stands, and the three test comments that motivated this round are now accurate against the shipped rule. The value_guarded_containers signature and the global-state leakage are pre-existing carryovers, not regressions from this round.

| Branch: `gh/bobrenjc93/1144/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:

test/dynamo/test_guard_serialization.py:1978-1982 still forward-references this change: "this test cannot tell a whole-container guard from a per-element one; a later commit in this stack adds a full-compile round trip that can." This is that commit -- test_whole_defaults_equals_match_survives_a_called_default is the round trip, and shape=(1, 2) is the non-literal default that makes it discriminating. Name it:

        # A rebuilt local function's __defaults__ and __kwdefaults__ (the latter
        # never carried before) round-trip and reject a change. Every default
        # here is a float, which _is_literal carries unconditionally, so this
        # test cannot tell a whole-container guard from a per-element one;
        # test_whole_defaults_equals_match_survives_a_called_default does.

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/guards.py
"""Whether a function container (__defaults__/__dict__/...) is carried whole
rather than pruned per value; the rule and its reasons are in the Note
[Reconstructing a function a guard is rooted at] above."""
if not self._keep(container):

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:

Decide the tuple case on the recording alone:

    def _keep_container_verbatim(self, container: object) -> bool:
        if type(container) is tuple:
            return id(container) in self.value_guarded_containers
        if type(container) is dict:
            return False
        return self._keep(container)

Identical today -- EQUALS_MATCH always reaches get_guard_manager, which registers the value in guard_tree_values, so a recorded tuple is always _keep-able -- but it drops the tuple branch's dependency on a second invariant whose failure mode is the silent forever-miss this change exists to prevent.

Comment thread torch/_dynamo/guards.py
self.tensor_converter = torch._subclasses.fake_tensor.FakeTensorConverter()
self.guard_tree_values = guard_tree_values
# The plain tuples an EQUALS_MATCH reads whole, by id; see the Note
# above _keep. Required, because omitting it silently prunes every

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 plain tuples an EQUALS_MATCH reads whole, by id; see the Note
        # above _keep. Required, because omitting it would carry no plain
        # tuple verbatim.

"every container per value" overstates the argument's reach: a plain dict is pruned per value with or without the map, and a dict/tuple subclass stays verbatim either way.

@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

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 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/1144/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