Skip to content

[DistMuon] Split fused gated linear shape for correct NS computation - #4531

Closed
WhoisZihan wants to merge 4 commits into
pytorch:mainfrom
WhoisZihan:bugfix/split-gated-linear-muon-ns-shape
Closed

WhoisZihan wants to merge 4 commits into
pytorch:mainfrom
WhoisZihan:bugfix/split-gated-linear-muon-ns-shape

Conversation

@WhoisZihan

@WhoisZihan WhoisZihan commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Fix DistMuon NS shape for fused gated linear parameters. Fused SwiGLU stores w13.weight in the interleaved layout

[gate_0, up_0, gate_1, up_1, ...]

These rows represent two independent logical matrices and should not be orthogonalized as a single matrix, which leads to incorrect result for muon and post-NS normalization used in normuon.

To correctly identify fused gate and layout, an explicit matrix_layout metadata is added to ComputeLayout. Before muon computation, fused gate/up rows are converted into an independent matrix batch, so that we can apply NS orthogonalization independently. The interleaved layout is restored afterwards.

Before:
fused w13 -> Newton-Schulz(fused matrix)

After:
fused w13
  -> split gate/up
  -> Newton-Schulz(gate)
  -> Newton-Schulz(up)
  -> restore fused layout

The default standard matrix layout is unchanged

@rakkit

rakkit commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

can you add/test FusedQKVLinear as well?
It would be even better to make it optional so one can also have per-head muon out-of-box

@WhoisZihan

WhoisZihan commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor Author

@rakkit That's good advice. The new implementation introduces MatrixBatchLayout to DistMuon to represent cases where one stored parameter contains multiple logical matrices, so that packed parameters can be interpreted as independent logical matrices during NS computation.

@dataclass(frozen=True, slots=True)
class MatrixBatchLayout:
    """Interpret a flat 2D tensor as a batch of Muon matrices.

    ``matrix_rows`` is required for ``Owned`` compute and optional with
    ``BlockShard``, where it can be derived from the block size. When
    ``num_interleaved_matrices`` is greater than one, each storage group has
    shape ``[matrix_rows, num_interleaved_matrices, columns]``.
    """

    matrix_rows: int | None = None
    num_interleaved_matrices: int = 1
flowchart LR
    A["Parameter gradient<br/>same shape as parameter"] --> B{"ComputeLayout"}

    B -->|"Owned()"| C["Gather complete tensor<br/>to one compute owner"]
    B -->|"BlockShard(dim=0,<br/>block_size=storage_group_rows)"| D["Distribute complete storage groups<br/>without splitting matrix boundaries"]

    C --> E{"MatrixBatchLayout?"}
    D --> E

    E -->|"None"| F["Owned: entire tensor is one matrix<br/>BlockShard: each block is one matrix"]
    E -->|"Non-interleaved"| G["View as<br/>[num_matrices, R, C]"]
    E -->|"Interleaved, F > 1"| H["View storage as<br/>[G, R, F, C]"]
    H --> I["Permute view to<br/>[G, F, R, C]"]

    F --> J["Logical matrix batch"]
    G --> J
    I --> J

    J --> K["Newton-Schulz independently<br/>over the last two dimensions"]
    K --> L["Write through logical view strides"]
    L --> M["Original storage layout preserved"]
    M --> N["Reshard and apply Muon update"]

    O["Configuration examples"] --> P["Non-interleaved per-head QKV<br/>BlockShard block_size=head_dim<br/>matrix_batch omitted"]
    O --> Q["Interleaved fused gate/up<br/>block_size=2*R when BlockShard<br/>num_interleaved_matrices=2"]
    O --> S["Owned matrix batch<br/>matrix_rows must be explicit"]
Loading

The implementation supports concatenated matrices, interleaved fused projections, and per-head weights. Interleaved layouts use a zero-copy permuted view, and the computed direction is written back through the view strides to preserve the original storage layout.

  • For BlockShard:
    • For an interleaved layout, matrix_batch must explicitly specify num_interleaved_matrices.
    • For a non-interleaved layout, matrix_batch can be omitted because matrix_rows is inferred from BlockShard.block_size, with num_interleaved_matrices = 1. For example, BlockShard(dim=0, block_size=head_dim) performs Muon independently per head.
  • For Owned, matrix_batch.matrix_rows must be explicitly specified when the tensor should be interpreted as multiple matrices.
Fused w13 storage (interleaved)
┌──────────┬──────────┬──────────┬──────────┐
│ gate r0  │ up r0    │ gate r1  │ up r1    │ ...
└──────────┴──────────┴──────────┴──────────┘
                         │ zero-copy view + permute
                         ▼
              ┌─────────────────────┐
              │ Matrix 0: gate [R,C]│ ── NS independently
              ├─────────────────────┤
              │ Matrix 1: up   [R,C]│ ── NS independently
              └─────────────────────┘
                         │ copy_ through view strides
                         ▼
                 Original interleaved storage

Model integration

Kimi’s DistMuon configuration now recognizes fused SwiGLU w13 parameters after overrides, registers them in the appropriate optimizer buckets, and treats gate/up as two independent matrices.

Since only Kimi uses DistMuon at the moment, I did not add e2e tests for other models that uses QKV fusion. But these cases are covered in unit tests.

The coverage includes fused gate/up layouts, per-head fused QKV across MQA/GQA/MHA, configuration idempotency, and a successful two-GPU Kimi FSDP+EP end-to-end run.

@weifengpy

Copy link
Copy Markdown
Contributor

@anijain2305 @tianyu-l is this PR the same or different to the swiglue weight fusion chat yesterday?

@anijain2305

anijain2305 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

@anijain2305 @tianyu-l is this PR the same or different to the swiglue weight fusion chat yesterday?

It could be related. Some thoughts

  • Today with fused w13, the rows are interleaved as mentioned in the description. My PR to make FusedFeedForward the default Make fused gate-up projection the default #4535 will also keep the fused w13 in the same layout. So, this PR should still work as-is even with the Make fused gate-up projection the default #4535 landed.
  • Even if, hypothetically, we made w13 laid out w1 and then w3 (not interleaved), we would still need this PR to break the w13 into separate w1 and w3 for muon. The original reason why w13 (and also fused qkv) interleaves is to facilitate TP.

Allow Muon to treat packed parameter storage as independent logical matrices,
including concatenated blocks, interleaved fused projections, and per-head
weights. Preserve the logical view through Newton-Schulz computation and write
results back through the original storage strides.
@WhoisZihan
WhoisZihan force-pushed the bugfix/split-gated-linear-muon-ns-shape branch from 7680f61 to 3a195a7 Compare September 14, 2026 03:21
@WhoisZihan

Copy link
Copy Markdown
Contributor Author

Rebased onto the latest main after #4535 landed and updated the configuration registry accordingly, other parts remains unchanged.

Since dense FeedForward now uses an interleaved w13 parameter by default, the Kimi DistMuon configuration directly assigns MatrixBatchLayout to w13. Unit tests are also updated to use the new FeedForward and QKVLinear APIs.

@tianyu-l

Copy link
Copy Markdown
Contributor

@WhoisZihan thanks for the PR!

I believe interleaved layout is less natural than stacked layout

  • blockwise quantization changes
  • not consistent with the MoE which is stacked
  • less intuitive for muon and in general

We are making that change in #4676. Could you adapt? cc @anijain2305

@WhoisZihan

Copy link
Copy Markdown
Contributor Author

We are making that change in #4676. Could you adapt? cc @anijain2305

@tianyu-l Makes sense. Since #4676 changes the linear layout from interleaved to stacked, the MatrixBatchLayout is not needed anymore, and is removed. Also, w13 is now represented directly as a batch-first [2, F, D] parameter. Extend Owned compute to accept batch-first 3D tensors and account for every matrix in owner load balancing.

Though I wonder is it necessary to unflatten the Linear parameter first, then perform flatten in forward? What is the benefit compare to directly double the out_features?

As for #4677 , seem the interleave still happens in num_heads level instead of head_dim, so the PR should still work with BlockShard(dim=0, block_size=head_dim).

NOTE. the latest commit depends on #4676, I've managed to rebase locally and run some tests, but it might better wait for it to get merged.

JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Sep 15, 2026
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 follow
pytorch#4531 and stay whole-matrix until the stacked layout from pytorch#4676 lands.

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.
JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Sep 15, 2026
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 follow
pytorch#4531 and stay whole-matrix until the stacked layout from pytorch#4676 lands.

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

Copy link
Copy Markdown
Contributor

@WhoisZihan Thanks for your patience as we make several changes around the fused matrices. You have gotten the right picture that for Linear, we will stack the weights, and for QKV, they will still be interleaved. So we need different Muon handling for the two. Lets wait for the PRs to be merged. I am hopeful that they could be merged this week.

@weifengpy

Copy link
Copy Markdown
Contributor

@WhoisZihan I added you as co-author for the same w13, w2 fix: #4811

the delta is mainly

  • S1 storage sharding [2, F, D]
  • S0 optimizer compute sharding [2, F, D], instead of owned

this is more aligned with other parts of DistMuon, per-expert, per-head sharding at the right boundary

Screenshot 2026-09-21 at 12 15 48 AM

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

see above

@WhoisZihan

Copy link
Copy Markdown
Contributor Author

@WhoisZihan I added you as co-author for the same w13, w2 fix: #4811

the delta is mainly

  • S1 storage sharding [2, F, D]
  • S0 optimizer compute sharding [2, F, D], instead of owned

this is more aligned with other parts of DistMuon, per-expert, per-head sharding at the right boundary

@weifengpy Awesome, thanks! I'll try rebasing onto main after it gets merged, and see if there is still anything missing. Looks most of changes of this pr have been absorbed into the new PR.

The only thing left is for _estimate_muon_compute_cost to support 3D shape. I can continue with this PR or start a new one.

weifengpy added a commit that referenced this pull request Sep 21, 2026
…#4811)

w13 didn't get any fqn match after splitting w123 into w13 and w2. this
PR fixes it:
  * #4535
  * https://github.com/pytorch/torchtitan/pull/4676/changes#r4058499709
* same problem first raised in
#4531 by @WhoisZihan

the next follow up is adding validation prevent future cases like above
in optimizer init: #4816


Co-authored-by: Zihan Yang <[email protected]>

Co-authored-by: Zihan Yang <[email protected]>
@shuhuayu

Copy link
Copy Markdown
Contributor

The only thing left is for _estimate_muon_compute_cost to support 3D shape. I can continue with this PR or start a new one.

Cool, let's close this pr and use a new pr for that.

@shuhuayu shuhuayu closed this Sep 21, 2026
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Sep 21, 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.

[Bug][DistMuon] split fused gated linear weights before NS computation

6 participants