Skip to content

DeepSeek-V3: populate kvHeads and update the KV cache once per attention call - #457

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
GoodOlClint:pr/deepseek-v3-double-cache-update
Jul 22, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
GoodOlClint:pr/deepseek-v3-double-cache-update

Conversation

@GoodOlClint

Copy link
Copy Markdown
Contributor

Proposed changes

Two bugs on DeepSeek-V3's cached path. Together they mean the model cannot generate — only a cache: nil forward pass works.

This came out of @davidkoski's review on #379, which flagged the same double-update in the DeepSeek-V2 port and noted "DeepseekV3 would need the same fix". It does — plus a more basic one that hides it.

1. kvHeads was never populated (generation crashes)

public var kvHeads: [Int] = []   // never assigned

newCache derives the layer count from kvHeads.count, so it returned an empty array. The layer loop then does cache?[i], which traps immediately:

Swift/ContiguousArrayBuffer.swift:692: Fatal error: Index out of range

Fixed by populating it as the other models do — one entry per layer:

self.kvHeads = Array(repeating: args.numKeyValueHeads, count: args.numHiddenLayers)

2. The KV cache was updated twice per attention call

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.

Dropped 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.

Test

Adds DeepseekV3Tests (there were none) with a cache-growth regression test — a tiny config, no downloads. A 5-token forward pass must leave every layer's cache at offset 5.

The two bugs isolate cleanly, which is how I verified the test actually discriminates:

State Result
kvHeads empty (current main) crashes — Index out of range, test cannot run
kvHeads fixed, double-update present fails — cache advanced by 10 for 5 tokens
both fixed passes

Full MLXLMTests run is green (223 XCTest, 0 failures). Note: Gemma4ChunkedPrefillTests fails on my machine both before and after this change — a pre-existing tight-tolerance numeric issue unrelated to DeepSeek.

Checklist

Put an x in the boxes that apply.

  • 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) — no doc changes needed

🤖 Generated with Claude Code

…ion call

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>

@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.

Fix looks great, thank you!

@davidkoski
davidkoski merged commit 12d2da0 into ml-explore:main Jul 22, 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>
@GoodOlClint
GoodOlClint deleted the pr/deepseek-v3-double-cache-update branch August 1, 2026 16:44
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