Repository navigation
Conversation
Register a `deepseek_v4` text model that reuses the DeepSeek-V3 backbone: MLA attention, group-limited sigmoid-routed MoE, the unclamped shared-expert DenseMLP, and V3's multi-token-prediction layer handling. `DeepSeekV4Model` is a thin wrapper over `DeepSeekV3Model`; `DeepSeekV4Config` is parsed independently and mapped onto the V3 config via `to_dsv3_config`, mirroring the existing `glm_moe_dsa` wrapper. Config defaults track the mlx-vlm `deepseek_v4` reference. Scope is the backbone only. The two V4-specific features, HiSA hierarchical sparse attention and the shared-expert SwiGLU `swiglu_limit` clamp, are tracked as separate follow-up issues; their config fields are parsed for forward-compatibility but not applied by this port. Wiring: `ModelType::DeepSeekV4` plus the `deepseek_v4` detection arm, the `LoadedModel` variant and delegation, the config-backed metadata entry, the tensor-parallel fallback arch string, `ALL_MODEL_TYPES`, `metadata()`, and a `docs/supported-models.md` row. Tests: `deepseek_v4_tests` pin the config defaults and the V3 mapping; `tests/deepseek_v4_parity.rs` asserts the config maps to reference-derived V3 values and that the V4 backbone produces bit-identical logits to DeepSeek-V3 on shared synthetic weights.
Member
Author
|
Closing without merging, per maintainer decision. This PR ported DeepSeek-V4 as a thin wrapper over DeepSeek-V3. Investigation against the in-tree reference (references/mlx-vlm/mlx_vlm/models/deepseek_v4/) and the real DeepSeek-V4-Flash checkpoint showed the real deepseek_v4 architecture is genuinely novel (HyperConnections, pooled-KV Compressor, HiSA Indexer, hash-routed MoE with sqrtsoftplus, MultiLinear output projection), not a V3 variant, so a V3 wrapper cannot load or run a real V4 checkpoint. Issue #523 is re-scoped to a faithful port of the real architecture. This PR's diff is preserved here for reference. |
5 tasks done
inureyes
added a commit
that referenced
this pull request
Aug 27, 2026
* 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 #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 * 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 #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 #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 #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 #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 #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 #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 #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 #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 #523, #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 #523, #1455 * docs: add technical report for PR #1455
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds DeepSeek-V4 support by porting the backbone only.
DeepSeekV4Modelreuses the DeepSeek-V3 stack (MLA attention, group-limited sigmoid-routed MoE, unclamped shared-expertDenseMLP, and V3's multi-token-prediction layer handling) as a thin wrapper:DeepSeekV4Configis parsed independently and mapped ontoDeepSeekV3Configviato_dsv3_config, mirroring the existingglm_moe_dsawrapper over DeepSeek V3.2. Config defaults track the mlx-vlmdeepseek_v4reference.A
deepseek_v4checkpoint previously errored with "Unsupported model type"; it now detects, loads, and runs on the V3-equivalent backbone.Scope
Backbone only, exactly as the issue directs. The two V4-specific features are deferred to separate follow-up issues and are intentionally not implemented here:
swiglu_limitclampTheir config fields (
head_dim,swiglu_limit,num_nextn_predict_layers) are parsed for forward-compatibility but not applied by the backbone.What changed
src/models/deepseek_v4.rs(new):DeepSeekV4Config+DeepSeekV4Config::to_dsv3_config+DeepSeekV4Model(wrapsDeepSeekV3Model).src/models/deepseek_v4_tests.rs(new): config default and V3-mapping unit tests.tests/deepseek_v4_parity.rs(new): reference-config parity + a synthetic forward-equivalence proof that the V4 backbone is bit-identical to DeepSeek-V3.ModelType::DeepSeekV4and thedeepseek_v4detection.rsarm;LoadedModel::DeepSeekV4+ delegation;model_metadata.rsconfig-backed entry;tensor_parallel/inference.rsfallback arch string;ALL_MODEL_TYPES,metadata(), and theall_variants!registry list inmod.rs.docs/supported-models.md: DeepSeek-V4 backbone row.Test plan
cargo fmtcargo check --lib --testscargo clippy --lib --tests -- -D warningscargo test --lib deepseek_v4(5 passed)cargo test --test deepseek_v4_parity(2 passed, incl. forward-equivalence vs DeepSeek-V3)cargo test --lib -- models::detection metadata_tests model_metadata(registry completeness, 19 passed)deepseek_v4export yet)Closes #523