Repository navigation
Conversation
jundot
force-pushed
the
qwen4-moe-vision
branch
from
December 4, 2026 01:42
b009360 to
9e1accb
Compare
This was referenced Dec 4, 2026
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
5 tasks done
This was referenced Dec 5, 2026
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
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.
* 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