Skip to content

Add Qwen4 MoE - #2140

Draft
jundot wants to merge 1 commit into
ml-explore:mainfrom
jundot:qwen4-moe
Draft

jundot wants to merge 1 commit into
ml-explore:mainfrom
jundot:qwen4-moe

Conversation

@jundot

@jundot jundot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Requirements

  • ☑️ I understand it is strictly prohibited to use AI to write PR description
  • AI usage disclosure: help write the code and tests.

* This is a draft because of the open PR limit. I will mark it ready for review once my other open PRs are merged.

Text only, through the qwen4_exp model. Image input and kernels will follow in separate PRs.

It also loads the FP8 checkpoint (as bf16) and configs saved by transformers.

The tokenizer is remote code and needs tiktoken and xgrammar. Its apply_chat_template does not take continue_final_message, which mlx_lm.generate always passes, so the command below writes the chat template into the prompt and uses --ignore-chat-template.

Model information

Supported checkpoints

Verification

Run mlx-lm command:

mlx_lm.generate --model Qwen/Qwen4-35B-A3B --trust-remote-code --ignore-chat-template -p '<|im_start|>system\nReasoning effort is set to high.<|im_end|>\n<|im_start|>user\nThe secret to baking a good cake is<|im_end|>\n<|im_start|>assistant\n<think>' -m 1024

Output:

==========
The user has given an incomplete sentence: "The secret to baking a good cake is" — this seems like a prompt inviting me to complete it, or perhaps they want me to continue writing. It's ambiguous. It could be a creative writing prompt, or they might want baking advice.

The best response: treat it as an invitation to share the "secret" — give a genuinely useful answer about cake baking, while acknowledging there are many secrets. Maybe I should ask what they mean, but a better approach is to just engage: offer the real secrets of cake baking, and note that if they had a specific direction in mind (a story, an essay, a specific cake), they can tell me.

Let me give a substantive, knowledgeable answer about cake baking. Key real secrets:

1. Accurate measurement — baking is chemistry; weigh ingredients (scale) rather than cups.
2. Room temperature ingredients (butter, eggs) for emulsion.
3. Don't overmix after adding flour — gluten development makes tough cake.
4. Leavening: fresh baking powder/soda, correct amounts.
5. Oven temperature — use an oven thermometer; ovens lie.
6. Don't open the door early.
7. Pan choice, prep (bake-even strips, parchment).
8. Cooling before frosting.
9. Quality fats and butter flavor; salt to balance.
10. Don't overbake — pull when slightly jiggly / toothpick with few moist crumbs.
11. Cake flour or the cornstarch trick for tender crumb.
12. Creaming butter and sugar properly for aeration.

The single biggest one, if I had to pick: measuring accurately and not overmixing. Or "temperature and timing."

I'll write a nice response — maybe lead with a punchy answer then a short list. Keep it reasonably concise but useful. Format: a short intro, a compact list, and a closing offer.

Length: medium. Use a few headers or bold. Not too long.</think>...is mostly unglamorous: precision and restraint. But if I had to name the handful that matter most:

**Weigh your ingredients.** A cup of flour can weigh anywhere from 120 to 160 grams depending on how you scoop it, and that swing is the difference between a tender crumb and a dry, dense one. A $15 kitchen scale does more for home bakers than any expensive ingredient.

**Use room-temperature butter and eggs.** They hold an emulsion instead of breaking into curdled bits, which traps air and gives you lift and a fine, even texture.

**Mix the flour in as little as possible.** Stir until you no longer see streaks, then stop. Overmixing develops gluten, and gluten is exactly what you *don't* want in a cake — it's what you want in bread.

**Check your oven.** Most home ovens run 25°F hot or cold, and no dial tells you. An oven thermometer is the cheapest upgrade there is. Also: don't open the door before the first ~20 minutes, when the structure is still setting.

**Pull it out early.** A toothpick with a few moist crumbs beats one bone-dry. Cakes keep going for a minute or two after they leave the oven.

**Let it cool completely before frosting.** Warm cake melts buttercream into a sliding disaster.

And the quiet ones: fresh leaveners (baking powder dies in the pantry), and enough salt — it's not optional, it's what makes the butter and sugar taste like something.

Were you after something specific here — a particular cake, a recipe that went wrong, or were you just starting a sentence somewhere?
==========
Prompt: 30 tokens, 152.364 tokens-per-sec
Generation: 790 tokens, 46.327 tokens-per-sec
Peak memory: 134.793 GB

joshuaswarren added a commit to joshuaswarren/mlx-lm that referenced this pull request Dec 4, 2026
* qwen4_exp: port Qwen4 MoE (qwen4_moe) model from upstream mlx-lm

Ports ml-explore/mlx-lm's qwen4_exp package + PR ml-explore#2140 (FP8 expert
dequant, per-expert stacking, indexed_attention layer-type alias,
ngram weight_scale) onto this fork's models/ layout.

Fork adaptations: old-layout imports (models.base / switch_layers /
gated_delta / cache), Metal-only mlx_lm.kernels.sparse_attention
imported under a guard so the gather+SDPA fallback runs on non-Metal
backends, and an MtpModule that binds the checkpoint's mtp.* weights
instead of dropping them (strict load keeps the draft head for
speculative decoding; its forward is wired separately).

test_qwen4_exp covers all four checkpoint layouts, n-gram shard merge,
mtp.* retention, and prefill/decode/batch cache equivalence.

* lint: pre-commit fixes for #5 + pre-existing .github/scripts failures

black/isort reformats on the new qwen4_exp files and test_models.py.
Also fixes .github/scripts contributor-upkeep files (added unformatted
in #3, failing Check Lint on main): copyright headers, drop dead
contextlib/io imports.

* qwen4_exp: fix mtp pre_fc_norm_hidden size to hidden*hc_count

The checkpoint normalizes the concatenated hyper-connection streams
(8192 = 2048x4), not a single hidden stream.
dpalmqvist added a commit to motsognirr/applerum that referenced this pull request Dec 4, 2026
…eckpoint layout (#800)

* feat(models): serve Qwen4-35B-A3B through mlx-vlm 0.8.3, in either checkpoint layout (#798)

Qwen4 (qwen4_moe) is qwen4_exp's architecture with other sizes, and
mlx-vlm 0.8.3 serves it with the same Model class. It joins qwen4_exp in
the native-hybrid routing and the VLM checkpoint path.

The plain mlx-community Qwen4-35B-A3B-{3,4,6}bit repos were converted
with mlx-lm (ml-explore/mlx-lm#2140/#2141) and use another weight layout,
which mlx-vlm rejects. A sanitize hook installed in load_vlm rewrites
such a checkpoint to mlx-vlm's layout at load: names, 1+w norms, the
block-inject rows merged into input_mix_weight_down, per-head n-gram
tables to row shards, and the flattened patch embedding. Rows are only
moved, so quantized weights are not re-rounded.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(qwen4): pin the folded-norm list to mlx-vlm's classes; reject an unexpected patch-embed width

Review follow-ups on #800. The folded-norm list is now tested against
mlx-vlm's Qwen4ExpRMSNorm (the class that scales by 1 + weight) instead
of only round-tripping against itself. A patch embedding that is not the
flattened Conv3d width raises a clear error. The routing comment says why
qwen4_moe is listed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(qwen4): detect the mlx-lm layout by its per-head n-gram tables

Review follow-up on #800. Detection required only the absence of mlx-vlm
marks, so a text-only mlx-vlm checkpoint that stores one n-gram table
(save_original_format=False) was claimed and mis-prefixed. It now needs
the per-head tables only the mlx-lm port writes. The hook install also
tolerates any import failure, so it cannot fail another VLM's load.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
KakkoiDev added a commit to KakkoiDev/agentbench that referenced this pull request Dec 5, 2026
…ect into input_mix_weight_down; cut those rows back out on load (and drop the copies fetched yesterday)

ml-explore/mlx-lm#2140 merges each hyper-connection's block_inject_weight into its input_mix_weight_down (260 =
256 + 4 rows); mlx-vlm keeps them apart, so these builds did not load in mlx-vlm. The rows are cut back out in the
variant's sanitize (exact: rows are quantized one by one). Names and row counts checked against the model for the
3-bit (whole and table on disk) and the 4-bit table-on-disk builds; loading still to be smoke-tested (queue #6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MMzzHSGjhPnmLyjXfFdzE7
rromenskyi added a commit to ipsupport-llc/mlx-lm that referenced this pull request Dec 5, 2026
Add Qwen4 MoE (text): upstream qwen4_exp package + ml-explore#2140
@Weschera

Weschera commented Dec 5, 2026

Copy link
Copy Markdown

Tested this on an M4 Max with 128 GB (macOS 26.5.2), using mlx-community/Qwen4-35B-A3B-4bit-text and the PR head 7b35ab5, which is on current main.

  • tests.test_models: all 136 tests pass. test_qwen4_exp fails with the mlx_lm/ changes reverted, so the new checks cover the change.
  • Loads in 3.6 s. I built the prompt by hand in the format from your description (system "Reasoning effort is set to high.", then <think>), and decoded greedy.
  • 17*23 → 391, capital of Australia → Canberra, is_prime → working code. Every reply closed </think> before answering.
  • Your cake prompt at 1024 tokens finishes its reasoning and starts the answer, like your output.

Speed and memory (stream_generate, greedy):

Prompt tokens Prompt tok/s Gen tokens Gen tok/s Peak memory
~35 305-392 116-242 77.6-79.6 31.5 GB
527 1,137 / 1,299 440 / 512 67.7 / 61.9 32.3 GB
6,272 1,465 / 1,592 512 67.0 / 68.7 33.5 GB
24,911 1,588 / 1,591 512 68.5 / 69.2 34.2 GB

For scale, mlx-serve 26.12.2 decodes the same 4-bit pack at 125.0 tok/s on this machine with no draft model and no prompt lookup (--no-mtp --no-pld). Prefill is similar (1,761 at 6.2K, 1,526 at 24.4K). So decode is where the kernels you mentioned should pay off. Happy to rerun once they're up.

Thanks for getting this in!

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.

2 participants