Skip to content

[DistMuon] support storage sharding of EP Shard(0) EFSDP Shard(1) - #4122

Merged
weifengpy merged 40 commits into
mainfrom
gh/weifengpy/53/head
Aug 20, 2026
Merged

weifengpy merged 40 commits into
mainfrom
gh/weifengpy/53/head

Conversation

@weifengpy

@weifengpy weifengpy commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

support storage sharding EP Shard(0) EFSDP Shard(1)

  • redistribute to optimizer compute sharding Shard(0) on EFSDP and EP, ordered EP-outer by shard_order_by_tensor_dim={0: ("ep", "efsdp")}; FlexShard derives the _StridedShard split factor from the bound mesh
  • one bucket for routed expert, on 2D mesh
  • one bucket for the dense, on 1D mesh

torchtitan-distmuon integration UX

build_dist_muon(
    params,
    compute_sharding_by_fqn={
        wq_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "dp_shard": BlockShard(
                    dim=0,
                    block_size=query_rows_per_head,
                ),
            },
        ),
        wo_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "dp_shard": Owned(),
            },
        ),
        routed_expert_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "efsdp": Shard(0),
                "ep": Shard(0),
            },
            shard_order_by_tensor_dim={0: ("ep", "efsdp")},
        ),
    },
    bucket_configs=(
        BucketConfig(
            name="layer",
            patterns=(wq_fqn, wo_fqn),
        ),
        BucketConfig(
            name="layer.routed-experts",
            patterns=(routed_expert_fqn,),
        ),
    ),
)

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 12, 2026
Split logical optimizer buckets into homogeneous physical transport groups and normalize DTensor storage regions to subgroup-local domains. Support one-axis redistribution while preserving orthogonal shards, including sharded and replicated Muon compute targets.

Cover mixed dense and sparse transport groups with a four-GPU numerical test.


ghstack-source-id: 5fbbc7f
Pull-Request: #4122
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 19, 2026
Normalize DTensor storage regions to transport-subgroup-local domains so DistMuon can redistribute native 3D expert tensors from EFSDP Shard(1) to _StridedShard(0, split_factor=ep_size) while preserving EP Shard(0) ownership.

Teach ComputeLayout and TorchTitan config parsing to preserve same-dimension sharding order, refresh Kimi expert layouts after EP overrides, and cover both nonempty and empty EFSDP compute shards with a four-GPU numerical test.

ghstack-source-id: f16ed97

Pull-Request: #4122
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 19, 2026
Normalize DTensor storage regions to transport-subgroup-local domains so DistMuon can redistribute native 3D expert tensors from EFSDP Shard(1) to _StridedShard(0, split_factor=ep_size) while preserving EP Shard(0) ownership.

Teach ComputeLayout and TorchTitan config parsing to preserve same-dimension sharding order, refresh Kimi expert layouts after EP overrides, and cover both nonempty and empty EFSDP compute shards with a four-GPU numerical test.

ghstack-source-id: 33a8ed7

Pull-Request: #4122
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 19, 2026
Normalize DTensor storage regions to transport-subgroup-local domains so DistMuon can redistribute native 3D expert tensors from EFSDP Shard(1) to _StridedShard(0, split_factor=ep_size) while preserving EP Shard(0) ownership.

Teach ComputeLayout and TorchTitan config parsing to preserve same-dimension sharding order, refresh Kimi expert layouts after EP overrides, and cover both nonempty and empty EFSDP compute shards with a four-GPU numerical test.

ghstack-source-id: dd5d30b

Pull-Request: #4122
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 19, 2026
Normalize DTensor storage regions to transport-subgroup-local domains so DistMuon can redistribute native 3D expert tensors from EFSDP Shard(1) to _StridedShard(0, split_factor=ep_size) while preserving EP Shard(0) ownership.

Teach ComputeLayout and TorchTitan config parsing to preserve same-dimension sharding order, refresh Kimi expert layouts after EP overrides, and cover both nonempty and empty EFSDP compute shards with a four-GPU numerical test.

ghstack-source-id: f0a6374

Pull-Request: #4122
@weifengpy weifengpy changed the title [FlexShard] Preserve orthogonal shards during optimizer resharding [DistMuon] support storage sharding of EP Shard(0) EFSDP Shard(1) Aug 19, 2026
@weifengpy
weifengpy marked this pull request as ready for review August 19, 2026 19:48
@weifengpy
weifengpy requested a review from shuhuayu August 19, 2026 19:52
# benchmarks show that the fixed nonempty EFSDP coordinates are a hotspot.
return ComputeLayout(
shardings_by_mesh_axis={
MeshAxisName.EFSDP.value: _StridedShard(0, split_factor=ep_size),

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.

Anything happen in config is user-facing, so we shouldn't expose private concept of _StridedShard. One way to alleviate this is via spmd_types / jax layout, where we annotate PartitionSpec on dim-0 to be (EP, EFSDP), but I don't know if it plays well with Owned and other flex-optimizer-shard placements

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_StridedShard can be expressed by Shard + shard_order. I can look up if PartitionSpec is something similar

@weifengpy
weifengpy marked this pull request as draft August 19, 2026 23:40
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 20, 2026
support storage sharding EP Shard(0) EFSDP Shard(1)
* redistribute to optimizer compute sharding `_StridedShard(0, split_factor=ep_size), Shard(0)`
* one bucket for routed expert, on 2D mesh
* one bucket for the dense, on 1D mesh

torchtitan-distmuon integration UX
```
build_dist_muon(
    params,
    compute_sharding_by_fqn={
        wq_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "dp_shard": BlockShard(
                    dim=0,
                    block_size=query_rows_per_head,
                ),
            },
        ),
        wo_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "dp_shard": Owned(),
            },
        ),
        routed_expert_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "efsdp": _StridedShard(0, split_factor=ep_size),
                "ep": Shard(0),
            },
        ),
    },
    bucket_configs=(
        BucketConfig(
            name="layer",
            patterns=(wq_fqn, wo_fqn),
        ),
        BucketConfig(
            name="layer.routed-experts",
            patterns=(routed_expert_fqn,),
        ),
    ),
)
```

ghstack-source-id: c58b532
Pull-Request: #4122
[ghstack-poisoned]
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 20, 2026
support storage sharding EP Shard(0) EFSDP Shard(1)
* redistribute to optimizer compute sharding `_StridedShard(0, split_factor=ep_size), Shard(0)`
* one bucket for routed expert, on 2D mesh
* one bucket for the dense, on 1D mesh

torchtitan-distmuon integration UX
```
build_dist_muon(
    params,
    compute_sharding_by_fqn={
        wq_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "dp_shard": BlockShard(
                    dim=0,
                    block_size=query_rows_per_head,
                ),
            },
        ),
        wo_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "dp_shard": Owned(),
            },
        ),
        routed_expert_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "efsdp": _StridedShard(0, split_factor=ep_size),
                "ep": Shard(0),
            },
        ),
    },
    bucket_configs=(
        BucketConfig(
            name="layer",
            patterns=(wq_fqn, wo_fqn),
        ),
        BucketConfig(
            name="layer.routed-experts",
            patterns=(routed_expert_fqn,),
        ),
    ),
)
```

ghstack-source-id: 2e5f2dc
Pull-Request: #4122
@weifengpy
weifengpy marked this pull request as ready for review August 20, 2026 06:41
@weifengpy
weifengpy requested a review from tianyu-l August 20, 2026 06:41
weifengpy added a commit that referenced this pull request Aug 20, 2026
support storage sharding EP Shard(0) EFSDP Shard(1)
* redistribute to optimizer compute sharding `_StridedShard(0, split_factor=ep_size), Shard(0)`
* one bucket for routed expert, on 2D mesh
* one bucket for the dense, on 1D mesh

torchtitan-distmuon integration UX
```
build_dist_muon(
    params,
    compute_sharding_by_fqn={
        wq_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "dp_shard": BlockShard(
                    dim=0,
                    block_size=query_rows_per_head,
                ),
            },
        ),
        wo_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "dp_shard": Owned(),
            },
        ),
        routed_expert_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "efsdp": _StridedShard(0, split_factor=ep_size),
                "ep": Shard(0),
            },
        ),
    },
    bucket_configs=(
        BucketConfig(
            name="layer",
            patterns=(wq_fqn, wo_fqn),
        ),
        BucketConfig(
            name="layer.routed-experts",
            patterns=(routed_expert_fqn,),
        ),
    ),
)
```

ghstack-source-id: 2e5f2dc
Pull-Request: #4122
Comment on lines +418 to +422
bucket_configs_list.append(
BucketConfig(
name=f"{name}.routed-experts",
patterns=routed_fqns,
)

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.

With EP, this is putting experts and dense params into two buckets, and it seems dist muon runtime will figure out they are on different meshes by looking at patterns and realize which mesh we perform A2A on. The good thing is that we still only need one DistMuon param group.

*,
parallelism: ParallelismConfig,
) -> OptimizersContainer.Config:
"""Align routed-expert layouts with the final parallelism config."""

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.

oh I see what this is doing -- CLI can change parallelisms in the config file, so we need to adjust

As @fegin mentioned earlier, we are going to deprecate this CLI capability, so hopefully we can remove this function soon. Could you add a TODO?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated the PR with the TODO

[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 20, 2026
support storage sharding EP Shard(0) EFSDP Shard(1)
* redistribute to optimizer compute sharding `_StridedShard(0, split_factor=ep_size), Shard(0)`
* one bucket for routed expert, on 2D mesh
* one bucket for the dense, on 1D mesh

torchtitan-distmuon integration UX
```
build_dist_muon(
    params,
    compute_sharding_by_fqn={
        wq_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "dp_shard": BlockShard(
                    dim=0,
                    block_size=query_rows_per_head,
                ),
            },
        ),
        wo_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "dp_shard": Owned(),
            },
        ),
        routed_expert_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "efsdp": _StridedShard(0, split_factor=ep_size),
                "ep": Shard(0),
            },
        ),
    },
    bucket_configs=(
        BucketConfig(
            name="layer",
            patterns=(wq_fqn, wo_fqn),
        ),
        BucketConfig(
            name="layer.routed-experts",
            patterns=(routed_expert_fqn,),
        ),
    ),
)
```

ghstack-source-id: 274375a
Pull-Request: #4122
weifengpy added a commit that referenced this pull request Aug 20, 2026
support storage sharding EP Shard(0) EFSDP Shard(1)
* redistribute to optimizer compute sharding `_StridedShard(0, split_factor=ep_size), Shard(0)`
* one bucket for routed expert, on 2D mesh
* one bucket for the dense, on 1D mesh

torchtitan-distmuon integration UX
```
build_dist_muon(
    params,
    compute_sharding_by_fqn={
        wq_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "dp_shard": BlockShard(
                    dim=0,
                    block_size=query_rows_per_head,
                ),
            },
        ),
        wo_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "dp_shard": Owned(),
            },
        ),
        routed_expert_fqn: ComputeLayout(
            shardings_by_mesh_axis={
                "efsdp": _StridedShard(0, split_factor=ep_size),
                "ep": Shard(0),
            },
        ),
    },
    bucket_configs=(
        BucketConfig(
            name="layer",
            patterns=(wq_fqn, wo_fqn),
        ),
        BucketConfig(
            name="layer.routed-experts",
            patterns=(routed_expert_fqn,),
        ),
    ),
)
```

ghstack-source-id: 274375a
Pull-Request: #4122
@weifengpy
weifengpy merged commit 6ee6b10 into main Aug 20, 2026
23 of 24 checks passed
depeng1994 pushed a commit to depeng1994/torchtitan-npu that referenced this pull request Sep 23, 2026
Co-authored-by: zzyyjj012<[email protected]>



# message auto-generated for no-merge-commit merge:
!879 merge feat/dsv4-muon-efsdp-ep-shard-order into master

fix: support E-FSDP and EP Muon shard order for DSV4&4.1

Created-by: zzyyjj012
Commit-by: zzyyjj012
Merged-by: cann-robot
Description: # fix: support E-FSDP and EP Muon shard order

## 描述

该 PR 修复 DeepSeek-V4&4.1在同时启用 Expert Parallel(EP)与 Expert Fully Sharded Data Parallel(E-FSDP)时,routed expert 参数无法按正确顺序进入分布式 Muon 计算布局的问题。

实现不新增一套 Muon 通信框架,而是复用 torchtitan 上游 FlexShard/DistMuon 的 optimizer reshard 机制,并回移上游 PR [pytorch/torchtitan#4122](pytorch/torchtitan#4122) 的 `ComputeLayout.shard_order_by_tensor_dim` 能力(对应上游提交 `6ee6b10b934730df00cbcd0cab5c93d04ae2e38a`)。当前项目固定的 torchtitan 版本尚未包含该能力,因此本仓通过 `torchtitan_npu/patches/torchtitan/distributed/flex_shard/` 临时补齐;依赖版本包含上游 PR 后可以删除这组 patch。

## 为什么需要修改

DeepSeek-V4 routed expert 权重的第 0 维同时受到 EP 和 E-FSDP 切分。Muon 计算要求先按 EP 选定本 rank 负责的 expert,再在对应 expert 内按 E-FSDP 切分,即:

```text
完整 expert 集合
  -> EP:选择当前 EP rank 的 expert
  -> E-FSDP:切分该 expert 的参数
```

该顺序与 DTensor 按 storage mesh 轴顺序生成的默认切分顺序不一致。如果只声明两个轴均为 `Shard(0)`,无法表达「EP 在外、E-FSDP 在内」,会使 Muon 看到错误的 expert 分片边界。

本 PR 为 routed expert 参数显式配置:

```python
ComputeLayout(
    shardings_by_mesh_axis={
        "ep": Shard(0),
        "efsdp": Shard(0),
    },
    shard_order_by_tensor_dim={
        0: ("ep", "efsdp"),
    },
)
```

上游能力会将该逻辑顺序 lower 为可执行的 DTensor placement,并由 FlexShard 为 storage layout 与 Muon compute layout 之间的差异生成定向 redistribution plan。

## 实现方式

- 回移上游 PR #4122 的 `ComputeLayout.shard_order_by_tensor_dim` 接口、校验和 lowering 逻辑。
- 扩展 DistMuon 的 layout 解析,使其支持 routed expert 的正交分片场景:参数存储在 EP/E-FSDP 二维 mesh 上,通信时保留 EP 归属,只在对应 E-FSDP 子组内补齐 Muon 计算所需的分片。
- 为该场景生成 dim-0 redistribution plan,并继续复用上游 `_BucketedRedistributionRuntime`、packed `all_to_all_single` 和双 slot pipeline,不在模型侧引入新的 collective 实现。
- 将每层 bucket 拆分为 dense bucket 与 `routed-experts` bucket,避免两类参数因通信 mesh 不同而被放入同一个 redistribution bucket。
- 在 patch 初始化时同步替换 `optimizer_reshard.ComputeLayout`、`flex_shard.ComputeLayout` 及 DistMuon 引用,保证配置构造与运行时使用同一类型。

## Muon step 中的两类 AllToAllV

profiling 中看到的 AllToAllV 可分为两类语义:

1. **常规 Muon 矩阵重分布**:在 Newton-Schulz(NS)前,将各 rank 持有的存储分片组织成负责计算的 rank 所需的完整矩阵或计算分片;NS 完成后,再通过反向 plan 将更新结果送回原存储分片。这是 FlexShard/DistMuon 原有的全局 Muon 计算路径。
2. **routed expert 的 E-FSDP 定向重分布**:expert 已先由 EP 确定归属,E-FSDP rank 本地只持有该 expert 的不完整参数分片。该 AllToAllV 只在对应的 E-FSDP 子组内按 plan 定点交换缺失区域,使每个 rank 获得其 Muon compute shard;计算完成后按反向 plan 写回原 E-FSDP storage shard。它不会跨 EP 汇集其他 rank 的 expert,也不是一次全局 all-gather。

需要注意,「两类 AllToAllV」描述的是通信职责,不表示一个 Muon step 只有两个 HCCL kernel。对每个需要重分布的 bucket,上游 runtime 都会执行一对方向相反的 packed AllToAllV:

```text
storage_to_compute AllToAllV
  -> momentum / Nesterov / Newton-Schulz
  -> compute_to_storage AllToAllV
```

多个 bucket 会重复该过程,并由上游双 slot pipeline 尝试将相邻 bucket 的通信与计算重叠。

### 其他修改
- DeepSeek-V4.1 在 `--no-engram-enabled` 时将 HostSparse optimizer 配置降级为普通 `OptimizerConfig`,从而选择常规 swap optimizer,而不是 HostSparse swap container。
- 延迟导入 CPU-offload Muon 实现,避免普通 optimizer 路径被其依赖影响。

## 类型

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

## Checklist

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

## 如何测试

### 8 卡 E-FSDP + EP 训练与 profiling

验证配置:

- 设备数:8 卡 Ascend NPU
- 模型配置:`deepseek_v4_debugmodel`
- 并行配置:`EP=4`、`E-FSDP=2`
- Muon:启用
- 编译:关闭
- 训练步数:10

验证结果:

- 8 卡 mesh 成功创建,active dimensions 包含 `ep` 与 `efsdp`。
- 日志中的 routed expert `ComputeLayout` 为 `shard_order_by_tensor_dim={0: ('ep', 'efsdp')}`。
- step 6 profiling 成功生成 `trace_view.json`、`kernel_details.csv`、`operator_details.csv` 和 `communication.json`。
- trace 中 `Optimizer.step#DistMuon.step` 范围内可见 `hcom_alltoallv`,可对应检查 NS 前后的 storage/compute 重分布以及 routed expert 的 E-FSDP 子组定向交换。


![image.png](https://raw.gitcode.com/user-images/assets/9028822/f3375c78-5454-4284-8a1c-932b71c21416/image.png 'image.png')

本次 profiling 证明 EP/E-FSDP shard-order 路径可以进入 DistMuon step、执行 AllToAllV 并完成训练。
性能分析:efsdp使得expert内部被切分导致额外增加的通信时间很少,在等效裁剪模型下可以被NS计算掩盖。当减少专家数导致单rank计算量不够时,可能会出现通信尾部未完全掩盖的情况。

### 精度验证
debug model EP4 vs EP2/eFSDP2  4卡
![ep4_vs_ep2_efsdp2_loss_alignment.png](https://raw.gitcode.com/user-images/assets/9028822/429a2828-b88a-412e-871f-bcb03fc8ad0d/ep4_vs_ep2_efsdp2_loss_alignment.png 'ep4_vs_ep2_efsdp2_loss_alignment.png')

## 其他信息

- 上游来源:`pytorch/torchtitan#4122`,提交 `6ee6b10b934730df00cbcd0cab5c93d04ae2e38a`。
- NPU admission 的后续上游跟踪:`pytorch/torchtitan#4405`。
- patch 退出条件:项目固定的 torchtitan 依赖包含 PR #4122 及本场景所需的 NPU storage admission 后,删除本地 FlexShard backport,并改为直接使用上游实现。


See merge request: cann/torchtitan-npu!879
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants