diff --git a/Libraries/MLXLMCommon/GatedDelta.swift b/Libraries/MLXLMCommon/GatedDelta.swift index d00e89126c..fa2917a8a8 100644 --- a/Libraries/MLXLMCommon/GatedDelta.swift +++ b/Libraries/MLXLMCommon/GatedDelta.swift @@ -348,21 +348,29 @@ private func hasFastGatedDelta(q: MLXArray, v: MLXArray, mask: MLXArray?) -> Boo } } -/// `MLXFast.gatedDeltaUpdate` with `g` and `beta` kept in float32. +/// `MLXFast.gatedDeltaUpdate` in the activation dtype. /// -/// mlx core casts `g` and `beta` to the dtype of `q` and `k`. In bf16 a decay -/// just below 1 rounds to 1, so the state stops decaying (ml-explore/mlx#4725). -/// Float32 `q` and `k` prevent the cast. Remove the casts when mlx-swift includes -/// ml-explore/mlx#4760. +/// mlx core used to cast `g` and `beta` to the dtype of `q` and `k`; in bf16 a decay just below 1 +/// rounds to 1 and the state stops decaying (ml-explore/mlx#4725). Upstream (#740) worked around +/// that with float32 `q` and `k`. This fork's core carries the fix, ml-explore/mlx#4760 +/// (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. private func fastGatedDelta( q: MLXArray, k: MLXArray, v: MLXArray, g: MLXArray, beta: MLXArray, state: MLXArray ) -> (MLXArray, MLXArray) { - let (y, state) = MLXFast.gatedDeltaUpdate( - queries: q.asType(.float32), keys: k.asType(.float32), values: v, - gamma: g, beta: beta, initialState: state) - return (y.asType(q.dtype), state) + MLXFast.gatedDeltaUpdate( + queries: q, keys: k, values: v, gamma: g, beta: beta, initialState: state) } +/// The fewest rows `GatedDeltaFastRoute` sends to `MLXFast.gatedDeltaUpdate`. +/// +/// mlx core runs its chunked kernels only above 8 rows (`gated_delta_chunk_size`: chunks of 8, or +/// 16 on NAX GPUs); at 8 rows or fewer it runs a per-step kernel, the same recurrence as +/// `gated_delta_step` without the compensated sum, so there is no chunked kernel to gain there and +/// such calls keep the custom kernel (numen-tech/gemma4-qat#1693). +public let gatedDeltaFastRouteMinRows = 9 + // MARK: - Public API /// Whether `gatedDeltaUpdate` may take `MLXFast.gatedDeltaUpdate` (upstream #740) for the @@ -375,10 +383,11 @@ private func fastGatedDelta( /// `GatedDeltaFastRoute.$isEnabled.withValue(true) { ... }`. The route is chosen when the graph /// is built, which happens inside the call, so the task-local reaches it. /// -/// Even when on, a single-row call keeps the custom kernel: compiled single-token decode traces -/// (`CompiledTrace`) keep the graph of their first call, so a decode step traced inside an -/// opted-in region would otherwise carry the fast route into every later step. A rollback- -/// recorded verify (Qwen3.5 VLM) also keeps the custom kernel, matching its replay. +/// Even when on, a call of fewer than `gatedDeltaFastRouteMinRows` rows keeps the custom kernel: +/// mlx core would run its per-step kernel there, not a chunked one, and compiled single-token +/// decode traces (`CompiledTrace`) keep the graph of their first call, so a decode step traced +/// inside an opted-in region would otherwise carry the fast route into every later step. A +/// rollback-recorded verify (Qwen3.5 VLM) also keeps the custom kernel, matching its replay. public enum GatedDeltaFastRoute { @TaskLocal public static var isEnabled = false } @@ -445,7 +454,8 @@ public func gatedDeltaUpdate( // The MLXFast kernel has a gradient and is faster than both, so upstream // sends the layouts it supports there in training and in inference. On this // fork only a caller that opts in takes it (`GatedDeltaFastRoute`). - if GatedDeltaFastRoute.isEnabled, q.dim(1) > 1, hasFastGatedDelta(q: q, v: v, mask: mask) { + if GatedDeltaFastRoute.isEnabled, q.dim(1) >= gatedDeltaFastRouteMinRows, + hasFastGatedDelta(q: q, v: v, mask: mask) { return fastGatedDelta(q: q, k: k, v: v, g: g, beta: beta, state: state) } if useKernel, GatedDeltaKernelManager.shared.kernel != nil, Dk % 32 == 0 { diff --git a/Tests/MLXLMTests/GatedDeltaTests.swift b/Tests/MLXLMTests/GatedDeltaTests.swift index 87327fc661..f7a912151d 100644 --- a/Tests/MLXLMTests/GatedDeltaTests.swift +++ b/Tests/MLXLMTests/GatedDeltaTests.swift @@ -316,9 +316,11 @@ public class GatedDeltaTests: XCTestCase { /// A decay just below 1 must still decay the state. /// - /// In bf16, 0.999 rounds to 1. mlx core casts `g` to the dtype of `q`, so - /// without float32 `q` and `k` the state stops decaying and drifts away - /// from the custom kernel, which keeps `g` in float32 (ml-explore/mlx#4725). + /// In bf16, 0.999 rounds to 1. mlx core used to cast `g` to the dtype of `q`, so the state + /// stopped decaying and drifted away from the custom kernel, which keeps `g` in float32 + /// (ml-explore/mlx#4725). This fork's core keeps `g` and `beta` float32 (ml-explore/mlx#4760), + /// and the fast route feeds bf16 `q` and `k` as they are (numen-tech/gemma4-qat#1693), so this + /// checks the core's fix, not a cast in Swift. /// /// On NAX hardware mlx core runs a chunked kernel that drifts more over 256 /// steps. A lost decay still drifts far more than that. @@ -342,10 +344,11 @@ public class GatedDeltaTests: XCTestCase { } } - /// The fork's routing (numen-tech/gemma4-qat#1692): without an opt-in a fused layout keeps - /// the custom kernel, bit for bit; inside one, a multi-row call takes the MLXFast kernel - /// (different rounding) and a single-row call does not, so a compiled decode trace built - /// inside an opted-in region cannot carry the fast route into later steps. + /// The fork's routing (numen-tech/gemma4-qat#1692, #1693): without an opt-in a fused layout + /// keeps the custom kernel, bit for bit; inside one, a call of `gatedDeltaFastRouteMinRows` + /// rows or more takes the MLXFast kernel (different rounding) and a shorter one does not, so a + /// compiled decode trace built inside an opted-in region cannot carry the fast route into later + /// steps, and the rows mlx core would run step by step stay on the custom kernel. func testGatedDeltaFastRouteIsOptInAndMultiRowOnly() throws { func run(_ inputs: Inputs) -> (MLXArray, MLXArray) { gatedDeltaUpdate( @@ -364,10 +367,17 @@ public class GatedDeltaTests: XCTestCase { XCTAssertTrue(identical(byDefault, forcedOff), "the default must be the custom kernel") XCTAssertFalse(identical(byDefault, optedIn), "an opt-in must reach the MLXFast kernel") - let step = makeQwen35Inputs(T: 1) - XCTAssertTrue( - identical(run(step), GatedDeltaFastRoute.$isEnabled.withValue(true) { run(step) }), - "a single-row call keeps the custom kernel inside an opt-in") + for rows in [1, gatedDeltaFastRouteMinRows - 1] { + let short = makeQwen35Inputs(T: rows) + XCTAssertTrue( + identical(run(short), GatedDeltaFastRoute.$isEnabled.withValue(true) { run(short) }), + "a \(rows)-row call keeps the custom kernel inside an opt-in") + } + let shortest = makeQwen35Inputs(T: gatedDeltaFastRouteMinRows) + XCTAssertFalse( + identical( + run(shortest), GatedDeltaFastRoute.$isEnabled.withValue(true) { run(shortest) }), + "a \(gatedDeltaFastRouteMinRows)-row call takes the MLXFast kernel inside an opt-in") } /// Training must differentiate through the MLXFast kernel and get the