Skip to content

[dynamo] Serialize guarded tensors' .grad on the package guard path - #195686

Closed
bobrenjc93 wants to merge 9 commits into
gh/bobrenjc93/1105/basefrom
gh/bobrenjc93/1105/head
Closed

bobrenjc93 wants to merge 9 commits into
gh/bobrenjc93/1105/basefrom
gh/bobrenjc93/1105/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

When CompilePackage serializes a guard state, GuardsStatePickler turns each
guarded tensor into a meta tensor via reducer_override. Previously a plain
tensor's .grad was passed to the reducer but never registered in the guard
tree, so the reducer turned it into the _Missing sentinel and loading a guard
on a tensor with a populated grad failed hard ("assigned grad expected to be a
Tensor or None but got grad of type _Missing") unless the grad was itself
guarded (a GradSource guard registers it in the guard tree); the
wrapper-subclass path did not carry the outer grad at all, so it silently
loaded with grad=None, and rebuilding a guard on that grad then failed.

Why registering in the reducer alone is not enough: pickle memoizes by object id. A tensor's .grad can also be reached
through an unguarded leaf (e.g. a plain local dict whose TYPE_MATCH guard never
visits its values). If that leaf is pickled before the grad's owner tensor, the
grad object is first encountered outside the guard tree and memoized as the
_Missing sentinel; when the owner is later reduced, pickle reuses the sentinel
and the grad is lost. Whether this happens depends purely on f_locals ordering.

Fix: register grads before pickling starts. pickle_guards_state walks the known
guarded tensors, descending into a wrapper subclass's inner tensors (which are
in the guard tree only when Dynamo guarded them: TENSOR_MATCH on the subclass
does, TYPE_MATCH alone does not), and adds each live .grad to guard_tree_values
(removing it from missing_values), transitively, so the grad is always seen
first as a real tensor and reduced to a meta tensor. reducer_override keeps its
own setdefault for anything still discovered mid-dump.

The wrapper-subclass unpickle path also restores the outer requires_grad
(recorded on the meta stand-in): tensor_unflatten derives it from the inner
tensors, so a leaf subclass over an autograd-free inner, or a grad produced
under create_graph, loaded with requires_grad=False and its TENSOR_MATCH guard
rejected the input it was built from. This predates the stack but the
grad-carrying path makes it reachable through .grad too.

A non-strided grad (a sparse grad from nn.Embedding(sparse=True)) is
serialized as None: Dynamo refuses to trace sparse tensors, so no guard can
compare against its metadata, and pickling a meta tensor drops the layout,
which would otherwise substitute a dense stand-in. Grads are read through
torch._subclasses.meta_utils.safe_grad (unconditionally, with the non-leaf
warning suppressed, as Dynamo's builder does): a non-leaf can hold a manually
assigned grad that a GradSource guard then checks. A failing .grad access is
classified as a PackageError like every other serialization failure.

The test harness's guard_filter_fn now accepts a tuple of guard types and
asserts each requested type matches at least one emitted guard, so the grad
ordering tests can require both the tensor's TENSOR_MATCH and the aliasing
dict's TYPE_MATCH to be present.

Test Plan:

python test/dynamo/test_guard_serialization.py

New tests: test_tensor_match_populated_grad,
test_tensor_grad_aliased_by_unguarded_local (grad reached through a dict local
listed before its owner) and _swapped (owner listed first),
test_subclass_grad_metadata_guard_round_trips, test_none_grad_reference_tensor_round_trips,
test_sparse_grad_serializes_as_none (asserts the serialized grad is None),
test_module_parameter_grad_round_trips, test_grad_of_grad_round_trips,
test_non_leaf_assigned_grad_round_trips, test_grad_metadata_guard_round_trips
(coverage of the GradSource guard; it and the other tests whose grad is itself
guarded pass on the pre-fix code), and
test_subclass_inner_grad_aliased_by_unguarded_local (only a TYPE_MATCH on the
subclass, so the walk must descend into the inner tensors itself) and
test_subclass_outer_requires_grad_round_trips.

Authored with an AI assistant.

Co-Authored-By: Claude Fable 5.1 [email protected]

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 7 Cancelled Jobs, 13 Pending, 1 Unrelated Failure

As of commit 03049a0 with merge base 3d3d3f4 (image):

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

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

[ghstack-poisoned]

@sylvesterkaczmarek sylvesterkaczmarek 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.

Could we fail closed for non-strided grads rather than serializing them through this path?

The new comment already notes that sparse COO/CSR grads are not faithfully round-tripped by the meta empty_like reduction. Since .grad can itself be part of the guard tree, loading such a package can reconstruct different layout metadata from what was captured.

If sparse-grad serialization is not supported yet, explicitly rejecting a non-strided grad.layout during guard serialization seems safer than emitting an artifact with altered tensor metadata. A sparse embedding-gradient regression would also pin this boundary.

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

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: dynamo"

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Thanks for the careful read. The current behavior is the middle option between what you describe and what the first version did: a non-strided grad is now serialized as None rather than through the meta empty_like path, so the artifact never carries altered layout metadata for it. The reasoning in _serializable_grad is that Dynamo refuses to wrap sparse tensors outside export, so no serialized guard can compare against a sparse grad's metadata, and None is exactly what the loaded guard state would have had if the grad had never been populated. test_sparse_grad_serializes_as_none pins that (an nn.Embedding(sparse=True) gradient), and the loaded guards accept sparse-grad, dense-grad and no-grad candidates alike.

Failing closed instead would make every package that guards on an embedding table with a sparse grad unserializable, which felt too strict given no guard reads that metadata. If you still prefer fail-closed for the guard-tree case specifically (a GradSource guard rooted at a sparse grad), that is a small change: raise GuardSerializationError from _serializable_grad when the grad is itself in the guard tree. Happy to do that if you think the None round-trip is the wrong default.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Closing in favor of the canonical stack #195353-#195362 (now also #195911-#195929). Note for future readers: this change has no counterpart there yet; the code remains in this PR's history if it is wanted later.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants