Repository navigation
Add DistMuon support for DeepSeek V4 - #4920
Conversation
|
Hi @jiesihu! Thank you for your pull request and welcome to our community. Action RequiredIn 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. ProcessIn 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 If you have received this in error or have any questions, please contact us at [email protected]. Thanks! |
2240694 to
90cf2c8
Compare
90cf2c8 to
b301450
Compare
|
|
b301450 to
74ec0a1
Compare
|
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! |
|
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: |
There was a problem hiding this comment.
Heavily compressed attention uses attention.compressor_128 so it is not using muon as intended.
There was a problem hiding this comment.
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,), |
There was a problem hiding this comment.
should we use attention.o_lora_rank as block size here?
There was a problem hiding this comment.
Fixed. The NS block boundary now uses o_lora_rank, matching the matrix used in the forward computation.
|
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 |
74ec0a1 to
652df03
Compare
|
Thanks for the detailed review. The changes and validation are summarized below:
CP still requires model communication changes beyond layout definitions, so it remains deferred. PP is also outside the currently validated scope. |
| @@ -0,0 +1,102 @@ | |||
| # Copyright (c) Meta Platforms, Inc. and affiliates. | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
remove after we remove the two helper functions.
There was a problem hiding this comment.
Removed the helper-specific test.
|
@jiesihu cool, can you rebase, there is a conflict for now. |
c68eb3f to
5f3a86d
Compare
Rebased onto the latest main and resolved the conflicts. |
shuhuayu
left a comment
There was a problem hiding this comment.
thx, some final checks.
|
|
||
|
|
||
| def deepseek_v4_debugmodel_fsdp2_tp2_ep2() -> Trainer.Config: | ||
| def deepseek_v4_debugmodel_fsdp4_ep4() -> Trainer.Config: |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Updated the README smoke-test command to use deepseek_v4_debugmodel_fsdp4_ep4 and corrected the parallelism description.
| return config | ||
|
|
||
|
|
||
| def deepseek_v4_debugmodel_seed_checkpoint() -> Trainer.Config: |
There was a problem hiding this comment.
looks like this is not needed in this pr?
There was a problem hiding this comment.
Removed the seed-checkpoint config.
| return config | ||
|
|
||
|
|
||
| def deepseek_v4_debugmodel_fsdp4() -> Trainer.Config: |
There was a problem hiding this comment.
this is not needed since we have added fsdp4_ep4
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
is this commonly used, so put as default?
There was a problem hiding this comment.
yes, this is default from the original muon blog.
|
@claude review |
|
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. |
There was a problem hiding this comment.
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
- The PR description doesn't match HEAD. It says the PR "shares expert-layout helpers with Kimi" (they were removed, and
per_expertis 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 thatdeepseek_v4_debugmodel/deepseek_v4_mtp_debugmodelno longer support--checkpoint.create_seed_checkpointout of the box. It fails withDistMuon requires DTensor parametersunless you swap in AdamW. 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 theDistMuondefault and setting the schedule in the recipe is right. Please reply on the thread.torchtitan_recipes/tests/models/deepseek_v4.py:296:muon_ns_steps/muon_ns_coefficientsare only used by a test. Hardcode the schedule instead (see inline).torchtitan/components/optim/optimizer.py:197: check that the schedule length equalsns_stepsinConfig.__post_init__, not after parallelize (see inline).torchtitan_recipes/tests/models/deepseek_v4.py:278: add theTODO(#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/wkvsplit as[nope; rope]:attention.py:376,382.wo_asplit intoo_lora_rankrow groups:attention.py:438.- CSA
compressor.wkviscoff=2halves ofhead_dim, each[nope; rope]:flavors.py:147,compressor.py:110,192. - HCA
compressor_128hascoff=1, sowgateis a single matrix. - Indexer
wq_bis 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.
| muon_ns_steps: int = 10, | ||
| muon_ns_coefficients: _NSCoefficientSchedule = _DEFAULT_NS_COEFFICIENTS, |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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").
| 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." | ||
| ) |
There was a problem hiding this comment.
Two things about this guard:
- 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. - 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.
There was a problem hiding this comment.
dsv4 pp is not supported yet.
| # DistMuon optimizer-state redistribution requires real collectives. | ||
| use_real_pg=True, |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
| _NSCoefficients = tuple[float, float, float] | ||
| _NSCoefficientSchedule = _NSCoefficients | tuple[_NSCoefficients, ...] |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
|
the claude's review is non-blocking, so would merge it. |
) ## 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`.
Summary
Add a mixed DistMuon + AdamW recipe for DeepSeek-V4, adapting the model-specific layouts from torchtitan-npu to upstream TorchTitan.
ComputeLayoutmappings for attention, indexer, experts, router, HC, compressor, and MTP parameters.muon_ns_stepsandmuon_ns_coefficients.Related Muon optimization: #5633.
Validation
pyreflychecks passed.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.