Skip to content

[kimi k3] Switch K3 recipe to per-head DistMuon - #4596

Merged
shuhuayu merged 2 commits into
pytorch:mainfrom
JavaZeroo:feat/k3-per-head-muon
Sep 23, 2026
Merged

shuhuayu merged 2 commits into
pytorch:mainfrom
JavaZeroo:feat/k3-per-head-muon

Conversation

@JavaZeroo

Copy link
Copy Markdown
Contributor

Summary

Implements the "Add Per-Head Muon" item from the Kimi K3 tracking issue #4272: kimi_k3_debugmodel now trains with DistMuon instead of AdamW, with per-head compute layouts for both attention variants.

cc @tianyu-l @shuhuayu @weifengpy

Design

MLA layers (layers.N.attention): Support K3's extra output gate projection (num_heads * v_head_dim rows) gets a per-value-head layout.
Note K3 has no q_lora_rank branch: wq_a/wq_b are unconditional, unlike DeepSeek-V3.

KDA layers (layers.N.delta_attention, 3/4 of all layers): q_proj/k_proj/v_proj/forget_b/output_gate are per-head with block_size=head_dim. forget_a and output_proj stay whole-matrix.

LatentMoE: routed experts reuse _per_expert_compute_layout from K2.7; router gate, shared experts, and the latent routed_down/routed_up stay whole-matrix.

Stay on AdamW: beta (its rows are per-head scalars — per-head compute would degenerate to block_size=1 and Newton-Schulz on rank-1 rows is meaningless), A_log/dt_bias/depthwise convs (non-matrix), all norms, the single-row [1, D] residual
projections, embeddings, LM head, and the vision tower.

Numerics

Validated on 4x RTX 5090. All runs share one model-only seed checkpoint, --debug.seed=42 --debug.deterministic, 200 steps, 8192 tokens/step:

  • FSDP4, twice
  • FSDP4 vs FSDP4+EP4

Loss curves:

k3_muon_only_loss

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 11, 2026
@tianyu-l
tianyu-l requested a review from shuhuayu September 11, 2026 08:01
@JavaZeroo
JavaZeroo force-pushed the feat/k3-per-head-muon branch 2 times, most recently from 731cdbf to 6b11d80 Compare September 14, 2026 11:11

@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 for the pr. had some questions and comments.



@dataclass(frozen=True, slots=True)
class MatrixBatchLayout:

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 think using owned + MatrixBatchLayout is actually solving the problem of strided blocks for BlockShard, maybe we should add this @weifengpy @tianyu-l?

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.

commented in #4596 (comment) that i prefer BlockShard + shard_order_by_tensor_dim over adding new tricks to MatrixBatchLayout

@JavaZeroo

JavaZeroo commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author

thx for the pr. had some questions and comments.

thx for the review. I've create a issue #4692 with the overall plan.

This PR is now main + #4693 (segments) + the K3 recipe commit, no longer stacked on #4531. Merge order: it should land after #4676 and #4643, since the recipe then switches w13 to Shard(0) over the [2, F, D] batch and follows the new routed-expert layout. Also renamed to "Switch K3 recipe".

@WhoisZihan

Copy link
Copy Markdown
Contributor

thx for the review. two things first: I've create a issue #4692 with the overall plan, and this pr is based on #4531 so some of the comments below land on Zihan's commit rather than mine. after #4531 merges I'll rebase main again.

Thanks for quoting, I think they are changing the default fused w13 linear layout from interleaved to stacked in #4676 , so MatrixBatchLayout is removed in my pr for now. Is there specific situation when we need to shard an owned parameter? If so, maybe we should add it back.

@JavaZeroo
JavaZeroo force-pushed the feat/k3-per-head-muon branch from 6b11d80 to f3371be Compare September 15, 2026 13:13
@JavaZeroo

Copy link
Copy Markdown
Contributor Author

thx for the review. two things first: I've create a issue #4692 with the overall plan, and this pr is based on #4531 so some of the comments below land on Zihan's commit rather than mine. after #4531 merges I'll rebase main again.

Thanks for quoting, I think they are changing the default fused w13 linear layout from interleaved to stacked in #4676 , so MatrixBatchLayout is removed in my pr for now. Is there specific situation when we need to shard an owned parameter? If so, maybe we should add it back.

Thanks for the explanation. I think removing MatrixBatchLayout is ok for me, since w13 becomes a native [2, F, D] batch after #4676 anyway.
For your question, I don't think we need to shard an owned parameter. What K3 needs is a bit different: splitting each BlockShard block into contiguous matrices with different row counts, for MLA wq_b / wkv_a / wkv_b. It only touches BlockShard, so I can create another PR for this new split strategy and we can handle it separately.

@JavaZeroo
JavaZeroo force-pushed the feat/k3-per-head-muon branch 2 times, most recently from 3064574 to 1d6209b Compare September 15, 2026 14:30
@JavaZeroo JavaZeroo changed the title [kimi k3] Switch debugmodel recipe to per-head DistMuon [kimi k3] Switch K3 recipe to per-head DistMuon Sep 15, 2026
class _MatrixBatchView:
matrix_rows: int
matrix_columns: int
num_rows_per_segment: tuple[int, ...] | None = 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.

we don't have this in Kimi 2.7 . how come Kimi 3 need this? If it's strided BlockShard, can we use shard_order_by_tensor_dim to address this?

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 am thinking of using strided blockshard to handle the fused w13 layout like physical [6, 2]:

  row 0: gate_0
  row 1: up_0
  row 2: gate_1
  row 3: up_1
  row 4: gate_2
  row 5: up_2

not sure we can use shard_order_by_tensor_dim to address this since iiuc 1) it only accepts shard 2) it is two layer reordering, but here w13 is an interleaved fusion.

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 are moving away from interleaved #4596 (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.

i see, let's wait the upstream changes get landed in this case.

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.

thanks for explaining. [2, F, D] with 2 being leading dim make things easy

@weifengpy weifengpy Sep 16, 2026 •

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 am thinking of using strided blockshard to handle the fused w13 layout like physical [6, 2]:

  row 0: gate_0
  row 1: up_0
  row 2: gate_1
  row 3: up_1
  row 4: gate_2
  row 5: up_2

not sure we can

btw, this is exactly the definition of w1 and w3 being _StridedShard on 1d mesh (just mention it for fun)

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.

how about copy kernel efficiency? #4676 (comment)

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

done with review: I care about whether changes in distributed/flex_shard are true gaps, thus i have the comment above

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

pytorch-bot Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

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

tianyu-l pushed a commit that referenced this pull request Sep 16, 2026
…pe (#4755)

## Summary

Prerequisite split out of #4596, as requested there:
`_dist_muon_optimizer` in the Kimi K2.7 recipe took a single `lr` for
both the DistMuon and the AdamW parameter groups. This changes it to
`muon_lr` and `adamw_lr` so a recipe can tune them independently. All
four recipes (`kimi_k2_5_debugmodel`, `moonlight_16b_a3b`, `kimi_k2_5`,
`kimi_vl_a3b`) keep passing the same value to both, so no configuration
changes. The K3 recipe in #4596 uses the same signature.

## Test plan

- Built all four K2.7 recipes and checked both param groups still get
the recipe's lr.
- `pre-commit run` and pyrefly clean on the file.
tianyu-l pushed a commit that referenced this pull request Sep 16, 2026
## Summary

Split out of #4596 as requested there. The K2.7 DistMuon recipe built
`compute_sharding_by_fqn`, the per-layer FQN lists and the bucket FQNs
through three intermediate tuples and comprehensions; this collapses
them into one loop over layers and one loop over bucket groups, and
drops `bucket_fqns`. Pure refactor. K2.7 is the only recipe on main that
builds DistMuon buckets; the K3 recipe in #4596 is written the same way.

## Test plan

- Dumped `bucket_configs`, `compute_sharding_by_fqn` and the param
groups for `kimi_k2_5_debugmodel`, `moonlight_16b_a3b`, `kimi_k2_5` and
`kimi_vl_a3b` on `main` and on this branch: identical.
- `pre-commit run` and pyrefly clean on the file.
@JavaZeroo
JavaZeroo force-pushed the feat/k3-per-head-muon branch 5 times, most recently from a2d94d8 to 9405936 Compare September 21, 2026 05:59
@shuhuayu shuhuayu mentioned this pull request Sep 21, 2026
14 of 18 tasks
@shuhuayu
shuhuayu force-pushed the feat/k3-per-head-muon branch 2 times, most recently from 0df5669 to fbd096a Compare September 23, 2026 05:03
kimi_k3_debugmodel trains with DistMuon instead of AdamW. Matrix
parameters use per-head compute layouts for both attention variants; the
fused MLA projections are split into one Newton-Schulz matrix per logical
projection, following Kimi's implementation (pytorch#4692):

- wq_b: per head [q_nope; q_rope] via num_rows_per_segment
- wkv_a: one block [kv_latent; k_rope]
- wkv_b: per head [k_nope; v]

KDA q/k/v/forget_b/output_gate are per head with block_size=head_dim;
forget_a and output_proj are whole-matrix. Routed experts reuse the K2.7
per-expert layout. Dense feed_forward and shared_experts w13 stay
whole-matrix until the stacked layout from pytorch#4676 lands, then switch to
Shard(0) compute over the [2, F, D] batch.

AdamW keeps the non-matrix parameters (norms, embeddings, LM head, A_log,
dt_bias, depthwise convs), the per-head-scalar beta rows, the single-row
residual projections, and the vision tower.
kimi_k3_debugmodel now defaults to DistMuon, which rejects TP-produced
_StridedShard storage, so the fsdp2 x tp2 x ep2 test replaces the
optimizer with AdamW the same way kimi_k2_5_debugmodel_seed_checkpoint
does. Add kimi_k3_mm_muon (fsdp2 x ep2) to cover the default optimizer.
@shuhuayu
shuhuayu force-pushed the feat/k3-per-head-muon branch from fbd096a to 7198b25 Compare September 23, 2026 05:17
@shuhuayu

Copy link
Copy Markdown
Contributor

Hi @JavaZeroo, I rebased it on #4799 and used most of you changes, thx.

@shuhuayu
shuhuayu merged commit b641030 into pytorch:main Sep 23, 2026
14 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Sep 23, 2026
from torchtitan_recipes.tests import _set_spmd_typechecking


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

why still keep kimi_k3_debugmodel_mm ? in other words, why not update it in place to use muon?

@shuhuayu shuhuayu Sep 23, 2026 •

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 for tp is not supported yet, and we want to keep this test for tp composibility. will merge these two test once the distmuon tp pr lands.

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.

got you. thanks

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

Status: Done

Development

Successfully merging this pull request may close these issues.

5 participants