Repository navigation
[DistMuon] Support oversharded QKV heads - #4078
Conversation
[ghstack-poisoned]
[ghstack-poisoned]
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]
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]
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
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]
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
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
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
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
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
| 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 |
There was a problem hiding this comment.
Does it only supports 2D parameter? What happens if param is 2D but BlockShard has dim=1 -- does the code crash?
There was a problem hiding this comment.
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"
)
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
Does it imply that after dim 0, every dim should be contiguous in a block?
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
we can use regular Shard(0) for [num_heads, rows_per_head, in_features]
| 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 |
There was a problem hiding this comment.
would be good to add some more docstring and validation check, e.g. BlockShard currently only accepts 2D param
[ghstack-poisoned]
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
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
|
did follwing before landing
|
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
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
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
we have two ways to do per-head muon. This PR switch from option 1 to option 2
option 2 becomes cleaner and explicit, when handling FSDP2 Shard(0) oversharding QKV
Before:
After:
sanity check: