Repository navigation
[ref-stack][dynamo] Prune guard state by the guard tree and diagnose the offending value - #195912
bobrenjc93 wants to merge 54 commits into
Conversation
[ghstack-poisoned]
🔗 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. |
[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]
|
@claude /pr-review |
|
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 Full review of PR #195912PR Review: #195912SummaryGeneralizes guard-state pruning from nn.Module attributes to any guard-tree-reached object, adds a Code Quality1.
That asymmetry is load-bearing here because of how if "_forward_pre_hooks" not in self.__dict__:
self._forward_pre_hooks = OrderedDict()
The comment at 2.
# Reading .grad off a non-leaf warns and is always None anyway;
obj.grad if obj.is_leaf else None,The warning predicate is This is reachable: 3. The gate reads the instance dict safely, then the pruner re-reads it unsafely.
4. 5. 6. Interned-singleton allowlist is a hand-maintained denylist of the same shape as the bug it fixes. 7. Dead field. Testing1. No test for the 2. No test for the 3. No test for the 4. No test for the 5. The diagnostic tests build hand-rolled fakes rather than exercising the real path. Four of the five new Backward CompatibilityGuards-state bytes now contain persistent ids, so any consumer without a
Relatedly, defining RecommendationRequest Changes Findings 1 and 2 are correctness bugs (a |
[ghstack-poisoned]
[ghstack-poisoned]
|
@claude /pr-review |
Reviewing PR #195912
|
[ghstack-poisoned]
|
@claude please re-review: round-39 fixes are in (all inline threads addressed; FAQ updated in the description). |
|
Claude finished @bobrenjc93's task in 3m 24s —— View job Re-reviewed round 39: the previously-flagged Full review of PR #195912 (round 39)PR Review: #195912SummaryGeneralizes guard-state attribute pruning from Confirmed fixed since round 38 (no action needed): Code Quality1. guards.py:4667 calls
if not isinstance(self._all_weights[0][0], str):
This is newly reachable at this commit: before The minimal fix is to apply the same gate the generic path uses — prune a module only when 2. The generic gate at guards.py:4778 reads: and not type(obj).__module__.startswith("torch.")Note the trailing dot. A class defined in
Same predicate hole, lower likelihood: 3. 4. 5. Dead field. Testing1. No test for a module subclass with a real 2. No test that a 3. 4. Four of the five diagnostic tests still drive Backward CompatibilityArtifacts written by this commit cannot be read by an older Separately, the ~30 bare RecommendationRequest Changes Findings 1 and 2 are correctness bugs newly introduced by this commit's generalization, and both fail at load rather than through the |
[ghstack-poisoned]
|
@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 finished @bobrenjc93's task in 50m 55s —— View job Re-reviewed round 40: the round-39 blockers are genuinely fixed ( Full review of PR #195912 (round 40)PR Review: #195912SummaryGeneralizes guard-state attribute pruning from Confirmed fixed since round 39 (no action needed): the generic gate now compares the top-level package ( Code Quality1.
The docstring's own justification does not cover these two types:
Bounding the two by length would keep the poisoning fix intact and restore the pruning: skip 2. The guards.py:4674 prunes a module only when
Exactly one of these reads a pruned value. The other six read nothing — they are presence checks and The narrower fix is the one the file already has a mechanism for: 3. The four raises converted to 4. 5. Process-global shared sentinel. Testing1. The FakeTensor 2. 3. Nothing pins which module types the RecommendationRequest Changes Finding 1 is a regression against the base branch that CI cannot see: unguarded |

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
codesnapshot of the guard'scode_list at inspection time, since later build_guards calls reset it; the
capture session (a later commit) reads it.
Test Plan:
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 raisesother 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 itscontainer edge and bound-method probe, so no user code runs there. Covered by
test_attribute_guard_on_a_slotted_receiver_runs_no_user_getattrin #195353,which compiles a slotted receiver whose
__getattr__raises RuntimeError for__dict__under caching_precompile.Q:
_pickles_by_defaultignores__getnewargs__/__getnewargs_ex__; a prunedattribute 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: aclass returning
(self.a,)from__getnewargs__loaded witha = _Missing).Fixed by excluding classes with either hook from the default protocol, with
test_object_rebuilt_from_newargs_is_pickled_whole.Q:
.gradis read only for leaf tensors, but aretain_grad()non-leaf --which torch.optim accepts as a param -- has a real
.grad.A: Real at this commit (the parent read
.gradunconditionally); theobj.is_leaf or obj.retains_gradpredicate andtest_retained_grad_non_leaf_survives_pickleare folded down here from #195924.Q: nn.Module hook dicts are pruned to
_Missingon a loaded module;__setstate__or
__getattr__could read them.A: Behaviour-identical to the parent commit: an
OrderedDictis not an exactdict, so it already went throughreducer_overrideand was pruned by id. It isdeliberate -- 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 moduleis fed to
CheckFunctionManagerto rebuild the guard manager, never called.(Correction: that argument holds for
nn.Module.__setstate__itself, not for aSUBCLASS with its own
__setstate__; see the RNNBase item below, which is fixed.)Q: The gate uses
_instance_dictbut the pruner loop usesvars(obj).A: Made consistent (the loop reads
_instance_dict(obj)too). No behaviourchange: for an object past the gate
vars()can only differ via a__getattribute__override, and plain pickle fails on the same object before thepruner is reached.
Q:
last_reducedcan misattribute the culprit when a nested reduce fails.A: The C pickler consults
reducer_overridefor every object outside the exactbuiltin fast paths, including the object whose own
__getstate__/__reduce_ex__then fails, so
last_reducedis 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.
SDPBackendmembers, 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-emptyconstant tuple is re-emitted only from a
co_consts/__defaults__a guard alsoreads, and then it is in
guard_tree_values.SDPBackendmembers arepybind11_objects, not ints, and no reducer emits one, so they need no entry.Q: No dtype/device pickler-level test, no
persistent_loadrejection test, noBackendpruning test, andtest_grad_mode_loadingusespickle.loadson aguards 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'sBackend, skipped without distributed), andtest_grad_mode_loadingnow goesthrough
load_guards_state. The otherpickle.loadsin the file are onpickler-level fixtures that emit no persistent id.
Q:
no_dispatch()aroundempty_likefor a FakeTensor loses dynamic-shapeinformation.
A: Both with and without
no_dispatchthe pickle receives a sym-sized metatensor and hits the pre-existing
PackageError: Cannot serialize SymInt, so thechange 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_pathis a pure function over the state, so its unit teststarget its traversal;
test_unpicklable_function_default_names_the_pathcoversthe real
pickle_guards_state/last_reducedpath end to end.Q: Should the two persistent-id namespaces (guards state, AOT) be documented as
disjoint?
A: The
_PRUNED_VALUE_PIDcomment already says any other pid in a guards state isa bug, and
persistent_idis defined onGuardsStatePicklerrather than theshared base precisely because
AOTCompilePickler.persistent_idhas its ownnamespace; format-version gating is
SystemInfo'storch_versioncheck.Q: An nn.Module subclass with its own
__setstate__(RNNBase indexes_all_weights) reads a pruned attribute at load, so a saved LSTM frame failsto load.
A: Real; fixed. Pruning now runs only for modules whose
__setstate__isnn.Module.__setstate__(presence checks only) plus DDP, which is rebuiltthrough
nn.Module.__setstate__explicitly; a module with its own__setstate__is pickled whole. Reproduced withallow_rnn=True(the defaultconfig 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.aoquantized modules, or a user subclass whose
__setstate__reads a prunedattribute). 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_setstatecovers theLSTM shape end to end through the serialization harness.
Q:
type(obj).__module__.startswith("torch.")letstorch.SymFloat,torch.SymBoolandtorch._TorchCompileInductorWrapper(module exactly"torch") through the pruner; only
SymIntis refused.A: Fixed: the exclusion compares the top-level package (
partition(".")[0] != "torch"), and the refusal coversSymInt,SymFloatandSymBool.test_torch_namespace_objects_are_pickled_wholeround-trips the inductorwrapper whole and checks a SymFloat raises
PackageError.Q:
persistent_loadreturns a fresh_Missingper occurrence, so twoattributes that shared one pruned object load as two sentinels.
A:
_GuardsStateUnpicklernow hands out one shared sentinel. Note the invariantthe review assumes did not hold before either: distinct pruned objects never
shared a sentinel on the
missing_valuespath (the_missing()cache serves thesnapshot
_pruneonly); sharing is restored outright rather than per object.Q: The
_NN_MODULE_STATE_ATTRSand pruner comments say__getattr__runs "onevery 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), andstate_dict/named_buffersread
_non_persistent_buffers_set.Q:
GuardFilterEntry.codeis dead in this commit; move it to the commit thatreads it.
A: The reader is the capture session (#195919,
precompile_package.py). Thesnapshot has to be taken in
make_guard_filter_entry, because laterbuild_guardscalls resetcode_list: that is a guards.py invariant, so thefield 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 aFakeProcessGroupdirectly.A:
FakeProcessGrouphas no Python constructor ("No constructor defined!"). Thetest now builds
ProcessGroupGloo(HashStore(), 0, 1)directly, which is aBackend, needs no default group and leavesdist.is_initialized()False;skipped when gloo is unavailable.
Q: Artifacts written by this commit contain persistent-id opcodes an older
load_guards_state(barepickle.loads) cannot read.A: Every reader gates on
SystemInfo.check_compatibility(torch_versionequality) BEFORE
load_guards_state:initialize()->check_versionsrunsbefore
install()on both the eval_frame andload_and_install_packagepaths,and
CompileArtifacts.__post_init__precedes the AOT load. An artifact is onlyever read by the torch that wrote it. This commit also changes
_unpickle_tensor'sreduce tuple (
dispatch_keys), so a pre-PR reader fails on any tensor-bearingartifact regardless of persistent ids; the guards-state stream has never been
cross-version. Caveat for the record:
torch_versionistorch.__version__,which a build pinning a constant version string across commits would not
distinguish; that is a pre-existing
SystemInfoproperty, not this PR's. The_PRUNED_VALUE_PIDcomment 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 remainingpickle.loadsround-trips a plainpickle.dumps, not a guards state).[no ci]