Skip to content

feat(models): add the Kimi K3 text backbone - #1741

Merged
inureyes merged 9 commits into
mainfrom
feature/issue-1334-kimi-k3-text-backbone
Sep 10, 2026
Merged

inureyes merged 9 commits into
mainfrom
feature/issue-1334-kimi-k3-text-backbone

Conversation

@inureyes

@inureyes inureyes commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds the Kimi K3 text decoder (model_type: "kimi_k3", text_config.model_type: "kimi_linear") as src/models/kimi_k3.rs with its sanitizer and tests beside it. It reuses Kimi Linear's ShortConv1d, MultiLinear and (now shared) kv_b_proj decomposition, and adds what that module lacks: fused-QKV KDA with a full-rank output gate and the gate_lower_bound = -5.0 recurrence, NoPE MLA with q-LoRA and a sigmoid output gate, SiTU everywhere (including the routed experts through SwitchGluActivation::SiTU), the latent MoE (896 experts on a 3584-wide latent with routed_expert_norm and two shared experts), Attention Residuals over 12-layer blocks with the model-level output mix, and the compressed-tensors mxfp4-pack-quantized expert layout stacked into MLX's mxfp4 form at sanitize time. The tokenizer (#1338) and vision tower (#1342) are sibling sub-issues and are not part of this PR.

Two shared-function changes, both no-ops for existing callers: gated_delta::compute_g_lower_bounded / gated_delta_update_with_lower_bound (None is the existing softplus gate, same graph) and SwitchGLU::with_activation (default SwiGLU; the fused decode kernel declines any other activation). The pipeline partition profile prices KDA, MLA, dense and MoE layers separately for this family, and the tensor-parallel plan generator replicates it beside kimi_linear rather than letting it fall through to a generic q/k/v/o shard plan it has no projections for.

Kimi K3 opts out of chunked prefill. forward_for_sequence reads any multi-token forward carrying no sequence id as the start of a prompt and resets the model-owned KDA and MLA state, which is what makes the cache-less forward entry point safe across two unrelated prompts; a chunked prefill sends exactly that shape once per chunk, so every chunk after the first would discard what its predecessors built and the model would answer from the last MLXCEL_PREFILL_CHUNK tokens with nothing raised. kimi_linear.rs and five other families carry the same shape and are filed as #1749.

Validation

Unit tests and lints

  • cargo test --profile test-fast --features metal,accelerate --lib models::kimi_k3 (25 passed): SiTU vs scalar, lower-bounded gate range, fused QKV vs separate projections, decode vs prefill, absorbed q-LoRA MLA vs the unabsorbed path, latent MoE vs a per-expert loop, AttnRes mix vs a scalar softmax, block accounting, sanitize incl. mxfp4 repack vs scalar dequant, causality, config validation, eos ids, sequence-state isolation, and negative tests for every load-time refusal added by the review commits (router bounds, six config-versus-checkpoint mismatches, mismatched expert planes, mismatched fused q/k/v planes, a kv_b_proj that disagrees with the config, the three Attention Residual widths, the five gate and output widths, and the chunked-prefill opt-out).
  • --lib models::gated_delta (6), --lib models::switch_layers (24), --lib models::detection (61), --lib distributed::tensor_parallel::plan_generator (28, including a new kimi_k3_is_replicated pinning that the family gets a replicated plan rather than the generic q/k/v/o shard plan), --lib distributed::pipeline::partition_profile (7), --lib cli::turbo_args (19).
  • cargo clippy --lib --tests --features metal,accelerate -- -D warnings and cargo fmt --all -- --check clean.

Real checkpoint

The full checkpoint is about 1.4 TB resident at 4 bits, so the gate runs on a layer-truncated local copy of moonshotai/Kimi-K3 at models/kimi-k3-8l-mxfp4: text_config.num_hidden_layers lowered from 93 to 4 (config.json.orig kept beside it), model.safetensors.index.json rewritten to the 7 shards that hold layers 0 to 3 plus the embeddings, the final norm and lm_head (model.safetensors.index.json.orig kept beside it), and metadata.total_size corrected to the 54.46 GiB those shards actually contain so the preflight sizes the truncated copy rather than the full one.

Four layers is where the published schedule already contains one of every layer kind this family has: [KimiK3] Config loaded: 4 layers (1 MLA, 3 KDA, 3 MoE), attn_res_block_size Some(12), with the dense MLP at layer 0 and the MLA layer at index 3 (1-based 4, the first entry of full_attn_layers). Each further layer is a repeat that costs about 17 GB of MoE experts, on a 137 GB host shared with seven concurrent build agents, so the memory went into a second variant instead of more layers.

Gate Command Result
Pre-load budget mlxcel inspect -m models/kimi-k3-8l-mxfp4 54.46 GiB weights, 1.88 GiB KV at 8192 tokens, 67.69 GiB total, FITS with 53.91 GiB headroom
Load, prefill, decode mlxcel generate -m models/kimi-k3-8l-mxfp4 -p "def fib(n):" -n 32 loaded in 5.3 s, resident 45.41 GB, peak 49.71 GB, 32 tokens in 0.60 s (53.66 tok/s), exit 0, no NaN and no abort
Finite logits examples/logit_trace models/kimi-k3-8l-mxfp4 <corpus> 32 2 8 0 64 teacher-forced positions, 512 top-k logits, 0 non-finite; NLL 10.35 to 17.23 (mean 13.65), top-k logits 6.66 to 10.38
Multi-block Attention Residuals same two commands on models/kimi-k3-4l-attnres2 32 tokens at 54.61 tok/s, 64 positions traced, 0 non-finite; NLL 10.56 to 18.19 (mean 13.85)

models/kimi-k3-4l-attnres2 is the same 7 shards by symlink with attn_res_block_size lowered from 12 to 2, so layers 0 and 2 both freeze a block and layer 3's mix scores three entries against real res_proj / res_norm weights. At the published block size of 12 a copy small enough to load would only ever store one block, so the multi-entry softmax path would go untested on real data; the 13-layer copy that would exercise it naturally is about 220 GB.

Every row was re-run on the binary built from the final commit; both traces and both generations reproduce to the digit, which is also the determinism check. The generated text is multilingual noise in both runs. That is what 4 of 93 layers produces, compounded by the generic tiktoken fallback reading tiktoken.model with the wrong pre-tokenization regex until #1338 lands. The gate is the load, the shapes, the absence of NaN and the finiteness of the logits, not the text.

Review

Two review passes (pr-reviewer with a Codex second opinion, and pr-security-checker) ran against this branch. Their findings are in #1741 (comment) and are closed by the four fix(kimi_k3) commits: the Attention Residual mix no longer holds the whole window promoted to float32, the router top-k is bounded before argpartition, every stack / view / concatenate / reshape that takes checkpoint-derived arguments is checked first (each of those aborts the process instead of returning, so an unchecked one is an uncatchable std::terminate with no key named), 20-plus config-versus-checkpoint widths fail at load naming the tensor and the field, the chunked-prefill truncation above is fixed, and the two documentation paragraphs that claimed working pipeline parallelism are corrected.

Acceptance criteria

  • Loads from the compressed-tensors mxfp4 checkpoint (layer-truncated) and runs prefill and decode with finite logits: see the table above.
  • KDA, MLA, latent SiTU MoE and Attention Residuals implemented as specified and unit-tested against scalar references.
  • Fluent output on the full model through the distributed pipeline: not reachable on one machine (about 1.4 TB at 4 bits, three 512 GB nodes) and not reachable in code either, because this PR adds the partition profile but no pipeline stage executor. Discharged by the open follow-up feat(distributed): Kimi K3 pipeline stage executor and full-model multi-node validation #1734, which also carries the layer-by-layer f32 reference trace. docs/distributed.md and docs/supported-models.md now say so instead of describing PP as working.
  • docs/supported-models.md updated; detection table and test added.
  • The workspace-wide cargo test / cargo clippy --workspace --all-targets gates were not run on this shared machine (concurrent mlxcel-core test binaries abort each other); the narrow scopes above plus CI cover them.

Follow-ups filed

Closes #1334

@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:low Low priority area:models Model architectures, weights, loading, metadata area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware modeltype:text Text-only language model arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) status:review Under review labels Sep 10, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance re-check

Of the four HIGH findings claimed fixed in 4fcddfd and 9828b5c, three are closed and one was only half closed. That one plus a new HIGH are fixed in 9c8ad3c.

  • Attention Residuals transient (was half closed, now fixed). The stacked [B, T, n + 1, D] value tensor is gone, but each block still went through one float32 array read twice, by the logit matmul and by the weighted term. Every consumer of the softmax runs after every logit, so all of those promotions stayed resident from the first loop until the fold: the same whole-window float32 residency the stack was removed to avoid, about 0.9 GB at hidden_size 7168 for a 4096-token prefill. Blocks now enter matmul and multiply in their stored dtype and MLX promotes inside each op, so each promotion is an op-local temporary. Bit-identical arithmetic (MLX's matmul and multiply both promote with the same astype the code was doing by hand).
  • Config versus checkpoint cross-checks: closed for the cases named. hidden_size is covered transitively through the model.norm.weight numel check, so input-axis mismatches fail at load too.
  • Router bounds: closed. validate() runs on both load paths, and num_experts_per_token in [1, num_experts] keeps argpartition(kth = k - 1) and the [0, k) slice inside the score axis.
  • stack / view / concatenate guards: closed.

New HIGH (fixed in 9c8ad3c). decompose_kv_b_proj reshaped checkpoint data with four config.json dimensions and no cross-check. A mismatched text_config aborted inside reshape during sanitize with no key to name, and a width that divides but is not kv_lora_rank survived sanitize and aborted inside the absorbed MLA matmul on the first forward pass. Kimi Linear shares the helper and now shares the guard.

MEDIUM (reported, not fixed). Remaining cross-check gaps that still surface as a mid-forward MLX abort rather than a load error: lm_head.weight rows against vocab_size, routed_expert_up_proj against hidden_size and the latent width, moe_intermediate_size against the stacked expert planes, intermediate_size against the dense MLP. num_hidden_layers is unbounded, so a hostile config.json turns sanitize_weights's 0..num_hidden_layers loop into a hang and from_weights's Vec::with_capacity into a capacity-overflow panic. The residual window holds ceil(num_hidden_layers / attn_res_block_size) full-width copies of the residual stream for the whole forward (8 blocks at the published config, about 470 MB in bf16 for a 4096-token prefill) with no chunking for this family. Decode pays two mixes per layer, each one gemv plus one broadcast multiply per stored block, roughly 1.5k extra tiny ops per token at 93 layers and 8 blocks. ResidualBlocks::push, KimiK3SparseMoE::forward and conv_decode_step use mlxcel_core::copy, which is a real MLX Copy op; astype to the same dtype shares the handle for free, and the conv-state copy runs once per KDA layer per decode step.

LOW. attention() panics on a cache-type mismatch and forward_for_sequence panics on a missing prepared sequence state (the KimiLinear precedent, process-level in the server). canonical_key builds six format strings per key on the scope pass. Shape arithmetic such as 3 * delta_projection_dim() is usize math on unbounded config fields and wraps in release before the shape comparison rejects it. situ_activation is pub and divides by beta with no guard of its own.

Also folded into 9c8ad3c: only .weight was counted against num_experts, so a short .scales set stacked into a mismatched expert axis and aborted in gather_qmm; Vec::with_capacity(num_experts) reserved an unvalidated config field; the per-layer leftover scan built its prefix once per key.

Green after the change: cargo fmt --all -- --check, cargo clippy --lib --tests --features metal,accelerate -- -D warnings, 23 models::kimi_k3 tests and 7 models::kimi_linear tests.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Sep 10, 2026
inureyes added a commit that referenced this pull request Sep 10, 2026
The repository tracks its reports (`TECHNICAL_REPORTS/.keep-reports`), so the bilingual report lands inside PR #1741 rather than trailing behind it.

Beyond the five new mechanisms, the report keeps three things a future reader would otherwise have to rediscover: why the Attention Residual mix was rewritten twice to keep a 4096-token residual window out of float32 residency, why `decompose_kv_b_proj` is now shared with `kimi_linear` and carries a reshape cross-check, and how a state reset keyed on the token count silently truncates a chunked prefill in seven families (#1749). It also states what the layer-truncated gate does not establish: the full model, fluent output, and token-exactness against any external reference.

Refs #1334, #1331, #1734, #1749.
Kimi K3 (`model_type: "kimi_k3"`, `text_config.model_type: "kimi_linear"`) shares Kimi Linear's absorbed NoPE MLA and sigmoid router but differs in every layer, so it lands as its own module rather than as flags on `kimi_linear.rs`, which stays the reference for Kimi Linear 48B.

- KDA layers: one fused `qkv_proj` / `qkv_conv` over the concatenated q/k/v channels, a full-rank sigmoid output gate `g_proj`, and the lower-bounded recurrence gate `exp(gate_lower_bound * sigmoid(exp(A_log) * (a + dt_bias)))` (`gated_delta::compute_g_lower_bounded`, `None` reproduces the existing softplus gate bit for bit, so no other family changes). The q/k RMS-norm eps is `1e-6 / head_dim` so the scaled norm equals FLA's in-kernel l2norm.
- MLA layers: q-LoRA (`q_a_proj`, `q_a_layernorm` at eps 1e-6, `q_b_proj`) and `o * sigmoid(g_proj(x))` before `o_proj`; `kv_b_proj` is decomposed into `embed_q` / `unembed_out` through the helper now shared with Kimi Linear.
- SiTU activation in f32 for every gated MLP, including the routed experts through `SwitchGluActivation::SiTU` on `SwitchGLU` (the fused decode kernel is SwiGLU-only and declines any other activation).
- Latent MoE: `routed_expert_down_proj` to 3584, 16 of 896 experts on the latent, `routed_expert_norm`, `routed_expert_up_proj`, plus two shared experts on the full hidden state; layer 0 is the dense MLP.
- Attention Residuals: frozen residual blocks every `attn_res_block_size` layers, a per-token f32 softmax mix in front of each sublayer and a model-level `output_attn_res` mix; the block list is rebuilt per forward, so no cache entry exists for it.
- Sanitize: strips `language_model.`, drops the vision tower, MTP heads and layers past `num_hidden_layers`, renames the legacy residual spellings and `block_sparse_moe.*`, fuses the KDA planes, slices `A_log` to the head count, and stacks the compressed-tensors `mxfp4-pack-quantized` experts into MLX's mxfp4 layout (uint32 codes, uint8 E8M0 scales, no biases). The nested `text_config.quantization_config` now counts as quantization metadata, so the bf16 planes are not converted to f16 around the packed experts.
- Wiring: detection, registry, metadata, `LoadedModel`, the special / nonstandard loaders, the hybrid-SSM prompt-cache list, the MLA latent-cache family list, and a per-layer pipeline partition cost that prices KDA, MLA, dense and MoE layers separately. Docs: `supported-models.md` entry and the pipeline memory note in `distributed.md`.

Validated with `cargo test --profile test-fast --features metal,accelerate --lib` on `models::kimi_k3` (17 tests against scalar / unabsorbed references), `models::gated_delta`, `models::switch_layers` and `models::detection`, plus clippy and fmt. The real-checkpoint gate on a layer-truncated `moonshotai/Kimi-K3` copy is reported in the PR.

Refs #1334
…oint

Four hardening findings from the review of the backbone, none of which changes what a well-formed checkpoint computes.

- The Attention Residuals mix folded its weighted sum by stacking every stored block into one `[B, T, n + 1, D]` float32 array and matmul'ing the probability row against it. Same arithmetic, but the stack is a contiguous copy of the whole residual window on top of the blocks themselves: about 0.9 GB of transient at `hidden_size` 7168 for a 4096-token prefill with a full 12-layer window, growing with the block count. The mix now broadcasts one `[B, T, 1]` probability column against one block at a time and never builds the stacked copy.
- `num_experts_per_token` reached `argpartition(kth = k - 1)` and a `[0, k)` slice unchecked, so a zero or an over-count indexed past the score axis inside MLX rather than failing at load. Config validation now bounds it by `num_experts`, and rejects a zero `routed_expert_hidden_size`.
- Nothing compared the config's head counts, ranks, expert count, vocabulary and hidden size against the tensors they index: the projections take their shapes from the checkpoint while the forward pass slices with the config. A layer-truncated debug copy or a mismatched `text_config` surfaced as an MLX abort mid-forward with no key to name, or broadcast into fluent nonsense. `check_axis` / `check_numel` now fail at load naming the tensor and the field, on the KDA fused projection and gate widths, the MLA q-LoRA and kv-LoRA widths, the stacked expert count, the latent width, the embedding rows and the final norm.
- The sanitizer handed `stack` and `view` arguments derived from checkpoint data. Both abort the process instead of returning: `stack` on expert planes whose shapes disagree, `view` on a uint8 trailing axis that is not a whole number of uint32 words. Both are now checked first, and the error names the offending expert index.

Three tests cover the new refusals: the router bounds, the six config-versus-checkpoint mismatches, and the mismatched expert plane.

Refs #1334
Two more findings of the same shape as the previous commit's: an MLX call reached with checkpoint-derived arguments that aborts the process instead of returning, so a malformed or mis-paired checkpoint takes the runtime down with no key to name.

- The Attention Residuals score weight is built at load from `res_proj.weight` and `res_norm.weight` and then multiplied against the residual stream, but nothing tied either width to `hidden_size`. A pair that disagrees with each other aborts inside `multiply` at load; a pair that agrees with each other but not with the config survives load and aborts inside `attn_res_mix`'s `matmul` on the first forward pass, which is the harder one to read because it is layers away from the tensor that caused it. `load_attn_res_weight` now takes `hidden_size` and checks both keys with `check_numel` first, at all three call sites (the per-layer attention and MLP residuals, and the model-level output mix).
- `fuse_axis0` handed `concatenate` the q / k / v projection and conv planes straight from the map. `concatenate` aborts on planes whose ranks disagree or whose extents differ away from the concatenated axis, and this runs during sanitize, before any of the load-time checks in `kimi_k3.rs` can name the tensor. `check_concat_compatible` now rejects that set first and names the offending key and the shape it disagrees with.

Two tests cover the new refusals: the three attention-residual keys against a wrong `hidden_size`, and a mismatched `k_proj` plane plus a mismatched `v_conv1d` plane.

Refs #1334
Re-review follow-ups to 4fcddfd and 9828b5c. The mix rewrite is bit-identical arithmetic (MLX promotes a half-precision operand against a float32 one with the same `astype` the code did by hand); the rest are refusals on inputs that previously aborted the process.

The Attention Residuals mix stopped stacking its values, but each block still went through one float32 array read twice, by the logit matmul and by the weighted term. Every consumer of the softmax runs after every logit, so all of those promotions stayed resident from the first loop until the fold: the same whole-window float32 residency the stack was removed to avoid, about 0.9 GB at hidden_size 7168 for a 4096-token prefill. Blocks now enter `matmul` and `multiply` in their stored dtype, so each promotion is an op-local temporary.

`decompose_kv_b_proj` reshaped checkpoint data with four `config.json` dimensions unchecked: a mismatched `text_config` aborted inside `reshape` during sanitize with no key to name, and a width that divides but is not `kv_lora_rank` aborted inside the absorbed MLA matmul on the first forward pass. Both are load errors now. Kimi Linear shares the helper and the guard.

Also: only `.weight` was counted against `num_experts`, so a short `.scales` set stacked into a mismatched expert axis and aborted in `gather_qmm`; `Vec::with_capacity(num_experts)` reserved an unvalidated config field; the leftover scan built its prefix once per key.

Refs #1334
Three findings from the second review pass, one of them a silent correctness bug on long prompts.

- `forward_for_sequence` treats any multi-token forward carrying no sequence id as the start of a prompt and resets the model-owned KDA and MLA state, which is what makes the cache-less `forward` entry point safe to call for two unrelated prompts in a row. `supports_chunked_prefill` defaults to true, so a prompt longer than `MLXCEL_PREFILL_CHUNK` (2048) reaches exactly that shape once per chunk and every chunk after the first discards the state its predecessors built: no error, no shape mismatch, just an answer conditioned on the last 2048 tokens. On a family whose `max_position_embeddings` is 1048576 that is the headline use case. Kimi K3 now returns false, which costs the per-chunk prefill memory bound of #672 and keeps the answer right. Carrying state across chunks means teaching `forward_for_sequence` to tell a new prompt from a continuation by something other than the token count, which is a change to the shared `ModelOwnedSequenceState` contract that `kimi_linear.rs` and `qwen3_next.rs` also sit on, so it is filed separately.
- `docs/distributed.md` and `docs/supported-models.md` both said the family runs through pipeline parallelism across three 512 GB nodes. It does not: `resolve_stage_family` has no `kimi_k3` arm and there is no stage executor, so `--pp-size` and `--pp-layers` refuse the model. What this port adds is the partition profile, which is a planning input. Both paragraphs now say the executor is missing and point at #1734, which tracks it and the full-model multi-node run. The tensor-parallel side had the mirror problem: the comment beside `ModelType::KimiK3` claimed the plan generator refuses the label, but `kimi_k3` was absent from the SSM and hybrid replicate list, so it fell through to `build_generic_transformer_plan` and got a q / k / v / o and gate / up / down shard plan for a model whose projections are `qkv_proj`, `kv_a_proj_with_mqa`, `embed_q` and `switch_mlp`. It now replicates, beside `kimi_linear`.
- Three more widths the forward pass never re-derives are checked at load, in the same style as the ones already there: the KDA gate projection (reshaped to `[B, T, num_heads, head_dim]`), the MLA gate projection (broadcast against `num_attention_heads * v_head_dim`), and the latent MoE up-projection and both output projections against `hidden_size`. Each of those failures is a `reshape` or a broadcast throw inside MLX, which crosses the cxx bridge as an uncatchable abort rather than an error the loader can name.

Two tests: the five refused widths, and the chunked-prefill opt-out.

Refs #1334
…ters

The `// Used by:` comment above a shared function is how the next person answers "what breaks if I change this", so a new caller has to appear in it. Kimi K3 was added to the two rosters the port modified (`gated_delta.rs`, `switch_layers.rs`'s module header) but not to the four it only calls into.

- `switch_layers::moe_weighted_sum` and `SwitchGLU::from_weights_with_mode`, both called directly from `kimi_k3.rs`. The second one's doc still read as if Inkling's nvfp4 export were the only reason a caller would pass an explicit mode; Kimi K3's compressed-tensors experts pass `mxfp4` for the same reason, so the doc now names both and carries a roster of its own.
- `layers::infer_quantization_mode`, called from `kimi_k3.rs`'s expert-plane probe.
- `utils::create_causal_mask`, whose roster counts the files under `src/models` that materialize an explicit prefill mask; Kimi K3 adds the mask to the MLA scores by hand, so it joins that group and the count goes from 44 to 45.

`docs/turbo-kv-cache.md` and the `resolve_kv_cache_mode_for_model` doc comment both enumerate the MLA-latent families for a reader, and both listed the six that predate this port even though `kimi_k3` was already added to `MLA_LATENT_CACHE_FAMILIES`, which is what actually performs the fp16 downgrade. The runtime was right and the two enumerations were stale.

Comments and prose only; no behavior change.

Refs #1334
The plan generator's match arm added "kimi_k3" beside its "kimi_linear" sibling in the SSM/hybrid replicated group, but no test exercised that entry, unlike jamba, nemotron_h and the other neighbours already covered by ssm_models_are_replicated and qwen3_next_is_replicated. Add kimi_k3_is_replicated to close the gap the same way.

Validation:
- cargo test --profile test-fast --features metal,accelerate --lib distributed::tensor_parallel::plan_generator (28 passed)
- cargo fmt --all -- --check
- cargo clippy --lib --tests --features metal,accelerate -- -D warnings

Refs #1334
The repository tracks its reports (`TECHNICAL_REPORTS/.keep-reports`), so the bilingual report lands inside PR #1741 rather than trailing behind it.

Beyond the five new mechanisms, the report keeps three things a future reader would otherwise have to rediscover: why the Attention Residual mix was rewritten twice to keep a 4096-token residual window out of float32 residency, why `decompose_kv_b_proj` is now shared with `kimi_linear` and carries a reshape cross-check, and how a state reset keyed on the token count silently truncates a chunked prefill in seven families (#1749). It also states what the layer-truncated gate does not establish: the full model, fluent output, and token-exactness against any external reference.

Refs #1334, #1331, #1734, #1749.
The uint8 `weight_packed` plane for `down_proj` is `[3584, 1536]`, and reinterpreting it as uint32 divides the trailing axis by 4, so the stacked mxfp4 plane is `[896, 3584, 384]` rather than the `[896, 3584, 192]` the entry claimed. The `gate_proj` / `up_proj` planes at `[896, 3072, 448]` were already correct.
@inureyes
inureyes force-pushed the feature/issue-1334-kimi-k3-text-backbone branch from b57dfaf to c330c97 Compare September 10, 2026 11:48
@inureyes
inureyes merged commit a8bb2b9 into main Sep 10, 2026
15 checks passed
@inureyes
inureyes deleted the feature/issue-1334-kimi-k3-text-backbone branch September 10, 2026 12:07
inureyes added a commit that referenced this pull request Sep 10, 2026
…1768)

Adds the Kimi K3 vision path on top of the #1741 text backbone and the #1743 XTML renderer: the MoonViT3D tower, the `sd2_tpool` merger, the `patchmergerv2` projector, the navit image preprocessor, detection of the VLM layout, the loader, and the prompt placement on both fronts.

## What changed

- Tower, merger, projector and preprocessor as specified: `encoders/moonvit3d` (RMSNorm at `2^-7`, fused `wqkv` over a 1536-wide qkv space, the MoonViT 2D rotary table reused from `kimi_vl::rope`, bilinear half-pixel position resampling, sincos time table for `t > 1`, per-image attention through the fast SDPA kernel, `tpool_merge`), `vision/kimi_k3_vl` (projector, count-checked merge at id 163605, `LanguageModel` delegation to the K3 backbone, which gains an embeddings-injection forward with the token-id path's state-reset rule), `processors/kimi_k3` (navit rule in f64 like the reference, chessboard alpha fill after the resize, padding to multiples of 28, patchify in either layout, `preprocessor_config.json` parsing with the geometry bounded the way `processors::locateanything` bounds its own).
- Loader `loading/vlm_kimi_k3`: index-filtered read so a truncated copy never opens the shards it drops, vision keys split off before the unchanged text sanitize, the Axis A surgery hook run as the text and common VLM routes run it, a load-time check that `vision_config` and `preprocessor_config.json` agree on the patch size and the merge kernel, and the dtype policy from `config_has_quantization_metadata`, so the checkpoint counts as quantized and the bf16 tower is not promoted to f16, matching the text-only route.
- Detection: `kimi_k3` with `vision_config` and `vision_tower.*` tensors is `ModelType::KimiK3VLM`, otherwise the text backbone; `inkling_has_vision_weights` now shares a `checkpoint_has_weight_prefix` helper.
- Prompts: the XTML renderer emits `<|media_begin|>image {w}x{h}<|media_content|>` + `<|media_pad|>` x `gh*gw/4` + `<|media_end|>` per `image_url` part (sized from the image header, navit parameters read from the checkpoint on every server construction path including the router front-end); `multimodal/kimi_k3_prompt` verifies the pre-rendered runs on the worker and splices the same block in front of a raw `mlxcel generate --image` prompt. A run that disagrees with the processor's grid is refused rather than scattered, and so is an `image_url` part with no prompt behind it or on a `tool` message.
- Resource bounds: one request's images may ask for at most 32,768 merged media tokens (`MLXCEL_KIMI_K3_MAX_MEDIA_TOKENS` overrides), checked at the render boundary and again on the worker; images are preprocessed, run and projected one at a time rather than as one batch tensor.
- `docs/supported-models.md`: Kimi K3 VLM entry; the text-backbone sentence about vision keys now describes the split.

## Review findings fixed

Two review passes ran over the branch (implementation, then security and performance). Fixed here, highest severity first:

- **Graph SDPA in the tower.** `scaled_dot_product_attention` materializes the `[1, heads, L, L]` score matrix, and `L` is one image's whole patch count; at the navit ceiling of about 67,000 patches that is hundreds of gigabytes. Switched to `fast_scaled_dot_product_attention`.
- **No per-request media bound.** The image count, the pixel dimensions and the decode allocation were each capped and their product was not: sixteen 4000x3000 photos ask for 247,104 media tokens and 988,416 tower tokens from one POST. `check_media_token_budget` bounds the sum, and geometry is now planned before any pixel work so the budget and the placeholder check both decide before the tower runs.
- **Whole-request batch tensor.** The path built one host `Vec<f32>` of every image, copied it into MLX, cast and transposed it, and the tower sliced it apart per image anyway. `project_image_stream` streams one image at a time and evaluates each before the next starts.
- **f32 promotion at block 0.** The rotary tables are f32 and nothing cast q and k back, so `wo` and the residual add promoted the stream and all 27 blocks ran bf16 weights against f32 activations. The harness now asserts the tower returns the dtype it was given.
- **Images on reordered tool results.** A run of tool messages is sorted into the assistant's tool-call order while images stay in wire order, so two same-grid images on tool results would swap features with every count check passing. Refused.
- **`--surgery` a silent no-op** on this route, which reads the shards directly and never reached the hook `load_text_weights` and `finish_vlm_weights_common` run.
- **A degenerate oracle fixture.** The real-weights harness ran on a flat single-colour square where all 256 patches are identical, so patch order, intra-patch layout and padding were unobservable. It now runs on `navit_probe.png`, a 303x181 crop with 230 colours that pads on both axes, and the bf16 arm is compared against the same run's f32 arm as well as the numpy dump.
- Smaller: an `image_url` part with no prompt supplied emitted placeholder text and no ids; the router front-end attached the renderer without the model directory; the projector indexed `shape[0]` before checking the rank; the navit grid arithmetic ran in u32 over checkpoint-supplied values; `fixed_output_tokens` was silently ignored; `merge_llava` and `temporal_sinusoid` gained their `Used by:` entries; the fixture docs pointed at the wrong test file.

Reported and not fixed:

- The tower re-runs in full every turn: the Kimi K3 branch discards the `active_caches` and `image_cache_keys` other families use for an opportunistic vision cache.
- Preprocessing is per pixel (`get_pixel` plus `push`, and a per-pixel chessboard composite), `flatten()` and `resized_rgb()` clone whole images, and the padding path fills a whole new image for a border of at most 27 pixels.
- `memory_estimate.rs` has no term for the vision working set. That gap is shared by every VLM family in the tree.
- `decode_request_images_with_limits` warns and skips an image it cannot decode, so the K3 path sees fewer images than the prompt was rendered for. The mismatch error now names that as a cause; refusing at the decode boundary is cross-family behavior and belongs in its own change.
- `checkpoint_has_weight_prefix` trusts a parsed index and does not fall back to the shard headers when it finds no match, so a truncated index would downgrade a real VLM to text-only. Adding the fallback makes every text checkpoint scan every shard header at detection time, which wants a measurement first.
- The rope and position tables are rebuilt per image inside one forward, and the patch-embedding conv over `[N, 14, 14, 3]` with stride 14 is a matmul in disguise. Both want a measurement before a change, per `docs/benchmarks.md`.
- The published layout has no flag to force the text-only route, and the VLM route skips LoRA and `sanitize_tied_embeddings`.
- `init_pos_emb_time` is unused, so `t > 4` extrapolates the time table rather than being refused; video is out of scope for this issue.

## Validation

Unit tests (`cargo test --profile test-fast --features metal,accelerate --lib <module>`) over `vision::encoders::moonvit3d`, `vision::processors::kimi_k3`, `vision::kimi_k3_vl`, `models::detection`, `server::kimi_k3_chat`, `server::chat_request`, `multimodal::kimi_k3_prompt` and `loading::vlm`: all pass, including the seven tests the issue names (`navit_resize_rule`, `chessboard_fill`, `pos_emb_bilinear_matches_half_pixel_formula`, `time_embedding_sincos`, `rope2d_angle_layout`, `tpool_merge_averages_over_time_and_groups_2x2`, `projector_shapes_and_merge_count_mismatch_errors`), the three detection-table tests, the prompt splice and verify tests, the renderer image-prompt and refusal tests, the media-budget and patch-layout tests, and a synthetic two-image tower test.

Real weights (`cargo test --profile test-fast --features metal,accelerate --lib vision::encoders::moonvit3d -- --ignored kimi_k3_tower_real_weights --nocapture`): the tower and projector on shards 00095 and 00096 of `models/kimi-k3-8l-mxfp4` over `tests/fixtures/kimi_k3_vision/navit_probe.png` (303x181, padded to 308x196, grid (1, 14, 22), 77 tokens, 230 distinct colours so no two patches are alike), compared with `tests/fixtures/kimi_k3_vision/reference.json`, which `generate_reference.py` computes in numpy float32 from the same shards, parsing the safetensors headers itself with no torch, transformers or mlx. With the weights cast to f32 the relative mean-abs error over 8,624 sampled projected values is 7.3e-6 (per-token statistic 9.3e-7, final-norm 2.0e-7), so the port and the independent transcription agree to float32 rounding. In the checkpoint's own bf16, which is what the loader runs, the sampled values sit at 3.0e-2 relative and 3.0e-2 against the f32 arm of the same run, while the per-token statistic is within 2.9e-4 and the final norm within 2.0e-3. The harness gates the f32 arm at 1e-2, the bf16 arm at 5e-2 against the dump and at 5e-2 against the f32 arm, and asserts the tower does not change the activation dtype. The preprocessed pixels match the dump over all 181,104 values.

The checkpoint's own Python (`media_utils.py` from `models/kimi-k3-tokenizer`, which needs only numpy and pillow) was run directly out of band: `navit_resize_image` reproduces the Rust plan on 4000x3000 (15,444 tokens), 10000x100 (side-capped, 6x512 grid), 100x100 (16), 8000x8000 (129x129) and 303x181 (77), and its `image_to_np` / `navit_patchify` / `normalize` pixel tensor matches `reference.json` in shape, grid, mean absolute value and its first sixteen values. The tower half has no vendor equivalent to run: the checkpoint ships no modeling file and torch is not installed, which is why the numpy transcription exists.

End to end (`./target/release/mlxcel generate -m models/kimi-k3-8l-mxfp4 --image tests/fixtures/kimi_k3_vision/navit_probe.png -p "What is in this picture?" -n 64`; the issue names `tests/fixtures/cat.jpg`, which is not in the repository): detected as `KimiK3VLM`, loaded in 5.1 s (45.4 GB resident), `Kimi K3: spliced 1 image block(s) (77 <|media_pad|> tokens)` for the (1, 14, 22) grid, 64 tokens at 34.4 tok/s, exit 0. On `mlxcel-server` at port 20342 a `/v1/chat/completions` request with a base64 `image_url` part is 179 prompt tokens against 94 for the same text alone (the 77 pads plus the block framing and the `image 303x181` label), 8 completion tokens, no error; the same image attached to a `tool` message is refused at the HTTP boundary with a named error. This is a load, placeholder-count and finite-logits gate only. The copy runs 4 of the published 93 layers, so the generated text is meaningless and is not a correctness result. The full model (about 1.4 TB at 4 bits, a pipeline over at least three 512 GB hosts with no stage executor yet) is not reachable on one machine; #1734 tracks it.

`cargo fmt --all -- --check` and `cargo clippy --lib --tests --features metal,accelerate -- -D warnings` pass. The workspace gate was not run as one command on this shared machine; the affected suites were run per module as listed above.

Deviations from the issue text: attention runs per image rather than through a block-diagonal mask (the issue allows either); the loader reads the four media control ids from `tokenizer_config.json` so the CLI can splice a block without a tokenizer; Pillow resizes palette images with nearest-neighbour sampling before the alpha fill while the `image` crate decodes palettes to RGB(A) first, noted in the processor docs.

Closes #1342

Refs #1331
beardedeagle pushed a commit to beardedeagle-mirrors/mlxcel that referenced this pull request Oct 5, 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
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
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
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:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware modeltype:text Text-only language model priority:low Low priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

1 participant