Skip to content

[dynamo] Carry a bound method's function and receiver explicitly when getattr cannot resolve it - #196473

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

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

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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 [dynamo] Surface an unpicklable guarded value as a PackageError, not an internal error #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.

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

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

⏳ No Failures, 2 Pending

As of commit a75feb0 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
    • Replaces the unguarded getattr(method_self, func.__name__) probe (old guards.py hunk) with FunctionPicklerBase._reduce_bound_method at torch/_dynamo/package.py:166-224
    • The fall-through to pickle's default path is strictly stricter than the old func is not inner_func: it requires inspect.ismethod(inner) and inner.__func__ is func and inner.__self__ is receiver (package.py:218-223)
    • Every receiver read (__dict__, getattr_static, the resolution getattr, and hasattr(cls, "__getattr__")) is inside the try at package.py:192-213, so a raising probe returns explicit instead of escaping the reducer
  • Testing
    • Eight new pickler tests at test/dynamo/test_guard_serialization.py:622-722 reach each return: name-self-lacks, __slots__ member, __getattr__ proxy, raising __getattribute__, staticmethod name, functools.partial __func__, classmethod fall-through, and nn.Module
    • test_bound_method_the_class_resolves_falls_through (:676-681) asserts _reduce_bound_method returns None for PlainMethods().add and PlainMethods.make, pinning that ordinary methods keep pickle's compact form
    • test_bound_method_of_a_module_keeps_its_function (:703-722) calls the loaded method and checks the result, proving _unpickle_module's bare torch.nn.Module (guards.py:4176-4179) does not resolve to the forward placeholder
  • Scope
    • Confined to the inspect.ismethod branch of GuardsStatePickler.reducer_override (guards.py:4463-4466) plus the new base-class helper; no public API, CI, or build file touched
    • Broadening the explicit path to all __getattr__ receivers routes the function through the inspect.isfunction branch (guards.py:4448-4462), where a module-level forward resolves by fqn and a class-body lambda degrades to _Missing from a pre-change AttributeError bypass
    • AOTCompilePickler's duplicate of the old logic is untouched but disclosed by the FunctionPicklerBase docstring at package.py:118-121, so no stale guarantee is left behind

reason: clean
Reviewed commit: a75feb0

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 45m 34s —— View job


PR Review: #196473

Moving the bound-method reduce decision into FunctionPicklerBase._reduce_bound_method fixes a real crash, but the sibling pickler that the base class exists to keep in sync was not updated, the __getattr__ gate is broader than the "harmless" claim in the description, and one of the three motivating bugs has no test.

Full review

Summary

Replaces the unguarded getattr(self, func.__name__) probe in GuardsStatePickler.reducer_override with a new shared FunctionPicklerBase._reduce_bound_method that decides structurally whether a name is served per-instance. The underlying AttributeError-escaping-the-reducer bug is real and the fix is the right shape, but three things need addressing before landing.

Infrastructure

  • torch/_dynamo/aot_compile.py:129-142 still contains the exact bug this PR fixes, and this PR is what makes that a documented contract violation. AOTCompilePickler declares class AOTCompilePickler(pickle.Pickler) (aot_compile.py:64) — not FunctionPicklerBase — and carries a verbatim copy of the old logic:

    func = obj.__func__
    method_self = obj.__self__
    inner_func = getattr(method_self, func.__name__)   # aot_compile.py:138

    All three failure modes named in the PR description are present here unchanged: a name self lacks raises AttributeError out of the reducer, a functools.partial __func__ raises on func.__name__, and a __getattr__ receiver gets probed. It also misses the instance-__dict__ and __slots__ cases the pre-PR code was written for. FunctionPicklerBase.__doc__ (package.py:115-118) states the invariant this breaks verbatim:

    "Each subclass keeps its own dispatch; this class fixes HOW they are rebuilt so a fix in one pickler cannot be missed in the other."

    The docstring says "the other" but there is exactly one subclass (GuardsStatePickler, guards.py:4155) and AOTCompilePickler is the pickler it was written about. Either reparent AOTCompilePickler onto FunctionPicklerBase and delete its duplicated _unpickle_bound_method / _unpickle_code / _unpickle_module / _unpickle_nested_function (aot_compile.py:93-116, all byte-identical to the base), or drop the "cannot be missed in the other" claim from the docstring. As it stands the docstring is asserting a guarantee the PR does not deliver. Its cell reducer diverges the same way — aot_compile.py:120-121 reads obj.cell_contents unguarded, the empty-cell ValueError that _reduce_cell (package.py:144-157) exists to handle. Fix this →

Code Quality

  • hasattr(cls, "__getattr__") (package.py:186) is not harmless for nn.Module, and narrowing it is free. torch.nn.Module defines __getattr__ (torch/nn/modules/module.py:1963), so every nn.Module bound method now takes the explicit (func, self) path and the func is inner fall-through at package.py:190-195 becomes unreachable for module receivers. The description argues this "only rebuilds the method from (func, self), which is correct" — but on that path the raw function object is pickled as a first-class value and therefore flows through GuardsStatePickler.reducer_override's inspect.isfunction branch (guards.py:4444-4458), which the default getattr(self, name) reduce never touched. A class-body lambda degrades:

    class M(torch.nn.Module):
        forward = lambda self, x: x     # __qualname__ == "M.<lambda>"

    The fqn walk at guards.py:4455-4456 does getattr(M, "<lambda>", None) → None is not obj → _Missing, ("fqn mismatch") (guards.py:4457-4458), and the method rebuilds as types.MethodType(_Missing(...), self). Pre-PR this returned None and round-tripped via getattr(m, "forward"). Separately, every method of a function-local nn.Module subclass — the dominant shape in test_guard_serialization.py itself, e.g. line 647 — now goes through _unpickle_nested_function (guards.py:4445-4452), which pickles __closure__ and loses function identity. pickle_guards_state's broad except Exception (guards.py:4579-4585) turns any resulting failure into a PackageError bypass rather than a crash, so this shows up as a silently narrower package, not a test failure.

    The stated reason for keeping the gate coarse — "narrowing it with getattr_static per name at every guard build buys nothing but cost" — does not hold on either half. It buys keeping every nn.Module method on the cheap default path, and it costs nothing: package.py:182 already calls inspect.getattr_static(cls, name, None). Hoist that one call into a local and gate on it:

    static = inspect.getattr_static(cls, name, None) if name is not None else None
    instance_served = not isinstance(method.__self__, type) and (
        (isinstance(self_dict, dict) and name in self_dict)
        or isinstance(static, types.MemberDescriptorType)
        or (static is None and hasattr(cls, "__getattr__"))
    )

    static is None is exactly the condition under which __getattr__ could be what serves the name, so this is a strict tightening with no new probing. Fix this →

  • The reducer still performs unguarded attribute lookups on user objects, so it still runs user code and still raises. The docstring goal is to avoid probing, but two lookups survive. package.py:190 getattr(method.__self__, name, None) invokes descriptors, and the three-arg default swallows only AttributeError:

    def g(): pass
    g.__name__ = "prop"
    class C:
        @property
        def prop(self): raise ValueError("boom")
    # _reduce_bound_method(types.MethodType(g, C())) -> ValueError

    And package.py:176 getattr(method.__self__, "__dict__", None) is a new lookup with no pre-PR equivalent, so a __getattribute__ override that raises non-AttributeError on "__dict__" is a failure mode this PR introduces. A class receiver is also still probed: not isinstance(method.__self__, type) at :177 short-circuits the whole exemption group, so for a name absent from the class MRO the metaclass __getattr__ runs at :190 — the exact user-code execution the PR set out to avoid, just relocated from instances to classes. Either wrap :176/:186/:190 in a try/except Exception that falls back to the explicit reduce (the conservative direction is always safe: an unnecessary (func, self) is still correct), or use inspect.getattr_static for the probe too. If instead the position is that a raise here is acceptable because pickle_guards_state converts it to a bypass, the docstring at package.py:164-166 should say that rather than claiming it "falls through to the explicit reduce rather than raising out of the reducer."

  • The description says "a functools.partial receiver has no __name__" — it is method.__func__ that is the partial, not the receiver. The in-code comment at package.py:164-166 gets this right; the PR body does not.

  • test_bound_method_under_a_slot_name's comment (test:579-581) asserts a rationale the test does not exercise: "the slot value is restored only after the method is rebuilt" describes a reference cycle, but the slot holds global_add, not the method, so there is no ordering dependency in this test. The three new pickler tests also restate package.py:167-174 nearly verbatim on top of the class-level comments at test:150-151 and test:156-157 — three copies of one rationale. The cross-reference style used at test:615 is the right one.

Testing

  • The functools.partial branch — one of the three bugs the description claims to fix — has no test. package.py:167 name = getattr(func, "__name__", None) and the name is not None guards at :180 and :190 are entirely uncovered; nothing in the file constructs types.MethodType(functools.partial(f, 1), obj). This is the branch most likely to be broken by a future refactor, since a reader who does not know MethodType accepts arbitrary callables will "simplify" getattr(func, "__name__", None) to func.__name__. Fix this →

  • test_bound_method_on_a_getattr_proxy_is_not_probed (test:591) does not test what its name asserts. GetattrProxy.__getattr__ (test:156-161) is benign and records nothing, so the test only checks the round-trip result — it would pass unchanged if the implementation probed. The hazard the production comment cites at package.py:173 ("it can recurse") is untested. Have __getattr__ append to a list and assertEqual(probes, []), or make it recurse so a probing implementation blows the stack.

  • The func is inner fall-through at package.py:194-195 has no assertion on the reduce result anywhere. A future change that made every method take the explicit path would pass the entire file silently — which matters precisely because, per the Code Quality finding above, that is already what happens for nn.Module. One assertIsNone(pickler._reduce_bound_method(MyClass().add)) pins it.

  • The class-receiver exemption (isinstance(method.__self__, type), package.py:177) has no test — no classmethod or metaclass case exists in the file.

  • The three new pickler tests (test:564, :577, :591) differ only in the receiver and otherwise share an identical five-line body. CLAUDE.md asks for @parametrize over multiple inputs; a single parametrized test over [Inputs(1, 2), SlottedByName_instance, GetattrProxy()] would read better and make adding the partial case a one-line change.

Recommendation

Request Changes

The core fix is correct and worth landing. Blocking items: the functools.partial branch is claimed as fixed in the description but untested, and the hasattr(cls, "__getattr__") gate silently changes what gets pickled for every nn.Module method with a free and strictly-safer narrowing available. The AOTCompilePickler divergence is pre-existing, but this PR is what turns FunctionPicklerBase's docstring guarantee into a false statement, so it should be resolved here — by fixing it or by softening the docstring.

| Branch: `gh/bobrenjc93/1138/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. From the review: every probe that touches the receiver (__dict__, getattr_static, the resolution getattr) runs under a try and falls back to the explicit reduce, with a test for a raising __getattribute__; the __getattr__ gate is evaluated first so such receivers are never probed, and the proxy test now asserts that; the nn.Module test uses a function-local class so the receiver is rebuilt as a bare nn.Module; there are tests for the fall-through (plain method, classmethod), a functools.partial __func__, and a staticmethod name; the message says partial as __func__, not receiver. Narrowing the gate with getattr_static and parametrizing the receiver tests 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 34m 12s —— View job


Re-review: #196473

Every item I raised is addressed and the new tests pin the behavior they claim — one pre-merge check remains: assertEqual(GetattrProxy.probed, []) also captures pickle's own dunder lookups, which differ on Python 3.10.

Full review

Verification of the claimed changes

Claim Where Verdict
Every receiver probe under try, falling back to the explicit reduce package.py:188-206 Confirmed — __dict__, getattr_static, and the resolution getattr are all inside one try/except Exception, and RaisingProbes (test:191-197, :667-676) exercises the __dict__ probe specifically, which was the lookup this PR introduced
__getattr__ gate evaluated first, receiver never read package.py:186 before the try Confirmed
Proxy test asserts no probing test:654-666 Confirmed structurally; see the 3.10 caveat below
nn.Module test uses a function-local class test:704-719 Confirmed, and it is the strongest test in the set — {id(mod): mod} keeps the module out of _Missing, the local class forces _unpickle_module → bare nn.Module, and assertEqual(out(torch.ones(1)), ...) proves the placeholder was not loaded. This is the empirical backing the FAQ needed
Fall-through tests (plain method, classmethod) test:678-683 Confirmed — pins both package.py:211-216 and the isinstance(receiver, type) exemption at :190
functools.partial __func__ test:694-702 Confirmed — name is None now reaches both guards at :191 and :201
staticmethod name test:685-692 Confirmed, with assertIsInstance(out, types.MethodType) — the assertion that a plain func is inner check would fail
Message says partial as __func__ PR body Confirmed

The getattr_static narrowing and the parametrization are answered in the FAQ; I withdraw both. On the narrowing specifically, the function-local module test settles it — the narrowed gate would route that receiver back onto getattr(self, "forward") against a bare nn.Module.

One pre-merge check

  • assertEqual(GetattrProxy.probed, []) (test:663) asserts more than the PR controls, and the extra part is version-dependent. probed records every failed attribute lookup on the instance, including the ones the pickler makes while serializing the receiver as a first-class value. object.__getstate__ only exists from Python 3.11; on 3.10 object.__reduce_ex__ looks __getstate__ up on the instance and falls back on AttributeError, which is exactly the classic proxy-class gotcha — that lookup would land in probed and fail this assertion. pyproject.toml:348 sets requires-python = ">=3.10" and .ci/docker/build.sh still builds many py3.10 images, so this can go red on a config you did not run locally. I could not confirm on 3.10 here (no 3.10 interpreter in this checkout). The narrower assertion is also the more precise one, since the claim under test is that the resolution probe never happens:

    self.assertNotIn("global_add", GetattrProxy.probed)

    Fix this →

Nits, none blocking

  • hasattr(cls, "__getattr__") (package.py:186) is the last lookup outside the try. For a class with a custom metaclass defining __getattr__, that lookup runs user code, and hasattr swallows only AttributeError — a metaclass __getattr__ raising RuntimeError escapes the reducer, the failure mode the rest of the function now handles. Moving the gate inside the try (before the __dict__ read, so the ordering guarantee is kept) closes it in one line.
  • isinstance(receiver, type) is evaluated twice (package.py:186, :190). A local would read better and makes the "type receiver is exempt from all three per-instance cases" structure visible in one place.
  • The slot test's comment (test:641-646) still describes the self-bound-method cycle, which the test does not construct — the "that also covers" phrasing no longer overclaims, but a reader may go looking for the cycle.
  • The FAQ's "explicit reduce, which is always correct" is true of the shape but not always of the payload: on that path the raw function is pickled as a first-class value and can degrade to _Missing("fqn mismatch") (guards.py:4455-4460). The FAQ already concedes this for the class-body lambda; worth remembering that it generalizes to any method function whose __qualname__ does not resolve.
  • AOTCompilePickler still carries the pre-fix copy (aot_compile.py:129-142) and the unguarded obj.cell_contents (aot_compile.py:120-121). The base docstring (package.py:118-120) now says explicitly that it is moved onto the base separately, so this is disclosed rather than a broken guarantee — dropping my earlier objection, but the AttributeError bug does still exist on that path.

Recommendation

Approve once the probed assertion is either narrowed or confirmed green on Python 3.10. The core change is correct and the test set now covers each branch of _reduce_bound_method, including the fall-through that a future refactor would most easily break.

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

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Round-2 review follow-up: message corrections only (the -k bound_method selection and count; the FAQ's lambda example holds for a module-level class, while a function-local class's lambda is rebuilt through the <locals> path).

@claude

@claude

claude Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

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


Round-3 review: #196473

The code is byte-identical to round 2, so this is message-only as stated; the "thirteen matched / nine failing" arithmetic checks out and the FAQ's lambda claim is correct, but the correction to "partial receiver" landed in the prose paragraph and not in the Test Plan sentence where the phrase actually appears.

Full review

Diff is unchanged (message-only confirmed)

git diff origin/gh/bobrenjc93/1138/base...HEAD is the same three-file, +213/-7 change reviewed in round 2. The two source hunks that appear between the round-2 head (f4d0081) and this head (c5208bc) — raise_local_type_error (guards.py:1025) and the _DynamoCodeCacheEntry docstring (package.py:331) — are absorbed by the base update (eb6ba6f → f6b165b), not part of this commit's diff. Nothing in _reduce_bound_method or reducer_override moved.

-k bound_method: the count is right, the parenthetical is not

Thirteen is correct. unittest -k is a case-sensitive substring match on the test id, so bound_methods_missing/bound_methods_empty are included, and TestGuardSerializationFSDP derives from TestGuardSerializationBase rather than TestGuardSerialization, so it contributes none:

Test Class On the base
test_bound_method_under_a_name_self_lacks (test:625) Pickler fails — getattr(self, "global_add") raises AttributeError
test_bound_method_under_a_slot_name (:638) Pickler fails — slot hands back the raw function, func is inner holds, out.__func__ missing
test_bound_method_on_a_getattr_proxy_is_not_probed (:654) Pickler fails — both the probed assertion and out.__func__
test_bound_method_whose_probe_raises_is_carried_explicitly (:667) Pickler errors — no _reduce_bound_method
test_bound_method_the_class_resolves_falls_through (:677) Pickler errors — no _reduce_bound_method
test_bound_method_over_a_staticmethod_name (:684) Pickler fails — loads a function
test_bound_method_of_a_partial (:694) Pickler fails — func.__name__ on the partial
test_bound_method_of_a_module_keeps_its_function (:704) Pickler fails — loads _forward_unimplemented
test_guard_rooted_at_bound_method_under_a_name_self_lacks (:785) Capture fails
test_bound_method_input (:1870), test_bound_methods_missing (:1883), test_bound_methods_empty (:1902), test_bound_method_patched_forward (:2134) Capture pass (pre-existing, green on base)

Nine of thirteen — the number is right. Two problems with the list that explains it:

  • The parenthetical accounts for seven, not nine. It names six pickler cases plus "the capture tests", and omits test_bound_method_the_class_resolves_falls_through and test_bound_method_of_a_module_keeps_its_function. The nn.Module test in particular is the one the FAQ leans on, so leaving it out of the failing list undersells it.
  • "the capture tests" is plural but there is exactly one new capture test. The other four bound_method* capture tests are pre-existing and pass on the base, so the plural reads as if they fail too.
  • "partial receiver" survives here. The body paragraph now correctly says "a functools.partial as __func__ has no __name__ at all", but the Test Plan enumeration still says partial receiver — and the test binds the partial over Inputs(1, 2) (test:697), so the receiver is ordinary. This is precisely the wording this round set out to fix; it just needs the same edit in the second place. Fix this →

The FAQ's lambda claim holds, and the reason is worth one clause

Verified both halves of "a class-body lambda forward on a module-level class degrades to _Missing under both gates (on a function-local class its qualname contains <locals>, so it is rebuilt from its code object and loads fine)":

  • Module-level class M(nn.Module): forward = lambda self, x: x → __qualname__ == "M.<lambda>", no <locals>, so the fqn walk at guards.py:4457-4462 does getattr(M, "<lambda>", None) → None is not obj → _Missing, ("fqn mismatch",). Under the narrowed gate too, because CPython's method.__reduce__ (and hence the name this code keys on) is __func__.__name__ — "<lambda>", not "forward". inspect.getattr_static(M, "<lambda>", None) is None, so static is None and hasattr(cls, "__getattr__") fires and the narrowed gate also returns explicit. Claim confirmed.
  • Function-local → "...<locals>.M.<lambda>" → _unpickle_nested_function (guards.py:4449-4456) → rebuilt from the code object. Confirmed.

The <lambda>-vs-forward step is the load-bearing one and is currently implicit: a reader checking the narrowed gate will look up getattr_static(M, "forward"), find the lambda, and conclude the narrowed gate falls through to the default path. One clause — "the name reduced is __func__.__name__, i.e. <lambda>" — closes that. Same fact also explains the partial case more strongly than the FAQ does: method.__reduce__ itself reads __func__.__name__, so a partial __func__ is unpicklable on the default path regardless of this reducer, not merely mis-resolved.

Still open from round 2 (not claimed as fixed)

  • assertEqual(GetattrProxy.probed, []) (test:662) is unchanged. To restate the mechanism now that I have chased it down: object.__getstate__ was added in 3.11; on 3.10 reduce_newobj reaches _PyObject_GetState, which looks __getstate__ up on the instance and swallows the AttributeError — so "__getstate__" lands in probed and the equality assertion goes red. GetattrProxy is module-level, so reducer_override returns NotImplemented for it and it does take that default path. requires-python = ">=3.10" (pyproject.toml:348) and linux-jammy-cuda13.0-py3.10-gcc11 in periodic.yml still run 3.10, so this would surface post-merge rather than on this PR's checks. assertNotIn("global_add", GetattrProxy.probed) is both version-independent and the precise claim under test. I could not execute 3.10 here (only 3.12.3 available, no built torch in this checkout).
  • hasattr(cls, "__getattr__") (package.py:186) remains the one lookup outside the try; a metaclass __getattr__ raising non-AttributeError still escapes. Nit, as before.
  • isinstance(receiver, type) evaluated twice (package.py:186, :190); AOTCompilePickler's copy (aot_compile.py:129-142) still has the original bug, now disclosed by the base docstring (package.py:118-120). Both non-blocking, unchanged.

Recommendation

Approve on the code. Two message edits before submitting: the "partial receiver" leftover in the Test Plan and the "seven named, nine claimed / capture tests plural" mismatch. The probed assertion is the only thing I would still change in the test file, and it is a one-line narrowing.

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

@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 10, 2026 16:53
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]

@aorenste aorenste left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

(Reviewed by me, assisted by AI)

[cleanup] My agent says:

The description's account of the transient gap -- an fqn-mismatched __func__ "is pruned to _Missing" -- understates it when __func__.__module__ does not resolve. guards.py:4457 gates the whole resolution walk on if obj.__module__ in sys.modules:, so such a function never reaches the _Missing return at :4462: it falls out of the chain to return NotImplemented and pickle's save_global raises, i.e. a PackageError bypass rather than a silent prune. torch.fx.GraphModule is an in-tree instance -- _forward_from_src execs forward into the graph globals, so __module__ is None and __qualname__ is a bare "forward" (no <locals>, so the rebuild at :4449 does not fire either):

gm = torch.fx.symbolic_trace(M())
>>> GuardsStatePickler({id(gm): gm}, {}, {}, buf).dump({"m": gm.forward})            # ok, 941 bytes
>>> GuardsStatePickler({id(gm): gm}, {}, {}, buf).dump({"f": gm.forward.__func__})
PicklingError: Can't pickle <function forward ...>: attribute lookup forward on __main__ failed

#196474 draws exactly this distinction in its own message ("rather than fall through and fail the dump with pickle's PicklingError (a bypass)"); this is the commit the window opens in, so its message should say the same.


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

Comment thread torch/_dynamo/package.py
# __name__ is not guaranteed: MethodType accepts any callable, so
# method.__func__ may be a functools.partial with no __name__. Fall
# through to the explicit reduce rather than raising out of the reducer.
name = getattr(func, "__name__", 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.

[cleanup] My agent says:

Move it inside the try; explicit is built two lines above the try, so the except still has something to return:

        explicit = (type(self)._unpickle_bound_method, (func, receiver))
        is_type = issubclass(cls, type)
        try:
            name = getattr(func, "__name__", None)

This is the one user-code path still outside the try. getattr swallows only AttributeError, and __func__ is an arbitrary callable by this line's own premise, so a proxy that raises anything else escapes the reducer -- while the receiver-side equivalent is already guarded:

class ProxyFunc:
    def __getattr__(self, n): raise RuntimeError(f"proxy has no {n}")
    def __call__(self, x): return x

>>> pickler._reduce_bound_method(types.MethodType(ProxyFunc(), Plain()))
RuntimeError: proxy has no __name__
>>> pickler._reduce_bound_method(types.MethodType(global_add, RaisingProbes()))
(<bound method ...>, (<function global_add>, <RaisingProbes>))

Comment thread torch/_dynamo/package.py
return explicit
self_dict = getattr(receiver, "__dict__", None)
if not is_type and (
(isinstance(self_dict, dict) and name in self_dict)

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:

Nothing reaches the __dict__ half of this condition. SlottedByName declares __slots__, so it has no instance __dict__ and test_bound_method_under_a_slot_name lands on the getattr_static half; no other new or pre-existing bound_method* test puts the name in an instance __dict__. Ablating isinstance(self_dict, dict) and name in self_dict leaves the suite green while the self-cycle this clause exists for breaks at load:

obj = Plain()                                      # no __getattr__, no __slots__
obj.global_add = types.MethodType(global_add, obj)
GuardsStatePickler({}, {}, {}, buf).dump({"m": obj.global_add})
# with the clause:    loads back as MethodType(global_add, Plain)
# without the clause: AttributeError: 'Plain' object has no attribute 'global_add'

The comment above does not document the reachable shape either: for m.forward = MethodType(f, m) on an nn.Module the hasattr(cls, "__getattr__") gate returns first, so a plain receiver is the only thing that can get here.

Comment thread torch/_dynamo/package.py
type(self)._set_cell_contents,
)

def _reduce_bound_method(self, method: types.MethodType) -> tuple[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
def _reduce_bound_method(self, method: types.MethodType) -> tuple[Any, ...] | None:
def _reduce_bound_method(self, method: types.MethodType) -> tuple[object, ...] | None:

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Thanks; fixed forward in #196764 at the top of the stack: the __name__ probe moved inside the try (with a proxy-func test that raised RuntimeError before), the __dict__ clause is pinned by a test that monkeypatches a method onto a plain instance, and the comment says only a plain receiver reaches it since nn.Module takes the __getattr__ gate first. The return annotation is tuple[object, ...] | None now.

@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
…#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
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/1138/head branch November 18, 2026 01:45
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