Repository navigation
[guards] Carry a tensor's guard-traversed Python attributes through the pickle - #194317
Closed
bobrenjc93 wants to merge 3 commits into
Closed
bobrenjc93 wants to merge 3 commits into
bobrenjc93 wants to merge 3 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194317
Note: Links to docs will display an error until the docs builds have been completed. ❌ 24 New Failures, 1 Unrelated FailureAs of commit 75226dd with merge base 1b4e490 ( NEW FAILURES - The following jobs have failed:
BROKEN TRUNK - The following job failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This was referenced Aug 21, 2026
Closed
Closed
This was referenced Aug 22, 2026
Closed
Contributor
Author
|
@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
1 similar comment
Contributor
Author
|
@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
Contributor
Author
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Guard serialization rebuilds a tensor from its metadata --
torch.empty_like(obj, device="meta", ...)plus dtype, device, dispatch keysand
.grad-- and throws its__dict__away. So a guard whose SOURCEtraverses a plain Python attribute assigned onto a tensor cannot be rebuilt:
capture writes the guard happily, and rebuilding the tree later evaluates
L['x']._cpu_copyagainst the reconstructed scope and raisesAttributeError: 'FakeTensor' object has no attribute '_cpu_copy'.Hanging metadata on a tensor is a common trick, not an exotic one -- torch does
it itself, which is why generated guard code is full of
hasattr(..., '_dynamo_dynamic_indices')-- and the model that prompted thiskeeps a CPU twin of selected GPU tensors that way so downstream kernels can read
lengths without a D2H sync. This is not precompile-specific either:
torch.compile(fn).aot_compile(...)+load_compiled_functionandcaching_precompile+DynamoCachereproduce it identically, so the fix ishere rather than in any one consumer.
Carry the attributes, pruned to what a guard can actually reach, which is the
policy
_prune_unguarded_attributesalready applies to nn.Modules and to userobjects; the tensor branch was the outlier in dropping everything. Pruned rather
than whole because an unguarded neighbour is nobody's business and may not even
be picklable.
Four details are each load-bearing, and each was found by it going wrong.
They ride in the reduce STATE slot rather than as another constructor argument.
Pickle memoizes the tensor before it saves state, so
x.companion = xand atwo-tensor cycle terminate instead of recursing -- the two-tensor cycle is a hard
load failure today -- and
_unpickle_tensor's signature is untouched, so anartifact written before this still loads.
The FakeTensor-bookkeeping skip is gated on the tensor actually BEING fake.
Ungated, a user attribute named
constantorreal_tensoris silentlydropped, and because a reconstructed FakeTensor already owns that name there is
no AttributeError to notice: the artifact loads and then rejects every call,
including its own capture input. The four names a FakeTensor structurally needs
to be one are refused by name instead, since carrying those would overwrite it.
The dimension-marking allowlist has seven entries, not five. A TENSOR_MATCH
guard reads those off the example value rather than through a source, so nothing
registers them in the guard tree and pruning cannot see them -- but two of them
(
_dynamo_shape_ids,_dynamo_unbacked_bounds) are DEPENDENT, gated on_dynamo_unbacked_indices. Carrying the gate without them activates a guardwhose expected value is now None, and a
mark_unbackedartifact stops servingthe very tensor it was captured on. A partial list is worse than no list: today
all of them are dropped, so the guard is vacuous and the artifact works.
And the state is None rather than an empty dict when nothing is carried, or
every tensor pays for a state slot it does not use: +0.7% on a 12-layer MLP.
With it, a resnet18 artifact is byte-identical at 1,005,932.
torch.Generatorjoins the unsupported types. It pickles but does notunpickle -- its
__setstate__raises and surfaces as a bareSystemErrorfrom inside load() -- so it degrades to the
_Missingsentinel liketorch.cuda.Streamalready does.One behaviour change: a guard-traversed attribute that cannot be pickled at all
(a lock, a file, a socket) now fails at CAPTURE rather than at load. The artifact
never worked either way, and the commit below this one makes that error name
where the value lives.
Test Plan:
test_aot_compile.py has 3 pre-existing failures in this environment
(test_aot_compile_with_aoti*,
fatal error: cuda.h: No such file or directory),identical with and without this change.
Six new tests, one per hazard above: the guard round-tripping in both serving
modes; the attribute being carried by VALUE rather than baked, so rebinding it
between capture and serve changes the answer and a large one does not land in
the artifact; a self-referential attribute; a
mark_unbackedartifact servingthe tensor it captured; the reserved-name refusal; and, at the
guard_serialization level, that the rebuilt manager still discriminates on the
attribute's dtype and shape rather than merely existing.
A warning for whoever writes the next test here: every marking test in these
suites marks one tensor and then serves a DIFFERENT, unmarked one, which passes
with this bug fully present. That is why nothing caught it. A regression test
has to serve the marked tensor itself.
Also checked by hand: DTensor, a TwoTensor with a plain attribute, an attribute
on an nn.Parameter, on a buffer, on a tensor inside a list and inside a dict, a
16 MB attribute (artifact stays at 25,742 chars, so no baked weights), and a
second round trip through the invariant-guard policy.
Authored with an AI assistant.
Differential Revision: D116884336