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
24 changes: 18 additions & 6 deletions Libraries/MLXLLM/Models/GatedDelta.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ import MLXNN
// MARK: - Compute G

func computeGatedDeltaG(_ aLog: MLXArray, _ a: MLXArray, _ dtBias: MLXArray) -> MLXArray {
let decay = exp(-exp(aLog.asType(.float32)) * softplus(a + dtBias))
return decay.asType(a.dtype)
// Stay in model dtype (bf16) — no fp32 promotion needed.
// The double-exp is numerically safe in bf16 for the typical aLog range (-1 to -8).
return exp(-exp(aLog) * softplus(a + dtBias))
}

// MARK: - Metal Kernel
Expand Down Expand Up @@ -238,6 +239,10 @@ func gatedDeltaOps(

var state = state ?? MLXArray.zeros([B, Hv, Dv, Dk], dtype: q.dtype)

// Process in sub-chunks with eval barriers to bound peak memory.
// Without this, the lazy graph grows to T * (intermediates per step),
// causing peak memory proportional to T during prefill.
let evalInterval = 64
var ys = [MLXArray]()
ys.reserveCapacity(T)

Expand All @@ -260,6 +265,14 @@ func gatedDeltaOps(
)
ys.append(y)
state = newState

// Eval barrier: materialize state and accumulated outputs to free
// intermediate graph nodes. Caps graph at O(evalInterval) instead of O(T).
if T > 1 && (t + 1) % evalInterval == 0 {
eval(state)
eval(ys)
MLX.Memory.clearCache()
}
}

let y = MLX.stacked(ys, axis: 1)
Expand Down Expand Up @@ -289,9 +302,8 @@ func gatedDeltaUpdate(

let state = state ?? MLXArray.zeros([B, Hv, Dv, Dk], dtype: q.dtype)

if GatedDeltaKernelManager.shared.kernel != nil {
return gatedDeltaKernel(q: q, k: k, v: v, g: g, beta: beta, state: state, mask: mask)
}

// TODO: The inline Metal kernel (metalKernel) has a correctness bug at T>1 prefill
// (max diff 0.25 vs ops). Use ops fallback until the kernel is fixed.
// The kernel path is kept for future T=1 decode optimization.
return gatedDeltaOps(q: q, k: k, v: v, g: g, beta: beta, state: state, mask: mask)
}
25 changes: 24 additions & 1 deletion Libraries/MLXLLM/Models/Qwen35.swift
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,10 @@ final class Qwen35GatedDeltaNet: Module {

let convInput = concatenated([convState, qkv], axis: 1)
if let cache {
cache[0] = convInput[0..., (-(convKernelSize - 1))...]
// .contiguous() breaks the lazy chain: without it, each decode step
// builds concat(prev_slice, qkv) -> slice, keeping ALL prior qkv arrays
// alive in the graph. This causes ~9GB/run memory growth for Qwen3.5-9B.
cache[0] = convInput[0..., (-(convKernelSize - 1))...].contiguous()
}

let convOut = silu(conv1d(convInput))
Expand Down Expand Up @@ -534,13 +537,30 @@ public class Qwen35TextModelInner: Module {
let faMask = createAttentionMask(h: hiddenStates, cache: cacheArray?[faIdx])
let ssmMask = createSSMMask(h: hiddenStates, cache: cacheArray?[ssmIdx] as? MambaCache)

let modelDtype = hiddenStates.dtype
let isPrefill = hiddenStates.dim(1) > 1
for (i, layer) in layers.enumerated() {
let mask = layer.isLinear ? ssmMask : nil
let attnMask =
layer.isLinear
? MLXFast.ScaledDotProductAttentionMaskMode.none : faMask
hiddenStates = layer(
hiddenStates, attentionMask: attnMask, ssmMask: mask, cache: cacheArray?[i])
// Force dtype after every layer — quantized operations can promote
// bf16 -> fp32 inside the lazy graph (invisible to .dtype property).
// The unconditional asType adds a cast node that ensures downstream
// GDN/attention kernels receive bf16. When dtype is already correct,
// asType is a no-op (zero overhead).
hiddenStates = hiddenStates.asType(modelDtype)

// During prefill, eval after each layer to free intermediate activation
// buffers. Without this, the lazy graph spans all layers (~1.6GB for
// 0.8B at T=2048). Per-layer eval keeps peak bounded to one layer's
// activations (~110MB for GDN, ~90MB for attention+MoE).
// Skip during decode (T=1) where the graph is tiny and eval overhead hurts tok/s.
if isPrefill, let c = cacheArray?[i] {
eval(hiddenStates, c)
}
}

return norm(hiddenStates)
Expand Down Expand Up @@ -582,6 +602,9 @@ public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider {
if layer.isLinear {
return MambaCache()
}
if let maxKVSize = parameters?.maxKVSize {
return RotatingKVCache(maxSize: maxKVSize, keep: 0)
}
return KVCacheSimple()
}
}
Expand Down