Skip to content

[DistMuon] Support oversharded QKV heads - #4078

Merged
weifengpy merged 56 commits into
mainfrom
gh/weifengpy/49/head
Aug 19, 2026
Merged

weifengpy merged 56 commits into
mainfrom
gh/weifengpy/49/head

Conversation

@weifengpy

@weifengpy weifengpy commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

we have two ways to do per-head muon. This PR switch from option 1 to option 2

  • option 1: storage sharding -> view [num_head * head_dim, hidden_dim] to [num_head, head_dim, hidden_dim] -> compute sharding. this treats view as a parameter prep outside of Muon core
  • option 2: storage sharding -> compute sharding -> view [num_head * head_dim, hidden_dim] to [num_head, head_dim, hidden_dim]. this treats view as part of Muon core

option 2 becomes cleaner and explicit, when handling FSDP2 Shard(0) oversharding QKV

  • storage sharding Shard(0) -> compute sharding BlockShard(block_size=head_dim) -> view [num_head * head_dim, hidden_dim] to [num_head, head_dim, hidden_dim]

Before:

  build_dist_muon(
      params,
      compute_sharding_by_fqn={
          wq_fqn: MuonComputeShardingConfig(
              compute_layout=wq_layout,
              compute_view=AttentionPerHeadComputeView(num_heads=num_heads),
          ),
          wo_fqn: MuonComputeShardingConfig(
              compute_layout=ComputeLayout(shardings_by_mesh_axis={"dp_shard": Owned()}),
          ),
      },
      bucket_configs=buckets,
  )

After:

  build_flex_shard_muon(
      params,
      compute_sharding_by_fqn={
          wq_fqn: ComputeLayout(
              shardings_by_mesh_axis={"dp_shard": BlockShard(dim=0, block_size=query_rows_per_head)},
          ),
          wo_fqn: ComputeLayout(
              shardings_by_mesh_axis={"dp_shard": Owned()},
          ),
      },
      bucket_configs=buckets,
  )

sanity check:

  • Loss and grad norm: bitwise identical across all 10 steps.
  • CUDA kernels, communication, memcpy, and memset ordering: identical on all 4 ranks.
  • Peak memory and allocator history: identical.

[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 6, 2026
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 7, 2026
Repartition split FSDP2 row shards into complete logical head matrices for Muon compute, then return the update to the original storage layout. Preserve the aligned local fast path and existing bucket overlap schedule.

Add split-head numerical parity, actual FSDP2, uneven-shard, state-dict, and mixed DP+EP coverage.

ghstack-source-id: fb33fff
Pull-Request: #4078
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 7, 2026
Repartition split FSDP2 row shards into complete logical head matrices for Muon compute, then return the update to the original storage layout. Preserve the aligned local fast path and existing bucket overlap schedule.

Add split-head numerical parity, actual FSDP2, uneven-shard, state-dict, and mixed DP+EP coverage.

ghstack-source-id: e81f905
Pull-Request: #4078
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 7, 2026
Repartition split FSDP2 row shards into complete logical head matrices for Muon compute, then return the update to the original storage layout. Preserve the aligned local fast path and existing bucket overlap schedule.

Add split-head numerical parity, actual FSDP2, uneven-shard, state-dict, and mixed DP+EP coverage.

ghstack-source-id: 6d26e4a
Pull-Request: #4078
weifengpy added a commit that referenced this pull request Aug 8, 2026
Repartition split FSDP2 row shards into complete logical head matrices for Muon compute, then return the update to the original storage layout. Preserve the aligned local fast path and existing bucket overlap schedule.

Add split-head numerical parity, actual FSDP2, uneven-shard, state-dict, and mixed DP+EP coverage.

ghstack-source-id: 6d26e4a
Pull-Request: #4078
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Aug 15, 2026
Add BlockShard as the compute-sharding contract for flat matrix batches. FlexShard redistributes the flat 2D tensor into complete fixed-size matrix blocks, and DistMuon applies the local 3D matrix-batch view immediately before Muon compute.

Kimi declares separate query and key/value block sizes. The one-axis planner supports Shard(0) or Replicate storage with replicated outer mesh axes, including storage shard boundaries that split a matrix. The numerical and checkpoint test exercises a 6/6-row storage split across three four-row matrices.

ghstack-source-id: 76d39b6

Pull-Request: pytorch/torchtitan#4078
@weifengpy weifengpy changed the title Support oversharded QKV heads in DistributedMuon [Kimi 2.7] Support oversharded QKV heads in DistributedMuon Aug 15, 2026
@weifengpy weifengpy changed the title [Kimi 2.7] Support oversharded QKV heads in DistributedMuon [DistMuon] Support oversharded QKV heads Aug 15, 2026
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 15, 2026
Add BlockShard as the compute-sharding contract for flat matrix batches. FlexShard redistributes the flat 2D tensor into complete fixed-size matrix blocks, and DistMuon applies the local 3D matrix-batch view immediately before Muon compute.

Kimi declares separate query and key/value block sizes. The one-axis planner supports Shard(0) or Replicate storage with replicated outer mesh axes, including storage shard boundaries that split a matrix. The numerical and checkpoint test exercises a 6/6-row storage split across three four-row matrices.

ghstack-source-id: 7ce6d76

Pull-Request: #4078
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 15, 2026
Add BlockShard as the compute-sharding contract for flat matrix batches. FlexShard redistributes the flat 2D tensor into complete fixed-size matrix blocks, and DistMuon applies the local 3D matrix-batch view immediately before Muon compute.

Kimi declares separate query and key/value block sizes. The one-axis planner supports Shard(0) or Replicate storage with replicated outer mesh axes, including storage shard boundaries that split a matrix. The numerical and checkpoint test exercises a 6/6-row storage split across three four-row matrices.

ghstack-source-id: 4164930

Pull-Request: #4078
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 15, 2026
Add BlockShard as the compute-sharding contract for flat matrix batches. FlexShard redistributes the flat 2D tensor into complete fixed-size matrix blocks, and DistMuon applies the local 3D matrix-batch view immediately before Muon compute.

Kimi declares separate query and key/value block sizes. The one-axis planner supports Shard(0) or Replicate storage with replicated outer mesh axes, including storage shard boundaries that split a matrix. The numerical and checkpoint test exercises a 6/6-row storage split across three four-row matrices.

ghstack-source-id: 4103cc3

Pull-Request: #4078
@weifengpy
weifengpy marked this pull request as ready for review August 15, 2026 13:25
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Aug 15, 2026
Add BlockShard as the compute-sharding contract for flat matrix batches. FlexShard redistributes the flat 2D tensor into complete fixed-size matrix blocks, and DistMuon applies the local 3D matrix-batch view immediately before Muon compute.

Kimi declares separate query and key/value block sizes. The one-axis planner supports Shard(0) or Replicate storage with replicated outer mesh axes, including storage shard boundaries that split a matrix. The numerical and checkpoint test exercises a 6/6-row storage split across three four-row matrices.

ghstack-source-id: 4164930

Pull-Request: pytorch/torchtitan#4078
@weifengpy
weifengpy requested a review from shuhuayu August 15, 2026 17:22
storage-to-compute transitions, and constructs the optimizer.
- `build_dist_muon` consumes optimizer-agnostic per-parameter `ComputeLayout`
values in `compute_sharding_by_fqn`. Within DistMuon,
`BlockShard(dim=0, block_size=R)` interprets a 2D parameter `[M * R, C]` as

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.

Does it only supports 2D parameter? What happens if param is 2D but BlockShard has dim=1 -- does the code crash?

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.

DistMuon math supoprt 2 cases

  • 2D param
  • 3D param with dim-0 being batch dim

if model has a native 3D param, that means batch dimension is already explicit, we should use Shard(0) in compute_sharding_by_fqn

for 2D with BlockShard dim=1, we raise following error at optimizer construction

if any(dim != 0 for dim in normalized_dims):
      raise ValueError(
          f"Muon parameter {fqn!r} matrix-batch BlockShard must shard "
          "tensor dimension 0"
      )

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.

would be good to add some more docstring and validation check, e.g. BlockShard currently only accepts 2D param

- `build_dist_muon` consumes optimizer-agnostic per-parameter `ComputeLayout`
values in `compute_sharding_by_fqn`. Within DistMuon,
`BlockShard(dim=0, block_size=R)` interprets a 2D parameter `[M * R, C]` as
`M` independent matrices `[M, R, C]`. FlexShard routes the flat 2D compute

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.

What happens if I have [M*R, C] but FSDP2 degree > M?

In some sense this is similar to EP S(0) and EFSDP S(0), but I worry that we don't have a way to detect that.

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.

uneven sharding is the similar across BlockShard(dim=0, block_size=R) and Shard(0). when FSDP2 degree > M, last k ranks receive zero-sized params

  # torchtitan/torchtitan/distributed/flex_shard/dist_muon.py:667
  return torch.Size(
      (
          compute_tensor_shape[0] // self.matrix_rows,
          self.matrix_rows,
          self.matrix_columns,
      )
  )

per_query_head = ComputeLayout(
shardings_by_mesh_axis={
MeshAxisName.DP_SHARD.value: BlockShard(
dim=0,

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.

Does it imply that after dim 0, every dim should be contiguous in a block?

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.

that's correct. we reject non-contiguous case

#  torchtitan/torchtitan/distributed/flex_shard/dist_muon.py:1266
  local = param.to_local()
  if (
      ...
      or not local.is_contiguous()
  ):
      _raise_unsupported_layout(fqn)

compute_layout=ComputeLayout(
shardings_by_mesh_axis={MeshAxisName.DP_SHARD.value: Shard(0)},
),
compute_view=AttentionPerHeadComputeView(

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 found the new UX to be much better.

Alternatively, I even wonder if we could change the definition of this folded dim to be unfolded, and only flatten them before fwd computation.
https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/gpt_oss/__init__.py#L106

But that's an intrusive change which seems this PR helps avoid.

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.

we can use regular Shard(0) for [num_heads, rows_per_head, in_features]

@weifengpy
weifengpy requested a review from tianyu-l August 18, 2026 20:51
storage-to-compute transitions, and constructs the optimizer.
- `build_dist_muon` consumes optimizer-agnostic per-parameter `ComputeLayout`
values in `compute_sharding_by_fqn`. Within DistMuon,
`BlockShard(dim=0, block_size=R)` interprets a 2D parameter `[M * R, C]` as

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.

would be good to add some more docstring and validation check, e.g. BlockShard currently only accepts 2D param

[ghstack-poisoned]
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 18, 2026
Add BlockShard as the compute-sharding contract for flat matrix batches. FlexShard redistributes the flat 2D tensor into complete fixed-size matrix blocks, and DistMuon applies the local 3D matrix-batch view immediately before Muon compute.

Kimi declares separate query and key/value block sizes. The one-axis planner supports Shard(0) or Replicate storage with replicated outer mesh axes, including storage shard boundaries that split a matrix. The numerical and checkpoint test exercises a 6/6-row storage split across three four-row matrices.

ghstack-source-id: 4103cc3

Pull-Request: #4078
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Aug 18, 2026
Add BlockShard as the compute-sharding contract for flat matrix batches. FlexShard redistributes the flat 2D tensor into complete fixed-size matrix blocks, and DistMuon applies the local 3D matrix-batch view immediately before Muon compute.

Kimi declares separate query and key/value block sizes. The one-axis planner supports Shard(0) or Replicate storage with replicated outer mesh axes, including storage shard boundaries that split a matrix. The numerical and checkpoint test exercises a 6/6-row storage split across three four-row matrices.

ghstack-source-id: d023a1e

Pull-Request: #4078
@weifengpy

Copy link
Copy Markdown
Contributor Author

did follwing before landing

  • added validation for 2D parameter with BlockShard
  • improved build_dist_muon docstring and README on 2D and contiguous requirements
  • docstring that batch-first 3D [M, R, C] parameters should use Shard(0)

@weifengpy
weifengpy merged commit 858b9e2 into main Aug 19, 2026
22 checks passed
weifengpy added a commit that referenced this pull request Aug 23, 2026
DistMuon issues one Newton-Schulz call per parameter. A layer with many
same-shaped sibling matrices therefore produces a long tail of small NS calls,
each with its own GEMM sequence and its own compute scratch.

Batch such siblings into a single NS call, while keeping momentum preparation
and the parameter update per parameter. Which parameters batch together is
declared, never inferred.

Declaring the group

A bucket is sized for communication, so it is deliberately heterogeneous:
coarse buckets amortize collective launch overhead. Local compute wants the
opposite. Rather than re-deriving a compute partition from FQN strings and
tensor shapes, `BucketConfig.batch_groups` declares it directly, as fnmatch
patterns resolved against the FQNs the bucket already matched.

* The bucket remains the communication unit. `batch_groups` is a separate axis
  that only subdivides the bucket's local work.
* Members must share a matrix shape, dtype, and device. `DistMuon` validates
  this at construction and raises, so a bad declaration fails loudly instead
  of silently degrading.
* A group whose patterns select nothing is a configuration error, not a
  silently unbatched parameter. A stale pattern cannot quietly cost
  performance at every step.
* Parameters that no group names execute one at a time, as before.

Executing the group

* `_LocalBucketExecutor` is a new seam on the redistribution runtime
  (`_plan_local_bucket` / `_execute_local_bucket`) so scratch for a batch is
  preplanned and eagerly reserved during construction; a steady-state step
  does not allocate.
* A declared group is still split into scratch-bounded runs at
  `_MAX_LOCAL_MATRIX_BATCH_BYTES` (256 MiB), because the bound is physical and
  local shard shapes are not known until construction. That split warns, so a
  silently chunked group is visible.
* No Newton-Schulz settings are re-checked at execution time.
  `_validate_groups` already requires exactly one parameter group, so every
  member reads the same ns_coefficients, ns_steps, and eps even if that group
  dict is mutated after construction.

Kimi

`config_registry` declares two groups per routed-experts bucket: w1_EFD and
w3_EFD share the [F, D] matrix shape, and w2_EDF is its transpose. Both groups
span the bucket's layer pair, so `layers.1-2.routed-experts` costs two batched
NS calls rather than one per projection per layer.

A future group could also absorb w2_EDF through a transposed view, since
Newton-Schulz commutes with transpose and match_rms_adamw is
transpose-invariant. Not implemented here, but the declaration can express it
where a shape-derived key could not.

Test

`pytest tests/unit_tests/flex_shard/test_dist_muon.py` -- 6 passed on 2 GPUs.

`test_matches_plain_muon_across_flat_checkpoint` exercises both paths in one
optimizer: an oversharded stack whose storage shard boundary splits a matrix
(unbatched redistribution path), plus two aligned siblings declared as one
batch group. Both are compared against per-matrix `torch.optim.Muon`
references across a flat checkpoint save/load.

`TestDistMuonDeclaredBatchGroups` covers the contract: batching happens only
where declared -- an identically shaped undeclared sibling stays unbatched --
and each rejection path raises.

Submitted standalone against main rather than in the original ghstack stack:
the lower entries #4078 and #4102 have landed, and this change does not depend
on the still-open #4077.

ghstack-source-id: 74987c6
Pull-Request: #4280
weifengpy added a commit that referenced this pull request Aug 23, 2026
DistMuon issues one Newton-Schulz call per parameter. A layer with many
same-shaped sibling matrices therefore produces a long tail of small NS calls,
each with its own GEMM sequence and its own compute scratch.

Batch such siblings into a single NS call, while keeping momentum preparation
and the parameter update per parameter. Which parameters batch together is
declared, never inferred.

Declaring the group

A bucket is sized for communication, so it is deliberately heterogeneous:
coarse buckets amortize collective launch overhead. Local compute wants the
opposite. Rather than re-deriving a compute partition from FQN strings and
tensor shapes, `BucketConfig.batch_groups` declares it directly, as fnmatch
patterns resolved against the FQNs the bucket already matched.

* The bucket remains the communication unit. `batch_groups` is a separate axis
  that only subdivides the bucket's local work.
* Members must share a matrix shape, dtype, and device. `DistMuon` validates
  this at construction and raises, so a bad declaration fails loudly instead
  of silently degrading.
* A group whose patterns select nothing is a configuration error, not a
  silently unbatched parameter. A stale pattern cannot quietly cost
  performance at every step.
* Parameters that no group names execute one at a time, as before.

Executing the group

* `_LocalBucketExecutor` is a new seam on the redistribution runtime
  (`_plan_local_bucket` / `_execute_local_bucket`) so scratch for a batch is
  preplanned and eagerly reserved during construction; a steady-state step
  does not allocate.
* A declared group is still split into scratch-bounded runs at
  `_MAX_LOCAL_MATRIX_BATCH_BYTES` (256 MiB), because the bound is physical and
  local shard shapes are not known until construction. That split warns, so a
  silently chunked group is visible.
* No Newton-Schulz settings are re-checked at execution time.
  `_validate_groups` already requires exactly one parameter group, so every
  member reads the same ns_coefficients, ns_steps, and eps even if that group
  dict is mutated after construction.

Kimi

`config_registry` declares two groups per routed-experts bucket: w1_EFD and
w3_EFD share the [F, D] matrix shape, and w2_EDF is its transpose. Both groups
span the bucket's layer pair, so `layers.1-2.routed-experts` costs two batched
NS calls rather than one per projection per layer.

A future group could also absorb w2_EDF through a transposed view, since
Newton-Schulz commutes with transpose and match_rms_adamw is
transpose-invariant. Not implemented here, but the declaration can express it
where a shape-derived key could not.

Test

`pytest tests/unit_tests/flex_shard/test_dist_muon.py` -- 6 passed on 2 GPUs.

`test_matches_plain_muon_across_flat_checkpoint` exercises both paths in one
optimizer: an oversharded stack whose storage shard boundary splits a matrix
(unbatched redistribution path), plus two aligned siblings declared as one
batch group. Both are compared against per-matrix `torch.optim.Muon`
references across a flat checkpoint save/load.

`TestDistMuonDeclaredBatchGroups` covers the contract: batching happens only
where declared -- an identically shaped undeclared sibling stays unbatched --
and each rejection path raises.

Submitted standalone against main rather than in the original ghstack stack:
the lower entries #4078 and #4102 have landed, and this change does not depend
on the still-open #4077.

ghstack-source-id: 74987c6
Pull-Request: #4280
weifengpy added a commit that referenced this pull request Aug 23, 2026
DistMuon issues one Newton-Schulz call per parameter. A layer with many
same-shaped sibling matrices therefore produces a long tail of small NS calls,
each with its own GEMM sequence and its own compute scratch.

Batch compatible local matrices into a single NS call, while keeping momentum
preparation and the parameter update per parameter.

Grouping

Two local tensors can share one call exactly when they agree on matrix shape,
dtype, and device, so that is the whole grouping key. Nothing is read from the
FQN and nothing is declared in configuration:

* A bucket already bounds a batch, because local work is executed one bucket at
  a time and members of different buckets are never resident together. That is
  a property of the runtime, not a naming convention, so bucketing stays a pure
  communication concern and compute batching follows from it.
* Muon settings need no key either. `_validate_groups` requires exactly one
  parameter group, so every layout reads the same ns_coefficients, ns_steps,
  and eps even if that group dict is mutated after construction.
* A layout whose local compute is a lone matrix has no batch dimension to
  concatenate along and runs by itself.

Execution

* `_LocalBucketExecutor` is a new seam on the redistribution runtime
  (`_plan_local_bucket` / `_execute_local_bucket`) so scratch for a batch is
  preplanned and eagerly reserved during construction; a steady-state step does
  not allocate.
* A group is split into runs bounded by `_MAX_LOCAL_MATRIX_BATCH_BYTES`
  (256 MiB), because the bound is physical and local shard shapes are unknown
  until construction. The split warns, so a chunked group is visible rather
  than silent.

Measured on moonlight_16b_a3b at a simulated world size of 32: 26 batched
Newton-Schulz calls become 9, covering 78 parameters, with reserved buffers
unchanged at 292 MiB.

Test

`pytest tests/unit_tests/flex_shard/test_dist_muon.py` -- 5 passed on 2 GPUs.

`test_matches_plain_muon_across_flat_checkpoint` exercises both paths in one
optimizer: an oversharded stack whose storage shard boundary splits a matrix
(unbatched redistribution path), plus two aligned siblings that share one
batched call. Both are compared against per-matrix `torch.optim.Muon`
references across a flat checkpoint save/load.

`TestDistMuonLocalMatrixBatching` covers the grouping rule directly:
compatible matrices batch across layers inside one bucket, incompatible matrix
shapes stay in separate batches, and a batch never spans two buckets.

Submitted standalone against main rather than in the original ghstack stack:
the lower entries #4078 and #4102 have landed, and this change does not depend
on the still-open #4077.

ghstack-source-id: 1f125d0
Pull-Request: #4280
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu 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.

2 participants