Skip to content

Add DistMuon support for DeepSeek V4 - #4920

Merged
shuhuayu merged 4 commits into
pytorch:mainfrom
jiesihu:feat/deepseek-v4-distmuon
Oct 29, 2026
Merged

shuhuayu merged 4 commits into
pytorch:mainfrom
jiesihu:feat/deepseek-v4-distmuon

Conversation

@jiesihu

@jiesihu jiesihu commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

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

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.

@meta-cla

meta-cla Bot commented Sep 28, 2026

Copy link
Copy Markdown

Hi @jiesihu!

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!

@jiesihu
jiesihu force-pushed the feat/deepseek-v4-distmuon branch from 2240694 to 90cf2c8 Compare September 28, 2026 09:17
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 28, 2026
@jiesihu
jiesihu force-pushed the feat/deepseek-v4-distmuon branch from 90cf2c8 to b301450 Compare September 28, 2026 09:47
@tianyu-l
tianyu-l requested review from shuhuayu and weifengpy October 7, 2026 06:18
@jiesihu
jiesihu marked this pull request as ready for review October 14, 2026 06:09
@jiesihu jiesihu changed the title [WIP] Add DistMuon support for DeepSeek V4 Add DistMuon support for DeepSeek V4 Oct 14, 2026
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 14, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@jiesihu
jiesihu marked this pull request as draft October 14, 2026 06:17
@jiesihu jiesihu changed the title Add DistMuon support for DeepSeek V4 [WIP] Add DistMuon support for DeepSeek V4 Oct 14, 2026
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 14, 2026
@jiesihu
jiesihu force-pushed the feat/deepseek-v4-distmuon branch from b301450 to 74ec0a1 Compare October 14, 2026 07:36
@jiesihu
jiesihu marked this pull request as ready for review October 14, 2026 07:41
@jiesihu jiesihu changed the title [WIP] Add DistMuon support for DeepSeek V4 Add DistMuon support for DeepSeek V4 Oct 14, 2026
@jiesihu

jiesihu commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

@shuhuayu @weifengpy

This PR is now ready for review. It adds DeepSeek-V4 DistMuon layouts and configurable Newton-Schulz coefficients, with CPU unit tests and 4/8-NPU 10-step smoke tests passing. Could you please take a look and share any feedback? Thank you!

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 14, 2026
@weifengpy

Copy link
Copy Markdown
Contributor

will take a look tomorrow. thanks for doing this

shardings[f"{prefix}.moe.router.gate.weight"] = owned
for module in hc_pre_modules:
shardings[f"{prefix}.{module}.hc_fn"] = owned
if attention.compressor is not None:

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.

Heavily compressed attention uses attention.compressor_128 so it is not using muon as intended.

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.

Fixed. The HCA compressor_128.wkv and wgate projections are included in Muon, with coverage in the layout tests.

shardings_by_mesh_axis={
MeshAxisName.DP_SHARD.value: BlockShard(
dim=0,
block_sizes=(attention.wo_a.out_features,),

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.

should we use attention.o_lora_rank as block size here?

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.

Fixed. The NS block boundary now uses o_lora_rank, matching the matrix used in the forward computation.

@weifengpy

Copy link
Copy Markdown
Contributor

thanks for the PR! this is indeed a gap. following are from AI review. I care about 1 a lot, as it's numeric correctness and why we do DistMuon

 **1. Newton-Schulz should see the same matrix boundaries as the forward**
  
  Kimi runs one Newton-Schulz per logical matrix the forward uses, and splits fused weights with `BlockShard` (RFC #4692, #4840),
  including the no-RoPE/RoPE split inside each head. This recipe only splits `wq_b`, and only per head. File references below are
  in `torchtitan/models/deepseek_v4/`.

  - `attention.wq_b`: the forward splits each head into q_nope and q_rope (`attention.py:377`). Please use `BlockShard(dim=0,
  block_sizes=(head_dim - rope_head_dim, rope_head_dim))` instead of `(head_dim,)`, so each head becomes two matrices.
  - `attention.wkv`: the forward splits it into kv_nope and kv_rope (`attention.py:383`), but it is computed as one matrix
  (`Owned`). Please use the same `(head_dim - rope_head_dim, rope_head_dim)` blocks.
  - `attention.wo_a`: the forward views it as `n_groups` independent matrices (`attention.py:439`), but the block size is the full
  height, so Newton-Schulz runs on all groups stacked together. Please use `(o_lora_rank,)`, as @shuhuayu suggested.
  - `hc_attn_pre.hc_fn` and `hc_ffn_pre.hc_fn`: the output is split into pre (sigmoid), post (2 * sigmoid) and comb (Sinkhorn)
  (`mhc.py:44`). These are three different projections, so please use `(hc_mult, hc_mult, hc_mult * hc_mult)` instead of `Owned`.
  - CSA `attention.compressor.wkv`: the rows are two halves, one for the previous group's overlap candidates and one for the
  current group (`compressor.py:98`). Each half is no-RoPE followed by RoPE (`compressor.py:192`). That is four matrices, so
  please use `(head_dim - rope_head_dim, rope_head_dim)` blocks instead of `Owned`.
  - CSA `attention.compressor.wgate`: the same previous/current halves, so `(head_dim,)` blocks.
  - HCA `attention.compressor_128.*`: not on Muon at all today, as @shuhuayu noted. Its `wkv` should get the no-RoPE/RoPE split,
  and `wgate` is one matrix.

  The other Muon layouts match Kimi: `wq_a`, `wo_b`, the router gate, shared experts, routed experts, the MTP `e_proj`/`h_proj`,
  and `hc_head.hc_fn`. Please also extend the unit test to check these block sizes. Today it only checks `wq_b`.

  **2. Other gaps compared with Kimi**

  - **Seed checkpoints break.** Seed checkpoint creation skips `parallelize`, so DistMuon gets plain tensors and fails with
  `TypeError: DistMuon requires DTensor parameters`. The same path works with the old AdamW optimizer. Kimi has
  `kimi_k2_5_debugmodel_seed_checkpoint`, which swaps in AdamW. Please add the same for DeepSeek-V4.
  - **Muon vs AdamW choices.** Kimi keeps biases, embeddings and degenerate matrices on AdamW, and explains each choice in a
  comment. `compressor.ape` is an additive bias on the gate logits, not a linear map, so it should probably stay on AdamW. Please
  also add a comment explaining why the indexer stays on AdamW.
  - **TP guard.** Kimi K3 only rejects TP when DistMuon is in use. This recipe rejects TP > 1 unconditionally, so DeepSeek-V4
  can't run TP even with AdamW. Please gate it like K3, and keep the existing FSDP+TP+EP integration test with AdamW.
  - **CP.** Kimi K3 declares both `dp_shard` and `dp_shard_cp` in every layout. #5191 fixed exactly this optimizer-init failure.
  This recipe declares only `dp_shard`, so it would fail the same way under CP.
  - **PP.** Kimi has a DistMuon PP+FSDP+EP integration test and documents what PP needs. Is PP expected to work for DeepSeek-V4
  with DistMuon?
  - **Buckets.** Kimi pairs MoE layers into one bucket to amortize collective launches. This recipe uses two buckets per layer,
  about twice as many (87 vs about 45 for flash). Not blocking, but worth matching.
  - **Numerics.** Kimi K3 (#4596) was validated with deterministic runs from a shared seed checkpoint: FSDP4 twice, and FSDP4 vs
  FSDP4+EP4. Could you add a similar comparison? The 10-step smoke runs only show that loss goes down.
  - **Reuse.** `_per_expert_compute_layout` and `_align_dist_muon_expert_compute_layouts` are copied from `kimi_k2_7.py`. Please
  import them as `kimi_k3.py` does; that also picks up the `dp_shard_cp` axis.

@jiesihu
jiesihu force-pushed the feat/deepseek-v4-distmuon branch from 74ec0a1 to 652df03 Compare October 23, 2026 12:05
@jiesihu

jiesihu commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review. The changes and validation are summarized below:

  • Updated the NS layouts to follow the forward matrix boundaries, including wo_a, HC projections, and compressor projections. compressor_128 projections are included in Muon.
  • Leaving the indexer out of Muon was my mistake. Its linear projections now use Muon, with corresponding ComputeLayouts and test coverage. Additive ape parameters use AdamW.
  • Added the AdamW step-0 model-only seed checkpoint path. Creation and loading were verified on H800.
  • Kept the TP restriction specific to DistMuon and preserved the AdamW TP regression case.
  • Reused the Kimi expert-layout helpers and adopted its bucket grouping: layer 0 separately, followed by pairs of layers. In an Ascend 910B experiment with 4 experts, FSDP8 + EP4 + E-FSDP2, bucket merging reduced Muon optimizer time by 6.3%.
  • Added bucket coverage tests. The related CPU suite now passes 50 tests. A previously collected 8-NPU, 10-step comparison recorded identical loss and grad norm for original and paired buckets.
  • Added previously collected H800 50-step FSDP2 versus FSDP2 + EP2 numerical results. Loss and grad norm show numerical agreement, as illustrated in the PR description.

CP still requires model communication changes beyond layout definitions, so it remains deferred. PP is also outside the currently validated scope.

@jiesihu
jiesihu requested a review from shuhuayu October 26, 2026 00:29
@@ -0,0 +1,102 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.

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.

we can declare

per_expert = ComputeLayout(
    shardings_by_mesh_axis={
        "dp_shard": Shard(0),
        "dp_shard_cp": Shard(0),
        "ep": Shard(0),
        "edp_shard": Shard(0),
    },
    shard_order_by_tensor_dim={0: ("ep", "edp_shard")},
    compute_dtype=torch.bfloat16,
)

and remove both helper functions in this file and remove this file.

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.

Updated DeepSeek-V4 to use the suggested ComputeLayout directly and removed the new shared helper module.

_NSCoefficientSchedule = _NSCoefficients | tuple[_NSCoefficients, ...]
_FAST_NS: _NSCoefficients = (3.4445, -4.7750, 2.0315)
_STABLE_NS: _NSCoefficients = (2.0, -1.5, 0.5)
_DEFAULT_NS_COEFFICIENTS = (_FAST_NS,) * 8 + (_STABLE_NS,) * 2

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.

can you give some references on why we choose this sequence? if this is not well accepted in the community, can we just use the constant default triple.

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.

This follows the hybrid Newton–Schulz schedule in DeepSeek-V4, Section 2.4: 8 iterations with (3.4445, -4.7750, 2.0315), followed by 2 with (2.0, -1.5, 0.5). I'd suggest keeping this default to match the report. I've added the reference in the code.

assert muon_config.ns_coefficients == coefficients


def test_deepseek_v4_aligns_expert_layout_after_parallelism_change() -> None:

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.

remove after we remove the two helper functions.

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.

Removed the helper-specific test.

@shuhuayu

Copy link
Copy Markdown
Contributor

@jiesihu cool, can you rebase, there is a conflict for now.

@jiesihu
jiesihu requested a review from shuhuayu October 29, 2026 02:41
@jiesihu
jiesihu force-pushed the feat/deepseek-v4-distmuon branch from c68eb3f to 5f3a86d Compare October 29, 2026 02:49
@jiesihu jiesihu closed this Oct 29, 2026
@jiesihu

jiesihu commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

@jiesihu cool, can you rebase, there is a conflict for now.

Rebased onto the latest main and resolved the conflicts.

@jiesihu jiesihu reopened this Oct 29, 2026

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

thx, some final checks.



def deepseek_v4_debugmodel_fsdp2_tp2_ep2() -> Trainer.Config:
def deepseek_v4_debugmodel_fsdp4_ep4() -> Trainer.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.

i just realized this rename breaks the README’s smoke-test command, which still uses CONFIG=deepseek_v4_debugmodel_fsdp2_tp2_ep2, can we also update there?

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.

Updated the README smoke-test command to use deepseek_v4_debugmodel_fsdp4_ep4 and corrected the parallelism description.

Comment thread tests/integration_tests/models.py Outdated
return config


def deepseek_v4_debugmodel_seed_checkpoint() -> Trainer.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.

looks like this is not needed in this pr?

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.

Removed the seed-checkpoint config.

Comment thread tests/integration_tests/models.py Outdated
return config


def deepseek_v4_debugmodel_fsdp4() -> Trainer.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.

this is not needed since we have added fsdp4_ep4

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.

Removed the FSDP4-only config.

ns_coefficients: tuple[float, float, float] = (3.4445, -4.7750, 2.0315)
ns_coefficients: (
tuple[float, float, float] | tuple[tuple[float, float, float], ...]
) = (3.4445, -4.7750, 2.0315)

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.

is this commonly used, so put as default?

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.

yes, this is default from the original muon blog.

@shuhuayu

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @shuhuayu's task in 5m 12s —— View job


Approve -- please address the items before merging: the Newton-Schulz boundaries now match the forward pass. What's left is small cleanup (out-of-date PR description, recipe knobs nothing uses, config-time validation, TODO/PP guard). 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: Approve -- please address the items below before merging. The Newton-Schulz boundaries now match the forward pass, and the core change to dist_muon.py is small and correct. What's left is small cleanup: an out-of-date description, recipe knobs nothing uses, and config-time validation.

What this PR does. It switches the DeepSeek V4 recipes from AdamW to DistMuon + AdamW, with a ComputeLayout per Muon matrix. It also lets DistMuon take either one (a, b, c) triple or one triple per Newton-Schulz step, which is how the DeepSeek V4 report's 8 fast + 2 stable schedule is expressed.

Example.

# before: one triple reused for every step
DistMuon.Config(ns_coefficients=(3.4445, -4.775, 2.0315), ns_steps=5)
# after: a per-step schedule is also accepted; its length must equal ns_steps
DistMuon.Config(
    ns_coefficients=((3.4445, -4.775, 2.0315),) * 8 + ((2.0, -1.5, 0.5),) * 2,
    ns_steps=10,
)
# attention.wq_b: one Newton-Schulz per head -> one for [q_nope_h] and one for [q_rope_h]

Must fix

  1. The PR description doesn't match HEAD. It says the PR "shares expert-layout helpers with Kimi" (they were removed, and per_expert is now inlined). It says it adds "an AdamW step-0 seed checkpoint configuration" (removed at @shuhuayu's request). It reports "50 CPU unit tests" (the helper tests were removed and the bucket parametrization shrank). Please update the description, and note that deepseek_v4_debugmodel / deepseek_v4_mtp_debugmodel no longer support --checkpoint.create_seed_checkpoint out of the box. It fails with DistMuon requires DTensor parameters unless you swap in AdamW.
  2. torchtitan/components/optim/optimizer.py:199: @tianyu-l asked "is this commonly used, so put as default?" and it has no reply yet. My take: the hybrid schedule comes from the DeepSeek V4 report, so keeping the single triple as the DistMuon default and setting the schedule in the recipe is right. Please reply on the thread.
  3. torchtitan_recipes/tests/models/deepseek_v4.py:296: muon_ns_steps / muon_ns_coefficients are only used by a test. Hardcode the schedule instead (see inline).
  4. torchtitan/components/optim/optimizer.py:197: check that the schedule length equals ns_steps in Config.__post_init__, not after parallelize (see inline).
  5. torchtitan_recipes/tests/models/deepseek_v4.py:278: add the TODO(#3353) for TP that Kimi has, and explain why PP is gated when Kimi says DistMuon is PP-safe (see inline).

Should consider

  • tests/integration_tests/models.py:745: "requires real collectives" is contradicted by Kimi's DistMuon FSDP+EP test, which runs on Fake PG.
  • torchtitan/models/deepseek_v4/README.md:41: the Status section is out of date and doesn't list DistMuon's supported parallelisms.
  • torchtitan_recipes/tests/models/deepseek_v4.py:44: the same schedule type alias is defined in three places.
  • torchtitan/distributed/flex_shard/dist_muon.py:65: the tuple-only check is stricter than the old one and may reject list coefficients on resume (unverified).
Details

I checked the layouts against the forward pass:

  • wq_b/wkv split as [nope; rope]: attention.py:376,382.
  • wo_a split into o_lora_rank row groups: attention.py:438.
  • CSA compressor.wkv is coff=2 halves of head_dim, each [nope; rope]: flavors.py:147, compressor.py:110,192.
  • HCA compressor_128 has coff=1, so wgate is a single matrix.
  • Indexer wq_b is per index head with [nope; rope] (compressor.py:250). Its compressor always has overlap (flavors.py:185).

All of these match the BlockShard sizes. CP needs no recipe guard because DeepSeekV4Model.__init__ already raises when cp > 1 (model.py:261).

Not verified: GPU runs. I also couldn't check whether DCP round-trips nested tuples in param_groups.

Comment on lines +296 to +297
muon_ns_steps: int = 10,
muon_ns_coefficients: _NSCoefficientSchedule = _DEFAULT_NS_COEFFICIENTS,

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.

muon_ns_steps / muon_ns_coefficients are added to all four factories (debugmodel, mtp_debugmodel, flash, pro), but the only caller that passes them is test_deepseek_v4_recipe_configures_per_step_ns_coefficients, and that test just reads the values back. rules/config.md says to expose only options a verified recipe uses. The two arguments also have to agree with each other: deepseek_v4_debugmodel(muon_ns_steps=5) keeps the 10-entry default schedule and fails only when the optimizer is built.

Smallest fix: remove both arguments. In _dist_muon_optimizer, pass ns_coefficients=_DEFAULT_NS_COEFFICIENTS, ns_steps=len(_DEFAULT_NS_COEFFICIENTS), and delete that test. Anyone who wants a different schedule can still override the DistMuon.Config field.

Comment on lines +197 to 201
ns_coefficients: (
tuple[float, float, float] | tuple[tuple[float, float, float], ...]
) = (3.4445, -4.7750, 2.0315)
eps: float = 1e-7
ns_steps: int = 5

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 a per-step schedule, len(ns_coefficients) == ns_steps is now a config invariant. Today it is checked only in FlexShardDistMuon._validate_groups. That runs after model build and parallelize, and it raises a generic unsupported DistMuon group 0 that doesn't say which field is wrong. Please add a __post_init__ to this Config that raises ValueError(f"ns_coefficients has {len(...)} entries but ns_steps={self.ns_steps}") when a schedule is given, so the error comes at config time (rules/config.md, "Defaults and Validation").

Comment on lines +278 to +289
if (
self.parallelism.tensor_parallel_degree > 1
or self.parallelism.pipeline_parallel_degree > 1
) and any(
isinstance(config, DistMuon.Config)
for config in self.optim.optimizer.optimizers
):
raise ValueError(
"DeepSeek V4 DistMuon requires tensor_parallel_degree=1 and "
"pipeline_parallel_degree=1: TP _StridedShard and PP stage-local "
"parameter groups are not supported yet."
)

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.

Two things about this guard:

  1. TP is a known limitation that waits on an upstream fix. Kimi K2.7 and K3 put # TODO(#3353): Support TP-produced _StridedShard layouts in DistMuon. above the same guard. Please add that TODO here too.
  2. PP: Kimi K2.7 says "No PP gate: DistMuon is PP-safe" (kimi_k2_7.py:566), and its only stated precondition is that every stage owns at least one layer. The message here blames "PP stage-local parameter groups", which doesn't match that. What actually breaks for DeepSeek V4 under PP? Is it DistMuon, or is DeepSeek V4 PP not supported at all? If it's the model, say so in the message (and ideally reject PP in the model, not only in this recipe). If it's DistMuon, please point to the failure.

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.

dsv4 pp is not supported yet.

Comment on lines +745 to +746
# DistMuon optimizer-state redistribution requires real collectives.
use_real_pg=True,

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 reason doesn't hold in-repo: kimi_k2_5_muon_fsdp+ep runs DistMuon FSDP+EP on Fake PG (it is listed in fake_pg_model_tests in tests/unit_tests/cpu/test_integration_test_definitions.py). The existing DeepSeek V4 test needs a real PG because of sequence-parallel collective aliasing under TP. This config has TP=1, so that cause may not apply. Real-PG GPU capacity is the scarcer resource. Please try this test on Fake PG. If it really needs a real PG, replace the comment with the actual failure.

Comment on lines +41 to +42
The AdamW debug model has been smoke-tested with 4 GPUs using FSDP2, TP2, EP2,
and the `spmd_types` backend. The optional MTP path is available through

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 status is now out of date. No AdamW debug model is shipped in the recipes anymore: deepseek_v4_debugmodel is DistMuon + AdamW, and the AdamW FSDP2/TP2/EP2 variant exists only inside tests/integration_tests/models.py. The README also doesn't say that the DistMuon recipes reject TP and PP. Suggest one short "Supported parallelisms" note: DistMuon was verified with FSDP and EP (4 GPUs, FSDP2 vs FSDP2+EP2 numerics); TP and PP raise; CP is unsupported by the model; and TP needs the optimizer swapped for AdamW.

Comment on lines +44 to +45
_NSCoefficients = tuple[float, float, float]
_NSCoefficientSchedule = _NSCoefficients | tuple[_NSCoefficients, ...]

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 PR now spells the same schedule type three ways: the private aliases in dist_muon.py:59-60, these redefinitions here, and the inline union in optimizer.py:197-199. If you drop the recipe knobs (see the comment below), these aliases are no longer needed: _FAST_NS / _STABLE_NS can be plain tuples. Otherwise, make one public alias in dist_muon.py and reuse it here and in optimizer.py.


def _is_ns_coefficient_triple(coefficients: object) -> bool:
return (
isinstance(coefficients, tuple)

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.

The old check (len(coefficients) != 3 plus a numeric check) accepted any sequence. The new one requires tuple. _validate_groups also runs in _after_load_state_dict on the restored param_groups. So if checkpoint load or a config override gives back a list ([3.4445, -4.775, 2.0315]), resume now fails with unsupported DistMuon group 0 where it used to pass. Unverified whether DCP keeps these as tuples. Checking isinstance(..., Sequence) (excluding str) here and in _valid_ns_coefficients keeps the old behavior.

@shuhuayu

Copy link
Copy Markdown
Contributor

the claude's review is non-blocking, so would merge it.

@shuhuayu
shuhuayu merged commit 55797d6 into pytorch:main Oct 29, 2026
15 checks passed
fegin added a commit that referenced this pull request Oct 30, 2026
)

## Summary (human-written)

Merge conflicts from the previous PRs cause CI failing.
`disable_cuda_graph`->`disable_accelerator_graphs`

## Why
CPU Unit Test fails on main:
https://github.com/pytorch/torchtitan/actions/runs/40973844709/job/123796998693

#5353 renamed `training.disable_cuda_graphs` to
`training.disable_accelerator_graphs`. #4920 and #5556 landed after it
and still use the old name.
`TestShippedCpRecipes::test_every_cp_recipe_passes_the_gate` builds
`deepseek_v4_debugmodel_fsdp4_ep4` and fails:

AttributeError: 'TrainingConfig' object has no attribute
'disable_cuda_graphs'

`rl_grpo_deepseek_v3_debug_varlen` in `alphabet_sort.py` has the same
stale keyword. No CPU test builds it, but it raises `TypeError` when
run.

## What changed
- Mechanical rename in two places: `tests/integration_tests/models.py`
and `torchtitan_recipes/tests/rl/alphabet_sort.py`.

## Testing
- `git grep disable_cuda_graphs` returns nothing.
- Expect the CPU Unit Test job on this PR to pass
`test_every_cp_recipe_passes_the_gate`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests 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.

4 participants