diff --git a/Libraries/MLXLMCommon/AttentionUtils.swift b/Libraries/MLXLMCommon/AttentionUtils.swift index ab6d841ff5..12374dd3a3 100644 --- a/Libraries/MLXLMCommon/AttentionUtils.swift +++ b/Libraries/MLXLMCommon/AttentionUtils.swift @@ -55,7 +55,7 @@ package enum AttentionKVState { return MLXFast.scaledDotProductAttention( queries: queries, keys: keys, values: values, scale: scale, mask: mask) case .quantized(let keys, let values, let groupSize, let bits, let mode): - return quantizedScaledDotProductAttention( + return quantizedCacheAttention( queries: queries, quantizedKeys: keys, quantizedValues: values, scale: scale, mask: mask, groupSize: groupSize, bits: bits, mode: mode) case .native(let cache, let sequenceLength): @@ -153,7 +153,7 @@ public func attentionWithCacheUpdate( } else if let quantizedKVCache = cache as? QuantizedKVCacheProtocol { let (quantizedKeys, quantizedValues) = quantizedKVCache.updateQuantized( keys: keys, values: values) - return quantizedScaledDotProductAttention( + return quantizedCacheAttention( queries: queries, quantizedKeys: quantizedKeys, quantizedValues: quantizedValues, @@ -174,3 +174,58 @@ public func attentionWithCacheUpdate( ) } } + +/// Attention over a quantized cache's keys and values. Every quantized-cache route +/// goes through here so the fused-versus-quantized decision lives in one place. +package func quantizedCacheAttention( + queries: MLXArray, + quantizedKeys: (MLXArray, MLXArray, MLXArray?), + quantizedValues: (MLXArray, MLXArray, MLXArray?), + scale: Float, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + groupSize: Int, + bits: Int, + mode: QuantizationMode +) -> MLXArray { + // Scales carry one entry per group, so they recover the value head dim for any mode. + let valueHeadDim = quantizedValues.1.dim(-1) * groupSize + if usesDequantizedPrefillAttention(queries: queries, valueHeadDim: valueHeadDim) { + // Prefill over a quantized cache: dequantize once and run the fused kernel + // instead of materializing [B, H, L, N] scores through quantized matmuls. + let keys = dequantized( + quantizedKeys.0, scales: quantizedKeys.1, biases: quantizedKeys.2, + groupSize: groupSize, bits: bits, mode: mode, dtype: queries.dtype) + let values = dequantized( + quantizedValues.0, scales: quantizedValues.1, biases: quantizedValues.2, + groupSize: groupSize, bits: bits, mode: mode, dtype: queries.dtype) + return MLXFast.scaledDotProductAttention( + queries: queries, keys: keys, values: values, scale: scale, mask: mask) + } + return quantizedScaledDotProductAttention( + queries: queries, quantizedKeys: quantizedKeys, quantizedValues: quantizedValues, + scale: scale, mask: mask, groupSize: groupSize, bits: bits, mode: mode) +} + +/// Query length from which a quantized cache attends through the fused SDPA kernel over +/// dequantized keys and values rather than through quantized matmuls. +/// +/// This is a measured policy, not a kernel boundary. On M4 Pro (Qwen3-14B shapes, 4-bit +/// KV, 8k context) the quantized path is 1.45-1.7x slower from 64 queries up and +/// allocates [B, H, L, N] scores; below 32 the two are even, and at one query the +/// quantized path reads a quarter of the bytes. The crossover shifts with the GQA ratio, +/// head dim, cache length, bits, and GPU generation; retune it against new measurements. +package let dequantizedPrefillAttentionMinimumLength = 64 + +/// Head dims whose fused SDPA kernel MLX compiles for every GPU generation +/// (`mlx/backend/metal/scaled_dot_product_attention.cpp`). MLX routes 192 and 256 to +/// its unfused path, where the quantized matmuls are competitive, so they stay out. +package let dequantizedPrefillAttentionHeadDims: Set = [64, 72, 80, 96, 128] + +/// Whether prefill attention over a quantized cache should dequantize and use the fused +/// kernel. MLA-style caches with narrower values than queries stay on the quantized route. +package func usesDequantizedPrefillAttention(queries: MLXArray, valueHeadDim: Int) -> Bool { + let headDim = queries.dim(-1) + return queries.dim(2) >= dequantizedPrefillAttentionMinimumLength + && headDim == valueHeadDim + && dequantizedPrefillAttentionHeadDims.contains(headDim) +} diff --git a/Tests/MLXLMTests/KVCacheTests.swift b/Tests/MLXLMTests/KVCacheTests.swift index f827cc7ff8..dda1710a86 100644 --- a/Tests/MLXLMTests/KVCacheTests.swift +++ b/Tests/MLXLMTests/KVCacheTests.swift @@ -1797,6 +1797,102 @@ private final class ProtocolDefaultTrimmabilityCache: KVCache { ]) } + @Test(arguments: [ + (headDim: 64, bits: 4, dtype: DType.float16), + (headDim: 64, bits: 8, dtype: DType.bfloat16), + (headDim: 128, bits: 4, dtype: DType.bfloat16), + (headDim: 128, bits: 8, dtype: DType.float16), + ]) + func testQuantizedKVCachePrefillAttentionMatchesQuantizedMatmulPath( + headDim: Int, bits: Int, dtype: DType + ) { + // 64 queries over a 100-token quantized history take the dequantized fused route; + // it must agree with the quantized-matmul attention over the same cache contents + // and stay close to full-precision attention over the unquantized history. + let fusedCache = QuantizedKVCache(groupSize: 64, bits: bits) + let matmulCache = QuantizedKVCache(groupSize: 64, bits: bits) + let plainCache = KVCacheSimple() + let history = ( + keys: deterministicTensor(shape: [1, 2, 100, headDim], salt: 40).asType(dtype), + values: deterministicTensor(shape: [1, 2, 100, headDim], salt: 41).asType(dtype) + ) + for cache in [fusedCache, matmulCache] { + _ = cache.updateQuantized(keys: history.keys, values: history.values) + } + _ = plainCache.update(keys: history.keys, values: history.values) + + let queries = deterministicTensor(shape: [1, 4, 64, headDim], salt: 42).asType(dtype) + let keys = deterministicTensor(shape: [1, 2, 64, headDim], salt: 43).asType(dtype) + let values = deterministicTensor(shape: [1, 2, 64, headDim], salt: 44).asType(dtype) + let scale = 1 / sqrt(Float(headDim)) + #expect(usesDequantizedPrefillAttention(queries: queries, valueHeadDim: headDim)) + + let fused = attentionWithCacheUpdate( + queries: queries, keys: keys, values: values, cache: fusedCache, + scale: scale, mask: .causal) + let (quantizedKeys, quantizedValues) = matmulCache.updateQuantized( + keys: keys, values: values) + let viaMatmul = quantizedScaledDotProductAttention( + queries: queries, quantizedKeys: quantizedKeys, quantizedValues: quantizedValues, + scale: scale, mask: .causal, groupSize: 64, bits: bits) + let fullPrecision = attentionWithCacheUpdate( + queries: queries, keys: keys, values: values, cache: plainCache, + scale: scale, mask: .causal) + eval(fused, viaMatmul, fullPrecision) + + #expect(fused.shape == [1, 4, 64, headDim]) + #expect(fused.dtype == dtype) + #expect(relativeRMSError(fused, viaMatmul) < 1e-2) + #expect(relativeRMSError(fused, fullPrecision) < (bits == 4 ? 5e-2 : 1e-2)) + #expect(fusedCache.offset == 164) + } + + @Test func testAttentionKVStateQuantizedRouteSharesPrefillDispatch() { + // The state-based route (shared-KV layers) must make the same fused-versus-quantized + // decision as `attentionWithCacheUpdate`. + let stateCache = QuantizedKVCache(groupSize: 64, bits: 4) + let directCache = QuantizedKVCache(groupSize: 64, bits: 4) + let queries = deterministicTensor(shape: [1, 4, 64, 64], salt: 52) + let keys = deterministicTensor(shape: [1, 2, 64, 64], salt: 53) + let values = deterministicTensor(shape: [1, 2, 64, 64], salt: 54) + let scale = 1 / sqrt(Float(64)) + + let state = AttentionKVState.update(keys: keys, values: values, cache: stateCache) + guard case .quantized = state else { + Issue.record("expected a quantized attention state") + return + } + let viaState = state.attend(queries: queries, scale: scale, mask: .causal) + let direct = attentionWithCacheUpdate( + queries: queries, keys: keys, values: values, cache: directCache, + scale: scale, mask: .causal) + eval(viaState, direct) + + #expect(state.sequenceLength == 64) + #expect(allClose(viaState, direct).item(Bool.self)) + } + + @Test func testDequantizedPrefillAttentionRouteGates() { + #expect( + !usesDequantizedPrefillAttention( + queries: deterministicTensor(shape: [1, 4, 1, 64], salt: 46), valueHeadDim: 64)) + #expect( + !usesDequantizedPrefillAttention( + queries: deterministicTensor(shape: [1, 4, 63, 64], salt: 47), valueHeadDim: 64)) + #expect( + usesDequantizedPrefillAttention( + queries: deterministicTensor(shape: [1, 4, 64, 64], salt: 48), valueHeadDim: 64)) + // MLX runs head dim 256 unfused on most GPUs, so it keeps the quantized route. + #expect( + !usesDequantizedPrefillAttention( + queries: deterministicTensor(shape: [1, 4, 64, 256], salt: 49), + valueHeadDim: 256)) + // MLA-style caches with narrower values than queries stay on the quantized route. + #expect( + !usesDequantizedPrefillAttention( + queries: deterministicTensor(shape: [1, 4, 64, 128], salt: 51), valueHeadDim: 64)) + } + @Test func testVarianceNormalizedKVCacheQuantizedTileAttentionSupportsGQA() { let nativeCache = VarianceNormalizedKVCache( tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2)