Skip to content

feat(models): add Spark-X2.5 (spark2_5) sliding/full hybrid decoder - #3516

Merged
inureyes merged 4 commits into
mainfrom
feature/issue-2372-spark2-5
Nov 28, 2026
Merged

inureyes merged 4 commits into
mainfrom
feature/issue-2372-spark2-5

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

Adds Spark-X2.5 (model_type: spark2_5, Spark2_5ForCausalLM), ported from mlx-lm's spark2_5 package (ml-explore/mlx-lm#1891). It is a dense decoder that runs three sliding-window layers to one full-attention layer, with per-layer-type RoPE, a fused q/k/v projection and a per-head sigmoid attention gate.

  • Each layer type takes its own rope_parameters entry: full layers rotate the first 64 of 256 dims at theta 5e6, sliding layers all 256 at theta 1e4 (non-traditional, absolute cache offset).
  • q_k_v_proj is split at q_size and q_size + kv_size. The g_proj gate runs its sigmoid in f32, casts back to the output dtype, and scales each head before out_proj. The MLP uses erf GELU in the input dtype, reusing Limite's gelu_erf.
  • Sliding layers use RotatingKVCache(sliding_window, keep 0) with window_size = sliding_window masks (no + 1, unlike PLaMo 3), and full layers use KVCache. Both live in ModelOwnedSequenceState through the shared SlidingHybridModel bodies and AFMoE's hybrid_prefill_masks, which gives native batched decode, last-row prefill logits and snapshot reuse.
  • The loader accepts the mlx-lm (model.*), mlx-vlm (language_model.model.*) and model.embed_tokens layouts, drops rotary_emb.inv_freq and uses a tied head. It applies upstream's config checks (if layer_types is absent it defaults to mlx-lm's 3+1 pattern) and refuses projections whose shape disagrees with the config.

Verification (GB10, --features cuda)

  • Greedy parity against mlx_lm 0.32.2 with mlx-cuda-13 0.32.5, using a raw prompt, mlxcel generate --temp 0 --no-chat-template -n 64:
    • abenzerps/Spark-X2.5-4B-MLX-4bit, 8-token prompt: all 64 tokens match.
    • abenzerps/Spark-X2.5-4B-MLX-4bit, 1111-token prompt (wraps the 512-token window): all 64 tokens match.
    • XHToken/Spark-X2.5-1.7B (bf16), 8-token prompt: all 64 tokens match.
    • XHToken/Spark-X2.5-1.7B (bf16), 1111-token prompt: all 64 tokens match.
  • Parity was compared as decoded text, which is identical in all four runs. The mlx-lm prompt length was 8 and 1111 tokens, and the server's usage.prompt_tokens for the short prompt is also 8.
  • mlxcel-server smoke test on the 4B pack: /v1/completions returns the same continuation as the CLI, and /v1/chat/completions answers (reasoning output).
  • mlxcel arch lists the model and mlxcel arch --json includes spark2_5.
  • 13 spark2_5 unit tests pass, including the detection test. The four acceptance tests were checked by reverting the behavior each one covers:
    • RoPE test: fails when every layer uses the sliding table and when every layer uses the full table.
    • Gate test: fails when the sigmoid runs in bf16 (1 - sigmoid(12) rounds to 0), when the cast back to the output dtype is dropped, and aborts when the gate is broadcast over the wrong axis.
    • MLP test: fails with tanh GELU (MLX nn.gelu_approx, mlxcel gelu_tanh) and with SiLU. mlxcel's own gelu_approx is erf despite its name, so the test targets the tanh form.
    • Layout test: fails when any one of the three normalizations is removed.
  • Neighbouring selectors pass: registry, detection, model_metadata, batched/last-row coverage, memory_estimate, snapshot_sizing, tensor_parallel, loaded_model.
  • cargo clippy --lib --tests --features cuda -- -D warnings, cargo fmt --check, the four scripts/ci contract checks, and a release build all pass.

Not run: Metal (no Apple host), the full workspace test suite (left to CI), and the OptiQ pack.

Closes #2372

@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata modelsize:small 4-bit checkpoint <= 10GB; fast iteration, safe for smoke tests modeltype:text Text-only language model arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) labels Nov 28, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Add Spark-X2.5 (spark2_5) as a served text model with per-layer-type partial RoPE, a fused q/k/v projection, a per-head f32 sigmoid gate, erf GELU and a sliding/full hybrid cache, matching mlx-lm.

Findings Addressed

None needed. No CRITICAL or HIGH findings.

Remaining Items

  • When layer_types has no full layer, hybrid_prefill_masks still builds the full-attention mask from layer 0's geometry and discards it. Correct output, one wasted mask per prefill on a hypothetical all-sliding config (LOW), shared AFMoE helper so left alone.
  • Without layer_types, the generic KV memory estimate in kv_arch.rs counts every layer as full context. It overestimates, never underestimates, and every published config lists the types (LOW).
  • The docs/supported-models.md row puts its colon inside the opening parenthesis, unlike the neighbouring rows (LOW).

Verification

  • All stated requirements implemented (config validation matches upstream __post_init__, three key layouts, tied head, inv_freq drop, detection arm, registry, loader, server via LoadedModel, memory estimate and snapshot sizing ids, docs row)
  • No placeholder/mock code remaining
  • Integrated into project code flow (reuses sliding_hybrid_lm, hybrid_prefill_masks, AFMoE weight validators, gelu_erf)
  • Project conventions followed (// Used by: comments updated, contract checks pass)
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass: models::spark2_5 13/13 on GB10 CUDA

Extra checks run during review: making the gate sigmoid run in bf16 fails the gate test (1.25 vs 1.2421875). A throwaway test that built all-full and all-sliding stacks ran prefill, token-by-token decode, and a second multi-token piece on a warm sliding ring. All three matched the one-shot prefill, so the no-full and no-sliding edge cases work. That test was not committed.

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL, HIGH or MEDIUM findings, so no fixes were pushed.

Checked:

  • Untrusted config.json: validate() bounds layers, hidden, intermediate, heads, head_dim and vocab, so every as i32 product (num_heads * head_dim, q + 2 * kv) stays well inside i32. kv heads must divide heads, layer_types length and values are checked, rotary dims must be even, positive and at most head_dim, theta and eps must be finite and positive, and sliding_window goes through validate_sliding_window when a sliding layer exists. The Turbo4Asym rotating-cache panic is behind the shared rotating_mode_for_layer.
  • Malformed checkpoints: validate_weights checks every projection and norm shape against the config before any kernel runs, and validate_embedding_table rejects a vocab_size larger than the table.
  • Hot path: decode (L=1) builds no masks, batched decode passes no mask, and the q/k/v split is lazy views. The f32 sigmoid gate is one [B, L, H] tensor per layer, as upstream does it. Per-step cost matches AFMoE and Kolibri-1.

LOW, not fixed:

  • sanitize_weights lets a language_model.-prefixed key overwrite an unprefixed key of the same name, and leaves stale model.embed_tokens.* tensors in memory when model.embedding.weight already exists. Shape validation still catches a mismatched result.
  • A finite but very large rope_theta (above f32 max) becomes inf after the f32 cast. That gives NaN outputs, not a panic.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 28, 2026
Spark-X2.5 runs three sliding-window layers to one full-attention layer, and each layer type has its own RoPE (full layers rotate 64 of 256 dims at theta 5e6, sliding layers all 256 at 1e4). q/k/v come from one fused q_k_v_proj, a per-head sigmoid gate computed in f32 scales each head before out_proj, and the MLP uses exact erf GELU. Ported from mlx-lm's spark2_5 package.

Sliding layers keep a RotatingKVCache(sliding_window) with window_size = sliding_window masks, full layers a KVCache, both in model-owned state through the shared SlidingHybridModel bodies, so the family gets native batched decode, last-row prefill logits and snapshot reuse. The loader normalizes the mlx-lm, mlx-vlm (language_model.) and model.embed_tokens layouts, drops rotary_emb.inv_freq, and applies upstream's config checks plus projection shape checks.

Greedy 64-token output matches mlx_lm on GB10 for both validation checkpoints, including a 1111-token prompt that wraps the 512-token rotating cache.

Closes #2372
The Spark-X2.5 entry in docs/supported-models.md opened its parenthesis before the colon and closed it at the end of the description. Neighbouring rows close the parenthesis after the identifiers and put the colon outside, so the row now reads the same way.

Validation: cargo fmt --check, clippy --lib --tests --features cuda -D warnings, the four scripts/ci contract checks and 13 models::spark2_5 tests pass.

Refs #2372
…er MLX tests

Running the spark2_5 test selector with parallel threads on CUDA intermittently aborted the binary in cudaStreamEndCapture, because model_owned_batched_multistep ran without the shared MLX test guard. Take mlx_test_guard there like the other forward-pass tests in the module.
@inureyes
inureyes force-pushed the feature/issue-2372-spark2-5 branch from 75bab01 to c745a00 Compare November 28, 2026 16:02
@inureyes
inureyes marked this pull request as ready for review November 28, 2026 16:02
@inureyes
inureyes merged commit bca5242 into main Nov 28, 2026
15 checks passed
@inureyes
inureyes deleted the feature/issue-2372-spark2-5 branch November 28, 2026 16:02
inureyes added a commit that referenced this pull request Nov 28, 2026
Spark-X2.5 (#3516) added the "Spark" family to ModelType::metadata but not to FAMILY_ORDER, so `family_order_is_exhaustive` failed on main. Place it after PLaMo.

Refs #3516
inureyes added a commit that referenced this pull request Nov 29, 2026
Spark-X2.5 (#3516) gave `ModelType::Spark25` the new family "Spark", which `FAMILY_ORDER` in src/main.rs did not list, so `family_order_is_exhaustive` failed on main. The unit ran narrow test selectors and never built the `mlxcel` bin tests that hold this check; the post-run workspace gate caught it.

Add "Spark" after "PLaMo", beside the other sliding/full hybrid text families. `cargo test --features cuda --bin mlxcel family_order` passes.
@inureyes inureyes added this to the 0.9 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:models Model architectures, weights, loading, metadata modelsize:small 4-bit checkpoint <= 10GB; fast iteration, safe for smoke tests modeltype:text Text-only language model priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(models): add Spark-X2.5 (spark2_5) support

1 participant