Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
8bfcdde
fix segsum dtype promotion -- 2x memory waste on hybrid SSM models (#…
TheTom May 12, 2026
d8cbca8
Fix nomic-embed-text-v1.5 'Key embeddings.position_embeddings.weight …
JamalK Jun 17, 2026
f72395e
Fix EmbeddingGemma init-order crash + dense head hidden size (#223)
0xweb3r May 13, 2026
1d89424
fix: disable CIContext intermediate caching to prevent IOSurface exha…
Satchitananda May 13, 2026
e3dd4e3
fix gated delta state precision -- fp32 state to match Python (#224)
TheTom May 14, 2026
7f001ce
fix(ssm): fp32 g/beta consistency + masked-output zero in gatedDelta
Gajesh2007 Jun 23, 2026
447fe21
fix(kv-quant): gate maybeQuantizeKVCache on first KVCacheSimple (hybr…
Gajesh2007 Jun 23, 2026
fbaf8a3
feat(tools): add .gemma4 ToolCallFormat case + auto-detect (8c61800)
Gajesh2007 Jun 23, 2026
b50b690
fix(tools): string-aware bare-JSON + declared-tool filter + FIFO drai…
Gajesh2007 Jun 23, 2026
529d18a
fix(kv-quant): group-size auto-resolve + quant-param serialization (0…
Gajesh2007 Jun 23, 2026
81dedb5
revert(tools): drop distinct .gemma4 ToolCallFormat case (supersedes …
Gajesh2007 Jun 23, 2026
88a2f78
perf(moe): fused gate_up single matmul + compiled GLU/combine kernels…
Gajesh2007 Jun 23, 2026
45625ed
Fix Qwen35 VLM crash on text-only inference (SmallVector out of range…
dirvine May 7, 2026
1abd96e
Fix UserInput init not setting self.images / self.videos (#182) (#253)
john-rocky May 14, 2026
49ad1fc
fix Idefics3 prepare() to honor windowSize -- prompt prefill is never…
Adi2K May 22, 2026
004f783
fix Idefics3 vision encoder dtype -- SigLIP runs in float32 instead o…
Adi2K May 26, 2026
e499571
Fix vision-encoder attention mask being ignored in Qwen2.5-VL (#238)
NivDvir May 27, 2026
a4b7c79
Fix Qwen2-VL chat template: emit vision tokens before text (#242)
NivDvir May 27, 2026
b0ff526
Fix Qwen35 VLM sanitize for bare 'model.*' weight keys (#143) (#254)
john-rocky May 27, 2026
625c101
Fix SmolVLM2 tiles() upscaling small images, ~9x slowdown (#208) (#255)
john-rocky May 27, 2026
c3294f4
Qwen2/2.5-VL: default to the model card's image pixel budget (#243)
NivDvir Jun 9, 2026
48066d5
Expose ModelTypeRegistry.contains(_:) for pre-load support checks (#349)
jfranknichols Jun 16, 2026
1b68504
fix MLXVLM prepare(): honor windowSize for chunked prefill (FastVLM /…
john-rocky Jun 17, 2026
04afe43
fix(lfm2-moe): sigmoid routing + bias-selection-only + scaling (e3cb1e1)
Gajesh2007 Jun 23, 2026
563f9a7
fix(gemma4-vlm): no-cache KV share + 1D inputs + MoE router softmax o…
Gajesh2007 Jun 23, 2026
832167d
fix(qwen35-vlm): share fp32 gated-delta with MLXLLM (NB-1)
Gajesh2007 Jun 23, 2026
3a834ce
test(tools): cover declared-tool filter in JSON parser (NB-2)
Gajesh2007 Jun 23, 2026
fd01c04
test(lfm2-moe): lock sigmoid routing parity (NB-3)
Gajesh2007 Jun 23, 2026
f073a32
test(switchglu): quantized fused gate_up parity (N1)
Gajesh2007 Jun 23, 2026
48313a0
Merge origin/main (PR #48 EngineCore idle-clear marker) into feat/inh…
Gajesh2007 Jun 24, 2026
8a212b4
feat(gemma4): port vMLX decode hot path (#55)
Gajesh2007 Jun 26, 2026
b1af5c7
Merge remote-tracking branch 'origin/main' into feat/inherit-upstream…
Gajesh2007 Jun 26, 2026
b13f6b7
Merge remote-tracking branch 'origin/feat/inherit-upstream-2026-06' i…
Gajesh2007 Jun 26, 2026
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
62 changes: 55 additions & 7 deletions Libraries/MLXLLM/Models/Gemma4Text.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,45 @@ import MLX
import MLXLMCommon
import MLXNN

// MARK: - vMLX decode hot-path helpers (ported from osaurus/main Gemma4Text)
//
// File-private, self-contained compiled fusions. They do NOT depend on the
// SwitchLayers / HardwareInfo lane so this file builds stand-alone; when that
// lane lands public `safeGeluApproximate` / `MLXHardwareInfo` these can collapse
// to the shared symbols (identical math + same env knob) with no behavior change.
// `compile(shapeless: true)` is gated by `MLX_COMPILED_DECODE` (default on),
// mirroring `MLXHardwareInfo.isCompiledDecodeSupported`, so M1/M2 + macOS Tahoe
// (MLX #3329) can opt out without a code change. Matches the ungated
// `compiledSiluProduct` / `weightedExpertSum` convention already in this tree.
private let gemma4CompiledDecodeSupported: Bool = {
if let raw = ProcessInfo.processInfo.environment["MLX_COMPILED_DECODE"] {
return ["1", "true", "yes", "on"].contains(raw.lowercased())
}
return true
}()

/// Approximate (tanh) GELU written with `x * x * x` instead of the Power
/// primitive (`x ** 3`) so it is safe under `compile(shapeless: true)` — the
/// Power primitive returns zero results on the Tahoe Metal JIT (MLX #3329).
/// Numerically identical to `MLXNN.geluApproximate` (vMLX `safeGeluApproximate`).
private let gemma4SafeGeluApproximate: @Sendable (MLXArray) -> MLXArray = {
let body: @Sendable (MLXArray) -> MLXArray = { (x: MLXArray) -> MLXArray in
0.5 * x * (1 + tanh(sqrt(2 / Float.pi) * (x + 0.044715 * x * x * x)))
}
return gemma4CompiledDecodeSupported ? compile(shapeless: true, body) : body
}()

/// Final-logit softcap (`tanh(x / cap) * cap`) fused into one Metal dispatch
/// (vMLX `compiledLogitSoftcap`). The untyped (float32) cap keeps the softcap
/// math — and the logits handed to the sampler — full precision.
private let gemma4CompiledLogitSoftcap: @Sendable (MLXArray, MLXArray) -> MLXArray = {
let body: @Sendable (MLXArray, MLXArray) -> MLXArray = {
(x: MLXArray, cap: MLXArray) -> MLXArray in
tanh(x / cap) * cap
}
return gemma4CompiledDecodeSupported ? compile(shapeless: true, body) : body
}()

// MARK: - Configuration

struct Gemma4WeightQuantizationMetadata: Codable, Sendable {
Expand Down Expand Up @@ -573,7 +612,7 @@ private class Gemma4Experts: Module {
inputDims: config.hiddenSize,
hiddenDims: moeIntermediate,
numExperts: numExperts,
activation: { geluApproximate($0) },
activation: { gemma4SafeGeluApproximate($0) },
bias: false
)
super.init()
Expand All @@ -582,9 +621,15 @@ private class Gemma4Experts: Module {
func callAsFunction(
_ x: MLXArray, topKIndices: MLXArray, topKWeights: MLXArray
) -> MLXArray {
let w = MLX.expandedDimensions(topKWeights, axis: -1)
let y = switchGLU(x, topKIndices)
return (w * y).sum(axis: -2)
// Flatten [B, S, H] -> [B*S, H] (and indices/weights to [B*S, K]) so
// SwitchGLU runs its optimized 2D gather/sort path, then fuse the
// per-expert scale + reduce via the shared compiled `weightedExpertSum`
// and reshape back. Numerically identical to the prior
// `(expandDims(weights, -1) * switchGLU(x, idx)).sum(-2)`; matches vMLX.
let (B, S, H) = (x.dim(0), x.dim(1), x.dim(2))
let K = topKIndices.dim(-1)
let y = switchGLU(x.reshaped(B * S, H), topKIndices.reshaped(B * S, K))
return weightedExpertSum(y, topKWeights.reshaped(B * S, K)).reshaped(B, S, H)
}
}

Expand All @@ -608,7 +653,7 @@ private class Gemma4MLP: Module {
}

func callAsFunction(_ x: MLXArray) -> MLXArray {
downProj(geluApproximate(gateProj(x)) * upProj(x))
downProj(gemma4SafeGeluApproximate(gateProj(x)) * upProj(x))
}
}

Expand Down Expand Up @@ -746,7 +791,7 @@ public class Gemma4DecoderLayer: Module {
{
let residual3 = out
var g = gate(out)
g = geluApproximate(g)
g = gemma4SafeGeluApproximate(g)
g = g * perLayerInput
g = proj(g)
g = norm(g)
Expand Down Expand Up @@ -1008,7 +1053,10 @@ public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider {
} else {
out = model.embedTokens.asLinear(hidden)
}
out = tanh(out / config.finalLogitSoftcapping) * config.finalLogitSoftcapping
// Fused tanh-softcap (vMLX `compiledLogitSoftcap`). Untyped (float32) cap
// keeps the softcap math + sampler logits full precision; when the compile
// gate is off this is equivalent to `tanh(out / cap) * cap`.
out = gemma4CompiledLogitSoftcap(out, MLXArray(config.finalLogitSoftcapping))
return out
}

Expand Down
255 changes: 255 additions & 0 deletions Libraries/MLXLMCommon/CompilableKVCache.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
// CompilableKVCache: Fixed-size KV cache using the Overflow Bin pattern.
//
// Ported from osaurus-ai/vmlx-swift-lm (Libraries/MLXLMCommon/CompilableKVCache.swift).
// This is the foundation type for whole-step compiled decode: it is the only
// full-attention cache whose `update()` is graph-traceable, so a decode step
// (model forward + cache write) can be captured by `compile(inputs:outputs:)`.
//
// Standard KVCacheSimple returns keys[..<offset] — a dynamically sized slice that
// changes every decode step. This prevents compile() from tracing through the cache
// because DynamicSlice requires static slice_size.
//
// CompilableKVCache solves this by:
// 1. Pre-allocating a fixed-size buffer [B, H, maxLength, D]
// 2. Writing new keys/values via dynamicSliceUpdate (compile-traceable writes)
// 3. Returning the FULL buffer from update() — constant shape every step
// 4. Generating a boolean attention mask in makeMask() that marks active positions
//
// The attention kernel handles the masking, computing only on valid positions.
// This trades marginal redundant compute (masked zeros) for enabling compile()
// to fuse hundreds of FFI crossings into a single compiled call.
//
// Usage:
// // After prefill with standard cache, convert for compiled decode:
// let compilableCache = standardCache.map { c in
// CompilableKVCache(from: c, maxLength: 2048)
// }
//
// NOTE (Darkbloom): this type is presently UNWIRED — it ships as the verified
// foundation for a future compiled-decode path. See `CompiledDecode.swift` for
// the `compileDecodeForward` wrapper and the port plan for batched integration
// into `GenerationBatch`.

import Foundation
import MLX
import MLXNN

/// A KV cache that returns fixed-size buffers to enable compile().
///
/// Key differences from KVCacheSimple:
/// - `offsetArray` (MLXArray) tracks position in the computation graph
/// - Pre-allocated buffer of fixed size (no dynamic growth during decode)
/// - `update()` returns the FULL buffer — mask handles which positions are valid
/// - `makeMask()` always returns an array mask covering the full buffer
/// - `innerState()` returns [keys, values, offsetArray] — all compile-tracked
public class CompilableKVCache: BaseKVCache {

public var keys: MLXArray?
public var values: MLXArray?

/// Offset as MLXArray (1D [1] int32) — tracked by compile tracer.
/// Must be 1D (not scalar) for DynamicSlice start parameter compatibility.
public var offsetArray: MLXArray

/// Maximum sequence length the buffer can hold.
public let maxLength: Int

/// Pre-allocation chunk size (same semantics as KVCacheSimple.step).
public var step: Int

/// Pre-computed column indices for mask creation [0, 1, ..., maxLength-1].
/// Avoids re-creating every step.
private lazy var maskRinds: MLXArray = MLXArray(Int32(0) ..< Int32(maxLength))

public init(maxLength: Int = 4096, step: Int = 256) {
self.maxLength = maxLength
self.step = step
self.offsetArray = MLXArray([Int32(0)])
super.init()
}

/// Create from an existing KVCacheSimple (e.g., after prefill).
/// Copies the existing cache state into a fixed-size buffer.
public convenience init(from cache: KVCache, maxLength: Int = 4096) {
self.init(maxLength: maxLength)

let existingState = cache.state
if existingState.count >= 2 {
let existingKeys = existingState[0] // [B, H, seqLen, D]
let existingValues = existingState[1]

let seqLen = existingKeys.dim(2)
let B = existingKeys.dim(0)
let H = existingKeys.dim(1)
let kD = existingKeys.dim(3)
let vD = existingValues.dim(3)

// Pre-allocate to maxLength
self.keys = MLXArray.zeros([B, H, maxLength, kD], dtype: existingKeys.dtype)
self.values = MLXArray.zeros([B, H, maxLength, vD], dtype: existingValues.dtype)

// Copy existing data at position 0
self.keys![.ellipsis, ..<seqLen, 0...] = existingKeys
self.values![.ellipsis, ..<seqLen, 0...] = existingValues

self.offsetArray = MLXArray([Int32(seqLen)])
}
}

// MARK: - KVCache protocol

public override var offset: Int {
get {
// Materialize for compatibility with code that reads offset as Int.
// This triggers synchronous readback — avoid inside compiled paths.
offsetArray[0].item(Int.self)
}
set {
offsetArray = MLXArray([Int32(newValue)])
}
}

public override func innerState() -> [MLXArray] {
if let keys, let values {
return [keys, values, offsetArray]
}
return [offsetArray]
}

public override func update(keys newKeys: MLXArray, values newValues: MLXArray)
-> (MLXArray, MLXArray)
{
let nTokens = newKeys.dim(2)

// Lazy initialization on first call
if self.keys == nil {
let B = newKeys.dim(0)
let H = newKeys.dim(1)
let kD = newKeys.dim(3)
let vD = newValues.dim(3)
self.keys = MLXArray.zeros([B, H, maxLength, kD], dtype: newKeys.dtype)
self.values = MLXArray.zeros([B, H, maxLength, vD], dtype: newValues.dtype)
}

let prev = offsetArray
let newOffset = prev + MLXArray([Int32(nTokens)])

// Must use _updateInternal to preserve object identity — compile() captures
// stateInputs at innerCall start and expects the same objects to be mutated.
self.keys!._updateInternal(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 [INFO] 🔒 DynamicSlice start parameter lacks bounds validation

💡 Suggestion: Add validation that offsetArray values are within valid bounds for the buffer dimensions before calling dynamicSliceUpdate

📊 Score: 2×3 = 6 · Category: missing-input-validation

dynamicSliceUpdate(self.keys!, update: newKeys, start: prev, axes: [2]))
self.values!._updateInternal(
dynamicSliceUpdate(self.values!, update: newValues, start: prev, axes: [2]))

self.offsetArray._updateInternal(newOffset)

// OVERFLOW BIN: return the full static-size buffer.
// The attention mask from makeMask() handles which positions are valid.
// This keeps tensor shapes constant across all decode steps,
// enabling compile() to trace the entire forward pass.
return (self.keys!, self.values!)
}

// MARK: - Mask (Overflow Bin)

/// Generate attention mask for the full-buffer return.
///
/// Since update() returns the entire maxLength buffer, we ALWAYS need an array
/// mask to prevent attention to unwritten positions. The mask is boolean:
/// True = attend, False = don't attend (gets -inf in attention scores).
///
/// For decode (n=1): mask[0, j] = (j <= offset)
/// For prefill (n>1): mask[i, j] = (j <= offset + i) (causal)
///
/// Note: `offset` here is the PRE-update value. After update, positions
/// 0..<offset+n are valid, matching the mask exactly.
///
/// Uses `offsetArray` (MLXArray) for all computation so compile() can trace
/// the mask through the computation graph.
public override func makeMask(
n: Int, windowSize: Int?, returnArray: Bool
) -> MLXFast.ScaledDotProductAttentionMaskMode {
// Use offsetArray directly — compile-traceable, no .item() needed
let currentOffsetArr = offsetArray // MLXArray [1] int32

// Query positions: [offset, offset+1, ..., offset+n-1]
let linds: MLXArray
if n == 1 {
linds = currentOffsetArr.reshaped(1, 1)
} else {
linds = (MLXArray(Int32(0) ..< Int32(n)) + currentOffsetArr).reshaped(n, 1)
}

// Key positions: [0, 1, ..., maxLength-1]
let rinds = maskRinds.reshaped(1, maxLength)

// Causal + validity: attend to positions j where j <= query_position
var mask = linds .>= rinds

// Apply sliding window if specified
if let windowSize {
let windowStart = linds - Int32(windowSize - 1)
mask = mask & (rinds .>= windowStart)
}

return .array(mask)
}

// MARK: - State

public override var state: [MLXArray] {
get {
guard let keys, let values else { return [] }
let off: Int = offsetArray[0].item(Int.self)
if off == keys.dim(2) {
return [keys, values]
} else {
// Return only valid portion for serialization
return [
keys[.ellipsis, ..<off, 0...],
values[.ellipsis, ..<off, 0...],
]
}
}
set {
guard newValue.count == 2 else { return }
let seqLen = newValue[0].dim(2)
let B = newValue[0].dim(0)
let H = newValue[0].dim(1)
let kD = newValue[0].dim(3)
let vD = newValue[1].dim(3)

self.keys = MLXArray.zeros([B, H, maxLength, kD], dtype: newValue[0].dtype)
self.values = MLXArray.zeros([B, H, maxLength, vD], dtype: newValue[1].dtype)
self.keys![.ellipsis, ..<seqLen, 0...] = newValue[0]
self.values![.ellipsis, ..<seqLen, 0...] = newValue[1]
self.offsetArray = MLXArray([Int32(seqLen)])
}
}

public override var isTrimmable: Bool { true }

@discardableResult
public override func trim(_ n: Int) -> Int {
let current: Int = offsetArray[0].item(Int.self)
let trimmed = min(current, n)
offsetArray = MLXArray([Int32(current - trimmed)])
super.offset = current - trimmed
return trimmed
}

public override func copy() -> any KVCache {
let c = CompilableKVCache(maxLength: maxLength, step: step)
c.keys = keys
c.values = values
c.offsetArray = offsetArray
return c
}

// MARK: - Debug

public var debugDescription: String {
"CompilableKVCache(offset=\(offset), maxLength=\(maxLength), "
+ "shape=\(keys?.shape.description ?? "nil"))"
}
}
Loading