Skip to content

[dynamo] Extract FunctionPicklerBase from GuardsStatePickler - #196471

Closed
bobrenjc93 wants to merge 8 commits into
gh/bobrenjc93/1136/basefrom
gh/bobrenjc93/1136/head
Closed

bobrenjc93 wants to merge 8 commits into
gh/bobrenjc93/1136/basefrom
gh/bobrenjc93/1136/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

A pure move with no behavior change. At this commit the new base class has
exactly ONE subclass, GuardsStatePickler; the second user is
AOTCompilePickler, which #196685 (ten commits up this stack) moves onto the
base. The extraction happens here so the next five commits have one place to
add the by-value function reducers that both picklers will share.

GuardsStatePickler (guard state) and AOTCompilePickler
(torch/_dynamo/aot_compile.py, the AOT compile artifact) both have to rebuild
objects that pickle cannot do by reference -- code objects, python modules,
bound methods -- and each carries its own copy of those reducers. This commit
moves GuardsStatePickler's copies into a new FunctionPicklerBase in
package.py and makes GuardsStatePickler subclass it. Bodies are unchanged
(one parameter renamed, one return annotation tightened).

Until #196685, AOTCompilePickler keeps its own copies of these reducers,
including the same bugs the commits here fix in the guard pickler (an
unguarded cell_contents read and the old nested-function rebuild). #196685
changes its base to FunctionPicklerBase, deletes the duplicates and
rewrites its dispatch around the shared reducers; because the closure-cell,
bound-method and by-value function reducers that #196472-#196478 add already
live on the base, that commit adds no reducer bodies of its own.

The reducers are pickled by reference as getattr(GuardsStatePickler, name)
(pickle records the bound classmethod's owner), so an artifact records the
same reference before and after this move; they have to stay classmethods for
that reason. When AOTCompilePickler moves onto the base it must consciously
replace its own _unpickle_module (an importlib import) with the inherited
_unpickle_python_module, since GuardsStatePickler._unpickle_module
rebuilds an nn.Module.

guards.py now imports SerializedCode at module level (package.py does not
import guards.py, so there is no cycle) instead of inside two methods, and
drops import pickle, whose only use was the base class.

Test Plan:

python test/dynamo/test_guard_serialization.py

Authored with an AI assistant.

FAQ

Q: The docstring says the base exists "so that a fix cannot be missed in one
pickler", but there is exactly one subclass at this commit.

A: The same paragraph states that GuardsStatePickler is the one subclass
today; the clause is the reason AOTCompilePickler is moved onto the base
separately, not a claim that it already has been.

Q: The base shares the reducer bodies, but both reducer_overrides still
duplicate the iscode/ismodule/ismethod dispatch predicates.

A: This change is a pure move that prepares the base, and aot_compile.py is
deliberately untouched in this stack so the AOT move is one reviewable step.
The bound-method predicate does move into the base later in the stack
(FunctionPicklerBase._reduce_bound_method); the remaining predicates are
one-liners whose divergence risk lives in the reducer bodies the base now owns.

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

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

✅ No Failures

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

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

  • Pure move
    • _unpickle_code, _unpickle_python_module, _unpickle_bound_method move verbatim into FunctionPicklerBase at package.py:114-138; GuardsStatePickler inherits them (guards.py:4159)
    • alias -> name rename in _unpickle_python_module is safe: the reduce tuple passes it positionally at guards.py:4394
    • Inherited _unpickle_python_module does not collide with GuardsStatePickler._unpickle_module, which still rebuilds an nn.Module at guards.py:4176
  • Import safety
    • guards.py:77 promotes from torch._dynamo.package import ... to module level; package.py's only guards import is under TYPE_CHECKING at package.py:50
    • Its module-level deps (exc, graph_utils, bytecode_transformation, utils, config, bytecode_analysis, metrics_context) reach torch._guards, never torch._dynamo.guards
    • Dropping import pickle from guards.py is safe: grep finds no surviving pickle token in that file, and importlib remains used at guards.py:4306
  • Artifact compatibility
    • All three call sites still use type(self)._unpickle_* (guards.py:4319, :4394, :4479), so the bound classmethod's __self__ stays GuardsStatePickler and the reducer resolves through the MRO
    • The invariant is recorded in the comment at package.py:124-127, so a later @staticmethod conversion is flagged
  • Tests and scope
    • Existing coverage exercises the moved reducers: test_bound_method_input (test_guard_serialization.py:1627), test_bound_methods_empty (:1659), and test_opaque_obj_v2.py:1190 builds GuardsStatePickler directly
    • Scope is two files with no behavior change; aot_compile.py:64 AOTCompilePickler is deliberately left on pickle.Pickler with its own copies

reason: clean
Reviewed commit: 823db33

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

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


This is a genuine pure move — I verified the new module-level guards.py -> package.py import introduces no cycle and that the pickle payload bytes are unchanged in both directions, so the only comments are two forward-looking notes about invariants the new base class does not yet protect.

Full review

PR Review: #196471

Summary

Extracts three reducers (_unpickle_code, _unpickle_python_module, _unpickle_bound_method) out of GuardsStatePickler into a new FunctionPicklerBase in package.py, in preparation for rebasing AOTCompilePickler onto the same base. The move itself is correct and payload-compatible; two invariants that the change now depends on are undocumented and unenforced.

Verification performed

Two claims in this diff were load-bearing enough to check rather than assume:

1. No import cycle. guards.py:77 promotes from torch._dynamo.package import FunctionPicklerBase, SerializedCode to module level (previously lazy + TYPE_CHECKING-only). Traced the transitive module-level closure of package.py (torch._dynamo.exc, torch._dynamo.graph_utils, torch.utils.weak, .bytecode_transformation, .utils) — none imports guards at module level. package.py's only guards import is under if TYPE_CHECKING: (package.py:49-50); its two runtime uses (package.py:165, package.py:1026) are inside function bodies. Neither module is imported during import torch. The PR description's claim holds.

2. Pickle payload is byte-identical. This is the part that could have silently broken serialized guard state. CPython does not register types.MethodType in Pickler.dispatch, so a bound classmethod falls through to C-level method_reduce, which yields (getattr, (__self__, __func__.__name__)) — the payload stores the class reference plus the bare method name, and resolution happens through getattr at load time, i.e. through the MRO. Since every call site uses type(self)._unpickle_*, __self__ remains GuardsStatePickler, so the emitted opcodes are unchanged and inheritance is invisible in the bytes. Old payloads load on new code and vice versa.

Also confirmed import pickle is genuinely dead in guards.py after the move (no remaining pickle. attribute access; all grep hits are _unpickle_* identifiers, pickle_guards_state, or pickler.dump), and that importlib/types are still needed there (guards.py:4302).

Code Quality

  • package.py:121-131 — the @classmethod binding is now load-bearing for payload stability, and nothing says so. Per the analysis above, payload compatibility survives this refactor only because these are @classmethods. Converting any of them to @staticmethod or a plain function would make class access yield a FunctionType, which hits save_global and serializes by __qualname__ — the payload would then name FunctionPicklerBase._unpickle_code instead of GuardsStatePickler._unpickle_code. This is not hypothetical: guards.py:4272 already declares _unpickle_sdp_backend as a @staticmethod, so both conventions coexist in the sibling class and a future contributor has no signal that the choice matters here. The docstring already claims to fix "HOW they are rebuilt" — it is the right place to state that the reducers must stay classmethods because the reduce tuple resolves them by name off the subclass.

    Fix this →

  • package.py:115-119 — the docstring describes the end state of the stack, not this commit. "so a fix in one pickler cannot be missed in the other" reads oddly when AOTCompilePickler (aot_compile.py:64) is still a bare pickle.Pickler at this commit and there is exactly one subclass. Minor, and it resolves later in the stack; flagging only because a reader landing on this commit via git blame will look for a second subclass that isn't there yet.

API Design

  • The base unifies the reducer bodies but not the dispatch predicates, which is where the two picklers already diverge. The stated goal is that "a fix to how a function is rebuilt cannot be missed in one of the two picklers." That is half achieved: reducer_override still duplicates the inspect.iscode / inspect.ismodule / inspect.ismethod conditions in both classes (guards.py:4306-4478 vs aot_compile.py:119-153), including the identical five-line bound-method inner_func comparison (guards.py:4468-4475 vs aot_compile.py:129-142) — that shared logic decides whether to rebuild, and a fix there can still be missed in one pickler. Not a blocker for a pure move, but if the follow-up leaves the predicates duplicated, the class name is promising more than it delivers.

  • Naming collision hazard for the follow-up rebase. GuardsStatePickler._unpickle_module (guards.py:4172) reconstructs an nn.Module, while AOTCompilePickler._unpickle_module (aot_compile.py:97) does importlib.import_module — the same name means two unrelated things across the two classes that are about to share a base. The base sensibly picks the unambiguous _unpickle_python_module, but when AOTCompilePickler moves onto FunctionPicklerBase, dropping its _unpickle_module in favour of the inherited name must be a deliberate step, not a rename that appears to be a no-op. Worth a note in the follow-up PR.

Backward Compatibility

No issues. Payload format is unchanged (see Verification above). Separately, even a payload change would be contained: SystemInfo.check_compatibility (package.py:461-469) hard-rejects artifacts from a different torch_version or python_version, so these pickles are never read across versions. The alias -> name parameter rename in _unpickle_python_module is safe because the reduce tuple always passes it positionally (guards.py:4390).

Testing

No new tests required — pure move, and test/dynamo/test_guard_serialization.py plus test/test_opaque_obj_v2.py:1183 (which constructs GuardsStatePickler directly) exercise the moved reducers through the unchanged public path. I did not run the suite; no build was available in this environment.

Recommendation

Approve

The move is correct and payload-compatible. The two Code Quality / API Design notes are about documenting and following through on invariants, not defects in this diff — the classmethod note is the one worth acting on before landing, since it is a one-line docstring addition that prevents a future silent payload break.

· branch [`gh/bobrenjc93/1136/head`](https://github.com/pytorch/pytorch/tree/gh/bobrenjc93/1136/head)

[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 9, 2026
No behavior change: the reducers that rebuild objects pickle cannot do by
reference -- code objects, python modules, bound methods -- move from
`GuardsStatePickler` into a `FunctionPicklerBase` in package.py with their
bodies unchanged (one parameter renamed, one return annotation tightened), and
`GuardsStatePickler` subclasses it. The follow-up commits add the by-value
function reconstruction to this base. `AOTCompilePickler` still carries its
own copies of these reducers; moving it onto the base is done separately so a
fix to how an object is rebuilt cannot be missed in one of the two picklers.

The reducers are pickled by reference as `getattr(GuardsStatePickler, name)`
(pickle records the bound classmethod's owner), so an artifact records the
same reference before and after this move; they have to stay classmethods for
that reason. When `AOTCompilePickler` moves onto the base it must consciously
replace its own `_unpickle_module` (an `importlib` import) with the inherited
`_unpickle_python_module`, since `GuardsStatePickler._unpickle_module`
rebuilds an `nn.Module`.

guards.py now imports `SerializedCode` at module level (package.py does not
import guards.py, so there is no cycle) instead of inside two methods, and
drops `import pickle`, whose only use was the base class.

Test Plan:

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

Authored with an AI assistant.

FAQ

Q: The docstring says the base exists "so that a fix cannot be missed in one
pickler", but there is exactly one subclass at this commit.

A: The same paragraph states that `GuardsStatePickler` is the one subclass
today; the clause is the reason `AOTCompilePickler` is moved onto the base
separately, not a claim that it already has been.

Q: The base shares the reducer bodies, but both `reducer_override`s still
duplicate the `iscode`/`ismodule`/`ismethod` dispatch predicates.

A: This change is a pure move that prepares the base, and aot_compile.py is
deliberately untouched in this stack so the AOT move is one reviewable step.
The bound-method predicate does move into the base later in the stack
(`FunctionPicklerBase._reduce_bound_method`); the remaining predicates are
one-liners whose divergence risk lives in the reducer bodies the base now owns.

ghstack-source-id: 43da033
Pull-Request: #196471
@bobrenjc93 bobrenjc93 added the topic: not user facing topic category label Sep 9, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Updated: a comment above the reducers records the classmethod invariant (pickle reduces a bound classmethod to getattr(owner, name), so the artifact names the subclass), and the message notes what the future AOTCompilePickler move must replace. The docstring wording and the still-duplicated dispatch predicates are answered in the FAQ in the description.

@claude

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

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


The classmethod invariant is now recorded accurately at package.py:123-126, and I re-verified the payload-stability argument against the updated code — this addresses the one item from my earlier review I'd flagged as worth acting on before landing, so I have nothing blocking.

Full review (re-review of the update)

Re-review: #196471

  • Read the updated diff against origin/gh/bobrenjc93/1136/base
  • Verify the new classmethod-invariant comment is accurate and complete
  • Re-check imports/cycle after the module-level promotion
  • Post updated review

The comment addresses the finding, and it is technically correct

package.py:123-126:

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

Each of the three claims holds:

  • "pickle reduces a bound classmethod to getattr(owner, name)" — correct. CPython does not register types.MethodType in Pickler.dispatch, so a bound classmethod falls through to the C-level method_reduce, which emits (getattr, (__self__, __func__.__name__)).
  • "an artifact names the subclass and resolves the reducer through its MRO" — correct, and it depends on the call sites, which I re-checked: all three are type(self)._unpickle_* (guards.py:4317, guards.py:4392, guards.py:4477), so __self__ stays GuardsStatePickler and the moved definitions are invisible in the emitted opcodes.
  • "A staticmethod would pickle by __qualname__ and change the artifact" — correct. Class access on a staticmethod yields a plain FunctionType, which routes to save_global and would serialize as torch._dynamo.package / FunctionPicklerBase._unpickle_code instead of the current subclass-qualified reference.

The plural "The reducers" makes it clear the comment governs all three definitions below it, not just the adjacent _unpickle_code. Placement above the block rather than in the docstring is the better call — it sits where someone editing a decorator will actually see it.

The two remaining points from my earlier review (docstring wording describing the stack's end state; reducer_override predicates still duplicated between guards.py:4306-4478 and aot_compile.py:119-153) are answered in the description's FAQ, and I accept both answers: the docstring paragraph does say GuardsStatePickler is the one subclass today, and keeping aot_compile.py untouched so the AOT move is one reviewable step is the right sequencing.

Re-verification of the load-bearing claims

Both still hold on the current tree:

  • No import cycle from promoting from torch._dynamo.package import FunctionPicklerBase, SerializedCode to module level (guards.py:77). Re-checked the module-level closure of package.py (torch._dynamo.exc, torch._dynamo.graph_utils, torch.utils.weak, .bytecode_transformation, .utils) — none imports torch._dynamo.guards at module level. The hits in utils.py are all torch._guards, a different module. package.py's only torch._dynamo.guards import stays under if TYPE_CHECKING: (package.py:49-50).
  • import pickle is genuinely dead in guards.py — no remaining pickle. attribute access; importlib (3 uses) and types (23 uses) are still needed and correctly retained.
  • Payload unchanged in both directions, per the reducer analysis above. The alias -> name rename in _unpickle_python_module is safe because the reduce tuple passes it positionally (guards.py:4392).

One small forward-looking note for the follow-up (not this PR)

The base's signatures are looser than the AOT copies they will replace: package.py:136 is (func: Any, base: Any) while aot_compile.py:93 is (func: Callable, base: object) with a # pyrefly: ignore [implicit-any] above it. When AOTCompilePickler moves onto the base, it loses the tighter annotations, and that pyrefly suppression becomes stale and should be dropped rather than carried along. Cheap to tighten the base at that point; no reason to churn this diff for it.

Recommendation

Approve. The requested one-line invariant is in place and correct, the move remains payload-compatible, and the deferred items are deliberate stack sequencing rather than gaps. I did not run test/dynamo/test_guard_serialization.py — no build was available in this environment.

· branch [`gh/bobrenjc93/1136/head`](https://github.com/pytorch/pytorch/tree/gh/bobrenjc93/1136/head)

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 10, 2026
No behavior change: the reducers that rebuild objects pickle cannot do by
reference -- code objects, python modules, bound methods -- move from
`GuardsStatePickler` into a `FunctionPicklerBase` in package.py with their
bodies unchanged (one parameter renamed, one return annotation tightened), and
`GuardsStatePickler` subclasses it. The follow-up commits add the by-value
function reconstruction to this base. `AOTCompilePickler` still carries its
own copies of these reducers; moving it onto the base is done separately so a
fix to how an object is rebuilt cannot be missed in one of the two picklers.

The reducers are pickled by reference as `getattr(GuardsStatePickler, name)`
(pickle records the bound classmethod's owner), so an artifact records the
same reference before and after this move; they have to stay classmethods for
that reason. When `AOTCompilePickler` moves onto the base it must consciously
replace its own `_unpickle_module` (an `importlib` import) with the inherited
`_unpickle_python_module`, since `GuardsStatePickler._unpickle_module`
rebuilds an `nn.Module`.

guards.py now imports `SerializedCode` at module level (package.py does not
import guards.py, so there is no cycle) instead of inside two methods, and
drops `import pickle`, whose only use was the base class.

Test Plan:

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

Authored with an AI assistant.

FAQ

Q: The docstring says the base exists "so that a fix cannot be missed in one
pickler", but there is exactly one subclass at this commit.

A: The same paragraph states that `GuardsStatePickler` is the one subclass
today; the clause is the reason `AOTCompilePickler` is moved onto the base
separately, not a claim that it already has been.

Q: The base shares the reducer bodies, but both `reducer_override`s still
duplicate the `iscode`/`ismodule`/`ismethod` dispatch predicates.

A: This change is a pure move that prepares the base, and aot_compile.py is
deliberately untouched in this stack so the AOT move is one reviewable step.
The bound-method predicate does move into the base later in the stack
(`FunctionPicklerBase._reduce_bound_method`); the remaining predicates are
one-liners whose divergence risk lives in the reducer bodies the base now owns.

ghstack-source-id: aca9dfb
Pull-Request: #196471
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Round-2 review found nothing further to change here.

@claude

@claude

claude Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 1m 31s —— View job


The reworded docstring at package.py:118-121 now scopes the shared-fix claim to the future state ("until it is moved onto this base separately; once both share it, ..."), which is the only change in this PR since round 3 — my approval stands and I have nothing further.

Round-4 verification

Round 4: #196471

  • Re-diff against origin/gh/bobrenjc93/1136/base
  • Read the reworded docstring and check it is now accurate for this commit
  • Confirm nothing else in the PR moved
  • Re-verify the round-2/3 load-bearing claims on the current tree

The rewording is the whole delta, and it fixes the tense problem

Diffing this PR's contents against the round-3 state (5be6158...7a2a8d5 vs base...HEAD) shows exactly one hunk changed — the docstring's second paragraph. Everything else is byte-identical.

Before (round 3), the sentence asserted the invariant in the present tense while AOTCompilePickler still had its own copies:

    own copies of these reducers and is moved onto this base separately, so
    that a fix to how an object is rebuilt cannot be missed in one pickler.

Now (package.py:118-121):

    GuardsStatePickler is the one subclass today. AOTCompilePickler keeps its
    own copies of these reducers until it is moved onto this base separately;
    once both share it, a fix to how an object is rebuilt cannot be missed in
    one pickler.

until + once both share it makes the guarantee explicitly conditional on a step that has not happened yet, so a reader landing here via git blame is told the current state rather than having to reconcile "cannot be missed in one pickler" against a single subclass. I verified the premise is still literally true on this tree: aot_compile.py:64 is still class AOTCompilePickler(pickle.Pickler), with its own _unpickle_bound_method (:93), _unpickle_module (:97) and _unpickle_code (:101). This closes the second Code Quality note from my round-1 review; the first (the classmethod invariant) was addressed in round 2.

The paragraph is also now the docstring's own answer to the description's first FAQ entry, so the FAQ is arguably redundant for this point — not worth a change either way.

Round-2/3 conclusions re-checked, not assumed

A base rebase can invalidate an import-cycle argument even when the PR's own lines don't move, so I re-ran the checks rather than carrying them forward:

  • Payload still byte-identical. All three reducers are still @classmethod (package.py:128, :132, :136), and all three call sites still resolve off the subclass: type(self)._unpickle_code (guards.py:4320), type(self)._unpickle_python_module (guards.py:4395), type(self)._unpickle_bound_method (guards.py:4480). CPython does not register types.MethodType in Pickler.dispatch, so a bound classmethod falls through to the C-level method_reduce, which emits (getattr, (__self__, __func__.__name__)); __self__ remains GuardsStatePickler, so the emitted opcodes are unchanged and the inheritance is invisible in the bytes. Loads in both directions.
  • Still no import cycle from the module-level from torch._dynamo.package import FunctionPicklerBase, SerializedCode (guards.py:74). package.py's only references to torch._dynamo.guards are the TYPE_CHECKING import at package.py:50 and two in-function uses (package.py:172, package.py:1037) — no module-level path from package back to guards.
  • import pickle still genuinely dead in guards.py — grep finds no surviving pickle. attribute access; importlib is still needed (guards.py:879, 1807, 4307) and correctly retained.
  • The alias -> name rename in _unpickle_python_module remains safe — the reduce tuple passes it positionally (guards.py:4395).

The remaining deferred item (both reducer_overrides still duplicating the iscode/ismodule/ismethod dispatch predicates, guards.py:4317-4480 vs aot_compile.py:119-142) is answered in the description's FAQ, and I accept the sequencing: keeping aot_compile.py untouched makes the AOT move one reviewable step. My earlier forward-looking notes for that follow-up still apply — dropping AOTCompilePickler._unpickle_module (an importlib import) in favour of the inherited _unpickle_python_module must be a deliberate step rather than an apparent no-op rename, since GuardsStatePickler._unpickle_module means something entirely different (it rebuilds an nn.Module), and the stale # pyrefly: ignore [implicit-any] above aot_compile.py:93 should be dropped rather than carried along.

Recommendation

Approve — unchanged from rounds 2 and 3. Both actionable items from my first review are now resolved in the code, and this remains a payload-compatible pure move. I did not run test/dynamo/test_guard_serialization.py; no build is available in this environment.

· branch [`gh/bobrenjc93/1136/head`](https://github.com/pytorch/pytorch/tree/gh/bobrenjc93/1136/head)

bobrenjc93 added a commit that referenced this pull request Sep 10, 2026
A pure move with no behavior change. Within this stack the new base class has
exactly ONE subclass, `GuardsStatePickler`; the second user is
`AOTCompilePickler`, which #196454 (in the stack above, not yet rebased onto
this one) moves onto the base. The extraction happens here so the next five
commits have one place to add the by-value function reducers that both
picklers will share.

`GuardsStatePickler` (guard state) and `AOTCompilePickler`
(torch/_dynamo/aot_compile.py, the AOT compile artifact) both have to rebuild
objects that pickle cannot do by reference -- code objects, python modules,
bound methods -- and each carries its own copy of those reducers. This commit
moves `GuardsStatePickler`'s copies into a new `FunctionPicklerBase` in
package.py and makes `GuardsStatePickler` subclass it. Bodies are unchanged
(one parameter renamed, one return annotation tightened).

Until #196454 lands, `AOTCompilePickler` keeps its own copies of these
reducers, including the same bugs the commits here fix in the guard pickler
(an unguarded `cell_contents` read and the old nested-function rebuild).
#196454 changes its base to `FunctionPicklerBase` and deletes the duplicates;
because the closure-cell, bound-method and by-value function reducers that
#196472-#196478 add already live on the base, that move is a one-line
base-class change rather than a second relocation of the code.

The reducers are pickled by reference as `getattr(GuardsStatePickler, name)`
(pickle records the bound classmethod's owner), so an artifact records the
same reference before and after this move; they have to stay classmethods for
that reason. When `AOTCompilePickler` moves onto the base it must consciously
replace its own `_unpickle_module` (an `importlib` import) with the inherited
`_unpickle_python_module`, since `GuardsStatePickler._unpickle_module`
rebuilds an `nn.Module`.

guards.py now imports `SerializedCode` at module level (package.py does not
import guards.py, so there is no cycle) instead of inside two methods, and
drops `import pickle`, whose only use was the base class.

Test Plan:

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

Authored with an AI assistant.

FAQ

Q: The docstring says the base exists "so that a fix cannot be missed in one
pickler", but there is exactly one subclass at this commit.

A: The same paragraph states that `GuardsStatePickler` is the one subclass
today; the clause is the reason `AOTCompilePickler` is moved onto the base
separately, not a claim that it already has been.

Q: The base shares the reducer bodies, but both `reducer_override`s still
duplicate the `iscode`/`ismodule`/`ismethod` dispatch predicates.

A: This change is a pure move that prepares the base, and aot_compile.py is
deliberately untouched in this stack so the AOT move is one reviewable step.
The bound-method predicate does move into the base later in the stack
(`FunctionPicklerBase._reduce_bound_method`); the remaining predicates are
one-liners whose divergence risk lives in the reducer bodies the base now owns.

ghstack-source-id: 14e22de
Pull-Request: #196471
@bobrenjc93 bobrenjc93 added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 10, 2026
[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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #196472

pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
…196472)

When Dynamo serializes guard state it pickles some functions by value (every
`<locals>` function reached through a capture, and the wrapped functions the
commits above add), and pickling a function by value pickles every cell in its
`__closure__`. The old reducer read the cell's contents up front and passed
them as a constructor argument, `_unpickle_cell(cell.cell_contents)`. Two
ordinary shapes broke on that:

    def make(captured):
        def fn(x):
            if x is None:
                return unset  # never runs
            return x + captured

        if captured is None:
            unset = 1  # never runs, so the cell for `unset` stays EMPTY

        return fn

`fn` closes over `captured` (filled) and `unset` (never assigned, so its cell
is empty). Tracing a call to `fn` installs a TENSOR_MATCH on `captured`, and
serializing that guard state pickles `fn` with its closure. Reading
`cell_contents` on the empty cell raised `ValueError: Cell is empty` out of the
pickler: a `PackageError` under strict precompile (an internal error before the
previous commit), a bypass of a perfectly serializable frame otherwise.

    def outer():
        def fact(n):
            return 1 if n <= 1 else n * fact(n - 1)
        return fact

`fact`'s one cell contains `fact` itself. Pickling `fact` pickles its cell,
whose constructor argument was `fact`, which is not memoized yet because it is
still being pickled, so pickle started over: `RecursionError`, reported as
"exceeded the recursion limit while pickling guard state".

The fix rebuilds a cell in two steps, an empty `types.CellType()` that pickle
memoizes first and its contents assigned afterwards as pickle state. A cell
that refers back to its own function no longer recurses: the second time pickle
reaches the function it finds the CELL memoized, builds the inner copy of the
function and sets the cell's contents to it, and the outer `save_reduce` then
drops its duplicate through the recursive-object fallback because the object
is in the memo by then. A genuinely empty cell (reading
`cell_contents` raised `ValueError`) carries no state and is rebuilt empty,
and the contents are wrapped in a 1-tuple because pickle skips the state step
for a bare None, which would otherwise turn a cell holding None into an empty
one. The reducer lives on `FunctionPicklerBase` so the function-rebuilding
commits above share it; `AOTCompilePickler` keeps its own unguarded read until
#196454 moves it onto the base.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k test_empty_closure_cell_of_a_traced_local_function -k test_reduce_handles_an_empty_cell_reached_directly -k test_reduce_keeps_a_none_valued_cell -k test_reduce_preserves_a_self_referential_cell
```

On the previous commit the capture test and the direct-cell test error with
`ValueError: Cell is empty` and the self-referential one with `RecursionError`;
the capture test is the realistic trigger (a traced local function with an
empty sibling cell), the pickler-level one covers a raw cell, which no
serializable guard type can root at (CLOSURE_MATCH is unsupported). The new
`TestGuardsStatePickler` class drives the pickler directly.

Authored with an AI assistant.

FAQ

Q: Isn't the `keep_name_with_empty_cell` / `functools.wraps` / module-level
`EMPTY_CELL_WRAPPED` fixture more than this change needs? A local helper that
returns an empty cell would do.

A: At this commit only the empty cell is needed, but the fixture is shaped for
the by-value function commits above it: one pickles `EMPTY_CELL_WRAPPED`
itself as a rebuilt function with an empty sibling cell, and another renames
the wrapped function to prove the wrapper is rebuilt rather than resolved by
name. Defining it once here avoids reshaping it two commits later.

Q: The `FunctionPicklerBase` docstring claims a shared-fix invariant that
`AOTCompilePickler` violates.

A: The docstring states that `GuardsStatePickler` is the only subclass and
that `AOTCompilePickler` keeps its own copies until it is moved onto the base
separately; `prepare_f_locals` dereferences cells unconditionally there, so
that migration is a standalone change.

Pull Request resolved: #196472
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196505, #196470, #196471
pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
… getattr cannot resolve it (#196473)

A bound method (`obj.method`) is a pair: the function, and the object it was
fetched from -- the receiver, the `self` it will run against. Normally the pair
comes from a class attribute lookup, so it can be re-derived: `getattr(obj,
"method")` gives it back. Python also lets you build the pair by hand with
`types.MethodType(func, obj)`, in which case `obj`'s class may have no
attribute of that name at all. pickle's built-in rule for a bound method
stores the receiver and the NAME and does `getattr(receiver, name)` at load;
it never stores the function. The guard pickler therefore has an explicit
alternative that stores `(func, receiver)` -- the function by value (its code
object, rebuilt with `types.FunctionType`) and the receiver as the pickler
would store it anyway -- and rebuilds with `types.MethodType`.

Dynamo needs this whenever a compiled function receives a bound method:

    def on_step(state, x):
        return x + state.offset

    class State:
        offset = 1

    callback = types.MethodType(on_step, State())  # bind the state as `self`

    def fn(f, x):
        if callable(f):
            x = x + 1
        return f(x)

    torch.compile(fn)(callback, torch.randn(3))

`callable(f)` installs a TYPE_MATCH on `f`, and inlining `f(x)` adds an
ID_MATCH on `f.__func__.__code__` and a TYPE_MATCH on `f.__self__`. To
precompile, the bound method object is pickled with the guard state, and at
load those sources are re-walked against the reconstructed object, so it must
carry the same function and the same receiver.

The old code chose between pickle's rule and the explicit pair with a probe,
`getattr(receiver, func.__name__)`, taking the explicit pair only when the
probe did not return the same function. The probe was the bug:

- For `callback` it ran `getattr(State(), "on_step")`; `State` has no such
  attribute, and the AttributeError escaped the reducer: a PackageError under
  strict precompile, a bypass of a fine frame otherwise (an internal error
  before #196470 mapped every reducer exception to a PackageError). pickle's rule would have failed the same way at
  load, so the explicit pair is the only form that works here.
- A `functools.partial` as the method's function has no `__name__`, so the
  probe raised before looking anything up.
- A class holding the function as a `staticmethod` under that name makes the
  probe return the raw function, so `func is inner` held, pickle's rule ran,
  and the object loaded back as a plain function where a bound method was.
- Any receiver whose class defines `__getattr__` -- every nn.Module -- runs
  that user code in the probe, which can have side effects or recurse. And its
  answer means nothing for this pickler: a non-referenceable module is rebuilt
  as a bare `torch.nn.Module` placeholder at load, on which `getattr` would
  not find `forward`.

The nn.Module case also shows why the explicit pair, not the class, is what
makes the method reloadable. A module whose class is not a module-level name
cannot be pickled by reference, so the guard pickler stores its state and
rebuilds it as a plain `torch.nn.Module` with that state; the class is
forgotten. pickle's rule would then look `forward` up on the plain module and
find nn.Module's placeholder. With the explicit pair the loaded method is that
plain module with `forward`'s own code attached by `types.MethodType`, which is
all the guards read (the pickler-level test pins this; end to end this exact
shape is refused earlier by the local-class TYPE_MATCH check).

The fix moves the decision into `FunctionPicklerBase._reduce_bound_method`,
which stores the explicit pair unless it can PROVE pickle's rule will produce
the same bound method at load:

1. A receiver whose class defines `__getattr__` is never probed; the pair is
   stored without touching the instance. This is deliberately coarse; a false
   "store the pair" is still correct, and narrowing it per name with
   `getattr_static` at every guard build buys nothing but cost.
2. A name served per instance (in the instance `__dict__`, or a `__slots__`
   member) is stored as the pair: `getattr` at load hands back whatever the
   dict or slot holds -- a raw function or a method bound to another object --
   never a method over this pair (and in the self-cycle case the slot is not
   restored yet).
3. Otherwise probe, under a `try`: `getattr(receiver, name)` can raise anything
   through a `__getattribute__` override, a property or a metaclass
   `__getattr__`, and any exception falls back to the pair instead of escaping
   the reducer. A function without `__name__` skips the probe.
4. pickle's rule is taken only on proof: the probe must return a method bound
   to THIS receiver over THIS function (`inspect.ismethod(inner) and
   inner.__func__ is func and inner.__self__ is receiver`).

A method the class genuinely supplies to a plain instance still takes pickle's
compact rule, so ordinary bound methods pickle exactly as before.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k bound_method
```

Eight of the thirteen tests matched by the second command fail or error
against the previous commit's logic: seven new pickler-level tests (name self
lacks, slot, `__getattr__` proxy, raising probes, staticmethod name, a
`functools.partial` as `__func__`, the nn.Module method) and the one new
capture test. The fall-through test pins that plain methods and classmethods
keep pickle's compact `getattr` form (an always-explicit implementation fails
it); the four pre-existing `bound_method` capture tests pass on both. A known
gap closed by #196481: an nn.Module method whose `__func__` is fqn-mismatched
now reaches the `isfunction` branch and is pruned to `_Missing` unless a guard
registers the function, where pickle's name-based rule never needed the fqn.
The staticmethod case also fails against a plain `func is inner` check,
loading a function. The proxy test asserts the receiver's `__getattr__` was
never asked for the method name (pickle itself may probe protocol names on
the instance); the nn.Module test uses a function-local class so the receiver
is rebuilt as a bare `nn.Module`, where the default reconstruction would
resolve `forward` to the placeholder.

Authored with an AI assistant.

FAQ

Q: Should the `__getattr__` gate be narrowed with `getattr_static` so that
nn.Module methods stay on pickle's default path?

A: No. The default path rebuilds the method as `getattr(self, name)` on the
RELOADED receiver, and `GuardsStatePickler` rebuilds any nn.Module whose class
cannot be pickled by reference as a bare `torch.nn.Module`, on which `forward`
resolves to `_forward_unimplemented`. Empirically the narrowed gate loads that
placeholder and raises `NotImplementedError` on call; the coarse gate loads the
right function. A class-body lambda `forward` on a module-level class degrades
to `_Missing` under both gates, because the name a bound method reduces by is
`__func__.__name__`, i.e. `<lambda>`, not `forward` (on a function-local class
its qualname contains `<locals>`, so it is rebuilt from its code object and
loads fine); it raised `AttributeError` before this change, so it is not a
regression. The same fact covers the `functools.partial` case: pickle's own
`method.__reduce__` reads `__func__.__name__`, so a partial `__func__` is
unpicklable on the default path regardless of this reducer.

Q: Could the three receiver tests be one parametrized test?

A: Each asserts something different (the bound-method type for the
staticmethod case, `.func` of the partial, the receiver class for the module)
and documents a distinct failure mode; a shared body would need per-case
assertions.

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

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.

Pull Request resolved: #196474
Approved by: https://github.com/pytorchgreenlight, https://github.com/aorenste
ghstack dependencies: #196505, #196470, #196471, #196472, #196473
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
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1136/head branch November 18, 2026 01:44
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.

2 participants