Repository navigation
feat(distributed): add tensor-parallel support for Qwen3 MoE - #3730
Open
Jaeyeong-CHOI wants to merge 1 commit into
Open
Jaeyeong-CHOI wants to merge 1 commit into
Jaeyeong-CHOI wants to merge 1 commit into
Conversation
Qwen3 MoE checkpoints (qwen3_moe) were refused by --tp-size > 1. Add a Qwen3Moe tensor-parallel runtime kind that shards attention and dense MLP layers like the dense Qwen3 kind and shards every expert within itself (gate_proj/up_proj along the expert intermediate dimension, down_proj along its input), with the router replicated and one reduction per MoE layer after the weighted expert sum is cast back to the activation dtype, matching mlx-lm's qwen3_moe Model.shard. A quantized checkpoint whose moe_intermediate_size / tp_size is not a multiple of the quantization group size is refused at startup, before any weight is read, with both numbers in the message.
This branch has not been deployed
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.
Summary
Closes #2405.
--tp-size N(N > 1) refused every Qwen3 MoE checkpoint (qwen3_moe, e.g.Qwen3-30B-A3B). This adds aQwen3Moetensor-parallel runtime kind that shards Qwen3 MoE the way mlx-lm'sqwen3_moeshard_layersdoes (ml-explore/mlx-lm#1774), somlxcel generateandmlxcel-serverrun it at--tp-size2 and 4.What changed
TensorParallelRuntimeKind::Qwen3Moe, returned byruntime_kind_forforModelType::Qwen3Moewhen the architecture string isqwen3_moe;TensorParallelQwen3MoeModel(oneQwen3MoeModelper rank),LoadedModel::TensorParallelQwen3Moe, and the loader arm inload_model_with_tensor_parallel. The refusal message that lists the TP families now names Qwen3 MoE.shard_qwen3_moe_weight_map/qwen3_moe_mlp_shard_spec:Qwen3kind;compute_local_moe_shapesinMoEParallelMode::WithinExpertSharding;switch_mlp.gate_proj/up_projare split on their output rows (axis -2, the same rows for.weight,.scales,.biases) anddown_projon its last axis, with the range scaled by the packing (.weight) or group size (.scales/.biases); the routermlp.gateis replicated;mlp.experts.{e}.{proj}, whichSwitchGLUstacks at load) is sharded the same way;mlp_only_layers/decoder_sparse_step) are split onintermediate_sizethroughcompute_local_ffn_shapes, like theLlamaStyleFFN;gather_qmmkernels, which need the last two axes of the weight and its scales row-contiguous ([gather_qmm] No implementation for problem shape: 1x384x2048x72 ...on the real checkpoint at tp 2 before this), and the copy also lets the unsliced tensor be released once every rank has its slice.moe_weighted_sum, which casts the weighted sum back to the activation dtype; the partial sums are then reduced once per MoE layer withreduce_sum(float32 accumulation, result in the activation dtype). This is the placement ofall_sumafter(y * scores[..., None]).sum(axis=-2).astype(y.dtype)in mlx-lm'sSparseMoeBlock. Attention and dense MLP outputs are reduced with the samereduce_sum, so the residual stream keeps the dtype the single-rank model carries. Native batched decode (forward_batched) is implemented as for theQwen3kind.local_qwen3_moe_argschecks the geometry before any weight is read: heads and KV heads as forQwen3;moe_intermediate_size(andintermediate_sizeonly if a dense layer exists) divisible bytp_size; and for a quantized checkpoint,moe_intermediate_size / tp_sizea multiple of the quantization group size, refusing otherwise with a message that namesmoe_intermediate_size, the per-rank width,tp_sizeand the group size.qwen3_moe::ModelArgs::is_moe_layerreplaces the inline sparse/dense decision inDecoderLayer::from_weights_with_rope(same logic) so the runtime uses the same rule.src/models/batched_decode_coverage_tests.rs: the new runtime is listed as a native batched-decode model.docs/distributed.md(TP section),docs/supported-models.md,docs/CONTINUOUS_BATCHING.md, the--tp-sizehelp text, and a CHANGELOG entry under## [Unreleased].Deviations from the issue
--tp-size 2reproduces--tp-size 1forHello, 32 tokens) holds at tp 4 (32/32) but not at tp 2, which takes the second-ranked token at token 23. There the single-rank logits are 35.0 against 34.75, one bf16 step, and the single-rank model itself changes that same token when only its prefill schedule changes. Of the 576 steps compared across four prompts, tp 2 and tp 4 change the argmax at 11; ten are at single-rank margins of 0.25 or less, and the eleventh (Fibonacci prompt, tp 4, margin 1.75) comes from the two tokens moving +1.25 and -0.75, within that prompt's per-step spread (median about 1.1, worst 6.0 for the schedule-only baseline). Details under Verification.--tp-moe-modedefaults toexpert_parallel, and the acceptance command does not pass it, so the Qwen3 MoE runtime ignores the flag and always shards within experts (the issue rejects expert parallelism for this runtime). The help text anddocs/distributed.mdsay so. The Gemma 4 runtime also ignores the flag (it runs each expert whole on every rank rather than sharding it).intermediate_sizewhen a dense layer exists, since itsdown_projscales split the same way.Verification
NVIDIA GB10 (sm_121, 121 GB unified memory), CUDA 13.0, driver 580.178.04, rustc 1.97.1,
--features cuda,test-fastprofile. Checkpoint:mlx-community/Qwen3-30B-A3B-4bitat revisiond388dead1515f5e085ef7a0431dd8fadf0886c57(48 layers, 128 experts, top-8,moe_intermediate_size768, 4 KV heads, 4-bit, group size 64).Before (main 9402cf8)
The new unit tests reference
TensorParallelRuntimeKind::Qwen3MoeandTensorParallelQwen3MoeModel, which do not exist on main.Unit tests (this branch)
cargo test --locked --profile test-fast --features cuda -p mlxcel --lib -- batched_decode_coverage tensor_parallel qwen3_moe --test-threads=1: 421 passed, 0 failed, 4 ignored. New tests inllama_runtime_tests.rs:tensor_parallel_qwen3_moe_f16_matches_single_rank_logits: random f16 weights, 3 layers (two sparse with 8 experts / top-2, one dense throughmlp_only_layers), 6-token prompt routed to 6 distinct experts in the first layer. Logits against the single-rankQwen3MoeModel: tp 10, tp 22.75e-4, tp 44.96e-4max abs diff (bound1e-3).tensor_parallel_qwen3_moe_quantized_experts_match_single_rank: 4-bit affine experts (group 64) withmoe_intermediate_size128, so each of 2 ranks holds exactly one group ofdown_projscales (checked:[8, 64, 1]per rank); logits within1e-4of the single-rank model on the same quantized weights.tensor_parallel_qwen3_moe_per_expert_layout_matches_stacked: the unstackedexperts.{e}layout at tp 2 and 4 matches the stacked single-rank model within1e-4.tensor_parallel_qwen3_moe_refuses_split_inside_a_quantization_group: tp 1 and 2 accepted; tp 4 (32 columns per rank, group size 64) refused throughlocal_qwen3_moe_argsand throughfrom_model_diron a directory with onlyconfig.json, so the refusal comes before any weight is read. Message:Qwen3 MoE tensor parallelism splits moe_intermediate_size (128) into 32 columns per rank at tp_size 4, which is not a multiple of the quantization group_size (64); ....local_qwen3_moe_args_boundaries: one column per rank (unquantized) accepted; an uneven split refused;intermediate_sizechecked only when a dense layer exists; fewer KV heads than ranks refused.runtime_kind_for_maps_qwen3_moe_to_its_runtime(tp 1, 2, 4),tensor_parallel_qwen3_moe_tp{1,2}_native_batched_decode,tensor_parallel_qwen3_moe_last_row_matches_full_forward_row(tp 1, 2, 4).parallel_moe_tests::test_qwen3_moe_within_expert_ranges_tile_the_expert_width: the Qwen3-30B-A3B geometry tiles[0, 768)exactly once at tp 1, 2, 4 and 8.Real checkpoint
MLXCEL_PRINT_TOKEN_IDS=1 mlxcel generate -m Qwen3-30B-A3B-4bit --temp 0 --tp-size N ..., comparing generated token ids with--tp-size 1:-nHello(the issue's command)Explain the difference between tensor parallelism and pipeline parallelism in three sentences.Write a Python function that returns the n-th Fibonacci number.Continue this sequence with more entries separated by commas: red, blue, green,(--no-chat-template)Every run produces coherent text. To see whether the differences are a sharding error or bf16 rounding, the single-rank model and the TP runtime were run step by step along the single-rank greedy sequence and their logits compared at each step (vocabulary 151,936, top logits 20 to 48):
Per-step max abs logit difference: median 0.67 to 1.16 and worst 2.9 to 6.4 across the four prompts, for tp 2 and tp 4 alike.
Along the single-rank path, tp 2 and tp 4 pick a different argmax at 11 of 576 steps in total. At 10 of them the single-rank model's own top two logits differ by at most 0.25 (three are exact bf16 ties, e.g. 34.5 vs 34.5 at token 9 of the long prompt; at these magnitudes one bf16 step is 0.125 to 0.25); the eleventh is token 31 of the Fibonacci prompt at tp 4, with a single-rank margin of 1.75.
Accumulating the reductions in float32 and keeping the residual in float32 (as the dense
Qwen3kind does) did not bring the logits closer on the two prompts tried (Hello and long): medians 0.75 to 0.91, worst 3.3 to 5.1, again with argmax changes at near-ties of 0.0 to 0.25. The branch therefore keeps the activation-dtype reduction, which is what mlx-lm'sall_sumdoes.For scale, the single-rank model against itself with only the schedule changed (one prefill over the whole sequence instead of one decode step per token) gives a per-step max abs logit difference of median 0.53 to 1.13 and worst 2.2 to 6.0 on the same four sequences, and its argmax changes at 5 of 288 steps, all at single-rank margins of 0.25 or less. One of them is token 23 of
Hello, the same position where tp 2 changes.So the issue's last acceptance item holds at tp 4 but not at tp 2 for
Hello: tp 2 takes the second-ranked token at a position where the single-rank logits differ by one bf16 step and where the single-rank model itself changes its pick when only the prefill schedule changes. Within-expert sharding changes the summation order of the expert down projections and the attention output projection, and bf16 rounding then moves such near-ties; the TP spread is the size of the single-rank model's own spread, and the f16, f32 and quantized unit tests above show the sharded runtime agrees with the single-rank model to rounding.Server:
mlxcel-server -m Qwen3-30B-A3B-4bit --tp-size 2 --parallel 2reportsdecode path: native batched forward; two greedy chat completions (48 tokens each) sent one after the other and then concurrently return identical text in both modes.Throughput is not a goal here (every rank runs on one device until #488): over the four prompts, decode runs at 51 to 80 tok/s at tp 1, 14 to 48 tok/s at tp 2 and 12 to 26 tok/s at tp 4.
Checks
cargo fmt --all -- --check: pass.cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings: pass.python3 scripts/ci/check_used_by.py,bash scripts/ci/check_used_by_test.sh,check_env_var_docs.py,check_native_env_writes.py,check_cross_repo_refs.py,check_binary_assets.py,check_windows_reserved_paths.py: pass.make verify-test-cuda(workspace, single-threaded): 18,901 passed, 2 failed, 578 ignored. Both failures also fail on unmodified main 9402cf8 with the same assertions and are untouched by this change:tests/mlx_test_guard_coverage.rs::mlx_evaluating_lib_tests_take_mlx_test_guard(flagssrc/vision/encoders/nemotron_h_nano_omni_tests.rs:276 pos_embed_resample_runs_in_f32) andtests/step3p7_parity.rs::text_decode_delegates_sequence_local_native_batching(assertion failed: !wrapper.supports_padded_prefill()); test: fix two stale tests that keep make verify-test red #3720 (Refs [nightly-verify] main is red #3652) fixes both.main(git merge-tree).Review checklist
src/models/batched_decode_coverage_tests.rs,EXPECTED_NATIVE) gainsTensorParallelQwen3MoeModel, which implements the nativeforward_batchedroute.shard_tensor,compute_shard_spec,reduce_sum,compute_local_moe_shapesandcompute_local_ffn_shapesare reused unchanged.DecoderLayer::from_weights_with_ropenow callsModelArgs::is_moe_layer, the same expression it had inline. The MLP shards are made contiguous only inside the new Qwen3 MoE sharder;shard_tensoritself is unchanged.## [Unreleased].cargo fmt --all -- --checkpasses on the final commit.Limits
mlxcel-serverruntime settings still reportmoe_mode: expert_parallel(the flag's default) for this runtime, although it shards within experts; making the flag explicit-only touches the CLI and server startup types and is left for a follow-up with feat: multi-GPU tensor-parallel runtime with per-rank device placement and cross-GPU collectives #488.