Skip to content

Resolve nested ACT inputs before AOTAutograd tracing - #186442

Closed
aditvenk wants to merge 7 commits into
mainfrom
fix-nested-act-dtensor-subclass-codegen
Closed

aditvenk wants to merge 7 commits into
mainfrom
fix-nested-act-dtensor-subclass-codegen

Conversation

@aditvenk

@aditvenk aditvenk commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

AOTAutograd previously handled AsyncCollectiveTensor inputs only when the ACT was itself a top-level input. Nested ACTs, such as a DTensor whose _local_tensor is an ACT from async redistribution or FSDP2 async all-gather, could survive into traced subclass metadata. That created two related problems: forward execution under Inductor could use in-flight data if the ACT was not waited before the compiled graph consumed it, and backward metadata could record an ACT tangent expectation even though autograd later supplies a plain local tensor cotangent.

Fix this by making process_inputs recursively resolve ACTs through traceable wrapper subclass attributes. It records each ACT location as an input index plus attribute path, waits at trace time before fakification, and stores those paths on ViewAndMutationMeta.

At runtime, the generated subclass wrapper now threads those recorded ACT paths into the existing input unwrapping codegen. Top-level ACT paths emit a guarded wait around the plain input, and nested ACT paths emit the guarded wait at the exact subclass leaf that is appended to the compiled graph's flat inputs. This avoids rebuilding wrapper subclasses at runtime and still tolerates direct AOTAutograd entry points where a path that was ACT during tracing is later a plain tensor.

Because ACT paths affect the generated runtime wrapper, include them in the AOTAutograd cache key. This specializes cached entries by the ACT path set rather than patching loaded metadata after cache lookup.

When nested ACT resolution rebuilds a wrapper input during tracing, preserve Dynamo's symbolic context on the replacement. Without that, fakeification can allocate source-less shape symbols and Inductor can fail while emitting shape guards for the compiled graph.

Fixes #180614

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

@aditvenk
aditvenk requested review from aorenste and bdhirsh as code owners June 6, 2026 02:17
@pytorch-bot

pytorch-bot Bot commented Jun 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (4 Unrelated Failures)

As of commit f6587ef with merge base 757703a (image):

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

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/dtensor Run DTensor specific tests ciflow/inductor labels Jun 6, 2026
@aditvenk

aditvenk commented Jun 6, 2026

Copy link
Copy Markdown
Contributor Author

Before (buggy):

    _inner_2 = _inp_0._local_tensor
    unwrapped_args.append(_inner_2.elem)

After (fixed):

    _inner_2 = _inp_0._local_tensor
    _resolved_4 = _inner_2.trigger_wait() if type(_inner_2) is _act_type_3 else _inner_2
    unwrapped_args.append(_resolved_4)
   ```

@aditvenk

aditvenk commented Jun 6, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Jun 6, 2026
@aditvenk

aditvenk commented Jun 6, 2026

Copy link
Copy Markdown
Contributor Author

Verified this fixes the crash seen with Inductor in pytorch/torchtitan#3497

@aditvenk
aditvenk requested a review from xmfan June 6, 2026 02:18
@aditvenk

aditvenk commented Jun 6, 2026

Copy link
Copy Markdown
Contributor Author

@claude Review

@claude

claude Bot commented Jun 6, 2026 •

Copy link
Copy Markdown

Claude finished @aditvenk's task in 2m 10s —— View job


PR Review: Wait nested AsyncCollectiveTensor in DTensor under subclass codegen

  • Gather context and understand the PR
  • Review implementation changes
  • Review test changes
  • Post final review

Overall: This is a well-reasoned fix for a real correctness/crash bug. The approach is sound -- handling ACT as a special case in the recursive unwrap codegen is the right call since ACT is a transient wrapper that may or may not be present at runtime.

Implementation (subclass_codegen.py)

Strengths:

  • The type(x) is ACT else x runtime guard correctly handles both the ACT-present and already-plain cases
  • The assertion at lines 142-148 is a good defensive check that ACT's layout hasn't changed
  • Factoring _emit_subclass_symints into a shared helper keeps the two branches DRY
  • Using trigger_wait() rather than raw .elem access both waits the collective and returns the inner tensor in one operation

Minor observations:

  1. Comment length (lines 129-141): The 13-line block comment explaining the ACT handling is thorough but long relative to the codebase style. It serves as important documentation for a subtle interaction, so I understand the motivation -- just noting it's well above the "default to no comments" bar in CLAUDE.md. The key insight (ACT may or may not exist at runtime) could arguably fit in 3-4 lines. That said, this is complex enough that erring on the side of documentation seems reasonable here.

  2. _is_async_collective_tensor_type lazy import: The try/except Exception at line 72 is broad -- it will swallow import errors unrelated to the module being unavailable (e.g., a syntax error in a transitive import). Consider narrowing to except (ImportError, ModuleNotFoundError) to surface real breakage earlier. Though since this pattern is common in the distributed codebase, it's not a blocker.

  3. Symint extraction on resolved (line 159): This extracts size/stride symints from _resolved (the plain inner tensor). This is correct because ACT's __new__ uses elem.size() / elem.stride() for its wrapper metadata, so the outer shape matches the inner tensor exactly. Worth confirming this invariant holds if ACT is ever subclassed (unlikely but possible).

Tests (test_dtensor_compile.py)

Strengths:

  • Two separate tests covering both failure modes (missing wait + crash) is excellent
  • test_compile_waits_act_nested_in_dtensor_local_tensor: The warm-up + clear pattern isolates the compiled runtime path
  • test_compile_dtensor_local_tensor_act_to_plain_no_crash: Correctly traces with ACT then runs with plain tensor

Question:

  1. Test patching (line 289): The test patches funcol.wait_tensor, and trigger_wait() calls wait_tensor(self.elem) as a module-level function. This works because trigger_wait references wait_tensor from the same module (torch.distributed._functional_collectives), so patch.object(funcol, "wait_tensor", ...) correctly intercepts it. However, in the compiled codegen path, trigger_wait is called as a method on the ACT object -- does the inductor compilation inline/optimize this in a way that could bypass the patch? If so, the test might pass spuriously. Worth a sanity check, but likely fine since this is testing the subclass-unwrap wrapper (not an inductor-compiled kernel body).

  2. Test isolation: The second test (test_compile_dtensor_local_tensor_act_to_plain_no_crash) relies on dynamo reusing the ACT-specialized graph for a plain-tensor input. This is the correct real-world scenario, but it's sensitive to guard specialization changes. If dynamo ever adds a guard on the nested subclass type, this test would stop exercising the fix. A unit test that directly calls _codegen_subclass_wrapper_source with an ACT meta and verifies the generated source string would be more robust as a supplement (not a replacement).

Summary

The fix is correct and well-motivated. The code quality is good. No blockers -- the observations above are all minor/advisory.


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

[blocker] This is a forward-only fix and shouldn't land as the nested-ACT fix without completing the backward side. Top-level ACTs are resolved in process_inputs at trace time (so they never enter the traced metadata); this PR instead keeps the nested ACT in the metadata and handles it only in the unwrap codegen. That divergence leaves a backward correctness gap.

Backward/tangent gap: the top-level scan in process_inputs is non-recursive, so a nested ACT survives into the traced metadata -- including the tangent metadata derived from forward outputs. A grad-requiring DTensor(_local_tensor=ACT) that reaches a forward output via passthrough / view-only ops (ACT unwraps on non-view compute, so only those preserve it) records _local_tensor: AsyncCollectiveTensor in the tangent meta; at backward, autograd supplies a plain-local cotangent and process_runtime_tangent raises Expected a AsyncCollectiveTensor tangent but got a plain Tensor -- the same mismatch the top-level unwrap exists to prevent, one level down. (Static analysis, not reproduced; the new tests are forward-only so it is uncovered.)

The fix -- generalize the top-level mechanism to ACT paths. Make process_inputs recurse, resolve nested ACTs at trace time (record (input_index, attr_path) instead of flat indices) and re-wait per-path at runtime. That gives one mechanism for top-level and nested, fixes forward and backward together, and removes the divergence. It supersedes this PR's unwrap-codegen ACT branch: once the ACT is gone from the metadata, that branch is dead code. The forward crash (torchtitan #3497) is real, but the path-based fix covers it too -- so landing the codegen version first just means redoing and reverting it.

It also subsumes the top-level act_input_indices wait in _codegen_subclass_wrapper_source, which today is unconditional (args[i] = args[i].trigger_wait()) and so crashes under non-strict tracing / direct aot_* entry points when the runtime arg has already collapsed to a plain tensor (same 'Tensor' object has no attribute 'trigger_wait' -- there's no dynamo type-guard there). The path-based re-wait would carry the type and guard uniformly.

@aditvenk
aditvenk force-pushed the fix-nested-act-dtensor-subclass-codegen branch from 1e69f01 to e47c6c4 Compare June 9, 2026 01:16
@aditvenk
aditvenk requested review from Chillee and ezyang as code owners June 9, 2026 01:16
@aditvenk aditvenk changed the title Wait nested AsyncCollectiveTensor in DTensor under subclass codegen Resolve nested ACT inputs before AOTAutograd tracing Jun 9, 2026
@aditvenk
aditvenk requested review from Skylion007 and aorenste June 9, 2026 01:25
@ezyang
ezyang removed their request for review June 9, 2026 02:12
@aditvenk

aditvenk commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

@claude Check failing tests in latest CI run

@claude

claude Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

Claude finished @aditvenk's task in 1m 47s —— View job


Checking Failing Tests in Latest CI Run

  • Get CI status for the latest commit
  • Analyze failing tests
  • Report findings

Summary

There is 1 failing test in the latest CI run, and it is a pre-existing trunk failure (not introduced by this PR).

Failed job: inductor / unit-test / inductor-cpu-test / test-osdc (inductor_amx, 2, 2, mt-l-x86iamx-8-64)

Failed test: test_modules.py::TestModuleCPU::test_to_nn_LinearCrossEntropyLoss_swap_True_set_grad_False_cpu_float32

Error:

RuntimeError: Expected use_count of t1 to be 1 or 2 with an AccumulateGrad node
but got 3 make sure you are not holding references to the tensor in other places.

RuntimeError: _apply(): Couldn't swap Linear.weight

The test fails when calling m.to(dtype=torch.half) on a LinearCrossEntropyLoss module with swap_module_params_on_conversion enabled. The tensor swap fails because there are extra references being held to Linear.weight.

Verdict: Unrelated to this PR

The pytorch-bot already flagged this as BROKEN TRUNK -- this same test also fails on the merge base commit (fa4b665). This is a pre-existing issue in nn.LinearCrossEntropyLoss tensor swapping behavior under Inductor, completely unrelated to the nested ACT/DTensor subclass codegen changes in this PR.

No action needed from this PR. Rebasing onto viable/strict would avoid this failure if a green CI signal is needed.


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

[blocker] This is close but needs a little change: I think this is doing too much work at runtime instead of unwrapping the subclasses directly into waits.

(Claude Review) [cleanup] Follow-up test gap (not blocking). The runtime wait for act_input_paths on a warm AOTAutograd cache hit depends on the field surviving the ViewAndMutationMeta pickle round-trip. That holds today (the whole GenericAOTAutogradResult, metadata included, is pickled wholesale), and test_different_act_input_paths covers the cache key. What is untested is the hit path: compile with an ACT input -> populate the cache -> drop the in-memory compiled fn -> recompile into a cache hit -> assert the wrapper still emits trigger_wait(). If metadata serialization is ever narrowed to a field subset (as some other inductor caches do), this field would be silently dropped and the in-flight-read bug this PR fixes would regress on warm caches with nothing catching it. A small warm-cache regression test would lock the contract.

@aditvenk

Copy link
Copy Markdown
Contributor Author

@aorenste thanks for your feedback. I have changed to avoiding unwrapping at runtime. PTAL again. Thanks

@aditvenk
aditvenk requested a review from aorenste June 10, 2026 05:15
Comment thread test/dynamo/test_aot_autograd_cache.py Resolved
@aditvenk

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@aditvenk

Copy link
Copy Markdown
Contributor Author

@claude review failures in latest CI run whether they are caused by this PR

@claude

claude Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Claude finished @aditvenk's task in 3m 35s —— View job


CI failure review — all 4 failures are caused by this PR

  • Get CI status for latest commit (c35db20)
  • Analyze the failing test jobs
  • Determine if failures are caused by this PR
  • Report findings

The only failing workflow on the latest commit is trunk (the inductor failure is the pre-existing broken-trunk LinearCrossEntropyLoss test, unrelated — same as before). The 4 new failures are all in tests introduced by this PR, and all are real:


1 & 2. test_compile_dtensor_local_tensor_act_backward_passthrough (CUDA 13.0 + ROCm mi355)

Fails in the TestDTensorCompileWithCompiledAutograd variant — the base dtensor job is green, but test/inductor/test_compiled_autograd.py auto-wraps every test in TestDTensorCompile via wrap_test_class and re-runs it under compiled autograd. The backward you added (out.to_local().sum().backward() at test_dtensor_compile.py:363) graph-breaks under compiled-autograd tracing:

torch._dynamo.exc.Unsupported: Attempted to call function marked as skipped
  ... torch._C._DTensor_compute_global_tensor_info
  File ".../torch/distributed/tensor/_api.py", line 124, in backward
    _, tensor_stride = compute_global_tensor_info(...)

This is the only new test in the class that runs a real .backward(), so it's the only one that hits compiled-autograd's DTensor-backward graph break. The other DTensor tests don't trigger it. This is a genuine PR-caused failure — the new test isn't compatible with the compiled-autograd variant. Fix options: add it to skipped_tests/xfail_by_backend in test_compiled_autograd.py, or gate the test so the compiled-autograd wrapper skips it.

3 & 4. test_act_input_paths_cache_hit + test_act_wait_nested_codegen (macOS arm64)

Both fail because macOS CI builds PyTorch without distributed, so the ACT type can't be imported:

# test_act_input_paths_cache_hit (test_aot_autograd_cache.py:516)
import torch.distributed._functional_collectives as funcol
  ...
ModuleNotFoundError: No module named 'torch._C._distributed_c10d'; 'torch._C' is not a package

# test_act_wait_nested_codegen (subclass_codegen.py:325, via test_subclass_codegen.py:185)
AssertionError: ACT input paths require the ACT type to be loaded

The codegen-only test fails on the get_loaded_async_collective_tensor_type() is None assertion you added at subclass_codegen.py:325 — on macOS the module is never loaded, so the assert trips. Both are genuine PR-caused failures from missing skip guards. Fix: guard both tests so they skip when distributed isn't available, e.g.

from torch.testing._internal.common_distributed import requires_distributed
# or
@unittest.skipIf(not torch.distributed.is_available(), "requires distributed build")

For test_act_wait_nested_codegen, since it only needs the ACT type loaded, importing torch.distributed._functional_collectives in the test (guarded/skipped if unavailable) before calling _codegen_subclass_wrapper_source would both satisfy the assert and document the precondition.


Verdict

Failure Caused by this PR?
test_compile_dtensor_local_tensor_act_backward_passthrough (CUDA, ROCm) Yes — new test incompatible with the compiled-autograd test wrapper
test_act_input_paths_cache_hit (macOS) Yes — missing distributed-build skip guard
test_act_wait_nested_codegen (macOS) Yes — missing distributed-build skip guard / ACT type not loaded
LinearCrossEntropyLoss (inductor-cpu) No — pre-existing broken trunk

None of these are flaky or infra-related; all three new-test failures need code changes before merge. The merge attempt failed specifically on #1.

Fix these →

@aditvenk
aditvenk force-pushed the fix-nested-act-dtensor-subclass-codegen branch from c35db20 to 92fb510 Compare June 12, 2026 17:32
@aditvenk

Copy link
Copy Markdown
Contributor Author

@claude can you rebase on top of main fixing merge conflicts reported?

@claude

claude Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Claude finished @aditvenk's task in 2m 21s —— View job


Rebase onto main — blocked by environment permissions

I'm unable to perform the rebase from here. Every git operation a rebase needs is denied in this CI environment, and the checkout is a shallow clone, which compounds the problem:

  • git fetch --deepen (needed because this is a shallow clone — git merge-base origin/main HEAD fails, so there's no common ancestor to rebase against until history is deepened) → denied
  • git rebase origin/main → denied
  • git merge-tree / git merge-base (read-only conflict preview) → denied

Because branch operations like rebasing aren't something I'm permitted to do in this context (and the shallow checkout blocks even a local conflict preview), you'll need to run the rebase locally. See the FAQ for more on this limitation.

What I can tell you about the likely conflicts

The current origin/main tip is 8bc0aa7 "Fix AOTAutograd wrapper subclass metadata mutation (#186515)", which touches the same AOTAutograd subsystem this PR modifies. Expect conflicts concentrated in:

  • torch/_functorch/_aot_autograd/subclass_codegen.py
  • torch/_functorch/_aot_autograd/schemas.py (ViewAndMutationMeta)
  • torch/_functorch/_aot_autograd/runtime_wrappers.py
  • possibly frontend_utils.py / autograd_cache.py

Suggested local commands

git fetch origin main
git checkout fix-nested-act-dtensor-subclass-codegen
git rebase origin/main
# resolve conflicts, then:
git rebase --continue
git push --force-with-lease origin fix-nested-act-dtensor-subclass-codegen

If you'd like, re-run @claude once the clone is non-shallow / git operations are permitted in this workflow (adjust --allowedTools to include the git fetch/rebase commands), and I'll carry out the rebase and conflict resolution directly.

aditvenk added 7 commits June 14, 2026 20:44
AOTAutograd previously handled AsyncCollectiveTensor inputs only when the ACT
was itself a top-level input. Nested ACTs, such as a DTensor whose
_local_tensor is an ACT from async redistribution or FSDP2 async all-gather,
could survive into traced subclass metadata. That created two related problems.
Forward execution under Inductor could use in-flight data if the ACT was not
waited before the compiled graph consumed it, and backward metadata could
record an ACT tangent expectation even though autograd later supplies a plain
local tensor cotangent.

Fix this by making process_inputs recursively resolve ACTs through traceable
wrapper subclass attributes. It records each ACT location as an input index plus
attribute path, waits at trace time before fakification, and stores those paths
on ViewAndMutationMeta. The generated subclass wrapper then follows the same
paths at runtime and waits only if the runtime leaf is still an ACT, so direct
AOTAutograd entry points also tolerate a later plain tensor at a path that was
ACT during tracing.

Because the ACT paths affect the runtime wrapper, include them in the
AOTAutograd cache key. This specializes cached entries by the ACT path set
rather than patching loaded metadata after cache lookup; keeping the paths in
the key makes the wrapper contract explicit and avoids reusing a compiled
wrapper with stale ACT path assumptions.

When nested ACT resolution rebuilds a wrapper input, preserve Dynamo's symbolic
context on the replacement. Without that, fakeification can allocate
source-less shape symbols and Inductor can fail while emitting shape guards for
the compiled graph.

Fixes #180614

Test Plan:

```bash
python test/distributed/tensor/test_dtensor_compile.py TestDTensorCompile.test_compile_waits_act_nested_in_dtensor_local_tensor TestDTensorCompile.test_direct_aot_dtensor_local_tensor_act_to_plain_no_crash TestDTensorCompile.test_compile_dtensor_local_tensor_act_backward_passthrough
python test/distributed/test_c10d_functional_native.py ACTCompileTest.test_direct_aot_top_level_act_path_accepts_plain_runtime_input
python test/dynamo/test_aot_autograd_cache.py AOTAutogradCachePicklerTests.test_different_act_input_paths
git diff --check
python -m py_compile torch/_functorch/_aot_autograd/frontend_utils.py torch/_functorch/_aot_autograd/subclass_codegen.py torch/_functorch/aot_autograd.py test/distributed/tensor/test_dtensor_compile.py test/distributed/test_c10d_functional_native.py test/dynamo/test_aot_autograd_cache.py
lintrunner -a -m origin/main
lintrunner -a
```

Authored with assistance from an AI assistant.
Strengthen the nested ACT DTensor regression tests by asserting that the
measured second invocation reuses the graph compiled from the ACT input. Without
that precondition, a future guard change could recompile on the second call and
make the tests pass through retracing instead of exercising the runtime ACT path.

The torch.compile test now uses CompileCounterWithBackend("inductor") and the
direct AOTAutograd test counts fw_compiler invocations, matching the two
different compilation paths under test.

Test Plan:

```bash
python test/distributed/tensor/test_dtensor_compile.py TestDTensorCompile.test_compile_waits_act_nested_in_dtensor_local_tensor TestDTensorCompile.test_direct_aot_dtensor_local_tensor_act_to_plain_no_crash TestDTensorCompile.test_compile_dtensor_local_tensor_act_backward_passthrough
python -m py_compile test/distributed/tensor/test_dtensor_compile.py
git diff --check
lintrunner -a -m origin/main
lintrunner -a
```

Authored with assistance from an AI assistant.
The previous path-based runtime wait followed ACT paths before input unwrapping
and rebuilt wrapper subclasses with waited leaves. That worked but did too much
runtime work: a wrapper could be reconstructed once per ACT path, and the wait
logic lived beside rather than inside the existing subclass unwrap codegen.

Instead, group ACT paths at codegen time and thread the relevant path set through
the input unwrapping emitter. Top-level ACT paths now emit a guarded wait around
the plain input, and nested ACT paths emit the guarded wait at the exact subclass
leaf that is appended to the flat compiled-graph inputs. This preserves the
plain-runtime fallback while avoiding runtime wrapper reconstruction.

The follow-up tests split the contracts: subclass codegen tests assert the
generated top-level and nested ACT wait source, while the AOTAutograd cache test
only verifies that an ACT-path compile produces a cache miss followed by a hit.

Test Plan:

```bash
python test/functorch/test_subclass_codegen.py
```

```bash
python test/dynamo/test_aot_autograd_cache.py AOTAutogradCacheTests.test_act_input_paths_cache_hit AOTAutogradCachePicklerTests.test_different_act_input_paths
```

```bash
python test/distributed/tensor/test_dtensor_compile.py TestDTensorCompile.test_compile_waits_act_nested_in_dtensor_local_tensor TestDTensorCompile.test_direct_aot_dtensor_local_tensor_act_to_plain_no_crash TestDTensorCompile.test_compile_dtensor_local_tensor_act_backward_passthrough
```

```bash
python test/distributed/test_c10d_functional_native.py ACTCompileTest.test_direct_aot_top_level_act_path_accepts_plain_runtime_input
```

```bash
python -m py_compile test/functorch/test_subclass_codegen.py test/dynamo/test_aot_autograd_cache.py torch/_functorch/_aot_autograd/frontend_utils.py torch/_functorch/_aot_autograd/subclass_codegen.py
```

```bash
git diff --check
```

```bash
lintrunner -a -m origin/main
lintrunner -a
```

Authored with assistance from an AI assistant.
The ACT input path type appears across the tracing, cache, metadata, and
subclass codegen layers. Add shared aliases in the AOTAutograd schemas module
and use them at API boundaries and mutable metadata fields so the path contract
is named consistently instead of repeating the nested tuple annotation.

Also share the lazy ACT type lookup used by tracing and subclass codegen. The
helper only imports AsyncCollectiveTensor if distributed functional collectives
are already loaded, avoiding an eager distributed import from unrelated AOT
Autograd paths. While updating the tracing-side use, hoist the Dynamo tracing
context lookup out of the ACT input scan loop.

Test Plan:

```bash
python -m py_compile torch/_functorch/_aot_autograd/schemas.py torch/_functorch/_aot_autograd/frontend_utils.py torch/_functorch/_aot_autograd/subclass_codegen.py torch/_functorch/_aot_autograd/autograd_cache.py torch/_functorch/aot_autograd.py
```

```bash
python -m py_compile torch/_functorch/_aot_autograd/utils.py torch/_functorch/_aot_autograd/frontend_utils.py torch/_functorch/_aot_autograd/subclass_codegen.py
```

```bash
python test/functorch/test_subclass_codegen.py
```

```bash
python test/dynamo/test_aot_autograd_cache.py AOTAutogradCacheTests.test_act_input_paths_cache_hit AOTAutogradCachePicklerTests.test_different_act_input_paths
```

```bash
python test/distributed/test_c10d_functional_native.py ACTCompileTest.test_direct_aot_top_level_act_path_accepts_plain_runtime_input
```

```bash
python test/distributed/tensor/test_dtensor_compile.py TestDTensorCompile.test_compile_waits_act_nested_in_dtensor_local_tensor TestDTensorCompile.test_compile_dtensor_local_tensor_act_backward_passthrough
```

```bash
lintrunner -a -m origin/main
lintrunner -a
```

Authored with assistance from an AI assistant.
The generated ACT wait helper previously resolved AsyncCollectiveTensor from
sys.modules on each runtime invocation and used an exact type check. Trace-time
ACT path recording uses isinstance, so pass the already-loaded ACT type into the
generated helper and use the same isinstance check at runtime. This avoids
repeating module lookup on the hot path and keeps trace-time and runtime ACT
detection aligned.

The warm AOTAutograd cache test now verifies that the cache-hit wrapper actually
waits the runtime ACT input. Result equality alone is not enough because
wait_tensor on the test tensor is an identity; the test now patches wait_tensor
and checks the ACT completed flag on the warm cache-hit call.

Test Plan:

```bash
python test/dynamo/test_aot_autograd_cache.py AOTAutogradCacheTests.test_act_input_paths_cache_hit AOTAutogradCachePicklerTests.test_different_act_input_paths
```

```bash
python test/functorch/test_subclass_codegen.py
```

```bash
python -m py_compile test/dynamo/test_aot_autograd_cache.py torch/_functorch/_aot_autograd/subclass_codegen.py
```

```bash
git diff --check
```

```bash
lintrunner -a -m origin/main
```

```bash
lintrunner -a
```

Authored with assistance from an AI assistant.
The nested ACT regression tests added by this stack exposed two test-environment
assumptions. The cache and source-codegen tests require distributed because they
need the AsyncCollectiveTensor type, while macOS CI can build without
distributed. Guard those tests so they skip cleanly in non-distributed builds.

The new DTensor backward passthrough test is valid for the normal AOTAutograd
path, but compiled-autograd's auto-generated DTensor suite currently graph
breaks in DTensor backward while calling the global-shape helper. Skip this
single test in the compiled-autograd wrapper until that DTensor backward path is
supported there.

Finally, let subclass codegen import the ACT type when ACT input paths are
present. The broad input-processing path still uses the no-side-effect helper,
so ordinary AOTAutograd compilations do not import distributed just to check for
ACTs.

Test Plan:

```bash
python test/functorch/test_subclass_codegen.py TestSubclassCodegen.test_act_wait_top_level_codegen TestSubclassCodegen.test_act_wait_nested_codegen
```

```bash
python test/dynamo/test_aot_autograd_cache.py AOTAutogradCacheTests.test_act_input_paths_cache_hit AOTAutogradCachePicklerTests.test_different_act_input_paths
```

```bash
python test/inductor/test_compiled_autograd.py TestDTensorCompileWithCompiledAutograd.test_compile_dtensor_local_tensor_act_backward_passthrough
```

```bash
python -m py_compile torch/_functorch/_aot_autograd/utils.py torch/_functorch/_aot_autograd/subclass_codegen.py test/functorch/test_subclass_codegen.py test/dynamo/test_aot_autograd_cache.py test/inductor/test_compiled_autograd.py
```

```bash
git diff --check
```

```bash
lintrunner -a -m origin/main
lintrunner -a
```

Authored with assistance from an AI assistant.
After rebasing onto main, subclass wrapper codegen emits the output index bookkeeping for these ACT wait wrappers even though their output metadata is plain. The tests still cover the same ACT wait insertion points, but their inline expected sources need to reflect the current generated wrapper shape.

Test Plan:

```bash
python test/distributed/tensor/test_dtensor_compile.py TestDTensorCompile.test_compile_waits_act_nested_in_dtensor_local_tensor TestDTensorCompile.test_direct_aot_dtensor_local_tensor_act_to_plain_no_crash TestDTensorCompile.test_compile_dtensor_local_tensor_act_backward_passthrough
```

```bash
python test/distributed/test_c10d_functional_native.py ACTCompileTest.test_direct_aot_top_level_act_path_accepts_plain_runtime_input
```

```bash
python test/dynamo/test_aot_autograd_cache.py AOTAutogradCacheTests.test_act_input_paths_cache_hit AOTAutogradCachePicklerTests.test_different_act_input_paths
```

```bash
python test/functorch/test_subclass_codegen.py TestSubclassCodegen.test_act_wait_top_level_codegen TestSubclassCodegen.test_act_wait_nested_codegen
```

```bash
lintrunner -a
```

Authored with assistance from an AI assistant.
@aditvenk
aditvenk force-pushed the fix-nested-act-dtensor-subclass-codegen branch from 92fb510 to f6587ef Compare June 15, 2026 04:07
@aditvenk

Copy link
Copy Markdown
Contributor Author

@claude review failing tests in latest CI whether they are caused by this PR

@claude

claude Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Claude finished @aditvenk's task in 59s —— View job


CI failure review — all failures are unrelated to this PR

  • Get CI status for the latest commit (f6587ef)
  • Analyze failing jobs/tests
  • Determine whether failures are caused by this PR
  • Report findings

On the latest commit f6587ef, 8 of 10 workflows passed, including the ones that actually exercise this PR's new tests:

  • ✅ dtensor — runs test/distributed/tensor/test_dtensor_compile.py (the new nested-ACT forward/backward tests). Passed.
  • ✅ pull — runs test_aot_autograd_cache.py / test_subclass_codegen.py (the new cache-key and codegen tests, plus the macOS-skip guards added after the earlier failures). Passed.

The 2 failing workflows are inductor and trunk, and all 4 underlying failures are pre-existing flakes / broken-trunk, none of which touch the AOTAutograd / DTensor / subclass-codegen code this PR modifies:

Failure Workflow Caused by this PR?
mobilenetv2_100 (inductor_timm, shard 1/2) inductor No — flaky on trunk
tf_efficientnet_b0 (inductor_timm, shard 2/2) inductor No — flaky on trunk
shufflenet_v2_x1_0 (inductor_torchbench, shard 2/2) inductor No — flaky on trunk
pr_time_benchmarks MISSING REGRESSION TEST trunk No — broken trunk (present on merge base 757703a)

These are exactly the failures Dr. CI already classified in the PR status comment: the three inductor timm/torchbench model failures are FLAKY (matched against existing trunk flakes), and the pr_time_benchmarks failure is BROKEN TRUNK — it also fails on the merge base commit 757703a523f29b38beea5655fe7055b7ac477c42, so it is not introduced here.

Verdict

None of the current CI failures are caused by this PR. All are model-benchmark flakes or a pre-existing trunk regression-test failure, in code paths unrelated to nested-ACT resolution. Notably, the earlier real PR-caused failures (the compiled-autograd backward-passthrough test and the two macOS distributed-build skip-guard failures) are now resolved — the dtensor and pull workflows that run this PR's tests are green.

Dr. CI's banner reflects this: "You can merge normally! (4 Unrelated Failures)." Rebasing onto viable/strict would clear the broken-trunk pr_time_benchmarks signal if a fully green run is desired before merging.

@aditvenk

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

1 similar comment
@aditvenk

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@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

Can't merge closed PR #186442

gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
AOTAutograd previously handled AsyncCollectiveTensor inputs only when the ACT was itself a top-level input. Nested ACTs, such as a DTensor whose `_local_tensor` is an ACT from async redistribution or FSDP2 async all-gather, could survive into traced subclass metadata. That created two related problems: forward execution under Inductor could use in-flight data if the ACT was not waited before the compiled graph consumed it, and backward metadata could record an ACT tangent expectation even though autograd later supplies a plain local tensor cotangent.

Fix this by making `process_inputs` recursively resolve ACTs through traceable wrapper subclass attributes. It records each ACT location as an input index plus attribute path, waits at trace time before fakification, and stores those paths on `ViewAndMutationMeta`.

At runtime, the generated subclass wrapper now threads those recorded ACT paths into the existing input unwrapping codegen. Top-level ACT paths emit a guarded wait around the plain input, and nested ACT paths emit the guarded wait at the exact subclass leaf that is appended to the compiled graph's flat inputs. This avoids rebuilding wrapper subclasses at runtime and still tolerates direct AOTAutograd entry points where a path that was ACT during tracing is later a plain tensor.

Because ACT paths affect the generated runtime wrapper, include them in the AOTAutograd cache key. This specializes cached entries by the ACT path set rather than patching loaded metadata after cache lookup.

When nested ACT resolution rebuilds a wrapper input during tracing, preserve Dynamo's symbolic context on the replacement. Without that, fakeification can allocate source-less shape symbols and Inductor can fail while emitting shape guards for the compiled graph.

Fixes pytorch#180614

Pull Request resolved: pytorch#186442
Approved by: https://github.com/aorenste
@github-actions
github-actions Bot deleted the fix-nested-act-dtensor-subclass-codegen branch July 16, 2026 02:25
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
AOTAutograd previously handled AsyncCollectiveTensor inputs only when the ACT was itself a top-level input. Nested ACTs, such as a DTensor whose `_local_tensor` is an ACT from async redistribution or FSDP2 async all-gather, could survive into traced subclass metadata. That created two related problems: forward execution under Inductor could use in-flight data if the ACT was not waited before the compiled graph consumed it, and backward metadata could record an ACT tangent expectation even though autograd later supplies a plain local tensor cotangent.

Fix this by making `process_inputs` recursively resolve ACTs through traceable wrapper subclass attributes. It records each ACT location as an input index plus attribute path, waits at trace time before fakification, and stores those paths on `ViewAndMutationMeta`.

At runtime, the generated subclass wrapper now threads those recorded ACT paths into the existing input unwrapping codegen. Top-level ACT paths emit a guarded wait around the plain input, and nested ACT paths emit the guarded wait at the exact subclass leaf that is appended to the compiled graph's flat inputs. This avoids rebuilding wrapper subclasses at runtime and still tolerates direct AOTAutograd entry points where a path that was ACT during tracing is later a plain tensor.

Because ACT paths affect the generated runtime wrapper, include them in the AOTAutograd cache key. This specializes cached entries by the ACT path set rather than patching loaded metadata after cache lookup.

When nested ACT resolution rebuilds a wrapper input during tracing, preserve Dynamo's symbolic context on the replacement. Without that, fakeification can allocate source-less shape symbols and Inductor can fail while emitting shape guards for the compiled graph.

Fixes pytorch#180614

Pull Request resolved: pytorch#186442
Approved by: https://github.com/aorenste
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/trunk Trigger trunk jobs on your pull request Merged module: dynamo module: inductor topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Inductor does not wait AsyncCollectiveTensor nested inside DTensor._local_tensor

4 participants