Skip to content

feat(distributed): add tensor-parallel support for Qwen3 MoE - #3730

Open
Jaeyeong-CHOI wants to merge 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:feat/2405-tp-qwen3-moe
Open

Jaeyeong-CHOI wants to merge 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:feat/2405-tp-qwen3-moe

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

Summary

Closes #2405.

--tp-size N (N > 1) refused every Qwen3 MoE checkpoint (qwen3_moe, e.g. Qwen3-30B-A3B). This adds a Qwen3Moe tensor-parallel runtime kind that shards Qwen3 MoE the way mlx-lm's qwen3_moe shard_layers does (ml-explore/mlx-lm#1774), so mlxcel generate and mlxcel-server run it at --tp-size 2 and 4.

What changed

  • TensorParallelRuntimeKind::Qwen3Moe, returned by runtime_kind_for for ModelType::Qwen3Moe when the architecture string is qwen3_moe; TensorParallelQwen3MoeModel (one Qwen3MoeModel per rank), LoadedModel::TensorParallelQwen3Moe, and the loader arm in load_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:
    • attention (q/k/v column-parallel, o row-parallel, q/k norms replicated) through the existing shard plan, as in the dense Qwen3 kind;
    • MoE layers use within-expert sharding: the rank's range comes from compute_local_moe_shapes in MoEParallelMode::WithinExpertSharding; switch_mlp.gate_proj/up_proj are split on their output rows (axis -2, the same rows for .weight, .scales, .biases) and down_proj on its last axis, with the range scaled by the packing (.weight) or group size (.scales/.biases); the router mlp.gate is replicated;
    • the unstacked per-expert layout (mlp.experts.{e}.{proj}, which SwitchGLU stacks at load) is sharded the same way;
    • dense MLP layers (mlp_only_layers / decoder_sparse_step) are split on intermediate_size through compute_local_ffn_shapes, like the LlamaStyle FFN;
    • every MLP shard is copied to a contiguous array. A strided slice of the expert stack is refused by the CUDA gather_qmm kernels, 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.
  • Forward: every rank runs the replicated router (so every rank picks the same top-k experts), its expert shard, and the existing moe_weighted_sum, which casts the weighted sum back to the activation dtype; the partial sums are then reduced once per MoE layer with reduce_sum (float32 accumulation, result in the activation dtype). This is the placement of all_sum after (y * scores[..., None]).sum(axis=-2).astype(y.dtype) in mlx-lm's SparseMoeBlock. Attention and dense MLP outputs are reduced with the same reduce_sum, so the residual stream keeps the dtype the single-rank model carries. Native batched decode (forward_batched) is implemented as for the Qwen3 kind.
  • local_qwen3_moe_args checks the geometry before any weight is read: heads and KV heads as for Qwen3; moe_intermediate_size (and intermediate_size only if a dense layer exists) divisible by tp_size; and for a quantized checkpoint, moe_intermediate_size / tp_size a multiple of the quantization group size, refusing otherwise with a message that names moe_intermediate_size, the per-rank width, tp_size and the group size.
  • qwen3_moe::ModelArgs::is_moe_layer replaces the inline sparse/dense decision in DecoderLayer::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: docs/distributed.md (TP section), docs/supported-models.md, docs/CONTINUOUS_BATCHING.md, the --tp-size help text, and a CHANGELOG entry under ## [Unreleased].

Deviations from the issue

  • The last acceptance item (--tp-size 2 reproduces --tp-size 1 for Hello, 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-mode defaults to expert_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 and docs/distributed.md say so. The Gemma 4 runtime also ignores the flag (it runs each expert whole on every rank rather than sharding it).
  • The refusal also covers dense intermediate_size when a dense layer exists, since its down_proj scales 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-fast profile. Checkpoint: mlx-community/Qwen3-30B-A3B-4bit at revision d388dead1515f5e085ef7a0431dd8fadf0886c57 (48 layers, 128 experts, top-8, moe_intermediate_size 768, 4 KV heads, 4-bit, group size 64).

Before (main 9402cf8)

$ mlxcel generate -m Qwen3-30B-A3B-4bit --tp-size 2 -p "Hello" -n 32 --temp 0
Error: tensor-parallel runtime currently supports only dense Llama/Qwen2/Qwen3/Qwen3.5/Gemma3/Gemma4/ERNIE/Hunyuan models, got Qwen3Moe (qwen3_moe)

The new unit tests reference TensorParallelRuntimeKind::Qwen3Moe and TensorParallelQwen3MoeModel, 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 in llama_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 through mlp_only_layers), 6-token prompt routed to 6 distinct experts in the first layer. Logits against the single-rank Qwen3MoeModel: tp 1 0, tp 2 2.75e-4, tp 4 4.96e-4 max abs diff (bound 1e-3).
  • tensor_parallel_qwen3_moe_quantized_experts_match_single_rank: 4-bit affine experts (group 64) with moe_intermediate_size 128, so each of 2 ranks holds exactly one group of down_proj scales (checked: [8, 64, 1] per rank); logits within 1e-4 of the single-rank model on the same quantized weights.
  • tensor_parallel_qwen3_moe_per_expert_layout_matches_stacked: the unstacked experts.{e} layout at tp 2 and 4 matches the stacked single-rank model within 1e-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 through local_qwen3_moe_args and through from_model_dir on a directory with only config.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_size checked 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:

Prompt -n tp 2 tp 4
Hello (the issue's command) 32 first 22 equal, differs at token 23 32/32 equal
Explain the difference between tensor parallelism and pipeline parallelism in three sentences. 128 first 8 equal, differs at token 9 128/128 equal
Write a Python function that returns the n-th Fibonacci number. 64 64/64 equal first 30 equal, differs at token 31
Continue this sequence with more entries separated by commas: red, blue, green, (--no-chat-template) 64 differs at token 3 differs at token 3

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 Qwen3 kind 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's all_sum does.

  • 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 2 reports decode 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 (flags src/vision/encoders/nemotron_h_nano_omni_tests.rs:276 pos_embed_resample_runs_in_f32) and tests/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.
  • Merges cleanly onto current main (git merge-tree).

Review checklist

  • Boundaries: tp 1 (identity), the narrowest legal quantized split (one group per rank), one column per rank unquantized, a split inside a group (refused), an uneven split (refused), KV heads below the rank count (refused), and a config without dense layers.
  • Complexity: sharding is one pass over the weight map; the per-layer sparse/dense scan is linear in the layer count.
  • The batched-decode coverage list (src/models/batched_decode_coverage_tests.rs, EXPECTED_NATIVE) gains TensorParallelQwen3MoeModel, which implements the native forward_batched route.
  • Other callers: shard_tensor, compute_shard_spec, reduce_sum, compute_local_moe_shapes and compute_local_ffn_shapes are reused unchanged. DecoderLayer::from_weights_with_rope now calls ModelArgs::is_moe_layer, the same expression it had inline. The MLP shards are made contiguous only inside the new Qwen3 MoE sharder; shard_tensor itself is unchanged.
  • CHANGELOG entry under ## [Unreleased].
  • No explanatory comment removed; the TP family refusal message now names Qwen3 MoE.
  • cargo fmt --all -- --check passes on the final commit.

Limits

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

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Add tensor-parallel support for Qwen3 MoE

1 participant