Repository navigation
[DistMuon] variable-sized BlockShard to shard inside a q/kv head - #4840
Merged
Merged
Conversation
[ghstack-poisoned] Kimi MLA weights pack distinct logical projections into the same parameter. Extend BlockShard to assign and optimize those projections independently: wkv_a uses (512, 64) for the shared KV latent and RoPE key, while query and key/value head weights split into their component projections. block_sizes is a nonempty tuple of positive integers whose pattern repeats along the sharded dimension. Prefix boundaries define complete blocks and redistribution routes, including owners that start inside a repetition and reordered DeviceMesh ranks. Ranks can own different numbers of rows. Resolve parameter layouts once and build explicit shape/stride/offset matrix views after compute ownership is known. Each pattern position becomes a local matrix batch. Rebuild the views after checkpoint loading; dense Muon helpers consume ordinary tensors and views while orchestration handles redistribution. Parameter normalization and group bookkeeping retain their original behavior. Use one global reference shape per parameter: a complete block-size repetition for BlockShard, or the original matrix shape otherwise. Scale each independent matrix direction by its shape factor relative to that reference, skipping the multiply when the factors match. The original final update applies the LR adjusted for the reference shape. Owned and uniform-block paths retain their original arithmetic, while variable blocks receive their own effective LR. Validation: - CPU FlexShard: all 8 existing tests passed. - GPU DistMuon: both existing tests passed with their original exact numerical comparisons and mocked-update expectations. The only test changes are the two required block_sizes API edits. - Temporary numerical probes: 240 legacy-layout cases with three steps each matched original directions, parameters, and momentum bitwise in FP32/BF16 across all four LR settings. Fourteen distributed variable-block cases passed, including reordered meshes and checkpoint resume; maximum parameter error against independent torch.optim.Muon was 5.96e-8 and momentum was exact. - Tests and probes used PyTorch 2.15.0a0+git494947c on B200 GPUs. - A fresh 30-step Kimi run with legacy layouts matched base 6c2dadb bitwise for loss, grad_norm, and both optimizer learning-rate schedules, using FSDP=4/EP=4, --debug.seed=42, and --debug.deterministic on the same runtime. - A 30-step Kimi run with variable layouts and the same deterministic settings completed with finite loss and grad_norm; loss decreased from 8.10280514 to 3.10400152. This is a short training check, not a convergence study. - pre-commit run --all-files passed, including type checking. Co-authored-by: JavaZeroo <[email protected]>
weifengpy
marked this pull request as ready for review
September 23, 2026 02:49
weifengpy
requested review from
fegin,
tianyu-l,
wconstab and
wwwjn
as code owners
September 23, 2026 02:49
shuhuayu
approved these changes
Sep 23, 2026
tianyu-l
approved these changes
Sep 23, 2026
meta-codesync Bot
pushed a commit
to meta-pytorch/flex_shard
that referenced
this pull request
Oct 8, 2026
…anges Summary: Recent TorchTitan syncs changed several APIs that `experiments/fb/flex_shard` depends on, so `flex_shard_tests` now fails at import time (`unittest` `loadTestsFromName` ImportError). This diff moves the fb FlexShard code to the new APIs, fixes the EP>1 DistMuon break from #4419, and ports the Qwen3 recipe. - pytorch/torchtitan#4904 (optimizer config refactor): `build_dist_muon(...)` is replaced by the `DistMuon(...)` class, which takes the same arguments. `comm_free_adapter.build_local_dist_muon` now constructs `DistMuon` directly. - pytorch/torchtitan#4660 (`components.optimizer` -> `components.optim`, `Trainer.Config.optim`): - Imports now come from `torchtitan.components.optim`. - DSV3 Muon configs set `config.optim.optimizer`. - `FlexShardDistMuonOptimizers` accepts the new `enable_cuda_graph` kwarg. It raises if the flag is set, the same way upstream `OptimizersContainer` rejects optimizers that can't be captured. - `_log_optimizer` now takes a pattern string. - pytorch/torchtitan#4617: `ParallelismConfig` now lives in `torchtitan.config.parallelism`. - pytorch/torchtitan#4905: - `ParallelDims` is now `ParallelismContext`, and the `parallel_dims=` kwarg is now `parallelism_context=`. - `get_spmd_context(...)` is replaced by `parallelism_context.activate_spmd()`. - The `efsdp` mesh axis is now `edp_shard`. This also covers the `partition_rank_axis_name` passed to the DistMuon bucket planner. - Tests build the context with `ParallelismContext.from_config(config, DistributedTopology(world_size=...))`. - pytorch/torchtitan#4840: `BlockShard(block_size=R)` is now `BlockShard(block_sizes=(R,))`. - pytorch/torchtitan#4878: the DSV3 `model_registry` now requires `enable_sp`. The FlexShard wrapper passes `enable_sp=False`. FlexShard rejects TP, and `False` keeps the shared-expert `w2` as a plain `Linear`, as it was before #4878. - pytorch/torchtitan#4419 (EP without DTensor): `Module._parallelize` now leaves EP-sharded routed experts as plain local `nn.Parameter` shards. It records their layouts in each module's `_sharding_config` instead of returning DTensors. With EP>1, DistMuon failed with "Partitioned block parameters must be DTensors", and `dtensor_to_global_layout` no longer found anything to declare. - flex_shard `dist_muon/placement.py` and `storage_layout.py` now read the FlexShard `GlobalLayout` contract (`get_global_layout`) instead of DTensor placements. `get_dim0_block_partitions` no longer takes `partition_axis_name`. - The new `experiments/fb/flex_shard/spmd_layouts.py` `declare_spmd_global_layouts(model, mesh)` collects `_sharding_config.state_shardings` and declares them through `spmd_types_to_global_layout`. The DSV3 recipes and tests call it where they used to call `dtensor_to_global_layout`. - EP>1 configs now need `training.disable_cuda_graphs`: upstream config validation rejects CUDA graphs with the all-to-all token dispatcher. `flex_shard_deepseek_v3_debug_muon` sets EP=2 after construction, so it skipped that check and would fail when launched from the CLI. It now disables CUDA graphs, as upstream EP configs do. - Qwen3 recipe port. It was broken before these syncs, by `protocols.model_spec`, `FusedQKVLinear`, `components.metrics`, `tools.logging`, `default_adamw` and `set_spmd_backend`. - It follows the DSV3 pattern: `FlexShardQwen3Model(Qwen3Model)` with `Config.muon_pattern`, and `parallelize()` runs `parallelize_qwen3_muon` under `activate_spmd()`. - Configs are rebuilt on the current `Trainer.Config` fields with the same hyperparameters. - Q/K/V BlockShard plans use the fused `QKVLinear.wqkv`: one `head_dim`-row matrix per Q/K/V head. - `parallelize_qwen3_muon` uses `dp_shard`, always calls `_parallelize` (as DSV3 does), and declares the EP layouts. - DSV3 `test_debug_muon_train_step` now disables autograd multithreading, as upstream `init_distributed` does. The SPMD mesh is thread-local, and FSDPTest skips `init_distributed`. So selective-AC recompute ran on an autograd device thread with no mesh set, the MoE token dispatch skipped EP there, and backward failed in `torch._grouped_mm` with "matrix batch sizes have to match". The upstream Trainer is not affected: the DSV3 debug model with EP=2 + SAC trains normally. The `comm_free_adapter` change is the same as the one in D122391176, the auto-generated Test Blame fix. This diff also covers the other breakages in fb/flex_shard. The DistMuon tests (DSV3 `test_shard0_owned_mixed` and `test_debug_muon_train_step`, and Qwen3 `test_debug_muon_train_step`) now get past every API break. They still fail on the fused `w13` weights, which the next diff (D122443668) fixes. Reviewed By: weifengpy Differential Revision: D122692766 Pull Request resolved: #50
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
land #4799 again into
mainbranch this time.re-implementation of BlockShard with variable size: #4693
Co-authored-by: JavaZeroo [email protected]