diff --git a/Libraries/MLXLLM/Models/MiMoV2Flash.swift b/Libraries/MLXLLM/Models/MiMoV2Flash.swift index b309f891c5..f6537aae0d 100644 --- a/Libraries/MLXLLM/Models/MiMoV2Flash.swift +++ b/Libraries/MLXLLM/Models/MiMoV2Flash.swift @@ -31,7 +31,14 @@ private func attentionWithCacheUpdateAndSinks( ) } - if let quantizedKVCache = cache as? QuantizedKVCacheProtocol { + if let attentionCache = cache as? KVCacheAttentionProtocol, sinks == nil { + return attentionCache.updateAndAttend( + queries: queries, + keys: keys, + values: values, + scale: scale, + mask: mask) + } else if let quantizedKVCache = cache as? QuantizedKVCacheProtocol { precondition(sinks == nil, "Quantized SDPA does not support attention sinks.") let (quantizedKeys, quantizedValues) = quantizedKVCache.updateQuantized( keys: keys, values: values) diff --git a/Libraries/MLXLMCommon/AttentionUtils.swift b/Libraries/MLXLMCommon/AttentionUtils.swift index 2829a818a7..2f66f197e2 100644 --- a/Libraries/MLXLMCommon/AttentionUtils.swift +++ b/Libraries/MLXLMCommon/AttentionUtils.swift @@ -10,6 +10,7 @@ import MLX /// /// This function matches Python's `scaled_dot_product_attention` in base.py: /// - Detects if cache is `QuantizedKVCache` using `isinstance` pattern +/// - Detects cache-native attention implementations /// - Routes to `quantizedScaledDotProductAttention` or `MLXFast.scaledDotProductAttention` /// - Handles cache updating automatically /// - Transparent to models - they just call this function @@ -69,6 +70,13 @@ public func attentionWithCacheUpdate( queries: queries, keys: keys, values: values, scale: scale, mask: mask ) + } else if let attentionCache = cache as? KVCacheAttentionProtocol { + return attentionCache.updateAndAttend( + queries: queries, + keys: keys, + values: values, + scale: scale, + mask: mask) } else if let quantizedKVCache = cache as? QuantizedKVCacheProtocol { let (quantizedKeys, quantizedValues) = quantizedKVCache.updateQuantized( keys: keys, values: values) diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index 4c29b0e97e..685fc04571 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -138,6 +138,12 @@ public struct GenerateParameters: Sendable { /// maximum compression; K sensitivity varies by model family, so /// validate on your model (asym is the recommended starting point). /// + /// Variance-normalized (KVarN-inspired) schemes for memory-bound long context: + /// - "varn" / "varn4v2" 4-bit K + 2-bit V, 128-token tiles + /// - "varn4" / "varn4v4" 4-bit K/V + /// - "varn2" / "varn2v2" 2-bit K/V + /// - "varn4v2t32" / "varn4v2t64" explicit tile size variants + /// /// Unrecognized schemes are rejected when generation starts. Prefer /// ``kvCache`` for compile-time-safe configuration. public var kvScheme: String? diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index 22e5cd8e6f..6d78b45c0b 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -180,6 +180,23 @@ public protocol QuantizedKVCacheProtocol: KVCache { func getQuantizedState() -> ((MLXArray, MLXArray, MLXArray?), (MLXArray, MLXArray, MLXArray?))? } +/// Protocol for caches that can update and compute attention from their own storage layout. +/// +/// Used by compressed caches such as ``VarianceNormalizedKVCache`` that keep completed +/// tiles in a non-materialized representation and compute scores/values via cache-native +/// kernels (e.g. `quantizedMM` in a rotated domain). +public protocol KVCacheAttentionProtocol: KVCache { + /// Update the cache with new K/V tensors and compute attention without first returning a + /// fully materialized cache tensor pair. + func updateAndAttend( + queries: MLXArray, + keys: MLXArray, + values: MLXArray, + scale: Float, + mask: MLXFast.ScaledDotProductAttentionMaskMode + ) -> MLXArray +} + /// Base cache implementation providing default behaviors open class BaseKVCache: KVCache { public var offset: Int = 0 @@ -1742,6 +1759,7 @@ private func cacheClassName(_ cache: KVCache) -> String { case is MambaCache: return "MambaCache" case is ArraysCache: return "ArraysCache" case is RotatingKVCache: return "RotatingKVCache" + case is VarianceNormalizedKVCache: return "VarianceNormalizedKVCache" case is QuantizedKVCache: return "QuantizedKVCache" case is TurboQuantKVCache: return "TurboQuantKVCache" case is KVCacheSimple: return "KVCache" @@ -2083,6 +2101,80 @@ private func restoreCacheFromMetaState( cache.metaState = metaState return cache + case "VarianceNormalizedKVCache": + guard metaState.count == 7 || metaState.count == 10 else { + throw KVCacheError( + message: + "Corrupt prompt cache: VarianceNormalizedKVCache metadata must contain 7 legacy or 10 versioned values." + ) + } + let values = try promptCacheIntegers(Array(metaState.prefix(7)), className: className) + let tileSize = values[0] + let offset = values[1] + let keyBits = values[2] + let valueBits = values[3] + let sinkhornIterations = values[4] + let tileCount = values[5] + let tailLength = values[6] + guard + (try? VarianceNormalizedKVCacheConfiguration( + keyBits: keyBits, + valueBits: valueBits, + tileSize: tileSize, + sinkhornIterations: sinkhornIterations)) != nil, + offset >= 0, + tileCount >= 0, + (0 ..< tileSize).contains(tailLength), + metaState.count == 7 + || (Int(metaState[7]) == VarianceNormalizedKVCache.metadataVersion + && (metaState[8] == "none" + || varianceNormalizedDType(named: metaState[8]) + .map(isSupportedVarianceNormalizedDType) == true) + && (metaState[9] == "none" + || varianceNormalizedDType(named: metaState[9]) + .map(isSupportedVarianceNormalizedDType) == true)) + else { + throw KVCacheError( + message: "Corrupt prompt cache: invalid VarianceNormalizedKVCache metadata." + ) + } + let (tiledLength, tileLengthOverflow) = tileCount.multipliedReportingOverflow( + by: tileSize) + let (representedLength, offsetOverflow) = tiledLength.addingReportingOverflow(tailLength) + let tailStateCount = + tailLength > 0 ? VarianceNormalizedKVCache.tailStateCount : 0 + let tileStateCount = state.count - min(state.count, tailStateCount) + let hasValidTileStateCount = + if tileCount == 0 { + tileStateCount == 0 + } else { + tileStateCount.isMultiple(of: tileCount) + && [ + VarianceNormalizedKVCache.compactTileStateCount, + VarianceNormalizedKVCache.legacyTileStateCount, + ].contains(tileStateCount / tileCount) + } + guard + !tileLengthOverflow, + !offsetOverflow, + offset == representedLength, + state.count >= tailStateCount, + hasValidTileStateCount, + state.allSatisfy({ $0.ndim == 4 }) + else { + throw KVCacheError( + message: "Corrupt prompt cache: invalid VarianceNormalizedKVCache state." + ) + } + let cache = VarianceNormalizedKVCache( + tileSize: tileSize, + keyBits: keyBits, + valueBits: valueBits, + sinkhornIterations: sinkhornIterations) + cache.metaState = metaState + cache.state = state + return cache + case "ChunkedKVCache": try validatePromptCache( className: className, state: state, stateCounts: [0, 2], @@ -2483,7 +2575,8 @@ public func maybeQuantizeKVCache( ) { if let kvScheme, resolveAffineScheme(kvScheme) == nil, - resolveTurboScheme(kvScheme) == nil + resolveTurboScheme(kvScheme) == nil, + resolveVarianceNormalizedScheme(kvScheme) == nil { return } @@ -2518,3 +2611,126 @@ func maybeAffineQuantizeKVCache( } return !awaitsCompressionStart } + +@discardableResult +func maybeVarianceNormalizeKVCache( + cache: inout [KVCache], + keyBits: Int, + valueBits: Int, + tileSize: Int, + sinkhornIterations: Int, + compressionStart: Int +) -> Bool { + var awaitsCompressionStart = false + KVCacheTree.rewrite(&cache) { leaf in + guard case .simple(let simple) = leaf.kind else { return leaf.cache } + guard simple.offset > compressionStart else { + awaitsCompressionStart = true + return simple + } + + let state = simple.innerState() + if state.count >= 2 { + guard + supportsVarianceNormalizedKVCache( + keyHeadDim: state[0].dim(3), + valueHeadDim: state[1].dim(3), + tileSize: tileSize) + else { + return simple + } + } + + return simple.toVarianceNormalized( + tileSize: tileSize, + keyBits: keyBits, + valueBits: valueBits, + sinkhornIterations: sinkhornIterations) + } + return !awaitsCompressionStart +} + +// MARK: - Attention Helpers + +/// Apply a symbolic or array attention mask to score logits. +func applyAttentionMask( + scores: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode +) -> MLXArray { + switch mask { + case .causal: + let (qL, kL) = (scores.dim(-2), scores.dim(-1)) + let qIndices = MLXArray(0 ..< qL) + MLXArray(kL - qL) + let kIndices = MLXArray(0 ..< kL) + let causalMask = greaterEqual( + expandedDimensions(qIndices, axis: -1), expandedDimensions(kIndices, axis: -2)) + return MLX.where(causalMask, scores, MLXArray.maskFill(for: scores.dtype)) + + case .array(let maskArray): + if maskArray.dtype == .bool { + return MLX.where(maskArray, scores, MLXArray.maskFill(for: scores.dtype)) + } else { + return scores + maskArray + } + + case .arrays(let maskArrays): + if let maskArray = maskArrays.first { + if maskArray.dtype == .bool { + return MLX.where(maskArray, scores, MLXArray.maskFill(for: scores.dtype)) + } else { + return scores + maskArray + } + } + return scores + + case .none: + return scores + } +} + +func attentionScores( + queries: MLXArray, + keys: MLXArray, + scale: Float +) -> MLXArray { + let (batchSize, queryHeadCount, queryLength, headDim) = ( + queries.dim(0), queries.dim(1), queries.dim(2), queries.dim(3) + ) + let kvHeadCount = keys.dim(1) + let repeats = queryHeadCount / kvHeadCount + let scaledQueries = queries * scale + + if repeats > 1 { + let groupedQueries = scaledQueries.reshaped([ + batchSize, kvHeadCount, repeats, queryLength, headDim, + ]) + let groupedKeys = expandedDimensions(keys, axis: -3) + return matmul(groupedQueries, groupedKeys.transposed(0, 1, 2, 4, 3)) + .reshaped(batchSize, queryHeadCount, queryLength, keys.dim(2)) + } else { + return matmul(scaledQueries, keys.transposed(0, 1, 3, 2)) + } +} + +func attentionValues( + weights: MLXArray, + values: MLXArray, + queryHeadCount: Int +) -> MLXArray { + let (batchSize, _, queryLength, keyLength) = ( + weights.dim(0), weights.dim(1), weights.dim(2), weights.dim(3) + ) + let kvHeadCount = values.dim(1) + let repeats = queryHeadCount / kvHeadCount + + if repeats > 1 { + let groupedWeights = weights.reshaped([ + batchSize, kvHeadCount, repeats, queryLength, keyLength, + ]) + let groupedValues = expandedDimensions(values, axis: -3) + return matmul(groupedWeights, groupedValues) + .reshaped(batchSize, queryHeadCount, queryLength, values.dim(3)) + } else { + return matmul(weights, values) + } +} diff --git a/Libraries/MLXLMCommon/KVCacheConfiguration.swift b/Libraries/MLXLMCommon/KVCacheConfiguration.swift index 759c22d0ff..8428df619f 100644 --- a/Libraries/MLXLMCommon/KVCacheConfiguration.swift +++ b/Libraries/MLXLMCommon/KVCacheConfiguration.swift @@ -65,6 +65,7 @@ public struct KVCacheConfiguration: Sendable, Hashable { case fullPrecision case affine(AffineKVCacheConfiguration) case turboQuant(TurboQuantKVCacheConfiguration) + case varianceNormalized(VarianceNormalizedKVCacheConfiguration) } package let storage: Storage @@ -85,12 +86,19 @@ public struct KVCacheConfiguration: Sendable, Hashable { Strategy(storage: .turboQuant(configuration)) } + public static func varianceNormalized( + _ configuration: VarianceNormalizedKVCacheConfiguration + ) -> Strategy { + Strategy(storage: .varianceNormalized(configuration)) + } + /// Stable algorithm identity for diagnostics and persistence adapters. public var identifier: KVCacheStrategyIdentifier { switch storage { case .fullPrecision: .fullPrecision case .affine: .affine case .turboQuant: .turboQuant + case .varianceNormalized: .varianceNormalized } } @@ -99,6 +107,7 @@ public struct KVCacheConfiguration: Sendable, Hashable { case .fullPrecision: 0 case .affine(let configuration): configuration.compressionStart case .turboQuant(let configuration): configuration.compressionStart + case .varianceNormalized(let configuration): configuration.compressionStart } } } @@ -115,6 +124,7 @@ public struct KVCacheStrategyIdentifier: Sendable, Hashable, CustomStringConvert public static let fullPrecision = KVCacheStrategyIdentifier("full-precision") public static let affine = KVCacheStrategyIdentifier("affine") public static let turboQuant = KVCacheStrategyIdentifier("turbo-quant") + public static let varianceNormalized = KVCacheStrategyIdentifier("variance-normalized") public var description: String { rawValue } } @@ -252,6 +262,80 @@ public struct TurboQuantKVCacheConfiguration: Sendable, Hashable { compressionStart: 0) } +/// Variance-normalized (KVarN-inspired) cache compression settings. +/// +/// Completed tiles are rotated, dual-axis variance-normalized, and quantized +/// asymmetrically (keys and values may use different bit widths). The intended +/// use case is memory-constrained long-context decoding rather than latency- +/// sensitive generation. +/// +/// - Warning: This strategy is experimental. Models must route attention through +/// `attentionWithCacheUpdate`; direct `KVCache.update` call sites use a full-cache +/// materialization fallback that is not suitable for long-context decode. +public struct VarianceNormalizedKVCacheConfiguration: Sendable, Hashable { + private static let supportedBitWidths: Set = [2, 3, 4, 5, 6, 8] + private static let supportedTileSizes: Set = [32, 64, 128] + + public let keyBits: Int + public let valueBits: Int + public let tileSize: Int + public let sinkhornIterations: Int + public let compressionStart: Int + + public init( + keyBits: Int = 4, + valueBits: Int = 2, + tileSize: Int = 128, + sinkhornIterations: Int = 8, + compressionStart: Int = 0 + ) throws { + guard Self.supportedBitWidths.contains(keyBits) else { + throw KVCacheConfigurationError.invalidAffineBits(keyBits) + } + guard Self.supportedBitWidths.contains(valueBits) else { + throw KVCacheConfigurationError.invalidAffineBits(valueBits) + } + guard Self.supportedTileSizes.contains(tileSize) else { + throw KVCacheConfigurationError.invalidTileSize(tileSize) + } + guard sinkhornIterations > 0 else { + throw KVCacheConfigurationError.invalidSinkhornIterations(sinkhornIterations) + } + guard compressionStart >= 0 else { + throw KVCacheConfigurationError.invalidCompressionStart(compressionStart) + } + self.keyBits = keyBits + self.valueBits = valueBits + self.tileSize = tileSize + self.sinkhornIterations = sinkhornIterations + self.compressionStart = compressionStart + } + + package init( + uncheckedKeyBits keyBits: Int, + valueBits: Int, + tileSize: Int, + sinkhornIterations: Int, + compressionStart: Int + ) { + self.keyBits = keyBits + self.valueBits = valueBits + self.tileSize = tileSize + self.sinkhornIterations = sinkhornIterations + self.compressionStart = compressionStart + } + + /// 4-bit keys and 2-bit values with 128-token tiles; the paper-inspired default. + public static let memoryFirst = VarianceNormalizedKVCacheConfiguration( + uncheckedKeyBits: 4, valueBits: 2, tileSize: 128, sinkhornIterations: 8, + compressionStart: 0) + + /// 4-bit keys and values for higher fidelity at still-reduced memory. + public static let balanced = VarianceNormalizedKVCacheConfiguration( + uncheckedKeyBits: 4, valueBits: 4, tileSize: 128, sinkhornIterations: 8, + compressionStart: 0) +} + /// Validation failures for typed or legacy KV-cache configuration. public enum KVCacheConfigurationError: Error, Sendable, Equatable, LocalizedError { case conflictingLegacyConfiguration @@ -260,6 +344,8 @@ public enum KVCacheConfigurationError: Error, Sendable, Equatable, LocalizedErro case invalidPreservedPrefix(Int, capacity: Int) case invalidAffineBits(Int) case invalidGroupSize(Int) + case invalidTileSize(Int) + case invalidSinkhornIterations(Int) case invalidCompressionStart(Int) case unsupportedLegacyScheme(String) case incompatibleCapacity(expected: Int, count: Int) @@ -280,6 +366,10 @@ public enum KVCacheConfigurationError: Error, Sendable, Equatable, LocalizedErro "Affine KV-cache bit width must be one of 2, 3, 4, 5, 6, or 8; received \(value)." case .invalidGroupSize(let value): "KV-cache group size must be positive; received \(value)." + case .invalidTileSize(let value): + "Variance-normalized KV-cache tile size must be 32, 64, or 128; received \(value)." + case .invalidSinkhornIterations(let value): + "Variance-normalized Sinkhorn iterations must be positive; received \(value)." case .invalidCompressionStart(let value): "KV-cache compression start must be non-negative; received \(value)." case .unsupportedLegacyScheme(let value): diff --git a/Libraries/MLXLMCommon/KVCachePlan.swift b/Libraries/MLXLMCommon/KVCachePlan.swift index 99f66c7c59..0f7300f441 100644 --- a/Libraries/MLXLMCommon/KVCachePlan.swift +++ b/Libraries/MLXLMCommon/KVCachePlan.swift @@ -495,6 +495,15 @@ extension GenerateParameters { valuePrecision: valuePrecision, compressionStart: quantizedKVStart)) } + if let varn = resolveVarianceNormalizedScheme(scheme) { + return .varianceNormalized( + try .init( + keyBits: varn.keyBits, + valueBits: varn.valueBits, + tileSize: varn.tileSize, + sinkhornIterations: varn.sinkhornIterations, + compressionStart: quantizedKVStart)) + } throw KVCacheConfigurationError.unsupportedLegacyScheme(scheme) } } diff --git a/Libraries/MLXLMCommon/KVCacheRound.swift b/Libraries/MLXLMCommon/KVCacheRound.swift index b6334aaec1..2aecbdbdcb 100644 --- a/Libraries/MLXLMCommon/KVCacheRound.swift +++ b/Libraries/MLXLMCommon/KVCacheRound.swift @@ -195,7 +195,7 @@ enum KVCacheRoundStrategyFactory { return RotatingRoundStrategy(slot: slot, live: rotating) case .recurrent: return nil - case .simple, .affine, .turboQuant, .unsupported: + case .simple, .affine, .turboQuant, .varianceNormalized, .unsupported: // Write-through plus a clamp is sound exactly when a later trim undoes the appended // positions -- asked with the round's real width, because the entry that matters is // one that is trimmable now and would stop being trimmable during the round. diff --git a/Libraries/MLXLMCommon/KVCacheRuntime.swift b/Libraries/MLXLMCommon/KVCacheRuntime.swift index b9cb3227a9..b546fbcfcc 100644 --- a/Libraries/MLXLMCommon/KVCacheRuntime.swift +++ b/Libraries/MLXLMCommon/KVCacheRuntime.swift @@ -70,6 +70,14 @@ package func applyKVCacheConfigurationFast( keyBits: turbo.keyPrecision.bitWidth, valueBits: turbo.valuePrecision.bitWidth, quantizedKVStart: turbo.compressionStart) + case .varianceNormalized(let varn): + maybeVarianceNormalizeKVCache( + cache: &cache, + keyBits: varn.keyBits, + valueBits: varn.valueBits, + tileSize: varn.tileSize, + sinkhornIterations: varn.sinkhornIterations, + compressionStart: varn.compressionStart) } } @@ -224,6 +232,12 @@ extension KVCacheLeaf { reason: matches ? (turbo.isCompressed ? nil : .awaitingCompressionStart) : .differentStrategy) + case .varianceNormalized: + let matches = requested == .varianceNormalized + return status( + state: matches ? .active : .skipped, + resolvedStrategy: .varianceNormalized, + reason: matches ? nil : .differentStrategy) case .affine: let isBoundaryProtection = requested == .turboQuant && protectedPaths.contains(path) diff --git a/Libraries/MLXLMCommon/KVCacheTree.swift b/Libraries/MLXLMCommon/KVCacheTree.swift index 7182f45627..2212a2db40 100644 --- a/Libraries/MLXLMCommon/KVCacheTree.swift +++ b/Libraries/MLXLMCommon/KVCacheTree.swift @@ -8,6 +8,7 @@ struct KVCacheLeaf { case simple(KVCacheSimple) case affine(QuantizedKVCache) case turboQuant(TurboQuantKVCache) + case varianceNormalized(VarianceNormalizedKVCache) case unsupported } @@ -19,6 +20,7 @@ struct KVCacheLeaf { case is MambaCache, is ArraysCache: .recurrent case let cache as RotatingKVCache: .rotating(cache) case let cache as TurboQuantKVCache: .turboQuant(cache) + case let cache as VarianceNormalizedKVCache: .varianceNormalized(cache) case let cache as QuantizedKVCache: .affine(cache) case let cache as KVCacheSimple: .simple(cache) default: .unsupported @@ -32,7 +34,7 @@ struct KVCacheLeaf { var isCompressed: Bool { switch kind { - case .affine, .turboQuant: true + case .affine, .turboQuant, .varianceNormalized: true default: false } } @@ -47,7 +49,7 @@ struct KVCacheLeaf { var participatesInTurboQuantBoundaryProtection: Bool { switch kind { case .simple, .affine, .turboQuant: true - case .recurrent, .rotating, .unsupported: false + case .recurrent, .rotating, .varianceNormalized, .unsupported: false } } @@ -64,29 +66,38 @@ struct KVCacheLeaf { case .rotating, .unsupported: return strategy == .fullPrecision case .simple(let simple): - let groupSize: Int + let state = simple.innerState() switch configuration.strategy.storage { case .fullPrecision: return true case .affine(let affine): - groupSize = affine.groupSize + guard state.count >= 2 else { return true } + return resolvedKVQuantizationGroupSize( + requested: affine.groupSize, + keyHeadDim: state[0].dim(3), + valueHeadDim: state[1].dim(3)) != nil case .turboQuant(let turbo): guard protectedPaths.contains(path) || turbo.keyPrecision == .affineEightBit else { return true } - groupSize = 64 + guard state.count >= 2 else { return true } + return resolvedKVQuantizationGroupSize( + requested: 64, + keyHeadDim: state[0].dim(3), + valueHeadDim: state[1].dim(3)) != nil + case .varianceNormalized(let varn): + guard state.count >= 2 else { return true } + return supportsVarianceNormalizedKVCache( + keyHeadDim: state[0].dim(3), + valueHeadDim: state[1].dim(3), + tileSize: varn.tileSize) } - - let state = simple.innerState() - guard state.count >= 2 else { return true } - return resolvedKVQuantizationGroupSize( - requested: groupSize, - keyHeadDim: state[0].dim(3), - valueHeadDim: state[1].dim(3)) != nil case .affine: return strategy == .affine || (strategy == .turboQuant && protectedPaths.contains(path)) case .turboQuant: return strategy == .turboQuant + case .varianceNormalized: + return strategy == .varianceNormalized } } } diff --git a/Libraries/MLXLMCommon/VarianceNormalizedKVCache.swift b/Libraries/MLXLMCommon/VarianceNormalizedKVCache.swift new file mode 100644 index 0000000000..bcb74083c1 --- /dev/null +++ b/Libraries/MLXLMCommon/VarianceNormalizedKVCache.swift @@ -0,0 +1,1134 @@ +// Copyright © 2024 Apple Inc. + +import Foundation +import MLX +import MLXNN + +private struct VarianceNormalizedKVTile { + var keyWeight: MLXArray + var keyScales: MLXArray + var keyBiases: MLXArray + var keyColumnScales: MLXArray + + var valueWeight: MLXArray + var valueScales: MLXArray + var valueBiases: MLXArray + var valueColumnScales: MLXArray +} + +private struct VarianceNormalizedKVSlab { + var records: VarianceNormalizedKVTile + let count: Int +} + +private let varianceNormalizationEpsilon: Float = 1e-8 +private let varianceNormalizationMinimumStandardDeviation: Float = 1e-3 +private let varianceNormalizationMaximumStandardDeviation: Float = 1e3 +private let varianceNormalizationMinimumLogScale: Float = -0.3 +private let varianceNormalizationMaximumLogScale: Float = 10 + +private func isPowerOfTwo(_ value: Int) -> Bool { + value > 0 && (value & (value - 1)) == 0 +} + +func isSupportedVarianceNormalizedDType(_ dtype: DType) -> Bool { + dtype == .float16 || dtype == .bfloat16 || dtype == .float32 +} + +private func varianceNormalizedDTypeName(_ dtype: DType?) -> String { + dtype.map { String(describing: $0) } ?? "none" +} + +func varianceNormalizedDType(named name: String) -> DType? { + guard name != "none" else { return nil } + return DType.allCases.first { String(describing: $0) == name } +} + +private func varianceNormalizedValueGroupSize(valueHeadDim: Int) -> Int? { + resolvedKVQuantizationGroupSize( + requested: min(128, max(32, valueHeadDim)), + keyHeadDim: valueHeadDim, + valueHeadDim: valueHeadDim + ) +} + +func supportsVarianceNormalizedKVCache( + keyHeadDim: Int, + valueHeadDim: Int, + tileSize: Int +) -> Bool { + [32, 64, 128].contains(tileSize) + && keyHeadDim > 0 + && valueHeadDim > 0 + && isPowerOfTwo(keyHeadDim) + && isPowerOfTwo(valueHeadDim) + && varianceNormalizedValueGroupSize(valueHeadDim: valueHeadDim) != nil +} + +extension KVCacheSimple { + /// Convert to a variance-normalized tile cache. + public func toVarianceNormalized( + tileSize: Int = 128, + keyBits: Int = 4, + valueBits: Int = 2, + sinkhornIterations: Int = 8 + ) -> VarianceNormalizedKVCache { + let cache = VarianceNormalizedKVCache( + tileSize: tileSize, + keyBits: keyBits, + valueBits: valueBits, + sinkhornIterations: sinkhornIterations) + + if let keys = self.keys, let values = self.values { + let currentKeys = keys[.ellipsis, .. [MLXArray] { + state + } + + private func rotate(_ x: MLXArray) -> MLXArray { + let dimensions = x.dim(-1) + guard x.size > 0, isPowerOfTwo(dimensions) else { return x } + return hadamardTransform(x) + } + + private func inverseRotate(_ x: MLXArray) -> MLXArray { + // Sylvester Hadamard is symmetric and orthonormal, so the inverse is itself. + rotate(x) + } + + private func balanced( + original: MLXArray, + columnScales: MLXArray, + rowScales: MLXArray + ) -> MLXArray { + original / columnScales / rowScales + } + + private func clippedStd(_ x: MLXArray, axis: Int) -> MLXArray { + clip( + maximum( + std(x, axis: axis, keepDims: true, ddof: 1), + MLXArray(varianceNormalizationEpsilon)), + min: MLXArray(varianceNormalizationMinimumStandardDeviation), + max: MLXArray(varianceNormalizationMaximumStandardDeviation)) + } + + private func varianceImbalance(_ x: MLXArray) -> MLXArray { + let columnStd = std(x, axis: -2, keepDims: true, ddof: 1) + let rowStd = std(x, axis: -1, keepDims: true, ddof: 1) + let columnSpread = + columnStd.max(axis: -1, keepDims: true) + / maximum( + columnStd.min(axis: -1, keepDims: true), + MLXArray(varianceNormalizationEpsilon)) + let rowSpread = + rowStd.max(axis: -2, keepDims: true) + / maximum( + rowStd.min(axis: -2, keepDims: true), + MLXArray(varianceNormalizationEpsilon)) + return columnSpread + rowSpread + } + + private func varianceNormalize(_ tile: MLXArray) -> (MLXArray, MLXArray, MLXArray) { + let original = tile.asType(.float32) + var logColumnScales = MLXArray.zeros( + std(original, axis: -2, keepDims: true, ddof: 1).shape) + var logRowScales = MLXArray.zeros( + std(original, axis: -1, keepDims: true, ddof: 1).shape) + var columnScales = exp(logColumnScales) + var rowScales = exp(logRowScales) + var balancedTile = original + var bestColumnScales = columnScales + var bestRowScales = rowScales + var bestImbalance = varianceImbalance(balancedTile) + + for _ in 0 ..< sinkhornIterations { + logColumnScales = clip( + logColumnScales + log(clippedStd(balancedTile, axis: -2)), + min: MLXArray(varianceNormalizationMinimumLogScale), + max: MLXArray(varianceNormalizationMaximumLogScale)) + columnScales = exp(logColumnScales) + balancedTile = balanced( + original: original, columnScales: columnScales, rowScales: rowScales) + + logRowScales = clip( + logRowScales + log(clippedStd(balancedTile, axis: -1)), + min: MLXArray(varianceNormalizationMinimumLogScale), + max: MLXArray(varianceNormalizationMaximumLogScale)) + rowScales = exp(logRowScales) + balancedTile = balanced( + original: original, columnScales: columnScales, rowScales: rowScales) + + let imbalance = varianceImbalance(balancedTile) + let useCandidate = imbalance .<= bestImbalance + bestColumnScales = MLX.where(useCandidate, columnScales, bestColumnScales) + bestRowScales = MLX.where(useCandidate, rowScales, bestRowScales) + bestImbalance = MLX.where(useCandidate, imbalance, bestImbalance) + } + + return ( + balanced(original: original, columnScales: bestColumnScales, rowScales: bestRowScales), + bestColumnScales, + bestRowScales + ) + } + + private func quantizeBalanced(_ balanced: MLXArray, groupSize: Int, bits: Int) -> ( + MLXArray, MLXArray, MLXArray + ) { + let quantized = quantized(balanced, groupSize: groupSize, bits: bits, mode: .affine) + return ( + quantized.wq, + quantized.scales, + quantized.biases + ?? MLXArray.zeros(quantized.scales.shape, dtype: quantized.scales.dtype) + ) + } + + private func compactAuxiliary(_ array: MLXArray) -> MLXArray { + // The reference cache stores all auxiliary scales in FP16. Clamp before narrowing so a + // pathological BF16/FP32 activation cannot serialize an infinity into persistent state. + clip(array, min: MLXArray(-65_504), max: MLXArray(65_504)).asType(.float16) + } + + /// Compress one or more complete tiles for a bounded group of KV heads. The tile axis is + /// retained at index 2 so a prefill can be installed directly as immutable slabs. + private func compressedHeadBatch( + rotatedKeys: MLXArray, rotatedValues: MLXArray + ) -> VarianceNormalizedKVTile { + let tileCount = rotatedKeys.dim(2) / tileSize + precondition(tileCount > 0 && rotatedKeys.dim(2).isMultiple(of: tileSize)) + + let keyTile = rotatedKeys.reshaped([ + rotatedKeys.dim(0), rotatedKeys.dim(1), tileCount, tileSize, rotatedKeys.dim(3), + ]).transposed(0, 1, 2, 4, 3) + let (balancedKeys, keyColumnScales, keyRowScales) = varianceNormalize(keyTile) + let (keyWeight, keyScales, keyBiases) = quantizeBalanced( + balancedKeys, groupSize: tileSize, bits: keyBits) + let fusedKeyScales = compactAuxiliary(keyScales * keyRowScales) + let fusedKeyBiases = compactAuxiliary(keyBiases * keyRowScales) + + let valueTiles = rotatedValues.reshaped([ + rotatedValues.dim(0), rotatedValues.dim(1), tileCount, tileSize, + rotatedValues.dim(3), + ]) + let valueGroupSize = validatedValueGroupSize(rotatedValues.dim(3)) + let (balancedValues, valueColumnScales, valueRowScales) = varianceNormalize(valueTiles) + let (valueWeight, valueScales, valueBiases) = quantizeBalanced( + balancedValues, groupSize: valueGroupSize, bits: valueBits) + let fusedValueScales = compactAuxiliary(valueScales * valueRowScales) + let fusedValueBiases = compactAuxiliary(valueBiases * valueRowScales) + + return VarianceNormalizedKVTile( + keyWeight: keyWeight, + keyScales: fusedKeyScales, + keyBiases: fusedKeyBiases, + keyColumnScales: compactAuxiliary(keyColumnScales), + valueWeight: valueWeight, + valueScales: fusedValueScales, + valueBiases: fusedValueBiases, + valueColumnScales: compactAuxiliary(valueColumnScales) + ) + } + + /// Compress complete tiles while bounding the FP32 normalization workspace. Variance + /// normalization is independent across KV heads, so realizing four heads at a time preserves + /// the exact algorithm and 32-tile batching without making all model heads live at once. + private func compressedBatch( + rotatedKeys: MLXArray, rotatedValues: MLXArray + ) -> VarianceNormalizedKVTile { + precondition(rotatedKeys.dim(1) == rotatedValues.dim(1)) + guard rotatedKeys.dim(1) > Self.compressionBatchHeadCount else { + return compressedHeadBatch(rotatedKeys: rotatedKeys, rotatedValues: rotatedValues) + } + + var headRecords: [VarianceNormalizedKVTile] = [] + for start in stride( + from: 0, to: rotatedKeys.dim(1), by: Self.compressionBatchHeadCount) + { + let end = min(start + Self.compressionBatchHeadCount, rotatedKeys.dim(1)) + let record = compressedHeadBatch( + rotatedKeys: rotatedKeys[0..., start ..< end, 0..., 0...], + rotatedValues: rotatedValues[0..., start ..< end, 0..., 0...]) + evaluate(record) + headRecords.append(record) + } + + let merged = VarianceNormalizedKVTile( + keyWeight: contiguous(concatenated(headRecords.map(\.keyWeight), axis: 1)), + keyScales: contiguous(concatenated(headRecords.map(\.keyScales), axis: 1)), + keyBiases: contiguous(concatenated(headRecords.map(\.keyBiases), axis: 1)), + keyColumnScales: contiguous( + concatenated(headRecords.map(\.keyColumnScales), axis: 1)), + valueWeight: contiguous(concatenated(headRecords.map(\.valueWeight), axis: 1)), + valueScales: contiguous(concatenated(headRecords.map(\.valueScales), axis: 1)), + valueBiases: contiguous(concatenated(headRecords.map(\.valueBiases), axis: 1)), + valueColumnScales: contiguous( + concatenated(headRecords.map(\.valueColumnScales), axis: 1)) + ) + evaluate(merged) + return merged + } + + private func tileView( + _ records: VarianceNormalizedKVTile, index: Int + ) -> VarianceNormalizedKVTile { + return VarianceNormalizedKVTile( + keyWeight: records.keyWeight[0..., 0..., index, 0..., 0...], + keyScales: records.keyScales[0..., 0..., index, 0..., 0...], + keyBiases: records.keyBiases[0..., 0..., index, 0..., 0...], + keyColumnScales: records.keyColumnScales[0..., 0..., index, 0..., 0...], + valueWeight: records.valueWeight[0..., 0..., index, 0..., 0...], + valueScales: records.valueScales[0..., 0..., index, 0..., 0...], + valueBiases: records.valueBiases[0..., 0..., index, 0..., 0...], + valueColumnScales: records.valueColumnScales[0..., 0..., index, 0..., 0...] + ) + } + + private func evaluate(_ tile: VarianceNormalizedKVTile) { + eval([ + tile.keyWeight, tile.keyScales, tile.keyBiases, tile.keyColumnScales, + tile.valueWeight, tile.valueScales, tile.valueBiases, tile.valueColumnScales, + ]) + } + + private func byteCount(_ tile: VarianceNormalizedKVTile) -> Int { + tile.keyWeight.nbytes + tile.keyScales.nbytes + tile.keyBiases.nbytes + + tile.keyColumnScales.nbytes + tile.valueWeight.nbytes + + tile.valueScales.nbytes + tile.valueBiases.nbytes + + tile.valueColumnScales.nbytes + } + + /// Physical compact-record bytes retained by this cache, excluding the raw tail. Slabs have + /// no spare capacity, and pending views share an exactly-sized backing batch. + var compactStorageByteCount: Int { + tileSlabs.reduce(0) { $0 + byteCount($1.records) } + + pendingTiles.reduce(0) { $0 + byteCount($1) } + } + + var attentionPartitionCount: Int { + tileSlabs.count + pendingTiles.count + } + + private func stackedRecords(_ tiles: [VarianceNormalizedKVTile]) -> VarianceNormalizedKVTile { + precondition(!tiles.isEmpty) + return VarianceNormalizedKVTile( + keyWeight: stacked(tiles.map(\.keyWeight), axis: 2), + keyScales: stacked(tiles.map(\.keyScales), axis: 2), + keyBiases: stacked(tiles.map(\.keyBiases), axis: 2), + keyColumnScales: stacked(tiles.map(\.keyColumnScales), axis: 2), + valueWeight: stacked(tiles.map(\.valueWeight), axis: 2), + valueScales: stacked(tiles.map(\.valueScales), axis: 2), + valueBiases: stacked(tiles.map(\.valueBiases), axis: 2), + valueColumnScales: stacked(tiles.map(\.valueColumnScales), axis: 2) + ) + } + + private var completedTileCount: Int { + tileSlabs.reduce(pendingTiles.count) { $0 + $1.count } + } + + private func appendSlab(_ records: VarianceNormalizedKVTile, count: Int) { + tileSlabs.append(VarianceNormalizedKVSlab(records: records, count: count)) + + // Immutable tiered compaction: eight equal adjacent slabs become one larger slab. Each + // record is copied only at exponentially spaced boundaries (4, 32, 256 tiles...), while + // attention sees at most seven slabs per level instead of one dispatch per page. + while tileSlabs.count >= Self.slabFanout { + let suffix = Array(tileSlabs.suffix(Self.slabFanout)) + guard let first = suffix.first, suffix.allSatisfy({ $0.count == first.count }) else { + break + } + let records = suffix.map(\.records) + let merged = VarianceNormalizedKVTile( + keyWeight: contiguous(concatenated(records.map(\.keyWeight), axis: 2)), + keyScales: contiguous(concatenated(records.map(\.keyScales), axis: 2)), + keyBiases: contiguous(concatenated(records.map(\.keyBiases), axis: 2)), + keyColumnScales: contiguous( + concatenated(records.map(\.keyColumnScales), axis: 2)), + valueWeight: contiguous(concatenated(records.map(\.valueWeight), axis: 2)), + valueScales: contiguous(concatenated(records.map(\.valueScales), axis: 2)), + valueBiases: contiguous(concatenated(records.map(\.valueBiases), axis: 2)), + valueColumnScales: contiguous( + concatenated(records.map(\.valueColumnScales), axis: 2)) + ) + evaluate(merged) + tileSlabs.removeLast(Self.slabFanout) + tileSlabs.append( + VarianceNormalizedKVSlab( + records: merged, count: first.count * Self.slabFanout)) + } + } + + private func appendCompressedBatch(_ records: VarianceNormalizedKVTile, count: Int) { + precondition(count > 0 && records.keyWeight.dim(2) == count) + var index = 0 + + while !pendingTiles.isEmpty && index < count { + pendingTiles.append(tileView(records, index: index)) + index += 1 + if pendingTiles.count == Self.baseSlabTileCount { + let slabRecords = stackedRecords(pendingTiles) + evaluate(slabRecords) + appendSlab(slabRecords, count: Self.baseSlabTileCount) + pendingTiles.removeAll(keepingCapacity: true) + } + } + + while index + Self.baseSlabTileCount <= count { + let end = index + Self.baseSlabTileCount + let slabRecords = contiguousRecords(records, range: index ..< end) + evaluate(slabRecords) + appendSlab(slabRecords, count: Self.baseSlabTileCount) + index = end + } + + if index < count { + let pendingRecords = contiguousRecords(records, range: index ..< count) + evaluate(pendingRecords) + pendingTiles.append( + contentsOf: (0 ..< count - index).map { + tileView(pendingRecords, index: $0) + }) + } + } + + private func contiguousRecords( + _ records: VarianceNormalizedKVTile, range: Range + ) -> VarianceNormalizedKVTile { + VarianceNormalizedKVTile( + keyWeight: contiguous(records.keyWeight[0..., 0..., range, 0..., 0...]), + keyScales: contiguous(records.keyScales[0..., 0..., range, 0..., 0...]), + keyBiases: contiguous(records.keyBiases[0..., 0..., range, 0..., 0...]), + keyColumnScales: contiguous( + records.keyColumnScales[0..., 0..., range, 0..., 0...]), + valueWeight: contiguous(records.valueWeight[0..., 0..., range, 0..., 0...]), + valueScales: contiguous(records.valueScales[0..., 0..., range, 0..., 0...]), + valueBiases: contiguous(records.valueBiases[0..., 0..., range, 0..., 0...]), + valueColumnScales: contiguous( + records.valueColumnScales[0..., 0..., range, 0..., 0...]) + ) + } + + private func allTiles() -> [VarianceNormalizedKVTile] { + tileSlabs.flatMap { slab in + (0 ..< slab.count).map { tileView(slab.records, index: $0) } + } + pendingTiles + } + + private func installTiles(_ tiles: [VarianceNormalizedKVTile]) { + tileSlabs.removeAll(keepingCapacity: true) + pendingTiles.removeAll(keepingCapacity: true) + var index = 0 + while index + Self.baseSlabTileCount <= tiles.count { + let records = stackedRecords(Array(tiles[index ..< index + Self.baseSlabTileCount])) + evaluate(records) + appendSlab(records, count: Self.baseSlabTileCount) + index += Self.baseSlabTileCount + } + pendingTiles.append(contentsOf: tiles[index...]) + } + + private func reconstructedRotated( + _ tile: VarianceNormalizedKVTile + ) -> (MLXArray, MLXArray) { + let scaledKeys = dequantized( + tile.keyWeight, + scales: tile.keyScales.asType(.float32), + biases: tile.keyBiases.asType(.float32), + groupSize: tileSize, bits: keyBits, mode: .affine) + let rotatedKeys = (scaledKeys * tile.keyColumnScales.asType(.float32)) + .transposed(0, 1, 3, 2) + + let valueHeadDim = tile.valueColumnScales.dim(-1) + let valueGroupSize = validatedValueGroupSize(valueHeadDim) + let scaledValues = dequantized( + tile.valueWeight, + scales: tile.valueScales.asType(.float32), + biases: tile.valueBiases.asType(.float32), + groupSize: valueGroupSize, bits: valueBits, mode: .affine) + let rotatedValues = scaledValues * tile.valueColumnScales.asType(.float32) + + return ( + rotatedKeys.asType(keyDType ?? .float32), + rotatedValues.asType(valueDType ?? .float32) + ) + } + + private func reconstructed(_ tile: VarianceNormalizedKVTile) -> (MLXArray, MLXArray) { + let (rotatedKeys, rotatedValues) = reconstructedRotated(tile) + return (inverseRotate(rotatedKeys), inverseRotate(rotatedValues)) + } + + private func reconstructedParts() -> [(keys: MLXArray, values: MLXArray)] { + var parts: [(keys: MLXArray, values: MLXArray)] = [] + for tile in allTiles() { + let (keys, values) = reconstructed(tile) + parts.append((keys, values)) + } + + if let tailKeys, let tailValues { + parts.append((inverseRotate(tailKeys), inverseRotate(tailValues))) + } + return parts + } + + private func materializedState() -> (MLXArray, MLXArray)? { + let parts = reconstructedParts() + let keyParts = parts.map { $0.keys } + let valueParts = parts.map { $0.values } + + guard !keyParts.isEmpty else { return nil } + return (concatenated(keyParts, axis: 2), concatenated(valueParts, axis: 2)) + } + + private func validatedValueGroupSize(_ valueHeadDim: Int) -> Int { + guard let groupSize = varianceNormalizedValueGroupSize(valueHeadDim: valueHeadDim) else { + fatalError( + "VarianceNormalizedKVCache requires value head dimension \(valueHeadDim) to be compatible with MLX quantization group sizes 32, 64, or 128." + ) + } + return groupSize + } + + private func quantizedTileScores( + rotatedQueries: MLXArray, + tile: VarianceNormalizedKVTile, + scale: Float + ) -> MLXArray { + let (batchSize, queryHeadCount, queryLength, headDim) = ( + rotatedQueries.dim(0), rotatedQueries.dim(1), rotatedQueries.dim(2), + rotatedQueries.dim(3) + ) + let kvHeadCount = tile.keyWeight.dim(1) + let repeats = queryHeadCount / kvHeadCount + + if repeats > 1 { + let groupedQueries = rotatedQueries.reshaped([ + batchSize, kvHeadCount, repeats, queryLength, headDim, + ]) + let scores = + quantizedMM( + groupedQueries, + expandedDimensions(tile.keyWeight, axis: -3), + scales: expandedDimensions(tile.keyScales, axis: -3), + biases: expandedDimensions(tile.keyBiases, axis: -3), + transpose: false, + groupSize: tileSize, + bits: keyBits, + mode: .affine + ) * expandedDimensions(tile.keyColumnScales, axis: -3) * scale + return scores.reshaped(batchSize, queryHeadCount, queryLength, tileSize) + } else { + return quantizedMM( + rotatedQueries, + tile.keyWeight, + scales: tile.keyScales, + biases: tile.keyBiases, + transpose: false, + groupSize: tileSize, + bits: keyBits, + mode: .affine + ) * tile.keyColumnScales * scale + } + } + + private func quantizedTileValues( + weights: MLXArray, + tile: VarianceNormalizedKVTile, + queryHeadCount: Int + ) -> MLXArray { + let (batchSize, _, queryLength, keyLength) = ( + weights.dim(0), weights.dim(1), weights.dim(2), weights.dim(3) + ) + let kvHeadCount = tile.valueWeight.dim(1) + let repeats = queryHeadCount / kvHeadCount + let groupSize = validatedValueGroupSize(tile.valueColumnScales.dim(-1)) + + if repeats > 1 { + let groupedWeights = weights.reshaped([ + batchSize, kvHeadCount, repeats, queryLength, keyLength, + ]) + let output = + quantizedMM( + groupedWeights, + expandedDimensions(tile.valueWeight, axis: -3), + scales: expandedDimensions(tile.valueScales, axis: -3), + biases: expandedDimensions(tile.valueBiases, axis: -3), + transpose: false, + groupSize: groupSize, + bits: valueBits, + mode: .affine + ) * expandedDimensions(tile.valueColumnScales, axis: -3) + return output.reshaped( + batchSize, queryHeadCount, queryLength, tile.valueColumnScales.dim(-1)) + } else { + return quantizedMM( + weights, + tile.valueWeight, + scales: tile.valueScales, + biases: tile.valueBiases, + transpose: false, + groupSize: groupSize, + bits: valueBits, + mode: .affine + ) * tile.valueColumnScales + } + } + + private func stackedTileScores( + rotatedQueries: MLXArray, + records: VarianceNormalizedKVTile, + tileCount: Int, + scale: Float + ) -> MLXArray { + let (batchSize, queryHeadCount, queryLength, headDim) = ( + rotatedQueries.dim(0), rotatedQueries.dim(1), rotatedQueries.dim(2), + rotatedQueries.dim(3) + ) + let kvHeadCount = records.keyWeight.dim(1) + let repeats = queryHeadCount / kvHeadCount + let keyWeights = records.keyWeight + let keyScales = records.keyScales + let keyBiases = records.keyBiases + let keyColumnScales = records.keyColumnScales + + if repeats > 1 { + let groupedQueries = rotatedQueries.reshaped([ + batchSize, kvHeadCount, repeats, queryLength, headDim, + ]) + let scores = + quantizedMM( + expandedDimensions(groupedQueries, axis: 2), + expandedDimensions(keyWeights, axis: 3), + scales: expandedDimensions(keyScales, axis: 3), + biases: expandedDimensions(keyBiases, axis: 3), + transpose: false, + groupSize: tileSize, + bits: keyBits, + mode: .affine + ) * expandedDimensions(keyColumnScales, axis: 3) * scale + return + scores + .transposed(0, 1, 3, 4, 2, 5) + .reshaped(batchSize, queryHeadCount, queryLength, tileCount * tileSize) + } else { + let scores = + quantizedMM( + expandedDimensions(rotatedQueries, axis: 2), + keyWeights, + scales: keyScales, + biases: keyBiases, + transpose: false, + groupSize: tileSize, + bits: keyBits, + mode: .affine + ) * keyColumnScales * scale + return + scores + .transposed(0, 1, 3, 2, 4) + .reshaped(batchSize, queryHeadCount, queryLength, tileCount * tileSize) + } + } + + private func stackedTileValues( + weights: MLXArray, + records: VarianceNormalizedKVTile, + tileCount: Int, + queryHeadCount: Int + ) -> MLXArray { + let (batchSize, _, queryLength, _) = ( + weights.dim(0), weights.dim(1), weights.dim(2), weights.dim(3) + ) + let kvHeadCount = records.valueWeight.dim(1) + let repeats = queryHeadCount / kvHeadCount + let valueHeadDim = records.valueColumnScales.dim(-1) + let groupSize = validatedValueGroupSize(valueHeadDim) + let valueWeights = records.valueWeight + let valueScales = records.valueScales + let valueBiases = records.valueBiases + let valueColumnScales = records.valueColumnScales + + if repeats > 1 { + let groupedWeights = + weights + .reshaped([batchSize, kvHeadCount, repeats, queryLength, tileCount, tileSize]) + .transposed(0, 1, 4, 2, 3, 5) + let output = + quantizedMM( + groupedWeights, + expandedDimensions(valueWeights, axis: 3), + scales: expandedDimensions(valueScales, axis: 3), + biases: expandedDimensions(valueBiases, axis: 3), + transpose: false, + groupSize: groupSize, + bits: valueBits, + mode: .affine + ) * expandedDimensions(valueColumnScales, axis: 3) + return + output + .sum(axis: 2) + .reshaped(batchSize, queryHeadCount, queryLength, valueHeadDim) + } else { + let groupedWeights = + weights + .reshaped([batchSize, queryHeadCount, queryLength, tileCount, tileSize]) + .transposed(0, 1, 3, 2, 4) + let output = + quantizedMM( + groupedWeights, + valueWeights, + scales: valueScales, + biases: valueBiases, + transpose: false, + groupSize: groupSize, + bits: valueBits, + mode: .affine + ) * valueColumnScales + return output.sum(axis: 2) + } + } + + private func quantizedRotatedAttention( + queries: MLXArray, + scale: Float, + mask: MLXFast.ScaledDotProductAttentionMaskMode + ) -> MLXArray { + let rotatedQueries = rotate(queries) + var scoreParts = tileSlabs.map { slab in + stackedTileScores( + rotatedQueries: rotatedQueries, + records: slab.records, + tileCount: slab.count, + scale: scale) + } + scoreParts.append( + contentsOf: pendingTiles.map { tile in + quantizedTileScores(rotatedQueries: rotatedQueries, tile: tile, scale: scale) + }) + if let tailKeys { + scoreParts.append( + attentionScores(queries: rotatedQueries, keys: tailKeys, scale: scale)) + } + + let scores = applyAttentionMask(scores: concatenated(scoreParts, axis: -1), mask: mask) + // `precise` makes MLX compute the normalization in FP32 for half/bfloat inputs. This is + // particularly important once the score vector spans many compressed slabs. + let weights = softmax(scores, axis: -1, precise: true) + + var start = 0 + var rotatedOutputParts: [MLXArray] = [] + for slab in tileSlabs { + let end = start + slab.count * tileSize + rotatedOutputParts.append( + stackedTileValues( + weights: weights[.ellipsis, start ..< end], + records: slab.records, + tileCount: slab.count, + queryHeadCount: queries.dim(1))) + start = end + } + for tile in pendingTiles { + let end = start + tileSize + let tileWeights = weights[.ellipsis, start ..< end] + rotatedOutputParts.append( + quantizedTileValues( + weights: tileWeights, + tile: tile, + queryHeadCount: queries.dim(1))) + start = end + } + + if let tailValues { + let end = start + tailValues.dim(2) + let tailWeights = weights[.ellipsis, start ..< end] + rotatedOutputParts.append( + attentionValues( + weights: tailWeights, + values: tailValues, + queryHeadCount: queries.dim(1))) + } + + let rotatedOutput = rotatedOutputParts.dropFirst().reduce(rotatedOutputParts[0]) { + $0 + $1 + } + return inverseRotate(rotatedOutput).asType(queries.dtype) + } + + private func absorbTail() { + guard var keys = tailKeys, var values = tailValues else { return } + + while keys.dim(2) >= tileSize { + // Thirty-two tiles amortize both prefill and decode dispatch while bounding each + // FP32 normalization batch to 4,096 tokens at the default tile size. + let tileCount = min(Self.compressionBatchTileCount, keys.dim(2) / tileSize) + let length = tileCount * tileSize + let records = compressedBatch( + rotatedKeys: keys[.ellipsis, .. (MLXArray, MLXArray) { + append(keys: keys, values: values) + + // KVCache requires this materializing fallback for attention implementations that call + // update directly. The standard attentionWithCacheUpdate path uses updateAndAttend below + // and never reconstructs completed tiles during decode. + guard let state = materializedState() else { + return (keys, values) + } + return state + } + + public func updateAndAttend( + queries: MLXArray, + keys: MLXArray, + values: MLXArray, + scale: Float, + mask: MLXFast.ScaledDotProductAttentionMaskMode = .none + ) -> MLXArray { + append(keys: keys, values: values) + return quantizedRotatedAttention(queries: queries, scale: scale, mask: mask) + } + + public override var state: [MLXArray] { + get { + var arrays: [MLXArray] = [] + for tile in allTiles() { + arrays.append(contentsOf: [ + tile.keyWeight, tile.keyScales, tile.keyBiases, + tile.keyColumnScales, + tile.valueWeight, tile.valueScales, tile.valueBiases, + tile.valueColumnScales, + ]) + } + if let tailKeys, let tailValues { + arrays.append(tailKeys) + arrays.append(tailValues) + } + return arrays + } + set { + let tileCount = + restoredTileCount + ?? (newValue.count / Self.compactTileStateCount) + let tailStateCount = (restoredTailLength ?? 0) > 0 ? Self.tailStateCount : 0 + let tileStateCount = + if newValue.count - tailStateCount == tileCount * Self.legacyTileStateCount { + Self.legacyTileStateCount + } else { + Self.compactTileStateCount + } + var index = 0 + var restored: [VarianceNormalizedKVTile] = [] + for _ in 0 ..< tileCount { + guard index + tileStateCount - 1 < newValue.count else { + fatalError("VarianceNormalizedKVCache state is missing tile arrays") + } + if tileStateCount == Self.legacyTileStateCount { + restored.append( + VarianceNormalizedKVTile( + keyWeight: newValue[index], + keyScales: newValue[index + 1] * newValue[index + 4], + keyBiases: newValue[index + 2] * newValue[index + 4], + keyColumnScales: newValue[index + 3], + valueWeight: newValue[index + 5], + valueScales: newValue[index + 6] * newValue[index + 9], + valueBiases: newValue[index + 7] * newValue[index + 9], + valueColumnScales: newValue[index + 8] + )) + } else { + restored.append( + VarianceNormalizedKVTile( + keyWeight: newValue[index], + keyScales: newValue[index + 1], + keyBiases: newValue[index + 2], + keyColumnScales: newValue[index + 3], + valueWeight: newValue[index + 4], + valueScales: newValue[index + 5], + valueBiases: newValue[index + 6], + valueColumnScales: newValue[index + 7] + )) + } + index += tileStateCount + } + installTiles(restored) + + if (restoredTailLength ?? 0) > 0 { + guard index + 1 < newValue.count else { + fatalError("VarianceNormalizedKVCache state is missing tail arrays") + } + tailKeys = newValue[index] + tailValues = newValue[index + 1] + keyDType = tailKeys?.dtype + valueDType = tailValues?.dtype + } else { + tailKeys = nil + tailValues = nil + } + } + } + + public override var metaState: [String] { + get { + [ + String(tileSize), + String(offset), + String(keyBits), + String(valueBits), + String(sinkhornIterations), + String(completedTileCount), + String(tailKeys?.dim(2) ?? 0), + String(Self.metadataVersion), + varianceNormalizedDTypeName(keyDType), + varianceNormalizedDTypeName(valueDType), + ] + } + set { + guard newValue.count == 7 || newValue.count == 10 else { + fatalError("VarianceNormalizedKVCache metaState must have 7 or 10 values") + } + guard + let offset = Int(newValue[1]), + let tileCount = Int(newValue[5]), + let tailLength = Int(newValue[6]) + else { + fatalError("Failed to parse VarianceNormalizedKVCache metaState") + } + self.offset = offset + self.restoredTileCount = tileCount + self.restoredTailLength = tailLength + if newValue.count == 10 { + guard Int(newValue[7]) == Self.metadataVersion else { + fatalError("Unsupported VarianceNormalizedKVCache metadata version") + } + let restoredKeyDType = varianceNormalizedDType(named: newValue[8]) + let restoredValueDType = varianceNormalizedDType(named: newValue[9]) + guard + newValue[8] == "none" + || restoredKeyDType.map(isSupportedVarianceNormalizedDType) == true, + newValue[9] == "none" + || restoredValueDType.map(isSupportedVarianceNormalizedDType) == true + else { + fatalError("Invalid VarianceNormalizedKVCache dtype metadata") + } + keyDType = restoredKeyDType + valueDType = restoredValueDType + } else { + keyDType = nil + valueDType = nil + } + } + } + + public override var isTrimmable: Bool { true } + + public override func isTrimmable(after positions: Int) -> Bool { + guard positions >= 0 else { return false } + let tailLength = tailKeys?.dim(2) ?? 0 + // A staged round that crosses a tile boundary would quantize some provisional rows. + // Trimming back into that tile reconstructs them approximately, so it is not the exact + // rollback required by KVCacheRound. Refuse that round and let generation fall back to + // the non-speculative path; rounds wholly inside the raw tail remain exactly rewindable. + return tailLength + positions < tileSize + } + + @discardableResult + public override func trim(_ n: Int) -> Int { + guard n > 0 else { return 0 } + let trimmed = min(offset, n) + guard trimmed > 0 else { return 0 } + + let remaining = offset - trimmed + let retainedTileCount = remaining / tileSize + let retainedTailLength = remaining % tileSize + + if retainedTailLength == 0 { + tailKeys = nil + tailValues = nil + } else if retainedTileCount < completedTileCount { + let (rotatedKeys, rotatedValues) = reconstructedRotated(allTiles()[retainedTileCount]) + tailKeys = rotatedKeys[.ellipsis, .. any KVCache { + let new = VarianceNormalizedKVCache( + tileSize: tileSize, keyBits: keyBits, valueBits: valueBits, + sinkhornIterations: sinkhornIterations) + new.metaState = metaState + let s = state + if !s.isEmpty { + new.state = s.map { $0[.ellipsis] } + } + return new + } + + public var debugDescription: String { + "\(String(describing: Self.self)) offset: \(offset), tileSize: \(tileSize), keyBits: \(keyBits), valueBits: \(valueBits), tiles: \(completedTileCount), slabs: \(tileSlabs.count), pending: \(pendingTiles.count), tail: \(tailKeys?.shape.description ?? "-")" + } +} + +/// Resolve a legacy `kvScheme` string for variance-normalized compression. +/// +/// Supported schemes: +/// - `"varn"` / `"varn4v2"`: 4-bit keys, 2-bit values, 128-token tiles +/// - `"varn4"` / `"varn4v4"`: 4-bit keys and values +/// - `"varn2"` / `"varn2v2"`: 2-bit keys and values +/// - `"varn4v2t32"` / `"varn4v2t64"` / `"varn4v2t128"`: explicit tile size +public func resolveVarianceNormalizedScheme( + _ scheme: String? +) -> (keyBits: Int, valueBits: Int, tileSize: Int, sinkhornIterations: Int)? { + guard let scheme else { return nil } + + switch scheme { + case "varn", "varn4v2": + return (4, 2, 128, 8) + case "varn4", "varn4v4": + return (4, 4, 128, 8) + case "varn2", "varn2v2": + return (2, 2, 128, 8) + case "varn4v2t32": + return (4, 2, 32, 8) + case "varn4v2t64": + return (4, 2, 64, 8) + case "varn4v2t128": + return (4, 2, 128, 8) + case "varn4v4t32": + return (4, 4, 32, 8) + default: + return nil + } +} diff --git a/Tests/MLXLMTests/EvalTests.swift b/Tests/MLXLMTests/EvalTests.swift index 8d8e4e567e..80850e3902 100644 --- a/Tests/MLXLMTests/EvalTests.swift +++ b/Tests/MLXLMTests/EvalTests.swift @@ -10,6 +10,151 @@ import XCTest public class EvalTests: XCTestCase { + private enum TestKVCacheMode: String { + case fp16 + case affine4 + case varianceNormalized4Value2 + + var parameters: GenerateParameters { + switch self { + case .fp16: + GenerateParameters(temperature: 0) + case .affine4: + GenerateParameters( + kvBits: 4, + kvGroupSize: 32, + quantizedKVStart: 0, + temperature: 0) + case .varianceNormalized4Value2: + // Prefer typed configuration once rebased on main's cache plan API. + GenerateParameters( + kvCache: .init( + strategy: .varianceNormalized( + try! .init( + keyBits: 4, valueBits: 2, tileSize: 32, sinkhornIterations: 4)), + compatibility: .allowPartial), + temperature: 0) + } + } + } + + private struct DecodeResult { + var tokens: [Int] + var cacheBytes: Int + var elapsed: TimeInterval + + var tokensPerSecond: Double { + Double(tokens.count) / elapsed + } + } + + private func makeQualityGateLlamaModel(seed: UInt64 = 11) -> LlamaModel { + withRandomState(MLXRandom.RandomState(seed: seed)) { + let config = LlamaConfiguration( + hiddenSize: 64, hiddenLayers: 2, intermediateSize: 128, attentionHeads: 2, + rmsNormEps: 0.00001, vocabularySize: 100, kvHeads: 1) + let model = LlamaModel(config) + eval(model) + return model + } + } + + private func applyDynamicKVQuantization(cache: inout [KVCache], mode: TestKVCacheMode) throws { + if let configuration = mode.parameters.kvCache { + _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) + return + } + maybeQuantizeKVCache( + cache: &cache, + kvBits: mode.parameters.kvBits, + kvGroupSize: mode.parameters.kvGroupSize, + quantizedKVStart: mode.parameters.quantizedKVStart, + kvScheme: mode.parameters.kvScheme) + } + + private func cacheBytes(_ cache: [KVCache]) -> Int { + let arrays = cache.flatMap { $0.state } + if !arrays.isEmpty { + eval(arrays) + } + return arrays.reduce(0) { $0 + $1.nbytes } + } + + private func nextToken( + model: LlamaModel, + token: Int, + cache: [KVCache] + ) -> Int { + let input = MLXArray([token])[.newAxis, .ellipsis] + let logits = model.callAsFunction(input, cache: cache) + let next = argMax(logits[0..., -1, 0...], axis: -1) + eval(next) + return next.item(Int.self) + } + + private func generateTokens( + model: LlamaModel, + prompt: [Int], + maxTokens: Int, + mode: TestKVCacheMode + ) throws -> DecodeResult { + var cache = try model.newCache(parameters: nil) + let start = Date.timeIntervalSinceReferenceDate + let promptLogits = model.callAsFunction(MLXArray(prompt)[.newAxis, .ellipsis], cache: cache) + eval(promptLogits) + try applyDynamicKVQuantization(cache: &cache, mode: mode) + + var previous = argMax(promptLogits[0..., -1, 0...], axis: -1).item(Int.self) + var generated: [Int] = [] + generated.reserveCapacity(maxTokens) + + for _ in 0 ..< maxTokens { + generated.append(previous) + previous = nextToken(model: model, token: previous, cache: cache) + try applyDynamicKVQuantization(cache: &cache, mode: mode) + } + + return DecodeResult( + tokens: generated, + cacheBytes: cacheBytes(cache), + elapsed: Date.timeIntervalSinceReferenceDate - start) + } + + private func autoregressiveCrossEntropy( + model: LlamaModel, + sequence: [Int], + mode: TestKVCacheMode + ) throws -> Float { + precondition(sequence.count > 1) + var cache = try model.newCache(parameters: nil) + var loss: Float = 0 + + for i in 0 ..< sequence.count - 1 { + let input = MLXArray([sequence[i]])[.newAxis, .ellipsis] + let target = MLXArray([sequence[i + 1]])[.newAxis, .ellipsis] + let logits = model.callAsFunction(input, cache: cache) + let tokenLoss = mean(crossEntropy(logits: logits, targets: target)) + eval(tokenLoss) + loss += tokenLoss.item(Float.self) + try applyDynamicKVQuantization(cache: &cache, mode: mode) + } + + return loss / Float(sequence.count - 1) + } + + private func tokenAgreement(_ lhs: [Int], _ rhs: [Int]) -> Float { + precondition(lhs.count == rhs.count) + let matches = zip(lhs, rhs).filter { $0 == $1 }.count + return Float(matches) / Float(lhs.count) + } + + private func firstTokenMismatch(_ lhs: [Int], _ rhs: [Int]) -> String { + for (index, pair) in zip(lhs, rhs).enumerated() where pair.0 != pair.1 { + return "index \(index): \(pair.0) != \(pair.1)" + } + return "none" + } + func testLlamaEval() throws { let config = LlamaConfiguration( hiddenSize: 64, hiddenLayers: 16, intermediateSize: 512, attentionHeads: 32, @@ -23,6 +168,171 @@ public class EvalTests: XCTestCase { XCTAssertEqual(output.shape, [1, 5, 100]) } + func testLlamaVarianceNormalizedKVCacheGenerationPath() throws { + let config = LlamaConfiguration( + hiddenSize: 64, hiddenLayers: 2, intermediateSize: 128, attentionHeads: 2, + rmsNormEps: 0.00001, vocabularySize: 100, kvHeads: 1) + let model = LlamaModel(config) + let parameters = GenerateParameters( + kvCache: .init( + strategy: .varianceNormalized( + try .init(keyBits: 4, valueBits: 4, tileSize: 32, sinkhornIterations: 4)), + compatibility: .allowPartial), + temperature: 0) + + var cache = try model.newCache(parameters: parameters) + XCTAssertTrue(cache.allSatisfy { $0 is KVCacheSimple }) + + let prompt = MLXArray([1, 2, 3, 4])[.newAxis, .ellipsis] + let output = model.callAsFunction(prompt, cache: cache) + eval(output) + XCTAssertEqual(output.shape, [1, 4, 100]) + + let configuration = try XCTUnwrap(parameters.kvCache) + _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) + XCTAssertTrue(cache.allSatisfy { $0 is VarianceNormalizedKVCache }) + + let next = MLXArray([5])[.newAxis, .ellipsis] + let nextOutput = model.callAsFunction(next, cache: cache) + eval(nextOutput) + XCTAssertEqual(nextOutput.shape, [1, 1, 100]) + } + + func testLlamaVarianceNormalizedKVCacheAutoregressivePerplexityTracksBaselines() throws { + let model = makeQualityGateLlamaModel() + let sequence = (0 ..< 128).map { (($0 * 37 + 11) % 99) + 1 } + + let fp16Loss = try autoregressiveCrossEntropy(model: model, sequence: sequence, mode: .fp16) + let affineLoss = try autoregressiveCrossEntropy( + model: model, sequence: sequence, mode: .affine4) + let varianceNormalizedLoss = try autoregressiveCrossEntropy( + model: model, sequence: sequence, mode: .varianceNormalized4Value2) + + let affineDrift = abs(affineLoss - fp16Loss) + let varianceNormalizedDrift = abs(varianceNormalizedLoss - fp16Loss) + print( + "KV perplexity gate: fp16=\(fp16Loss), affine4=\(affineLoss), " + + "varianceNormalized4/value2=\(varianceNormalizedLoss)" + ) + + XCTAssertLessThan(affineDrift, 0.20) + XCTAssertLessThan(varianceNormalizedDrift, 0.20) + } + + func testLlamaVarianceNormalizedKVCacheGreedyDecodeTracksFP16ForOneHundredTokens() throws { + let model = makeQualityGateLlamaModel() + let prompt = [1, 7, 13, 29, 31, 43, 59, 61] + let fp16 = try generateTokens(model: model, prompt: prompt, maxTokens: 100, mode: .fp16) + let affine = try generateTokens( + model: model, prompt: prompt, maxTokens: 100, mode: .affine4) + let varianceNormalized = try generateTokens( + model: model, prompt: prompt, maxTokens: 100, mode: .varianceNormalized4Value2) + + let affineAgreement = tokenAgreement(affine.tokens, fp16.tokens) + let varianceNormalizedAgreement = tokenAgreement(varianceNormalized.tokens, fp16.tokens) + print( + "KV token agreement: affine4=\(affineAgreement) " + + "(first mismatch: \(firstTokenMismatch(affine.tokens, fp16.tokens))), " + + "varianceNormalized4/value2=\(varianceNormalizedAgreement) " + + "(first mismatch: \(firstTokenMismatch(varianceNormalized.tokens, fp16.tokens)))" + ) + + XCTAssertGreaterThanOrEqual(affineAgreement, 0.95) + XCTAssertGreaterThanOrEqual(varianceNormalizedAgreement, 0.95) + } + + func testLlamaVarianceNormalizedKVCacheAppleSiliconDecodePerformanceSmoke() throws { + #if os(macOS) && arch(arm64) + let model = makeQualityGateLlamaModel() + let prompt = [3, 5, 8, 13, 21, 34, 55, 89] + + _ = try generateTokens(model: model, prompt: prompt, maxTokens: 16, mode: .fp16) + _ = try generateTokens(model: model, prompt: prompt, maxTokens: 16, mode: .affine4) + _ = try generateTokens( + model: model, prompt: prompt, maxTokens: 16, mode: .varianceNormalized4Value2) + + let fp16 = try generateTokens(model: model, prompt: prompt, maxTokens: 96, mode: .fp16) + let affine = try generateTokens(model: model, prompt: prompt, maxTokens: 96, mode: .affine4) + let varianceNormalized = try generateTokens( + model: model, prompt: prompt, maxTokens: 96, mode: .varianceNormalized4Value2) + + print( + "KV decode smoke: fp16=\(fp16.tokensPerSecond) tok/s " + + "(\(fp16.cacheBytes) bytes), affine4=\(affine.tokensPerSecond) tok/s " + + "(\(affine.cacheBytes) bytes), varianceNormalized4/value2=" + + "\(varianceNormalized.tokensPerSecond) tok/s " + + "(\(varianceNormalized.cacheBytes) bytes)" + ) + + XCTAssertGreaterThan(fp16.tokensPerSecond, 0) + XCTAssertGreaterThan(affine.tokensPerSecond, 0) + XCTAssertGreaterThan(varianceNormalized.tokensPerSecond, 0) + XCTAssertLessThan(affine.cacheBytes, fp16.cacheBytes) + XCTAssertLessThan(varianceNormalized.cacheBytes, fp16.cacheBytes) + + // This is a smoke threshold for Apple Silicon CI variance, not a benchmark claim. + XCTAssertLessThan(varianceNormalized.elapsed, fp16.elapsed * 10) + XCTAssertLessThan(varianceNormalized.elapsed, affine.elapsed * 10) + #else + throw XCTSkip("Apple Silicon decode performance smoke test requires arm64 macOS.") + #endif + } + + func testVarianceNormalizedKVCache32KIngestAndDecodePeakMetalMemorySmoke() throws { + #if os(macOS) && arch(arm64) + let tokenCount = 32_768 + let cache = VarianceNormalizedKVCache( + tileSize: 128, keyBits: 4, valueBits: 2, sinkhornIterations: 8) + // Qwen3-4B-like grouped-query attention exercises the bounded four-KV-head + // normalization batches instead of measuring only the unsplit four-head path. + let queries = MLXRandom.normal([1, 32, 1, 128]).asType(.float16) + let keys = MLXRandom.normal([1, 8, tokenCount, 128]).asType(.float16) + let values = MLXRandom.normal([1, 8, tokenCount, 128]).asType(.float16) + eval(queries, keys, values) + Memory.clearCache() + let baselineActiveMemory = Memory.activeMemory + Memory.peakMemory = 0 + + let start = Date.timeIntervalSinceReferenceDate + let output = cache.updateAndAttend( + queries: queries, + keys: keys, + values: values, + scale: 1 / sqrt(Float(128))) + eval(output) + let elapsed = Date.timeIntervalSinceReferenceDate - start + let peakWorkspaceBytes = max(0, Memory.peakMemory - baselineActiveMemory) + let rawKVBytes = keys.nbytes + values.nbytes + let compactBytes = cache.state.reduce(0) { $0 + $1.nbytes } + + let decodeQuery = MLXRandom.normal([1, 32, 1, 128]).asType(.float16) + let decodeKey = MLXRandom.normal([1, 8, 1, 128]).asType(.float16) + let decodeValue = MLXRandom.normal([1, 8, 1, 128]).asType(.float16) + let decodeStart = Date.timeIntervalSinceReferenceDate + let decodeOutput = cache.updateAndAttend( + queries: decodeQuery, + keys: decodeKey, + values: decodeValue, + scale: 1 / sqrt(Float(128))) + eval(decodeOutput) + let decodeElapsed = Date.timeIntervalSinceReferenceDate - decodeStart + + print( + "KVarN 32K ingest/decode smoke: elapsed=\(elapsed)s, raw=\(rawKVBytes) bytes, " + + "compact=\(compactBytes) bytes, peak workspace=\(peakWorkspaceBytes) bytes, " + + "one-layer decode=\(decodeElapsed)s") + + XCTAssertEqual(output.shape, [1, 32, 1, 128]) + XCTAssertLessThan(compactBytes, rawKVBytes) + // A regression guard against retaining prompt-sized geometric spare capacity or an + // unbounded normalization graph. This is deliberately loose for different Apple GPUs. + XCTAssertLessThan(peakWorkspaceBytes, 768 * 1_024 * 1_024) + XCTAssertLessThan(decodeElapsed, 0.25) + #else + throw XCTSkip("Metal memory instrumentation requires arm64 macOS.") + #endif + } + func testLlamaLora() throws { let config = LlamaConfiguration( hiddenSize: 64, hiddenLayers: 16, intermediateSize: 512, attentionHeads: 32, diff --git a/Tests/MLXLMTests/KVCacheConfigurationTests.swift b/Tests/MLXLMTests/KVCacheConfigurationTests.swift index 0d7b260728..ad0f362553 100644 --- a/Tests/MLXLMTests/KVCacheConfigurationTests.swift +++ b/Tests/MLXLMTests/KVCacheConfigurationTests.swift @@ -23,6 +23,7 @@ struct KVCacheConfigurationTests { #expect(TurboQuantKVCacheConfiguration.qualityFirst.valuePrecision == .fourBit) #expect(TurboQuantKVCacheConfiguration.balanced.keyPrecision == .affineEightBit) #expect(TurboQuantKVCacheConfiguration.balanced.valuePrecision == .threeBit) + #expect(VarianceNormalizedKVCacheConfiguration.memoryFirst.sinkhornIterations == 8) } @Test func invalidTypedValuesAreRejectedAtConstruction() { @@ -165,6 +166,23 @@ struct KVCacheConfigurationTests { #expect(report.layers[2].reason == .slidingWindow) } + @Test func runtimeReportClassifiesVarianceNormalizedCache() throws { + let configuration = KVCacheConfiguration( + strategy: .varianceNormalized( + try .init(keyBits: 4, valueBits: 4, tileSize: 32, sinkhornIterations: 2))) + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + + let report = kvCacheRuntimeReport(cache: [cache], configuration: configuration) + + #expect(report.layers.count == 1) + #expect(report.layers[0].kind == .attention(maxSize: nil)) + #expect(report.layers[0].capacitySource == .unbounded) + #expect(report.layers[0].state == .active) + #expect(report.layers[0].resolvedStrategy == .varianceNormalized) + #expect(report.layers[0].reason == nil) + } + @Test func typedTurboQuantDispatchRewritesNestedAttentionCache() throws { let simple = KVCacheSimple() simple.offset = 8 diff --git a/Tests/MLXLMTests/KVCacheRoundTests.swift b/Tests/MLXLMTests/KVCacheRoundTests.swift index 40d48b1cdb..22c341ede6 100644 --- a/Tests/MLXLMTests/KVCacheRoundTests.swift +++ b/Tests/MLXLMTests/KVCacheRoundTests.swift @@ -128,6 +128,39 @@ private struct RingSnapshot { #expect(live.offset == 6, "rollback did not clamp the append-only layer back") } +@Test func testVarianceNormalizedRoundCommitsExactlyBelowTileBoundary() throws { + let live = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let initial = positionedKV(0 ..< 20, headDim: 32) + _ = live.update(keys: initial.0, values: initial.1) + + let staged = try #require(StagedRound([live], width: 4)) + let provisional = positionedKV(20 ..< 24, headDim: 32) + _ = staged.caches[0].update(keys: provisional.0, values: provisional.1) + staged.commit(accepted: 2) + + let empty = MLXArray.zeros([1, 1, 0, 32]) + let materialized = live.update(keys: empty, values: empty) + let expected = positionedKV(0 ..< 22, headDim: 32) + eval(materialized.0, materialized.1) + + #expect(live.offset == 22) + #expect(allClose(materialized.0, expected.0, rtol: 0, atol: 1e-5).item(Bool.self)) + #expect(allClose(materialized.1, expected.1, rtol: 0, atol: 1e-5).item(Bool.self)) +} + +@Test func testVarianceNormalizedRoundRefusesCompressionBoundary() { + let live = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let initial = positionedKV(0 ..< 30, headDim: 32) + _ = live.update(keys: initial.0, values: initial.1) + + #expect(live.isTrimmable(after: 1)) + #expect(!live.isTrimmable(after: 2)) + #expect(StagedRound([live], width: 2) == nil) + #expect(live.offset == 30, "refusing the round must leave the live cache untouched") +} + // MARK: - Invariant 2: the presentation is the live write path's, exactly /// The overlay's whole correctness argument: what the adapter returns is what the live cache diff --git a/Tests/MLXLMTests/KVCacheTests.swift b/Tests/MLXLMTests/KVCacheTests.swift index 71147850fa..38b4965d21 100644 --- a/Tests/MLXLMTests/KVCacheTests.swift +++ b/Tests/MLXLMTests/KVCacheTests.swift @@ -8,6 +8,7 @@ private let cacheCreators: [@Sendable () -> any KVCache] = [ { KVCacheSimple() }, { RotatingKVCache(maxSize: 32) }, { QuantizedKVCache() }, + { VarianceNormalizedKVCache(tileSize: 32, keyBits: 4, valueBits: 4) }, { ChunkedKVCache(chunkSize: 16) }, { ArraysCache(size: 2) }, { MambaCache() }, @@ -21,6 +22,14 @@ private func tempURL() -> URL { .appendingPathExtension("safetensors") } +private func deterministicTensor(shape: [Int], salt: Int) -> MLXArray { + let count = shape.reduce(1, *) + let values = (0 ..< count).map { index in + Float((index * 37 + salt * 17) % 101 - 50) / 23 + } + return MLXArray(values).reshaped(shape).asType(.float16) +} + private struct SerializedCacheFixture { let className: String let arrayCount: Int @@ -67,6 +76,15 @@ private func assertArraysClose(_ lhs: [MLXArray], _ rhs: [MLXArray], label: Stri } } +private func relativeRMSError(_ actual: MLXArray, _ expected: MLXArray) -> Float { + let actual = actual.asType(.float32) + let expected = expected.asType(.float32) + let diff = actual - expected + let mse = mean(diff * diff).item(Float.self) + let ref = max(mean(expected * expected).item(Float.self), 1e-6) + return sqrt(mse / ref) +} + private final class LifecycleRecordingCache: BaseKVCache { private(set) var preparedLengths: [Int]? private(set) var finalizeCallCount = 0 @@ -559,6 +577,9 @@ func testCacheSerialization(creator: (() -> any KVCache)) async throws { .init( className: "QuantizedKVCache", arrayCount: 3, metadata: ["256", "0", "64", "4"]), + .init( + className: "VarianceNormalizedKVCache", arrayCount: 7, + metadata: ["32", "32", "4", "4", "2", "1", "0"]), .init(className: "ChunkedKVCache", arrayCount: 1, metadata: ["None", "0"]), ]) } @@ -575,6 +596,12 @@ func testCacheSerialization(creator: (() -> any KVCache)) async throws { .init( className: "QuantizedKVCache", arrayCount: 0, metadata: ["256", "invalid", "64", "4"]), + .init( + className: "VarianceNormalizedKVCache", arrayCount: 0, + metadata: ["24", "0", "4", "4", "2", "0", "0"]), + .init( + className: "VarianceNormalizedKVCache", arrayCount: 8, + metadata: ["32", "31", "4", "4", "2", "1", "0"]), .init(className: "ChunkedKVCache", arrayCount: 0, metadata: ["invalid", "0"]), ]) } @@ -583,7 +610,11 @@ func testCacheSerialization(creator: (() -> any KVCache)) async throws { try expectPromptCacheLoadToFail([ .init( className: "KVCacheSimple", arrayCount: 2, metadata: [""], - arrayShape: [1, 1]) + arrayShape: [1, 1]), + .init( + className: "VarianceNormalizedKVCache", arrayCount: 8, + metadata: ["32", "32", "4", "4", "2", "1", "0"], + arrayShape: [1, 1]), ]) } @@ -1489,3 +1520,559 @@ private func fillOneAtATime(_ cache: RotatingKVCache, positions: Range) { allClose(out, reference, rtol: 1e-5, atol: 1e-5).item(Bool.self), "post-wrap attention diverged from the logical-order reference") } + +// MARK: - Variance-normalized KV cache + +@Test func testVarianceNormalizedKVCacheStoresCompletedTilesAndTail() throws { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 40, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 40, 32]).asType(.float16) + + let (cachedKeys, cachedValues) = cache.update(keys: keys, values: values) + eval(cachedKeys, cachedValues) + + #expect(cache.offset == 40) + #expect(cachedKeys.shape == keys.shape) + #expect(cachedValues.shape == values.shape) + #expect(cache.metaState == ["32", "40", "4", "4", "2", "1", "8", "1", "float16", "float16"]) + #expect(cache.state.count == 10) + #expect(relativeRMSError(cachedKeys, keys) < 0.5) + #expect(relativeRMSError(cachedValues, values) < 0.5) +} + +@Test func testVarianceNormalizedKVCacheSerializationRoundTrip() throws { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 68, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 68, 32]).asType(.float16) + let (originalKeys, originalValues) = cache.update(keys: keys, values: values) + eval(originalKeys, originalValues) + + let url = tempURL() + try savePromptCache(url: url, cache: [cache], metadata: ["kind": "variance-normalized"]) + let (loaded, metadata) = try loadPromptCache(url: url) + + #expect(metadata["kind"] == "variance-normalized") + let restored = try #require(loaded[0] as? VarianceNormalizedKVCache) + #expect(restored.metaState == cache.metaState) + + let moreKeys = MLXRandom.normal([1, 1, 1, 32]).asType(.float16) + let moreValues = MLXRandom.normal([1, 1, 1, 32]).asType(.float16) + let (restoredKeys, restoredValues) = restored.update(keys: moreKeys, values: moreValues) + eval(restoredKeys, restoredValues) + + #expect(restored.offset == 69) + #expect(restoredKeys.shape == [1, 1, 69, 32]) + #expect(restoredValues.shape == [1, 1, 69, 32]) +} + +@Test func testVarianceNormalizedKVCachePreservesDTypeAtExactTileBoundary() throws { + for dtype in [DType.float32, .bfloat16] { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let keys = deterministicTensor(shape: [1, 1, 64, 32], salt: 21).asType(dtype) + let values = deterministicTensor(shape: [1, 1, 64, 32], salt: 22).asType(dtype) + _ = cache.update(keys: keys, values: values) + eval(cache.state) + + let url = tempURL() + try savePromptCache(url: url, cache: [cache]) + let (loaded, _) = try loadPromptCache(url: url) + let restored = try #require(loaded[0] as? VarianceNormalizedKVCache) + let copied = try #require(cache.copy() as? VarianceNormalizedKVCache) + let emptyKeys = MLXArray.zeros([1, 1, 0, 32], dtype: dtype) + let emptyValues = MLXArray.zeros([1, 1, 0, 32], dtype: dtype) + + for candidate in [restored, copied] { + let (materializedKeys, materializedValues) = candidate.update( + keys: emptyKeys, values: emptyValues) + eval(materializedKeys, materializedValues) + #expect(materializedKeys.dtype == dtype) + #expect(materializedValues.dtype == dtype) + } + } +} + +@Test func testVarianceNormalizedKVCacheTrimOnlyReconstructsTheAffectedTile() throws { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 70, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 70, 32]).asType(.float16) + let (beforeKeys, beforeValues) = cache.update(keys: keys, values: values) + eval(beforeKeys, beforeValues) + + #expect(cache.trim(10) == 10) + let emptyKeys = MLXArray.zeros([1, 1, 0, 32], dtype: .float16) + let emptyValues = MLXArray.zeros([1, 1, 0, 32], dtype: .float16) + let (afterKeys, afterValues) = cache.update(keys: emptyKeys, values: emptyValues) + eval(afterKeys, afterValues) + + #expect(cache.offset == 60) + #expect(cache.metaState == ["32", "60", "4", "4", "2", "1", "28", "1", "float16", "float16"]) + #expect(cache.state.count == 10) + #expect(relativeRMSError(afterKeys, beforeKeys[.ellipsis, ..<60, 0...]) < 1e-3) + #expect(relativeRMSError(afterValues, beforeValues[.ellipsis, ..<60, 0...]) < 1e-3) +} + +@Test func testVarianceNormalizedKVCacheSupportsAsymmetricKeyValueBits() { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) + + let (cachedKeys, cachedValues) = cache.update(keys: keys, values: values) + eval(cachedKeys, cachedValues) + + #expect(cache.offset == 32) + #expect(cache.metaState == ["32", "32", "4", "2", "2", "1", "0", "1", "float16", "float16"]) + #expect(cachedKeys.shape == keys.shape) + #expect(cachedValues.shape == values.shape) +} + +@Test func testVarianceNormalizedKVCacheSupportsPaperTargetTwoBitKV() { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 2, valueBits: 2, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) + + let (cachedKeys, cachedValues) = cache.update(keys: keys, values: values) + eval(cachedKeys, cachedValues) + + #expect(cache.offset == 32) + #expect(cache.metaState == ["32", "32", "2", "2", "2", "1", "0", "1", "float16", "float16"]) + #expect(cache.state.count == 8) + #expect(cachedKeys.shape == keys.shape) + #expect(cachedValues.shape == values.shape) +} + +@Test func testVarianceNormalizedKVCacheMaterializationPreservesWideInputDTypes() { + for dtype in [DType.float32, .bfloat16] { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let magnitude = MLXArray(Float(100_000), dtype: dtype) + let keys = deterministicTensor(shape: [1, 1, 32, 32], salt: 11).asType(dtype) * magnitude + let values = deterministicTensor(shape: [1, 1, 32, 32], salt: 12).asType(dtype) * magnitude + + let (cachedKeys, cachedValues) = cache.update(keys: keys, values: values) + eval(cachedKeys, cachedValues) + + #expect(cachedKeys.dtype == dtype) + #expect(cachedValues.dtype == dtype) + #expect(isFinite(cachedKeys).all().item(Bool.self)) + #expect(isFinite(cachedValues).all().item(Bool.self)) + } +} + +@Test func testVarianceNormalizedKVCacheQuantizedTileAttentionMatchesMaterializedAttention() { + let nativeCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let materializedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let queries = deterministicTensor(shape: [1, 1, 4, 32], salt: 31) + let keys = deterministicTensor(shape: [1, 1, 36, 32], salt: 32) + let values = deterministicTensor(shape: [1, 1, 36, 32], salt: 33) + let scale = 1 / sqrt(Float(32)) + + let native = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: nativeCache, + scale: scale) + let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) + let materialized = attentionWithCacheUpdate( + queries: queries, + keys: cachedKeys, + values: cachedValues, + cache: nil, + scale: scale) + eval(native, materialized) + + #expect(relativeRMSError(native, materialized) < 1.5e-3) + #expect(nativeCache.offset == 36) + #expect( + nativeCache.metaState == ["32", "36", "4", "4", "2", "1", "4", "1", "float16", "float16"]) +} + +@Test func testVarianceNormalizedKVCacheQuantizedTileAttentionSupportsGQA() { + let nativeCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let materializedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let queries = deterministicTensor(shape: [1, 4, 3, 32], salt: 34) + let keys = deterministicTensor(shape: [1, 2, 33, 32], salt: 35) + let values = deterministicTensor(shape: [1, 2, 33, 32], salt: 36) + let scale = 1 / sqrt(Float(32)) + + let native = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: nativeCache, + scale: scale) + let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) + let materialized = attentionWithCacheUpdate( + queries: queries, + keys: cachedKeys, + values: cachedValues, + cache: nil, + scale: scale) + eval(native, materialized) + + #expect(relativeRMSError(native, materialized) < 1.5e-3) + #expect(native.shape == [1, 4, 3, 32]) + #expect( + nativeCache.metaState == ["32", "33", "4", "4", "2", "1", "1", "1", "float16", "float16"]) +} + +@Test func testVarianceNormalizedKVCacheStackedTileAttentionMatchesMaterializedAttention() { + let nativeCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let materializedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let queries = deterministicTensor(shape: [1, 1, 2, 32], salt: 1) + // Thirty-three tiles exercises one immutable slab plus one pending tile. + let keys = deterministicTensor(shape: [1, 1, 1_056, 32], salt: 2) + let values = deterministicTensor(shape: [1, 1, 1_056, 32], salt: 3) + let scale = 1 / sqrt(Float(32)) + + let native = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: nativeCache, + scale: scale) + let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) + let materialized = attentionWithCacheUpdate( + queries: queries, + keys: cachedKeys, + values: cachedValues, + cache: nil, + scale: scale) + eval(native, materialized) + + #expect(relativeRMSError(native, materialized) < 1e-3) + #expect( + nativeCache.metaState == [ + "32", "1056", "4", "4", "2", "33", "0", "1", "float16", "float16", + ]) +} + +@Test func testVarianceNormalizedKVCacheStackedTileAttentionSupportsGQA() { + let nativeCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let materializedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let queries = deterministicTensor(shape: [1, 4, 2, 32], salt: 4) + let keys = deterministicTensor(shape: [1, 2, 1_056, 32], salt: 5) + let values = deterministicTensor(shape: [1, 2, 1_056, 32], salt: 6) + let scale = 1 / sqrt(Float(32)) + + let native = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: nativeCache, + scale: scale) + let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) + let materialized = attentionWithCacheUpdate( + queries: queries, + keys: cachedKeys, + values: cachedValues, + cache: nil, + scale: scale) + eval(native, materialized) + + #expect(relativeRMSError(native, materialized) < 1e-3) + #expect(native.shape == [1, 4, 2, 32]) + #expect( + nativeCache.metaState == [ + "32", "1056", "4", "4", "2", "33", "0", "1", "float16", "float16", + ]) +} + +@Test func testApplyAttentionMaskSuppressesBoolMaskedLogits() { + let scores = MLXArray([Float(-10), Float(-20), Float(-30)]).reshaped(1, 1, 1, 3) + let mask = MLXArray([true, false, false]).reshaped(1, 1, 1, 3) + + let weights = softmax(applyAttentionMask(scores: scores, mask: .array(mask)), axis: -1) + eval(weights) + + let values = weights.asArray(Float.self) + #expect(values[0] > 0.999) + #expect(values[1] < 1e-6) + #expect(values[2] < 1e-6) +} + +@Test func testVarianceNormalizedKVCacheMaskedAttentionMatchesMaterializedAttention() { + let nativeCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let materializedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let queries = MLXArray.ones([1, 1, 4, 32], dtype: .float16) * -1 + let keys = MLXArray.ones([1, 1, 36, 32], dtype: .float16) + let values = concatenated( + [ + MLXArray.zeros([1, 1, 32, 32], dtype: .float16), + MLXArray.ones([1, 1, 4, 32], dtype: .float16) * 10, + ], axis: 2) + let scale = 1 / sqrt(Float(32)) + let mask = MLXFast.ScaledDotProductAttentionMaskMode.causal + + let native = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: nativeCache, + scale: scale, + mask: mask) + let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) + let materialized = attentionWithCacheUpdate( + queries: queries, + keys: cachedKeys, + values: cachedValues, + cache: nil, + scale: scale, + mask: mask) + eval(native, materialized) + + #expect(relativeRMSError(native, materialized) < 1e-3) +} + +@Test func testVarianceNormalizedKVCacheAttentionTracksFP16OverLongDecode() { + let fp16Cache = KVCacheSimple() + let varianceNormalizedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let randomState = MLXRandom.RandomState(seed: 7) + let scale = 1 / sqrt(Float(32)) + var totalError: Float = 0 + var maxError: Float = 0 + let tokenCount = 96 + + for _ in 0 ..< tokenCount { + let queries = MLXRandom.normal([1, 1, 1, 32], key: randomState).asType(.float16) + let keys = MLXRandom.normal([1, 1, 1, 32], key: randomState).asType(.float16) + let values = MLXRandom.normal([1, 1, 1, 32], key: randomState).asType(.float16) + + let fp16 = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: fp16Cache, + scale: scale) + let compressed = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: varianceNormalizedCache, + scale: scale) + eval(fp16, compressed) + + let error = relativeRMSError(compressed, fp16) + totalError += error + maxError = max(maxError, error) + } + + #expect( + varianceNormalizedCache.metaState == [ + "32", "96", "4", "4", "2", "3", "0", "1", "float16", "float16", + ]) + #expect(totalError / Float(tokenCount) < 0.15) + #expect(maxError < 0.45) +} + +@Test func testVarianceNormalizedKVCacheMemoryAccountingIncludesScaleOverhead() { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 64, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 64, 32]).asType(.float16) + + _ = cache.update(keys: keys, values: values) + eval(cache.state) + + let state = cache.state + let compressedBytes = state.reduce(0) { $0 + $1.nbytes } + let quantizedPayloadBytes = stride(from: 0, to: state.count, by: 8).reduce(0) { + $0 + state[$1].nbytes + state[$1 + 4].nbytes + } + let fp16Bytes = keys.nbytes + values.nbytes + + #expect(cache.metaState == ["32", "64", "4", "4", "2", "2", "0", "1", "float16", "float16"]) + #expect(cache.compactStorageByteCount == compressedBytes) + #expect(compressedBytes > quantizedPayloadBytes) + #expect(compressedBytes < fp16Bytes) +} + +@Test func testVarianceNormalizedKVCacheCoalescesTieredSlabs() { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 1) + let tokenCount = 32 * 32 * 8 + let queries = deterministicTensor(shape: [1, 1, 1, 32], salt: 41) + let keys = deterministicTensor(shape: [1, 1, tokenCount, 32], salt: 42) + let values = deterministicTensor(shape: [1, 1, tokenCount, 32], salt: 43) + + let output = cache.updateAndAttend( + queries: queries, + keys: keys, + values: values, + scale: 1 / sqrt(Float(32))) + eval(output) + + #expect(cache.offset == tokenCount) + #expect(cache.attentionPartitionCount == 1) + #expect(cache.compactStorageByteCount == cache.state.reduce(0) { $0 + $1.nbytes }) +} + +@Test func testVarianceNormalizedKVCacheBoundsPartitionsBeforeLargeSlabBoundary() { + let nativeCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) + let materializedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) + let tokenCount = 31 * 32 + let queries = deterministicTensor(shape: [1, 4, 1, 32], salt: 51) + let keys = deterministicTensor(shape: [1, 2, tokenCount, 32], salt: 52) + let values = deterministicTensor(shape: [1, 2, tokenCount, 32], salt: 53) + let scale = 1 / sqrt(Float(32)) + + let native = nativeCache.updateAndAttend( + queries: queries, keys: keys, values: values, scale: scale) + let (materializedKeys, materializedValues) = materializedCache.update( + keys: keys, values: values) + let materialized = attentionWithCacheUpdate( + queries: queries, + keys: materializedKeys, + values: materializedValues, + cache: nil, + scale: scale) + eval(native, materialized) + + // Four-tile base slabs cap the old 31-dispatch cliff at ten partitions while preserving + // the quantized attention result. The next tile still coalesces to one 32-tile slab. + #expect(nativeCache.attentionPartitionCount == 10) + #expect(relativeRMSError(native, materialized) < 1.5e-3) +} + +@Test func testVarianceNormalizedKVCacheHeadBatchesMatchIndependentHeads() { + let keys = deterministicTensor(shape: [1, 8, 128, 32], salt: 54) + let values = deterministicTensor(shape: [1, 8, 128, 32], salt: 55) + let batchedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) + let (batchedKeys, batchedValues) = batchedCache.update(keys: keys, values: values) + + var independentKeys: [MLXArray] = [] + var independentValues: [MLXArray] = [] + for head in 0 ..< 8 { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) + let (headKeys, headValues) = cache.update( + keys: keys[0..., head ..< head + 1, 0..., 0...], + values: values[0..., head ..< head + 1, 0..., 0...]) + independentKeys.append(headKeys) + independentValues.append(headValues) + } + + let referenceKeys = concatenated(independentKeys, axis: 1) + let referenceValues = concatenated(independentValues, axis: 1) + eval(batchedKeys, batchedValues, referenceKeys, referenceValues) + + #expect(relativeRMSError(batchedKeys, referenceKeys) < 1e-6) + #expect(relativeRMSError(batchedValues, referenceValues) < 1e-6) +} + +@Test func testVarianceNormalizedKVCacheTwoBitMemoryAccountingIsPaperRelevant() { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 2, valueBits: 2, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 64, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 64, 32]).asType(.float16) + + _ = cache.update(keys: keys, values: values) + eval(cache.state) + + let compressedBytes = cache.state.reduce(0) { $0 + $1.nbytes } + let fp16Bytes = keys.nbytes + values.nbytes + + #expect(cache.metaState == ["32", "64", "2", "2", "2", "2", "0", "1", "float16", "float16"]) + #expect(compressedBytes < fp16Bytes) +} + +@Test func testMaybeQuantizeKVCacheCanUseVarianceNormalizedStrategy() throws { + let simple = KVCacheSimple() + let keys = MLXRandom.normal([1, 1, 33, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 33, 32]).asType(.float16) + _ = simple.update(keys: keys, values: values) + + var cache: [KVCache] = [simple] + let configuration = try KVCacheConfiguration( + strategy: .varianceNormalized( + .init(keyBits: 4, valueBits: 4, tileSize: 32, sinkhornIterations: 4)), + compatibility: .allowPartial) + _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) + + let converted = cache[0] as? VarianceNormalizedKVCache + #expect(converted != nil) + #expect(converted?.offset == 33) + #expect( + converted?.metaState == ["32", "33", "4", "4", "4", "1", "1", "1", "float16", "float16"]) +} + +@Test func testMaybeQuantizeKVCacheDefersVarianceNormalizedStrategyUntilThreshold() throws { + let simple = KVCacheSimple() + let keys = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) + _ = simple.update(keys: keys, values: values) + + var cache: [KVCache] = [simple] + let configuration = try KVCacheConfiguration( + strategy: .varianceNormalized( + .init( + keyBits: 4, valueBits: 4, tileSize: 32, sinkhornIterations: 4, + compressionStart: 64)), + compatibility: .allowPartial) + _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) + + #expect(cache[0] is KVCacheSimple) + + let moreKeys = MLXRandom.normal([1, 1, 33, 32]).asType(.float16) + let moreValues = MLXRandom.normal([1, 1, 33, 32]).asType(.float16) + _ = cache[0].update(keys: moreKeys, values: moreValues) + _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) + + #expect(cache[0] is VarianceNormalizedKVCache) + #expect(cache[0].offset == 65) +} + +@Test func testMaybeQuantizeKVCacheSkipsUnsupportedVarianceNormalizedDimensions() throws { + let simple = KVCacheSimple() + let keys = MLXRandom.normal([1, 1, 33, 24]).asType(.float16) + let values = MLXRandom.normal([1, 1, 33, 24]).asType(.float16) + _ = simple.update(keys: keys, values: values) + + var cache: [KVCache] = [simple] + let configuration = try KVCacheConfiguration( + strategy: .varianceNormalized( + .init(keyBits: 4, valueBits: 4, tileSize: 32, sinkhornIterations: 4)), + compatibility: .allowPartial) + _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) + + #expect(cache[0] is KVCacheSimple) + #expect(cache[0].offset == 33) + #expect( + !supportsVarianceNormalizedKVCache( + keyHeadDim: 96, valueHeadDim: 96, tileSize: 32)) +} + +@Test func testLegacyVarianceNormalizedSchemeResolvesToTypedConfiguration() throws { + let parameters = GenerateParameters(quantizedKVStart: 8, kvScheme: "varn4v2t32") + let resolved = try #require(try parameters.resolvedKVCacheConfiguration()) + #expect(resolved.strategy.identifier == KVCacheStrategyIdentifier.varianceNormalized) + guard case .varianceNormalized(let varn) = resolved.strategy.storage else { + Issue.record("Expected a variance-normalized strategy") + return + } + #expect(varn.keyBits == 4) + #expect(varn.valueBits == 2) + #expect(varn.tileSize == 32) + #expect(varn.sinkhornIterations == 8) + #expect(varn.compressionStart == 8) +} diff --git a/Tests/MLXLMTests/VarianceNormalizedKVCacheBenchmark.swift b/Tests/MLXLMTests/VarianceNormalizedKVCacheBenchmark.swift new file mode 100644 index 0000000000..6e670c7de7 --- /dev/null +++ b/Tests/MLXLMTests/VarianceNormalizedKVCacheBenchmark.swift @@ -0,0 +1,123 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import Testing + +@testable import MLXLMCommon + +/// Opt-in microbenchmarks for the variance-normalized KV-cache hot path. +/// +/// Run with: +/// +/// ```sh +/// MLX_RUN_VARN_BENCHMARKS=1 swift test --filter VarianceNormalizedKVCacheBenchmark +/// ``` +/// +/// These tests print measurements but deliberately enforce only correctness. Absolute GPU timing +/// is not stable enough for a portable CI threshold. +@Suite(.serialized) +struct VarianceNormalizedKVCacheBenchmark { + private func median(_ values: [Double]) -> Double { + let sorted = values.sorted() + return sorted[sorted.count / 2] + } + + private func relativeRMSE(_ actual: MLXArray, _ reference: MLXArray) -> Float { + let numerator = sqrt(mean(square(actual.asType(.float32) - reference.asType(.float32)))) + let denominator = maximum( + sqrt(mean(square(reference.asType(.float32)))), MLXArray(Float(1e-8))) + let result = numerator / denominator + eval(result) + return result.item(Float.self) + } + + @Test func decodeContextMatrix() throws { + guard ProcessInfo.processInfo.environment["MLX_RUN_VARN_BENCHMARKS"] == "1" else { return } + + let contexts = [512, 1_024, 2_048, 3_968, 4_096, 8_192, 32_768] + let queryHeads = 8 + let kvHeads = 4 + let headDimension = 128 + let scale = 1 / sqrt(Float(headDimension)) + + for context in contexts { + let cache = VarianceNormalizedKVCache( + tileSize: 128, keyBits: 4, valueBits: 2, sinkhornIterations: 8) + let prefillQuery = MLXRandom.normal([1, queryHeads, 1, headDimension]).asType(.float16) + let prefillKeys = MLXRandom.normal([1, kvHeads, context, headDimension]).asType( + .float16) + let prefillValues = MLXRandom.normal([1, kvHeads, context, headDimension]).asType( + .float16) + let prefillOutput = cache.updateAndAttend( + queries: prefillQuery, keys: prefillKeys, values: prefillValues, scale: scale) + eval(prefillOutput) + + var samples: [Double] = [] + for iteration in 0 ..< 20 { + let query = MLXRandom.normal([1, queryHeads, 1, headDimension]).asType(.float16) + let key = MLXRandom.normal([1, kvHeads, 1, headDimension]).asType(.float16) + let value = MLXRandom.normal([1, kvHeads, 1, headDimension]).asType(.float16) + let start = ContinuousClock.now + let output = cache.updateAndAttend( + queries: query, keys: key, values: value, scale: scale) + eval(output) + let elapsed = ContinuousClock.now - start + if iteration >= 5 { + samples.append( + Double(elapsed.components.seconds) * 1_000 + + Double(elapsed.components.attoseconds) / 1e15) + } + #expect(output.shape == [1, queryHeads, 1, headDimension]) + } + + print( + String( + format: + "[VARNBENCH] context=%6d partitions=%2d median_decode=%7.3f ms compact=%8.2f MiB", + context, cache.attentionPartitionCount, median(samples), + Double(cache.compactStorageByteCount) / 1_048_576)) + } + } + + @Test func sinkhornIterationMatrix() throws { + guard ProcessInfo.processInfo.environment["MLX_RUN_VARN_BENCHMARKS"] == "1" else { return } + + let context = 4_096 + let queryHeads = 8 + let kvHeads = 4 + let headDimension = 128 + let scale = 1 / sqrt(Float(headDimension)) + let query = MLXRandom.normal([1, queryHeads, 1, headDimension]).asType(.float16) + let keys = MLXRandom.normal([1, kvHeads, context, headDimension]).asType(.float16) + let values = MLXRandom.normal([1, kvHeads, context, headDimension]).asType(.float16) + let reference = MLXFast.scaledDotProductAttention( + queries: query, keys: keys, values: values, scale: scale, mask: nil) + eval(query, keys, values, reference) + + // Warm each graph shape before recording the ingest measurement. + for iterations in [4, 8, 16] { + let cache = VarianceNormalizedKVCache( + tileSize: 128, keyBits: 4, valueBits: 2, sinkhornIterations: iterations) + eval(cache.updateAndAttend(queries: query, keys: keys, values: values, scale: scale)) + } + + for iterations in [4, 8, 16] { + let cache = VarianceNormalizedKVCache( + tileSize: 128, keyBits: 4, valueBits: 2, sinkhornIterations: iterations) + let start = ContinuousClock.now + let output = cache.updateAndAttend( + queries: query, keys: keys, values: values, scale: scale) + eval(output) + let elapsed = ContinuousClock.now - start + let milliseconds = + Double(elapsed.components.seconds) * 1_000 + + Double(elapsed.components.attoseconds) / 1e15 + print( + String( + format: + "[VARNBENCH] sinkhorn=%2d ingest=%7.3f ms attention_relative_rmse=%.6f", + iterations, milliseconds, relativeRMSE(output, reference))) + } + } +}