Skip to content

[dynamo] Restore __dict__, __doc__, __annotations__ and __type_params__ on a rebuilt function - #196475

Closed
bobrenjc93 wants to merge 2 commits into
gh/bobrenjc93/1140/basefrom
gh/bobrenjc93/1140/head
Closed

bobrenjc93 wants to merge 2 commits into
gh/bobrenjc93/1140/basefrom
gh/bobrenjc93/1140/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

types.FunctionType(code, ...) takes __doc__ and __annotations__ from the
code object and starts with an empty __dict__. functools.wraps overwrote
all three on the live function (it copies __doc__, __annotations__ and
updates __dict__), and a guard rooted at a wrapper reads them: an
EQUALS_MATCH on func.scale_flag or func.__doc__, 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).

Carry __dict__, __doc__, __annotations__ and __type_params__ in the
pickle state next to the defaults. State is applied after memoization, so
wrapper.me = wrapper -- a function reaching itself through its own
__dict__ -- terminates. __dict__ is assigned before __type_params__
because on Python < 3.12 the latter has no slot and would land in __dict__,
where a wholesale assignment afterwards would discard it. Annotations are read
with _read_raw_annotations, which on 3.14+ takes the FORWARDREF format so a
TYPE_CHECKING-only name does not raise during the dump; its resolve=True
mode is for the AOT pickler, which needs real values to serialize.

Test Plan:

python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k fqn_mismatched_function_attribute -k fqn_mismatched_function_annotations -k test_guard_rooted_at_wrapper_preserves_copied_doc -k test_guard_rooted_at_wrapper_that_reaches_itself -k test_function_reaching_itself_through_its_dict -k test_guard_rooted_at_a_lambda

All six tests fail or error on the previous commit.

Authored with an AI assistant.

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 9, 2026
@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/196475

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

⏳ No Failures, 25 Pending

As of commit 6a8eb57 with merge base e67c870 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot

pytorch-bot Bot commented Sep 9, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

[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 14m 23s —— View job


This restores __dict__/__doc__/__annotations__/__type_params__ on by-value-rebuilt functions and is correct for the three attributes it tests, but the wholesale __dict__/__annotations__ capture can turn previously-serializable compiles into bypasses, __type_params__ ships untested, and _read_raw_annotations(resolve=True) has no caller.

Full review

PR Review: #196475

Summary

Carries __dict__, __doc__, __annotations__ and __type_params__ in the pickle state for a function rebuilt by value, so a guard rooted at a functools.wraps wrapper does not rebake against the code object's empty values. The core fix and the state-vs-argument reasoning are right; the problems are in what gets captured unconditionally, one attribute landing with no test, and a parameter with no caller.

Backward Compatibility

  • torch/_dynamo/guards.py:4305 passes attributes=obj.__dict__ — the whole live dict, with no filter for what the guard tree actually reads. Before this PR a by-value-reduced function contributed nothing from __dict__ to the payload; now every value in it must pickle. Concretely: functools.wraps sets __wrapped__, so reducing a wrapper now drags the entire decorator chain into the guard state, and any decorator that stashes something unpicklable (a logging.Logger, a lock, a locally-defined class instance) turns a compile that previously serialized fine into a PackageError. That is not a crash — pickle_guards_state at torch/_dynamo/guards.py:4595-4605 converts it to a bypass — but a bypass is permanent loss of precompile coverage for that model, and it is silent unless strict_precompile is on. _get_unsupported_types() (guards.py:4142) only covers Stream/weakref/ProcessGroup; anything else hits either the "defined in local scope" PackageError at guards.py:4496 or a raw PicklingError.

    The same argument applies to annotations=self._read_raw_annotations(obj) on the next line: an annotation naming a locally-defined class is now a bypass where before it was inert.

    There is precedent in this exact file for the fix. The nn.Module reducer at guards.py:4375-4382 walks obj.__dict__.values() and registers anything not in guard_tree_values into self.missing_values, so it degrades to a _Missing sentinel instead of failing the dump. The by-value function path should do the same for its __dict__ (and annotation values) rather than capturing wholesale — nothing outside the guard tree is read at load, so pruning it is free. Fix this →

Code Quality

  • torch/_dynamo/package.py:223-245 — _read_raw_annotations grows a resolve: bool = False parameter and eight lines of comment explaining it ("A caller that must SERIALIZE the annotations passes resolve=True instead"), but nothing in the tree passes it. The only call site is guards.py:4306, which uses the default. AOTCompilePickler (torch/_dynamo/aot_compile.py:64) does not derive from FunctionPicklerBase and does not call this at all. Per CLAUDE.md ("Don't design for hypothetical future requirements"), drop the parameter and the branch, and add them in whichever stack entry actually introduces the AOT caller.

  • torch/_dynamo/package.py:226-227 — the comment says the guard pickler "takes FORWARDREF and prunes the proxies later," but no pruning exists: _reduce_function_by_value hands the FORWARDREF dict straight into the pickle state, and _apply_function_state assigns it verbatim at package.py:214. On 3.14+ a TYPE_CHECKING-only annotation on a guarded function therefore reaches pickle.dump as a ForwardRef proxy, which the comment two lines below asserts is not picklable — so a PackageError bypass, on a path the pre-PR code never touched. Either implement the pruning the comment promises (drop entries whose value is a ForwardRef before building the state — a guard reading a lazily-evaluated annotation cannot be honored anyway) or correct the comment.

  • torch/_dynamo/package.py:123-127 — the class docstring now reads "Defaults, __doc__, and __dict__ travel as pickle STATE," but the state tuple also carries annotations and type_params. This is the contract doc for both picklers; enumerate all of it or say "everything except the closure."

  • torch/_dynamo/package.py:308-311 vs 317 — the keyword-only parameters are declared attributes, annotations, doc, type_params but the positional state tuple is (defaults, kwdefaults, attributes, doc, annotations, type_params). The two orders differ only in doc/annotations, both loosely typed (doc: Any), and the tuple is what _apply_function_state unpacks positionally. Align the signature order with the tuple order so a future edit cannot silently transpose them.

Testing

  • __type_params__ is in the PR title, in the state tuple, and is the reason for the load-order constraint at package.py:215-220, yet no test exercises it — grep type_params test/dynamo/test_guard_serialization.py returns nothing. The __dict__-before-__type_params__ ordering comment describes exactly the kind of invariant that a reordering silently breaks; a PEP 695 def f[T](...) case, gated on sys.version_info >= (3, 12), with a guard rooted at the function and an assertion that loaded.__type_params__ round-trips, would lock it in. Add a < 3.12 companion asserting a manually-set fn.__type_params__ (which lives in __dict__ on those versions) survives.

  • No test covers the 3.14 annotationlib branch of _read_raw_annotations. A version-gated case with a TYPE_CHECKING-only annotation on a guarded function is cheap and is the only thing that would surface the missing ForwardRef pruning above.

  • No regression test for a wrapper carrying an attribute the guard never reads that does not pickle — the BC risk in the first section. test_guard_rooted_at_wrapper_that_reaches_itself covers the cycle, not the unpicklable-payload case.

Recommendation

Request Changes

__type_params__ lands with no coverage, and the unfiltered __dict__/__annotations__ capture converts a class of previously-serializable compiles into silent bypasses. The resolve=True dead parameter should move to the stack entry that uses it. The rest of the change — state-not-argument, the __dict__-before-__type_params__ ordering, and the six new tests for the attributes that are covered — is sound.

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

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Folded into #196476: restoring a rebuilt function's attributes and pruning what no guard reads now land in one commit, since either alone regresses its parent (verbatim restore fails the dump for every generic function and for a local function with an unpicklable attribute; pruning needs the restore plumbing).

@bobrenjc93 bobrenjc93 closed this Sep 9, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1140/head branch November 16, 2026 01:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant