diff --git a/IntegrationTesting/IntegrationTestingTests/Qwen3VLCacheIntegrationTests.swift b/IntegrationTesting/IntegrationTestingTests/Qwen3VLCacheIntegrationTests.swift new file mode 100644 index 0000000000..54dceb8d36 --- /dev/null +++ b/IntegrationTesting/IntegrationTestingTests/Qwen3VLCacheIntegrationTests.swift @@ -0,0 +1,40 @@ +// Copyright © 2026 Apple Inc. + +import CoreImage +import HuggingFace +import IntegrationTestHelpers +import MLXHuggingFace +import MLXLMCommon +import MLXVLM +import Testing +import Tokenizers + +@Suite(.serialized) +struct Qwen3VLCacheIntegrationTests { + @Test func imageContinuationAfterCacheRotation() async throws { + let modelID = IntegrationTestModelIDs.vlm + let configuration = + hfSnapshotDir(modelId: modelID).map { + ModelConfiguration(directory: $0) + } ?? ModelConfiguration(id: modelID) + let container = try await VLMModelFactory.shared.loadContainer( + from: #hubDownloader(), using: #huggingFaceTokenizerLoader(), + configuration: configuration) + let parameters = GenerateParameters( + maxTokens: 8, + kvCache: KVCacheConfiguration( + capacity: try .init(maxTokens: 32, preservedPrefixTokens: 4)), + temperature: 0, prefill: .init(stepSize: 16)) + let session = ChatSession(container, generateParameters: parameters) + + _ = try await session.respond(to: String(repeating: "One two three. ", count: 32)) + let response = try await session.respond( + to: "What color is this image?", image: .ciImage(VisionTestImages.solidColor(.red))) + #expect(!response.isEmpty) + + let status = try await session.cacheStatus() + #expect(status.capacityDisposition == .fullyApplied) + #expect((status.processedTokenCount ?? 0) > 32) + #expect(status.attentionMaxSizes.allSatisfy { $0 == 32 }) + } +} diff --git a/Libraries/MLXVLM/Models/Qwen3VL.swift b/Libraries/MLXVLM/Models/Qwen3VL.swift index e2d7ac2e16..8b4707fc27 100644 --- a/Libraries/MLXVLM/Models/Qwen3VL.swift +++ b/Libraries/MLXVLM/Models/Qwen3VL.swift @@ -1145,7 +1145,7 @@ enum Qwen3VLLanguage { func callAsFunction( _ x: MLXArray, - mask: MLXArray?, + mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache?, positionIds: MLXArray? ) -> MLXArray { @@ -1163,20 +1163,14 @@ enum Qwen3VLLanguage { values = values.reshaped(batch, length, kvHeads, headDim).transposed(0, 2, 1, 3) - var kvSequenceLength = keys.dim(-2) var positionIds = positionIds if positionIds == nil { let offset = cache?.offset ?? 0 - kvSequenceLength += offset + 1 var base = MLXArray(stride(from: offset, to: offset + length, by: 1)).asType(.int32) base = tiled(base[.newAxis, 0...], repetitions: [batch, 1]) positionIds = base[.newAxis, 0..., 0...] positionIds = tiled(positionIds!, repetitions: [3, 1, 1]) - } else { - if let cache { - kvSequenceLength += cache.offset + 1 - } } let (cosValues, sinValues) = rotaryEmbedding(positionIds: positionIds!, dtype: x.dtype) @@ -1184,21 +1178,13 @@ enum Qwen3VLLanguage { (queries, keys) = Qwen3VLLanguage.applyMultimodalRotary( q: queries, k: keys, cos: cosValues, sin: sinValues) - let attentionMask: MLXFast.ScaledDotProductAttentionMaskMode - if let mask { - let slicedMask = mask[.ellipsis, 0 ..< kvSequenceLength] - attentionMask = .array(slicedMask) - } else { - attentionMask = .none - } - let output = attentionWithCacheUpdate( queries: queries, keys: keys, values: values, cache: cache, scale: scale, - mask: attentionMask + mask: mask ) .transposed(0, 2, 1, 3) .reshaped(batch, length, -1) @@ -1245,7 +1231,7 @@ enum Qwen3VLLanguage { func callAsFunction( _ x: MLXArray, - mask: MLXArray?, + mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache?, positionIds: MLXArray? ) -> MLXArray { @@ -1291,9 +1277,11 @@ enum Qwen3VLLanguage { fatalError("Either input ids or embeddings must be provided") } - var mask = mask - if mask == nil { - mask = createAttentionMask(h: hidden, cache: cache) + let attentionMask: MLXFast.ScaledDotProductAttentionMaskMode + if let mask { + attentionMask = .array(mask) + } else { + attentionMask = createAttentionMask(h: hidden, cache: cache?.first) } // Loop-invariant: the scatter targets the same token positions in @@ -1306,7 +1294,8 @@ enum Qwen3VLLanguage { for (index, layer) in layers.enumerated() { let layerCache = cache?[index] - hidden = layer(hidden, mask: mask, cache: layerCache, positionIds: positionIds) + hidden = layer( + hidden, mask: attentionMask, cache: layerCache, positionIds: positionIds) if let embeds = deepstackEmbeds, index < embeds.count, let deepstackIndices diff --git a/Tests/MLXLMTests/Qwen3VLContinuationTests.swift b/Tests/MLXLMTests/Qwen3VLContinuationTests.swift index 8db1e3b810..5112daa513 100644 --- a/Tests/MLXLMTests/Qwen3VLContinuationTests.swift +++ b/Tests/MLXLMTests/Qwen3VLContinuationTests.swift @@ -108,6 +108,111 @@ final class Qwen3VLContinuationTests: XCTestCase { try continuation.assertWarmTextContinuation(try makeTinyModel()) } + func testWarmContinuationAfterCacheRotationMatchesDecode() throws { + for (capacity, suffixLength) in [(16, 6), (16, 1), (16, 23), (1, 6)] { + let model = try makeTinyModel() + let parameters = GenerateParameters( + kvCache: KVCacheConfiguration( + capacity: try .init(maxTokens: capacity, preservedPrefixTokens: 0))) + let cache = try model.newCache(parameters: parameters) + let (_, initialState) = try lastLogits( + model.prepare( + LMInput(text: .init(tokens: textTokens(capacity))), cache: cache, state: nil, + prefill: .init(chunking: .unchunked))) + var state = initialState + let decoded = textTokens(5, seed: 3) + for index in 0 ..< decoded.dim(1) { + let output = model( + .init(tokens: decoded[0..., index ..< index + 1]), cache: cache, state: state) + eval(output.logits) + state = output.state + } + XCTAssertTrue(cache.allSatisfy { $0.offset == capacity + 5 }) + + let referenceCache = cache.map { $0.copy() } + let suffix = textTokens(suffixLength, seed: 9) + var referenceState = state + var expected = [MLXArray]() + for index in 0 ..< suffix.dim(1) { + let output = model( + .init(tokens: suffix[0..., index ..< index + 1]), cache: referenceCache, + state: referenceState) + eval(output.logits) + expected.append(output.logits) + referenceState = output.state + } + + let result = try model.prepare( + LMInput(text: .init(tokens: suffix)), cache: cache, state: state, + prefill: .init(chunking: .unchunked)) + guard case .logits(let output) = result else { + return XCTFail("expected logits from warm continuation") + } + XCTAssertLessThanOrEqual( + maxAbsDiff(output.logits, concatenated(expected, axis: 1)), + MatmulPrecision.splitTolerance) + XCTAssertTrue(cache.allSatisfy { $0.offset == capacity + 5 + suffixLength }) + } + } + + func testWindowedPrefillBeyondCacheCapacityMatchesDecode() throws { + let model = try makeTinyModel() + let parameters = GenerateParameters( + kvCache: KVCacheConfiguration( + capacity: try .init(maxTokens: 16, preservedPrefixTokens: 0))) + let tokens = textTokens(40) + let referenceCache = try model.newCache(parameters: parameters) + let (_, initialState) = try lastLogits( + model.prepare( + LMInput(text: .init(tokens: tokens[0..., 0 ..< 1])), cache: referenceCache, + state: nil, prefill: .init())) + var state = initialState + var expected = MLXArray(0) + for index in 1 ..< tokens.dim(1) { + let output = model( + .init(tokens: tokens[0..., index ..< index + 1]), cache: referenceCache, + state: state) + expected = output.logits[0..., -1, 0...] + eval(expected) + state = output.state + } + + let cache = try model.newCache(parameters: parameters) + let (actual, _) = try lastLogits( + model.prepare( + LMInput(text: .init(tokens: tokens)), cache: cache, state: nil, + prefill: .init(stepSize: 7))) + XCTAssertLessThanOrEqual(maxAbsDiff(actual, expected), MatmulPrecision.splitTolerance) + XCTAssertEqual(cache.first?.offset, 40) + XCTAssertEqual(cache.first?.state.first?.dim(2), 16) + } + + func testWindowedImageContinuationWithPreservedCachePrefix() throws { + try withRandomState(MLXRandom.RandomState(seed: 47)) { + let model = try makeTinyModel() + let parameters = GenerateParameters( + kvCache: KVCacheConfiguration( + capacity: try .init(maxTokens: 16, preservedPrefixTokens: 4))) + let cache = try model.newCache(parameters: parameters) + let prompt = concatenated( + [textTokens(6), visionStart(), imageRun(), textTokens(12, seed: 2)], axis: 1) + let (initialLogits, state) = try lastLogits( + model.prepare( + LMInput(text: .init(tokens: prompt), image: makeImage()), cache: cache, + state: nil, prefill: .init(stepSize: 5))) + eval(initialLogits) + XCTAssertEqual(cache.first?.offset, 23) + + let (logits, _) = try lastLogits( + model.prepare( + LMInput(text: .init(tokens: textTokens(9, seed: 5))), cache: cache, + state: state, prefill: .init(stepSize: 4))) + XCTAssertTrue(logits.asArray(Float.self).allSatisfy(\.isFinite)) + XCTAssertEqual(cache.first?.offset, 32) + XCTAssertEqual(cache.first?.state.first?.dim(2), 16) + } + } + /// A text-only follow-up may be rank-1 even though the cache was seeded by /// a batched image prompt. Warm routing must normalize it before slicing. func testRank1WarmImageContinuationMatchesFullPrefill() throws {