Skip to content

feat(models): port DeepSeek-V4 as a net-new architecture (#523) - #1455

Merged
inureyes merged 13 commits into
mainfrom
feature/issue-523-deepseek-v4-port
Aug 27, 2026
Merged

inureyes merged 13 commits into
mainfrom
feature/issue-523-deepseek-v4-port

Conversation

@inureyes

@inureyes inureyes commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Port DeepSeek-V4 (DeepSeek-V4-Flash) as a genuinely new architecture from the in-tree reference references/mlx-vlm/mlx_vlm/models/deepseek_v4/, replacing the rejected V3-wrapper premise of PR #592. A V3 wrapper cannot load or run a real V4 checkpoint: V4 carries a rank-4 [B, L, hc_mult, D] hidden state through Sinkhorn-normalised HyperConnections, a pooled-KV Compressor over a single shared 512-wide KV head in a 128-token rotating window instead of MLA, HiSA hierarchical sparse selection, hash-routed MoE with sqrtsoftplus gating, and a grouped MultiLinear output projection with an inverse RoPE on the attention output.

What changed

  • src/models/deepseek_v4.rs: config parsing (including the real checkpoint's duplicate quantization/quantization_config keys and its 44-for-43 compress_ratios list), validation of every allocation-sizing scalar and the per-path quantization overrides, the block/model assembly, model-owned heterogeneous sequence state (gemma3/afmoe pattern), and the LanguageModel impl.
  • src/models/deepseek_v4_hyper.rs: HyperConnection / HyperHead / hc_expand, the pure-ops Sinkhorn path in float32 (softmax + eps, initial column normalisation, then hc_sinkhorn_iters - 1 row/column rounds).
  • src/models/deepseek_v4_rope.rs: full-head proportional RoPE with inf-padded frequency tables, Yarn correction, inverse tables for the output un-rotation, and freq_scale division for pooled positions.
  • src/models/deepseek_v4_compress.rs: PoolingCache (prompt and decode branches, remainder buffer) plus the Compressor with the NON-interchangeable simple (ratio 128) and overlap (ratio 4, doubled feature width, one-window-back shift) pooling functions, and the additive pooled-visibility mask helpers.
  • src/models/deepseek_v4_indexer.rs: the HiSA Indexer with its own compressor: decode fast path, batched causality-honouring tiled path, and the flat fallback the hierarchy must agree with.
  • src/models/deepseek_v4_attention.rs: one attention struct across the three compress_ratios kinds (v4_attention_factory semantics), single shared KV head, weightless Q RMSNorm, per-head sinks, inverse output RoPE, grouped wo_a MultiLinear + wo_b, and the split-softmax _sparse_pooled_attention sharing one log-normalizer with the sinks.
  • src/models/deepseek_v4_moe.rs: tid2eid hash routing for the first num_hash_layers layers (indices from token ids, weights from logits, input_ids threaded through every block), selection on bias-corrected scores with weights gathered from unbiased ones, sqrtsoftplus scoring in float32, and the limited SwiGLU clamp in both routed and shared experts; routed experts load through the shared switch_layers::SwitchLinear with the checkpoint's per-path mxfp4/group-32 overrides under an affine/64 top level.
  • src/models/deepseek_v4_sanitize.rs: both tensor-name planes (mlx-community and the legacy reference plane with hc_* renames, w1/w2/w3, per-expert stacking, uint8 view(uint32) fixups), mtp.* and beyond-layer drops, tid2eid int32 cast, 2-D wo_a reshape, and a strict weight-coverage check that fails the load naming any tensor that maps onto no module path or any required tensor that is missing.
  • Registration: ModelType::DeepSeekV4 in src/models/mod.rs, detection.rs arm, LoadedModel variant via delegate_language_model!, src/model_metadata.rs config-backed row, tensor-parallel fallback table entry.
  • docs/supported-models.md: house-style deepseek_v4 entry; the v1/v2/v3/v3.2 paragraph now states V4 is not a fifth member of that implementation family. CHANGELOG.md: an [Unreleased] entry for the family addition.
  • Tests: 39 unit tests in src/models/deepseek_v4_tests.rs with float64 fixture replays of the reference math, a detection test, and tests/deepseek_v4_real_model.rs (a non-ignored real-config parse preflight plus three ignore-gated real-checkpoint gates).

Hardening applied during review

Review closed several boundaries where untrusted checkpoint or config data reached MLX unguarded. Each is now a load-time Result rather than an uncatchable abort at first forward, and each is covered by a test.

  • tid2eid contents were never range checked, only its shape. V4 is the only routing path in the tree whose expert indices come from a checkpoint tensor rather than an argpartition over the score row, so the in-range-by-construction argument that covers bailing_moe / afmoe / klear does not reach it. Those indices feed take_along_axis and gather_qmm, and MLX gathers fold negative indices but never clamp, so an out-of-range expert id in a downloaded checkpoint was an out-of-bounds read.
  • PoolingCache::update_and_fetch deep-copied the entire pooled buffer on every call, including the no-op branch that dominates decode (3 of every 4 steps at ratio 4, 127 of 128 at ratio 128), roughly 54 MB per decoded token at 8k context. It now returns a borrow, matching the reference.
  • The indexer's pooling cache accumulated an unevaluated MLX graph across decode steps, pinning each step's hidden state, because its only consumer is discarded on two of the three sparse branches. eval_state after the layer loop mirrors KVCache::eval_state.
  • e_score_correction_bias had no shape check, the 2-D wo_a reshape ran unguarded on checkpoint data, architecture scalars were bounded below but not above, and index_block / index_keep were unvalidated while being multiplied in i32.

Test plan

  • cargo test --lib models::deepseek_v4: 39/39 passed, including float64 fixture replays of the reference math (Sinkhorn gates, hc_expand, yarn tables, inf-prefix/inverse/freq-scale rope composition, both compress functions, limited SwiGLU, sqrtsoftplus), HiSA hierarchical-vs-flat agreement on tie-free inputs, the biased-selection/unbiased-weighting gate contract, hash routing via tid2eid, hostile config and quantization-override rejection with positive controls, legacy-plane sanitize, strict coverage rejection, load-time shape checks, the tiny three-kind end-to-end model, and window-aligned chunked-prefill parity.
  • cargo test --lib models::deepseek: 68/68 across the whole DeepSeek family (v1/v2/v3/v3.2/v4), no regression. models::detection 43/43 including the new arm; models::switch_layers 23/23; loaded_model 5/5.
  • cargo clippy --lib --tests -- -D warnings: exit 0. cargo fmt --check: clean.
  • Coverage preflight against the real index: the expected-tensor generator cross-checked against all 2481 tensors of model.safetensors.index.json, zero missing and zero unknown after ratio truncation. All 641 quantized planes satisfy packed_in * 32 == bits * num_groups * group_size.
  • Real-checkpoint load and generation: all three #[ignore] gates pass against mlx-community/DeepSeek-V4-Flash-4bit (43 layers, 2481 tensors, ~151 GB on disk) on an M3 Ultra / 512 GB, in 80s. The checkpoint was verified complete before the run two independent ways: every file matching the upstream declared byte count, and every shard self-consistent against its own safetensors header. Results are in feat(models): port DeepSeek-V4 as a net-new architecture (#523) #1455 (comment) and were re-run unchanged after the hardening commits above, producing byte-identical output.
[deepseek-v4] long-context prompt: 2234 tokens
[deepseek-v4] long-context answer: " The Pacific Ocean is the largest ocean on Earth. The Pacific"
test deepseek_v4_real_model_long_context_hits_sparse_and_compressed_paths ... ok
[deepseek-v4] prompt: "The capital of France is"
[deepseek-v4] greedy continuation (24 tokens): " Paris. The capital of France is Paris. ..."
test deepseek_v4_real_model_loads_and_generates_coherently ... ok
test deepseek_v4_real_model_decode_crosses_pooling_windows ... ok

test result: ok. 3 passed; 0 failed

The long-context gate is the load-bearing one: at 2234 tokens a ratio-4 layer's pooled count passes index_topk (512), so SparseCompressedAttention takes the HiSA selection and split-softmax branch rather than the dense concat fallback, and it still has to retrieve the right fact from early in the context. The repetition in the short greedy continuation is ordinary temperature-0 decoding on a base checkpoint, not a porting artifact.

Follow-ups (out of scope here, as scoped in the issue)

  • The reference's fused HC Sinkhorn+collapse Metal kernel (_hc_sinkhorn_collapse_kernel); this port implements the pure-ops correctness baseline the reference itself uses off-Metal.
  • MTP drafting (num_nextn_predict_layers; mtp.* tensors are dropped at load).
  • Tensor-parallel / pipeline sharding (the reference's shard()), VLM wrapping, and a fused-MoE decode kernel with a clamp stage (MLXCEL_FUSED_MOE stays unfused for this family).
  • No forward_last_logits override, so a prefill chunk materialises full [1, 2048, 129280] logits to sample one row. Deferred deliberately rather than fixed alongside a first-time architecture port.
  • sparse_pooled_attention promotes to f32 where the reference stays in the activation dtype, roughly 2x on the largest intermediates. Left because changing it moves numerics.
  • Issues feat(deepseek-v4): implement HiSA hierarchical sparse attention #549 (HiSA) and feat(deepseek-v4): clamp shared-expert SwiGLU to swiglu_limit #550 (shared-expert swiglu_limit clamp) were filed under the old, rejected V3-wrapper scope; this port subsumes both (HiSA in deepseek_v4_indexer.rs, the clamp in deepseek_v4_moe.rs). Left open for a human to close.

Closes #523

Port references/mlx-vlm/mlx_vlm/models/deepseek_v4 faithfully instead of wrapping DeepSeekV3Model (the premise PR #592 was closed over): HyperConnections with the Sinkhorn-normalised comb gates carry a rank-4 [B, L, hc_mult, D] state between blocks; per-layer compress_ratios select local (0), pooled-compressed (128), or HiSA sparse-compressed (4) attention over one shared 512-wide KV head in a 128-token rotating window; the Compressor pools ratio-sized windows with a learned ape and window softmax (overlap mode at ratio 4), RMS-norms, and Yarn-ropes them at compress_rope_theta with freq_scale = ratio; the Indexer scores its own pooled stream and returns index_topk rows for a split-softmax sparse attention sharing one log-normalizer with the per-head sinks; the MoE routes the first num_hash_layers layers by tid2eid token-id lookup (input_ids threads through every block), selects on bias-corrected scores while weighting from unbiased ones, and clamps both expert paths at swiglu_limit; wo_a is the grouped MultiLinear low-rank output projection.

Heterogeneous per-layer state (RotatingKVCache plus one or two PoolingCaches) rides in ModelOwnedSequenceState following the gemma3/afmoe pattern, with placeholder KVCaches from make_caches. Sanitization handles both the mlx-community tensor plane the real DeepSeek-V4-Flash-4bit ships and the legacy export plane the reference handles (hc_* renames, w1/w2/w3, per-expert stacking, uint8 view fixups), drops mtp.* tensors, casts tid2eid to int32, and reshapes 2-D wo_a planes; a strict coverage check then requires the tensor set to match the config exactly, so nothing loads by silent fallback. Config validation bounds every allocation-sizing scalar, the compress ratio set {0, 4, 128}, the scoring function, and the per-path quantization overrides (mxfp4/32 experts under an affine/64 top level).

Registered across ModelType, detection, LoadedModel via delegate_language_model!, model_metadata, and the tensor-parallel fallback table.

Refs #523
Add 26 unit tests for the V4 port. The numeric fixtures replay the reference math (_hc_split_sinkhorn_ops, DeepseekV4RoPE yarn tables, _limited_swiglu, sqrtsoftplus, _simple/_overlap_compress_kv) in float64 outside MLX, so a port bug and a fixture bug cannot share a cause. Component coverage: Sinkhorn gate output, hc_expand, HyperHead collapse, yarn frequency correction, inf-prefix/negation/freq_scale table composition and forward-inverse rope identity, PoolingCache prompt/decode window emission and visibility counts, both compress functions, limited-SwiGLU clamping, the biased-selection/unbiased-weighting gate contract, hash routing via tid2eid, hostile config and per-path quantization override rejection with positive controls, legacy-plane sanitize remaps, wo_a reshape plus tid2eid int32 cast, strict weight-coverage rejection naming the offending tensor, a three-kind tiny end-to-end model (prefill, decode, cache topology), chunked-prefill parity, and a detection arm test.

The HiSA selection paths now take precomputed head weights so the hierarchical/flat agreement test can drive them with strictly positive tie-free inputs: relu'd indexer scores tie at exact 0.0 routinely, and argpartition tie-breaking across differently shaped calls is reference-inherited indeterminism, not a port defect. The chunked-parity test splits at a window boundary for the same reason: _overlap_compress_kv shifts the overlap half within each ready batch, so a ratio-4 window completed at a chunk boundary legitimately sees the zero/-inf prefix (now documented in the compress module).

Refs #523
…test

Add the deepseek_v4 entry to docs/supported-models.md in the surrounding house style, naming what is silently wrong if done the easy way (Sinkhorn iteration count and order, the non-interchangeable overlap compressor and its within-batch shift, inverse output RoPE, selection-vs-weighting gate contract, hash routing needing input_ids, per-path mxfp4/32 expert overrides under an affine/64 top level), and detach V4 from the v1/v2/v3/v3.2 implementation-family paragraph since it shares nothing structural with them.

Add tests/deepseek_v4_real_model.rs, ignore-gated on the ~145 GB local checkpoint: loading alone proves strict weight coverage (every tensor maps to a module path and vice versa), and two greedy generations exercise all three attention kinds, both gate routings, and decode-mode pooling across window boundaries with a factual-answer coherence gate.

Refs #523
The real DeepSeek-V4-Flash-4bit config.json ships BOTH `quantization` and `quantization_config` with identical content; a serde alias treats the pair as a duplicate field and rejects the whole config, which would have surfaced only after a full checkpoint load. Split them into two optional fields behind a precedence accessor (`quantization` wins), and add a unit test pinning the both-keys shape plus the 44-for-43 `compress_ratios` truncation the reference performs in `__post_init__`. Also add a non-ignored preflight in tests/deepseek_v4_real_model.rs that parses and validates the real config.json (skipping when the checkpoint is absent), asserting the layer count, truncated ratio tail, hash-layer count, the per-path mxfp4/32 expert override, and the eos id, so serde shape drift against the shipped config fails in seconds instead of after a 145 GB load.

Refs #523
Mirror the reference exactly: _sparse_pooled_attention receives attn_sink already cast to the activation dtype, and the logaddexp against the f32 normalizer performs the promotion. Passing the raw f32 tensor was slightly more precise than the reference, which is still a parity deviation.

Refs #523
The sparse split-softmax and HiSA selection only engage past index_topk * ratio prompt tokens (~2048), and the ratio-128 layers only pool past their first 128-token window, so the short smokes cannot reach either. Build a ~2200-token factual prompt, generate greedily, and gate on retrieving a fact from deep context.

Refs #523
@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 labels Aug 26, 2026
`cargo clippy --lib --tests -- -D warnings` failed on this branch: the long-context real-model gate added in c4847cc builds its prompt with `if i % 8 == 0`, which trips `clippy::manual_is_multiple_of` and fails the whole `deepseek_v4_real_model` test target under `-D warnings`. The rest of the port already uses `is_multiple_of` (see `ModelArgs::validate`), so this brings the one remaining site in line.

Verified by reintroducing the old expression and confirming clippy rejects it, then restoring the fix and confirming `cargo clippy --lib --tests -- -D warnings` exits 0. `cargo fmt --check` is clean on every V4 file.

Refs #523
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Port DeepSeek-V4 as a genuinely new architecture (rank-4 HyperConnection state, pooled-KV Compressor, HiSA indexer, hash-routed sqrtsoftplus MoE, grouped MultiLinear output), replacing the rejected V3-wrapper premise of PR #592, and register it end to end.

Findings Addressed

  • cargo clippy --lib --tests -- -D warnings failed on this branch: clippy::manual_is_multiple_of at tests/deepseek_v4_real_model.rs:164 (if i % 8 == 0) failed the whole deepseek_v4_real_model test target. The implementer's "clippy zero warnings" result was true when it ran but went stale when c4847cc added the long-context gate. Fixed in 1c8b07a. Verified by reintroducing the old expression, confirming clippy rejects it, restoring the fix, and confirming cargo clippy --lib --tests -- -D warnings exits 0. (HIGH, CI-breaking)

Reference-Parity Verification

The reference math was re-derived from references/mlx-vlm/mlx_vlm/models/deepseek_v4/ in an independent from-scratch transcription rather than read off the port, and the committed float64 fixtures match to 8 decimal places:

  • HyperConnection: post, the full 4x4 comb, and collapsed reproduce _hc_split_sinkhorn_ops exactly. The softmax then +eps then INITIAL column normalisation then iters - 1 rounds of (row, column) ordering is correct, as are pre = sigmoid + eps and post = 2 * sigmoid, all in float32 over an f32 copy of the widened state.
  • _simple_compress_kv and _overlap_compress_kv both reproduce exactly, including the feature-axis split, the one-window backshift with the zero / -inf prefix, the window-axis concat, and ape added before the softmax. The two paths are genuinely distinct and correctly selected on compress_ratio == 4.
  • _limited_swiglu at limit 10 (min on gate, clip on up) and sqrt(softplus(x)) both reproduce exactly.
  • hc_expand, HyperHead, PoolingCache prompt/decode branches, make_mask giving pool_idx < (offset + 1 + j) / ratio with None for L == 1, all three HiSA paths including the batched valid_len causality, the biased-selection / unbiased-weighting gate contract, tid2eid hash routing, the MultiLinear wo_a/wo_b path, the inverse output RoPE, per-head sinks, and the weightless Q RMSNorm were diffed line by line against the reference and match.

Real-Checkpoint Predictions

Real load and generation have not been run yet, so the load path was exercised statically against models/deepseek-v4-flash-4bit:

  • Weight coverage: the sanitize_weights keep rules and validate_weight_coverage required/allowed sets were re-derived from the config and run against all 2481 tensors of model.safetensors.index.json. Result: 0 missing, 0 unknown, 0 dropped (the checkpoint ships no mtp.* tensors despite num_nextn_predict_layers: 1, and the 44-entry compress_ratios truncates to 43 so the last layer is ratio 4, matching the reference __post_init__).
  • Quantization overrides: all 641 quantized planes satisfy packed_in * 32 == bits * num_groups * group_size under the per-path override the loader would read, with 0 mode/bias mismatches. The 129 expert planes resolve to mxfp4 group 32 with U8 scales and no .biases; the other 512 overrides are all (64, 4, affine), identical to the top level, so reading the top-level pair for non-expert paths is correct on this checkpoint.
  • Shapes and dtypes spot-checked against what each loader expects: attn_hc.fn F32 [24, 16384], hc_head.fn F32 [4, 16384], attn_sink F32 [64], tid2eid I64 [129280, 6], wo_a.weight 2-D [8192, 512] reshaping cleanly to [8, 1024, 512], ratio-4 compressor.ape [4, 1024] against ratio-128 [128, 512], and indexer compressor.ape [4, 256]. Nothing in deepseek_v4_sanitize.rs fires a legacy-plane arm on this checkpoint: .scales (plural) correctly does not match the .scale legacy quant fixup.
  • Prefill masking: create_sliding_window_prefill_mask is the UNCAPPED builder, giving [L, min(offset, window - 1) + L], which is exactly the shape RotatingKVCache::update_concat returns and exactly what the reference's RotatingKVCache.make_mask produces, so align_local_mask is a no-op on the real path and there is no all-masked-row degeneration at L > 128.
  • Chunked prefill: the default MLXCEL_PREFILL_CHUNK of 2048 is a multiple of both 4 and 128, so chunk boundaries land on window boundaries for every compressed layer.

Remaining Items

  • LimitedSwitchGlu skips the gather_sort / scatter_unsort fast path that the shared SwitchGLU takes once tokens * top_k >= 64, so V4 prefill routes every expert dispatch through unsorted gather_qmm. Correctness is unaffected (sorting is an optimisation), but a 2048-token chunk at top-k 6 is 12288 unsorted gathers per layer. Follow-up, not a blocker. (LOW)
  • No forward_last_logits override. With vocab_size 129280 the default computes the full [1, chunk, 129280] logits per prefill chunk (about 530 MB in bf16 at chunk 2048) to sample one row. Several large-vocab families in this tree override it. Deliberately not fixed here: adding an untested projection shortcut to a port whose real-checkpoint run has not happened yet trades a transient allocation on a 512 GB host for new risk. (MEDIUM, follow-up)
  • src/models/deepseek_v4.rs imports crate::models::bailing_moe::TokenIdField. Every other family that needs this helper declares its own copy (11 of them do), and this is the only text family importing an unrelated text family's config type. Left as is rather than churning the PR: reuse is defensible and duplicating an 11th copy is not obviously better. (LOW)
  • TECHNICAL_REPORTS/.keep-reports is present and no report exists for this PR yet. Not generated in this pass.

Notes On Faithfully Ported Reference Quirks

These are correct ports, documented in the module docs, and are called out here only so they are not mistaken for defects later: the overlap compressor's backshift applies WITHIN each ready batch, so every decode-completed ratio-4 window and the first window a chunked continuation completes takes the zero / -inf prefix instead of its real predecessor's feature half. During decode that means the ratio-4 compressor degenerates to a softmax over the second feature half alone. The reference _overlap_compress_kv behaves identically, and tiny_model_chunked_prefill_matches_single_pass scopes its parity claim honestly around it.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow (ModelType, detection arm plus test, LoadedModel via delegate_language_model!, model_metadata.rs row, TP fallback table, docs/supported-models.md; nothing orphaned)
  • Project conventions followed (load-time rejection of every allocation-sizing scalar, compress_ratios values and length, scoring_func, num_experts_per_tok, and every per-path quantization override, so no MLX C++ throw can cross the cxx bridge at first forward)
  • Existing modules reused where applicable (MultiLinear, SwitchLinear, RMSNorm, UnifiedLinear, UnifiedEmbedding, RotatingKVCache, ModelOwnedSequenceState, moe_weighted_sum, validate_expert_quantization_*)
  • No unintended structural changes (all shared-file edits are single-line registrations)
  • Tests pass (cargo clippy --lib --tests -- -D warnings exits 0 after the fix; cargo fmt --check clean on every V4 file; cargo test --lib models::deepseek_v4 26/26, models::detection 43/43, loaded_model 5/5 confirmed separately)
  • Real-checkpoint load and generation: still outstanding, as the PR body states

@inureyes

Copy link
Copy Markdown
Member Author

Real-checkpoint validation

Ran against the real DeepSeek-V4-Flash 4-bit checkpoint (43 layers, 33 shards, 2481 tensors, ~151 GB) on an M3 Ultra / 512 GB. The checkpoint was verified complete two independent ways before the run: every file matches the upstream declared byte count, and every shard is self-consistent against its own safetensors header (filesize == 8 + header_len + max(data_offsets)).

cargo test --test deepseek_v4_real_model --release --features metal,accelerate -- --ignored --nocapture

running 3 tests
[deepseek-v4] long-context prompt: 2234 tokens
[deepseek-v4] long-context answer: " The Pacific Ocean is the largest ocean on Earth. The Pacific"
test deepseek_v4_real_model_long_context_hits_sparse_and_compressed_paths ... ok
[deepseek-v4] prompt: "The capital of France is"
[deepseek-v4] greedy continuation (24 tokens): " Paris. The capital of France is Paris. The capital of France is Paris. ..."
test deepseek_v4_real_model_loads_and_generates_coherently ... ok
[deepseek-v4] 48-token decode: "\",\"answer\":\"The ocean is vast and mysterious.\",\"model\":\"gpt-4o-mini\", ..."
test deepseek_v4_real_model_decode_crosses_pooling_windows ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 71.93s

What each gate covers:

  • loads_and_generates_coherently exercises the full weight-load path (both tensor-name planes, the 641 per-module-path quantization overrides mixing mxfp4 group-32 experts with affine group-64 everything else) and a greedy prefill plus decode. The repetition in the continuation is ordinary greedy decoding on a base checkpoint, not a porting artifact.
  • decode_crosses_pooling_windows drives 48 decode steps so the PoolingCache remainder buffer fills and flushes across window boundaries in both the ratio-4 and ratio-128 layers, which is where the prompt-mode and decode-mode branches diverge.
  • long_context_hits_sparse_and_compressed_paths is the one that matters most: at 2234 tokens the pooled prefix exceeds index_topk, so SparseCompressedAttention takes the _sparse_pooled_attention branch with HiSA top-k selection rather than the dense concat fallback. Retrieving the right fact from deep in the prompt is the signal that the indexer selects real positions and the split softmax shares its log-normalizer correctly.

Note on layer composition: the checkpoint ships 44 compress_ratios entries for 43 layers. Following the reference __post_init__, the list truncates to the first 43, which makes the final layer ratio 4 (sparse) rather than the trailing 0 (local). A port that required len == num_hidden_layers would reject this checkpoint outright, and one that kept the last 43 entries would build the wrong attention class in every layer.

Five review findings on the DeepSeek-V4 port, four of them boundaries where untrusted checkpoint or config data reached MLX unchecked. An MLX C++ exception crossing the cxx bridge is an uncatchable std::terminate rather than a catchable Rust error, so each of these has to be a load-time Result in Rust and not a precondition MLX gets to assert on.

- MoEGate::from_weights now bounds the tid2eid table's VALUES to 0..n_routed_experts, not just its shape. Hash routing is the only path in the tree whose expert indices come from a checkpoint tensor instead of an argpartition over the score row, and MLX gathers only fold negative indices (offset_neg_idx in backend/cpu/indexing.cpp) without ever clamping, so an out-of-range expert id was an out-of-bounds read through take_along_axis and gather_qmm.
- The Biased routing arm now shape-checks e_score_correction_bias against [n_routed_experts], the one tensor in that constructor that lacked the check its siblings have. Any other length made MoEGate::forward's add throw at the first forward pass instead of failing the load.
- sanitize_weights Pass 5 now rejects a 2-D wo_a plane whose element count is zero or not a multiple of o_groups * o_lora_rank (computed in i64) before handing it to reshape. That pass runs before validate_weight_coverage, so the mismatch used to abort the process mid-load rather than return an error naming the tensor.
- ModelArgs::validate now bounds every architecture scalar above at i32::MAX as well as below at zero, adds index_block and index_keep to the checked set, and rejects a hidden_size * hc_mult product that does not fit i32. Every one of these scalars is cast as i32 on its way into MLX, and a usize past i32::MAX truncates silently to zero or to a negative dimension. Indexer::forward's hierarchical gate computes index_block * index_keep in i64 for the same reason: a wrapped product could pass the gate while nb == np / index_block is 0, driving kb to 0 and reaching argpartition(kth = -1).
- PoolingCache::update_and_fetch and Compressor::forward now return a borrow of the cache's pooled buffer instead of mlxcel_core::copy of it. mlxcel_core::copy is mlx::core::copy (mlx/ops.cpp:340), a real Copy primitive, so both branches materialised the whole Np * D buffer on every call, the no-op branch that dominates decode included (3 of every 4 steps at compress ratio 4, 127 of every 128 at ratio 128), with Np growing with context. The reference PoolingCache returns self.pooled directly. Call sites in deepseek_v4_attention.rs and deepseek_v4_indexer.rs take the borrow; the sparse arm relies on cache.pool and cache.idx_pool being disjoint field projections through the same &mut V4LayerCache.

Tests: hostile-config cases for index_block 0, index_keep 0, and scalars above i32::MAX; new load-rejection tests for an out-of-range and a negative tid2eid entry, a wrong-length e_score_correction_bias, and an indivisible 2-D wo_a plane, each with the honest tensor as its positive control.

Validated with cargo fmt, cargo clippy --lib --tests -- -D warnings, and cargo test --lib models::deepseek_v4 (29 passed, up from 26).

Refs #1455
MLX is lazy, so an unevaluated array keeps its inputs alive through its primitive until `eval` detaches it. On a sparse (compress ratio 4) DeepSeek-V4 layer the attention compressor's cache is fine: `V4Attention::forward` feeds its `pooled` buffer into the SDPA on every branch it can take, so evaluating the logits forces `pooled` and transitively the `copy(&buf_kv)` and the bounded `slice_update` chains behind it. The indexer compressor's cache is not. The only consumer of the indexer's pooled buffer is the top-k selection `Indexer::forward` returns, and the `AttnKind::Sparse` arm discards that selection on both the `np == 0` branch and the `np <= index_topk` short-context branch. Nothing else reads `idx_pool`.

So while the sparse selection path is not being taken, the indexer cache's `pooled` concat chain grew by one unevaluated node per completed window and its `buf_kv` / `buf_gate` `slice_update` chains grew by one node per decode step, none of them ever forced, each node pinning that step's normed hidden state plus its `wkv` / `wgate` projections. The sparse branch only fires past `index_topk * compress_ratio` tokens (512 * 4 = 2048 on the real config), so every sequence paid this over its first ~2048 tokens and a sequence that never got that long paid it for its whole life: roughly 190 KB per decode step across the real config's 20 sparse layers, released only when the sparse path finally fired or the sequence state was dropped, and then forced in one burst down a chain thousands of nodes deep.

`PoolingCache::eval_state` calls `mlxcel_core::eval` on each of `buf_kv`, `buf_gate`, `pooled` that is `Some`, modelled on `mlxcel_core::cache::KVCache::eval_state`, which plays the same role on the ordinary KV path (upstream mlx-lm evaluates `[c.state for c in cache]` after each step). `V4LayerCache::eval_state` forwards to `pool` and `idx_pool`; `local` is deliberately excluded because the rotating window is concatenated into the SDPA input on every layer of every step and is in the logits graph already.

The barrier runs in `DeepSeekV4Model::forward_with_caches` after the layer loop and before `hc_head`, not at the consumer. The pooled buffers depend only on the layer stack, so forcing them there forces the stack while leaving the `hc_head` / `norm` / `lm_head` chain unevaluated, the same trade `KVCache::eval_state` documents: the full `[B, L, vocab]` logits tensor and its peak allocation are not forced by this. A consumer-side eval would instead fire inside the layer loop, once per compressed layer, and could not run at all on the branches that drop the selection, which are exactly the branches that accumulate. `forward_with_caches` has one production caller, `forward_for_sequence`, which runs inside `ModelOwnedSequenceState::with_or_create_sequence_state`; that either removes the per-sequence state Vec from the map for the duration of the call or holds a `RefCell` mutable borrow of the internal state, so `caches` is exclusively borrowed and no aliased reader can observe a half-forced cache.

Tests: `pooling_cache_eval_state_is_safe_and_neutral_in_every_state` calls the barrier on a freshly constructed cache (all three buffers `None`), after a prompt-mode `accumulate_windows` that completes no window, after one that completes two, with `pooled` populated, and after a decode-mode accumulate, asserting the emitted rows and the pooled contents are unchanged and match an identically driven cache that is never forced. `tiny_model_cache_barrier_is_observationally_neutral` drives the tiny model through a 26-token prefill plus ten decode steps twice, forcing the caches again between steps on one run, and asserts identical last-step logits and identical cache offsets and remainders. `tiny_model_prefill_and_decode_produce_finite_logits` goes from three decode steps to ten so the barrier is exercised repeatedly.

Verified with `cargo fmt`, `cargo clippy --lib --tests -- -D warnings`, and `cargo test --lib models::deepseek_v4` (31 passed, 0 failed).

Refs #1455
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

Static analysis only. The real checkpoint under models/ was not loaded (four shards still downloading), so nothing here is backed by a real-model run.

Two commits land the fixes: db05a80c (four load-boundary guards plus the pooled-cache copy) and 233d4279 (the pooling-cache eval barrier). cargo fmt --check clean, cargo clippy --lib --tests -- -D warnings exit 0, cargo test --lib models::deepseek_v4 31 passed / 0 failed (26 before).

Fixed

HIGH, security. tid2eid values were never range checked. MoEGate::from_weights validated the table's shape but not its contents. At forward time those entries feed take_along_axis over a [B, L, n_routed_experts] score row and gather_qmm over the stacked [n_routed_experts, out, packed_in] expert planes. MLX gathers only fold negative indices (offset_neg_idx in mlx/backend/cpu/indexing.cpp) and never clamp, so an out-of-range expert id in a downloaded checkpoint was a straight out-of-bounds read. This is the only routing path in the tree whose expert indices come from a checkpoint tensor rather than an argpartition over the score row, so the in-range-by-construction argument that covers bailing_moe / afmoe / klear does not reach it. Now bounded to 0..n_routed_experts at load with one min_all / max_all pair per hash layer.

HIGH, performance. PoolingCache::update_and_fetch deep-copied the whole pooled buffer on every call. mlxcel_core::copy is mlx::core::copy (mlx/ops.cpp:340), a real Copy primitive, not a handle alias, so both branches materialised Np * D elements per call, including the n_new == 0 branch that dominates decode (3 of every 4 steps at compress ratio 4, 127 of every 128 at ratio 128). Np grows with context, so the copy traffic grew without bound: roughly 54 MB per decoded token at 8k context and 860 MB per decoded token at 128k across the real config's 40 compressed and sparse layers. The reference PoolingCache.update_and_fetch returns self.pooled directly. update_and_fetch and Compressor::forward now return a borrow of the cache's buffer; the sparse arm relies on cache.pool and cache.idx_pool being disjoint field projections through the same &mut V4LayerCache.

MEDIUM, performance. The indexer pooling cache accumulated an unevaluated MLX graph across decode steps. The only consumer of the indexer's pooled buffer is the top-k selection Indexer::forward returns, and the AttnKind::Sparse arm discards it on both the np == 0 and the np <= index_topk branches. Nothing else reads idx_pool, so while the sparse selection path is not being taken its pooled concat chain grew by one unevaluated node per completed window and its buf_kv / buf_gate slice_update chains grew by one per decode step, each node pinning that step's normed hidden state plus its wkv / wgate projections. The sparse branch only fires past index_topk * compress_ratio tokens (2048 on the real config), so every sequence paid this over its first ~2048 tokens and a shorter sequence paid it for its whole life: about 190 KB per decode step across 20 sparse layers, then forced in one burst down a chain thousands of nodes deep. PoolingCache::eval_state and V4LayerCache::eval_state now run after the layer loop and before hc_head, mirroring KVCache::eval_state, so the layer stack is forced but the [B, L, vocab] logits tensor is not.

MEDIUM, security. e_score_correction_bias had no shape check while both sibling tensors in the same constructor did. MoEGate::forward adds it straight onto a [B, L, n_routed_experts] score row, so any other length made MLX's add throw at the first forward pass instead of failing the load, and that throw is an uncatchable std::terminate, not a catchable Rust error. Now checked against [n_routed_experts].

MEDIUM, security. The 2-D wo_a reshape in sanitize_weights Pass 5 ran unguarded on checkpoint data. The element count comes from the checkpoint and the divisor from config.json. MLX's reshape asserts the -1 axis divides evenly, and that pass runs before validate_weight_coverage, so a mismatch aborted the process mid-load rather than returning an error naming the tensor. Now rejected when the size is zero or not a multiple of o_groups * o_lora_rank, computed in i64.

MEDIUM, security. ModelArgs::validate bounded every architecture scalar below but never above. Each one is cast as i32 on its way into MLX, and a usize past i32::MAX does not fail that cast: it truncates silently to zero or to a negative dimension that then reaches reshape / broadcast_to / zeros. index_block and index_keep were not validated at all despite gating the HiSA hierarchical path and dividing Np inside it. All scalars now capped at i32::MAX, index_block / index_keep added to the checked set, and hidden_size * hc_mult rejected when the product does not fit i32. Indexer::forward's hierarchical gate now computes index_block * index_keep in i64: a wrapped product could pass the gate while nb = np / index_block was 0, driving kb to 0 and reaching argpartition(kth = -1).

Reported, not fixed

MEDIUM, performance. sparse_pooled_attention promotes to float32 where the reference stays in the activation dtype. gathered is [B, L, index_topk, head_dim], which on the real config at a 2048-token prefill chunk is 537M elements: 1.07 GB in bf16, 2.15 GB in f32, with both live across the cast. local_scores goes from 0.57 GB to 1.14 GB and local_weights again the same. That is roughly a 2x multiplier on the largest intermediates in the model. The reference _sparse_pooled_attention runs the whole split softmax in the activation dtype. This looks deliberate (the doc comment says so, and 2b875ca4 tuned the sink dtype here), and changing it moves numerics, so it should be decided against the real-model run rather than in review.

LOW, performance. The local KV is duplicated to fill the rotating cache's value side. V4Attention::forward does let kv_values = mlxcel_core::copy(&kv); because K and V are the same tensor for a single shared KV head. The reference passes a zero-width mx.zeros((B, 1, L, 0)) placeholder instead, so it stores nothing on the V side. The port copies L * head_dim per layer per call and keeps a values buffer it never reads: about 96 MB of both during a 2048-token prefill chunk across 43 layers. Left alone because a zero-width value tensor interacts with this tree's RotatingKVCache quantization modes and that is not safe to change without the real-model run.

LOW, performance. Indexer::flat_select materialises [B, H, L, Np] f32 scores with no tiling, about 268 MB for a 2048-token prefill chunk at Np = 512, and it is the path taken for the entire first prefill chunk because hierarchical needs Np >= index_block * index_keep = 1024. The tiled hisa_select_batched bound does hold: cand is [B, min(512, L), 1024, 128] f32 per tile with an eval barrier between tiles. The flat fallback that runs first has no equivalent bound, but it matches the reference, so it is a shared property rather than a port defect.

LOW, security. RMSNorm weight shapes are never validated (attn_norm.weight, ffn_norm.weight, attn.q_norm.weight, attn.kv_norm.weight, model.norm.weight, compressor.norm.weight). validate_weight_coverage checks presence only, so a wrong-width norm weight reaches mx.fast.rms_norm and throws. This is a repo-wide pattern rather than something this PR introduced, so it belongs in a follow-up that covers every family at once.

Informational. Token ids are not bounded before take(tid2eid, input_ids, 0), the same exposure the embedding lookup already carries in every family. PoolingCache::pooled grows monotonically with context by design (the pooled KV is the long-term memory), reaching roughly 7 GB across all layers at the declared 1048576-token max_position_embeddings; that is architectural and matches the reference.

Checked and clear

Registration edits in mod.rs, detection.rs, loaded_model.rs, model_metadata.rs and the tensor-parallel fallback table are mechanical and complete. Quantization bounds meet docs/adding-models.md: the top-level pair, the mode string, and every one of the 641 per-path overrides are validated in ModelArgs::validate, and LimitedSwitchGlu runs both validate_expert_quantization_params and validate_expert_quantization_shapes rather than bypassing the shared loader's bound. PoolingCache::accumulate_windows slice arithmetic holds on every branch, including the usable == 0 and remainder-boundary cases. The topk_indices kth argument stays in range on all three selection paths. pool_visible_counts, align_local_mask and extend_mask are additive-f32 throughout and agree with the mask create_sliding_window_prefill_mask produces. RoPE frequency tables are precomputed per (head_dim, inverse) pair at load, and the prefill mask is built once outside the layer loop. The transpose of the HC fn plane and the MoE gate weight on every forward is not a real cost: MLX's Transpose shares the buffer and matmul consumes the transposed strides directly.

The implementation and security/performance review passes covered reference-math parity, gate contracts, sanitize, weight coverage, HiSA agreement, and the bounds checks they added, but several load-time shape checks and a couple of pure config helpers that predate those passes had no test naming them at all: `MoEGate::from_weights`'s router-weight and `tid2eid` shape checks, `V4Attention::from_weights`'s `attn_sink` shape check, `Compressor::from_weights`'s `ape` shape check, `sanitize_weights`'s rejection of a legacy per-expert plane missing one index (the same defect class `bailing_moe` documents: a checkpoint missing a late expert must not register a short stack the router can index past), `v4_rope_base_freqs`'s yarn-scaling field checks (missing `factor`, missing `original_max_position_embeddings`, a non-positive factor, a zero `original_max_position_embeddings`), `AttnKind::for_ratio`'s reject-unknown-ratio arm, and `ModelArgs::eos_token_ids`'s default-id fallback when `eos_token_id` is absent or an empty list.

Each new test follows the existing house pattern: a positive control with the honest tensor or config, then the corrupted case asserted to return `Err` naming the offending field. 8 new tests, all passing; the DeepSeek-V4 lib suite goes from 31 to 39.

Validation:
- cargo test --lib models::deepseek_v4 (39 passed)
- cargo clippy --lib --tests -- -D warnings (clean)
- cargo fmt --check (clean)

Refs #523, #1455
… a changelog entry

The `docs/supported-models.md` DeepSeek-V4 entry estimated the validation checkpoint at "~145 GB" before it had actually been fetched; the real `mlx-community/DeepSeek-V4-Flash-4bit` snapshot occupies ~151 GB on disk (147,952,784 KB, du), so both the doc entry and the matching comment in `tests/deepseek_v4_real_model.rs` now carry the observed figure instead of the pre-fetch estimate. The doc entry's validation sentence is also expanded to name what each of the three `#[ignore]`d real-checkpoint gates actually checks (a capital-of-France sanity decode, a pooling-window-crossing decode, and a >2100-token prompt into the HiSA sparse selection path) instead of pointing at the test file with no detail, matching the density of the surrounding entries. The "DeepSeek v1 / v2 / v3 / v3.2" summary line already closes with the explicit "DeepSeek V4 is NOT a fifth member of this implementation family" pointer added alongside the V4 entry, so no change was needed there.

This repository records every merged model-support PR in `CHANGELOG.md`; the DeepSeek-V4 port had no entry under `## [Unreleased]`. Added one under `### Added` following the existing bold-headline style, naming the architecture's distinguishing pieces (HyperConnections, the single shared KV head, per-layer compression kind selection, HiSA, hash-routed MoE), the validation checkpoint and gates, and the boundary defects review closed.

`docs/adding-models.md`'s Shared Function Policy section and its listed shared-helper files (`src/lib/mlxcel-core/src/layers.rs`, `src/lib/mlxcel-core/src/utils.rs`) were checked against the PR diff and are untouched by this port, so no usage-comment update is needed there. This repository carries no `docs/ko` tree (`mkdocs.ko.yml` points at a `docs/ko` directory that does not exist in this checkout), so there is no Korean translation to update either.

Refs #523, #1455
@inureyes

Copy link
Copy Markdown
Member Author

PR Finalization Complete

Summary

  • Tests: added 8 tests closing gaps the implementation and security/performance reviews did not target (they covered reference-math parity, gate contracts, sanitize, coverage, HiSA agreement, and the new bounds checks). New coverage: MoEGate::from_weights's router-weight and tid2eid shape checks, V4Attention::from_weights's attn_sink shape check, Compressor::from_weights's ape shape check, sanitize_weights's rejection of a legacy per-expert plane missing one index, v4_rope_base_freqs's yarn-scaling field checks (missing factor/original_max_position_embeddings, non-positive factor, zero orig), AttnKind::for_ratio's reject-unknown-ratio arm, and ModelArgs::eos_token_ids's default-fallback branch. DeepSeek-V4 lib suite: 31 -> 39, all passing.
  • Documentation: docs/supported-models.md's DeepSeek-V4 entry checked field-by-field against the implementation (HyperConnections/Sinkhorn params, attention shape, compress-ratio dispatch, HiSA defaults, MoE hash routing, quantization overrides) and confirmed accurate; the checkpoint size was corrected from the pre-fetch "~145 GB" estimate to the observed "~151 GB" (matched in tests/deepseek_v4_real_model.rs's doc comment), and the validation sentence now names what each of the three real-checkpoint gates actually checks. The "DeepSeek v1 / v2 / v3 / v3.2" summary line already closed with an explicit pointer to the V4 entry, so it needed no change. Added a CHANGELOG.md [Unreleased] entry, which this port had none of. docs/adding-models.md's shared-helper files are untouched by this PR, so no comment update was needed there; this repo carries no docs/ko tree, so no Korean translation exists to update.
  • Lint/Format: cargo fmt and cargo clippy --lib --tests -- -D warnings clean on all touched files.

Left alone (per scope)

  • Reference-math parity, gate contracts, sanitize/coverage correctness, HiSA agreement, and the review's bounds-check fixes: already covered, not re-reviewed.
  • The three #[ignore]d real-checkpoint tests: not re-run.
  • Everything under models/.

All checks passing. Ready for merge.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Aug 26, 2026
@inureyes
inureyes deleted the feature/issue-523-deepseek-v4-port branch October 6, 2026 12:12
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…lablup#1455)

* feat(models): port the DeepSeek-V4 backbone as a net-new architecture

Port references/mlx-vlm/mlx_vlm/models/deepseek_v4 faithfully instead of wrapping DeepSeekV3Model (the premise PR lablup#592 was closed over): HyperConnections with the Sinkhorn-normalised comb gates carry a rank-4 [B, L, hc_mult, D] state between blocks; per-layer compress_ratios select local (0), pooled-compressed (128), or HiSA sparse-compressed (4) attention over one shared 512-wide KV head in a 128-token rotating window; the Compressor pools ratio-sized windows with a learned ape and window softmax (overlap mode at ratio 4), RMS-norms, and Yarn-ropes them at compress_rope_theta with freq_scale = ratio; the Indexer scores its own pooled stream and returns index_topk rows for a split-softmax sparse attention sharing one log-normalizer with the per-head sinks; the MoE routes the first num_hash_layers layers by tid2eid token-id lookup (input_ids threads through every block), selects on bias-corrected scores while weighting from unbiased ones, and clamps both expert paths at swiglu_limit; wo_a is the grouped MultiLinear low-rank output projection.

Heterogeneous per-layer state (RotatingKVCache plus one or two PoolingCaches) rides in ModelOwnedSequenceState following the gemma3/afmoe pattern, with placeholder KVCaches from make_caches. Sanitization handles both the mlx-community tensor plane the real DeepSeek-V4-Flash-4bit ships and the legacy export plane the reference handles (hc_* renames, w1/w2/w3, per-expert stacking, uint8 view fixups), drops mtp.* tensors, casts tid2eid to int32, and reshapes 2-D wo_a planes; a strict coverage check then requires the tensor set to match the config exactly, so nothing loads by silent fallback. Config validation bounds every allocation-sizing scalar, the compress ratio set {0, 4, 128}, the scoring function, and the per-path quantization overrides (mxfp4/32 experts under an affine/64 top level).

Registered across ModelType, detection, LoadedModel via delegate_language_model!, model_metadata, and the tensor-parallel fallback table.

Refs lablup#523

* test(models): add DeepSeek-V4 reference-parity and component tests

Add 26 unit tests for the V4 port. The numeric fixtures replay the reference math (_hc_split_sinkhorn_ops, DeepseekV4RoPE yarn tables, _limited_swiglu, sqrtsoftplus, _simple/_overlap_compress_kv) in float64 outside MLX, so a port bug and a fixture bug cannot share a cause. Component coverage: Sinkhorn gate output, hc_expand, HyperHead collapse, yarn frequency correction, inf-prefix/negation/freq_scale table composition and forward-inverse rope identity, PoolingCache prompt/decode window emission and visibility counts, both compress functions, limited-SwiGLU clamping, the biased-selection/unbiased-weighting gate contract, hash routing via tid2eid, hostile config and per-path quantization override rejection with positive controls, legacy-plane sanitize remaps, wo_a reshape plus tid2eid int32 cast, strict weight-coverage rejection naming the offending tensor, a three-kind tiny end-to-end model (prefill, decode, cache topology), chunked-prefill parity, and a detection arm test.

The HiSA selection paths now take precomputed head weights so the hierarchical/flat agreement test can drive them with strictly positive tie-free inputs: relu'd indexer scores tie at exact 0.0 routinely, and argpartition tie-breaking across differently shaped calls is reference-inherited indeterminism, not a port defect. The chunked-parity test splits at a window boundary for the same reason: _overlap_compress_kv shifts the overlap half within each ready batch, so a ratio-4 window completed at a chunk boundary legitimately sees the zero/-inf prefix (now documented in the compress module).

Refs lablup#523

* docs(models): document DeepSeek-V4 and add the real-checkpoint smoke test

Add the deepseek_v4 entry to docs/supported-models.md in the surrounding house style, naming what is silently wrong if done the easy way (Sinkhorn iteration count and order, the non-interchangeable overlap compressor and its within-batch shift, inverse output RoPE, selection-vs-weighting gate contract, hash routing needing input_ids, per-path mxfp4/32 expert overrides under an affine/64 top level), and detach V4 from the v1/v2/v3/v3.2 implementation-family paragraph since it shares nothing structural with them.

Add tests/deepseek_v4_real_model.rs, ignore-gated on the ~145 GB local checkpoint: loading alone proves strict weight coverage (every tensor maps to a module path and vice versa), and two greedy generations exercise all three attention kinds, both gate routings, and decode-mode pooling across window boundaries with a factual-answer coherence gate.

Refs lablup#523

* fix(models): accept the real V4 config's duplicate quantization keys

The real DeepSeek-V4-Flash-4bit config.json ships BOTH `quantization` and `quantization_config` with identical content; a serde alias treats the pair as a duplicate field and rejects the whole config, which would have surfaced only after a full checkpoint load. Split them into two optional fields behind a precedence accessor (`quantization` wins), and add a unit test pinning the both-keys shape plus the 44-for-43 `compress_ratios` truncation the reference performs in `__post_init__`. Also add a non-ignored preflight in tests/deepseek_v4_real_model.rs that parses and validates the real config.json (skipping when the checkpoint is absent), asserting the layer count, truncated ratio tail, hash-layer count, the per-path mxfp4/32 expert override, and the eos id, so serde shape drift against the shipped config fails in seconds instead of after a 145 GB load.

Refs lablup#523

* refactor(models): pass activation-dtype sinks into the V4 sparse softmax

Mirror the reference exactly: _sparse_pooled_attention receives attn_sink already cast to the activation dtype, and the logaddexp against the f32 normalizer performs the promotion. Passing the raw f32 tensor was slightly more precise than the reference, which is still a parity deviation.

Refs lablup#523

* test(models): add a long-context V4 real-model gate for the sparse paths

The sparse split-softmax and HiSA selection only engage past index_topk * ratio prompt tokens (~2048), and the ratio-128 layers only pool past their first 128-token window, so the short smokes cannot reach either. Build a ~2200-token factual prompt, generate greedily, and gate on retrieving a fact from deep context.

Refs lablup#523

* chore: format the V4 real-model test

* fix(tests): use is_multiple_of in the V4 long-context prompt builder

`cargo clippy --lib --tests -- -D warnings` failed on this branch: the long-context real-model gate added in c4847cc builds its prompt with `if i % 8 == 0`, which trips `clippy::manual_is_multiple_of` and fails the whole `deepseek_v4_real_model` test target under `-D warnings`. The rest of the port already uses `is_multiple_of` (see `ModelArgs::validate`), so this brings the one remaining site in line.

Verified by reintroducing the old expression and confirming clippy rejects it, then restoring the fix and confirming `cargo clippy --lib --tests -- -D warnings` exits 0. `cargo fmt --check` is clean on every V4 file.

Refs lablup#523

* fix(models): bound DeepSeek-V4 gather indices, borrow pooled cache

Five review findings on the DeepSeek-V4 port, four of them boundaries where untrusted checkpoint or config data reached MLX unchecked. An MLX C++ exception crossing the cxx bridge is an uncatchable std::terminate rather than a catchable Rust error, so each of these has to be a load-time Result in Rust and not a precondition MLX gets to assert on.

- MoEGate::from_weights now bounds the tid2eid table's VALUES to 0..n_routed_experts, not just its shape. Hash routing is the only path in the tree whose expert indices come from a checkpoint tensor instead of an argpartition over the score row, and MLX gathers only fold negative indices (offset_neg_idx in backend/cpu/indexing.cpp) without ever clamping, so an out-of-range expert id was an out-of-bounds read through take_along_axis and gather_qmm.
- The Biased routing arm now shape-checks e_score_correction_bias against [n_routed_experts], the one tensor in that constructor that lacked the check its siblings have. Any other length made MoEGate::forward's add throw at the first forward pass instead of failing the load.
- sanitize_weights Pass 5 now rejects a 2-D wo_a plane whose element count is zero or not a multiple of o_groups * o_lora_rank (computed in i64) before handing it to reshape. That pass runs before validate_weight_coverage, so the mismatch used to abort the process mid-load rather than return an error naming the tensor.
- ModelArgs::validate now bounds every architecture scalar above at i32::MAX as well as below at zero, adds index_block and index_keep to the checked set, and rejects a hidden_size * hc_mult product that does not fit i32. Every one of these scalars is cast as i32 on its way into MLX, and a usize past i32::MAX truncates silently to zero or to a negative dimension. Indexer::forward's hierarchical gate computes index_block * index_keep in i64 for the same reason: a wrapped product could pass the gate while nb == np / index_block is 0, driving kb to 0 and reaching argpartition(kth = -1).
- PoolingCache::update_and_fetch and Compressor::forward now return a borrow of the cache's pooled buffer instead of mlxcel_core::copy of it. mlxcel_core::copy is mlx::core::copy (mlx/ops.cpp:340), a real Copy primitive, so both branches materialised the whole Np * D buffer on every call, the no-op branch that dominates decode included (3 of every 4 steps at compress ratio 4, 127 of every 128 at ratio 128), with Np growing with context. The reference PoolingCache returns self.pooled directly. Call sites in deepseek_v4_attention.rs and deepseek_v4_indexer.rs take the borrow; the sparse arm relies on cache.pool and cache.idx_pool being disjoint field projections through the same &mut V4LayerCache.

Tests: hostile-config cases for index_block 0, index_keep 0, and scalars above i32::MAX; new load-rejection tests for an out-of-range and a negative tid2eid entry, a wrong-length e_score_correction_bias, and an indivisible 2-D wo_a plane, each with the honest tensor as its positive control.

Validated with cargo fmt, cargo clippy --lib --tests -- -D warnings, and cargo test --lib models::deepseek_v4 (29 passed, up from 26).

Refs lablup#1455

* fix(models): eval DeepSeek-V4 pooling cache state after the layer loop

MLX is lazy, so an unevaluated array keeps its inputs alive through its primitive until `eval` detaches it. On a sparse (compress ratio 4) DeepSeek-V4 layer the attention compressor's cache is fine: `V4Attention::forward` feeds its `pooled` buffer into the SDPA on every branch it can take, so evaluating the logits forces `pooled` and transitively the `copy(&buf_kv)` and the bounded `slice_update` chains behind it. The indexer compressor's cache is not. The only consumer of the indexer's pooled buffer is the top-k selection `Indexer::forward` returns, and the `AttnKind::Sparse` arm discards that selection on both the `np == 0` branch and the `np <= index_topk` short-context branch. Nothing else reads `idx_pool`.

So while the sparse selection path is not being taken, the indexer cache's `pooled` concat chain grew by one unevaluated node per completed window and its `buf_kv` / `buf_gate` `slice_update` chains grew by one node per decode step, none of them ever forced, each node pinning that step's normed hidden state plus its `wkv` / `wgate` projections. The sparse branch only fires past `index_topk * compress_ratio` tokens (512 * 4 = 2048 on the real config), so every sequence paid this over its first ~2048 tokens and a sequence that never got that long paid it for its whole life: roughly 190 KB per decode step across the real config's 20 sparse layers, released only when the sparse path finally fired or the sequence state was dropped, and then forced in one burst down a chain thousands of nodes deep.

`PoolingCache::eval_state` calls `mlxcel_core::eval` on each of `buf_kv`, `buf_gate`, `pooled` that is `Some`, modelled on `mlxcel_core::cache::KVCache::eval_state`, which plays the same role on the ordinary KV path (upstream mlx-lm evaluates `[c.state for c in cache]` after each step). `V4LayerCache::eval_state` forwards to `pool` and `idx_pool`; `local` is deliberately excluded because the rotating window is concatenated into the SDPA input on every layer of every step and is in the logits graph already.

The barrier runs in `DeepSeekV4Model::forward_with_caches` after the layer loop and before `hc_head`, not at the consumer. The pooled buffers depend only on the layer stack, so forcing them there forces the stack while leaving the `hc_head` / `norm` / `lm_head` chain unevaluated, the same trade `KVCache::eval_state` documents: the full `[B, L, vocab]` logits tensor and its peak allocation are not forced by this. A consumer-side eval would instead fire inside the layer loop, once per compressed layer, and could not run at all on the branches that drop the selection, which are exactly the branches that accumulate. `forward_with_caches` has one production caller, `forward_for_sequence`, which runs inside `ModelOwnedSequenceState::with_or_create_sequence_state`; that either removes the per-sequence state Vec from the map for the duration of the call or holds a `RefCell` mutable borrow of the internal state, so `caches` is exclusively borrowed and no aliased reader can observe a half-forced cache.

Tests: `pooling_cache_eval_state_is_safe_and_neutral_in_every_state` calls the barrier on a freshly constructed cache (all three buffers `None`), after a prompt-mode `accumulate_windows` that completes no window, after one that completes two, with `pooled` populated, and after a decode-mode accumulate, asserting the emitted rows and the pooled contents are unchanged and match an identically driven cache that is never forced. `tiny_model_cache_barrier_is_observationally_neutral` drives the tiny model through a 26-token prefill plus ten decode steps twice, forcing the caches again between steps on one run, and asserts identical last-step logits and identical cache offsets and remainders. `tiny_model_prefill_and_decode_produce_finite_logits` goes from three decode steps to ten so the barrier is exercised repeatedly.

Verified with `cargo fmt`, `cargo clippy --lib --tests -- -D warnings`, and `cargo test --lib models::deepseek_v4` (31 passed, 0 failed).

Refs lablup#1455

* test(models): cover DeepSeek-V4 shape-check and default-fallback paths

The implementation and security/performance review passes covered reference-math parity, gate contracts, sanitize, weight coverage, HiSA agreement, and the bounds checks they added, but several load-time shape checks and a couple of pure config helpers that predate those passes had no test naming them at all: `MoEGate::from_weights`'s router-weight and `tid2eid` shape checks, `V4Attention::from_weights`'s `attn_sink` shape check, `Compressor::from_weights`'s `ape` shape check, `sanitize_weights`'s rejection of a legacy per-expert plane missing one index (the same defect class `bailing_moe` documents: a checkpoint missing a late expert must not register a short stack the router can index past), `v4_rope_base_freqs`'s yarn-scaling field checks (missing `factor`, missing `original_max_position_embeddings`, a non-positive factor, a zero `original_max_position_embeddings`), `AttnKind::for_ratio`'s reject-unknown-ratio arm, and `ModelArgs::eos_token_ids`'s default-id fallback when `eos_token_id` is absent or an empty list.

Each new test follows the existing house pattern: a positive control with the honest tensor or config, then the corrupted case asserted to return `Err` naming the offending field. 8 new tests, all passing; the DeepSeek-V4 lib suite goes from 31 to 39.

Validation:
- cargo test --lib models::deepseek_v4 (39 passed)
- cargo clippy --lib --tests -- -D warnings (clean)
- cargo fmt --check (clean)

Refs lablup#523, lablup#1455

* docs(models): record the observed DeepSeek-V4 checkpoint size and add a changelog entry

The `docs/supported-models.md` DeepSeek-V4 entry estimated the validation checkpoint at "~145 GB" before it had actually been fetched; the real `mlx-community/DeepSeek-V4-Flash-4bit` snapshot occupies ~151 GB on disk (147,952,784 KB, du), so both the doc entry and the matching comment in `tests/deepseek_v4_real_model.rs` now carry the observed figure instead of the pre-fetch estimate. The doc entry's validation sentence is also expanded to name what each of the three `#[ignore]`d real-checkpoint gates actually checks (a capital-of-France sanity decode, a pooling-window-crossing decode, and a >2100-token prompt into the HiSA sparse selection path) instead of pointing at the test file with no detail, matching the density of the surrounding entries. The "DeepSeek v1 / v2 / v3 / v3.2" summary line already closes with the explicit "DeepSeek V4 is NOT a fifth member of this implementation family" pointer added alongside the V4 entry, so no change was needed there.

This repository records every merged model-support PR in `CHANGELOG.md`; the DeepSeek-V4 port had no entry under `## [Unreleased]`. Added one under `### Added` following the existing bold-headline style, naming the architecture's distinguishing pieces (HyperConnections, the single shared KV head, per-layer compression kind selection, HiSA, hash-routed MoE), the validation checkpoint and gates, and the boundary defects review closed.

`docs/adding-models.md`'s Shared Function Policy section and its listed shared-helper files (`src/lib/mlxcel-core/src/layers.rs`, `src/lib/mlxcel-core/src/utils.rs`) were checked against the PR diff and are untouched by this port, so no usage-comment update is needed there. This repository carries no `docs/ko` tree (`mkdocs.ko.yml` points at a `docs/ko` directory that does not exist in this checkout), so there is no Korean translation to update either.

Refs lablup#523, lablup#1455

* docs: add technical report for PR lablup#1455
@inureyes inureyes added this to the 0.7 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata 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): port DeepSeek-V4 (MLA + group-limited MoE backbone)

1 participant