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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions Libraries/MLXLLM/Models/Qwen35.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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)
)
}

Expand Down
32 changes: 27 additions & 5 deletions Libraries/MLXLMCommon/GatedDelta.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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`.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
}

Expand Down
19 changes: 15 additions & 4 deletions Libraries/MLXVLM/Models/Qwen35.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Comment on lines +813 to +816

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the float16 seed when replaying an initially empty cache

When float16 storage is enabled and rollback recording begins on an empty MambaCache, this seeds the forward pass with float16 zeros without putting that seed in the recorded base. If commitRollback(keepingRows:) subsequently keeps a shorter prefix, the rollback closure passes base[1] (still nil) to gatedDeltaReplayState, which defaults to float32 zeros and returns a float32 state. Subsequent forwards prefer that cached state, silently disabling float16 storage for the rest of the session and producing a different state than a direct float16 prefix pass. Have the rollback rebuild use the effective seeded recurrent state when the recorded base is nil.

Useful? React with 👍 / 👎.

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 {
Expand Down Expand Up @@ -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)
)
}

Expand Down Expand Up @@ -918,7 +926,10 @@ public enum Qwen35Language {
v: v[0..., ..<rows, 0..., 0...],
g: g[0..., ..<rows, 0...],
beta: beta[0..., ..<rows, 0...],
state: base[1], useKernel: kernelOK)
// A cold cache's base has no state: start from the pass's own initial
// state (a float16 one when the layer stores float16), so the rebuilt
// state keeps the storage dtype (Codex P2, #1697).
state: base[1] ?? recState, useKernel: kernelOK)
let conv =
window > 0
? contiguous(convInput[0..., rows ..< (rows + window), 0...]) : nil
Expand Down
46 changes: 46 additions & 0 deletions Tests/MLXLMTests/GatedDeltaTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
22 changes: 22 additions & 0 deletions Tests/MLXLMTests/MambaCacheHoldTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down