Skip to content
Closed
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
90 changes: 90 additions & 0 deletions Libraries/MLXLLM/Models/MiMo/MiMoV26IndependentHistoryCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public final class MiMoV26IndependentHistoryCache: KVCache {
let values: MLXArray
}
private var pages: [Page] = []
private var lastAppendTokens = 0
private var layout: MiMoV26PagedKVLayout
private var shape: (heads: Int, keyWidth: Int, valueWidth: Int, dtype: DType)?
public var offset: Int { layout.offset }
Expand Down Expand Up @@ -79,6 +80,7 @@ public final class MiMoV26IndependentHistoryCache: KVCache {
shape = (keys.dim(1), keys.dim(3), values.dim(3), keys.dtype)
}
let update = layout.append(keys.dim(2))
lastAppendTokens = keys.dim(2)
if let retained = update.retained {
let old = pages
pages = []
Expand Down Expand Up @@ -192,6 +194,93 @@ public final class MiMoV26IndependentHistoryCache: KVCache {
}
}

/// A verify call must have appended one complete multi-token window.
/// Validate every layer first; only then may the owner mutate any layer.
public func validateWindowRollback(by count: Int) throws {
guard count >= 0 else { throw MiMoV26ExecutionError.cacheGeometry(layer: layerIndex) }
guard count > 0 else { return }
guard lastAppendTokens >= 2, count < lastAppendTokens,
layout.index == layout.count, layout.count > count, offset >= count
else {
throw MiMoV26ExecutionError.cacheGeometry(layer: layerIndex)
}
}

public func rollbackWindow(by count: Int) throws {
try validateWindowRollback(by: count)
guard count > 0 else { return }
layout.restore(
count: layout.count - count, offset: offset - count, index: layout.count - count)
pages = Array(
pages.prefix(
(layout.count + MiMoV26PagedKVLayout.pageTokens - 1)
/ MiMoV26PagedKVLayout.pageTokens))
// A settled window cannot be rolled back a second time.
lastAppendTokens = 0
}

/// Checked phase transfer into a fresh owner. The source physical order
/// and absolute offset/index are preserved, while backing is page-owned.
public func validateRestore(keys: MLXArray, values: MLXArray, offset: Int, index: Int) throws {
guard pages.isEmpty, self.offset == 0 else {
throw MiMoV26ExecutionError.cacheGeometry(layer: layerIndex)
}
try validateReplacement(keys: keys, values: values, offset: offset, index: index)
}

public func restore(keys: MLXArray, values: MLXArray, offset: Int, index: Int) throws {
try validateRestore(keys: keys, values: values, offset: offset, index: index)
replace(keys: keys, values: values, offset: offset, index: index)
}

private func validateReplacement(keys: MLXArray, values: MLXArray, offset: Int, index: Int)
throws
{
guard let shape, keys.ndim == 4, values.ndim == 4,
keys.dim(0) == 1, values.dim(0) == 1,
keys.dim(1) == shape.heads, values.dim(1) == shape.heads,
keys.dim(3) == shape.keyWidth, values.dim(3) == shape.valueWidth,
keys.dtype == shape.dtype, values.dtype == shape.dtype,
keys.dim(2) > 0, keys.dim(2) == values.dim(2),
offset >= keys.dim(2), offset <= maximumContext,
index >= 0, index <= keys.dim(2),
maxSize != nil || (offset == keys.dim(2) && index == offset)
else {
throw MiMoV26ExecutionError.cacheGeometry(layer: layerIndex)
}
}

private func replace(keys: MLXArray, values: MLXArray, offset: Int, index: Int) {
pages = []
write(keys: keys, values: values, at: 0)
layout.restore(count: keys.dim(2), offset: offset, index: index)
lastAppendTokens = 0
}

/// The assistant's completion fence measures every independent page root,
/// never a gathered view. Copy bit patterns without floating arithmetic.
func detachPages() {
func detached(_ array: MLXArray) -> MLXArray {
let bits = array.view(dtype: array.dtype == .float32 ? .uint32 : .uint16)
return MLX.where(MLXArray(true), bits, bits).view(dtype: array.dtype)
}
pages = pages.map { .init(keys: detached($0.keys), values: detached($0.values)) }
}

func compactRetainedHistory() {
guard let window = maxSize, layout.count > 0 else { return }
if layout.count > window {
// Multi-token appends have already put the buffer in temporal order.
precondition(layout.index == layout.count)
let rows = gathered()
let frontier = offset
replace(
keys: rows[0][.ellipsis, (-window)..., 0...],
values: rows[1][.ellipsis, (-window)..., 0...], offset: frontier, index: window)
}
detachPages()
}

public var isTrimmable: Bool { layout.isTrimmable }
@discardableResult public func trim(_ n: Int) -> Int {
let removed = layout.trim(n)
Expand Down Expand Up @@ -242,6 +331,7 @@ public final class MiMoV26IndependentHistoryCache: KVCache {
result.layout = layout
result.shape = shape
result.pages = pages
result.lastAppendTokens = lastAppendTokens
return result
}
}
Expand Down
63 changes: 50 additions & 13 deletions Libraries/MLXLLM/Models/MiMo/MiMoV26MTP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,17 @@ private final class MiMoV26MTPTargetOwner {
init(_ target: MiMoV26TextModel) { self.target = target }
}

/// The default retains the admitted engine's existing cache contract. Cluster
/// owners can explicitly select page-owned histories with their extra budget.
public enum MiMoV26MTPHistoryStorage: Sendable, Equatable { case contiguous, paged }

/// Cache-local history starts at zero; RoPE uses the absolute next-token offset.
/// Only the sealed request owner can obtain this protocol view.
final class MiMoV26MTPPositionedCache: KVCache {
let storage: RotatingKVCache
private(set) var storage: any KVCache
let firstPosition: Int
init(window: Int, firstPosition: Int) {
storage = RotatingKVCache(maxSize: window)
init(window: Int, firstPosition: Int, pages: MiMoV26IndependentHistoryCache? = nil) {
if let pages { storage = pages } else { storage = RotatingKVCache(maxSize: window) }
self.firstPosition = firstPosition
}
var offset: Int { firstPosition + storage.offset }
Expand All @@ -71,6 +75,11 @@ final class MiMoV26MTPPositionedCache: KVCache {
storage.makeMask(n: n, windowSize: windowSize, returnArray: returnArray)
}
func copy() -> any KVCache {
if let pages = storage as? MiMoV26IndependentHistoryCache {
return MiMoV26MTPPositionedCache(
window: pages.maxSize!, firstPosition: firstPosition,
pages: pages.copy() as? MiMoV26IndependentHistoryCache)
}
let result = MiMoV26MTPPositionedCache(
window: storage.maxSize!, firstPosition: firstPosition)
let snapshot = storage.copy()
Expand All @@ -86,6 +95,10 @@ final class MiMoV26MTPPositionedCache: KVCache {
// for attention. Once that forward has captured its reads, keep a detached
// chronological suffix; metadata preserves the absolute rotary frontier.
func compactRetainedHistory() {
if let pages = storage as? MiMoV26IndependentHistoryCache {
pages.compactRetainedHistory()
return
}
let arrays = storage.state
guard arrays.count == 2 else { return }
let window = storage.maxSize!
Expand All @@ -106,7 +119,11 @@ final class MiMoV26MTPPositionedCache: KVCache {

func detachedCopy() -> MiMoV26MTPPositionedCache {
let result = copy() as! MiMoV26MTPPositionedCache
if !result.state.isEmpty { result.state = result.state.map(mimoV26MTPCopy) }
if let pages = result.storage as? MiMoV26IndependentHistoryCache {
pages.detachPages()
} else if !result.state.isEmpty {
result.state = result.state.map(mimoV26MTPCopy)
}
return result
}
}
Expand All @@ -119,15 +136,28 @@ public final class MiMoV26MTPRequestCache: Evaluatable {
fileprivate let generation: UInt64
fileprivate let layers: [MiMoV26MTPPositionedCache]
fileprivate var batchSize: Int?
let historyStorage: MiMoV26MTPHistoryStorage

fileprivate init(
owner: MiMoV26MTP, generation: UInt64, window: Int,
count: Int, basePosition: Int
count: Int, basePosition: Int, historyStorage: MiMoV26MTPHistoryStorage, dtype: DType
) {
self.owner = owner
self.generation = generation
layers = (0 ..< count).map {
MiMoV26MTPPositionedCache(window: window, firstPosition: basePosition + $0 + 1)
self.historyStorage = historyStorage
let request = UUID()
let model = UUID()
let geometry = owner.configuration.slidingAttention
layers = (0 ..< count).map { depth in
let pages: MiMoV26IndependentHistoryCache? =
historyStorage == .paged
? .init(
modelIdentity: model, requestIdentity: request, layerIndex: depth,
maximumContext: owner.configuration.maxPositionEmbeddings,
heads: geometry.keyValueHeads, keyWidth: geometry.headDim,
valueWidth: geometry.valueHeadDim, dtype: dtype, window: window) : nil
return MiMoV26MTPPositionedCache(
window: window, firstPosition: basePosition + depth + 1, pages: pages)
}
}
public var nextTokenPositions: [Int] { layers.map(\.offset) }
Expand All @@ -144,6 +174,7 @@ public final class MiMoV26MTPRequestCache: Evaluatable {
private init(copying source: MiMoV26MTPRequestCache) {
owner = source.owner
generation = source.generation
historyStorage = source.historyStorage
layers = source.layers.map { $0.detachedCopy() }
batchSize = source.batchSize
}
Expand All @@ -154,7 +185,7 @@ public final class MiMoV26MTPRequestCache: Evaluatable {
// Validate raw storage and metadata BEFORE RotatingKVCache.state can slice.
// Full rings stay in their original physical order with their exact idx.
func prefixHeads(count: Int, expectedOwner: MiMoV26MTP) -> [MiMoV26MTPPrefixHead]? {
guard owner === expectedOwner, expectedOwner.isLoaded,
guard historyStorage == .contiguous, owner === expectedOwner, expectedOwner.isLoaded,
generation == expectedOwner.loadedGeneration, batchSize == 1,
layers.count == 3, count >= 4,
count < expectedOwner.configuration.maxPositionEmbeddings
Expand Down Expand Up @@ -195,7 +226,8 @@ public final class MiMoV26MTPRequestCache: Evaluatable {
_ heads: [MiMoV26MTPPrefixHead], count: Int,
expectedOwner: MiMoV26MTP
) -> Bool {
guard owner === expectedOwner, generation == expectedOwner.loadedGeneration,
guard historyStorage == .contiguous, owner === expectedOwner,
generation == expectedOwner.loadedGeneration,
expectedOwner.isLoaded, batchSize == nil, layers.count == 3,
layers.allSatisfy({ $0.innerState().isEmpty && $0.storage.offset == 0 }),
heads.count == 3,
Expand Down Expand Up @@ -463,14 +495,18 @@ public final class MiMoV26MTP: Module {
/// Begins an explicitly supplied history segment. A nonzero base does not
/// reconstruct earlier context: callers must replay the required window.
/// It is not a prefix-cache restore or speculative transaction constructor.
public func newCache(basePosition: Int = 0) throws -> MiMoV26MTPRequestCache {
public func newCache(
basePosition: Int = 0, historyStorage: MiMoV26MTPHistoryStorage = .contiguous
) throws -> MiMoV26MTPRequestCache {
guard basePosition >= 0, basePosition < configuration.maxPositionEmbeddings - headCount,
targetOwner.target != nil
let target = targetOwner.target,
historyStorage == .contiguous || [.bfloat16, .float32].contains(target.activationDType)
else { throw MiMoV26MTPError.invalidHistory("invalid live owner/base position") }
return MiMoV26MTPRequestCache(
owner: self, generation: weightGeneration,
window: configuration.slidingWindow, count: headCount,
basePosition: basePosition)
basePosition: basePosition, historyStorage: historyStorage,
dtype: target.activationDType)
}

/// Every depth consumes the same normalized target feature. MiMoV2MTP is
Expand Down Expand Up @@ -546,7 +582,8 @@ public final class MiMoV26MTP: Module {
throw MiMoV26MTPError.contextExceeded
}
let firstTokenPosition = features.firstPosition + advance
guard cache.layers[depth].offset == firstTokenPosition,
guard cache.historyStorage == .contiguous || batch == 1,
cache.layers[depth].offset == firstTokenPosition,
cache.batchSize == nil || cache.batchSize == batch
else {
throw MiMoV26MTPError.invalidHistory(
Expand Down
40 changes: 36 additions & 4 deletions Libraries/MLXLLM/Models/MiMo/MiMoV26MTPAssistant.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public final class MiMoV26MTPAssistant: CBv2MTPRequestStatefulDrafter,
weak var target: MiMoV26TextModel?
let predictor: MiMoV26MTP
let generation: UInt64
public let historyStorage: MiMoV26MTPHistoryStorage
/// Immutable per-loaded-binding choice. Rectangular is an experimental
/// target scoring strategy, not a declaration of numerical equivalence.
public let verificationMode: CBv2MTPVerificationMode
Expand All @@ -22,7 +23,8 @@ public final class MiMoV26MTPAssistant: CBv2MTPRequestStatefulDrafter,
public init(
target: MiMoV26TextModel, predictor: MiMoV26MTP,
retaining owner: AnyObject? = nil,
verificationMode: CBv2MTPVerificationMode = .serialTarget
verificationMode: CBv2MTPVerificationMode = .serialTarget,
historyStorage: MiMoV26MTPHistoryStorage = .contiguous
) throws {
guard verificationMode == .serialTarget || verificationMode == .rectangular else {
throw MiMoV26MTPError.unsupportedConfiguration(
Expand All @@ -35,6 +37,7 @@ public final class MiMoV26MTPAssistant: CBv2MTPRequestStatefulDrafter,
loadLifetimeOwner = owner
generation = predictor.loadedGeneration
self.verificationMode = verificationMode
self.historyStorage = historyStorage
}

func isCompatible(with target: MiMoV26TextModel) -> Bool {
Expand Down Expand Up @@ -89,7 +92,9 @@ public final class MiMoV26MTPAssistant: CBv2MTPRequestStatefulDrafter,
-> CBv2MTPBoundedAllocationSpec?
{
guard let target, isCompatible(with: target) else { return nil }
return Self.boundedRequestAllocation(configuration: predictor.configuration, limits: limits)
return Self.boundedRequestAllocation(
configuration: predictor.configuration, limits: limits,
historyStorage: historyStorage)
}

/// Metadata-only shape proof, intentionally independent of native array
Expand All @@ -99,7 +104,8 @@ public final class MiMoV26MTPAssistant: CBv2MTPRequestStatefulDrafter,
/// they are not an assertion that kernel-internal workspace is zero.
static func boundedRequestAllocation(
configuration c: MiMoV26Configuration,
limits: CBv2MTPAllocationLimits
limits: CBv2MTPAllocationLimits,
historyStorage: MiMoV26MTPHistoryStorage = .contiguous
) -> CBv2MTPBoundedAllocationSpec? {
let g = c.slidingAttention
let w = c.slidingWindow
Expand Down Expand Up @@ -188,6 +194,31 @@ public final class MiMoV26MTPAssistant: CBv2MTPRequestStatefulDrafter,
let hostBytes = add(64 << 10, tokenHostBytes)
else { return nil }

if historyStorage == .paged {
// Keep the complete prior envelope. Per-page allocation rounding
// is additional: four banks cover settled/speculative pages and
// prior measured contexts; each transient append/repack is priced
// separately before the normal native completion fence retires it.
let page = MiMoV26PagedKVLayout.pageTokens
guard let rounded = add(w, page - 1) else { return nil }
let residentCount = (rounded / page).multipliedReportingOverflow(by: 12)
guard !residentCount.overflow,
append(&resident, [g.keyValueHeads, page, g.headDim], residentCount.partialValue),
append(
&resident, [g.keyValueHeads, page, g.valueHeadDim], residentCount.partialValue)
else { return nil }
for rows in [limits.maximumPrefillTokens, 3, 1] {
guard let extent = add(w, rows), let rounded = add(extent, page - 1) else {
return nil
}
let count = (rounded / page).multipliedReportingOverflow(by: 12)
guard !count.overflow,
append(&working, [g.keyValueHeads, page, g.headDim], count.partialValue),
append(&working, [g.keyValueHeads, page, g.valueHeadDim], count.partialValue)
else { return nil }
}
}

// Independent where-copy predicates, scalar/index temporaries, and
// tiny token concatenations. Four-byte extents bound Bool predicates.
guard append(&working, [4], 128) else { return nil }
Expand All @@ -200,7 +231,8 @@ public final class MiMoV26MTPAssistant: CBv2MTPRequestStatefulDrafter,
throw MiMoV26MTPError.incompatibleOwner
}
return MiMoV26MTPState(
owner: self, generation: generation, cache: try predictor.newCache())
owner: self, generation: generation,
cache: try predictor.newCache(historyStorage: historyStorage))
} catch { preconditionFailure("MiMo MTP request construction: \(error)") }
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ extension MiMoV26MTPAssistant: CBv2HistoricalMTPPrefixCheckpointCoding {
}

private var prefixConfiguration: MiMoV26Configuration? {
guard let target, isCompatible(with: target), target.activationDType == .bfloat16,
guard historyStorage == .contiguous, let target, isCompatible(with: target),
target.activationDType == .bfloat16,
predictor.headCount == 3
else { return nil }
return predictor.configuration
Expand Down
Loading
Loading