Repository navigation
feat(models): add DeepSeek-V4.1 text decoder (deepseek_v41) - #3603
Merged
Merged
Conversation
Add the deepseek_v41 family, covering DeepSeek-V4.1-Flash. V4.1 is not a config variant of V4: its non-overlapping compressor with pending rows, decoupled cross-layer indexer, candidate-block selection and n-gram engram memory are all new modules. Only the hyper-connection coefficient math, the limited SwiGLU and the MoE expert plane loading are reused from deepseek_v4. The model owns its heterogeneous per-layer state (window, compressed KV, index keys, open pooling rows and the engram token history) through ModelOwnedSequenceState, detects both the nested `deepseek_v41` VLM config and `deepseek_v41_text`, and loads three checkpoint key layouts (native, mlx-lm `model.*`, and mlx-vlm `language_model.*`). `MLXCEL_ENGRAM_OFFLOAD=1` reads only requested engram rows from the safetensors shard instead of making the ~384M-row tables resident. Unit tests cover the compressor chunked-vs-one-shot carry, published `_shared_reads` resolution, newest-block candidate selection, FP8/FP4 fake-quant round trips, three-layout sanitize equivalence, engram hash determinism against an independent integer implementation, the engram on/off residual difference, token-mask gating, short prompts producing no compressed rows, and both detection paths. Refs #2386
The reference contract makes a negative `index_topk` mean "no sparse selection", so the layer attends its window only. The clamp to at least one selection turned -1 into a single compressed pick; return an empty width instead.
The V4.1 attention applied `fast_rope_with_freqs` directly to `[B, L, H, D]` query and output tensors. MLX fast RoPE rotates along the second-to-last axis (the sequence axis), so this rotated along the head axis: head `h` of every token took the angle of position `start_pos + h` and no token used its own position. The reference `_apply_rope` transposes to `[B, H, L, D]` first. `V41Rope::apply` now does the same whenever its input is rank four, and casts the rotated lanes to f32 and back as the reference does. KV, latent and index-key tensors are rank three and already rotated along the token axis. The engram bucket offsets restarted at zero for every n-gram size, so the 3-gram and 4-gram hash columns folded back onto the 2-gram range and looked up the wrong table rows. The reference flattens a layer's primes and takes `cumsum([0, *sizes[:-1]])`, one disjoint range per (n-gram, head); the offsets are now that global prefix sum. The engram hash test used the same per-n-gram offsets in its independent reimplementation, so it could not catch the fold. It now uses the reference global offsets, and the committed golden ids are regenerated. New rope tests pin the token-axis rotation against identical-head inputs, the compressed-group `scale = ratio` position, and the forward/inverse round trip. Validated with `cargo test --lib models::deepseek_v41` (42 passed), `models::detection` (109) and `models::deepseek_v4` (92), plus `cargo check --lib --tests`, `cargo clippy --lib --tests -- -D warnings` and `cargo fmt --all -- --check`. The engram multipliers remain a deterministic SplitMix64 stream rather than NumPy's PCG64, so engram row parity still needs the real checkpoint or a shipped multiplier set.
The engram n-gram multipliers came from a SplitMix64 stream seeded with 10007 * layer_id, while the mlx-vlm reference draws them from numpy.random.default_rng(10007 * layer_id). Different multipliers make every hashed row lookup diverge from the reference on a real checkpoint, so the issue's golden-id parity criterion could not hold.
Add src/models/deepseek_v41_numpy_rng.rs, a bit-exact port of the NumPy 2.0 machinery the reference touches: SeedSequence with the four-word 32-bit pool, generate_state(4, uint64), the PCG64 XSL RR 128/64 engine, and the Lemire bounded-integer draw used by Generator.integers. hash_multipliers now seeds one generator per layer and reproduces compute_hash_multipliers, including the odd value * 2 + 1 result and the bound derived from the compressed vocab size. The engram call site passes engram_compressed_vocab_size, matching the reference, instead of the raw engram_vocab_size.
The committed engram hash-id goldens were regenerated from an independent Python script that takes the NumPy multipliers and applies the reference id hashing, so the test checks reference parity rather than freezing this implementation's output. The RNG module carries its own goldens for SeedSequence state, raw PCG64 output, and the final multipliers at both published compressed vocab sizes.
The offloaded engram table loader now tries the native singular {prefix}.scale alias when {prefix}.scales is absent, mirroring the reference's removesuffix("s") lookup, so a pack using native names is no longer mis-read as unquantized. A new test covers the singular alias.
The row-offloaded engram path parses a safetensors header from an untrusted checkpoint and seeks into the shard by byte offset, but trusted every header field: shape entries were cast with `as i32` (non-integers became 0, oversized and negative dims passed through), the row-width and offset math was unchecked, data_offsets were never checked against the file, and scale/bias planes were read over the weight's row range without covering it. A malformed shard could panic, size a huge allocation, seek outside the file, or pass a negative dimension to the tensor constructor. Validate dtype, shape (positive, integer, fits i32), data_offsets arity/order/extent, and that each tensor ends inside the file, using checked arithmetic throughout. Require the scale and bias planes to cover the weight's rows and reject a shard name that escapes the model directory. Validate at load that each table holds the hash-id range (sum of the per-bucket primes), clamp the gather defensively, and guard the wo_a split and the prime search. The gather now opens each plane once and reads all rows into one buffer instead of opening per row and concatenating per row. Verified with cargo test --lib models::deepseek_v41 (59 passed), cargo check --lib --tests, cargo clippy --lib --tests -- -D warnings, and cargo fmt --all -- --check. Refs #2386
…idate `candidate_source_layer_id` only had an upper bound, so a value below the -1 "no candidate source" sentinel was silently accepted. Reject it. Make the `compress_ratios` lookups in `validate` use `get` so calling it on an un-normalized, short table returns an error instead of panicking with an index-out-of-bounds. Verified with cargo test --lib models::deepseek_v41 (61 passed), cargo clippy --lib --tests -- -D warnings, and cargo fmt --all -- --check. Refs #2386
The three-layout sanitize test only compared the key set and tensor shapes, so a layout that rewrote a value would still normalize "equivalently". Compare the arrays themselves, and give the canonical fixture's stacked expert planes distinct per-expert values so the value comparison is not vacuous. Validation: cargo test --lib models::deepseek_v41 (61 passed), cargo fmt --all -- --check, cargo clippy --lib --tests -- -D warnings. Refs #2386
inureyes
marked this pull request as ready for review
December 1, 2026 08:58
inureyes
added a commit
that referenced
this pull request
Dec 1, 2026
## Problem `main` at `b468c9628` fails two of the cheap consistency gates that every PR runs: - `make verify-env-var-docs`: `MLXCEL_ENGRAM_OFFLOAD`, read in `src/models/deepseek_v41.rs:137`, is neither documented on `docs/environment-variables.md` nor allowlisted. Introduced by #3603. - `make verify-used-by`: `create_causal_mask_with_window_full` (`src/lib/mlxcel-core/src/utils.rs`) has an unaccounted caller, `src/audio/lfm3_audio/encoder.rs`. Introduced by #3610. Both are documentation-side omissions; the code is correct. Either one alone would fail the contract gate of any PR that runs them, so every in-flight PR inherits a red gate it did not cause. ## Change - Document `MLXCEL_ENGRAM_OFFLOAD` next to `MLXCEL_PLE_IO` and `MLXCEL_PLE_CACHE_BYTES`, the existing entries for external n-gram table handling. It is an operator-facing load switch, not an internal diagnostic, so documenting it is the right fix rather than allowlisting it. - Name the LFM3-Audio encoder in the `Used by:` roster of `create_causal_mask_with_window_full`. ## Verification ``` make verify-env-var-docs # PASS make verify-used-by # PASS ``` Both were confirmed failing on a pristine `origin/main` worktree before the change, and pass after it. No Rust behavior changes.
26 tasks
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 the
deepseek_v41text decoder family (DeepSeek-V4.1-Flash), a new architecture rather than a config variant of V4. Its non-overlapping compressor with pending rows, decoupled cross-layer indexer with candidate-block selection, and n-gram engram memory are new modules; only the hyper-connection coefficient math, limited SwiGLU and expert-plane loading are shared withdeepseek_v4. Ported from mlx-lm'sdeepseek_v41(attention/compressor/indexer) and mlx-vlm'sdeepseek_v41(engram, since mlx-lm rejectsengram_layer_ids).What changed
src/models/deepseek_v41*.rsmodules: model/config, block/cache, compressor, indexer, attention, MoE, engram hash+apply, row-offloaded engram table, sanitize, fake-quant, rope, a NumPy-compatible PRNG, and tests beside each.ModelType::DeepSeekV41, detected from top-leveldeepseek_v41(nestedtext_configmerged) anddeepseek_v41_text, registered in the metadata macro, loader dispatch,mlxcel archand the memory estimator.wo_asplit, expert stacking), mlx-lmmodel.*/lm_head.*, and mlx-vlmlanguage_model.*with vision/MTP dropped.[B, H, L, D]first); engram bucket offsets use the reference's global cumulative prime ranges.SeedSequence+ PCG64 + Lemire bounded draw, so hashed row ids matchnp.random.default_rng(10007 * layer_id)exactly; golden vectors from numpy 2.0.2 are pinned in tests. The offloaded table also accepts the native singular.scalealias.data_offsetsextent checks against the file length, scale/bias row-count agreement, checked arithmetic, shard path traversal rejection, and load-time validation that each table holds the hash-id range.compress_ratiosand candidate-layer ids are validated, and the engram prime search avoids i64 overflow.MLXCEL_ENGRAM_OFFLOAD=1reads only requested engram rows from the safetensors shard; the resident path stays the default.docs/supported-models.mdgains the V4.1 row, including the memory requirement (smallest MLX pack ~239 GB, so >=256 GB unified memory, or the offloaded engram path plus a reduced-expert pack).Tests
cargo test --lib models::deepseek_v41(61 passed)cargo test --lib models::detection(109 passed),models::deepseek_v4(111 passed),models::registry(22 passed),models::metadata_tests(4 passed)cargo clippy --lib --tests -- -D warningscargo fmt --all -- --checkpython3 scripts/ci/check_cross_repo_refs.pyandpython3 scripts/ci/check_used_by.pyAccepted coverage: compressor chunked-equals-one-shot pending carry,
_shared_readsfor the published layer lists, newest-block candidate retention, fake-quant round trips against hand-computed grids, value-level equality across the three sanitize layouts, engram golden hash ids against an independent integer implementation plus engram on/off residual difference, short prompt emits no compressed rows, and both detection forms.Not validated
No real-checkpoint validation was possible: the smallest MLX pack,
mlx-community/DeepSeek-V4.1-Flash-MLX-2bit, is not in the local store and was not downloaded (~239 GB). Specifically not run:mlxcel archlisting on a real pack;mlx_vlm.generate --temp 0, including a >4096-token prompt exercising compression, candidate blocks and cross-layer sharing;mlxcel-serversmoke test on the real pack.Required to validate: a host with at least 256 GB of unified memory holding that pack (or the offloaded engram path with a reduced-expert pack such as
rapid-mlx/DeepSeek-V4.1-Flash-REAP-2bit-MLX). Engram multipliers now match NumPy bit-exactly; ids still depend on the shippedengram_token_map.jsonmatching the config, and derivation fromtokenizer.jsonis approximate.Closes #2386