Skip to content

Unwrap AsyncCollectiveTensor inputs before AOT autograd tracing and at runtime - #179849

Closed
aorenste wants to merge 5 commits into
gh/aorenste/239/basefrom
gh/aorenste/239/head
Closed

aorenste wants to merge 5 commits into
gh/aorenste/239/basefrom
gh/aorenste/239/head

Conversation

@aorenste

@aorenste aorenste commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

When tensor parallel (TP) async collectives overlap with torch.compile,
AsyncCollectiveTensor (ACT) wrappers can leak into compiled regions as
input types. This happens in MoE models where a PrepareModuleInputOutput
hook triggers an all-gather producing a DTensor(ACT), then eager code
calls to_local() yielding a bare ACT that flows into a compiled
sub-module.

This causes two problems:

Compile-time: AOT autograd fakifies the ACT and records it in
SubclassCreationMeta for output tangent metadata. At runtime, autograd
produces plain tensor tangents, causing:

RuntimeError: Expected a AsyncCollectiveTensor tangent but got a
plain Tensor

Runtime: ACT inputs to a compiled graph whose first usage is an inductor
triton kernel bypass torch_dispatch entirely, so trigger_wait()
never fires — resulting in silent data corruption.

Fix:

  1. Compile-time (process_inputs): resolve ACTs via trigger_wait() before
    entering FakeTensorMode, preventing ACT from being recorded in tangent
    metadata. Record which input indices held ACTs on
    ViewAndMutationMeta.act_input_indices.

  2. Runtime (subclass codegen): emit direct trigger_wait() calls for the
    recorded ACT input positions inside the existing codegen'd subclass
    wrapper (_codegen_subclass_wrapper_source). This avoids scanning every
    arg on every graph invocation — only known ACT positions are touched.

First observed in torchtitan's GPT-OSS MoE model with TP + EP + compile.

Fixes pytorch/torchtitan#2776

…t runtime

When tensor parallel (TP) async collectives overlap with torch.compile,
AsyncCollectiveTensor (ACT) wrappers can leak into compiled regions as
input types. This happens in MoE models where a PrepareModuleInputOutput
hook triggers an all-gather producing a DTensor(ACT), then eager code
calls to_local() yielding a bare ACT that flows into a compiled
sub-module.

This causes two problems:

Compile-time: AOT autograd fakifies the ACT and records it in
SubclassCreationMeta for output tangent metadata. At runtime, autograd
produces plain tensor tangents, causing:

  RuntimeError: Expected a AsyncCollectiveTensor tangent but got a
  plain Tensor

Runtime: ACT inputs to a compiled graph whose first usage is an inductor
triton kernel bypass __torch_dispatch__ entirely, so trigger_wait()
never fires — resulting in silent data corruption.

Fix:

1. Compile-time (process_inputs): resolve ACTs via trigger_wait() before
   entering FakeTensorMode, preventing ACT from being recorded in tangent
   metadata. Record which input indices held ACTs on
   ViewAndMutationMeta.act_input_indices.

2. Runtime (subclass codegen): emit direct trigger_wait() calls for the
   recorded ACT input positions inside the existing codegen'd subclass
   wrapper (_codegen_subclass_wrapper_source). This avoids scanning every
   arg on every graph invocation — only known ACT positions are touched.

First observed in torchtitan's GPT-OSS MoE model with TP + EP + compile.

Fixes pytorch/torchtitan#2776

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Apr 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ No Failures

As of commit ee774f4 with merge base cd540ad (image):
💚 Looks good so far! There are no failures yet. 💚

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 release notes: distributed (c10d) release notes category labels Apr 9, 2026
aorenste added a commit that referenced this pull request Apr 9, 2026
…t runtime

When tensor parallel (TP) async collectives overlap with torch.compile,
AsyncCollectiveTensor (ACT) wrappers can leak into compiled regions as
input types. This happens in MoE models where a PrepareModuleInputOutput
hook triggers an all-gather producing a DTensor(ACT), then eager code
calls to_local() yielding a bare ACT that flows into a compiled
sub-module.

This causes two problems:

Compile-time: AOT autograd fakifies the ACT and records it in
SubclassCreationMeta for output tangent metadata. At runtime, autograd
produces plain tensor tangents, causing:

  RuntimeError: Expected a AsyncCollectiveTensor tangent but got a
  plain Tensor

Runtime: ACT inputs to a compiled graph whose first usage is an inductor
triton kernel bypass __torch_dispatch__ entirely, so trigger_wait()
never fires — resulting in silent data corruption.

Fix:

1. Compile-time (process_inputs): resolve ACTs via trigger_wait() before
   entering FakeTensorMode, preventing ACT from being recorded in tangent
   metadata. Record which input indices held ACTs on
   ViewAndMutationMeta.act_input_indices.

2. Runtime (subclass codegen): emit direct trigger_wait() calls for the
   recorded ACT input positions inside the existing codegen'd subclass
   wrapper (_codegen_subclass_wrapper_source). This avoids scanning every
   arg on every graph invocation — only known ACT positions are touched.

First observed in torchtitan's GPT-OSS MoE model with TP + EP + compile.

Fixes pytorch/torchtitan#2776

ghstack-source-id: 6536b62
Pull Request resolved: #179849
fake_mode,
shape_env,
)
aot_state.fw_metadata.act_input_indices = act_input_indices

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.

@claude where is aot_state.fw_metadata.act_input_indices used?

@aditvenk

aditvenk commented Apr 9, 2026

Copy link
Copy Markdown
Contributor

@aorenste -- can confirm this fixes gpt-oss problem in Titan

@aditvenk

aditvenk commented Apr 9, 2026

Copy link
Copy Markdown
Contributor

@claude where is aot_state.fw_metadata.act_input_indices used?

@claude

claude Bot commented Apr 9, 2026 •

Copy link
Copy Markdown

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


  • Find definition of act_input_indices
  • Trace where it's populated
  • Trace where it's consumed

Where act_input_indices is used

act_input_indices flows through the following path:

1. Defined on ViewAndMutationMeta as a dataclass field:

2. Populated in process_inputs():

3. Stored on aot_state.fw_metadata at these call sites in aot_autograd.py:

4. Consumed at runtime in the subclass wrapper codegen path:

  • runtime_wrappers.py:1015 — The guard if self.maybe_subclass_meta is None and not runtime_metadata.act_input_indices ensures codegen runs even when there are no subclass inputs but there are ACT inputs.
  • runtime_wrappers.py:1026 — Passed to codegen_subclass_wrapper(... act_input_indices=runtime_metadata.act_input_indices).
  • subclass_codegen.py:269-271 — The actual consumer: emits args[i] = args[i].trigger_wait() calls into the generated wrapper source for each recorded ACT index. This ensures that at runtime, the async collective is waited on before the compiled graph touches the data (since Inductor Triton kernels bypass __torch_dispatch__ and would otherwise skip trigger_wait()).

In short: act_input_indices is populated at compile time and consumed at runtime via codegen to emit targeted trigger_wait() calls only at the input positions that were originally AsyncCollectiveTensors.


…acing and at runtime"

When tensor parallel (TP) async collectives overlap with torch.compile,
AsyncCollectiveTensor (ACT) wrappers can leak into compiled regions as
input types. This happens in MoE models where a PrepareModuleInputOutput
hook triggers an all-gather producing a DTensor(ACT), then eager code
calls to_local() yielding a bare ACT that flows into a compiled
sub-module.

This causes two problems:

Compile-time: AOT autograd fakifies the ACT and records it in
SubclassCreationMeta for output tangent metadata. At runtime, autograd
produces plain tensor tangents, causing:

  RuntimeError: Expected a AsyncCollectiveTensor tangent but got a
  plain Tensor

Runtime: ACT inputs to a compiled graph whose first usage is an inductor
triton kernel bypass __torch_dispatch__ entirely, so trigger_wait()
never fires — resulting in silent data corruption.

Fix:

1. Compile-time (process_inputs): resolve ACTs via trigger_wait() before
   entering FakeTensorMode, preventing ACT from being recorded in tangent
   metadata. Record which input indices held ACTs on
   ViewAndMutationMeta.act_input_indices.

2. Runtime (subclass codegen): emit direct trigger_wait() calls for the
   recorded ACT input positions inside the existing codegen'd subclass
   wrapper (_codegen_subclass_wrapper_source). This avoids scanning every
   arg on every graph invocation — only known ACT positions are touched.

First observed in torchtitan's GPT-OSS MoE model with TP + EP + compile.

Fixes pytorch/torchtitan#2776

[ghstack-poisoned]
aorenste added a commit that referenced this pull request Apr 9, 2026
…t runtime

When tensor parallel (TP) async collectives overlap with torch.compile,
AsyncCollectiveTensor (ACT) wrappers can leak into compiled regions as
input types. This happens in MoE models where a PrepareModuleInputOutput
hook triggers an all-gather producing a DTensor(ACT), then eager code
calls to_local() yielding a bare ACT that flows into a compiled
sub-module.

This causes two problems:

Compile-time: AOT autograd fakifies the ACT and records it in
SubclassCreationMeta for output tangent metadata. At runtime, autograd
produces plain tensor tangents, causing:

  RuntimeError: Expected a AsyncCollectiveTensor tangent but got a
  plain Tensor

Runtime: ACT inputs to a compiled graph whose first usage is an inductor
triton kernel bypass __torch_dispatch__ entirely, so trigger_wait()
never fires — resulting in silent data corruption.

Fix:

1. Compile-time (process_inputs): resolve ACTs via trigger_wait() before
   entering FakeTensorMode, preventing ACT from being recorded in tangent
   metadata. Record which input indices held ACTs on
   ViewAndMutationMeta.act_input_indices.

2. Runtime (subclass codegen): emit direct trigger_wait() calls for the
   recorded ACT input positions inside the existing codegen'd subclass
   wrapper (_codegen_subclass_wrapper_source). This avoids scanning every
   arg on every graph invocation — only known ACT positions are touched.

First observed in torchtitan's GPT-OSS MoE model with TP + EP + compile.

Fixes pytorch/torchtitan#2776

ghstack-source-id: be09763
Pull Request resolved: #179849
@aorenste aorenste added ciflow/trunk Trigger trunk jobs on your pull request ci-no-td Do not run TD on this PR ciflow/torchtitan Run TorchTitan integration tests labels Apr 9, 2026
@aorenste
aorenste marked this pull request as ready for review April 9, 2026 22:36
@aorenste
aorenste requested a review from bdhirsh as a code owner April 9, 2026 22:36
…acing and at runtime"

When tensor parallel (TP) async collectives overlap with torch.compile,
AsyncCollectiveTensor (ACT) wrappers can leak into compiled regions as
input types. This happens in MoE models where a PrepareModuleInputOutput
hook triggers an all-gather producing a DTensor(ACT), then eager code
calls to_local() yielding a bare ACT that flows into a compiled
sub-module.

This causes two problems:

Compile-time: AOT autograd fakifies the ACT and records it in
SubclassCreationMeta for output tangent metadata. At runtime, autograd
produces plain tensor tangents, causing:

  RuntimeError: Expected a AsyncCollectiveTensor tangent but got a
  plain Tensor

Runtime: ACT inputs to a compiled graph whose first usage is an inductor
triton kernel bypass __torch_dispatch__ entirely, so trigger_wait()
never fires — resulting in silent data corruption.

Fix:

1. Compile-time (process_inputs): resolve ACTs via trigger_wait() before
   entering FakeTensorMode, preventing ACT from being recorded in tangent
   metadata. Record which input indices held ACTs on
   ViewAndMutationMeta.act_input_indices.

2. Runtime (subclass codegen): emit direct trigger_wait() calls for the
   recorded ACT input positions inside the existing codegen'd subclass
   wrapper (_codegen_subclass_wrapper_source). This avoids scanning every
   arg on every graph invocation — only known ACT positions are touched.

First observed in torchtitan's GPT-OSS MoE model with TP + EP + compile.

Fixes pytorch/torchtitan#2776

[ghstack-poisoned]
aorenste added a commit that referenced this pull request Apr 10, 2026
…t runtime

When tensor parallel (TP) async collectives overlap with torch.compile,
AsyncCollectiveTensor (ACT) wrappers can leak into compiled regions as
input types. This happens in MoE models where a PrepareModuleInputOutput
hook triggers an all-gather producing a DTensor(ACT), then eager code
calls to_local() yielding a bare ACT that flows into a compiled
sub-module.

This causes two problems:

Compile-time: AOT autograd fakifies the ACT and records it in
SubclassCreationMeta for output tangent metadata. At runtime, autograd
produces plain tensor tangents, causing:

  RuntimeError: Expected a AsyncCollectiveTensor tangent but got a
  plain Tensor

Runtime: ACT inputs to a compiled graph whose first usage is an inductor
triton kernel bypass __torch_dispatch__ entirely, so trigger_wait()
never fires — resulting in silent data corruption.

Fix:

1. Compile-time (process_inputs): resolve ACTs via trigger_wait() before
   entering FakeTensorMode, preventing ACT from being recorded in tangent
   metadata. Record which input indices held ACTs on
   ViewAndMutationMeta.act_input_indices.

2. Runtime (subclass codegen): emit direct trigger_wait() calls for the
   recorded ACT input positions inside the existing codegen'd subclass
   wrapper (_codegen_subclass_wrapper_source). This avoids scanning every
   arg on every graph invocation — only known ACT positions are touched.

First observed in torchtitan's GPT-OSS MoE model with TP + EP + compile.

Fixes pytorch/torchtitan#2776

ghstack-source-id: 730ab54
Pull Request resolved: #179849
…acing and at runtime"

When tensor parallel (TP) async collectives overlap with torch.compile,
AsyncCollectiveTensor (ACT) wrappers can leak into compiled regions as
input types. This happens in MoE models where a PrepareModuleInputOutput
hook triggers an all-gather producing a DTensor(ACT), then eager code
calls to_local() yielding a bare ACT that flows into a compiled
sub-module.

This causes two problems:

Compile-time: AOT autograd fakifies the ACT and records it in
SubclassCreationMeta for output tangent metadata. At runtime, autograd
produces plain tensor tangents, causing:

  RuntimeError: Expected a AsyncCollectiveTensor tangent but got a
  plain Tensor

Runtime: ACT inputs to a compiled graph whose first usage is an inductor
triton kernel bypass __torch_dispatch__ entirely, so trigger_wait()
never fires — resulting in silent data corruption.

Fix:

1. Compile-time (process_inputs): resolve ACTs via trigger_wait() before
   entering FakeTensorMode, preventing ACT from being recorded in tangent
   metadata. Record which input indices held ACTs on
   ViewAndMutationMeta.act_input_indices.

2. Runtime (subclass codegen): emit direct trigger_wait() calls for the
   recorded ACT input positions inside the existing codegen'd subclass
   wrapper (_codegen_subclass_wrapper_source). This avoids scanning every
   arg on every graph invocation — only known ACT positions are touched.

First observed in torchtitan's GPT-OSS MoE model with TP + EP + compile.

Fixes pytorch/torchtitan#2776

[ghstack-poisoned]
aorenste added a commit that referenced this pull request Apr 10, 2026
…t runtime

When tensor parallel (TP) async collectives overlap with torch.compile,
AsyncCollectiveTensor (ACT) wrappers can leak into compiled regions as
input types. This happens in MoE models where a PrepareModuleInputOutput
hook triggers an all-gather producing a DTensor(ACT), then eager code
calls to_local() yielding a bare ACT that flows into a compiled
sub-module.

This causes two problems:

Compile-time: AOT autograd fakifies the ACT and records it in
SubclassCreationMeta for output tangent metadata. At runtime, autograd
produces plain tensor tangents, causing:

  RuntimeError: Expected a AsyncCollectiveTensor tangent but got a
  plain Tensor

Runtime: ACT inputs to a compiled graph whose first usage is an inductor
triton kernel bypass __torch_dispatch__ entirely, so trigger_wait()
never fires — resulting in silent data corruption.

Fix:

1. Compile-time (process_inputs): resolve ACTs via trigger_wait() before
   entering FakeTensorMode, preventing ACT from being recorded in tangent
   metadata. Record which input indices held ACTs on
   ViewAndMutationMeta.act_input_indices.

2. Runtime (subclass codegen): emit direct trigger_wait() calls for the
   recorded ACT input positions inside the existing codegen'd subclass
   wrapper (_codegen_subclass_wrapper_source). This avoids scanning every
   arg on every graph invocation — only known ACT positions are touched.

First observed in torchtitan's GPT-OSS MoE model with TP + EP + compile.

Fixes pytorch/torchtitan#2776

ghstack-source-id: f1860f6
Pull Request resolved: #179849
@aorenste

Copy link
Copy Markdown
Contributor Author

The CI failure ([pull / linux-jammy-py3.10-clang18 / test (crossref, 1, 2, lf.linux.2xlarge)]) seems to be an existing trunk flaky
@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 27 checks: pull / linux-jammy-py3.14-clang18 / test (crossref, 2, 2, lf.linux.2xlarge), pull / linux-jammy-py3.14-clang18 / test (default, 1, 5, lf.linux.4xlarge), pull / linux-jammy-py3.14-clang18 / test (crossref, 1, 2, lf.linux.2xlarge), pull / linux-jammy-py3.14-clang18 / test (dynamo_wrapped, 1, 3, lf.linux.2xlarge), pull / linux-jammy-py3.14-clang18 / test (default, 2, 5, lf.linux.4xlarge), pull / linux-jammy-aarch64-py3.10 / test (default, 2, 5, lf.linux.arm64.m8g.4xlarge), pull / linux-jammy-py3.10-clang18-asan / test (default, 2, 7, lf.linux.4xlarge), pull / linux-jammy-py3.14t-clang18 / test (crossref, 2, 2, lf.linux.2xlarge), pull / linux-jammy-py3.14t-clang18 / test (default, 1, 5, lf.linux.4xlarge), pull / linux-jammy-py3.14t-clang18 / test (crossref, 1, 2, lf.linux.2xlarge), pull / linux-jammy-py3.14t-clang18 / test (dynamo_wrapped, 1, 3, lf.linux.2xlarge), pull / linux-jammy-py3.14t-clang18 / test (default, 2, 5, lf.linux.4xlarge), pull / linux-jammy-py3.10-clang18 / test (default, 2, 5, lf.linux.4xlarge), pull / linux-jammy-py3.10-clang18 / test (dynamo_wrapped, 1, 3, lf.linux.2xlarge), pull / linux-jammy-py3.10-clang18 / test (crossref, 2, 2, lf.linux.2xlarge), pull / linux-jammy-py3.10-clang18 / test (crossref, 1, 2, lf.linux.2xlarge), pull / linux-jammy-py3.10-clang18 / test (default, 1, 5, lf.linux.4xlarge), pull / linux-jammy-py3.10-gcc11 / test (default, 1, 5, lf.linux.4xlarge), pull / linux-jammy-py3.10-gcc11 / test (default, 2, 5, lf.linux.4xlarge), trunk / linux-jammy-rocm-py3.10-mi355 / test (default, 1, 6, linux.rocm.gpu.gfx950.1), trunk / linux-jammy-rocm-py3.10-mi355 / test (distributed, 3, 3, linux.rocm.gpu.gfx950.2), trunk / linux-jammy-rocm-py3.10-mi355 / test (default, 2, 6, linux.rocm.gpu.gfx950.1), trunk / linux-jammy-rocm-py3.10-mi355 / test (default, 5, 6, linux.rocm.gpu.gfx950.1), trunk / linux-jammy-rocm-py3.10-mi355 / test (default, 6, 6, linux.rocm.gpu.gfx950.1), trunk / linux-jammy-rocm-py3.10-mi355 / test (default, 4, 6, linux.rocm.gpu.gfx950.1), trunk / linux-jammy-rocm-py3.10-mi355 / test (default, 3, 6, linux.rocm.gpu.gfx950.1), trunk / linux-jammy-rocm-py3.10-mi355 / test (distributed, 1, 3, linux.rocm.gpu.gfx950.2)

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

@aorenste

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@aorenste aorenste removed ci-no-td Do not run TD on this PR ciflow/torchtitan Run TorchTitan integration tests ciflow/dtensor Run DTensor specific tests labels Apr 11, 2026
@aorenste

Copy link
Copy Markdown
Contributor Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased gh/aorenste/239/orig onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via ghstack checkout https://github.com/pytorch/pytorch/pull/179849)

pytorchmergebot pushed a commit that referenced this pull request Apr 11, 2026
…t runtime

When tensor parallel (TP) async collectives overlap with torch.compile,
AsyncCollectiveTensor (ACT) wrappers can leak into compiled regions as
input types. This happens in MoE models where a PrepareModuleInputOutput
hook triggers an all-gather producing a DTensor(ACT), then eager code
calls to_local() yielding a bare ACT that flows into a compiled
sub-module.

This causes two problems:

Compile-time: AOT autograd fakifies the ACT and records it in
SubclassCreationMeta for output tangent metadata. At runtime, autograd
produces plain tensor tangents, causing:

  RuntimeError: Expected a AsyncCollectiveTensor tangent but got a
  plain Tensor

Runtime: ACT inputs to a compiled graph whose first usage is an inductor
triton kernel bypass __torch_dispatch__ entirely, so trigger_wait()
never fires — resulting in silent data corruption.

Fix:

1. Compile-time (process_inputs): resolve ACTs via trigger_wait() before
   entering FakeTensorMode, preventing ACT from being recorded in tangent
   metadata. Record which input indices held ACTs on
   ViewAndMutationMeta.act_input_indices.

2. Runtime (subclass codegen): emit direct trigger_wait() calls for the
   recorded ACT input positions inside the existing codegen'd subclass
   wrapper (_codegen_subclass_wrapper_source). This avoids scanning every
   arg on every graph invocation — only known ACT positions are touched.

First observed in torchtitan's GPT-OSS MoE model with TP + EP + compile.

Fixes pytorch/torchtitan#2776

ghstack-source-id: e945919
Pull Request resolved: #179849
@pytorch-bot pytorch-bot Bot added ciflow/dtensor Run DTensor specific tests ciflow/inductor labels Apr 11, 2026
@aorenste

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

@github-actions
github-actions Bot deleted the gh/aorenste/239/head branch May 12, 2026 02:25
drizzlezyk pushed a commit to hicann/torchtitan-npu that referenced this pull request May 27, 2026
Co-authored-by: zhangwei1177<[email protected]>



# message auto-generated for no-merge-commit merge:
!251 merge fix_dsv4_tp_af into v0.2.2-dev

[fix] Fix DeepSeek V4 MTP TP compile wait path

Created-by: zhangwei1177
Commit-by: zhangwei1177
Merged-by: cann-robot
Description: ## 描述
本 PR 修复 DeepSeek-V4 在同时开启 TP、MTP 和 torch.compile 时 backward 报错的问题。报错现象是 AOTAutograd 期望 backward tangent 类型为 AsyncCollectiveTensor,但运行时实际收到的是普通 torch.Tensor,触发 expected/runtime type mismatch。
![image.png](https://raw.gitcode.com/user-images/assets/9028822/4335c1ee-03f9-4eeb-8ba4-1734b0dd3a2f/image.png 'image.png')

根因是 MTP 分支中 input_offset = self.tok_embeddings(token_offset) 的输出在 TP RowwiseParallel 下可能仍是 AsyncCollectiveTensor,随后会直接进入 compiled enorm。本 PR 改为在 MTP + compile 场景下让 tok_embeddings 使用 AwaitRowwiseParallel,对异步 collective 输出显式 wait(),使其进入 MTP module 前稳定为普通 Tensor,从源头避免 AOTAutograd 类型预测不一致。同时移除了原先的全局 functional collectives monkey patch,改为更局部的修复方式。

相关问题在pytorch修改:pytorch/pytorch#179849

## 类型
- [x] Bug 修复
- [ ] 新功能
- [ ] 重构(即不是新增功能,也不是修改bug的代码变动)
- [ ] 构建过程或辅助工具的变动
- [ ] 文档内容更新

## Checklist:
- [x] 我的代码遵循这个项目的代码风格
- [x] 我已经自己测试过我的代码
- [x] 我已经更新了相应的文档
- [x] 我已经在标题中正确使用了类型标签(例如:`feat`, `fix`, `refactor`, `docs`, `test`)

## 如何测试
同时开启tp+mtp+compile

## 其他信息
tp=1/mtp=1/开启compile 和 tp2/mtp=1/开启compile的图像比较:
![compare_tp1_tp2_4layers_mtp1.png](https://raw.gitcode.com/user-images/assets/9028822/48057ea3-3be4-4305-88a4-05f05bfac14a/compare_tp1_tp2_4layers_mtp1.png 'compare_tp1_tp2_4layers_mtp1.png')

See merge request: cann/torchtitan-npu!251
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…t runtime (pytorch#179849)

When tensor parallel (TP) async collectives overlap with torch.compile,
AsyncCollectiveTensor (ACT) wrappers can leak into compiled regions as
input types. This happens in MoE models where a PrepareModuleInputOutput
hook triggers an all-gather producing a DTensor(ACT), then eager code
calls to_local() yielding a bare ACT that flows into a compiled
sub-module.

This causes two problems:

Compile-time: AOT autograd fakifies the ACT and records it in
SubclassCreationMeta for output tangent metadata. At runtime, autograd
produces plain tensor tangents, causing:

  RuntimeError: Expected a AsyncCollectiveTensor tangent but got a
  plain Tensor

Runtime: ACT inputs to a compiled graph whose first usage is an inductor
triton kernel bypass __torch_dispatch__ entirely, so trigger_wait()
never fires — resulting in silent data corruption.

Fix:

1. Compile-time (process_inputs): resolve ACTs via trigger_wait() before
   entering FakeTensorMode, preventing ACT from being recorded in tangent
   metadata. Record which input indices held ACTs on
   ViewAndMutationMeta.act_input_indices.

2. Runtime (subclass codegen): emit direct trigger_wait() calls for the
   recorded ACT input positions inside the existing codegen'd subclass
   wrapper (_codegen_subclass_wrapper_source). This avoids scanning every
   arg on every graph invocation — only known ACT positions are touched.

First observed in torchtitan's GPT-OSS MoE model with TP + EP + compile.

Fixes pytorch/torchtitan#2776
Pull Request resolved: pytorch#179849
Approved by: https://github.com/aditvenk
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…t runtime (pytorch#179849)

When tensor parallel (TP) async collectives overlap with torch.compile,
AsyncCollectiveTensor (ACT) wrappers can leak into compiled regions as
input types. This happens in MoE models where a PrepareModuleInputOutput
hook triggers an all-gather producing a DTensor(ACT), then eager code
calls to_local() yielding a bare ACT that flows into a compiled
sub-module.

This causes two problems:

Compile-time: AOT autograd fakifies the ACT and records it in
SubclassCreationMeta for output tangent metadata. At runtime, autograd
produces plain tensor tangents, causing:

  RuntimeError: Expected a AsyncCollectiveTensor tangent but got a
  plain Tensor

Runtime: ACT inputs to a compiled graph whose first usage is an inductor
triton kernel bypass __torch_dispatch__ entirely, so trigger_wait()
never fires — resulting in silent data corruption.

Fix:

1. Compile-time (process_inputs): resolve ACTs via trigger_wait() before
   entering FakeTensorMode, preventing ACT from being recorded in tangent
   metadata. Record which input indices held ACTs on
   ViewAndMutationMeta.act_input_indices.

2. Runtime (subclass codegen): emit direct trigger_wait() calls for the
   recorded ACT input positions inside the existing codegen'd subclass
   wrapper (_codegen_subclass_wrapper_source). This avoids scanning every
   arg on every graph invocation — only known ACT positions are touched.

First observed in torchtitan's GPT-OSS MoE model with TP + EP + compile.

Fixes pytorch/torchtitan#2776
Pull Request resolved: pytorch#179849
Approved by: https://github.com/aditvenk
fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 9, 2026
…regions (#5886)

Stacked PRs:
 * #5904
 * #5895
 * #5894
 * #5893
 * #5892
 * #5891
 * #5890
 * #5889
 * #5888
 * #5887
 * #5885
 * __->__#5886


--- --- ---

### [distributed] Keep grads of async collective inputs to local_compile
regions


## Summary (human-written)
See the issue: pytorch/pytorch#201700

This is a bug when compiling: AOTAutograd doesn't trace through
AsyncCollectiveTensors and loses the requires_grad. This PR works around
the problem in general.

But the real solution should be fixing pytorch/pytorch#201700.

## Why
On main, Muse Spark with TP > 1 and local compile on never trains
tok_embeddings: its grad is None, for text-only and multimodal runs,
with SP on and off. Module-boundary redistributions return un-awaited
AsyncCollectiveTensors (async_op=True). AOTAutograd unwraps such an
input with trigger_wait(), which returns the inner tensor without
requires_grad (torch/_functorch/_aot_autograd/frontend_utils.py, added
by pytorch/pytorch#179849), so the compiled region's output has no grad
path back to the input. In Spark, the embedding output redistribution
feeds the compiled embedding norm. Tracking issue:
pytorch/pytorch#201700 (pytorch/pytorch#191113 is a closed, unmerged PR
for the same bug).

**Example.**
```
emb = tok_embeddings(tokens)          # redistributed at the Module boundary -> AsyncCollectiveTensor
h = compiled_norm(emb)                # local_compile region
loss(h).backward()
before: tok_embeddings.weight.grad is None
after:  tok_embeddings.weight.grad is set
```

## What changed
- Every local_compile region and always-compiled helper is wrapped so an
AsyncCollectiveTensor argument is awaited by a small autograd Function
before the compiled call. The Function keeps the autograd edge.
- Only top-level arguments are awaited. No in-tree region or
always-compiled helper takes tensors inside a container (checked every
signature; the only container argument is gdn's split_sizes: list[int]).
- TODO(pytorch/pytorch#201700) in code: remove once AOTAutograd keeps
the requires_grad of an unwrapped AsyncCollectiveTensor input.
- The same bug hits the async k_shared all-gather into the mla_kv region
in open PRs #5564 and #5682, which work around it with async_op=False.
k_shared is a top-level argument of that region, so this fix covers it
and they can keep async_op=True. In-tree CP MLA is not affected: in
UlyssesMLAAttention only the k_shared all-gather stays async, and it
feeds the eager materialize_mla_kv. The Q/KV all-to-all is synchronous
in spmd_types 0.3.1, so the compiled flex call gets plain tensors.

## Alternatives considered
- Wait inside Module redistribution (async_op=False): gives up the comm
overlap for every Module boundary, not only compiled regions.
- Fix in each model: the bug is in the local_compile layer and affects
any model with a compiled region after a redistribution.

## Numerics
Only Muse Spark with TP > 1 and local compile on changes: tok_embeddings
gets grads and trains. Configs below were checked; others are unchecked.

Setup: 2x H100, BASE = parent commit, TEST = this commit. debug.seed =
42, debug.deterministic = True, 10 steps, c4_test. Loss and grad_norm
are read from TensorBoard.

**Muse Spark debugmodel, TP2 + EP2 + SP, flex, default local_compile
regions.** Changes, as expected. Step 1 loss is equal (same forward);
step 1 grad_norm differs by the added tok_embeddings grad.

| step | BASE loss | BASE grad_norm | TEST loss | TEST grad_norm |
|---|---|---|---|---|
| 1 | 7.82727003 | 4.97379541 | 7.82727003 | 4.97423124 |
| 2 | 7.03273010 | 3.67558002 | 7.03092051 | 3.66602159 |
| 3 | 6.13859034 | 2.72887707 | 6.14003372 | 2.73221183 |
| 4 | 5.76145124 | 2.13588810 | 5.76339674 | 2.15090728 |
| 5 | 5.83007097 | 2.06997371 | 5.82927275 | 2.06360984 |
| 6 | 5.56987143 | 1.85165656 | 5.56976700 | 1.84894443 |
| 7 | 5.37956715 | 1.88629401 | 5.37123251 | 1.88281417 |
| 8 | 6.01605892 | 1.97213578 | 6.01554680 | 1.95823133 |
| 9 | 5.18035460 | 1.96500850 | 5.18841839 | 1.98249125 |
| 10 | 5.20351505 | 1.78124106 | 5.20615530 | 1.78476560 |

- Step 1 per-parameter grads (local grad norm, both ranks):
tok_embeddings.embedding.weight is None in BASE and nonzero in TEST
(rank 0: 0.06576, rank 1: 0.00345). The other 225 parameters have
bitwise equal grad norms.
- Determinism: two TEST runs give bitwise equal loss and grad_norm at
all 10 steps and equal step 1 per-parameter grads. So the BASE/TEST
difference comes from this change.

**DeepSeek V3 debugmodel, CP2, flex, default local_compile regions.**
Unchanged: loss, grad_norm, and step 1 per-parameter grads are bitwise
equal for both CP MLA backends.
- UlyssesMLAAttention (no load balancer): step 10 loss 4.13782024,
grad_norm 2.26978993 in BASE and TEST.
- AllGatherKVMLAFlexAttention (no load balancer; the CP attention of the
deepseek_v3_cp_pp golden): step 10 loss 4.13834953, grad_norm 2.27362609
in BASE and TEST.

Not checked: DeepSeek V3 varlen with CP, because FlashAttention 3
supports head dim at most 128 and the debug MLA head dim is 192.

## Testing
- CPU test: a compiled region (aot_eager) on an AsyncCollectiveTensor
input passes the grad back. It fails without the fix.
- CPU tests at this commit:
tests/unit_tests/cpu/config/test_compile_config.py, 9 passed.
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 release notes: distributed (c10d) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants