diff --git a/Libraries/MLXLLM/Models/GPTOSS.swift b/Libraries/MLXLLM/Models/GPTOSS.swift index f8ca2bcfca..06bb5bd52b 100644 --- a/Libraries/MLXLLM/Models/GPTOSS.swift +++ b/Libraries/MLXLLM/Models/GPTOSS.swift @@ -224,11 +224,13 @@ class AttentionBlock: Module { return active }() - // Quantized cache path + // Quantized cache path (taken when the cache conforms to + // QuantizedKVCacheProtocol, i.e. the native quantized-attention kernel). + // Attention sinks are threaded through so the kernel folds them into the + // softmax denominator and stays correct for sink models — no fatalError. + // (Note: GPT-OSS defaults to the dequant cache for decode speed; this + // path is used only when the kernel cache is selected.) if let qcache = cache as? QuantizedKVCacheProtocol { - if sinksActive { - fatalError("Quantized attention does not support non-zero sinks.") - } q = applyRotaryPosition(rope, to: q, cache: cache) k = applyRotaryPosition(rope, to: k, cache: cache) @@ -241,7 +243,8 @@ class AttentionBlock: Module { mask: mask, groupSize: qcache.groupSize, bits: qcache.bits, - mode: qcache.mode + mode: qcache.mode, + sinks: sinksActive ? sinks : nil ) return oProj(vHat.swappedAxes(1, 2).reshaped(B, L, -1)) diff --git a/Libraries/MLXLMCommon/BatchKVCache.swift b/Libraries/MLXLMCommon/BatchKVCache.swift index 256ea525ec..382e7a204e 100644 --- a/Libraries/MLXLMCommon/BatchKVCache.swift +++ b/Libraries/MLXLMCommon/BatchKVCache.swift @@ -180,7 +180,7 @@ public final class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCac self.keys?[.ellipsis, prev ..< _idx, 0...] = keys self.values?[.ellipsis, prev ..< _idx, 0...] = values - // DAR-325: collapse the per-step `batchOffset` lazy chain on decode. + // Collapse the per-step `batchOffset` lazy chain on decode. // gemma-4 shares one RoPE `perRowOffset` from the first cache // (Gemma4.swift:1264), so other caches never consume their own // `batchOffset` and leak a tiny scalar buffer/step (COUNT leak, flat @@ -610,7 +610,7 @@ public final class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, Ba _idx = maxCacheSize } - // DAR-325: collapse the per-step `batchOffset`/`leftPadding` lazy chains + // Collapse the per-step `batchOffset`/`leftPadding` lazy chains // on decode (rebuilt at :594/:600). gemma-4 consumes each from only one // representative cache (shared RoPE offset + one sliding mask), so the // others leak ~2 tiny scalar buffers/step until `numResources` hits the diff --git a/Libraries/MLXLMCommon/ContinuousBatching/EngineCore.swift b/Libraries/MLXLMCommon/ContinuousBatching/EngineCore.swift index b7ce861257..f778d384b9 100644 --- a/Libraries/MLXLMCommon/ContinuousBatching/EngineCore.swift +++ b/Libraries/MLXLMCommon/ContinuousBatching/EngineCore.swift @@ -110,18 +110,20 @@ public final class EngineCore: @unchecked Sendable { // live-buffer climb (count climbs while cache stays small -> needs admission // control) — the latter is the `[metal::malloc] Resource limit (499000)` crash. // - // DEFAULT ON: `darkbloom report` collects logs via - // `log show --predicate 'subsystem == "dev.darkbloom.provider"'`, so the - // `[rsrc]` line is emitted via os_log under that subsystem (not just stdout) - // and is therefore captured in every uploaded report — giving us the - // resource-count trajectory before a crash without asking the operator to set - // any env var. Opt out with DARKBLOOM_MLX_RESOURCE_DEBUG=0 (or false/no/off). + // DEFAULT OFF (opt-in): the `Memory.*` resource/byte reads in the step loop + // (see `engineLoop`) sit on the per-step decode hot path, so they are gated + // behind this flag and not evaluated at all unless an operator opts in. + // Enable with DARKBLOOM_MLX_RESOURCE_DEBUG=1 (or true/yes/on) to collect the + // `[rsrc]` trajectory; `darkbloom report` then captures the os_log line via + // `log show --predicate 'subsystem == "dev.darkbloom.provider"'`. The + // capability is unchanged — it simply costs nothing when disabled, which is + // the default. private static let resourceDebug: Bool = { switch ProcessInfo.processInfo.environment["DARKBLOOM_MLX_RESOURCE_DEBUG"]? .lowercased() { - case "0", "false", "no", "off": return false - default: return true + case "1", "true", "yes", "on": return true + default: return false } }() // Console cadence (stdout). Frequent, so the console line is TTY-gated (see diff --git a/Libraries/MLXLMCommon/ContinuousBatching/Scheduler.swift b/Libraries/MLXLMCommon/ContinuousBatching/Scheduler.swift index f8f3d60db4..b041ce499b 100644 --- a/Libraries/MLXLMCommon/ContinuousBatching/Scheduler.swift +++ b/Libraries/MLXLMCommon/ContinuousBatching/Scheduler.swift @@ -8,7 +8,29 @@ import MLX final class TokenHistoryHolder: @unchecked Sendable { var tokens: [Int] - init(tokens: [Int]) { self.tokens = tokens } + /// Per-token occurrence counts, maintained incrementally as tokens are + /// appended (see ``append(_:)``). The original repetition sampler rebuilt + /// this dictionary from the entire history on every decode step — O(n) per + /// token, i.e. O(n²) over a generation. Maintaining it here makes each + /// sampler call O(unique tokens) instead. Counts include every appended id; + /// the sampler filters to the in-range `[0, vocab)` ids (matching the old + /// `t >= 0 && t < vocab` guard) when it builds the device arrays. + private(set) var counts: [Int: Int] + + init(tokens: [Int]) { + self.tokens = tokens + var counts: [Int: Int] = [:] + for t in tokens { counts[t, default: 0] += 1 } + self.counts = counts + } + + /// Append a generated token, keeping `tokens` and `counts` in sync in + /// O(1) amortized. Must be called instead of `tokens.append(_:)` so the + /// incremental counts stay correct. + func append(_ token: Int) { + tokens.append(token) + counts[token, default: 0] += 1 + } } func makeRepetitionSampler( @@ -19,28 +41,90 @@ func makeRepetitionSampler( frequencyPenalty: Float ) -> RowSampler { return { @Sendable logits in - let tokens = history.tokens - guard !tokens.isEmpty else { return base(logits) } + // Incremental counts: no rescan of the full history. Empty history + // (no counts) → pass through to the base sampler, as before. + guard !history.counts.isEmpty else { return base(logits) } let vocab = logits.dim(-1) - var counts: [Int: Int] = [:] - for t in tokens where t >= 0 && t < vocab { - counts[t, default: 0] += 1 + // Build parallel host arrays of the unique in-range penalized token ids + // and their counts. This is the only host-side work and is O(unique + // tokens) — not O(history length) and not O(vocab). Filtering to + // `0 ..< vocab` preserves the original guard exactly. + var idList: [Int32] = [] + var countList: [Float] = [] + idList.reserveCapacity(history.counts.count) + countList.reserveCapacity(history.counts.count) + for (tokenId, count) in history.counts where tokenId >= 0 && tokenId < vocab { + idList.append(Int32(tokenId)) + countList.append(Float(count)) } - guard !counts.isEmpty else { return base(logits) } - - eval(logits) - var flat = logits.reshaped(-1).asArray(Float.self) - for (tokenId, count) in counts { - var v = flat[tokenId] - if repetitionPenalty != 1.0 { - v = v > 0 ? v / repetitionPenalty : v * repetitionPenalty - } - v -= presencePenalty - v -= frequencyPenalty * Float(count) - flat[tokenId] = v + // No in-range counts → pass through (matches the old `counts.isEmpty` guard). + guard !idList.isEmpty else { return base(logits) } + + // Apply the penalties entirely on-device via gather → transform → + // scatter. No `eval`, no `asArray`, no full-vocab GPU↔host round trip. + // + // Upcast to float32 first so the math is bit-for-bit the original CPU + // formula, which read the logits as `Float` before penalizing. The + // scatter produces a new array (functional op), so the caller's + // `logits` is never mutated. + // + // Numerics, in order (identical to the original): + // if repetitionPenalty != 1: v = v > 0 ? v / rp : v * rp + // v -= presencePenalty + // v -= frequencyPenalty * count + let idsArr = MLXArray(idList) + let countsArr = MLXArray(countList) + let flat = logits.reshaped(-1).asType(.float32) // [vocab] + let gathered = take(flat, idsArr, axis: 0) // [K] + + var penalized = gathered + if repetitionPenalty != 1.0 { + penalized = which( + gathered .> 0, + gathered / repetitionPenalty, + gathered * repetitionPenalty + ) } - return base(MLXArray(flat).reshaped(logits.shape)) + penalized = penalized - presencePenalty + penalized = penalized - frequencyPenalty * countsArr + + flat[idsArr] = penalized // scatter back + return base(flat.reshaped(logits.shape)) + } +} + +/// Which quantized batched-cache implementation to use for full-attention +/// layers when KV quantization is enabled. +public enum KVQuantCacheKind: Sendable, Equatable { + /// Use ``QuantizedBatchKVCache`` and the native quantized attention kernel. + case kernel + /// Use ``DequantBatchKVCache``: stores quantized, but returns dequantized + /// fp16 so the model's regular attention path (including sinks) is used. + case dequant +} + +/// Configuration for per-layer KV-cache quantization in the continuous-batching +/// scheduler. When set on ``SchedulerConfig/kvQuantization``, full-attention +/// layers use ``QuantizedBatchKVCache`` (or ``DequantBatchKVCache`` when +/// ``cacheKind`` is ``KVQuantCacheKind/dequant``); rotating / sliding-window +/// layers keep ``BatchRotatingKVCache``. +public struct KVQuantizationConfig: Sendable { + public let groupSize: Int + public let bits: Int + public let mode: QuantizationMode + public let cacheKind: KVQuantCacheKind + + public init( + groupSize: Int = 128, + bits: Int = 8, + mode: QuantizationMode = .affine, + cacheKind: KVQuantCacheKind = .kernel + ) { + self.groupSize = groupSize + self.bits = bits + self.mode = mode + self.cacheKind = cacheKind } } @@ -55,19 +139,25 @@ public struct SchedulerConfig: Sendable { /// When a new admission would exceed this, the running request with the /// largest KV footprint is preempted and re-queued. 0 = unlimited. public var maxKVCacheTokens: Int + /// Optional KV-cache quantization configuration. When non-nil, full-attention + /// layers are backed by ``QuantizedBatchKVCache``; sliding-window layers + /// remain ``BatchRotatingKVCache``. + public var kvQuantization: KVQuantizationConfig? public init( maxNumSeqs: Int = 64, maxNumBatchedTokens: Int = 8192, prefillStepSize: Int = 512, streamInterval: Int = 1, - maxKVCacheTokens: Int = 0 + maxKVCacheTokens: Int = 0, + kvQuantization: KVQuantizationConfig? = nil ) { self.maxNumSeqs = maxNumSeqs self.maxNumBatchedTokens = maxNumBatchedTokens self.prefillStepSize = prefillStepSize self.streamInterval = streamInterval self.maxKVCacheTokens = maxKVCacheTokens + self.kvQuantization = kvQuantization } } @@ -117,6 +207,11 @@ private struct PendingPrefill { var remaining: [[Int]] // Last token of each sequence; used as the seed for GenerationBatch. var seeds: [Int] + // Whether the resulting decode batch can skip the per-step logSumExp + // normalization (no row uses top-p or a penalty sampler). Computed at + // admission and applied to the GenerationBatch once prefill completes, + // since `PromptProcessingBatch.generate` builds the batch internally. + var skipLogprobNorm: Bool } public final class Scheduler: @unchecked Sendable { @@ -368,6 +463,7 @@ public final class Scheduler: @unchecked Sendable { if genBatch?.hasActiveMTPSession == true { return } // All sequences prefilled — transition to decode. let gen = pp.ppBatch.generate(lastTokensOf: pp.seeds.map { [$0] }, mtpRuntime: mtpRuntime) + gen.skipLogprobNormalization = pp.skipLogprobNorm mergeIntoGenBatch(gen) pendingPrefill = nil return @@ -427,6 +523,7 @@ public final class Scheduler: @unchecked Sendable { return } let gen = pp.ppBatch.generate(lastTokensOf: pp.seeds.map { [$0] }, mtpRuntime: mtpRuntime) + gen.skipLogprobNormalization = pp.skipLogprobNorm mergeIntoGenBatch(gen) pendingPrefill = nil } else { @@ -435,6 +532,10 @@ public final class Scheduler: @unchecked Sendable { } private func mergeIntoGenBatch(_ gen: GenerationBatch) { + // Only extract (dequant + copy) a finished row's prompt cache when a + // prefix cache can consume it. This skips a per-finish fp16 copy of the + // KV history on runs without prefix caching. + gen.capturePromptCacheOnFinish = prefixCache != nil if let existing = genBatch, !existing.isEmpty { existing.extend(gen) } else { @@ -545,11 +646,21 @@ public final class Scheduler: @unchecked Sendable { var existingCache: [KVCache]? = nil var restoredCaches: [any KVCache]? = nil - // Checkpoint restore (hybrid models) takes precedence: the - // provider attached a per-layer mixed cache covering the first - // `tokenCount` prompt tokens. Only valid for a real prefix - // (1 <= tokenCount < promptTokens.count) so there is a suffix to - // decode from; otherwise ignore and fall through to cold. + // Checkpoint restore (hybrid models) takes precedence: the provider + // attached a per-layer mixed cache covering the first `tokenCount` + // prompt tokens. Only valid for a real prefix (1 <= tokenCount < + // promptTokens.count) so there is a suffix to decode from; otherwise + // ignore and fall through to cold. + // + // Checkpoint restore composes with KV-quant. + // `admitRestoredCheckpoint` rebuilds full-attention rows as QUANTIZED + // batched caches via the cold cache factory + // (`restoredFullAttentionCache`), so a restored row stays concrete- + // class-compatible with quantized cold rows under `extendBatched`. + // The engine-tier warm prefix path (`prefixCache` → + // `doExternalPrefill` + `BatchKVCache.merge`) still rebuilds fp16 + // only, so it stays cold-only under quantization until it too + // rebuilds quantized rows. if let rc = request.restoredCheckpoint, rc.tokenCount >= 1, rc.tokenCount < promptTokens.count, rc.caches.count == model.newCache(parameters: nil).count @@ -557,7 +668,7 @@ public final class Scheduler: @unchecked Sendable { restoredCaches = rc.caches tokensToPrefill = Array(promptTokens[rc.tokenCount...]) request.cachedTokens = rc.tokenCount - } else if let pc = prefixCache { + } else if config.kvQuantization == nil, let pc = prefixCache { let (cached, remaining) = pc.fetchPrefix( requestId: request.requestId, tokens: promptTokens) if let cached { @@ -699,6 +810,8 @@ public final class Scheduler: @unchecked Sendable { stateMachines: warmMachines, mtpRuntime: mtpRuntime ) + warmGen.skipLogprobNormalization = Self.batchCanSkipLogprobNorm( + warm.map { $0.request.samplingParams }) mergeIntoGenBatch(warmGen) } @@ -721,7 +834,11 @@ public final class Scheduler: @unchecked Sendable { return toks.count > 1 ? Array(toks.dropLast()) : [] } let seeds = cold.map { $0.tokensToPrefill.last ?? 0 } - pendingPrefill = PendingPrefill(ppBatch: ppBatch, remaining: remaining, seeds: seeds) + let skipLogprobNorm = Self.batchCanSkipLogprobNorm( + cold.map { $0.request.samplingParams }) + pendingPrefill = PendingPrefill( + ppBatch: ppBatch, remaining: remaining, seeds: seeds, + skipLogprobNorm: skipLogprobNorm) } return newScheduled @@ -761,14 +878,22 @@ public final class Scheduler: @unchecked Sendable { // it's rejected on either side. var batched: [any BatchedCache] = [] batched.reserveCapacity(restored.count) - for (layer, exp) in zip(restored, expected) { + for (idx, (layer, exp)) in zip(restored, expected).enumerated() { if layer is ChunkedKVCache || exp is ChunkedKVCache { admitColdFallback(entry) // unsupported subclass return false } else if let rot = layer as? RotatingKVCache, exp is RotatingKVCache { batched.append(BatchRotatingKVCache.fromSingleRow(rot)) } else if let simple = layer as? KVCacheSimple, exp is KVCacheSimple { - batched.append(BatchKVCache.merge([simple])) + // Build a batched cache matching the cold path's + // per-layer type so a restored row stays concrete-class- + // compatible with quantized cold rows under `extendBatched`. + // Under KV-quant the cold factory yields a + // QuantizedBatchKVCacheBase for eligible full-attention layers; + // re-quantize the restored fp16 prefix into it via `update()` + // (the same path cold prefill uses). KV-quant off → fp16 + // `BatchKVCache.merge`. + batched.append(restoredFullAttentionCache(layerIndex: idx, restored: simple)) } else { // Type mismatch (e.g. Rotating where the model wants Simple), // recurrent, or unknown — restore is unsound; cold-prefill. @@ -795,10 +920,34 @@ public final class Scheduler: @unchecked Sendable { stateMachines: [entry.machine] ) let gen = ppBatch.generate(lastTokensOf: [suffix], mtpRuntime: mtpRuntime) + gen.skipLogprobNormalization = Self.batchCanSkipLogprobNorm([entry.request.samplingParams]) mergeIntoGenBatch(gen) return true } + /// Build the batched cache for a restored full-attention layer, matching + /// the cold path's per-layer cache type. Under KV-quant the cold factory + /// (`cacheFactories`) produces a `QuantizedBatchKVCacheBase`; ingest the + /// restored fp16 K/V via `update()` so the prefix is re-quantized into the + /// exact layout cold rows use — keeping each genBatch layer a single + /// concrete class (an `extendBatched` precondition). When the layer is not + /// quantized (KV-quant off, or ineligible) fall back to fp16 + /// `BatchKVCache.merge`. + private func restoredFullAttentionCache( + layerIndex: Int, restored: KVCacheSimple + ) -> any BatchedCache { + let coldCache = cacheFactories[layerIndex](1) + guard let quant = coldCache as? QuantizedBatchKVCacheBase else { + return BatchKVCache.merge([restored]) + } + let st = restored.state + guard st.count == 2 else { return BatchKVCache.merge([restored]) } + // `update` quantizes the incoming fp16 K/V and appends along the time + // axis (B==1, T = restored prefix length), exactly as cold prefill does. + _ = quant.update(keys: st[0], values: st[1]) + return quant + } + /// Fallback when a restored cache can't be rebuilt (an unsupported layer /// type slipped past the provider's capability gate). Fully unwinds the /// admission state this entry already took (mirroring `preemptOne`), @@ -839,24 +988,146 @@ public final class Scheduler: @unchecked Sendable { return SequenceStateMachine(states: ["normal": seqs]) } + /// Whether a decode batch made up of rows with these sampling params can + /// skip the per-step `logSumExp` normalization in `GenerationBatch.step()`. + /// + /// Safe to skip only when NO row needs normalized logprobs: + /// - a penalty sampler (repetition/presence/frequency) applies a transform + /// that is not invariant to the constant `logSumExp` shift, and + /// - an active top-p (nucleus) filter compares a cumulative probability mass + /// against `1 - topP`, which is also not shift-invariant. + /// Temperature scaling, top-k, min-p, categorical and argMax are all + /// shift-invariant, so a pure-temperature / greedy batch can skip it. + /// Mirrors the exact predicates in `makeRowSampler` / `makeRepetitionSampler`. + private static func batchCanSkipLogprobNorm(_ params: [SamplingParams]) -> Bool { + !params.contains { p in + let needsPenalty = + p.repetitionPenalty != 1.0 + || p.presencePenalty != 0.0 + || p.frequencyPenalty != 0.0 + let topPActive = p.temperature != 0 && p.topP > 0 && p.topP < 1 + return needsPenalty || topPActive + } + } + private lazy var cacheFactories: [(Int) -> any BatchedCache] = { - model.newCache(parameters: nil).map { layer -> (Int) -> any BatchedCache in - if layer is MambaCache { - return { MambaCache(leftPadding: Array(repeating: 0, count: $0)) } + let quantConfig = config.kvQuantization + return model.newCache(parameters: nil).map { layer -> (Int) -> any BatchedCache in + Self.makeCacheFactory(for: layer, quantConfig: quantConfig) + } + }() + + private func makeBatchedCache(batchSize B: Int) -> [any BatchedCache] { + cacheFactories.map { $0(B) } + } + + /// Internal decision of which batched cache type to build for a layer. + /// Kept in one place so the production factory and the test-facing + /// type-name helper cannot drift. + private enum CacheFactoryKind: Sendable { + case mamba + case arrays(size: Int) + case rotating(maxSize: Int) + case quantized(config: KVQuantizationConfig) + case fp16 + + var typeName: String { + switch self { + case .mamba: return String(describing: MambaCache.self) + case .arrays: return String(describing: ArraysCache.self) + case .rotating: return String(describing: BatchRotatingKVCache.self) + case .quantized(let config): + switch config.cacheKind { + case .kernel: return String(describing: QuantizedBatchKVCache.self) + case .dequant: return String(describing: DequantBatchKVCache.self) + } + case .fp16: return String(describing: BatchKVCache.self) } - if let arrays = layer as? ArraysCache { - let size = arrays.slotCount - return { ArraysCache(size: size, leftPadding: Array(repeating: 0, count: $0)) } + } + } + + private static func cacheFactoryKind( + for layer: any KVCache, + quantConfig: KVQuantizationConfig? + ) -> CacheFactoryKind { + if layer is MambaCache { + return .mamba + } + if let arrays = layer as? ArraysCache { + return .arrays(size: arrays.slotCount) + } + if let rotating = layer as? RotatingKVCache, let maxSize = rotating.maxSize { + return .rotating(maxSize: maxSize) + } + // Composite caches (e.g. CacheList = MambaCache + KVCacheSimple in + // BaichuanM1 / FalconH1) must not be replaced wholesale by a quantized + // KV cache: those models downcast the per-layer cache back to CacheList + // in their forward pass. Only plain full-attention layers are eligible + // for KV-quant; leave everything else on the existing fp16 path. + if layer is CacheList { + return .fp16 + } + if let quantConfig { + // Only plain full-attention `KVCacheSimple` layers are eligible for KV + // quantization. `ChunkedKVCache` (a `KVCacheSimple` subclass with + // bespoke chunked semantics) and any non-`KVCacheSimple` custom cache + // (e.g. `DeepseekV4LayerCache`, which the model downcasts back to its + // concrete type in its attention path) must stay fp16: quantizing them + // would trip a downcast or silently drop their semantics. RotatingKVCache + // is already handled above and is not a `KVCacheSimple` subclass. + if layer is KVCacheSimple, !(layer is ChunkedKVCache) { + return .quantized(config: quantConfig) } - if let rotating = layer as? RotatingKVCache, let maxSize = rotating.maxSize { - return { BatchRotatingKVCache(maxSize: maxSize, leftPadding: Array(repeating: 0, count: $0)) } + return .fp16 + } + return .fp16 + } + + /// Build a single cache factory for a layer, optionally using quantized + /// storage for full-attention layers. Exposed publicly so provider tests + /// can verify per-layer factory selection without constructing a live model. + public static func makeCacheFactory( + for layer: any KVCache, + quantConfig: KVQuantizationConfig? + ) -> (Int) -> any BatchedCache { + switch cacheFactoryKind(for: layer, quantConfig: quantConfig) { + case .mamba: + return { MambaCache(leftPadding: Array(repeating: 0, count: $0)) } + case .arrays(let size): + return { ArraysCache(size: size, leftPadding: Array(repeating: 0, count: $0)) } + case .rotating(let maxSize): + return { BatchRotatingKVCache(maxSize: maxSize, leftPadding: Array(repeating: 0, count: $0)) } + case .quantized(let config): + return { + switch config.cacheKind { + case .kernel: + QuantizedBatchKVCache( + leftPadding: Array(repeating: 0, count: $0), + groupSize: config.groupSize, + bits: config.bits, + mode: config.mode + ) + case .dequant: + DequantBatchKVCache( + leftPadding: Array(repeating: 0, count: $0), + groupSize: config.groupSize, + bits: config.bits, + mode: config.mode + ) + } } + case .fp16: return { BatchKVCache(leftPadding: Array(repeating: 0, count: $0)) } } - }() + } - private func makeBatchedCache(batchSize B: Int) -> [any BatchedCache] { - cacheFactories.map { $0(B) } + /// Test-facing type-name helper. Avoids instantiating caches (which would + /// require a Metal device) while still pinning the exact per-layer selection. + public static func cacheFactoryTypeName( + for layer: any KVCache, + quantConfig: KVQuantizationConfig? + ) -> String { + cacheFactoryKind(for: layer, quantConfig: quantConfig).typeName } private func doExternalPrefill( @@ -916,14 +1187,14 @@ extension Scheduler { let newText: String if !isFinished { request.appendOutputToken(tokenId) - tokenHistories[rid]?.tokens.append(tokenId) + tokenHistories[rid]?.append(tokenId) var detok = activeDetokenizers[rid]! detok.append(token: tokenId) newText = detok.next() ?? "" activeDetokenizers[rid] = detok } else if resp.finishReason == "length" { request.appendOutputToken(tokenId) - tokenHistories[rid]?.tokens.append(tokenId) + tokenHistories[rid]?.append(tokenId) newText = "" } else { newText = "" diff --git a/Libraries/MLXLMCommon/GenerationBatch.swift b/Libraries/MLXLMCommon/GenerationBatch.swift index 4e70831558..af145ae6f1 100644 --- a/Libraries/MLXLMCommon/GenerationBatch.swift +++ b/Libraries/MLXLMCommon/GenerationBatch.swift @@ -62,6 +62,29 @@ public final class GenerationBatch: @unchecked Sendable { public let fallbackSampler: RowSampler public private(set) var stateMachines: [SequenceStateMachine] + /// When true, `step()` skips the per-step `logSumExp` normalization of the + /// decode logits and hands the raw logits to the row samplers. This is a + /// pure host/GPU-overhead optimization and is **only** safe when no active + /// row needs the normalized logprobs: temperature scaling, top-k, min-p, + /// categorical and argMax are all invariant to the per-row constant + /// `logSumExp` shift, but top-p (nucleus) sampling's cumulative-probability + /// threshold is not, and the repetition/presence/frequency penalty sampler + /// applies its (non-shift-invariant) transform to the values it receives. + /// + /// The `Scheduler` sets this from the admitted rows' sampling params (it is + /// the only place that knows them); it defaults to `false` so any batch that + /// is never told otherwise keeps the exact previous behavior. `extend` + /// combines with logical AND so a merged batch normalizes if *either* side + /// needed it. + public var skipLogprobNormalization: Bool = false + + /// When false, finished rows skip the `extractBatched` dequant-and-copy of + /// their prompt cache (only a prefix cache consumes it). The scheduler sets + /// this true only when a prefix cache is active, so runs without prefix + /// caching — e.g. KV-quant models whose prefix tier isn't the in-GPU block + /// cache — don't pay a per-finish fp16 copy of the KV history. + public var capturePromptCacheOnFinish: Bool = false + /// Tokens queued for the next model call. At construction this is the /// final prompt token for each row. After priming, and after every /// decode step, it holds the sampled token that should be returned on @@ -189,7 +212,8 @@ public final class GenerationBatch: @unchecked Sendable { } if finishReason != nil { - let extracted: [any KVCache] = promptCache.map { $0.extractBatched(i) } + let extracted: [any KVCache]? = + capturePromptCacheOnFinish ? promptCache.map { $0.extractBatched(i) } : nil responses.append( GenerationBatchResponse( uid: uids[i], @@ -283,6 +307,9 @@ public final class GenerationBatch: @unchecked Sendable { matcherStates.append(contentsOf: other.matcherStates) numTokens.append(contentsOf: other.numTokens) nextTokens = concatenated([nextTokens, other.nextTokens], axis: 0) + // Only keep skipping normalization if BOTH batches were safe to skip; + // a single incoming top-p / penalty row forces normalization again. + skipLogprobNormalization = skipLogprobNormalization && other.skipLogprobNormalization // MTP: transfer state from donor batch when BatchGenerator merges a fresh // single-sequence batch into self via extend(). The MTP post-init fires on // the donor (whose __init__ ran with uids=[1]); without this transfer the @@ -384,7 +411,16 @@ public final class GenerationBatch: @unchecked Sendable { let sampledTokens: MLXArray if samplers.contains(where: { $0 != nil }) { - let logprobs = stepLogits - logSumExp(stepLogits, axis: -1, keepDims: true) + // The `logSumExp` reduction over the full vocabulary is only needed + // when a row uses top-p (or a penalty sampler keyed on logprobs). + // When no active row needs it (`skipLogprobNormalization`), pass the + // raw logits through: every other filter/sampler is invariant to the + // per-row constant shift, so results are unchanged. See the property + // doc on `skipLogprobNormalization`. + let logprobs = + skipLogprobNormalization + ? stepLogits + : stepLogits - logSumExp(stepLogits, axis: -1, keepDims: true) var samples: [MLXArray] = [] samples.reserveCapacity(uids.count) for i in 0 ..< uids.count { @@ -408,7 +444,15 @@ public final class GenerationBatch: @unchecked Sendable { asyncEval(sampledTokens) eval(currentTokens) - let stepTokens = currentTokens.asArray(UInt32.self).map { Int($0) } + // For the common single-row batch, read the one scalar via `item` + // instead of materializing a 1-element Swift array. Multi-row batches + // keep the bulk `asArray` extraction unchanged. + let stepTokens: [Int] + if uids.count == 1 { + stepTokens = [currentTokens.item(Int.self)] + } else { + stepTokens = currentTokens.asArray(UInt32.self).map { Int($0) } + } for (i, t) in stepTokens.enumerated() { tokens[i].append(t) diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index 8152aa8335..92e43bf63b 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -1756,6 +1756,60 @@ public typealias StandardKVCache = KVCacheSimple // MARK: - Quantized Attention Operations +// Compiled, shape-agnostic softmax cores for `quantizedScaledDotProductAttention`. +// +// The softmax over the score tensor is the largest cluster of small elementwise +// kernels in the quantized-attention path (max, sub, exp, where, sum, div) — +// each a separate GPU dispatch. Wrapping it in `compile(shapeless:)` fuses those +// launches into a single graph and cuts the per-step launch overhead that +// dominates decode latency. +// +// `shapeless: true` is what makes this safe on the decode path. During +// single-query decode the query length is 1 but the cached-KV (`kL`) axis grows +// by one every token, so the score tensor's *shape* changes every step. A +// shapeless graph is NOT recompiled when only shapes change — only a change in +// rank (ndim) or dtype forces a recompile. The score tensor is always rank-4 +// (`[B, nQHeads, L, kL]`, collapsed below before softmax) and keeps a stable +// dtype during a run, so the graph compiles once and is reused for every step; +// there is no per-shape recompilation churn. +// +// The cores use only `axis: -1` reductions and broadcasts, so they are +// independent of batch size, head count, query length and `kL`, and they carry +// no quantization parameters (groupSize/bits/mode live in the surrounding +// `quantizedMM` calls, which stay outside the compiled core). The matmuls +// themselves are intentionally left out: each is a single large kernel whose +// launch overhead is marginal, and folding the GQA reshape (which depends on the +// batch axis) into a shapeless graph would bake in a stale batch constant. +// +// Numerics are identical to the previous inline version — the same ops in the +// same order, just fused into one graph. + +/// Stable no-sink softmax. Keeps fully-masked query rows finite by assigning +/// zero probability to every key (there is no sink to absorb the mass). +private let compiledQuantizedAttentionSoftmax: @Sendable (MLXArray) -> MLXArray = compile( + shapeless: true +) { scores in + let rowMax = scores.max(axis: -1, keepDims: true) + let validRow = rowMax .> MLXArray(-Float.greatestFiniteMagnitude / 2) + let expScores = MLX.where(validRow, exp(scores - rowMax), MLXArray(Float(0))) + let denom = expScores.sum(axis: -1, keepDims: true) + return MLX.where(denom .> MLXArray(Float(0)), expScores / denom, MLXArray(Float(0))) +} + +/// Sink-aware stable softmax with the sink folded into the denominator. +/// `sinkLogits` is pre-reshaped to `[1, nQHeads, 1, 1]` by the caller so the +/// compiled core stays a pure elementwise/broadcast graph (the reshape uses +/// `nQHeads`, a per-config constant we deliberately keep out of the core). +private let compiledQuantizedAttentionSoftmaxWithSink: @Sendable (MLXArray, MLXArray) -> MLXArray = + compile(shapeless: true) { scores, sinkLogits in + let rowMax = scores.max(axis: -1, keepDims: true) + let m = maximum(rowMax, sinkLogits) + let expScores = exp(scores - m) + let sinkExp = exp(sinkLogits - m) + let denom = expScores.sum(axis: -1, keepDims: true) + sinkExp + return expScores / denom + } + public func quantizedScaledDotProductAttention( queries: MLXArray, quantizedKeys: (MLXArray, MLXArray, MLXArray?), @@ -1764,7 +1818,8 @@ public func quantizedScaledDotProductAttention( mask: MLXFast.ScaledDotProductAttentionMaskMode = .none, groupSize: Int = 64, bits: Int = 8, - mode: QuantizationMode = .affine + mode: QuantizationMode = .affine, + sinks: MLXArray? = nil ) -> MLXArray { let (B, nQHeads, L, D) = (queries.dim(0), queries.dim(1), queries.dim(2), queries.dim(3)) @@ -1791,26 +1846,36 @@ public func quantizedScaledDotProductAttention( ) } - // Compute attention scores using quantized matmul - var scores = quantizedMM( + // Compute attention scores using quantized matmul. In the GQA case this is + // 5D [B, nKVHeads, nRepeats, L, kL]; otherwise 4D [B, nQHeads, L, kL]. + let rawScores = quantizedMM( scaledQueries, qKeys.0, scales: qKeys.1, biases: qKeys.2, transpose: true, groupSize: groupSize, bits: bits, mode: mode ) + let kL = rawScores.dim(-1) + + // Collapse to the canonical 4D [B, nQHeads, L, kL] layout for masking, sink, + // and softmax. This is required for correctness with GQA *and* batching: + // standard attention masks are [B, 1, L, kL] / [B, nQHeads, L, kL] / [L, kL] + // and cannot broadcast against the 5D GQA score tensor when B > 1 (the 5D + // path only "worked" at B == 1 because the leading 1s happened to broadcast). + var scores = nRepeats > 1 ? rawScores.reshaped([B, nQHeads, L, kL]) : rawScores // Apply mask 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 (qL, kLen) = (scores.dim(-2), scores.dim(-1)) + let qIndices = MLXArray(0 ..< qL) + MLXArray(kLen - qL) + let kIndices = MLXArray(0 ..< kLen) let causalMask = greaterEqual( expandedDimensions(qIndices, axis: -1), expandedDimensions(kIndices, axis: -2)) - scores = MLX.where(causalMask, scores, MLXArray(Float.leastNormalMagnitude)) + // Local patch: keep -Float.greatestFiniteMagnitude here until the upstream fix lands. + scores = MLX.where(causalMask, scores, MLXArray(-Float.greatestFiniteMagnitude)) case .array(let maskArray): if maskArray.dtype == .bool { - scores = MLX.where(maskArray, scores, MLXArray(Float.leastNormalMagnitude)) + scores = MLX.where(maskArray, scores, MLXArray(-Float.greatestFiniteMagnitude)) } else { scores = scores + maskArray } @@ -1819,7 +1884,7 @@ public func quantizedScaledDotProductAttention( // Handle multiple mask arrays - just use the first one for simplicity if let maskArray = maskArrays.first { if maskArray.dtype == .bool { - scores = MLX.where(maskArray, scores, MLXArray(Float.leastNormalMagnitude)) + scores = MLX.where(maskArray, scores, MLXArray(-Float.greatestFiniteMagnitude)) } else { scores = scores + maskArray } @@ -1829,7 +1894,37 @@ public func quantizedScaledDotProductAttention( break } - let attentionWeights = softmax(scores, axis: -1) + let attentionWeights4D: MLXArray + if let sinks { + // Attention sink: a learned per-(query)head logit that acts as one extra + // "virtual" key in the softmax — it has no value vector, so it only + // absorbs softmax mass, making the real-token weights sum to < 1. + // (Equivalent to concatenating `sinks` as an extra score column and + // dropping it after softmax, but done without concat/slice so the + // weights stay contiguous for `quantizedMM`.) A no-sink cache is the + // `sink -> -inf` limit, i.e. `sinks == nil` below, NOT a zero sink. + // + // In the canonical 4D layout `sinks` ([nQHeads]) maps directly onto the + // head axis. The reshape stays outside the compiled core so the core + // never bakes in a head-count constant. The fused, numerically-stable + // softmax then folds the sink into the denominator. + let sinkLogits = sinks.reshaped([1, nQHeads, 1, 1]) + attentionWeights4D = compiledQuantizedAttentionSoftmaxWithSink(scores, sinkLogits) + } else { + // Fused, stable no-sink softmax. Unlike the generic softmax, this keeps + // fully masked query rows finite by assigning zero probability to every + // real key (there is no sink to absorb probability mass). Model code + // ignores padded query rows, but keeping them finite avoids NaN + // propagation. + attentionWeights4D = compiledQuantizedAttentionSoftmax(scores) + } + + // Restore the GQA-expanded layout [B, nKVHeads, nRepeats, L, kL] for the value + // matmul (qValues were expanded along axis -3 above). + let attentionWeights = + nRepeats > 1 + ? attentionWeights4D.reshaped([B, nKVHeads, nRepeats, L, kL]) + : attentionWeights4D // Compute output using quantized matmul var output = quantizedMM( diff --git a/Libraries/MLXLMCommon/QuantizedBatchKVCache.swift b/Libraries/MLXLMCommon/QuantizedBatchKVCache.swift new file mode 100644 index 0000000000..d95128b128 --- /dev/null +++ b/Libraries/MLXLMCommon/QuantizedBatchKVCache.swift @@ -0,0 +1,634 @@ +import Foundation +import MLX + +/// Quantized, continuously-batchable KV cache. +/// +/// Mirrors ``BatchKVCache`` in layout (right-justified per-row storage with +/// `leftPadding` / `batchOffset`) but stores keys and values as quantized +/// tuples `(wq, scales, biases?)`. New tokens are quantized incrementally +/// (`O(step)`) and appended along the time axis; the full logical view can be +/// returned either dequantized (``update(keys:values:)``) or as quantized +/// tuples (``updateQuantized(keys:values:)``) for the native quantized +/// attention kernel. +public final class QuantizedBatchKVCache: QuantizedBatchKVCacheBase, + QuantizedKVCacheProtocol +{ +} + +/// Quantized-storage, continuously-batchable KV cache that does **not** +/// conform to ``QuantizedKVCacheProtocol``. +/// +/// Use this for models whose quantized attention kernel is not sink-safe +/// (e.g. GPT-OSS). The cache still stores K/V in quantized form for the +/// capacity win, but ``update(keys:values:)`` returns dequantized fp16 so the +/// model falls back to the regular sink-aware attention path. +public final class DequantBatchKVCache: QuantizedBatchKVCacheBase { + /// Because this path returns dequantized fp16 K/V and attends through the + /// regular `MLXFast.scaledDotProductAttention`, it must mirror the fast-path + /// in ``BatchKVCache/makeMask(n:windowSize:returnArray:)``: for single-token + /// decode with no left padding, return `.none` so SDPA takes its unmasked + /// kernel path. Passing an explicit (all-`true`) mask here routes SDPA + /// through the divergent MLX #3384 branch whose numerical drift flips top-1 + /// logprobs on quantized Gemma 4 and traps continuous-batched decode in + /// repetition loops. The base class (kernel path) keeps its always-masked + /// behavior, which is what the Gemma 4 g128 kernel scheme was validated on. + public override func makeMask( + n: Int, windowSize: Int?, returnArray returnArrayFlag: Bool + ) -> MLXFast.ScaledDotProductAttentionMaskMode { + if n == 1, leftPadding.max().item(Int32.self) <= 0 { + return .none + } + return super.makeMask(n: n, windowSize: windowSize, returnArray: returnArrayFlag) + } +} + +/// Base implementation for quantized batched KV caches. +/// +/// Holds all the storage, batched-cache logic, and the dequantizing +/// ``update(keys:values:)`` path. The two final subclasses differ only in +/// whether they also conform to ``QuantizedKVCacheProtocol`` (the native +/// quantized-kernel path) or stay off that path (the dequant-only path). +public class QuantizedBatchKVCacheBase: BaseKVCache, BatchPositionedKVCache, + BatchedCache +{ + + // MARK: - Quantization parameters + + public let groupSize: Int + public let bits: Int + public let mode: QuantizationMode + + // MARK: - BatchedCache / BatchPositionedKVCache + + /// Allocation chunk size along the time axis. + public static let allocationStep = 256 + + /// Per-row position counter `[B]`. Starts at `-leftPadding[b]`. + public private(set) var batchOffset: MLXArray + + /// Per-row left padding `[B]`. + public private(set) var leftPadding: MLXArray + + // MARK: - Storage + + /// Quantized key tuple: `(wq, scales, biases?)`. Time axis is `-2`. + private var keys: (MLXArray, MLXArray, MLXArray?)? + + /// Quantized value tuple: `(wq, scales, biases?)`. Time axis is `-2`. + private var values: (MLXArray, MLXArray, MLXArray?)? + + /// Rightmost-valid slot along the time axis. + private var _idx: Int = 0 + + /// Pending right-padding applied by ``finalizeBatched()``. + private var _rightPadding: MLXArray? + + public override var offset: Int { + get { _idx } + set { _idx = newValue } + } + + public override var maxSize: Int? { nil } + public override var isTrimmable: Bool { true } + + // MARK: - Init + + public required init( + leftPadding: [Int], + groupSize: Int = 64, + bits: Int = 8, + mode: QuantizationMode = .affine + ) { + self.groupSize = groupSize + self.bits = bits + self.mode = mode + self.leftPadding = MLXArray(leftPadding.map { Int32($0) }) + self.batchOffset = MLXArray(leftPadding.map { Int32(-$0) }) + super.init() + } + + fileprivate init( + groupSize: Int, + bits: Int, + mode: QuantizationMode, + keys: (MLXArray, MLXArray, MLXArray?)?, + values: (MLXArray, MLXArray, MLXArray?)?, + offset: MLXArray, + leftPadding: MLXArray, + idx: Int, + rightPadding: MLXArray? + ) { + self.groupSize = groupSize + self.bits = bits + self.mode = mode + self.keys = keys + self.values = values + self.batchOffset = offset + self.leftPadding = leftPadding + self._idx = idx + self._rightPadding = rightPadding + super.init() + } + + // MARK: - Update + + /// Append `[B, kvHeads, T, D]` keys/values, quantize only the incoming + /// slice, and return the **dequantized** full logical view. This is the + /// fallback path for models without a quantized attention kernel. + public override func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + let (quantizedKeys, quantizedValues) = updateQuantized(keys: keys, values: values) + + let dequantizedKeys = dequantized( + quantizedKeys.0, + scales: quantizedKeys.1, + biases: quantizedKeys.2, + groupSize: groupSize, + bits: bits, + mode: mode + ) + let dequantizedValues = dequantized( + quantizedValues.0, + scales: quantizedValues.1, + biases: quantizedValues.2, + groupSize: groupSize, + bits: bits, + mode: mode + ) + + return (dequantizedKeys, dequantizedValues) + } + + /// Append `[B, kvHeads, T, D]` keys/values, quantize only the incoming + /// slice, and return the **quantized** full logical view. + public func updateQuantized(keys: MLXArray, values: MLXArray) -> ( + (MLXArray, MLXArray, MLXArray?), (MLXArray, MLXArray, MLXArray?) + ) { + let prev = _idx + let stepCount = keys.dim(2) + let B = keys.dim(0) + let nKVHeads = keys.dim(1) + let kHeadDim = keys.dim(3) + let vHeadDim = values.dim(3) + + precondition( + kHeadDim % groupSize == 0 && vHeadDim % groupSize == 0, + "QuantizedBatchKVCacheBase requires groupSize to divide head_dim" + ) + + var currentKeys = self.keys + var currentValues = self.values + + let needGrow: Bool = { + guard let storedKeys = currentKeys else { return true } + return (prev + stepCount) > storedKeys.0.dim(-2) + }() + + if needGrow { + let nSteps = (Self.allocationStep + stepCount - 1) / Self.allocationStep + let newShape = [B, nKVHeads, nSteps * Self.allocationStep] + + if var existingKeys = currentKeys, var existingValues = currentValues { + if prev % Self.allocationStep != 0 { + existingKeys = trimmedTo(existingKeys, limit: prev) + existingValues = trimmedTo(existingValues, limit: prev) + } + currentKeys = expandQuant(existingKeys, newShape: newShape) + currentValues = expandQuant(existingValues, newShape: newShape) + } else { + currentKeys = initQuant(dim: kHeadDim, shape: newShape, dtype: keys.dtype) + currentValues = initQuant(dim: vHeadDim, shape: newShape, dtype: keys.dtype) + } + + self.keys = currentKeys + self.values = currentValues + } + + guard var ck = currentKeys, var cv = currentValues else { + fatalError("QuantizedBatchKVCacheBase storage not initialized") + } + + let qk = quantized(keys, groupSize: groupSize, bits: bits) + let qv = quantized(values, groupSize: groupSize, bits: bits) + let newKeys = (qk.wq, qk.scales, qk.biases) + let newValues = (qv.wq, qv.scales, qv.biases) + + _idx += stepCount + batchOffset = batchOffset + Int32(stepCount) + + assign(into: &ck, from: newKeys, range: prev..<_idx) + assign(into: &cv, from: newValues, range: prev..<_idx) + + self.keys = ck + self.values = cv + + // Collapse the per-step `batchOffset` lazy chain on decode, + // mirroring `BatchKVCache.update`. gemma-4 shares one RoPE + // `perRowOffset` from the first cache (Gemma4.swift:1264), so other + // caches never consume their own `batchOffset` and leak a tiny scalar + // buffer/step (COUNT leak, flat bytes) until the iogpu `numResources` + // ceiling aborts. `asyncEval` detaches it, no GPU sync. Prefill + // untouched. + if stepCount == 1 { + asyncEval(batchOffset) + } + + return (trimmedTo(ck, limit: _idx), trimmedTo(cv, limit: _idx)) + } + + public func getQuantizedState() -> ( + (MLXArray, MLXArray, MLXArray?), (MLXArray, MLXArray, MLXArray?) + )? { + guard let keys = keys, let values = values else { return nil } + return (trimmedTo(keys, limit: _idx), trimmedTo(values, limit: _idx)) + } + + // MARK: - Mask + + public override func makeMask( + n: Int, windowSize: Int?, returnArray _: Bool + ) -> MLXFast.ScaledDotProductAttentionMaskMode { + // Single-query decode fast path: one query attends to every stored key, + // so the causal mask is all-`true` — a no-op. Skip building and applying + // it on the kernel path. This is only valid when nothing would actually + // be masked: + // * `windowSize == nil` — a sliding window would mask keys older than + // the window. This cache stores all tokens (it grows; it does not + // evict), so a windowed layer still needs the materialized mask. + // * `leftPadding.max() <= 0` — left padding would mask the leading + // padded slots of right-justified rows. + // Under both conditions the omitted mask is bit-identical to the + // materialized all-`true` mask (in `quantizedScaledDotProductAttention`, + // `.none` skips the masking step while an all-`true` array mask leaves + // every score untouched), so decode numerics are preserved exactly while + // saving the per-step `createCausalMask` build and `where` application. + // The `n == 1` / `windowSize == nil` checks short-circuit before the + // `leftPadding` device sync, so prefill (n > 1) never pays for it. + // For n > 1 (prefill / chunked) the mask is materialized exactly as + // before. Mirrors `BatchKVCache.makeMask`'s fast path. + if n == 1, windowSize == nil, leftPadding.max().item(Int32.self) <= 0 { + return .none + } + let mask = createCausalMask( + n: n, + offset: _idx, + windowSize: windowSize, + leftPadding: leftPadding + ) + return .array(mask) + } + + // MARK: - BatchedCache + + public func prepareBatched( + leftPadding additionalLeftPadding: [Int]?, + lengths _: [Int]?, + rightPadding: [Int]? + ) { + if let additionalLeftPadding { + precondition( + keys == nil, + "prepareBatched() with leftPadding can only be called on an empty QuantizedBatchKVCacheBase" + ) + let additional = MLXArray(additionalLeftPadding.map { Int32($0) }) + leftPadding = leftPadding + additional + batchOffset = batchOffset - additional + } + + if let rightPadding, rightPadding.contains(where: { $0 > 0 }) { + _rightPadding = MLXArray(rightPadding.map { Int32($0) }) + } + } + + public func finalizeBatched() { + guard let pending = _rightPadding else { return } + guard let storedK = keys, let storedV = values else { + _rightPadding = nil + return + } + + let shifts = pending[0..., .newAxis] + keys = treeMap({ dynamicRoll($0, shifts: shifts, axis: 2) }, storedK) + values = treeMap({ dynamicRoll($0, shifts: shifts, axis: 2) }, storedV) + batchOffset = batchOffset - pending + leftPadding = leftPadding + pending + _rightPadding = nil + } + + public func filterBatched(batchIndices: MLXArray) { + if keys != nil { + keys = treeMap({ take($0, batchIndices, axis: 0) }, keys!) + values = treeMap({ take($0, batchIndices, axis: 0) }, values!) + } + batchOffset = take(batchOffset, batchIndices, axis: 0) + leftPadding = take(leftPadding, batchIndices, axis: 0) + + let minLeftPad = leftPadding.min().item(Int32.self) + if minLeftPad > 0 { + let minPadInt = Int(minLeftPad) + if let storedK = keys, let storedV = values { + keys = treeMap({ $0[.ellipsis, minPadInt..., 0...] }, storedK) + values = treeMap({ $0[.ellipsis, minPadInt..., 0...] }, storedV) + } + _idx -= minPadInt + leftPadding = leftPadding - Int32(minPadInt) + } + } + + public func extendBatched(_ other: any BatchedCache) { + guard let other = other as? QuantizedBatchKVCacheBase else { + preconditionFailure( + "QuantizedBatchKVCacheBase.extendBatched requires another QuantizedBatchKVCacheBase" + ) + } + extend(other) + } + + public func extractBatched(_ idx: Int) -> any KVCache { + let cache = KVCacheSimple() + guard let storedK = keys, let storedV = values else { + return cache + } + + let leftPad = max(0, Int(leftPadding[idx].item(Int32.self))) + let kTuple = treeMap( + { $0[idx..<(idx + 1), 0..., leftPad..<_idx, 0...] }, storedK) + let vTuple = treeMap( + { $0[idx..<(idx + 1), 0..., leftPad..<_idx, 0...] }, storedV) + + let kDQ = dequantized( + kTuple.0, scales: kTuple.1, biases: kTuple.2, + groupSize: groupSize, bits: bits, mode: mode) + let vDQ = dequantized( + vTuple.0, scales: vTuple.1, biases: vTuple.2, + groupSize: groupSize, bits: bits, mode: mode) + + eval(kDQ, vDQ) + cache.state = [kDQ, vDQ] + return cache + } + + public func advanceBatched(_: Int) {} + + // MARK: - Extend (in-place admission) + + /// In-place concatenation of another batched cache's rows onto this one. + /// Both caches are padded to the same right-justified time-axis size, then + /// concatenated along the batch axis. + public func extend(_ other: QuantizedBatchKVCacheBase) { + precondition( + groupSize == other.groupSize && bits == other.bits && mode == other.mode, + "QuantizedBatchKVCacheBase.extend requires matching quantization params" + ) + + if keys == nil && other.keys == nil { + leftPadding = concatenated([leftPadding, other.leftPadding], axis: 0) + batchOffset = concatenated([batchOffset, other.batchOffset], axis: 0) + return + } + + let maxIdx = max(_idx, other._idx) + var L1 = 0 + var L2 = 0 + var H = 0 + var Dk = 0 + var Dv = 0 + + if let storedK = keys { + L1 = storedK.0.dim(-2) + H = storedK.0.dim(-3) + // The unpacked head dim is derived from the scales, not the packed + // weights, so the empty-cache branch creates correctly-shaped zeros. + Dk = storedK.1.dim(-1) * groupSize + Dv = values!.1.dim(-1) * groupSize + } + if let storedK = other.keys { + L2 = storedK.0.dim(-2) + H = storedK.0.dim(-3) + Dk = storedK.1.dim(-1) * groupSize + Dv = other.values!.1.dim(-1) * groupSize + } + let maxSize = max(L1, L2) + + func pad( + _ cacheKeys: (MLXArray, MLXArray, MLXArray?)?, + _ cacheValues: (MLXArray, MLXArray, MLXArray?)?, + cacheIdx: Int, + cacheOffset: MLXArray, + cacheLeftPadding: MLXArray + ) -> ((MLXArray, MLXArray, MLXArray?), (MLXArray, MLXArray, MLXArray?), MLXArray, MLXArray) + { + var k: (MLXArray, MLXArray, MLXArray?) + var v: (MLXArray, MLXArray, MLXArray?) + if let cacheKeys = cacheKeys, let cacheValues = cacheValues { + k = cacheKeys + v = cacheValues + } else { + let Bc = cacheOffset.dim(0) + let keyZeros = initQuant(dim: Dk, shape: [Bc, H, 0], dtype: .float32) + let valueZeros = initQuant(dim: Dv, shape: [Bc, H, 0], dtype: .float32) + k = keyZeros + v = valueZeros + } + + let leftPad = maxIdx - cacheIdx + var rightPad = maxSize - k.0.dim(-2) - leftPad + if rightPad < 0 { + k = trimmedTo(k, limit: k.0.dim(-2) + rightPad) + v = trimmedTo(v, limit: v.0.dim(-2) + rightPad) + rightPad = 0 + } + if leftPad != 0 || rightPad != 0 { + let widths: [IntOrPair] = [ + .init(0), .init(0), .init((leftPad, rightPad)), .init(0), + ] + k = treeMap({ padded($0, widths: widths) }, k) + v = treeMap({ padded($0, widths: widths) }, v) + } + return (k, v, cacheOffset, cacheLeftPadding + Int32(leftPad)) + } + + let (k1, v1, o1, lp1) = pad( + keys, values, cacheIdx: _idx, + cacheOffset: batchOffset, cacheLeftPadding: leftPadding) + let (k2, v2, o2, lp2) = pad( + other.keys, other.values, cacheIdx: other._idx, + cacheOffset: other.batchOffset, cacheLeftPadding: other.leftPadding) + + keys = ( + concatenated([k1.0, k2.0], axis: 0), + concatenated([k1.1, k2.1], axis: 0), + zipOptional(k1.2, k2.2) { concatenated([$0, $1], axis: 0) } + ) + values = ( + concatenated([v1.0, v2.0], axis: 0), + concatenated([v1.1, v2.1], axis: 0), + zipOptional(v1.2, v2.2) { concatenated([$0, $1], axis: 0) } + ) + batchOffset = concatenated([o1, o2], axis: 0) + leftPadding = concatenated([lp1, lp2], axis: 0) + _idx = maxIdx + } + + // MARK: - Trim / state / copy + + @discardableResult + public override func trim(_ n: Int) -> Int { + let trimmed = min(_idx, n) + _idx -= trimmed + batchOffset = batchOffset - Int32(trimmed) + return trimmed + } + + public override var state: [MLXArray] { + get { + guard let storedK = keys, let storedV = values else { + return [batchOffset, leftPadding] + } + let tk = trimmedTo(storedK, limit: _idx) + let tv = trimmedTo(storedV, limit: _idx) + return [ + tk.0, tk.1, tk.2, + tv.0, tv.1, tv.2, + batchOffset, leftPadding, + ].compactMap { $0 } + } + set { + switch newValue.count { + case 2: + batchOffset = newValue[0] + leftPadding = newValue[1] + keys = nil + values = nil + _idx = 0 + case 6: + keys = (newValue[0], newValue[1], nil) + values = (newValue[2], newValue[3], nil) + batchOffset = newValue[4] + leftPadding = newValue[5] + _idx = newValue[0].dim(-2) + case 8: + keys = (newValue[0], newValue[1], newValue[2]) + values = (newValue[3], newValue[4], newValue[5]) + batchOffset = newValue[6] + leftPadding = newValue[7] + _idx = newValue[0].dim(-2) + default: + fatalError( + "QuantizedBatchKVCacheBase.state setter expects 2, 6, or 8 arrays" + ) + } + } + } + + public override func innerState() -> [MLXArray] { + state + } + + public override var metaState: [String] { + get { + let modeName = mode == .affine ? "affine" : "symmetric" + return [ + String(Self.allocationStep), + String(_idx), + String(groupSize), + String(bits), + modeName, + ] + } + set { + // TODO: metaState currently restores only _idx; groupSize, + // bits, and mode are not serialized here. Acceptable for v1 because + // prefix-cache/checkpoint is disabled when quantization is on. + guard newValue.count == 5 else { + fatalError("QuantizedBatchKVCacheBase.metaState expects 5 values") + } + if let off = Int(newValue[1]) { + _idx = off + } + } + } + + public override func copy() -> any KVCache { + let new = Self( + leftPadding: Array(repeating: 0, count: leftPadding.dim(0)), + groupSize: groupSize, + bits: bits, + mode: mode + ) + let s = state + if !s.isEmpty { + new.state = s.map { $0[.ellipsis] } + } + new.metaState = metaState + return new + } + + // MARK: - Quantized tuple helpers + + private func initQuant(dim: Int, shape: [Int], dtype: DType) + -> (MLXArray, MLXArray, MLXArray?) + { + let temp = MLXArray.zeros(shape + [dim], dtype: dtype) + let q = quantized(temp, groupSize: groupSize, bits: bits) + return (q.wq, q.scales, q.biases) + } + + private func expandQuant( + _ tuple: (MLXArray, MLXArray, MLXArray?), + newShape: [Int] + ) -> (MLXArray, MLXArray, MLXArray?) { + return treeMap({ array in + let zeros = MLXArray.zeros(newShape + [array.dim(-1)], dtype: array.dtype) + return concatenated([array, zeros], axis: 2) + }, tuple) + } + + private func trimmedTo( + _ tuple: (MLXArray, MLXArray, MLXArray?), + limit: Int + ) -> (MLXArray, MLXArray, MLXArray?) { + return treeMap({ $0[.ellipsis, .. + ) { + target.0[.ellipsis, range, 0...] = source.0 + target.1[.ellipsis, range, 0...] = source.1 + switch (target.2, source.2) { + case (.some(let tb), .some(let sb)): + tb[.ellipsis, range, 0...] = sb + case (.none, .none): + break + default: + fatalError("QuantizedBatchKVCacheBase bias mismatch during assignment") + } + } + + private func treeMap( + _ transform: (MLXArray) -> T, + _ tuple: (MLXArray, MLXArray, MLXArray?) + ) -> (T, T, T?) { + if let biases = tuple.2 { + return (transform(tuple.0), transform(tuple.1), transform(biases)) + } else { + return (transform(tuple.0), transform(tuple.1), nil) + } + } + + private func zipOptional( + _ a: T?, _ b: T?, + combine: (T, T) -> T + ) -> T? { + switch (a, b) { + case (.some(let x), .some(let y)): + return combine(x, y) + case (.none, .none): + return nil + default: + fatalError("QuantizedBatchKVCacheBase optional mismatch") + } + } +} diff --git a/Tests/MLXLMTests/CBCacheFactorySelectionTests.swift b/Tests/MLXLMTests/CBCacheFactorySelectionTests.swift new file mode 100644 index 0000000000..0f221349b1 --- /dev/null +++ b/Tests/MLXLMTests/CBCacheFactorySelectionTests.swift @@ -0,0 +1,69 @@ +// Tests for Scheduler's per-layer KV-cache factory selection under +// `KVQuantizationConfig`. These exercise the pure type-selection logic via +// `Scheduler.cacheFactoryTypeName(for:quantConfig:)`, which only inspects the +// concrete cache class — so no Metal device / metallib is required. +// +// Regression intent: KV quantization must replace ONLY plain full-attention +// `KVCacheSimple` layers. `ChunkedKVCache` (a `KVCacheSimple` subclass) and +// non-`KVCacheSimple` caches must stay on their fp16 batched paths so models +// that downcast their per-layer cache back to a concrete type are not broken. + +import Foundation +import XCTest + +@testable import MLXLMCommon + +final class CBCacheFactorySelectionTests: XCTestCase { + + private let kernel = KVQuantizationConfig( + groupSize: 128, bits: 8, mode: .affine, cacheKind: .kernel) + private let dequant = KVQuantizationConfig( + groupSize: 64, bits: 8, mode: .affine, cacheKind: .dequant) + + func testQuantOffKeepsFp16BatchedCaches() { + XCTAssertEqual( + Scheduler.cacheFactoryTypeName(for: KVCacheSimple(), quantConfig: nil), + "BatchKVCache") + XCTAssertEqual( + Scheduler.cacheFactoryTypeName( + for: RotatingKVCache(maxSize: 1024, keep: 0, step: 1024), + quantConfig: nil), + "BatchRotatingKVCache") + } + + func testKVCacheSimpleIsQuantizedByKind() { + XCTAssertEqual( + Scheduler.cacheFactoryTypeName(for: KVCacheSimple(), quantConfig: kernel), + "QuantizedBatchKVCache") + XCTAssertEqual( + Scheduler.cacheFactoryTypeName(for: KVCacheSimple(), quantConfig: dequant), + "DequantBatchKVCache") + } + + func testSlidingLayersStayFp16WhenQuantOn() { + XCTAssertEqual( + Scheduler.cacheFactoryTypeName( + for: RotatingKVCache(maxSize: 1024, keep: 0, step: 1024), + quantConfig: kernel), + "BatchRotatingKVCache") + } + + func testChunkedKVCacheIsNotQuantized() { + // ChunkedKVCache subclasses KVCacheSimple but has bespoke chunked + // semantics; quantizing it would drop that behavior. It must stay fp16. + XCTAssertEqual( + Scheduler.cacheFactoryTypeName( + for: ChunkedKVCache(chunkSize: 256), quantConfig: kernel), + "BatchKVCache") + } + + func testRecurrentAndArrayCachesAreNotQuantized() { + XCTAssertEqual( + Scheduler.cacheFactoryTypeName(for: ArraysCache(size: 4), quantConfig: kernel), + "ArraysCache") + XCTAssertEqual( + Scheduler.cacheFactoryTypeName( + for: MambaCache(), quantConfig: kernel), + "MambaCache") + } +} diff --git a/Tests/MLXLMTests/CBCheckpointRestoreTests.swift b/Tests/MLXLMTests/CBCheckpointRestoreTests.swift index f9f3a4b01c..78683d89b3 100644 --- a/Tests/MLXLMTests/CBCheckpointRestoreTests.swift +++ b/Tests/MLXLMTests/CBCheckpointRestoreTests.swift @@ -75,6 +75,61 @@ private func makeRestoreScheduler(window: Int) -> Scheduler { eosTokenIds: []) } +// head_dim = 64 variant so the full-attention layer (layer 0) is KV-quant- +// eligible (groupSize must divide head_dim). Same position-sensitive logit +// rule as RestoreHybridModel; the model ignores K/V VALUES, so quantization +// noise cannot change outputs — these tests gate the restore PATH (quantized +// cache assembly + positional correctness + extendBatched type-compat), not +// quant value fidelity (covered by QuantizedSDPATests). Layer 1 stays sliding +// (fp16 RotatingKVCache), mirroring GPT-OSS's hybrid full+sliding layout. +private final class RestoreQuantHybridModel: Module, LanguageModel, KVCacheDimensionProvider { + let vocabularySize = 16 + let window: Int + var kvHeads: [Int] { [1, 1] } + init(window: Int) { self.window = window } + func prepare(_ input: LMInput, cache: [any KVCache], windowSize: Int?) throws -> PrepareResult { + .tokens(input.text) + } + func newCache(parameters: GenerateParameters?) -> [any KVCache] { + [KVCacheSimple(), RotatingKVCache(maxSize: window, keep: 0)] + } + func callAsFunction(_ inputs: MLXArray, cache: [any KVCache]?) -> MLXArray { + let B = inputs.dim(0), S = inputs.dim(1) + // PER-ROW absolute position (unlike the B==1 RestoreHybridModel which + // reads row 0) so a multi-row batch — cold + restored together — is + // positionally correct, which the concurrent test requires. + var basePos = [Int](repeating: 0, count: B) + if let cache, cache.count > 1, let pos = cache[1] as? BatchPositionedKVCache { + let off = pos.batchOffset.asArray(Int32.self) + for b in 0 ..< B { basePos[b] = b < off.count ? Int(off[b]) : 0 } + } + if let cache { + let keys = MLXArray.ones([B, 1, S, 64], dtype: .float32) + for c in cache { _ = c.update(keys: keys, values: keys * 2) } + } + let tok = inputs.asArray(UInt32.self).map { Int($0) } + var logits = Array(repeating: Float(-1_000), count: B * S * vocabularySize) + for b in 0 ..< B { + for t in 0 ..< S { + let next = (tok[b * S + t] + 1 + basePos[b] + t) % vocabularySize + logits[(b * S + t) * vocabularySize + next] = 0 + } + } + return MLXArray(logits).reshaped([B, S, vocabularySize]) + } +} + +private func makeRestoreQuantScheduler(window: Int) -> Scheduler { + Scheduler( + model: RestoreQuantHybridModel(window: window), + tokenizer: IdentityTokenizer(), + config: SchedulerConfig( + maxNumSeqs: 4, maxNumBatchedTokens: 128, prefillStepSize: 16, streamInterval: 1, + kvQuantization: KVQuantizationConfig( + groupSize: 64, bits: 8, mode: .affine, cacheKind: .dequant)), + eosTokenIds: []) +} + /// Run one request to completion, returning its output token ids. private func runOutputs(_ sched: Scheduler, _ req: Request, maxSteps: Int = 400) -> [Int] { sched.addRequest(req) @@ -188,4 +243,80 @@ final class CBCheckpointRestoreTests: XCTestCase { tokenCount: 4) XCTAssertEqual(runOutputs(s3, r3), coldOut, "wrong per-position type order must fall back to cold") } + + // DAR-319 v2: restore must match cold output even when KV-quant is ON (the + // full-attention layer is a QuantizedBatchKVCache). The restore path + // re-quantizes the captured fp16 prefix into a quantized batched cache via + // the cold cache factory; this gates that it runs, preserves positions, and + // matches a cold full-prompt run under the same quantization. + func testRestoreMatchesColdOutputUnderKVQuant() { + let window = 8 + let prompt = Array(0..<12).map { $0 % 16 } + let maxTokens = 6 + + let coldSched = makeRestoreQuantScheduler(window: window) + coldSched.checkpointBoundaries = [4, 8] + final class Cap: @unchecked Sendable { var atL: [Int: [any KVCache]] = [:] } + let cap = Cap() + coldSched.onCheckpointCapture = { _, length, caches in cap.atL[length] = caches } + let coldOut = runOutputs(coldSched, makeIntRequest(tokens: prompt, maxTokens: maxTokens)) + + guard let restoredAt8 = cap.atL[8] else { + return XCTFail("expected a checkpoint capture at L=8 under KV-quant") + } + XCTAssertEqual(coldOut.count, maxTokens) + + let warmSched = makeRestoreQuantScheduler(window: window) + let req = makeIntRequest(tokens: prompt, maxTokens: maxTokens) + req.restoredCheckpoint = (caches: restoredAt8.map { $0.copy() }, tokenCount: 8) + let warmOut = runOutputs(warmSched, req) + + XCTAssertEqual(warmOut, coldOut, + "restored-checkpoint output must match cold output under KV-quant") + XCTAssertEqual(req.cachedTokens, 8, "restore should report 8 cached prompt tokens") + } + + // The real DAR-319 v1 crash this fix removes: a restored row rebuilt as + // fp16 (old behavior) trips `extendBatched`'s concrete-class precondition + // when merged into a genBatch holding a QUANTIZED cold row. With the + // re-quantizing restore both rows are QuantizedBatchKVCache, so a concurrent + // cold + restored batch coexists and BOTH outputs stay correct. + func testConcurrentRestoreAndColdUnderKVQuant() { + let window = 8 + let promptB = Array(0..<12).map { $0 % 16 } + let promptA = Array(2..<13).map { $0 % 16 } + let maxTokens = 6 + + // Capture a checkpoint for promptB and a cold reference for it. + let capSched = makeRestoreQuantScheduler(window: window) + capSched.checkpointBoundaries = [4, 8] + final class Cap: @unchecked Sendable { var atL: [Int: [any KVCache]] = [:] } + let cap = Cap() + capSched.onCheckpointCapture = { _, length, caches in cap.atL[length] = caches } + let coldB = runOutputs(capSched, makeIntRequest(tokens: promptB, maxTokens: maxTokens)) + guard let restoredAt8 = cap.atL[8] else { + return XCTFail("expected a checkpoint capture at L=8") + } + let coldA = runOutputs(makeRestoreQuantScheduler(window: window), + makeIntRequest(tokens: promptA, maxTokens: maxTokens)) + + // Concurrent: cold A + restored B share one scheduler → one genBatch. + // The restored B merges first, then A's cold prefill completes and + // extendBatched-es into B's quantized genBatch. Pre-fix this crashed. + let sched = makeRestoreQuantScheduler(window: window) + let reqA = makeIntRequest(tokens: promptA, maxTokens: maxTokens) + let reqB = makeIntRequest(tokens: promptB, maxTokens: maxTokens) + reqB.restoredCheckpoint = (caches: restoredAt8.map { $0.copy() }, tokenCount: 8) + sched.addRequest(reqA) + sched.addRequest(reqB) + var steps = 0 + while !(sched.finishedReqIds.contains(reqA.requestId) + && sched.finishedReqIds.contains(reqB.requestId)), steps < 800 { + _ = sched.step(); steps += 1 + } + XCTAssertEqual(reqB.outputTokenIds, coldB, + "restored B must match its cold output when batched with a quantized cold row") + XCTAssertEqual(reqA.outputTokenIds, coldA, + "cold A must match its cold output when batched with a restored quantized row") + } } diff --git a/Tests/MLXLMTests/CBSamplingTests.swift b/Tests/MLXLMTests/CBSamplingTests.swift index 8c16a92a8c..e647b3586f 100644 --- a/Tests/MLXLMTests/CBSamplingTests.swift +++ b/Tests/MLXLMTests/CBSamplingTests.swift @@ -125,3 +125,163 @@ final class CBRepetitionPenaltyTests: XCTestCase { XCTAssertEqual(sample(sampler, [3.0, 1.6, 0.0, 0.0]), 1) } } + +// MARK: - §4b On-device penalty sampler (gather/scatter) numerics + +/// Box used to capture the penalized logits the repetition sampler hands to its +/// base sampler, so the test can compare them against the reference CPU formula. +private final class CapturedLogitsBox: @unchecked Sendable { + private let lock = NSLock() + private var value: MLXArray? + func set(_ v: MLXArray) { + lock.lock(); value = v; lock.unlock() + } + func get() -> MLXArray? { + lock.lock(); defer { lock.unlock() }; return value + } +} + +/// Verifies the on-device gather/scatter repetition sampler is numerically +/// equivalent to the original CPU formula it replaced, and that the incremental +/// counts maintained on `TokenHistoryHolder.append` match a full rescan. +final class CBRepetitionPenaltyDeviceTests: XCTestCase { + + /// The exact original CPU formula, computed host-side for reference. + private func cpuReference( + logits: MLXArray, history: [Int], + repetitionPenalty rp: Float, presencePenalty pp: Float, frequencyPenalty fp: Float + ) -> [Float] { + let vocab = logits.dim(-1) + var flat = logits.reshaped(-1).asArray(Float.self) + var counts: [Int: Int] = [:] + for t in history where t >= 0 && t < vocab { counts[t, default: 0] += 1 } + for (tokenId, count) in counts { + var v = flat[tokenId] + if rp != 1.0 { v = v > 0 ? v / rp : v * rp } + v -= pp + v -= fp * Float(count) + flat[tokenId] = v + } + return flat + } + + /// Capture the logits passed to `base` after on-device penalization. + private func devicePenalized( + logits: MLXArray, history: TokenHistoryHolder, + repetitionPenalty rp: Float, presencePenalty pp: Float, frequencyPenalty fp: Float + ) -> [Float] { + let captured = CapturedLogitsBox() + let sampler = makeRepetitionSampler( + base: { @Sendable l in captured.set(l); return argMax(l, axis: -1) }, + history: history, + repetitionPenalty: rp, presencePenalty: pp, frequencyPenalty: fp + ) + _ = sampler(logits) + return captured.get()!.reshaped(-1).asArray(Float.self) + } + + func testOnDevicePenaltyMatchesCPUFormula() { + let vocab = 16 + // Repeats across positive and negative logits exercise both the + // repetition-scaling branches and the per-count frequency penalty. + let history = [1, 1, 2, 5, 5, 5, 7, 0, 3, 3, 9, 9, 2] + let rp: Float = 1.3 + let pp: Float = 0.4 + let fp: Float = 0.25 + + // Mixed-sign deterministic row [1, vocab]: -7.5 ... +7.5 (no exact zeros). + let raw: [Float] = (0 ..< vocab).map { Float($0) - 7.5 } + let logits = MLXArray(raw)[.newAxis, .ellipsis] + + let expected = cpuReference( + logits: logits, history: history, + repetitionPenalty: rp, presencePenalty: pp, frequencyPenalty: fp) + let got = devicePenalized( + logits: logits, history: TokenHistoryHolder(tokens: history), + repetitionPenalty: rp, presencePenalty: pp, frequencyPenalty: fp) + + XCTAssertEqual(got.count, vocab) + for i in 0 ..< vocab { + XCTAssertEqual(got[i], expected[i], accuracy: 1e-4, "mismatch at token \(i)") + } + } + + /// presence/frequency-only (repetitionPenalty == 1) must also match — the + /// repetition-scaling branch is skipped in that case. + func testOnDevicePresenceFrequencyOnlyMatchesCPUFormula() { + let vocab = 16 + let history = [2, 2, 2, 8, 0, 0, 14] + let rp: Float = 1.0 + let pp: Float = 0.6 + let fp: Float = 0.5 + + let raw: [Float] = (0 ..< vocab).map { Float($0) * 0.5 - 4.0 } + let logits = MLXArray(raw)[.newAxis, .ellipsis] + + let expected = cpuReference( + logits: logits, history: history, + repetitionPenalty: rp, presencePenalty: pp, frequencyPenalty: fp) + let got = devicePenalized( + logits: logits, history: TokenHistoryHolder(tokens: history), + repetitionPenalty: rp, presencePenalty: pp, frequencyPenalty: fp) + + for i in 0 ..< vocab { + XCTAssertEqual(got[i], expected[i], accuracy: 1e-4, "mismatch at token \(i)") + } + } + + /// The incremental counts maintained on `append` must produce identical + /// penalized logits to a holder constructed from the full token list. + func testIncrementalCountsMatchFullRescan() { + let vocab = 16 + let prompt = [3, 3, 1, 0] + let appended = [5, 5, 3, 9, 5, 1] + let rp: Float = 1.5 + let pp: Float = 0.3 + let fp: Float = 0.5 + + let raw: [Float] = (0 ..< vocab).map { Float($0) - 8.0 } + let logits = MLXArray(raw)[.newAxis, .ellipsis] + + let full = TokenHistoryHolder(tokens: prompt + appended) + let incremental = TokenHistoryHolder(tokens: prompt) + for t in appended { incremental.append(t) } + + XCTAssertEqual(full.counts, incremental.counts, "incremental counts diverged from rescan") + + let a = devicePenalized( + logits: logits, history: full, + repetitionPenalty: rp, presencePenalty: pp, frequencyPenalty: fp) + let b = devicePenalized( + logits: logits, history: incremental, + repetitionPenalty: rp, presencePenalty: pp, frequencyPenalty: fp) + + for i in 0 ..< vocab { + XCTAssertEqual(a[i], b[i], accuracy: 1e-6, "incremental vs rescan mismatch at token \(i)") + } + } + + /// Empty history and out-of-range-only history must pass through to base + /// untouched (the two original guards). + func testGuardsPassThroughUnchanged() { + let vocab = 8 + let raw: [Float] = (0 ..< vocab).map { Float($0) - 3.0 } + let logits = MLXArray(raw)[.newAxis, .ellipsis] + + // Empty history → identical to input. + let empty = devicePenalized( + logits: logits, history: TokenHistoryHolder(tokens: []), + repetitionPenalty: 2.0, presencePenalty: 1.0, frequencyPenalty: 1.0) + for i in 0 ..< vocab { + XCTAssertEqual(empty[i], raw[i], accuracy: 1e-6) + } + + // Only out-of-range ids (>= vocab) → no in-range counts → unchanged. + let oob = devicePenalized( + logits: logits, history: TokenHistoryHolder(tokens: [99, 100, 100]), + repetitionPenalty: 2.0, presencePenalty: 1.0, frequencyPenalty: 1.0) + for i in 0 ..< vocab { + XCTAssertEqual(oob[i], raw[i], accuracy: 1e-6) + } + } +} diff --git a/Tests/MLXLMTests/QuantizedSDPATests.swift b/Tests/MLXLMTests/QuantizedSDPATests.swift new file mode 100644 index 0000000000..fe43746d02 --- /dev/null +++ b/Tests/MLXLMTests/QuantizedSDPATests.swift @@ -0,0 +1,262 @@ +import Foundation +import MLX +import Testing + +@testable import MLXLMCommon + +/// Focused numerical-parity tests for the quantized scaled-dot-product attention +/// kernel path after the decode performance changes: +/// +/// * Lever A — the softmax is fused via `compile(shapeless:)`. These tests pin +/// that the fused result still matches an independent (plain-softmax, +/// dequantized-matmul) reference within fp tolerance, for both single-query +/// decode (`n == 1`) and multi-query prefill (`n > 1`), with grouped-query +/// attention (GQA). +/// * Lever B — `QuantizedBatchKVCacheBase.makeMask` returns `.none` for the +/// single-query decode no-op-mask case. These tests pin that skipping the +/// mask is bit-identical to applying the materialized all-`true` mask, and +/// that the fast path is taken only under the safe conditions. +@Suite("QuantizedSDPATests") +struct QuantizedSDPATests { + + // MARK: - Config / helpers + + /// `groupSize` must divide the head dim for the quantized cache. + static let groupSize = 64 + static let bits = 8 + static let headDim = 64 + + /// Deterministic, varied, non-degenerate data in roughly `[-1, 1]` so the + /// test does not depend on `MLXRandom` (which the test target does not link). + private func varied(_ shape: [Int], phase: Float) -> MLXArray { + let total = shape.reduce(1, *) + let idx = MLXArray(Int32(0) ..< Int32(total)).asType(.float32) + return sin(idx * 0.13 + phase).reshaped(shape) + } + + private func quantize(_ x: MLXArray) -> (MLXArray, MLXArray, MLXArray?) { + let q = quantized(x, groupSize: Self.groupSize, bits: Self.bits) + return (q.wq, q.scales, q.biases) + } + + private func dequantize(_ t: (MLXArray, MLXArray, MLXArray?)) -> MLXArray { + dequantized( + t.0, scales: t.1, biases: t.2, + groupSize: Self.groupSize, bits: Self.bits, mode: .affine) + } + + /// Repeat KV heads to match query heads, mirroring the GQA layout used by the + /// kernel: `[B, nKVHeads, T, D] -> [B, nQHeads, T, D]`. + private func repeatKVHeads(_ x: MLXArray, repeats: Int) -> MLXArray { + if repeats == 1 { return x } + let (b, h, t, d) = (x.dim(0), x.dim(1), x.dim(2), x.dim(3)) + let expanded = expandedDimensions(x, axis: 2) // [B, H, 1, T, D] + let tiled = broadcast(expanded, to: [b, h, repeats, t, d]) + return tiled.reshaped([b, h * repeats, t, d]) + } + + /// Independent reference attention computed from the **dequantized** K/V with + /// a plain `softmax`. `maskBool` is an optional `[n, T]` (or broadcastable) + /// boolean mask: `true` = attend, `false` = masked out. + private func referenceAttention( + queries: MLXArray, + keysDeq: MLXArray, + valuesDeq: MLXArray, + scale: Float, + maskBool: MLXArray? + ) -> MLXArray { + let nQHeads = queries.dim(1) + let nKVHeads = keysDeq.dim(1) + let repeats = nQHeads / nKVHeads + + let k = repeatKVHeads(keysDeq, repeats: repeats) + let v = repeatKVHeads(valuesDeq, repeats: repeats) + + var scores = matmul(queries * scale, k.swappedAxes(-1, -2)) // [B, nQHeads, n, T] + if let maskBool { + scores = MLX.where(maskBool, scores, MLXArray(-Float.greatestFiniteMagnitude)) + } + let weights = softmax(scores, axis: -1) + return matmul(weights, v) // [B, nQHeads, n, D] + } + + private func maxAbsDiff(_ a: MLXArray, _ b: MLXArray) -> Float { + abs(a - b).max().item(Float.self) + } + + private static func isNone(_ m: MLXFast.ScaledDotProductAttentionMaskMode) -> Bool { + if case .none = m { return true } + return false + } + + private static func isArray(_ m: MLXFast.ScaledDotProductAttentionMaskMode) -> Bool { + if case .array = m { return true } + return false + } + + // MARK: - Lever A: fused softmax matches reference (no sinks) + + /// Single-query decode (`n == 1`), GQA, a few cached tokens, no mask. + @Test func decodeMatchesReference() { + let (b, nKVHeads, nQHeads, d) = (1, 2, 4, Self.headDim) + let t = 6 // a few cached tokens + let scale = 1.0 / Float(d).squareRoot() + + let q = varied([b, nQHeads, 1, d], phase: 0.0) + let k = varied([b, nKVHeads, t, d], phase: 1.0) + let v = varied([b, nKVHeads, t, d], phase: 2.0) + + let qK = quantize(k) + let qV = quantize(v) + + let out = quantizedScaledDotProductAttention( + queries: q, quantizedKeys: qK, quantizedValues: qV, + scale: scale, mask: .none, + groupSize: Self.groupSize, bits: Self.bits, mode: .affine) + + let ref = referenceAttention( + queries: q, keysDeq: dequantize(qK), valuesDeq: dequantize(qV), + scale: scale, maskBool: nil) + + #expect(out.shape == [b, nQHeads, 1, d]) + let diff = maxAbsDiff(out, ref) + #expect(diff < 1e-3, "decode max|Δ| = \(diff)") + } + + /// Multi-query prefill (`n > 1`), GQA, causal mask, batch > 1 (exercises the + /// `[n, T]` mask broadcasting against `[B, nQHeads, n, T]` scores). + @Test func prefillMatchesReference() { + let (b, nKVHeads, nQHeads, d) = (2, 2, 4, Self.headDim) + let n = 4 // a few cached tokens, all attended causally + let scale = 1.0 / Float(d).squareRoot() + + let q = varied([b, nQHeads, n, d], phase: 0.5) + let k = varied([b, nKVHeads, n, d], phase: 1.5) + let v = varied([b, nKVHeads, n, d], phase: 2.5) + + let qK = quantize(k) + let qV = quantize(v) + + // Production n>1 path uses an explicit causal array mask. + let maskArray = createCausalMask(n: n, offset: 0) // [n, n] lower-triangular + + let out = quantizedScaledDotProductAttention( + queries: q, quantizedKeys: qK, quantizedValues: qV, + scale: scale, mask: .array(maskArray), + groupSize: Self.groupSize, bits: Self.bits, mode: .affine) + + let ref = referenceAttention( + queries: q, keysDeq: dequantize(qK), valuesDeq: dequantize(qV), + scale: scale, maskBool: maskArray) + + #expect(out.shape == [b, nQHeads, n, d]) + let diff = maxAbsDiff(out, ref) + #expect(diff < 1e-3, "prefill max|Δ| = \(diff)") + } + + // MARK: - Lever A: fused sink softmax matches reference + + /// Single-query decode with attention sinks (the compiled sink core). + @Test func decodeWithSinksMatchesReference() { + let (b, nKVHeads, nQHeads, d) = (1, 2, 4, Self.headDim) + let t = 5 + let scale = 1.0 / Float(d).squareRoot() + + let q = varied([b, nQHeads, 1, d], phase: 0.2) + let k = varied([b, nKVHeads, t, d], phase: 1.2) + let v = varied([b, nKVHeads, t, d], phase: 2.2) + let sinks = varied([nQHeads], phase: 3.0) // per-query-head sink logits + + let qK = quantize(k) + let qV = quantize(v) + + let out = quantizedScaledDotProductAttention( + queries: q, quantizedKeys: qK, quantizedValues: qV, + scale: scale, mask: .none, + groupSize: Self.groupSize, bits: Self.bits, mode: .affine, + sinks: sinks) + + // Reference: same scores, but softmax denominator includes the sink's + // exp() term (the sink has no value vector, so it only removes mass). + let kDeq = repeatKVHeads(dequantize(qK), repeats: nQHeads / nKVHeads) + let vDeq = repeatKVHeads(dequantize(qV), repeats: nQHeads / nKVHeads) + let scores = matmul(q * scale, kDeq.swappedAxes(-1, -2)) // [b, nQHeads, 1, t] + let sinkLogits = sinks.reshaped([1, nQHeads, 1, 1]) + let m = maximum(scores.max(axis: -1, keepDims: true), sinkLogits) + let expScores = exp(scores - m) + let denom = expScores.sum(axis: -1, keepDims: true) + exp(sinkLogits - m) + let ref = matmul(expScores / denom, vDeq) + + #expect(out.shape == [b, nQHeads, 1, d]) + let diff = maxAbsDiff(out, ref) + #expect(diff < 1e-3, "decode+sinks max|Δ| = \(diff)") + } + + // MARK: - Lever B: skipping the n==1 mask is numerically identical + + /// For `n == 1` with no left padding / no window, the causal mask is all + /// `true`, so attending with `.none` must equal attending with the explicit + /// all-`true` array mask (bit-identical: same scores feed the same softmax). + @Test func maskSkipParityDecode() { + let (b, nKVHeads, nQHeads, d) = (1, 2, 4, Self.headDim) + let t = 7 + let scale = 1.0 / Float(d).squareRoot() + + let q = varied([b, nQHeads, 1, d], phase: 0.7) + let k = varied([b, nKVHeads, t, d], phase: 1.7) + let v = varied([b, nKVHeads, t, d], phase: 2.7) + + let qK = quantize(k) + let qV = quantize(v) + + // The all-`true` mask the old always-masked path would have built for a + // single decode query over `t` cached keys. + let allTrueMask = createCausalMask(n: 1, offset: t - 1) // [1, t], all true + + let outSkipped = quantizedScaledDotProductAttention( + queries: q, quantizedKeys: qK, quantizedValues: qV, + scale: scale, mask: .none, + groupSize: Self.groupSize, bits: Self.bits, mode: .affine) + + let outMasked = quantizedScaledDotProductAttention( + queries: q, quantizedKeys: qK, quantizedValues: qV, + scale: scale, mask: .array(allTrueMask), + groupSize: Self.groupSize, bits: Self.bits, mode: .affine) + + let diff = maxAbsDiff(outSkipped, outMasked) + #expect(diff < 1e-5, ".none vs all-true mask max|Δ| = \(diff)") + } + + // MARK: - Lever B: makeMask fast-path conditions + + /// `makeMask` returns `.none` only for the safe single-query decode case and + /// otherwise materializes the array mask. + @Test func makeMaskFastPathConditions() { + let (nKVHeads, d) = (2, Self.headDim) + let t = 5 + + func freshCache(leftPadding: [Int]) -> QuantizedBatchKVCache { + let cache = QuantizedBatchKVCache( + leftPadding: leftPadding, groupSize: Self.groupSize, bits: Self.bits) + let bSize = leftPadding.count + let k = varied([bSize, nKVHeads, t, d], phase: 1.1) + let v = varied([bSize, nKVHeads, t, d], phase: 2.1) + _ = cache.updateQuantized(keys: k, values: v) + return cache + } + + // n == 1, no left padding, no window -> fast path (.none). + let c1 = freshCache(leftPadding: [0]) + #expect(Self.isNone(c1.makeMask(n: 1, windowSize: nil, returnArray: false))) + + // n > 1 -> materialized mask (prefill/chunked). + #expect(Self.isArray(c1.makeMask(n: 2, windowSize: nil, returnArray: false))) + + // n == 1 but a sliding window is set -> conservative materialized mask. + #expect(Self.isArray(c1.makeMask(n: 1, windowSize: 4, returnArray: false))) + + // n == 1 but left padding present -> materialized mask. + let c2 = freshCache(leftPadding: [3]) + #expect(Self.isArray(c2.makeMask(n: 1, windowSize: nil, returnArray: false))) + } +}