diff --git a/Libraries/MLXLLM/Documentation.docc/using-model.md b/Libraries/MLXLLM/Documentation.docc/using-model.md index e4d4f400ee..e1cbc6045c 100644 --- a/Libraries/MLXLLM/Documentation.docc/using-model.md +++ b/Libraries/MLXLLM/Documentation.docc/using-model.md @@ -56,6 +56,27 @@ public class LLMModelFactory: ModelFactory { Callers with specialized requirements can use these individual components to manually load models, if needed. +### Inspecting LoRA Metadata + +Use ``LLMModelFactory/loraMetadata(configurationData:)`` to discover the model's LoRA +layer count and default runtime module paths without loading checkpoint weights: + +```swift +let configurationURL = modelDirectory.appending(component: "config.json") +let configurationData = try Data(contentsOf: configurationURL) + +if let metadata = try await LLMModelFactory.shared.loraMetadata( + configurationData: configurationData +) { + print(metadata.layerCount) + print(metadata.defaultKeys) +} +``` + +The returned `LoRAModelMetadata.defaultKeys` come from the registered model architecture, +not from safetensors names. This accounts for models that rename or reshape checkpoint weights +while loading. + ## Evaluation Flow - Load the Model diff --git a/Libraries/MLXLLM/LLMModelFactory.swift b/Libraries/MLXLLM/LLMModelFactory.swift index 8687638bda..55dce335db 100644 --- a/Libraries/MLXLLM/LLMModelFactory.swift +++ b/Libraries/MLXLLM/LLMModelFactory.swift @@ -675,6 +675,14 @@ public final class LLMModelFactory: GenericModelFactory { /// by the model itself, e.g. DeepSeek-R1 public let conventionsRegistry: ChatConventionsRegistry + /// Returns the model's LoRA metadata from its configuration without loading weights. + /// + /// The registered model architecture is instantiated so custom `LoRAModel.loraDefaultKeys` + /// implementations remain authoritative. No checkpoint files are read. + public func loraMetadata(configurationData: Data) async throws -> LoRAModelMetadata? { + try await typeRegistry.loraMetadata(configurationData: configurationData) + } + public func _load( configuration: ResolvedModelConfiguration, tokenizerLoader: any TokenizerLoader diff --git a/Libraries/MLXLLM/Models/Qwen35.swift b/Libraries/MLXLLM/Models/Qwen35.swift index b2420c9bc7..4128159355 100644 --- a/Libraries/MLXLLM/Models/Qwen35.swift +++ b/Libraries/MLXLLM/Models/Qwen35.swift @@ -424,7 +424,8 @@ final class Qwen35GatedDeltaNet: Module { aLog: aLog, dtBias: dtBias, state: recState, - mask: prefixMask) + mask: prefixMask, + useKernel: !training) let (suffixOut, suffixState) = gatedDeltaUpdate( q: qNormed[0..., split..., 0..., 0...], k: kNormed[0..., split..., 0..., 0...], @@ -434,7 +435,8 @@ final class Qwen35GatedDeltaNet: Module { aLog: aLog, dtBias: dtBias, state: prefixState, - mask: suffixMask) + mask: suffixMask, + useKernel: !training) out = concatenated([prefixOut, suffixOut], axis: 1) newRecState = suffixState @@ -458,7 +460,8 @@ final class Qwen35GatedDeltaNet: Module { aLog: aLog, dtBias: dtBias, state: recState, - mask: mask) + mask: mask, + useKernel: !training) checkpoint = nil } diff --git a/Libraries/MLXLLM/Models/Qwen3Next.swift b/Libraries/MLXLLM/Models/Qwen3Next.swift index 6a7f78678c..003fc5ef4c 100644 --- a/Libraries/MLXLLM/Models/Qwen3Next.swift +++ b/Libraries/MLXLLM/Models/Qwen3Next.swift @@ -346,7 +346,8 @@ public final class Qwen3NextGatedDeltaNet: Module { aLog: aLog, dtBias: dtBias, state: recState, - mask: mask + mask: mask, + useKernel: !training ) let normalized = norm(out, gate: z) diff --git a/Libraries/MLXLMCommon/Adapters/LoRA/LoRAModel.swift b/Libraries/MLXLMCommon/Adapters/LoRA/LoRAModel.swift index 072e2f4cd1..36bb7b8e01 100644 --- a/Libraries/MLXLMCommon/Adapters/LoRA/LoRAModel.swift +++ b/Libraries/MLXLMCommon/Adapters/LoRA/LoRAModel.swift @@ -9,6 +9,36 @@ import Foundation import MLX import MLXNN +/// Metadata describing where a model applies LoRA adapters. +public struct LoRAModelMetadata: Sendable, Equatable { + /// Number of model layers that support LoRA adapters. + public let layerCount: Int + + /// Default module paths, relative to each LoRA layer, that receive adapters. + public let defaultKeys: [String] + + public init(layerCount: Int, defaultKeys: [String]) { + self.layerCount = layerCount + self.defaultKeys = defaultKeys + } +} + +extension ModelTypeRegistry where T == any LanguageModel { + /// Inspects the registered model's LoRA layers without loading checkpoint weights. + /// + /// Model construction and metadata access use an independent random state. + /// Returns `nil` if the model does not conform to ``LoRAModel``. + public func loraMetadata(configurationData: Data) throws -> LoRAModelMetadata? { + try withRandomState(MLXRandom.RandomState(seed: 0)) { + let configuration = try JSONDecoder.json5().decode( + BaseConfiguration.self, from: configurationData) + let model = try createModel( + configuration: configurationData, modelType: configuration.modelType) + return (model as? LoRAModel)?.loraMetadata + } + } +} + public protocol LoRAModel { /// Return the layers to apply LoRA adapters to. @@ -26,6 +56,14 @@ public protocol LoRAModel { extension LoRAModel { + /// Metadata for configuring LoRA without inspecting checkpoint weight names. + public var loraMetadata: LoRAModelMetadata { + LoRAModelMetadata( + layerCount: loraLayers.count, + defaultKeys: loraDefaultKeys.sorted() + ) + } + /// By default we apply LoRA to all Linear layers. /// This is aligned with `mlx-lm` Python logic. public var loraDefaultKeys: [String] { diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index 3bbf198bd1..e7496eb79a 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -2418,9 +2418,11 @@ private func generateLoopTask< let handler = SendableBox(handler) let tokenCollector = consume tokenCollector - // Launch a Task to perform iteration asynchronously. + // Keep task cancellation and task-local values while moving blocking MLX work + // onto a separate queue for each generation. let task = Task { - let performIteration = { + let worker = GenerationWorker() + let performIteration = { @Sendable in var iterator = iterator.consume() var handler = handler.consume() var tokenCollector = tokenCollector @@ -2546,10 +2548,10 @@ private func generateLoopTask< if let ticket = wiredMemoryTicket { return await WiredMemoryTicket.withWiredLimit(ticket) { - performIteration() + await worker.run(performIteration) } } else { - return performIteration() + return await worker.run(performIteration) } } @@ -2840,7 +2842,7 @@ private enum TokenLoopDisposition { } } -private protocol TokenLoopHandler { +private protocol TokenLoopHandler: SendableMetatype { associatedtype Output /// Semantic boundaries contributed by the response protocol handled by diff --git a/Libraries/MLXLMCommon/GatedDelta.swift b/Libraries/MLXLMCommon/GatedDelta.swift index 58335e57a7..9e248a1443 100644 --- a/Libraries/MLXLMCommon/GatedDelta.swift +++ b/Libraries/MLXLMCommon/GatedDelta.swift @@ -230,6 +230,59 @@ private func gatedDeltaStepOps( return (y.asType(q.dtype), state) } +/// Steps per recompute chunk in `gatedDeltaOps`. +/// +/// The ops path is the one that can be trained through (the fused kernel +/// has no gradient), and a recurrence run as plain ops keeps every step's +/// state for the backward pass: at Qwen3.5-27B's shapes (48 heads of +/// 128x128 fp32) that is about 4 MB a step, gigabytes per layer at a +/// thousand tokens. Each chunk is run through a custom function whose +/// backward recomputes the chunk instead, so only the chunk boundaries are +/// kept - what `mx.checkpoint` does for the Python trainer. Inference is +/// unaffected: the forward is the same ops in the same order. +let gatedDeltaRecomputeChunk = 16 + +private enum GatedDeltaRecompute { + /// `inputs` = [q, k, v, g, beta, state] plus the mask when there is one, + /// each sliced to the chunk; returns [y, state]. + static func steps(_ inputs: [MLXArray], masked: Bool) -> [MLXArray] { + let (q, k, v, g, beta) = (inputs[0], inputs[1], inputs[2], inputs[3], inputs[4]) + var state = inputs[5] + let mask = masked ? inputs[6] : nil + var ys = [MLXArray]() + ys.reserveCapacity(q.dim(1)) + for t in 0 ..< q.dim(1) { + let (y, newState) = gatedDeltaStepOps( + q: q[0..., t], + k: k[0..., t], + v: v[0..., t], + g: g[0..., t], + beta: beta[0..., t], + state: state, + mask: mask.map { $0[0..., t] } + ) + ys.append(y) + state = newState + } + return [MLX.stacked(ys, axis: 1), state] + } + + // The closure holds a locked state object; two callers serialise on it. + nonisolated(unsafe) static let unmasked: ([MLXArray]) -> [MLXArray] = CustomFunction { + Forward { steps($0, masked: false) } + VJP { primals, cotangents in + vjp({ steps($0, masked: false) }, primals: primals, cotangents: cotangents).1 + } + } + + nonisolated(unsafe) static let masked: ([MLXArray]) -> [MLXArray] = CustomFunction { + Forward { steps($0, masked: true) } + VJP { primals, cotangents in + vjp({ steps($0, masked: true) }, primals: primals, cotangents: cotangents).1 + } + } +} + func gatedDeltaOps( q: MLXArray, k: MLXArray, @@ -258,30 +311,27 @@ func gatedDeltaOps( var state = state ?? MLXArray.zeros([B, Hv, Dv, Dk], dtype: .float32) var ys = [MLXArray]() - ys.reserveCapacity(T) - - for t in 0 ..< T { - let qT = q[0..., t] - let kT = k[0..., t] - let vT = v[0..., t] - let gT = g[0..., t] - let betaT = beta[0..., t] - let maskT = mask == nil ? nil : mask![0..., t] - - let (y, newState) = gatedDeltaStepOps( - q: qT, - k: kT, - v: vT, - g: gT, - beta: betaT, - state: state, - mask: maskT - ) - ys.append(y) - state = newState + ys.reserveCapacity((T + gatedDeltaRecomputeChunk - 1) / gatedDeltaRecomputeChunk) + + for start in stride(from: 0, to: T, by: gatedDeltaRecomputeChunk) { + let steps = start ..< min(start + gatedDeltaRecomputeChunk, T) + var inputs = [ + q[0..., steps], k[0..., steps], v[0..., steps], g[0..., steps], beta[0..., steps], + state, + ] + let run: ([MLXArray]) -> [MLXArray] + if let mask { + inputs.append(mask[0..., steps]) + run = GatedDeltaRecompute.masked + } else { + run = GatedDeltaRecompute.unmasked + } + let out = run(inputs) + ys.append(out[0]) + state = out[1] } - let y = MLX.stacked(ys, axis: 1) + let y = ys.count == 1 ? ys[0] : MLX.concatenated(ys, axis: 1) return (y, state) } @@ -296,7 +346,8 @@ public func gatedDeltaUpdate( aLog: MLXArray, dtBias: MLXArray, state: MLXArray? = nil, - mask: MLXArray? = nil + mask: MLXArray? = nil, + useKernel: Bool = true ) -> (MLXArray, MLXArray) { let beta = sigmoid(b).asType(.float32) let g = computeGatedDeltaG(aLog, a, dtBias) @@ -320,7 +371,11 @@ public func gatedDeltaUpdate( // Dk = 192 (a multiple of 32), but the value is config-driven, so route any // non-multiple-of-32 Dk to the ops fallback, which handles an arbitrary key // dimension correctly (slower, but never truncating). - if GatedDeltaKernelManager.shared.kernel != nil, Dk % 32 == 0 { + // + // `useKernel: false` is for training: the kernel is a custom Metal + // kernel and has no gradient, so a model in training mode passes + // `!training` here, as the Python model does with `use_kernel`. + if useKernel, GatedDeltaKernelManager.shared.kernel != nil, Dk % 32 == 0 { return gatedDeltaKernel(q: q, k: k, v: v, g: g, beta: beta, state: state, mask: mask) } diff --git a/Libraries/MLXLMCommon/Gemma4Fusions.swift b/Libraries/MLXLMCommon/Gemma4Fusions.swift new file mode 100644 index 0000000000..cff38c19ce --- /dev/null +++ b/Libraries/MLXLMCommon/Gemma4Fusions.swift @@ -0,0 +1,14 @@ +import MLX + +private let compiledGemma4Softcap = compile(shapeless: true) { + (logits: MLXArray, cap: MLXArray) in tanh(logits / cap) * cap +} + +package func gemma4LogitSoftcap(_ logits: MLXArray, _ cap: MLXArray) -> MLXArray { + guard cap.dtype == .float32 else { return tanh(logits / cap) * cap } + // Promote before tracing: mixed float16/float32 division can round differently inside compile. + if logits.dtype == .float16 || logits.dtype == .bfloat16 { + return compiledGemma4Softcap(logits.asType(.float32), cap) + } + return compiledGemma4Softcap(logits, cap) +} diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index 6d78b45c0b..42dd2f01c5 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -568,6 +568,17 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { private var step: Int private var idx: Int = 0 + /// In ring layout all rows are live, with `idx...` preceding `keep ..< idx`. + /// At the end of the buffer the ring is already in temporal order. Otherwise, + /// temporal layout holds only the first `idx` rows, even when `offset` is larger. + /// `nil` defers legacy inference until arrays and metadata have both been restored. + /// Every write or trim resolves it before changing either buffers or counters. + private var wrappedFlag: Bool? = false + + private var wrapped: Bool { + wrappedFlag ?? (idx < (keys?.dim(2) ?? 0) && offset > idx) + } + /// Model-native sliding-window caches deliberately keep their architectural /// window and do not participate in requested-capacity validation. package var capacityOrigin = CapacityOrigin.modelNative @@ -607,10 +618,13 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { } private func temporalOrder(_ array: MLXArray) -> MLXArray { - // Rearrange the cache into temporal order, slicing off the end if unused + // Rearrange the cache into temporal order, slicing off the end if unused. + // `idx` bounds the live rows: after a post-wrap trim the logical `offset` + // exceeds the rows actually held, so the layout question is `wrapped`, + // never an `idx`/`offset` comparison. if idx == array.dim(2) { return array - } else if idx < offset { + } else if wrapped { return concatenated( [ array[.ellipsis, ..= self.keys!.dim(2) && self.keys!.dim(2) < maxCacheSize) - { - let newSize = min(step, maxCacheSize - prev) + // May not have hit the max size yet, so potentially keep growing the cache. + // Fill is tracked by `idx`, not `offset`: after a post-wrap trim the logical + // offset exceeds the rows actually held, and growth must resume from the rows. + let filled = self.keys?.dim(2) ?? 0 + if self.keys == nil || (!wrapped && idx >= filled && filled < maxCacheSize) { + let newSize = min(step, maxCacheSize - filled) let kShape = [B, nKVHeads, newSize, kHeadDim] let vShape = [B, nKVHeads, newSize, vHeadDim] @@ -724,7 +739,6 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { self.keys = newK self.values = newV } - idx = prev } // Trim if needed @@ -738,6 +752,7 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { // Rotate if we've hit the end if idx == maxCacheSize { idx = keep + wrappedFlag = true } // Assign @@ -746,17 +761,19 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { offset += S idx += S - // Return the appropriate cache slice - if offset < maxCacheSize { + // Return the appropriate cache slice: live rows are bounded by `idx` in + // temporal layout, while a wrapped ring is fully live. + if !wrapped, idx < self.keys!.dim(2) { return ( - self.keys![.ellipsis, .. (MLXArray, MLXArray) { + wrappedFlag = wrapped let result = if keys.dim(2) == 1 { updateInPlace(keys: keys, values: values) @@ -769,10 +786,10 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { public override var state: [MLXArray] { get { guard let keys = self.keys, let values = self.values else { return [] } - if offset < keys.dim(2) { + if !wrapped, idx < keys.dim(2) { return [ - keys[.ellipsis, ..= 6 { guard let origin = CapacityOrigin(rawValue: newValue[5]) else { fatalError("Invalid RotatingKVCache capacity origin '\(newValue[5])'") } @@ -828,6 +845,16 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { } else { self.capacityOrigin = .modelNative } + if newValue.count == 7 { + guard let wrappedValue = Bool(newValue[6]) else { + fatalError("Invalid RotatingKVCache wrapped flag '\(newValue[6])'") + } + self.wrappedFlag = wrappedValue + } else { + // Either setter may run first. Defer inference until the restored + // arrays are available, then freeze the layout before any mutation. + self.wrappedFlag = nil + } } } @@ -836,14 +863,46 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { } public override func isTrimmable(after positions: Int) -> Bool { + // This is the *exact rewind* predicate: past the window a trim is merely + // consistent (see `trim`), because rows the rewound writes overwrote are + // gone. Consumers that must undo writes exactly -- the staged-round and + // prompt-cache-reuse machinery -- key off this and fall back to staging, + // snapshots, or a rebuild once it turns false. offset + positions < maxCacheSize } + /// Rewind the newest `n` positions. + /// + /// Before the ring wraps this is exact bookkeeping. After it wraps, the ring is + /// linearized and the newest rows are cut: the cache stays consistent and the + /// logical offset rewinds, but rows the rewound writes overwrote at the old edge + /// of the window cannot come back, so the window is up to `n` rows short until + /// it refills. Callers that need an exact rewind must gate on + /// ``isTrimmable(after:)`` instead of calling this unconditionally. + /// Once older rows have been evicted, trimming stops at the pinned `keep` prefix. @discardableResult public override func trim(_ n: Int) -> Int { - let trimmed = min(offset, n) + guard n > 0, let keys, let values else { return 0 } + wrappedFlag = wrapped + let live = wrapped ? keys.dim(2) : idx + // A gap between history and live rows means eviction has occurred. Preserve + // the pinned prefix regardless of layout, including after repeated trims. + // Without a gap, an exact rewind can still remove any of the original rows. + let minimum = offset > live ? Swift.min(keep, live) : 0 + let trimmed = Swift.min(n, live - minimum) + guard trimmed > 0 else { return 0 } + let bound = live - trimmed + + if wrapped || keys.dim(2) > maxCacheSize { + // Linearize a ring before cutting its newest rows. Also shrink oversized + // prefill buffers: the next single-token write compacts those buffers to + // maxCacheSize and must not treat a discarded suffix as live history. + self.keys = temporalOrder(keys)[.ellipsis, .. MLXFast.ScaledDotProductAttentionMaskMode { if n > 1 { - // Multi-token case + // Multi-token case. The mask must span the rows the write will present: + // in temporal layout that is the live rows (`idx`), which fall below the + // logical offset after a post-wrap trim. let actualWindowSize = windowSize ?? maxCacheSize - let cappedOffset = min(maxCacheSize - 1, offset) + let liveRows = wrapped ? maxCacheSize : idx + let cappedOffset = min(maxCacheSize - 1, liveRows) // Decide if we need an array mask if cappedOffset + n > actualWindowSize || returnArray { @@ -875,7 +937,7 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { currentIdx = 0 } - let maskSize = offset < maxCacheSize ? offset + 1 : maxCacheSize + let maskSize = (!wrapped && idx < maxCacheSize) ? idx + 1 : maxCacheSize let mask = MLXArray(0 ..< Int32(maskSize)) .>= Int32(maskSize - windowSize) // Roll the mask to account for rotation @@ -888,7 +950,7 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { } public var debugDescription: String { - "\(String(describing: Self.self)) offset: \(offset), maxSize: \(maxCacheSize.description), keep: \(keep), idx: \(idx)" + "\(String(describing: Self.self)) offset: \(offset), maxSize: \(maxCacheSize.description), keep: \(keep), idx: \(idx), wrapped: \(wrapped)" } public override func copy() -> any KVCache { @@ -2071,9 +2133,9 @@ private func restoreCacheFromMetaState( case "RotatingKVCache": try validatePromptCache( className: className, state: state, stateCounts: [0, 2], - metadata: metaState, metadataCounts: [5, 6]) + metadata: metaState, metadataCounts: [5, 6, 7]) let values = try promptCacheIntegers(metaState.prefix(5), className: className) - if metaState.count == 6, + if metaState.count >= 6, RotatingKVCache.CapacityOrigin(rawValue: metaState[5]) == nil { throw KVCacheError( @@ -2081,6 +2143,12 @@ private func restoreCacheFromMetaState( "Corrupt prompt cache: invalid RotatingKVCache capacity origin '\(metaState[5])'." ) } + if metaState.count == 7, Bool(metaState[6]) == nil { + throw KVCacheError( + message: + "Corrupt prompt cache: invalid RotatingKVCache wrapped flag '\(metaState[6])'." + ) + } let cache = RotatingKVCache(maxSize: values[1]) if !state.isEmpty { diff --git a/Libraries/MLXLMCommon/Tokenizer.swift b/Libraries/MLXLMCommon/Tokenizer.swift index c08383e647..0b376a09d5 100644 --- a/Libraries/MLXLMCommon/Tokenizer.swift +++ b/Libraries/MLXLMCommon/Tokenizer.swift @@ -113,8 +113,21 @@ public struct NaiveStreamingDetokenizer: StreamingDetokenizer { // boundary, so that holds; a decode that rewrote an already-emitted // interior character would re-emit the tail (no worse than the old // behavior, and not observed in practice). - let common = newSegment.commonPrefix(with: segment) - let new = newSegment.dropFirst(common.count) + // + // The prefix is measured in Unicode scalars, not `Character`s. A + // `Character` is a grapheme cluster, and a token routinely appends a + // combining scalar to the cluster the previous token ended: a + // variation selector (`🏳` then U+FE0F), a zero-width joiner, a + // combining accent (`e` then U+0301). Compared as `Character`s the + // old text's last cluster no longer equals the merged cluster, so a + // `Character`-level prefix (`commonPrefix(with:)`) stops one cluster + // early and the whole merged cluster is emitted a second time β€” the + // consumer receives `🏳🏳️`, `''️`, `eΓ©`. Scalars compare exactly (no + // canonical equivalence), and the emitted tail is precisely the + // scalars the new token added. + let common = zip(newSegment.unicodeScalars, segment.unicodeScalars) + .prefix { $0 == $1 }.count + let new = String(newSegment.unicodeScalars.dropFirst(common)) // if the new segment ends with REPLACEMENT CHARACTER this means // that the token didn't produce a complete unicode character @@ -128,6 +141,6 @@ public struct NaiveStreamingDetokenizer: StreamingDetokenizer { self.segment = newSegment } - return String(new) + return new } } diff --git a/Libraries/MLXLMCommon/Utilities/GenerationWorker.swift b/Libraries/MLXLMCommon/Utilities/GenerationWorker.swift new file mode 100644 index 0000000000..eca553045a --- /dev/null +++ b/Libraries/MLXLMCommon/Utilities/GenerationWorker.swift @@ -0,0 +1,18 @@ +// Copyright Β© 2026 Apple Inc. + +import Dispatch + +/// Runs one generation's blocking work outside Swift's cooperative pool. +actor GenerationWorker { + private nonisolated let queue = DispatchSerialQueue( + label: "ml-explore.mlx-swift-lm.generation") + + nonisolated var unownedExecutor: UnownedSerialExecutor { + queue.asUnownedSerialExecutor() + } + + // Keep the body synchronous so all evaluation and cleanup stay on this executor. + func run(_ body: @Sendable () -> R) -> R { + body() + } +} diff --git a/Libraries/MLXVLM/Models/Gemma4.swift b/Libraries/MLXVLM/Models/Gemma4.swift index 7d6b58fd6b..9f5b241494 100644 --- a/Libraries/MLXVLM/Models/Gemma4.swift +++ b/Libraries/MLXVLM/Models/Gemma4.swift @@ -1452,7 +1452,7 @@ final class Gemma4TextLanguageModel: Module, KVCacheDimensionProvider { let softcappedLogits: MLXArray if let finalLogitSoftcapping, finalLogitSoftcapping > 0 { let scale = MLXArray(finalLogitSoftcapping) - softcappedLogits = tanh(logits / scale) * scale + softcappedLogits = gemma4LogitSoftcap(logits, scale) } else { softcappedLogits = logits } diff --git a/Libraries/MLXVLM/Models/Qwen35.swift b/Libraries/MLXVLM/Models/Qwen35.swift index 010e820766..ab04920ab5 100644 --- a/Libraries/MLXVLM/Models/Qwen35.swift +++ b/Libraries/MLXVLM/Models/Qwen35.swift @@ -662,7 +662,8 @@ public enum Qwen35Language { aLog: aLog, dtBias: dtBias, state: state, - mask: prefixMask) + mask: prefixMask, + useKernel: !training) let (suffixOut, suffixState) = gatedDeltaUpdate( q: qNormed[0..., split..., 0..., 0...], k: kNormed[0..., split..., 0..., 0...], @@ -672,7 +673,8 @@ public enum Qwen35Language { aLog: aLog, dtBias: dtBias, state: prefixState, - mask: suffixMask) + mask: suffixMask, + useKernel: !training) out = concatenated([prefixOut, suffixOut], axis: 1) state = suffixState @@ -701,7 +703,8 @@ public enum Qwen35Language { aLog: aLog, dtBias: dtBias, state: state, - mask: mask) + mask: mask, + useKernel: !training) } if let cache { diff --git a/Libraries/MLXVLM/VLMModelFactory.swift b/Libraries/MLXVLM/VLMModelFactory.swift index 79ea625e28..fcd09a212e 100644 --- a/Libraries/MLXVLM/VLMModelFactory.swift +++ b/Libraries/MLXVLM/VLMModelFactory.swift @@ -384,6 +384,13 @@ public final class VLMModelFactory: GenericModelFactory { /// resolvers for processor metadata that is absent or incorrect in a checkpoint public let processorLoadingRegistry: VLMProcessorLoadingRegistry + /// Returns the model's LoRA metadata without loading checkpoint weights or a processor. + /// + /// Uses the registered model's `LoRAModel` conformance to select adapter targets. + public func loraMetadata(configurationData: Data) async throws -> LoRAModelMetadata? { + try await typeRegistry.loraMetadata(configurationData: configurationData) + } + public func _load( configuration: ResolvedModelConfiguration, tokenizerLoader: any TokenizerLoader diff --git a/Package.swift b/Package.swift index 562a99f599..519dd0c6ca 100644 --- a/Package.swift +++ b/Package.swift @@ -61,7 +61,7 @@ let package = Package( .default(enabledTraits: ["FoundationModelsIntegration"]), ], dependencies: [ - // Keep the SightRoll sibling fork; it includes upstream MLX 0.31.6. + // Keep the SightRoll sibling fork and its quantization compatibility fixes. .package(path: "../mlx-swift"), // 602.0.0 floor: swift.org publishes signed prebuilt swift-syntax artifacts only for // >= 602 tags on current toolchains; a 600.x/601.x resolution falls back to the full diff --git a/QWEN38_INTEGRATION.md b/QWEN38_INTEGRATION.md index 07ff4648a3..8dc0c4253f 100644 --- a/QWEN38_INTEGRATION.md +++ b/QWEN38_INTEGRATION.md @@ -1,7 +1,7 @@ # Qwen3.8 runtime integration -This branch integrates upstream runtime/test changes through -`e3d4a20e9e20e7b8ab39aded7bbfad4ae22c9438`, followed by: +This fork integrates merged upstream runtime/test changes through +`604fae710a4e3324346fc59e3845952350acd4b7`, preserving: - [PR545](https://github.com/ml-explore/mlx-swift-lm/pull/545), head `1a562aa00bb66d611a086174e14951f41c43e100`: Qwen3.8 language/vision model @@ -10,8 +10,18 @@ This branch integrates upstream runtime/test changes through `65c7f45eb5c9c58cafe1300f0ed356d742155221`: DFlash2 text speculative decoding. PR607 does not include PR545. The runtime prerequisite update also includes -Qwen checkpoint norm sanitization and processor-loading fixes. Imported paths are -`Libraries`, `Tests` and `Package.swift`; upstream CI/workflows are not imported. +Qwen checkpoint norm sanitization and processor-loading fixes. The September 14 +sync includes upstream reference documentation alongside the runtime and unit +tests. Fork CI/workflows, the separate integration project, and contributor policy +are retained. + +The sync includes generation worker isolation (#611), Unicode streaming fixes +(#613), Gemma VLM softcapping fusion (#615), differentiable gated-delta recurrence +(#616), configuration-based LoRA metadata (#597), and wrapped rotating-cache +trimming (#584). Pair it with the sibling MLX fork synced through +`ea8a179690170ca891a97bc0473198ab1ecda5f4`, including wired-memory cancellation +handling (#471) and the core update from upstream #450. No additional open PRs +are included, and speculative decoding remains opt-in. The fork retains the local `../mlx-swift` dependency, Swift tools 6.2, Gemma4 audio support and assistant registrations, generation-config propagation, and @@ -22,12 +32,16 @@ the sibling fork's NVFP4 representation cannot safely discard that scale. ## Consumer compatibility +The synced sibling MLX package requires Swift 6.3 or newer (including its +experimental C generation support). Validation uses Xcode 26.6 / Swift 6.3.3. + + Use the accompanying mlx-swift-structured compatibility change. Its constrained iterator handles throwing cache creation, the current prefill policy and public iterator state; examples handle rejected tool calls. These API adaptations do not add DFlash2 support to the constrained iterator. -The current DFlash2 target is `MLXLLM.Qwen35`. It rejects visual input and +The current DFlash2 targets are `MLXLLM.Qwen35TextModel` and `MLXLLM.Qwen35Model`. It rejects visual input and unsupported caches; the production `MLXVLM` target is not supported. SightRoll's grammar processor also lacks an independent state-copy contract for speculative branches. DFlash2 remains disabled in the four-model SightRoll benchmark. @@ -91,7 +105,27 @@ stalled on shared MLX evaluation/compiled-function locks, so the full gate ran serially. The SightRoll performance benchmark separately records and uses the production TF32 default. -Structured's full suite passed 30 tests. CatalogKit's deterministic core passed +In the earlier 2026-09-06 validation, Structured's full suite passed 30 tests. +CatalogKit's deterministic core passed 927 tests against this runtime before the final benchmark-runner review. Actual four-model output, failure, timing and memory evidence is retained in private SightRoll benchmark reports, outside these repositories. + +## Upstream sync validation β€” 2026-09-14 + +The merged upstream runtime at `604fae710a4e3324346fc59e3845952350acd4b7`, +paired with the sibling MLX integration at +`76bb2f25e1708867b50feeec84bdea6f67a5e9fe`, passed a fresh host build and the +serial full-precision suite: 638 XCTest executions (two skipped, zero failures) +and 853 Swift Testing tests across 77 suites. The existing disabled +`ConstraintCachingTests` suite remains unavailable for the reason documented +above. No optional real-checkpoint benchmark is claimed by these totals. + +Six cache-validation fixtures now materialize loaded tensors before rewriting +the file they came from. This avoids reading lazy arrays from a file while it +is being replaced; typed cache validation assertions remain unchanged. + +The paired MLX core passed 584 MLX tests and one C bridge test. Structured +passed all 35 tests across nine suites, and CatalogKit built against these +updated dependencies. Model-quality and performance measurements run separately +with production TF32 settings and frozen benchmark inputs. diff --git a/Tests/MLXLMTests/GatedDeltaTests.swift b/Tests/MLXLMTests/GatedDeltaTests.swift index eba5076244..1419138567 100644 --- a/Tests/MLXLMTests/GatedDeltaTests.swift +++ b/Tests/MLXLMTests/GatedDeltaTests.swift @@ -159,4 +159,103 @@ public class GatedDeltaTests: XCTestCase { ) } + /// A model in training mode must be able to differentiate the recurrence. + /// + /// The fused kernel is a `CustomKernel`, which has no VJP, so the first + /// backward pass of a LoRA fine-tune of Qwen3.5 or Qwen3-Next died with + /// `[Primitive::vjp] Not implemented for CustomKernel` - three of every + /// four layers in those models are gated-delta layers, so this was every + /// fine-tune of them rather than an edge case. `useKernel: false` takes + /// the ops path, which is differentiable. The Python model spells the + /// same thing `use_kernel=not self.training`. + /// + /// T spans more than one recompute chunk on purpose: the ops path runs + /// the recurrence in chunks through a custom function whose backward + /// recomputes the chunk, and a gradient that stopped at a chunk boundary + /// would still pass at T <= 16. + func testGatedDeltaOpsPathIsDifferentiable() throws { + let inputs = makeInputs(T: 40) + let loss: ([MLXArray]) -> [MLXArray] = { arrays in + let (y, _) = gatedDeltaUpdate( + q: arrays[0], k: arrays[1], v: arrays[2], + a: inputs.a, b: inputs.b, + aLog: inputs.aLog, dtBias: inputs.dtBias, + useKernel: false + ) + return [y.asType(.float32).square().sum()] + } + let (value, gradients) = valueAndGrad(loss, argumentNumbers: [0, 1, 2])( + [inputs.q, inputs.k, inputs.v]) + eval(value) + eval(gradients) + + XCTAssertEqual(gradients.count, 3) + for (name, gradient) in zip(["q", "k", "v"], gradients) { + let magnitude = abs(gradient.asType(.float32)).max() + eval(magnitude) + let largest = magnitude.item(Float.self) + XCTAssertTrue( + largest.isFinite, + "d(loss)/d\(name) is \(largest); the recurrence produced a " + + "non-finite gradient." + ) + XCTAssertGreaterThan( + largest, 0, + "d(loss)/d\(name) is all zero, so no gradient reached the " + + "input through the recurrence." + ) + } + } + + /// Turning the kernel off must not change the answer. + /// + /// Training takes the ops path and inference takes the kernel, so a model + /// would be fine-tuned against arithmetic it never runs at generation + /// time if these two disagreed. T spans three recompute chunks, which is + /// where a mistake in carrying state across a chunk boundary would show. + /// + /// **Compared relative to the state, not absolutely.** These inputs are + /// random, so the recurrent state compounds: it reaches ~1.2e6 by T = 40, + /// where the two paths differ by 1.25 - about one part in a million, and + /// the same one part in a million as at T = 16, which is a single chunk + /// and has no boundary to get wrong. An absolute bound would therefore + /// be a test of how long the sequence is rather than of the arithmetic. + func testGatedDeltaOpsPathMatchesTheKernel() throws { + let inputs = makeInputs(T: 40) + let (yKernel, stateKernel) = gatedDeltaUpdate( + q: inputs.q, k: inputs.k, v: inputs.v, + a: inputs.a, b: inputs.b, + aLog: inputs.aLog, dtBias: inputs.dtBias, + useKernel: true + ) + let (yOps, stateOps) = gatedDeltaUpdate( + q: inputs.q, k: inputs.k, v: inputs.v, + a: inputs.a, b: inputs.b, + aLog: inputs.aLog, dtBias: inputs.dtBias, + useKernel: false + ) + + /// Largest disagreement as a fraction of the largest value involved. + func relativeDrift(_ lhs: MLXArray, _ rhs: MLXArray) -> Float { + let left = lhs.asType(.float32) + let right = rhs.asType(.float32) + let drift = abs(left - right).max() + let scale = maximum(abs(left).max(), abs(right).max()) + eval(drift) + eval(scale) + let magnitude = scale.item(Float.self) + return magnitude > 0 ? drift.item(Float.self) / magnitude : drift.item(Float.self) + } + + XCTAssertLessThan( + relativeDrift(yKernel, yOps), 1e-4, + "The differentiable ops path and the fused kernel disagree on the " + + "output, so training and inference would run different maths." + ) + XCTAssertLessThan( + relativeDrift(stateKernel, stateOps), 1e-4, + "The two paths disagree on the carried recurrent state." + ) + } + } diff --git a/Tests/MLXLMTests/Gemma4FusionTests.swift b/Tests/MLXLMTests/Gemma4FusionTests.swift new file mode 100644 index 0000000000..71775ac274 --- /dev/null +++ b/Tests/MLXLMTests/Gemma4FusionTests.swift @@ -0,0 +1,74 @@ +import Foundation +import MLX +import MLXLMCommon +import XCTest + +final class Gemma4FusionTests: XCTestCase { + private func assertIdentical( + _ actual: MLXArray, _ expected: MLXArray, + file: StaticString = #filePath, line: UInt = #line + ) { + XCTAssertEqual(actual.shape, expected.shape, file: file, line: line) + XCTAssertEqual(actual.dtype, expected.dtype, file: file, line: line) + XCTAssertEqual( + actual.asType(.float32).asArray(Float.self).map(\.bitPattern), + expected.asType(.float32).asArray(Float.self).map(\.bitPattern), + file: file, line: line) + } + + func testSoftcapPreservesScalarPromotionAndRuntimeCaps() { + for dtype in [DType.float16, .bfloat16, .float32] { + let x = MLX.linspace(Float(-100), Float(100), count: 4096).reshaped(1, 4096) + .asType(dtype) + for value: Float in [30, 7.25, 1] { + for cap in [MLXArray(value), value.asMLXArray(dtype: dtype)] { + assertIdentical(gemma4LogitSoftcap(x, cap), tanh(x / cap) * cap) + let strided = x[.ellipsis, .stride(by: 2)] + assertIdentical( + gemma4LogitSoftcap(strided, cap), tanh(strided / cap) * cap) + } + } + } + } + + func testGradientsMatchOriginal() { + let cap = MLXArray(Float(30)) + for dtype in [DType.float16, .bfloat16, .float32] { + let logits = MLX.linspace(Float(-3), Float(3), count: 64) + .reshaped(1, 1, 64).asType(dtype) + assertIdentical( + grad({ sum(gemma4LogitSoftcap($0, cap)) })(logits), + grad({ sum(tanh($0 / cap) * cap) })(logits)) + } + } + + func testFusionLatency() throws { + guard ProcessInfo.processInfo.environment["MLX_BENCHMARK_GEMMA4_FUSIONS"] == "1" else { + throw XCTSkip("Set MLX_BENCHMARK_GEMMA4_FUSIONS=1 to benchmark") + } + let logits = MLXRandom.normal([1, 1, 262144]).asType(.bfloat16) + let cap = MLXArray(Float(30)) + eval(logits, cap) + let cases: [(String, () -> MLXArray, () -> MLXArray)] = [ + ("VLM softcap", { tanh(logits / cap) * cap }, { gemma4LogitSoftcap(logits, cap) }) + ] + for (name, original, fused) in cases { + assertIdentical(fused(), original()) + for _ in 0 ..< 10 { eval(original(), fused()) } + var samples = [[Double]](repeating: [], count: 2) + for round in 0 ..< 10 { + for arm in (round.isMultiple(of: 2) ? [0, 1] : [1, 0]) { + let body = arm == 0 ? original : fused + let start = ProcessInfo.processInfo.systemUptime + for _ in 0 ..< 100 { eval(body()) } + samples[arm].append((ProcessInfo.processInfo.systemUptime - start) * 10000) + } + } + let medians = samples.map { values in + let sorted = values.sorted() + return (sorted[4] + sorted[5]) / 2 + } + print("[Gemma4 fusion] \(name): original \(medians[0]) Β΅s, fused \(medians[1]) Β΅s") + } + } +} diff --git a/Tests/MLXLMTests/GenerationExecutionTests.swift b/Tests/MLXLMTests/GenerationExecutionTests.swift new file mode 100644 index 0000000000..7e904fc046 --- /dev/null +++ b/Tests/MLXLMTests/GenerationExecutionTests.swift @@ -0,0 +1,303 @@ +// Copyright Β© 2026 Apple Inc. + +import Dispatch +import MLX +import XCTest + +@testable import MLXLMCommon + +final class GenerationExecutionTests: XCTestCase { + private enum Context { + @TaskLocal static var value = 0 + } + + private struct CancellingPolicy: WiredMemoryPolicy { + let identifier = UUID() + var id: AnyHashable { identifier } + + func limit(baseline: Int, activeSizes: [Int]) -> Int { baseline } + + func canAdmit(baseline: Int, activeSizes: [Int], newSize: Int) -> Bool { + withUnsafeCurrentTask { $0?.cancel() } + return true + } + } + + private struct Iterator: GenerationFinalizingTokenIterator { + var maxTokens: Int? = 1 + var tokenCount = 0 + var promptPrefillTime: TimeInterval { 0 } + var onNext: @Sendable () -> Void = {} + var onFinalize: @Sendable () -> Void = {} + + mutating func next() -> Int? { + guard tokenCount < (maxTokens ?? Int.max) else { return nil } + onNext() + tokenCount += 1 + return 42 + } + + mutating func finalizeGeneration() { + onFinalize() + } + } + + // Run with LIBDISPATCH_COOPERATIVE_POOL_STRICT=1 to expose pool starvation + // deterministically. The timeout also lets a regressed implementation finish. + func testBlockingIteratorLeavesCooperativeWorkerAvailable() async { + for useTicket in [false, true] { + let iterator = Iterator( + onNext: Self.assertCooperativeProgress, + onFinalize: Self.assertCooperativeProgress) + let ticket = useTicket ? MLX.WiredSumPolicy().ticket(size: 0) : nil + let (stream, task) = generateTask( + promptTokenCount: 1, modelConfiguration: .init(id: "test"), + tokenizer: TestTokenizer(), iterator: iterator, wiredMemoryTicket: ticket) + for await _ in stream {} + await task.value + } + } + + private static func assertCooperativeProgress() { + let resumed = DispatchSemaphore(value: 0) + Task { resumed.signal() } + XCTAssertEqual(resumed.wait(timeout: .now() + 5), .success) + } + + func testGenerationPreservesDeviceOverrideAndCooperativeProgress() async { + await Device.withDefaultDevice(.cpu) { + let (stream, task) = generateTaskRecordingTokens( + promptTokenCount: 1, modelConfiguration: .init(id: "test"), + tokenizer: TestTokenizer(), + iterator: Iterator( + maxTokens: 3, + onNext: { + XCTAssertEqual(Device.defaultDevice().deviceType, .cpu) + Self.assertCooperativeProgress() + }, + onFinalize: { + XCTAssertEqual(Device.defaultDevice().deviceType, .cpu) + Self.assertCooperativeProgress() + })) + var completion: GenerateCompletionInfo? + for await event in stream { + if case .info(let info) = event { completion = info } + } + let tokens = await task.value + XCTAssertEqual(tokens, [42, 42, 42]) + XCTAssertEqual(completion?.generationTokenCount, 3) + XCTAssertEqual(completion?.stopReason, .length) + } + } + + func testCancellingOneGenerationDoesNotCancelAnother() async { + let firstEntered = expectation(description: "first generation entered next") + let secondEntered = expectation(description: "second generation entered next") + let resumeFirst = DispatchSemaphore(value: 0) + let resumeSecond = DispatchSemaphore(value: 0) + let (firstStream, first) = generateTaskRecordingTokens( + promptTokenCount: 1, modelConfiguration: .init(id: "test"), + tokenizer: TestTokenizer(), + iterator: Iterator( + maxTokens: 10, + onNext: { + firstEntered.fulfill() + XCTAssertEqual(resumeFirst.wait(timeout: .now() + 5), .success) + XCTAssertTrue(Task.isCancelled) + }, + onFinalize: { XCTAssertTrue(Task.isCancelled) })) + let (secondStream, second) = generateTaskRecordingTokens( + promptTokenCount: 1, modelConfiguration: .init(id: "test"), + tokenizer: TestTokenizer(), + iterator: Iterator( + onNext: { + secondEntered.fulfill() + XCTAssertEqual(resumeSecond.wait(timeout: .now() + 5), .success) + XCTAssertFalse(Task.isCancelled) + }, + onFinalize: { XCTAssertFalse(Task.isCancelled) })) + + await fulfillment(of: [firstEntered, secondEntered], timeout: 5) + first.cancel() + resumeFirst.signal() + let firstTokens = await first.value + XCTAssertEqual(firstTokens, [42]) + XCTAssertFalse(second.isCancelled) + resumeSecond.signal() + let secondTokens = await second.value + XCTAssertEqual(secondTokens, [42]) + + var firstCompletion: GenerateCompletionInfo? + for await event in firstStream { + if case .info(let info) = event { firstCompletion = info } + } + var secondCompletion: GenerateCompletionInfo? + for await event in secondStream { + if case .info(let info) = event { secondCompletion = info } + } + XCTAssertEqual(firstCompletion?.stopReason, .cancelled) + XCTAssertEqual(secondCompletion?.stopReason, .length) + } + + func testIndependentGenerationsCanMakeProgressConcurrently() async { + let firstStarted = DispatchSemaphore(value: 0) + let secondStarted = DispatchSemaphore(value: 0) + let (firstStream, first) = generateTask( + promptTokenCount: 1, modelConfiguration: .init(id: "test"), + tokenizer: TestTokenizer(), + iterator: Iterator(onNext: { + firstStarted.signal() + XCTAssertEqual(secondStarted.wait(timeout: .now() + 5), .success) + })) + let (secondStream, second) = generateTask( + promptTokenCount: 1, modelConfiguration: .init(id: "test"), + tokenizer: TestTokenizer(), + iterator: Iterator(onNext: { + XCTAssertEqual(firstStarted.wait(timeout: .now() + 5), .success) + secondStarted.signal() + })) + await first.value + await second.value + withExtendedLifetime((firstStream, secondStream)) {} + } + + func testCancellationDuringNextStillFinalizesBeforeTaskCompletes() async { + let entered = expectation(description: "entered next") + let resume = DispatchSemaphore(value: 0) + let finalized = expectation(description: "finalized after cancellation") + let (stream, task) = generateTaskRecordingTokens( + promptTokenCount: 1, modelConfiguration: .init(id: "test"), + tokenizer: TestTokenizer(), + iterator: Iterator( + maxTokens: 10, + onNext: { + entered.fulfill() + XCTAssertEqual(resume.wait(timeout: .now() + 5), .success) + XCTAssertTrue(Task.isCancelled) + }, + onFinalize: { + XCTAssertTrue(Task.isCancelled) + finalized.fulfill() + })) + await fulfillment(of: [entered], timeout: 5) + task.cancel() + resume.signal() + var completion: GenerateCompletionInfo? + for await event in stream { + if case .info(let info) = event { completion = info } + } + let tokens = await task.value + XCTAssertEqual(tokens, [42]) + XCTAssertEqual(completion?.stopReason, .cancelled) + XCTAssertEqual(completion?.generationTokenCount, 1) + await fulfillment(of: [finalized], timeout: 0) + } + + func testCancellationDuringTicketAdmissionSkipsNextAndFinalizes() async throws { + try XCTSkipIf(Device.defaultDevice().deviceType != .gpu, "Admission requires a GPU backend") + let finalized = expectation(description: "cancelled iterator finalized") + let ticket = CancellingPolicy().ticket(size: 0) + let (stream, task) = generateTaskRecordingTokens( + promptTokenCount: 1, modelConfiguration: .init(id: "test"), + tokenizer: TestTokenizer(), + iterator: Iterator( + onNext: { XCTFail("Cancelled generation must not call next") }, + onFinalize: { + XCTAssertTrue(Task.isCancelled) + finalized.fulfill() + }), + wiredMemoryTicket: ticket) + var completion: GenerateCompletionInfo? + for await event in stream { + if case .info(let info) = event { completion = info } + } + let tokens = await task.value + XCTAssertEqual(tokens, []) + XCTAssertEqual(completion?.stopReason, .cancelled) + await fulfillment(of: [finalized], timeout: 0) + } + + func testConsumerCancellationReachesBlockedGeneration() async { + let entered = expectation(description: "entered next") + let resume = DispatchSemaphore(value: 0) + let finalized = expectation(description: "consumer cancellation finalized") + let (stream, task) = generateTask( + promptTokenCount: 1, modelConfiguration: .init(id: "test"), + tokenizer: TestTokenizer(), + iterator: Iterator( + onNext: { + entered.fulfill() + XCTAssertEqual(resume.wait(timeout: .now() + 5), .success) + XCTAssertTrue(Task.isCancelled) + }, + onFinalize: { finalized.fulfill() })) + let consumer = Task { + for await _ in stream {} + } + await fulfillment(of: [entered], timeout: 5) + consumer.cancel() + await consumer.value + resume.signal() + await task.value + XCTAssertTrue(task.isCancelled) + await fulfillment(of: [finalized], timeout: 0) + } + + @MainActor + func testMainActorCallerDoesNotRunIteratorOnMainThread() async { + let (stream, task) = generateTask( + promptTokenCount: 1, modelConfiguration: .init(id: "test"), + tokenizer: TestTokenizer(), + iterator: Iterator(onNext: { + XCTAssertFalse(Thread.isMainThread) + Self.assertCooperativeProgress() + })) + for await _ in stream {} + await task.value + } + + func testEmptyGenerationStillFinalizes() async { + let finalized = expectation(description: "empty iterator finalized") + let (stream, task) = generateTaskRecordingTokens( + promptTokenCount: 1, modelConfiguration: .init(id: "test"), + tokenizer: TestTokenizer(), + iterator: Iterator( + maxTokens: 0, onNext: { XCTFail("Empty iterator must not produce a token") }, + onFinalize: { finalized.fulfill() })) + var completion: GenerateCompletionInfo? + for await event in stream { + if case .info(let info) = event { completion = info } + } + let tokens = await task.value + XCTAssertEqual(tokens, []) + XCTAssertEqual(completion?.stopReason, .length) + XCTAssertEqual(completion?.generationTokenCount, 0) + await fulfillment(of: [finalized], timeout: 0) + } + + func testTaskContextAndRecordedTokensSurviveExecutionHop() async { + let finalized = expectation(description: "iterator finalized") + let (stream, task) = Context.$value.withValue(123) { + generateTaskRecordingTokens( + promptTokenCount: 1, modelConfiguration: .init(id: "test"), + tokenizer: TestTokenizer(), + iterator: Iterator( + onNext: { + XCTAssertEqual(Context.value, 123) + XCTAssertTrue(withUnsafeCurrentTask { $0 != nil }) + }, + onFinalize: { + XCTAssertEqual(Context.value, 123) + finalized.fulfill() + })) + } + var completion: GenerateCompletionInfo? + for await event in stream { + if case .info(let info) = event { completion = info } + } + let tokens = await task.value + XCTAssertEqual(tokens, [42]) + XCTAssertEqual(completion?.stopReason, .length) + await fulfillment(of: [finalized], timeout: 5) + } +} diff --git a/Tests/MLXLMTests/KVCacheTests.swift b/Tests/MLXLMTests/KVCacheTests.swift index c3a14db572..fd105e98b8 100644 --- a/Tests/MLXLMTests/KVCacheTests.swift +++ b/Tests/MLXLMTests/KVCacheTests.swift @@ -160,6 +160,9 @@ private final class ProtocolDefaultTrimmabilityCache: KVCache { } @Test func testRotatingKVCacheIsNotTrimmableAtOrPastWindow() { + // `isTrimmable` is the *exact rewind* predicate. Past the window a trim is + // merely consistent (the window loses its oldest rows), so this must stay + // false to keep the staged-round and prompt-cache-reuse machinery exact. let cache = RotatingKVCache(maxSize: 8) cache.offset = 8 @@ -374,6 +377,8 @@ func testCacheSerialization(creator: (() -> any KVCache)) async throws { try savePromptCache(url: url, cache: [cache], state: state) let (arrays, savedMetadata) = try loadArraysAndMetadata(url: url) + // The fixture overwrites its source file; finish lazy reads before save truncates it. + eval(arrays.values) var malformedMetadata = savedMetadata malformedMetadata["1.__mlx_lm_state_count"] = "2" try save(arrays: arrays, metadata: malformedMetadata, url: url) @@ -396,6 +401,7 @@ func testCacheSerialization(creator: (() -> any KVCache)) async throws { try savePromptCache(url: url, cache: [cache], state: state) let (arrays, savedMetadata) = try loadArraysAndMetadata(url: url) + eval(arrays.values) var malformedMetadata = savedMetadata malformedMetadata["1.__mlx_lm_state_version"] = "999" try save(arrays: arrays, metadata: malformedMetadata, url: url) @@ -420,6 +426,7 @@ func testCacheSerialization(creator: (() -> any KVCache)) async throws { try savePromptCache(url: url, cache: [cache], state: state) let (arrays, savedMetadata) = try loadArraysAndMetadata(url: url) + eval(arrays.values) var malformedMetadata = savedMetadata malformedMetadata["1.__mlx_lm_state_1_key"] = "test.first" try save(arrays: arrays, metadata: malformedMetadata, url: url) @@ -442,6 +449,7 @@ func testCacheSerialization(creator: (() -> any KVCache)) async throws { try savePromptCache(url: url, cache: [cache], state: state) let (storedArrays, metadata) = try loadArraysAndMetadata(url: url) + eval(storedArrays.values) var malformedArrays = storedArrays malformedArrays["__mlx_lm_state_tensor_99"] = MLXArray([Int32(99)]) try save(arrays: malformedArrays, metadata: metadata, url: url) @@ -464,6 +472,7 @@ func testCacheSerialization(creator: (() -> any KVCache)) async throws { try savePromptCache(url: url, cache: [cache], state: state) let (arrays, storedMetadata) = try loadArraysAndMetadata(url: url) + eval(arrays.values) var malformedMetadata = storedMetadata malformedMetadata["2.0"] = "KVCache" try save(arrays: arrays, metadata: malformedMetadata, url: url) @@ -483,6 +492,7 @@ func testCacheSerialization(creator: (() -> any KVCache)) async throws { try savePromptCache(url: url, cache: [cache]) let (arrays, storedMetadata) = try loadArraysAndMetadata(url: url) + eval(arrays.values) var malformedMetadata = storedMetadata malformedMetadata["2.0"] = "__mlx_lm_state_v1__:KVCache" try save(arrays: arrays, metadata: malformedMetadata, url: url) @@ -630,7 +640,9 @@ func testCacheSerialization(creator: (() -> any KVCache)) async throws { let rotating = try #require(restored.first as? RotatingKVCache) #expect(rotating.capacityOrigin == .modelNative) - #expect(rotating.metaState == ["0", "32", "256", "1", "1", "modelNative"]) + // Legacy metadata has no wrapped flag; the restored cache derives it (an + // unwrapped layout here) and re-serializes with the flag appended. + #expect(rotating.metaState == ["0", "32", "256", "1", "1", "modelNative", "false"]) } @Test func testPromptCacheRoundTripPreservesEmptyCaches() throws { @@ -2078,3 +2090,411 @@ private func fillOneAtATime(_ cache: RotatingKVCache, positions: Range) { #expect(varn.sinkhornIterations == 8) #expect(varn.compressionStart == 8) } + +// MARK: - RotatingKVCache wrap-aware trim +// +// Trimming a wrapped ring used to silently corrupt it (the ring invariants cannot +// express a hole in the timeline). A wrapped trim now linearizes the ring to temporal +// order and cuts the newest rows: consistent and clamped, though not exact -- rows the +// rewound writes overwrote at the old edge of the window cannot come back, which is why +// `isTrimmable` stays false past the window for the exact-rewind machinery. Every +// consumer of the buffer (writes, masks, state) now bounds live rows by `idx` instead +// of assuming the logical `offset` still equals the fill. + +@Test func testRotatingTrimAfterWrapCutsNewestAndKeepsChronology() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) // wrapped ring holding 12 ..< 20 + + let trimmed = cache.trim(3) // rewind 17, 18, 19 + + #expect(trimmed == 3) + #expect(cache.offset == 17) + let view = try #require(cache.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(12 ..< 17), "trim did not cut the newest rows") + #expect(encodedPositions(view.1).map { -$0 } == Array(12 ..< 17), "values diverged from keys") +} + +@Test func testRotatingTrimAfterWrapClampsToNonPinnedSpan() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 2) + fillOneAtATime(cache, positions: 0 ..< 13) // pinned [0, 1], ring holds 7 ..< 13 + + let trimmed = cache.trim(100) + + #expect(trimmed == 6, "the pinned prefix must bound the cut") + #expect(cache.offset == 7) + let view = try #require(cache.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == [0, 1], "the pinned prefix must survive a maximal trim") +} + +@Test func testRotatingSingleTokenRegrowthAfterWrapTrimPresentsOnlyLiveRows() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) + cache.trim(3) // holds 12 ..< 17 + + // The buffer regrows from 5 rows; the presentation must never include the + // freshly allocated (dead) rows. + let (k, v) = positionedKV(17 ..< 18) + let presented = cache.update(keys: k, values: v) + #expect(encodedPositions(presented.0) == Array(12 ..< 18)) + #expect(cache.offset == 18) + + // Refill through the rotation boundary and verify chronology survives re-wrapping. + fillOneAtATime(cache, positions: 18 ..< 25) + #expect(cache.offset == 25) + let view = try #require(cache.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(17 ..< 25)) +} + +@Test func testRotatingMultiTokenWriteAfterWrapTrimStaysChronological() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) + cache.trim(3) // holds 12 ..< 17 + + // The speculative verify shape: a multi-token write straight after a rewind. + let (k, v) = positionedKV(17 ..< 21) + let presented = cache.update(keys: k, values: v) + #expect(encodedPositions(presented.0) == Array(12 ..< 21)) + #expect(cache.offset == 21) + + fillOneAtATime(cache, positions: 21 ..< 24) + let view = try #require(cache.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(16 ..< 24)) +} + +@Test func testRotatingRepeatedTrimAfterWrapTakesTemporalPath() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) + + #expect(cache.trim(2) == 2) // ring path: holds 12 ..< 18 + #expect(cache.trim(2) == 2) // temporal path: holds 12 ..< 16 + + #expect(cache.offset == 16) + let view = try #require(cache.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(12 ..< 16)) +} + +@Test func testRotatingWrapTrimSurvivesCopyAndMetaStateRoundTrip() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) + + let copied = try #require(cache.copy() as? RotatingKVCache) + #expect(copied.trim(3) == 3) + let view = try #require(copied.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(12 ..< 17)) + #expect(cache.offset == 20, "trimming the copy must not touch the original") +} + +@Test func testRotatingLegacyMetaStateDerivesRingLayout() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) + + // A cache saved before the wrapped flag existed has 6 metaState values; the + // ring layout must be derived, not assumed away. + let legacyMetaState = Array(cache.metaState.dropLast()) + #expect(legacyMetaState.count == 6) + + let restored = RotatingKVCache(maxSize: 8, keep: 0) + restored.state = cache.state.map { $0[.ellipsis] } + restored.metaState = legacyMetaState + + let view = try #require(restored.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(12 ..< 20), "legacy restore lost the ring layout") + #expect(restored.trim(3) == 3) + let trimmedView = try #require(restored.logicalView(tail: 8)) + #expect(encodedPositions(trimmedView.0) == Array(12 ..< 17)) +} + +@Test(arguments: [5, 6, 7]) +func testRotatingRestoredTrimAtRingBoundary(metadataCount: Int) throws { + let source = RotatingKVCache(maxSize: 8) + fillOneAtATime(source, positions: 0 ..< 16) + + let restored = RotatingKVCache(maxSize: 8) + restored.state = source.state.map { $0[.ellipsis] } + restored.metaState = Array(source.metaState.prefix(metadataCount)) + + #expect(restored.trim(3) == 3) + #expect(restored.offset == 13) + let view = try #require(restored.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(8 ..< 13)) + #expect(encodedPositions(view.1) == Array(8 ..< 13).map { -$0 }) + #expect(restored.state.allSatisfy { $0.dim(2) == 5 }) +} + +@Test(arguments: [5, 6, 7]) +func testRotatingRestoredTrimKeepsKeysAndValuesAligned(metadataCount: Int) throws { + let source = RotatingKVCache(maxSize: 8) + fillOneAtATime(source, positions: 0 ..< 20) + + let restored = RotatingKVCache(maxSize: 8) + restored.state = source.state.map { $0[.ellipsis] } + restored.metaState = Array(source.metaState.prefix(metadataCount)) + + // The shortened key buffer ends before the old write index. Its new shape + // must not change how the value buffer is ordered during the same trim. + #expect(restored.trim(5) == 5) + #expect(restored.offset == 15) + let view = try #require(restored.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(12 ..< 15)) + #expect(encodedPositions(view.1) == Array(12 ..< 15).map { -$0 }) +} + +private func expectRotatingContents( + _ cache: RotatingKVCache, _ positions: [Int], + sourceLocation: SourceLocation = #_sourceLocation +) throws { + let view = try #require(cache.logicalView(tail: Int.max), sourceLocation: sourceLocation) + #expect(view.0.dim(2) == positions.count, sourceLocation: sourceLocation) + #expect(view.1.dim(2) == positions.count, sourceLocation: sourceLocation) + #expect( + cache.state.allSatisfy { $0.dim(2) == positions.count }, sourceLocation: sourceLocation) + // Empty MLX arrays need no host readback. + if !positions.isEmpty { + #expect(encodedPositions(view.0) == positions, sourceLocation: sourceLocation) + #expect(encodedPositions(view.1) == positions.map { -$0 }, sourceLocation: sourceLocation) + } +} + +@Test(arguments: [5, 6, 7], [false, true]) +func testRotatingRestorationAcceptsEitherSetterOrder( + metadataCount: Int, metadataFirst: Bool +) throws { + for count in [3, 8, 9, 16, 20] { + for prefill in [false, true] { + let source = RotatingKVCache(maxSize: 8, step: 4) + if prefill { + let (k, v) = positionedKV(0 ..< count) + _ = source.update(keys: k, values: v) + } else { + fillOneAtATime(source, positions: 0 ..< count) + } + let metadata = Array(source.metaState.prefix(metadataCount)) + let arrays = source.state.map { $0[.ellipsis] } + // The saved capacity must replace the constructor's capacity before inference. + let restored = RotatingKVCache(maxSize: 1) + if metadataFirst { + restored.metaState = metadata + restored.state = arrays + } else { + restored.state = arrays + restored.metaState = metadata + } + + let start = prefill ? 0 : max(0, count - 8) + try expectRotatingContents(restored, Array(start ..< count)) + #expect(restored.trim(2) == 2) + #expect(restored.offset == count - 2) + try expectRotatingContents(restored, Array(start ..< (count - 2))) + } + } +} + +@Test(arguments: [5, 6, 7], [false, true]) +func testRotatingRestoredShortChronologicalBufferCanGrow( + metadataCount: Int, metadataFirst: Bool +) throws { + let source = RotatingKVCache(maxSize: 8) + fillOneAtATime(source, positions: 0 ..< 20) + // Legacy updateConcat could leave maxSize - 1 chronological rows when given + // an empty append. idx < maxSize && offset > idx cannot identify its layout. + let empty = positionedKV(20 ..< 20) + _ = source.update(keys: empty.0, values: empty.1) + try expectRotatingContents(source, Array(13 ..< 20)) + + let restored = RotatingKVCache(maxSize: 8) + let metadata = Array(source.metaState.prefix(metadataCount)) + let arrays = source.state.map { $0[.ellipsis] } + if metadataFirst { + restored.metaState = metadata + restored.state = arrays + } else { + restored.state = arrays + restored.metaState = metadata + } + #expect(restored.metaState.last == "false") + fillOneAtATime(restored, positions: 20 ..< 21) + try expectRotatingContents(restored, Array(13 ..< 21)) + #expect(restored.trim(3) == 3) + try expectRotatingContents(restored, Array(13 ..< 18)) +} + +@Test(arguments: [5, 6, 7], [13, 14, 20]) +func testRotatingRestoredTrimPreservesPinnedPrefix(metadataCount: Int, count: Int) throws { + let source = RotatingKVCache(maxSize: 8, keep: 2) + fillOneAtATime(source, positions: 0 ..< count) + + for firstTrim in [3, 100] { + let restored = RotatingKVCache(maxSize: 8) + restored.state = source.state.map { $0[.ellipsis] } + restored.metaState = Array(source.metaState.prefix(metadataCount)) + let removed = min(firstTrim, 6) + #expect(restored.trim(firstTrim) == removed) + try expectRotatingContents( + restored, [0, 1] + Array((count - 6) ..< (count - removed))) + // The second trim operates on temporal storage, even if the first used a ring. + #expect(restored.trim(100) == 6 - removed) + #expect(restored.trim(1) == 0) + #expect(restored.offset == count - 6) + try expectRotatingContents(restored, [0, 1]) + + let next = restored.offset + fillOneAtATime(restored, positions: next ..< (next + 8)) + try expectRotatingContents(restored, [0, 1] + Array((next + 2) ..< (next + 8))) + } + try expectRotatingContents(source, [0, 1] + Array((count - 6) ..< count)) +} + +@Test(arguments: [1, 2, 5, 8]) +func testRotatingTrimBeforeEvictionCanRewindThroughPrefix(count: Int) throws { + let cache = RotatingKVCache(maxSize: 8, keep: 2) + fillOneAtATime(cache, positions: 0 ..< count) + let metadata = cache.metaState + #expect(cache.trim(0) == 0) + #expect(cache.trim(-1) == 0) + #expect(cache.metaState == metadata) + #expect(cache.trim(100) == count) + #expect(cache.offset == 0) + try expectRotatingContents(cache, []) + fillOneAtATime(cache, positions: 0 ..< 3) + try expectRotatingContents(cache, [0, 1, 2]) +} + +@Test(arguments: [0, 2], [1, 3]) +func testRotatingTrimOversizedPrefillThenResume(keep: Int, nextCount: Int) throws { + let cache = RotatingKVCache(maxSize: 8, keep: keep, step: 4) + fillOneAtATime(cache, positions: 0 ..< 20) + let (k, v) = positionedKV(20 ..< 23) + _ = cache.update(keys: k, values: v) // ten chronological rows + #expect(cache.trim(5) == 5) + #expect(cache.offset == 18) + let prefix = Array(0 ..< keep) + try expectRotatingContents(cache, prefix + Array((13 + keep) ..< 18)) + + let mask = cache.makeMask(n: nextCount, windowSize: 8, returnArray: true) + let next = positionedKV(18 ..< (18 + nextCount)) + let presented = cache.update(keys: next.0, values: next.1) + let expected = prefix + Array((13 + keep) ..< (18 + nextCount)) + #expect(encodedPositions(presented.0) == expected) + #expect(encodedPositions(presented.1) == expected.map { -$0 }) + if case .array(let array) = mask { + #expect(array.dim(-1) == presented.0.dim(2)) + } + fillOneAtATime(cache, positions: (18 + nextCount) ..< 30) + try expectRotatingContents(cache, prefix + Array((22 + keep) ..< 30)) +} + +@Test(arguments: [5, 6, 7]) +func testRotatingTrimSurvivesPromptCachePersistenceAndCopy(metadataCount: Int) throws { + let source = RotatingKVCache(maxSize: 8) + fillOneAtATime(source, positions: 0 ..< 16) + let url = tempURL() + let legacyURL = tempURL() + let roundTripURL = tempURL() + defer { + for file in [url, legacyURL, roundTripURL] { + try? FileManager.default.removeItem(at: file) + } + } + try savePromptCache(url: url, cache: [source]) + // Exercise the real file loader with each historical metadata format. + let (arrays, savedMetadata) = try loadArraysAndMetadata(url: url) + var metadata = savedMetadata + for index in metadataCount ..< 7 { + metadata.removeValue(forKey: "0.0.\(index)") + } + // MLX loads lazily, so keep the source files intact while their arrays are live. + try save(arrays: arrays, metadata: metadata, url: legacyURL) + let (loaded, _) = try loadPromptCache(url: legacyURL) + let restored = try #require(loaded.first as? RotatingKVCache) + #expect(restored.trim(3) == 3) + try expectRotatingContents(restored, Array(8 ..< 13)) + + // A post-trim cache has more history than live rows; its explicit false flag + // must survive serialization instead of being inferred from those counters. + try savePromptCache(url: roundTripURL, cache: [restored]) + let (reloaded, _) = try loadPromptCache(url: roundTripURL) + let roundTrip = try #require(reloaded.first as? RotatingKVCache) + let copied = try #require(roundTrip.copy() as? RotatingKVCache) + #expect(copied.trim(2) == 2) + fillOneAtATime(copied, positions: 11 ..< 20) + try expectRotatingContents(copied, Array(12 ..< 20)) + try expectRotatingContents(roundTrip, Array(8 ..< 13)) + try expectRotatingContents(restored, Array(8 ..< 13)) + try expectRotatingContents(source, Array(8 ..< 16)) + #expect(roundTrip.offset == 13) + #expect(source.offset == 16) +} + +@Test(arguments: [5, 6, 7], [1, 3]) +func testRotatingRestoredTrimAttentionMatchesSurvivingContext( + metadataCount: Int, queryCount: Int +) throws { + let keys = deterministicTensor(shape: [1, 2, 20, 4], salt: 1).asType(.float32) + let values = deterministicTensor(shape: [1, 2, 20, 4], salt: 2).asType(.float32) + let queries = deterministicTensor(shape: [1, 2, queryCount, 4], salt: 3).asType(.float32) + let source = RotatingKVCache(maxSize: 8) + for p in 0 ..< 20 { + _ = source.update( + keys: keys[.ellipsis, p ..< (p + 1), 0...], + values: values[.ellipsis, p ..< (p + 1), 0...]) + } + let restored = RotatingKVCache(maxSize: 8) + restored.state = source.state.map { $0[.ellipsis] } + restored.metaState = Array(source.metaState.prefix(metadataCount)) + #expect(restored.trim(5) == 5) // only positions 12, 13, 14 survive + let mask = restored.makeMask(n: queryCount, windowSize: 4, returnArray: false) + let (cachedKeys, cachedValues) = restored.update( + keys: keys[.ellipsis, 15 ..< (15 + queryCount), 0...], + values: values[.ellipsis, 15 ..< (15 + queryCount), 0...]) + let output = MLXFast.scaledDotProductAttention( + queries: queries, keys: cachedKeys, values: cachedValues, scale: 0.5, mask: mask) + let reference = MLXFast.scaledDotProductAttention( + queries: queries, + keys: keys[.ellipsis, 12 ..< (15 + queryCount), 0...], + values: values[.ellipsis, 12 ..< (15 + queryCount), 0...], + scale: 0.5, + mask: .array(createCausalMask(n: queryCount, offset: 3, windowSize: 4))) + #expect(allClose(output, reference, rtol: 1e-5, atol: 1e-5).item(Bool.self)) +} + +@Test func testRotatingSingleTokenMaskAfterWrapTrimMatchesEquivalentFreshCache() throws { + // After a wrapped trim the cache holds 5 live rows; the sliding-window mask for + // the next single-token step must match a fresh cache holding the same rows. + let windowSize = 4 + + let trimmedCache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(trimmedCache, positions: 0 ..< 20) + trimmedCache.trim(3) // 5 live rows + + let freshCache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(freshCache, positions: 0 ..< 5) // 5 live rows + + let trimmedMask = trimmedCache.makeMask(n: 1, windowSize: windowSize, returnArray: false) + let freshMask = freshCache.makeMask(n: 1, windowSize: windowSize, returnArray: false) + + guard case .array(let trimmedArray) = trimmedMask, case .array(let freshArray) = freshMask + else { + Issue.record("expected array masks, got \(trimmedMask) and \(freshMask)") + return + } + #expect(trimmedArray.shape == freshArray.shape) + #expect((trimmedArray .== freshArray).all().item(Bool.self)) +} + +@Test func testRotatingMultiTokenMaskWidthMatchesPresentationAfterWrapTrim() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) + cache.trim(3) // 5 live rows + + // Models build the mask before the write; its key width must equal the rows the + // write presents, or attention shapes diverge. + let mask = cache.makeMask(n: 3, windowSize: 4, returnArray: true) + let (k, v) = positionedKV(17 ..< 20) + let presented = cache.update(keys: k, values: v) + + guard case .array(let maskArray) = mask else { + Issue.record("expected an array mask, got \(mask)") + return + } + #expect(maskArray.dim(-1) == presented.0.dim(2)) +} diff --git a/Tests/MLXLMTests/LoRAModelMetadataTests.swift b/Tests/MLXLMTests/LoRAModelMetadataTests.swift new file mode 100644 index 0000000000..1d9fb64890 --- /dev/null +++ b/Tests/MLXLMTests/LoRAModelMetadataTests.swift @@ -0,0 +1,191 @@ +// Copyright Β© 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN +import MLXVLM +import XCTest + +@testable import MLXLLM + +final class LoRAModelMetadataTests: XCTestCase { + func testVLMMetadataUsesLanguageLayers() async throws { + let configuration = Data( + """ + { + "model_type": "gemma3", + "mm_tokens_per_image": 4, + "text_config": { + "model_type": "gemma3_text", + "hidden_size": 16, + "num_hidden_layers": 2, + "intermediate_size": 32, + "sliding_window": 16, + "num_attention_heads": 2, + "num_key_value_heads": 1, + "head_dim": 8 + }, + "vision_config": { + "model_type": "siglip_vision_model", + "hidden_size": 16, + "num_hidden_layers": 1, + "intermediate_size": 32, + "num_attention_heads": 2, + "patch_size": 2, + "image_size": 4 + } + } + """.utf8 + ) + let result = try await VLMModelFactory.shared.loraMetadata( + configurationData: configuration) + let metadata = try XCTUnwrap(result) + + XCTAssertEqual(metadata.layerCount, 2) + XCTAssertEqual(metadata.defaultKeys, Self.defaultKeys) + } + + func testMetadataPreservesCallerRandomSequence() async throws { + let registry = ModelTypeRegistry() + await registry.registerModelType("metadata_test") { _ in MetadataTestModel() } + await registry.registerModelType("throwing_test") { _ in + _ = MLXRandom.uniform() + throw TestError.construction + } + let factory = LLMModelFactory( + typeRegistry: registry, modelRegistry: AbstractModelRegistry()) + let expected = MLXRandom.RandomState(seed: 42) + + try await withRandomState(MLXRandom.RandomState(seed: 42)) { + XCTAssertEqual(resolve().asArray(UInt32.self), expected.next().asArray(UInt32.self)) + for _ in 0 ..< 2 { + _ = try await factory.loraMetadata( + configurationData: Data(#"{"model_type":"metadata_test"}"#.utf8)) + XCTAssertEqual( + resolve().asArray(UInt32.self), expected.next().asArray(UInt32.self)) + } + + do { + _ = try await factory.loraMetadata( + configurationData: Data(#"{"model_type":"throwing_test"}"#.utf8)) + XCTFail("Expected the constructor error") + } catch TestError.construction { + XCTAssertEqual( + resolve().asArray(UInt32.self), expected.next().asArray(UInt32.self)) + } + } + } + + func testModelWithoutLoRAConformanceReturnsNil() async throws { + let registry = ModelTypeRegistry() + await registry.registerModelType("plain_test") { _ in PlainTestModel() } + let result = try await registry.loraMetadata( + configurationData: Data(#"{"model_type":"plain_test"}"#.utf8)) + XCTAssertNil(result) + } + + func testUnknownModelTypeThrows() async throws { + let registry = ModelTypeRegistry() + do { + _ = try await registry.loraMetadata( + configurationData: Data(#"{"model_type":"unknown"}"#.utf8)) + XCTFail("Expected an unsupported model type error") + } catch ModelFactoryError.unsupportedModelType(let type) { + XCTAssertEqual(type, "unknown") + } + } + + func testInvalidConfigurationThrows() async throws { + do { + _ = try await LLMModelFactory.shared.loraMetadata( + configurationData: Data(#"{"model_type":"qwen3"}"#.utf8)) + XCTFail("Expected a configuration decoding error") + } catch is DecodingError { + } + } + + func testFactoryUsesRegisteredModelLoRAMetadata() async throws { + let typeRegistry = ModelTypeRegistry() + await typeRegistry.registerModelType("metadata_test") { _ in + MetadataTestModel() + } + let factory = LLMModelFactory( + typeRegistry: typeRegistry, + modelRegistry: AbstractModelRegistry() + ) + + let result = try await factory.loraMetadata( + configurationData: Data(#"{"model_type":"metadata_test"}"#.utf8) + ) + let metadata = try XCTUnwrap(result) + + XCTAssertEqual(metadata.layerCount, 1) + XCTAssertEqual(metadata.defaultKeys, ["runtime.a_proj", "runtime.z_proj"]) + } + + func testBuiltInModelMetadataUsesRuntimeModulePaths() async throws { + let configuration = Data( + """ + { + "model_type": "qwen3", + "hidden_size": 16, + "num_hidden_layers": 2, + "intermediate_size": 32, + "num_attention_heads": 2, + "num_key_value_heads": 1, + "head_dim": 8, + "rms_norm_eps": 1e-5, + "vocab_size": 64 + } + """.utf8 + ) + + let result = try await LLMModelFactory.shared.loraMetadata( + configurationData: configuration + ) + let metadata = try XCTUnwrap(result) + + XCTAssertEqual(metadata.layerCount, 2) + XCTAssertEqual(metadata.defaultKeys, Self.defaultKeys) + } + + private static let defaultKeys = [ + "mlp.down_proj", + "mlp.gate_proj", + "mlp.up_proj", + "self_attn.k_proj", + "self_attn.o_proj", + "self_attn.q_proj", + "self_attn.v_proj", + ] + + private enum TestError: Error { + case construction + } +} + +private class PlainTestModel: Module, LanguageModel, KVCacheDimensionProvider { + let kvHeads: [Int] = [] + + func prepare( + _ input: LMInput, cache: [KVCache], state: LMOutput.State?, prefill: PrefillParameters + ) throws -> PrepareResult { + .tokens(input.text) + } + + func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + inputs + } +} + +private final class MetadataTestModel: PlainTestModel, LoRAModel { + private let layer = Linear(4, 4) + + var loraLayers: [Module] { [layer] } + var loraDefaultKeys: [String] { + // Exercise random-state isolation during metadata access as well as construction. + _ = MLXRandom.uniform() + return ["runtime.z_proj", "runtime.a_proj"] + } +} diff --git a/Tests/MLXLMTests/StreamingDetokenizerTests.swift b/Tests/MLXLMTests/StreamingDetokenizerTests.swift index 6fe8a80b40..bc3748e9c6 100644 --- a/Tests/MLXLMTests/StreamingDetokenizerTests.swift +++ b/Tests/MLXLMTests/StreamingDetokenizerTests.swift @@ -78,6 +78,7 @@ private struct SplitMultibyteTokenizer: MLXLMCommon.Tokenizer { out += "\u{fffd}" // incomplete: only the first half so far case 51: out += "\u{fffd}" // second half without its first half + case 60: out += "\u{FE0F}" // VARIATION SELECTOR-16, its own token case 65: out += "a" case 66: out += "b" default: break @@ -166,4 +167,59 @@ final class StreamingDetokenizerTests: XCTestCase { streamed.contains(","), "comma dropped across a newline segment reset: \(streamed.debugDescription)") } + + // MARK: grapheme clusters that grow across a token boundary + + /// Exact scalar sequences: `String ==` compares under canonical + /// equivalence, which would let `e` + U+0301 equal `Γ©`. + private func scalars(_ text: String) -> [UInt32] { + text.unicodeScalars.map(\.value) + } + + /// A token that appends a combining scalar to the previous token's + /// character must emit only that scalar. A `Character`-level common + /// prefix treats `🏳` and `🏳️` as different characters and re-emits the + /// base, so `πŸ³οΈβ€πŸŒˆ` streamed as `πŸ³πŸ³οΈπŸ³οΈβ€πŸ³οΈβ€πŸŒˆ`. + func testCombiningScalarAppendedToPreviousCharacterIsEmittedOnce() { + let tokenizer = AppendOnlyTokenizer(pieces: [ + 1: "\u{1F3F3}", // 🏳 WAVING WHITE FLAG + 2: "\u{FE0F}", // VARIATION SELECTOR-16 + 3: "\u{200D}", // ZERO WIDTH JOINER + 4: "\u{1F308}", // 🌈 RAINBOW + ]) + let tokens = [1, 2, 3, 4] + let streamed = stream(tokens, tokenizer) + XCTAssertEqual( + scalars(streamed), [0x1F3F3, 0xFE0F, 0x200D, 0x1F308], + "base character re-emitted: \(streamed.debugDescription)") + XCTAssertEqual( + streamed, tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false)) + } + + /// The same growth on an ASCII base: `'` then U+FE0F then `'` is three + /// scalars, not four. + func testVariationSelectorAfterASCIIDoesNotRepeatTheBase() { + let tokenizer = AppendOnlyTokenizer(pieces: [1: "'", 2: "\u{FE0F}", 3: "'"]) + let streamed = stream([1, 2, 3], tokenizer) + XCTAssertEqual(scalars(streamed), [0x27, 0xFE0F, 0x27], streamed.debugDescription) + } + + /// A combining accent arriving as its own token: `e` + U+0301 + `x`. + func testCombiningAccentDoesNotRepeatTheBase() { + let tokenizer = AppendOnlyTokenizer(pieces: [1: "e", 2: "\u{0301}", 3: "x"]) + let streamed = stream([1, 2, 3], tokenizer) + XCTAssertEqual(scalars(streamed), [0x65, 0x0301, 0x78], streamed.debugDescription) + } + + /// The REPLACEMENT CHARACTER hold-back and the cluster growth compose: + /// a multi-byte character completed across two tokens, then a variation + /// selector token joining it, emits each scalar exactly once. + func testVariationSelectorAfterSplitMultibyteCharacterIsEmittedOnce() { + let tokenizer = SplitMultibyteTokenizer() + let tokens = [65, 50, 51, 60, 66] // "a", δΈ­(first half), δΈ­(second half), U+FE0F, "b" + let streamed = stream(tokens, tokenizer) + XCTAssertEqual(scalars(streamed), [0x61, 0x4E2D, 0xFE0F, 0x62], streamed.debugDescription) + XCTAssertEqual( + streamed, tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false)) + } } diff --git a/skills/mlx-swift-lm/references/kv-cache.md b/skills/mlx-swift-lm/references/kv-cache.md index cd8bc191f8..98a0ef3b47 100644 --- a/skills/mlx-swift-lm/references/kv-cache.md +++ b/skills/mlx-swift-lm/references/kv-cache.md @@ -115,8 +115,40 @@ let simpleAgain = quantizedCache.toUnquantized() ```swift // Models create appropriate cache for their architecture let cache = model.newCache(parameters: generateParameters) + +// Inspect planned topology, capacity, and strategy state +let status = try model.cacheStatus(parameters: generateParameters) +// Or via ModelContainer / ChatSession: +// let status = try await container.cacheStatus(parameters: params) +// let status = try await session.cacheStatus() + +switch status.capacityDisposition { +case .notRequested: break +case .fullyApplied: break // every attention layer is at or below the request +case .partiallyApplied: break // only some attention layers satisfy the request +case .unsupported: break // pure SSM β€” no attention KV to limit +case .ignored: break // attention exists but stayed unbounded +} + +for layer in status.layers { + print(layer.path, layer.kind, layer.capacitySource as Any, + layer.state, layer.resolvedStrategy as Any) +} ``` +Hybrid attention / state-space models (Qwen3.5, Jamba, LFM2, Falcon-H1, …) +apply `maxKVSize` only to attention layers. Architecture sliding-window layers +use `min(slidingWindow, maxKVSize)`. State-space caches are never token-windowed. + +Typed `KVCacheConfiguration.Capacity` follows its separate contract: it bounds +caller-configurable full-attention caches while leaving model-native sliding +windows unchanged. `KVCacheStatus` normalizes both entry points into one +requested configuration while preserving `.legacy` / `.typed` request source, +per-layer capacity provenance, and planned / realized phase. + +Prefer `makeAttentionKVCache(parameters:)` / `makeHybridAttentionKVCache(...)` +inside model `newCache` overrides so the limit cannot be silently dropped. + ### Via Utility Functions ```swift diff --git a/skills/mlx-swift-lm/references/lora-adapters.md b/skills/mlx-swift-lm/references/lora-adapters.md index 16116a3def..250917940c 100644 --- a/skills/mlx-swift-lm/references/lora-adapters.md +++ b/skills/mlx-swift-lm/references/lora-adapters.md @@ -34,6 +34,7 @@ public struct LoRAConfiguration: Sendable, Codable { public struct LoRAParameters: Sendable, Codable { public let rank: Int // Low-rank dimension (default: 8) public let scale: Float // Scaling factor (default: 10.0) + public let dropout: Float // Training-only input dropout (default: 0.0) public let keys: [String]? // Layer keys to adapt (nil = all Linear) } @@ -61,6 +62,7 @@ let config = LoRAConfiguration( loraParameters: .init( rank: 16, scale: 20.0, + dropout: 0.05, keys: ["self_attn.q_proj", "self_attn.v_proj"] ) ) @@ -75,6 +77,7 @@ let config = LoRAConfiguration( "lora_parameters": { "rank": 16, "scale": 20.0, + "dropout": 0.05, "keys": ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"] } } @@ -95,6 +98,10 @@ let adapter = try LoRAContainer.from(directory: adapterURL) try adapter.load(into: model) ``` +`ModelContext` places its model in evaluation mode, so adapters with nonzero dropout are +deterministic during normal generation. If you invoke a model directly without a `ModelContext`, +call `model.train(false)` before inference. `LoRATrain.train` enables training mode while it runs. + ### From Model (Create New Adapter) ```swift @@ -153,7 +160,7 @@ public class LoRALinear: Linear, LoRALayer { @ParameterInfo(key: "lora_a") var loraA: MLXArray @ParameterInfo(key: "lora_b") var loraB: MLXArray - // Forward: y = Wx + scale * (x @ A @ B) + // Forward: y = Wx + scale * (dropout(x) @ A @ B) } ``` diff --git a/skills/mlx-swift-lm/references/model-porting.md b/skills/mlx-swift-lm/references/model-porting.md index 17f57577ae..cd2b1c30d0 100644 --- a/skills/mlx-swift-lm/references/model-porting.md +++ b/skills/mlx-swift-lm/references/model-porting.md @@ -332,6 +332,45 @@ extension YourModel: LoRAModel { If you need custom keys, override `loraDefaultKeys`. +## Compiled decode paths + +`compile` traces a function once and turns every `MLXArray` the body reads, but +does not take as an argument, into a constant of that trace. A body that reads +weights through a captured module therefore keeps the values of its first call +and ignores a loaded adapter or a training step. + +`compile` in this package resolves to the `MLXLMCommon` overload, whose +`@Sendable` body cannot capture a `Module` or an `MLXArray`, so that mistake +does not build. Use it for bodies that read only their arguments: + +```swift +private let siluProduct: @Sendable (MLXArray, MLXArray) -> MLXArray = compile(shapeless: true) { + gate, up in silu(gate) * up +} +``` + +For a body that reads weights, use `CompiledTrace`. It takes the owner as a +parameter and declares the modules whose weights the body reads, which become +compile `inputs:`: + +```swift +final class YourMoEBlock: Module, UnaryLayer { + // Default state is the owner, which covers a body that stays inside it. + private let compiledForward = CompiledTrace { block, arguments in + [block.forward(arguments[0])] + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + compiledForward(self, x) + } +} +``` + +Traces are lazy, so a trace created in `init` still reads weights loaded later, +and it never retains its owner. Anything that replaces modules invalidates a +trace: `Module.invalidateCompiledTraces()` resets every trace in a model tree +and already runs on the adapter and quantization paths. + ## Registration 1. Add model type mapping in `Libraries/MLXLLM/LLMModelFactory.swift`: @@ -349,6 +388,8 @@ If you need custom keys, override `loraDefaultKeys`. - Bias flags are model-specific (check config and Python implementation). - GQA models require `kvHeads` distinct from `attentionHeads`. - Sliding-window or special caches may require overriding `newCache` or `prepare`. +- A compiled body must read weights through `CompiledTrace`, not through a + captured `self`, or the trace bakes them in. ## Minimal checklist diff --git a/skills/mlx-swift-lm/references/supported-models.md b/skills/mlx-swift-lm/references/supported-models.md index 8f7d455929..cd4c065b3e 100644 --- a/skills/mlx-swift-lm/references/supported-models.md +++ b/skills/mlx-swift-lm/references/supported-models.md @@ -141,6 +141,7 @@ VLMRegistry.paligemma3bMix448_8bit // mlx-community/paligemma-3b-mix-448-8bit | `pixtral` | Pixtral | | `mistral3` | Mistral 3 VLM | | `lfm2_vl`, `lfm2-vl` | LFM2 VL | +| `muse_glimmer` | Meta Muse Glimmer (text, image, reasoning, and ATEM tool calls) | ## Loading Any Model diff --git a/skills/mlx-swift-lm/references/tool-calling.md b/skills/mlx-swift-lm/references/tool-calling.md index 556a67dadb..afa9e8691e 100644 --- a/skills/mlx-swift-lm/references/tool-calling.md +++ b/skills/mlx-swift-lm/references/tool-calling.md @@ -30,7 +30,8 @@ mlx-swift-lm supports function calling / tool use with multiple model-specific f |--------|--------|----------------| | `.json` | Llama, Qwen, most models | `{"name":"f","arguments":{...}}` | | `.lfm2` | LFM2 | `<\|tool_call_start\|>{"name":"f",...}<\|tool_call_end\|>` | -| `.xmlFunction` | Nemotron, Qwen3 Coder, Qwen3.5 | `v` | +| `.xmlFunction` | Nemotron, Qwen3 Coder, Qwen3 Next | `v` | +| `.qwen35` | Qwen 3.5 | Same `` frame as `.xmlFunction`, but also accepts a framed Qwen/Hermes JSON payload (`{"name":"f","arguments":{...}}`) that Qwen 3.5 sporadically emits instead of XML. Bare (unframed) JSON is not recovered. | | `.glm4` | GLM4 | `funckv` | | `.gemma` | Gemma | `call:name{key:value}` | | `.kimiK2` | Kimi K2 | `functions.name:0<\|tool_call_argument_begin\|>{...}` | @@ -184,18 +185,34 @@ let processor = ToolCallProcessor( ) ``` -## Format Auto-Detection +## Format Resolution -Formats are auto-detected from model type: +When a model is loaded, the factories resolve the format in this order: + +1. an explicit value on the `ModelConfiguration` (registry entry or caller), +2. a `ChatConventionsResolving` registered with `ChatConventionsRegistry` + (keyed on repo id / model type, for conventions the model cannot know), +3. an explicit `tool_parser_type` in the checkpoint's tokenizer files, +4. the selected tool template reconciled with the model's own + `ChatConventionsProviding` declaration. + +Nothing resolved means the default `.json` parser is used. + +At step 4, the model declaration remains selected when it can parse the template's +dialect. Otherwise, the template refines it because the template is what teaches +the model what to emit. This lets Qwen 3.5 keep its dual-dialect parser while a +Hermes checkpoint can refine the Llama 3 architecture heuristic from inline JSON +to framed JSON. If the template has no recognizable tool syntax, the model +declaration remains the fallback. ```swift -// Auto-detected based on model_type in config.json -ToolCallFormat.infer(from: "lfm2") // -> .lfm2 -ToolCallFormat.infer(from: "glm4") // -> .glm4 -ToolCallFormat.infer(from: "gemma") // -> .gemma -ToolCallFormat.infer(from: "llama") // -> nil (use default .json) +ToolCallFormat.inferred(fromChatTemplate: template) // -> .mistral, .glm4, ... +ToolCallFormat(toolParserType: "qwen3_coder") // -> .xmlFunction ``` +Protocols with token-level framing (`.gptOSS`, `.atem`) are deliberately not +inferred from templates β€” they are selected by the models that own them. + ### Explicit Format in Configuration ```swift diff --git a/skills/mlx-swift-lm/references/training.md b/skills/mlx-swift-lm/references/training.md index 978d22f33d..eea755267b 100644 --- a/skills/mlx-swift-lm/references/training.md +++ b/skills/mlx-swift-lm/references/training.md @@ -27,6 +27,7 @@ public struct Parameters: Sendable { public var validationBatches: Int = 10 // 0 = full validation set public var saveEvery: Int = 100 // Checkpoint frequency public var adapterURL: URL? // Save location + public var completedIterations: Int = 0 // Resume progress offset public init( batchSize: Int = 4, @@ -35,11 +36,28 @@ public struct Parameters: Sendable { stepsPerEval: Int = 100, validationBatches: Int = 10, saveEvery: Int = 100, - adapterURL: URL? = nil + adapterURL: URL? = nil, + completedIterations: Int = 0 ) } ``` +When resuming, apply matching LoRA layers, load the saved weights, and set the number of +iterations already completed. `iterations` remains the desired total: + +```swift +try LoRATrain.loadLoRAWeights(model: model, url: adapterURL) + +let parameters = LoRATrain.Parameters( + iterations: 1000, + completedIterations: 400 +) +``` + +This reloads adapter parameters only. Persist and restore optimizer state separately when exact +optimizer continuation is required. The saved file must contain only keys present in the model's +adapter structure. + ## Training Workflow ### 1. Load Model