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
12 changes: 6 additions & 6 deletions Libraries/MLXLLM/Models/AfMoE.swift
Original file line number Diff line number Diff line change
Expand Up @@ -557,13 +557,13 @@ public class AfMoEModel: Module, LLMModel, KVCacheDimensionProvider {
}

public func newCache(parameters: GenerateParameters?) -> [KVCache] {
// Create cache based on layer type (rotating for sliding attention, simple for full attention)
// Create cache based on layer type (sliding-window or unbounded). When
// `compressionAlgorithm == .affine(...)`, every attention layer is
// constructed directly as an AffineQuantizedKVCache (no runtime swap).
layerUsesSliding.map { usesSliding in
if usesSliding {
StandardKVCache(maxSize: slidingWindow)
} else {
StandardKVCache()
}
makeAttentionCache(
parameters: parameters,
maxSize: usesSliding ? slidingWindow : nil)
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions Libraries/MLXLLM/Models/BaichuanM1.swift
Original file line number Diff line number Diff line change
Expand Up @@ -265,8 +265,9 @@ public class BaichuanM1Model: Module, LLMModel, KVCacheDimensionProvider {
return model.layers.enumerated().map { (i, _) in
let isSWA = configuration.slidingWindowLayers.contains(i)
let convCache = SSMStateCache()
let kvCache: KVCache =
isSWA ? StandardKVCache(maxSize: configuration.slidingWindow) : StandardKVCache()
let kvCache = makeAttentionCache(
parameters: parameters,
maxSize: isSWA ? configuration.slidingWindow : nil)
return CacheList(convCache, kvCache)
}
}
Expand Down
8 changes: 3 additions & 5 deletions Libraries/MLXLLM/Models/Exaone4.swift
Original file line number Diff line number Diff line change
Expand Up @@ -217,11 +217,9 @@ public class Exaone4Model: Module, LLMModel, KVCacheDimensionProvider {

public func newCache(parameters: GenerateParameters? = nil) -> [KVCache] {
return model.layers.map { layer in
if layer.attention.isLocal, let slidingWindow = configuration.slidingWindow {
return StandardKVCache(maxSize: slidingWindow, keep: 0)
} else {
return StandardKVCache()
}
let maxSize: Int? =
(layer.attention.isLocal ? configuration.slidingWindow : nil)
return makeAttentionCache(parameters: parameters, maxSize: maxSize)
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion Libraries/MLXLLM/Models/FalconH1.swift
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,9 @@ public class FalconH1Model: Module, LLMModel, KVCacheDimensionProvider {
}

public func newCache(parameters: GenerateParameters?) -> [any KVCache] {
model.layers.map { _ in CacheList(SSMStateCache(), StandardKVCache()) }
model.layers.map { _ in
CacheList(SSMStateCache(), makeAttentionCache(parameters: parameters))
}
}
}

Expand Down
16 changes: 9 additions & 7 deletions Libraries/MLXLLM/Models/GPTOSS.swift
Original file line number Diff line number Diff line change
Expand Up @@ -521,14 +521,16 @@ public class GPTOSSModel: Module, LLMModel, KVCacheDimensionProvider {
var caches: [KVCache] = []
for lt in model.layerTypes {
if lt == "full_attention" {
if let maxKVSize = parameters?.maxKVSize {
// keep: 4 preserves attention-sink tokens for full-attention layers.
caches.append(StandardKVCache(maxSize: maxKVSize, keep: 4))
} else {
caches.append(StandardKVCache())
}
// keep: 4 preserves attention-sink tokens for full-attention layers.
caches.append(makeAttentionCache(
parameters: parameters,
maxSize: parameters?.maxKVSize,
keep: 4))
} else {
caches.append(StandardKVCache(maxSize: configuration.slidingWindow, keep: 0))
caches.append(makeAttentionCache(
parameters: parameters,
maxSize: configuration.slidingWindow,
keep: 0))
}
}
return caches
Expand Down
19 changes: 9 additions & 10 deletions Libraries/MLXLLM/Models/Gemma3Text.swift
Original file line number Diff line number Diff line change
Expand Up @@ -400,17 +400,16 @@ public class Gemma3TextModel: Module, LLMModel {
for i in 0 ..< config.hiddenLayers {
let isGlobalLayer = (i % slidingWindowPattern == slidingWindowPattern - 1)

if isGlobalLayer {
// For global layers, use standard cache but with reasonable step size for long sequences
let cache = StandardKVCache()
cache.step = 1024 // Larger step size for efficiency with long sequences
caches.append(cache)
} else {
// For sliding window layers, use rotating cache
caches.append(
StandardKVCache(maxSize: slidingWindow, keep: 0)
)
let cache = makeAttentionCache(
parameters: parameters,
maxSize: isGlobalLayer ? nil : slidingWindow)
// For global layers (unbounded StandardKVCache), bump the step
// size for long-sequence efficiency. Affine-quantized caches
// don't honor `step` and ignore this.
if isGlobalLayer, let standard = cache as? StandardKVCache {
standard.step = 1024
}
caches.append(cache)
}

return caches
Expand Down
12 changes: 7 additions & 5 deletions Libraries/MLXLLM/Models/Gemma3nText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -704,11 +704,13 @@ public class Gemma3nLanguageModel: Module {

for i in 0 ..< firstKvSharedLayerIdx {
let layerType = layerTypes[i]
if layerType == "full_attention" {
caches.append(StandardKVCache())
} else if layerType == "sliding_attention" {
caches.append(StandardKVCache(maxSize: slidingWindow, keep: 0))
} else {
switch layerType {
case "full_attention":
caches.append(makeAttentionCache(parameters: parameters))
case "sliding_attention":
caches.append(
makeAttentionCache(parameters: parameters, maxSize: slidingWindow))
default:
fatalError("Unknown layer type: \(layerType) for layer \(i)")
}
}
Expand Down
12 changes: 4 additions & 8 deletions Libraries/MLXLLM/Models/Gemma4.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1171,17 +1171,13 @@ public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider {
var caches = [KVCache]()

for layerType in config.layerTypes {
let maxSize: Int?
if layerType == "full_attention" {
if let maxKVSize = parameters?.maxKVSize {
caches.append(StandardKVCache(maxSize: maxKVSize, keep: 0))
} else {
caches.append(StandardKVCache())
}
maxSize = parameters?.maxKVSize
} else {
caches.append(
StandardKVCache(maxSize: config.slidingWindow, keep: 0)
)
maxSize = config.slidingWindow
}
caches.append(makeAttentionCache(parameters: parameters, maxSize: maxSize))
}

// Mark KV-sharing donor caches — these must not be turbo-compressed
Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXLLM/Models/GraniteMoeHybrid.swift
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,7 @@ public class GraniteMoeHybridModel: Module, LLMModel, KVCacheDimensionProvider {
if layerType == "mamba" {
return SSMStateCache()
} else {
return StandardKVCache()
return makeAttentionCache(parameters: parameters)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXLLM/Models/Jamba.swift
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ public class JambaModel: Module, LLMModel, KVCacheDimensionProvider {
public func newCache(parameters: GenerateParameters?) -> [KVCache] {
return model.layers.map { layer in
if layer.isAttn {
return StandardKVCache()
return makeAttentionCache(parameters: parameters)
} else {
return SSMStateCache()
}
Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXLLM/Models/LFM2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ public class LFM2Model: Module, LLMModel, KVCacheDimensionProvider {
public func newCache(parameters: GenerateParameters?) -> [KVCache] {
(0 ..< configuration.hiddenLayers).map { layerIdx in
if configuration.fullAttnIdxs.contains(layerIdx) {
StandardKVCache()
makeAttentionCache(parameters: parameters)
} else {
SSMStateCache()
}
Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXLLM/Models/LFM2MoE.swift
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ public class LFM2MoEModel: Module, LLMModel, KVCacheDimensionProvider {
public func newCache(parameters: GenerateParameters?) -> [KVCache] {
(0 ..< configuration.hiddenLayers).map { layerIdx in
if configuration.fullAttnIdxs.contains(layerIdx) {
StandardKVCache()
makeAttentionCache(parameters: parameters)
} else {
SSMStateCache()
}
Expand Down
8 changes: 3 additions & 5 deletions Libraries/MLXLLM/Models/MiMoV2Flash.swift
Original file line number Diff line number Diff line change
Expand Up @@ -459,11 +459,9 @@ public class MiMoV2FlashModel: Module, LLMModel, KVCacheDimensionProvider {

public func newCache(parameters: GenerateParameters?) -> [KVCache] {
return model.layers.map { layer in
if layer.isSlidingWindow {
return StandardKVCache(maxSize: configuration.slidingWindowSize)
} else {
return StandardKVCache()
}
makeAttentionCache(
parameters: parameters,
maxSize: layer.isSlidingWindow ? configuration.slidingWindowSize : nil)
}
}
}
Expand Down
7 changes: 2 additions & 5 deletions Libraries/MLXLLM/Models/Mistral3Text.swift
Original file line number Diff line number Diff line change
Expand Up @@ -351,11 +351,8 @@ public class Mistral3TextModel: Module, LLMModel, KVCacheDimensionProvider {
/// full attention layers use standard StandardKVCache.
public func newCache(parameters: GenerateParameters?) -> [KVCache] {
return model.layers.map { layer in
if layer.useSliding, let slidingWindow = args.slidingWindow {
return StandardKVCache(maxSize: slidingWindow)
} else {
return StandardKVCache()
}
let maxSize: Int? = layer.useSliding ? args.slidingWindow : nil
return makeAttentionCache(parameters: parameters, maxSize: maxSize)
}
}
}
Expand Down
53 changes: 40 additions & 13 deletions Libraries/MLXLLM/Models/NemotronH.swift
Original file line number Diff line number Diff line change
Expand Up @@ -762,38 +762,65 @@ public class NemotronHModel: Module, LLMModel, KVCacheDimensionProvider, LoRAMod
public func newCache(parameters: GenerateParameters?) -> [KVCache] {
// Detect turbo from the typed compressionAlgorithm.
let turbo: (keyBits: Int, valueBits: Int)?
if case let .turbo(kb, vb) = parameters?.compressionAlgorithm {
if case let .turbo(kb, vb, _, _) = parameters?.compressionAlgorithm {
turbo = (kb, vb)
} else {
turbo = nil
}

let pattern = Array(configuration.hybridOverridePattern)
return pattern.compactMap { char -> KVCache? in
let blockType = NemotronHBlockType(from: char)
switch blockType {

// Walk the hybrid pattern once to find which positions in the
// emitted cache list are attention layers. Mamba layers also
// produce a cache (advance the index); mlp/moe blocks emit no
// cache (don't advance the index). The shared helper then picks
// the boundary-skip subset.
var emittedIndex = 0
var attentionEmittedIndices: [Int] = []
for char in pattern {
switch NemotronHBlockType(from: char) {
case .mamba:
return SSMStateCache()
emittedIndex += 1
case .attention:
if let turbo {
attentionEmittedIndices.append(emittedIndex)
emittedIndex += 1
case .mlp, .moe:
break // no cache emitted; don't advance index
}
}
let skipSet = turboBoundarySkipSet(
attentionLayerIndices: attentionEmittedIndices,
algorithm: parameters?.compressionAlgorithm)

var caches: [KVCache] = []
for char in pattern {
switch NemotronHBlockType(from: char) {
case .mamba:
caches.append(SSMStateCache())
case .attention:
let currentIdx = caches.count
if let turbo, !skipSet.contains(currentIdx) {
// Pass headDim so the cache can pre-warm MLX kernel JIT
// for the rotation matmul at model load time — without it,
// the first decode step pays JIT cost inside TTFT.
let attentionHeadDim = configuration.headDim ?? (configuration.hiddenSize / configuration.numAttentionHeads)
return TurboQuantizedKVCache(
caches.append(TurboQuantizedKVCache(
bits: max(turbo.keyBits, turbo.valueBits),
keyBits: turbo.keyBits, valueBits: turbo.valueBits,
maxSize: parameters?.maxKVSize,
headDim: attentionHeadDim)
}
if let maxKVSize = parameters?.maxKVSize {
return StandardKVCache(maxSize: maxKVSize, keep: 0)
headDim: attentionHeadDim))
} else {
// Either turbo is off, or this attention layer falls in
// the boundary-skip set — hand to the standard factory.
caches.append(makeAttentionCache(
parameters: parameters,
maxSize: parameters?.maxKVSize))
}
return StandardKVCache()
case .mlp, .moe:
return nil // No cache needed for MLP/MoE layers
continue // No cache needed for MLP/MoE layers
}
}
return caches
}

public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] {
Expand Down
8 changes: 3 additions & 5 deletions Libraries/MLXLLM/Models/Olmo3.swift
Original file line number Diff line number Diff line change
Expand Up @@ -225,11 +225,9 @@ public class Olmo3Model: Module, LLMModel, KVCacheDimensionProvider {
public func newCache(parameters: GenerateParameters) -> [KVCache] {
var caches: [KVCache] = []
for layerType in args.layerTypes {
if layerType == "full_attention" {
caches.append(StandardKVCache())
} else {
caches.append(StandardKVCache(maxSize: args.slidingWindow))
}
let maxSize: Int? =
(layerType == "full_attention") ? nil : args.slidingWindow
caches.append(makeAttentionCache(parameters: parameters, maxSize: maxSize))
}
return caches
}
Expand Down
33 changes: 23 additions & 10 deletions Libraries/MLXLLM/Models/Qwen35.swift
Original file line number Diff line number Diff line change
Expand Up @@ -894,21 +894,31 @@ public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider {

public func newCache(parameters: GenerateParameters?) -> [KVCache] {
// Detect turbo from the typed compressionAlgorithm. Other algorithms
// (.affine, .none) follow the standard StandardKVCache path; the
// generation loop's maybeQuantizeKVCache swap handles the affine→
// AffineQuantizedKVCache transition at first decode token.
// (.affine, .none) are handled by makeAttentionCache below — affine
// gets an AffineQuantizedKVCache up-front, .none gets a StandardKVCache.
let turbo: (keyBits: Int, valueBits: Int)?
if case let .turbo(kb, vb) = parameters?.compressionAlgorithm {
if case let .turbo(kb, vb, _, _) = parameters?.compressionAlgorithm {
turbo = (kb, vb)
} else {
turbo = nil
}

return model.layers.map { layer in
// Boundary-skip: leave the first N and last N attention layers
// uncompressed under turbo (most PPL-sensitive). Shared helper
// computes the skip set; Qwen 3.5's index space is `model.layers`-
// based, so attention layers are the non-linear (non-GDN) ones.
let attentionLayerIndices: [Int] = model.layers.enumerated().compactMap {
(i, layer) in layer.isLinear ? nil : i
}
let skipSet = turboBoundarySkipSet(
attentionLayerIndices: attentionLayerIndices,
algorithm: parameters?.compressionAlgorithm)

return model.layers.enumerated().map { (i, layer) in
if layer.isLinear {
return SSMStateCache()
}
if let turbo {
if let turbo, !skipSet.contains(i) {
// TurboQuantizedKVCache: Phase 1 stores raw fp16 (zero prefill overhead),
// Phase 2 compresses and uses compressedAttention (no fp16 copy).
// Pass headDim so the cache can pre-warm MLX kernel JIT at
Expand All @@ -920,10 +930,13 @@ public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider {
maxSize: parameters?.maxKVSize,
headDim: configuration.headDim ?? (configuration.hiddenSize / configuration.attentionHeads))
}
if let maxKVSize = parameters?.maxKVSize {
return StandardKVCache(maxSize: maxKVSize, keep: 0)
}
return StandardKVCache()
// Either turbo is off, or this is a boundary attention layer
// that the user opted to keep uncompressed. Either way, hand
// off to the standard factory (raw `StandardKVCache` for .none,
// `AffineQuantizedKVCache` for .affine).
return makeAttentionCache(
parameters: parameters,
maxSize: parameters?.maxKVSize)
}
}

Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXLLM/Models/Qwen3Next.swift
Original file line number Diff line number Diff line change
Expand Up @@ -716,7 +716,7 @@ public class Qwen3NextModel: Module, LLMModel, KVCacheDimensionProvider {
if layer.isLinear {
return SSMStateCache()
}
return StandardKVCache()
return makeAttentionCache(parameters: parameters)
}
}

Expand Down
1 change: 1 addition & 0 deletions Libraries/MLXLMCommon/Documentation.docc/Documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Common language model code.
## Articles

- <doc:v2-to-v3-migration>
- <doc:v3-to-v4-migration>
- <doc:speculative-decoding>
- <doc:wired-memory>

Expand Down
Loading