Skip to content

Add DeepSeek-V2 model - #379

Merged
davidkoski merged 3 commits into
ml-explore:mainfrom
GoodOlClint:pr/deepseek-v2
Jul 23, 2026
Merged

davidkoski merged 3 commits into
ml-explore:mainfrom
GoodOlClint:pr/deepseek-v2

Conversation

@GoodOlClint

Copy link
Copy Markdown
Contributor

Proposed changes

Adds the DeepSeek-V2 architecture (model_type: "deepseek_v2") to MLXLLM — a port of mlx-lm's deepseek_v2.py. Covers DeepSeek-V2 / V2-Lite, which had no Swift implementation.

It reuses the in-tree DeepSeek-V3 MLA machinery (q_a/q_b + kv_a_proj_with_mqa/kv_b low-rank compression, qk nope/rope split, the shared initializeRope YaRN path) and SwitchGLU MoE with shared experts.

It differs from V3 only in the router (DeepseekV2MoEGate):

  • plain softmax scoring (no sigmoid + e_score_correction_bias),
  • optional group_limited_greedy group masking by each group's max score (vs V3's top-2-per-group sum),
  • an unconditional routed_scaling_factor.

Dense layers below first_k_dense_replace use the standard MLP. sanitize() stacks per-expert gate/up/down projections (weight/scales/biases) into switch_mlp.

Tests (DeepseekV2Tests, no model download): forward-pass logit shape; a deterministic group-limited-greedy routing test (synthetic gate weights → the winning group confines top-k); and sanitize() expert-stacking. Verified via xcodebuild test ... -only-testing:MLXLMTests/DeepseekV2Tests → 3 tests, 0 failures, TEST SUCCEEDED.

Note: validation is structural/unit-level (shape + routing + weight-remap); end-to-end numerical parity against a downloaded DeepSeek-V2 checkpoint has not been run.

Checklist

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

@GoodOlClint

Copy link
Copy Markdown
Contributor Author

End-to-end validation (real weights) — caught and fixed a load bug.

Loading mlx-community/DeepSeek-V2-Lite-Chat-4bit-mlx initially failed: V2-Lite sets q_lora_rank: null (direct q_proj, no low-rank q compression), but the config defaulted a null/absent value to 1536, taking the q_a/q_b LoRA path and mismatching the checkpoint's q_proj. Fixed by making qLoraRank optional (nil ⇒ q_proj); added a regression test.

After the fix, forward-pass parity on a fixed token sequence [1..8] vs the Python mlx_lm reference:

argmax top5(last)
Python mlx_lm [185,1,4,5,6,826,4698,575] [575,2,185,4,746]
this PR (Swift) [185,1,4,5,6,826,4698,575] [575,2,185,4,746]

Byte-exact match (MLA + YaRN + group-routed MoE + quantized loading).

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, but take a look at the question on the double KVCache update. DeepseekV3 would need the same fix, assuming this is an issue.

GoodOlClint and others added 3 commits July 22, 2026 15:27
Port of mlx-lm's deepseek_v2.py. Reuses the in-tree DeepSeek-V3 MLA
machinery (q_a/q_b + kv_a_with_mqa/kv_b compression, qk nope/rope split,
shared initializeRope YaRN path) and SwitchGLU MoE with shared experts.

Differs from V3 in the router (DeepseekV2MoEGate): plain softmax scoring
(no sigmoid + e_score_correction_bias), optional group_limited_greedy
group masking by per-group max (vs V3's top-2-group-sum), and an
unconditional routed_scaling_factor. Dense layers below first_k_dense_replace
use the standard MLP. sanitize() stacks per-expert gate/up/down projections
into switch_mlp. Registered as "deepseek_v2".

Tests (DeepseekV2Tests, no model download): forward-pass logits shape,
deterministic group-limited-greedy routing (winning group confines top-k),
and sanitize() expert-stacking.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
DeepSeek-V2-Lite sets `q_lora_rank: null` — direct q_proj with no low-rank
q compression — while full DeepSeek-V2 sets 1536. The config previously
defaulted a null/absent value to 1536, which built the q_a/q_b LoRA path and
failed to load V2-Lite checkpoints (q_proj weight present, q_a_proj/q_b_proj
expected). Make qLoraRank `Int?`; nil ⇒ q_proj. Caught by end-to-end load of
mlx-community/DeepSeek-V2-Lite-Chat-4bit-mlx.

Adds a regression test (null → nil, 1536 → 1536) and switches the test config
to the realistic null form.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The attention path called `cache.update(...)` explicitly and then passed the
resulting keys/values to `attentionWithCacheUpdate`, which performs the cache
update itself. The second update appended the already-returned history back into
the cache, so a prompt of L tokens left the cache at 2L and every subsequent
token attended over duplicated keys.

Drop the explicit update and let `attentionWithCacheUpdate` own the single one,
matching Llama/Qwen3/Cohere and the Python reference. This also routes the
quantized-cache path correctly, which the manual update bypassed.

The new test pins cache growth: a 5-token forward pass must leave every layer's
cache at offset 5. Before this change it reported 10.

Also fix the `topk_method` default spelling ("gready" -> "greedy"), carried over
from the Python port. It is cosmetic: the only comparison is against
"group_limited_greedy", and real configs set the key explicitly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New model looks good, thank you!

davidkoski pushed a commit that referenced this pull request Jul 22, 2026
…ion call (#457)

Two bugs on the cached path, so DeepSeek-V3 could not generate.

1. `kvHeads` was declared `[Int] = []` and never assigned. `newCache` derives the
   layer count from `kvHeads.count`, so it returned an empty array, and the first
   `cache?[i]` in the layer loop trapped with "Index out of range". Any generation
   crashed; only a `cache: nil` forward pass worked. Populate it the way the other
   models do: one entry per layer.

2. Attention called `cache.update(...)` explicitly and then passed the resulting
   keys/values to `attentionWithCacheUpdate`, which performs the update itself.
   The second update appended the already-returned history back into the cache, so
   a prompt of L tokens left the cache at 2L and every subsequent token attended
   over duplicated keys. Drop the explicit update and let the helper own the single
   one, matching Llama/Qwen3/Cohere and the Python reference. This also routes the
   quantized-cache path correctly, which the manual update bypassed.

Adds DeepseekV3Tests with a cache-growth regression test: a 5-token forward pass
must leave every layer's cache at offset 5. With (1) unfixed the test crashes;
with (1) fixed and (2) unfixed it reports 10.

Reported by @davidkoski in #379, where the same double-update was found in the
DeepSeek-V2 port.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New

@davidkoski
davidkoski merged commit 294c31f into ml-explore:main Jul 23, 2026
2 checks passed
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
…ion call (ml-explore#457)

Two bugs on the cached path, so DeepSeek-V3 could not generate.

1. `kvHeads` was declared `[Int] = []` and never assigned. `newCache` derives the
   layer count from `kvHeads.count`, so it returned an empty array, and the first
   `cache?[i]` in the layer loop trapped with "Index out of range". Any generation
   crashed; only a `cache: nil` forward pass worked. Populate it the way the other
   models do: one entry per layer.

2. Attention called `cache.update(...)` explicitly and then passed the resulting
   keys/values to `attentionWithCacheUpdate`, which performs the update itself.
   The second update appended the already-returned history back into the cache, so
   a prompt of L tokens left the cache at 2L and every subsequent token attended
   over duplicated keys. Drop the explicit update and let the helper own the single
   one, matching Llama/Qwen3/Cohere and the Python reference. This also routes the
   quantized-cache path correctly, which the manual update bypassed.

Adds DeepseekV3Tests with a cache-growth regression test: a 5-token forward pass
must leave every layer's cache at offset 5. With (1) unfixed the test crashes;
with (1) fixed and (2) unfixed it reports 10.

Reported by @davidkoski in ml-explore#379, where the same double-update was found in the
DeepSeek-V2 port.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
Add DeepSeek-V2 model

Port of mlx-lm's deepseek_v2.py, reusing the in-tree V3 MLA machinery (q_a/q_b + kv_a_with_mqa/kv_b compression, qk nope/rope split, YaRN rope) and SwitchGLU MoE with shared experts. Router differs from V3: plain softmax scoring, optional group-limited-greedy masking, unconditional routed_scaling_factor. Dense layers below first_k_dense_replace use standard MLP.

Fixes along the way:
- Make `qLoraRank` optional (`Int?`); V2-Lite sets `q_lora_rank: null` and needs direct q_proj instead of the q_a/q_b LoRA path. Fixes loading mlx-community/DeepSeek-V2-Lite-Chat-4bit-mlx.
- Update the KV cache once per attention call instead of twice — the explicit `cache.update()` plus `attentionWithCacheUpdate`'s internal update was duplicating cached keys/values, doubling cache size and corrupting attention beyond the first token.
- Fix `topk_method` default typo ("gready" → "greedy"), cosmetic only.

Includes tests for logits shape, group-limited-greedy routing, expert-stacking in `sanitize()`, qLoraRank parsing, and KV cache growth.
@GoodOlClint
GoodOlClint deleted the pr/deepseek-v2 branch August 1, 2026 16:44
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…arallel

Gemma 4: tensor-parallel hooks and CBv2 layer submission
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants