Skip to content

[DistMuon] Split BlockShard blocks into matrix segments - #4693

Closed
JavaZeroo wants to merge 7 commits into
pytorch:mainfrom
JavaZeroo:feat/dist-muon-segments
Closed

JavaZeroo wants to merge 7 commits into
pytorch:mainfrom
JavaZeroo:feat/dist-muon-segments

Conversation

@JavaZeroo

@JavaZeroo JavaZeroo commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Part 1 of #4692. MLA fuses several projections into one parameter with different row counts per piece: wq_b is per head [q_nope; q_rope], wkv_b per head [k_nope; v], wkv_a one block [kv_latent; k_rope]. Kimi runs Newton-Schulz per logical projection, but BlockShard can only cut equal-sized blocks, so there is no way to express split([nope, v]) today.

This lets BlockShard.block_size be a tuple: a block made of contiguous matrices with different row counts. The block is still sum(block_size) rows and is never split between ranks; the pieces only tell DistMuon where one matrix ends and the next begins.

ComputeLayout(
    shardings_by_mesh_axis={"dp_shard": BlockShard(dim=0, block_size=(nope, v))},
)
  • Transport is unchanged: BlockShard still moves whole blocks of nope + v rows, so the redistribution plan does not know about the pieces. Making each piece its own unit would let a rank's local rows start mid-head and break the [M, R, C] batched view.
  • At compute time each segment is a narrowed [M, rows_i, C] view of the block batch; NS runs once per segment and writes back through the view.
  • Segments have different shapes, so the aspect-ratio lr adjustment (match_rms_adamw etc.) is applied per segment inside _compute_update. It cannot be done in _apply_update because the storage shard that applies the update may not hold complete blocks.
  • An integer block_size behaves exactly as before.

Only BlockShard is touched, so this is independent of #4531 and of the w13 layout change in #4676.

The second commit switches the Kimi K2.7 recipe to it: wq / wq_b per head (128, 64), wkv_b per head (128, 128), wkv_a one block (512, 64). Today K2.7 runs NS on the whole [k_nope; v] block per head and on the whole wkv_a matrix, which couples projections that Kimi's implementation keeps separate (https://kexue.fm/archives/11126/comment-page-2#comment-28601). This changes K2.7 numerics on purpose; there are no loss goldens for the K2.5 Muon recipes, only the functionality integration tests. The K3 recipe (#4596) uses the same layouts.

Test plan

  • tests/unit_tests/gpu/flex_shard/test_dist_muon.py::test_segments_match_independent_matrix_updates: 2-GPU, one block per rank with block_size=(3, 2), compared against torch.optim.Muon on the four split matrices with match_rms_adamw. I only have one GPU locally, so this one relies on CI.
  • Single-GPU check with the K2.5 debugmodel shapes (wq [3072, 256], wkv_a [576, 256], wkv_b [4096, 512]): DistMuon step matches per-matrix torch.optim.Muon to 5e-10; against whole-block NS the difference is 3e-4 to 4e-4 on updates of 7e-4.
  • Single-GPU check with the K3 debugmodel shapes (wq_b [1536, 512], wkv_a [288, 1024], wkv_b [2048, 256]) and an unequal-head-dim variant: DistMuon step matches per-matrix torch.optim.Muon to 4.7e-10 for wkv_a / wkv_b; wq_b differs by 7e-6, which is bf16 bmm-vs-mm accumulation order in NS (with a single block it is 1.2e-10), not layout.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 15, 2026
@tianyu-l
tianyu-l requested a review from shuhuayu September 15, 2026 20:12
@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.

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

but BlockShard can only cut equal-sized blocks, so there is no way to express split([nope, v]) today

I am checking motivation from PR description - what do you think of improving blockshard to express non-uniform length? segments in ComputeLayout feels like a downsteam bandit because of blockshard contraints

@JavaZeroo

Copy link
Copy Markdown
Contributor Author

but BlockShard can only cut equal-sized blocks, so there is no way to express split([nope, v]) today

I am checking motivation from PR description - what do you think of improving blockshard to express non-uniform length? segments in ComputeLayout feels like a downsteam bandit because of blockshard contraints

sure, BlockShard.block_size now accepts a tuple and ComputeLayout.num_rows_per_segment is removed

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

this PR is very valuable! i didn't know we have incorrect numerics. will spend more time to figure out what's needed to land unequal-sized BlockShard

Image

@weifengpy

Copy link
Copy Markdown
Contributor

@JavaZeroo

Copy link
Copy Markdown
Contributor Author

this PR is very valuable! i didn't know we have incorrect numerics. will spend more time to figure out what's needed to land unequal-sized BlockShard

Image

Thanks for the confirmation. I spent a lot of time last year on Muon, mostly on numerical correctness and distributed performance in another training stack, so I'd like to keep contributing in torchtitan.

weifengpy added a commit that referenced this pull request Sep 19, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. Let BlockShard(block_sizes=(512, 64)) assign the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition. Matching matrices use zero-copy
strided batches and receive their own shape-dependent learning-rate
adjustment. Keep _MatrixBatchView unchanged for uniform matrices.

Express per-block adjustments relative to a common application multiplier
to preserve FP32 update rounding when matrix ownership changes.

Validation:

- CPU FlexShard suite: 22 tests and 16 subtests passed.
- GPU DistMuon suite: 7 tests passed, including checkpoint resume,
  variable block boundaries, reversed meshes, and exact update equivalence
  with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- Before the API rename, Kimi PP=2/FSDP=2/EP=2 on 4 GPUs passed
  a 10-step deterministic smoke test.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: 1f1f339
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 19, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. Let BlockShard(block_sizes=(512, 64)) assign the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition. Matching matrices use zero-copy
strided batches and receive their own shape-dependent learning-rate
adjustment. Keep _MatrixBatchView unchanged for uniform matrices.

Express per-block adjustments relative to a common application multiplier
to preserve FP32 update rounding when matrix ownership changes.

Validation:

- CPU FlexShard suite: 22 tests and 16 subtests passed.
- GPU DistMuon suite: 7 tests passed, including checkpoint resume,
  variable block boundaries, reversed meshes, and exact update equivalence
  with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- Before the API rename, Kimi PP=2/FSDP=2/EP=2 on 4 GPUs passed
  a 10-step deterministic smoke test.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: b0a6e8d
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 19, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. Let BlockShard(block_sizes=(512, 64)) assign the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition. Matching matrices use zero-copy
strided batches and receive their own shape-dependent learning-rate
adjustment. Keep _MatrixBatchView unchanged for uniform matrices.

Express per-block adjustments relative to a common application multiplier
to preserve FP32 update rounding when matrix ownership changes.

Validation:

- CPU FlexShard suite: 22 tests and 16 subtests passed.
- GPU DistMuon suite: 7 tests passed, including checkpoint resume,
  variable block boundaries, reversed meshes, and exact update equivalence
  with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- Before the API rename, Kimi PP=2/FSDP=2/EP=2 on 4 GPUs passed
  a 10-step deterministic smoke test.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: f8341a2
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 19, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. BlockShard(block_sizes=(512, 64)) assigns the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition and reordered DeviceMesh ranks.

Uniform and variable blocks share one zero-copy matrix-batch iterator and
Muon update loop. Planning uses the parameter shape and block boundaries;
there is no separate matrix-view descriptor or derived compute shape.
Each matrix receives its own shape-dependent learning-rate adjustment.
Express adjustments relative to a common application multiplier to preserve
FP32 update rounding when matrix ownership changes.

Validation:

- CPU FlexShard suite: 23 tests and 16 subtests passed, including uniform
  matrix views with nonzero storage offsets and exact writeback boundaries.
- GPU DistMuon suite: 8 tests passed, including checkpoint resume,
  multiple uniform matrices per rank, variable block boundaries, reversed
  meshes, and exact update equivalence with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: f733e94
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 20, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. BlockShard(block_sizes=(512, 64)) assigns the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition and reordered DeviceMesh ranks.

Uniform and variable blocks share logical matrix-batch views of the full
parameter. Each view describes an ordinary strided [M, R, C] tensor;
uniform blocks are equivalent to unflattening the row dimension. Planning
narrows these views to each rank's logical compute rows. The Muon update
loop consumes prepared views without block indices or ownership arithmetic.
Each matrix receives its own shape-dependent learning-rate adjustment.
Express adjustments relative to a common application multiplier to preserve
FP32 update rounding when matrix ownership changes.

Validation:

- CPU FlexShard suite: 25 tests and 16 subtests passed, including full-to-local
  view equivalence, nonzero storage offsets, writeback boundaries, and
  rejection of views that would escape a supplied tensor slice.
- GPU DistMuon suite: 8 tests passed, including checkpoint resume,
  multiple uniform matrices per rank, variable block boundaries, reversed
  meshes, and exact update equivalence with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: 0b00450
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 20, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. BlockShard(block_sizes=(512, 64)) assigns the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition and reordered DeviceMesh ranks.

Uniform and variable blocks share logical matrix-batch views of the full
parameter. Each view describes an ordinary strided [M, R, C] tensor;
uniform blocks are equivalent to unflattening the row dimension. Planning
narrows these views to each rank's logical compute rows. The Muon update
loop consumes prepared views without block indices or ownership arithmetic.
Each matrix receives its own shape-dependent learning-rate adjustment.
Express adjustments relative to a common application multiplier to preserve
FP32 update rounding when matrix ownership changes.

Validation:

- CPU FlexShard suite: 26 tests and 16 subtests passed, including full-to-local
  view equivalence, nonzero storage offsets, writeback boundaries, rejection
  of views escaping a supplied tensor slice, and block geometry retained
  on size-one mesh axes.
- GPU DistMuon suite: 8 tests passed, including checkpoint resume,
  multiple uniform matrices per rank, variable block boundaries, reversed
  meshes, and exact update equivalence with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: cbd0a6f
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 20, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. BlockShard(block_sizes=(512, 64)) assigns the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition and reordered DeviceMesh ranks.

Uniform and variable blocks share logical matrix-batch views of the full
parameter. Each view describes an ordinary strided [M, R, C] tensor;
uniform blocks are equivalent to unflattening the row dimension. Planning
narrows these views to each rank's logical compute rows. The Muon update
loop consumes prepared views without block indices or ownership arithmetic.
Each matrix receives its own shape-dependent learning-rate adjustment.
Express adjustments relative to a common application multiplier to preserve
FP32 update rounding when matrix ownership changes.

Validation:

- CPU FlexShard suite: 26 tests and 16 subtests passed, including full-to-local
  view equivalence, nonzero storage offsets, writeback boundaries, rejection
  of views escaping a supplied tensor slice, and block geometry retained
  on size-one mesh axes.
- GPU DistMuon suite: 8 tests passed, including checkpoint resume,
  multiple uniform matrices per rank, variable block boundaries, reversed
  meshes, and exact update equivalence with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: 7988f52
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 20, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. BlockShard(block_sizes=(512, 64)) assigns the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition and reordered DeviceMesh ranks.

Uniform and variable blocks share logical matrix-batch views of the full
parameter. Each view describes an ordinary strided [M, R, C] tensor;
uniform blocks are equivalent to unflattening the row dimension. Planning
narrows these views to each rank's logical compute rows. The Muon update
loop consumes prepared views without block indices or ownership arithmetic.
Each matrix receives its own shape-dependent learning-rate adjustment.
Express adjustments relative to a common application multiplier to preserve
FP32 update rounding when matrix ownership changes.

Validation:

- CPU FlexShard suite: 26 tests and 16 subtests passed, including full-to-local
  view equivalence, nonzero storage offsets, writeback boundaries, rejection
  of views escaping a supplied tensor slice, and block geometry retained
  on size-one mesh axes.
- GPU DistMuon suite: 8 tests passed, including checkpoint resume,
  multiple uniform matrices per rank, variable block boundaries, reversed
  meshes, and exact update equivalence with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: 8060621
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 20, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. BlockShard(block_sizes=(512, 64)) assigns the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition and reordered DeviceMesh ranks.

Uniform and variable blocks share logical matrix-batch views of the full
parameter, represented by shape, element strides, and a relative offset.
The row-packed layout builder narrows these views to each rank's logical
compute rows; uniform blocks are equivalent to unflattening the row dimension.
The Muon update
loop consumes prepared views without block indices or ownership arithmetic.
Each matrix receives its own shape-dependent learning-rate adjustment.
Express adjustments relative to a common application multiplier to preserve
FP32 update rounding when matrix ownership changes.

Validation:

- CPU FlexShard suite: 28 tests and 16 subtests passed, including full-to-local
  view equivalence, nonzero storage offsets, writeback boundaries, rejection
  of views escaping a supplied tensor slice, noncontiguous inputs and zero-width
  matrices, and block geometry retained on size-one mesh axes.
- GPU DistMuon suite: 8 tests passed, including checkpoint resume,
  multiple uniform matrices per rank, variable block boundaries, reversed
  meshes, and exact update equivalence with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: d78b1a9
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 20, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. BlockShard(block_sizes=(512, 64)) assigns the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition and reordered DeviceMesh ranks.

Uniform and variable blocks use views represented by shape, element strides,
and a relative offset. Planning binds these views to each rank's actual compute
partition, including EP subgroup shapes. Native 2D and 3D tensors receive
identity views that preserve their rank; packed matrices receive localized
projection views, and empty owners have no views. The update loop consumes
all views uniformly. Uniform blocks remain equivalent to unflattening the
row dimension. Each matrix receives its own shape-dependent learning-rate
adjustment, expressed relative to a common application multiplier to preserve
FP32 update rounding when matrix ownership changes.

Validation:

- CPU FlexShard suite: 31 tests and 16 subtests passed, including native
  identity views, empty owners, mixed buckets, EP subgroup shapes, consistent
  bound records, full-to-local view equivalence, storage offsets and writeback
  boundaries. Rejection checks cover slice escapes, noncontiguous inputs,
  zero-width matrices, and invalid block sizes.
- GPU DistMuon suite: 8 tests passed, including checkpoint resume,
  multiple uniform matrices per rank, variable block boundaries, reversed
  meshes, and exact update equivalence with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: 2a82763
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 20, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. BlockShard(block_sizes=(512, 64)) assigns the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition and reordered DeviceMesh ranks.

Uniform and variable blocks use views represented by shape, element strides,
and a relative offset. Planning binds these views to each rank's actual compute
partition, including EP subgroup shapes. Native 2D and 3D tensors receive
identity views that preserve their rank; packed matrices receive localized
projection views, and empty owners have no views. The update loop consumes
all views uniformly. Uniform blocks remain equivalent to unflattening the
row dimension. Each matrix receives its own shape-dependent learning-rate
adjustment, expressed relative to a common application multiplier to preserve
FP32 update rounding when matrix ownership changes.

Validation:

- CPU FlexShard suite: 31 tests and 16 subtests passed, including native
  identity views, empty owners, mixed buckets, EP subgroup shapes, consistent
  bound records, full-to-local view equivalence, storage offsets and writeback
  boundaries. Rejection checks cover slice escapes, noncontiguous inputs,
  zero-width matrices, and invalid block sizes.
- GPU DistMuon suite: 8 tests passed, including checkpoint resume,
  multiple uniform matrices per rank, variable block boundaries, reversed
  meshes, and exact update equivalence with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: 8c9cf09
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 20, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. BlockShard(block_sizes=(512, 64)) assigns the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition and reordered DeviceMesh ranks.

Uniform and variable blocks use views represented by shape, element strides,
and a relative offset. Planning binds these views to each rank's actual compute
partition, including EP subgroup shapes. Native 2D and 3D tensors receive
identity views that preserve their rank; packed matrices receive localized
projection views, and empty owners have no views. The update loop consumes
all views uniformly. Uniform blocks remain equivalent to unflattening the
row dimension. Each matrix receives its own shape-dependent learning-rate
adjustment, expressed relative to a common application multiplier to preserve
FP32 update rounding when matrix ownership changes.

Muon math stays independent of sharding: dist_muon.py consumes ordinary
tensors, explicit views, and an already-resolved learning-rate reference
shape. The private resharding adapter owns DTensor state, layout resolution,
view localization, and runtime callbacks. The public build_dist_muon entry
point and optimizer state_dict format remain unchanged.

Validation:

- CPU FlexShard suite: 32 tests and 16 subtests passed, including native
  identity views, empty owners, mixed buckets, EP subgroup shapes, consistent
  bound records, full-to-local view equivalence, storage offsets and writeback
  boundaries. Rejection checks cover slice escapes, noncontiguous inputs,
  zero-width matrices, and invalid block sizes. A math-only test compares
  explicit tensor views against independent torch.optim.Muon updates.
- GPU DistMuon suite: 8 tests passed, including checkpoint resume,
  multiple uniform matrices per rank, variable block boundaries, reversed
  meshes, and exact update equivalence with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: d1fa61d
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 20, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. BlockShard(block_sizes=(512, 64)) assigns the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition and reordered DeviceMesh ranks.

Uniform and variable blocks use views represented by shape, element strides,
and a relative offset. Planning binds these views to each rank's actual compute
partition, including EP subgroup shapes. Native 2D and 3D tensors receive
identity views that preserve their rank; packed matrices receive localized
projection views, and empty owners have no views. The update loop consumes
all views uniformly. Uniform blocks remain equivalent to unflattening the
row dimension. Each matrix receives its own shape-dependent learning-rate
adjustment, expressed relative to a common application multiplier to preserve
FP32 update rounding when matrix ownership changes.

Muon math helpers consume ordinary tensors, explicit views, and an
already-resolved learning-rate reference shape. Optimizer orchestration in
dist_muon.py manages DTensor state, layout resolution, view localization,
and runtime callbacks. The math helpers do not inspect sharding placements.
The public build_dist_muon entry point and optimizer state_dict format
remain unchanged.

Validation:

- CPU FlexShard suite: 32 tests and 16 subtests passed, including native
  identity views, empty owners, mixed buckets, EP subgroup shapes, consistent
  bound records, full-to-local view equivalence, storage offsets and writeback
  boundaries. Rejection checks cover slice escapes, noncontiguous inputs,
  zero-width matrices, and invalid block sizes. A math-only test compares
  explicit tensor views against independent torch.optim.Muon updates.
- GPU DistMuon suite: 8 tests passed, including checkpoint resume,
  multiple uniform matrices per rank, variable block boundaries, reversed
  meshes, and exact update equivalence with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: da9d0bc
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 20, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. BlockShard(block_sizes=(512, 64)) assigns the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition and reordered DeviceMesh ranks.

Layout resolution validates block declarations and returns the compute
sharding used by planning, view construction, and LR-reference setup.

Uniform and variable blocks use views represented by shape, element strides,
and a relative offset. Planning binds these views to each rank's actual compute
partition, including EP subgroup shapes. Native 2D and 3D tensors receive
identity views that preserve their rank; packed matrices receive localized
projection views, and empty owners have no views. The update loop consumes
all views uniformly. Uniform blocks remain equivalent to unflattening the
row dimension. Each matrix receives its own shape-dependent learning-rate
adjustment, expressed relative to a common application multiplier to preserve
FP32 update rounding when matrix ownership changes.

Muon math helpers consume ordinary tensors, explicit views, and an
already-resolved learning-rate reference shape. Optimizer orchestration in
dist_muon.py manages DTensor state, layout resolution, view localization,
and runtime callbacks. The math helpers do not inspect sharding placements.
The public build_dist_muon entry point and optimizer state_dict format
remain unchanged.

Validation:

- CPU FlexShard suite: 34 tests and 23 subtests passed, covering block-layout
  validation, ownership and geometry (including unit axes and EP subgroups),
  view aliasing and bounds, and tensor-only math against independent Muon
  updates. Validation includes absent mesh axes, negative dimensions,
  inconsistent block patterns, empty/incomplete rows, and invalid storage.
- GPU DistMuon suite: 8 tests passed, including checkpoint resume,
  multiple uniform matrices per rank, variable block boundaries, reversed
  meshes, and exact update equivalence with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: 16422ae
Pull-Request: #4799
weifengpy added a commit that referenced this pull request Sep 20, 2026
Kimi MLA weights pack logical projections with different row counts into
one parameter. BlockShard(block_sizes=(512, 64)) assigns the two matrices
in wkv_a independently, instead of requiring one owner for all 576 rows.
Use the same per-projection rule for query and key/value head weights.

The block_sizes field is a nonempty tuple of positive integers, with
(R,) for uniform blocks. It replaces the block_size keyword and scalar
form. The tuple repeats independent block sizes along the sharded dimension.
Prefix offsets determine ownership and redistribution, including shards
that start midway through a repetition and reordered DeviceMesh ranks.

Layout resolution validates block declarations and returns the compute
sharding used by planning, view construction, and LR-reference setup.

Uniform and variable blocks use views represented by shape, element strides,
and a relative offset. For packed matrices, planning constructs each rank's
views directly from its compute shape, row-size pattern, and logical starting
row. Each pattern position remains a separate batch. Native 2D and 3D tensors
receive identity views that preserve their rank and EP subgroup shapes;
empty owners have no views. The update loop consumes all views uniformly.
Uniform blocks remain equivalent to unflattening the row dimension. Each matrix receives its own shape-dependent learning-rate
adjustment, expressed relative to a common application multiplier to preserve
FP32 update rounding when matrix ownership changes.

Muon math helpers consume ordinary tensors, explicit views, and an
already-resolved learning-rate reference shape. Optimizer orchestration in
dist_muon.py manages DTensor state, layout resolution, view construction,
and runtime callbacks. The math helpers do not inspect sharding placements.
The public build_dist_muon entry point and optimizer state_dict format
remain unchanged.

Validation:

- CPU FlexShard suite: 35 tests and 25 subtests passed, covering block-layout
  validation, ownership and geometry (including unit axes and EP subgroups),
  view aliasing, bounds and complete-matrix coverage, and tensor-only math
  against independent Muon updates. Validation includes absent mesh axes, negative dimensions,
  inconsistent block patterns, empty/incomplete rows, and invalid storage.
- GPU DistMuon suite: 8 tests passed, including checkpoint resume,
  multiple uniform matrices per rank, variable block boundaries, reversed
  meshes, and exact update equivalence with uniform blocks.
- Kimi debugmodel on 8 B200 GPUs, FSDP=8/EP=8, 10 training steps:
  loss and grad_norm exactly match PR #4693 at every step with
  --debug.seed=42 --debug.deterministic.
- pre-commit run --all-files passed.

Co-authored-by: JavaZeroo <[email protected]>
ghstack-source-id: a951a87
Pull-Request: #4799
Add ComputeLayout.num_rows_per_segment so one BlockShard block can hold
contiguous Muon matrices with different row counts, e.g. the per-head
[K_nope; V] stack of an MLA wkv_b projection or the single [latent; rope]
block of wkv_a. BlockShard still transports whole blocks, so redistribution
planning is unchanged; inside a block each segment gets its own
Newton-Schulz batch through a narrowed view and its own aspect-ratio
learning-rate adjustment, which is folded into the direction at compute
time because the storage shard that applies the update may not hold
complete blocks.

Adds CPU tests for the view, validation, and a two-GPU test comparing the
segmented update against torch.optim.Muon on the split matrices.
Use num_rows_per_segment on the Kimi K2.7 DistMuon recipe so Newton-Schulz
runs per logical projection, matching Kimi's implementation: wq / wq_b per
head [q_nope; q_rope], wkv_b per head [k_nope; v], wkv_a one block
[kv_latent; k_rope]. Transport is unchanged; wkv_a moves from Owned to a
single BlockShard block so its two segments can be split.
Address review: the segment description is a property of the block, so it
moves from ComputeLayout.num_rows_per_segment to BlockShard.block_size,
which now accepts a tuple such as (128, 64) for a per-head [K_nope; V]
stack. The block is still sum(block_size) rows and is never split, so
redistribution planning is unchanged; only DistMuon's Newton-Schulz view
reads the pieces. This drops the ComputeLayout field and the two checks
that tied it to BlockShard.

The Kimi K2.7 recipe and the two-GPU test use the tuple form.
Keep _apply_update, _apply_muon_update and _adjust_muon_learning_rate as
they are on main. _apply_update still adjusts the lr for the whole
block's shape; _compute_update rescales each piece's direction by
(piece ratio / block ratio) so every piece ends up with the adjustment of
its own shape. Also drop a redundant assert and a docstring example.
@JavaZeroo
JavaZeroo force-pushed the feat/dist-muon-segments branch from 5729ed9 to 81268da Compare September 21, 2026 05:59
@weifengpy

weifengpy commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

@JavaZeroo, I added you as co-author in #4799

Screenshot 2026-09-20 at 11 38 31 PM

@JavaZeroo

Copy link
Copy Markdown
Contributor Author

@JavaZeroo, I added you as co-author in #4799

Screenshot 2026-09-20 at 11 38 31 PM

Thanks for the co-author! I'll rebase onto your PR and continue with the remaining Muon work on top of it.

attention_shardings = {
**query_shardings,
"wkv_a": owned,
"wkv_a": kv_latent_and_rope,

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 helps splitting logical matrices, but all blockshard will place wkv_a on the first rank, since all heads share this tensor per layer. will have a load balancing problem.

@weifengpy

Copy link
Copy Markdown
Contributor
  • your PR still have extra things like scales each segment’s direction by segment_ratio / block_ratio. are you intersted in rebase?

I absorbed this change as well otherwise it breaks existing numeric test. that means the PR is fully absorbed. let me know if i still miss anything. hope the co-author PR help keep your contribution in record

direction_i *= s_i / s_ref
parameter.add_(direction, alpha=-(lr * s_ref))
Screenshot 2026-09-21 at 2 49 56 PM

weifengpy added a commit that referenced this pull request Sep 22, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* __->__ #4799

re-implementation of BlockShard with variable size:
#4693
* within a head, we have [no rope, rope]. it's critical to further split
the head

<img width="755" height="607" alt="Screenshot 2026-09-20 at 11 46 55 PM"
src="https://github.com/user-attachments/assets/a9e005c6-60e1-4f1b-8ae8-37d441bb3d21"
/>



Co-authored-by: JavaZeroo <[email protected]>

---------

Co-authored-by: JavaZeroo <[email protected]>
shuhuayu pushed a commit that referenced this pull request Sep 23, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* __->__ #4799

land #4799 again into `main`
branch this time.

re-implementation of BlockShard with variable size:
#4693
* within a head, we have [no rope, rope]. it's critical to further split
the head

<img width="755" height="607" alt="Screenshot 2026-09-20 at 11 46 55 PM"
src="https://github.com/user-attachments/assets/a9e005c6-60e1-4f1b-8ae8-37d441bb3d21"
/>



Co-authored-by: JavaZeroo <[email protected]>

---------

Co-authored-by: JavaZeroo <[email protected]>
@JavaZeroo JavaZeroo closed this Sep 24, 2026
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Sep 24, 2026
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.

3 participants