Skip to content

[dynamo] Rebuild a function a guard is rooted at from its code object - #196474

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

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

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Enabler for the precompile stack above this one.

pickle saves a function by NAME: it stores __module__ and __qualname__,
and at load imports the module and walks the dotted name. That is the cheap,
exact default -- the loaded function IS the one the serving process has -- and
it works only if walking the name lands back on the same function.
functools.wraps breaks that: it copies the wrapped function's __module__,
__qualname__, __name__, __doc__, __annotations__ (and __type_params__
on 3.12+) and __dict__ onto the wrapper, so the
wrapper CLAIMS to be the original and the original's name now resolves to the
wrapper. A module-level lambda (qualname <lambda>), an exec-created
function, or a __module__ of None have the same problem. Dynamo calls these
fqn mismatches, and until now the guard pickler replaced any such function
whose module was in sys.modules with a _Missing("fqn mismatch") sentinel,
which is right for a function nothing depends on; one whose module was not
(exec-created, or __module__ None) fell through to pickle's by-reference rule
and failed the dump (a bypass).

def keep_defaults(func):
    @functools.wraps(func)
    def wrapper(self, x):
        if len(func.__defaults__) == 2:
            x = x + 1
        return func(self, x)
    return wrapper

class M(torch.nn.Module):
    @keep_defaults
    def forward(self, x, scale=2.0, shift=1.0):
        return x * scale + shift

torch.compile(M())(torch.randn(3))

Dynamo inlines wrapper and reaches func, the undecorated forward,
through the closure. func.__qualname__ is M.forward, but M.forward now
resolves to wrapper: an fqn mismatch. The len(func.__defaults__) == 2
check installs a SEQUENCE_LENGTH guard whose source walks through func.
Serialization stored func as the sentinel, so at load re-walking that source
hit '_Missing' object has no attribute '__defaults__' and the package failed
to load. A guard on func.__module__ was worse: the sentinel happens to have
one, so the guard silently rebaked against torch._dynamo.guards and never
matched again. Every functools.wraps decorator that reads anything off the
function it wraps hits one of these.

The fix: a function whose name does not resolve back to it, and that some
guard is rooted at, is stored by value -- its code object, its __module__,
__qualname__ and __name__, its closure cells, and its defaults -- and
rebuilt at load with types.FunctionType, using the imported module's dict as
globals (or an empty dict if the module cannot be imported; a guard reads
attributes off the function and never calls it). The three names are set
explicitly afterwards because FunctionType derives them from the code object
and wraps had changed them; a guard on func.__name__ must see the value it
saw at trace time. Defaults travel as pickle state so a default that refers
back to the function does not recurse. Importing the module at load runs its
top-level code if it is not loaded yet (for a wraps wrapper that is the
wrapped function's module, almost always already imported); an import that
fails is logged at debug level before the empty scope is used. A __module__
that is not a str is restored as is: Dynamo's own trace rules cannot trace
such a function, but a decorator can leave one behind and the reducer must not
TypeError on it. The three names are restored unconditionally, None included,
so the result does not depend on the scope the caller happened to pass. A
<locals> function is rebuilt whether or not a guard is rooted at it, as
before; unlike a wraps wrapper it has no module-level neighbourhood to drag
along.

Two boundaries keep this narrow. An fqn-mismatched function that no guard
reads still becomes the sentinel, so rebuilding does not drag every wrapper's
neighbourhood into the artifact. And <locals> functions, which were already
rebuilt by value, now share this reducer; that fixes the old path passing
__qualname__ as the function's NAME (test_rebuilt_locals_function_keeps_its_name
pins it: __name__ was outer.<locals>.f before) and failing the load on an
unimportable module. Keyword-only defaults, the other attributes, and pruning of what no
guard reads land in the next commit; the Note in guards.py lists what the
rebuilt function carries so that gap is visible. _apply_function_state is a
classmethod like the other reducers embedded in an artifact, so the artifact
names the pickler subclass and resolves through its MRO.

Test Plan:

python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k fqn_mismatch -k test_guard_rooted_at_a_none_valued_closure_cell -k test_rebuilt_function_keeps_an_empty_closure_cell -k test_reduce_restores_a_non_str_module -k test_rebuilt_functions_keep_a_shared_closure_cell_shared

The parametrized test_guard_rooted_at_fqn_mismatched_function cases each
mutate the restored attribute (__defaults__, __name__, __qualname__,
__module__) on the live function and assert the loaded guard REJECTS it,
since a reconstruction that pinned nothing passes the positive check alone.
Four of the six parametrized cases (defaults_length, default_value,
renamed_name, qualname) error on the previous commit with '_Missing' object has no attribute ..., as do the module-gone-at-load, None-valued-cell
and empty-cell tests; the module_name case instead loads a guard pinned to
the sentinel's own __module__ (torch._dynamo.guards) and never matches,
the silent form of the same failure; none_module fails the dump on the
previous commit, where pickle's by-reference rule cannot place a function
without a module. The none_module case covers a __module__
of None through the guard (Dynamo traces func.__module__ as the scope's
__name__, a pre-existing divergence, so the guard's real-attribute round trip
is what it pins); the non-str case is pickler-level, since Dynamo cannot
trace such a function; and a function whose module was never in sys.modules
at dump time, which used to fail the dump by reference (a bypass), now rebuilds
and rejects a change like the others.

Authored with an AI assistant.

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

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

✅ No Failures

As of commit 43ab387 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
    • reducer_override at guards.py:4461-4485 keeps the old outcome for an unguarded fqn mismatch (_Missing) and for a function whose qualname resolves back to it (falls through to by-reference), so only the guarded-mismatch case changes.
    • The <locals> path now passes fn.__name__ rather than __qualname__ into types.FunctionType (package.py:168, :305), fixing the old _unpickle_nested_function bug it replaces.
    • isinstance(obj.__module__, str) at guards.py:4470 keeps an unhashable __module__ from raising out of the reducer on the in sys.modules probe.
  • Testing
    • Six FQN_MISMATCH_CASES subtests each assert the loaded guard REJECTS after mutating the restored attribute, so a reconstruction pinning nothing cannot pass on the positive check alone.
    • test_rebuilt_locals_function_keeps_its_name, test_rebuilt_function_keeps_an_empty_closure_cell and test_rebuilt_functions_keep_a_shared_closure_cell_shared pin the name, empty-cell and cell-sharing properties of the shared rebuild.
    • test_unguarded_fqn_mismatched_function_is_pruned pins the id(obj) not in self.guard_tree_values prune at guards.py:4483, bounding what the widening drags into the artifact.
  • Preservation
    • No defensive branch is dropped: the _Missing arms, UNSUPPORTED_SERIALIZATION_GUARD_TYPES (guards.py:4852) and pickle_guards_state's PackageError mapping (:4573-4607) are untouched.
    • The new except Exception in _unpickle_fn_from_module (package.py:205-209) is a deliberate widening away from load failure and logs at debug rather than swallowing silently.
  • Scope
    • Three files, confined to FunctionPicklerBase reducers, GuardsStatePickler.reducer_override's function arm, and test_guard_serialization.py; no public API, CI, or release plumbing touched.
    • importlib.import_module at load is not a new trust boundary: _unpickle_python_module (package.py:141) and the inlined-source check (:883) already import from the artifact.

reason: clean
Reviewed commit: 43ab387

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

  • Gather context (diff, changed files)
  • Run PyTorch /pr-review checks
  • Post review

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

[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 added the topic: not user facing topic category label Sep 9, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Updated. The previous review run timed out without posting; this head carries the isinstance(str) guard on __module__, __qualname__/__module__ subtests, and no longer carries __kwdefaults__ (moved to the restore-and-prune commit above).

@claude

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

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


PR Review: #196474

The design is sound and well-documented, but I found one documented-invariant violation (_apply_function_state is a @staticmethod) and three untested paths, including the isinstance(__module__, str) gate this head specifically adds.

Full review

PR Review: #196474

Summary

Widens GuardsStatePickler so a function whose fqn does not resolve back to it (every functools.wraps wrapper's inner target, module-level lambdas, exec-created functions) is pickled by value and rebuilt from its code object when a guard is rooted at it, sharing one reconstruction with the pre-existing <locals> branch. The mechanism and the reason for each restored attribute are unusually well documented; the problems below are one invariant violation, an annotation that contradicts its own code, and coverage gaps on the paths this head newly added.

Code Quality

  • torch/_dynamo/package.py:210-213 — _apply_function_state is a @staticmethod, contradicting the invariant documented 80 lines above it. package.py:131-134 states the rule explicitly:

    # The reducers stay classmethods: pickle reduces a bound classmethod to
    # getattr(owner, name), so an artifact names the subclass and resolves the
    # reducer through its MRO. A staticmethod would pickle by __qualname__ and
    # change the artifact.

    _apply_function_state is embedded in the artifact — _reduce_function returns it as the 6th element of the reduce tuple (package.py:296, type(self)._apply_function_state), and pickle serializes the state-setter. Every other function this class puts into an artifact (_unpickle_code, _unpickle_python_module, _unpickle_bound_method, _unpickle_empty_cell, _set_cell_contents, _build_function, _unpickle_fn_from_module) is a @classmethod. As written the artifact names FunctionPicklerBase._apply_function_state by qualname, so a GuardsStatePickler (or the AOTCompilePickler that package.py:120-122 says is being moved onto this base) override would not be honored — which is precisely the failure mode the comment exists to prevent. It loads today only because no override exists. Make it a @classmethod for consistency with the stated rule. Fix this →

  • torch/_dynamo/package.py:161 and :181 — the module: str | None annotation contradicts the code directly below it. _unpickle_fn_from_module's own comment at :195-198 says "__module__ need not be an importable string: a decorator can set it to a non-str (42)", and the isinstance(module, str) check at :201 exists only because of that; guards.py:4458-4459 makes the same point. _reduce_function puts fn.__module__ verbatim into the args tuple (:293), so a non-str really does arrive here and _build_function assigns it back at :174. Under the current annotation the isinstance check reads as dead code. Annotate the parameter as Any in both signatures.

  • torch/_dynamo/package.py:202-205 — the bare except Exception around importlib.import_module swallows the failure with no record. The comment justifies swallowing (a relative name, a module body that raises), and empty globals are genuinely safe on this path. But a module that should import and fails because of an unrelated bug now yields a silently empty scope with nothing to grep for. A log.debug naming the module and the exception would make that diagnosable at zero cost on the success path.

Testing

I was not able to run test/dynamo/test_guard_serialization.py — this checkout has no built torch and no .venv, so the assertions below are from reading the tests, not from executing them.

  • The isinstance(obj.__module__, str) gate added in this head (guards.py:4460) has no test. The trigger comment calls it out as the notable change, and it is the one branch with two distinct downstream behaviors (guards.py:4460 skipping the sys.modules probe, and package.py:201 falling through to an empty scope while package.py:174 still assigns the non-str back). Neither a non-str __module__ nor __module__ is None appears anywhere in FQN_MISMATCH_CASES or the new standalone tests. A guard rooted at func.__module__ on a function whose __module__ a decorator set to a non-str, or to None, would cover the gate and the round-trip together. Fix this →

  • The branch whose behavior this PR actually changes for non-<locals> functions is untested. Pre-PR, the fqn check was nested inside if obj.__module__ in sys.modules:, so a function whose __module__ was absent from sys.modules at dump time fell through the reducer entirely and was pickled by reference. After this PR it is an fqn mismatch (guards.py:4464-4475). test_fqn_mismatched_function_from_a_module_gone_at_load does not reach it — it registers the module in sys.modules before _test_serialization and only removes it before the load, so at dump time it takes the resolve-and-mismatch path. Nothing exercises "absent at dump".

  • test_fqn_mismatched_function_keeps_a_shared_closure_cell_shared does not test the fqn-mismatch branch its name claims. a and b come from outer(), so their __qualname__ contains <locals> and they return at guards.py:4456, never reaching the new code at :4464. The cell-sharing property it verifies is real and both branches share _reduce_function, so the coverage is equivalent in effect — but the name will mislead the next reader into thinking the new branch is what was pinned. Rename to drop fqn_mismatched, or root it at a functools.wraps-decorated module-level function so it actually takes the new branch.

API Design

  • The set of attributes a rebuilt function carries is now a load-time contract, and it is documented only implicitly by what _build_function/_apply_function_state happen to assign. A guard source that walks through an attribute outside that set reproduces the exact bug this PR fixes — evaluation during guard-manager build raises and the whole load fails, since GuardBuilder.get → Source.get_value evals the source template with no exception handling (guards.py:1716, guards.py:2238, torch/_guards.py:1510). Two such attributes exist today:

    • __kwdefaults__: reachable via DefaultsSource(fn_source, name, is_kw=True) (variables/functions.py:302, template {0}.__kwdefaults__['name'] at source.py:710-715). The rebuilt function has __kwdefaults__ is None, so the eval raises TypeError: 'NoneType' object is not subscriptable. The PR body acknowledges this and defers it to the next commit — noting it only because between these two commits the failure is a bare TypeError from inside eval, which is materially harder to attribute than the pre-PR _Missing AttributeError.
    • The function's __dict__: lookup_instance_dict (variables/functions.py:623-641) installs AttrSource(fn_source, name) for any attribute in a real function's __dict__, and decorators do set them (torch/_dynamo/decorators.py:195 sets fn._dynamo_marked_constant; functools.wraps copies the wrapped __dict__ onto the wrapper). The rebuilt function's __dict__ is empty, so that source raises AttributeError at load. Per the PR body this one is not covered by the follow-up commit.

    Neither is a regression — both failed the load pre-PR through the sentinel — so this is not a blocker. But since the note at guards.py:4286-4295 is the place a future reader will look, it should state the restored set as the contract and name __dict__ as a known gap, so the next person who hits it recognizes it rather than rediscovering the whole failure mode.

Recommendation

Request Changes

The @staticmethod at package.py:210 should be a @classmethod before this lands — it violates an invariant this same file documents explicitly, and the cost of fixing it is one line. The isinstance(__module__, str) gate that is the headline of this head also needs a test. Everything else above is small: two annotations, a debug log, one test rename, and one sentence in the note at guards.py:4286.

Checks I ran that found nothing to report, recorded so they are not redone: ID_MATCH/FUNCTION_MATCH/CLOSURE_MATCH are all in CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES (guards.py:4840-4849) and raise PackageError at serialize time, so the object-identity change from by-reference to by-value cannot produce a silently always-failing identity guard. Removing GuardsStatePickler._unpickle_nested_function is not a load break for persisted artifacts: _DynamoCacheEntry.check_versions compares torch_version and raises before any guard state is unpickled (package.py:632-635, :674-677, :866). And __annotations__ is an empty dict on both the pre-PR sentinel and the rebuilt function, so that gap is pre-existing and unchanged.

  • Gather context (diff, changed files)
  • Run PyTorch /pr-review checks
  • Post review
    | Branch: gh/bobrenjc93/1139/head

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Round-2 review follow-up: module is annotated Any where the code deliberately restores a non-str __module__; the Note in guards.py and the message now describe the silent form of the failure too (a guard on a name the sentinel happens to have, like __module__, rebakes against the sentinel's value and never matches, rather than raising at load), which is what the module_name subtest pins.

@claude

@claude

claude Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

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


Round-2 Review: #196474

Two of the round-1 items landed; one I need to retract as overstated on my part (_apply_function_state as a @staticmethod is an artifact-stability nit, not the dispatch bug I described), and the three coverage gaps plus one new observation about load-time imports remain.

Full review

What changed since the head I reviewed

git diff 7bd74a2..HEAD is small and matches the trigger comment:

  • package.py:162,182 — module: str | None → module: Any on both _build_function and _unpickle_fn_from_module, plus a sentence at :172-173 ("Any other value is restored as is: __module__ need not be a str"). This resolves the round-1 annotation finding: the isinstance(module, str) check at :202 and the assignment at :175 are no longer contradicted by the signature.
  • guards.py:4295-4299 — the Note now covers the silent failure mode as well as the raising one. This is the right framing, and it is the framing the module_name subtest actually pins: DecoratedModuleNameForwardModule guards EQUALS_MATCH on func.__module__, a name _Missing genuinely has, so pre-PR the load succeeded and the guard was baked against torch._dynamo.guards and never matched. Worth stating explicitly for the next reader that this is the only one of the five subtests whose pre-PR failure is silent — the other four raise '_Missing' object has no attribute ....

The raise_local_type_error message change and the _DynamoCodeCacheEntry docstring edit also show up in 7bd74a2..HEAD, but they are not in git diff origin/gh/bobrenjc93/1139/base...HEAD — they arrived with the base update (4357acb) from a lower commit in the stack. Out of scope here; I am not reviewing them.

Retraction from round 1

I claimed _apply_function_state being a @staticmethod means "a subclass override would not be honored." That is wrong and I should not have called it a blocker. _reduce_function reads type(self)._apply_function_state at dump time, so a subclass override is picked up either way; with a staticmethod pickle then saves that override function by its own __qualname__ (Subclass._apply_function_state), which resolves correctly.

The real difference is narrower: with a classmethod the artifact names the pickler subclass and resolves through its MRO, so moving the implementation up or down the hierarchy later keeps old artifacts loading. With a staticmethod the artifact pins the defining class, so an artifact written today names FunctionPicklerBase._apply_function_state and would keep resolving to the base even after a subclass gains an override. That is a plausible thing to want on purpose, and it is not a live bug.

But package.py:131-134 states the rule unconditionally ("The reducers stay classmethods"), and _apply_function_state is embedded in the artifact as the 6th reduce-tuple element at :297 while every sibling that ends up in an artifact (_unpickle_code, _unpickle_python_module, _unpickle_bound_method, _unpickle_empty_cell, _set_cell_contents, _build_function, _unpickle_fn_from_module) is a classmethod. Note that _set_cell_contents is the exact analogue — also a state-setter, also embedded, and it is a classmethod. So the file currently says one thing and does another in one place. Either make it a @classmethod to match, or add a one-line comment saying the pin is deliberate. Not a blocker. Fix this →

Still open from round 1

  • The isinstance(__module__, str) gate has no test. All five FQN_MISMATCH_CASES and both new standalone tests use a real str __module__; the module_name case mutates str → str ("other"). So neither the gate at guards.py:4464 nor the else: f_globals = {} arm at package.py:207 is exercised. Note the two are not the same branch: test_fqn_mismatched_function_from_a_module_gone_at_load reaches the except Exception arm at :205 (valid name, import fails), not the non-str/empty arm. A guard rooted at func.__module__ on a function whose __module__ a decorator set to 42, and one where it is None, would cover the gate, the empty-scope fallback, and the if module is not None asymmetry in _build_function in one go. Fix this →

  • "Module absent from sys.modules at dump time" is still untested, and it is the one case whose outcome class changes. Pre-PR the fqn check was nested under if obj.__module__ in sys.modules:, so such a function fell out of reducer_override entirely and pickle tried to save it by reference — a PicklingError at dump, mapped to PackageError, i.e. a bypass. Post-PR it is an fqn mismatch (guards.py:4468) and either becomes _Missing or is rebuilt by value, so a compile that previously bypassed now succeeds. That is the intended improvement, but nothing pins it. test_fqn_mismatched_function_from_a_module_gone_at_load does not: it registers the module in sys.modules before _test_serialization and removes it only before the manual reload, so the dump takes the resolve-and-mismatch path.

  • test_fqn_mismatched_function_keeps_a_shared_closure_cell_shared does not take the branch its name claims. a and b come from outer(), so <locals> is in their __qualname__ and they return at guards.py:4460. Both branches funnel into _reduce_function, so the cell-sharing property it verifies is genuinely covered — the name is the only problem, and it will mislead the next reader into thinking the new branch is pinned. Drop fqn_mismatched from the name, or root it at a functools.wraps-decorated module-level function.

  • The restored-attribute set is a load-time contract and the Note still does not say so. The Note now explains why rebuilding happens and both failure shapes, which is the important half. What it does not say is what the rebuilt function carries — __code__, __qualname__, __name__, __module__, __closure__, __defaults__ — so a guard source that walks through anything else reproduces exactly the bug this PR fixes, since GuardBuilder.get → Source.get_value evals the template with no exception handling. Two such attributes exist: __kwdefaults__ (the PR body defers this to the next commit; between the two commits the failure is a bare TypeError: 'NoneType' object is not subscriptable from inside eval, harder to attribute than the pre-PR _Missing AttributeError) and the function's __dict__, which lookup_instance_dict in variables/functions.py turns into AttrSources and which decorators do populate — functools.wraps copies the wrapped __dict__ onto the wrapper, and decorators.py sets _dynamo_marked_constant. Neither is a regression; both failed the load pre-PR through the sentinel. One sentence naming the set and flagging __dict__ as a known gap would save the next person the whole rediscovery.

  • package.py:203-206 still swallows the import failure with no record. Empty globals are safe on this path and the comment says why, but a module that should import and fails for an unrelated reason now yields a silently empty scope with nothing to grep for. logger already exists at package.py:46; a logger.debug naming the module and the exception costs nothing on the success path.

New observation

This PR widens the set of functions whose __module__ gets imported at guard-load time, and that is unremarked. _unpickle_fn_from_module calls importlib.import_module(module) (:204), which executes arbitrary module-level code. Pre-PR that only happened for <locals> functions (the old _unpickle_nested_function); now it happens for every fqn-mismatched guarded function. For the motivating functools.wraps case this is usually free — __module__ is the wrapped function's module, almost certainly already imported. But a guard rooted at a function whose __module__ names a module not otherwise loaded at guard-check time now pays a real import during load, and any import side effect with it. Worth a clause in the comment at :188-194, which currently discusses only the failure case (empty scope) and not the cost of the success case.

Verified, nothing to report

Recording these so they are not redone:

  • _reduce_function's 6-element reduce tuple works irrespective of DEFAULT_PROTOCOL: CPython's save_reduce has no protocol guard on the state_setter arm, and _reduce_cell already relies on this in shipped code.
  • The state is (defaults,), a 1-tuple, so it is never None and the setter always runs — the same reason _set_cell_contents wraps its payload. A bare None default tuple would have skipped the BUILD step.
  • guard_tree_values is fully populated before pickle_guards_state runs (guards.py:1719 during guard-manager build, :4563 at serialize), and it records the example_value of every named source. So a function is in it exactly when a guard walks through it — the invariant the prune at :4477 depends on holds.
  • test_guard_rooted_at_fqn_mismatched_function's negative half is sound: _test_check_fn asserts ref.check == loaded.check as well as ref.check == expected, so a reconstruction that pinned nothing fails on the loaded side rather than passing vacuously.
  • raise_local_type_error (guards.py:1032) dropping {obj} while the inline copy at :4499 keeps it is not an inconsistency to fix: the former runs outside pickler.dump, where a raising repr would escape as an internal compiler error, and the latter runs inside, where it is mapped. Both came from the base update anyway.
  • instantiate_parametrized_tests inside config.patch is ordered correctly and the NB explains it: _ConfigPatch.__call__ (_config_module.py:1026-1049) subclasses the decorated TestCase, and instantiate_parametrized_tests delattrs the template method (common_utils.py:748), which only works on the class that defines it.
  • Removing GuardsStatePickler._unpickle_nested_function is not a load break for persisted artifacts: _DynamoCacheEntry.check_versions compares torch_version and raises before any guard state is unpickled. aot_compile.py:107 keeps its own _unpickle_nested_function and is untouched, consistent with the class docstring's note that AOTCompilePickler moves onto this base separately.
  • ID_MATCH, FUNCTION_MATCH and CLOSURE_MATCH are all in UNSUPPORTED_SERIALIZATION_GUARD_TYPES (guards.py:4844-4853) and raise PackageError at serialize time, so switching a function from by-reference to by-value cannot produce a silently always-failing identity guard.

I could not execute the tests. This checkout has no built torch and no .venv, so every assertion above is from reading code, not from running python test/dynamo/test_guard_serialization.py.

Recommendation

Approve with comments. Nothing here blocks. Correcting my round-1 verdict: the @staticmethod is a consistency nit, not a defect. The remaining items are the two coverage gaps (non-str __module__, absent-at-dump module), one test rename, a logger.debug, and two sentences in comments.

  • Diff current head vs. the head I reviewed last round
  • Verify each prior finding is addressed (or consciously deferred)
  • Look for new issues introduced by the round-2 changes
  • Post review
    | Branch: gh/bobrenjc93/1139/head

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot drci

… 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)


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
See Note [Reconstructing a function a guard is rooted at].
"""
return self._reduce_function(
obj, defaults=obj.__defaults__, closure=obj.__closure__

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 gate above (id(obj) not in self.guard_tree_values) is per-function, but this payload is unconditional, so a closure cell no guard reads can fail the dump. A wraps wrapper capturing an ordinary threading.Lock, under an outer decorator whose guard reads only func.__module__:

def synchronized(func):
    lock = threading.Lock()
    @functools.wraps(func)
    def wrapper(self, x):
        if x is None:
            with lock:
                pass
        return func(self, x)
    return wrapper

class M(torch.nn.Module):
    @keep_module      # guard: func.__module__ == THIS
    @synchronized
    def forward(self, x):
        return x * 2
parent commit : dump+load OK  (ref.check=True, loaded.check=False -- the silent miss this change targets)
this commit   : PackageError: TypeError: cannot pickle '_thread.lock' object

#196476 closes this by pruning each cell/default through the same guard_tree_values test. Worth folding that down to here: reverting #196476 on its own would leave this widening in place without the prune.

@@ -722,7 +970,11 @@ def forward(self, x):
self.assertEqual(out(torch.ones(1)), torch.ones(1) + 1)

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 comment three lines up -- "at this commit the <locals> rebuild passes __qualname__ as the function's NAME, and on 3.10 FunctionType then reports the bare co_name as __qualname__" -- describes the bug this change fixes, so it now reads backwards. Measured on this receiver (py3.10):

parent: __name__='make.<locals>.Local.forward'  __qualname__='forward'
head:   __name__='forward'                      __qualname__='make.<locals>.Local.forward'

Drop the comment and pin the fix here too:

self.assertEqual(out.__func__.__name__, "forward")

self.assertIs(a.__closure__[0], b.__closure__[0])
buf = io.BytesIO()
cell = a.__closure__[0]
gtv = {id(a): a, id(b): b, id(cell): cell}

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:

This dict is inert. a and b are <locals> functions, and that branch returns at guards.py:4466 before the guard_tree_values gate, so nothing reads it -- and the test passes unchanged on the parent commit. As written it pins pre-existing _reduce_cell memoization, not the branch this change adds. Use a module-level fqn-mismatched pair sharing a cell so the new gate is what carries them.

Comment thread torch/_dynamo/guards.py
# change: it can never be found by name, and unlike a wraps
# wrapper it has no module-level neighbourhood to drag along.
return self._reduce_function_by_value(obj)
resolved: Any = None

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.

nit:

Suggested change
resolved: Any = None
resolved: object = None

Comment thread torch/_dynamo/package.py
# off the rebuilt function without calling it; a pickler whose
# functions are CALLED after load would see an empty scope as a
# NameError at first call, not a load error.
f_globals: dict[str, Any]

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.

nit:

Suggested change
f_globals: dict[str, Any]
f_globals: dict[str, object]

Comment thread torch/_dynamo/package.py

@classmethod
def _apply_function_state(
cls, fn: types.FunctionType, state: tuple[Any, ...]

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.

nit:

Suggested change
cls, fn: types.FunctionType, state: tuple[Any, ...]
cls, fn: types.FunctionType, state: tuple[object, ...]

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Thanks; fixed forward in #196764 at the top of the stack: the shared-cell test now uses a module-level wraps pair so the guard_tree_values gate is what carries it, the module-method test asserts the rebuilt __name__ (its stale comment is gone), and the object nits are applied where the type checker allows (the state tuple has to stay Any, its elements are assigned to typed function slots). The unconditional cell/default payload at this commit is pruned by #196476 two commits up, which is where the prune lives 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
…ard reads (#196476)

`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.

Pull Request resolved: #196476
Approved by: https://github.com/pytorchgreenlight, https://github.com/aorenste
ghstack dependencies: #196505, #196470, #196471, #196472, #196473, #196474
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
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
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
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1139/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