Skip to content

[DistMuon] Deduplicate HSDP replica compute - #4411

Closed
yu-chen-code wants to merge 4 commits into
pytorch:mainfrom
yu-chen-code:main-muon-hsdp-dp-dedup
Closed

yu-chen-code wants to merge 4 commits into
pytorch:mainfrom
yu-chen-code:main-muon-hsdp-dp-dedup

Conversation

@yu-chen-code

Copy link
Copy Markdown
Contributor

Summary

This PR adds an opt-in path to deduplicate DistMuon optimizer compute across
an HSDP replicated storage mesh axis.

  • Add deduplicate_compute_mesh_axis to build_dist_muon.
  • Run the existing DistMuon redistribution, Newton-Schulz compute, and
    parameter update only on coordinate zero of that replicated axis.
  • Keep the replicated momentum state updated locally on the other replica
    coordinates.
  • Broadcast the updated local parameter shards from coordinate zero after the
    optimizer update.
  • Enable this automatically for the Kimi DistMuon recipes when
    data_parallel_replicate_degree > 1.

The default remains None, so non-HSDP configurations and existing DistMuon
callers keep their current behavior.

Motivation

With HSDP, each coordinate of dp_replicate stores the same local parameter
shard. DistMuon currently performs the same Muon matrix computation on every
replica, even though the resulting parameter update is replicated.

This PR makes one replica coordinate responsible for the Muon compute and
synchronizes the updated local parameter shard to its peers. The optimizer
state layout and checkpoint format do not change.

For a two-way replica axis, the four-GPU test asserts that the global Muon
compute call count is reduced from 4 to 2 across two optimizer steps while
preserving the local parameters and momentum buffers exactly.

Design

deduplicate_compute_mesh_axis must name an active storage mesh axis with an
exact Replicate() placement for every DistMuon parameter.

During optimizer construction:

  1. DistMuon validates the requested storage mesh axis.
  2. The owner is selected using coordinate zero of the parameter's storage
    DeviceMesh, rather than relying on process-group-local rank ordering.
  3. Parameter broadcasts are grouped by ProcessGroup in deterministic
    parameter order.

During step():

  1. The owner runs the existing DistMuon redistribution and update path.
  2. Non-owners update only their local momentum buffers from the same reduced
    gradients.
  3. The owner broadcasts each updated local parameter shard to the other
    replica coordinates.

Broadcasts remain asynchronous within one process group. DistMuon waits for
all work on that group before starting collectives on another process group.
This matters for configurations such as Kimi that can have distinct dense and
sparse parameter meshes.

Kimi integration

The Kimi registry derives the setting from the final parallelism
configuration:

  • HSDP (data_parallel_replicate_degree > 1): use dp_replicate.
  • FSDP-only or single-replica configurations: leave deduplication disabled.

This is aligned after CLI overrides are applied, so users do not need a new
recipe option to enable it for a Kimi HSDP run.

Relation to existing work

Related to #3353. Builds on the DistMuon/FlexShard implementation introduced
in #4060.

#4077 adds support for explicitly replicated Muon compute layouts. This PR is
orthogonal: it keeps the existing HSDP replicated storage layout, executes the
optimizer compute on one replica coordinate, and broadcasts the updated local
parameter shards to the other coordinates.

Testing

Added four-GPU CUDA coverage under
TestDistMuonHSDPReplicaDeduplication:

  • Compare deduplicated and non-deduplicated HSDP updates across two steps,
    including exact parameter and momentum-buffer equality.
  • Verify that non-owner replica coordinates do not run Muon compute.
  • Verify that the owner and broadcast source are selected from storage mesh
    coordinate zero, independently of process-group rank ordering.
  • Verify that broadcasts complete before switching between replica process
    groups.

Checks completed locally:

  • git diff --check
  • Python 3.14 AST parsing for the modified implementation and test files

GPU functionality and numerical correctness are pending comprehensive
validation.

Draft status

I am opening this as a Draft to get early feedback on:

  1. Whether deduplicate_compute_mesh_axis is the preferred public API for
    selecting the HSDP replica axis.
  2. Whether the Kimi recipes should enable the optimization automatically from
    data_parallel_replicate_degree.
  3. Whether maintainers prefer this to be coordinated with or stacked relative
    to Support explicit replicated Muon compute #4077.

Before marking the PR ready, I plan to complete GPU functionality and numerical
correctness validation and add the results here.

@meta-cla

meta-cla Bot commented Sep 2, 2026

Copy link
Copy Markdown

Hi @yu-chen-code!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@meta-cla

meta-cla Bot commented Sep 2, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 2, 2026
@meta-cla

meta-cla Bot commented Sep 2, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

_normalize_param_groups(params),
compute_sharding_by_fqn=compute_sharding_by_fqn,
bucket_configs=bucket_configs,
deduplicate_compute_mesh_axis=deduplicate_compute_mesh_axis,

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.

have your considered using existing redistribution API to fuse comm into all2all?

storage sharding : Replicate, Shard
compute sharding: shard, shard with shard_order

most importantly, why dedup? it's a perf trade off:

  • hsdp with duplicate compute: no sync required along Replicate mesh
  • with deduped compute: all rank syncs
  • when we run out of parameters with Owned and BlockShard, because 1D mesh are just too big, it's nature to use 2D mesh

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.

Thanks for the detailed feedback. You are right that deduplicating Muon compute is a performance trade-off rather than an unconditional optimization.
I have pushed an initial update that distributes different parameters across the replica coordinates instead of placing all Muon compute on a single replica. The existing 1D redistribution is still used within the owning replica, and the updated local parameter shards are synchronized through coalesced broadcasts. This avoids the single-replica compute hotspot while keeping the current redistribution path unchanged.
This update does not yet fully address your suggestion of expressing the (Replicate, Shard) -> (Shard, Shard) transition as a 2D redistribution and folding the replica synchronization into the packed all-to-all. I am still investigating that approach, including its collective synchronization, memory, and topology-dependent performance trade-offs.
I’ll continue working on the remaining points and update the PR with further changes and validation results. Thanks again for pointing me in this direction.

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.

if you were to support this, it needs to be done with existing API build_dist_muon(compute_sharding_by_fqn, bucket_configs), insteazd of adding deduplicate_compute_mesh_axis for a bucket based transport (_REPLICA_BROADCAST_BUFFER_SIZE_BYTES)

storage sharding : Replicate, Shard
compute sharding: shard, shard with shard_order

above is a capability gap that's worth addressing. BUT, I am still not aligned on making it default. when choosing HSDP, it's already duplicating compute in forward/backward. I still don't understand duplicating compute in opt.step becomes unacceptable

could you elaborate your usecase?

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.

@yu-chen-code have you addressed the comment?

@tianyu-l
tianyu-l requested a review from weifengpy September 3, 2026 09:52
@yu-chen-code
yu-chen-code force-pushed the main-muon-hsdp-dp-dedup branch from e541b12 to 23393f4 Compare September 4, 2026 07:55
@tianyu-l tianyu-l closed this Oct 7, 2026
submartingales pushed a commit to botcanlearn/torchtitan-npu-upstream that referenced this pull request Oct 10, 2026
Co-authored-by: NoGood<[email protected]>
Co-authored-by: zzyyjj012<[email protected]>



# message auto-generated for no-merge-commit merge:
!877 merge hsdp-dedup-early-broadcast-swap-indexer into master

Muon优化器支持HSDP去冗余

Created-by: zzyyjj012
Commit-by: zzyyjj012;NoGood
Merged-by: cann-robot
Description: 
## 描述

新增 DeepSeek-V4 DistMuon 的 HSDP replica dedup 可选路径。

HSDP 的 `dp_replicate` 轴上保存相同的本地参数分片。启用
`--optimizer.muon-enable-hsdp-replica-dedup` 后,代码为每个参数 FQN
确定一个 replica owner,仅在 owner 上保留并执行 Muon momentum、重分布、
Newton--Schulz 和参数更新;更新后的本地参数分片再按真实
`dp_replicate` process group 异步 broadcast 给其他 replica。

相对 `master` 的主要改动:

- 在 `OptimizerConfig` 新增 opt-in 开关,并将其传入 `DistMuon` factory。
- 新增 `replica_dedup.py` 临时 TorchTitan patch:
  - 校验 `dp_replicate` mesh axis 及受管参数的 `Replicate()` placement;
  - 基于 FQN 为参数选择稳定 owner;
  - 为本 rank 的 owner 参数重建原生 FlexShard bucket plan;
  - 对更新后的参数按 canonical 顺序执行异步 replica broadcast;
  - 在 step 前校验所有 replica 的 FQN/owner 及 collective 合约一致。
- DCP save/load 使用临时标准 state layout:
  - save 时物化并从 owner 同步 momentum;
  - load 时先安装 state template,load 后恢复 owner-only momentum state。
- NovaSwap checkpoint 初始化不再通过零梯度 AdamW `step()` 创建缺失 state,
- 补充 HSDP replica dedup feature guide、单测契约和上游追踪 TODO。

本地 patch 跟踪上游 TorchTitan PR #4411。上游合入且本仓依赖升级后,应删除
`replica_dedup.py`、其导入注册及临时测试。
pytorch/torchtitan#4411

## 类型

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

## Checklist:

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


## 如何测试

### 单元测试

```bash
pytest -q tests/unit_tests/test_dsv4_muon.py
```

结果:`9 passed`。

### A5 HSDP replica dedup性能验证
![image.png](https://raw.gitcode.com/user-images/assets/9028822/6d0b31ec-758d-4633-9940-7cca7c83b2c6/image.png 'image.png')

### HSDP replica dedup debug模型精度与 DCP 验证

在 8 卡 HSDP(`replicate_degree=2`、`shard_degree=4`、`expert_degree=4`)下,使用
`deepseek_v4_debugmodel`、Golden sparse attention、固定 seed `42`、deterministic、
关闭 compile、`seq_len=128`、global batch size `8` 进行验证。

#### dedup 开关精度

无 checkpoint 场景连续运行 10 step,对比:

- A:dedup off、NovaSwap off
- B:dedup on、NovaSwap off
- C:dedup off、NovaSwap on
- D:dedup on、NovaSwap on

A/B、A/C、C/D、B/D 的 step 集合完全一致;每个 step 的原始 TensorBoard
`loss_metrics/global_avg_loss` 与 `grad_norm` 均逐 float 完全一致。

#### DCP 自恢复与跨 dedup 开关恢复

四个 A/B/C/D 组合均在 step 3 保存 DCP,并由新进程恢复执行 step 4–6:

- 每个组合的 continuous 与 resume 后缀 `loss`、`grad_norm` 均逐 float 完全一致;
- dedup off 保存 → dedup on 恢复:逐 float 完全一致;
- dedup on 保存 → dedup off 恢复:逐 float 完全一致。

修复 NovaSwap AdamW checkpoint state materialization 后,额外比较了 dedup off +
NovaSwap off 与 dedup on + NovaSwap on 的 checkpoint state:328 个模型/优化器 tensor
及全部 optimizer scalar 完全一致(不包含独立的 dataloader bookkeeping state)。

### 8 卡 NPU 端到端验证

使用 `deepseek_v4_flash_43layers_16experts`,HSDP R2/S4/EP4,
`--optimizer.muon-enable-hsdp-replica-dedup`、固定 seed、golden 路径、
`seq_len=128`、global batch size 8。

1. 连续训练 6 step,在 step 3 保存 DCP。
2. 新进程从 step 3 恢复:
   - NovaSwap 开:执行 step 4–6;
   - NovaSwap 关:执行 step 4–5。
3. 从 TensorBoard 读取未截断的 `loss_metrics/global_avg_loss` 与 `grad_norm`。

结果:

- NovaSwap 开/关的连续 step 1–6,两项原始 float 均完全一致。
- NovaSwap 开时,DCP 恢复 step 4–6 与连续训练完全一致。
- NovaSwap 关时,DCP 恢复 step 4–5 与连续训练完全一致。
- 两组运行均同时包含 DistMuon 与 AdamW 参数组。
- rank-0 稳态 allocator memory:
  - 连续训练:NovaSwap 开 `39.48 GiB`,关 `49.96 GiB`;
  - DCP 恢复:NovaSwap 开 `39.47 GiB`,关 `54.91 GiB`。

### 已知边界

当前只验证了单机 8 卡、HSDP R2/S4/EP4、TP=1、PP=1 的 DSV4 golden 路径。
TP>1、PP>1、跨 world size 恢复、其他 HSDP 拓扑与
`async_with_pinned_mem` checkpoint 尚未验证。

## 其他信息

`replica_dedup.py` 顶部已标记上游 PR #4411 的删除条件。该 PR 当前仍为 Draft。

上游 PR #4411 描述的也是在 HSDP replica 轴上去除重复 DistMuon 计算、并广播 owner 更新后的参数分片。[PR #4411](pytorch/torchtitan#4411)

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

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants