Skip to content

[WIP] Balance singleton expert NS compute across E-FSDP ranks - #5633

Closed
jiesihu wants to merge 1 commit into
pytorch:mainfrom
jiesihu:feat/distmuon-efsdp-balance
Closed

jiesihu wants to merge 1 commit into
pytorch:mainfrom
jiesihu:feat/distmuon-efsdp-balance

Conversation

@jiesihu

@jiesihu jiesihu commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

WIP status

We are evaluating bucket-wide balancing across Owned, Shard and BlockShard workloads, including fixed local work. Upstream #5468 has now merged a general implementation of this approach. We are checking its coverage of this PR's singleton E-FSDP case before proposing any further changes.

Summary

When an EP-local expert batch contains one expert, Shard(0) assigns its entire Newton-Schulz workload to the first E-FSDP rank. Multiple layers in the same bucket can therefore leave the other E-FSDP ranks idle.

Balance these singleton expert tensors within each bucket using the existing deterministic greedy load allocator. The planner estimates NS compute cost and reorders compute-shard ranks per tensor, while preserving complete matrices, storage placements and the existing transport path. Eligible E-FSDP layouts are detected automatically, without new configuration options.

The change is limited to dist_muon.py and one new CPU unit test covering balanced ownership, complete matrix shapes, routing and plan-cache separation.

Validation

  • 42 relevant CPU tests passed, including the new test. Changed-file lint/format checks and type checking passed.
  • Tested DeepSeek-V4 Flash on 8 Ascend 910B3 devices and 8 NVIDIA H800 GPUs: 23 layers, 4 experts, FSDP8 + EP4 + E-FSDP2, paired-layer buckets, and no CPU swap. On both setups, the original and balanced versions completed 15 steps with identical recorded loss and grad norm, and matching final model and optimizer-state hashes on all ranks.
Hardware Original Muon time Balanced Muon time Reduction
Ascend 910B3 1296.47 ms 1140.56 ms ~12%
NVIDIA H800 328.60 ms 300.86 ms 8.44%

910B3 timing is from the inspected rank-0 profiling region. H800 timing uses CUDA events: the median of steps 6-11, taking the slowest of 8 ranks at each step. These are preliminary Muon optimizer measurements.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 27, 2026
@jiesihu
jiesihu marked this pull request as ready for review October 28, 2026 01:38
@jiesihu jiesihu changed the title [WIP] Balance singleton expert NS compute across E-FSDP ranks Balance singleton expert NS compute across E-FSDP ranks Oct 28, 2026
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 28, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 28, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/fake-pg

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@jiesihu
jiesihu marked this pull request as draft October 28, 2026 01:42
@jiesihu jiesihu changed the title Balance singleton expert NS compute across E-FSDP ranks [WIP] Balance singleton expert NS compute across E-FSDP ranks Oct 28, 2026
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 28, 2026
@jiesihu
jiesihu marked this pull request as ready for review October 28, 2026 02:43
@jiesihu jiesihu changed the title [WIP] Balance singleton expert NS compute across E-FSDP ranks Balance singleton expert NS compute across E-FSDP ranks Oct 28, 2026
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 28, 2026
@tianyu-l
tianyu-l requested a review from weifengpy October 28, 2026 03:04
shuhuayu pushed a commit that referenced this pull request Oct 29, 2026
## Summary

Add a mixed DistMuon + AdamW recipe for DeepSeek-V4, adapting the
model-specific layouts from torchtitan-npu to upstream TorchTitan.

- Define `ComputeLayout` mappings for attention, indexer, experts,
router, HC, compressor, and MTP parameters.
- Align Newton–Schulz matrix boundaries with the model’s forward
computation.
- Share expert-layout helpers with Kimi and follow its bucket grouping:
layer 0 separately, then pairs of layers. Dense and routed-expert
buckets remain separate.
- Support fixed and per-iteration NS coefficients through the Python
recipe arguments `muon_ns_steps` and `muon_ns_coefficients`.
- Add an AdamW step-0 seed checkpoint configuration and preserve the
AdamW TP regression test.

Related Muon optimization:
#5633.

## Validation

- **50 CPU unit tests passed**, covering NS coefficients, storage
validation, optimizer/layout mappings, bucket grouping, MTP, and
parameter groups.
- Changed-file formatting, lint, and local `pyrefly` checks passed.
- Previously collected Ascend results include successful 4/8-NPU,
10-step training runs. A bucket comparison with 4 experts and FSDP8 +
EP4 + E-FSDP2 reduced Muon optimizer time by **6.3%**.
- Previously collected H800 results include successful seed checkpoint
creation/loading and two deterministic 10-step runs with identical
recorded loss and grad norm.
- Previously collected H800 numerical results are shown below. The
50-step FSDP2 versus FSDP2 + EP2 comparison shows numerical agreement in
loss and grad norm.

![H800 FSDP2 versus FSDP2 + EP2, 50-step numerical
comparison](https://raw.githubusercontent.com/jiesihu/torchtitan/db725c15a7a8055ae80eb76da8fca36564d6fd3b/pr-assets/4920/H800-fsdp2-ep2-50steps.png)

## Limitations

The DeepSeek-V4 DistMuon recipe currently targets FSDP and EP. TP and PP
are disabled for this recipe, and CP support remains follow-up work. The
existing AdamW TP path is preserved.
@jiesihu

jiesihu commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Hi @weifengpy, could you please review this PR when you have a chance? The CI workflows are also awaiting maintainer approval. Thanks!

@tianyu-l

tianyu-l commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 59s —— View job


Request changes -- see the review.

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

Verdict: Request changes -- the new balancer runs separately from the existing Owned balancer and its cross-bucket loads. It is also turned on by an axis-name check, and the only benchmark is a reduced model where num_experts == EP.

What this PR does. Take a redistributed Shard(0) expert tensor whose group-local batch is a single expert. The PR picks which E-FSDP rank gets shard index 0, the only non-empty compute shard, using the existing LPT helper within each bucket. Ownership varies per tensor. Storage, transport participants, and numerics stay the same.

Example. Mesh (edp_shard=2, ep=4), 4 experts, so each EP rank holds 1 expert and the edp group is {0, 4}.

main: layers.{1,2}.routed_experts.{w13,w2}: Newton-Schulz on rank 0, rank 4 idle
PR:   bucket [l1.w13, l1.w2, l2.w13, l2.w2] -> l1.w13->0, l2.w13->4, l1.w2->4, l2.w2->0
      bucket with one layer [l1.w13, l1.w2] -> w13 always on rank 0, w2 always on rank 4

Must fix

  1. dist_muon.py:1074 -- a second balancer that starts at zero loads in every bucket and ignores Owned loads. Fold singletons into _assign_balanced_owner_ranks (inline).
  2. dist_muon.py:1048 -- gated on the axis name "edp_shard" hard-coded in generic flex_shard code. Use only the structural conditions (inline).
  3. dist_muon.py:1084 -- overloads _RedistributionGroup.mesh_axis_participants through replace(). Pass shard_participants explicitly (inline).
  4. torchtitan_recipes/tests/models/kimi_k2_7.py:303-305 -- the comment there says to "add balanced rank assignment only after benchmarks show..." and is stale after this PR. Update or remove it in this PR.

Should consider

  • dist_muon.py:1062 -- only batch size 1 is handled. Any group-local batch that doesn't divide evenly over the participants has the same hotspot (inline).

Questions

  • Which production config hits this? On the in-repo deepseek_v4_flash flavor (256 experts) with EP4 and E-FSDP2, each EP rank has 64 experts, so this code does nothing. The benchmark used a 23-layer, 4-expert model where num_experts == EP. A single local expert with E-FSDP > 1 needs EP equal to the expert count (e.g. EP256 for Flash, EP384 for Kimi). Please name the target config, and give a number on a real flavor or an end-to-end step time, not only the Muon region.
Details
  • Smaller design: _assign_balanced_owner_ranks treats "singleton redistributed Shard compute" layouts as candidates, with cost from _dtensor_storage_regions(...)[0]. _resolve_muon_redistribution_plans turns the owner into shard_participants = (owner, *others) and passes it to _build_parameter_redistribution_plan, with the owner in spec. The assertion owner_rank is None for Shard needs relaxing, or the order can go in a separate field. This removes _balance_singleton_compute_groups (~58 lines) for about 15-20 changed lines, and shares cumulative loads with Owned items.
  • Cross-rank consistency checks out: each edp group computes the same assignment indices from identical shapes and FQN tie-breaks, and the plan cache keys on the shard order. Momentum stays in storage layout, so checkpoints are unaffected.
  • The new test checks a perf property (owner balance), not numerics. It's a cheap CPU test, but it should change along with the design above. It also needs a case with one layer per bucket, which is where the current per-bucket reset shows up.

Not verified: the expected loss of the gain with one layer per bucket (no GPU run).

Comment on lines +1074 to +1076
assignments, _ = _balance_loads_across_partitions(
loads, initial_cumulative_primary_loads=(0,) * len(participants)
)

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.

This is a second LPT balancer that ignores the first one. _resolve_muon_redistribution_plans already balances Owned items with _assign_balanced_owner_ranks, carrying cumulative_loads_by_participants across buckets. This call starts at (0,) * len(participants) in every bucket and ignores any Owned load in the same bucket. Two consequences:

  • When a bucket has one singleton tensor, or the same uneven w13/w2 pair in every bucket, ties go to partition 0 every time, so participants[0] gets the heavier work in every bucket. The 8-12% gain was measured with paired-layer buckets, which hides this. With one layer per bucket I'd expect most of the gain to disappear (unverified).
  • Owned and singleton loads on the same participants never see each other.

A singleton Shard(0) batch is really one owner computing the whole group-local tensor. Smallest fix: make these layouts candidates in _assign_balanced_owner_ranks, with cost taken from the group-local shape, so both kinds share one balancer and the cumulative loads. Then delete this function.

or type(layout.compute_sharding) is not Shard
or storage_axis is None
or mesh_axis_names is None
or mesh_axis_names[storage_axis] != "edp_shard"

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.

This gates the behavior on a hard-coded mesh axis name. Nothing else in flex_shard/*.py checks axis names; layouts are resolved from placements and declared ComputeLayouts. The imbalance doesn't depend on the axis being called edp_shard: any redistributed Shard(0) compute whose group-local batch is smaller than the group size has it. If an axis gets renamed, or the same layout runs on another axis, the balancing turns off silently. Drop the name check and keep only the structural conditions (Shard compute, a redistribution axis, and the group-local batch size).

participants,
required_storage_mesh_axis=storage_axis,
)
if local_shape[0] != 1:

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.

Only local_shape[0] == 1 is handled. The same fixed-coordinate hotspot happens whenever the group-local batch doesn't divide evenly over the participants. For example, 2 local experts over edp_shard=4 means ranks at shard index 0 and 1 compute every layer while 2 and 3 never do. That's the case the Kimi recipe comment describes ("EP-local expert count is smaller than the edp_shard size"). Is there a reason to stop at 1? Rotating the shard order per tensor would cover any remainder. If you want to keep only the singleton case, say why in a comment.

rank for rank in context.group.mesh_axis_participants if rank != owner
)
# Keep transport participants unchanged; only reorder compute shards.
groups[index] = replace(context.group, mesh_axis_participants=shard_order)

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.

_RedistributionGroup.mesh_axis_participants is the rank order along the mesh axis (_optimizer_reshard_schedule.py:903). Here a copied group is built only to carry a per-tensor compute shard order under that name. The plan builders already take an explicit shard_participants argument (_build_dim0_shard_redistribution_plan). Pass the shard order through directly, e.g. as an extra argument to _build_parameter_redistribution_plan and an element of spec, and keep context.group unchanged. That also removes the new replace import.

@jiesihu
jiesihu marked this pull request as draft November 2, 2026 12:25
@jiesihu jiesihu changed the title Balance singleton expert NS compute across E-FSDP ranks [WIP] Balance singleton expert NS compute across E-FSDP ranks Nov 2, 2026
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 2, 2026
@jiesihu jiesihu closed this Nov 12, 2026
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Nov 12, 2026
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