Skip to content

[dynamo] Record the container edge on __defaults__ and instance mappings, not just the base object - #196480

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

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

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

The container->element edge keys on id(base_example_value). Two ordinary
shapes put the guarded element's REAL container somewhere else, so the edge
missed and _keep_container_verbatim carried the container whole with its
unpicklable sibling:

  • A call-site default binding (DefaultsSource, def forward(self, x, scale=2.0, junk=threading.Lock()) called without scale) has the FUNCTION
    as its base, while the whole-tuple SEQUENCE_LENGTH guard registers the
    __defaults__ tuple itself. Record the edge on the __defaults__ /
    __kwdefaults__ container too.
  • An attribute read func.tag records its edge on func, while a guard that
    reads the whole func.__dict__ (DunderDictVariable registers
    AttrSource(base, "__dict__")) makes the mapping _keep. Record the edge on
    the instance __dict__ that holds the attribute, and on __annotations__
    only when the base is a type, routine or module, since reading it off an
    arbitrary instance would key on the class dict and can run a user
    __getattr__.

Neither shape is reachable through _test_serialization, whose guard filter
drops the whole-container guard so the container is never _keep to begin
with; the two new tests drive a real torch.compile under caching_precompile
instead.

Test Plan:

python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k test_fqn_mismatched_function_prunes_an_unpicklable_called_default -k test_fqn_mismatched_function_prunes_a_verbatim_dict_read

Both error on the previous commit with PackageError: TypeError: cannot pickle '_thread.lock' object.

Authored with an AI assistant.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196480

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

❌ 21 New Failures, 2 Cancelled Jobs

As of commit e5d5d12 with merge base e67c870 (image):

NEW FAILURES - The following jobs have failed:

CANCELLED JOBS - The following jobs were cancelled. Please retry:

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

@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

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 42m 38s —— View job


Reviewed: the two container-edge repairs look correct and well-motivated, but the __annotations__ arm appears unmotivated and latently harmful, the unconditional getattr(base, "__dict__") can execute user code on every attribute guard, and neither new test verifies that the surviving guard still discriminates.

Full review

PR Review: #196480

Summary

Records the container->element edge on the real container (__defaults__/__kwdefaults__ tuple/dict, and the instance __dict__) rather than only on the base object, so _keep_container_verbatim prunes per value instead of dragging an unpicklable sibling into the pickle. The two core repairs are correct; three issues below.

Code Quality

1. The __annotations__ arm is unmotivated and is a latent false-positive. torch/_dynamo/guards.py:1757-1764

The only consumer of guard_tree_children is _keep_container_verbatim (line 4415), and its only five call sites (4463, 4470, 4482, 4492, 4500) are all inside _reduce_function_by_value(obj: types.FunctionType). So the read side never looks up a class or module container id — the isinstance(base_example_value, type) and inspect.ismodule(...) arms are dead by construction.

Worse, for the remaining inspect.isroutine case the arm is a name collision, not a real edge. The already-covered shape (keep_annotations at test/dynamo/test_guard_serialization.py:170-182) reads func.__annotations__["x"], which is a GetItemSource(AttrSource(func, "__annotations__"), "x") — its base already is the annotations dict, so the generic edge at line 1740 keys it correctly with no help needed. The new arm only fires for AttrSource(func, member) where member happens to also be an annotation key, i.e. an attribute named x and a parameter annotated x — two unrelated things sharing a name. The example_value recorded is the attribute value, which is not an annotation value, so normally nothing matches on the read side and the entry is dead. But if the two coincide (func.x = int alongside func.__annotations__ = {"x": int}), the edge forces a spurious per-value prune of __annotations__ — exactly the failure mode the comment at 4411-4414 warns about ("an element that is _keep for an unrelated reason ... must not force a prune that would then break a whole-container guard reading this same slot").

Nothing in the diff tests this arm. Deleting lines 1754-1764 removes the dead type/module branches, the false-positive risk, and the comment defending it — leaving just the __dict__ mapping the two new tests actually exercise.

Fix this →

2. The membership test should be an identity check, not a key check. torch/_dynamo/guards.py:1766

source.member in mapping only proves the container has a key of that name; it does not prove the container's value for that key is the element the edge points at. mapping.get(source.member, _sentinel) is example_value is both exact and simpler, and it is what the read side actually compares (any(id(v) in children for v in values)). With that check in place, the __annotations__ name-collision case in (1) self-eliminates.

3. getattr(base_example_value, "__dict__", None) can execute user code and escape the None default. torch/_dynamo/guards.py:1753

This is unconditional — it runs for every AttrSource, so for arbitrary traced user objects. For a normal class __dict__ resolves via the type's getset descriptor and is inert, but for a __slots__ class with no __dict__, __getattribute__ raises and CPython then calls type(obj).__getattr__. The None default only swallows AttributeError; a __getattr__ (or a __dict__ @property) that raises anything else propagates out of guard building and turns a program that previously compiled into a hard compile error. This file already traces such shapes — see the SlottedByName and GetattrProxy fixtures at test/dynamo/test_guard_serialization.py:627 and :633. Note the diff's own comment at 1754-1756 recognizes this hazard for __annotations__ but leaves the far more frequently executed __dict__ read ungated. Reading the instance dict via the type slot (type(base_example_value).__dict__.get("__dict__") descriptor, or simply a try/except Exception) avoids invoking user code.

4. isinstance(mapping, dict) does not match the reader's type(container) in (dict, tuple). torch/_dynamo/guards.py:1766 vs :4410

The writer accepts dict subclasses; the reader treats any subclass as unconditionally verbatim and never consults the edge. Harmless today (a dead entry), but the mismatch invites a future reader to assume subclass mappings are pruned. type(mapping) is dict states the actual contract.

5. The two repairs are 250 lines apart. The DefaultsSource edge lands at line 2011 inside the istype(source, DefaultsSource) dispatch branch, while the structurally identical AttrSource repair sits at 1752 next to the generic edge. Both comments have to cross-reference each other ("Mirror the DefaultsSource repair below", "The generic edge above keys on..."), which is the smell. Folding the DefaultsSource case into the same block next to the generic edge (the source type is available there) would keep one place that answers "which container really holds this element."

6. Docstring enumerates shapes that will rot. torch/_dynamo/guards.py:4398-4406 adds ~9 lines listing "the shapes we have identified." That inventory has already grown once in this stack and will grow again; the invariant ("an edge is recorded on the container that actually holds the element") is the durable statement and is already covered by the preceding sentences. Per CLAUDE.md ("minimize comments; be concise"), the enumeration is worth dropping.

Testing

7. Neither new test verifies that the guard still discriminates after the round trip. test/dynamo/test_guard_serialization.py:1589-1616

Both tests are only torch.compile(mod, backend="eager")(torch.randn(3)) with no assertions. They do fail on the parent commit — TestGuardSerialization is decorated @torch._dynamo.config.patch({"strict_precompile": True}) at line 1344, so the PackageError at guards.py:5036-5038 re-raises rather than calling bypass_package — so they are genuine regression tests for the crash. But "did not throw" is all they check.

That leaves the direction this PR actually risks untested. The change makes containers get pruned per value where they previously went verbatim; the bug it could introduce is pruning too much — dropping the guarded scale / func.tag alongside the lock — which yields a guard that silently never matches again, a permanent cache miss with no load error. That is precisely the failure the Note at guards.py:4362-4366 calls out as invisible. Both tests would pass through it.

Every sibling test for this machinery does check it: test_fqn_mismatched_function_prunes_unpicklable_dict_attributes (1557), test_fqn_mismatched_function_prunes_unpicklable_defaults (1572), and test_fqn_mismatched_function_prunes_a_none_valued_guarded_default (1618) each call _test_check_fn(ref, loaded, inputs, True), then mutate the guarded slot and assert False. The new tests should reach the same bar. If the whole point is that _test_serialization's guard filter drops the whole-container guard and so cannot reproduce the shape, then the tests need to load the serialized guards back from the real compile path and check them (or at minimum assert the compiled output value and that no bypass was recorded on the package), not just that the compile completed.

Fix this →

8. Untested branches. As noted in (1), the type / isroutine / ismodule gate and the __annotations__ mapping have no coverage in this diff. If they are kept rather than deleted, they need a test that demonstrates a shape they actually repair.

Recommendation

Request Changes

The two real repairs (the __defaults__/__kwdefaults__ container edge and the instance __dict__ edge) are correct and each is backed by a test that fails on the parent commit. Blocking items are (1) the __annotations__/type/module arm, which is dead on the read side and a latent spurious-prune source with no test, (3) the ungated getattr(base, "__dict__") running user __getattr__ on every attribute guard, and (7) tests that only assert "did not raise" and so cannot catch over-pruning — the silent-permanent-cache-miss failure this change is most likely to introduce. (2) folds naturally into fixing (1).

I could not run the test suite: python execution is blocked in this environment (no .venv found and every invocation form was denied), so all findings are from reading source. Verifying python test/dynamo/test_guard_serialization.py locally is still needed.

| Branch `gh/bobrenjc93/1145/head`

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Superseded by #196479, redesigned: instead of recording container-to-element edges per source, GuardBuilder.EQUALS_MATCH records the plain dict/tuple values it reads whole and a rebuilt function's container is carried verbatim only for those. That fixes the whole-tuple EQUALS_MATCH silent miss, the still-broken unread unpicklable default, and removes the annotations read that raised NameError on 3.14.

@bobrenjc93 bobrenjc93 closed this Sep 9, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1145/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