Skip to content

feat(models): qualify Qwen3.8-27B on the qwen3_5 path - #1174

Merged
inureyes merged 4 commits into
mainfrom
feature/issue-1163-qualify-qwen38
Aug 15, 2026
Merged

inureyes merged 4 commits into
mainfrom
feature/issue-1163-qualify-qwen38

Conversation

@inureyes

@inureyes inureyes commented Aug 15, 2026 •

Copy link
Copy Markdown
Member

Summary

Qualifies mlx-community/Qwen3.8-27B-4bit on the existing qwen3_5 path. Qwen3.8-27B declares model_type: "qwen3_5" / Qwen3_5ForConditionalGeneration and is architecturally identical to Qwen3.5-27B down to a byte-identical weight-map key set, so it already loaded and ran on main with zero code changes. That was accidental rather than guaranteed: Qwen35Config carries no deny_unknown_fields, so every key the generation added was dropped silently, three of which are load-bearing upstream. This PR registers the checkpoint in the docs and the real-model tests and converts those silent drops into explicit reads or named errors. No new model family, no inference-math change.

Premise correction: the two upstream ports were already implemented

The issue asked to port two post-pin mlx-vlm fixes. Both were verified present on main @ 865bede2 before any code was written, so per CLAUDE.md ("Verify the premise before building. If it does not hold, correcting the premise with evidence is the deliverable") the deliverable became confirm, pin, and correct the issue. Neither was re-implemented, and neither was skipped. Both pins were re-verified by mutation testing during finalization (see below): forcing the mask helper to size from the matcher's vocabulary instead of the model's logits axis aborts the process on an MLX broadcast-shape mismatch, and dropping the MRoPE reuse condition's batch check fails its own regression test.

Neywa-Labs/mlx-vlm#1805, padded-vocab structured-output mask: already correct. apply_structured_mask_to_logits at src/server/structured.rs:736-788 already pins the bias length to vocab_size_hint, the model's logits axis, not to the matcher's vocabulary (let vocab_size = vocab_size_hint; at :747), and already masks every position in [matcher_vocab, vocab_size_hint) via let allowed = i < mask_len && constraint.mask_buf[i]; at :780. Its doc comment at :718-735 names this exact case ("the model has padded its embedding table beyond the tokenizer's natural vocabulary"). The scheduler call site at src/server/batch/scheduler.rs:2988 passes the hint through unchanged. What this PR adds instead is apply_mask_covers_the_qwen3_8_padded_lm_head in tests/structured_outputs.rs, which builds a synthetic 248,077-entry byte-level tokenizer and pins the real 248077-into-248320 shape: the bias must come back 248320 long, and all 243 unnameable rows must be -inf. The pre-existing generic test used a 16-row gap; this one fails with the checkpoint's own numbers if a refactor starts sizing the bias from the matcher. It runs in 0.48s.

Neywa-Labs/mlx-vlm#1741, chunked MRoPE position slice: already correct, and stronger. Qwen35Model::forward_with_mrope_state in src/models/qwen3_5.rs already sliced the stored position_ids to [cache_offset, cache_offset + seq_len) during chunked prefill, already validated pos_shape[1] == batch before reuse (Neywa-Labs/mlx-vlm#1040, which #1741 does not do), and already fell back to delta-based compute when the stored tensor no longer covered the window. The comment block already cited the upstream lineage. It was untestable without a 16 GB checkpoint, so the reuse decision moved into a pure mrope_position_source(stored_shape, batch, seq_len, cache_offset) -> MRopePositionSource helper covered by four unit tests. Behavior is byte-for-byte unchanged; the bare #1048 / #1040 cross-repo refs in that comment were also qualified per CLAUDE.md.

What changed

  • src/models/qwen3_5.rs: adds Qwen35Config::output_gate_type and mrope_interleaved(), a Qwen35UnsupportedConfig error enum, Qwen35Config::validate_supported() for the text-config keys, validate_qwen35_wrapper_config() for the top-level language_model_only, and the extracted mrope_position_source / MRopePositionSource pair that forward_with_mrope_state now calls.
  • Validation is wired into every Qwen3.5-family parse site, all six of them: Qwen35Model::load, the pipeline-stage loader, src/loading/vlm_qwen.rs (VLM), src/loading/special.rs (from-weights special path), src/distributed/tensor_parallel/llama_runtime.rs (TP), and (added in finalization) src/loading/vlm_special.rs's MiniCPM-V 4.6 text-backbone loader. MiniCPM-V 4.6 reuses Qwen35Config as its language backbone, and the gated-delta / MRoPE invariants validate_supported enforces belong to Qwen35Model itself, not to the qwen3_5 model_type string, so excluding this site was a review finding (S-M1) rather than a deliberate design choice. Both local MiniCPM-V 4.6 checkpoints (bf16 and mxfp4) were checked before wiring the call in: neither declares output_gate_type or mrope_interleaved, so no working load turns into a startup failure.
  • src/loading/vlm.rs: replaces qwen35_vlm_token_defaults() with qwen35_vl_token_ids(), which requires vision_start_token_id from the config for this family and keeps the image/video defaults. The stale 248045 fallback is gone. All three vision token ids are now range-checked against the checkpoint's own vocab_size (added in finalization; see S-M3 below). The shared qwen_vl_token_ids is untouched, so Qwen2-VL, Qwen2.5-VL, Qwen3-VL, Qwen3-VL MoE, and GLM-4V keep their existing defaults. vision_end_token_id is deliberately not read: nothing in the tree consumes it, so a field would be dead code.
  • src/models/qwen3_5_tests.rs: a config-shape fixture pinned to the published config.json (inline, so it runs without the checkpoint) asserting that output_gate_type, attn_output_gate, mamba_ssm_dtype, mtp_num_hidden_layers, the duplicated top-level partial_rotary_factor, the absent mlp_only_layers, and the nested generation_config all still parse; plus accept and reject cases for each of the three keys, and four mrope_position_source tests.
  • src/loading/vlm_tests.rs: a non-regression test walking the five families that still use qwen_vl_token_ids, and three tests for the new Qwen3.5 resolver.
  • tests/tensor_parallel_real_models.rs: qwen3_8_27b_tp4_matches_single_rank_stepwise, next to the existing qwen3.5-27b-4bit entry, using the same repo_model_dir + skip-if-absent pattern.
  • docs/supported-models.md: names mlx-community/Qwen3.8-27B-4bit as the validated checkpoint with the measured decode and cache-footprint numbers, states the three unsupported surfaces (MTP feat(inference): support the qwen3_5_mtp drafter for Qwen3.5/3.6/3.8 MTP speculative decoding #1165, video feat(models): video input for the Qwen VL families (Qwen3.5-VL / Qwen3.8, then the rest) #1166, no audio tower at all), and records that despite the family naming this is a vision-only VLM, not an omni model.

Finalization (post-review hardening)

Review and security passes reported no CRITICAL or HIGH findings. This pass closed five code findings and corrected three documentation findings; commits 4e2fab1e (code), 298b511e (docs + CHANGELOG.md), 7a9c6d87 (technical reports).

  • S-M1 (Medium): validate_supported() was missing from the sixth Qwen35Config parse site, the MiniCPM-V 4.6 text backbone (src/loading/vlm_special.rs). Fixed by wiring the call in, right after text_config is parsed and before any weight is read. Confirmed safe against both local MiniCPM-V 4.6 checkpoints first (see above).
  • S-M2 (Medium): validate_qwen35_wrapper_config and Qwen35Config::mrope_interleaved() used .as_bool(), so a present-but-wrong-typed value (language_model_only: "true"/1/{}, mrope_interleaved: "false"/0) silently read as absent and loaded instead of hitting the named error. Fixed with two new Qwen35UnsupportedConfig variants (LanguageModelOnlyWrongType, MropeInterleavedWrongType) and a private strict accessor used only by validate_supported.
  • S-M3 (Medium): qwen35_vl_token_ids cast vision_start_token_id/image_token_id/video_token_id from i64 to i32 with an unchecked truncating as i32; vision_start_token_id: 1099511627776 (2^40) used to truncate to 0 and -5 loaded unchanged, both with no diagnostic. Fixed with i32::try_from plus a range check against the checkpoint's own vocab_size, shared by all three ids via a new qwen35_vl_token_id_in_range helper.
  • R-M2 (Medium): output_gate_type matching was exact and case-sensitive against {"silu", "swish"}. Fixed with eq_ignore_ascii_case.
  • S-L2 (Low): The OutputGateType error echoed the offending config value uncapped; a 1,002,990-byte value reproduced as 1,000,568 bytes of process output. Fixed with a shared truncate_for_error helper (64-char cap) used by all three wrong-value error variants.
  • R-M1 (doc): Qwen3.5-VL and Qwen3.8-VL appeared in two consecutive docs/supported-models.md bullets. Collapsed to the one detailed bullet.
  • R-L1 (doc): The KV-footprint sentence called the measured 64.1 KiB/token figure "exactly" the 65,536 B/token (64.0 KiB) architectural minimum; they differ by about 0.16%. Reworded to state both numbers as the distinct things they are.
  • R-L2 (doc): The weight-map key list in that paragraph described the upstream Qwen/Qwen3.8-27B repo, not the mlx-community/Qwen3.8-27B-4bit conversion named as validated in the same sentence. Split the list and attributed each half to the repo it actually describes, verified against both checkpoints' model.safetensors.index.json.
  • CHANGELOG.md gained the ## [Unreleased] entry for feat(models): qualify and register Qwen3.8 (Qwen3.8-27B) on the existing qwen3_5 path #1163, including the upgrade note that making vision_start_token_id mandatory can turn a previously-working deployment into a startup failure if a checkpoint's config omits the key.

Finalization test plan (all commands DEVELOPER_DIR=/Applications/Xcode-26.6.0.app/Contents/Developer, --release --features metal,accelerate):

  • cargo test --release -p mlxcel --lib --features metal,accelerate qwen3_5 — 25 passed, 11 ignored (pre-existing serial-MLX gates), 0 failed.
  • cargo test --release -p mlxcel --lib --features metal,accelerate loading::vlm — 178 passed, 0 failed, including a new end-to-end wiring test (load_minicpmv4_6_vlm_rejects_an_unsupported_output_gate_type) that drives the real load_minicpmv4_6_vlm entry point rather than only the shared config helper.
  • cargo clippy --release --lib --tests --features metal,accelerate -- -D warnings — clean.
  • cargo fmt --check — clean.
  • Mutation-verified both premise-correction pins, then reverted: forcing apply_structured_mask_to_logits to size from the matcher vocabulary aborts apply_mask_covers_the_qwen3_8_padded_lm_head on an MLX broadcast-shape mismatch; dropping the shape[1] == batch check in mrope_position_source fails mrope_position_source_rejects_a_batch_mismatch_and_a_wrong_rank.

Test plan

Every command ran with DEVELOPER_DIR=/Applications/Xcode-26.6.0.app/Contents/Developer and --release --features metal,accelerate (the debug profile cannot build on this box).

  • cargo test --release -p mlxcel --lib --features metal,accelerate qwen3_5_tests:: — 11 passed, 11 ignored (pre-existing serial-MLX gates), 0 failed.
  • cargo test --release -p mlxcel --lib --features metal,accelerate loading::vlm — 173 passed, 0 failed.
  • cargo test --release -p mlxcel --lib --features metal,accelerate qwen35 — 10 passed, 4 ignored (need CUDA), 0 failed.
  • cargo test --release --features metal,accelerate --test structured_outputs — 16 passed, 2 ignored (need local weights), 0 failed, including the new padded-lm_head test.
  • cargo clippy --release --features metal,accelerate -p mlxcel --lib --tests -- -D warnings — clean.
  • cargo fmt on every touched file; python3 scripts/ci/check_cross_repo_refs.py — OK.
  • Real checkpoint, CLI text: mlxcel generate -m models/qwen3.8-27b-4bit -p "What is 17 times 23?" -n 300 --temp 0 answers 391 at 18.81 tok/s, within noise of the 18.21 tok/s baseline recorded in the issue.
  • Real checkpoint, CLI image: 224x224 synthetic PNG (red circle, blue square), --image ... -p "Describe the shapes and their colors" -n 400 --temp 0 inserts 49 image tokens and names both shapes with the correct colors and positions.
  • Shared-path non-regression, other Qwen VL families: models/qwen3.5-27b-4bit (49 image tokens, both shapes correct), models/qwen3-vl-4b-4bit (49 image tokens, both shapes correct), models/qwen2.5-vl-3b-4bit (64 image tokens, loads and answers; the answer quality is that 3B model's own, and the code path is untouched by this PR).
  • All four rejection paths driven end to end against config variants of the real 16 GB checkpoint (weights symlinked, config.json patched): language_model_only: true, output_gate_type: "sigmoid", mrope_interleaved: false, and a removed vision_start_token_id each abort the load with their named error instead of loading.

Not verified here: the server surface (text and image over /v1/chat/completions) was not re-run, since the change is confined to config validation at load time and to token-id resolution, both of which the CLI exercises on the same code path. The TP real-model test is #[ignore]d in line with its Qwen3.5 sibling and was not run.

Closes #1163

Qwen3.8-27B declares `model_type: "qwen3_5"` and is architecturally identical to Qwen3.5-27B, so it already loaded and ran on main with zero code changes. That was accidental rather than guaranteed: `Qwen35Config` carries no `deny_unknown_fields`, so every key the generation added was dropped silently, including three that are load-bearing upstream. This registers the checkpoint and converts those silent drops into explicit reads or named errors.

Three ignored keys now fail loudly instead of loading wrong. `text_config.output_gate_type` selects the gated-delta output gate in vLLM; mlxcel hardcodes SiLU in `RMSNormGated::forward`, so `Qwen35Config::validate_supported` accepts `silu`, `swish`, and absent, and rejects anything else (notably `sigmoid`). `rope_parameters.mrope_interleaved` is rejected when explicitly `false`, since `InterleavedMRoPE` is unconditional. Top-level `language_model_only: true` is rejected by `validate_qwen35_wrapper_config` in the VLM loader only, matching the still-open upstream gap in Neywa-Labs/mlx-vlm#1812; it is not an error on the text-only path, where a vision-stripped checkpoint is what the caller asked for. Validation is wired into every Qwen3.5-family parse site: the text loader, the pipeline-stage loader, the VLM loader, the from-weights special path, and the tensor-parallel runtime.

The Qwen3.5 family no longer defaults `vision_start_token_id`. The old 248045 fallback is stale for every shipped checkpoint in the family (Qwen3.5-0.8B through 27B, the 3.5/3.6 MoE builds, and Qwen3.8-27B all declare 248053), and a wrong start id mis-segments MRoPE vision spans quietly instead of failing. `qwen35_vl_token_ids` requires the key and keeps the image/video defaults, which do match. The shared `qwen_vl_token_ids` is untouched, so Qwen2-VL, Qwen2.5-VL, Qwen3-VL, Qwen3-VL MoE, and GLM-4V keep their own defaults; a new test pins that.

Premise correction on the two upstream ports the issue asked for. Both were already implemented on main and neither needed porting. `apply_structured_mask_to_logits` (src/server/structured.rs:736-788) already sizes the bias from the model's logits axis and masks the padded rows, which is what Neywa-Labs/mlx-vlm#1805 fixes. `forward_with_mrope_state` already sliced the stored `position_ids` to the chunk window and additionally validated the batch dimension, a superset of Neywa-Labs/mlx-vlm#1741. What landed instead is coverage: a regression test pinning the 248077-into-248320 shape at production magnitudes, and the MRoPE reuse decision extracted into a pure `mrope_position_source` helper with four unit tests. Behavior is unchanged in both cases.

Validated on the real checkpoint at models/qwen3.8-27b-4bit. CLI text answers 17x23 correctly at 18.81 tok/s, CLI image names both shapes in the synthetic fixture. Qwen3.5-27B, Qwen2.5-VL-3B, and Qwen3-VL-4B all still load and answer, proving the shared token-id path did not regress. All four rejection paths were driven end to end against config variants of the real checkpoint and produced their named errors.

Refs #1163
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata area:docs User and developer documentation modelsize:medium 4-bit checkpoint 10-50GB; comfortable on a 128GB dev box modeltype:vlm Vision-language model arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) status:review Under review labels Aug 15, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Qualify mlx-community/Qwen3.8-27B-4bit on the existing qwen3_5 path: register it in docs and tests, convert three silently dropped config keys into named errors, stop defaulting vision_start_token_id for this family, and pin (rather than re-implement) the two upstream fixes that were already present.

Findings Addressed

None. No CRITICAL or HIGH finding was raised, so no auto-fix commit was made and the branch is unchanged at 34f14df3.

Verification performed

Shared VLM path, regression risk:

  • qwen_vl_token_ids is byte-for-byte identical between main and HEAD (compared as text, not only as a diff hunk).
  • Exactly one call site moved to the strict resolver: load_qwen3_5_vlm_with_variant. The other seven qwen_vl_token_ids call sites (Qwen2-VL, Qwen2.5-VL, Qwen3-VL, Qwen3-VL MoE, GLM-4V and the remaining two) are untouched.
  • The strict resolver is reachable only when vision_config is present, because detect_text_or_vlm routes on that key. A text-only qwen3_5 checkpoint never reaches it. Locally, qwen3.5-0.8b-optiq-4bit is exactly that shape and is unaffected.
  • All 11 local qwen3_5 / qwen3_5_moe checkpoints declare vision_start_token_id: 248053, not the seven cited in the PR body.
  • No production code in the tree writes a config.json, and sanitize_config_json only rewrites Infinity / NaN, so there is no in-tree path that could strip the now-required key.
  • MiniCPM-V 4.6 loads through src/loading/vlm_special.rs with its own MiniCPMO processor and never calls either token-id resolver, so reusing Qwen35Config as a text backbone does not put it on the strict path.

Rejection scoping:

  • output_gate_type: accepts silu, swish, and absent; rejects everything else. Accept and reject cases both tested.
  • mrope_interleaved: accepts true and absent; rejects only explicit false. Accept and reject cases both tested.
  • language_model_only: validate_qwen35_wrapper_config is called only from the VLM loader, so the text-only path is unaffected. Accept (false and absent) and reject (true) cases tested.
  • validate_supported() is wired into five of the six production Qwen35Config parse sites; the sixth is MiniCPM-V 4.6, left out deliberately and documented.

Premise-correction pinning tests, checked by mutation:

  • Mutating mrope_position_source to drop the shape[1] == batch check and force the slice window to [0, seq_len) fails mrope_position_source_rejects_a_batch_mismatch_and_a_wrong_rank and mrope_position_source_slices_each_chunk_of_a_chunked_prefill. Both pins are real.
  • Mutating apply_structured_mask_to_logits to size the bias from the matcher vocabulary instead of vocab_size_hint fails apply_mask_covers_the_qwen3_8_padded_lm_head with the checkpoint's own numbers (Shapes (1,248320) and (1,248077) cannot be broadcast). The pin is real.

Documentation, checked against the artifacts:

  • 2180 weight-map keys, byte-identical to qwen3.5-27b-4bit: confirmed.
  • mtp.* present in the HF bf16 repo (15 tensors) and dropped by the mlx-community 4-bit conversion (0): confirmed.
  • No audio_config / audio_tower / thinker_config / talker_config: confirmed.
  • Tokenizer 248,044 vocab plus 33 added tokens equals the 248,077 stated, against vocab_size: 248320: confirmed.
  • 16 x 4 x 256 x 2 x 2 = 65,536 B/token, and 262,144 tokens x 65,536 B = 16 GiB: confirmed.

Remaining Items

  • docs/supported-models.md: Qwen3.5-VL and Qwen3.8-VL now appear in two consecutive bullets, the summary line and the new detail bullet (MEDIUM). Every other family in that list appears once.
  • output_gate_type matching is exact and case-sensitive against {"silu", "swish"} (MEDIUM). A checkpoint spelling it "SiLU" would hard-fail a load that the implemented path handles correctly. No published checkpoint does this; eq_ignore_ascii_case would close it.
  • docs/supported-models.md: "64.1 KiB per token, which is exactly ... 65,536 B/token" (LOW). 65,536 B is 64.0 KiB. The measured fit and the architectural minimum differ by about 0.16 percent, so "exactly" overstates it.
  • docs/supported-models.md: the weight-map list (model.language_model.*, model.visual.*, mtp.*, lm_head.weight) describes the upstream Qwen/Qwen3.8-27B repo, while the named validated checkpoint in the same paragraph is the mlx-community 4-bit conversion, whose map is language_model.* / vision_tower.* with mtp.* dropped (LOW).
  • mrope_position_source is pinned at the helper level only (LOW). A regression that reverted forward_with_mrope_state to a naive head slice, or dropped the helper call, would leave all four unit tests green. Acknowledged in the PR body as a checkpoint-size constraint.
  • Two .expect() calls carry the SliceStored invariant in forward_with_mrope_state (LOW). Provably unreachable and documented, but expect in library code is against the project Rust standards.
  • MiniCPM-V 4.6 keeps the old silent-drop behavior for output_gate_type and mrope_interleaved (LOW). Deliberate and documented; no such checkpoint exists.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL and no HIGH findings, so nothing was auto-fixed and no commits were pushed. Three MEDIUM and three LOW items below, plus the negative results, which are the more useful half of this review.

Verified clean

No panic on adversarial config. 14 malformed config.json variants were run through a release binary built from 34f14df3: output_gate_type as number, object, array, bool, and null; rope_parameters as string, number, and array; mrope_interleaved as string and integer; and 5,000-level nesting. Every one produced a clean Error: line. Deep nesting is caught by serde_json's 128-level recursion limit (parse_vlm_config uses from_str, src/loading/vlm.rs:166) and reports failed to parse config.json with no stack overflow.

No terminal escape or log injection. The only new error interpolating config content is OutputGateType, and it uses {0:?}. Feeding it a value containing ESC, BEL, CRLF, and a forged log line produced output_gate_type="\u{1b}[2J\u{1b}]0;pwned\u{7}sigmoid\r\n2026-08-16 ERROR forged log line" with zero raw ESC bytes in the process output. Debug for str routes through char::escape_debug, which escapes CR, LF, quote, backslash and unicode-escapes every non-printable, so both the terminal-control and the forged-log-line vectors are closed. Nothing sensitive is echoed: the messages carry a config key, a config value, and an operator-supplied model directory path.

The two .expect() calls are genuinely unreachable. stored_shape is Some iff entry.position_ids is Some, and mrope_position_source returns SliceStored only for a Some shape, so both hold by construction inside a 12-line block. The slice bounds are safe too: cache_offset comes from kv.offset (non-negative) and shape[2] >= cache_offset + seq_len is checked before slicing. No crafted config or cache state reaches them.

Performance is neutral. All three validators run once per model load, from the five loader entry points, never per request or per token. mrope_position_source is allocation-neutral in the decode path: before, one Vec<i32> from array_shape inside the if let Some arm; after, the same single Vec<i32> via .map(), still only when position_ids is Some, plus a free as_deref(). Same &MlxArray handed to slice, no extra copy. [profile.release] carries lto = true and codegen-units = 1, so the extracted free function inlines. cargo clippy --release --features metal,accelerate --lib --all-targets -- -D warnings exits 0, and the 11 new qwen3_5_tests pass.

MEDIUM

M1. validate_supported() is missing from the sixth Qwen35Config call site. src/loading/vlm_special.rs:510 parses a Qwen35Config for MiniCPM-V 4.6 and hands it to models::Qwen35Model::from_weights at :556, which builds the same RMSNormGated hardcoded-SiLU gated-delta layers. The PR added the call at the other five sites (qwen3_5.rs:1519, qwen3_5.rs:2250, vlm_qwen.rs:401, special.rs:118, llama_runtime.rs:318) but not this one, so a MiniCPM-V 4.6 checkpoint declaring output_gate_type: "sigmoid" still gets exactly the silently-wrong-output mode this PR set out to close. The invariant belongs to Qwen35Model, not to the qwen3_5 model_type string. One line after the parse.

M2. Two of the three new guards are bypassed by a type mismatch, silently. validate_qwen35_wrapper_config and mrope_interleaved() both use .as_bool(), so a present-but-wrong-typed value reads as absent. Confirmed on the release binary: language_model_only: "true", language_model_only: 1, language_model_only: {}, mrope_interleaved: "false", and mrope_interleaved: 0 all pass validation and proceed to load. output_gate_type behaves differently because it is a typed serde field and correctly rejects a non-string. Three guards documented as equivalent have two different strictness policies, and mrope_interleaved: "false" is precisely the "produce silently wrong output" case the error text names.

M3. vision_start_token_id is checked for presence but not for range. qwen35_vl_token_ids does .as_i64()...? as i32, an unchecked truncating cast. Verified against the real 16 GB checkpoint with the weights symlinked: vision_start_token_id: 1099511627776 (2^40, truncates to 0) and vision_start_token_id: -5 both load and generate with no diagnostic at all. The justification for making the key mandatory is in its own error string, "a wrong start id silently mis-segments vision spans in MRoPE position assignment instead of failing", and an out-of-range value reproduces that failure mode while passing the new guard. i32::try_from plus a 0..vocab_size check would close it. Same pattern on image_token_id and video_token_id in the same function.

LOW

L1. Availability blast radius of the mandatory vision_start_token_id. The requirement lands on the whole family, both Qwen35VlmVariant::Dense and ::Moe, not just Qwen3.8. Any VLM checkpoint routing through load_qwen3_5_vlm_with_variant whose top-level config omits the key now fails to start where it previously started on the stale 248045 default. All three local qwen3_5-family VLM checkpoints supply vision_start_token_id: 248053 at the top level. Text-only qwen3_5 checkpoints have no vision_config and route to the text path, so they are unaffected, and qwen3_5_mtp is a different model_type. The change is correctly fail-closed, since a wrong start id degrades silently and that is worse, the message names the exact fix, and the failure is at startup rather than mid-serving. Two residual notes: the lookup is top-level only, so a checkpoint nesting the key under text_config fails (no local checkpoint does, and the shared qwen_vl_token_ids makes the same assumption), and this is worth a release-note line because it can turn a working server deployment into a startup failure on upgrade.

L2. Unbounded config value echoed into the error. Measured: a config with a 1,002,990-byte output_gate_type produced 1,000,568 bytes of process output, a 1:1 amplification of config content into logs. Not a DoS vector, because model load is startup-only and the path comes from the CLI rather than a request (model_path at src/server/model_worker.rs:194 is set at worker construction, and there is no request-driven model-load surface). Truncating the quoted value to something like 64 chars would close it.

L3. The new .expect() pair re-derives an invariant the types could carry. Unreachable as analyzed above, so this is style rather than risk, but it is the one new expect the PR adds and the tree's Rust convention is to avoid it in library code. Hoisting the match inside if let Some(stored_pos) = entry.position_ids.as_ref() and passing the shape down removes both with no behavior change.

… review

Wires `Qwen35Config::validate_supported()` into the MiniCPM-V 4.6 text-backbone loader, the sixth Qwen3.5-family parse site that PR #1174 deliberately skipped; the invariant belongs to `Qwen35Model`, not to the `qwen3_5` model_type string, so a MiniCPM-V 4.6 checkpoint declaring `output_gate_type: "sigmoid"` reproduced the exact silently-wrong-output failure the PR set out to close. Verified against both local MiniCPM-V 4.6 checkpoints (bf16 and mxfp4): neither declares `output_gate_type` or `mrope_interleaved`, so no working load turns into a failure.

`validate_qwen35_wrapper_config` and `Qwen35Config::mrope_interleaved()` used `.as_bool()`, so a present-but-wrong-typed value (`language_model_only: "true"`, `1`, `{}`; `mrope_interleaved: "false"`, `0`) read as absent and loaded silently instead of hitting the named error the correctly-typed value would trigger. Both are now checked strictly through new named errors (`LanguageModelOnlyWrongType`, `MropeInterleavedWrongType`), with the offending value capped to 64 characters before it is echoed into the error text.

`qwen35_vl_token_ids` cast `vision_start_token_id` (and `image_token_id`/`video_token_id`) from `i64` to `i32` with an unchecked `as i32`; a checkpoint value like 2^40 truncated to 0 and a negative value passed through unchanged, both loading with no diagnostic. All three ids are now converted with `i32::try_from` and bounds-checked against the checkpoint's own `vocab_size`.

`output_gate_type` matching was exact and case-sensitive against `{"silu", "swish"}`; a checkpoint spelling it `"SiLU"` would have hard-failed a load the implemented path already handles correctly. Matching is now case-insensitive via `eq_ignore_ascii_case`.

Validation: `cargo test --release -p mlxcel --lib --features metal,accelerate qwen3_5` (25 passed, 11 ignored, 0 failed) and `... loading::vlm` (178 passed, 0 failed), `cargo clippy --release --lib --tests --features metal,accelerate -- -D warnings` (clean), `cargo fmt --check` (clean). Both premise-correction pins from the parent PR were mutation-verified and then reverted: forcing `apply_structured_mask_to_logits` to size the bias from the matcher vocabulary instead of `vocab_size_hint` aborts the process on an MLX broadcast-shape mismatch, and dropping the `shape[1] == batch` check in `mrope_position_source` fails `mrope_position_source_rejects_a_batch_mismatch_and_a_wrong_rank`.

Refs #1163, #1174
… attribution

`docs/supported-models.md`: Qwen3.5-VL and Qwen3.8-VL appeared in two consecutive bullets, the family summary line and the detailed entry right after it; every other family in that list appears once, so the summary line now omits them and the detail bullet stays the only mention. The KV-footprint sentence claimed the measured 64.1 KiB/token figure was "exactly" the 65,536 B/token (64.0 KiB) architectural minimum for the 16 full-attention layers; the two differ by about 0.16%, so the wording now states the measured and theoretical numbers as the two distinct things they are instead of collapsing them into one. The weight-map key list (`model.language_model.*`, `model.visual.*`, `mtp.*`, `lm_head.weight`) described the upstream `Qwen/Qwen3.8-27B` repo, while the checkpoint named as validated in that same sentence is the `mlx-community` 4-bit conversion, whose weight map is `language_model.*` (with `lm_head.*` folded inside that prefix) and `vision_tower.*`, with `mtp.*` dropped entirely; verified against both checkpoints' `model.safetensors.index.json` locally. Each list is now attributed to the repo it actually describes.

`CHANGELOG.md`: adds the `## [Unreleased]` entry for #1163, including the upgrade note that making `vision_start_token_id` mandatory for the Qwen3.5-family VLM path can turn a previously-working server deployment into a startup failure if a checkpoint's config omits the key.

Refs #1163, #1174
Records the five code findings closed and three doc findings corrected during finalization, the local-checkpoint check that cleared S-M1's new validate_supported() call site before wiring it in, and the mutation-verified confirmation of both premise-correction pins (the padded-vocab structured-output mask and the chunked-MRoPE position-slice reuse condition) that PR #1174 confirmed rather than re-implemented.

Refs #1163, #1174
@inureyes

Copy link
Copy Markdown
Member Author

Orchestrator verification

Full workspace suite re-run after the finalization commits, cargo test --release --workspace --features metal,accelerate --no-fail-fast with DEVELOPER_DIR set to Xcode 26.6.0.

Totals: 6059 passed, 4 failed. The mlxcel lib went 5621 (pre-PR baseline) to 5665, so this PR net-added 44 tests.

Both failure groups are pre-existing and attributed, neither is a regression:

  1. Three multimodal::video::tests::* — ffmpeg 9 removed -vsync, which src/multimodal/video.rs:1123 still passes. Filed as fix(video): every video path is broken on ffmpeg 8+ because -vsync was removed, and the tests hide it by passing when ffmpeg is absent #1172. This PR touches 0 lines of that file. A PATH-controlled experiment on the same binary gives 34 passed / 0 failed with ffmpeg hidden versus 31 passed / 3 failed with ffmpeg 9.0.1 present.
  2. One hunyuan_vl_parity::text_only_forward_produces_finite_logits — this is fix: Resolve flaky text_only_forward_produces_finite_logits in granite4_vision and hunyuan_vl parity tests #997, which names this exact file, line, and assertion (tests/hunyuan_vl_parity.rs:105, "text-only logits must be finite") and predates this work. Attribution checked rather than assumed: hunyuan loads through src/loading/vlm_hunyuan_vl.rs, untouched here, and five standalone repeats of that single test on this branch gave 4 passed / 1 failed, so the flake is present independently of the whole-suite context. New evidence contributed back to fix: Resolve flaky text_only_forward_produces_finite_logits in granite4_vision and hunyuan_vl parity tests #997: the hunyuan case now reproduces in isolation at roughly 20 percent, which contradicts the "passes every time in isolation" premise currently in that issue body.

Real-checkpoint validation

Server surface re-verified on this branch against models/qwen3.8-27b-4bit, since the implementer's report listed it as not run:

request result usage.prompt_tokens
text, temperature 0 391 66
image (base64 data URI) + text "The image contains a red circle and a blue square." 102

Both prompt_tokens values are byte-identical to the pre-change baseline measured on main before this PR, which is the useful part: the token-id resolution change did not shift prompt construction.

On the premise correction

Worth restating for the record, because it changed what this PR is. Two of the issue's six deliverables asked to port Neywa-Labs/mlx-vlm#1805 and #1741. Both were already implemented in this tree, and #1741's equivalent here is strictly stronger than upstream (it also validates the batch dimension before reusing stored positions). The deliverable became confirm-and-pin, and both pins were mutation-verified twice, independently, by the reviewer and the finalizer.

That correction is the orchestrator's error to own: the issue was written without checking the code closely enough. Recording it here so the next person reads the pins as deliberate rather than redundant.

@inureyes
inureyes merged commit 0de77ce into main Aug 15, 2026
7 checks passed
@inureyes
inureyes deleted the feature/issue-1163-qualify-qwen38 branch August 15, 2026 22:15
@inureyes inureyes self-assigned this Aug 27, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
## Summary

Qualifies `mlx-community/Qwen3.8-27B-4bit` on the existing `qwen3_5` path. Qwen3.8-27B declares `model_type: "qwen3_5"` / `Qwen3_5ForConditionalGeneration` and is architecturally identical to Qwen3.5-27B down to a byte-identical weight-map key set, so it already loaded and ran on `main` with zero code changes. That was accidental rather than guaranteed: `Qwen35Config` carries no `deny_unknown_fields`, so every key the generation added was dropped silently, three of which are load-bearing upstream. This PR registers the checkpoint in the docs and the real-model tests and converts those silent drops into explicit reads or named errors. No new model family, no inference-math change.

## Premise correction: the two upstream ports were already implemented

The issue asked to port two post-pin mlx-vlm fixes. Both were verified present on `main` @ `865bede2` before any code was written, so per CLAUDE.md ("Verify the premise before building. If it does not hold, correcting the premise with evidence *is* the deliverable") the deliverable became confirm, pin, and correct the issue. Neither was re-implemented, and neither was skipped. Both pins were re-verified by mutation testing during finalization (see below): forcing the mask helper to size from the matcher's vocabulary instead of the model's logits axis aborts the process on an MLX broadcast-shape mismatch, and dropping the MRoPE reuse condition's batch check fails its own regression test.

**Neywa-Labs/mlx-vlm#1805, padded-vocab structured-output mask: already correct.** `apply_structured_mask_to_logits` at `src/server/structured.rs:736-788` already pins the bias length to `vocab_size_hint`, the model's logits axis, not to the matcher's vocabulary (`let vocab_size = vocab_size_hint;` at `:747`), and already masks every position in `[matcher_vocab, vocab_size_hint)` via `let allowed = i < mask_len && constraint.mask_buf[i];` at `:780`. Its doc comment at `:718-735` names this exact case ("the model has padded its embedding table beyond the tokenizer's natural vocabulary"). The scheduler call site at `src/server/batch/scheduler.rs:2988` passes the hint through unchanged. What this PR adds instead is `apply_mask_covers_the_qwen3_8_padded_lm_head` in `tests/structured_outputs.rs`, which builds a synthetic 248,077-entry byte-level tokenizer and pins the real 248077-into-248320 shape: the bias must come back 248320 long, and all 243 unnameable rows must be `-inf`. The pre-existing generic test used a 16-row gap; this one fails with the checkpoint's own numbers if a refactor starts sizing the bias from the matcher. It runs in 0.48s.

**Neywa-Labs/mlx-vlm#1741, chunked MRoPE position slice: already correct, and stronger.** `Qwen35Model::forward_with_mrope_state` in `src/models/qwen3_5.rs` already sliced the stored `position_ids` to `[cache_offset, cache_offset + seq_len)` during chunked prefill, already validated `pos_shape[1] == batch` before reuse (Neywa-Labs/mlx-vlm#1040, which lablup#1741 does not do), and already fell back to delta-based compute when the stored tensor no longer covered the window. The comment block already cited the upstream lineage. It was untestable without a 16 GB checkpoint, so the reuse decision moved into a pure `mrope_position_source(stored_shape, batch, seq_len, cache_offset) -> MRopePositionSource` helper covered by four unit tests. Behavior is byte-for-byte unchanged; the bare `lablup#1048` / `lablup#1040` cross-repo refs in that comment were also qualified per CLAUDE.md.

## What changed

- `src/models/qwen3_5.rs`: adds `Qwen35Config::output_gate_type` and `mrope_interleaved()`, a `Qwen35UnsupportedConfig` error enum, `Qwen35Config::validate_supported()` for the text-config keys, `validate_qwen35_wrapper_config()` for the top-level `language_model_only`, and the extracted `mrope_position_source` / `MRopePositionSource` pair that `forward_with_mrope_state` now calls.
- Validation is wired into every Qwen3.5-family parse site, all six of them: `Qwen35Model::load`, the pipeline-stage loader, `src/loading/vlm_qwen.rs` (VLM), `src/loading/special.rs` (from-weights special path), `src/distributed/tensor_parallel/llama_runtime.rs` (TP), and (added in finalization) `src/loading/vlm_special.rs`'s MiniCPM-V 4.6 text-backbone loader. MiniCPM-V 4.6 reuses `Qwen35Config` as its language backbone, and the gated-delta / MRoPE invariants `validate_supported` enforces belong to `Qwen35Model` itself, not to the `qwen3_5` model_type string, so excluding this site was a review finding (S-M1) rather than a deliberate design choice. Both local MiniCPM-V 4.6 checkpoints (bf16 and mxfp4) were checked before wiring the call in: neither declares `output_gate_type` or `mrope_interleaved`, so no working load turns into a startup failure.
- `src/loading/vlm.rs`: replaces `qwen35_vlm_token_defaults()` with `qwen35_vl_token_ids()`, which requires `vision_start_token_id` from the config for this family and keeps the image/video defaults. The stale 248045 fallback is gone. All three vision token ids are now range-checked against the checkpoint's own `vocab_size` (added in finalization; see S-M3 below). The shared `qwen_vl_token_ids` is untouched, so Qwen2-VL, Qwen2.5-VL, Qwen3-VL, Qwen3-VL MoE, and GLM-4V keep their existing defaults. `vision_end_token_id` is deliberately not read: nothing in the tree consumes it, so a field would be dead code.
- `src/models/qwen3_5_tests.rs`: a config-shape fixture pinned to the published `config.json` (inline, so it runs without the checkpoint) asserting that `output_gate_type`, `attn_output_gate`, `mamba_ssm_dtype`, `mtp_num_hidden_layers`, the duplicated top-level `partial_rotary_factor`, the absent `mlp_only_layers`, and the nested `generation_config` all still parse; plus accept and reject cases for each of the three keys, and four `mrope_position_source` tests.
- `src/loading/vlm_tests.rs`: a non-regression test walking the five families that still use `qwen_vl_token_ids`, and three tests for the new Qwen3.5 resolver.
- `tests/tensor_parallel_real_models.rs`: `qwen3_8_27b_tp4_matches_single_rank_stepwise`, next to the existing `qwen3.5-27b-4bit` entry, using the same `repo_model_dir` + skip-if-absent pattern.
- `docs/supported-models.md`: names `mlx-community/Qwen3.8-27B-4bit` as the validated checkpoint with the measured decode and cache-footprint numbers, states the three unsupported surfaces (MTP lablup#1165, video lablup#1166, no audio tower at all), and records that despite the family naming this is a vision-only VLM, not an omni model.

## Finalization (post-review hardening)

Review and security passes reported no CRITICAL or HIGH findings. This pass closed five code findings and corrected three documentation findings; commits `4e2fab1e` (code), `298b511e` (docs + `CHANGELOG.md`), `7a9c6d87` (technical reports).

- **S-M1** (Medium): `validate_supported()` was missing from the sixth `Qwen35Config` parse site, the MiniCPM-V 4.6 text backbone (`src/loading/vlm_special.rs`). Fixed by wiring the call in, right after `text_config` is parsed and before any weight is read. Confirmed safe against both local MiniCPM-V 4.6 checkpoints first (see above).
- **S-M2** (Medium): `validate_qwen35_wrapper_config` and `Qwen35Config::mrope_interleaved()` used `.as_bool()`, so a present-but-wrong-typed value (`language_model_only: "true"`/`1`/`{}`, `mrope_interleaved: "false"`/`0`) silently read as absent and loaded instead of hitting the named error. Fixed with two new `Qwen35UnsupportedConfig` variants (`LanguageModelOnlyWrongType`, `MropeInterleavedWrongType`) and a private strict accessor used only by `validate_supported`.
- **S-M3** (Medium): `qwen35_vl_token_ids` cast `vision_start_token_id`/`image_token_id`/`video_token_id` from `i64` to `i32` with an unchecked truncating `as i32`; `vision_start_token_id: 1099511627776` (2^40) used to truncate to 0 and `-5` loaded unchanged, both with no diagnostic. Fixed with `i32::try_from` plus a range check against the checkpoint's own `vocab_size`, shared by all three ids via a new `qwen35_vl_token_id_in_range` helper.
- **R-M2** (Medium): `output_gate_type` matching was exact and case-sensitive against `{"silu", "swish"}`. Fixed with `eq_ignore_ascii_case`.
- **S-L2** (Low): The `OutputGateType` error echoed the offending config value uncapped; a 1,002,990-byte value reproduced as 1,000,568 bytes of process output. Fixed with a shared `truncate_for_error` helper (64-char cap) used by all three wrong-value error variants.
- **R-M1** (doc): Qwen3.5-VL and Qwen3.8-VL appeared in two consecutive `docs/supported-models.md` bullets. Collapsed to the one detailed bullet.
- **R-L1** (doc): The KV-footprint sentence called the measured 64.1 KiB/token figure "exactly" the 65,536 B/token (64.0 KiB) architectural minimum; they differ by about 0.16%. Reworded to state both numbers as the distinct things they are.
- **R-L2** (doc): The weight-map key list in that paragraph described the upstream `Qwen/Qwen3.8-27B` repo, not the `mlx-community/Qwen3.8-27B-4bit` conversion named as validated in the same sentence. Split the list and attributed each half to the repo it actually describes, verified against both checkpoints' `model.safetensors.index.json`.
- `CHANGELOG.md` gained the `## [Unreleased]` entry for lablup#1163, including the upgrade note that making `vision_start_token_id` mandatory can turn a previously-working deployment into a startup failure if a checkpoint's config omits the key.

Finalization test plan (all commands `DEVELOPER_DIR=/Applications/Xcode-26.6.0.app/Contents/Developer`, `--release --features metal,accelerate`):

- [x] `cargo test --release -p mlxcel --lib --features metal,accelerate qwen3_5` — 25 passed, 11 ignored (pre-existing serial-MLX gates), 0 failed.
- [x] `cargo test --release -p mlxcel --lib --features metal,accelerate loading::vlm` — 178 passed, 0 failed, including a new end-to-end wiring test (`load_minicpmv4_6_vlm_rejects_an_unsupported_output_gate_type`) that drives the real `load_minicpmv4_6_vlm` entry point rather than only the shared config helper.
- [x] `cargo clippy --release --lib --tests --features metal,accelerate -- -D warnings` — clean.
- [x] `cargo fmt --check` — clean.
- [x] Mutation-verified both premise-correction pins, then reverted: forcing `apply_structured_mask_to_logits` to size from the matcher vocabulary aborts `apply_mask_covers_the_qwen3_8_padded_lm_head` on an MLX broadcast-shape mismatch; dropping the `shape[1] == batch` check in `mrope_position_source` fails `mrope_position_source_rejects_a_batch_mismatch_and_a_wrong_rank`.

## Test plan

Every command ran with `DEVELOPER_DIR=/Applications/Xcode-26.6.0.app/Contents/Developer` and `--release --features metal,accelerate` (the debug profile cannot build on this box).

- [x] `cargo test --release -p mlxcel --lib --features metal,accelerate qwen3_5_tests::` — 11 passed, 11 ignored (pre-existing serial-MLX gates), 0 failed.
- [x] `cargo test --release -p mlxcel --lib --features metal,accelerate loading::vlm` — 173 passed, 0 failed.
- [x] `cargo test --release -p mlxcel --lib --features metal,accelerate qwen35` — 10 passed, 4 ignored (need CUDA), 0 failed.
- [x] `cargo test --release --features metal,accelerate --test structured_outputs` — 16 passed, 2 ignored (need local weights), 0 failed, including the new padded-lm_head test.
- [x] `cargo clippy --release --features metal,accelerate -p mlxcel --lib --tests -- -D warnings` — clean.
- [x] `cargo fmt` on every touched file; `python3 scripts/ci/check_cross_repo_refs.py` — OK.
- [x] Real checkpoint, CLI text: `mlxcel generate -m models/qwen3.8-27b-4bit -p "What is 17 times 23?" -n 300 --temp 0` answers `391` at 18.81 tok/s, within noise of the 18.21 tok/s baseline recorded in the issue.
- [x] Real checkpoint, CLI image: 224x224 synthetic PNG (red circle, blue square), `--image ... -p "Describe the shapes and their colors" -n 400 --temp 0` inserts 49 image tokens and names both shapes with the correct colors and positions.
- [x] Shared-path non-regression, other Qwen VL families: `models/qwen3.5-27b-4bit` (49 image tokens, both shapes correct), `models/qwen3-vl-4b-4bit` (49 image tokens, both shapes correct), `models/qwen2.5-vl-3b-4bit` (64 image tokens, loads and answers; the answer quality is that 3B model's own, and the code path is untouched by this PR).
- [x] All four rejection paths driven end to end against config variants of the real 16 GB checkpoint (weights symlinked, `config.json` patched): `language_model_only: true`, `output_gate_type: "sigmoid"`, `mrope_interleaved: false`, and a removed `vision_start_token_id` each abort the load with their named error instead of loading.

Not verified here: the server surface (text and image over `/v1/chat/completions`) was not re-run, since the change is confined to config validation at load time and to token-id resolution, both of which the CLI exercises on the same code path. The TP real-model test is `#[ignore]`d in line with its Qwen3.5 sibling and was not run.

Closes lablup#1163
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) area:docs User and developer documentation area:models Model architectures, weights, loading, metadata modelsize:medium 4-bit checkpoint 10-50GB; comfortable on a 128GB dev box modeltype:vlm Vision-language model priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(models): qualify and register Qwen3.8 (Qwen3.8-27B) on the existing qwen3_5 path

1 participant