Skip to content

fix(DeepseekV3): one cache per layer, one cache update per step, and a sanitize that removes per-expert tensors - #213

Merged
Gajesh2007 merged 3 commits into
mainfrom
fix/deepseekv3-cache
Oct 2, 2026
Merged

Gajesh2007 merged 3 commits into
mainfrom
fix/deepseekv3-cache

Conversation

@davidtai

@davidtai davidtai commented Sep 30, 2026 •

Copy link
Copy Markdown

Proposed changes

Fixes #203

This PR fixes the three defects of #203 in two commits: the cache defects (1 and 2), then the loader defect (3). Line numbers are on main at 0871943. The reference is mlx-lm ml-explore/mlx-lm at a9bd8af.

Defect 1: no cache. Libraries/MLXLLM/Models/DeepseekV3.swift:417: DeepseekV3Model sets kvHeads to [] and never fills it. The default newCache(parameters:) (KVCacheDimensionProvider, LanguageModel.swift:261) builds one cache per kvHeads entry, so it gives no cache, and cache?[i] in the model is out of range. Generation with a cache does not run.
Fix: set kvHeads to one entry per layer (numKeyValueHeads, repeated numHiddenLayers times).

Defect 2: the cache is updated twice. DeepseekV3.swift:205-218: the attention calls cache.update (205-207) and then attentionWithCacheUpdate with the same cache (214-218), which updates it again (AttentionUtils.swift). The cache holds every key and value twice.
Reference: mlx_lm/models/deepseek_v3.py:144 calls cache.update_and_fetch once per attention call.
Fix: remove the first update. attentionWithCacheUpdate does the only update, as in the other models of this package.

Defect 3: sanitize keeps the per-expert tensors. DeepseekV3.swift:434-478: sanitize(weights:) starts from a copy of every key (435) and stacks the per-expert tensors into model.layers.N.mlp.switch_mlp.* (470), but keeps the per-expert keys. The strict update rejects them as unused keys, so a checkpoint with one tensor per expert does not load.
Reference: mlx_lm/models/deepseek_v3.py:428-438 takes each tensor out with weights.pop(...) before it stacks them.
Fix: take each per-expert tensor out of the result with removeValue(forKey:). The loop now reads the result dictionary, not the input, so it also stacks the dequantized tensor of an fp8 checkpoint, as the reference does.

Origin. Defects 1 and 2 are the same as at the fork base 7e2b710. Upstream ml-explore/mlx-swift-lm fixed them later (ml-explore#457), and this PR makes the same change. Defect 3 is also on upstream main.

Tests. Tests/MLXLMTests/DeepseekV3CacheAndLoaderTests.swift, a tiny DeepSeek V3 model with seeded random weights (multi-head latent attention, one dense layer, one layer with 4 routed experts; no real weights):

  • newCacheGivesOneCachePerLayer: newCache(parameters:) gives 2 caches for 2 layers (defect 1).
  • cachedDecodeMatchesTheFullForwardPass: a prompt in chunks 5, 3 and three decode steps gives the logits of the full pass (tolerance 1e-4), with the cache of newCache(parameters:) and with a list of KVCacheSimple. After 11 tokens each cache has offset 11, not 22 (defects 1 and 2).
  • loaderStacksPerExpertWeights: splits the stacked experts of a reference model into one tensor per expert, checks that sanitize(weights:) gives the stacked [4, 16, 32] tensor and no .experts. key, loads the checkpoint through loadWeights (strict update), and checks that the loaded model gives the logits of the reference model exactly (defect 3).

The tests are copies of newCacheGivesOneCachePerLayer, cachedDecodeMatchesTheFullForwardPass and loaderStacksPerExpertWeights of DeepseekV3ForwardPassTests in #185, without the withKnownIssue blocks. The cached test also checks the new cache and the offsets, and the loader test also compares the logits. The helpers they need live only in #183 (Tests/MLXLMTests/Kernel/Support/SyntheticModel.swift and ModelCase.swift), so the file has small private copies of randomize, tokens, logits, maxAbsDifference, load and CheckpointLayout.splitExperts. They are private to the suite, so they do not collide with the #183 types.

fork.yaml has a new section "DeepSeek V3 cache and loader fixes" for the two files.

Not in scope. sanitize(weights:) also keeps the *.weight_scale_inv keys of an fp8 checkpoint; the reference drops them. No test covers that, and this PR does not change it.

Merge note. After this PR and #185 are both on main, remove the three withKnownIssue blocks from Tests/MLXLMTests/Kernel/LLM/DeepseekV3ForwardPassTests.swift of #185: in newCacheGivesOneCachePerLayer, cachedDecodeMatchesTheFullForwardPass and loaderStacksPerExpertWeights. The pull request that merges second (this one or #185) must remove the named withKnownIssue blocks in the same change. A known issue that is not intermittent and no longer fails is reported as a failure.

Merge order. This PR and the Gemma 3n PRs (#215, #217, #218) conflict in fork.yaml: each inserts a section after the SwitchGLUTests.swift glob. After the first of #213 or a Gemma 3n PR merges, rebase the other and keep both sections.

Merge order (fork.yaml). This PR has a fork.yaml conflict with #274. After the first of these PRs merges, each other one needs a merge of main and a new Fork Tests run before it merges.

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 (ran swift format on the changed Swift files)
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed) (fork.yaml)

🤖 Generated with Claude Code

davidtai and others added 2 commits September 30, 2026 18:34
DeepseekV3Model set kvHeads to [] and never filled it. The default
newCache(parameters:) builds one cache per kvHeads entry, so it gave no
cache, and cache?[i] in the model was out of range. Set one entry per
layer.

The attention called cache.update and then attentionWithCacheUpdate with
the same cache, which updates it again. The cache held each key and value
twice. Remove the first update, so attentionWithCacheUpdate does the only
update, as in mlx-lm deepseek_v3.py.

Add DeepseekV3CacheAndLoaderTests: the cache count, and a cached prompt in
chunks plus decode steps against the full pass on a tiny random model.

Part of #203

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…them

sanitize(weights:) starts from a copy of every key and stacks the
per-expert tensors into model.layers.N.mlp.switch_mlp.*, but it kept the
per-expert keys. The strict update then rejected them as unused keys, so
a checkpoint with one tensor per expert did not load.

Take each per-expert tensor out of the result when it is stacked, as
mlx-lm deepseek_v3.py pops it. The stack now also reads the dequantized
tensor, as the reference does, not the tensor before dequantization.

Add loaderStacksPerExpertWeights to DeepseekV3CacheAndLoaderTests: it
splits the experts of a tiny random model, loads the checkpoint through
loadWeights, and compares the logits with the reference model.

Fixes #203

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Gajesh2007
Gajesh2007 merged commit a8a62cd into main Oct 2, 2026
4 of 5 checks passed
@davidtai
davidtai deleted the fix/deepseekv3-cache branch October 15, 2026 05:20
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.

DeepseekV3: kvHeads is empty, the cache is updated twice, and sanitize keeps per-expert tensors

2 participants