Repository navigation
fix(DeepseekV3): one cache per layer, one cache update per step, and a sanitize that removes per-expert tensors - #213
Merged
Merged
Conversation
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>
This was referenced Oct 1, 2026
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.
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
mainat 0871943. The reference is mlx-lmml-explore/mlx-lmat a9bd8af.Defect 1: no cache.
Libraries/MLXLLM/Models/DeepseekV3.swift:417:DeepseekV3ModelsetskvHeadsto[]and never fills it. The defaultnewCache(parameters:)(KVCacheDimensionProvider,LanguageModel.swift:261) builds one cache perkvHeadsentry, so it gives no cache, andcache?[i]in the model is out of range. Generation with a cache does not run.Fix: set
kvHeadsto one entry per layer (numKeyValueHeads, repeatednumHiddenLayerstimes).Defect 2: the cache is updated twice.
DeepseekV3.swift:205-218: the attention callscache.update(205-207) and thenattentionWithCacheUpdatewith 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:144callscache.update_and_fetchonce per attention call.Fix: remove the first update.
attentionWithCacheUpdatedoes 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 intomodel.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-438takes each tensor out withweights.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 ofnewCache(parameters:)and with a list ofKVCacheSimple. 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 thatsanitize(weights:)gives the stacked[4, 16, 32]tensor and no.experts.key, loads the checkpoint throughloadWeights(strict update), and checks that the loaded model gives the logits of the reference model exactly (defect 3).The tests are copies of
newCacheGivesOneCachePerLayer,cachedDecodeMatchesTheFullForwardPassandloaderStacksPerExpertWeightsofDeepseekV3ForwardPassTestsin #185, without thewithKnownIssueblocks. 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.swiftandModelCase.swift), so the file has small private copies ofrandomize,tokens,logits,maxAbsDifference,loadandCheckpointLayout.splitExperts. They are private to the suite, so they do not collide with the #183 types.fork.yamlhas a new section "DeepSeek V3 cache and loader fixes" for the two files.Not in scope.
sanitize(weights:)also keeps the*.weight_scale_invkeys 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 threewithKnownIssueblocks fromTests/MLXLMTests/Kernel/LLM/DeepseekV3ForwardPassTests.swiftof #185: innewCacheGivesOneCachePerLayer,cachedDecodeMatchesTheFullForwardPassandloaderStacksPerExpertWeights. The pull request that merges second (this one or #185) must remove the namedwithKnownIssueblocks 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 theSwitchGLUTests.swiftglob. 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 afork.yamlconflict with #274. After the first of these PRs merges, each other one needs a merge ofmainand a new Fork Tests run before it merges.Checklist
pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes (ranswift formaton the changed Swift files)fork.yaml)🤖 Generated with Claude Code