Skip to content

[guards] Carry a tensor's guard-traversed Python attributes through the pickle - #194317

Closed
bobrenjc93 wants to merge 3 commits into
gh/bobrenjc93/1016/basefrom
gh/bobrenjc93/1016/head
Closed

bobrenjc93 wants to merge 3 commits into
gh/bobrenjc93/1016/basefrom
gh/bobrenjc93/1016/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Guard serialization rebuilds a tensor from its metadata --
torch.empty_like(obj, device="meta", ...) plus dtype, device, dispatch keys
and .grad -- and throws its __dict__ away. So a guard whose SOURCE
traverses 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_copy against the reconstructed scope and raises
AttributeError: '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 this
keeps 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_function and
caching_precompile + DynamoCache reproduce it identically, so the fix is
here rather than in any one consumer.

Carry the attributes, pruned to what a guard can actually reach, which is the
policy _prune_unguarded_attributes already applies to nn.Modules and to user
objects; 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 = x and a
two-tensor cycle terminate instead of recursing -- the two-tensor cycle is a hard
load failure today -- and _unpickle_tensor's signature is untouched, so an
artifact written before this still loads.

The FakeTensor-bookkeeping skip is gated on the tensor actually BEING fake.
Ungated, a user attribute named constant or real_tensor is silently
dropped, 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 guard
whose expected value is now None, and a mark_unbacked artifact stops serving
the 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.Generator joins the unsupported types. It pickles but does not
unpickle -- its __setstate__ raises and surfaces as a bare SystemError
from inside load() -- so it degrades to the _Missing sentinel like
torch.cuda.Stream already 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:

python test/test_precompile.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_package.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_aot_compile.py

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_unbacked artifact serving
the 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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 21, 2026 •

Copy link
Copy Markdown

🔗 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 Failure

As of commit 75226dd with merge base 1b4e490 (image):

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.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Aug 21, 2026
This was referenced Aug 21, 2026
@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Aug 21, 2026
This was referenced Aug 22, 2026
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

1 similar comment
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Superseded by the canonical precompile stack #195353-#195362; this change lives in #195362 (with the guard-drop policy half in #195360). Closing to consolidate review there. The branch is kept on GitHub.

@bobrenjc93 bobrenjc93 closed this Sep 3, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1016/head branch November 12, 2026 01:45
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 topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant