Skip to content

Add image input to Qwen4 MoE - #2141

Draft
jundot wants to merge 2 commits into
ml-explore:mainfrom
jundot:qwen4-moe-vision
Draft

jundot wants to merge 2 commits into
ml-explore:mainfrom
jundot:qwen4-moe-vision

Conversation

@jundot

@jundot jundot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor
  • ☑️ 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.

Stacked on #2140.

Image input for qwen4_exp, so Qwen4 MoE and Qwen3.8-Flash-Next take images. The vision tower and the processor follow transformers and the Muse Spark package layout.

Image tokens use 3D RoPE positions. embed_inputs computes them and the model keeps them for the next prefill calls, so generate and the server do not change. The first attention layer cache keeps the positions of the last few tokens, only when the model has a vision tower. Text without images runs the same code as before.

ArraysCache.extract now keeps empty entries, as filter does.

Supported checkpoints

Verification

The image is 640 x 480 with a red circle, a blue square, a green triangle and the text MLX 2026.

mlx_lm.generate --model Qwen/Qwen4-35B-A3B --trust-remote-code --ignore-chat-template --image shapes.png -p '<|im_start|>system\nReasoning effort is set to high.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe this image.<|im_end|>\n<|im_start|>assistant\n<think>' -m 1024
==========
The user wants a description of the image. Let me look carefully at what's present. There are three geometric shapes arranged horizontally in the upper portion: a red circle on the left, a blue square in the middle, and a green triangle on the right. Below them is text in black reading "MLX 2026". The background is a very light gray/white. I should describe these elements clearly and concisely, noting positions and colors. No need for elaborate reasoning beyond accurate observation. I'll produce a straightforward paragraph.</think>The image shows three simple geometric shapes arranged in a horizontal row against a pale, off-white background. On the left is a solid red circle, in the center is a solid blue square, and on the right is a solid green triangle (pointing upward). Below this row of shapes, centered horizontally, is the text "MLX 2026" written in bold black lettering.
==========
Prompt: 328 tokens, 936.222 tokens-per-sec
Generation: 192 tokens, 45.842 tokens-per-sec
Peak memory: 135.687 GB

inureyes added a commit to lablup/mlxcel that referenced this pull request Dec 4, 2026
…#3772)

* feat(models): load Qwen4-35B-A3B (qwen4_moe) on the qwen4_exp path

Qwen4-35B-A3B declares model_type qwen4_moe, which was not a recognized type, although it is the architecture mlxcel already serves as qwen4_exp. Its public checkpoints also store the same model in three tensor layouts that no config field tells apart, and the loader read only two of them.

- One alias list (QWEN4_EXP_FAMILY_MODEL_TYPES in mlxcel-core) now backs detection, the registry aliases, prompt-cache snapshot sizing, SSD expert streaming and prepare-expert-stream, and embedded MTP head detection, so the next alias is a one-line change.
- The zero-centered norm storage is decided from the text key prefix, as mlx-lm's sanitize does: model.language_model.* and language_model.* hold w, bare model.* holds 1 + w. Before this only an optiq_vision block triggered the unfold, so an mlx-lm conversion would have run with 1 + (1 + w). Norms under two prefixes are a named error.
- The mlx-lm layout loads: block_inject_weight merged into input_mix_weight_down is split back, per-head n-gram tables are read as the same logical table as the row shards with the hash state derived from the config, model.vision_tower.* maps to the vision tower with its 2-D patch embedding restored, and ngram_embedding.weight_scale is applied.
- A checkpoint without vision_config loads text-only through the same wrapper.
- qwen4_moe config defaults (rope_parameters, output_gate_type from hidden_act) follow mlx-vlm's config class; qwen4_exp keeps its stricter contract.

Validated with tiny float32 fixtures written by mlx-vlm (Hugging Face layout) and by the ml-explore/mlx-lm#2141 converter: both reproduce mlx-vlm's logits for a 40-token prefill and eight decode steps within the existing 1e-5 relative tolerance, and a negative control that skips the fold detection misses by more than 1000 times that. On mlx-community/Qwen4-35B-A3B-4bit-text, greedy generation loads in 10.8 s at 29.5 GB and answers "Paris".

Refs #3767

* docs: document Qwen4-35B-A3B support and its validation

Adds the qwen4_moe entry to docs/supported-models.md: the layouts accepted and how each is recognized, the norm-storage rule and its named error, text-only builds, the tokenizer-compat fallback, the chat controls (tri-state enable_thinking, the xhigh/high/low/off efforts, data-segment encoding of message text on the server), what is refused, and the real-checkpoint validation.

Adds scripts/qwen4_moe_mlx_vlm_logit_trace.py, the mlx-vlm reference arm for the mlx-lm-layout conversions. mlx-vlm cannot read that layout, so the script converts the tensors in memory; it is what shows that the gap between mlxcel and the mlx-lm branch on mlx-community/Qwen4-35B-A3B-4bit-text (1 of 476 decided, +1.75% perplexity) is the gap between the two references (mlx-lm against mlx-vlm: 2 of 469, -2.14%), while mlxcel against mlx-vlm has 0 of 469 decided disagreements.

Refs #3767

* fix(models): refuse bare-prefix Qwen4 checkpoints that carry HF-only tensors

The prefix rule read every bare model.* checkpoint as folded (1 + w). A text-only Hugging Face export also has bare keys but stores w, and mlx-vlm's text-only sanitize reads it that way, so the rule would have subtracted one from raw norms without an error. Such a checkpoint is recognizable by tensors no mlx-lm save contains (fused or per-expert mlp.experts.*, shard_K, the n-gram hash state) and is now the named ConflictingNormLayout error, which points at MLXCEL_QWEN4_NORM_STORAGE. An optiq_vision block still decides.

Also in this commit:

- The disaggregated router's refusal of pre-rendered prompt ids now names the Qwen4 case. The data-segment encoder is attached on the router too, so a request whose message text spells a control token reaches that refusal, and its message named only Kimi K3 and DeepSeek-VL2.
- A test for the tokenizer-compat fallback: the tokenizer and the template are read from tokenizer-compat/ when the root has no tokenizer.json, and a root tokenizer.json wins.
- The supported-models entry states what the canonical generate command prints at the default effort and corrects the router sentence.

Refs #3767

* fix(server): keep Qwen4 message text as data on every marked request

The Qwen4 segment encoder declined the data boundary whenever message text held a sentinel character, and checked each content part on its own. Both sent a request back to the flat encoding, where a control spelling in user text becomes a protocol token: one by typing U+FDD0, the other by splitting `<think>` across two text parts that the template concatenates.

The sentinel pair is now chosen per request from the 32 noncharacters U+FDD0..U+FDEF so that it occurs in no message text, tool definition or kwarg; only a request that uses every candidate and also spells a control token is refused, never answered flat. Control spellings are detected over each message's joined content. Multipart assistant content is trimmed at its rendered edges only, as the template's `| trim` does, so marking no longer changes the prompt.

Layout detection also refuses `language_model.*` keys beside per-head n-gram tables by name (PerHeadTablesUnderMlxVlmPrefix): mlx-lm reads that prefix as `w` only beside `shards.K`, so there mlx-lm and mlx-vlm disagree.

Validated with the qwen4_chat_segments, qwen4_moe_chat_tests and qwen4_exp layout test modules.

Refs #3767

* fix(server): derive Qwen4 sentinel candidates from the default pair

The default sentinel pair was only referenced from test helpers, so the non-test build flagged DATA_OPEN, DATA_CLOSE and DataMarkers::DEFAULT as dead code under clippy -D warnings. The candidate list now starts from DEFAULT, which keeps one definition of the first pair and clears the lint.

Refs #3767

* fix(server): pick the Qwen4 sentinel pair against the whole message list

The pair was checked only against the marked message text, tools and kwargs. The template also renders fields that are not marked, such as a historical tool call's name and arguments, so a sentinel there kept the default pair selected, unbalanced the split and sent the request to the flat encoding. The pair is now checked against the serialized message list as a whole.

Validated with the qwen4_chat_segments module including the ignored README worked-example test against the local Qwen4-35B-A3B tokenizer.

Refs #3767

* fix: harden Qwen4 segment path, layout detection and loader checks

Review follow-ups for the Qwen4 (qwen4_moe) support.

The n-gram hash-state tensors are no longer treated as Hugging Face-only evidence in norm-storage detection, since the OptiQ Qwen3.8-Flash-Next checkpoint stores them under bare model.*, and a text-only OptiQ build without the vision marker would have been refused. mlp.experts. and shard_ still identify an HF text export.

--lang-bias now hashes the tokenizer.json the loader actually read, including the tokenizer-compat/ fallback.

When a message text spells a control token and the data-segment encoding then fails for any reason, the request now errors instead of falling back to flat tokenization, which would turn those spellings into protocol tokens. The next-turn prompt-cache warm-up is skipped for such Qwen4 requests (and replies), mirroring the Kimi K3 opt-out, because the flat-tokenized probe can never match segment-encoded ids.

Loader hardening: apply_ngram_weight_scale rejects NaN, infinite and zero scales with WeightScaleInvalid, split_merged_block_inject checks the scales and biases rank and leading dimension before slicing (MixDownSidecarShape), and restore_mlx_lm_patch_embed uses checked arithmetic for the config dimensions. Known limitations (assistant-prefill and media requests not segmented, tool-call names and arguments) stay documented.

Validation:
- cargo test --profile test-fast --features metal,accelerate --lib, filtered to qwen4_chat_segments, qwen4_moe_chat, models::qwen4_exp::layout (including parity tests) and the patch-embed test: all pass
- cargo clippy --lib --tests --features metal,accelerate -- -D warnings: clean
- cargo fmt --check: clean

Refs #3767

* fix: mark the qwen4_moe logit trace script executable
rromenskyi added a commit to ipsupport-llc/mlx-lm that referenced this pull request Dec 5, 2026
Qwen4 MoE image input: upstream ml-explore#2141 + the server's image path

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.

1 participant