From 5d0e95351af76c147422e5e5ced8e71186720729 Mon Sep 17 00:00:00 2001 From: Clint Branham Date: Wed, 22 Jul 2026 15:38:24 -0500 Subject: [PATCH] DeepSeek-V3: populate kvHeads and update the KV cache once per attention 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 #379, where the same double-update was found in the DeepSeek-V2 port. Co-Authored-By: Claude Opus 4.8 --- Libraries/MLXLLM/Models/DeepseekV3.swift | 14 ++--- Tests/MLXLMTests/DeepseekV3Tests.swift | 78 ++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 10 deletions(-) create mode 100644 Tests/MLXLMTests/DeepseekV3Tests.swift diff --git a/Libraries/MLXLLM/Models/DeepseekV3.swift b/Libraries/MLXLLM/Models/DeepseekV3.swift index 8e0109046a..23f3814b9d 100644 --- a/Libraries/MLXLLM/Models/DeepseekV3.swift +++ b/Libraries/MLXLLM/Models/DeepseekV3.swift @@ -195,21 +195,14 @@ class DeepseekV3Attention: Module { kv = kv.reshaped(B, L, self.numHeads, -1).transposed(0, 2, 1, 3) let splitKv = split(kv, indices: [self.qkNopeHeadDim], axis: -1) - var (kNope, values) = (splitKv[0], splitKv[1]) + let (kNope, values) = (splitKv[0], splitKv[1]) let offset = cache?.ropeOffset qPe = applyRotaryPosition(rope, to: qPe, offset: offset) kPe = applyRotaryPosition(rope, to: kPe, offset: offset) kPe = repeated(kPe, count: numHeads, axis: 1) - var keys: MLXArray - if let cache = cache { - (keys, values) = cache.update( - keys: concatenated([kNope, kPe], axis: -1), values: values) - } else { - keys = concatenated([kNope, kPe], axis: -1) - } - + let keys = concatenated([kNope, kPe], axis: -1) let queries = concatenated([qNope, qPe], axis: -1) let output = attentionWithCacheUpdate( @@ -415,7 +408,7 @@ public class DeepseekV3ModelInner: Module { } public class DeepseekV3Model: Module, LLMModel, KVCacheDimensionProvider, LoRAModel { - public var kvHeads: [Int] = [] + public var kvHeads: [Int] var args: DeepseekV3Configuration public var model: DeepseekV3ModelInner @@ -423,6 +416,7 @@ public class DeepseekV3Model: Module, LLMModel, KVCacheDimensionProvider, LoRAMo public init(_ args: DeepseekV3Configuration) { self.args = args + self.kvHeads = Array(repeating: args.numKeyValueHeads, count: args.numHiddenLayers) self.model = DeepseekV3ModelInner(config: args) self._lmHead.wrappedValue = Linear(args.hiddenSize, args.vocabSize, bias: false) } diff --git a/Tests/MLXLMTests/DeepseekV3Tests.swift b/Tests/MLXLMTests/DeepseekV3Tests.swift new file mode 100644 index 0000000000..097bb1a793 --- /dev/null +++ b/Tests/MLXLMTests/DeepseekV3Tests.swift @@ -0,0 +1,78 @@ +import Foundation +import MLX +import MLXLMCommon +import MLXNN +import XCTest + +@testable import MLXLLM + +final class DeepseekV3Tests: XCTestCase { + + // Tiny MoE config: 4 routed experts in 2 groups, top-1 group, top-2 experts. + private func makeConfig() throws -> DeepseekV3Configuration { + let json = """ + { + "model_type": "deepseek_v3", + "vocab_size": 32, + "hidden_size": 8, + "intermediate_size": 16, + "moe_intermediate_size": 8, + "num_hidden_layers": 2, + "num_attention_heads": 2, + "num_key_value_heads": 2, + "n_routed_experts": 4, + "n_shared_experts": 1, + "num_experts_per_tok": 2, + "n_group": 2, + "topk_group": 1, + "norm_topk_prob": true, + "routed_scaling_factor": 1.0, + "first_k_dense_replace": 1, + "moe_layer_freq": 1, + "q_lora_rank": 4, + "kv_lora_rank": 4, + "qk_rope_head_dim": 2, + "qk_nope_head_dim": 2, + "v_head_dim": 4, + "rms_norm_eps": 1e-6, + "rope_theta": 10000.0, + "max_position_embeddings": 128, + "attention_bias": false + } + """ + return try JSONDecoder().decode(DeepseekV3Configuration.self, from: Data(json.utf8)) + } + + /// Attention must update the KV cache exactly once per forward pass. + /// + /// The attention path builds `keys`/`values` and hands them to + /// `attentionWithCacheUpdate`, which performs the cache update itself. An + /// additional explicit `cache.update(...)` beforehand appended the returned + /// history a second time, so a prompt of L tokens left the cache at 2L and + /// every subsequent token attended over duplicated keys. + func testForwardPassUpdatesCacheExactlyOnce() throws { + let model = DeepseekV3Model(try makeConfig()) + let cache = model.newCache(parameters: nil) + let tokenCount = 5 + let inputs = MLXArray(Array(Int32(1) ... Int32(tokenCount))).reshaped(1, tokenCount) + + let logits = model(inputs, cache: cache) + eval(logits) + + for (i, layerCache) in cache.enumerated() { + XCTAssertEqual( + layerCache.offset, tokenCount, + "layer \(i) cache advanced by \(layerCache.offset) for \(tokenCount) tokens") + } + } + + func testForwardPassProducesLogitsShape() throws { + let model = DeepseekV3Model(try makeConfig()) + let inputs = MLXArray([1, 2, 3] as [Int32]).reshaped(1, 3) + + let logits = model(inputs, cache: nil) + eval(logits) + + XCTAssertEqual(logits.shape, [1, 3, 32]) + } +}