Repository navigation
[MoE] Make structured fused grouped-expert projection the default - #4643
Conversation
There was a problem hiding this comment.
looks great in general
suspicious as it didn't touch
- https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/fsdp.py#L296
- not sure if we need to adapt anything here https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/rl/models/vllm_wrapper.py#L564
There was a problem hiding this comment.
Updated the fallback FSDP placement for the structured parameter: when the E/FSDP degree exceeds the expert count, w13_E2FD now shards its hidden dimension with Shard(2), while w2_EDF retains Shard(1). The distributed tests now assert both placements in the EP=1 and EP>1 paths instead of checking only the first expert parameter. The placement map is derived from the actual expert parameters, so GPT-OSS keeps its existing model-specific layout; a new four-rank GPT-OSS regression test exercises that exact compatibility path. The vLLM state-dict path now also accounts for the removed projection axis: selecting gate or up from physical [E, 2, F, D] translates physical S(2) to logical S(1) for each exported [E, F, D] tensor. The helper preserves the other mesh-axis types and rejects selecting a sharded dimension. test_state_dict_layouts_include_split_expert_weights now asserts distinct physical and exported layouts. The full 8-GPU real-PG model and feature integration suites passed with these changes.
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.18.0) (oldest at bottom): * #4543 * #4542 * #4541 * #4623 * #4559 * #4591 * #4592 * #4540 * #4539 * #4643 * #4526 * #4546 * __->__ #4535 Use one physical w13 Linear config and parameter for dense feed-forward gate and up projections. Compose their initialization before module construction, configure activation implementations directly, and translate external gate/up checkpoint keys in model state-dict adapters.
6c3bd24 to
af67a49
Compare
Summary: Carry forward the reviewed implementation from pytorch/torchtitan#4552 while storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches DistMoE's native parameter layout and keeps the feature axis independently shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and returns `[R, 2, F]` before the existing activation. Logical initialization and checkpoint keys remain `w1_EFD`, `w2_EDF`, and `w3_EFD`. Routing, activation, grouped-GEMM, and dispatcher behavior are unchanged. This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain untouched. Test Plan: - `CUDA_VISIBLE_DEVICES='' python -m pytest -q tests/unit_tests/cpu/test_moe.py tests/unit_tests/cpu/test_inference_moe.py tests/unit_tests/cpu/test_quantization.py torchtitan/experiments/transformers_modeling_backend/tests/test_moe_parallelism.py tests/unit_tests/gpu/test_fused_swiglu_override.py -k 'not TestFusedSwiGLUGroupedExpertsNumerics and not TestFusedSwiGLUOverrideKernels'` (69 passed, 3 skipped, 6 deselected) - TorchTitan pre-commit hooks pass except for the existing unrelated Pyrefly error in `torchtitan/hf_datasets/multimodal/utils/video.py`. - GPU coverage compares the structured and interleaved layouts bitwise for output, input gradients, and weight gradients; execution requires a grouped-MM-capable CUDA build. ghstack-source-id: 85b0f87 Pull-Request: pytorch/torchtitan#4643
af67a49 to
dd03f6f
Compare
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
[ghstack-poisoned]
[ghstack-poisoned]
Summary: Carry forward the reviewed implementation from pytorch/torchtitan#4552 while storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches DistMoE's native parameter layout and keeps the feature axis independently shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and returns `[R, 2, F]` before the existing activation. Logical initialization and checkpoint keys remain `w1_EFD`, `w2_EDF`, and `w3_EFD`. Routing, activation, grouped-GEMM, and dispatcher behavior are unchanged. The physical fusion intentionally changes seeded random initialization order, so the affected real-PG integration goldens are refreshed; checkpoint-loaded weights retain their logical values. Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts native `[..., rows, columns]` parameters, matching the existing Newton-Schulz implementation, and its expert redistribution test exercises the production `[E, 2, F, D]` layout without adding another test case. This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain untouched. Test Plan: - `python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py` (2 passed) - `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py` (4 passed) - `CUDA_VISIBLE_DEVICES='' python -m pytest -q tests/unit_tests/cpu/test_moe.py tests/unit_tests/cpu/test_inference_moe.py tests/unit_tests/cpu/test_quantization.py torchtitan/experiments/transformers_modeling_backend/tests/test_moe_parallelism.py tests/unit_tests/gpu/test_fused_swiglu_override.py -k 'not TestFusedSwiGLUGroupedExpertsNumerics and not TestFusedSwiGLUOverrideKernels'` (69 passed, 3 skipped, 6 deselected) - TorchTitan formatting, flake8, pydoclint, codespell, and link checks passed; Pyrefly reports one existing unrelated optional-`av` diagnostic in `torchtitan/hf_datasets/multimodal/utils/video.py`. - The real-PG A10G model suite produced the refreshed 10-step loss and gradient-norm goldens. ghstack-source-id: ae440ac Pull Request resolved: pytorch/torchtitan#4643
Summary: Carry forward the reviewed implementation from pytorch/torchtitan#4552 while storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches DistMoE's native parameter layout and keeps the feature axis independently shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and returns `[R, 2, F]` before the existing activation. Logical initialization and checkpoint keys remain `w1_EFD`, `w2_EDF`, and `w3_EFD`. Routing, activation, grouped-GEMM, and dispatcher behavior are unchanged. The physical fusion intentionally changes seeded random initialization order, so the affected real-PG integration goldens are refreshed; checkpoint-loaded weights retain their logical values. Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts native `[..., rows, columns]` parameters, matching the existing Newton-Schulz implementation, and its expert redistribution test exercises the production `[E, 2, F, D]` layout without adding another test case. This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain untouched. Test Plan: - `python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py` (2 passed) - `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py` (4 passed) - `CUDA_VISIBLE_DEVICES='' python -m pytest -q tests/unit_tests/cpu/test_moe.py tests/unit_tests/cpu/test_inference_moe.py tests/unit_tests/cpu/test_quantization.py torchtitan/experiments/transformers_modeling_backend/tests/test_moe_parallelism.py tests/unit_tests/gpu/test_fused_swiglu_override.py -k 'not TestFusedSwiGLUGroupedExpertsNumerics and not TestFusedSwiGLUOverrideKernels'` (69 passed, 3 skipped, 6 deselected) - TorchTitan formatting, flake8, pydoclint, codespell, and link checks passed; Pyrefly reports one existing unrelated optional-`av` diagnostic in `torchtitan/hf_datasets/multimodal/utils/video.py`. - The real-PG A10G model suite produced the refreshed 10-step loss and gradient-norm goldens. ghstack-source-id: ae440ac Pull Request resolved: pytorch/torchtitan#4643
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
There was a problem hiding this comment.
@shuhuayu @weifengpy could you review the flex_shard changes
There was a problem hiding this comment.
flex_shard related changes lgtm.
| expert_param_placements = { | ||
| param: Shard(2 if name == "w13_E2FD" else 1) | ||
| for name, param in experts.named_parameters() | ||
| } |
There was a problem hiding this comment.
I assume this explicit term will be refactored away in next PR when introducing GroupedLinear so that you can apply something similar https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/fsdp.py#L299
There was a problem hiding this comment.
Implemented in the child PR #4539. _linear_param_shard_placements() now handles both stacked Linear and GroupedLinear modules by deriving the matrix-row dimension from each parameter rank, including ordinary [E, F, D] grouped weights when E/FSDP must row-shard. No W13/W2 FQN special case remains.
| 2. Split the GroupedExperts' weight into separate expert's weight. | ||
| """ | ||
| state_dict = self._native_fused_linears_to_hf(state_dict) | ||
| state_dict = self._to_logical_expert_state( |
There was a problem hiding this comment.
I feel we could merge this ability into the _native_fused_linears_to_hf function, maybe in next PR?
There was a problem hiding this comment.
Implemented in #4539. The existing fused-linear state-adapter helpers now accept an explicit routed-W13 opt-in and own both split and merge for HF schemas with separate expert projections. GPT-OSS and Qwen3.5 continue to use their fused HF layouts.
| torch.empty(config.num_experts, config.hidden_dim, config.dim) | ||
| ) | ||
| self.activation_fn = config.activation_fn.build() | ||
| self.register_load_state_dict_pre_hook(self._merge_w13_on_load) |
There was a problem hiding this comment.
save hook and load hook should happen in a pair -- a single merge hook doesn't make sense?
| # Fused grouped experts expose split gate/up state-dict keys | ||
| # while the layout is declared on the fused w13 parameter. | ||
| w13_layout = sharding_config.state_shardings.get("w13") | ||
| if w13_layout is not None: | ||
| for state_name in ("w1_EFD", "w3_EFD"): | ||
| layouts[f"{module_prefix}{state_name}"] = w13_layout | ||
|
|
There was a problem hiding this comment.
I thought this can be removed only when
- we don't have save/load hooks in model (i.e. MoE)
- we move the state dict fuse / unfuse to hf state_dict_adapters
In this PR you kept the merge hook in model, which I haven't thought about what would happen. But I suggest we be consistent on load / save.
There was a problem hiding this comment.
Removed the model-level load hook. Native model, DCP, optimizer, and EMA state now consistently use the physical w13_E2FD key, while the HF adapters own the paired split/merge conversion at the external checkpoint boundary.
[ghstack-poisoned]
| "w2_EDF": partial(nn.init.trunc_normal_, std=0.02), | ||
| "w3_EFD": partial(nn.init.trunc_normal_, std=0.02), | ||
| }, | ||
| param_init=fused_grouped_experts_param_init( |
There was a problem hiding this comment.
used w13_E2FD, but the muon pattern still uses w3_EFD and w1_EFD, can you revise that part?
There was a problem hiding this comment.
Updated Kimi K3's DistMuon expert_projections to the physical w13_E2FD and w2_EDF parameters. The focused optimizer-config test now checks both compute-layout FQNs, verifies that the DistMuon regex selects both native parameters, and rejects the stale w1_EFD/w3_EFD names.
[ghstack-poisoned]
Not dimissing, but have addressed the issue, thanks!
…default" Summary: Carry forward the reviewed implementation from #4552 while storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches DistMoE's native parameter layout and keeps the feature axis independently shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and returns `[R, 2, F]` before the existing activation. Logical initialization and external HF keys remain `w1_EFD`, `w2_EDF`, and `w3_EFD`. Native model, DCP, optimizer, and EMA state use the physical `w13_E2FD` key, keeping `named_parameters()` and state-dict FQNs identical. Adapters split or merge W13 only at the HF boundary; the model installs no state-dict hooks, so save and load share the same native contract. Routing and activation semantics are unchanged. The physical fusion intentionally resets deterministic from-seed numerics. The old parameter order consumed random values as W1, W2, W3; the fused parameter initializes its slices as W1, W3 before W2. It also replaces two BF16 grouped GEMMs with one wider W13 grouped GEMM, whose rounding need not match two independent launches. Fixed-weight forward/backward tests validate the mapping, and the affected DeepSeek V3 and Qwen3 A10G goldens are regenerated from full-precision TensorBoard metrics for fake-PG and real-PG configurations. Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts native `[..., rows, columns]` parameters, matching the existing Newton-Schulz implementation, and its expert redistribution test exercises the production `[E, 2, F, D]` layout without adding another test case. Kimi K3's DistMuon configuration now assigns the physical `w13_E2FD` and `w2_EDF` expert parameters directly, so the fused W13 weight cannot fall through to the fallback AdamW group. This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain untouched. Test Plan: - `python -m pytest tests/unit_tests/cpu -q --deselect tests/unit_tests/cpu/test_lora.py::test_lora_forward` (1244 passed, 23 skipped, 1 deselected) - `python -m pytest -q tests/unit_tests/cpu/test_convert_ema_to_hf.py tests/unit_tests/cpu/test_state_dict_adapter.py tests/unit_tests/cpu/test_moe.py` (41 passed) - Transformer-backend native-W13 round-trip and focused MoE/quantization tests (60 passed, 23 skipped) - `python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py` (7 passed) - `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py tests/unit_tests/gpu/test_fused_swiglu_override.py` (20 passed) - Native state-key, EMA-export, and HF adapter round-trip tests pass without model state-dict hooks. - The Kimi K3 optimizer-pattern test verifies that native W13/W2 expert parameters are owned by DistMuon and stale logical W1/W3 names are absent. - A10G fake-PG and real-PG numerics were exported from the exact CI configurations; repeated DeepSeek V3 and Qwen3 runs produced identical full-precision trajectories. - Scoped formatting, flake8, pydoclint, codespell, link, and targeted Pyrefly checks passed. Project-wide Pyrefly retains one unrelated nullable-video-duration baseline error. [ghstack-poisoned]
…default" Summary: Carry forward the reviewed implementation from #4552 while storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches DistMoE's native parameter layout and keeps the feature axis independently shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and returns `[R, 2, F]` before the existing activation. Logical initialization and external HF keys remain `w1_EFD`, `w2_EDF`, and `w3_EFD`. Native model, DCP, optimizer, and EMA state use the physical `w13_E2FD` key, keeping `named_parameters()` and state-dict FQNs identical. Adapters split or merge W13 only at the HF boundary; the model installs no state-dict hooks, so save and load share the same native contract. Routing and activation semantics are unchanged. The physical fusion intentionally resets deterministic from-seed numerics. The old parameter order consumed random values as W1, W2, W3; the fused parameter initializes its slices as W1, W3 before W2. It also replaces two BF16 grouped GEMMs with one wider W13 grouped GEMM, whose rounding need not match two independent launches. Fixed-weight forward/backward tests validate the mapping, and the affected DeepSeek V3 and Qwen3 A10G goldens are regenerated from full-precision TensorBoard metrics for fake-PG and real-PG configurations. Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts native `[..., rows, columns]` parameters, matching the existing Newton-Schulz implementation, and its expert redistribution test exercises the production `[E, 2, F, D]` layout without adding another test case. Kimi K3's DistMuon configuration now assigns the physical `w13_E2FD` and `w2_EDF` expert parameters directly, so the fused W13 weight cannot fall through to the fallback AdamW group. This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain untouched. Test Plan: - `python -m pytest tests/unit_tests/cpu -q --deselect tests/unit_tests/cpu/test_lora.py::test_lora_forward` (1244 passed, 23 skipped, 1 deselected) - `python -m pytest -q tests/unit_tests/cpu/test_convert_ema_to_hf.py tests/unit_tests/cpu/test_state_dict_adapter.py tests/unit_tests/cpu/test_moe.py` (41 passed) - Transformer-backend native-W13 round-trip and focused MoE/quantization tests (60 passed, 23 skipped) - `python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py` (7 passed) - `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py tests/unit_tests/gpu/test_fused_swiglu_override.py` (20 passed) - Native state-key, EMA-export, and HF adapter round-trip tests pass without model state-dict hooks. - The Kimi K3 optimizer-pattern test verifies that native W13/W2 expert parameters are owned by DistMuon and stale logical W1/W3 names are absent. - A10G fake-PG and real-PG numerics were exported from the exact CI configurations; repeated DeepSeek V3 and Qwen3 runs produced identical full-precision trajectories. - Scoped formatting, flake8, pydoclint, codespell, link, and targeted Pyrefly checks passed. Project-wide Pyrefly retains one unrelated nullable-video-duration baseline error. Review history: This replaces #4643, which retains the original review discussion and approvals. [ghstack-poisoned]
|
merge to main? |
) Replacement for #4643; the original PR retains the review discussion and approvals.
Summary: Carry forward the reviewed implementation from pytorch/torchtitan#4552 while storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches DistMoE's native parameter layout and keeps the feature axis independently shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and returns `[R, 2, F]` before the existing activation. Logical initialization and external HF keys remain `w1_EFD`, `w2_EDF`, and `w3_EFD`. Native model, DCP, optimizer, and EMA state use the physical `w13_E2FD` key, keeping `named_parameters()` and state-dict FQNs identical. Adapters split or merge W13 only at the HF boundary; the model installs no state-dict hooks, so save and load share the same native contract. Routing and activation semantics are unchanged. The physical fusion intentionally resets deterministic from-seed numerics. The old parameter order consumed random values as W1, W2, W3; the fused parameter initializes its slices as W1, W3 before W2. It also replaces two BF16 grouped GEMMs with one wider W13 grouped GEMM, whose rounding need not match two independent launches. Fixed-weight forward/backward tests validate the mapping, and the affected DeepSeek V3 and Qwen3 A10G goldens are regenerated from full-precision TensorBoard metrics for fake-PG and real-PG configurations. Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts native `[..., rows, columns]` parameters, matching the existing Newton-Schulz implementation, and its expert redistribution test exercises the production `[E, 2, F, D]` layout without adding another test case. Kimi K3's DistMuon configuration now assigns the physical `w13_E2FD` and `w2_EDF` expert parameters directly, so the fused W13 weight cannot fall through to the fallback AdamW group. This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain untouched. Test Plan: - `python -m pytest tests/unit_tests/cpu -q --deselect tests/unit_tests/cpu/test_lora.py::test_lora_forward` (1244 passed, 23 skipped, 1 deselected) - `python -m pytest -q tests/unit_tests/cpu/test_convert_ema_to_hf.py tests/unit_tests/cpu/test_state_dict_adapter.py tests/unit_tests/cpu/test_moe.py` (41 passed) - Transformer-backend native-W13 round-trip and focused MoE/quantization tests (60 passed, 23 skipped) - `python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py` (7 passed) - `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py tests/unit_tests/gpu/test_fused_swiglu_override.py` (20 passed) - Native state-key, EMA-export, and HF adapter round-trip tests pass without model state-dict hooks. - The Kimi K3 optimizer-pattern test verifies that native W13/W2 expert parameters are owned by DistMuon and stale logical W1/W3 names are absent. - A10G fake-PG and real-PG numerics were exported from the exact CI configurations; repeated DeepSeek V3 and Qwen3 runs produced identical full-precision trajectories. - Scoped formatting, flake8, pydoclint, codespell, link, and targeted Pyrefly checks passed. Project-wide Pyrefly retains one unrelated nullable-video-duration baseline error. ghstack-source-id: 916a644 Pull Request resolved: pytorch/torchtitan#4643
Yeah fucked up, accidentaly used ghstack land :') |
Stack from ghstack (oldest at bottom):
Summary:
Carry forward the reviewed implementation from #4552 while
storing routed-expert W13 as
[E, 2, F, D]. The explicit gate/up axis matchesDistMoE's native parameter layout and keeps the feature axis independently
shardable. Standard grouped GEMM consumes a zero-copy
[E, 2F, D]view andreturns
[R, 2, F]before the existing activation.Logical initialization and external HF keys remain
w1_EFD,w2_EDF, andw3_EFD. Native model, DCP, optimizer, and EMA state use the physicalw13_E2FDkey, keepingnamed_parameters()and state-dict FQNs identical.Adapters split or merge W13 only at the HF boundary; the model installs no
state-dict hooks, so save and load share the same native contract. Routing and
activation semantics are unchanged.
The physical fusion intentionally resets deterministic from-seed numerics. The
old parameter order consumed random values as W1, W2, W3; the fused parameter
initializes its slices as W1, W3 before W2. It also replaces two BF16 grouped
GEMMs with one wider W13 grouped GEMM, whose rounding need not match two
independent launches. Fixed-weight forward/backward tests validate the mapping,
and the affected DeepSeek V3 and Qwen3 A10G goldens are regenerated from
full-precision TensorBoard metrics for fake-PG and real-PG configurations.
Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts
native
[..., rows, columns]parameters, matching the existing Newton-Schulzimplementation, and its expert redistribution test exercises the production
[E, 2, F, D]layout without adding another test case.Kimi K3's DistMuon configuration now assigns the physical
w13_E2FDandw2_EDFexpert parameters directly, so the fused W13 weight cannot fallthrough to the fallback AdamW group.
This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain
untouched.
Test Plan:
python -m pytest tests/unit_tests/cpu -q --deselect tests/unit_tests/cpu/test_lora.py::test_lora_forward(1244 passed, 23 skipped, 1 deselected)python -m pytest -q tests/unit_tests/cpu/test_convert_ema_to_hf.py tests/unit_tests/cpu/test_state_dict_adapter.py tests/unit_tests/cpu/test_moe.py(41 passed)python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py(7 passed)python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py tests/unit_tests/gpu/test_fused_swiglu_override.py(20 passed)