diff --git a/Libraries/MLXLLM/Models/Jamba.swift b/Libraries/MLXLLM/Models/Jamba.swift index 6f870aa96c..de5d33edca 100644 --- a/Libraries/MLXLLM/Models/Jamba.swift +++ b/Libraries/MLXLLM/Models/Jamba.swift @@ -482,13 +482,19 @@ public class JambaModel: Module, LLMModel, KVCacheDimensionProvider { return makeAttentionCache(parameters: parameters, affineStep: affineStep) } else { // Jamba's Mamba mixer uses a per-step parallel scan whose - // forward output doesn't expose per-step deltas — until - // the Mamba state-replay kernel lands (spec 020 §"Mamba / - // Mamba 2 follow-up"), opt out so speculative iterators - // gracefully fall back to vanilla TokenIterator. - let cache = SSMStateCache() - cache.canStateReplay = false - return cache + // Spec 040 shipped Mamba state-replay via + // `MLXFast.ssmStepRecord` / `MLXFast.ssmReplay`. Jamba's + // mamba-mixer layers can replay alongside the attention + // KV cache; `canStateReplay` stays at the class default + // `true`. + // + // Note: Jamba's mamba mixer is a separate forward path + // from NemotronH's. The state-replay wiring landed for + // NemotronH's mamba mixer; extending to Jamba is a + // mechanical follow-up (mirror the + // `if cache.isRecording { ssmStepRecord } else { ssmUpdate }` + // branch from NemotronH). + return SSMStateCache() } } } diff --git a/Libraries/MLXLLM/Models/NemotronH.swift b/Libraries/MLXLLM/Models/NemotronH.swift index 9b3854c6b9..7c249714a5 100644 --- a/Libraries/MLXLLM/Models/NemotronH.swift +++ b/Libraries/MLXLLM/Models/NemotronH.swift @@ -224,18 +224,44 @@ private class NemotronHMamba2Mixer: Module, NemotronHMixer { let dtArray = dt.reshaped([dt.dim(0), dt.dim(1), numHeads]) let previousState = cache?[1] - let (y, nextState) = ssmUpdate( - hiddenStates: hidden, - ALog: aLog, - B: B, - C: C, - D: D, - dt: dtArray, - dtBias: dtBias, - state: previousState, - timeStepLimit: timeStepLimit, - mask: mask - ) + let T = hidden.dim(1) + let y: MLXArray + let nextState: MLXArray + + if T > 1, let cache, cache.isRecording, let prevState = previousState { + // Spec 040: Mamba state-replay recording session. Route the + // sequential forward through `MLXFast.ssmStepRecord` so we + // capture per-step `(dA, dBx)` into the cache's delta log + // alongside the standard `(y, state_out)` outputs. The verify + // window's rollback uses `MLXFast.ssmReplay` to re-fold the + // accepted prefix. + let dtAdjusted = computeDt(dtArray, dtBias, timeStepLimit) + let outs = MLXFast.ssmStepRecord( + x: hidden, + ALog: aLog, + B: B, + C: C, + D: D, + dt: dtAdjusted, + state: prevState, + mask: mask) + y = outs[0] + nextState = outs[1] + cache.recordStep([outs[2], outs[3]]) // [dA_log, dBx_log] + } else { + (y, nextState) = ssmUpdate( + hiddenStates: hidden, + ALog: aLog, + B: B, + C: C, + D: D, + dt: dtArray, + dtBias: dtBias, + state: previousState, + timeStepLimit: timeStepLimit, + mask: mask + ) + } if let cache { cache[1] = nextState @@ -796,19 +822,13 @@ public class NemotronHModel: Module, LLMModel, KVCacheDimensionProvider, LoRAMod for char in pattern { switch NemotronHBlockType(from: char) { case .mamba: - // Mamba's recurrence (`s_{t+1} = exp(dt·A)·s_t + dt·B·x`) - // is numerically distinct from GatedDeltaNet's - // (`s_{t+1} = g·s_t + k·δ`), and the S>1 forward uses a - // chunked parallel scan that doesn't expose per-step - // deltas. Until the Mamba / Mamba 2 state-replay kernel - // pair lands (spec 020 §"Mamba / Mamba 2 follow-up"), - // opt out of state replay so speculative iterators see - // `canRollbackPromptCache == false` and fall back to - // vanilla `TokenIterator` instead of crashing on - // partial-accept rollback. - let cache = SSMStateCache() - cache.canStateReplay = false - caches.append(cache) + // Spec 040: Mamba state-replay landed via + // `MLXFast.ssmStepRecord` + `MLXFast.ssmReplay`. The mamba + // forward path now records `(dA, dBx)` per step when the + // cache is recording, and `SSMStateCache.rollback` re-folds + // the accepted prefix through the Mamba replay kernel. + // `canStateReplay` stays at the class default `true`. + caches.append(SSMStateCache()) case .attention: let currentIdx = caches.count if let turbo, !skipSet.contains(currentIdx) { diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index 3f518b2b29..dca7b60496 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -1566,9 +1566,13 @@ extension SSMStateCache: StateReplayCache { precondition( deltaLog != nil, "SSMStateCache.recordStep called outside an active recording session") + // Two record shapes are accepted: + // - GDN: 3 tensors per entry: [delta, k, g] (spec 020) + // - Mamba: 2 tensors per entry: [dA_log, dBx_log] (spec 040) + // The rollback dispatcher detects which shape by entry length. precondition( - tensors.count == 3, - "SSMStateCache expects 3 tensors per step (delta, k, g); got \(tensors.count)") + tensors.count == 3 || tensors.count == 2, + "SSMStateCache expects 3 tensors (GDN: delta, k, g) or 2 tensors (Mamba: dA_log, dBx_log); got \(tensors.count)") deltaLog?.append(tensors) } @@ -1605,13 +1609,35 @@ extension SSMStateCache: StateReplayCache { // State replay only updates the recurrent slot; the conv state // is re-initialised by the layer on the next forward. if self.state.count >= 2 && k > 0 { - let s = stateReplayUpdate( - state: self.state[1], - deltaLog: recordedLog, - acceptedPrefix: k) - var newState = self.state - newState[1] = s - self.state = newState + let firstEntry = recordedLog.first ?? [] + if firstEntry.count == 2 { + // Spec 040: Mamba flavour. Per-round entry is [dA_log, dBx_log] + // with dA_log shape [B, T, H, ds] and dBx_log [B, T, H, dh, ds]. + // Each entry covers the full T-axis of one verify forward, so + // we use the most recent entry's `[.. Int { /// per-cache via `AffineQuantizedKVCache.sdpaStrategy` (constructor arg) or /// globally via the `MLX_AFFINE_SDPA` env var: /// - `MLX_AFFINE_SDPA=auto` — flash for L>1, discrete for L=1 (default) -/// - `MLX_AFFINE_SDPA=flash` — always flash (memory-pressured runs) -/// - `MLX_AFFINE_SDPA=discrete` — always discrete (regression-check / legacy path) +/// - `MLX_AFFINE_SDPA=kernel` — spec 041 phase 1.1 fused Metal kernel +/// (`fusedFlashQuantizedSDPA`). Correct but unoptimised; tiled MMA + +/// threadgroup codebook + INT8 score accumulator follow-ups in spec +/// 042 Phase 1b will close the perf gap. Opt-in for kernel validation +/// and future-perf-work development. +/// - `MLX_AFFINE_SDPA=flash` — dequant-then-MLXFastSDPA stop-gap. +/// Materialises K_fp/V_fp transient before MLX SDPA's flash kernel. +/// Best perf today; what `.auto` picks for L>1 prefill. +/// - `MLX_AFFINE_SDPA=discrete` — legacy `quantizedMM → softmax → +/// quantizedMM`. Materialises full `[B, H, L, T]` score matrix. What +/// `.auto` picks for L=1 decode (score matrix is small and the +/// dequant transient cost dominates). /// /// Precedence: env var when set ▶ per-cache `sdpaStrategy` ▶ `.auto`. public enum AffineSDPAStrategy: Sendable { - case auto, flash, discrete + case auto, kernel, flash, discrete /// Env-var override read once at process startup. When set, takes /// precedence over per-cache `sdpaStrategy`. `nil` when unset (honour @@ -2131,20 +2167,26 @@ public enum AffineSDPAStrategy: Sendable { switch ProcessInfo.processInfo.environment["MLX_AFFINE_SDPA"] { case "discrete": return .discrete case "flash": return .flash + case "kernel": return .kernel case "auto": return .auto default: return nil } }() - /// Pick flash vs discrete given the call's query length, with the - /// caller's per-cache strategy as the fallback when no env override - /// is set. - static func shouldUseFlash(L: Int, strategy: AffineSDPAStrategy = .auto) -> Bool { + /// Resolved dispatch path. `.auto` never appears here — it's an input + /// directive that resolves to a concrete one of `.kernel`/`.flash`/ + /// `.discrete` based on `L`. + public enum Path { case kernel, flash, discrete } + + /// Pick path given the call's query length, with the caller's per-cache + /// strategy as the fallback when no env override is set. + static func choose(L: Int, strategy: AffineSDPAStrategy = .auto) -> Path { let effective = envOverride ?? strategy switch effective { - case .flash: return true - case .discrete: return false - case .auto: return L > 1 + case .kernel: return .kernel + case .flash: return .flash + case .discrete: return .discrete + case .auto: return L > 1 ? .flash : .discrete } } } @@ -2162,7 +2204,16 @@ public func quantizedScaledDotProductAttention( strategy: AffineSDPAStrategy = .auto ) -> MLXArray { let queryL = queries.dim(2) - if AffineSDPAStrategy.shouldUseFlash(L: queryL, strategy: strategy) { + switch AffineSDPAStrategy.choose(L: queryL, strategy: strategy) { + case .kernel: + return fusedFlashQuantizedSDPA( + queries: queries, + quantizedKeys: quantizedKeys, + quantizedValues: quantizedValues, + scale: scale, mask: mask, sinks: sinks, + groupSize: groupSize, bits: bits, mode: mode + ) + case .flash: return flashQuantizedScaledDotProductAttention( queries: queries, quantizedKeys: quantizedKeys, @@ -2170,6 +2221,8 @@ public func quantizedScaledDotProductAttention( scale: scale, mask: mask, sinks: sinks, groupSize: groupSize, bits: bits, mode: mode ) + case .discrete: + break } let (B, nQHeads, L, D) = (queries.dim(0), queries.dim(1), queries.dim(2), queries.dim(3)) @@ -2333,6 +2386,108 @@ public func quantizedScaledDotProductAttention( return output } +/// Spec 041 phase 1.1: fused flash-quantized SDPA via `MLXFast.flashQuantizedSDPA`. +/// +/// Calls the new Metal kernel that dequantises K/V per tile inside the +/// online-softmax loop. Unlike the dequant-then-SDPA stop-gap below, this +/// path never materialises the full FP K_fp / V_fp transient — the only +/// long-lived per-call buffer is the [B, n_q, T_q, V] output. +/// +/// The Metal kernel supports `bits ∈ {2,3,4,6,8}`, `groupSize = 64`, and head +/// dimensions in `{64, 96, 128, 256, 512}`. Shapes outside those instantiations +/// fall through to the dequant-then-SDPA path (`flashQuantizedScaledDotProductAttention`) +/// which handles arbitrary shapes via MLX's generic `dequantized()` op. +/// +/// Mask modes: +/// - `.causal` → kernel-side causal mask (no array materialised) +/// - `.array(m)` → bool / float mask passed through +/// - `.none` → unmasked +/// - `.slidingWindow(_)` → caller must supply the mask as `.array(...)`; +/// the kernel doesn't yet have a fused sliding-window path. Falls back +/// to the discrete + manual softmax fold. +private func fusedFlashQuantizedSDPA( + queries: MLXArray, + quantizedKeys: (MLXArray, MLXArray, MLXArray?), + quantizedValues: (MLXArray, MLXArray, MLXArray?), + scale: Float, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + sinks: MLXArray?, + groupSize: Int, + bits: Int, + mode: QuantizationMode +) -> MLXArray { + // Only affine + groupSize=64 + supported bits are instantiated in the + // kernel. Anything else: fall back to dequant-then-SDPA. + let supportedBits: Set = [2, 3, 4, 6, 8] + let headDim = queries.dim(-1) + let supportedDim: Set = [64, 96, 128, 256, 512] + if mode != .affine || groupSize != 64 || !supportedBits.contains(bits) + || !supportedDim.contains(headDim) + { + return flashQuantizedScaledDotProductAttention( + queries: queries, + quantizedKeys: quantizedKeys, + quantizedValues: quantizedValues, + scale: scale, mask: mask, sinks: sinks, + groupSize: groupSize, bits: bits, mode: mode) + } + + // Map mask mode → (causal flag, array mask). + let causal: Bool + let maskArr: MLXArray? + switch mask { + case .causal: + causal = true + maskArr = nil + case .array(let m): + causal = false + maskArr = m + case .arrays(let arrs): + causal = false + maskArr = arrs.first + case .slidingWindow: + // Sliding-window: kernel doesn't have a native windowed path yet; + // route through the dequant-then-SDPA stop-gap which calls + // `MLXFast.scaledDotProductAttention(... mask: .slidingWindow(...))`. + return flashQuantizedScaledDotProductAttention( + queries: queries, + quantizedKeys: quantizedKeys, + quantizedValues: quantizedValues, + scale: scale, mask: mask, sinks: sinks, + groupSize: groupSize, bits: bits, mode: mode) + case .none: + causal = false + maskArr = nil + } + + // The kernel's bias arg is non-optional; affine quantize always emits + // a bias array. Defensive guard for mxfp4 / unbiased schemes (which + // route through dequant-then-SDPA path above before reaching here). + guard let kBiases = quantizedKeys.2, let vBiases = quantizedValues.2 else { + return flashQuantizedScaledDotProductAttention( + queries: queries, + quantizedKeys: quantizedKeys, + quantizedValues: quantizedValues, + scale: scale, mask: mask, sinks: sinks, + groupSize: groupSize, bits: bits, mode: mode) + } + + return MLXFast.flashQuantizedSDPA( + queries: queries, + kPacked: quantizedKeys.0, + kScales: quantizedKeys.1, + kBiases: kBiases, + vPacked: quantizedValues.0, + vScales: quantizedValues.1, + vBiases: vBiases, + scale: scale, + bits: bits, + groupSize: groupSize, + causal: causal, + mask: maskArr, + sinks: sinks) +} + /// Spec 041 phase 1: flash-quantized SDPA via dequant-then-MLXFastSDPA. /// /// This is the "stop-gap" implementation of phase 1: rather than write a diff --git a/Tests/MLXLMTests/KVCacheTests.swift b/Tests/MLXLMTests/KVCacheTests.swift index 7cef715de3..d229aafa81 100644 --- a/Tests/MLXLMTests/KVCacheTests.swift +++ b/Tests/MLXLMTests/KVCacheTests.swift @@ -1598,6 +1598,93 @@ func testToQuantizedDispatchesOnEviction() async throws { "Head (sink=5) heads should differ from no-sinks; max diff \(headDiff)") } +/// Spec 041 phase 1.1: the fused Metal kernel (`MLXFast.flashQuantizedSDPA`) +/// must match the discrete reference within affine-quantization noise. Forces +/// the kernel path via env override so the test exercises the new kernel +/// regardless of the default L>1/L=1 auto-strategy. +@Test func testFusedFlashQuantizedSDPAMatchesDiscrete() throws { + let B = 1, nQ = 4, nKV = 2, L = 8, T = 32, D = 64 + let bits = 4, groupSize = 64 + let queries = MLXRandom.normal([B, nQ, L, D], dtype: .float32) + let keys = MLXRandom.normal([B, nKV, T, D], dtype: .float32) + let values = MLXRandom.normal([B, nKV, T, D], dtype: .float32) + + let (qK, qKs, qKb) = quantized(keys, groupSize: groupSize, bits: bits) + let (qV, qVs, qVb) = quantized(values, groupSize: groupSize, bits: bits) + + setenv("MLX_AFFINE_SDPA", "kernel", 1) + let outKernel = quantizedScaledDotProductAttention( + queries: queries, + quantizedKeys: (qK, qKs, qKb), + quantizedValues: (qV, qVs, qVb), + scale: 1.0 / Float(D).squareRoot(), + mask: .causal, sinks: nil, + groupSize: groupSize, bits: bits, mode: .affine + ) + + setenv("MLX_AFFINE_SDPA", "discrete", 1) + defer { setenv("MLX_AFFINE_SDPA", "auto", 1) } + let outDiscrete = quantizedScaledDotProductAttention( + queries: queries, + quantizedKeys: (qK, qKs, qKb), + quantizedValues: (qV, qVs, qVb), + scale: 1.0 / Float(D).squareRoot(), + mask: .causal, sinks: nil, + groupSize: groupSize, bits: bits, mode: .affine + ) + eval(outKernel, outDiscrete) + + let maxDiff = MLX.abs(outKernel - outDiscrete).max().item(Float.self) + let meanRef = MLX.abs(outDiscrete).mean().item(Float.self) + let hasNaN = MLX.isNaN(outKernel).any().item(Bool.self) + let hasInf = MLX.isInf(outKernel).any().item(Bool.self) + #expect(!hasNaN, "kernel output must be NaN-free") + #expect(!hasInf, "kernel output must be INF-free") + // Online-softmax accumulation order vs full fp32 softmax — sub-1% + // relative drift expected on this shape. + #expect(maxDiff < 5e-2, + "fused kernel vs discrete: max diff \(maxDiff), mean ref \(meanRef)") +} + +/// Sinks fold inside the fused kernel matches the discrete-path sinks fold. +@Test func testFusedFlashQuantizedSDPASinks() throws { + let B = 1, nQ = 4, nKV = 2, L = 4, T = 32, D = 64 + let bits = 4, groupSize = 64 + let queries = MLXRandom.normal([B, nQ, L, D], dtype: .float32) + let keys = MLXRandom.normal([B, nKV, T, D], dtype: .float32) + let values = MLXRandom.normal([B, nKV, T, D], dtype: .float32) + let sinks = MLXArray([Float(-0.5), 0.5, 1.0, -1.0]) + + let (qK, qKs, qKb) = quantized(keys, groupSize: groupSize, bits: bits) + let (qV, qVs, qVb) = quantized(values, groupSize: groupSize, bits: bits) + + setenv("MLX_AFFINE_SDPA", "kernel", 1) + let outKernel = quantizedScaledDotProductAttention( + queries: queries, + quantizedKeys: (qK, qKs, qKb), + quantizedValues: (qV, qVs, qVb), + scale: 1.0 / Float(D).squareRoot(), + mask: .causal, sinks: sinks, + groupSize: groupSize, bits: bits, mode: .affine + ) + + setenv("MLX_AFFINE_SDPA", "discrete", 1) + defer { setenv("MLX_AFFINE_SDPA", "auto", 1) } + let outDiscrete = quantizedScaledDotProductAttention( + queries: queries, + quantizedKeys: (qK, qKs, qKb), + quantizedValues: (qV, qVs, qVb), + scale: 1.0 / Float(D).squareRoot(), + mask: .causal, sinks: sinks, + groupSize: groupSize, bits: bits, mode: .affine + ) + eval(outKernel, outDiscrete) + + let maxDiff = MLX.abs(outKernel - outDiscrete).max().item(Float.self) + #expect(maxDiff < 5e-2, + "fused kernel sinks vs discrete sinks: max diff \(maxDiff)") +} + /// Flash-quantized SDPA (spec 041 phase 1) at L>1 must match the discrete /// path's output within affine-quantization noise. This is the regression /// gate on the new dequant-then-MLXFastSDPA path that auto-engages for diff --git a/Tests/MLXLMTests/StateReplayCacheTests.swift b/Tests/MLXLMTests/StateReplayCacheTests.swift index 27e932cb02..2a931eecab 100644 --- a/Tests/MLXLMTests/StateReplayCacheTests.swift +++ b/Tests/MLXLMTests/StateReplayCacheTests.swift @@ -631,3 +631,102 @@ struct SSMStateCacheStateReplayTests { #expect(cache.offset == 101) } } + +// MARK: - Spec 040: Mamba state-replay round-trip + +/// Round-trip test for the new Mamba state-replay kernels +/// (`MLXFast.ssmStepRecord` + `MLXFast.ssmReplay`). +@Test func testMambaStateReplayRoundTrip() throws { + let B = 1, T = 8, H = 16, dh = 64, ds = 64, G = 1 + let x = MLXRandom.normal([B, T, H, dh], dtype: .float16) + let ALog = MLXRandom.normal([H], dtype: .float16) * MLXArray(Float16(0.1)) + let Barr = MLXRandom.normal([B, T, G, ds], dtype: .float16) * MLXArray(Float16(0.1)) + let Carr = MLXRandom.normal([B, T, G, ds], dtype: .float16) * MLXArray(Float16(0.1)) + let Darr = MLXArray.zeros([H], dtype: .float16) + let dt = MLX.abs(MLXRandom.normal([B, T, H], dtype: .float16)) * MLXArray(Float16(0.1)) + let stateIn = MLXArray.zeros([B, H, dh, ds], dtype: .float16) + + let outs = MLXFast.ssmStepRecord( + x: x, ALog: ALog, B: Barr, C: Carr, D: Darr, dt: dt, state: stateIn) + #expect(outs.count == 4) + let stateAfterT = outs[1] + let dALog = outs[2] + let dBxLog = outs[3] + eval(stateAfterT, dALog, dBxLog) + + #expect(dALog.shape == [B, T, H, ds]) + #expect(dBxLog.shape == [B, T, H, dh, ds]) + + let replayedAtT = MLXFast.ssmReplay( + stateSnapshot: stateIn, dALog: dALog, dBxLog: dBxLog, acceptedPrefix: T) + eval(replayedAtT) + let diffT = MLX.abs(replayedAtT - stateAfterT).max().item(Float.self) + #expect(diffT < 5e-3, + "replay(k=T) should reproduce recorded state; max diff \(diffT)") + + let replayedAt0 = MLXFast.ssmReplay( + stateSnapshot: stateIn, dALog: dALog, dBxLog: dBxLog, acceptedPrefix: 0) + eval(replayedAt0) + let diff0 = MLX.abs(replayedAt0 - stateIn).max().item(Float.self) + #expect(diff0 < 1e-6, "replay(k=0) should equal snapshot; max diff \(diff0)") + + let kHalf = T / 2 + let replayedAtHalf = MLXFast.ssmReplay( + stateSnapshot: stateIn, dALog: dALog, dBxLog: dBxLog, + acceptedPrefix: kHalf) + eval(replayedAtHalf) + let diffHalfFromZero = MLX.abs(replayedAtHalf - stateIn).max().item(Float.self) + let diffHalfFromT = MLX.abs(replayedAtHalf - stateAfterT).max().item(Float.self) + #expect(diffHalfFromZero > 1e-4, + "replay(k=T/2) should differ from snapshot; max diff \(diffHalfFromZero)") + #expect(diffHalfFromT > 1e-4, + "replay(k=T/2) should differ from final state; max diff \(diffHalfFromT)") +} + +/// End-to-end SSMStateCache rollback through the Mamba dispatcher. +@Test func testSSMStateCacheMambaRollback() throws { + let B = 1, T = 8, H = 16, dh = 64, ds = 64, G = 1 + let snapshot = MLXArray.zeros([B, H, dh, ds], dtype: .float16) + let x = MLXRandom.normal([B, T, H, dh], dtype: .float16) + let ALog = MLXRandom.normal([H], dtype: .float16) * MLXArray(Float16(0.1)) + let Barr = MLXRandom.normal([B, T, G, ds], dtype: .float16) * MLXArray(Float16(0.1)) + let Carr = MLXRandom.normal([B, T, G, ds], dtype: .float16) * MLXArray(Float16(0.1)) + let Darr = MLXArray.zeros([H], dtype: .float16) + let dt = MLX.abs(MLXRandom.normal([B, T, H], dtype: .float16)) * MLXArray(Float16(0.1)) + + let outs = MLXFast.ssmStepRecord( + x: x, ALog: ALog, B: Barr, C: Carr, D: Darr, dt: dt, state: snapshot) + let stateAfterT = outs[1] + let dALog = outs[2] + let dBxLog = outs[3] + eval(stateAfterT, dALog, dBxLog) + + let cache = SSMStateCache() + let convPlaceholder = MLXArray.zeros([B, 4, 32], dtype: .float16) + cache.state = [convPlaceholder, snapshot] + cache.offset = 0 + cache.beginRecord() + cache.state = [convPlaceholder, stateAfterT] + cache.offset = T + cache.recordStep([dALog, dBxLog]) + + cache.rollback(acceptedPrefix: T) + eval(cache.state[1]) + let diffT = MLX.abs(cache.state[1] - stateAfterT).max().item(Float.self) + #expect(diffT < 5e-3, + "rollback(k=T) should reproduce final state; max diff \(diffT)") + #expect(cache.offset == T) + + cache.state = [convPlaceholder, snapshot] + cache.offset = 0 + cache.beginRecord() + cache.state = [convPlaceholder, stateAfterT] + cache.offset = T + cache.recordStep([dALog, dBxLog]) + cache.rollback(acceptedPrefix: 0) + eval(cache.state[1]) + let diff0 = MLX.abs(cache.state[1] - snapshot).max().item(Float.self) + #expect(diff0 < 1e-6, + "rollback(k=0) should restore snapshot; max diff \(diff0)") + #expect(cache.offset == 0) +} diff --git a/specs/040-mamba-state-replay.md b/specs/040-mamba-state-replay.md index 6d5a193875..ab51b55afc 100644 --- a/specs/040-mamba-state-replay.md +++ b/specs/040-mamba-state-replay.md @@ -1,6 +1,6 @@ # 040 — Mamba / Mamba 2 state-replay rollback -**Status:** Spec extracted 2026-05-12 from [spec 020](020-tape-replay-rollback-generalised.md)'s "Mamba / Mamba 2 follow-up (post-MVP)" section. **Not started — scoped at ~1500 LOC across the 4-repo chain (Option 1) or ~200 LOC pure-Swift (Option 2 fallback); both require focused multi-day implementation + per-shape numerical validation against `ssmAttn` reference output.** +**Status:** Option 1 kernel pair shipped 2026-05-13 in the fork's `ek/spec-041-040-fused-kernels` branch (mlx / mlx-c / mlx-swift / mlx-swift-lm). `MLXFast.ssmStepRecord` + `MLXFast.ssmReplay` are live; `NemotronH.mambaForward` routes `T > 1 && cache.isRecording` through the record kernel and `SSMStateCache.rollback` re-folds via the replay kernel. Round-trip unit tests (`testMambaStateReplayRoundTrip`, `testSSMStateCacheMambaRollback`) pass. End-to-end Nemotron-30B-A3B with `--ngram 3` exercises the path (7/25 draft tokens accepted at the first verify cycle). **Known limitation**: conv-state mismatch on partial accept causes mild output drift — recurrent state replays correctly but `applyConv`'s `cache[0]` (the depthwise-conv buffer of last `kernel_size - 1` tokens) stays at its pre-record value. Same issue spec 020's GDN path has (see the comment in `SSMStateCache.rollback`); capturing per-step conv state via a parallel log is the follow-up. The 2026-05-13 session surfaced one design tension worth recording for the next attempt: diff --git a/specs/041-flash-quantized-sdpa.md b/specs/041-flash-quantized-sdpa.md index 2800857ad8..faed231e87 100644 --- a/specs/041-flash-quantized-sdpa.md +++ b/specs/041-flash-quantized-sdpa.md @@ -79,7 +79,7 @@ Group-size + bit-width-specific kernel instantiations (the same template fan-out ### Phase 1 — minimum-viable kernel (affine 4-bit / 8-bit, groupSize=64, GQA, sliding-window mask) -**Status:** Phase 1 stop-gap shipped 2026-05-13 via the **dequant-then-MLXFastSDPA** path (see `flashQuantizedScaledDotProductAttention` in `Libraries/MLXLMCommon/KVCache.swift`). Phases 1, 2, and 4 all pass through the same call: +**Status:** Phase 1 stop-gap shipped 2026-05-13 via the **dequant-then-MLXFastSDPA** path (see `flashQuantizedScaledDotProductAttention` in `Libraries/MLXLMCommon/KVCache.swift`). The **Phase 1.1 fused Metal kernel** also shipped same day (see `mlx/backend/metal/kernels/flash_quantized_sdpa.{h,metal}` in the fork's `ek/spec-041-040-fused-kernels` branch + matching `mlx-c` / `mlx-swift` / `mlx-swift-lm` plumbing). Auto-strategy keeps `.flash` (dequant-then-SDPA) as default because the kernel is correct but not yet matrix-engine-optimised (47% prefill / 18% decode regression vs `.flash` on Qwen 0.8B 8k); `MLX_AFFINE_SDPA=kernel` opts in. Phase 1.2 (simdgroup_matrix_multiply_accumulate MMA + threadgroup codebook + INT8 score accumulator) is the remaining work to close the perf gap. Phases 1, 2, and 4 all pass through the same call: - **Phase 1** (4-bit / 8-bit): MLX's `dequantized()` + `MLXFast.scaledDotProductAttention(...)` cover this shape. - **Phase 2** (2-/3-/6-bit / mxfp4): comes free — `dequantized()` already supports `bits ∈ {2,3,4,5,6,8}` and mxfp4.