Skip to content

[dynamo] Fix precompile guard serialization for transparent tensor subclasses - #190576

Closed
williamwen42 wants to merge 3 commits into
gh/williamwen42/525/basefrom
gh/williamwen42/525/head
Closed

williamwen42 wants to merge 3 commits into
gh/williamwen42/525/basefrom
gh/williamwen42/525/head

Conversation

@williamwen42

@williamwen42 williamwen42 commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

Stack from ghstack (oldest at bottom):

GuardsStatePickler serializes a traceable-wrapper-subclass guard value as
torch.empty_like(obj, device="meta") and separately records pytype=type(obj).
On reload, _unpickle_traceable_wrapper_subclass called
type(meta_tensor).tensor_unflatten instead of the recorded pytype. For a
transparent subclass such as AsyncCollectiveTensor -- whose torch_dispatch
desugars factory ops to the inner tensor -- torch.empty_like returns a plain
Tensor, so type(meta_tensor) is torch.Tensor and reload crashes with
"type object 'Tensor' has no attribute 'tensor_unflatten'". Unflatten
through the recorded pytype instead; it is already carried in the pickled
payload, so no extra state is needed.

Test Plan:

python test/dynamo/test_guard_serialization.py -k test_transparent_subclass_tensor_match

This PR was authored with the assistance of an AI coding assistant.

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 Jul 20, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 1 Unrelated Failure

As of commit b228571 with merge base 33a34d6 (image):

NEW FAILURE - The following job has failed:

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.

@williamwen42

Copy link
Copy Markdown
Member Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jul 21, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

[ghstack-poisoned]
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #189482

pytorchmergebot pushed a commit that referenced this pull request Jul 29, 2026
…nsor input (#189482)

Fixes #187073.

Root cause: for a traceable wrapper subclass input, Dynamo installs
class-identity guards (a TYPE_MATCH leaf, TENSOR_SUBCLASS_METADATA_MATCH, and
the pytype check baked into the outer TENSOR_MATCH). When a compiled region's
input alternates between an AsyncCollectiveTensor (ACT) and the resolved plain
Tensor -- as happens under FSDP + TP, where an all-gather output is natively an
ACT but is awaited to a plain Tensor before the compiled region on some steps
-- those guards fail on the class change and force a recompile, even though the
two graphs are equivalent (the AOTAutograd runtime wrapper already unwraps ACT
inputs). Users hit this as recompiles blowing past cache_size_limit.

Fix: an ACT flattens to a single inner tensor `elem` whose metadata mirrors the
wrapper, and the AOTAutograd forward runtime unwrap already tolerates a plain
Tensor where a subclass was traced. So for an ACT input, guard the unwrapped
inner tensor through a new guard-only UnwrapCollectiveTensorSource (which yields
x.elem when x is an ACT and x unchanged otherwise) instead of the ACT-locked
class/metadata guards. The traced graph, grapharg, and AOT calling convention
are unchanged -- only guard installation changes -- so an ACT-traced graph is
reused for the resolved plain Tensor with no recompile. Only the
ACT-at-trace -> Tensor-at-runtime direction is relaxed (the relaxation triggers
only when the traced value is an ACT); the reverse direction stays guarded,
since a Tensor-traced graph may skip the collective await.

Soundness: the only way an ACT-traced graph can differ from a plain-Tensor one
is if the region observes the input's Python class. Rather than enumerate
observation channels, the guard is reinstalled on demand at the sites that fold
the class into a value: TensorVariable.var_getattr("__class__") now attaches a
TypeSource (mirroring BuiltinVariable.call_type, so it self-guards downstream --
this is general for all tensors), and call_isinstance installs a TYPE_MATCH for
an ACT arg only when the check actually discriminates ACT from torch.Tensor
(so isinstance(w, torch.Tensor) still reuses, isinstance(w, ACT) recompiles).
type()-based channels already carry provenance via TypeSource and self-guard.

Alternatives considered: (1) a config flag to gate the relaxation was dropped
because, once observation sites self-guard, the change is sound and does not
need an opt-in. (2) Anchoring the ACT inner tensor's ShapeEnv symbols at the
unwrap source (to make dynamic shapes reuse perfectly too) was prototyped and
abandoned: the symbolic-shape and guard machinery hard-require subclass inner
sources to be AttrSource, so this needs a broader design for polymorphic
subclass inner sources. As a result, under dynamic shapes the ACT and the
resolved plain Tensor land in two separate cache entries: the ShapeEnv derives
the inner dim from a plain `.elem` AttrSource rather than the unwrap source, so
the symbolic-shape guard evaluates `L['w'].elem.size()` and fails with an
AttributeError on a plain Tensor. This split is one-time and stable (each class
always hits its own entry; 4 and 8 reps both compile exactly twice), not a
per-alternation recompile. Static shapes reuse perfectly.

Test Plan:

```
python test/dynamo/test_subclasses.py -k async_collective_tensor
python test/dynamo/test_subclasses.py -k dunder_class_provenance
python test/dynamo/test_subclasses.py
python test/dynamo/test_functions.py
```

Distributed (requires 2 GPUs):

```
python test/distributed/test_inductor_collectives.py -k async_collective_tensor
```

This PR was authored with the assistance of an AI coding assistant.

Pull Request resolved: #189482
Approved by: https://github.com/aorenste
ghstack dependencies: #190576
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 Merged module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants