diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bad1fa82..97c2cda19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [Unreleased] + +### Fixed + +- **Ling-2.6-flash (`bailing_hybrid`) loads.** The load-time shape check read the absorbed MLA `embed_q` plane as `[H, qk_nope_head_dim, kv_lora_rank]`, but `kv_b_proj` splits into (and the mlx-community conversion ships) `[H, kv_lora_rank, qk_nope_head_dim]`. Any checkpoint whose two widths differ, Ling-2.6-flash's 512 and 128 among them, was refused with `unexpected ...embed_q.weight shape`. `mlx-community/Ling-2.6-flash-mlx-4bit` now loads, and a 32-token greedy continuation matches mlx-lm's byte for byte. + ## [v0.9.0] - 2026-11-30 ### Added diff --git a/docs/supported-models.md b/docs/supported-models.md index 80cfc9ab0..df47ab7a9 100644 --- a/docs/supported-models.md +++ b/docs/supported-models.md @@ -37,7 +37,7 @@ Implemented model families include: - dots.llm1 (`dots1`, rednote: a DeepSeek-V3-style Mixture-of-Experts without MLA. Standard multi-head attention with per-head Q/K RMSNorm, a dense first layer (`first_k_dense_replace`), then sigmoid-routed experts that select on `gate.weight` logits plus an `e_score_correction_bias`, with a single always-on shared expert. Validated against `mlx-community/dots.llm1.inst-mixed-4-6bit`, a mixed 4/6-bit export whose `v_proj` and `down_proj` tensors are 6-bit while the rest are 4-bit; the unified loaders detect the per-tensor bit width from shape.) - Ling / Bailing MoE (`bailing_moe`, Ant Group: a DeepSeek-shaped sparse decoder, RMSNorm before attention and before the FFN, grouped-query attention with RoPE, `num_experts` routed SwiGLU experts selected per token, and one always-on shared expert, so the expert machinery is the shared `switch_layers` path unchanged. What is not shared with DeepSeek is where the port's work went. The checkpoint uses GPT-NeoX naming rather than Llama naming: the token table is `model.word_embeddings`, the output projection is `attention.dense`, and Q, K and V arrive fused in one `attention.query_key_value` matrix that on `inclusionAI/Ling-lite-1.5` is `[3072, 2048]`, which is `(16 + 2 * 4) * 128` for 16 query heads and 4 KV heads of width 128; the split offsets are therefore `(2048, 2560)`, the uneven GQA form rather than an even three-way split, and MLX's `slice` clamps an out-of-range stop instead of throwing, so the even split would produce tensors of exactly the right shape assembled from the wrong channels. The router is renamed by upstream mlx-lm's `sanitize` from `mlp.gate.weight` to `mlp.gate.gate_proj.weight`, which collides with the `gate_proj` every routed expert also has; the loader resolves the router from two fully anchored keys instead of matching a suffix, so a raw `inclusionAI` export and an mlx-lm conversion both load and neither can read an expert's SwiGLU gate as the router. The raw checkpoint stores each routed expert separately at `mlp.experts.{e}.{gate,up,down}_proj`, 64 experts times 3 projections times 28 layers on Ling-lite; the loader joins those individually-keyed tensors into `SwitchLinear`'s stacked `[num_experts, out, in]` layout at load, checking every expert index rather than only index 0 so a checkpoint missing a late expert cannot register a short stack the router can index past, and an mlx-lm conversion that already ships the pre-stacked `mlp.switch_mlp.{proj}` form loads unchanged on the same path. Three routing details are load-bearing and invisible downstream: the correction bias is added to a copy of the scores used for SELECTION only, and the returned weights are gathered from the unbiased scores (gathering from the biased copy leaves the output finite and plausible while misweighting every routed contribution); `norm_topk_prob` is applied only when `num_experts_per_tok > 1` and divides by `sum + 1e-20` rather than a bare sum; and `score_function` defaults to `"softmax"`, not to DeepSeek-V3's sigmoid, so reusing the DeepSeek gate as-is would change the routing distribution on every token. `moe_router_enable_routed_scaling` is dead code upstream (`BailingMoeGate` stores it and never reads it, and `group_expert_select` ends with an unconditional multiply), and this port mirrors upstream so a checkpoint decodes here as it does under the reference; the loader prints a diagnostic naming both fields for the one combination where the two readings diverge, a non-unit `routed_scaling_factor` with the flag false. The shared expert is ONE wide MLP of `(moe_shared_expert_intermediate_size or moe_intermediate_size) * num_shared_experts`, which is `1408 * 2 = 2816` on Ling-lite, added to the routed mixture at a fixed weight of 1.0 and never packed into the switch tensors; there is no per-shared-expert axis anywhere in the checkpoint. Grouped top-k routing (`n_group` groups scored by the sum of their top two experts, `topk_group` kept) and the router expert bias are implemented and unit-tested, but no published Bailing checkpoint reaches either: Ling-lite declares neither field and both default to off, so a passing real-checkpoint run says nothing about them. `norm_head` is live upstream despite appearing vestigial, and is implemented as an axis-0 L2 normalization of `lm_head.weight` in float32 with a `1e-7` epsilon cast back to the weight's own dtype; `norm_softmax` is declared by upstream's `ModelArgs` and never read, does not appear in the vendored `modeling_bailing_moe.py`, and is not a named parameter of the vendored config, so a config setting it true is rejected at load rather than parsed and ignored. Loading also rejects an architecture scalar that could size an allocation, divide, or truncate through an `as i32` cast (zero checks precede divisibility checks, since `0.is_multiple_of(0)` is true in Rust); routing parameters that would put `argpartition(kth = n_group - topk_group - 1)` out of range or reshape the score row into unequal groups, which upstream checks neither of; a rotary width that is zero, odd or wider than the head, and a non-positive or non-finite `rope_theta` or `rms_norm_eps`; a `rope_scaling` block other than an absent, empty or `"default"` one, since upstream threads it into `initialize_rope` while this loader always builds the plain rotation; a `quantization` block whose `bits` falls outside `1..=32` or whose `group_size` is non-positive; the output head's input width against `hidden_size`, the one axis nothing else in the loader checked, with its row count checked exactly against upstream's own strict `nn.Linear(hidden_size, vocab_size)` load and the check skipped only when `tie_word_embeddings` ships no separate `lm_head` tensor; a quantized token table's own input width, reconstructed the same way, since the shared `validate_embedding_table` checks the row count unconditionally but the width only on the unquantized path; and any tensor whose real shape disagrees with the config, on both axes, per expert index rather than only the first (a checkpoint missing a late expert would otherwise register a short stack the router can index past), and on the quantized path, where packing compresses the input axis only so the input width is recovered from the scales the way MLX recovers it, `scales.shape(-1) * group_size`. Each of those is a load-time rejection because an MLX C++ exception crossing the cxx bridge is an uncatchable `std::terminate` at the first forward pass rather than a Rust error. Validation checkpoint: `inclusionAI/Ling-lite-1.5` (16.8B total / 2.75B activated, raw bf16, 5603 tensors, no mlx-community conversion needed). A token-exact comparison against the mlx-lm reference needs `--no-chat-template` on both sides, because this checkpoint does ship a chat template embedded in `tokenizer_config.json` while the reference harness feeds the raw prompt.) - Ling / Ring linear-attention MoE (`bailing_moe_linear`, Ant Group: the `bailing_moe` sparse block interleaved with gated-linear-attention layers. The FFN half is the dense family's unchanged, down to the `mlp.gate.gate_proj` router rename, the selection-only expert bias and the single wide shared MLP, so this port reuses those types rather than restating them; every delta is in the attention stack. The linear attention is GLA, not gated-delta: `h_t = h_{t-1} * exp(g) + k_t^T v_t` with `y_t = (q_t h_t) * scale` and NO delta term, so reusing `gated_delta.rs` (which computes `delta = (v - k h) * beta` and adds `k^T delta`) yields a model that loads, runs and emits fluent text from the wrong recurrence. The decay `g` is read from no tensor at all: it is the ALiBi slope schedule for `num_attention_heads`, negated and scaled by `1 - max(0, layer_idx - 1) / max(1, num_hidden_layers - 1) + 1e-5`, so every linear layer decays at its own constant per-head rate and nothing in the checkpoint disagrees if it is computed wrong (the non-power-of-two head-count fallback is implemented and unit-tested but unreachable on the published checkpoint's 16 heads). Because `exp(g)` does not depend on `t`, the recurrence has a closed form, and the port carries both evaluations: `gla_sequential` is upstream's per-token loop transcribed step for step, and `gla_chunked` is the closed form over 64-token chunks. **Chunked is the default as of #1040**; set `MLXCEL_BAILING_LINEAR_CHUNKED_PREFILL=0` for upstream's arithmetic, which is what a mlx-lm reference diff needs. Chunking measures 2.6x to 4x faster on prefill (0.07s against 0.29s at 101 tokens, 1.07s against 2.81s at 2048 on an M1 Ultra), since the intra-chunk sum lands in a matmul accumulator instead of a bf16 running state. It shipped opt-in first because this stack amplifies a reassociation hard: reordering the sum moves layer 0's mean absolute activation by 0.04%, layer 3 then multiplies its input magnitude by roughly 23x, and the 256-expert top-8 router converts a sub-ulp score difference into a different selected expert, so the two paths decode different continuations from the same checkpoint. #1040 measured which of the two differing answers is better rather than assuming they were equivalent, and teacher-forced perplexity on a WikiText-2 excerpt favours chunked at every window length: 115.83 against 114.09 at 128 tokens, 39.39 against 36.39 at 1024, 155.47 against 151.42 over 8192 in 256-token windows, and 85.96 against 74.14 over 16384 in 512-token windows. The advantage grows with the window within a fixed scoring shape, which is what a compounding bf16 accumulation error predicts, so the faster path is also the more accurate one and the cost of the promotion is only token-for-token comparability with mlx-lm. The same sensitivity means token-exactness against mlx-lm is not a meaningful gate for this family in general: the reference disagrees with ITSELF between its cached and its full-recompute paths, flipping a 0.0625-wide top-2 tie (exactly one bf16 ulp at that magnitude) six tokens into a 12-token prompt. What was validated instead is the layer-by-layer numerical trace, which is stronger: on a 101-token prompt the default path reproduces the reference's mean absolute activation at layer 0 to six significant figures (0.033069 against 0.033069) and at layer 1 to five, confirming the recurrence, the RoPE offset threading, the QK-norm ordering, `GroupRMSNorm`, the sigmoid output gate and both residuals at once; a single-token prefill reproduces the reference's top-5 logits exactly; and greedy decode matches the reference's full-recompute path for all 40 tokens of a low-entropy counting prompt. `GroupRMSNorm` is not RMSNorm: it splits the `num_heads * head_dim` axis into `group_norm_size` groups (4 on Ring-mini), RMS-normalizes each group WITHOUT a weight, flattens, and only then multiplies by the full-width weight, so substituting a plain RMSNorm changes every linear layer's output while leaving it finite. The linear layers are MHA and the full-attention layers are GQA, which gives one checkpoint two fused-QKV widths and two head widths: on `mlx-community/Ring-mini-linear-2.0-4bit` a linear layer's `attention.query_key_value` is `[6144, 2048]` (`3 * 16 * 128`) and a global layer's is `[3072, 2048]` (`(16 + 2 * 4) * 128`), and upstream's `LinearAttention` derives `hidden_size // num_attention_heads` while ignoring any explicit `head_dim`, so weight validation checks each layer against its own width rather than one shared one; MLX's `slice` clamps an out-of-range stop instead of throwing, so a single shared width would let a mislabeled layer silently read the wrong channels. The hybrid schedule is `(layer_idx + 1) % layer_group_size == 0` plus a tail clause that makes every leftover layer global when the stack does not divide evenly (layers 4, 9, 14 and 19 of 20 on Ring-mini; the tail clause never fires there and is unit-tested separately), and the RoPE offset every linear layer uses is read from a global layer's KV cache, since the recurrence has no position of its own. Upstream hardcodes that lookup as `layer_group_size - 1` and would index out of range for a stack shorter than one group; this loader resolves it by scan. The linear layers hold a recurrent state and the global ones a KV cache, which does not fit the trait's homogeneous `&mut [KVCache]`, so the model owns its heterogeneous per-sequence state the way `qwen3_next` does, with snapshot and restore wired for exact-prefix reuse and batched decode declined. `norm_softmax` and `use_rmsnorm` are both declared by upstream's `ModelArgs` and never read (every normalizer in the file is an RMSNorm or a GroupRMSNorm unconditionally), so a config that sets `norm_softmax: true` or `use_rmsnorm: false` is rejected at load rather than parsed and ignored. Unlike the dense family, this one reaches grouped top-k routing on a real checkpoint (`n_group` 8, `topk_group` 4, 256 experts), so the guards against an out-of-range `argpartition(kth = n_group - topk_group - 1)` and an expert count that does not divide into equal groups are live rather than theoretical. The config also carries per-tensor quantization overrides (the router `mlp.gate.gate_proj` at 8 bits while the rest of the checkpoint is 4-bit); those keys are deliberately not parsed, because `UnifiedLinear`, `SwitchLinear` and `UnifiedEmbedding` each reconcile bits and group size from the tensor shapes they load. Validation checkpoint: `mlx-community/Ring-mini-linear-2.0-4bit` (16B total / 1.4B activated, 8.6 GB, 20 layers, 256 routed experts plus one shared, 698 tensors).) -- Ling-2.6-flash hybrid (`bailing_hybrid`, Ant Group: a 104B-total / 7.4B-active decoder that interleaves two attention flavours and two FFN flavours. Every `layer_group_size`-th layer (1:7, so 7, 15, 23 and 31 of 32) is DeepSeek-style absorbed MLA: `q_a_proj` -> `q_a_layernorm` -> `q_b_proj` (or a direct `q_proj` when `q_lora_rank` is null), `kv_a_proj_with_mqa` split into a latent plus `k_pe`, RoPE over `qk_rope_head_dim` with `traditional = rope_interleave`, and the `kv_b_proj` plane pre-split into `embed_q` (`[H, kv_lora, nope]`) and `unembed_out` (`[H, v, kv_lora]`). The other layers are gated linear attention with the same `recurrent_gla` recurrence as `bailing_moe_linear` but three deltas that a load cannot see: the decay is `1 - layer_idx / max(1, n_layers - 1) + 1e-5` with no `max(0, layer_idx - 1)` clamp (`layer_decay_unshifted`, a sibling of the Ring schedule which is left untouched), the recurrent state and `exp(g)` are float32 as upstream's `recurrent_gla` initializes `h` in `mx.float32`, and RoPE uses `traditional = false` on `int(head_dim * partial_rotary_factor)` channels at the FIRST MLA layer's KV-cache offset, not a per-layer counter. The GLA output is `dense(GroupRMSNorm(y) * sigmoid(g_proj(x)))`, `GroupRMSNorm` being the weightless per-group RMS followed by a full-width weight that `bailing_moe_linear` already implements. The FFN half reuses the Bailing sparse block, but the group-limited router masks dropped groups with `-inf` rather than the shared zero fill, because `expert_bias` is added to the selection scores and can make a KEPT score negative, at which point a zero fill outranks it and hands the top-k row to the dropped group; `n_group == topk_group` skips the mask entirely, as upstream does. The `expert_bias` cast is excluded as upstream's `cast_predicate` does, and `num_shared_experts == 0` means no shared MLP. Sanitize renames `mlp.gate.weight` to `mlp.gate.gate_proj.weight`, splits `kv_b_proj` (dequantizing first when the plane is quantized; skipped when `embed_q` already exists, which is the mlx-community `-mlx-*bit` layout because the converter applies this sanitizer and then keeps `embed_q` / `unembed_out` unquantized), and drops every `model.layers.N.*` with `N >= num_hidden_layers`, which is the MTP trailer the checkpoint appends; the predicate parses the layer index so shared-expert and router keys survive. MLA layers hold a `KVCache` of `(kv_latent, k_pe)` and GLA layers a recurrent state, so the model owns its heterogeneous per-sequence state as `bailing_moe_linear` does, with snapshot and restore wired to a `bailing_hybrid` family tag; multi-row decode is a per-row fallback over each sequence's own state, and padded prefill is declined because the recurrent state absorbs pad tokens with no trailing slots to trim. Detection reads `architectures[0]`: `BailingMoeV2_5ForCausalLM` (or an absent list) is this family, while `BailingMoeV3ForCausalLM` (Ling-3.0 / Ling-3.1-flash, KDA plus head-gated MLA, #2385) is refused by name with "Ling-3.0 (bailing_moe_v3) is not supported yet", and any other architecture under this `model_type` is refused rather than guessed onto the V2.5 decoder. Target checkpoint: `mlx-community/Ling-2.6-flash-mlx-4bit` (about 55 to 59 GB) but was NOT available on the validation host, so this port is unit-tested only: no real-checkpoint greedy parity, no chunked-GLA decode on a real prompt, and no served run were performed. The unit tests pin the decay hand values and the Ring-shift difference, the global-layer predicate, the `-inf` group mask against the zero fill (including a gate-level selection), sanitize's split and MTP drop, and the V3 refusal. Set `MLXCEL_BAILING_HYBRID_CHUNKED_PREFILL=0` for the per-token recurrence when diffing against a reference. Validation checkpoint: `mlx-community/Ling-2.6-flash-mlx-4bit` (104B total / 7.4B activated, 32 layers, 256 routed experts plus one shared, `model_type: bailing_hybrid`). +- Ling-2.6-flash hybrid (`bailing_hybrid`, Ant Group: a 104B-total / 7.4B-active decoder that interleaves two attention flavours and two FFN flavours. Every `layer_group_size`-th layer (1:7, so 7, 15, 23 and 31 of 32) is DeepSeek-style absorbed MLA: `q_a_proj` -> `q_a_layernorm` -> `q_b_proj` (or a direct `q_proj` when `q_lora_rank` is null), `kv_a_proj_with_mqa` split into a latent plus `k_pe`, RoPE over `qk_rope_head_dim` with `traditional = rope_interleave`, and the `kv_b_proj` plane pre-split into `embed_q` (`[H, kv_lora, nope]`) and `unembed_out` (`[H, v, kv_lora]`). The other layers are gated linear attention with the same `recurrent_gla` recurrence as `bailing_moe_linear` but three deltas that a load cannot see: the decay is `1 - layer_idx / max(1, n_layers - 1) + 1e-5` with no `max(0, layer_idx - 1)` clamp (`layer_decay_unshifted`, a sibling of the Ring schedule which is left untouched), the recurrent state and `exp(g)` are float32 as upstream's `recurrent_gla` initializes `h` in `mx.float32`, and RoPE uses `traditional = false` on `int(head_dim * partial_rotary_factor)` channels at the FIRST MLA layer's KV-cache offset, not a per-layer counter. The GLA output is `dense(GroupRMSNorm(y) * sigmoid(g_proj(x)))`, `GroupRMSNorm` being the weightless per-group RMS followed by a full-width weight that `bailing_moe_linear` already implements. The FFN half reuses the Bailing sparse block, but the group-limited router masks dropped groups with `-inf` rather than the shared zero fill, because `expert_bias` is added to the selection scores and can make a KEPT score negative, at which point a zero fill outranks it and hands the top-k row to the dropped group; `n_group == topk_group` skips the mask entirely, as upstream does. The `expert_bias` cast is excluded as upstream's `cast_predicate` does, and `num_shared_experts == 0` means no shared MLP. Sanitize renames `mlp.gate.weight` to `mlp.gate.gate_proj.weight`, splits `kv_b_proj` (dequantizing first when the plane is quantized; skipped when `embed_q` already exists, which is the mlx-community `-mlx-*bit` layout because the converter applies this sanitizer first; current mlx-lm's `quant_predicate` keeps `embed_q` / `unembed_out` unquantized, but `mlx-community/Ling-2.6-flash-mlx-4bit` (revision `bd458afd`) ships both 4-bit affine-quantized, and both forms load), and drops every `model.layers.N.*` with `N >= num_hidden_layers`, which is the MTP trailer the checkpoint appends; the predicate parses the layer index so shared-expert and router keys survive. MLA layers hold a `KVCache` of `(kv_latent, k_pe)` and GLA layers a recurrent state, so the model owns its heterogeneous per-sequence state as `bailing_moe_linear` does, with snapshot and restore wired to a `bailing_hybrid` family tag; multi-row decode is a per-row fallback over each sequence's own state, and padded prefill is declined because the recurrent state absorbs pad tokens with no trailing slots to trim. Detection reads `architectures[0]`: `BailingMoeV2_5ForCausalLM` (or an absent list) is this family, while `BailingMoeV3ForCausalLM` (Ling-3.0 / Ling-3.1-flash, KDA plus head-gated MLA, #2385) is refused by name with "Ling-3.0 (bailing_moe_v3) is not supported yet", and any other architecture under this `model_type` is refused rather than guessed onto the V2.5 decoder. Target checkpoint: `mlx-community/Ling-2.6-flash-mlx-4bit` (58.6 GB). Revision `bd458afd` loads on GB10 (CUDA), and its 32-token greedy continuation of a 5-token prompt (`--no-chat-template`) is byte-identical to mlx-lm 0.32.2's. Longer prompts and a served run have not been compared. The unit tests pin the decay hand values and the Ring-shift difference, the global-layer predicate, the `-inf` group mask against the zero fill (including a gate-level selection), sanitize's split and MTP drop, and the V3 refusal. Set `MLXCEL_BAILING_HYBRID_CHUNKED_PREFILL=0` for the per-token recurrence when diffing against a reference. Validation checkpoint: `mlx-community/Ling-2.6-flash-mlx-4bit` (104B total / 7.4B activated, 32 layers, 256 routed experts plus one shared, `model_type: bailing_hybrid`). - Omoikane-50M (`omoikane`, hybrid Gated DeltaNet and multi-head latent attention with dense and mixture-of-experts layers). Phase 2 checkpoint: `Goekdeniz-Guelmez/Omoikane-50M-Base-Phase-2`. - Arcee AFMoE / Trinity (`afmoe`, Arcee: a hybrid sliding/full attention MoE decoder. The issue that requested it described the family as "structurally a qwen3_moe / deepseek MoE derivative with QK-norm", which is true of the expert machinery and wrong about the model class: five features change how every layer is built and four are invisible to a shape check. `layer_types` interleaves `sliding_attention` and `full_attention` (three sliding then one global, 56 times over on Trinity-Nano-Preview), so sliding layers need a `RotatingKVCache` and global layers a `KVCache` and the model owns its heterogeneous per-sequence state the way `gemma3` does, reusing that module's `Cache` enum rather than restating it. The schedule comes from the LIST, not a modulus: `global_attn_every_n_layers` is declared beside it and upstream never reads it, so a port that trusts the modulus agrees with Trinity by coincidence and diverges on any checkpoint whose list is irregular. **Full-attention layers are NoPE**: upstream builds `self.rope` only when `is_local_attention`, so global layers apply no positional encoding at all, and rotating them anyway loads every tensor and is invisible at position 0 where the rotation is the identity, which is why it is pinned by a reference-free unit test that runs a global block at two sequence offsets and asserts the output does not move (and that a sliding block's does). Attention carries a sigmoid output gate applied BEFORE `o_proj`, so every block has an extra `self_attn.gate_proj` weight qwen3_moe has no counterpart for, and the name collides with both the SwiGLU `gate_proj` and the MoE router at `mlp.router.gate`. There are FOUR norms per layer in a sandwich (`input_layernorm`, `post_attention_layernorm`, `pre_mlp_layernorm`, `post_mlp_layernorm`), applied so the two "post" norms normalize each branch's OUTPUT before it joins the residual rather than normalizing the residual on the way in; a two-norm pre-norm block loads every tensor the checkpoint ships except two per layer and still generates. When `mup_enabled` the embeddings are multiplied by `sqrt(hidden_size)` before the stack, a config flag rather than a tensor, so dropping it shrinks every hidden state 32x on Trinity-Nano and still produces finite logits. `head_dim` is read rather than derived: Trinity-Nano declares 128 with hidden 1024 and 8 heads so the derived value coincides, which is exactly the coincidence that hides a derived implementation. The first `num_dense_layers` (2) use a plain SwiGLU MLP. Routing is sigmoid-scored with the `expert_bias` added to a SELECTION-only copy while the returned weights are gathered from the unbiased scores (the same silent-misweighting contract `bailing_moe` documents), then `route_norm` renormalization and a `route_scale` multiply (2.826); the routing weights stay float32 through the combine because `AfmoeMoE.__call__` never casts them back, so this family deliberately does not use the shared `moe_weighted_sum` helper, which casts them down first. Grouped routing exists but `n_group` is 1 on every published checkpoint, so it is unit-tested rather than exercised. **Validation is by numerical trace, not token-exactness, and that is not a shortcut.** `Trinity-Nano-Preview` amplifies a perturbation roughly twofold per layer across its 56 layers: rounding the routing weights to bf16, the smallest change an equally-valid implementation could make, changes the REFERENCE's own top-5 logits from `[64, 68, 3049, 88, 89]` to `[1265, 9370, 11041, 6569, 8650]` with no token in common, so no two implementations that differ by a single rounding can agree on output. What was verified instead is stronger per unit of evidence: on both a 1-token and a 6-token prompt, layers 0 and 1 (the dense prefix, which has no MoE) reproduce the reference's mean absolute activation EXACTLY to six significant figures at every stage (`ln`, `attn`, `mlp`, and the layer output), which confirms the muP scale, the embeddings, the full sliding-attention block including RoPE at nonzero positions and the sigmoid gate, the sliding-window prefill mask, all four norms, both residuals and the dense SwiGLU MLP on real weights; and at layer 2, the first MoE layer, the routing indices and weights match the reference exactly (`[98, 18, 63, 17, 64, 99, 34, 81]`, weights summing to `route_scale`). Loading rejects an architecture scalar that could size an allocation or divide, a `layer_types` list shorter than the stack (which would silently make the uncovered tail global) or containing an undefined kind, a zero `sliding_window` when a layer slides, an odd `head_dim`, a `num_experts_per_tok` outside `1..=num_experts`, the grouped-routing parameters that would put `argpartition` out of range, a non-default `rope_scaling` block, and any tensor whose real shape disagrees with the config including an expert stack with fewer planes than `num_experts`. Validation checkpoint: `mlx-community/Trinity-Nano-Preview-4bit` (3.2 GB, 56 layers, 128 experts top-8 plus one shared, 2389 tensors). Note this is a preview checkpoint of limited quality: it emits repetitive degenerate text under the mlx-lm reference as well as here, so fluency is not a usable signal for it. The family also answers `supports_snapshot_reuse()` since #1335, reusing `gemma3`'s shared `Cache` serializer to donate a model-state snapshot for exact-prefix, and truncating while every sliding layer is still unwrapped, multi-turn prompt-cache reuse; see [Exact-prefix snapshots for recurrent state](turbo-kv-cache.md#exact-prefix-snapshots-for-recurrent-state).) - Arcee AFM dense (`arcee`, `ArceeForCausalLM`, `arcee-ai/AFM-4.5B`): a separate family from AFMoE above and from Apple's AFM-7 (`afm7`). The decoder is Llama-shaped (GQA, RMSNorm before attention and before the MLP, untied head, Llama weight names) except for its MLP, which has no gate: `down_proj(relu(up_proj(x))^2)`, so each layer ships only `mlp.up_proj` and `mlp.down_proj` and the MLP is 7.2x the hidden width. Attention is the shared `llama3` attention, so YaRN RoPE (`factor` 20 over an original 4096 context, attention factor `0.1 * ln(20) + 1`), paged decode, the KV cache modes and native batched decode are the Llama paths (`src/models/arcee.rs`). Neither mlx-lm nor mlx-vlm implements `arcee`, so the parity reference is Hugging Face transformers' `ArceeForCausalLM` (5.24.0), scored by `scripts/arcee_oracle_trace.py` (see `docs/benchmarks.md`). Refused at load with an error naming the field: a `hidden_act` other than `relu2`, a `gate_proj` tensor, a RoPE type other than `default` / `linear` / `llama3` / `yarn`, a scaled block without a usable `factor`, YaRN `beta_fast` below `beta_slow`, YaRN `truncate: false`, a YaRN `attention_factor` / `mscale` / `mscale_all_dim` combination whose magnitude differs from the one transformers derives, a `partial_rotary_factor` other than 1, a top-level `original_max_position_embeddings` that differs from the RoPE block's, a `type` / `rope_type` pair that disagree, and oversized or inconsistent geometry. The same screening runs on the adapter route. Tensor parallelism is not enabled for this family. diff --git a/src/models/bailing_hybrid.rs b/src/models/bailing_hybrid.rs index 65405818a..4f2901e65 100644 --- a/src/models/bailing_hybrid.rs +++ b/src/models/bailing_hybrid.rs @@ -674,7 +674,9 @@ mlxcel_core::impl_rope_lifting_deserialize!(ModelArgs); /// Skipped when `embed_q` already exists, which is the mlx-community /// `-mlx-*bit` layout: the converter runs this sanitizer and then quantizes /// through the model's `quant_predicate`, which keeps `embed_q` / -/// `unembed_out` unquantized. +/// `unembed_out` unquantized. The published +/// `mlx-community/Ling-2.6-flash-mlx-4bit` (revision `bd458afd`) nevertheless +/// ships both planes 4-bit quantized; `MultiLinear` loads either form. /// - Every `model.layers.N.*` with `N >= num_hidden_layers` is dropped. The /// checkpoint appends its MTP layer after the decoder stack. The check names /// the layer index exactly, so the shared expert at `mlp.shared_experts` and @@ -1048,12 +1050,17 @@ pub fn validate_weights(weights: &WeightMap, args: &ModelArgs) -> Result<(), Str if weights.contains_key(&format!("{embed_q}.weight")) || weights.contains_key(&format!("{unembed_out}.weight")) { + // `embed_q` maps the `qk_nope_head_dim` query slice into the + // latent, so it is `[H, kv_lora, nope]` (what `split_kv_b_proj` + // and mlx-lm's `MultiLinear(nope, kv_lora, H)` produce), while + // `unembed_out` maps the latent back out and is + // `[H, v, kv_lora]`. validate_multi_linear( weights, &embed_q, args.num_attention_heads, - args.qk_nope_head_dim, args.kv_lora_rank, + args.qk_nope_head_dim, group_size, bits, )?; diff --git a/src/models/bailing_hybrid_tests.rs b/src/models/bailing_hybrid_tests.rs index f1d1aa19c..b22279ecb 100644 --- a/src/models/bailing_hybrid_tests.rs +++ b/src/models/bailing_hybrid_tests.rs @@ -722,6 +722,67 @@ fn validate_weights_rejects_a_mis_shaped_absorbed_plane_and_expert_bias() { assert!(error.contains("expert_bias"), "{error}"); } +/// `embed_q` is `[H, kv_lora_rank, qk_nope_head_dim]`, the layout +/// `split_kv_b_proj` produces and mlx-lm's `MultiLinear(nope, kv_lora, H)` +/// stores. `tiny_config` sets `kv_lora_rank == qk_nope_head_dim`, which hides +/// an axis swap, so this walks unequal pairs on both sides plus Ling-2.6-flash's +/// 4:1 ratio (512 / 128) and an extreme 8:1, for the pre-split layout the +/// mlx-community conversion ships and for a raw `kv_b_proj` that +/// `sanitize_weights` splits itself. +#[test] +fn validate_weights_reads_embed_q_as_kv_lora_by_nope() { + for (kv_lora, nope) in [(2, 2), (4, 2), (2, 4), (8, 2), (8, 1)] { + let mut args = tiny_config(); + args.kv_lora_rank = kv_lora; + args.qk_nope_head_dim = nope; + args.validate().unwrap(); + let heads = args.num_attention_heads as i32; + let v = args.v_head_dim as i32; + let (kv_lora, nope) = (kv_lora as i32, nope as i32); + let case = format!("kv_lora_rank {kv_lora}, qk_nope_head_dim {nope}"); + + // Pre-split planes. + let mut weights = tiny_weights(&args); + assert_eq!( + mlxcel_core::array_shape(&weights["model.layers.1.attention.embed_q.weight"]), + vec![heads, kv_lora, nope], + "{case}" + ); + validate_weights(&weights, &args).unwrap_or_else(|e| panic!("{case}: {e}")); + // The transposed plane is a different matmul, so it must still be + // refused whenever the two widths differ. + if kv_lora != nope { + weights.insert( + "model.layers.1.attention.embed_q.weight".into(), + filled(&[heads, nope, kv_lora]), + ); + let error = validate_weights(&weights, &args).unwrap_err(); + assert!(error.contains("embed_q"), "{case}: {error}"); + } + + // Raw `kv_b_proj` (`[H * (nope + v), kv_lora]`), split by sanitize. + let mut weights = tiny_weights(&args); + weights.remove("model.layers.1.attention.embed_q.weight"); + weights.remove("model.layers.1.attention.unembed_out.weight"); + weights.insert( + "model.layers.1.attention.kv_b_proj.weight".into(), + filled(&[heads * (nope + v), kv_lora]), + ); + let weights = sanitize_weights(weights, &args).unwrap(); + assert_eq!( + mlxcel_core::array_shape(&weights["model.layers.1.attention.embed_q.weight"]), + vec![heads, kv_lora, nope], + "{case}" + ); + assert_eq!( + mlxcel_core::array_shape(&weights["model.layers.1.attention.unembed_out.weight"]), + vec![heads, v, kv_lora], + "{case}" + ); + validate_weights(&weights, &args).unwrap_or_else(|e| panic!("{case}: {e}")); + } +} + #[test] fn chunked_prefill_gate_reads_the_off_spellings() { assert!(chunked_prefill_enabled_from(None)); @@ -974,6 +1035,40 @@ fn synthetic_forward_runs_prefill_and_decode_over_both_layer_kinds() { assert!(!model.supports_chunked_prefill()); } +/// Ling-2.6-flash has `kv_lora_rank` 512 and `qk_nope_head_dim` 128. With the +/// two widths unequal the model has to load and run both MLA paths: the +/// materializing prefill (`embed_q` applied to the latent without a transpose) +/// and the absorbed decode (`embed_q` applied to the nope query). +#[test] +fn synthetic_forward_runs_with_kv_lora_rank_unequal_to_nope() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + use mlxcel_core::generate::LanguageModel; + + let mut args = tiny_config(); + args.kv_lora_rank = 8; + args.qk_nope_head_dim = 2; + args.validate().unwrap(); + let weights = tiny_weights(&args); + let model = super::BailingHybridModel::from_weights(&weights, &args).unwrap(); + + let prompt = mlxcel_core::from_slice_i32(&[1, 2, 3], &[1, 3]); + let mut caches = model.make_caches(); + let logits = model.forward(&prompt, &mut caches, None); + assert_eq!( + mlxcel_core::array_shape(&logits), + vec![1, 3, args.vocab_size as i32] + ); + assert_finite(&logits, "prefill logits"); + + let token = mlxcel_core::from_slice_i32(&[4], &[1, 1]); + let logits = model.forward(&token, &mut caches, None); + assert_eq!( + mlxcel_core::array_shape(&logits), + vec![1, 1, args.vocab_size as i32] + ); + assert_finite(&logits, "decode logits"); +} + #[test] fn synthetic_state_snapshots_round_trip_both_cache_kinds() { let _guard = crate::models::embedding_test_support::mlx_test_guard();