Repository navigation
feat(models): port DeepSeek-V4 as a net-new architecture (#523) - #1455
Conversation
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
`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
Implementation Review SummaryIntent
Findings Addressed
Reference-Parity VerificationThe reference math was re-derived from
Real-Checkpoint PredictionsReal load and generation have not been run yet, so the load path was exercised statically against
Remaining Items
Notes On Faithfully Ported Reference QuirksThese 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 / Verification
|
Real-checkpoint validationRan against the real What each gate covers:
Note on layer composition: the checkpoint ships 44 |
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
Security and performance reviewStatic analysis only. The real checkpoint under Two commits land the fixes: FixedHIGH, security. HIGH, performance. 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 MEDIUM, security. MEDIUM, security. The 2-D MEDIUM, security. Reported, not fixedMEDIUM, performance. LOW, performance. The local KV is duplicated to fill the rotating cache's value side. LOW, performance. LOW, security. RMSNorm weight shapes are never validated ( Informational. Token ids are not bounded before Checked and clearRegistration edits in |
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
PR Finalization CompleteSummary
Left alone (per scope)
All checks passing. Ready for merge. |
…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
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 withsqrtsoftplusgating, 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 duplicatequantization/quantization_configkeys and its 44-for-43compress_ratioslist), 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 theLanguageModelimpl.src/models/deepseek_v4_hyper.rs: HyperConnection / HyperHead /hc_expand, the pure-ops Sinkhorn path in float32 (softmax + eps, initial column normalisation, thenhc_sinkhorn_iters - 1row/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, andfreq_scaledivision for pooled positions.src/models/deepseek_v4_compress.rs:PoolingCache(prompt and decode branches, remainder buffer) plus theCompressorwith 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 HiSAIndexerwith 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 threecompress_ratioskinds (v4_attention_factorysemantics), single shared KV head, weightless Q RMSNorm, per-head sinks, inverse output RoPE, groupedwo_aMultiLinear +wo_b, and the split-softmax_sparse_pooled_attentionsharing one log-normalizer with the sinks.src/models/deepseek_v4_moe.rs:tid2eidhash routing for the firstnum_hash_layerslayers (indices from token ids, weights from logits,input_idsthreaded through every block), selection on bias-corrected scores with weights gathered from unbiased ones,sqrtsoftplusscoring in float32, and the limited SwiGLU clamp in both routed and shared experts; routed experts load through the sharedswitch_layers::SwitchLinearwith 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 withhc_*renames,w1/w2/w3, per-expert stacking, uint8view(uint32)fixups),mtp.*and beyond-layer drops,tid2eidint32 cast, 2-Dwo_areshape, 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.ModelType::DeepSeekV4insrc/models/mod.rs,detection.rsarm,LoadedModelvariant viadelegate_language_model!,src/model_metadata.rsconfig-backed row, tensor-parallel fallback table entry.docs/supported-models.md: house-styledeepseek_v4entry; 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.src/models/deepseek_v4_tests.rswith float64 fixture replays of the reference math, a detection test, andtests/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
Resultrather than an uncatchable abort at first forward, and each is covered by a test.tid2eidcontents 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 anargpartitionover the score row, so the in-range-by-construction argument that coversbailing_moe/afmoe/kleardoes not reach it. Those indices feedtake_along_axisandgather_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_fetchdeep-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.eval_stateafter the layer loop mirrorsKVCache::eval_state.e_score_correction_biashad no shape check, the 2-Dwo_areshape ran unguarded on checkpoint data, architecture scalars were bounded below but not above, andindex_block/index_keepwere unvalidated while being multiplied ini32.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 viatid2eid, 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::detection43/43 including the new arm;models::switch_layers23/23;loaded_model5/5.cargo clippy --lib --tests -- -D warnings: exit 0.cargo fmt --check: clean.model.safetensors.index.json, zero missing and zero unknown after ratio truncation. All 641 quantized planes satisfypacked_in * 32 == bits * num_groups * group_size.#[ignore]gates pass againstmlx-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.The long-context gate is the load-bearing one: at 2234 tokens a ratio-4 layer's pooled count passes
index_topk(512), soSparseCompressedAttentiontakes 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)
_hc_sinkhorn_collapse_kernel); this port implements the pure-ops correctness baseline the reference itself uses off-Metal.num_nextn_predict_layers;mtp.*tensors are dropped at load).shard()), VLM wrapping, and a fused-MoE decode kernel with a clamp stage (MLXCEL_FUSED_MOEstays unfused for this family).forward_last_logitsoverride, 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_attentionpromotes to f32 where the reference stays in the activation dtype, roughly 2x on the largest intermediates. Left because changing it moves numerics.swiglu_limitclamp) were filed under the old, rejected V3-wrapper scope; this port subsumes both (HiSA indeepseek_v4_indexer.rs, the clamp indeepseek_v4_moe.rs). Left open for a human to close.Closes #523