From 5c02e0c4854dd87b58dd16f45490f65d923a9062 Mon Sep 17 00:00:00 2001 From: Jeethu Rao Date: Sun, 15 Nov 2026 21:55:12 +0000 Subject: [PATCH 1/2] GatedDelta: float16 recurrent state storage, opt-in per layer (numen-tech/gemma4-qat#1697) --- Libraries/MLXLLM/Models/Qwen35.swift | 14 ++++++-- Libraries/MLXLMCommon/GatedDelta.swift | 32 +++++++++++++++--- Libraries/MLXVLM/Models/Qwen35.swift | 14 ++++++-- Tests/MLXLMTests/GatedDeltaTests.swift | 46 ++++++++++++++++++++++++++ 4 files changed, 95 insertions(+), 11 deletions(-) diff --git a/Libraries/MLXLLM/Models/Qwen35.swift b/Libraries/MLXLLM/Models/Qwen35.swift index ee5a3f5d90..4b8fbf9f61 100644 --- a/Libraries/MLXLLM/Models/Qwen35.swift +++ b/Libraries/MLXLLM/Models/Qwen35.swift @@ -179,7 +179,7 @@ public struct Qwen35TextConfiguration: Codable, Sendable { // MARK: - GatedDeltaNet -final class Qwen35GatedDeltaNet: Module { +final class Qwen35GatedDeltaNet: Module, GatedDeltaRecurrentStateStorage { let hiddenSize: Int let numVHeads: Int let numKHeads: Int @@ -207,6 +207,9 @@ final class Qwen35GatedDeltaNet: Module { @ModuleInfo(key: "norm") var norm: Qwen3NextRMSNormGated @ModuleInfo(key: "out_proj") var outProj: Linear + /// `GatedDeltaRecurrentStateStorage`: float32 unless the caller opts in to float16. + var recurrentStateDType: DType = .float32 + init(_ args: Qwen35TextConfiguration) { self.hiddenSize = args.hiddenSize self.numVHeads = args.linearNumValueHeads @@ -353,8 +356,13 @@ final class Qwen35GatedDeltaNet: Module { ) -> MLXArray { let convState = cache?[0] ?? zeroStates(batch: inputs.dim(0), dtype: inputs.dtype).conv + // A float32 state stays implicit (`gatedDeltaUpdate` builds the zeros), as before. + let recState = + cache?[1] + ?? (recurrentStateDType == .float32 + ? nil : zeroStates(batch: inputs.dim(0), dtype: inputs.dtype).rec) let (out, newConvState, newRecState, checkpoint) = forward( - inputs, convState: convState, recState: cache?[1], mask: mask, + inputs, convState: convState, recState: recState, mask: mask, checkpointAfter: checkpointAfter) if let cache { if let checkpoint, let checkpointAfter { @@ -375,7 +383,7 @@ final class Qwen35GatedDeltaNet: Module { func zeroStates(batch: Int, dtype: DType) -> (conv: MLXArray, rec: MLXArray) { ( MLXArray.zeros([batch, convKernelSize - 1, convDim], dtype: dtype), - MLXArray.zeros([batch, numVHeads, headVDim, headKDim], dtype: .float32) + MLXArray.zeros([batch, numVHeads, headVDim, headKDim], dtype: recurrentStateDType) ) } diff --git a/Libraries/MLXLMCommon/GatedDelta.swift b/Libraries/MLXLMCommon/GatedDelta.swift index fa2917a8a8..e9f1a5e6ba 100644 --- a/Libraries/MLXLMCommon/GatedDelta.swift +++ b/Libraries/MLXLMCommon/GatedDelta.swift @@ -308,7 +308,10 @@ func gatedDeltaOps( k = repeated(k, count: repeatFactor, axis: -2) } - var state = state ?? MLXArray.zeros([B, Hv, Dv, Dk], dtype: .float32) + // A float16 state (`GatedDeltaRecurrentStateStorage`) is stored float16 only: the steps run in + // float32, like the kernel's, and the state is rounded back once at the end. + let stateType = state?.dtype ?? .float32 + var state = (state ?? MLXArray.zeros([B, Hv, Dv, Dk], dtype: .float32)).asType(.float32) var ys = [MLXArray]() ys.reserveCapacity((T + gatedDeltaRecomputeChunk - 1) / gatedDeltaRecomputeChunk) @@ -332,7 +335,7 @@ func gatedDeltaOps( } let y = ys.count == 1 ? ys[0] : MLX.concatenated(ys, axis: 1) - return (y, state) + return (y, stateType == .float32 ? state : state.asType(stateType)) } // MARK: - MLXFast @@ -356,11 +359,15 @@ private func hasFastGatedDelta(q: MLXArray, v: MLXArray, mask: MLXArray?) -> Boo /// (numen-tech/mlx#22: `gated_delta_update` keeps `g` and `beta` float32 whatever the dtype of /// `q`), so `q`, `k` and `v` go in as they are (numen-tech/gemma4-qat#1693). The state stays /// float32 inside the op either way. +/// +/// mlx core reads the initial state into float32 and returns a float32 state; a float16 state +/// (`GatedDeltaRecurrentStateStorage`) is rounded back once at the end of the call. private func fastGatedDelta( q: MLXArray, k: MLXArray, v: MLXArray, g: MLXArray, beta: MLXArray, state: MLXArray ) -> (MLXArray, MLXArray) { - MLXFast.gatedDeltaUpdate( + let (y, newState) = MLXFast.gatedDeltaUpdate( queries: q, keys: k, values: v, gamma: g, beta: beta, initialState: state) + return (y, newState.dtype == state.dtype ? newState : newState.asType(state.dtype)) } /// The fewest rows `GatedDeltaFastRoute` sends to `MLXFast.gatedDeltaUpdate`. @@ -392,6 +399,19 @@ public enum GatedDeltaFastRoute { @TaskLocal public static var isEnabled = false } +/// A Gated DeltaNet layer whose recurrent state a caller may store in float16 +/// (numen-tech/gemma4-qat#1697). +/// +/// `.float32` (the default) is what every layer stored before. With `.float16` the layer seeds a +/// fresh cache with float16 zeros, and `gatedDeltaUpdate` keeps a float16 state float16: every +/// path reads it into float32, runs the recurrence in float32 and rounds the new state to float16 +/// once per call (the custom kernel per call, `MLXFast.gatedDeltaUpdate` and the ops fallback the +/// same way). Set it before the first forward: a compiled decode trace keeps the dtype it was +/// traced with. +public protocol GatedDeltaRecurrentStateStorage: AnyObject { + var recurrentStateDType: DType { get set } +} + /// The decay gate `g` and write strength `beta` of a GDN layer, in fp32. public func gatedDeltaGates( a: MLXArray, b: MLXArray, aLog: MLXArray, dtBias: MLXArray @@ -433,9 +453,11 @@ public func gatedDeltaUpdate( let Dv = v.dim(3) // State kept in fp32 to match Python mlx-lm. Using q.dtype (bf16) loses - // precision across T-step recurrence, compounding rounding error. + // precision across T-step recurrence, compounding rounding error. A float16 state is a + // caller's storage choice (`GatedDeltaRecurrentStateStorage`): it stays float16 between + // calls, and every path below still runs the recurrence in float32. var state = state ?? MLXArray.zeros([B, Hv, Dv, Dk], dtype: .float32) - if state.dtype != .float32 { + if state.dtype != .float32 && state.dtype != .float16 { state = state.asType(.float32) } diff --git a/Libraries/MLXVLM/Models/Qwen35.swift b/Libraries/MLXVLM/Models/Qwen35.swift index c13ca5e33d..b454759734 100644 --- a/Libraries/MLXVLM/Models/Qwen35.swift +++ b/Libraries/MLXVLM/Models/Qwen35.swift @@ -602,7 +602,7 @@ public enum Qwen35Language { } } - open class GatedDeltaNet: Module { + open class GatedDeltaNet: Module, GatedDeltaRecurrentStateStorage { let hiddenSize: Int let numVHeads: Int let numKHeads: Int @@ -637,6 +637,9 @@ public enum Qwen35Language { @ModuleInfo(key: "norm") var norm: RMSNormGated @ModuleInfo(key: "out_proj") var outProj: Linear + /// `GatedDeltaRecurrentStateStorage`: float32 unless the caller opts in to float16. + public var recurrentStateDType: DType = .float32 + public init(_ args: Qwen35Configuration.TextConfiguration) { self.hiddenSize = args.hiddenSize self.numVHeads = args.linearNumValueHeads @@ -806,8 +809,13 @@ public enum Qwen35Language { // a shorter prefix (`MambaCache.beginRollbackRecording`). The checkpoint split is the // older single-depth mechanism; the two are not combined. let recording = cache?.isRecordingRollback == true && checkpointAfter == nil + // A float32 state stays implicit (`gatedDeltaUpdate` builds the zeros), as before. + let recState = + cache?[1] + ?? (recurrentStateDType == .float32 + ? nil : zeroStates(batch: inputs.dim(0), dtype: inputs.dtype).rec) let result = forward( - inputs, convState: convState, recState: cache?[1], mask: mask, + inputs, convState: convState, recState: recState, mask: mask, checkpointAfter: checkpointAfter, recordRollback: recording) if recording, let cache { if let rollback = result.rollback { @@ -835,7 +843,7 @@ public enum Qwen35Language { MLXArray.zeros( [batch, max(0, convKernelSize - 1), convDim], dtype: dtype), MLXArray.zeros( - [batch, numVHeads, headVDim, headKDim], dtype: .float32) + [batch, numVHeads, headVDim, headKDim], dtype: recurrentStateDType) ) } diff --git a/Tests/MLXLMTests/GatedDeltaTests.swift b/Tests/MLXLMTests/GatedDeltaTests.swift index f7a912151d..c2a0a91ced 100644 --- a/Tests/MLXLMTests/GatedDeltaTests.swift +++ b/Tests/MLXLMTests/GatedDeltaTests.swift @@ -409,4 +409,50 @@ public class GatedDeltaTests: XCTestCase { } } } + + // MARK: - Float16 state storage (numen-tech/gemma4-qat#1697) + + /// A float16 state is storage only, on every path: it comes back float16, and each call runs + /// the float32 recurrence from the stored values and rounds the new state once. So a call from + /// a float16 state equals, bit for bit, the same call from those values held in float32 with + /// its new state rounded to float16, and the outputs are identical. + func testFloat16StateIsStorageOnlyOnEveryPath() throws { + let inputs = makeQwen35Inputs(T: 37) + func run(_ state: MLXArray?, useKernel: Bool = true) -> (MLXArray, MLXArray) { + gatedDeltaUpdate( + q: inputs.q, k: inputs.k, v: inputs.v, a: inputs.a, b: inputs.b, + aLog: inputs.aLog, dtBias: inputs.dtBias, state: state, useKernel: useKernel) + } + let stored = run(nil).1.asType(.float16) + let paths: [(String, (MLXArray) -> (MLXArray, MLXArray))] = [ + ("custom kernel", { run($0) }), + ("ops", { run($0, useKernel: false) }), + ("MLXFast", { state in GatedDeltaFastRoute.$isEnabled.withValue(true) { run(state) } }), + ] + for (name, path) in paths { + let (y16, state16) = path(stored) + let (y32, state32) = path(stored.asType(.float32)) + XCTAssertEqual(state16.dtype, .float16, name) + XCTAssertEqual(state32.dtype, .float32, name) + XCTAssertEqual(y16.dtype, inputs.q.dtype, name) + XCTAssertTrue(arrayEqual(y16, y32).item(Bool.self), "\(name): outputs") + XCTAssertTrue( + arrayEqual(state16, state32.asType(.float16)).item(Bool.self), "\(name): state") + } + } + + /// Without a state the recurrence starts from float32 zeros, and a bfloat16 state is still + /// widened to float32: only float16 is kept as a storage dtype. + func testStateDTypeDefaultsStayFloat32() throws { + let inputs = makeQwen35Inputs(T: 4) + func state(after initial: MLXArray?) -> DType { + gatedDeltaUpdate( + q: inputs.q, k: inputs.k, v: inputs.v, a: inputs.a, b: inputs.b, + aLog: inputs.aLog, dtBias: inputs.dtBias, state: initial + ).1.dtype + } + XCTAssertEqual(state(after: nil), .float32) + XCTAssertEqual(state(after: MLXArray.zeros([1, 32, 128, 128], dtype: .bfloat16)), .float32) + XCTAssertEqual(state(after: MLXArray.zeros([1, 32, 128, 128], dtype: .float16)), .float16) + } } From 002e1c9002e5da359065a3128a7e2f16de6ec45f Mon Sep 17 00:00:00 2001 From: Jeethu Rao Date: Mon, 16 Nov 2026 04:09:34 +0000 Subject: [PATCH 2/2] Qwen35 rollback replay: a cold cache rebuilds from the pass's initial state, keeping float16 storage (numen-tech/gemma4-qat#1697, Codex P2) --- Libraries/MLXVLM/Models/Qwen35.swift | 5 ++++- Tests/MLXLMTests/MambaCacheHoldTests.swift | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Libraries/MLXVLM/Models/Qwen35.swift b/Libraries/MLXVLM/Models/Qwen35.swift index b454759734..0982cae761 100644 --- a/Libraries/MLXVLM/Models/Qwen35.swift +++ b/Libraries/MLXVLM/Models/Qwen35.swift @@ -926,7 +926,10 @@ public enum Qwen35Language { v: v[0..., .. 0 ? contiguous(convInput[0..., rows ..< (rows + window), 0...]) : nil diff --git a/Tests/MLXLMTests/MambaCacheHoldTests.swift b/Tests/MLXLMTests/MambaCacheHoldTests.swift index 0d0352dd82..1b21868db8 100644 --- a/Tests/MLXLMTests/MambaCacheHoldTests.swift +++ b/Tests/MLXLMTests/MambaCacheHoldTests.swift @@ -275,6 +275,28 @@ final class MambaCacheHoldTests: XCTestCase { try assertRewindReplays(compiled: true) } + /// numen-tech/gemma4-qat#1697 (Codex P2): a verify pass recorded on a cold cache, then a + /// partial commit, rebuilds the state from the pass's own initial state, so a layer that + /// stores float16 still holds float16 after the rollback (float32 by default). + func testColdRollbackKeepsTheStorageDType() throws { + for dtype in [DType.float32, .float16] { + let model = try makeModel(seed: 47) + let storages = model.modules().compactMap { $0 as? GatedDeltaRecurrentStateStorage } + XCTAssertFalse(storages.isEmpty) + for storage in storages { storage.recurrentStateDType = dtype } + let mamba = MambaCache() + let cache: [KVCache?] = [mamba, KVCacheSimple()] + mamba.beginRollbackRecording() + let input = MLXArray(Array(tokens.prefix(4))).reshaped(1, 4) + let positionIds = MLXArray( + (0 ..< 3).flatMap { axis in positions.prefix(4).map { $0[axis] } } + ).reshaped(3, 1, 4) + eval(model.forward(input, cache: cache, positionIds: positionIds, useCompiledDecode: false)) + XCTAssertTrue(mamba.commitRollback(keepingRows: 2), "\(dtype)") + XCTAssertEqual(mamba[1]?.dtype, dtype, "the rebuilt state keeps the storage dtype") + } + } + /// A prefill chunk (more than one token) never leaves a hold, so a trim after prefill is /// refused rather than restoring the wrong state. func testPrefillLeavesNothingHeld() throws {