Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Libraries/MLXLLM/Models/MiMoV2Flash.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 8 additions & 0 deletions Libraries/MLXLMCommon/AttentionUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions Libraries/MLXLMCommon/Evaluate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down
218 changes: 217 additions & 1 deletion Libraries/MLXLMCommon/KVCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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],
Expand Down Expand Up @@ -2483,7 +2575,8 @@ public func maybeQuantizeKVCache(
) {
if let kvScheme,
resolveAffineScheme(kvScheme) == nil,
resolveTurboScheme(kvScheme) == nil
resolveTurboScheme(kvScheme) == nil,
resolveVarianceNormalizedScheme(kvScheme) == nil
{
return
}
Expand Down Expand Up @@ -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)
}
}
Loading
Loading