Skip to content

[dynamo] Reuse AsyncCollectiveTensor-traced graph for the resolved Tensor input - #189482

Closed
williamwen42 wants to merge 6 commits into
gh/williamwen42/503/basefrom
gh/williamwen42/503/head
Closed

williamwen42 wants to merge 6 commits into
gh/williamwen42/503/basefrom
gh/williamwen42/503/head

Conversation

@williamwen42

@williamwen42 williamwen42 commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Stack from ghstack (oldest at bottom):

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.

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 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (6 Unrelated Failures)

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

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

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 Jul 9, 2026
@williamwen42 williamwen42 added the topic: not user facing topic category label Jul 9, 2026
[ghstack-poisoned]
williamwen42 added a commit that referenced this pull request Jul 10, 2026
…nsor input

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 first
ACT<->Tensor transition recompiles once (like normal dynamic-shape warmup) and
then stabilizes; 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.


ghstack-source-id: b0716ef
Pull-Request: #189482
[ghstack-poisoned]
williamwen42 added a commit that referenced this pull request Jul 20, 2026
…nsor input

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 first
ACT<->Tensor transition recompiles once (like normal dynamic-shape warmup) and
then stabilizes; 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.

ghstack-source-id: 75d940b
Pull-Request: #189482
williamwen42 added a commit that referenced this pull request Jul 20, 2026
…nsor input

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.

ghstack-source-id: 75d940b
Pull-Request: #189482
@williamwen42
williamwen42 marked this pull request as ready for review July 21, 2026 02:34
[ghstack-poisoned]
williamwen42 added a commit that referenced this pull request Jul 21, 2026
…nsor input

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.

ghstack-source-id: eec6826
Pull-Request: #189482

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

(Reviewed by me, assisted by AI)

[cleanup] Only top-level ACT inputs are tested (fn(x, w) with w an ACT or plain Tensor), but the FSDP+TP shape this PR targets is an ACT nested inside DTensor._local_tensor (async all-gather / redistribute(async_op=True)) -- the shape #186442 was built for. Tracing the guards shows this case reuses by the same mechanism as the flat one: the recursion into _local_tensor re-enters wrap_tensor, hits is_polymorphic_act, and relaxes the inner guard via UnwrapCollectiveTensorSource(AttrSource(dt, "_local_tensor")), while the outer DTensor guards (TYPE_MATCH, DTENSOR_SPEC_MATCH, requires_grad) don't discriminate on the local's class. So it should reuse -- but there's no regression test locking it in, even though it is the motivating scenario. Add one: it can run single-process on a fake PG in TestDTensorCompile (the Dynamo twin of test_direct_aot_dtensor_local_tensor_act_to_plain_no_crash), no multi-GPU needed.

[cleanup] My agent says: The serialization coverage for this relaxation stops one assertion short of its core property. test_transparent_subclass_tensor_match (added in the stacked #190576) round-trips an AsyncCollectiveTensor input, and at this PR's HEAD it does exercise the new UnwrapCollectiveTensorSource guard path -- but it only asserts the reloaded guard matches an ACT (_test_check_fn(ref, loaded, {"w": AsyncCollectiveTensor(base)}, True)). It never asserts the reloaded guard also matches the resolved plain Tensor (_test_check_fn(ref, loaded, {"w": base}, True)) -- which is exactly the ACT->Tensor reuse this PR exists to enable, and the case that matters for precompile under FSDP+TP. The property holds by construction (guard state is rebuilt by name on load rather than pickled), so this is a lock-in regression test, not a suspected bug -- low priority. The assertion lands in #190576's file (test/dynamo/test_guard_serialization.py), not this one.

Comment thread torch/_dynamo/source.py
# plain Tensor is passed at runtime. See
# torch._dynamo.variables.builder.VariableBuilder.wrap_tensor.
@dataclass_with_cached_hash(frozen=True)
class UnwrapCollectiveTensorSource(ChainedSource):

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.

Anchored here for UI visibility -- see the review body for the two test-coverage findings (nested ACT-in-DTensor reuse; serialized-guard round-trip). This UnwrapCollectiveTensorSource is the guard source both findings turn on.

Comment thread torch/_dynamo/variables/builder.py Outdated
Comment on lines +3102 to +3107
if not is_dtensor and is_traceable_wrapper_subclass(value):
from torch._functorch._aot_autograd.utils import (
is_async_collective_tensor_type,
)

is_polymorphic_act = is_async_collective_tensor_type(type(value))

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.

nit: Unnecessary complexity - I would do the import at top-level and just check is_async_collective_tensor_type (which is actually going to be faster to check than is_traceable_wrapper_subclass anyway)

Comment thread torch/_dynamo/guards.py Outdated
_async_collective_tensor_type: type | None = None


def unwrap_async_collective_tensor(x: Any) -> Any:

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.

nit: Should be either:

def unwrap_async_collective_tensor(x: Tensor) -> Tensor:

or possibly:

def unwrap_async_collective_tensor(x: T) -> T | Tensor:

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added the ciflow/dtensor Run DTensor specific tests label Jul 28, 2026
williamwen42 added a commit that referenced this pull request Jul 28, 2026
…nsor input

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.

ghstack-source-id: db6fe4c
Pull-Request: #189482
@williamwen42 williamwen42 added the ciflow/trunk Trigger trunk jobs on your pull request label Jul 28, 2026
[ghstack-poisoned]
williamwen42 added a commit that referenced this pull request Jul 29, 2026
…nsor input

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.

ghstack-source-id: 4ec8250
Pull-Request: #189482
@williamwen42

Copy link
Copy Markdown
Member Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 0 checks:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/dtensor Run DTensor specific tests 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