Repository navigation
fix(models): return a load error on mismatched MoE expert shapes - #3304
Merged
Merged
Conversation
inureyes
force-pushed
the
fix/issue-3297-moe-expert-shape-errors
branch
from
November 23, 2026 03:29
d4c11dd to
8cb061b
Compare
`drain_numbered_expert_planes` and `stack_individual_experts_with_count` passed every expert's plane straight to `mlxcel_core::stack`, which is not fallible across the FFI, so one expert of another shape terminated the process instead of failing the load. Both now compare each expert's `weight`, `scales` and `biases` (shape and dtype) with the first expert's before stacking and return an error naming the key, the expert index and both shapes. The NVFP4 `global_scale` sidecar stays exempt because it is concatenated, not stacked. An unstacked expert that lacks the `scales` or `biases` expert 0 carries is refused with its key instead of falling through to `Missing weight`. The drain helper returns `Result<(), String>`, and the error propagates through `qwen3_5::sanitize_weights` and `sanitize_moe_weights`, `Qwen3NextModel::sanitize_weights`, `stack_gemma4_per_expert_planes` and `kolibri1_weights::sanitize_weights` to their loaders. `SwitchLinear::from_weights_with_mode` returns the error for the unstacked-expert families. Kolibri-1's `LanguageModel` impl was AFMoE's with the names changed. The shared bodies (sequence state, KV mode table, snapshot, restore, truncated restore, ring checkpoint, batched decode) move to `src/models/sliding_hybrid_lm.rs`, parameterized by the snapshot family tag and `KvSnapshotNames` through a `SlidingHybridModel` trait, and both impls delegate to it. Messages and behavior are unchanged; Kolibri-1 still does not take ring checkpoints. Closes #3297
inureyes
force-pushed
the
fix/issue-3297-moe-expert-shape-errors
branch
from
November 23, 2026 07:26
8cb061b to
435bc90
Compare
inureyes
marked this pull request as ready for review
November 23, 2026 07:33
inureyes
added a commit
that referenced
this pull request
Nov 23, 2026
…riant (#3330) ## Summary Two follow-ups from #3303 and #3304, in one PR as the issue asks. ### 1. K2-Horizon budget close matches the opened variant K2-Horizon's template primes `<ifm|think>`, `<ifm|think_fast>` or `<ifm|think_faster>` by `reasoning_effort` (high, medium, low). An exhausted `thinking_budget_tokens` cap or a `reasoning_end` control request always forced `</ifm|think>`, so a `medium` or `low` block was closed with a tag the model never saw paired with its open. - `ThinkingTokenIds` gains `alt_opens`, index-paired with `alt_closes` and filled from the same `THINK_EFFORT_VARIANTS` entries, plus `close_for_open`. - `ThinkingState` keeps a private `active_close`. `observe` sets it when the model emits the pair's open or a variant open (a variant open now enters `InBlock` too), and `with_primed_close` sets it for a primed prompt, accepted only when `ids.is_close(close)`. Both forcing paths force `active_close.unwrap_or(ids.close)`, so the `--reasoning-budget-message` run is unchanged and still precedes the close. - `ServerGenerateOptions::thinking_primed_close` carries the `primed_open_thinking_close_marker` value the routes already compute. It is set wherever `thinking_enter_block_on_start` is set from the primed prompt: `prepare_chat_generation` (`/v1/chat/completions` and the `mlxcel chat` / `mlxcel run` CLI through `InProcessServer::chat`), the router front, `/v1/responses` (run and non-streaming), responses compaction, Anthropic `/v1/messages` (streaming and not) and the ASR chat path. - `build_thinking_state` resolves the marker to an id through the new `thinking_budget::resolve_primed_close_id` (the tokenizer's `token_to_id`, only when the prompt primed the block; a multi-token close resolves to nothing and falls back to the pair's close). - A variant open whose close is missing from the vocabulary opens nothing, so a mismatched close is never forced. - Out of scope, as the issue says: the disaggregated handoff (`build_handoff_thinking_state` and the `kv_cache_serde` wire format). The router front sets the field, but the prefill frame does not carry it, so a primed variant on that path still gets `</ifm|think>`; a comment at the assignment, `docs/supported-models.md` and the CHANGELOG say so. ### 2. Stale Qwen3.5 ragged-rollback test `rollback_speculative_cache_panics_on_ragged_batched_accepts` expected a panic that #2442 removed. It is replaced by `rollback_speculative_cache_compacts_ragged_batched_accepts`: rows `[1, 2, 3, 4]` and `[5, 6, 7, 0]` verified with accepts `[3, 1]`; each row's linear-layer `conv_state` and `state_cache` must match a B = 1 rollback of that row with its own accept, and the attention offset must be `max(accepted) + 1` = 4. The shared `verify_and_rollback` helper now checks the returned count against `max(accepted)`, which is what `rollback_speculative_cache` returns for both uniform and ragged accepts. ## Tests - `server::k2_horizon_reasoning_tests::a_primed_budget_forces_the_close_of_the_primed_variant`: for `high`, `medium`, `low`, a primed state with a budget of 2 built through `with_primed_close` forces that effort's own close, and so does a `reasoning_end` flag. - `a_model_emitted_variant_open_is_closed_with_its_own_close`: a non-primed state that observes each open enters `InBlock` and forces the matching close at the cap. - `an_unrelated_primed_close_falls_back_to_the_pair_close`. - `the_primed_close_marker_resolves_to_its_token_id`: each effort's close resolves, an unprimed prompt and a multi-token close resolve to nothing. - `variant_close_edge_cases`: a `--reasoning-budget-message` run precedes the variant close, a zero budget forces the variant close at once, and a model's own matching or mismatched close is let through. - `chat_completions_pass_the_primed_variant_close_to_the_scheduler`: the real chat route, streaming and not, hands the scheduler the primed variant's close for each effort. - Existing `server::thinking_budget` tests (Qwen, Gemma 4, `<|content_thinking|>` pairs) pass unchanged. ## Verification Narrow equivalents of the issue's Verification block (the broad gate is left to the orchestrator): - `cargo fmt --all -- --check`, `cargo clippy --lib --tests --features metal,accelerate -- -D warnings`: clean. - `server::thinking_budget server::k2_horizon_reasoning_tests server::routes::chat`: 131 passed. - `models::qwen3_5_tests --ignored --test-threads=1` (GPU lock): 7 of 7 passed. - `coverage_tests`: 18 passed; the seven CI contract scripts pass. - Real checkpoint, `mlxcel-server --skip-chat-parsing` on `models/k2-horizon-0.9b`, greedy, `thinking_budget_tokens: 6`: `high` ends the reasoning with `</ifm|think>` after six tokens, `medium` with `</ifm|think_fast>` after six tokens, and `low` closes on its own with `</ifm|think_faster>` at the first token. With parsing on, the budgeted tokens land in `reasoning_content` for every effort. Technical report: `TECHNICAL_REPORTS/3330-k2-horizon-variant-close-20261123.en.md` and `.ko.md`. Closes #3321
inureyes
added a commit
that referenced
this pull request
Nov 23, 2026
…3335) ## Summary Six MoE families stack per-expert planes in their own sanitize code: DeepSeek-V3, Mistral4, PhiMoE, OLMoE, MiMo-V2 and Mellum. They passed the parts straight to `mlxcel_core::stack` / `stack_owned` / `stack_expert_leaf`, and that FFI is not fallible, so one malformed expert in a checkpoint raised MLX's `[stack] All arrays must have the same shape` across the cxx bridge and aborted the process at load. Each site now runs #3304's `refuse_mismatched_expert_parts` before the stack call and returns a load error naming the expert's on-disk key, its shape and dtype, and expert 0's shape and dtype. ## Changes - `switch_layers::refuse_mismatched_expert_parts` is now `pub(crate)` and its `Used by` list names the six families. - DeepSeek-V3 (`sanitize_weights`), Mistral4 (`sanitize_weights`) and PhiMoE (`sanitize_weights`): the per-leaf loop collects `(expert, &array)` pairs, checks them, then stacks. The `global_scale` sidecar is exempt because `stack_expert_leaf` concatenates it, as in #3304. - OLMoE `sanitize_weights`: returns `Result<WeightMap, String>`; the removed experts are checked before `stack`. `OlmoeModel::load` propagates the error. - MiMo-V2 `stack_experts`: checks the drained parts before `stack_owned`. - Mellum `MellumModel::sanitize` and its `stack_experts` return `Result<(), String>`; `MellumModel::load` propagates. - Mistral4 `sanitize_weights` returns `Result<(), String>`; the callers in `Mistral4Model::load`, `load_from_text_config`, `src/loading/mod.rs` and `src/loading/vlm_pixtral.rs` propagate it. - On error nothing is inserted for the refused leaf. ## Tests Each family has one test on synthetic weights where expert 1's gate `weight` is `[4, 6]` and expert 0's is `[4, 8]`; each asserts the sanitize call returns `Err` naming expert 1's key and both shapes. The PhiMoE test sits in `phimoe.rs`'s inline `sanitize_tests` module beside the existing stacking test, because `PhiMoeModel::sanitize_weights` is private and `phimoe_tests.rs` is a sibling module that cannot reach it. Failing first: with the helper short-circuited to `Ok(())`, all six tests abort the test binary with `[stack] All arrays must have the same shape` (SIGABRT); with the check they pass. Selectors run (`--profile test-fast --features metal,accelerate --lib`, under the GPU lock): `mismatched_expert` (9 passed, the six new tests plus the existing Qwen3.5, Laguna and Kimi-K3 ones), `models::deepseek_v3` (73), `models::mistral4` (4), `models::phimoe` (15), `models::olmoe` (2, 2 ignored), `models::mimo_v2` (20), `models::mellum` (7), `models::switch_layers` (66, 1 ignored), `coverage_tests` (18). The broad `--test-threads=1` gate in the issue is left to the orchestrator. `cargo clippy --lib --tests --features metal,accelerate -- -D warnings`, `cargo fmt --all -- --check` and the `scripts/ci` contract checks pass. ## Checkpoint regressions `mlxcel generate -p "The capital of France is" -n 24 --temp 0`, release build, under the GPU lock; each answers "Paris.": - `gigachat3-10b-a1.8b-bf16` (DeepSeek-V3, per-expert layout stacked by this code) - `olmoe-1b-7b-0125-4bit` (OLMoE, per-expert layout stacked by this code) - `gigachat3-10b-a1.8b-mlx-8bit` and `moonlight-16b-a3b-instruct-4bit` (DeepSeek-V3, quantized) No local Mistral4, PhiMoE or Mellum checkpoint exists; `MiMo-V2-Flash-4bit` (162 GB) was skipped under the 100 GB limit. The bilingual technical report is in `TECHNICAL_REPORTS/3335-family-moe-expert-shape-checks-20261123.{en,ko}.md`. Closes #3320
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Two items from #3297, in one PR.
1. Mismatched per-expert planes fail the load instead of aborting
drain_numbered_expert_planesandstack_individual_experts_with_count(src/models/switch_layers.rs) passed every expert's plane straight tomlxcel_core::stack. That FFI is not declared fallible, so MLX's[stack]shape exception terminated the process. A new helper,refuse_mismatched_expert_parts, compares each expert'sweight,scalesandbiases(shape and dtype) with the first expert that carries the leaf, before anystackcall, and returns an error naming the key, the expert index and both shapes, for examplemodel.layers.0.mlp.experts.1.gate_proj.weight: expert 1 has shape [4, 6] (dtype ...), but expert 0 (...) has shape [4, 8] ....global_scalesidecar is exempt: it is flattened and concatenated, not stacked, so a malformed one changes the vector's length andSwitchLinearalready refuses that.drain_numbered_expert_planesreturnsResult<(), String>and inserts nothing on failure. The error propagates throughqwen3_5::sanitize_weightsandsanitize_moe_weights,Qwen3NextModel::sanitize_weights,stack_gemma4_per_expert_planesandkolibri1_weights::sanitize_weights(each now returnsResult), and through their loaders: the Qwen3.5 text, MoE, VLM, special-VLM and tensor-parallel paths, the Qwen3-Next model and pipeline-stage loaders, the Gemma 4 NVFP4 sanitize, andKolibri1Model::from_weights.stack_individual_experts_with_countreturnsResult<Option<..>, String>, soSwitchLinear::from_weights_with_mode/from_weights(the unstacked-expert path used by AFMoE, Mixtral, Qwen2-MoE and the other families listed in itsUsed by) and DeepSeek v1'sstack_individual_expertsreturn the error. An unstacked expert that lacks thescalesorbiasesexpert 0 carries is now refused with its key; before, it fell through toMissing weight: <prefix>.stackused to promote and load, are now refused. No known checkpoint mixes expert dtypes; the issue asks for the check, and a mixed packed/float stack would otherwise load wrong values.2. Kolibri-1's
LanguageModelimpl delegates to AFMoE's shared bodiesimpl LanguageModel for Kolibri1Modelwas AFMoE's impl with the names changed. The shared bodies move tosrc/models/sliding_hybrid_lm.rs: a crate-privateSlidingHybridModeltrait supplies the snapshot family tag (FAMILY), theKvSnapshotNames, and accessors for the sequence state, KV mode table, internal caches, layer kinds, window and batched decode; generic functions implement reset, sequence-state layout, prepare, sync, KV mode table and storage modes, snapshot, restore, truncatable check, truncated restore, ring checkpoint,make_cachesandforward_batched_with_ids. Both impls delegate to them. Error, log and panic texts are the same strings as before (for examplecannot restore X snapshot into AFMoE,kolibri1 batched decode: ...).AFMoE keeps its ring-checkpoint methods (#3255), now one-line delegations. Kolibri-1 still does not override them, as on main; enabling ring checkpoints there would be a behavior change and is left out of this PR.
CHANGELOG: Fixed entry.
Review
Implementation review and security/performance review found no CRITICAL or HIGH findings. Open, not fixed here: several family-local stacking loops still call
stackorstack_expert_leafunchecked (deepseek_v3.rs,mistral4.rs,phimoe.rs,olmoe.rs,jamba.rs,mimo_v2_weights.rs,laguna_sanitize.rs,bailing_moe_linear.rs), outside this issue's scope;refuse_mismatched_expert_partscan be reused for a follow-up. LOW: the check instack_individual_experts_with_countturns the collected raw pointers back into references in oneunsafeblock (sound, the map is borrowed for the whole function); and when a later projection fails, earlier projections of the same layer are already stacked in the map (the load fails either way).Test plan
models::switch_layers::expert_shape_tests(7): drain refuses another weight shape, another dtype and mismatched scales, and still stacks well-formed experts;SwitchLinear::from_weights_with_modeandfrom_weightsrefuse an unstacked expert of another shape and one missingscales;stack_individual_expertsreports the mismatch. Newqwen3_5::sanitize_tests::sanitize_weights_refuses_mismatched_expert_shapes(bothw1andgate_proj-style names) andkolibri1::tests::an_expert_plane_of_another_shape_fails_the_load_instead_of_aborting(sanitize andKolibri1Model::from_weights). On main these tests do not compile against the old signatures, and the same inputs there reachmlxcel_core::stack, which aborts the test binary rather than failing a test.--profile test-fast --features metal,accelerate, serial, under the GPU lock):models::switch_layers66 passed,models::qwen3_5::12,models::qwen3_next19,models::sanitize::62,gemma4285,models::afmoe32 (snapshot, restore, truncation, ring checkpoint and batched tests unchanged),models::kolibri120,coverage_tests18 (includeslast_row_logits_coverage_testsandbatched_decode_coverage_tests). All passed.models::qwen3_5_tests: 6 passed, 1 failed:rollback_speculative_cache_panics_on_ragged_batched_acceptsdoes not panic as expected. It builds its model withfrom_weightsand never reaches sanitize or expert stacking, and the panic text it expects now lives only indrafter/dflash/round_loop_batched.rs, so this looks pre-existing; I did not rerun it on main.examples/logit_traceonmodels/kolibri-1-mlx-4bit, release binaries built from origin/main (aaf8e81) and from this branch, corpusdocs/architecture.md: prefill (256 2 8),MLXCEL_TRACE_LAST_ROW=1, andMLXCEL_TRACE_BATCH_ROWS=2width-one batched decode (192 1 8 64) are byte-identical before and after (520, 11 and 201 lines;cmpequal).cargo fmt --all -- --check;cargo clippy --lib --tests --features metal,accelerate -- -D warnings;cargo check --bins;scripts/ci/check_used_by.py,check_kernel_dtype_keys.py,check_env_var_docs.py,check_crate_versions.py,check_kernel_port_dispatch.py,check_binary_assets.py;scripts/insert_apache_header.py --check.cargo clippy --workspace --all-targets,cargo test --workspace -- --test-threads=1) were not run here; left to the orchestrator.Closes #3297