Skip to content

[ref-stack][dynamo] Prune guard state by the guard tree and diagnose the offending value - #195912

Closed
bobrenjc93 wants to merge 54 commits into
gh/bobrenjc93/1114/basefrom
gh/bobrenjc93/1114/head
Closed

bobrenjc93 wants to merge 54 commits into
gh/bobrenjc93/1114/basefrom
gh/bobrenjc93/1114/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Guard-state pickling prunes what the guard tree does not reach, but the
pruning had three holes. Only nn.Module attributes were pruned, so one
unpicklable bystander on any other guarded object (a pipeline holding a
generator, a wrapper holding a process group) took the whole frame down. An
exact builtin container (list, dict, tuple, ...) is saved by the C pickler by
type before reducer_override is ever consulted, so a pruned container was still
walked and still failed; a persistent_id hook now substitutes those, paired
with a persistent_load in load_guards_state that maps the token back to the
_Missing sentinel and rejects any other persistent id. And pruning is keyed by
id(), so registering an interned value (torch.float32, the empty tuple) as
missing poisoned every other reference to it and the artifact failed to load
with "empty_strided(): argument 'dtype' must be torch.dtype, not _Missing".

_Missing moves to package.py so both the pickler and the unpickler can name
it. nn.Module's own bookkeeping containers stay real containers, so attribute
misses on a loaded submodule keep raising AttributeError rather than
TypeError. A FakeTensor is reduced from its recorded dispatch keys under
no_dispatch, .grad is read only off leaves, and a serialization failure now
names the original exception type plus the attribute path to the offending
value, found by identity from the scopes and the state, since a type alone is
not actionable in a model with a thousand-frame guard tree. Pruning applies only
to objects that pickle by the default protocol; a class with its own
reduce_ex/getstate/setstate (enum members, a pipeline recomputing a
field in setstate) reads attributes no guard named on the way back, so it is
pickled whole as before.

Two adjacent fixes ride along. A concrete c10d backend (ProcessGroupNCCL,
FakeProcessGroup) is bound as a subclass of Backend, not ProcessGroup, so
_get_unsupported_types now lists Backend and such an object is pruned rather
than failing the frame. GuardFilterEntry gains a code snapshot of the guard's
code_list at inspection time, since later build_guards calls reset it; the
capture session (a later commit) reads it.

Test Plan:

python test/dynamo/test_guard_serialization.py
python test/test_precompile.py

Authored with an AI assistant.

FAQ

Q: The whole-object pruner gates on hasattr(obj, "__dict__"); on a __slots__
receiver that falls through to the user's __getattr__, and anything it raises
other than AttributeError fails the dump (a bypass, or an error under
strict_precompile) for an object that pickles fine.

A: Fixed: the gate reads the instance dict through package.py's _instance_dict
(a plain-slot object.__getattribute__), the same read #195353 uses for its
container edge and bound-method probe, so no user code runs there. Covered by
test_attribute_guard_on_a_slotted_receiver_runs_no_user_getattr in #195353,
which compiles a slotted receiver whose __getattr__ raises RuntimeError for
__dict__ under caching_precompile.

Q: _pickles_by_default ignores __getnewargs__/__getnewargs_ex__; a pruned
attribute one of them returns is embedded in the pickle, bypassing substitution.

A: The gap is real but the mechanism differs: newargs ride the same pickler, so a
pruned attribute reaches cls.__new__ as the sentinel at load (reproduced: a
class returning (self.a,) from __getnewargs__ loaded with a = _Missing).
Fixed by excluding classes with either hook from the default protocol, with
test_object_rebuilt_from_newargs_is_pickled_whole.

Q: .grad is read only for leaf tensors, but a retain_grad() non-leaf --
which torch.optim accepts as a param -- has a real .grad.

A: Real at this commit (the parent read .grad unconditionally); the
obj.is_leaf or obj.retains_grad predicate and
test_retained_grad_non_leaf_survives_pickle are folded down here from #195924.

Q: nn.Module hook dicts are pruned to _Missing on a loaded module; __setstate__
or __getattr__ could read them.

A: Behaviour-identical to the parent commit: an OrderedDict is not an exact
dict, so it already went through reducer_override and was pruned by id. It is
deliberate -- a module with a local-lambda hook is unpicklable whole, and pruning
the hook dicts is what keeps that frame serializable. nn.Module.__setstate__
only does presence checks and never reads a hook dict's value, __getattr__
indexes only the three dicts in _NN_MODULE_STATE_ATTRS, and the loaded module
is fed to CheckFunctionManager to rebuild the guard manager, never called.
(Correction: that argument holds for nn.Module.__setstate__ itself, not for a
SUBCLASS with its own __setstate__; see the RNNBase item below, which is fixed.)

Q: The gate uses _instance_dict but the pruner loop uses vars(obj).

A: Made consistent (the loop reads _instance_dict(obj) too). No behaviour
change: for an object past the gate vars() can only differ via a
__getattribute__ override, and plain pickle fails on the same object before the
pruner is reached.

Q: last_reduced can misattribute the culprit when a nested reduce fails.

A: The C pickler consults reducer_override for every object outside the exact
builtin fast paths, including the object whose own __getstate__/__reduce_ex__
then fails, so last_reduced is set immediately before the failing reduce
(reproduced for a __getstate__ that asserts and for a generator inside a list;
both name the right object). Exact builtins cannot fail on their own.

Q: The interned-singleton allowlist is a hole for any other interned value, e.g.
SDPBackend members, which are ints.

A: Poisoning needs one object to be both a pruned attribute and re-emitted by a
reducer outside the guard tree; the reducers here emit dtype/device/layout (every
tensor) and () (every code object), which is what the list covers. A non-empty
constant tuple is re-emitted only from a co_consts/__defaults__ a guard also
reads, and then it is in guard_tree_values. SDPBackend members are
pybind11_objects, not ints, and no reducer emits one, so they need no entry.

Q: No dtype/device pickler-level test, no persistent_load rejection test, no
Backend pruning test, and test_grad_mode_loading uses pickle.loads on a
guards state.

A: All four added/fixed: test_an_unguarded_interned_singleton_is_not_pruned
(the headline dtype poisoning, pickler level),
test_loader_rejects_a_foreign_persistent_id,
test_an_unguarded_process_group_backend_is_pruned (a fake process group's
Backend, skipped without distributed), and test_grad_mode_loading now goes
through load_guards_state. The other pickle.loads in the file are on
pickler-level fixtures that emit no persistent id.

Q: no_dispatch() around empty_like for a FakeTensor loses dynamic-shape
information.

A: Both with and without no_dispatch the pickle receives a sym-sized meta
tensor and hits the pre-existing PackageError: Cannot serialize SymInt, so the
change does not alter the dynamic-shape outcome (a bypass either way); a static
fake round-trips.

Q: The diagnostic tests use hand-rolled fakes instead of real pickle failures.

A: _offending_value_path is a pure function over the state, so its unit tests
target its traversal; test_unpicklable_function_default_names_the_path covers
the real pickle_guards_state/last_reduced path end to end.

Q: Should the two persistent-id namespaces (guards state, AOT) be documented as
disjoint?

A: The _PRUNED_VALUE_PID comment already says any other pid in a guards state is
a bug, and persistent_id is defined on GuardsStatePickler rather than the
shared base precisely because AOTCompilePickler.persistent_id has its own
namespace; format-version gating is SystemInfo's torch_version check.

Q: An nn.Module subclass with its own __setstate__ (RNNBase indexes
_all_weights) reads a pruned attribute at load, so a saved LSTM frame fails
to load.

A: Real; fixed. Pruning now runs only for modules whose __setstate__ is
nn.Module.__setstate__ (presence checks only) plus DDP, which is rebuilt
through nn.Module.__setstate__ explicitly; a module with its own
__setstate__ is pickled whole. Reproduced with allow_rnn=True (the default
config graph-breaks on an RNN, so the module is not guard-tree-reached and lands
as the "module guard tree" sentinel; the trigger is allow_rnn=True, torch.ao
quantized modules, or a user subclass whose __setstate__ reads a pruned
attribute). Trade-off: the in-tree modules with a presence-check __setstate__
(Conv*, MultiheadAttention, Transformer layers, ...) are now pickled whole, so an
unpicklable bystander attribute on one of them bypasses the frame as it did
before this commit. test_loaded_rnn_module_survives_its_own_setstate covers the
LSTM shape end to end through the serialization harness.

Q: type(obj).__module__.startswith("torch.") lets torch.SymFloat,
torch.SymBool and torch._TorchCompileInductorWrapper (module exactly
"torch") through the pruner; only SymInt is refused.

A: Fixed: the exclusion compares the top-level package (partition(".")[0] != "torch"), and the refusal covers SymInt, SymFloat and SymBool.
test_torch_namespace_objects_are_pickled_whole round-trips the inductor
wrapper whole and checks a SymFloat raises PackageError.

Q: persistent_load returns a fresh _Missing per occurrence, so two
attributes that shared one pruned object load as two sentinels.

A: _GuardsStateUnpickler now hands out one shared sentinel. Note the invariant
the review assumes did not hold before either: distinct pruned objects never
shared a sentinel on the missing_values path (the _missing() cache serves the
snapshot _prune only); sharing is restored outright rather than per object.

Q: The _NN_MODULE_STATE_ATTRS and pruner comments say __getattr__ runs "on
every attribute miss" and a pruned dict breaks "every attribute miss"; it is
narrower and wider than that.

A: Reworded: __getattr__ indexes the three dicts for every attribute outside
__dict__ (parameters, buffers, submodules), and state_dict/named_buffers
read _non_persistent_buffers_set.

Q: GuardFilterEntry.code is dead in this commit; move it to the commit that
reads it.

A: The reader is the capture session (#195919, precompile_package.py). The
snapshot has to be taken in make_guard_filter_entry, because later
build_guards calls reset code_list: that is a guards.py invariant, so the
field belongs with the producer. It is a default-valued dataclass field with no
behaviour, so bisectability is unaffected.

Q: The pickler-level Backend test spins up a default process group
(init_process_group); use a FakeProcessGroup directly.

A: FakeProcessGroup has no Python constructor ("No constructor defined!"). The
test now builds ProcessGroupGloo(HashStore(), 0, 1) directly, which is a
Backend, needs no default group and leaves dist.is_initialized() False;
skipped when gloo is unavailable.

Q: Artifacts written by this commit contain persistent-id opcodes an older
load_guards_state (bare pickle.loads) cannot read.

A: Every reader gates on SystemInfo.check_compatibility (torch_version
equality) BEFORE load_guards_state: initialize() -> check_versions runs
before install() on both the eval_frame and load_and_install_package paths,
and CompileArtifacts.__post_init__ precedes the AOT load. An artifact is only
ever read by the torch that wrote it. This commit also changes _unpickle_tensor's
reduce tuple (dispatch_keys), so a pre-PR reader fails on any tensor-bearing
artifact regardless of persistent ids; the guards-state stream has never been
cross-version. Caveat for the record: torch_version is torch.__version__,
which a build pinning a constant version string across commits would not
distinguish; that is a pre-existing SystemInfo property, not this PR's. The
_PRUNED_VALUE_PID comment now states the ordering.

Q: About twenty tests still read guards-state bytes with bare pickle.loads.

A: All switched to torch._dynamo.package.load_guards_state (the one remaining
pickle.loads round-trips a plain pickle.dumps, not a guards state).

[no ci]

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

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 3, 2026
This was referenced Sep 3, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 36m 4s —— View job


Reviewed: the pruning generalization is a real fix, but I found one likely-breaking gap (nn.Module hook dicts get pruned to _Missing with no repair path), one correctness gap in the new .grad handling (retain_grad() non-leaves do have a real .grad), and a diagnostic that can print a misleading path.

Full review of PR #195912

PR Review: #195912

Summary

Generalizes guard-state pruning from nn.Module attributes to any guard-tree-reached object, adds a persistent_id/persistent_load pair so exact builtin containers can be pruned, exempts interned singletons from id-keyed pruning, and appends an attribute path to serialization failures. The core diagnosis is right and the _is_interned_singleton fix addresses a real load failure, but I found three correctness issues and several consistency gaps below.


Code Quality

1. nn.Module is pruned without the _pickles_by_default gate, and its hook dicts have no repair path — this can produce a _Missing where an OrderedDict is expected.

torch/_dynamo/guards.py:4667 calls _prune_unguarded_attributes(obj) unconditionally for every nn.Module, while the new non-module path at guards.py:4779-4787 gates on _pickles_by_default(obj). nn.Module defines both __getstate__ (torch/nn/modules/module.py:1928) and __setstate__ (:1933), so it fails _pickles_by_default — the module path is doing exactly what the new gate exists to prevent.

That asymmetry is load-bearing here because of how nn.Module.__setstate__ repairs missing state. module.py:1937-1951 is a sequence of presence checks:

if "_forward_pre_hooks" not in self.__dict__:
    self._forward_pre_hooks = OrderedDict()

_NN_MODULE_STATE_ATTRS (guards.py:4255-4257) allowlists only _parameters, _buffers, _modules, _non_persistent_buffers_set. The hook OrderedDicts are deliberately left prunable (per the comment at :4251-4254). A pruned hook dict is replaced by _Missing, so the key is present, __setstate__ skips the repair, and the attribute stays _Missing rather than becoming an OrderedDict.

The comment at :4253-4254 asserts hook dicts "were, and stay, pruned unless a guard reads them" — but that was true under the old code only because the old loop was reached via the same path; the pre-existing behavior isn't evidence of safety, and the new _pickles_by_default gate is an explicit admission that objects with __setstate__ are unsafe to prune. Either add the hook OrderedDicts to _NN_MODULE_STATE_ATTRS, or make __setstate__-having types repair by type rather than presence. Please confirm whether the loaded module is only ever inspected by guard checks or can also be called; if it can be called, _call_impl iterating self._forward_pre_hooks raises AttributeError: '_Missing' object has no attribute 'items'.

Fix this →

2. .grad is not always None on a non-leaf — retain_grad() breaks the stated invariant.

guards.py:4658-4660:

# Reading .grad off a non-leaf warns and is always None anyway;
obj.grad if obj.is_leaf else None,

The warning predicate is !is_leaf() && !retains_grad() && !maybe_grad.defined() (aten/src/ATen/templates/TensorBody.h:487). A non-leaf with retain_grad() called does not warn, and after backward() its .grad is a real tensor. So the comment's justification is wrong on both clauses, and the code silently substitutes None for a populated gradient.

This is reachable: GradSource guards are installed on parameter gradients (torch/_dynamo/variables/optimizer.py:312-323) and GradGuardAccessor reads .grad at guard-check time (torch/csrc/dynamo/guards.cpp around the grad() unpack). The correct predicate is obj.is_leaf or obj.retains_grad. Please also confirm whether a .grad reachable through GradSource on a retain_grad() non-leaf can end up in this reducer — if it can, the deserialized guard state disagrees with the captured one.

Fix this →

3. The gate reads the instance dict safely, then the pruner re-reads it unsafely.

guards.py:4781 gates on _instance_dict(obj) is not None — which exists precisely so a user __getattr__ never runs (torch/_dynamo/package.py:117-124, and the PR's own FAQ cites this as the fix for the __slots__ receiver). But _prune_unguarded_attributes at guards.py:4856 then does for name, attr in vars(obj).items(), and vars() goes through normal attribute lookup, so a __dict__ property or descriptor runs after all. Use _instance_dict(obj) inside the pruner and pass it through, so the safe read is the only read. The nn.Module call site at :4667 reaches the pruner with no _instance_dict gate at all.

4. _pickles_by_default doesn't check __getnewargs__ / __getnewargs_ex__. A class inheriting object.__reduce_ex__ (so it passes the check) but defining __getnewargs__ has those newargs read from attributes at dump time and embedded as values, bypassing missing_values substitution. Low likelihood, but the helper's docstring claims to characterize "round-trips as type(obj).__new__ plus its __dict__", which is stronger than what it verifies. copyreg.dispatch_table is not a gap — it's consulted after the default protocol (/usr/lib/python3.12/pickle.py:559).

5. _offending_value_path can print a misleading path. self.last_reduced = obj is set unconditionally on every reducer_override call (guards.py:4589) with no unwinding, and reducer_override returns NotImplemented for most objects — after which the pickler saves the object by default protocol and inspects its children, each overwriting last_reduced. When the failure is raised from inside a __getstate__/__reduce_ex__ the pickler invoked without routing through reducer_override (the GradScaler.__getstate__ case the PR's own comment at :5080-5081 cites), last_reduced points at the last-inspected sibling, not the culprit. Since the walk matches by identity and siblings are usually reachable from state, it prints a confident path to an innocent object. The unreachable case degrades gracefully to "" (:5001); the reachable-but-wrong case does not. Consider hedging the wording ("last object inspected before the failure") or tracking a reduce depth so the attribution is only emitted when last_reduced is plausibly the failing object.

6. Interned-singleton allowlist is a hand-maintained denylist of the same shape as the bug it fixes. _is_interned_singleton (guards.py:4196-4231) exempts empty tuple/frozenset and the scalar/torch-enum types. Non-empty module-level tuple/frozenset constants remain a hole with the identical failure mode. I could not substantiate a concrete instance, so this is low confidence — but the allowlist approach means each new hole is found in production. A comment noting the residual hole would help the next reader. (SDPBackend is fine: pybind11 enums are int subclasses, so the int entry covers them despite the dedicated reducer at :4812 sitting after the missing_values check.)

7. Dead field. GuardFilterEntry.code (torch/_dynamo/types.py:50-53) is written at guards.py:4901 and read nowhere in this PR. The description says a later commit reads it. Adding it in the commit that uses it would make the stack bisectable; if it must land here, the field name code reads oddly next to guard_type / derived_guard_types given the source is code_list.


Testing

1. No test for the _is_interned_singleton fix — the headline bug of this PR. The description names the exact failure: "empty_strided(): argument 'dtype' must be torch.dtype, not _Missing". There is no test in the diff that registers an unguarded torch.float32/torch.device attribute and asserts a different reference to that same dtype survives. test_prunes_an_unguarded_builtin_container_holding_a_generator (test_guard_serialization.py:3408-3421) covers the empty-tuple case via h.empty/"shared", but not the dtype/device/layout arm, which is the one that produced the reported load failure. Without it the whole _is_interned_singleton list is untested.

2. No test for the persistent_load rejection path. _GuardsStateUnpickler.persistent_load (package.py:410-413) raises UnpicklingError for an unknown pid, and nothing exercises it. Cheap to add.

3. No test for the Backend pruning fix. guards.py:4192 adds torch._C._distributed_c10d.Backend to _get_unsupported_types() to fix "cannot pickle FakeProcessGroup". FakeProcessGroup is available without a real distributed launch (torch/csrc/distributed/c10d/init.cpp:4684 binds it with backend as base), so this is testable — a guarded object holding a FakeProcessGroup attribute should serialize rather than fail the frame.

4. No test for the no_dispatch() FakeTensor change. guards.py:4632-4651 changes both the dispatch keys source (obj.dispatch_keys when set) and the empty_like context. Both attributes exist and are DispatchKeySet | None (torch/_subclasses/fake_tensor.py:866-867), so .raw_repr() is valid on both arms. But the dynamic-shape case is unverified: under no_dispatch() the Python key is off, so empty_like hits the meta backend reading the fake's sym sizes directly. I could not find precedent for no_dispatch() + empty_like on a symbolic-shaped fake, and fake_tensor.py:1388 explicitly special-cases _has_symbolic_sizes_strides elsewhere. Please add a dynamic-shape (mark_dynamic / dynamic=True) serialization test covering this path, or state why symbolic sizes cannot reach it.

5. The diagnostic tests build hand-rolled fakes rather than exercising the real path. Four of the five new _offending_value_path tests (test_guard_serialization.py:1387-1478) construct bare _Scope/SimpleNamespace stand-ins for GuardsState and drive the private helper directly. They pin the helper's traversal, not the behavior users see — and they'd keep passing if last_reduced attribution regressed (finding 5), since none of them go through reducer_override. test_unpicklable_function_default_names_the_path (:1480-1503) does call pickle_guards_state, which is the right shape; the others would be more durable built the same way.


Backward Compatibility

Guards-state bytes now contain persistent ids, so any consumer without a persistent_load will fail — please confirm the read paths are exhaustive. pickle_guards_state output is read via load_guards_state at package.py:1626 and aot_compile.py:317, both of which now go through _GuardsStateUnpickler. The nesting cases are not a problem — _GuardedCodeCacheEntry.guards_state and CompileArtifacts.guards_state are typed bytes (package.py:405, aot_compile.py:56), so DiskDynamoStore.read's plain pickle.loads (package.py:1926) and AOTCompileUnpickler carry them as opaque bytes and never interpret the inner stream. But two things are worth confirming:

  • test/dynamo/test_guard_serialization.py:2828 (test_grad_mode_loading, pre-existing, unmodified) still calls pickle.loads(self._cached_guards_state) directly. It presumably passes only because that particular capture emits no persistent id. It is now a latent failure that will trip the day the fixture prunes a container, and it documents the wrong pattern for the next test author.
  • Old artifacts still load (persistent ids are additive), but new artifacts are unreadable by an older load_guards_state. If precompile artifacts are ever version-gated across releases, this needs a format-version bump; if they are always same-version, say so.

Relatedly, defining persistent_id on GuardsStatePickler rather than the shared FunctionPicklerBase is the right call — AOTCompilePickler.persistent_id (aot_compile.py:117-124) already uses the mechanism for external data with different semantics, and AOTCompileUnpickler.persistent_load (:245-253) would mis-handle the "missing values" token. Worth a one-line note at _PRUNED_VALUE_PID (package.py:143-146) that the two persistent-id namespaces are deliberately disjoint, since a future refactor that hoists persistent_id to the base class would silently cross them.


Recommendation

Request Changes

Findings 1 and 2 are correctness bugs (a _Missing reaching an OrderedDict slot with no repair path; a real .grad silently serialized as None). Beyond those, the PR's own headline fix — _is_interned_singleton, the dtype poisoning that produced the reported load failure — ships with no test, as do the Backend and no_dispatch() changes.

• Branch: `gh/bobrenjc93/1114/head`

[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Reviewing PR #195912

  • Gather context (diff, commits, surrounding code)
  • Deep review against checklist
  • Fact-check findings
  • Post review

View job run • Branch: gh/bobrenjc93/1114/head

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude please re-review: round-39 fixes are in (all inline threads addressed; FAQ updated in the description).

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

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


Re-reviewed round 39: the previously-flagged .grad, _instance_dict, __getnewargs__, interned-singleton, persistent_load and Backend items are all genuinely fixed, but generalizing the pruner surfaced two new correctness gaps — nn.Module subclasses with a real __setstate__ (nn.LSTM) are still pruned unconditionally, and torch.SymFloat/SymBool fall through the "torch." module exclusion and load with a _Missing node.

Full review of PR #195912 (round 39)

PR Review: #195912

Summary

Generalizes guard-state attribute pruning from nn.Module to any guard-tree-reached object, adds a persistent_id/persistent_load pair so exact builtin containers can be pruned, exempts interned singletons from id-keyed pruning, and appends an attribute path to serialization failures. Round 38's findings are addressed; verification of the fixes turned up two new correctness gaps introduced by the generalization itself, plus one sharing regression in the new persistent_id path.

Confirmed fixed since round 38 (no action needed): .grad now uses obj.is_leaf or obj.retains_grad (guards.py:4660) with test_retained_grad_non_leaf_survives_pickle; the pruner reads _instance_dict(obj) rather than vars() (guards.py:4849); _pickles_by_default covers __getnewargs__/__getnewargs_ex__ (guards.py:4243-4244); _is_interned_singleton has a pickler-level test; persistent_load rejection, Backend pruning and the test_grad_mode_loading read path all have tests.


Code Quality

1. nn.Module is still pruned without the _pickles_by_default gate, and nn.LSTM breaks on load.

guards.py:4667 calls _prune_unguarded_attributes(obj) unconditionally for every nn.Module, while the generic path at guards.py:4772-4779 gates on _pickles_by_default(obj) — and explicitly excludes nn.Module from that gate via not isinstance(obj, (torch.nn.Module, torch.Tensor)). So the one branch the gate was written for is the one branch that doesn't apply it. The helper's own docstring (guards.py:4844-4846) states the invariant it then violates: "Only objects that pickle by default protocol are pruned ... a custom __setstate__ or __reduce__ would read a pruned attribute and see _Missing at load."

nn.RNNBase is a concrete instance. type(nn.LSTM).__qualname__ == type(nn.LSTM).__name__, so guards.py:4675 returns NotImplemented and the module is saved by default protocol, which calls RNNBase.__setstate__ (torch/nn/modules/rnn.py:419) at load. That method does not do a presence check — line 429 indexes:

if not isinstance(self._all_weights[0][0], str):

_all_weights is a plain unguarded list of lists of strings (rnn.py:170, 214). It is not a Tensor/Module, not in _NN_MODULE_STATE_ATTRS, not callable, and not an interned singleton, so _prune_unguarded_attributes registers it in missing_values, and — because it is an exact list — the PR's new persistent_id (guards.py:4579) substitutes it. At load self._all_weights is _Missing, and line 429 raises TypeError: '_Missing' object is not subscriptable from inside load_guards_state.

This is newly reachable at this commit: before persistent_id existed, an exact list was saved by type and never pruned, so _all_weights survived. Note this fails at load (package.py:1649), not at dump, so it is not caught by pickle_guards_state's PackageError bypass — it surfaces as an exception during precompile-artifact loading. Compiling any nn.LSTM/nn.GRU/nn.RNN under caching_precompile should reproduce it; there is no test covering a module subclass with a real __setstate__.

The minimal fix is to apply the same gate the generic path uses — prune a module only when _pickles_by_default(type(obj)) holds for its __setstate__, or add an explicit carve-out keyed on cls.__setstate__ is not nn.Module.__setstate__. Note nn.Module itself defines __getstate__/__setstate__ (module.py:1928, 1933), so _pickles_by_default cannot be applied verbatim; the check has to be "no __setstate__ beyond nn.Module's own".

Fix this →

2. torch.SymFloat and torch.SymBool fall through the "torch." exclusion and are pruned into an unusable state.

The generic gate at guards.py:4778 reads:

and not type(obj).__module__.startswith("torch.")

Note the trailing dot. A class defined in torch/__init__.py has __module__ == "torch" exactly, which does not match, so it is not excluded. torch.SymFloat (torch/init.py:971) and torch.SymBool (:1080) each store exactly one field, self.node (:981, :1096), and neither defines __reduce__/__reduce_ex__/__getstate__/__setstate__/__getnewargs__ anywhere in its MRO — so _pickles_by_default returns True and both enter the pruner. node is a SymNode, not a Tensor/Module, not callable, not interned, so unless a guard is rooted at that exact SymNode it is registered missing and the loaded SymFloat has node = _Missing. Every subsequent __float__/__bool__/guard_float then raises AttributeError on the sentinel — a silent corruption rather than a clean bypass.

SymInt is safe only by accident: guards.py:4710 intercepts it with an explicit PackageError before the new block. There is no equivalent branch for SymFloat or SymBool anywhere in the reducer_override chain or in FunctionPicklerBase. Two changes are wanted: make the exclusion type(obj).__module__ == "torch" or ...startswith("torch.") (the comment at guards.py:4790-4796 says "USER objects only", which is the intent the predicate misses), and widen guards.py:4710 to (torch.SymInt, torch.SymFloat, torch.SymBool) so a symbolic float fails the same honest way a symbolic int does.

Same predicate hole, lower likelihood: _TorchCompileInductorWrapper / _TorchCompileWrapper (torch/init.py:2842, 2992) also qualify, and pruning their config/kwargs dicts breaks their __eq__.

Fix this →

3. persistent_id loses object sharing that the reducer_override path preserved. save_pers in the C pickler does not memoize, and the loader emits no PUT, so persistent_load runs once per occurrence: two attributes referencing one pruned list become two distinct _Missing objects. The reducer_override path at guards.py:4597 went through save_reduce and did memoize — and _missing() (guards.py:4427) exists precisely to share one sentinel per reason, which test_snapshot_globals_share_one_missing_sentinel (test_guard_serialization.py:1325) asserts. Nothing appears to depend on sentinel identity today, but the new hook silently opts out of an invariant the file elsewhere tests for, and _PRUNED_VALUE_PID is a single constant so the loader could not distinguish occurrences even if it wanted to. Worth a comment at guards.py:4578 recording that pruned containers do not share, so the next reader doesn't assume the _missing() cache covers this path.

4. _NN_MODULE_STATE_ATTRS's comment overstates what __getattr__ reads. guards.py:4252-4254 says __getattr__ "indexes the three dicts", then the frozenset lists four names. nn.Module.__getattr__ (module.py:1963-1978) indexes _parameters, _buffers, _modules only; _non_persistent_buffers_set is in the set because state_dict/_apply need it, which the comment does not say. Also, guards.py:4853 justifies the skip as avoiding a TypeError on "every attribute miss", but a pruned _modules additionally breaks plain attribute hits on submodules, which is what test_loaded_nested_module_keeps_its_bookkeeping_containers actually exercises.

5. Dead field. GuardFilterEntry.code (types.py:50-53) is written at guards.py:4894 and read nowhere in the repo (GuardFilterEntry( has exactly one construction site). The description says a later commit reads it; landing it with its consumer would keep the stack bisectable.


Testing

1. No test for a module subclass with a real __setstate__. The new test_loaded_nested_module_keeps_its_bookkeeping_containers (test_guard_serialization.py:2869) covers nn.Linear, whose __setstate__ is nn.Module's. Finding 1 is exactly the case that isn't covered: a builtin module whose own __setstate__ reads a pruned attribute. A test compiling nn.LSTM(4, 4) through _test_serialization and then calling load_guards_state would have caught it.

2. No test that a __module__ == "torch" class is excluded from pruning. test_guarded_object_with_a_custom_setstate_is_pickled_whole (:1105) covers the __setstate__ arm of the gate and test_object_rebuilt_from_newargs_is_pickled_whole (:1085) the newargs arm, but nothing pins the torch.-module exclusion the gate's comment (guards.py:4790-4796) describes at length. A test asserting a SymFloat-shaped object keeps its node would pin finding 2.

3. test_an_unguarded_process_group_backend_is_pruned calls real dist.init_process_group in a pickler-level test class. test_guard_serialization.py:1092-1104 initializes and destroys global distributed state inside TestGuardsStatePickler, whose stated contract (:1121-1123) is that these tests "drive GuardsStatePickler directly rather than through a capture, so none of TestGuardSerialization's setup applies". init_process_group mutates process-global state; if the test fails between init and addCleanup registration, or if another test in the file already initialized a group, this leaks or conflicts. FakeProcessGroup can be constructed directly without init_process_group — preferable here, since the assertion only needs an object that is a Backend.

4. Four of the five diagnostic tests still drive _offending_value_path through hand-rolled _Scope fakes (:1467-1600). Same note as round 38: they pin the helper's traversal rather than the last_reduced attribution that feeds it, so an attribution regression would leave them green. test_unpicklable_function_default_names_the_path (:1568) is the right shape.


Backward Compatibility

Artifacts written by this commit cannot be read by an older load_guards_state. pickle_guards_state output now contains persistent-id opcodes whenever a container is pruned; a pre-PR reader is a bare pickle.loads and raises UnpicklingError: A load persistent id instruction was encountered, but no persistent_load function was specified. Old→new is fine (additive). I verified the in-tree read paths are exhaustive — package.py:1649 and aot_compile.py:339 both go through _GuardsStateUnpickler, and every other pickle.loads (package.py:1949, aot_compile.py:482, :836) carries the guards state as opaque nested bytes. So this only matters if precompile artifacts are ever read across versions; if they are, it needs a format-version bump, and if they are strictly same-version, the _PRUNED_VALUE_PID comment (package.py:146-149) is the place to say so.

Separately, the ~30 bare pickle.loads(buf.getvalue()) calls remaining in TestGuardsStatePickler are safe only because each passes missing_values={} and dumps functions/cells/tensors that never reach _prune_unguarded_attributes. Since that method mutates self.missing_values mid-dump, the first future test in that class that roots a guard at a user object with a container attribute will fail with the "no persistent_load" error rather than an informative one. The new tests correctly use load_guards_state; converting the rest would stop the file documenting the pattern that no longer works.


Recommendation

Request Changes

Findings 1 and 2 are correctness bugs newly introduced by this commit's generalization, and both fail at load rather than through the PackageError bypass: an nn.LSTM guards state raises TypeError: '_Missing' object is not subscriptable from RNNBase.__setstate__, and a SymFloat/SymBool loads with node = _Missing and raises on first use. Each needs a regression test; the nn.LSTM one is a few lines through the existing _test_serialization helper.

• Branch: `gh/bobrenjc93/1114/head`

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude please re-review: round-40 fixes are in (every finding from the last review is fixed or answered in the description's FAQ).

@claude

claude Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 50m 55s —— View job


Re-reviewed round 40: the round-39 blockers are genuinely fixed (SymFloat/SymBool now refused, the "torch" top-level-package exclusion, the __setstate__ gate, shared sentinel), but verifying the two new fixes turned up one behavior regression versus the base branch — unguarded str/bytes are no longer pruned, so they now land verbatim in the artifact — and one gate that is far broader than the single class that needed it, which silently disables the PR's own headline fix for Conv/Transformer/Softmax-containing models.

Full review of PR #195912 (round 40)

PR Review: #195912

Summary

Generalizes guard-state attribute pruning from nn.Module to any guard-tree-reached user object, adds a persistent_id/persistent_load pair so exact builtin containers can be pruned, exempts interned singletons from id-keyed pruning, and appends an attribute path to serialization failures. Round 39's two correctness findings are fixed; verifying the fixes surfaced one regression relative to the base branch and one over-broad gate, both below.

Confirmed fixed since round 39 (no action needed): the generic gate now compares the top-level package (type(obj).__module__.partition(".")[0] != "torch", guards.py:4786) and SymFloat/SymBool are refused alongside SymInt (guards.py:4718-4721), with test_torch_namespace_objects_are_pickled_whole; module pruning is gated on type(obj).__setstate__ is torch.nn.Module.__setstate__ (guards.py:4674) with test_loaded_rnn_module_survives_its_own_setstate; _GuardsStateUnpickler._pruned (package.py:420) is a single shared sentinel.


Code Quality

1. _is_interned_singleton returns True for unbounded str and bytes, so unguarded strings and blobs that the base branch replaced with _Missing are now written into the artifact verbatim.

_is_interned_singleton (guards.py:4198-4232) lists str and bytes alongside torch.dtype, bool, int. It is used at two sites to skip pruning: guards.py:5025 (pickle_guards_state, over pytree.tree_leaves(state.output_graph.local_scope)) and guards.py:4869 (_prune_unguarded_attributes). Neither skip exists on the base branch — base has a bare elif id(leaf) not in guard_tree_values: and a pruning loop with no singleton check — so on the base branch a guarded nn.Module's self.raw_blob = b"...100MB...", or a long string local in local_scope, became _Missing in the serialized state. It is now embedded.

The docstring's own justification does not cover these two types:

These are also exactly the values pruning gains nothing from: they are immutable, trivially picklable, and a handful of bytes.

str and bytes are unbounded. And the poisoning mechanism the helper exists to prevent only applies to interned values — the argument for str is that a code-object reducer re-emits interned identifiers (co_name, co_varnames) that guard_tree_values never names, which is real but is confined to short identifier-shaped strings. A 100 MB bytes blob cannot be re-emitted by any reducer here, so skipping it buys nothing and costs artifact size plus writing user payload data to disk that the base branch scrubbed.

Bounding the two by length would keep the poisoning fix intact and restore the pruning: skip str/bytes only up to a small cap (identifiers and interned literals are short), and prune anything longer. Please also say in the docstring which of these entries are there for the poisoning mechanism versus for cheapness, since the two rationales now cover different subsets.

Fix this →

2. The __setstate__ gate is keyed on one class but disables pruning for most in-tree module types, including every Conv and Transformer layer — which un-fixes this PR's headline benefit for the models most likely to need it.

guards.py:4674 prunes a module only when type(obj).__setstate__ is torch.nn.Module.__setstate__. That is an identity check on the resolved attribute, so any subclass that inherits a custom __setstate__ fails it. Grepping torch/nn for def __setstate__, the classes that now stop pruning are:

class file:line what __setstate__ does
_ConvNd (→ all Conv1d/2d/3d, ConvTranspose1d/2d/3d) conv.py:219 if not hasattr(self, "padding_mode") — presence only
MultiheadAttention activation.py:1249 if "_qkv_same_embed_dim" not in state — presence only
TransformerEncoderLayer / TransformerDecoderLayer transformer.py:794, 1081 if not hasattr(self, "activation") — presence only
Softmax / Softmin / LogSoftmax activation.py:1748, 1815, 1902 if not hasattr(self, "dim") — presence only
AvgPool3d pooling.py:906 three setdefaults — presence only
Upsample upsampling.py:183 if "recompute_scale_factor" not in state — presence only
RNNBase (→ LSTM/GRU/RNN) rnn.py:419 reads a value: self._all_weights[0][0] at rnn.py:429

Exactly one of these reads a pruned value. The other six read nothing — they are presence checks and setdefaults, which is the same shape as nn.Module.__setstate__ (module.py:1933-1958) that the gate deliberately allows. So the gate trades away pruning on any model containing a convolution, a transformer layer, or a softmax — i.e. most real models — to protect against RNNBase alone, and for those models one unpicklable bystander attribute on a Conv2d bypasses the frame exactly as it did before this commit. The PR description names this trade-off, but the list is broader than "Conv*, MultiheadAttention, Transformer layers, ..." suggests, and it lands on the common case rather than the rare one.

The narrower fix is the one the file already has a mechanism for: RNNBase.__setstate__ reads self._all_weights (a plain list, so newly prunable via persistent_id) and otherwise only num_layers/bidirectional/bias/proj_size, which are int/bool and already skipped as interned singletons. Adding _all_weights to _NN_MODULE_STATE_ATTRS (guards.py:4254-4258) fixes the LSTM case while keeping pruning universal across modules. If the gate is kept instead, the reasoning for preferring a coarse gate over naming the one attribute belongs in the comment at guards.py:4670-4672, because as written the comment reads as though RNNBase were the only class affected.

Fix this →

3. The four raises converted to PackageError in this commit are the ones that now skip the new path diagnostic. guards.py:5061-5062 is except torch._dynamo.exc.PackageError: raise — bare, no path appended — while guards.py:5085-5088 appends _offending_value_path(...) in the broad arm. This commit converts RuntimeError→PackageError for the Sym* refusal (guards.py:4718), and AssertionError→PackageError for the sympy _torch_unpickler invariant (guards.py:4705) and the two FSDP invariants (guards.py:4831, 4838). Before the change all four fell into the broad arm. The net behavior is unchanged (both arms produce a PackageError and therefore a bypass), so this is message quality only — but the PR's own rationale at guards.py:5082-5084 is that "a type alone ... is not actionable in a model with a thousand-frame guard tree", and Cannot serialize SymFloat s0 (node: ...) is precisely a value with no location. Passing the path through the PackageError arm too, or noting in the comment that these raises are self-locating by design, would keep the two halves consistent.

4. _offending_value_path reads vars(value) where the rest of the PR uses _instance_dict. guards.py:4994-4995 does if hasattr(value, "__dict__"): attributes = list(vars(value).items()). Both calls go through normal attribute lookup, so a user __getattr__, a __dict__ property, or a proxy runs during error reporting — the exact thing _instance_dict (package.py:120-128) was introduced to avoid, and which the pruner at guards.py:4857 now uses. The per-node try/except means a raise is absorbed, but a property with side effects still runs. Use _instance_dict(value) here so there is one rule in the file.

5. Process-global shared sentinel. _GuardsStateUnpickler._pruned (package.py:420) is a class attribute, so one _Missing instance is shared across every artifact loaded in the process, not just across occurrences within one load. That is more sharing than the invariant needs (_Missing carries a mutable _reason). Making it per-instance in __init__ gets the same within-artifact sharing the FAQ describes without the cross-artifact coupling.


Testing

1. The FakeTensor dispatch_keys / no_dispatch() change still has no test. guards.py:4635-4654 changes two things for a FakeTensor: the dispatch-key source (obj.dispatch_keys when non-None, otherwise _dispatch_keys(obj)) and the empty_like context (no_dispatch()). Nothing in the diff exercises either arm — the only _dispatch_keys uses in the test file are test_guard_serialization.py:2658 and :2664, which build a DispatchKeySet as a guarded input, not as a fake-tensor reducer payload. The description's answer (both paths hit Cannot serialize SymInt for a dynamic fake, and a static fake round-trips) is a testable claim in two lines; asserting the round-tripped dispatch_keys.raw_repr() for a static fake would pin the obj.dispatch_keys branch, which is the one that changes what lands in the artifact.

2. last_reduced attribution has no test. The description says the attribution was reproduced by hand "for a __getstate__ that asserts and for a generator inside a list; both name the right object", but neither reproduction is in the diff. Four of the five new diagnostic tests (test_guard_serialization.py:1490-1600) drive _offending_value_path through hand-rolled _Scope fakes and never touch reducer_override, so they stay green if self.last_reduced = obj (guards.py:4592) starts misattributing. test_unpicklable_function_default_names_the_path (:1568) is the one that goes through pickle_guards_state; a second in that shape — a nested __getstate__ that raises, asserting the path names the object whose __getstate__ failed rather than a sibling — would pin the claim the FAQ makes.

3. Nothing pins which module types the __setstate__ gate excludes. test_loaded_rnn_module_survives_its_own_setstate (:2929) covers the LSTM that motivated the gate, and test_loaded_nested_module_keeps_its_bookkeeping_containers (:2893) covers nn.Linear, which inherits nn.Module.__setstate__. Neither records the consequence in finding 2 — that a Conv2d/MultiheadAttention/Softmax submodule now prunes nothing. A test asserting an unguarded unpicklable attribute on a Conv2d is (or is not) pruned would make the trade-off visible and would fail loudly if the gate is later narrowed, which is the point of having it.


Recommendation

Request Changes

Finding 1 is a regression against the base branch that CI cannot see: unguarded str/bytes used to be scrubbed from the guards state and are now written verbatim, unbounded in size. Finding 2 means the pruning generalization — the point of the commit — is switched off for any model containing a Conv or Transformer layer, in exchange for protecting one class that a single entry in _NN_MODULE_STATE_ATTRS would cover. Both are design-level and both should be settled before landing; the testing items are smaller but items 1 and 2 there each pin a claim the description currently makes by assertion.

• Branch: `gh/bobrenjc93/1114/head`

@bobrenjc93 bobrenjc93 changed the title [dynamo] Prune guard state by the guard tree and diagnose the offending value [ref-stack][dynamo] Prune guard state by the guard tree and diagnose the offending value Sep 19, 2026
@bobrenjc93 bobrenjc93 closed this Oct 16, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1114/head branch November 17, 2026 01:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request module: dynamo release notes: dynamo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant