diff --git a/Libraries/MLXLLM/Models/MiMo.swift b/Libraries/MLXLLM/Models/MiMo/MiMo.swift similarity index 100% rename from Libraries/MLXLLM/Models/MiMo.swift rename to Libraries/MLXLLM/Models/MiMo/MiMo.swift diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26Attention.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26Attention.swift new file mode 100644 index 0000000000..fbcba1bd5f --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26Attention.swift @@ -0,0 +1,77 @@ +// Copyright © 2026 Eigen Labs. +// Native MiMo V2.6 text attention. Architecture reference: XiaomiMiMo +// MiMo-V2.6-Flash-RL, revision 5711b268169967567844e1e560e8a3966da959b1. + +import MLX +import MLXLMCommon +import MLXNN + +/// Unequal K/V widths are intentional. Do not pad values to the key width: +/// that changes the cache/storage contract and adds unnecessary residency. +final class MiMoV26Attention: Module { + let geometry: MiMoV26AttentionGeometry + let scale: Float + let valueScale: Float + let rope: RoPE + + @ModuleInfo(key: "q_proj") var qProj: Linear + @ModuleInfo(key: "k_proj") var kProj: Linear + @ModuleInfo(key: "v_proj") var vProj: Linear + @ModuleInfo(key: "o_proj") var oProj: Linear + @ParameterInfo(key: "attention_sink_bias") var attentionSinkBias: MLXArray? + + init(_ config: MiMoV26Configuration, geometry: MiMoV26AttentionGeometry) { + self.geometry = geometry + scale = 1 / Float(geometry.headDim).squareRoot() + valueScale = Float(config.attentionValueScale) + rope = RoPE( + dimensions: geometry.rotaryDimensions, traditional: false, + base: Float(geometry.ropeTheta)) + _qProj.wrappedValue = Linear( + config.hiddenSize, geometry.queryHeads * geometry.headDim, + bias: config.attentionBias) + _kProj.wrappedValue = Linear( + config.hiddenSize, geometry.keyValueHeads * geometry.headDim, + bias: config.attentionBias) + _vProj.wrappedValue = Linear( + config.hiddenSize, geometry.keyValueHeads * geometry.valueHeadDim, + bias: config.attentionBias) + _oProj.wrappedValue = Linear( + geometry.queryHeads * geometry.valueHeadDim, + config.hiddenSize, bias: false) + _attentionSinkBias.wrappedValue = + geometry.hasSinks ? MLXArray.zeros([geometry.queryHeads]) : nil + // No updateMissing override: a missing learned sink must fail strict loading. + } + + /// The text component validates cache kinds before any layer mutates state. + /// CBv2 integration needs its own unequal-width cache contract and is not + /// enabled by this ordinary-cache component. + func callAsFunction( + _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: KVCache? + ) -> MLXArray { + let (batch, length) = (x.dim(0), x.dim(1)) + var q = qProj(x).reshaped(batch, length, geometry.queryHeads, geometry.headDim) + .transposed(0, 2, 1, 3) + var k = kProj(x).reshaped(batch, length, geometry.keyValueHeads, geometry.headDim) + .transposed(0, 2, 1, 3) + var v = vProj(x).reshaped(batch, length, geometry.keyValueHeads, geometry.valueHeadDim) + .transposed(0, 2, 1, 3) + // Scaling is part of the native model and happens before cache insertion. + v = v * valueScale + q = applyRotaryPosition(rope, to: q, cache: cache) + k = applyRotaryPosition(rope, to: k, cache: cache) + if let cache { + (k, v) = cache.update(keys: k, values: v) + } + let attended = + MiMoV26NAXAttention.tryAttention( + queries: q, keys: k, values: v, scale: scale, mask: mask, + sinks: attentionSinkBias) + ?? MLXFast.scaledDotProductAttention( + queries: q, keys: k, values: v, scale: scale, mask: mask, + sinks: attentionSinkBias) + return oProj(attended.transposed(0, 2, 1, 3).reshaped(batch, length, -1)) + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26AudioInputConfiguration.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26AudioInputConfiguration.swift new file mode 100644 index 0000000000..e26d971681 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26AudioInputConfiguration.swift @@ -0,0 +1,194 @@ +// Copyright © 2026 Eigen Labs. +// HF5711 codec; pinned SGLang67/Torchaudio2.11 PCM frontend. No MLX dependency. +import Foundation + +public enum MiMoV26AudioInputError: Error, Equatable, Sendable { + case configuration(String) + case input(String) + case limit(String) + case weights(String) + case weightsNotLoaded, cancelled, nonfiniteResult +} + +/// Input codec, distinct from MiMoV26AudioConfiguration (the patch encoder). +public struct MiMoV26AudioInputConfiguration: Equatable, Sendable { + public static let codecProfile = "hf5711-bf16-registered-rope-rvq-v1" + public static let frontendProfile = "sglang67-torchaudio2.11-pcm-default-f32-v1" + public let rawFields: [String: MiMoV26JSONValue] + public let hiddenSize, heads, headDim, layers, ffnSize, skipLayerIndex: Int + public let localLookBack, quantizers: Int + public let codebookSizes: [Int] + public let sampleRate, fftSize, hopLength, windowSize, melBands: Int + public let segmentSize, groupSize, maximumGroupValidMelFrames: Int + public let ropeTheta: Float + public let maxAudioSecondsMetadata: Int + public let audioStartToken, audioToken, audioEndToken: Int + let synthetic: Bool + + public init(sidecarJSON: Data, mainConfiguration: MiMoV26Configuration) throws { + guard !sidecarJSON.isEmpty, sidecarJSON.count <= 1 << 20 else { + throw MiMoV26AudioInputError.limit("audio sidecar config bytes") + } + let fields = try JSONDecoder().decode([String: MiMoV26JSONValue].self, from: sidecarJSON) + try self.init(fields: fields, synthetic: false) + guard let audio = mainConfiguration.audio, let p = mainConfiguration.processorFields, + audio.channels == quantizers, audio.groupSize == groupSize, + audio.segmentSize == segmentSize + else { + throw MiMoV26AudioInputError.configuration("main audio-patch/codec contract mismatch") + } + for (name, value) in [ + "audio_avg_pooler": 2, "audio_channels": quantizers, "audio_group_size": groupSize, + "audio_hop_length": hopLength, "audio_kernel_size": 3, "audio_n_mels": melBands, + "audio_nfft": fftSize, + "audio_sampling_rate": sampleRate, "audio_segment_size": segmentSize, + "audio_stride_size": 2, + "audio_window_size": windowSize, "audio_start_token_id": audioStartToken, + "audio_token_id": audioToken, "audio_end_token_id": audioEndToken, "audio_fmin": 0, + ] { + guard try Self.integer(p, name) == value else { + throw MiMoV26AudioInputError.configuration(name) + } + } + guard p["audio_fmax"] == .null, + mainConfiguration.tokenIDs["audio_start_token_id"] == audioStartToken, + mainConfiguration.tokenIDs["audio_token_id"] == audioToken, + mainConfiguration.tokenIDs["audio_end_token_id"] == audioEndToken + else { + throw MiMoV26AudioInputError.configuration( + "main audio token/frontend metadata mismatch") + } + } + + public func encodedSidecar() throws -> Data { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return try encoder.encode(rawFields) + } + public func usesLocalAttention(layer: Int) -> Bool { layer % 2 == 0 } + public func allowsAttention(query: Int, key: Int, layer: Int) -> Bool { + key >= 0 && query >= key + && (!usesLocalAttention(layer: layer) || query - key <= localLookBack) + } + + static func integer(_ fields: [String: MiMoV26JSONValue], _ key: String) throws -> Int { + guard case .number(let value) = fields[key] else { + throw MiMoV26AudioInputError.configuration(key) + } + let number = NSDecimalNumber(decimal: value) + let integer = number.int64Value + guard Decimal(integer) == value, let result = Int(exactly: integer) else { + throw MiMoV26AudioInputError.configuration(key + " is not a representable integer") + } + return result + } + private init(fields: [String: MiMoV26JSONValue], synthetic: Bool) throws { + self.rawFields = fields + self.synthetic = synthetic + func int(_ key: String) throws -> Int { try Self.integer(fields, key) } + hiddenSize = try int("d_model") + heads = try int("encoder_attention_heads") + layers = try int("encoder_layers") + ffnSize = try int("encoder_ffn_dim") + let skip = try int("encoder_skip_layer_id") + guard hiddenSize > 0, hiddenSize <= Int(Int32.max), heads > 0, + hiddenSize % heads == 0, (hiddenSize / heads) % 2 == 0, + layers > 0, layers <= 1024, ffnSize > 0, ffnSize <= Int(Int32.max), + (1 ... layers).contains(skip) + else { throw MiMoV26AudioInputError.configuration("codec dimensions") } + headDim = hiddenSize / heads + skipLayerIndex = skip - 1 + guard case .array(let window) = fields["encoder_attn_window_size"], window.count == 2, + case .number(let left) = window[0], case .number(let right) = window[1], right == 0, + left >= 0, left <= Decimal(Int32.max), + Decimal(NSDecimalNumber(decimal: left).intValue) == left + else { + throw MiMoV26AudioInputError.configuration("encoder_attn_window_size") + } + localLookBack = NSDecimalNumber(decimal: left).intValue + guard fields["encoder_causal"] == .bool(true), fields["hybrid_attention"] == .bool(true), + try int("swa_per_block") == 2, try int("hybrid_block_size") == 8, + fields["scale_embedding"] == .bool(false), + fields["activation_function"] == .string("gelu"), + fields["position_embedding_type"] == .string("rope"), + fields["rope_type"] == .string("default"), + fields["ln_type"] == .string("LayerNorm"), try int("kernel_size") == 3, + try int("stride_size") == 2, try int("avg_pooler") == 2 + else { + throw MiMoV26AudioInputError.configuration("unsupported HF5711 codec semantics") + } + let theta = try int("rope_theta") + guard theta == 10000 else { throw MiMoV26AudioInputError.configuration("rope_theta") } + ropeTheta = Float(theta) + quantizers = try int("num_quantizers") + guard case .array(let bins) = fields["codebook_size"], bins.count == quantizers, + quantizers > 0 + else { + throw MiMoV26AudioInputError.configuration("codebook_size") + } + codebookSizes = try bins.map { value in + let n = try Self.integer(["value": value], "value") + guard n > 1, n <= 1024 else { + throw MiMoV26AudioInputError.configuration("codebook range") + } + return n + } + sampleRate = try int("sampling_rate") + fftSize = try int("nfft") + hopLength = try int("hop_length") + windowSize = try int("window_size") + melBands = try int("n_mels") + maxAudioSecondsMetadata = try int("max_audio_seconds") // metadata, not an execution cap + guard sampleRate == 24000, fftSize == 960, hopLength == 240, windowSize == 960, + melBands > 0, melBands <= 128, maxAudioSecondsMetadata > 0, + try int("fmin") == 0, fields["fmax"] == .null + else { + throw MiMoV26AudioInputError.configuration("frontend geometry") + } + segmentSize = 6000 + groupSize = 4 + maximumGroupValidMelFrames = 256000 + audioStartToken = 151673 + audioToken = 151669 + audioEndToken = 151674 + if !synthetic { + guard hiddenSize == 1024, heads == 16, layers == 24, ffnSize == 4096, skip == 3, + localLookBack == 128, melBands == 128, quantizers == 20, + codebookSizes == [1024, 1024, 256] + Array(repeating: 128, count: 17) + else { + throw MiMoV26AudioInputError.configuration( + "not selected MiMo V2.6 input codec geometry") + } + } + } + + /// Internal fixture construction executes the same algorithm at tiny shapes; + /// no public loader/serving path accepts this as the selected artifact. + static func fixture( + hiddenSize: Int = 8, heads: Int = 2, layers: Int = 4, + melBands: Int = 2, bins: [Int] = [4, 4], lookBack: Int = 2 + ) throws -> Self { + guard hiddenSize > 0, hiddenSize <= Int(Int32.max) / 2 else { + throw MiMoV26AudioInputError.configuration("fixture width") + } + var f: [String: MiMoV26JSONValue] = [ + "encoder_causal": .bool(true), "hybrid_attention": .bool(true), + "scale_embedding": .bool(false), "activation_function": .string("gelu"), + "position_embedding_type": .string("rope"), + "rope_type": .string("default"), "ln_type": .string("LayerNorm"), "fmax": .null, + ] + for (key, value) in [ + "d_model": hiddenSize, "encoder_attention_heads": heads, "encoder_layers": layers, + "encoder_ffn_dim": hiddenSize * 2, "encoder_skip_layer_id": min(3, layers), + "swa_per_block": 2, "hybrid_block_size": 8, + "kernel_size": 3, "stride_size": 2, "avg_pooler": 2, "rope_theta": 10000, + "num_quantizers": bins.count, + "sampling_rate": 24000, "nfft": 960, "hop_length": 240, "window_size": 960, + "n_mels": melBands, + "max_audio_seconds": 300, "fmin": 0, + ] { f[key] = .number(Decimal(value)) } + f["codebook_size"] = .array(bins.map { .number(Decimal($0)) }) + f["encoder_attn_window_size"] = .array([.number(Decimal(lookBack)), .number(0)]) + return try .init(fields: f, synthetic: true) + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26AudioInputPlan.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26AudioInputPlan.swift new file mode 100644 index 0000000000..429f58eee8 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26AudioInputPlan.swift @@ -0,0 +1,397 @@ +// Copyright © 2026 Eigen Labs. Pure checked metadata; no native execution. +import Foundation + +public enum MiMoV26AudioChecked { + public static func add(_ a: Int, _ b: Int, _ label: String) throws -> Int { + let (n, o) = a.addingReportingOverflow(b) + guard a >= 0, b >= 0, !o else { throw MiMoV26AudioInputError.limit(label + " overflow") } + return n + } + public static func product(_ values: [Int], _ label: String) throws -> Int { + try values.reduce(1) { a, b in + let (n, o) = a.multipliedReportingOverflow(by: b) + guard a >= 0, b >= 0, !o else { + throw MiMoV26AudioInputError.limit(label + " overflow") + } + return n + } + } + public static func ceilDivide(_ n: Int, _ d: Int) throws -> Int { + guard n >= 0, d > 0 else { throw MiMoV26AudioInputError.limit("invalid division") } + return n / d + (n % d == 0 ? 0 : 1) + } +} + +public struct MiMoV26AudioPCMDescriptor: Codable, Equatable, Sendable { + public let sourceIdentity: String + public let channels, frameCount, sampleRate: Int + public init(sourceIdentity: String, channels: Int, frameCount: Int, sampleRate: Int) { + self.sourceIdentity = sourceIdentity + self.channels = channels + self.frameCount = frameCount + self.sampleRate = sampleRate + } +} + +/// Explicit caller bounds, not advertised model/context capacity or a process +/// memory permit. Actual native allocations require root's separate admission. +public struct MiMoV26AudioInputLimits: Equatable, Sendable { + public let maximumClips, maximumChannels, maximumSampleRate: Int + public let maximumInputSamples, maximumResampledSamples, maximumResampleCoefficients: Int + public let maximumMelFrames, maximumSegments, maximumPaddedMelFrames: Int + public let maximumWorkingElements, frontendFrameBlockSize, rvqTileFrames: Int + public init( + maximumClips: Int, maximumChannels: Int, maximumSampleRate: Int, + maximumInputSamples: Int, maximumResampledSamples: Int, maximumResampleCoefficients: Int, + maximumMelFrames: Int, maximumSegments: Int, maximumPaddedMelFrames: Int, + maximumWorkingElements: Int, frontendFrameBlockSize: Int, rvqTileFrames: Int + ) { + self.maximumClips = maximumClips + self.maximumChannels = maximumChannels + self.maximumSampleRate = maximumSampleRate + self.maximumInputSamples = maximumInputSamples + self.maximumResampledSamples = maximumResampledSamples + self.maximumResampleCoefficients = maximumResampleCoefficients + self.maximumMelFrames = maximumMelFrames + self.maximumSegments = maximumSegments + self.maximumPaddedMelFrames = maximumPaddedMelFrames + self.maximumWorkingElements = maximumWorkingElements + self.frontendFrameBlockSize = frontendFrameBlockSize + self.rvqTileFrames = rvqTileFrames + } + func validate() throws { + guard + [ + maximumClips, maximumChannels, maximumSampleRate, maximumInputSamples, + maximumResampledSamples, + maximumResampleCoefficients, maximumMelFrames, maximumSegments, + maximumPaddedMelFrames, + maximumWorkingElements, frontendFrameBlockSize, rvqTileFrames, + ].allSatisfy({ $0 > 0 }), + [maximumChannels, maximumSampleRate, frontendFrameBlockSize, rvqTileFrames].allSatisfy({ + $0 <= Int(Int32.max) + }) + else { + throw MiMoV26AudioInputError.limit("invalid explicit audio bounds") + } + } +} + +public struct MiMoV26AudioResamplePlan: Codable, Equatable, Sendable { + public let originalRate, targetRate, originalFrames, outputFrames: Int + public let originalRatio, targetRatio, width, taps, coefficients: Int + public var isIdentity: Bool { originalRate == targetRate } + + public static func make( + originalRate: Int, frames: Int, targetRate: Int = 24000, + maximumCoefficients: Int + ) throws -> Self { + guard originalRate > 0, originalRate <= Int(Int32.max), targetRate > 0, + targetRate <= Int(Int32.max), frames > 0, frames <= Int(Int32.max), + maximumCoefficients > 0 + else { + throw MiMoV26AudioInputError.input("invalid resample geometry") + } + if originalRate == targetRate { + return .init( + originalRate: originalRate, targetRate: targetRate, originalFrames: frames, + outputFrames: frames, + originalRatio: 1, targetRatio: 1, width: 0, taps: 0, coefficients: 0) + } + var a = originalRate + var b = targetRate + while b != 0 { + let r = a % b + a = b + b = r + } + let p = originalRate / a + let q = targetRate / a + let base = Double(min(p, q)) * 0.99 + let support = ceil(6 * Double(p) / base) + guard support.isFinite, support <= Double(Int32.max) else { + throw MiMoV26AudioInputError.limit("resample support") + } + let width = Int(support) + let taps = try MiMoV26AudioChecked.add( + try MiMoV26AudioChecked.product([2, width], "resample taps"), p, "resample taps") + let coefficients = try MiMoV26AudioChecked.product([q, taps], "resample coefficients") + guard coefficients <= maximumCoefficients, coefficients <= Int(Int32.max) else { + throw MiMoV26AudioInputError.limit("resample coefficient ceiling/flat native shape") + } + let numerator = try MiMoV26AudioChecked.product([q, frames], "resample length") + let rawFrames = try MiMoV26AudioChecked.product( + [frames / p + 1, q], "untrimmed resample shape") + guard rawFrames <= Int(Int32.max) else { + throw MiMoV26AudioInputError.limit("untrimmed native resample shape") + } + guard numerator <= 9_007_199_254_740_992 else { + throw MiMoV26AudioInputError.limit("resample Float64 integer precision") + } + // Match pinned torchaudio's Python division -> default-F32 tensor -> + // ceil conversion, NOT exact rational ceil. Identity bypasses this. + let converted = Float(Double(numerator) / Double(p)).rounded(.up) + guard converted.isFinite, converted > 0, Double(converted) <= Double(Int32.max) else { + throw MiMoV26AudioInputError.limit("resampled frame count") + } + return .init( + originalRate: originalRate, targetRate: targetRate, originalFrames: frames, + outputFrames: Int(converted), + originalRatio: p, targetRatio: q, width: width, taps: taps, coefficients: coefficients) + } +} + +public struct MiMoV26AudioInputPlan: Equatable, Sendable { + public struct Segment: Codable, Equatable, Sendable { + public let clipIndex, melStart, melFrames, convFrames, codeFrames: Int + } + public struct Group: Codable, Equatable, Sendable { + public let segmentIndices: [Int] + public let maximumMelFrames, maximumConvFrames, pooledWidth, validMelFrames, + paddedMelFrames: Int + public func repeatsLastBeforePooling(segment: Segment) -> Bool { + segment.convFrames % 2 == 1 && segment.convFrames < maximumConvFrames + } + } + public let configuration: MiMoV26AudioInputConfiguration + public let limits: MiMoV26AudioInputLimits + public let pcmDescriptors: [MiMoV26AudioPCMDescriptor]? + public let sourceIdentities: [String] + public let resampling: [MiMoV26AudioResamplePlan] + public let melFrameCounts, codeFrameCounts, patchCounts: [Int] + public let segments: [Segment] + public let groups: [Group] + /// Logical FP32-equivalent element ceiling, not measured physical usage. + public let workingElementUpperBound: Int + public var totalCodeFrames: Int { codeFrameCounts.reduce(0, +) } + public var totalPatches: Int { patchCounts.reduce(0, +) } + + public static func make( + clips: [MiMoV26AudioPCMDescriptor], configuration: MiMoV26AudioInputConfiguration, + limits: MiMoV26AudioInputLimits + ) throws -> Self { + try limits.validate() + guard clips.count <= limits.maximumClips else { + throw MiMoV26AudioInputError.limit("audio clip count") + } + var resampling: [MiMoV26AudioResamplePlan] = [] + var mel: [Int] = [] + var inputSamples = 0 + var outputSamples = 0 + var frontWorking = 0 + for clip in clips { + guard !clip.sourceIdentity.isEmpty, clip.sourceIdentity.utf8.count <= 1024, + clip.channels > 0, clip.channels <= limits.maximumChannels, + clip.sampleRate > 0, clip.sampleRate <= limits.maximumSampleRate + else { + throw MiMoV26AudioInputError.input("PCM descriptor") + } + let count = try MiMoV26AudioChecked.product( + [clip.channels, clip.frameCount], "PCM samples") + guard count <= Int(Int32.max) else { + throw MiMoV26AudioInputError.limit("flat native PCM shape") + } + inputSamples = try MiMoV26AudioChecked.add(inputSamples, count, "total PCM") + let resample = try MiMoV26AudioResamplePlan.make( + originalRate: clip.sampleRate, frames: clip.frameCount, + targetRate: configuration.sampleRate, + maximumCoefficients: limits.maximumResampleCoefficients) + guard resample.outputFrames > configuration.fftSize / 2 else { + throw MiMoV26AudioInputError.input( + "centered reflect STFT requires more than480 resampled frames") + } + let output = try MiMoV26AudioChecked.product( + [clip.channels, resample.outputFrames], "resampled samples") + outputSamples = try MiMoV26AudioChecked.add( + outputSamples, output, "total resampled PCM") + let frames = resample.outputFrames / configuration.hopLength + 1 + resampling.append(resample) + mel.append(frames) + let rawFrames = + resample.isIdentity + ? resample.outputFrames + : try MiMoV26AudioChecked.product( + [resample.originalFrames / resample.originalRatio + 1, resample.targetRatio], + "untrimmed resample frames") + let paddedFrames = + resample.isIdentity + ? clip.frameCount + : try MiMoV26AudioChecked.add( + clip.frameCount, + MiMoV26AudioChecked.add( + resample.width, resample.width + resample.originalRatio, "resample padding"), + "padded PCM") + guard paddedFrames <= Int(Int32.max) else { + throw MiMoV26AudioInputError.limit("padded native PCM shape") + } + let rawAndPadded = try MiMoV26AudioChecked.product( + [ + clip.channels, + MiMoV26AudioChecked.add(rawFrames, paddedFrames, "resample buffers"), + ], "resample buffers") + frontWorking = try MiMoV26AudioChecked.add( + frontWorking, + MiMoV26AudioChecked.product( + [4, try MiMoV26AudioChecked.add(count, rawAndPadded, "PCM coexistence")], + "PCM coexistence"), "frontend work") + frontWorking = try MiMoV26AudioChecked.add( + frontWorking, + MiMoV26AudioChecked.product( + [4, resample.coefficients], "kernel coefficient intermediates"), "frontend work" + ) + frontWorking = try MiMoV26AudioChecked.add( + frontWorking, + MiMoV26AudioChecked.product( + [frames, configuration.fftSize, 8], "FFT/magnitude/frame graph"), + "frontend work") + } + guard inputSamples <= limits.maximumInputSamples, + outputSamples <= limits.maximumResampledSamples + else { + throw MiMoV26AudioInputError.limit("decoded/resampled audio sample ceiling") + } + return try build( + mel: mel, identities: clips.map(\.sourceIdentity), configuration: configuration, + limits: limits, + pcm: clips, resampling: resampling, frontWorking: frontWorking) + } + + /// Explicit precomputed-mel namespace, never labeled decoded PCM. + public static func makeMelInputs( + frameCounts: [Int], sourceIdentities: [String], + configuration: MiMoV26AudioInputConfiguration, limits: MiMoV26AudioInputLimits + ) throws -> Self { + try limits.validate() + return try build( + mel: frameCounts, identities: sourceIdentities, configuration: configuration, + limits: limits, + pcm: nil, resampling: [], frontWorking: 0) + } + + private static func build( + mel: [Int], identities: [String], configuration c: MiMoV26AudioInputConfiguration, + limits: MiMoV26AudioInputLimits, pcm: [MiMoV26AudioPCMDescriptor]?, + resampling: [MiMoV26AudioResamplePlan], + frontWorking: Int + ) throws -> Self { + guard mel.count == identities.count, mel.count <= limits.maximumClips, + identities.allSatisfy({ !$0.isEmpty && $0.utf8.count <= 1024 }), + mel.allSatisfy({ $0 > 0 && $0 <= Int(Int32.max) }) + else { throw MiMoV26AudioInputError.input("mel item descriptors") } + let totalMel = try mel.reduce(0) { try MiMoV26AudioChecked.add($0, $1, "total mel frames") } + guard totalMel <= limits.maximumMelFrames else { + throw MiMoV26AudioInputError.limit("mel frame ceiling") + } + var segments: [Segment] = [] + var codes = Array(repeating: 0, count: mel.count) + for (clip, length) in mel.enumerated() { + var start = 0 + while start < length { + guard segments.count < limits.maximumSegments else { + throw MiMoV26AudioInputError.limit("segment ceiling") + } + let count = min(c.segmentSize, length - start) + let conv = try MiMoV26AudioChecked.ceilDivide(count, 2) + let code = try MiMoV26AudioChecked.ceilDivide(conv, 2) + segments.append( + .init( + clipIndex: clip, melStart: start, melFrames: count, convFrames: conv, + codeFrames: code)) + codes[clip] = try MiMoV26AudioChecked.add(codes[clip], code, "per-clip code frames") + start += count + } + } + var groupIndices: [[Int]] = [] + var current: [Int] = [] + var currentSum = 0 + for (i, segment) in segments.enumerated() { + if currentSum + segment.melFrames > c.maximumGroupValidMelFrames && !current.isEmpty { + groupIndices.append(current) + current = [] + currentSum = 0 + } + current.append(i) + currentSum += segment.melFrames + } + if !current.isEmpty { groupIndices.append(current) } + var paddedTotal = 0 + var working = frontWorking + let groups = try groupIndices.map { indices -> Group in + let maximum = indices.map { segments[$0].melFrames }.max()! + let conv = try MiMoV26AudioChecked.ceilDivide(maximum, 2) + let padded = try MiMoV26AudioChecked.product( + [indices.count, maximum], "original padded mel group") + paddedTotal = try MiMoV26AudioChecked.add(paddedTotal, padded, "padded groups") + let group = Group( + segmentIndices: indices, maximumMelFrames: maximum, maximumConvFrames: conv, + pooledWidth: try MiMoV26AudioChecked.ceilDivide(conv, 2), + validMelFrames: indices.reduce(0) { $0 + segments[$1].melFrames }, + paddedMelFrames: padded) + working = try MiMoV26AudioChecked.add( + working, + MiMoV26AudioChecked.product( + [padded, c.hiddenSize, 8], "padded convolution/skip/coexistence"), "codec work") + for i in indices { + let t = segments[i].convFrames + let attention = try MiMoV26AudioChecked.product( + [t, t, c.heads, 8, c.layers], "attention graph ceiling") + let ffn = try MiMoV26AudioChecked.product( + [t, c.ffnSize, 4, c.layers], "FFN graph ceiling") + working = try MiMoV26AudioChecked.add( + working, MiMoV26AudioChecked.add(attention, ffn, "transformer graph"), + "codec work") + } + return group + } + guard paddedTotal <= limits.maximumPaddedMelFrames else { + throw MiMoV26AudioInputError.limit( + "original padded group ceiling; regrouping is forbidden") + } + let patches = try codes.map { try MiMoV26AudioChecked.ceilDivide($0, c.groupSize) } + let rvq = + totalMel == 0 + ? 0 + : try MiMoV26AudioChecked.product( + [limits.rvqTileFrames, max(c.hiddenSize, c.codebookSizes.max()!), 8, c.quantizers], + "RVQ tile graph") + working = try MiMoV26AudioChecked.add(working, rvq, "working elements") + working = try MiMoV26AudioChecked.add( + working, MiMoV26AudioChecked.product([totalMel, c.melBands, 4], "retained mels"), + "working elements") + guard working <= limits.maximumWorkingElements else { + throw MiMoV26AudioInputError.limit("audio working-element ceiling") + } + return .init( + configuration: c, limits: limits, pcmDescriptors: pcm, sourceIdentities: identities, + resampling: resampling, + melFrameCounts: mel, codeFrameCounts: codes, patchCounts: patches, segments: segments, + groups: groups, workingElementUpperBound: working) + } + + /// Canonical identity MATERIAL, not authentication. Provider must bind its + /// real decoded content/tenant/weight identities before persistent reuse. + public func preparationIdentityData() throws -> Data { + struct Record: Encodable { + let codec, frontend, inputKind: String + let configuration: [String: MiMoV26JSONValue] + let sourceIdentities: [String] + let pcm: [MiMoV26AudioPCMDescriptor]? + let resampling: [MiMoV26AudioResamplePlan] + let segments: [Segment] + let groups: [Group] + let fftBlock, rvqTile: Int + let synthetic: Bool + } + let record = Record( + codec: MiMoV26AudioInputConfiguration.codecProfile, + frontend: MiMoV26AudioInputConfiguration.frontendProfile, + inputKind: pcmDescriptors == nil ? "mel" : "pcm", + configuration: configuration.rawFields, sourceIdentities: sourceIdentities, + pcm: pcmDescriptors, resampling: resampling, + segments: segments, groups: groups, fftBlock: limits.frontendFrameBlockSize, + rvqTile: limits.rvqTileFrames, synthetic: configuration.synthetic) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return try encoder.encode(record) + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26CBv2.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26CBv2.swift new file mode 100644 index 0000000000..69f4f34f1e --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26CBv2.swift @@ -0,0 +1,1349 @@ +// Copyright © 2026 Eigen Labs. +// Unregistered contiguous CBv2 adapter over the existing native MiMo target. +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +public enum MiMoV26CBv2Error: Error, Equatable, Sendable { + case invalidInput(String) + case invalidCache(layer: Int, reason: String) + case contextExceeded + case unloadedPrecision + case nativeProbeRequired +} + +/// Ownership metadata only. Entries never retain rows, arrays or request state. +final class MiMoV26CBv2RowLedger { + final class Entry { + weak var row: (any CBv2SequenceKV)? + let backend: UUID + let request: UUID + let layer: Int + init(row: any CBv2SequenceKV, backend: UUID, request: UUID, layer: Int) { + self.row = row + self.backend = backend + self.request = request + self.layer = layer + } + } + private let lock = NSLock() + private var entries: [ObjectIdentifier: Entry] = [:] + + // Construction/retirement boundaries prune weak tombstones. Lookup stays + // O(1) in the engine hot path and never retains a row merely for cleanup. + private func pruneDeadRowsLocked() { entries = entries.filter { $0.value.row != nil } } + var metadataEntryCount: Int { + lock.lock() + defer { lock.unlock() } + return entries.count + } + + func register(_ rows: [CBv2SequenceKV?], backend: UUID) throws { + lock.lock() + defer { lock.unlock() } + pruneDeadRowsLocked() + let request = UUID() + var pending: [(ObjectIdentifier, Entry)] = [] + for (index, value) in rows.enumerated() { + guard let row = value else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "backend omitted owning row") + } + let key = ObjectIdentifier(row) + guard entries[key]?.row == nil, !pending.contains(where: { $0.0 == key }) else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "backend reused a live row") + } + pending.append((key, Entry(row: row, backend: backend, request: request, layer: index))) + } + for (key, entry) in pending { entries[key] = entry } + } + func identity(_ row: any CBv2SequenceKV, layer: Int) throws -> UUID { + lock.lock() + defer { lock.unlock() } + guard let entry = entries[ObjectIdentifier(row)], entry.row === row, entry.layer == layer + else { + throw MiMoV26CBv2Error.invalidCache( + layer: layer, reason: "foreign, released or wrong-layer row") + } + return entry.request + } + func remove(_ rows: [CBv2SequenceKV?], backend: UUID) throws { + lock.lock() + defer { lock.unlock() } + pruneDeadRowsLocked() + var keys = Set() + var request: UUID? + for (index, value) in rows.enumerated() { + guard let row = value, let entry = entries[ObjectIdentifier(row)], entry.row === row, + entry.backend == backend, entry.layer == index, + keys.insert(ObjectIdentifier(row)).inserted, + request == nil || request == entry.request + else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "foreign or mixed request release") + } + request = entry.request + } + for key in keys { entries.removeValue(forKey: key) } + } + func invalidate(backend: UUID) { + lock.lock() + defer { lock.unlock() } + entries = entries.filter { $0.value.backend != backend && $0.value.row != nil } + } +} + +/// Thin owner facade over the existing contiguous allocator/accounting. It +/// adds row provenance only, with no second row implementation or tensor copy. +public final class MiMoV26CBv2Backend: CBv2KVBackend, CBv2ContiguousHistoricalBackend { + private let backend: CBv2ContiguousKVBackend + private let ledger: MiMoV26CBv2RowLedger + private let owner = UUID() + private let expectedKinds: [CBv2LayerKind] + private let maximumContext: Int + fileprivate init( + kinds: [CBv2LayerKind], context: Int, dtype: DType, bytesCapacity: Int, + ledger: MiMoV26CBv2RowLedger + ) { + expectedKinds = kinds + maximumContext = context + self.ledger = ledger + backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: bytesCapacity, kvDType: dtype)) + } + public var bytesCapacity: Int { backend.bytesCapacity } + public var bytesInUse: Int { backend.bytesInUse } + public var bytesReserved: Int { backend.bytesReserved } + public var prefixReuseBackend: CBv2PrefixReuseBackend { .unknown } + public func updateBytesCapacity(_ bytes: Int) { backend.updateBytesCapacity(bytes) } + public func makeSequenceState(layerKinds: [CBv2LayerKind], promptLength: Int, maxLength: Int) + throws -> [CBv2SequenceKV?] + { + guard layerKinds == expectedKinds, maxLength <= maximumContext else { + throw MiMoV26CBv2Error.invalidInput("backend target layout/context mismatch") + } + let rows = try backend.makeSequenceState( + layerKinds: layerKinds, promptLength: promptLength, maxLength: maxLength) + do { try ledger.register(rows, backend: owner) } catch { + backend.release(rows) + throw error + } + return rows + } + public func releaseValidated(_ state: [CBv2SequenceKV?]) throws { + guard state.count == expectedKinds.count else { + throw MiMoV26CBv2Error.invalidInput("release requires a complete request") + } + try ledger.remove(state, backend: owner) + backend.release(state) + } + package func adoptContiguousHistoricalState( + _ state: [CBv2SequenceKV?], codec: CBv2CompleteCheckpointCodec, + layerKinds: [CBv2LayerKind], position: Int, + requestID: CBv2RequestID, maximumSequenceLength: Int + ) throws { + guard layerKinds == expectedKinds, state.count == expectedKinds.count, + maximumSequenceLength <= maximumContext, position > 1 + else { + throw MiMoV26CBv2Error.invalidInput( + "historical checkpoint target layout/context mismatch") + } + // Validate the real staged lease, native widths/dtypes and fresh request + // transfer before publishing rows into this model's exact ownership map. + try backend.adoptContiguousHistoricalState( + state, codec: codec, layerKinds: layerKinds, + position: position, requestID: requestID, maximumSequenceLength: maximumSequenceLength) + do { try ledger.register(state, backend: owner) } catch { + backend.release(state) + throw error + } + } + public func release(_ state: [CBv2SequenceKV?]) { + do { try releaseValidated(state) } catch { + preconditionFailure("MiMo CBv2 owned release invariant: \(error)") + } + } + deinit { ledger.invalidate(backend: owner) } +} + +/// Private model provenance facade; it is not a generic paging capability. +private protocol MiMoV26OwnedLayerCache: CBv2AttendingLayerCache, KVCache { + var owner: UUID { get } + var boundOffsets: [Int] { get } + var mtpSerializesRectangularAttention: Bool { get set } + var mtpBatchesRectangularAttention: Bool { get set } +} + +/// Owns a causal-only common cache. No span-binding interface is exposed, so +/// external callers cannot install Gemma bidirectional overlays on MiMo. +private final class MiMoV26ContiguousLayerCache: MiMoV26OwnedLayerCache, + CBv2MTPRectangularSerializing +{ + let owner: UUID + var blockBatchBudget: MiMoV26BlockBatchBudget? { + get { base.mimoV26BlockBatchBudget } + set { base.mimoV26BlockBatchBudget = newValue } + } + private let base: CBv2LayerCache + private(set) var boundOffsets: [Int] = [] + var layerIndex: Int { base.layerIndex } + var kind: CBv2LayerKind { base.kind } + var rows: [CBv2SequenceKV] { base.rows } + var positionOffsets: MLXArray { base.positionOffsets } + // The exact owned base implements serial per-query causal/SWA attention. + // No cache substitution, span capability, or attention kernel is added. + var mtpSerializesRectangularAttention: Bool { + get { base.mtpSerializesRectangularAttention } + set { base.mtpSerializesRectangularAttention = newValue } + } + var mtpBatchesRectangularAttention: Bool { + get { base.mtpBatchesRectangularAttention } + set { base.mtpBatchesRectangularAttention = newValue } + } + + init(owner: UUID, index: Int, kind: CBv2LayerKind) { + self.owner = owner + base = CBv2LayerCache( + layerIndex: index, kind: kind, + mimoV26NAXAttention: true) + } + func setRows(_ rows: [CBv2SequenceKV]) { + // Engine binding is nonthrowing; external callers use adapter.bindRows + // for a recoverable all-layer preflight before any cache is rebound. + precondition( + rows.allSatisfy { $0.absoluteOffset >= 0 && $0.absoluteOffset <= Int(Int32.max) }) + boundOffsets = rows.map(\.absoluteOffset) + base.setRows(rows) + } + func updateAndAttend( + queries: MLXArray, keys: MLXArray, values: MLXArray, + scale: Float, sinks: MLXArray? + ) -> MLXArray { + let result = base.updateAndAttend( + queries: queries, keys: keys, values: values, + scale: scale, sinks: sinks) + let length = queries.dim(2) + boundOffsets = boundOffsets.map { $0 + length } + return result + } + func attendBorrowing( + source: CBv2AttendingLayerCache, queries: MLXArray, + scale: Float, sinks: MLXArray? + ) -> MLXArray { + preconditionFailure("MiMo V2.6 owns every layer's K/V; no borrowed attention") + } + // EngineLoopV2 evaluates KVCache.innerState to collapse lazy position/KV + // graphs. Preserve this bridge without permitting legacy update dispatch. + func innerState() -> [MLXArray] { base.innerState() } + var offset: Int { base.offset } + var maxSize: Int? { base.maxSize } + var state: [MLXArray] { + get { [] } + set { preconditionFailure("MiMo CBv2 cache has request-owned rows") } + } + var metaState: [String] { + get { [] } + set { preconditionFailure("MiMo CBv2 cache has no legacy metadata") } + } + var isTrimmable: Bool { false } + func trim(_ n: Int) -> Int { 0 } + func copy() -> any KVCache { + preconditionFailure("Copy request rows through their owning backend") + } + func makeMask(n: Int, windowSize: Int?, returnArray: Bool) + -> MLXFast.ScaledDotProductAttentionMaskMode + { + preconditionFailure("MiMo CBv2 attention owns its row-local masks") + } + func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + preconditionFailure("MiMo CBv2 must call updateAndAttend") + } +} + +/// Genuine page-backed attention facade over the SAME PagedLayerCache that +/// consumes pool-issued write/read tickets. No contiguous fallback or snapshot +/// gather is used to validate native row ownership. +private final class MiMoV26PagedLayerCache: MiMoV26OwnedLayerCache, CBv2KVSourceChunkRetaining { + let owner: UUID + private let base: PagedLayerCache + private(set) var boundOffsets: [Int] = [] + init(owner: UUID, base: PagedLayerCache) { + self.owner = owner + self.base = base + } + var layerIndex: Int { base.layerIndex } + var kind: CBv2LayerKind { base.kind } + var rows: [CBv2SequenceKV] { base.rows } + var positionOffsets: MLXArray { base.positionOffsets } + // Keep the actual bank's borrower policy visible through the provenance + // facade. Hiding it leaves the inner standalone default ON, retaining a + // final prefill loan even though no MiMo layer borrows another layer's KV. + func setRetainsChunkForBorrowers(_ retains: Bool) { + base.setRetainsChunkForBorrowers(retains) + } + fileprivate var sourceRetentionWitnessForTesting: + (retainsForBorrowers: Bool, chunks: Int, workLoans: Int) + { + base.retainedSourceChunkWitnessForTesting + } + // This facade intentionally does NOT conform to the public MTP capability. + // Serial-target MTP needs no rectangular cache capability. An explicitly + // requested rectangular mode is refused by the native paged producer. + var mtpSerializesRectangularAttention: Bool { + get { false } + set { precondition(!newValue, "native paged MTP is not issued") } + } + var mtpBatchesRectangularAttention: Bool { + get { false } + set { precondition(!newValue, "native paged MTP is not issued") } + } + func setRows(_ rows: [CBv2SequenceKV]) { + boundOffsets = rows.map(\.absoluteOffset) + base.setRows(rows) + } + func updateAndAttend( + queries: MLXArray, keys: MLXArray, values: MLXArray, + scale: Float, sinks: MLXArray? + ) -> MLXArray { + let result = base.updateAndAttend( + queries: queries, keys: keys, values: values, + scale: scale, sinks: sinks) + boundOffsets = boundOffsets.map { $0 + queries.dim(2) } + return result + } + func attendBorrowing( + source: CBv2AttendingLayerCache, queries: MLXArray, + scale: Float, sinks: MLXArray? + ) -> MLXArray { + preconditionFailure("MiMo owns every paged layer") + } + func innerState() -> [MLXArray] { base.innerState() } + var offset: Int { base.offset } + var maxSize: Int? { base.maxSize } + var state: [MLXArray] { + get { [] } + set { preconditionFailure("native paged rows are request-owned") } + } + var metaState: [String] { + get { [] } + set { preconditionFailure("native paged rows have no legacy metadata") } + } + var isTrimmable: Bool { false } + func trim(_ n: Int) -> Int { 0 } + func copy() -> any KVCache { preconditionFailure("copy through the issued paged backend") } + func makeMask(n: Int, windowSize: Int?, returnArray: Bool) + -> MLXFast.ScaledDotProductAttentionMaskMode + { + preconditionFailure("native paged attention owns masks") + } + func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + preconditionFailure("native paged attention requires updateAndAttend") + } +} + +/// Package test observation through the genuine private provenance facade. +/// Does not grant a capability or expose a native owner/array to the caller. +package func mimoV26PagedSourceRetentionWitnessForTesting(_ cache: any CBv2AttendingLayerCache) + -> (retainsForBorrowers: Bool, chunks: Int, workLoans: Int)? +{ + (cache as? MiMoV26PagedLayerCache)?.sourceRetentionWitnessForTesting +} + +public struct MiMoV26CBv2NativePagedExecutionResources { + public let backend: PagedKVBackend + public let cacheProvider: CBv2LayerCacheBank + public let contract: CBv2NativeExecutionContract +} + +/// Native-local resources from one protected setup scope. The contract is issued +/// by the SDK for these exact identities, never asserted by provider metadata. +public struct MiMoV26CBv2NativeExecutionResources { + public let backend: MiMoV26CBv2Backend + public let cacheProvider: CBv2LayerCacheBank + public let contract: CBv2NativeExecutionContract +} + +/// One reference to one target; this is not another Module/parameter tree. +/// Batching here is an explicit component seam, not a packed-serving default. +public final class MiMoV26CBv2Adapter: CBv2SteppableModel, CBv2PrefillSteppableModel, + CBv2ModelCapabilityProviding, CBv2MTPPrefillSteppableModel, + CBv2MTPPolicyTopTwoProviding, CBv2MTPRequestScopedMediaFallback, + CBv2HistoricalAttentionCheckpointProviding, + CBv2CompleteCheckpointKVTypeProviding, + MiMoV26BlockBatchAllocatingModel, + MiMoV26RectangularDenseAllocatingModel +{ + public let target: MiMoV26TextModel + /// Retains the native factory's loaded components and host permit through + /// this adapter's lifetime. Directly extracting target is a borrowed API; + /// only the officially returned wrapper/binding carries this owner. + private let loadLifetimeOwner: AnyObject? + public let assistant: MiMoV26MTPAssistant? + private let useRowLocalRectangularDense = MiMoV26RectangularDense.enabledByEnvironment + package var cbv2MiMoRectangularDenseScratch: MiMoV26RectangularDenseScratchSpec? { + guard useRowLocalRectangularDense, !target.model.useFusedDecodeNorms, + assistant?.requiredVerificationMode == .rectangular, + supportsRequestStatefulMTP + else { return nil } + return MiMoV26RectangularDense.scratchSpec(target) + } + public let layerKinds: [CBv2LayerKind] + private let cacheOwner = UUID() + private let rowLedger = MiMoV26CBv2RowLedger() + private var nativePagedBinding: CBv2NativePagedModelBinding? + private var nativeProbeScope = false + private var nativeProbeFailed = false + private var nativeProbeCaches = Set() + private var observedKVDTypes: [DType]? + // Exact historical target KV is distinct from ordinary frozen replay. + // Persistent assistants require their own complete-state codec, and the + // protected provider profile must separately authorize store/I/O lifetime. + public var cbv2SupportsHistoricalAttentionCheckpoint: Bool { + guard !nativeProbeFailed, let types = observedKVDTypes, + types.count == layerKinds.count, + types.allSatisfy({ $0 == .bfloat16 || $0 == .float16 || $0 == .float32 }) + else { return false } + guard let assistant else { return true } + // A real loaded native assistant must provide its complete three-head + // codec. A declared MTP flag or target-only KV never enables this path. + guard supportsRequestStatefulMTP, + let codec = assistant as? any CBv2HistoricalMTPPrefixCheckpointCoding, + let descriptors = codec.prefixCheckpointTensorDescriptors(targetInputCount: 4), + !descriptors.isEmpty + else { return false } + return true + } + package var nativeCompletePrefixAssistantCodecID: String? { + (assistant as? any CBv2HistoricalMTPPrefixCheckpointCoding)?.prefixCheckpointCodecID + } + package func validateNativeCompletePrefixOwner(_ owner: AnyObject) throws { + guard loadLifetimeOwner === owner, cbv2SupportsHistoricalAttentionCheckpoint else { + throw MiMoV26CBv2Error.invalidInput("invalid native historical-prefix owner/capability") + } + } + public var cbv2CompleteCheckpointKVDTypes: [DType]? { + nativeProbeFailed ? nil : observedKVDTypes + } + // ONE bounded weak association, not a provider registry. Never displaces + // another live resource bundle; manually assembled banks stay unarmed. + private final class WeakCache { + weak var value: MiMoV26ContiguousLayerCache? + init(_ value: MiMoV26ContiguousLayerCache) { self.value = value } + } + private let blockBatchLock = NSLock() + private weak var blockBatchBackend: MiMoV26CBv2Backend? + private weak var blockBatchProvider: AnyObject? + private var blockBatchCaches: [WeakCache] = [] + private func associateBlockBatch( + backend: MiMoV26CBv2Backend, provider: AnyObject, + caches: [any CBv2AttendingLayerCache] + ) { + guard caches.count == layerKinds.count, caches.count <= 48, + caches.allSatisfy({ ($0 as? MiMoV26ContiguousLayerCache)?.owner == cacheOwner }) + else { return } + blockBatchLock.withLock { + guard blockBatchBackend == nil && blockBatchProvider == nil else { return } + blockBatchBackend = backend + blockBatchProvider = provider + blockBatchCaches = caches.compactMap { + ($0 as? MiMoV26ContiguousLayerCache).map(WeakCache.init) + } + } + } + package var cbv2MiMoBlockBatchLayerCount: Int? { + guard !layerKinds.isEmpty, layerKinds.count <= 48, + layerKinds.allSatisfy({ + $0.headDim == 192 && $0.valueHeadDim == 128 + && $0.queryHeads == 64 && [4, 8].contains($0.kvHeads) + && ($0.attention == .full || $0.attention == .slidingWindow(128)) + }) + else { return nil } + return layerKinds.count + } + package func cbv2TryInstallBlockBatchBudget(_ budget: MiMoV26BlockBatchBudget) -> Bool { + blockBatchLock.withLock { + guard budget.modelIdentity == ObjectIdentifier(self), + let backend = blockBatchBackend, let provider = blockBatchProvider, + budget.backendIdentity == ObjectIdentifier(backend), + budget.cacheProviderIdentity == ObjectIdentifier(provider), + blockBatchCaches.count == layerKinds.count + else { return false } + let caches = blockBatchCaches.compactMap(\.value) + guard caches.count == layerKinds.count, + caches.allSatisfy({ $0.blockBatchBudget == nil }) + else { return false } + for cache in caches { cache.blockBatchBudget = budget } + return true + } + } + + public var cbv2Capabilities: CBv2ModelCapabilities { + .init( + supportsPrefixReuse: false, supportsRecurrentCheckpointReuse: false, + supportsPagedKV: nativePagedBinding?.hasSealedNativeResources == true, + requiresNativePagedKV: false, + supportsCompiledDecode: false, supportsPackedPrefill: false, + supportsMTP: supportsRequestStatefulMTP, supportsCompactRecurrentMTPReplay: false) + } + + public init( + target: MiMoV26TextModel, assistant: MiMoV26MTPAssistant? = nil, + retaining owner: AnyObject? = nil + ) throws { + guard assistant == nil || assistant!.isCompatible(with: target) else { + throw MiMoV26MTPError.incompatibleOwner + } + self.target = target + loadLifetimeOwner = owner + self.assistant = assistant + layerKinds = try (0 ..< target.configuration.numHiddenLayers).map { index in + let geometry = try target.configuration.attentionGeometry(at: index) + return CBv2LayerKind( + attention: geometry.slidingWindow.map { .slidingWindow($0) } ?? .full, + hasSinks: geometry.hasSinks, headDim: geometry.headDim, + valueHeadDim: geometry.valueHeadDim, + kvHeads: geometry.keyValueHeads, queryHeads: geometry.queryHeads, + modelLayerIndex: index) + } + guard target.hasLoadedEmbeddingPrecision, target.hasLoadedReadoutPrecision else { + throw MiMoV26CBv2Error.unloadedPrecision + } + } + + public func makeCaches() -> [any CBv2AttendingLayerCache] { + layerKinds.enumerated().map { + MiMoV26ContiguousLayerCache(owner: cacheOwner, index: $0, kind: $1) + } + } + + /// Cold causal media stays on the ordinary target path. The explicit + /// request-scoped engine opt-in never observes/drafts media with the heads; + /// the same installed trained assistant remains available to text rows. + public var supportsMultimodalPrefill: Bool { assistant == nil || supportsRequestStatefulMTP } + public func supportsMultimodalPrefill(attention: CBv2MultimodalAttention) -> Bool { + supportsMultimodalPrefill && attention == .causal + } + public func embedPromptTokens(_ tokens: MLXArray) -> MLXArray { + target.model.embedTokens(tokens) + } + public func forward( + tokens: MLXArray, inputEmbeddings: MLXArray, + caches: [any CBv2AttendingLayerCache] + ) -> MLXArray { + do { + guard supportsMultimodalPrefill else { + throw MiMoV26CBv2Error.invalidInput("native media owner is invalid") + } + return try forwardValidated( + tokens: tokens, inputEmbeddings: inputEmbeddings, caches: caches) + } catch { preconditionFailure("MiMo causal media contract: \(error)") } + } + + /// Uses the exact native rows/probe/ledger. No cache gains a span-mask + /// setter, and ordinary arbitrary banks remain ineligible for media. + public func makeMultimodalCacheProvider() throws -> any CBv2LayerCacheProvider { + guard observedKVDTypes != nil else { throw MiMoV26CBv2Error.nativeProbeRequired } + guard supportsMultimodalPrefill else { + throw MiMoV26CBv2Error.invalidInput("native media owner is invalid") + } + return MiMoV26CausalMediaCacheProvider(adapter: self) + } + + public func makeBackend(bytesCapacity: Int) throws -> MiMoV26CBv2Backend { + guard nativePagedBinding == nil else { + throw MiMoV26CBv2Error.invalidInput( + "paged adapter cannot issue a competing contiguous bank") + } + guard bytesCapacity >= 0 else { + throw MiMoV26CBv2Error.invalidInput("negative backend capacity") + } + // Serving reservations must come from actual loaded projection/RoPE + // storage, never an unproven activation-dtype assumption. + guard let types = observedKVDTypes else { throw MiMoV26CBv2Error.nativeProbeRequired } + // The common backend has one estimate dtype; actual rows retain their + // native type. Mixed observed layers require its conservative FP32 bound. + let dtype: DType = Set(types).count == 1 ? types[0] : .float32 + return MiMoV26CBv2Backend( + kinds: layerKinds, context: target.configuration.maxPositionEmbeddings, + dtype: dtype, bytesCapacity: bytesCapacity, ledger: rowLedger) + } + + /// Native text/contiguous/default+CPU only. Call inside the factory's + /// protected construction helper, before an active engine exists. Register + /// the real owners before any subsequent veto or native engine construction. + public func makeNativeExecutionResources( + bytesCapacity: Int, retaining work: NativeConstructionScope + ) + throws -> MiMoV26CBv2NativeExecutionResources + { + try work.requireImmutableLoadedOwner(loadLifetimeOwner) + try work.retainOwner(self) // requires an already-active protected scope + try work.invalidateOnFailedCompletion(self) { [weak self] in + self?.nativeProbeFailed = true + self?.observedKVDTypes = nil + } + try work.capture(StreamOrDevice.cpu.stream) + try work.capture(StreamOrDevice.default.stream) + let backend = try makeBackend(bytesCapacity: bytesCapacity) + try work.retainOwner(backend) + let caches = makeCaches() + try work.retainValue(caches) + let bank = CBv2LayerCacheBank(caches: caches) + try work.retainOwner(bank) + associateBlockBatch(backend: backend, provider: bank, caches: caches) + try work.checkpoint("adapter.nativeExecutionResources") + let contract = try CBv2NativeExecutionContract( + model: self, backend: backend, + cacheProvider: bank, assistant: assistant, construction: work, + mtpVerificationMode: assistant?.verificationMode ?? .serialTarget) + return .init(backend: backend, cacheProvider: bank, contract: contract) + } + + /// Package-only issuer: the strict loaded wrapper supplies its genuine + /// session validator and exact registered store/process owner. No array + /// capability is inferred from the store's conformance or metadata alone. + package func makeNativeCompletePrefixResources( + bytesCapacity: Int, loadedOwner: AnyObject, + validator: any CBv2NativeCompletePrefixBindingValidating, + completePrefixCache: any CBv2NativeCompletePrefixCache, + processMemoryOwner: any CBv2ProcessMemoryOwner, retaining work: NativeConstructionScope + ) throws + -> MiMoV26CBv2NativeExecutionResources + { + try validateNativeCompletePrefixOwner(loadedOwner) + try validator.validateNativeCompletePrefixBinding() + try work.requireImmutableLoadedOwner(loadedOwner) + try work.retainOwner(self) + try work.retainOwner(validator) + try work.retainOwner(completePrefixCache) + try work.retainOwner(processMemoryOwner) + try work.invalidateOnFailedCompletion(self) { [weak self] in + self?.nativeProbeFailed = true + self?.observedKVDTypes = nil + } + try work.capture(StreamOrDevice.cpu.stream) + try work.capture(StreamOrDevice.default.stream) + let backend = try makeBackend(bytesCapacity: bytesCapacity) + try work.retainOwner(backend) + let caches = makeCaches() + try work.retainValue(caches) + let bank = CBv2LayerCacheBank(caches: caches) + try work.retainOwner(bank) + associateBlockBatch(backend: backend, provider: bank, caches: caches) + try work.checkpoint("adapter.nativeCompletePrefixResources") + try validator.validateNativeCompletePrefixBinding() + let contract = try CBv2NativeExecutionContract( + model: self, backend: backend, + cacheProvider: bank, assistant: assistant, construction: work, loadedOwner: loadedOwner, + mtpVerificationMode: assistant?.verificationMode ?? .serialTarget, + completePrefixCache: completePrefixCache, completePrefixValidator: validator, + prefixProcessMemoryOwner: processMemoryOwner) + return .init(backend: backend, cacheProvider: bank, contract: contract) + } + + /// Protected joint issuer. One actual media-capable provider owns the + /// same native caches used by text prefix/MTP and target-only media. + /// The loaded wrapper creates the processor and validates any typed audio + /// owner; Common then binds all identities in one consumed ticket. + package func makeNativeManagedCompletePrefixResources( + bytesCapacity: Int, processor: AnyObject, + loadedOwner: AnyObject, validator: any CBv2NativeCompletePrefixBindingValidating, + completePrefixCache: any CBv2NativeCompletePrefixCache, + processMemoryOwner: any CBv2ProcessMemoryOwner, + audioOwner: AnyObject? = nil, audioSessionID: UUID? = nil, + audioSourceIdentity: String? = nil, audioGeneration: UUID? = nil, + retaining work: NativeConstructionScope + ) throws + -> ( + backend: MiMoV26CBv2Backend, cacheProvider: any CBv2LayerCacheProvider, + contract: CBv2NativeExecutionContract + ) + { + try validateNativeCompletePrefixOwner(loadedOwner) + try validator.validateNativeCompletePrefixBinding() + try work.requireImmutableLoadedOwner(loadedOwner) + try work.retainOwner(self) + try work.retainOwner(processor) + try work.retainOwner(validator) + try work.retainOwner(completePrefixCache) + try work.retainOwner(processMemoryOwner) + if let audioOwner { + try work.requireImmutableLoadedOwner(audioOwner) + try work.retainOwner(audioOwner) + } + try work.invalidateOnFailedCompletion(self) { [weak self] in + self?.nativeProbeFailed = true + self?.observedKVDTypes = nil + } + try work.capture(StreamOrDevice.cpu.stream) + try work.capture(StreamOrDevice.default.stream) + let backend = try makeBackend(bytesCapacity: bytesCapacity) + try work.retainOwner(backend) + let provider = try makeMultimodalCacheProvider() + try work.retainOwner(provider) + if let native = provider as? MiMoV26CausalMediaCacheProvider { + associateBlockBatch(backend: backend, provider: native, caches: native.caches) + } + try work.checkpoint("adapter.nativeManagedCompletePrefixResources") + try validator.validateNativeCompletePrefixBinding() + let contract = try CBv2NativeExecutionContract( + model: self, backend: backend, + cacheProvider: provider, assistant: assistant, construction: work, + mediaProcessor: processor, loadedOwner: loadedOwner, audioOwner: audioOwner, + audioSessionID: audioSessionID, audioSourceIdentity: audioSourceIdentity, + audioGeneration: audioGeneration, + mtpVerificationMode: assistant?.verificationMode ?? .serialTarget, + completePrefixCache: completePrefixCache, completePrefixValidator: validator, + prefixProcessMemoryOwner: processMemoryOwner) + return (backend, provider, contract) + } + + /// Strict loaded producer only. All native handles stay inside its + /// protected assembly scope; no raw model crosses an async boundary. + package func validateNativePagedOwner(_ owner: AnyObject) throws { + guard loadLifetimeOwner === owner, !nativeProbeFailed, + assistant == nil + || (supportsRequestStatefulMTP && assistant?.verificationMode == .serialTarget), + observedKVDTypes?.count == layerKinds.count + else { + throw MiMoV26CBv2Error.invalidInput("invalid native paged loaded owner") + } + } + + package func makeNativePagedResources( + config: PagedKVPoolConfig, + processMemoryOwner: any CBv2ProcessMemoryOwner, loadedOwner: AnyObject, + validator: any CBv2NativePagedModelValidating, + retaining work: NativeConstructionScope, + completePrefixCache: (any CBv2NativeCompletePrefixCache)? = nil, + completePrefixValidator: (any CBv2NativeCompletePrefixBindingValidating)? = nil + ) throws + -> MiMoV26CBv2NativePagedExecutionResources + { + guard nativePagedBinding == nil, loadLifetimeOwner === loadedOwner, + assistant == nil + || (supportsRequestStatefulMTP && assistant?.verificationMode == .serialTarget), + !nativeProbeFailed, let types = observedKVDTypes, config.layerDTypes == types, + config.prefixSharingBlockSize == nil, config.segmentSizeBytes != nil, + config.gatheredAttention?.admissionMode == .stepOwned(.pinnedMetal) + else { + throw MiMoV26CBv2Error.invalidInput( + "native paged target requires completed probe and exclusive target/serial-MTP resources" + ) + } + try work.requireImmutableLoadedOwner(loadedOwner) + try validator.validateNativePagedModel() + guard (completePrefixCache != nil) == (completePrefixValidator != nil) else { + throw MiMoV26CBv2Error.invalidInput("incomplete native paged prefix tuple") + } + try completePrefixValidator?.validateNativeCompletePrefixBinding() + try work.retainOwner(self) + try work.retainOwner(validator) + try work.retainOwner(processMemoryOwner) + try work.capture(StreamOrDevice.default.stream) + try work.capture(StreamOrDevice.cpu.stream) + let ledger = rowLedger + let ownership = try CBv2NativePagedModelBinding( + model: self, loadedOwner: loadedOwner, assistant: assistant, + layerKinds: layerKinds, layerDTypes: types, + maximumContextTokens: target.configuration.maxPositionEmbeddings, + processMemoryOwner: processMemoryOwner, validator: validator, construction: work, + completePrefixCache: completePrefixCache, + completePrefixValidator: completePrefixValidator, + registerRows: { try ledger.register($0, backend: $1) }, + rowRequest: { try ledger.identity($0, layer: $1) }, + removeRows: { try ledger.remove($0, backend: $1) }) + try work.retainOwner(ownership) + // Capture the actual binding before a late constructor veto. + nativePagedBinding = ownership + try work.invalidateOnFailedCompletion(self) { [weak self] in + self?.nativeProbeFailed = true + self?.observedKVDTypes = nil + } + let backend = try PagedKVBackend( + layerKinds: layerKinds, config: config, + nativeModelBinding: ownership) + try work.retainOwner(backend) + let raw = backend.makeLayerCaches() + guard let bases = raw as? [PagedLayerCache], bases.count == layerKinds.count else { + throw MiMoV26CBv2Error.invalidInput("native paged cache construction mismatch") + } + let caches = bases.map { MiMoV26PagedLayerCache(owner: cacheOwner, base: $0) } + let bank = CBv2LayerCacheBank(caches: caches) + try work.retainOwner(bank) + try ownership.seal(bank: bank, caches: bases) + try work.checkpoint("adapter.nativePagedResources") + let contract = try CBv2NativeExecutionContract( + model: self, backend: backend, + cacheProvider: bank, assistant: assistant, construction: work, loadedOwner: loadedOwner, + completePrefixCache: completePrefixCache, + completePrefixValidator: completePrefixValidator, + prefixProcessMemoryOwner: completePrefixCache == nil ? nil : processMemoryOwner, + nativePagedBinding: ownership, nativePagedProcessMemoryOwner: processMemoryOwner) + return .init(backend: backend, cacheProvider: bank, contract: contract) + } + + // Insert beside makeNativeExecutionResources in MiMoV26CBv2Adapter. + // Package-only: the strict LoadedModel creates the exact processor, and + // the already-active construction scope authenticates this loaded owner. + package func makeNativeDecodedVisualResources( + bytesCapacity: Int, processor: AnyObject, + loadedOwner: AnyObject, retaining work: NativeConstructionScope + ) throws + -> ( + backend: MiMoV26CBv2Backend, cacheProvider: any CBv2LayerCacheProvider, + contract: CBv2NativeExecutionContract + ) + { + guard loadLifetimeOwner === loadedOwner else { + throw MiMoV26CBv2Error.invalidInput("foreign decoded-media owner") + } + try work.requireImmutableLoadedOwner(loadLifetimeOwner) + try work.retainOwner(self) + try work.retainOwner(processor) + try work.invalidateOnFailedCompletion(self) { [weak self] in + self?.nativeProbeFailed = true + self?.observedKVDTypes = nil + } + try work.capture(StreamOrDevice.cpu.stream) + try work.capture(StreamOrDevice.default.stream) + let backend = try makeBackend(bytesCapacity: bytesCapacity) + try work.retainOwner(backend) + let provider = try makeMultimodalCacheProvider() + try work.retainOwner(provider) + if let native = provider as? MiMoV26CausalMediaCacheProvider { + associateBlockBatch(backend: backend, provider: native, caches: native.caches) + } + try work.checkpoint("adapter.nativeDecodedVisualResources") + let contract = try CBv2NativeExecutionContract( + model: self, backend: backend, + cacheProvider: provider, assistant: assistant, construction: work, + mediaProcessor: processor, loadedOwner: loadedOwner, + mtpVerificationMode: assistant?.verificationMode ?? .serialTarget) + return (backend, provider, contract) + } + + /// Package-only audio issuer. MLXVLM authenticates the concrete sidecar and + /// authorizes its exact owner in this same protected construction scope. + package func makeNativeDecodedAudioResources( + bytesCapacity: Int, processor: AnyObject, + loadedOwner: AnyObject, audioOwner: AnyObject, audioSessionID: UUID, + audioSourceIdentity: String, audioGeneration: UUID, retaining work: NativeConstructionScope + ) throws + -> ( + backend: MiMoV26CBv2Backend, cacheProvider: any CBv2LayerCacheProvider, + contract: CBv2NativeExecutionContract + ) + { + guard loadLifetimeOwner === loadedOwner else { + throw MiMoV26CBv2Error.invalidInput("foreign decoded-audio owner") + } + try work.requireImmutableLoadedOwner(loadLifetimeOwner) + try work.requireImmutableLoadedOwner(audioOwner) + try work.retainOwner(self) + try work.retainOwner(processor) + try work.retainOwner(audioOwner) + try work.invalidateOnFailedCompletion(self) { [weak self] in + self?.nativeProbeFailed = true + self?.observedKVDTypes = nil + } + try work.capture(StreamOrDevice.cpu.stream) + try work.capture(StreamOrDevice.default.stream) + let backend = try makeBackend(bytesCapacity: bytesCapacity) + try work.retainOwner(backend) + let provider = try makeMultimodalCacheProvider() + try work.retainOwner(provider) + if let native = provider as? MiMoV26CausalMediaCacheProvider { + associateBlockBatch(backend: backend, provider: native, caches: native.caches) + } + try work.checkpoint("adapter.nativeDecodedAudioResources") + let contract = try CBv2NativeExecutionContract( + model: self, backend: backend, + cacheProvider: provider, assistant: assistant, construction: work, + mediaProcessor: processor, loadedOwner: loadedOwner, audioOwner: audioOwner, + audioSessionID: audioSessionID, audioSourceIdentity: audioSourceIdentity, + audioGeneration: audioGeneration, + mtpVerificationMode: assistant?.verificationMode ?? .serialTarget) + return (backend, provider, contract) + } + + /// Serialized construction/warmup-only observation of this loaded target. + /// The common probe installs its private RecordingRow, then unbinds it. + /// No active engine may use this adapter concurrently with the probe. + public func probeNativeKVTypes(retaining work: NativeConstructionScope) throws + -> CBv2NativeKVTypeProbe.Result + { + guard nativePagedBinding == nil else { + throw MiMoV26CBv2Error.invalidInput("cannot reprobe an issued paged adapter") + } + guard !nativeProbeFailed else { + throw MiMoV26CBv2Error.invalidInput( + "native construction completion failed; process restart required") + } + guard !nativeProbeScope else { + throw MiMoV26CBv2Error.invalidInput("nested native type probe") + } + do { + return try work.withPhase(.nativeKVProbe) { + try work.retainOwner(self) + try work.invalidateOnFailedCompletion(self) { [weak self] in + self?.nativeProbeFailed = true + self?.observedKVDTypes = nil + } + try work.capture(StreamOrDevice.cpu.stream) + try work.capture(StreamOrDevice.default.stream) + observedKVDTypes = nil + let caches = makeCaches() + try work.retainValue(caches) + nativeProbeCaches = Set(caches.map(ObjectIdentifier.init)) + nativeProbeScope = true + defer { + if !work.snapshot.isRetainedFault { + nativeProbeScope = false + nativeProbeCaches.removeAll() + } + } + let result = try CBv2NativeKVTypeProbe.run( + model: self, layerKinds: layerKinds, caches: caches, retaining: work) + observedKVDTypes = result.layerDTypes + return result + } + } catch { + if work.snapshot.isRetainedFault { + nativeProbeFailed = true + observedKVDTypes = nil + } + throw error + } + } + + /// Host-side external token validation. The engine forward intentionally + /// trusts values from its validated prompt/sampler and never reads them back. + public func validateTokenIDs(_ ids: [Int]) throws { + guard !ids.isEmpty, ids.count <= target.configuration.maxPositionEmbeddings, + ids.allSatisfy({ $0 >= 0 && $0 < target.configuration.vocabularySize }) + else { + throw MiMoV26CBv2Error.invalidInput("token IDs outside the native vocabulary/context") + } + } + + /// Recoverable external composition preflight. Checks all rows before the + /// first setRows call; ordinary engine bank binding remains a trusted seam. + public func bindRows(_ rowStates: [[CBv2SequenceKV?]], caches: [any CBv2AttendingLayerCache]) + throws + { + guard observedKVDTypes != nil else { throw MiMoV26CBv2Error.nativeProbeRequired } + let owned = try ownedCaches(caches) + guard !rowStates.isEmpty, rowStates.allSatisfy({ $0.count == layerKinds.count }) else { + throw MiMoV26CBv2Error.invalidInput("one state per layer and at least one row required") + } + var grouped: [[CBv2SequenceKV]] = [] + for index in layerKinds.indices { + var rows: [CBv2SequenceKV] = [] + for state in rowStates { + guard let row = state[index] else { + throw MiMoV26CBv2Error.invalidCache(layer: index, reason: "missing owning row") + } + rows.append(row) + } + grouped.append(rows) + } + try validateRows(grouped, length: 0) + for (cache, rows) in zip(owned, grouped) { cache.setRows(rows) } + } + + /// Shape/owner/history-only preflight. Array token VALUES are trusted; + /// callers accepting external IDs must run validateTokenIDs before upload. + public func validate( + tokens: MLXArray, inputEmbeddings: MLXArray? = nil, + caches: [any CBv2AttendingLayerCache] + ) throws { + try validate( + tokens: tokens, inputEmbeddings: inputEmbeddings, caches: caches, allowMTPStaging: false + ) + } + + private func validate( + tokens: MLXArray, inputEmbeddings: MLXArray? = nil, + caches: [any CBv2AttendingLayerCache], allowMTPStaging: Bool + ) throws { + guard !nativeProbeFailed else { + throw MiMoV26CBv2Error.invalidInput( + "native construction completion failed; process restart required") + } + let probeRows = + nativeProbeScope && Set(caches.map(ObjectIdentifier.init)) == nativeProbeCaches + guard observedKVDTypes != nil || probeRows else { + throw MiMoV26CBv2Error.nativeProbeRequired + } + guard tokens.ndim == 2, tokens.dtype == .int32 || tokens.dtype == .uint32, + tokens.dim(0) > 0, tokens.dim(1) > 0 + else { + throw MiMoV26CBv2Error.invalidInput("tokens require nonempty rank-two int32/uint32") + } + if let inputEmbeddings { + guard + inputEmbeddings.shape == [ + tokens.dim(0), tokens.dim(1), target.configuration.hiddenSize, + ], + inputEmbeddings.dtype == target.activationDType + else { + throw MiMoV26CBv2Error.invalidInput("native input embedding shape/dtype mismatch") + } + } + guard target.hasLoadedEmbeddingPrecision, target.hasLoadedReadoutPrecision else { + throw MiMoV26CBv2Error.unloadedPrecision + } + let owned = try ownedCaches(caches) + for cache in owned { + guard cache.rows.count == tokens.dim(0), cache.positionOffsets.shape == [tokens.dim(0)], + cache.positionOffsets.dtype == .int32, + cache.rows.map(\.absoluteOffset) == cache.boundOffsets + else { + throw MiMoV26CBv2Error.invalidCache( + layer: cache.layerIndex, + reason: "batch or position frontier changed without cache rebinding") + } + } + try validateRows( + owned.map(\.rows), length: tokens.dim(1), allowProbeRows: probeRows, + allowMTPStaging: allowMTPStaging) + } + + private func ownedCaches(_ caches: [any CBv2AttendingLayerCache]) throws + -> [any MiMoV26OwnedLayerCache] + { + guard caches.count == layerKinds.count else { + throw MiMoV26CBv2Error.invalidInput("one native cache per layer required") + } + var result: [any MiMoV26OwnedLayerCache] = [] + var identities = Set() + for (index, cache) in caches.enumerated() { + guard let owned = cache as? any MiMoV26OwnedLayerCache, + nativePagedBinding == nil + ? owned is MiMoV26ContiguousLayerCache : owned is MiMoV26PagedLayerCache, + owned.owner == cacheOwner, owned.layerIndex == index, + owned.kind == layerKinds[index], + identities.insert(ObjectIdentifier(owned)).inserted + else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "foreign, reordered or aliased cache owner") + } + result.append(owned) + } + return result + } + + private func validateRows( + _ rowsByLayer: [[CBv2SequenceKV]], length: Int, allowProbeRows: Bool = false, + allowMTPStaging: Bool = false + ) throws { + let maximum = target.configuration.maxPositionEmbeddings + guard length >= 0, length <= maximum else { throw MiMoV26CBv2Error.contextExceeded } + let batch = rowsByLayer.first?.count ?? 0 + let offsets = rowsByLayer.first?.map(\.absoluteOffset) ?? [] + var identities = Set() + var requestIdentities = [UUID?](repeating: nil, count: batch) + for (index, rows) in rowsByLayer.enumerated() { + let kind = layerKinds[index] + guard rows.count == batch else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "row count differs across layers") + } + for (rowIndex, row) in rows.enumerated() { + let pagedMetadata: CBv2NativePagedRowMetadata? + if row is PagedSequenceKV { + guard !allowProbeRows, let nativePagedBinding else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "unissued paged row") + } + pagedMetadata = try nativePagedBinding.metadata(row: row, layer: index) + } else { + pagedMetadata = nil + } + guard + pagedMetadata != nil || row is CBv2FullSequenceKV + || row is CBv2WindowedSequenceKV + || (allowProbeRows && !(row is PagedSequenceKV) + && !(row is CBv2FrozenReplayFullSequenceKV)) + else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "unqualified row backend") + } + if !allowProbeRows { + let request = + try pagedMetadata?.request ?? rowLedger.identity(row, layer: index) + guard + requestIdentities[rowIndex] == nil || requestIdentities[rowIndex] == request + else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "different requests spliced across layers") + } + requestIdentities[rowIndex] = request + } + guard identities.insert(ObjectIdentifier(row)).inserted else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "row aliases another layer/request slot") + } + let offset = row.absoluteOffset + guard offset >= 0, offset <= maximum - length else { + throw MiMoV26CBv2Error.contextExceeded + } + guard offset == offsets[rowIndex] else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "request history differs across layers") + } + if let full = row as? CBv2FullSequenceKV { + guard case .full = kind.attention, full.maxLength >= offset + length else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "full row policy/capacity mismatch") + } + } + if let window = row as? CBv2WindowedSequenceKV { + guard kind.attention == .slidingWindow(window.window), + window.retainedCount >= min(offset, window.window), + window.retainedCount + <= min(offset, window.window + (allowMTPStaging ? 3 : 0)) + else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "sliding row policy mismatch") + } + } + if let pagedMetadata { + guard pagedMetadata.offset == offset, + pagedMetadata.retainedCount == row.retainedCount, + pagedMetadata.maximumLength >= offset + length, + pagedMetadata.keyWidth == kind.headDim, + pagedMetadata.valueWidth == kind.valueHeadDim, + pagedMetadata.kvHeads == kind.kvHeads, + pagedMetadata.dtype == observedKVDTypes?[index], + pagedMetadata.oldestValidPosition <= offset - row.retainedCount + else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "native paged scalar geometry/history mismatch") + } + continue // NEVER gather/snapshot merely to validate ownership. + } + // Public snapshots expose only metadata here: no eval/item or + // data copy. Do not retain them or derive positions from data. + // The real native type probe uses its private RecordingRow, + // whose empty placeholders are FP16 before its first write. + let snapshot = row.snapshot() + guard snapshot.offset == offset, snapshot.keys.ndim == 4, snapshot.values.ndim == 4, + snapshot.keys.shape == [1, kind.kvHeads, row.retainedCount, kind.headDim], + snapshot.values.shape == [ + 1, kind.kvHeads, row.retainedCount, kind.valueHeadDim, + ] + else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "native K/V snapshot geometry mismatch") + } + if row.retainedCount > 0 { + let expected = observedKVDTypes?[index] ?? target.activationDType + let validDType = + allowProbeRows + ? snapshot.keys.dtype == snapshot.values.dtype + && [.float16, .bfloat16, .float32].contains(snapshot.keys.dtype) + : snapshot.keys.dtype == expected && snapshot.values.dtype == expected + guard validDType else { + throw MiMoV26CBv2Error.invalidCache( + layer: index, reason: "native K/V storage dtype mismatch") + } + } + } + } + } + + public func forwardValidated( + tokens: MLXArray, inputEmbeddings: MLXArray? = nil, + caches: [any CBv2AttendingLayerCache] + ) throws -> MLXArray { + try validate(tokens: tokens, inputEmbeddings: inputEmbeddings, caches: caches) + let hidden = trunk(tokens: tokens, inputEmbeddings: inputEmbeddings, caches: caches) + return target.lmHead.map { $0(hidden) } ?? target.model.embedTokens.asLinear(hidden) + } + + public func prefillValidated( + tokens: MLXArray, inputEmbeddings: MLXArray? = nil, + caches: [any CBv2AttendingLayerCache], + requirement: CBv2PrefillRequirement + ) throws -> MLXArray { + try validate(tokens: tokens, inputEmbeddings: inputEmbeddings, caches: caches) + let hidden = trunk(tokens: tokens, inputEmbeddings: inputEmbeddings, caches: caches) + switch requirement { + case .evaluationOnly: + // Full-trunk reduction proves all rows participate; no vocabulary + // projection is constructed for an intermediate prompt chunk. + return depends( + input: hidden.sum(axes: [1, 2]).reshaped(-1, 1), + dependencies: cacheRoots(caches)) + case .lastPositionLogits: + let last = hidden[0..., -1, 0...] + let logits = target.lmHead.map { $0(last) } ?? target.model.embedTokens.asLinear(last) + return depends(input: logits, dependencies: cacheRoots(caches)) + } + } + + public func forward(tokens: MLXArray, caches: [any CBv2AttendingLayerCache]) -> MLXArray { + do { return try forwardValidated(tokens: tokens, caches: caches) } catch { + preconditionFailure("MiMo CBv2 validated engine state invariant: \(error)") + } + } + public func prefill( + tokens: MLXArray, inputEmbeddings: MLXArray?, + caches: [any CBv2AttendingLayerCache], requirement: CBv2PrefillRequirement + ) -> MLXArray { + do { + return try prefillValidated( + tokens: tokens, inputEmbeddings: inputEmbeddings, + caches: caches, requirement: requirement) + } catch { preconditionFailure("MiMo CBv2 validated prefill state invariant: \(error)") } + } + + public var mtpCaptureLayers: CBv2MTPCaptureLayers? { nil } + public var supportsRequestStatefulMTP: Bool { assistant?.isCompatible(with: target) == true } + public var mtpTargetIdentity: ObjectIdentifier? { + supportsRequestStatefulMTP ? ObjectIdentifier(target) : nil + } + public func cbv2MTPTopTwo(_ logits: MLXArray) -> (ids: MLXArray, values: MLXArray) { + cbv2TopTwoRows(logits) + } + + /// MiMo's native heads consume the target's POST-final-norm features. + /// Logits and target KV use the identical ordinary trunk and readout. + public func forwardWithHidden(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) + -> (logits: MLXArray, lastHidden: MLXArray) + { + do { + guard supportsRequestStatefulMTP else { throw MiMoV26MTPError.weightsNotLoaded } + try validate(tokens: tokens, caches: caches, allowMTPStaging: true) + let rowLocalDense = MiMoV26RectangularDense.eligible( + tokens: tokens, caches: caches, + requested: useRowLocalRectangularDense + && MiMoV26RectangularDenseAdmission.isActive(for: self), + fusedNorms: target.model.useFusedDecodeNorms) + if rowLocalDense { MiMoV26RectangularDenseAdmission.recordSubmission(for: self) } + let hidden = trunk( + tokens: tokens, inputEmbeddings: nil, caches: caches, + rowLocalDense: rowLocalDense) + return (MiMoV26RectangularDense.readout(target, hidden, enabled: rowLocalDense), hidden) + } catch { preconditionFailure("MiMo CBv2 hidden contract: \(error)") } + } + + public func forwardWithHiddenForPrefill( + tokens: MLXArray, caches: [CBv2AttendingLayerCache], + requirement: CBv2PrefillRequirement + ) + -> (logits: MLXArray, lastHidden: MLXArray) + { + do { + guard supportsRequestStatefulMTP else { throw MiMoV26MTPError.weightsNotLoaded } + try validate(tokens: tokens, caches: caches) + let hidden = trunk(tokens: tokens, inputEmbeddings: nil, caches: caches) + switch requirement { + case .evaluationOnly: + return ( + depends( + input: hidden.sum(axes: [1, 2]).reshaped(-1, 1), + dependencies: cacheRoots(caches)), hidden + ) + case .lastPositionLogits: + let last = hidden[0..., -1, 0...] + let logits = + target.lmHead.map { $0(last) } ?? target.model.embedTokens.asLinear(last) + return (depends(input: logits, dependencies: cacheRoots(caches)), hidden) + } + } catch { preconditionFailure("MiMo CBv2 hidden prefill contract: \(error)") } + } + + private func cacheRoots(_ caches: [any CBv2AttendingLayerCache]) -> [MLXArray] { + caches.flatMap { ($0 as? KVCache)?.innerState() ?? [] } + } + private func trunk( + tokens: MLXArray, inputEmbeddings: MLXArray?, + caches: [any CBv2AttendingLayerCache], rowLocalDense: Bool = false + ) -> MLXArray { + var hidden = inputEmbeddings ?? target.model.embedTokens(tokens) + var nextInput: MLXArray? + for (index, layer) in target.model.layers.enumerated() { + let attention = layer.selfAttention + let normalized = nextInput ?? layer.inputNorm(hidden) + let (batch, length) = (hidden.dim(0), hidden.dim(1)) + let geometry = attention.geometry + var q = MiMoV26RectangularDense.projection( + attention.qProj, normalized, enabled: rowLocalDense + ) + .reshaped(batch, length, geometry.queryHeads, geometry.headDim).transposed(0, 2, 1, 3) + var k = MiMoV26RectangularDense.projection( + attention.kProj, normalized, enabled: rowLocalDense + ) + .reshaped(batch, length, geometry.keyValueHeads, geometry.headDim).transposed( + 0, 2, 1, 3) + let v = + MiMoV26RectangularDense.projection( + attention.vProj, normalized, enabled: rowLocalDense + ) + .reshaped(batch, length, geometry.keyValueHeads, geometry.valueHeadDim) + .transposed(0, 2, 1, 3) * attention.valueScale + let offsets = caches[index].positionOffsets + 0 + q = attention.rope(q, offset: offsets) + k = attention.rope(k, offset: offsets) + let output = caches[index].updateAndAttend( + queries: q, keys: k, values: v, + scale: attention.scale, sinks: attention.attentionSinkBias) + let projected = MiMoV26RectangularDense.projection( + attention.oProj, + output.transposed(0, 2, 1, 3).reshaped(batch, length, -1), enabled: rowLocalDense) + let nextNorm = + index + 1 < target.model.layers.count + ? target.model.layers[index + 1].inputNorm : target.model.norm + if let fused = MiMoV26DecodeKernels.finishLayer( + hidden, attentionOutput: projected, layer: layer, nextNorm: nextNorm, + enabled: target.model.useFusedDecodeNorms) + { + hidden = fused.residual + nextInput = fused.normalized + } else { + let residual = hidden + projected + hidden = + residual + + MiMoV26RectangularDense.mlp( + layer.mlp, layer.postAttentionNorm(residual), enabled: rowLocalDense) + nextInput = nil + } + } + // This remains target POST-final-norm for every MTP consumer. + return nextInput ?? target.model.norm(hidden) + } +} + +private final class MiMoV26CausalMediaCacheProvider: CBv2MultimodalAttentionCapabilityProviding, + CBv2CompositionInvalidating +{ + private let adapter: MiMoV26CBv2Adapter + private let bank: CBv2LayerCacheBank + fileprivate let caches: [any CBv2AttendingLayerCache] + init(adapter: MiMoV26CBv2Adapter) { + self.adapter = adapter + caches = adapter.makeCaches() + bank = CBv2LayerCacheBank(caches: caches) + } + func supportsMultimodalPrefill(attention: CBv2MultimodalAttention) -> Bool { + adapter.supportsMultimodalPrefill(attention: attention) + } + // This admits only the existing eligible text rounds. Media request + // exclusion, all-row scheduling costs and native head B=1 stay unchanged. + var supportsMTPRectangularVerification: Bool { + bank.supportsMTPRectangularVerification + } + func layerCaches(rowStates: [[CBv2SequenceKV?]]) -> [any CBv2AttendingLayerCache] { + do { try adapter.bindRows(rowStates, caches: caches) } catch { + preconditionFailure("MiMo media provider row ownership: \(error)") + } + return bank.layerCaches(rowStates: rowStates) + } + func invalidateBoundComposition() { bank.invalidateBoundComposition() } + func releaseBoundRows() { bank.releaseBoundRows() } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26CBv2PrefillPolicy.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26CBv2PrefillPolicy.swift new file mode 100644 index 0000000000..ed6edae842 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26CBv2PrefillPolicy.swift @@ -0,0 +1,25 @@ +// Copyright © 2026 Eigen Labs. +import MLX +import MLXLMCommon + +extension MiMoV26CBv2Adapter: MiMoV26PrefillDefaultProviding { + package var cbv2MiMoAutomaticPrefillMaximumTokens: Int? { + let config = target.configuration + guard cbv2MiMoBlockBatchLayerCount != nil, + config.hiddenSize == 4096, config.moeIntermediateSize == 2048, + config.routedExpertCount == 256, config.expertsPerToken == 8, + config.maxPositionEmbeddings >= 4096, + let types = cbv2CompleteCheckpointKVDTypes, + types.count == layerKinds.count, + types.allSatisfy({ $0 == .bfloat16 || $0 == .float16 }) + else { return nil } + let experts = target.model.layers.compactMap { $0.mlp as? MiMoV26MoE } + guard !experts.isEmpty else { return nil } + // 4096 tokens keep native top-8 routing at <=32768 sorted rows. + // The wider8192 profile requires the existing requested oversized + // gather to match every actual loaded expert projection. + return config.maxPositionEmbeddings >= 8192 + && experts.allSatisfy { $0.switchMLP.mimoV26SupportsOversizedPrefillGather } + ? 8192 : 4096 + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26CausalPositionContract.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26CausalPositionContract.swift new file mode 100644 index 0000000000..81f3d5c483 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26CausalPositionContract.swift @@ -0,0 +1,12 @@ +// Copyright © 2026 Eigen Labs. +import MLXLMCommon + +extension MiMoV26CBv2Adapter { + /// Native MiMo media occupies ordinary causal token positions. The real + /// trunk applies 1D RoPE at each row's cache offset, including chunked + /// prefill and sliding-window wrap. No Qwen-style position tensor is + /// synthesized or silently discarded. Supplied positions still pass the + /// engine's normal shape/positioned-forwarding checks and are rejected by + /// this non-positioned adapter. Tracked native media remains unqualified. + public var causalPositionRequirement: CBv2CausalPositionRequirement { .scalarCacheOffset } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26Configuration.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26Configuration.swift new file mode 100644 index 0000000000..ba285c8d0a --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26Configuration.swift @@ -0,0 +1,603 @@ +// Copyright © 2026 Eigen Labs. +// Configuration preparation only. This file deliberately has no MLX dependency. +import Foundation + +public enum MiMoV26ConfigurationError: Error, Equatable, Sendable, CustomStringConvertible, + LocalizedError +{ + case invalid(field: String, reason: String) + + public var description: String { + switch self { + case .invalid(let field, let reason): "MiMo V2.6 configuration \(field): \(reason)" + } + } + public var errorDescription: String? { description } +} + +/// Preserves semantic JSON, including unknown nested fields and explicit nulls. +/// Decimal avoids the loss of integer precision caused by a Double-only tree. +public indirect enum MiMoV26JSONValue: Codable, Equatable, Sendable { + case object([String: Self]) + case array([Self]) + case string(String) + case number(Decimal) + case bool(Bool) + case null + + public init(from decoder: any Decoder) throws { + let c = try decoder.singleValueContainer() + if c.decodeNil() { + self = .null + } else if let value = try? c.decode(Bool.self) { + self = .bool(value) + } else if let value = try? c.decode(String.self) { + self = .string(value) + } else if let value = try? c.decode([String: Self].self) { + self = .object(value) + } else if let value = try? c.decode([Self].self) { + self = .array(value) + } else { + self = .number(try c.decode(Decimal.self)) + } + } + + public func encode(to encoder: any Encoder) throws { + var c = encoder.singleValueContainer() + switch self { + case .object(let value): try c.encode(value) + case .array(let value): try c.encode(value) + case .string(let value): try c.encode(value) + case .number(let value): try c.encode(value) + case .bool(let value): try c.encode(value) + case .null: try c.encodeNil() + } + } +} + +private struct MiMoV26Fields { + let values: [String: MiMoV26JSONValue] + var prefix = "" + + func error(_ key: String, _ reason: String) -> MiMoV26ConfigurationError { + .invalid(field: prefix + key, reason: reason) + } + func string(_ key: String) throws -> String { + guard case .string(let value) = values[key] else { throw error(key, "requires a string") } + return value + } + func int(_ key: String, minimum: Int = 1) throws -> Int { + guard case .number(let value) = values[key] else { throw error(key, "requires an integer") } + let result = NSDecimalNumber(decimal: value).int64Value + guard value == Decimal(result), let exact = Int(exactly: result), exact >= minimum else { + throw error(key, "requires a representable integer >= \(minimum)") + } + return exact + } + func number(_ key: String, minimum: Double = 0, inclusive: Bool = false) throws -> Double { + guard case .number(let value) = values[key] else { throw error(key, "requires a number") } + let result = NSDecimalNumber(decimal: value).doubleValue + guard result.isFinite, inclusive ? result >= minimum : result > minimum else { + throw error(key, "requires a finite number \(inclusive ? ">=" : ">") \(minimum)") + } + return result + } + func bool(_ key: String) throws -> Bool { + guard case .bool(let value) = values[key] else { throw error(key, "requires a boolean") } + return value + } + func integers(_ key: String, minimum: Int = 0) throws -> [Int] { + guard case .array(let values) = values[key] else { + throw error(key, "requires an integer array") + } + return try values.enumerated().map { index, value in + try MiMoV26Fields(values: ["value": value], prefix: prefix + "\(key)[\(index)].") + .int("value", minimum: minimum) + } + } + func strings(_ key: String) throws -> [String] { + guard case .array(let values) = values[key] else { + throw error(key, "requires a string array") + } + return try values.map { + guard case .string(let value) = $0 else { throw error(key, "requires a string array") } + return value + } + } + func object(_ key: String) throws -> MiMoV26Fields { + guard case .object(let value) = values[key] else { throw error(key, "requires an object") } + return MiMoV26Fields(values: value, prefix: prefix + key + ".") + } + func optional(_ key: String, _ read: (String) throws -> T) throws -> T? { + if values[key] == nil || values[key] == .null { return nil } + return try read(key) + } + func require(_ condition: Bool, _ key: String, _ reason: String) throws { + if !condition { throw error(key, reason) } + } + func oneOf(_ key: String, _ supported: [String]) throws -> String { + let value = try string(key) + try require(supported.contains(value), key, "unsupported value \(value)") + return value + } + func product(_ a: Int, _ b: Int, _ key: String) throws -> Int { + let product = a.multipliedReportingOverflow(by: b) + try require( + !product.overflow && product.partialValue > 0, key, "dimension product overflows") + return product.partialValue + } +} + +public struct MiMoV26AttentionGeometry: Equatable, Sendable { + public let queryHeads: Int + public let keyValueHeads: Int + public let headDim: Int + public let valueHeadDim: Int + public let rotaryDimensions: Int + public let ropeTheta: Double + public let slidingWindow: Int? + public let hasSinks: Bool + + fileprivate init(_ f: MiMoV26Fields, sliding: Bool, factor: Double, window: Int) throws { + queryHeads = try f.int(sliding ? "swa_num_attention_heads" : "num_attention_heads") + keyValueHeads = try f.int(sliding ? "swa_num_key_value_heads" : "num_key_value_heads") + headDim = try f.int(sliding ? "swa_head_dim" : "head_dim") + valueHeadDim = try f.int(sliding ? "swa_v_head_dim" : "v_head_dim") + ropeTheta = try f.number(sliding ? "swa_rope_theta" : "rope_theta") + hasSinks = try f.bool( + sliding ? "add_swa_attention_sink_bias" : "add_full_attention_sink_bias") + slidingWindow = sliding ? window : nil + try f.require( + queryHeads.isMultiple(of: keyValueHeads), "attention_heads", + "Q heads must divide into KV groups") + let rotary = Double(headDim) * factor + guard rotary.isFinite, rotary >= 2, rotary < Double(Int.max) else { + throw f.error("partial_rotary_factor", "invalid rotary dimension") + } + rotaryDimensions = Int(rotary) + try f.require( + rotaryDimensions <= headDim && rotaryDimensions.isMultiple(of: 2), + "partial_rotary_factor", "rotary dimension must be even and within the head") + _ = try f.product(queryHeads, headDim, "Q projection") + _ = try f.product(keyValueHeads, headDim, "K projection") + _ = try f.product(keyValueHeads, valueHeadDim, "V projection") + _ = try f.product(queryHeads, valueHeadDim, "O projection") + } +} + +/// Original source FP8 metadata and converted MLX policy coexist. Only the +/// latter is an operational native quantization policy; neither proves layout. +public struct MiMoV26Quantization: Equatable, Sendable { + public struct Policy: Equatable, Sendable { + public let mode: String + public let bits: Int + public let groupSize: Int + + fileprivate init(_ f: MiMoV26Fields) throws { + mode = try f.oneOf("mode", ["mxfp4", "affine"]) + bits = try f.int("bits") + groupSize = try f.int("group_size") + try f.require( + (mode == "mxfp4" && bits == 4 && groupSize == 32) + || (mode == "affine" && [4, 8].contains(bits) && groupSize == 64), + "mode", "unsupported native bits/group_size combination") + } + } + public enum Override: Equatable, Sendable { + case skip + case quantize(Policy) + } + public let nativeDefault: Policy? + public let nativeOverrides: [String: Override] + public let sourceMetadata: [String: MiMoV26JSONValue]? + + fileprivate init(_ f: MiMoV26Fields) throws { + let declared = try f.optional("quantization_config", f.object) + let primary = try f.optional("quantization", f.object) + // MLX exporters may repeat their operational policy in both fields. + // Keep that distinct from the upstream FP8 conversion metadata, and + // reject contradictory aliases rather than silently picking one. + let nativeAlias = + declared.map { $0.values["mode"] != nil && $0.values["quant_method"] == nil } ?? false + if nativeAlias, let primary, primary.values != declared?.values { + throw f.error("quantization_config", "conflicting native quantization aliases") + } + sourceMetadata = nativeAlias ? nil : declared?.values + if let sourceMetadata { + let source = MiMoV26Fields(values: sourceMetadata, prefix: "quantization_config.") + _ = try source.oneOf("quant_method", ["fp8"]) + _ = try source.oneOf("store_dtype", ["mxfp4"]) + _ = try source.oneOf("fmt", ["e4m3"]) + _ = try source.oneOf("activation_scheme", ["dynamic"]) + try source.require( + try source.int("mxfp4_block_size") == 32, + "mxfp4_block_size", "expected group32") + try source.require( + try source.integers("weight_block_size") == [128, 128], + "weight_block_size", "expected block128 by128") + _ = try source.strings("ignored_layers") + } + if let native = primary ?? (nativeAlias ? declared : nil) { + nativeDefault = try Policy(native) + var overrides: [String: Override] = [:] + for key in native.values.keys where !["mode", "bits", "group_size"].contains(key) { + // Unknown non-module metadata is retained by rawFields, never + // interpreted as a module override or dropped on roundtrip. + if native.values[key] == .bool(false) { + overrides[key] = .skip + } else if case .object(let object) = native.values[key], + !Set(object.keys).isDisjoint(with: ["mode", "bits", "group_size"]) + { + overrides[key] = .quantize(try Policy(native.object(key))) + } else if key.contains(".") || native.values[key] == .bool(true) { + throw native.error(key, "module override requires a native policy or false") + } + } + nativeOverrides = overrides + } else { + nativeDefault = nil + nativeOverrides = [:] + } + } + + public func policy(for modulePath: String) -> Policy? { + switch nativeOverrides[modulePath] { + case .skip: nil + case .quantize(let policy): policy + case nil: nativeDefault + } + } +} + +public struct MiMoV26EmbeddedMTPMetadata: Equatable, Sendable { + public let architecture: String + public let numLayers: Int + public let storage: String + public let file: String + + fileprivate init(_ f: MiMoV26Fields, expectedLayers: Int) throws { + architecture = try f.oneOf("architecture", ["mimo_v2_nextn"]) + numLayers = try f.int("num_layers") + storage = try f.oneOf("storage", ["embedded"]) + file = try f.string("file") + try f.require( + numLayers == expectedLayers, "num_layers", "must equal num_nextn_predict_layers") + try f.require( + !file.isEmpty && !file.hasPrefix("/") + && !file.split(separator: "/").contains(".."), "file", + "requires a relative component path") + } +} + +public struct MiMoV26VisionConfiguration: Equatable, Sendable { + public let rawFields: [String: MiMoV26JSONValue] + public let depth, hiddenSize, intermediateSize, queryHeads, keyValueHeads: Int + public let outputHiddenSize, patchSize, temporalPatchSize, spatialMergeSize: Int + public let fullAttentionBlocks, windowAttentionTypes: [Int] + public let usesSinks: Bool + + fileprivate init(_ f: MiMoV26Fields, targetHidden: Int) throws { + rawFields = f.values + depth = try f.int("depth") + hiddenSize = try f.int("hidden_size") + intermediateSize = try f.int("intermediate_size") + queryHeads = try f.int("num_heads") + keyValueHeads = try f.int("num_key_value_heads") + outputHiddenSize = try f.int("out_hidden_size") + patchSize = try f.int("patch_size") + temporalPatchSize = try f.int("temporal_patch_size") + spatialMergeSize = try f.int("spatial_merge_size") + fullAttentionBlocks = try f.integers("fullatt_block_indexes") + windowAttentionTypes = try f.integers("vit_window_attn_types", minimum: -1) + usesSinks = try f.bool("use_sink") + _ = try f.oneOf("hidden_act", ["silu"]) + _ = try f.int("window_size") + _ = try f.int("visual_token_window_size") + try f.require( + hiddenSize.isMultiple(of: queryHeads) && queryHeads.isMultiple(of: keyValueHeads), + "num_heads", "invalid vision GQA geometry") + try f.require( + try f.int("num_query_groups") == queryHeads / keyValueHeads, + "num_query_groups", "must equal query/KV ratio") + try f.require( + try f.int("spatial_patch_size") == patchSize, + "spatial_patch_size", "must agree with patch_size") + try f.require( + outputHiddenSize == targetHidden, "out_hidden_size", "must match text hidden_size") + try f.require( + windowAttentionTypes.count == depth + && windowAttentionTypes.allSatisfy { [-1, 0, 1].contains($0) }, + "vit_window_attn_types", "requires one supported window type per layer") + try f.require( + Set(fullAttentionBlocks).count == fullAttentionBlocks.count + && fullAttentionBlocks.allSatisfy { $0 < depth } + && Set(fullAttentionBlocks) + == Set(windowAttentionTypes.indices.filter { windowAttentionTypes[$0] == -1 }), + "fullatt_block_indexes", "must exactly identify full-attention layers") + } +} + +public struct MiMoV26AudioConfiguration: Equatable, Sendable { + public let rawFields: [String: MiMoV26JSONValue] + public let channels, segmentSize, groupSize, hiddenSize, queryHeads, headDim, layers: Int + public let outputHiddenSize, speechVocabularySize, zeroEmbeddingIndex: Int + + fileprivate init(_ f: MiMoV26Fields, targetHidden: Int) throws { + rawFields = f.values + channels = try f.int("audio_channels") + segmentSize = try f.int("audio_segment_size") + groupSize = try f.int("group_size") + hiddenSize = try f.int("input_local_dim") + queryHeads = try f.int("input_local_attn_heads") + headDim = try f.int("input_local_head_dim") + layers = try f.int("input_local_layers") + outputHiddenSize = try f.int("out_hidden_size") + // These two fields are strings in the official schema. Keep the + // original JSON representation while exposing validated integers. + guard let vocabulary = Int(try f.string("speech_vocab_size")), vocabulary > 0, + let zero = Int(try f.string("speech_zeroemb_idx")), zero >= 0, zero < vocabulary + else { + throw f.error("speech_vocab_size", "invalid speech vocabulary/zero embedding index") + } + speechVocabularySize = vocabulary + zeroEmbeddingIndex = zero + _ = try f.bool("add_post_norm") + _ = try f.bool("input_full_attention") + _ = try f.int("input_local_intermediate_size") + _ = try f.int("projection_layers") + _ = try f.number("rope_theta") + let dropout = try f.number("input_local_hidden_dropout", inclusive: true) + let rotaryFactor = try f.number("partial_rotary_factor") + try f.require( + dropout < 1 && rotaryFactor <= 1, "input_local_hidden_dropout", + "invalid dropout/RoPE factor") + try f.require( + try f.product(queryHeads, headDim, "input_local_dim") == hiddenSize, + "input_local_dim", "must equal heads times head dimension") + try f.require( + outputHiddenSize == targetHidden, "out_hidden_size", "must match text hidden_size") + } +} + +/// Native target configuration. Unknown fields survive encoding; accepting +/// metadata is not factory registration or proof of checkpoint completeness. +public struct MiMoV26Configuration: Codable, Equatable, Sendable { + public let rawFields: [String: MiMoV26JSONValue] + public let modelType: String + public let architectures: [String] + public let hiddenSize, intermediateSize, moeIntermediateSize, vocabularySize, + numHiddenLayers: Int + public let maxPositionEmbeddings, slidingWindow, numNextnPredictLayers: Int + public let hybridLayerPattern, moeLayerFrequency: [Int] + public let partialRotaryFactor, attentionValueScale, layernormEpsilon: Double + public let attentionProjectionLayout, moeRouterDType, hiddenActivation, dtype: String + public let attentionBias, tieWordEmbeddings, normalizeTopKProbability: Bool + public let attentionDropout: Double + public let routedExpertCount, expertsPerToken, expertGroupCount, topKGroups: Int + public let sharedExpertCount: Int? + public let routedScalingFactor: Double? + public let fullAttention, slidingAttention: MiMoV26AttentionGeometry + public let vision: MiMoV26VisionConfiguration? + public let audio: MiMoV26AudioConfiguration? + public let processorFields: [String: MiMoV26JSONValue]? + public let quantization: MiMoV26Quantization + public let embeddedMTP: MiMoV26EmbeddedMTPMetadata? + /// Complete native stop set; tokenIDs retains its primary EOS convenience + /// entry for scalar callers, not a substitute for generation stop semantics. + public let eosTokenIDs: Set + public let tokenIDs: [String: Int] + public var numAttentionHeads: Int { fullAttention.queryHeads } + public var numKeyValueHeads: Int { fullAttention.keyValueHeads } + public var headDim: Int { fullAttention.headDim } + public var valueHeadDim: Int { fullAttention.valueHeadDim } + + public init(from decoder: any Decoder) throws { + try self.init(rawFields: [String: MiMoV26JSONValue](from: decoder)) + } + public func encode(to encoder: any Encoder) throws { try rawFields.encode(to: encoder) } + + public init(rawFields: [String: MiMoV26JSONValue]) throws { + let f = MiMoV26Fields(values: rawFields) + self.rawFields = rawFields + modelType = try f.oneOf("model_type", ["mimo_v2"]) + architectures = try f.strings("architectures") + try f.require( + architectures == ["MiMoV2ForCausalLM"], "architectures", + "requires the native MiMoV2 target") + hiddenSize = try f.int("hidden_size") + intermediateSize = try f.int("intermediate_size") + moeIntermediateSize = try f.int("moe_intermediate_size") + vocabularySize = try f.int("vocab_size") + numHiddenLayers = try f.int("num_hidden_layers") + maxPositionEmbeddings = try f.int("max_position_embeddings") + slidingWindow = try f.int("sliding_window_size") + numNextnPredictLayers = try f.int("num_nextn_predict_layers", minimum: 0) + hybridLayerPattern = try f.integers("hybrid_layer_pattern") + moeLayerFrequency = try f.integers("moe_layer_freq") + for (name, pattern) in [ + ("hybrid_layer_pattern", hybridLayerPattern), ("moe_layer_freq", moeLayerFrequency), + ] { + try f.require( + pattern.count == numHiddenLayers && pattern.allSatisfy { $0 == 0 || $0 == 1 }, + name, "requires one binary entry per text layer") + } + try f.require( + try f.int("sliding_window") == slidingWindow, + "sliding_window", "must agree with sliding_window_size") + partialRotaryFactor = try f.number("partial_rotary_factor") + try f.require(partialRotaryFactor <= 1, "partial_rotary_factor", "must be <=1") + attentionValueScale = try f.number("attention_value_scale") + layernormEpsilon = try f.number("layernorm_epsilon") + attentionProjectionLayout = try f.oneOf( + "attention_projection_layout", ["split", "fused_qkv"]) + moeRouterDType = try f.oneOf("moe_router_dtype", ["bfloat16", "float32"]) + hiddenActivation = try f.oneOf("hidden_act", ["silu"]) + dtype = try f.oneOf("dtype", ["bfloat16", "float16", "float32"]) + attentionBias = try f.bool("attention_bias") + tieWordEmbeddings = try f.bool("tie_word_embeddings") + attentionDropout = try f.number("attention_dropout", inclusive: true) + try f.require(attentionDropout < 1, "attention_dropout", "must be <1") + _ = try f.oneOf("scoring_func", ["sigmoid"]) + _ = try f.oneOf("topk_method", ["noaux_tc"]) + routedExpertCount = try f.int("n_routed_experts") + expertsPerToken = try f.int("num_experts_per_tok") + expertGroupCount = try f.int("n_group") + topKGroups = try f.int("topk_group") + normalizeTopKProbability = try f.bool("norm_topk_prob") + sharedExpertCount = try f.optional("n_shared_experts") { try f.int($0) } + routedScalingFactor = try f.optional("routed_scaling_factor") { try f.number($0) } + try f.require( + routedExpertCount.isMultiple(of: expertGroupCount) + && topKGroups <= expertGroupCount && expertsPerToken <= routedExpertCount, + "n_group", "invalid expert/topk grouping") + let groupWidth = routedExpertCount / expertGroupCount + try f.require( + groupWidth >= 2 && expertsPerToken <= groupWidth * topKGroups, + "num_experts_per_tok", "group selection cannot supply requested experts") + fullAttention = try .init( + f, sliding: false, factor: partialRotaryFactor, window: slidingWindow) + slidingAttention = try .init( + f, sliding: true, factor: partialRotaryFactor, window: slidingWindow) + _ = try f.product(hiddenSize, intermediateSize, "dense MLP") + _ = try f.product(hiddenSize, moeIntermediateSize, "expert MLP") + if let rope = try f.optional("rope_parameters", f.object) { + _ = try rope.oneOf("rope_type", ["default"]) + if rope.values["type"] != nil { _ = try rope.oneOf("type", ["default"]) } + try rope.require( + try rope.number("rope_theta") == fullAttention.ropeTheta + && rope.number("partial_rotary_factor") == partialRotaryFactor, + "rope_theta", "nested RoPE must agree with text geometry") + } + let targetHiddenSize = hiddenSize + let predictorCount = numNextnPredictLayers + vision = try f.optional("vision_config") { + try .init(f.object($0), targetHidden: targetHiddenSize) + } + audio = try f.optional("audio_config") { + try .init(f.object($0), targetHidden: targetHiddenSize) + } + processorFields = try f.optional("processor_config") { try f.object($0).values } + quantization = try .init(f) + embeddedMTP = try f.optional("omlx_mimo_mtp") { + try .init(f.object($0), expectedLayers: predictorCount) + } + var tokens: [String: Int] = [:] + let eos: [Int] + if case .array = rawFields["eos_token_id"] { + eos = try f.integers("eos_token_id") + } else { + eos = [try f.int("eos_token_id", minimum: 0)] + } + let eosVocabularySize = vocabularySize + try f.require( + !eos.isEmpty && Set(eos).count == eos.count + && eos.allSatisfy { $0 < eosVocabularySize }, + "eos_token_id", "requires nonempty unique IDs within the text vocabulary") + eosTokenIDs = Set(eos) + tokens["eos_token_id"] = eos[0] + let mainTokens = [ + "pad_token_id", "bos_token_id", "image_token_id", "video_token_id", + "vision_start_token_id", "vision_end_token_id", "audio_token_id", + "audio_start_token_id", "audio_end_token_id", + ] + for key in mainTokens { + if let value = try f.optional(key, { try f.int($0, minimum: 0) }) { + try f.require(value < vocabularySize, key, "token exceeds text vocabulary") + tokens[key] = value + } + } + try f.require( + tokens["eos_token_id"] != nil && tokens["pad_token_id"] != nil, + "eos_token_id", "EOS and padding token IDs are required") + tokenIDs = tokens + if vision != nil || audio != nil { + let processor = try f.object("processor_config") + let requiredTokens = + (vision != nil + ? [ + "image_token_id", "video_token_id", "vision_start_token_id", + "vision_end_token_id", + ] : []) + + (audio != nil + ? ["audio_token_id", "audio_start_token_id", "audio_end_token_id"] : []) + for key in requiredTokens { + guard let token = tokens[key] else { + throw f.error(key, "modality token is required") + } + try processor.require( + try processor.int(key, minimum: 0) == token, key, + "must agree with text token namespace") + } + if let audio { + for (key, expected) in [ + ("audio_channels", audio.channels), ("audio_group_size", audio.groupSize), + ("audio_segment_size", audio.segmentSize), + ] { + try processor.require( + try processor.int(key) == expected, key, "must agree with audio_config") + } + let zeros = try processor.integers("audio_zeroemb_idx") + try processor.require( + zeros.count == audio.channels + && zeros.allSatisfy { $0 == audio.zeroEmbeddingIndex }, + "audio_zeroemb_idx", "must preserve every speech-channel zero index") + _ = try processor.int("audio_sampling_rate") + _ = try processor.int("audio_n_mels") + } + } + } + + public func attentionGeometry(at layer: Int) throws -> MiMoV26AttentionGeometry { + guard hybridLayerPattern.indices.contains(layer) else { + throw MiMoV26ConfigurationError.invalid(field: "layer", reason: "out of range") + } + return hybridLayerPattern[layer] == 1 ? slidingAttention : fullAttention + } +} + +/// Separate draft metadata; decoding this never changes the native target's +/// architecture or replaces its num_nextn_predict_layers with draft depth. +public struct MiMoV26DFlashMetadata: Codable, Equatable, Sendable { + public let rawFields: [String: MiMoV26JSONValue] + public let modelType: String + public let numHiddenLayers, targetLayerCount, targetHiddenSize, vocabularySize, blockSize, + maskTokenID: Int + public let targetLayerIDs: [Int] + + public init(from decoder: any Decoder) throws { + rawFields = try [String: MiMoV26JSONValue](from: decoder) + let f = MiMoV26Fields(values: rawFields) + modelType = try f.oneOf("model_type", ["qwen3"]) + try f.require( + try f.strings("architectures") == ["DFlashDraftModel"], "architectures", + "requires separate DFlash draft metadata") + numHiddenLayers = try f.int("num_hidden_layers") + targetLayerCount = try f.int("num_target_layers") + targetHiddenSize = try f.int("target_hidden_size") + vocabularySize = try f.int("vocab_size") + blockSize = try f.int("block_size") + let draft = try f.object("dflash_config") + maskTokenID = try draft.int("mask_token_id", minimum: 0) + targetLayerIDs = try draft.integers("target_layer_ids") + try draft.require( + try draft.int("block_size") == blockSize, "block_size", + "must agree with outer draft block size") + try draft.require( + !targetLayerIDs.isEmpty && Set(targetLayerIDs).count == targetLayerIDs.count + && targetLayerIDs.allSatisfy { $0 < targetLayerCount }, "target_layer_ids", + "invalid target feature layers") + try f.require( + try !f.bool("is_causal"), "is_causal", "DFlash block metadata must be noncausal") + try f.require(vocabularySize > maskTokenID, "vocab_size", "mask token exceeds vocabulary") + } + public func encode(to encoder: any Encoder) throws { try rawFields.encode(to: encoder) } + + public func validateTarget(_ target: MiMoV26Configuration) throws { + guard targetLayerCount == target.numHiddenLayers, targetHiddenSize == target.hiddenSize, + vocabularySize == target.vocabularySize + else { + throw MiMoV26ConfigurationError.invalid( + field: "dflash.target", reason: "target geometry mismatch") + } + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26DecodeKernels.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26DecodeKernels.swift new file mode 100644 index 0000000000..ca8dde242d --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26DecodeKernels.swift @@ -0,0 +1,219 @@ +// SPDX-License-Identifier: Apache-2.0 +// Adapted from jundot/omlx PR #3990, decode_fast.py at +// e58cab4d5db6c3ca27742a45a50ab6287b1b1bcb (2026). +// RMS reduction derived from MLX rms_norm.metal, Copyright © 2024 Apple Inc. +// Swift adaptation Copyright © 2026 Eigen Labs. +// Attribution: docs/mimo-v26/DECODE-KERNEL-ATTRIBUTION.md. + +import MLX +import MLXLMCommon +import MLXNN + +/// Source-only candidate for the residual/norm portion of the short-forward +/// path. No routing, expert projection, attention or cache arithmetic changes. +/// All weights are read on each call; no reload-sensitive tensor cache exists. +enum MiMoV26DecodeKernels { + struct Result { + let residual: MLXArray + let normalized: MLXArray + } + + /// Matches MLX's one-row RMS reduction: four values per lane, 32 lanes + /// per SIMD group and at most 32 SIMD groups per row. Batching is deliberately + /// excluded until the complete batched-state gate is qualified. + static func supports(shape: [Int], dtype: DType, device: DeviceType?) -> Bool { + guard device == .gpu, shape.count == 3, shape[0] == 1, + (1 ... 7).contains(shape[1]), (4 ... 4096).contains(shape[2]), + shape[2] % 4 == 0 + else { return false } + return dtype == .bfloat16 || dtype == .float16 + } + + private static func supports( + _ x: MLXArray, norm: RMSNorm, + stream: StreamOrDevice = .default + ) -> Bool { + supports(shape: x.shape, dtype: x.dtype, device: MiMoV26DecodeStream.deviceType(of: stream)) + && ObjectIdentifier(type(of: norm)) == ObjectIdentifier(RMSNorm.self) + && norm.weight.shape == [x.dim(-1)] && norm.weight.dtype == x.dtype + && norm.eps.isFinite && norm.eps > 0 + } + + /// Optional result is the dispatch witness used by component tests. A nil + /// result has not constructed a custom kernel or changed a cache. + static func addRMS(_ x: MLXArray, _ y: MLXArray, norm: RMSNorm) -> Result? { + let stream = StreamOrDevice.default + guard supports(x, norm: norm, stream: stream), y.shape == x.shape, y.dtype == x.dtype else { + return nil + } + let width = x.dim(-1) + let threads = ((width + 127) / 128) * 32 + let out = addKernel( + [x, y, norm.weight, MLXArray([norm.eps])], + template: [("T", x.dtype), ("AXIS", width)], + grid: (threads * x.dim(1), 1, 1), threadGroup: (threads, 1, 1), + outputShapes: [x.shape, x.shape], outputDTypes: [x.dtype, x.dtype], stream: stream) + return Result(residual: out[0], normalized: out[1]) + } + + /// The reference widens expert activations for FP32 weighting/reduction, + /// rounds the sum to the activation dtype, adds the residual in that dtype, + /// then normalizes. Retain each of those rounding points explicitly. + static func combineRMS( + _ h: MLXArray, experts: MLXArray, weights: MLXArray, + norm: RMSNorm + ) -> Result? { + let stream = StreamOrDevice.default + guard supports(h, norm: norm, stream: stream), experts.ndim == 4, weights.ndim == 3, + experts.shape == [1, h.dim(1), weights.dim(-1), h.dim(2)], + experts.dtype == h.dtype, + weights.shape == [1, h.dim(1), experts.dim(2)], + weights.dtype == .float32, (1 ... 32).contains(experts.dim(2)), + weights.size < 64 + else { return nil } + let width = h.dim(-1) + let threads = ((width + 127) / 128) * 32 + let out = combineKernel( + [h, experts, weights, norm.weight, MLXArray([norm.eps])], + template: [("T", h.dtype), ("AXIS", width), ("TOPK", experts.dim(2))], + grid: (threads * h.dim(1), 1, 1), threadGroup: (threads, 1, 1), + outputShapes: [h.shape, h.shape], outputDTypes: [h.dtype, h.dtype], stream: stream) + return Result(residual: out[0], normalized: out[1]) + } + + /// Complete the layer after its existing attention operation. The caller + /// carries `normalized` into the next layer (or returns it as final target + /// post-norm hidden state), while feature captures retain `residual`. + static func finishLayer( + _ hidden: MLXArray, attentionOutput: MLXArray, + layer: MiMoV26DecoderLayer, nextNorm: RMSNorm, + enabled: Bool + ) -> Result? { + guard enabled, supports(hidden, norm: nextNorm), + supports(hidden, norm: layer.postAttentionNorm), + let post = addRMS(hidden, attentionOutput, norm: layer.postAttentionNorm) + else { return nil } + + if let moe = layer.mlp as? MiMoV26MoE, + ObjectIdentifier(type(of: moe.switchMLP)) == ObjectIdentifier(SwitchGLU.self), + moe.gate.config.expertsPerToken <= 32, + hidden.dim(1) * moe.gate.config.expertsPerToken < 64 + { + // Invoke the original router and SwitchGLU. In particular, retain + // the declared router operand precision and its exact selection. + let routed = moe.gate(post.normalized) + let experts = moe.switchMLP(post.normalized, routed.indices) + if let combined = combineRMS( + post.residual, experts: experts, + weights: routed.weights, norm: nextNorm) + { + return combined + } + // Same already-computed rows and weights if a future module changes + // their dtype/layout. Never rerun the router or drop a projection. + let output = (experts * routed.weights[.ellipsis, .newAxis]) + .sum(axis: -2).asType(hidden.dtype) + if let added = addRMS(post.residual, output, norm: nextNorm) { return added } + let residual = post.residual + output + return Result(residual: residual, normalized: nextNorm(residual)) + } + let output = layer.mlp(post.normalized) + if let added = addRMS(post.residual, output, norm: nextNorm) { return added } + let residual = post.residual + output + return Result(residual: residual, normalized: nextNorm(residual)) + } + + // Static kernels initialize lazily, only after the GPU/shape/dtype gate. + // This is ordinary SIMD Metal, with no NAX or M5-specific dispatch. + private static let rmsTail = """ + acc = simd_sum(acc); + if (simd_group_id == 0) { + local_sums[simd_lane_id] = 0; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (simd_lane_id == 0) { + local_sums[simd_group_id] = acc; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (simd_group_id == 0) { + acc = simd_sum(local_sums[simd_lane_id]); + if (simd_lane_id == 0) { + local_inv_mean[0] = metal::precise::rsqrt(acc / axis_size + eps); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int i = 0; i < N_READS; i++) { + if (lid * N_READS + i < axis_size) { + n_out[base + i] = w[lid * N_READS + i] + * static_cast(thread_x[i] * local_inv_mean[0]); + } + } + """ + + private static let addKernel = MLXFast.metalKernel( + name: "mimo_v26_decode_add_rms", + inputNames: ["x", "y", "w", "eps_in"], outputNames: ["h_out", "n_out"], + source: """ + constexpr int N_READS = 4; + threadgroup float local_inv_mean[1]; + threadgroup float local_sums[32]; + uint gid = threadgroup_position_in_grid.x; + uint lid = thread_position_in_threadgroup.x; + uint simd_lane_id = thread_index_in_simdgroup; + uint simd_group_id = simdgroup_index_in_threadgroup; + const uint axis_size = AXIS; + const float eps = eps_in[0]; + size_t base = size_t(gid) * axis_size + lid * N_READS; + float acc = 0; + float thread_x[N_READS]; + for (int i = 0; i < N_READS; i++) { + if (lid * N_READS + i < axis_size) { + T hv = x[base + i] + y[base + i]; + h_out[base + i] = hv; + thread_x[i] = hv; + } else { + thread_x[i] = 0; + } + acc += thread_x[i] * thread_x[i]; + } + """ + rmsTail, ensureRowContiguous: true) + + private static let combineKernel = MLXFast.metalKernel( + name: "mimo_v26_decode_combine_residual_rms", + inputNames: ["h", "y", "scores", "w", "eps_in"], + outputNames: ["h_out", "n_out"], + source: """ + constexpr int N_READS = 4; + threadgroup float local_inv_mean[1]; + threadgroup float local_sums[32]; + uint gid = threadgroup_position_in_grid.x; + uint lid = thread_position_in_threadgroup.x; + uint simd_lane_id = thread_index_in_simdgroup; + uint simd_group_id = simdgroup_index_in_threadgroup; + const uint axis_size = AXIS; + const float eps = eps_in[0]; + size_t base = size_t(gid) * axis_size + lid * N_READS; + size_t ybase = size_t(gid) * TOPK * axis_size + lid * N_READS; + float acc = 0; + float thread_x[N_READS]; + for (int i = 0; i < N_READS; i++) { + if (lid * N_READS + i < axis_size) { + float total = 0; + for (int k = 0; k < TOPK; k++) { + // The materialized reference rounds each FP32 product + // before the sum; volatile prohibits FMA contraction. + volatile float product = static_cast( + y[ybase + size_t(k) * axis_size + i]) * scores[gid * TOPK + k]; + total = product + total; + } + T yv = static_cast(total); + T hv = h[base + i] + yv; + h_out[base + i] = hv; + thread_x[i] = hv; + } else { + thread_x[i] = 0; + } + acc += thread_x[i] * thread_x[i]; + } + """ + rmsTail, ensureRowContiguous: true) +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26DecodeRouter.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26DecodeRouter.swift new file mode 100644 index 0000000000..9679a91084 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26DecodeRouter.swift @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: Apache-2.0 +// Adapted from jundot/omlx #3990 decode_fast.py, exact head +// e58cab4d5db6c3ca27742a45a50ab6287b1b1bcb. +// GEMV reduction derived from MLX gemv.h, Copyright © 2023-2024 Apple Inc. +// Swift adaptation Copyright © 2026 Eigen Labs. +// Attribution: docs/mimo-v26/DECODE-ROUTER-ATTRIBUTION.md. + +import Foundation +import MLX + +/// Streams each router weight once for 1...7 rows. Every row uses the pinned +/// M=1 FP32 GEMV reduction. Multi-row GEMM may have another FP32 sum order. +/// This helper does not select experts, normalize scores or retain weights. +enum MiMoV26DecodeRouter { + static let enabledByEnvironment = + ProcessInfo.processInfo.environment["DARKBLOOM_MIMO_DECODE_ROUTER_GEMV"] == "1" + + static func supports( + shape: [Int], weightShape: [Int], inputDType: DType, + weightDType: DType, operandDType: DType, + device: DeviceType? + ) -> Bool { + guard device == .gpu, shape.count == 3, weightShape.count == 2, + shape[0] == 1, (1 ... 7).contains(shape[1]), + shape[2] == weightShape[1], (1024 ... 4096).contains(shape[2]), + shape[2] % 1024 == 0, (4 ... 256).contains(weightShape[0]), + weightShape[0] % 4 == 0, shape[2] >= 16 * weightShape[0], + operandDType == .bfloat16 || operandDType == .float32 + else { return false } + let floats: [DType] = [.float16, .bfloat16, .float32] + return floats.contains(inputDType) && floats.contains(weightDType) + } + + static func logits( + _ x: MLXArray, weight: MLXArray, operandDType: DType, + enabled: Bool + ) -> MLXArray? { + let stream = StreamOrDevice.default + guard enabled, + supports( + shape: x.shape, weightShape: weight.shape, + inputDType: x.dtype, weightDType: weight.dtype, + operandDType: operandDType, + device: MiMoV26DecodeStream.deviceType(of: stream)) + else { return nil } + + // Preserve MiMoV26Router's declared operand rounding BEFORE widening. + // For loaded BF16 weights these are no-op views; no persistent FP32 + // copy is added. The kernel widens each already-rounded element exactly. + let operands = x.asType(operandDType, stream: stream) + let matrix = weight.asType(operandDType, stream: stream) + let outputs = kernel( + [operands, matrix], + template: [ + ("T", operands.dtype), ("W", matrix.dtype), + ("ROWS", x.dim(1)), ("KDIM", x.dim(2)), ("NOUT", weight.dim(0)), + ], + grid: (32 * (weight.dim(0) / 4), 8, 1), threadGroup: (32, 8, 1), + outputShapes: [[1, x.dim(1), weight.dim(0)]], outputDTypes: [.float32], stream: stream) + return outputs[0] + } + + private static let kernel = MLXFast.metalKernel( + name: "mimo_v26_decode_router_gemv", + inputNames: ["vec", "mat"], outputNames: ["out"], + source: """ + constexpr int TM = 4; + constexpr int TN = 4; + constexpr int SN = 32; + constexpr int BN = 8; + constexpr int blockM = 4; + constexpr int blockN = BN * SN * TN; + threadgroup float tgp_memory[ROWS * BN * (blockM + TM)]; + uint tid = threadgroup_position_in_grid.x; + uint simd_gid = simdgroup_index_in_threadgroup; + uint simd_lid = thread_index_in_simdgroup; + int thrN = simd_lid; + int sgN = simd_gid; + int bn = (SN * sgN + thrN) * TN; + int out_row = tid * blockM; + const device W* matp = mat + size_t(out_row) * KDIM; + + float result[ROWS][TM]; + for (int r = 0; r < ROWS; r++) { + for (int tm = 0; tm < TM; tm++) { result[r][tm] = 0; } + } + for (int i = 0; i < KDIM / blockN; ++i) { + float v_coeff[ROWS][TN]; + for (int r = 0; r < ROWS; r++) { + for (int tn = 0; tn < TN; tn++) { + v_coeff[r][tn] = static_cast(vec[size_t(r) * KDIM + bn + tn]); + } + } + int mat_offset = 0; + for (int tm = 0; tm < TM; tm++) { + float inter[TN]; + for (int tn = 0; tn < TN; tn++) { + inter[tn] = static_cast(matp[mat_offset + bn + tn]); + } + for (int r = 0; r < ROWS; r++) { + for (int tn = 0; tn < TN; tn++) { + result[r][tm] += inter[tn] * v_coeff[r][tn]; + } + } + mat_offset += KDIM; + } + bn += blockN; + } + for (int r = 0; r < ROWS; r++) { + for (int tm = 0; tm < TM; tm++) { + for (ushort sn = (SN / 2); sn >= 1; sn >>= 1) { + result[r][tm] += simd_shuffle_down(result[r][tm], sn); + } + } + } + threadgroup float* tgp_results = tgp_memory + sgN * (blockM + TM); + if (thrN == 0) { + for (int r = 0; r < ROWS; r++) { + for (int tm = 0; tm < TM; tm++) { + tgp_results[r * BN * (blockM + TM) + tm] = result[r][tm]; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sgN == 0 && thrN == 0) { + for (int r = 0; r < ROWS; r++) { + for (int sgn = 1; sgn < BN; sgn++) { + for (int tm = 0; tm < TM; tm++) { + result[r][tm] += tgp_memory[ + r * BN * (blockM + TM) + sgn * (blockM + TM) + tm]; + } + } + for (int tm = 0; tm < TM; tm++) { + out[size_t(r) * NOUT + out_row + tm] = result[r][tm]; + } + } + } + """, ensureRowContiguous: true) +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26DecodeStream.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26DecodeStream.swift new file mode 100644 index 0000000000..eee6f26062 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26DecodeStream.swift @@ -0,0 +1,20 @@ +// Copyright © 2026 Eigen Labs. + +import Cmlx +import MLX + +/// Resolve the actual operation stream, including a task-local override. +/// Device.defaultDevice alone does not describe StreamOrDevice.default. +enum MiMoV26DecodeStream { + static func deviceType(of stream: StreamOrDevice) -> DeviceType? { + var device = mlx_device_new() + defer { mlx_device_free(device) } + var type = MLX_CPU + guard mlx_stream_get_device(&device, stream.ctx) == 0, + mlx_device_get_type(&type, device) == 0 + else { return nil } + if type == MLX_GPU { return .gpu } + if type == MLX_CPU { return .cpu } + return nil + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26MTP.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26MTP.swift new file mode 100644 index 0000000000..a5f5cc738d --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26MTP.swift @@ -0,0 +1,583 @@ +// Copyright © 2026 Eigen Labs. +// Native next-N predictors, not the separately shipped DFlash draft model. +// Reference: sglang/mimo_v2_nextn.py @67bb6a58d0dad4a39af80fa1b2bf86f0de0cb99b. +// That file is byte-identical to the prior @2261c2e reference (see MTP-RESULT). +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +public enum MiMoV26MTPError: Error, Equatable, Sendable { + case unsupportedConfiguration(String) + case incompatibleOwner + case weightsNotLoaded + case invalidWeights(String) + case invalidInput(String) + case invalidHistory(String) + case contextExceeded +} + +/// Bit-preserving device copy. The request fence must verify its fresh compact +/// backing before granting materialized credit; construction alone proves none. +func mimoV26MTPCopy(_ array: MLXArray) -> MLXArray { + // A floating select may normalize BF16 subnormals or NaN payload bits. + // Select an equal-width integer view instead: no floating conversion or + // arithmetic, and even scalar/noncontiguous inputs keep their geometry. + let bits: MLXArray + switch array.dtype { + case .float16, .bfloat16: bits = array.view(dtype: .uint16) + case .float32: bits = array.view(dtype: .uint32) + case .float64, .complex64: bits = array.view(dtype: .uint64) + default: bits = array + } + return MLX.where(MLXArray(true), bits, bits).view(dtype: array.dtype) +} + +/// A non-Module box deliberately hides the weak target from Module reflection. +/// The live reference, not a potentially reused ObjectIdentifier, proves ownership. +private final class MiMoV26MTPTargetOwner { + weak var target: MiMoV26TextModel? + init(_ target: MiMoV26TextModel) { self.target = target } +} + +/// 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 + let firstPosition: Int + init(window: Int, firstPosition: Int) { + storage = RotatingKVCache(maxSize: window) + self.firstPosition = firstPosition + } + var offset: Int { firstPosition + storage.offset } + var maxSize: Int? { storage.maxSize } + var state: [MLXArray] { + get { storage.state } + set { storage.state = newValue } + } + var metaState: [String] { + get { storage.metaState } + set { storage.metaState = newValue } + } + var isTrimmable: Bool { false } + func trim(_ n: Int) -> Int { 0 } + func innerState() -> [MLXArray] { storage.innerState() } + func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + storage.update(keys: keys, values: values) + } + func makeMask(n: Int, windowSize: Int?, returnArray: Bool) + -> MLXFast.ScaledDotProductAttentionMaskMode + { + storage.makeMask(n: n, windowSize: windowSize, returnArray: returnArray) + } + func copy() -> any KVCache { + let result = MiMoV26MTPPositionedCache( + window: storage.maxSize!, firstPosition: firstPosition) + let snapshot = storage.copy() + let arrays = snapshot.state + // RotatingKVCache's setter requires exactly two arrays, even when the + // source is fresh. Preserve its empty initial state without that setter. + if !arrays.isEmpty { result.storage.state = arrays } + result.storage.metaState = snapshot.metaState + return result + } + + // Multi-token rotating updates temporarily keep window+chunk-1 entries + // for attention. Once that forward has captured its reads, keep a detached + // chronological suffix; metadata preserves the absolute rotary frontier. + func compactRetainedHistory() { + let arrays = storage.state + guard arrays.count == 2 else { return } + let window = storage.maxSize! + if arrays[0].dim(2) > window { + storage.state = arrays.map { mimoV26MTPCopy($0[0..., 0..., (-window)..., 0...]) } + var metadata = storage.metaState + metadata[4] = String(window) + storage.metaState = metadata + } else { + // A first multi-token update can retain transposed/shared projection + // storage even when it fits the window. Detach the live bytes before + // the unchanged request fence proves compact independent ownership. + // Full rings retain their PHYSICAL order and existing ring index; + // partial history retains its exact offset/first-position metadata. + storage.state = arrays.map(mimoV26MTPCopy) + } + } + + func detachedCopy() -> MiMoV26MTPPositionedCache { + let result = copy() as! MiMoV26MTPPositionedCache + if !result.state.isEmpty { result.state = result.state.map(mimoV26MTPCopy) } + return result + } +} + +/// One request owns all predictor histories; no externally mutable KV cache is +/// accepted. The assistant owns transactional copies for speculation; this +/// component remains append-only. Do not share a live cache across requests. +public final class MiMoV26MTPRequestCache: Evaluatable { + fileprivate weak var owner: MiMoV26MTP? + fileprivate let generation: UInt64 + fileprivate let layers: [MiMoV26MTPPositionedCache] + fileprivate var batchSize: Int? + + fileprivate init( + owner: MiMoV26MTP, generation: UInt64, window: Int, + count: Int, basePosition: Int + ) { + self.owner = owner + self.generation = generation + layers = (0 ..< count).map { + MiMoV26MTPPositionedCache(window: window, firstPosition: basePosition + $0 + 1) + } + } + public var nextTokenPositions: [Int] { layers.map(\.offset) } + public var consumedTokenCounts: [Int] { layers.map { $0.storage.offset } } + public var stateShapesByDepth: [[[Int]]] { layers.map { $0.innerState().map(\.shape) } } + /// Scalar-only observation for admitted-engine state tests. Each row is + /// firstPosition, keep, window, step, localOffset, physicalRingIndex. + /// No array/view, native read, evaluation or ownership transfer is created. + var retainedHistoryMetadataForTesting: [[String]] { + layers.map { [String($0.firstPosition)] + $0.metaState } + } + public func innerState() -> [MLXArray] { layers.flatMap { $0.innerState() } } + + private init(copying source: MiMoV26MTPRequestCache) { + owner = source.owner + generation = source.generation + layers = source.layers.map { $0.detachedCopy() } + batchSize = source.batchSize + } + + func detachedCopy() -> MiMoV26MTPRequestCache { .init(copying: self) } + func compactRetainedHistory(depth: Int) { layers[depth].compactRetainedHistory() } + + // 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, + generation == expectedOwner.loadedGeneration, batchSize == 1, + layers.count == 3, count >= 4, + count < expectedOwner.configuration.maxPositionEmbeddings + else { return nil } + let c = expectedOwner.configuration + var result: [MiMoV26MTPPrefixHead] = [] + for (depth, layer) in layers.enumerated() { + let raw = layer.innerState() + let strings = layer.metaState + guard raw.count == 2, strings.count == 5 else { return nil } + let scalars = strings.compactMap(Int64.init) + guard scalars.count == 5 else { return nil } + let metadata = + [Int64(layer.firstPosition)] + scalars + + [Int64(min(max(0, count - depth - 1), c.slidingWindow))] + let rawHead = MiMoV26MTPPrefixHead(keys: raw[0], values: raw[1], metadata: metadata) + guard + MiMoV26MTPPrefixValidation.headIsValid( + rawHead, depth: depth, count: count, + configuration: c, allowsUnusedCapacity: true) + else { return nil } + let live = layer.state + let head = MiMoV26MTPPrefixHead(keys: live[0], values: live[1], metadata: metadata) + guard + MiMoV26MTPPrefixValidation.headIsValid( + head, depth: depth, count: count, + configuration: c) + else { return nil } + result.append(head) + } + return result + } + + // A fresh, unobserved cache only. Preflight ALL heads before any mutation; + // this never writes a live request or donor. The caller owns the admitted + // off-to-the-side state until atomic target+assistant adoption completes. + func restorePrefixHeads( + _ heads: [MiMoV26MTPPrefixHead], count: Int, + expectedOwner: MiMoV26MTP + ) -> Bool { + guard owner === expectedOwner, generation == expectedOwner.loadedGeneration, + expectedOwner.isLoaded, batchSize == nil, layers.count == 3, + layers.allSatisfy({ $0.innerState().isEmpty && $0.storage.offset == 0 }), + heads.count == 3, + heads.enumerated().allSatisfy({ + MiMoV26MTPPrefixValidation.headIsValid( + $0.element, depth: $0.offset, + count: count, configuration: expectedOwner.configuration) + }) + else { return false } + for (depth, head) in heads.enumerated() { + layers[depth].state = [mimoV26MTPCopy(head.keys), mimoV26MTPCopy(head.values)] + layers[depth].metaState = head.metadata[1 ... 5].map(String.init) + } + batchSize = 1 + return true + } +} + +public enum MiMoV26MTPFeatureProvenance: Equatable, Sendable { + case targetPostNorm + case predictorPostNorm(depth: Int) +} + +/// Features describe the positions producing hidden states. The pinned MiMo +/// driver reuses the same post-final-norm TARGET feature at every predictor +/// depth; token positions advance by depth+1. Predictor readout features are +/// exposed for diagnostics, never accepted as the next predictor's input. +public struct MiMoV26MTPFeatures { + public let normalizedHiddenStates: MLXArray + public let firstPosition: Int + public let provenance: MiMoV26MTPFeatureProvenance + fileprivate let targetOwner: MiMoV26MTPTargetOwner + fileprivate weak var predictor: MiMoV26MTP? + fileprivate let generation: UInt64? + + /// Ownership and positions come from the target's actual forward output. + /// The caller may select rows, but cannot relabel their producer or position. + /// All validation precedes array indexing or creation of a sliced feature. + public init( + targetOutput: MiMoV26TextOutput, target: MiMoV26TextModel, + range: Range? = nil + ) throws { + guard targetOutput.ownerIdentity == target.identity else { + throw MiMoV26MTPError.incompatibleOwner + } + let hidden = targetOutput.normalizedHiddenStates + guard hidden.ndim == 3, hidden.dim(0) > 0, hidden.dim(1) > 0, + hidden.dim(2) == target.configuration.hiddenSize, + hidden.dtype == target.activationDType + else { + throw MiMoV26MTPError.invalidInput("target normalized-feature geometry or dtype") + } + let selected = range ?? (0 ..< hidden.dim(1)) + guard selected.lowerBound >= 0, selected.upperBound > selected.lowerBound, + selected.upperBound <= hidden.dim(1) + else { + throw MiMoV26MTPError.invalidInput( + "target feature range must be nonempty and in bounds") + } + let limit = target.configuration.maxPositionEmbeddings + let position = targetOutput.firstPosition.addingReportingOverflow(selected.lowerBound) + guard targetOutput.firstPosition >= 0, targetOutput.firstPosition <= limit, + hidden.dim(1) <= limit - targetOutput.firstPosition, + !position.overflow, position.partialValue >= 0, position.partialValue < limit, + selected.count <= limit - position.partialValue + else { + throw MiMoV26MTPError.contextExceeded + } + normalizedHiddenStates = hidden[0..., selected, 0...] + firstPosition = position.partialValue + provenance = .targetPostNorm + targetOwner = MiMoV26MTPTargetOwner(target) + predictor = nil + generation = nil + } + + fileprivate init( + hidden: MLXArray, firstPosition: Int, depth: Int, predictor: MiMoV26MTP, + owner: MiMoV26MTPTargetOwner, generation: UInt64 + ) { + normalizedHiddenStates = hidden + self.firstPosition = firstPosition + provenance = .predictorPostNorm(depth: depth) + targetOwner = owner + self.predictor = predictor + self.generation = generation + } + + // The CBv2 assistant is the sole consumer of the target's family-specific + // trusted hidden seam. This initializer is deliberately not public. + init(trustedTargetHidden: MLXArray, firstPosition: Int, target: MiMoV26TextModel) { + normalizedHiddenStates = trustedTargetHidden + self.firstPosition = firstPosition + provenance = .targetPostNorm + targetOwner = MiMoV26MTPTargetOwner(target) + predictor = nil + generation = nil + } +} + +public struct MiMoV26MTPOutput { + public let logits: MLXArray + public let features: MiMoV26MTPFeatures + public var normalizedHiddenStates: MLXArray { features.normalizedHiddenStates } +} + +/// Keys retain the checkpoint's pre_mlp_layernorm spelling. SGLang renames +/// that key to post_attention_layernorm internally, not in the original file. +final class MiMoV26MTPHead: Module { + let enorm: RMSNorm + let hnorm: RMSNorm + @ModuleInfo(key: "eh_proj") var ehProjection: Linear + @ModuleInfo(key: "input_layernorm") var inputNorm: RMSNorm + @ModuleInfo(key: "pre_mlp_layernorm") var preMLPNorm: RMSNorm + @ModuleInfo(key: "final_layernorm") var finalNorm: RMSNorm + @ModuleInfo(key: "self_attn") var attention: MiMoV26Attention + let mlp: MiMoV26DenseMLP + + init(_ config: MiMoV26Configuration) { + let eps = Float(config.layernormEpsilon) + enorm = RMSNorm(dimensions: config.hiddenSize, eps: eps) + hnorm = RMSNorm(dimensions: config.hiddenSize, eps: eps) + _ehProjection.wrappedValue = Linear(2 * config.hiddenSize, config.hiddenSize, bias: false) + _inputNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: eps) + _preMLPNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: eps) + _finalNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: eps) + _attention.wrappedValue = MiMoV26Attention(config, geometry: config.slidingAttention) + mlp = MiMoV26DenseMLP( + hiddenSize: config.hiddenSize, intermediateSize: config.intermediateSize) + } + + fileprivate func forward( + hidden: MLXArray, embeddings: MLXArray, + cache: MiMoV26MTPPositionedCache + ) -> MLXArray { + let projected = ehProjection(concatenated([enorm(embeddings), hnorm(hidden)], axis: -1)) + let mask = createAttentionMask( + h: projected, cache: cache.storage, windowSize: cache.maxSize) + let attended = projected + attention(inputNorm(projected), mask: mask, cache: cache) + return finalNorm(attended + mlp(preMLPNorm(attended))) + } +} + +/// Native trained-head component. The target owns its embedding/readout once; +/// this module borrows those exact objects during forward and never registers +/// them in its parameter tree. Every declared head must load strictly before use. +public final class MiMoV26MTP: Module { + public let configuration: MiMoV26Configuration + let layers: [MiMoV26MTPHead] + private let targetOwner: MiMoV26MTPTargetOwner + private var weightGeneration: UInt64 = 0 + public private(set) var isLoaded = false + public var headCount: Int { layers.count } + var loadedGeneration: UInt64 { weightGeneration } + func belongs(to target: MiMoV26TextModel) -> Bool { targetOwner.target === target } + + public init(target: MiMoV26TextModel, floatingProjections: Bool = false) throws { + let config = target.configuration + let doubled = config.hiddenSize.multipliedReportingOverflow(by: 2) + guard config.numNextnPredictLayers == 3, + !doubled.overflow, doubled.partialValue <= Int(Int32.max), + config.numNextnPredictLayers < config.maxPositionEmbeddings + else { + throw MiMoV26MTPError.unsupportedConfiguration("next-N/concatenation dimensions") + } + configuration = config + targetOwner = MiMoV26MTPTargetOwner(target) + layers = (0 ..< config.numNextnPredictLayers).map { _ in MiMoV26MTPHead(config) } + super.init() + // Native converted MTP projections have explicit affine policies. Never + // apply the trunk's MXFP4 default to an unlisted predictor projection. + if floatingProjections { + guard config.dtype == "bfloat16", config.quantization.nativeDefault?.mode == "affine", + config.quantization.nativeDefault?.bits == 4, + config.quantization.nativeDefault?.groupSize == 64, + !config.quantization.nativeOverrides.keys.contains(where: { + $0.hasPrefix("mtp.") || $0.hasPrefix("language_model.mtp.") + || $0.hasPrefix("language_model.model.mtp.") + }) + else { + throw MiMoV26MTPError.unsupportedConfiguration( + "floating MTP must not inherit or contradict a quantization policy") + } + } else if config.quantization.nativeDefault != nil { + var policies: [String: MiMoV26Quantization.Policy] = [:] + for (path, module) in leafModules().flattened() where module is Linear { + let short = config.quantization.nativeOverrides["mtp." + path] + let wrapped = config.quantization.nativeOverrides["language_model.mtp." + path] + if let short, let wrapped, short != wrapped { + throw MiMoV26MTPError.unsupportedConfiguration( + "conflicting MTP quantization aliases: \(path)") + } + guard let policy = short ?? wrapped else { + throw MiMoV26MTPError.unsupportedConfiguration( + "missing explicit MTP projection policy: \(path)") + } + switch policy { + case .skip: break + case .quantize(let value): + guard value.mode == "affine", value.bits == 4, value.groupSize == 64, + let linear = module as? Linear, + linear.weight.dim(1).isMultiple(of: value.groupSize) + else { + throw MiMoV26MTPError.unsupportedConfiguration( + "unsupported MTP projection policy: \(path)") + } + policies[path] = value + } + } + // Head-local updates avoid sparse array traversal when a declared + // head/projection intentionally stays in its source precision. + for (index, head) in layers.enumerated() { + var updates: [(String, Module)] = [] + for (path, module) in head.leafModules().flattened() { + guard let policy = policies["layers.\(index)." + path] else { continue } + guard + let replacement = quantizeSingle( + layer: module, groupSize: policy.groupSize, + bits: policy.bits, mode: .affine) + else { + throw MiMoV26MTPError.unsupportedConfiguration( + "unquantizable predictor: \(path)") + } + updates.append((path, replacement)) + } + try head.update(modules: .unflattened(updates), verify: .noUnusedKeys) + } + } + } + + /// Strict converted component load; no source FP8 expansion, fused-QKV + /// splitting or checkpoint-wide filtering occurs here. The caller must + /// supply exactly this component's tensors under its explicit prefix. + public func loadConvertedWeights(_ weights: [String: MLXArray], prefix: String = "mtp.") throws + { + guard let target = targetOwner.target else { throw MiMoV26MTPError.incompatibleOwner } + guard ["", "mtp.", "language_model.mtp."].contains(prefix) else { + throw MiMoV26MTPError.invalidWeights("unsupported converted component prefix") + } + var normalized: [String: MLXArray] = [:] + for (name, value) in weights { + guard name.hasPrefix(prefix) else { + throw MiMoV26MTPError.invalidWeights("out-of-component key: \(name)") + } + normalized[String(name.dropFirst(prefix.count))] = value + } + let expected = Dictionary(uniqueKeysWithValues: parameters().flattened()) + guard Set(normalized.keys) == Set(expected.keys) else { + throw MiMoV26MTPError.invalidWeights("missing or extra trained predictor tensors") + } + let dtype = target.activationDType + for (name, value) in normalized { + let shape = expected[name]! + let expectedDType: DType = shape.dtype == .uint32 ? .uint32 : dtype + guard value.shape == shape.shape, value.dtype == expectedDType else { + throw MiMoV26MTPError.invalidWeights("incompatible shape/dtype: \(name)") + } + } + // Preflight covers every head before update can modify the first head. + try update(parameters: .unflattened(normalized), verify: .all) + weightGeneration &+= 1 + isLoaded = true + } + + /// 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 { + guard basePosition >= 0, basePosition < configuration.maxPositionEmbeddings - headCount, + targetOwner.target != nil + else { throw MiMoV26MTPError.invalidHistory("invalid live owner/base position") } + return MiMoV26MTPRequestCache( + owner: self, generation: weightGeneration, + window: configuration.slidingWindow, count: headCount, + basePosition: basePosition) + } + + /// Every depth consumes the same normalized target feature. MiMoV2MTP is + /// deliberately absent from SGLang's chain_mtp_hidden_states allowlist. + /// IDs align depth+1 positions AFTER the target feature rows. The caller + /// owns per-depth shifted priming, scheduling and speculative rollback. + public func forward( + depth: Int, features: MiMoV26MTPFeatures, inputIDs: MLXArray, + target: MiMoV26TextModel, cache: MiMoV26MTPRequestCache + ) throws -> MiMoV26MTPOutput { + try forward( + depth: depth, features: features, inputIDs: inputIDs, target: target, + cache: cache, validateTokenValues: true) + } + + // Engine IDs already passed prompt/sampler vocabulary checks. Preserve all + // geometry/owner/generation checks without adding a host readback per head. + func forwardTrusted( + depth: Int, features: MiMoV26MTPFeatures, inputIDs: MLXArray, + target: MiMoV26TextModel, cache: MiMoV26MTPRequestCache + ) throws -> MiMoV26MTPOutput { + try forward( + depth: depth, features: features, inputIDs: inputIDs, target: target, + cache: cache, validateTokenValues: false) + } + + func primeTrusted( + depth: Int, features: MiMoV26MTPFeatures, inputIDs: MLXArray, + target: MiMoV26TextModel, cache: MiMoV26MTPRequestCache + ) throws { + _ = try forward( + depth: depth, features: features, inputIDs: inputIDs, target: target, + cache: cache, validateTokenValues: false, projectLogits: false) + } + + private func forward( + depth: Int, features: MiMoV26MTPFeatures, inputIDs: MLXArray, + target: MiMoV26TextModel, cache: MiMoV26MTPRequestCache, + validateTokenValues: Bool, projectLogits: Bool = true + ) throws -> MiMoV26MTPOutput { + guard targetOwner.target === target, features.targetOwner.target === target, + cache.owner === self + else { throw MiMoV26MTPError.incompatibleOwner } + guard isLoaded else { throw MiMoV26MTPError.weightsNotLoaded } + guard layers.indices.contains(depth), cache.generation == weightGeneration else { + throw MiMoV26MTPError.invalidHistory("head index or stale loaded-weight generation") + } + guard features.provenance == .targetPostNorm else { + throw MiMoV26MTPError.invalidHistory( + "MiMo predictors require target features, not a predictor chain") + } + let hidden = features.normalizedHiddenStates + guard hidden.ndim == 3, hidden.dim(2) == configuration.hiddenSize, + hidden.dtype == target.activationDType, inputIDs.ndim == 2, + inputIDs.dtype == .int32 || inputIDs.dtype == .uint32, + inputIDs.shape == Array(hidden.shape.prefix(2)), hidden.dim(0) > 0, hidden.dim(1) > 0, + target.hasLoadedEmbeddingPrecision + else { + throw MiMoV26MTPError.invalidInput( + "aligned IDs and loaded-precision normalized features required") + } + guard target.hasLoadedReadoutPrecision else { + throw MiMoV26MTPError.invalidInput( + "target readout must match the loaded native storage policy") + } + let batch = hidden.dim(0) + let length = hidden.dim(1) + let advance = depth + 1 + guard features.firstPosition >= 0, + features.firstPosition < configuration.maxPositionEmbeddings, + length <= configuration.maxPositionEmbeddings - features.firstPosition - advance + else { + throw MiMoV26MTPError.contextExceeded + } + let firstTokenPosition = features.firstPosition + advance + guard cache.layers[depth].offset == firstTokenPosition, + cache.batchSize == nil || cache.batchSize == batch + else { + throw MiMoV26MTPError.invalidHistory( + "noncontiguous shifted history or changed batch membership") + } + if validateTokenValues { + let minimum = + inputIDs.dtype == .int32 + ? Int64(inputIDs.min().item(Int32.self)) + : Int64(inputIDs.min().item(UInt32.self)) + let maximum = + inputIDs.dtype == .int32 + ? Int64(inputIDs.max().item(Int32.self)) + : Int64(inputIDs.max().item(UInt32.self)) + guard minimum >= 0, maximum < Int64(configuration.vocabularySize) else { + throw MiMoV26MTPError.invalidInput("token ID outside target vocabulary") + } + } + // All input/ownership checks precede cache mutation and embedding lookup. + cache.batchSize = batch + let output = layers[depth].forward( + hidden: hidden, embeddings: target.model.embedTokens(inputIDs), + cache: cache.layers[depth]) + let logits = + projectLogits + ? (target.lmHead.map { $0(output) } ?? target.model.embedTokens.asLinear(output)) + : MLXArray.zeros([batch, 0, configuration.vocabularySize], dtype: output.dtype) + return MiMoV26MTPOutput( + logits: logits, + features: .init( + hidden: output, firstPosition: firstTokenPosition, depth: depth, + predictor: self, owner: targetOwner, generation: weightGeneration)) + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26MTPAssistant.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26MTPAssistant.swift new file mode 100644 index 0000000000..ce3c1a2b15 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26MTPAssistant.swift @@ -0,0 +1,457 @@ +// Copyright © 2026 Eigen Labs. +// Native three-next-N request lifecycle. No Gemma/DFlash/Qwen head substitute. +import Foundation +import MLX +import MLXLMCommon + +public final class MiMoV26MTPAssistant: CBv2MTPRequestStatefulDrafter, + CBv2MTPBoundedAllocationProviding, + CBv2NativeMTPCompletionSplitting +{ + weak var target: MiMoV26TextModel? + let predictor: MiMoV26MTP + let generation: UInt64 + /// Immutable per-loaded-binding choice. Rectangular is an experimental + /// target scoring strategy, not a declaration of numerical equivalence. + public let verificationMode: CBv2MTPVerificationMode + /// Native factory passes its non-Module loaded owner. The owner contains + /// the verified components/reservation, never this assistant, so no cycle. + private let loadLifetimeOwner: AnyObject? + private var loadedSessionIsActive = true + + public init( + target: MiMoV26TextModel, predictor: MiMoV26MTP, + retaining owner: AnyObject? = nil, + verificationMode: CBv2MTPVerificationMode = .serialTarget + ) throws { + guard verificationMode == .serialTarget || verificationMode == .rectangular else { + throw MiMoV26MTPError.unsupportedConfiguration( + "MiMo verification requires explicit serial or rectangular mode") + } + guard predictor.belongs(to: target) else { throw MiMoV26MTPError.incompatibleOwner } + guard predictor.isLoaded else { throw MiMoV26MTPError.weightsNotLoaded } + self.target = target + self.predictor = predictor + loadLifetimeOwner = owner + generation = predictor.loadedGeneration + self.verificationMode = verificationMode + } + + func isCompatible(with target: MiMoV26TextModel) -> Bool { + loadedSessionIsActive && self.target === target && predictor.belongs(to: target) + && predictor.isLoaded + && predictor.loadedGeneration == generation + } + /// The loaded bundle is immutable while serving. A host supporting target + /// replacement/reload must quiesce and retire requests, invalidate this + /// assistant, then construct a new verified target/predictor/assistant set. + /// Arbitrary inherited Module/child mutation is unsupported and is not + /// detected by a per-token hash or by the named predictor-load generation. + public func invalidateLoadedSession() { loadedSessionIsActive = false } + public var mtpTargetIdentity: ObjectIdentifier? { + guard let target, isCompatible(with: target) else { return nil } + return ObjectIdentifier(target) + } + public var requiredVerificationMode: CBv2MTPVerificationMode? { verificationMode } + public var maximumDraftTokens: Int? { 3 } + public var maximumSpeculativeBatch: Int? { 1 } + public var supportsTargetPrefixAcceptance: Bool { false } + public var requiresCommittedObservationFence: Bool { true } + + // Conservative admission bound: current settled/speculative head KV plus + // the prior fence's two immutable measured generations retained until the + // successor fence. FP32 bounds RoPE storage even with BF16 activations. The + // legacy getter remains a conservative fallback for consumers that have + // not adopted resolved bounded admission. EngineV2 does not install this + // context-linear floor when the bounded declaration below is active. + public var requestStateBytesPerToken: Int { + let c = predictor.configuration + let g = c.slidingAttention + func product(_ values: [Int]) -> Int { + values.reduce(1) { value, factor in + let result = value.multipliedReportingOverflow(by: factor) + return result.overflow ? Int.max : result.partialValue + } + } + return [ + product([4, 3, g.keyValueHeads, g.headDim + g.valueHeadDim, 4]), + product([4, c.hiddenSize, 4]), 64, + ].reduce(0) { total, value in + let result = total.addingReportingOverflow(value) + return result.overflow ? Int.max : result.partialValue + } + } + // RotatingKVCache allocates in blocks of 256 before reaching its window. + public var requestStateTokenGranularity: Int { 256 } + public var requestStateTokenAllocationPadding: Int { 12 } + + public func boundedRequestAllocation(limits: CBv2MTPAllocationLimits) + -> CBv2MTPBoundedAllocationSpec? + { + guard let target, isCompatible(with: target) else { return nil } + return Self.boundedRequestAllocation(configuration: predictor.configuration, limits: limits) + } + + /// Metadata-only shape proof, intentionally independent of native array + /// allocation. Four banks cover settled/speculative roots PLUS the last + /// completed fence's two retained context banks during their replacement. + /// Working buffers cover lazy graph dependencies until the successor fence; + /// they are not an assertion that kernel-internal workspace is zero. + static func boundedRequestAllocation( + configuration c: MiMoV26Configuration, + limits: CBv2MTPAllocationLimits + ) -> CBv2MTPBoundedAllocationSpec? { + let g = c.slidingAttention + let w = c.slidingWindow + let h = c.hiddenSize + guard c.numNextnPredictLayers == 3, w > 0, h > 0, + g.keyValueHeads > 0, g.queryHeads > 0, g.headDim > 0, g.valueHeadDim > 0, + c.intermediateSize > 0, c.vocabularySize > 0, + limits.maximumPrefillTokens > 0, (1 ... 3).contains(limits.maximumDraftTokens) + else { return nil } + func add(_ a: Int, _ b: Int) -> Int? { + let (value, overflow) = a.addingReportingOverflow(b) + return a >= 0 && b >= 0 && !overflow ? value : nil + } + func bytes(_ factors: [Int]) -> Int? { + var value = 4 // FP32 bounds both supported activation/storage types. + for factor in factors { + let result = value.multipliedReportingOverflow(by: factor) + guard factor > 0, !result.overflow else { return nil } + value = result.partialValue + } + return value + } + var resident: [CBv2MTPFixedBufferSpec] = [] + var working: [CBv2MTPFixedBufferSpec] = [] + func append( + _ destination: inout [CBv2MTPFixedBufferSpec], _ dimensions: [Int], _ count: Int + ) -> Bool { + guard let size = bytes(dimensions), count > 0 else { return false } + destination.append(.init(logicalBytes: size, allocationCount: count)) + return true + } + // Single-token rotating allocation is min(step=256, window); retained + // multi-token updates are compacted to W. K/V remain separate owners. + guard append(&resident, [g.keyValueHeads, w, g.headDim], 12), + append(&resident, [g.keyValueHeads, w, g.valueHeadDim], 12), + append(&resident, [3, h], 6), // current/prior tail and accepted-row frontiers + append(&resident, [4], 12) // pending tokens, carry, per-depth inputs and prior contexts + else { return nil } + + // Before an ordinary observation, accepted-prefix replay is <=3 rows + // and carry repair <=1 row. Price each invocation independently because + // allocator padding and all three heads' lazy K/V graphs may coexist. + // primeTrusted does not project the vocabulary or retain head outputs: + // only embedding/norm/eh/input-norm/K/V dependencies are evaluated. + for rows in [limits.maximumPrefillTokens, 3, 1] { + guard let concatRows = add(w, rows), let featureRows = add(rows, 3), + append(&working, [rows, h], 24), // 3 heads * (embedding, norms, 2H concat, projection, input norm + spare) + append(&working, [featureRows, h], 2), // saved-feature concat and frontier copy source + append(&working, [rows, g.keyValueHeads, g.headDim], 12), // projection, rotary input/output and copy + append(&working, [rows, g.keyValueHeads, g.valueHeadDim], 6), // projection and native value scaling + append(&working, [concatRows, g.keyValueHeads, g.headDim], 6), + append(&working, [concatRows, g.keyValueHeads, g.valueHeadDim], 6), + append(&working, [w, g.keyValueHeads, g.headDim], 6), + append(&working, [w, g.keyValueHeads, g.valueHeadDim], 6) + else { return nil } + } + // Draft depths have at most 1/2/3 rows, never a context-wide readout. + // Enumerate the full head forward, masks and readout at each depth; + // target-forward work and opaque fused-kernel scratch keep their host + // safety reserve and receive no credit from this declaration. + for rows in 1 ... limits.maximumDraftTokens { + guard let attentionRows = add(w, rows), + append(&working, [rows, h], 18), + append(&working, [rows, c.intermediateSize], 4), + append(&working, [rows, g.queryHeads, g.headDim], 4), + append(&working, [rows, g.queryHeads, g.valueHeadDim], 2), + append(&working, [rows, g.keyValueHeads, g.headDim], 4), + append(&working, [rows, g.keyValueHeads, g.valueHeadDim], 2), + append(&working, [attentionRows, g.keyValueHeads, g.headDim], 2), + append(&working, [attentionRows, g.keyValueHeads, g.valueHeadDim], 2), + append(&working, [rows, attentionRows], 6), + append(&working, [attentionRows], 4), + append(&working, [rows, c.vocabularySize], 1) + else { return nil } + } + // Historical prompt context is optional at runtime, but its complete + // envelope is included in this same resolved admission even when MTP + // is used without persistence. No caller Array backing is retained. + // Native witness: current/prior measured descriptor plus replacement, + // concat and bit-copy dependencies. Serialized copies are additionally + // priced by the existing complete-checkpoint transient reservation. + guard c.maxPositionEmbeddings > 0, c.maxPositionEmbeddings <= Int(Int32.max), + append(&resident, [c.maxPositionEmbeddings], 3), + append(&working, [c.maxPositionEmbeddings], 4), + let tokenHostBytes = bytes([c.maxPositionEmbeddings, 8]), + let hostBytes = add(64 << 10, tokenHostBytes) + 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 } + return .init(resident: resident, working: working, hostBytes: hostBytes) + } + + public func makeRequestState() -> any CBv2MTPRequestState { + do { + guard let target, isCompatible(with: target) else { + throw MiMoV26MTPError.incompatibleOwner + } + return MiMoV26MTPState( + owner: self, generation: generation, cache: try predictor.newCache()) + } catch { preconditionFailure("MiMo MTP request construction: \(error)") } + } + + func checked(_ requestState: any CBv2MTPRequestState) throws -> MiMoV26MTPState { + guard let state = requestState as? MiMoV26MTPState, state.owner === self, + let target, isCompatible(with: target), state.generation == generation + else { + throw MiMoV26MTPError.incompatibleOwner + } + guard !state.isReleased, state.cache != nil else { + throw MiMoV26MTPError.invalidHistory("released request state") + } + return state + } + + public func configureRequestState( + _ requestState: any CBv2MTPRequestState, + maximumSequenceLength: Int + ) throws { + let state = try checked(requestState) + guard maximumSequenceLength > 0, + maximumSequenceLength <= predictor.configuration.maxPositionEmbeddings, + maximumSequenceLength >= state.committedInputCount, + state.maximumSequenceLength == nil + || state.maximumSequenceLength == maximumSequenceLength + else { + throw MiMoV26MTPError.invalidHistory("request context bound changed or is invalid") + } + state.maximumSequenceLength = maximumSequenceLength + } + + private func validateRows(tokens: MLXArray, hidden: MLXArray) throws { + guard let target, tokens.ndim == 2, tokens.dim(0) == 1, tokens.dim(1) > 0, + tokens.dtype == .int32 || tokens.dtype == .uint32, + hidden.shape == [1, tokens.dim(1), predictor.configuration.hiddenSize], + hidden.dtype == target.activationDType + else { + throw MiMoV26MTPError.invalidInput("MiMo MTP requires one aligned native target row") + } + } + + /// Teacher-force only committed inputs. At depth d, token position p is + /// paired with the original normalized target feature at p-d-1. Chunk + /// boundaries consume the saved final three target rows, never a head output. + private func observeAligned( + tokens: MLXArray, hidden: MLXArray, + state: MiMoV26MTPState + ) throws { + try validateRows(tokens: tokens, hidden: hidden) + let oldCount = state.observedCount + let count = tokens.dim(1) + state.prefixCaptureMayInstall = false + let maximum = state.maximumSequenceLength ?? predictor.configuration.maxPositionEmbeddings + guard count <= maximum - oldCount, let target else { throw MiMoV26MTPError.contextExceeded } + state.recordPrefixObservation(tokens: tokens) + let tailCount = state.tail?.dim(1) ?? 0 + let featureStart = oldCount - tailCount + let features = state.tail.map { concatenated([$0, hidden], axis: 1) } ?? hidden + for depth in 0 ..< 3 { + let tokenStart = max(oldCount, depth + 1) + let length = oldCount + count - tokenStart + guard length > 0 else { continue } + let firstFeature = tokenStart - depth - 1 + let selected = firstFeature - featureStart + try predictor.primeTrusted( + depth: depth, + features: .init( + trustedTargetHidden: features[0..., selected ..< selected + length, 0...], + firstPosition: firstFeature, target: target), + inputIDs: tokens[0..., (tokenStart - oldCount) ..< count], + target: target, cache: state.cache!) + state.cache!.compactRetainedHistory(depth: depth) + } + state.observedCount += count + let kept = min(3, state.observedCount) + // A slice alone can pin the complete prefill allocation after eval. + state.tail = mimoV26MTPCopy(features[0..., (features.dim(1) - kept)..., 0...]) + } + + private func flushAccepted(state: MiMoV26MTPState) throws { + if let tokens = state.pendingTokens, let hidden = state.pendingHidden { + try observeAligned(tokens: tokens, hidden: hidden, state: state) + state.pendingTokens = nil + state.pendingHidden = nil + } + } + + public func observeCommittedTarget( + _ observation: CBv2MTPCommittedTargetObservation, + requestState: any CBv2MTPRequestState + ) { + do { + let state = try checked(requestState) + guard state.round == nil else { + throw MiMoV26MTPError.invalidHistory("observation during draft round") + } + try validateRows(tokens: observation.tokens, hidden: observation.hidden) + state.willMutate() + try flushAccepted(state: state) + if let token = state.pendingLastToken { + // Generic historyCarry pairs the NEW carry token with the + // PREVIOUS target hidden. Complete the pending previous input; + // the next ordinary observation supplies the new token's hidden. + guard observation.tokens.dim(1) == 1 else { + throw MiMoV26MTPError.invalidHistory("missing carry history transition") + } + try observeAligned(tokens: token, hidden: observation.hidden, state: state) + state.pendingLastToken = nil + } else { + try observeAligned( + tokens: observation.tokens, hidden: observation.hidden, state: state) + } + } catch { preconditionFailure("MiMo MTP committed target contract: \(error)") } + } + + private final class UnusedCapture: CBv2MTPPreparedCapture {} + public func prepare(rows: [CBv2MTPRowCapture]) -> CBv2MTPPreparedCapture { UnusedCapture() } + public func draftStep(tokens: MLXArray, hidden: MLXArray, prepared: CBv2MTPPreparedCapture) + -> (tokens: MLXArray, hidden: MLXArray) + { + preconditionFailure("MiMo MTP requires request-owned state") + } + + public func draftStep( + tokens: MLXArray, hidden: MLXArray, shortlist: MLXArray?, + requestState: any CBv2MTPRequestState + ) -> (tokens: MLXArray, hidden: MLXArray) { + do { + let state = try checked(requestState) + try validateRows(tokens: tokens, hidden: hidden) + guard tokens.dim(1) == 1, shortlist == nil, let target else { + throw MiMoV26MTPError.invalidInput( + "native next-N requires one token and full readout") + } + guard state.hasRequiredRestoredSuffix else { + throw MiMoV26MTPError.invalidHistory( + "historical restore requires an actual target suffix before drafting") + } + state.prefixCaptureMayInstall = false + state.prefixCapturePromptOnly = false + state.willMutate() + if state.round == nil { + try flushAccepted(state: state) + if let token = state.pendingLastToken { + try observeAligned(tokens: token, hidden: hidden, state: state) + state.pendingLastToken = nil + } + guard state.observedCount > 0, state.tail != nil else { + throw MiMoV26MTPError.invalidHistory( + "target history was not primed from position zero") + } + state.round = .init(cache: state.cache!, baseCount: state.observedCount) + } + let round = state.round! + let depth = round.inputs.count + guard depth < 3, + round.baseCount + depth + < (state.maximumSequenceLength ?? predictor.configuration.maxPositionEmbeddings) + else { + throw MiMoV26MTPError.contextExceeded + } + round.inputs.append(mimoV26MTPCopy(tokens)) + let length = min(round.baseCount, depth + 1) + let tail = state.tail! + let firstPosition = round.baseCount - length + let tokenHistory = concatenated(round.inputs, axis: 1) + let output = try predictor.forwardTrusted( + depth: depth, + features: .init( + trustedTargetHidden: tail[0..., (tail.dim(1) - length)..., 0...], + firstPosition: firstPosition, target: target), + inputIDs: tokenHistory[0..., (depth + 1 - length)...], + target: target, cache: round.cache) + round.cache.compactRetainedHistory(depth: depth) + let proposed = argMax(output.logits[0..., -1, 0...], axis: -1).asType(.int32) + // Proposal output belongs to the engine. Keeping a second native + // view here would make the state claim an engine-owned allocation. + state.headProposalCounts[depth] += 1 + // The engine loops its returned hidden. Return the SAME target + // feature every time, never output.normalizedHiddenStates. + return (proposed, mimoV26MTPCopy(tail[0..., (-1)..., 0...])) + } catch { preconditionFailure("MiMo MTP draft contract: \(error)") } + } + + public func evaluationTargets(for requestState: any CBv2MTPRequestState) -> [MLXArray] { + guard let state = requestState as? MiMoV26MTPState, state.owner === self, !state.isReleased + else { return [] } + return state.ownedArrays + } + + /// Opt-in Common completion hook. Common has already joined every current + /// assistant root; state drains construction-stream references and records + /// independent backing receipts without constructing or evaluating graphs. + public func requestStateDidFinishEvaluation(_ requestState: any CBv2MTPRequestState) throws { + try checked(requestState).didFinishEvaluation() + } + + package func fenceRequestStateForNativeCompletion(_ requestState: any CBv2MTPRequestState) + throws + { + try checked(requestState).fenceForNativeCompletion() + } + + package func commitRequestStateNativeCompletion(_ requestState: any CBv2MTPRequestState) throws + { + try checked(requestState).commitNativeCompletion() + } + + public func finalizeRound( + requestState: any CBv2MTPRequestState, confirmedInputTokens: Int, + committedDraftTokens: MLXArray, committedTargetHidden: MLXArray + ) { + do { + let state = try checked(requestState) + guard let round = state.round else { + throw MiMoV26MTPError.invalidHistory("finalize without round") + } + guard committedDraftTokens.ndim == 2 else { + throw MiMoV26MTPError.invalidInput("accepted tokens require rank two") + } + let count = committedDraftTokens.dim(1) + guard committedDraftTokens.dim(0) == 1, + committedTargetHidden.shape == [1, count, predictor.configuration.hiddenSize], + count <= round.inputs.count, confirmedInputTokens == count + 1 + else { + throw MiMoV26MTPError.invalidHistory( + "accepted prefix does not match target verification") + } + state.willMutate() + let canonicalInputs = concatenated([round.inputs[0], committedDraftTokens], axis: 1) + if count > 0 { + // The generic API pairs each accepted draft with its preceding + // target hidden; realign by prepending the round's seed input. + state.pendingTokens = mimoV26MTPCopy(canonicalInputs[0..., 0 ..< count]) + state.pendingHidden = mimoV26MTPCopy(committedTargetHidden) + } + state.pendingLastToken = mimoV26MTPCopy(canonicalInputs[0..., count ..< count + 1]) + // Every proposal cache is discarded, including accepted proposals: + // canonical head KV is replayed only from verified TARGET features. + state.round = nil + } catch { preconditionFailure("MiMo MTP finalize contract: \(error)") } + } + + public func discardRound(requestState: any CBv2MTPRequestState) { + guard let state = requestState as? MiMoV26MTPState, state.owner === self, !state.isReleased + else { return } + state.willMutate() + state.round = nil + } + public func releaseRequestState(_ requestState: any CBv2MTPRequestState) { + guard let state = requestState as? MiMoV26MTPState, state.owner === self else { return } + state.releaseAfterFence() + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26MTPPrefixCheckpoint.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26MTPPrefixCheckpoint.swift new file mode 100644 index 0000000000..5b488daf99 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26MTPPrefixCheckpoint.swift @@ -0,0 +1,300 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX +import MLXLMCommon + +/// Private codec value, not a request/carry/sampler snapshot. Its copy graphs +/// remain owned by Common's existing complete-checkpoint reservation until +/// required evaluation AND every export/adoption alias have retired. +final class MiMoV26MTPPrefixCheckpoint: CBv2MTPPrefixCheckpoint { + weak var owner: MiMoV26MTPAssistant? + let generation: UInt64 + let targetInputCount: Int + let heads: [MiMoV26MTPPrefixHead] + let tail: MLXArray + let tokens: MLXArray + let metadata: MLXArray + // Independent, fixed-sized host witness. Never retain the donor's complete + // prompt/COW allocation after publication of a shorter prefix. + let expectedTokens: ContiguousArray + /// Conservative allocator bound, NOT measured native residency/refund. + /// Physical accounting stays with the complete-checkpoint owner. + let materializedBytes: Int + let imported: Bool + var importedStorageOwner: AnyObject? + + init( + owner: MiMoV26MTPAssistant, generation: UInt64, count: Int, + heads: [MiMoV26MTPPrefixHead], tail: MLXArray, tokens: MLXArray, + metadata: MLXArray, expectedTokens: ContiguousArray, + allocationBound: Int, imported: Bool = false + ) { + self.owner = owner + self.generation = generation + targetInputCount = count + self.heads = heads + self.tail = tail + self.tokens = tokens + self.metadata = metadata + self.expectedTokens = expectedTokens + materializedBytes = allocationBound + self.imported = imported + } + var evaluationTargets: [MLXArray] { + heads.flatMap { [$0.keys, $0.values] } + [tail, tokens, metadata] + } +} + +extension MiMoV26MTPAssistant: CBv2HistoricalMTPPrefixCheckpointCoding { + package func bindImportedPrefixCheckpointOwner( + _ checkpoint: any CBv2MTPPrefixCheckpoint, owner: AnyObject + ) throws { + guard let value = checkpoint as? MiMoV26MTPPrefixCheckpoint, + value.imported, belongsToCurrentOwner(value), + value.importedStorageOwner == nil || value.importedStorageOwner === owner + else { + throw MiMoV26MTPError.incompatibleOwner + } + value.importedStorageOwner = owner + } + + public var prefixCheckpointCodecID: String { + "mimo-v26-three-head-swa-bf16-target-tail-v1" + } + + private var prefixConfiguration: MiMoV26Configuration? { + guard let target, isCompatible(with: target), target.activationDType == .bfloat16, + predictor.headCount == 3 + else { return nil } + return predictor.configuration + } + + /// Common calls this exactly once on a fresh admitted state, or on a + /// pristine off-to-the-side restored state before its first suffix input. + /// The full caller request is not retained; each token is copied separately. + package func installPrefixCaptureContext( + requestState: any CBv2MTPRequestState, + promptTokens: [Int] + ) throws { + let state = try checked(requestState) + guard let c = prefixConfiguration, state.prefixCaptureMayInstall, + state.prefixCaptureContext == nil, state.prefixCapturePromptOnly, + state.round == nil, state.pendingTokens == nil, state.pendingHidden == nil, + state.pendingLastToken == nil, let maximum = state.maximumSequenceLength, + !promptTokens.isEmpty, promptTokens.count <= maximum, + promptTokens.count <= c.maxPositionEmbeddings, + promptTokens.allSatisfy({ $0 >= 0 && $0 < c.vocabularySize && $0 <= Int(Int32.max) }) + else { throw MiMoV26MTPError.invalidHistory("invalid or late historical capture context") } + if let boundary = state.prefixRestoredBoundary { + guard state.observedCount == boundary, boundary < promptTokens.count else { + throw MiMoV26MTPError.invalidHistory("restored prompt prefix changed") + } + let matches: Bool + if let source = state.prefixRestoreSource { + matches = source.expectedTokens.enumerated().allSatisfy { + Int($0.element) == promptTokens[$0.offset] + } + } else if let tokens = state.prefixObservedTokens { + matches = MiMoV26MTPPrefixValidation.tokensMatch(tokens, count: boundary) { + Int32(promptTokens[$0]) + } + } else { + matches = false + } + guard matches else { + throw MiMoV26MTPError.invalidHistory("restored prompt prefix changed") + } + } else { + guard state.observedCount == 0, !state.hasUnmeasuredResidency, + state.prefixObservedTokens == nil, + state.cache?.consumedTokenCounts == [0, 0, 0] + else { + throw MiMoV26MTPError.invalidHistory("context did not precede target observations") + } + } + state.prefixCaptureContext = MiMoV26MTPPrefixContext(promptTokens) + state.prefixCaptureMayInstall = false + } + + public func prefixCheckpointTensorDescriptors(targetInputCount count: Int) + -> [CBv2CheckpointTensorDescriptor]? + { + guard let c = prefixConfiguration, count >= 4, count < c.maxPositionEmbeddings else { + return nil + } + let g = c.slidingAttention + do { + var result: [CBv2CheckpointTensorDescriptor] = [] + for depth in 0 ..< 3 { + let rows = min(count - depth - 1, c.slidingWindow) + result.append( + try .init( + role: .assistantKeys, layer: depth, + shape: [1, g.keyValueHeads, rows, g.headDim], dtype: .bfloat16)) + result.append( + try .init( + role: .assistantValues, layer: depth, + shape: [1, g.keyValueHeads, rows, g.valueHeadDim], dtype: .bfloat16)) + } + result.append( + try .init(role: .assistantHidden, shape: [1, 3, c.hiddenSize], dtype: .bfloat16)) + result.append(try .init(role: .assistantTokens, shape: [1, count], dtype: .int32)) + result.append(try .init(role: .assistantCacheMetadata, shape: [3, 7], dtype: .int64)) + return result + } catch { return nil } + } + + public func capturePrefixCheckpoint( + requestState: any CBv2MTPRequestState, + targetInputCount count: Int + ) + -> (any CBv2MTPPrefixCheckpoint)? + { + guard let state = try? checked(requestState), let context = state.prefixCaptureContext, + state.prefixCapturePromptOnly, count >= 4, count < context.count, + state.observedCount == count, state.committedInputCount == count, + !state.hasUnmeasuredResidency, state.round == nil, + state.pendingTokens == nil, state.pendingHidden == nil, state.pendingLastToken == nil, + let tokens = state.prefixObservedTokens, context.matches(tokens, count: count), + let tail = state.tail, tail.shape == [1, 3, predictor.configuration.hiddenSize], + tail.dtype == .bfloat16, + let heads = state.cache?.prefixHeads(count: count, expectedOwner: predictor), + let descriptors = prefixCheckpointTensorDescriptors(targetInputCount: count), + let bound = allocationBound(descriptors), + let expected = copiedTokens(tokens, count: count) + else { return nil } + // Common must reserve BEFORE calling this. No stream fence/eval or + // request mutation occurs here. The donor's existing settled fence is + // required; the new copy graphs remain Common-owned until completion. + let copied = heads.map { + MiMoV26MTPPrefixHead( + keys: mimoV26MTPCopy($0.keys), + values: mimoV26MTPCopy($0.values), metadata: $0.metadata) + } + let metadata = MLXArray(heads.flatMap(\.metadata), [3, 7]) + return MiMoV26MTPPrefixCheckpoint( + owner: self, generation: generation, count: count, + heads: copied, tail: mimoV26MTPCopy(tail), tokens: mimoV26MTPCopy(tokens), + metadata: metadata, expectedTokens: expected, allocationBound: bound) + } + + public func encodePrefixCheckpoint(_ checkpoint: any CBv2MTPPrefixCheckpoint) -> [MLXArray]? { + guard let value = checkpoint as? MiMoV26MTPPrefixCheckpoint, + belongsToCurrentOwner(value), + let descriptors = prefixCheckpointTensorDescriptors( + targetInputCount: value.targetInputCount), + matches(value.evaluationTargets, descriptors) + else { return nil } + // Encoding may precede copy completion; the enclosing export owns and + // evaluates these exact roots. It must not release staging on failure. + return value.evaluationTargets + } + + public func decodePrefixCheckpoint(tensors: [MLXArray], prefixTokens: [Int]) + -> (any CBv2MTPPrefixCheckpoint)? + { + guard let c = prefixConfiguration, + let descriptors = prefixCheckpointTensorDescriptors( + targetInputCount: prefixTokens.count), + matches(tensors, descriptors), + prefixTokens.allSatisfy({ $0 >= 0 && $0 < c.vocabularySize && $0 <= Int(Int32.max) }), + MiMoV26MTPPrefixValidation.tokensMatch( + tensors[7], count: prefixTokens.count, + expected: { Int32(prefixTokens[$0]) }), + let metadata = MiMoV26MTPPrefixValidation.metadata(tensors[8]), + let bound = allocationBound(descriptors) + else { return nil } + let heads = (0 ..< 3).map { + MiMoV26MTPPrefixHead( + keys: tensors[2 * $0], + values: tensors[2 * $0 + 1], metadata: metadata[$0]) + } + guard + heads.enumerated().allSatisfy({ + MiMoV26MTPPrefixValidation.headIsValid( + $0.element, depth: $0.offset, + count: prefixTokens.count, configuration: c) + }), let expected = copiedTokens(tensors[7], count: prefixTokens.count) + else { return nil } + // Outer import validates artifact/numerics/tenant/actual prompt identity. + // Bind decoded state to THIS current assistant/generation; serialized + // object identifiers or prior load generations are never trusted. + return MiMoV26MTPPrefixCheckpoint( + owner: self, generation: generation, count: prefixTokens.count, + heads: heads, tail: tensors[6], tokens: tensors[7], metadata: tensors[8], + expectedTokens: expected, allocationBound: bound, imported: true) + } + + public func restorePrefixCheckpoint(_ checkpoint: any CBv2MTPPrefixCheckpoint) + -> (any CBv2MTPRequestState)? + { + guard let value = checkpoint as? MiMoV26MTPPrefixCheckpoint, + belongsToCurrentOwner(value), let c = prefixConfiguration, + let descriptors = prefixCheckpointTensorDescriptors( + targetInputCount: value.targetInputCount), + matches(value.evaluationTargets, descriptors), + value.evaluationTargets.allSatisfy({ (try? $0.evaluatedBufferInfo()) != nil }), + MiMoV26MTPPrefixValidation.tokensMatch( + value.tokens, count: value.targetInputCount, + expected: { value.expectedTokens[$0] }), + let metadata = MiMoV26MTPPrefixValidation.metadata(value.metadata), + metadata == value.heads.map(\.metadata), + value.heads.enumerated().allSatisfy({ + MiMoV26MTPPrefixValidation.headIsValid( + $0.element, depth: $0.offset, + count: value.targetInputCount, configuration: c) + }), let cache = try? predictor.newCache() + else { return nil } + // All input validation precedes copy graph construction or mutation. + // Build a NEW mutable owner, never alter donor or live target state. + let state = MiMoV26MTPState(owner: self, generation: generation, cache: cache) + state.willMutate() + guard + cache.restorePrefixHeads( + value.heads, count: value.targetInputCount, + expectedOwner: predictor) + else { return nil } + state.observedCount = value.targetInputCount + state.prefixRestoredBoundary = value.targetInputCount + state.tail = mimoV26MTPCopy(value.tail) + state.prefixObservedTokens = mimoV26MTPCopy(value.tokens) + state.prefixRestoreSource = value + // No next-token carry/logits/sampler/proposal state is synthesized. + // Common configures the admitted context and evaluates all roots before + // atomic target+assistant adoption. A suffix is still mandatory. + return state + } + + private func belongsToCurrentOwner(_ checkpoint: MiMoV26MTPPrefixCheckpoint) -> Bool { + checkpoint.owner === self && checkpoint.generation == generation + && prefixConfiguration != nil + } + private func matches(_ arrays: [MLXArray], _ descriptors: [CBv2CheckpointTensorDescriptor]) + -> Bool + { + arrays.count == descriptors.count + && zip(arrays, descriptors).allSatisfy { + $0.shape == $1.shape && $0.dtype == $1.dtype.mlxDType + } + } + private func allocationBound(_ descriptors: [CBv2CheckpointTensorDescriptor]) -> Int? { + var result = 0 + for descriptor in descriptors { + guard + let bytes = try? Memory.allocationFootprintUpperBound( + byteCount: descriptor.byteCount) + else { return nil } + let next = result.addingReportingOverflow(bytes) + guard !next.overflow else { return nil } + result = next.partialValue + } + return result + } + private func copiedTokens(_ array: MLXArray, count: Int) -> ContiguousArray? { + // Validate evaluated storage through the same read-only helper first. + // No asArray/item call here may secretly submit or wait for native work. + var result = ContiguousArray(repeating: 0, count: count) + guard MiMoV26MTPPrefixValidation.copyTokens(array, into: &result) else { return nil } + return result + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26MTPPrefixState.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26MTPPrefixState.swift new file mode 100644 index 0000000000..c934cd1bc3 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26MTPPrefixState.swift @@ -0,0 +1,127 @@ +// Copyright © 2026 Eigen Labs. +import Cmlx +import Foundation +import MLX +import MLXLMCommon + +/// No caller-owned Array/COW capacity is retained. The private compact witness +/// is bounded by maxPositionEmbeddings and charged by boundedRequestAllocation. +final class MiMoV26MTPPrefixContext { + private let tokens: ContiguousArray + var count: Int { tokens.count } + + init(_ prompt: [Int]) { + tokens = ContiguousArray(unsafeUninitializedCapacity: prompt.count) { buffer, count in + for (index, token) in prompt.enumerated() { buffer[index] = Int32(token) } + count = prompt.count + } + } + + func matches(_ array: MLXArray, count: Int) -> Bool { + guard count <= tokens.count else { return false } + return MiMoV26MTPPrefixValidation.tokensMatch(array, count: count) { tokens[$0] } + } +} + +struct MiMoV26MTPPrefixHead { + let keys: MLXArray + let values: MLXArray + // firstPosition, keep, window, step, localOffset, physicalRingIndex, liveLength + let metadata: [Int64] +} + +enum MiMoV26MTPPrefixValidation { + static func metadataIsValid( + _ row: [Int64], depth: Int, count: Int, + configuration c: MiMoV26Configuration + ) -> Bool { + guard (0 ..< 3).contains(depth), count >= 4, count < c.maxPositionEmbeddings, + row.count == 7, c.slidingWindow > 0 + else { return false } + let offset = count - depth - 1 + let window = c.slidingWindow + guard row[0] == Int64(depth + 1), row[1] == 0, + row[2] == Int64(window), row[3] == 256, row[4] == Int64(offset), + row[6] == Int64(min(offset, window)) + else { return false } + return offset < window + ? row[5] == Int64(offset) + : row[5] > 0 && row[5] <= Int64(window) + } + + static func headIsValid( + _ head: MiMoV26MTPPrefixHead, depth: Int, count: Int, + configuration c: MiMoV26Configuration, + allowsUnusedCapacity: Bool = false + ) -> Bool { + guard metadataIsValid(head.metadata, depth: depth, count: count, configuration: c), + head.keys.ndim == 4, head.values.ndim == 4, + head.keys.dtype == .bfloat16, head.values.dtype == .bfloat16 + else { return false } + let g = c.slidingAttention + let live = min(count - depth - 1, c.slidingWindow) + let length = head.keys.dim(2) + guard head.keys.shape == [1, g.keyValueHeads, length, g.headDim], + head.values.shape == [1, g.keyValueHeads, length, g.valueHeadDim] + else { return false } + return allowsUnusedCapacity + ? length >= live && length <= c.slidingWindow : length == live + } + + /// A non-evaluating readback. Lazy/noncontiguous imports fail cold; complete + /// checkpoint staging must already have completed its real native read. + static func tokensMatch( + _ array: MLXArray, count: Int, + expected: (Int) -> Int32 + ) -> Bool { + guard array.dtype == .int32, array.shape == [1, count], + let info = try? array.evaluatedBufferInfo(), info.isRowContiguous, + info.dataElements == array.size, + let pointer = mlx_array_data_int32(array.ctx) + else { return false } + return withExtendedLifetime(array) { + for index in 0 ..< count where pointer[index] != expected(index) { return false } + return true + } + } + + static func copyTokens(_ array: MLXArray, into output: inout ContiguousArray) -> Bool { + guard array.dtype == .int32, array.shape == [1, output.count], + let info = try? array.evaluatedBufferInfo(), info.isRowContiguous, + info.dataElements == array.size, + let pointer = mlx_array_data_int32(array.ctx) + else { return false } + return withExtendedLifetime(array) { + for index in output.indices { output[index] = pointer[index] } + return true + } + } + + static func metadata(_ array: MLXArray) -> [[Int64]]? { + guard array.dtype == .int64, array.shape == [3, 7], + let info = try? array.evaluatedBufferInfo(), info.isRowContiguous, + info.dataElements == array.size, + let pointer = mlx_array_data_int64(array.ctx) + else { return nil } + return withExtendedLifetime(array) { + (0 ..< 3).map { depth in (0 ..< 7).map { pointer[depth * 7 + $0] } } + } + } +} + +extension MiMoV26MTPState { + func recordPrefixObservation(tokens: MLXArray) { + guard prefixCapturePromptOnly, let context = prefixCaptureContext else { return } + let count = tokens.dim(1) + guard observedCount <= context.count, count <= context.count - observedCount else { + prefixCapturePromptOnly = false + return + } + // uint32 inputs have the same bytes; out-of-vocabulary/high-bit values + // cannot pass the later exact signed witness comparison. Never recast + // floating features or head caches in this path. + let incoming = tokens.dtype == .int32 ? tokens : tokens.view(dtype: .int32) + let joined = prefixObservedTokens.map { concatenated([$0, incoming], axis: 1) } ?? incoming + prefixObservedTokens = mimoV26MTPCopy(joined) + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26MTPState.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26MTPState.swift new file mode 100644 index 0000000000..831c349df2 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26MTPState.swift @@ -0,0 +1,192 @@ +// Copyright © 2026 Eigen Labs. +import Cmlx +import Foundation +import MLX +import MLXLMCommon + +/// A bounded private owner of a previously measured root set. Context snapshots +/// pin immutable MLX descriptors even if indexed updates replace the original +/// Swift MLXArray's context. They are not allocation identities and never escape +/// this request. The next drained fence retires them before measuring successors. +private final class MiMoV26MTPPhysicalOwner { + private var contexts: [MLXArray] = [] + private(set) var bytes = 0 + var count: Int { contexts.count } + + func clearAfterFence() { + contexts.removeAll() + bytes = 0 + } + + func measureAfterFence(_ arrays: [MLXArray]) throws { + clearAfterFence() + for array in arrays { + guard let info = try array.evaluatedBufferInfo(), info.isUnique, + info.isRowContiguous, info.dataOffset == 0, + info.dataElements == array.size, info.allocatedBytes >= array.nbytes, + info.allocatedBytes + <= (try Memory.allocationFootprintUpperBound(byteCount: array.nbytes)) + else { + throw MiMoV26MTPError.invalidHistory( + "request fence did not prove independent compact backing") + } + let next = bytes.addingReportingOverflow(info.allocatedBytes) + guard !next.overflow else { + throw MiMoV26MTPError.invalidHistory("physical residency overflow") + } + var context = mlx_array_new() + guard mlx_array_set(&context, array.ctx) == 0 else { + mlx_array_free(context) + throw MiMoV26MTPError.invalidHistory("unable to retain measured array context") + } + // Retain immediately: if a later root shares this descriptor/data, + // its isUnique proof fails. No guessed identity/deduplication. + contexts.append(MLXArray(context)) + bytes = next.partialValue + } + } +} + +/// One request, three trained-head SWA histories. Mutable caches never escape; +/// historical copies use the assistant codec and Common's admitted capture / +/// import owners, not an unpriced public snapshot of this state. +public final class MiMoV26MTPState: CBv2MTPRequestState, CBv2MTPRequestResidencyReporting { + weak var owner: MiMoV26MTPAssistant? + let generation: UInt64 + var cache: MiMoV26MTPRequestCache? + var observedCount = 0 + var tail: MLXArray? + var pendingTokens: MLXArray? + var pendingHidden: MLXArray? + var pendingLastToken: MLXArray? + var maximumSequenceLength: Int? + var round: Round? + // Historical prefix eligibility is request-local and cannot be re-enabled + // after any observation or draft. Restored states get one new context bind + // before their first actual suffix observation. + var prefixCaptureMayInstall = true + var prefixCapturePromptOnly = true + var prefixCaptureContext: MiMoV26MTPPrefixContext? + var prefixObservedTokens: MLXArray? + var prefixRestoreSource: MiMoV26MTPPrefixCheckpoint? + var prefixRestoredBoundary: Int? + private let physicalOwner = MiMoV26MTPPhysicalOwner() + private var constructionStream: StreamOrDevice? + public private(set) var hasUnmeasuredResidency = false + public private(set) var isReleased = false + public internal(set) var headProposalCounts = [0, 0, 0] + + final class Round { + let cache: MiMoV26MTPRequestCache + let baseCount: Int + var inputs: [MLXArray] = [] + init(cache: MiMoV26MTPRequestCache, baseCount: Int) { + self.cache = cache.detachedCopy() + self.baseCount = baseCount + } + } + + init(owner: MiMoV26MTPAssistant, generation: UInt64, cache: MiMoV26MTPRequestCache) { + self.owner = owner + self.generation = generation + self.cache = cache + } + public var committedInputCount: Int { + observedCount + (pendingTokens?.dim(1) ?? 0) + (pendingLastToken == nil ? 0 : 1) + } + public var stagedInputCount: Int { round?.inputs.count ?? 0 } + public var hasPendingPrefillForCostAccounting: Bool { false } + public var retainedFeatureRows: Int { tail?.dim(1) ?? 0 } + var hasRequiredRestoredSuffix: Bool { + prefixRestoredBoundary.map { observedCount > $0 } ?? true + } + public var headInputCounts: [Int] { cache?.consumedTokenCounts ?? [] } + public var retainedHistoryShapes: [[[Int]]] { cache?.stateShapesByDepth ?? [] } + public var measuredRootCount: Int { physicalOwner.count } + + var ownedArrays: [MLXArray] { + var result = cache?.innerState() ?? [] + result += [tail, pendingTokens, pendingHidden, pendingLastToken, prefixObservedTokens] + .compactMap { $0 } + if let round { result += round.cache.innerState() + round.inputs } + return result + } + /// Shape diagnostic only. This never claims allocator backing or residency. + public var logicalRootBytes: Int { + ownedArrays.reduce(0) { total, array in + let sum = total.addingReportingOverflow(array.nbytes) + return sum.overflow ? Int.max : sum.partialValue + } + } + /// Exact bytes of the explicitly retained measured owner. When + /// hasUnmeasuredResidency is true, this is a known subset, not total usage. + /// The getter performs no metadata inspection, evaluation or synchronization. + public var materializedBytes: Int { physicalOwner.bytes } + + func willMutate() { + let stream = StreamOrDevice.default + precondition( + constructionStream == nil || constructionStream == stream, + "MiMo request changed native streams before its completion fence") + constructionStream = stream + hasUnmeasuredResidency = true + } + + /// Caller has joined every evaluationTargets root. Drain native completion + /// references on the construction stream before replacing measured owners. + /// This never constructs or evaluates a graph and is never called by a getter. + func didFinishEvaluation() throws { + guard !isReleased else { throw MiMoV26MTPError.invalidHistory("fenced a released request") } + hasUnmeasuredResidency = true + if let constructionStream { try withError { constructionStream.stream.synchronize() } } + try physicalOwner.measureAfterFence(ownedArrays) + prefixRestoreSource = nil + constructionStream = nil + hasUnmeasuredResidency = false + } + + // Tracked-engine split of the existing method above. It adds no fence and + // changes no graph/math. Only Common's exact current-generation commit may + // call the second half after the first half returns successfully. + func fenceForNativeCompletion() throws { + guard !isReleased else { throw MiMoV26MTPError.invalidHistory("fenced a released request") } + hasUnmeasuredResidency = true + if let constructionStream { try withError { constructionStream.stream.synchronize() } } + } + + func commitNativeCompletion() throws { + guard !isReleased else { + throw MiMoV26MTPError.invalidHistory("committed a released request") + } + hasUnmeasuredResidency = true + // evaluatedBufferInfo is explicitly non-evaluating/non-waiting; the + // footprint bound is scalar arithmetic. No stream or host-ledger lock + // is taken here. Snapshot/context ownership is queue-confined. + try physicalOwner.measureAfterFence(ownedArrays) + constructionStream = nil + prefixRestoreSource = nil + hasUnmeasuredResidency = false + } + + /// Engine-owned retirement only, after its existing native drain boundary. + func releaseAfterFence() { + cache = nil + tail = nil + pendingTokens = nil + pendingHidden = nil + pendingLastToken = nil + round = nil + observedCount = 0 + maximumSequenceLength = nil + prefixCaptureMayInstall = false + prefixCapturePromptOnly = false + prefixCaptureContext = nil + prefixObservedTokens = nil + prefixRestoreSource = nil + prefixRestoredBoundary = nil + physicalOwner.clearAfterFence() + constructionStream = nil + hasUnmeasuredResidency = false + isReleased = true + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26MoE.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26MoE.swift new file mode 100644 index 0000000000..598cadabb2 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26MoE.swift @@ -0,0 +1,142 @@ +// Copyright © 2026 Eigen Labs. +// Native MiMo V2.6 sigmoid routing; no Qwen family substitution. + +import MLX +import MLXLMCommon +import MLXNN + +final class MiMoV26DenseMLP: Module, UnaryLayer { + @ModuleInfo(key: "gate_proj") var gateProj: Linear + @ModuleInfo(key: "up_proj") var upProj: Linear + @ModuleInfo(key: "down_proj") var downProj: Linear + + init(hiddenSize: Int, intermediateSize: Int) { + _gateProj.wrappedValue = Linear(hiddenSize, intermediateSize, bias: false) + _upProj.wrappedValue = Linear(hiddenSize, intermediateSize, bias: false) + _downProj.wrappedValue = Linear(intermediateSize, hiddenSize, bias: false) + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + downProj(silu(gateProj(x)) * upProj(x)) + } +} + +final class MiMoV26Router: Module { + let config: MiMoV26Configuration + let operandDType: DType + var useFusedDecodeRouter = MiMoV26DecodeRouter.enabledByEnvironment + @ParameterInfo(key: "weight") var weight: MLXArray + @ParameterInfo(key: "e_score_correction_bias") var correctionBias: MLXArray + + init(_ config: MiMoV26Configuration) { + self.config = config + operandDType = config.moeRouterDType == "bfloat16" ? .bfloat16 : .float32 + _weight.wrappedValue = MLXArray.zeros( + [config.routedExpertCount, config.hiddenSize], + dtype: operandDType) + _correctionBias.wrappedValue = MLXArray.zeros([config.routedExpertCount], dtype: .float32) + } + + func callAsFunction(_ x: MLXArray, rowLocal: Bool = false) + -> (indices: MLXArray, weights: MLXArray) + { + if rowLocal && MiMoV26RectangularDense.supports(x) { + // One shared declared-precision conversion per layer/forward. + // Every dot product AND score-selection/normalization stays [1,1,*]. + // Never rely on common-subexpression elimination of repeated casts. + let matrix = weight.asType(operandDType).asType(.float32).T + let routed = (0 ..< x.dim(1)).map { position in + let row = x[0..., position ..< (position + 1), 0...].contiguous() + let logits = + MiMoV26DecodeRouter.logits( + row, weight: weight, operandDType: operandDType, + enabled: useFusedDecodeRouter) + ?? matmul(row.asType(operandDType).asType(.float32), matrix) + return select(logits) + } + return ( + concatenated(routed.map(\.indices), axis: 1), + concatenated(routed.map(\.weights), axis: 1) + ) + } + // Quantize operands to the declared router precision, but do not round + // the dot-product result to BF16 before sigmoid. The reference CUDA + // router requests FP32 output for BF16 inputs. This explicit FP32 path + // remains subject to independent numerical qualification on Metal. + let logits = + MiMoV26DecodeRouter.logits( + x, weight: weight, operandDType: operandDType, enabled: useFusedDecodeRouter) + ?? matmul( + x.asType(operandDType).asType(.float32), + weight.asType(operandDType).asType(.float32).T) + return select(logits) + } + + private func select(_ logits: MLXArray) -> (indices: MLXArray, weights: MLXArray) { + let originalScores = sigmoid(logits) + var selection = originalScores + correctionBias.asType(.float32) + if config.topKGroups < config.expertGroupCount { + var grouped = unflatten( + selection, axis: -1, + shape: [config.expertGroupCount, -1]) + let groupScores = top(grouped, k: 2, axis: -1).sum(axis: -1, keepDims: true) + let excluded = config.expertGroupCount - config.topKGroups + let rankedGroups = argPartition(groupScores, kth: excluded - 1, axis: -2) + let indices = rankedGroups[.ellipsis, .. 1 && config.normalizeTopKProbability { + weights = weights / (weights.sum(axis: -1, keepDims: true) + 1e-20) + } + weights = weights * Float(config.routedScalingFactor ?? 1) + return (indices, weights) + } +} + +final class MiMoV26MoE: Module, UnaryLayer { + let gate: MiMoV26Router + private let useFP32WeightedReduction: Bool + @ModuleInfo(key: "switch_mlp") var switchMLP: SwitchGLU + + init( + _ config: MiMoV26Configuration, + fp32WeightedReduction: Bool = MiMoV26FP32WeightedReduction.isEnabled() + ) { + gate = MiMoV26Router(config) + useFP32WeightedReduction = fp32WeightedReduction + _switchMLP.wrappedValue = SwitchGLU( + inputDims: config.hiddenSize, + hiddenDims: config.moeIntermediateSize, + numExperts: config.routedExpertCount, + weightedReductionProfile: .mimoV26FP32, + mimoV26NAXGather: true) + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + forwardWithWeightedReductionRoute(x).output + } + + /// Same real router/projections used by callAsFunction, with scalar route + /// evidence for qualification. No scripted proposal or alternate weights. + func forwardWithWeightedReductionRoute(_ x: MLXArray, rowLocalRouter: Bool = false) + -> MiMoV26FP32WeightedReductionResult + { + let routed = gate(x, rowLocal: rowLocalRouter) + if useFP32WeightedReduction { + let reduced = switchMLP.callAndMiMoFP32WeightedReduce( + x, routed.indices, weights: routed.weights, enabled: true) + return .init(output: reduced.output.asType(x.dtype), route: reduced.route) + } + // Keep the default/OFF graph identical to the original MiMo expression. + let expertOutput = switchMLP(x, routed.indices) + return .init( + output: (expertOutput * routed.weights[.ellipsis, .newAxis]) + .sum(axis: -2).asType(x.dtype), route: .disabled) + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26RectangularDense.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26RectangularDense.swift new file mode 100644 index 0000000000..ab881d5516 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26RectangularDense.swift @@ -0,0 +1,165 @@ +// Copyright © 2026 Eigen Labs. +// Opt-in scalar-shape candidate; exact full-state qualification is pending. +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +enum MiMoV26RectangularDense { + static var enabledByEnvironment: Bool { + ProcessInfo.processInfo.environment["DARKBLOOM_MIMO_RECTANGULAR_SCALAR_DENSE"] == "1" + } + + static func eligible( + shape: [Int], rectangularCacheFlags: [Bool], + requested: Bool, fusedNorms: Bool + ) -> Bool { + requested && !fusedNorms && shape.count == 2 && shape[0] == 1 + && (2 ... 4).contains(shape[1]) && !rectangularCacheFlags.isEmpty + && rectangularCacheFlags.allSatisfy { $0 } + } + + static func eligible( + tokens: MLXArray, caches: [any CBv2AttendingLayerCache], + requested: Bool, fusedNorms: Bool + ) -> Bool { + eligible( + shape: tokens.shape, + rectangularCacheFlags: caches.map { + guard let cache = $0 as? any CBv2MTPRectangularSerializing else { return false } + return cache.mtpSerializesRectangularAttention + || cache.mtpBatchesRectangularAttention + }, requested: requested, fusedNorms: fusedNorms) + } + + static func supports(_ x: MLXArray) -> Bool { + x.ndim == 3 && x.dim(0) == 1 && (2 ... 4).contains(x.dim(1)) + && x.dim(2) > 0 && x.dim(2) <= 16384 + && (x.dtype == .bfloat16 || x.dtype == .float16) + } + + private static func rows(_ x: MLXArray, _ body: (MLXArray) -> MLXArray) -> MLXArray { + // Preserve scalar [1,1,D] rank and request row-contiguous operands. + // Already contiguous slices may alias their whole input backing; no + // compact-allocation or early-release claim follows from contiguous(). + // No weight conversion or host readback. + let values = (0 ..< x.dim(1)).map { position in + body(x[0..., position ..< (position + 1), 0...].contiguous()) + } + return concatenated(values, axis: 1) + } + + static func projection(_ layer: Linear, _ x: MLXArray, enabled: Bool) -> MLXArray { + guard enabled && supports(x) else { return layer(x) } + return rows(x) { layer($0) } + } + + static func readout(_ target: MiMoV26TextModel, _ x: MLXArray, enabled: Bool) -> MLXArray { + func project(_ value: MLXArray) -> MLXArray { + target.lmHead.map { $0(value) } ?? target.model.embedTokens.asLinear(value) + } + guard enabled && supports(x) else { return project(x) } + return rows(x, project) + } + + static func mlp(_ layer: any UnaryLayer, _ x: MLXArray, enabled: Bool) -> MLXArray { + guard enabled && supports(x) else { return layer(x) } + if let dense = layer as? MiMoV26DenseMLP { + // Keep the three dense projections and their activation rounding + // on the scalar path. This is not applied to expert projections. + return rows(x) { dense($0) } + } + if let moe = layer as? MiMoV26MoE { + return moe.forwardWithWeightedReductionRoute(x, rowLocalRouter: true).output + } + return layer(x) + } +} + +extension MiMoV26RectangularDense { + /// Additive source-visible graph envelope, not an MLX physical-peak claim. + /// Bound BOTH a predecessor and successor, all layers and every independent + /// row allocation. Do not subtract the ordinary target/assistant/OS reserve. + static func scratchSpec(_ target: MiMoV26TextModel) + -> MiMoV26RectangularDenseScratchSpec? + { + let c = target.configuration + guard target.activationDType == .bfloat16 || target.activationDType == .float16, + (1 ... 48).contains(c.numHiddenLayers), + target.model.layers.count == c.numHiddenLayers, + (1 ... 16384).contains(c.hiddenSize), + (1 ... 65536).contains(c.intermediateSize), + (1 ... 262144).contains(c.vocabularySize), + (1 ... 1024).contains(c.routedExpertCount) + else { return nil } + var buffers: [CBv2MTPFixedBufferSpec] = [] + func append(_ elements: Int, _ count: Int) -> Bool { + let bytes = elements.multipliedReportingOverflow(by: 4) + let copies = count.multipliedReportingOverflow(by: 2) // two live forwards + guard elements > 0, count > 0, !bytes.overflow, !copies.overflow else { return false } + buffers.append( + .init(logicalBytes: bytes.partialValue, allocationCount: copies.partialValue)) + return true + } + func projection(input: Int, output: Int) -> Bool { + guard (1 ... 16384).contains(input), (1 ... 262144).contains(output) else { + return false + } + // Worst L=4: compact inputs, independent outputs, final concat. + // Four-byte pricing conservatively includes native two-byte arrays. + return append(input, 4) && append(output, 4) && append(4 * output, 1) + } + for layer in target.model.layers { + let a = layer.selfAttention + let g = a.geometry + let q = g.queryHeads.multipliedReportingOverflow(by: g.headDim) + let k = g.keyValueHeads.multipliedReportingOverflow(by: g.headDim) + let v = g.keyValueHeads.multipliedReportingOverflow(by: g.valueHeadDim) + let o = g.queryHeads.multipliedReportingOverflow(by: g.valueHeadDim) + guard !q.overflow, !k.overflow, !v.overflow, !o.overflow, + a.qProj.shape == (q.partialValue, c.hiddenSize), + a.kProj.shape == (k.partialValue, c.hiddenSize), + a.vProj.shape == (v.partialValue, c.hiddenSize), + a.oProj.shape == (c.hiddenSize, o.partialValue), + projection(input: c.hiddenSize, output: q.partialValue), + projection(input: c.hiddenSize, output: k.partialValue), + projection(input: c.hiddenSize, output: v.partialValue), + projection(input: o.partialValue, output: c.hiddenSize) + else { return nil } + if let dense = layer.mlp as? MiMoV26DenseMLP { + guard dense.gateProj.shape == (c.intermediateSize, c.hiddenSize), + dense.upProj.shape == (c.intermediateSize, c.hiddenSize), + dense.downProj.shape == (c.hiddenSize, c.intermediateSize), + // Row compact; gate, SiLU, up, product; down + concat. + append(c.hiddenSize, 4), append(c.intermediateSize, 16), + append(c.hiddenSize, 4), append(4 * c.hiddenSize, 1) + else { return nil } + } else if let moe = layer.mlp as? MiMoV26MoE { + guard moe.gate.weight.shape == [c.routedExpertCount, c.hiddenSize], + moe.gate.correctionBias.shape == [c.routedExpertCount] + else { return nil } + let matrix = c.routedExpertCount.multipliedReportingOverflow(by: c.hiddenSize) + guard !matrix.overflow, + // ONE shared matrix per forward; price both possible casts, + // even when the first is an identity for this checkpoint. + append(matrix.partialValue, 2), + append(c.hiddenSize, 12), // compact + two casts per row + append(c.routedExpertCount, 4 * 32), // per-row logits, selection/group/top-k roots + append(4 * c.routedExpertCount, 2), // indices + weights concat, topK <= experts + append(4, 4 * 16) + else { return nil } + // Expert gather, SiLU/product and weighted reduction remain + // bulk, unchanged. Their baseline reserve is never discounted. + } else { + return nil + } + } + let readout = target.lmHead?.shape ?? target.model.embedTokens.shape + guard readout == (c.vocabularySize, c.hiddenSize), + projection(input: c.hiddenSize, output: c.vocabularySize) + else { return nil } + // Bounded Swift lists/graph handles/metadata; not a native allocator cap. + let host = 2 * (128 * 1024 + c.numHiddenLayers * 4 * 2048) + return .init(buffers: buffers, hostBytes: host) + } +} diff --git a/Libraries/MLXLLM/Models/MiMo/MiMoV26Text.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV26Text.swift new file mode 100644 index 0000000000..456974e130 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiMo/MiMoV26Text.swift @@ -0,0 +1,380 @@ +// Copyright © 2026 Eigen Labs. +// Native MiMo V2.6 text component, deliberately not a public factory alias. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +public enum MiMoV26ExecutionError: Error, Equatable, Sendable { + case unsupportedConfiguration(String) + case invalidInput(String) + case unsupportedCache(layer: Int) + case cacheGeometry(layer: Int) + case contextExceeded +} + +final class MiMoV26DecoderLayer: Module { + @ModuleInfo(key: "self_attn") var selfAttention: MiMoV26Attention + @ModuleInfo(key: "input_layernorm") var inputNorm: RMSNorm + @ModuleInfo(key: "post_attention_layernorm") var postAttentionNorm: RMSNorm + let mlp: UnaryLayer + let geometry: MiMoV26AttentionGeometry + + init(_ config: MiMoV26Configuration, layer: Int) throws { + geometry = try config.attentionGeometry(at: layer) + _selfAttention.wrappedValue = MiMoV26Attention(config, geometry: geometry) + _inputNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, + eps: Float(config.layernormEpsilon)) + _postAttentionNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, + eps: Float(config.layernormEpsilon)) + mlp = + config.moeLayerFrequency[layer] == 1 + ? MiMoV26MoE(config) + : MiMoV26DenseMLP( + hiddenSize: config.hiddenSize, + intermediateSize: config.intermediateSize) + } + + func callAsFunction( + _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: KVCache? + ) -> MLXArray { + let residual = x + selfAttention(inputNorm(x), mask: mask, cache: cache) + return residual + mlp(postAttentionNorm(residual)) + } +} + +public final class MiMoV26TextBackbone: Module { + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + @ModuleInfo(key: "norm") var norm: RMSNorm + let layers: [MiMoV26DecoderLayer] + let configuration: MiMoV26Configuration + + // Opt-in until this exact source/binary passes the native numerical and + // complete-state gates. Tests set this on a fresh model before evaluation. + var useFusedDecodeNorms = + ProcessInfo.processInfo.environment["DARKBLOOM_MIMO_FUSED_DECODE_NORMS"] == "1" + + init(_ config: MiMoV26Configuration) throws { + configuration = config + _embedTokens.wrappedValue = Embedding( + embeddingCount: config.vocabularySize, + dimensions: config.hiddenSize) + _norm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, + eps: Float(config.layernormEpsilon)) + layers = try (0 ..< config.numHiddenLayers).map { + try MiMoV26DecoderLayer(config, layer: $0) + } + } + + func forward(embeddings: MLXArray, cache: [KVCache]?, captureLayers: Set) + -> (normalized: MLXArray, features: [Int: MLXArray]) + { + var hidden = embeddings + var nextInput: MLXArray? + var features: [Int: MLXArray] = [:] + for (index, layer) in layers.enumerated() { + let layerCache = cache?[index] + let mask = createAttentionMask( + h: hidden, cache: layerCache, + windowSize: layer.geometry.slidingWindow) + let normalized = nextInput ?? layer.inputNorm(hidden) + let attention = layer.selfAttention(normalized, mask: mask, cache: layerCache) + let nextNorm = index + 1 < layers.count ? layers[index + 1].inputNorm : norm + if let fused = MiMoV26DecodeKernels.finishLayer( + hidden, attentionOutput: attention, layer: layer, + nextNorm: nextNorm, enabled: useFusedDecodeNorms) + { + hidden = fused.residual + nextInput = fused.normalized + } else { + let residual = hidden + attention + hidden = residual + layer.mlp(layer.postAttentionNorm(residual)) + nextInput = nil + } + if captureLayers.contains(index) { features[index] = hidden } + } + return (nextInput ?? norm(hidden), features) + } +} + +/// Request-owned outputs. Captured features are opt-in; the model never retains +/// a previous request's hidden tensors, rotary offsets or speculative state. +public struct MiMoV26TextOutput { + public let logits: MLXArray + public let normalizedHiddenStates: MLXArray + public let layerFeatures: [Int: MLXArray] + public let firstPosition: Int + let ownerIdentity: UUID +} + +/// Target-text building block for the future native omnimodal wrapper. It does +/// not register `mimo_v2`, discard non-text weights, advertise CBv2/paged support, +/// or infer MTP activation from the presence of trained heads in a checkpoint. +public final class MiMoV26TextModel: Module { + public let configuration: MiMoV26Configuration + public let model: MiMoV26TextBackbone + let activationDType: DType + let identity = UUID() + @ModuleInfo(key: "lm_head") var lmHead: Linear? + + /// Packed storage dtype is not the activation dtype. Validate all declared + /// affine parameters without materializing or dequantizing the full table. + var hasLoadedEmbeddingPrecision: Bool { + let embedding = model.embedTokens + if let packed = embedding as? QuantizedEmbedding { + return packed.mode == .affine && packed.bits == 8 && packed.groupSize == 64 + && packed.weight.dtype == .uint32 && packed.scales.dtype == activationDType + && packed.biases?.dtype == activationDType + && packed.weight.shape == [ + configuration.vocabularySize, configuration.hiddenSize / 4, + ] + && packed.scales.shape == [ + configuration.vocabularySize, configuration.hiddenSize / 64, + ] + && packed.biases?.shape == packed.scales.shape + } + return embedding.weight.dtype == activationDType + && embedding.weight.shape == [configuration.vocabularySize, configuration.hiddenSize] + } + + var hasLoadedReadoutPrecision: Bool { + guard let readout = lmHead else { return hasLoadedEmbeddingPrecision } + if let packed = readout as? QuantizedLinear { + return packed.mode == .affine && packed.bits == 8 && packed.groupSize == 64 + && packed.weight.dtype == .uint32 && packed.scales.dtype == activationDType + && packed.biases?.dtype == activationDType + && packed.weight.shape == [ + configuration.vocabularySize, configuration.hiddenSize / 4, + ] + && packed.scales.shape == [ + configuration.vocabularySize, configuration.hiddenSize / 64, + ] + && packed.biases?.shape == packed.scales.shape + } + return readout.weight.dtype == activationDType + && readout.weight.shape == [configuration.vocabularySize, configuration.hiddenSize] + } + + public init(_ config: MiMoV26Configuration) throws { + // Decoding preserves future metadata; construction must separately + // reject operational semantics not implemented by this component. + var dimensions: [Int] = [ + config.hiddenSize, config.intermediateSize, config.moeIntermediateSize, + config.vocabularySize, config.numHiddenLayers, config.maxPositionEmbeddings, + config.routedExpertCount, + ] + for geometry in [config.fullAttention, config.slidingAttention] { + dimensions.append(contentsOf: [ + geometry.queryHeads, geometry.keyValueHeads, + geometry.headDim, geometry.valueHeadDim, + ]) + dimensions.append(geometry.queryHeads * geometry.headDim) + dimensions.append(geometry.queryHeads * geometry.valueHeadDim) + dimensions.append(geometry.keyValueHeads * geometry.headDim) + dimensions.append(geometry.keyValueHeads * geometry.valueHeadDim) + } + guard dimensions.allSatisfy({ $0 > 0 && $0 <= Int(Int32.max) }) else { + throw MiMoV26ExecutionError.unsupportedConfiguration("MLX shape exceeds Int32") + } + var tensorShapes: [[Int]] = [ + [config.vocabularySize, config.hiddenSize], + [config.hiddenSize, config.intermediateSize], + [config.routedExpertCount, config.hiddenSize, config.moeIntermediateSize], + ] + for geometry in [config.fullAttention, config.slidingAttention] { + tensorShapes.append([geometry.queryHeads * geometry.headDim, config.hiddenSize]) + tensorShapes.append([geometry.keyValueHeads * geometry.headDim, config.hiddenSize]) + tensorShapes.append([geometry.keyValueHeads * geometry.valueHeadDim, config.hiddenSize]) + tensorShapes.append([geometry.queryHeads * geometry.valueHeadDim, config.hiddenSize]) + } + for shape in tensorShapes { + var bytes = 4 // Initial module parameters are FP32 before strict loading. + for dimension in shape { + let product = bytes.multipliedReportingOverflow(by: dimension) + guard !product.overflow else { + throw MiMoV26ExecutionError.unsupportedConfiguration( + "tensor byte geometry overflow") + } + bytes = product.partialValue + } + } + let scalars = [ + config.attentionValueScale, config.layernormEpsilon, + config.fullAttention.ropeTheta, config.slidingAttention.ropeTheta, + config.routedScalingFactor ?? 1, + ] + guard scalars.allSatisfy({ Float($0).isFinite && Float($0) > 0 }) else { + throw MiMoV26ExecutionError.unsupportedConfiguration("nonrepresentable Float scalar") + } + guard config.sharedExpertCount == nil || config.sharedExpertCount == 0 else { + throw MiMoV26ExecutionError.unsupportedConfiguration("shared experts") + } + if let scaling = config.rawFields["rope_scaling"], scaling != .null { + throw MiMoV26ExecutionError.unsupportedConfiguration("rope_scaling") + } + guard config.attentionDropout == 0 else { + throw MiMoV26ExecutionError.unsupportedConfiguration("nonzero attention dropout") + } + configuration = config + activationDType = + config.dtype == "bfloat16" + ? .bfloat16 + : (config.dtype == "float16" ? .float16 : .float32) + model = try MiMoV26TextBackbone(config) + _lmHead.wrappedValue = + config.tieWordEmbeddings + ? nil + : Linear(config.hiddenSize, config.vocabularySize, bias: false) + } + + public func newCache() -> [KVCache] { + model.layers.map { layer in + if let window = layer.geometry.slidingWindow { + return RotatingKVCache(maxSize: window) + } + return KVCacheSimple() + } + } + + /// Supply token IDs or already prepared native embeddings, never both. + /// Native processors must preserve media order/positions before this seam. + /// logitsStart avoids projecting discarded prefix rows without changing + /// attention, retained hidden states or cache updates for those rows. + public func forward( + inputIDs: MLXArray? = nil, embeddings: MLXArray? = nil, + cache: [KVCache]? = nil, logitsStart: Int = 0, + captureLayers: Set = [] + ) throws -> MiMoV26TextOutput { + guard (inputIDs != nil) != (embeddings != nil) else { + throw MiMoV26ExecutionError.invalidInput("provide IDs or embeddings, not both") + } + let batch: Int + let length: Int + if let inputIDs { + guard inputIDs.ndim == 2, inputIDs.dtype == .int32 || inputIDs.dtype == .uint32 else { + throw MiMoV26ExecutionError.invalidInput("IDs require rank-two int32/uint32") + } + batch = inputIDs.dim(0) + length = inputIDs.dim(1) + } else if let embeddings { + guard embeddings.ndim == 3, embeddings.dim(2) == configuration.hiddenSize, + embeddings.dtype == activationDType + else { + throw MiMoV26ExecutionError.invalidInput("invalid native embeddings") + } + batch = embeddings.dim(0) + length = embeddings.dim(1) + } else { + throw MiMoV26ExecutionError.invalidInput("missing input") + } + guard batch > 0, length > 0, logitsStart >= 0, logitsStart < length, + captureLayers.allSatisfy({ model.layers.indices.contains($0) }) + else { + throw MiMoV26ExecutionError.invalidInput("invalid forward geometry") + } + if let inputIDs { + // Direct SDK inputs must not inherit MLX's negative-index behavior. + // Validate before embedding access or mutation of any layer cache. + let minimum = + inputIDs.dtype == .int32 + ? Int64(inputIDs.min().item(Int32.self)) + : Int64(inputIDs.min().item(UInt32.self)) + let maximum = + inputIDs.dtype == .int32 + ? Int64(inputIDs.max().item(Int32.self)) + : Int64(inputIDs.max().item(UInt32.self)) + guard minimum >= 0, maximum < Int64(configuration.vocabularySize) else { + throw MiMoV26ExecutionError.invalidInput("token ID outside vocabulary") + } + guard hasLoadedEmbeddingPrecision, hasLoadedReadoutPrecision else { + throw MiMoV26ExecutionError.unsupportedConfiguration( + "embedding precision is not loaded") + } + } + try validateCache(cache, batch: batch, length: length) + let firstPosition = cache?.first?.offset ?? 0 + let hidden = embeddings ?? model.embedTokens(inputIDs!) + let result = model.forward(embeddings: hidden, cache: cache, captureLayers: captureLayers) + let projected = result.normalized[0..., logitsStart..., 0...] + let logits = lmHead.map { $0(projected) } ?? model.embedTokens.asLinear(projected) + return MiMoV26TextOutput( + logits: logits, normalizedHiddenStates: result.normalized, + layerFeatures: result.features, firstPosition: firstPosition, + ownerIdentity: identity) + } + + private func validateCache(_ cache: [KVCache]?, batch: Int, length: Int) throws { + guard length <= configuration.maxPositionEmbeddings else { + throw MiMoV26ExecutionError.contextExceeded + } + guard let cache else { return } + guard cache.count == model.layers.count else { + throw MiMoV26ExecutionError.invalidInput("one cache per target layer is required") + } + let absoluteOffset = cache.first?.offset ?? 0 + guard absoluteOffset >= 0, absoluteOffset <= configuration.maxPositionEmbeddings - length + else { + throw MiMoV26ExecutionError.contextExceeded + } + // Validate the complete list before the first layer can append anything. + var owners = Set() + for (index, entry) in cache.enumerated() { + let geometry = model.layers[index].geometry + guard let base = entry as? BaseKVCache, + type(of: base) == KVCacheSimple.self || type(of: base) == RotatingKVCache.self + else { + throw MiMoV26ExecutionError.unsupportedCache(layer: index) + } + guard owners.insert(ObjectIdentifier(base)).inserted, + entry.offset == absoluteOffset, entry.maxSize == geometry.slidingWindow + else { + throw MiMoV26ExecutionError.cacheGeometry(layer: index) + } + // Raw ownership state, before a malformed offset can create a slice. + let state = base.innerState() + guard state.isEmpty || (state.count == 2 && state.allSatisfy { $0.ndim == 4 }) else { + throw MiMoV26ExecutionError.cacheGeometry(layer: index) + } + if state.isEmpty && absoluteOffset != 0 { + throw MiMoV26ExecutionError.cacheGeometry(layer: index) + } + if let simple = base as? KVCacheSimple { + guard simple.step > 0, simple.step <= Int(Int32.max), + simple.step <= Int.max - length, + state.isEmpty || absoluteOffset <= state[0].dim(2) + else { + throw MiMoV26ExecutionError.cacheGeometry(layer: index) + } + } else { + let raw = base.metaState + let metadata = raw.compactMap(Int.init) + guard raw.count == 5, metadata.count == 5, metadata[0] == 0, + metadata[1] == geometry.slidingWindow, metadata[2] > 0, + metadata[2] <= Int(Int32.max), + metadata[2] <= Int.max - length, metadata[3] == absoluteOffset, + metadata[4] >= 0, metadata[4] <= min(absoluteOffset, state.first?.dim(2) ?? 0), + state.isEmpty || state[0].dim(2) >= min(absoluteOffset, metadata[1]) + else { + throw MiMoV26ExecutionError.cacheGeometry(layer: index) + } + } + if !state.isEmpty { + let key = state[0] + let value = state[1] + guard key.dim(0) == batch, value.dim(0) == batch, + key.dim(1) == geometry.keyValueHeads, value.dim(1) == geometry.keyValueHeads, + key.dim(2) == value.dim(2), key.dim(3) == geometry.headDim, + value.dim(3) == geometry.valueHeadDim, + key.dtype == activationDType, value.dtype == activationDType + else { + throw MiMoV26ExecutionError.cacheGeometry(layer: index) + } + } + } + } +} diff --git a/Libraries/MLXLLM/Models/MiMoV2Flash.swift b/Libraries/MLXLLM/Models/MiMo/MiMoV2Flash.swift similarity index 100% rename from Libraries/MLXLLM/Models/MiMoV2Flash.swift rename to Libraries/MLXLLM/Models/MiMo/MiMoV2Flash.swift diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/AdmissionCheckpointTransfer.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/AdmissionCheckpointTransfer.swift index b28ee0259d..b91ecc779e 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/AdmissionCheckpointTransfer.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/AdmissionCheckpointTransfer.swift @@ -4,6 +4,7 @@ struct CBv2CheckpointStageEntry { var bytes: Int var transferred: Bool var settled = false + var nativePreparationExtended = false } /// A native engine's typed staging charge. Its owner must drop all destination @@ -20,6 +21,7 @@ final class CBv2CheckpointStageLease: @unchecked Sendable { private let lock = NSLock() private var retainedDestination: Destination private var didSettle = false + private var didExtendNativePreparation = false var destination: Destination { lock.withLock { retainedDestination } } var targetBytes: Int { destination.targetBytes } var auxiliaryBytes: Int { destination.auxiliaryBytes } @@ -27,8 +29,10 @@ final class CBv2CheckpointStageLease: @unchecked Sendable { var destinationBytes: Int { destination.bytes } var totalBytes: Int { destinationBytes + scratchBytes } - init(admission: AdmissionV2, identity: UUID, targetBytes: Int, - auxiliaryBytes: Int, scratchBytes: Int) { + init( + admission: AdmissionV2, identity: UUID, targetBytes: Int, + auxiliaryBytes: Int, scratchBytes: Int + ) { self.admission = admission self.identity = identity self.retainedDestination = .init(targetBytes: targetBytes, auxiliaryBytes: auxiliaryBytes) @@ -40,8 +44,9 @@ final class CBv2CheckpointStageLease: @unchecked Sendable { func settleDestinationAfterEvaluation(targetBytes: Int, auxiliaryBytes: Int) throws { try lock.withLock { guard !didSettle, targetBytes >= 0, auxiliaryBytes >= 0, - targetBytes <= retainedDestination.targetBytes, - auxiliaryBytes <= retainedDestination.auxiliaryBytes else { + targetBytes <= retainedDestination.targetBytes, + auxiliaryBytes <= retainedDestination.auxiliaryBytes + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } let actual = Destination(targetBytes: targetBytes, auxiliaryBytes: auxiliaryBytes) @@ -53,6 +58,35 @@ final class CBv2CheckpointStageLease: @unchecked Sendable { } } + /// One native paged preparation may add its EXACT missing-suffix and + /// bounded host-map promise to this same stage, before constructing them. + /// This only grows C. No pool/request transfer or native credit occurs. + /// Initial imported destinations must already have settled; the enlarged + /// phase must itself settle once before the final atomic adoption. + func extendForNativePagedPreparation(targetBytes: Int, auxiliaryBytes: Int) throws { + try lock.withLock { + guard didSettle, !didExtendNativePreparation, + targetBytes >= 0, auxiliaryBytes >= 0, + targetBytes > 0 || auxiliaryBytes > 0 + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let target = try CBv2CheckpointAllocationFootprint.add( + retainedDestination.targetBytes, targetBytes) + let auxiliary = try CBv2CheckpointAllocationFootprint.add( + retainedDestination.auxiliaryBytes, auxiliaryBytes) + let additional = try CBv2CheckpointAllocationFootprint.add(targetBytes, auxiliaryBytes) + let expected = try CBv2CheckpointAllocationFootprint.add( + retainedDestination.bytes, scratchBytes) + try admission.extendCheckpointStage( + identity: identity, + expectedBytes: expected, additionalBytes: additional) + retainedDestination = .init(targetBytes: target, auxiliaryBytes: auxiliary) + didSettle = false + didExtendNativePreparation = true + } + } + func closeAfterDroppingOwners() { admission.closeCheckpointStage(identity: identity) } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/AdmissionV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/AdmissionV2.swift index 399b2145d3..f86b2cfa7a 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/AdmissionV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/AdmissionV2.swift @@ -277,6 +277,15 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { private var transientTargetBytes = 0 private var checkpointStages: [UUID: CBv2CheckpointStageEntry] = [:] private var checkpointRequestOwners: [CBv2RequestID: UUID] = [:] + private var contiguousCheckpointOwners: [CBv2RequestID: UUID] = [:] + private struct DetachedContiguousCheckpoint { + let bytes: Int + let nonBackendBytes: Int + var rowsReleased = false + var leaseReleased: Bool + } + private var detachedContiguousCheckpoints: [UUID: DetachedContiguousCheckpoint] = [:] + private var detachedContiguousTargetBytes = 0 /// Subset of reservedExactBytes belonging to imported recurrent/MTP state, /// not target KV. It follows the same request generation and retirement. private var checkpointAuxiliaryBytes: [CBv2RequestID: Int] = [:] @@ -287,14 +296,19 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { private var processMaterializedBytes = 0 var hasProcessMemoryOwner: Bool { processMemoryOwner != nil } + func usesProcessMemoryOwner(_ expected: any CBv2ProcessMemoryOwner) -> Bool { + processMemoryOwner === expected + } + public init( layerKinds: [CBv2LayerKind], bytesCapacity: Int, config: Config = .init(), residency: any CBv2KVResidencyPolicy = CBv2ContiguousKVResidency(), externalReserveBytes: Int = 0, processMemoryOwner: (any CBv2ProcessMemoryOwner)? = nil ) { - precondition(processMemoryOwner == nil || externalReserveBytes == 0, - "process-owned engines cannot start with an unreserved external carve") + precondition( + processMemoryOwner == nil || externalReserveBytes == 0, + "process-owned engines cannot start with an unreserved external carve") self.processMemoryOwner = processMemoryOwner self.residency = residency self.layerKinds = layerKinds @@ -345,8 +359,9 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { by: self.auxiliaryTokenGranularity) let (totalPerToken, auxiliaryOverflow) = perToken.addingReportingOverflow( max(maximumAuxiliaryGrowth, auxiliaryAllocationProjection?.maximumGrowthBytes ?? 0)) - self.maxPerTokenBytes = accountingOverflow || auxiliaryOverflow - || auxiliaryGrowthOverflow + self.maxPerTokenBytes = + accountingOverflow || auxiliaryOverflow + || auxiliaryGrowthOverflow ? Int.max : totalPerToken self.fullKVBytesPerToken = accountingOverflow ? Int.max : fullPerToken } @@ -355,32 +370,40 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { /// accepting requests. Other slots own independent AdmissionV2 instances. func bindBackendPhysicalFloor(initialBytes: Int) -> CBv2BackendPhysicalLease { precondition(initialBytes >= 0) - precondition(!hasProcessMemoryOwner || initialBytes == 0, - "process-owned segmented pools must bind before allocation") + precondition( + !hasProcessMemoryOwner || initialBytes == 0, + "process-owned segmented pools must bind before allocation") lock.lock() - precondition(!physicalFloor.isBound && ledgerBytes == 0 && reservedTokens.isEmpty, - "a physical floor must bind once before requests exist") + precondition( + !physicalFloor.isBound && ledgerBytes == 0 && reservedTokens.isEmpty, + "a physical floor must bind once before requests exist") physicalFloor.isBound = true physicalFloor.physicalBytes = initialBytes lock.unlock() - return CBv2BackendPhysicalLease(bytes: initialBytes, resize: { [self] bytes in - try resizeBackendPhysicalFloor(to: bytes) - }, onClose: { [self] in - lock.lock() - physicalFloor.physicalBytes = 0 - publishProcessReductionLocked() - lock.unlock() - }, snapshot: { [self] in - lock.withLock { - CBv2BackendPhysicalAccounting( - nominalKVBytes: physicalFloor.nominalBytes, - physicalFloorOverheadBytes: physicalFloor.overheadBytes) - } - }, admissionIdentity: ObjectIdentifier(self)) + return CBv2BackendPhysicalLease( + bytes: initialBytes, + resize: { [self] bytes in + try resizeBackendPhysicalFloor(to: bytes) + }, + onClose: { [self] in + lock.lock() + physicalFloor.physicalBytes = 0 + publishProcessReductionLocked() + lock.unlock() + }, + snapshot: { [self] in + lock.withLock { + CBv2BackendPhysicalAccounting( + nominalKVBytes: physicalFloor.nominalBytes, + physicalFloorOverheadBytes: physicalFloor.overheadBytes) + } + }, admissionIdentity: ObjectIdentifier(self)) } private func resizeBackendPhysicalFloor(to bytes: Int) throws { - guard bytes >= 0 else { throw CBv2KVError.backendIneligible(reason: "negative physical floor") } + guard bytes >= 0 else { + throw CBv2KVError.backendIneligible(reason: "negative physical floor") + } lock.lock() defer { lock.unlock() } guard let after = physicalFloor.chargedBytes(base: ledgerBytes, physical: bytes) else { @@ -406,7 +429,8 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { } private func nominalTargetBytes(forTokens tokens: Int, allocated: Int? = nil) -> Int? { guard let total = allocated ?? allocatedBytesChecked(forTokens: tokens), - let auxiliary = nonBackendBytesChecked(forTokens: tokens), total >= auxiliary else { return nil } + let auxiliary = nonBackendBytesChecked(forTokens: tokens), total >= auxiliary + else { return nil } return total - auxiliary } private func projectedNominal( @@ -415,8 +439,9 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { ) -> Int? { guard physicalFloor.isBound else { return 0 } guard let old = nominalTargetBytes(forTokens: oldTokens, allocated: oldAllocated), - let new = nominalTargetBytes(forTokens: newTokens, allocated: newAllocated), - let value = Self.add(nominal, new - old), value >= 0 else { return nil } + let new = nominalTargetBytes(forTokens: newTokens, allocated: newAllocated), + let value = Self.add(nominal, new - old), value >= 0 + else { return nil } return value } @@ -432,8 +457,7 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { do { try processMemoryOwner.replaceCharge(UInt64(complete)) processChargedBytes = complete - } - catch { + } catch { throw CBv2KVError.capacityExhausted( needed: max(0, charged - chargedLedgerBytes), available: 0) } @@ -441,8 +465,9 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { /// Callers have withdrawn coverage and dropped any retiring buffer aliases. private func publishProcessReductionLocked() { - do { try acceptProcessChargeLocked(chargedLedgerBytes) } - catch { preconditionFailure("process charge retirement refused: \(error)") } + do { try acceptProcessChargeLocked(chargedLedgerBytes) } catch { + preconditionFailure("process charge retirement refused: \(error)") + } } /// Only evaluated, exclusively owned native allocations may call this. @@ -458,8 +483,9 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { return CBv2MemoryCoverage { [self] in lock.withLock { precondition(bytes <= processMaterializedBytes) - do { try processMemoryOwner.withdrawCoverage(UInt64(bytes)) } - catch { preconditionFailure("process coverage retirement refused: \(error)") } + do { try processMemoryOwner.withdrawCoverage(UInt64(bytes)) } catch { + preconditionFailure("process coverage retirement refused: \(error)") + } processMaterializedBytes -= bytes } } @@ -509,9 +535,13 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { else { return nil } let physicalAuxiliary: Int if let auxiliaryAllocationProjection { - guard let bytes = auxiliaryAllocationProjection.bytes(forTokens: tokens) else { return nil } + guard let bytes = auxiliaryAllocationProjection.bytes(forTokens: tokens) else { + return nil + } physicalAuxiliary = max(auxiliary, bytes) - } else { physicalAuxiliary = auxiliary } + } else { + physicalAuxiliary = auxiliary + } return Self.add(fixedBytesPerRequest, physicalAuxiliary) } @@ -639,7 +669,8 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { let (tokens, overflow) = promptTokens.addingReportingOverflow(max(maxTokens, 0)) guard !overflow, additionalBackendBytes >= 0, let allocated = allocatedBytesChecked(forTokens: tokens), - let bytes = Self.add(allocated, additionalBackendBytes) else { + let bytes = Self.add(allocated, additionalBackendBytes) + else { return false } return bytes <= admissibleBytesCapacity @@ -699,15 +730,21 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { nextTokens[reservation.id] = newTokens let physical: Int if let projectedPhysicalBytes { - guard let estimated = projectedPhysicalBytes(nextTokens), estimated >= 0 else { return false } + guard let estimated = projectedPhysicalBytes(nextTokens), estimated >= 0 else { + return false + } // A projected release does not promise that free native // segments or asynchronous export owners have retired yet. physical = max(simulatedPhysicalBytes, estimated) - } else { physical = simulatedPhysicalBytes } - guard let nominal = projectedNominal( - from: simulatedNominalBytes, oldTokens: oldTokens, newTokens: newTokens, - oldAllocated: oldTokenBytes, newAllocated: newTokenBytes), - let charged = physicalFloor.chargedBytes(base: after, nominal: nominal, physical: physical), + } else { + physical = simulatedPhysicalBytes + } + guard + let nominal = projectedNominal( + from: simulatedNominalBytes, oldTokens: oldTokens, newTokens: newTokens, + oldAllocated: oldTokenBytes, newAllocated: newTokenBytes), + let charged = physicalFloor.chargedBytes( + base: after, nominal: nominal, physical: physical), let before = physicalFloor.chargedBytes( base: simulatedLedgerBytes, nominal: simulatedNominalBytes, physical: simulatedPhysicalBytes) @@ -835,10 +872,12 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { guard !afterOverflow else { throw CBv2KVError.capacityExhausted(needed: Int.max, available: 0) } - guard let nominal = projectedNominal( - from: physicalFloor.nominalBytes, oldTokens: old, newTokens: new, - oldAllocated: oldTokenBytes, newAllocated: newTokenBytes), - let charged = physicalFloor.chargedBytes(base: after, nominal: nominal) else { + guard + let nominal = projectedNominal( + from: physicalFloor.nominalBytes, oldTokens: old, newTokens: new, + oldAllocated: oldTokenBytes, newAllocated: newTokenBytes), + let charged = physicalFloor.chargedBytes(base: after, nominal: nominal) + else { throw CBv2KVError.capacityExhausted(needed: Int.max, available: 0) } guard charged <= mutationCeiling else { @@ -861,6 +900,9 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { precondition(tokens >= 0 && bytes >= 0) lock.lock() defer { lock.unlock() } + // Imported v2 rows own their complete N allocation until retirement. + // A logical cursor rollback cannot refund still-live native backing. + if contiguousCheckpointOwners[id] != nil { return } let old = reservedTokens[id] ?? 0 let new = max(0, old - tokens) let oldExact = reservedExactBytes[id] ?? 0 @@ -871,9 +913,11 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { } let oldAllocated = allocatedBytes(forTokens: old) let newAllocated = allocatedBytes(forTokens: new) - guard let nominal = projectedNominal( - from: physicalFloor.nominalBytes, oldTokens: old, newTokens: new, - oldAllocated: oldAllocated, newAllocated: newAllocated) else { + guard + let nominal = projectedNominal( + from: physicalFloor.nominalBytes, oldTokens: old, newTokens: new, + oldAllocated: oldAllocated, newAllocated: newAllocated) + else { preconditionFailure("invalid nominal KV release") } physicalFloor.nominalBytes = nominal @@ -906,12 +950,18 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { } private func releaseAllLocked(id: CBv2RequestID) { + if let owner = contiguousCheckpointOwners[id] { + detachContiguousCheckpointLocked(id: id, owner: owner, leaseReleased: true) + return + } checkpointRequestOwners.removeValue(forKey: id) checkpointAuxiliaryBytes.removeValue(forKey: id) let old = reservedTokens.removeValue(forKey: id) ?? 0 let exact = reservedExactBytes.removeValue(forKey: id) ?? 0 - guard let nominal = projectedNominal( - from: physicalFloor.nominalBytes, oldTokens: old, newTokens: 0) else { + guard + let nominal = projectedNominal( + from: physicalFloor.nominalBytes, oldTokens: old, newTokens: 0) + else { preconditionFailure("invalid nominal KV completion") } physicalFloor.nominalBytes = nominal @@ -926,13 +976,16 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { lock.lock() let (after, overflow) = ledgerBytes.addingReportingOverflow(bytes) guard !overflow, let charged = physicalFloor.chargedBytes(base: after), - charged <= mutationCeiling else { + charged <= mutationCeiling + else { let available = max(0, reserveCeiling - chargedLedgerBytes) lock.unlock() throw CBv2KVError.capacityExhausted(needed: bytes, available: available) } - do { try acceptProcessChargeLocked(charged) } - catch { lock.unlock(); throw error } + do { try acceptProcessChargeLocked(charged) } catch { + lock.unlock() + throw error + } ledgerBytes = after transientBytes += bytes lock.unlock() @@ -1016,6 +1069,36 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { auxiliaryBytes: auxiliaryBytes, scratchBytes: scratchBytes) } + /// Checked upward extension of an already evaluated, still-private stage. + /// The lease lock precedes this existing Admission lock. Nothing native, + /// no pool metadata, and no additional accounting owner is created here. + func extendCheckpointStage(identity: UUID, expectedBytes: Int, additionalBytes: Int) throws { + try lock.withLock { + guard var entry = checkpointStages[identity], !entry.transferred, entry.settled, + !entry.nativePreparationExtended, + entry.bytes == expectedBytes, additionalBytes > 0, + let bytes = Self.add(entry.bytes, additionalBytes), + let after = Self.add(ledgerBytes, additionalBytes), + let transient = Self.add(transientBytes, additionalBytes), + let charged = physicalFloor.chargedBytes(base: after) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + guard charged <= mutationCeiling else { + throw CBv2KVError.capacityExhausted( + needed: additionalBytes, + available: max(0, reserveCeiling - chargedLedgerBytes)) + } + try acceptProcessChargeLocked(charged) + entry.bytes = bytes + entry.settled = false + entry.nativePreparationExtended = true + checkpointStages[identity] = entry + ledgerBytes = after + transientBytes = transient + } + } + /// Typed private destination settlement, after all evaluated allocations /// succeeded. This removes only unused allowance, never backing or scratch. func settleCheckpointStage(identity: UUID, expectedBytes: Int, reduction: Int) throws { @@ -1041,13 +1124,111 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { } } + /// Same-buffer v2 contiguous adoption. No physical pool floor is involved. + /// Retain the original allocator BOUND, not just nbytes or a one-time actual + /// size: later same-shape contiguous updates may replace the allocation. + func transferContiguousCheckpointStage( + _ stage: CBv2CheckpointStageLease, requestID: CBv2RequestID, maximumTokens: Int + ) throws -> CBv2CheckpointAdoptionReservation { + let destination = stage.destination + let total = stage.totalBytes + try lock.withLock { + guard stage.admission === self, !physicalFloor.isBound, + residency is CBv2ContiguousKVResidency, destination.auxiliaryBytes >= 0, + maximumTokens > 0, reservedTokens[requestID] == nil, + reservedExactBytes[requestID] == nil, + checkpointRequestOwners[requestID] == nil, + checkpointStages[stage.identity]?.settled == true, + checkpointStages[stage.identity]?.transferred == false, + checkpointStages[stage.identity]?.bytes == total, + let allocated = allocatedBytesChecked(forTokens: maximumTokens), + let target = nominalTargetBytes(forTokens: maximumTokens, allocated: allocated), + let targetBound = Self.add(allocated, max(0, destination.targetBytes - target)), + // Imported assistant buffers/host witnesses coexist with the + // normal request's future mutable assistant state. Keep their + // FULL additional bound until the shared backing owner dies. + let final = Self.add(targetBound, destination.auxiliaryBytes), + let after = Self.add(ledgerBytes - destination.bytes, final), after >= 0 + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + guard after <= mutationCeiling else { + throw CBv2KVError.capacityExhausted( + needed: max(0, after - chargedLedgerBytes), + available: max(0, reserveCeiling - chargedLedgerBytes)) + } + try acceptProcessChargeLocked(after) + ledgerBytes = after + transientBytes -= destination.bytes + checkpointStages[stage.identity] = .init(bytes: stage.scratchBytes, transferred: true) + reservedTokens[requestID] = maximumTokens + let excess = final - allocated + if excess > 0 { reservedExactBytes[requestID] = excess } + checkpointRequestOwners[requestID] = stage.identity + contiguousCheckpointOwners[requestID] = stage.identity + if destination.auxiliaryBytes > 0 { + checkpointAuxiliaryBytes[requestID] = destination.auxiliaryBytes + } + } + // The typed backing owner is armed immediately after this call. Even + // failed publication keeps C until that owner's final arrays are gone. + return .init(rollback: { [self] in + lock.withLock { + guard contiguousCheckpointOwners[requestID] == stage.identity else { return } + detachContiguousCheckpointLocked( + id: requestID, owner: stage.identity, leaseReleased: true) + } + }) + } + + private func detachContiguousCheckpointLocked( + id: CBv2RequestID, owner: UUID, leaseReleased: Bool + ) { + precondition(contiguousCheckpointOwners.removeValue(forKey: id) == owner) + checkpointRequestOwners.removeValue(forKey: id) + let tokens = reservedTokens.removeValue(forKey: id) ?? 0 + let exact = reservedExactBytes.removeValue(forKey: id) ?? 0 + let auxiliary = checkpointAuxiliaryBytes.removeValue(forKey: id) ?? 0 + let bytes = allocatedBytes(forTokens: tokens) + exact + let nonBackend = (nonBackendBytesChecked(forTokens: tokens) ?? 0) + auxiliary + precondition(detachedContiguousCheckpoints[owner] == nil && bytes >= nonBackend) + detachedContiguousCheckpoints[owner] = .init( + bytes: bytes, nonBackendBytes: nonBackend, leaseReleased: leaseReleased) + detachedNonBackendBytes += nonBackend + detachedContiguousTargetBytes += bytes - nonBackend + // No refund. The request ID can now be reused without refunding this + // generation's buffers or charging them against a new request ID. + } + + func retireContiguousCheckpointRows(id: CBv2RequestID, owner: UUID) { + lock.withLock { + if contiguousCheckpointOwners[id] == owner { + detachContiguousCheckpointLocked(id: id, owner: owner, leaseReleased: true) + } + guard var value = detachedContiguousCheckpoints[owner] else { return } + value.rowsReleased = true + detachedContiguousCheckpoints[owner] = value + retireDetachedContiguousCheckpointLocked(owner) + } + } + + private func retireDetachedContiguousCheckpointLocked(_ owner: UUID) { + guard let value = detachedContiguousCheckpoints[owner], value.rowsReleased, + value.leaseReleased + else { return } + detachedContiguousCheckpoints.removeValue(forKey: owner) + ledgerBytes -= value.bytes + detachedNonBackendBytes -= value.nonBackendBytes + detachedContiguousTargetBytes -= value.bytes - value.nonBackendBytes + publishProcessReductionLocked() + } + /// Called under the pool's physical-lease lock, before allocating missing /// suffix backing. The stage destination becomes ordinary request/floor /// ownership in one Admission mutation; only its scratch stays transient. /// The caller owns the payload exclusively and must discard it on failure. func transferCheckpointStage( _ stage: CBv2CheckpointStageLease, requestID: CBv2RequestID, - maximumTokens: Int, previousPhysicalBytes: Int, physicalBytes: Int + maximumTokens: Int, previousPhysicalBytes: Int, physicalBytes: Int, + retainingNativeAuxiliaryStage: Bool = false ) throws -> CBv2CheckpointAdoptionReservation { // The stage lock precedes Admission; never acquire it while holding // this ledger lock. Settlement happens before the frame is exposed. @@ -1055,6 +1236,10 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { let targetBytes = destination.targetBytes let destinationBytes = destination.bytes let totalBytes = destinationBytes + stage.scratchBytes + // Native paged imports keep immutable assistant bytes and temporary + // host maps on the original stage until their actual owners retire. + // Only target backing moves to the active pool at this boundary. + let movingBytes = retainingNativeAuxiliaryStage ? targetBytes : destinationBytes let rollback = try lock.withLock { guard stage.admission === self, physicalFloor.isBound, physicalFloor.physicalBytes == previousPhysicalBytes, @@ -1064,14 +1249,19 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { reservedExactBytes[requestID] == nil, checkpointStages[stage.identity]?.transferred == false, checkpointStages[stage.identity]?.bytes == totalBytes, + !retainingNativeAuxiliaryStage || checkpointStages[stage.identity]?.settled == true, + !retainingNativeAuxiliaryStage + || checkpointStages[stage.identity]?.nativePreparationExtended == true, let allocated = allocatedBytesChecked(forTokens: maximumTokens), let auxiliary = nonBackendBytesChecked(forTokens: maximumTokens), let allocatedWithShortfall = Self.add( - allocated, max(0, destination.auxiliaryBytes - auxiliary)), + allocated, + retainingNativeAuxiliaryStage + ? 0 : max(0, destination.auxiliaryBytes - auxiliary)), let nominal = projectedNominal( from: physicalFloor.nominalBytes, oldTokens: 0, newTokens: maximumTokens, newAllocated: allocated), - let after = Self.add(ledgerBytes - destinationBytes, allocatedWithShortfall), + let after = Self.add(ledgerBytes - movingBytes, allocatedWithShortfall), let charged = physicalFloor.chargedBytes( base: after, nominal: nominal, physical: physicalBytes) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } @@ -1083,8 +1273,9 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { try acceptProcessChargeLocked(charged) let previousNominal = physicalFloor.nominalBytes ledgerBytes = after - transientBytes -= destinationBytes - checkpointStages[stage.identity] = .init(bytes: stage.scratchBytes, transferred: true) + transientBytes -= movingBytes + checkpointStages[stage.identity] = .init( + bytes: totalBytes - movingBytes, transferred: true) reservedTokens[requestID] = maximumTokens let auxiliaryShortfall = allocatedWithShortfall - allocated if auxiliaryShortfall > 0 { @@ -1094,8 +1285,10 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { checkpointRequestOwners[requestID] = stage.identity physicalFloor.nominalBytes = nominal physicalFloor.physicalBytes = physicalBytes - return (allocated: allocatedWithShortfall, auxiliaryShortfall: auxiliaryShortfall, - nominalDelta: nominal - previousNominal) + return ( + allocated: allocatedWithShortfall, auxiliaryShortfall: auxiliaryShortfall, + nominalDelta: nominal - previousNominal + ) } return CBv2CheckpointAdoptionReservation { [self] in lock.withLock { @@ -1112,6 +1305,20 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { ledgerBytes -= rollback.allocated physicalFloor.nominalBytes -= rollback.nominalDelta physicalFloor.physicalBytes = previousPhysicalBytes + if retainingNativeAuxiliaryStage { + // A stale grant/metadata refusal did not publish a page. + // Restore the SAME stage charge, not a refund while its + // real native owners await retirement. Queue exclusivity + // keeps this rollback before any ordinary pool mutation. + precondition(checkpointStages[stage.identity]?.transferred == true) + precondition( + checkpointStages[stage.identity]?.bytes == totalBytes - movingBytes) + ledgerBytes += movingBytes + transientBytes += movingBytes + checkpointStages[stage.identity] = .init( + bytes: totalBytes, transferred: false, + settled: true, nativePreparationExtended: true) + } publishProcessReductionLocked() } } @@ -1121,13 +1328,26 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { /// retirement. The detached lease can never release a reused request ID. func detachReservation(id: CBv2RequestID) -> CBv2CheckpointReservation { lock.lock() + if let owner = contiguousCheckpointOwners[id] { + detachContiguousCheckpointLocked(id: id, owner: owner, leaseReleased: false) + lock.unlock() + return CBv2CheckpointReservation { [self] in + lock.withLock { + guard var value = detachedContiguousCheckpoints[owner] else { return } + value.leaseReleased = true + detachedContiguousCheckpoints[owner] = value + retireDetachedContiguousCheckpointLocked(owner) + } + } + } checkpointRequestOwners.removeValue(forKey: id) let tokens = reservedTokens.removeValue(forKey: id) ?? 0 let exact = reservedExactBytes.removeValue(forKey: id) ?? 0 let bytes = allocatedBytes(forTokens: tokens) + exact let auxiliary = checkpointAuxiliaryBytes.removeValue(forKey: id) ?? 0 let nonBackendBytes = (nonBackendBytesChecked(forTokens: tokens) ?? 0) + auxiliary - let nominalBytes = physicalFloor.isBound + let nominalBytes = + physicalFloor.isBound ? (nominalTargetBytes(forTokens: tokens) ?? 0) : 0 detachedNonBackendBytes += nonBackendBytes lock.unlock() @@ -1169,11 +1389,9 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { kind: CBv2LayerKind, elementBytes: Int ) -> Int? { - guard kind.kvHeads >= 0, kind.headDim >= 0, elementBytes >= 0, - let elements = multiply(kind.kvHeads, kind.headDim), - let kvElements = multiply(elements, 2) - else { return nil } - return multiply(kvElements, elementBytes) + // This composition charges model/assistant auxiliary state separately. + // Do not duplicate extraStorageBytesPerToken in this target-KV term. + kind.kvGeometry?.bytesPerToken(elementBytes: elementBytes) } private static func multiply(_ lhs: Int, _ rhs: Int) -> Int? { @@ -1209,7 +1427,9 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { public var nonBackendBytesReserved: Int { lock.lock() defer { lock.unlock() } - guard let transfers = Self.add(transientBytes - transientTargetBytes, detachedNonBackendBytes), + guard + let transfers = Self.add( + transientBytes - transientTargetBytes, detachedNonBackendBytes), let withExternal = Self.add(externalReserveBytes, transfers), var total = Self.add(withExternal, physicalFloor.overheadBytes) else { return Int.max } @@ -1234,7 +1454,7 @@ public final class AdmissionV2: CBv2StepCapacity, @unchecked Sendable { ) -> (materialized: Int, unmaterialized: Int) { lock.lock() defer { lock.unlock() } - var materialized = transientTargetBytes + var materialized = transientTargetBytes + detachedContiguousTargetBytes var unmaterialized = 0 let ids = Set(reservedTokens.keys).union(reservedExactBytes.keys) for id in ids { diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/AttentionV1.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/AttentionV1.swift index 5570dd9bae..4cee8267ec 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/AttentionV1.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/AttentionV1.swift @@ -33,8 +33,9 @@ enum CBv2AttentionV1 { /// whole chunk — the pre-2026-07 behavior), which is the kill switch if /// this is ever implicated in a numerics or latency regression. static let queryBlockSize: Int = { - guard let raw = ProcessInfo.processInfo.environment[ - "DARKBLOOM_CBV2_ATTN_QUERY_BLOCK"], + guard + let raw = ProcessInfo.processInfo.environment[ + "DARKBLOOM_CBV2_ATTN_QUERY_BLOCK"], let value = Int(raw), value >= 0 else { return 128 } return value @@ -180,14 +181,16 @@ enum CBv2AttentionV1 { /// - spanContexts: when bound, one optional context per row. Non-nil /// entries select that row's vision overlay; nil entries retain q=128 /// query-block causal/window semantics in the same rectangular call. - /// - Returns `[B, queryHeads, L, headDim]`. + /// - Returns `[B, queryHeads, L, valueHeadDim]`. static func updateAndAttend( rows: [CBv2SequenceKV], kind: CBv2LayerKind, queries: MLXArray, keys: MLXArray, values: MLXArray, scale: Float, sinks: MLXArray?, softcap: Float? = nil, spanContexts: [CBv2SpanChunkContext?]? = nil, serializeQueries: Bool = false, metadata: CBv2AttentionMetadataObservation? = nil, - packet: CBv2AttentionPacketObservation? = nil + packet: CBv2AttentionPacketObservation? = nil, + mimoV26NAXAttention: Bool = false, + mimoV26BlockBatchBudget: MiMoV26BlockBatchBudget? = nil ) -> MLXArray { let B = queries.dim(0) let L = queries.dim(2) @@ -214,13 +217,16 @@ enum CBv2AttentionV1 { return updateAndAttendRowSerialQueries( row: rows[0], kind: kind, queries: queries, keys: keys, values: values, - scale: scale, sinks: effectiveSinks, softcap: softcap) + scale: scale, sinks: effectiveSinks, softcap: softcap, + mimoV26DecodeRows: mimoV26NAXAttention && metadata == nil && packet == nil) } return updateAndAttendRow( row: rows[0], kind: kind, queries: queries, keys: keys, values: values, scale: scale, sinks: effectiveSinks, softcap: softcap, - spanContext: spanContexts?[0], metadata: metadata, packet: packet) + spanContext: spanContexts?[0], metadata: metadata, packet: packet, + mimoV26NAXAttention: mimoV26NAXAttention, + mimoV26BlockBatchBudget: mimoV26BlockBatchBudget) } if L == 1 { @@ -259,7 +265,8 @@ enum CBv2AttentionV1 { row: rows[index], kind: kind, queries: slice(queries), keys: slice(keys), values: slice(values), scale: scale, sinks: effectiveSinks, softcap: softcap, - spanContext: spanContexts?[index]) + spanContext: spanContexts?[index], mimoV26NAXAttention: mimoV26NAXAttention, + mimoV26BlockBatchBudget: mimoV26BlockBatchBudget) } } @@ -333,7 +340,8 @@ enum CBv2AttentionV1 { "CBv2AttentionV1: last-query prefill Q shape does not match the layer kind") precondition( keys.dim(1) == kind.kvHeads && values.dim(1) == kind.kvHeads - && keys.dim(3) == kind.headDim && values.dim(3) == kind.headDim, + && keys.dim(3) == kind.headDim && values.dim(3) == kind.valueHeadDim + && keys.dtype == values.dtype, "CBv2AttentionV1: last-query prefill K/V shape does not match the layer kind") let effectiveSinks = dispatchSinks( @@ -362,16 +370,29 @@ enum CBv2AttentionV1 { queries: MLXArray, keys: MLXArray, values: MLXArray, scale: Float, sinks: MLXArray?, softcap: Float?, spanContext: CBv2SpanChunkContext?, metadata: CBv2AttentionMetadataObservation? = nil, - packet: CBv2AttentionPacketObservation? = nil + packet: CBv2AttentionPacketObservation? = nil, + mimoV26NAXAttention: Bool = false, + mimoV26BlockBatchBudget: MiMoV26BlockBatchBudget? = nil ) -> MLXArray { let L = queries.dim(2) let (cachedKeys, cachedValues) = row.update(keys: keys, values: values) + let useMiMoNAX = + mimoV26NAXAttention && !kind.isBidirectional + && spanContext == nil && softcap == nil && metadata == nil && packet == nil + if useMiMoNAX, shouldBlockQueries(L), + let grouped = MiMoV26BlockBatchAttention.tryAttention( + queries: queries, keys: cachedKeys, values: cachedValues, scale: scale, + sinks: sinks, window: window(of: kind), queryBlockSize: queryBlockSize, + budget: mimoV26BlockBatchBudget, layerIndex: kind.modelLayerIndex) + { + return grouped + } if shouldBlockQueries(L) && !kind.isBidirectional { return attendQueryBlocks( queries: queries, keys: cachedKeys, values: cachedValues, newTokenCount: L, window: window(of: kind), scale: scale, sinks: sinks, softcap: softcap, blockSize: queryBlockSize, - spanContext: spanContext) + spanContext: spanContext, mimoV26NAXAttention: useMiMoNAX) } if let spanContext { return attendSpanChunk( @@ -379,19 +400,35 @@ enum CBv2AttentionV1 { L: L, kL: cachedKeys.dim(2), window: window(of: kind), context: spanContext, sinks: sinks, softcap: softcap) } + if useMiMoNAX, + let output = MiMoV26NAXAttention.tryAttention( + queries: queries, keys: cachedKeys, values: cachedValues, scale: scale, + mask: maskMode(L: L, kL: cachedKeys.dim(2), window: window(of: kind)), + sinks: sinks) + { + return output + } return attend( queries: queries, keys: cachedKeys, values: cachedValues, scale: scale, L: L, kL: cachedKeys.dim(2), window: window(of: kind), - sinks: sinks, softcap: softcap, bidirectional: kind.isBidirectional, metadata: metadata, packet: packet) + sinks: sinks, softcap: softcap, bidirectional: kind.isBidirectional, metadata: metadata, + packet: packet) } private static func updateAndAttendRowSerialQueries( row: CBv2SequenceKV, kind: CBv2LayerKind, queries: MLXArray, keys: MLXArray, values: MLXArray, - scale: Float, sinks: MLXArray?, softcap: Float? + scale: Float, sinks: MLXArray?, softcap: Float?, mimoV26DecodeRows: Bool = false ) -> MLXArray { let L = queries.dim(2) let (cachedKeys, cachedValues) = row.update(keys: keys, values: values) + if mimoV26DecodeRows, !kind.isBidirectional, window(of: kind) == nil, softcap == nil, + let output = MiMoV26DecodeRows.tryAttention( + queries: queries, + keys: cachedKeys, values: cachedValues, scale: scale, sinks: sinks) + { + return output + } return attendSerialQueries( queries: queries, keys: cachedKeys, values: cachedValues, newTokenCount: L, window: window(of: kind), scale: scale, @@ -421,6 +458,15 @@ enum CBv2AttentionV1 { spanContexts: [CBv2SpanChunkContext?]? = nil, serializeQueries: Bool = false ) -> MLXArray { + precondition( + queries.ndim == 4 && queries.dim(1) == kind.queryHeads + && queries.dim(3) == kind.headDim, + "CBv2AttentionV1: borrowed query geometry mismatch") + precondition( + sourceKind.kvHeads == kind.kvHeads && sourceKind.headDim == kind.headDim + && sourceKind.valueHeadDim == kind.valueHeadDim + && sourceKind.attention == kind.attention, + "CBv2AttentionV1: borrowed K/V geometry mismatch") let B = queries.dim(0) let L = queries.dim(2) precondition(!sourceRows.isEmpty, "CBv2AttentionV1: no source rows to borrow from") @@ -471,10 +517,10 @@ enum CBv2AttentionV1 { } else { outputs.append( borrowAndAttendRow( - sourceRow: row, sourceKind: sourceKind, - queries: queries[index ..< (index + 1)], - scale: scale, sinks: effectiveSinks, softcap: softcap, - spanContext: spanContexts?[index])) + sourceRow: row, sourceKind: sourceKind, + queries: queries[index ..< (index + 1)], + scale: scale, sinks: effectiveSinks, softcap: softcap, + spanContext: spanContexts?[index])) } } return concatenated(outputs, axis: 0) @@ -592,7 +638,7 @@ enum CBv2AttentionV1 { queries: MLXArray, keys: MLXArray, values: MLXArray, newTokenCount: Int, window: Int?, scale: Float, sinks: MLXArray?, softcap: Float?, blockSize: Int, - spanContext: CBv2SpanChunkContext? = nil + spanContext: CBv2SpanChunkContext? = nil, mimoV26NAXAttention: Bool = false ) -> MLXArray { precondition(blockSize >= 1, "CBv2AttentionV1: query block size must be >= 1") let keyCount = keys.dim(2) @@ -642,6 +688,13 @@ enum CBv2AttentionV1 { keyAbsoluteStart: kStart + visibleStart, window: window, blocks: blocks, sinks: sinks, softcap: softcap)) + } else if mimoV26NAXAttention, + let output = MiMoV26NAXAttention.tryAttention( + queries: querySlice, keys: keySlice, values: valueSlice, scale: scale, + mask: maskMode(L: count, kL: visibleEnd - visibleStart, window: window), + sinks: sinks) + { + outputs.append(output) } else { outputs.append( attend( diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift index 8fca481fd3..20819cd1db 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift @@ -206,7 +206,8 @@ public struct CBv2PositionState: @unchecked Sendable { precondition(cacheOffset >= 0, "CBv2 cache offset must be non-negative") let delta: Int32 if let state { - precondition(state.axisCount == axes, "CBv2 position axes differ across decode rows") + precondition( + state.axisCount == axes, "CBv2 position axes differ across decode rows") delta = state.decodeDeltas[0] } else { delta = 0 @@ -242,7 +243,6 @@ extension CBv2PositionedForwardingCapabilityProviding { public var supportsPositionedForwarding: Bool { true } } - // MARK: - Multimodal input (vision prefill; additive) /// Attention behavior for visual placeholder tokens. @@ -289,18 +289,23 @@ public struct CBv2MultimodalInput: @unchecked Sendable { /// Image spans in ascending `tokenOffset` order, non-overlapping, fully /// inside the prompt. Validated at submit; violations throw /// `CBv2MultimodalError`. - public var spans: [CBv2ImageSpan] - public var attention: CBv2MultimodalAttention + public var spans: [CBv2ImageSpan] { didSet { nativeMediaToken = nil } } + public var attention: CBv2MultimodalAttention { didSet { nativeMediaToken = nil } } /// Optional positions paired with these exact prompt spans. Keeping this /// on the media input lets existing provider call sites hand one atomic /// prepared object to the bridge. - public var positionState: CBv2PositionState? + public var positionState: CBv2PositionState? { didSet { nativeMediaToken = nil } } /// Embeddings provider — one array per span, same order as `spans`. - public var embeddings: () throws -> [MLXArray] + public var embeddings: () throws -> [MLXArray] { didSet { nativeMediaToken = nil } } /// Optional Qwen DeepStack provider. The outer array is ordered by /// language-layer injection point; each inner array is one embedding per /// span, in the same order as `spans`. - public var deepstackEmbeddings: (() throws -> [[MLXArray]])? + public var deepstackEmbeddings: (() throws -> [[MLXArray]])? { + didSet { nativeMediaToken = nil } + } + /// SDK-issued identity only; no public initializer/setter or array escape. + /// Every payload mutation invalidates it, including closure replacement. + public internal(set) var nativeMediaToken: CBv2PreparedNativeMediaToken? public init( spans: [CBv2ImageSpan], @@ -359,7 +364,16 @@ public struct CBv2LayerKind: Sendable, Equatable { /// A backend that cannot honor sinks MUST be statically ineligible for /// models with `hasSinks == true` (it must throw at engine build). public var hasSinks: Bool + /// Query/key width. An omitted value width follows this mutable property. public var headDim: Int + private var explicitValueHeadDim: Int? + public var valueHeadDim: Int { + get { explicitValueHeadDim ?? headDim } + set { explicitValueHeadDim = newValue } + } + public var kvGeometry: CBv2KVGeometry? { + CBv2KVGeometry(kvHeads: kvHeads, keyHeadDim: headDim, valueHeadDim: valueHeadDim) + } public var kvHeads: Int public var queryHeads: Int /// Original transformer-layer index when the CBv2 storage layout is a @@ -376,7 +390,8 @@ public struct CBv2LayerKind: Sendable, Equatable { public init( attention: Attention, sharesKVWithLayer: Int? = nil, hasSinks: Bool = false, isBidirectional: Bool = false, - headDim: Int, kvHeads: Int, queryHeads: Int, modelLayerIndex: Int? = nil, + headDim: Int, valueHeadDim: Int? = nil, kvHeads: Int, queryHeads: Int, + modelLayerIndex: Int? = nil, extraStorageBytesPerToken: Int = 0, qwen4IndexerCompressRatio: Int? = nil ) { self.attention = attention @@ -384,12 +399,23 @@ public struct CBv2LayerKind: Sendable, Equatable { self.hasSinks = hasSinks self.isBidirectional = isBidirectional self.headDim = headDim + self.explicitValueHeadDim = valueHeadDim self.kvHeads = kvHeads self.queryHeads = queryHeads self.modelLayerIndex = modelLayerIndex self.extraStorageBytesPerToken = max(0, extraStorageBytesPerToken) self.qwen4IndexerCompressRatio = qwen4IndexerCompressRatio } + + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.attention == rhs.attention && lhs.sharesKVWithLayer == rhs.sharesKVWithLayer + && lhs.isBidirectional == rhs.isBidirectional && lhs.hasSinks == rhs.hasSinks + && lhs.headDim == rhs.headDim && lhs.valueHeadDim == rhs.valueHeadDim + && lhs.kvHeads == rhs.kvHeads && lhs.queryHeads == rhs.queryHeads + && lhs.modelLayerIndex == rhs.modelLayerIndex + && lhs.extraStorageBytesPerToken == rhs.extraStorageBytesPerToken + && lhs.qwen4IndexerCompressRatio == rhs.qwen4IndexerCompressRatio + } } /// Prefix snapshots are reusable only when prefill visibility is independent @@ -414,7 +440,8 @@ public protocol CBv2SequenceKV: AnyObject { /// windowed caches; == absoluteOffset for full caches). var retainedCount: Int { get } /// Append K/V for `n` new tokens and return (keys, values) views suitable - /// for attention: shapes [1, kvHeads, retainedAfterUpdate, headDim], in + /// for attention: K [1, kvHeads, retainedAfterUpdate, headDim] and V + /// [1, kvHeads, retainedAfterUpdate, valueHeadDim], in /// temporal order (oldest → newest). Windowed impls evict by absolute /// position and keep the RECENT end. func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) @@ -598,10 +625,11 @@ extension CBv2KVBackend { let capability = CBv2PrefixReuseCapability.derive( layerKinds: layerKinds, backend: prefixReuseBackend) - guard let plan = capability.compatibilityPlan( - adoptedOffset: adoptedOffset, - exactStagedFullKVBytes: exactBytes, - maximumSequenceLength: maxLength) + guard + let plan = capability.compatibilityPlan( + adoptedOffset: adoptedOffset, + exactStagedFullKVBytes: exactBytes, + maximumSequenceLength: maxLength) else { throw CBv2KVError.backendIneligible( reason: @@ -659,10 +687,10 @@ public protocol CBv2AttendingLayerCache: AnyObject { /// a KV-shared cache owns no rows, so its own `positionOffsets` is empty. var positionOffsets: MLXArray { get } /// Update per-row KV with this step's K/V and compute attention. - /// - queries/keys/values: [B, heads, L, headDim]; L == 1 for decode, - /// B == 1 for prefill chunks. + /// - queries/keys: [B, heads, L, headDim]; values use valueHeadDim. + /// L == 1 for decode, B == 1 for prefill chunks. /// - sinks: per-head learned sink logits, or nil. - /// - Returns attention output [B, queryHeads, L, headDim]. + /// - Returns attention output [B, queryHeads, L, valueHeadDim]. /// Implementations MUST be numerically pinned: one attention path per /// (model, phase), never switching mask representation across steps. func updateAndAttend( @@ -681,14 +709,14 @@ public protocol CBv2AttendingLayerCache: AnyObject { public enum CBv2RequestStatus: Sendable, Equatable { case waiting - case running // numComputedTokens < numTokens ⇒ still prefilling + case running // numComputedTokens < numTokens ⇒ still prefilling case preempted case finished(CBv2FinishReason) } public enum CBv2FinishReason: Sendable, Equatable { - case stop // stop token or stop string - case length // maxTokens or context limit + case stop // stop token or stop string + case length // maxTokens or context limit case cancelled case error(String) /// A typed platform/engine terminal: a monotonic deadline lease @@ -752,6 +780,11 @@ public struct CBv2SchedulerConfig: Sendable { /// to 16,384 (= 2,048 tokens x top-8); larger stripes stay correct but /// fall back off the tile route for MoE models with that geometry. public var soloPrefillStripeTokens: Int? + /// Optional ceiling for ANY actual multimodal request, including causal + /// media with no bidirectional blocks. Nil preserves existing semantics. + /// Automatic MiMo widening captures the previous media stripe here only + /// after its genuine wider budget installs; other callers stay unchanged. + public var soloPrefillStripeMediaCeiling: Int? /// Mean-TTFT prefill serialization (opt-in; nil = unlimited). Caps how /// many RUNNING rows may be mid-prefill at once. Measured basis: with /// the unlimited interleave, every row in a 4x8K burst reaches its @@ -784,6 +817,7 @@ public struct CBv2SchedulerConfig: Sendable { public init( maxConcurrentRequests: Int = 4, maxBatchedTokensPerStep: Int = 2048, prefillChunkSize: Int = 512, soloPrefillStripeTokens: Int? = nil, + soloPrefillStripeMediaCeiling: Int? = nil, maxConcurrentPartialPrefills: Int? = nil, mixedStepPrefillTokenCap: Int? = nil, maxWaiting: Int = 64, @@ -793,11 +827,25 @@ public struct CBv2SchedulerConfig: Sendable { self.maxBatchedTokensPerStep = maxBatchedTokensPerStep self.prefillChunkSize = prefillChunkSize self.soloPrefillStripeTokens = soloPrefillStripeTokens + self.soloPrefillStripeMediaCeiling = soloPrefillStripeMediaCeiling self.maxConcurrentPartialPrefills = maxConcurrentPartialPrefills self.mixedStepPrefillTokenCap = mixedStepPrefillTokenCap self.maxWaiting = maxWaiting self.enablePrefixCache = enablePrefixCache } + + /// Shared by real scheduling and first-token work projection. Block lists + /// encode attention visibility, not whether the request contains media. + func resolvedSoloPrefillStripeTokens(isMultimodal: Bool) -> Int? { + guard let configured = soloPrefillStripeTokens else { return nil } + let selected: Int + if isMultimodal, let ceiling = soloPrefillStripeMediaCeiling { + selected = min(configured, max(0, ceiling)) + } else { + selected = configured + } + return selected > prefillChunkSize ? selected : nil + } } // MARK: - Engine events (provider/consumer surface) @@ -1006,6 +1054,10 @@ public struct CBv2CapacitySnapshot: Sendable { public var activeRequests: Int public var waitingRequests: Int public var kvBytesInUse: Int + /// True means assistant in-use bytes include only a proven retained subset + /// while a lazy generation awaits measurement. The full conservative + /// obligation remains in kvBytesReserved; this is never reclaim credit. + public var hasUnmeasuredAssistantResidency: Bool /// Runtime admission ceiling, including request KV and auxiliary state. public var kvBytesCapacity: Int /// Backend ceiling. Contiguous and segmented paged grants resize; the @@ -1035,11 +1087,13 @@ public struct CBv2CapacitySnapshot: Sendable { activeRequests: Int, waitingRequests: Int, kvBytesInUse: Int, kvBytesCapacity: Int, kvBytesBackendCapacity: Int = 0, kvBytesReserved: Int = 0, activeTokens: Int, stepsExecuted: Int = 0, stepWallNanosTotal: UInt64 = 0, decodeRowsTotal: UInt64 = 0, - pagedStorage: PagedKVStorageSnapshot? = nil + pagedStorage: PagedKVStorageSnapshot? = nil, + hasUnmeasuredAssistantResidency: Bool = false ) { self.activeRequests = activeRequests self.waitingRequests = waitingRequests self.kvBytesInUse = kvBytesInUse + self.hasUnmeasuredAssistantResidency = hasUnmeasuredAssistantResidency self.kvBytesCapacity = kvBytesCapacity self.kvBytesBackendCapacity = kvBytesBackendCapacity self.kvBytesReserved = kvBytesReserved @@ -1524,3 +1578,10 @@ extension CBv2Engine { engine: String(describing: type(of: self))) } } + +// SDK-package-only optional optimization: the actual native MiMo resource +// producer proves the backend/cache association. No public caller assertion. +package protocol MiMoV26BlockBatchAllocatingModel: AnyObject { + var cbv2MiMoBlockBatchLayerCount: Int? { get } + func cbv2TryInstallBlockBatchBudget(_ budget: MiMoV26BlockBatchBudget) -> Bool +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2NativeCompletePrefixWork.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2NativeCompletePrefixWork.swift new file mode 100644 index 0000000000..f1773761f1 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2NativeCompletePrefixWork.swift @@ -0,0 +1,384 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX + +/// Package producer checks only sealed source/session/generation metadata. +/// Never a public caller assertion, array read, evaluator or user callback. +package protocol CBv2NativeCompletePrefixBindingValidating: AnyObject { + func validateNativeCompletePrefixBinding() throws +} + +enum CBv2NativeCompletePrefixPurpose: Equatable { case importing, publication, discard } + +/// A real operation held by the engine's existing native loan. Roots may be +/// registered from the serial provider/capture queue; they never enter the +/// engine-queue-only native root dictionary. No deinit refund is permitted. +final class CBv2NativeCompletePrefixWork: @unchecked Sendable { + let id = UUID() + let engineID: UUID + let executionContractID: UUID + let codecIdentity: CBv2CompleteCheckpointIdentity + let purpose: CBv2NativeCompletePrefixPurpose + private weak var codecOwner: CBv2CompleteCheckpointCodec? + private weak var storeOwner: (any CBv2NativeCompletePrefixCache)? + private var request: CBv2Request? + private let tracking: CBv2NativeShutdownState + private let queue: DispatchQueue + private let completionQueue: DispatchQueue + private let wake: @Sendable () -> Void + private let failure: @Sendable () -> Void + private var validateBinding: (@Sendable () throws -> Void)? + private let lock = NSLock() + private var loan: UUID? + private var streams: [MLX.Stream] + private var arrays: [MLXArray] = [] + private var owners: [AnyObject] = [] + private var retirement: (() throws -> Void)? + private var finishing = false + private var finished = false + private var failed = false + private var promotionFenceCompleted = false + private let beforeFence: ((MLX.Stream) throws -> Void)? + + init( + tracking: CBv2NativeShutdownState, codec: CBv2CompleteCheckpointCodec, + store: any CBv2NativeCompletePrefixCache, request: CBv2Request?, + purpose: CBv2NativeCompletePrefixPurpose, + streams: [MLX.Stream], duringDrain: Bool, queue: DispatchQueue, + completionQueue: DispatchQueue, wake: @escaping @Sendable () -> Void, + failure: @escaping @Sendable () -> Void, + validateBinding: @escaping @Sendable () throws -> Void + ) throws { + guard let contractID = tracking.contractID else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + self.tracking = tracking + self.codecOwner = codec + self.storeOwner = store + self.request = request + codecIdentity = codec.identity + self.purpose = purpose + owners = [codec, store] + engineID = tracking.engineID + executionContractID = contractID + self.streams = [] + for stream in streams where !self.streams.contains(stream) { self.streams.append(stream) } + self.queue = queue + self.completionQueue = completionQueue + self.wake = wake + self.failure = failure + self.validateBinding = validateBinding + beforeFence = tracking.beforeFenceForTesting + // All stored properties exist before self is loan-owned. + loan = try tracking.beginLoan(owner: self, duringDrain: duringDrain) + } + + /// Root's import plan/stage must check this before touching/consuming its + /// private native state; reused request IDs alone are not an authority. + func validate( + store: any CBv2CompletePrefixCache, codec: CBv2CompleteCheckpointCodec, + request: CBv2Request, engineID: UUID + ) throws { + try tracking.requireWork() + guard let validate = lock.withLock({ validateBinding }) else { + throw CBv2NativeShutdownError.operationClosed + } + try validate() + let state = lock.withLock { (self.request, finishing || finished || failed) } + guard self.storeOwner === store, self.codecOwner === codec, self.engineID == engineID, + self.executionContractID == tracking.contractID, + let original = state.0, original.id == request.id, + original.prefixCacheReceiptID == request.prefixCacheReceiptID, + original.promptTokens == request.promptTokens, + original.checkpointCacheSalt == request.checkpointCacheSalt, + original.maxTokens == request.maxTokens, + original.multimodal == nil, request.multimodal == nil, + original.positionState == nil, request.positionState == nil, + !state.1 + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + } + + func captureCurrentStreams() throws { + try tracking.requireWork() + do { + guard let validate = lock.withLock({ validateBinding }) else { + throw CBv2NativeShutdownError.operationClosed + } + try validate() + } catch { + requiredCompletionFailed() + throw error + } + let actual = [StreamOrDevice.cpu.stream, StreamOrDevice.default.stream] + let invalid = lock.withLock { () -> Bool in + for stream in actual where !streams.contains(stream) { streams.append(stream) } + promotionFenceCompleted = false + return finishing || finished || failed + } + if invalid { + requiredCompletionFailed() + throw CBv2NativeShutdownError.operationClosed + } + try tracking.requireWork() + } + + /// Keep late returned actual roots even if a concurrent watchdog won. + /// The caller registers each fresh array/reservation BEFORE evaluation. + func retain(arrays incoming: [MLXArray] = [], owners incomingOwners: [AnyObject] = []) throws { + let invalid = lock.withLock { () -> Bool in + for array in incoming where !arrays.contains(where: { $0 === array }) { + arrays.append(array) + } + for owner in incomingOwners where !owners.contains(where: { $0 === owner }) { + owners.append(owner) + } + promotionFenceCompleted = false + return finishing || finished || failed + } + if invalid { + requiredCompletionFailed() + throw CBv2NativeShutdownError.operationClosed + } + try tracking.requireWork() + do { + guard let validate = lock.withLock({ validateBinding }) else { + throw CBv2NativeShutdownError.operationClosed + } + try validate() + } catch { + requiredCompletionFailed() + throw error + } + } + + /// Called only before the engine enters its metadata commit. Executes the + /// real required stream fence without ending the operation or dropping C. + func fenceForProtectedPromotion() throws { + try tracking.requireWork() + guard !lock.withLock({ finishing || finished || failed }) else { + throw CBv2NativeShutdownError.operationClosed + } + let captured = lock.withLock { streams } + var firstError: Error? + for stream in captured { + do { + try beforeFence?(stream) + try withError { errors in + stream.synchronize() + try errors.check() + } + } catch { if firstError == nil { firstError = error } } + } + if let firstError { + requiredCompletionFailed() + throw firstError + } + try tracking.requireWork() + try lock.withLock { + guard !failed, !finishing, !finished else { + throw CBv2NativeShutdownError.operationClosed + } + promotionFenceCompleted = true + } + } + + var hasProtectedPromotionCompletion: Bool { + lock.withLock { promotionFenceCompleted && !failed && !finishing && !finished } + } + + /// Derived from the real sealed codec/binding, never a caller flag or + /// manifest layout string. Contiguous/foreign work keeps refusing pages. + func requireNativePagedSources() throws { + try tracking.requireWork() + guard purpose == .publication, let codec = codecOwner, codec.isNativePagedHistorical, + let store = storeOwner, let binding = codec.nativePagedBinding + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + guard + binding.validatesCompletePrefixCodec( + identity: codec.identity, + layerKinds: codec.layerKinds, layerDTypes: codec.kvDTypes, + assistant: codec.assistant.map { $0 as AnyObject }), + store.identity == codecIdentity + else { + requiredCompletionFailed() + throw CBv2NativeShutdownError.unsupportedConsumer + } + } + + /// The real imported assistant was evaluated/fenced off to the side. + /// This performs only its non-waiting ownership measurement under the + /// existing first-winner commit; it does not adopt a request or grant C. + func commitPreparedAssistant( + _ assistant: any CBv2NativeMTPCompletionSplitting, + state: any CBv2MTPRequestState + ) throws { + guard purpose == .importing, hasProtectedPromotionCompletion, + codecOwner?.assistant.map({ $0 as AnyObject }) === assistant as AnyObject + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + guard + try tracking.commitIfHealthyThrowing({ + try assistant.commitRequestStateNativeCompletion(state) + }) + else { throw CBv2NativeShutdownError.operationClosed } + } + + /// Keep export scratch bounded to the live readback segment. Only the + /// publication owner can use this, after copying bytes out of native + /// storage. Executes a real fence; no caller-supplied completion boolean. + /// Donor owners and the WHOLE-operation reservation/loan stay held. + func retireReadbackTemporaries(_ temporary: [MLXArray]) throws { + guard purpose == .publication else { throw CBv2NativeShutdownError.unsupportedConsumer } + try fenceForProtectedPromotion() + guard + tracking.commitIfHealthy({ + lock.withLock { + arrays.removeAll { array in temporary.contains(where: { $0 === array }) } + promotionFenceCompleted = false + } + }) + else { throw CBv2NativeShutdownError.operationClosed } + } + + func requiredCompletionFailed() { + lock.withLock { failed = true } + if tracking.fail(.nativeWorkFailed) { failure() } + } + + /// Called after the producer has severed/handed off its consumer aliases. + /// Returns after QUEUING, not after completion. Release the associated + /// reservation only inside retirement, never immediately after this call. + /// A first failure retains roots, loan and retirement closure permanently. + @discardableResult + func finishAfterDroppingConsumers(retirement: @escaping () throws -> Void = {}) -> Bool { + let accepted = lock.withLock { () -> Bool in + guard !finishing, !finished, !failed else { return false } + finishing = true + self.retirement = retirement + return true + } + guard accepted else { return false } + queue.async { [self] in + guard tracking.mayExecute else { return } + let captured = lock.withLock { streams } + var firstError: Error? + for stream in captured { + do { + try beforeFence?(stream) + try withError { error in + stream.synchronize() + try error.check() + } + } catch { if firstError == nil { firstError = error } } + } + if firstError != nil { + requiredCompletionFailed() + return + } + // The completion queue is the actual engine queue. No fence or + // provider/accounting callback is performed under the commit lock. + completionQueue.async { [self] in + var detached: + ([MLXArray], [AnyObject], (() throws -> Void)?, (@Sendable () throws -> Void)?)? + guard + tracking.commitIfHealthy({ + lock.withLock { + guard !failed, !finished else { return } + detached = (arrays, owners, self.retirement, self.validateBinding) + arrays = [] + owners = [] + self.retirement = nil + self.validateBinding = nil + request = nil + finished = true + } + tracking.captureCompletedPrefixStreams(captured) + }), var released = detached + else { return } + // Move the tuple before clearing its arrays: a second COW + // alias must not survive the retirement callback/endLoan/wake. + detached = nil + // Explicit order: native aliases, owner aliases, then credit. + released.0.removeAll() + released.1.removeAll() + released.3 = nil + do { try released.2?() } catch { + // A failed accounting/retirement callback retains its real + // captures too; no successful native receipt may follow. + lock.withLock { + self.retirement = released.2 + failed = true + } + if tracking.fail(.nativeWorkFailed) { failure() } + return + } + released.2 = nil + if let loan { tracking.endLoan(loan) } + wake() + } + } + return true + } + + var debugRetainedArrayCount: Int { lock.withLock { arrays.count } } + var debugIsFailed: Bool { lock.withLock { failed } } +} + +/// One completed-group donor. Kept in the native engine until the actual +/// publication/drop consumer closes, not merely until a token terminal. +final class CBv2NativeCompletePrefixRetiredRows: @unchecked Sendable { + let id = UUID() + let requestID: CBv2RequestID + let intent: CBv2DonationIntent? + private(set) var state: [CBv2SequenceKV?] + private var reservation: CBv2CheckpointReservation? + private var completion: (() -> Void)? + var started = false // engine queue only + init( + requestID: CBv2RequestID, state: [CBv2SequenceKV?], intent: CBv2DonationIntent?, + reservation: CBv2CheckpointReservation?, completion: @escaping () -> Void + ) { + self.requestID = requestID + self.state = state + self.intent = intent + self.reservation = reservation + self.completion = completion + } + func releaseRowsAndReservation(backend: CBv2KVBackend) { + if !state.isEmpty { backend.release(state) } + state.removeAll() + reservation?.release() + reservation = nil + intent?.retiredReservation?.release() + } + func complete() { + let callback = completion + completion = nil + callback?() + } +} + +/// An existing native loan owns both the exact store and its real async close. +/// The observer joins the close task's value before notifying the engine. +/// Neither task grants completion from a timeout or scalar counter. +final class CBv2NativeCompletePrefixStoreCloseJoin: @unchecked Sendable { + private let store: any CBv2NativeCompletePrefixCache + private var operation: Task? + private var observer: Task? + init(store: any CBv2NativeCompletePrefixCache) { self.store = store } + func start(completion: @escaping @Sendable () -> Void) { + precondition(operation == nil) + let store = self.store + let task = Task { await store.closeAndWait() } + operation = task + observer = Task { + await task.value + completion() + } + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2NativeShutdownOutcome.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2NativeShutdownOutcome.swift new file mode 100644 index 0000000000..040837e73c --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2NativeShutdownOutcome.swift @@ -0,0 +1,732 @@ +import Foundation +import MLX + +/// Additive: no requirement is added to generic CBv2Engine implementations. +public protocol CBv2NativeWorkShutdownReporting: Sendable { + var nativeShutdownEngineID: UUID { get } + var nativeShutdownExecutionContractID: UUID? { get } + func shutdownReportingNativeCompletion() async -> CBv2NativeShutdownOutcome +} + +public struct CBv2NativeShutdownReceipt: Sendable, Equatable { + public let engineID: UUID + public let generation: UInt64 + public let executionContractID: UUID + public let capturedStreamCount: Int + // No public initializer. This proves completion, NOT physical deallocation + // or materialized-memory credit. Only the SDK barrier may issue it. + init(engineID: UUID, generation: UInt64, executionContractID: UUID, capturedStreamCount: Int) { + self.engineID = engineID + self.generation = generation + self.executionContractID = executionContractID + self.capturedStreamCount = capturedStreamCount + } +} + +public struct CBv2NativeShutdownFault: Sendable, Equatable { + public enum Reason: String, Sendable { + case notTracked, unsupportedExecutionContract, shutdownTimedOut, stepWatchdog + case capturedFenceFailed, nativeWorkFailed + } + public let engineID: UUID + public let generation: UInt64 + public let reason: Reason + init(engineID: UUID, generation: UInt64, reason: Reason) { + self.engineID = engineID + self.generation = generation + self.reason = reason + } +} + +public enum CBv2NativeShutdownOutcome: Sendable, Equatable { + case quiescent(CBv2NativeShutdownReceipt) + case incomplete(CBv2NativeShutdownFault) +} + +/// Minted only by the SDK's protected strict-loaded MiMo resource bundle. The +/// package producer must authorize the exact immutable, materialized loaded +/// owner and create the real backend/cache bank together. Not a generic marker +/// or a caller assertion about an arbitrary model/private stream. +public struct CBv2NativeExecutionContract: Sendable { + public let id: UUID + public let constructionOwnerID: UUID + public let constructionEpoch: UInt64 + public let profile: String + /// Bound to the same one-use model/cache/assistant ticket. This declares + /// the permitted graph strategy, not a numerical certification. + public let mtpVerificationMode: CBv2MTPVerificationMode + public var supportsDecodedVisualMedia: Bool { + profile == "mimo_decoded_visual_contiguous_default_and_cpu_v1" + || profile == "mimo_complete_text_prefix_decoded_visual_contiguous_default_and_cpu_v1" + } + public var supportsDecodedAudioMedia: Bool { + profile == "mimo_decoded_audio_contiguous_default_and_cpu_v1" + || profile == "mimo_complete_text_prefix_decoded_audio_contiguous_default_and_cpu_v1" + } + public var supportsManagedDecodedMedia: Bool { + supportsDecodedVisualMedia || supportsDecodedAudioMedia + } + public let audioSidecarSessionID: UUID? + public let audioSidecarSourceIdentity: String? + public let audioSidecarGeneration: UUID? + public let supportsNativeCompletePrefix: Bool + public let supportsNativePagedTarget: Bool + /// Additional permission of the same exact page-bank ticket. It does not + /// authorize rectangular verification or managed media. Joint prefix + /// permission is separately validated against the same actual tuple. + public var supportsNativePagedSerialMTP: Bool { + supportsNativePagedTarget + && (profile == "mimo_text_native_gathered_paged_serial_mtp_default_and_cpu_v1" + || (supportsNativeCompletePrefix + && profile == "mimo_complete_text_prefix_native_gathered_paged_serial_mtp_v1")) + } + private let prefixIdentity: CBv2CompleteCheckpointIdentity? + private let prefixAssistantCodecID: String? + private let ticket: Ticket + private final class Ticket: @unchecked Sendable { + let lock = NSLock() + weak var model: AnyObject? + weak var backend: AnyObject? + weak var cacheProvider: AnyObject? + weak var assistant: AnyObject? + weak var mediaProcessor: AnyObject? + weak var loadedOwner: AnyObject? + weak var audioOwner: AnyObject? + weak var prefixStore: AnyObject? + weak var prefixValidator: (any CBv2NativeCompletePrefixBindingValidating)? + weak var prefixProcessOwner: AnyObject? + let hasPrefixProcessOwner: Bool + weak var pagedBinding: CBv2NativePagedModelBinding? + weak var pagedProcessOwner: AnyObject? + let hasAssistant: Bool + var consumed = false + init( + model: AnyObject, backend: AnyObject, cacheProvider: AnyObject, assistant: AnyObject?, + mediaProcessor: AnyObject?, loadedOwner: AnyObject?, audioOwner: AnyObject?, + prefixStore: AnyObject?, + prefixValidator: (any CBv2NativeCompletePrefixBindingValidating)?, + prefixProcessOwner: AnyObject?, pagedBinding: CBv2NativePagedModelBinding?, + pagedProcessOwner: AnyObject? + ) { + self.model = model + self.backend = backend + self.cacheProvider = cacheProvider + self.assistant = assistant + hasAssistant = assistant != nil + self.mediaProcessor = mediaProcessor + self.loadedOwner = loadedOwner + self.audioOwner = audioOwner + self.prefixStore = prefixStore + self.prefixValidator = prefixValidator + self.prefixProcessOwner = prefixProcessOwner + hasPrefixProcessOwner = prefixProcessOwner != nil + self.pagedBinding = pagedBinding + self.pagedProcessOwner = pagedProcessOwner + } + } + package init( + model: AnyObject, backend: AnyObject, cacheProvider: AnyObject, + assistant: AnyObject?, construction: NativeConstructionScope, + mediaProcessor: AnyObject? = nil, loadedOwner: AnyObject? = nil, + audioOwner: AnyObject? = nil, audioSessionID: UUID? = nil, + audioSourceIdentity: String? = nil, audioGeneration: UUID? = nil, + mtpVerificationMode: CBv2MTPVerificationMode = .serialTarget, + completePrefixCache: (any CBv2NativeCompletePrefixCache)? = nil, + completePrefixValidator: (any CBv2NativeCompletePrefixBindingValidating)? = nil, + prefixProcessMemoryOwner: (any CBv2ProcessMemoryOwner)? = nil, + nativePagedBinding: CBv2NativePagedModelBinding? = nil, + nativePagedProcessMemoryOwner: (any CBv2ProcessMemoryOwner)? = nil + ) throws { + let origin = construction.snapshot + guard case .active = origin.disposition, origin.epoch > 0 else { + throw NativeConstructionError.inactiveScope + } + guard mtpVerificationMode == .serialTarget || mtpVerificationMode == .rectangular else { + throw NativeConstructionError.inactiveScope + } + if mtpVerificationMode == .rectangular { + // Only the protected package producer may issue this permission. + // Match real loaded target identities and actual cache capability; + // neither a requested enum nor a profile string is sufficient. + guard let target = model as? any CBv2MTPSteppableModel, + target.supportsRequestStatefulMTP, + let targetID = target.mtpTargetIdentity, + let drafter = assistant as? any CBv2MTPRequestStatefulDrafter, + assistant is any CBv2NativeMTPCompletionSplitting, + drafter.mtpTargetIdentity == targetID, + drafter.requiredVerificationMode == .rectangular, + drafter.maximumDraftTokens == 3, drafter.maximumSpeculativeBatch == 1, + let bank = cacheProvider as? any CBv2LayerCacheProvider, + bank.supportsMTPRectangularVerification + else { + throw NativeConstructionError.inactiveScope + } + } + self.mtpVerificationMode = mtpVerificationMode + constructionOwnerID = origin.ownerID + constructionEpoch = origin.epoch + id = UUID() + let hasPrefix = completePrefixCache != nil + let hasNativePaged = nativePagedBinding != nil + guard hasNativePaged == (nativePagedProcessMemoryOwner != nil) else { + throw NativeConstructionError.inactiveScope + } + if let nativePagedBinding { + guard mediaProcessor == nil, audioOwner == nil, + loadedOwner != nil, mtpVerificationMode == .serialTarget, + let paged = backend as? PagedKVBackend, + paged.nativeModelBinding === nativePagedBinding + else { + throw NativeConstructionError.inactiveScope + } + try nativePagedBinding.validate( + model: model, backend: backend, bank: cacheProvider, assistant: assistant, + processMemoryOwner: nativePagedProcessMemoryOwner, + constructionOwnerID: origin.ownerID, constructionEpoch: origin.epoch) + if let completePrefixCache { + guard prefixProcessMemoryOwner === nativePagedProcessMemoryOwner else { + throw NativeConstructionError.inactiveScope + } + try nativePagedBinding.validateCompletePrefix( + store: completePrefixCache, + identity: completePrefixCache.identity, assistant: assistant, + processMemoryOwner: prefixProcessMemoryOwner) + } else if nativePagedBinding.completePrefixIdentity != nil { + throw NativeConstructionError.inactiveScope + } + } + supportsNativePagedTarget = hasNativePaged + guard hasPrefix == (completePrefixValidator != nil), + hasPrefix || prefixProcessMemoryOwner == nil + else { + throw NativeConstructionError.inactiveScope + } + if let completePrefixCache, let completePrefixValidator { + // Prefix authority is bound to the actual store/validator/owner. + // Joint media authority is issued by the protected loaded producer, + // never by upgrading a live ticket or copying a profile string. + guard loadedOwner != nil, + prefixProcessMemoryOwner != nil, + completePrefixCache.identity.isValid, + let target = model as? any CBv2HistoricalAttentionCheckpointProviding, + target.cbv2SupportsHistoricalAttentionCheckpoint, + let typed = model as? any CBv2CompleteCheckpointKVTypeProviding, + let types = typed.cbv2CompleteCheckpointKVDTypes, !types.isEmpty, + assistant == nil || assistant is any CBv2HistoricalMTPPrefixCheckpointCoding + else { + throw NativeConstructionError.inactiveScope + } + if mediaProcessor != nil { + guard let mediaModel = model as? any CBv2MultimodalSteppableModel, + mediaModel.supportsMultimodalPrefill(attention: .causal), + let mediaBank = cacheProvider + as? any CBv2MultimodalAttentionCapabilityProviding, + mediaBank.supportsMultimodalPrefill(attention: .causal) + else { + throw NativeConstructionError.inactiveScope + } + } + try completePrefixValidator.validateNativeCompletePrefixBinding() + } + supportsNativeCompletePrefix = hasPrefix + prefixIdentity = completePrefixCache?.identity + prefixAssistantCodecID = + (assistant as? any CBv2MTPPrefixCheckpointCoding)?.prefixCheckpointCodecID + guard hasPrefix || hasNativePaged || (mediaProcessor == nil) == (loadedOwner == nil) else { + throw NativeConstructionError.inactiveScope + } + if let loadedOwner { try construction.requireImmutableLoadedOwner(loadedOwner) } + let hasAudio = audioOwner != nil + guard hasAudio == (audioSessionID != nil), hasAudio == (audioSourceIdentity != nil), + hasAudio == (audioGeneration != nil), !hasAudio || mediaProcessor != nil + else { + throw NativeConstructionError.inactiveScope + } + if let audioOwner, let source = audioSourceIdentity { + try construction.requireImmutableLoadedOwner(audioOwner) + guard source.utf8.count == 64, + source.utf8.allSatisfy({ (48 ... 57).contains($0) || (97 ... 102).contains($0) }) + else { + throw NativeConstructionError.inactiveScope + } + } + audioSidecarSessionID = audioSessionID + audioSidecarSourceIdentity = audioSourceIdentity + audioSidecarGeneration = audioGeneration + if hasNativePaged { + if hasPrefix { + profile = + assistant == nil + ? "mimo_complete_text_prefix_native_gathered_paged_v1" + : "mimo_complete_text_prefix_native_gathered_paged_serial_mtp_v1" + } else { + profile = + assistant == nil + ? "mimo_text_native_gathered_paged_default_and_cpu_v1" + : "mimo_text_native_gathered_paged_serial_mtp_default_and_cpu_v1" + } + } else if hasPrefix { + profile = + hasAudio + ? "mimo_complete_text_prefix_decoded_audio_contiguous_default_and_cpu_v1" + : mediaProcessor != nil + ? "mimo_complete_text_prefix_decoded_visual_contiguous_default_and_cpu_v1" + : "mimo_complete_text_prefix_contiguous_default_and_cpu_v1" + } else { + profile = + hasAudio + ? "mimo_decoded_audio_contiguous_default_and_cpu_v1" + : (mediaProcessor == nil + ? "mimo_text_contiguous_default_and_cpu_v1" + : "mimo_decoded_visual_contiguous_default_and_cpu_v1") + } + ticket = Ticket( + model: model, backend: backend, cacheProvider: cacheProvider, assistant: assistant, + mediaProcessor: mediaProcessor, loadedOwner: loadedOwner, audioOwner: audioOwner, + prefixStore: completePrefixCache, prefixValidator: completePrefixValidator, + prefixProcessOwner: prefixProcessMemoryOwner, pagedBinding: nativePagedBinding, + pagedProcessOwner: nativePagedProcessMemoryOwner) + } + func matchesMedia(processor: AnyObject, owner: AnyObject) -> Bool { + ticket.lock.withLock { + supportsManagedDecodedMedia && ticket.consumed && ticket.mediaProcessor === processor + && ticket.loadedOwner === owner + && (!supportsDecodedAudioMedia || ticket.audioOwner != nil) + } + } + func consume( + model: AnyObject, backend: AnyObject, cacheProvider: AnyObject, assistant: AnyObject?, + mtpVerificationMode: CBv2MTPVerificationMode = .serialTarget, + completePrefixCache: (any CBv2CompletePrefixCache)? = nil, + processMemoryOwner: (any CBv2ProcessMemoryOwner)? = nil + ) -> Bool { + ticket.lock.withLock { + // Weak liveness prevents a stale numeric ObjectIdentifier from + // authorizing a different object after address reuse; no raw native + // owner is transported or retained by this Sendable ticket. + guard !ticket.consumed, self.mtpVerificationMode == mtpVerificationMode, + ticket.model === model, + ticket.backend === backend, ticket.cacheProvider === cacheProvider, + ticket.hasAssistant == (assistant != nil), ticket.assistant === assistant, + !supportsDecodedAudioMedia || ticket.audioOwner != nil + else { return false } + if mtpVerificationMode == .rectangular { + guard let target = model as? any CBv2MTPSteppableModel, + target.supportsRequestStatefulMTP, + let targetID = target.mtpTargetIdentity, + let drafter = assistant as? any CBv2MTPRequestStatefulDrafter, + drafter.mtpTargetIdentity == targetID, + drafter.requiredVerificationMode == .rectangular, + (cacheProvider as? any CBv2LayerCacheProvider)? + .supportsMTPRectangularVerification == true + else { return false } + } + if supportsNativeCompletePrefix { + guard let completePrefixCache, + ticket.prefixStore === completePrefixCache, + prefixIdentity == completePrefixCache.identity, + ticket.loadedOwner != nil, + ticket.hasPrefixProcessOwner == (processMemoryOwner != nil), + ticket.prefixProcessOwner === processMemoryOwner, + let validator = ticket.prefixValidator + else { return false } + do { try validator.validateNativeCompletePrefixBinding() } catch { return false } + } + if supportsNativePagedTarget { + guard completePrefixCache == nil || supportsNativeCompletePrefix, + ticket.loadedOwner != nil, + let binding = ticket.pagedBinding, ticket.pagedProcessOwner != nil, + ticket.pagedProcessOwner === processMemoryOwner + else { return false } + do { + try binding.validate( + model: model, backend: backend, bank: cacheProvider, assistant: assistant, + processMemoryOwner: processMemoryOwner, + constructionOwnerID: constructionOwnerID, + constructionEpoch: constructionEpoch) + if let completePrefixCache { + try binding.validateCompletePrefix( + store: completePrefixCache, + identity: completePrefixCache.identity, assistant: assistant, + processMemoryOwner: processMemoryOwner) + } + } catch { return false } + } else if !supportsNativeCompletePrefix + && (completePrefixCache != nil || processMemoryOwner != nil) + { + return false + } + ticket.consumed = true + return true + } + } + + /// Recheck immutable store/codec/loaded-generation binding when importing + /// or publishing, not merely once at construction. + func validateCompletePrefix( + store: any CBv2CompletePrefixCache, + codec: CBv2CompleteCheckpointCodec + ) throws { + try ticket.lock.withLock { + guard supportsNativeCompletePrefix, ticket.consumed, + ticket.prefixStore === store, prefixIdentity == store.identity, + codec.identity == store.identity, + codec.pagedConfig == nil + || (supportsNativePagedTarget && codec.isNativePagedHistorical), + codec.recurrentSpec == nil, ticket.loadedOwner != nil, + ticket.prefixProcessOwner != nil, + let validator = ticket.prefixValidator, + let typed = ticket.model as? any CBv2CompleteCheckpointKVTypeProviding, + typed.cbv2CompleteCheckpointKVDTypes == codec.kvDTypes, + ticket.assistant === codec.assistant.map({ $0 as AnyObject }), + prefixAssistantCodecID == codec.assistant?.prefixCheckpointCodecID + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try validator.validateNativeCompletePrefixBinding() + if supportsNativePagedTarget { + guard let binding = ticket.pagedBinding, codec.nativePagedBinding === binding, + ticket.prefixProcessOwner === ticket.pagedProcessOwner + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try binding.validateCompletePrefix( + store: store, identity: codec.identity, + assistant: codec.assistant.map { $0 as AnyObject }, + processMemoryOwner: ticket.pagedProcessOwner as? any CBv2ProcessMemoryOwner) + } + } + } +} + +enum CBv2NativeShutdownError: Error { case operationClosed, unsupportedConsumer } + +/// Only package-owned prepared media can supply this non-array handoff check. +/// It reuses the producer's generation/codec/reservation checks at actual bind. +package protocol CBv2NativeMediaBindingValidating: AnyObject { + func validateNativeMediaBinding() throws +} + +/// Opaque one-shot seal, not an admission assertion supplied by a caller. +/// Its native storage is accessed only on the owning engine queue. +public final class CBv2PreparedNativeMediaToken: @unchecked Sendable { + public let id = UUID() + let work: CBv2NativeMediaPreparation + let prompt: [Int] + let maximumOutputTokens: Int + // Engine queue only. The actual stream object is the generation identity. + var stream: CBv2OutputStream? + var disposed = false + init(work: CBv2NativeMediaPreparation, request: CBv2Request) { + self.work = work + prompt = request.promptTokens + maximumOutputTokens = request.maxTokens + } + func matches(_ request: CBv2Request, engineID: UUID) -> Bool { + !disposed && work.engineID == engineID && prompt == request.promptTokens + && maximumOutputTokens == request.maxTokens && request.maxTokens > 0 + && request.multimodal?.nativeMediaToken === self + && request.positionState == nil && request.multimodal?.positionState == nil + && request.multimodal?.attention == .causal + } +} + +/// Package-local producer context, acquired before pixel/native work. This +/// reuses the engine's loan/root/first-winner state; it is not construction. +package final class CBv2NativeMediaPreparation: @unchecked Sendable { + // Engine queue/loan guarantees liveness. A caller retaining a disposed + // token must not retain this engine's unrelated roots or stream consumers. + unowned let tracking: CBv2NativeShutdownState + let engineID: UUID + let generation: UInt64 + let executionContractID: UUID? + let loan: UUID + var rootIDs: [UInt64] = [] + var owners: [AnyObject] = [] + var resolved: CBv2ResolvedMultimodal? + var preparationCompleted = false + var didStartNativeWork = false + var onRequiredFailure: (() -> Void)? + private var retirement: (() throws -> Void)? + private var bindingValidator: (any CBv2NativeMediaBindingValidating)? + init(tracking: CBv2NativeShutdownState, loan: UUID) { + self.tracking = tracking + engineID = tracking.engineID + self.loan = loan + generation = tracking.generation + executionContractID = tracking.contractID + } + package func retain(_ owner: AnyObject) { owners.append(owner) } + package func validateAtBinding(_ validator: any CBv2NativeMediaBindingValidating) throws { + try tracking.requireWork() + guard bindingValidator == nil else { throw CBv2NativeShutdownError.unsupportedConsumer } + bindingValidator = validator + } + func validateBinding() throws { + guard let bindingValidator else { throw CBv2NativeShutdownError.unsupportedConsumer } + try bindingValidator.validateNativeMediaBinding() + } + package func beforeNativeWork(_ arrays: [MLXArray]) throws { + try tracking.requireWork() + tracking.captureStreams() + rootIDs.append(tracking.retain(arrays, owners: [])) + didStartNativeWork = true + } + package func requiredCompletionFailed() { + if let onRequiredFailure { + onRequiredFailure() + } else { + _ = tracking.fail(.nativeWorkFailed) + } + } + package func fencePreparation(_ stream: MLX.Stream) throws { + do { + try tracking.beforeFenceForTesting?(stream) + try withError { error in + stream.synchronize() + try error.check() + } + } catch { + requiredCompletionFailed() + throw error + } + } + package var completionFailed: Bool { tracking.isIncomplete } + package func completedPreparation() throws { + try tracking.requireWork() + preparationCompleted = true + } + /// The reviewed host callback only retires its existing reservation; it + /// must not perform native work or wait. Invoked outside outcome locks. + package func afterRetirement(_ body: @escaping () throws -> Void) { retirement = body } + // The short first-winner commit removes aliases, then a following queue + // callback runs accounting outside that lock while the loan stays armed. + func detachAfterCompletion() -> (() throws -> Void)? { + guard tracking.mayExecute else { return nil } + resolved = nil + bindingValidator = nil + owners.removeAll() + tracking.retireCompleted(rootIDs) + rootIDs.removeAll() + let result = retirement + retirement = nil + return result + } +} + +/// Only the reviewed native assistant implements this package-only seam. Its +/// existing construction-stream fence is outside the outcome lock; replacement +/// of measured owners is a separate non-evaluating, non-waiting commit. +package protocol CBv2NativeMTPCompletionSplitting: AnyObject { + func fenceRequestStateForNativeCompletion(_ state: any CBv2MTPRequestState) throws + func commitRequestStateNativeCompletion(_ state: any CBv2MTPRequestState) throws +} + +/// The status/first-winner mirror is locked; MLX roots and actual streams are +/// confined to the one engine queue. No native fence is performed under lock. +/// On incomplete, the strong engine reference intentionally becomes a permanent +/// restart-only retention cycle. There is no retry/reset/deinit-refund API. +final class CBv2NativeShutdownState: @unchecked Sendable { + let engineID: UUID + let generation: UInt64 = 1 + let contractID: UUID? + let supported: Bool + private let lock = NSRecursiveLock() + private weak var engine: EngineV2? + private var retainedFaultEngine: EngineV2? + private var result: CBv2NativeShutdownOutcome? + private var waiters: [CheckedContinuation] = [] + private var requested = false + private var loans: [UUID: AnyObject?] = [:] + private var capturedStreamCount = 0 + private var capturedRootCount = 0 + // Engine queue only. Array aliases never cross the status mirror. + private var streams: [MLX.Stream] = [] + private var roots: [UInt64: ([MLXArray], [AnyObject])] = [:] + private var nextRoot: UInt64 = 0 + // Refusal/hold hooks only, never a replacement for a successful fence. + var beforeFenceForTesting: ((MLX.Stream) throws -> Void)? + var afterSubmissionForTesting: (() -> Void)? + var afterAssistantFenceForTesting: ((any CBv2MTPRequestState) -> Void)? + + init(engineID: UUID, contractID: UUID?, supported: Bool) { + self.engineID = engineID + self.contractID = contractID + self.supported = supported + } + func installEngine(_ value: EngineV2) { + lock.withLock { engine = value } + if !supported { _ = fail(.unsupportedExecutionContract) } + } + var outcome: CBv2NativeShutdownOutcome? { lock.withLock { result } } + var isIncomplete: Bool { + lock.withLock { + if case .incomplete? = result { return true } + return false + } + } + var mayExecute: Bool { lock.withLock { supported && result == nil } } + var hasLoans: Bool { lock.withLock { !loans.isEmpty } } + /// Private pool lifetime only. Missing/wrong UUID never authorizes teardown. + func hasOnlyNativeLoan(_ id: UUID) -> Bool { + lock.withLock { supported && result == nil && loans.count == 1 && loans[id] != nil } + } + var debugRetainedRootCount: Int { lock.withLock { capturedRootCount } } + + func beginLoan(owner: AnyObject? = nil, duringDrain: Bool = false) throws -> UUID { + try lock.withLock { + guard supported, result == nil, duringDrain || !requested else { + throw CBv2NativeShutdownError.operationClosed + } + let id = UUID() + loans[id] = .some(owner) + return id + } + } + func endLoan(_ id: UUID) { + lock.withLock { + // A late caller cannot release the only private diagnostic owner + // after incomplete won. Its loan/owner remains part of the fault. + guard result == nil else { return } + loans.removeValue(forKey: id) + } + } + + /// Returns true for the one caller that must enqueue/schedule the drain. + func register(_ waiter: CheckedContinuation) -> Bool { + let answer: (CBv2NativeShutdownOutcome?, Bool) = lock.withLock { + if let result { return (result, false) } + waiters.append(waiter) + let first = !requested + requested = true + return (nil, first) + } + if let result = answer.0 { waiter.resume(returning: result) } + return answer.1 + } + + @discardableResult + func fail(_ reason: CBv2NativeShutdownFault.Reason) -> Bool { + let won: + (CBv2NativeShutdownOutcome, [CheckedContinuation])? = + lock.withLock { + guard result == nil else { return nil } + let value = CBv2NativeShutdownOutcome.incomplete( + .init(engineID: engineID, generation: generation, reason: reason)) + retainedFaultEngine = engine + result = value + let parked = waiters + waiters = [] + return (value, parked) + } + guard let won else { return false } + for waiter in won.1 { waiter.resume(returning: won.0) } + return true + } + + /// Short metadata/ownership commit only. Never put eval/readback/fences or + /// blocking hooks in this closure. Recursive solely for nested SDK cleanup. + @discardableResult + func commitIfHealthy(_ body: () -> Void) -> Bool { + return lock.withLock { + guard supported, result == nil else { return false } + body() + return true + } + } + func beginCommit() -> Bool { + lock.lock() + guard supported, result == nil else { + lock.unlock() + return false + } + return true + } + func endCommit() { lock.unlock() } + func commitIfHealthyThrowing(_ body: () throws -> Void) throws -> Bool { + return try lock.withLock { + guard supported, result == nil else { return false } + try body() + return true + } + } + + func requireWork() throws { + guard mayExecute else { throw CBv2NativeShutdownError.operationClosed } + } + func captureStreams() { + // Called on the engine queue BEFORE creating/submitting native work. + for value in [StreamOrDevice.cpu.stream, StreamOrDevice.default.stream] + where !streams.contains(value) { + streams.append(value) + } + lock.withLock { capturedStreamCount = streams.count } + } + /// Engine queue only: an external prefix operation already fenced these + /// actual streams before its completion callback reached this queue. + func captureCompletedPrefixStreams(_ completed: [MLX.Stream]) { + for value in completed where !streams.contains(value) { streams.append(value) } + lock.withLock { capturedStreamCount = streams.count } + } + var streamsForPrefixWork: [MLX.Stream] { streams } + var rootMark: UInt64 { nextRoot } + @discardableResult + func retain(_ arrays: [MLXArray] = [], owners: [AnyObject] = []) -> UInt64 { + precondition(nextRoot < UInt64.max, "native root generation exhausted") + nextRoot += 1 + roots[nextRoot] = (arrays, owners) + lock.withLock { capturedRootCount = roots.count } + return nextRoot + } + func rootIDs(since mark: UInt64) -> [UInt64] { roots.keys.filter { $0 > mark } } + func retireCompleted(_ ids: [UInt64]) { + // Completion authority is the existing successful step/future readback, + // not a global memory delta or a new blanket per-step stream fence. + _ = commitIfHealthy { + for id in ids { roots.removeValue(forKey: id) } + capturedRootCount = roots.count + } + } + func didSubmit() throws { + afterSubmissionForTesting?() + try requireWork() + } + func fenceCapturedStreams() throws { + // Engine queue only, outside the first-winner lock. Any failure retains + // all roots. A watchdog can win while this actual fence is blocked. + var firstFailure: Error? + for stream in streams { + do { + try beforeFenceForTesting?(stream) + try withError { error in + stream.synchronize() + try error.check() + } + } catch { if firstFailure == nil { firstFailure = error } } + } + if let firstFailure { throw firstFailure } + } + + func completeQuiescent(_ cleanup: () -> Void) { + let won: + (CBv2NativeShutdownOutcome, [CheckedContinuation])? = + lock.withLock { + guard supported, requested, result == nil, loans.isEmpty, let contractID else { + return nil + } + cleanup() // only post-fence SDK state/ownership cleanup + roots.removeAll() + capturedRootCount = 0 + let value = CBv2NativeShutdownOutcome.quiescent( + .init( + engineID: engineID, generation: generation, + executionContractID: contractID, + capturedStreamCount: capturedStreamCount)) + result = value + let parked = waiters + waiters = [] + return (value, parked) + } + if let won { for waiter in won.1 { waiter.resume(returning: won.0) } } + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/DefaultSamplerV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/DefaultSamplerV2.swift index 955f7ebc05..cefe9c5b19 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/DefaultSamplerV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/DefaultSamplerV2.swift @@ -39,6 +39,10 @@ public final class CBv2DefaultSampler: CBv2StepSampler { public private(set) var logprobGatherCount = 0 /// Test hook: the composed pipeline's logprob-capture counter. var pipelineLogprobBuildCount: Int { pipeline?.logprobBuildCount ?? 0 } + /// Metadata-only test observation of the REAL accepted sampler. Install + /// before engine use; never replace during execution. Invoked once per + /// sample on the engine queue. No callback result changes sampling. + var sampleObserverForTesting: (([CBv2RequestID], Int) -> Void)? public var supportsTokenConstraints: Bool { true } /// - Parameter fallbackSeed: engine-level seed for rows without a @@ -53,6 +57,7 @@ public final class CBv2DefaultSampler: CBv2StepSampler { stepIndex: Int, pendingSampledTokens: MLXArray?, rowContext: () -> [CBv2SamplerRow] ) -> MLXArray { + sampleObserverForTesting?(requestIDs, stepIndex) let vocab = logits.dim(-1) if pipeline?.vocabSize != vocab { pipeline = LogitsPipelineV2(vocabSize: vocab) @@ -84,10 +89,11 @@ public final class CBv2DefaultSampler: CBv2StepSampler { let output = pipeline.process( logits, rawLogprobsFrom: logits, - hardMask: constraintSampler.hasRows ? { [constraintSampler] transformed in - constraintSampler.mask( - transformed, requestIDs: requestIDs) - } : nil) + hardMask: constraintSampler.hasRows + ? { [constraintSampler] transformed in + constraintSampler.mask( + transformed, requestIDs: requestIDs) + } : nil) let tokens = sampler.sample(from: output.sampling) pipeline.commit(sampledTokens: tokens) sampler.commit() diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift index 175f6472f4..5fb4092d9f 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift @@ -17,6 +17,7 @@ // (`CBv2SequenceKV.rollback(1)`). The chain breaks on ANY membership change // (prefill completion into a different set, finish, cancel, join, pause). +import Cmlx import Foundation import MLX import os @@ -335,6 +336,8 @@ public struct CBv2EngineLoopConfig: Sendable { /// finalization materializes them (the ONE host sync per step, overlapped /// with the next step's GPU work when chained). final class CBv2InFlightStep { + var nativeRootIDs: [UInt64] = [] + var mimoKeyRangeWork: [MiMoV26NAXKeyRangeWork] = [] /// Exact scheduler work launched by this step. Scheduler records already /// contain these optimistic advances; deadline projection subtracts them /// to recover confirmed cursors, then charges the full work once. @@ -350,9 +353,11 @@ final class CBv2InFlightStep { /// `sampledTokens`). let sampledRows: [CBv2RequestID] /// Lazy [K] int32, or nil when no row sampled (all mid-prefill chunks). - let sampledTokens: MLXArray? + var sampledTokens: MLXArray? /// Cheap handles that force evaluation of non-sampling prefill chunks. - let evalTargets: [MLXArray] + var evalTargets: [MLXArray] + var pagedAttentionWork: CBv2PagedAttentionStepOwner? + var nativePagedMTPWork: CBv2NativePagedMTPWork? /// Rows finished/cancelled AFTER launch: their sampled token is /// discarded at finalization (the ≤1 wasted slot-step). var discard: Set = [] @@ -397,6 +402,7 @@ final class CBv2InFlightStep { var forwardShapes: CBv2ForwardShapeStep? var recurrentCheckpointChunkSizes: [CBv2RequestID: Int] = [:] var historicalCheckpoints: [CBv2RequestID: [CBv2CapturedCompleteCheckpoint]] = [:] + var nativeHistoricalCheckpointWork: [CBv2RequestID: CBv2NativeCompletePrefixWork] = [:] var permitsChainedSuccessor: Bool { mtpRound == nil && historicalCheckpoints.isEmpty && attentionPacket == nil } @@ -494,6 +500,7 @@ enum CBv2FirstTokenDeadlineEnqueueOutcome: Sendable { case deadlineUnreachable(CBv2FirstTokenProjectedWork) case cancelled case schedulerRejected(CBv2SchedulerError) + case mediaRejected(any Error) case capacityRejected } @@ -604,6 +611,195 @@ private final class CBv2DrainWaiter: @unchecked Sendable { /// steps). Cross-thread surface: `requestCancel`, `setPaused`, stream /// registration, and the watchdog — all lock-protected. public final class EngineLoopV2: @unchecked Sendable { + let nativeShutdownState: CBv2NativeShutdownState? + private let blockBatchBudget: MiMoV26BlockBatchBudget? + private let rectangularDenseBudget: MiMoV26RectangularDenseBudget? + // Build-to-step handoff only; real ownership remains the existing native + // root/loan. No process registry, second ledger or destructor refund. + private var buildingMiMoKeyRangeWork: [UInt64: MiMoV26NAXKeyRangeWork] = [:] + private var pendingMiMoKeyRangeByRequest: [CBv2RequestID: Int] = [:] + private var nativePagedBinding: CBv2NativePagedModelBinding? + private var pendingNativePagedByRequest: [CBv2RequestID: Int] = [:] + var mimoKeyRangeWorkCreatedForTesting: ((MiMoV26NAXKeyRangeWork) -> Void)? + // Confined to engineQueue, including unsubmitted prepared handoffs. + private var nativePreparedMedia: [UUID: CBv2PreparedNativeMediaToken] = [:] + + func prepareNativeMedia( + processor: AnyObject, owner: AnyObject, + _ body: (CBv2NativeMediaPreparation) throws -> CBv2Request + ) throws -> CBv2Request { + try onEngineQueueSync { + guard let tracking = nativeShutdownState else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + let loan = try tracking.beginLoan(owner: owner) + let work = CBv2NativeMediaPreparation(tracking: tracking, loan: loan) + work.onRequiredFailure = { [weak self] in self?.failNativeCompletion(.nativeWorkFailed) + } + work.retain(processor) + work.retain(owner) + work.rootIDs.append(tracking.retain(owners: [work])) + do { + var request = try body(work) + guard work.preparationCompleted, request.maxTokens > 0, + !request.promptTokens.isEmpty, let input = request.multimodal, + input.attention == .causal, input.positionState == nil, + input.deepstackEmbeddings == nil + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + let blocks = try CBv2MultimodalPlan.validate( + input, + promptTokenCount: request.promptTokens.count, model: model, + cacheProvider: cacheProvider, + maxBatchedTokensPerStep: scheduler.config.maxBatchedTokensPerStep) + // The exact package producer has already checked hidden width + // and dtype against its loaded target. Do not run the generic + // embedPromptTokens shape probe or expose feature aliases. + let arrays = try input.embeddings() + guard arrays.count == input.spans.count, + zip(arrays, input.spans).allSatisfy({ + $0.0.ndim == 2 && $0.0.dim(0) == $0.1.length + }) + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try work.beforeNativeWork(arrays) + let normalized = arrays.map { $0.expandedDimensions(axis: 0) } + let resolved = CBv2ResolvedMultimodal( + spans: input.spans, attention: .causal, + blocks: blocks, embeddings: normalized, deepstackEmbeddings: []) + try work.beforeNativeWork(normalized) + do { try withError { eval(normalized) } } catch { + work.requiredCompletionFailed() + throw error + } + try tracking.requireWork() + work.resolved = resolved + // No raw feature alias survives in a caller-held closure. + var sealed = CBv2MultimodalInput(spans: input.spans, attention: .causal) { + // Even a caller invoking the public closure cannot borrow + // an unpriced alias. Only the exact engine consumes the seal. + throw CBv2NativeShutdownError.unsupportedConsumer + } + let token = CBv2PreparedNativeMediaToken(work: work, request: request) + sealed.nativeMediaToken = token + request.multimodal = sealed + guard tracking.commitIfHealthy({ nativePreparedMedia[token.id] = token }) else { + throw CBv2NativeShutdownError.operationClosed + } + return request + } catch { + // Required completion errors are already sealed before cleanup. + // Ordinary cancellation/refusal may dispose only proven work. + if work.didStartNativeWork && !work.preparationCompleted { + work.requiredCompletionFailed() + } + var release: (() throws -> Void)? + if tracking.commitIfHealthy({ release = work.detachAfterCompletion() }) { + do { + try release?() // never under the first-winner/registry lock + tracking.endLoan(loan) + } catch { work.requiredCompletionFailed() } + } + throw error + } + } + } + + func bindPreparedMedia( + _ token: CBv2PreparedNativeMediaToken, request: CBv2Request, + stream: CBv2OutputStream + ) throws -> CBv2ResolvedMultimodal { + try onEngineQueueSync { + let value = try validatedUnboundPreparedMedia(token, request: request) + guard nativeShutdownState?.commitIfHealthy({ token.stream = stream }) == true else { + throw CBv2NativeShutdownError.operationClosed + } + return value + } + } + + /// Engine queue, outside the first-winner lock. No array construction, + /// materialization or consumption: a refused deadline keeps an unbound + /// seal for the caller's explicit discard or a later genuine retry. + private func validatedUnboundPreparedMedia( + _ token: CBv2PreparedNativeMediaToken, + request: CBv2Request + ) throws -> CBv2ResolvedMultimodal { + guard let tracking = nativeShutdownState else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try tracking.requireWork() + guard nativePreparedMedia[token.id] === token, token.stream == nil, + token.work.generation == tracking.generation, + token.work.executionContractID == tracking.contractID, + token.matches(request, engineID: tracking.engineID), let value = token.work.resolved, + request.multimodal?.spans == value.spans, + request.multimodal?.deepstackEmbeddings == nil + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try token.work.validateBinding() + return value + } + + func discardPreparedMedia(_ token: CBv2PreparedNativeMediaToken) { + onEngineQueueSync { + guard nativePreparedMedia[token.id] === token, token.stream == nil else { return } + finishPreparedMedia(token, acknowledging: nil) + } + } + private func finishPreparedMedia( + _ token: CBv2PreparedNativeMediaToken, + acknowledging stream: CBv2OutputStream? + ) { + guard let tracking = nativeShutdownState else { return } + var release: (() throws -> Void)? + guard + tracking.commitIfHealthy({ + token.disposed = true + token.stream = nil + nativePreparedMedia.removeValue(forKey: token.id) + release = token.work.detachAfterCompletion() + }) + else { return } + // Arrays/row aliases are gone, but the original loan remains armed + // through this reviewed host-only accounting consumer. + do { try release?() } catch { + token.work.requiredCompletionFailed() + return + } + tracking.endLoan(token.work.loan) + if stream != nil { + _ = tracking.commitIfHealthy { stream?.releaseEngineOwnership() } + } + completeDrainIfReady() + } + private let nativeQuiescentCleanup: (@Sendable () -> Void)? + // Engine-queue-only, bounded by registered stream generations. Keep each + // generation registered until its execution stack and tracked group owners + // have retired; terminal delivery alone is not a shared-C release signal. + private var nativePendingRetirements: + [( + id: CBv2RequestID, stream: CBv2OutputStream, + terminal: (() -> Void)?, terminalIsConsumer: Bool, + terminalStarted: Bool + )] = [] + private var nativeRetirementAcknowledgementQueued = false + private var nativeRetirementGroupDepth = 0 + private var nativeRetiredRowOwners: [CBv2RequestID: [[CBv2SequenceKV?]]] = [:] + var nativeRetirementBoundaryForTesting: ((String, CBv2InFlightStep?) -> Void)? + /// Root installs historical assistant capture here AFTER settled native + /// MTP observation, BEFORE required-copy fences and the metadata commit. + /// Root must retain/charge every attached copy before its execution. + var nativeHistoricalMTPCaptureBeforeCommit: ((CBv2InFlightStep) throws -> Void)? + var nativeSubmittedWorkFailureForTesting: (() throws -> Void)? + var nativeRequiredAssistantFenceForTesting: ((any CBv2MTPRequestState) throws -> Void)? + var nativePendingRetirementCountForTesting: Int { nativePendingRetirements.count } + /// Engine-queue-confined fact only. Call within the existing test boundary; + /// this getter deliberately does not nest onEngineQueueSync. + var hasInFlightStepForTesting: Bool { inFlight != nil } let scheduler: SchedulerV2 let capacity: CBv2StepCapacity? let backend: CBv2KVBackend @@ -626,6 +822,7 @@ public final class EngineLoopV2: @unchecked Sendable { private let engineQueue = DispatchQueue( label: "com.eigen.cbv2.engine", qos: .userInitiated) + private let nativePrefixQueueKey = DispatchSpecificKey() private let watchdogQueue = DispatchQueue( label: "com.eigen.cbv2.watchdog", qos: .utility) /// Prefix-cache donation runs here (hashing + indexing + optional device @@ -679,6 +876,10 @@ public final class EngineLoopV2: @unchecked Sendable { /// itself, and when it never fires the digest call throws rather than /// reporting a capability. private var prefillFrontierCaptureHook: (@Sendable (CBv2RequestID, MLXArray) -> Void)? + /// One-shot seam after real stream registration but before its deadline + /// operation is installed. Invoked on the submit caller outside both locks. + private var deadlineAdmissionBeforeRegistrationHookForTesting: + (@Sendable (CBv2RequestID) -> Void)? /// One-shot deterministic seam fired after a deadline closure has claimed /// its operation but before enqueue/adoption. Tests use it to place a /// cancellation in the exact formerly-orphaning window. @@ -708,6 +909,15 @@ public final class EngineLoopV2: @unchecked Sendable { /// drain cannot complete until each terminal donation releases its state /// back on the engine queue. private var pendingDonationReleaseCount = 0 + private var nativeCompletePrefixContract: CBv2NativeExecutionContract? + private var nativePrefixPendingByRequest: [CBv2RequestID: Int] = [:] + private var nativePrefixRetiredRows: [UUID: CBv2NativeCompletePrefixRetiredRows] = [:] + // Also holds the optional scalar-dense target charge in prefix-OFF + // native profiles, until the existing exact stream retirement boundary. + private var nativePrefixReservations: [CBv2RequestID: CBv2CheckpointReservation] = [:] + private var nativePrefixStoreCloseStarted = false + private var nativePrefixStoreCloseFinished = false + private var nativePrefixStoreCloseJoin: CBv2NativeCompletePrefixStoreCloseJoin? /// Resolved vision inputs (validated spans + materialized embeddings), /// keyed by request. Kept across PREEMPTION (a full re-prefill replays /// the span chunks and needs the embeddings again); dropped at finish. @@ -729,6 +939,7 @@ public final class EngineLoopV2: @unchecked Sendable { var attentionMetadata: CBv2AttentionMetadataState? var attentionPacket: CBv2AttentionPacketState? private var draining = false + var isDrainingForTesting: Bool { draining } // engine queue only, read-only private var drainWaiters: [CBv2DrainWaiter] = [] /// True after a rejecting MTP round advanced rows OUTSIDE the eager /// provider's caches' host truth: the next eager bind must be forced to @@ -737,6 +948,9 @@ public final class EngineLoopV2: @unchecked Sendable { var eagerCompositionStale = false /// Telemetry / test hooks. + // Engine-queue-only. Opt-in observation, never a stream/device override. + private var reportedFirstCheckedForwardStream = false + public private(set) var stepCount = 0 public private(set) var chainedStepCount = 0 public private(set) var preemptionCount = 0 @@ -839,6 +1053,15 @@ public final class EngineLoopV2: @unchecked Sendable { /// before enqueue ran) so the regression is deterministic. Zero in /// production. Set before submitting. var enqueueStartDelayForTesting: TimeInterval = 0 + /// Engine-queue-only, OUTSIDE native commit. Observe the actual completed + /// page preparation or inject refusal/cancellation; never supply a receipt. + var nativePagedPrefixPreparedForTesting: + ((CBv2RequestID, CBv2PreparedNativePagedCheckpoint) -> Void)? + /// Borrow-only post-adoption test boundary, after required fences. The + /// observer may copy bounded host bytes/metadata, never construct/evaluate + /// arrays, mutate state or retain a native alias beyond this invocation. + var nativePagedPrefixAdoptedForTesting: + ((CBv2RequestID, [CBv2SequenceKV?], (any CBv2MTPRequestState)?) -> Void)? /// Engine-queue test gate. Once `stepCount` reaches this value, scheduled /// step callbacks yield through the idle recheck path without finalizing /// or planning more work; admission closures on the same queue still run. @@ -853,9 +1076,8 @@ public final class EngineLoopV2: @unchecked Sendable { ((CBv2RequestID, Range, Int?, Bool, String, String) -> Void)? public var isHealthy: Bool { - stateLock.lock() - defer { stateLock.unlock() } - return _healthy + let healthy = stateLock.withLock { _healthy } + return healthy && nativeShutdownState?.isIncomplete != true } init( @@ -875,8 +1097,16 @@ public final class EngineLoopV2: @unchecked Sendable { nominalFullKVBytesPerToken: Int? = nil, mtp: CBv2MTPRoundDriver? = nil, config: CBv2EngineLoopConfig, - gauges: CBv2EngineGauges + gauges: CBv2EngineGauges, + nativeShutdownState: CBv2NativeShutdownState? = nil, + blockBatchBudget: MiMoV26BlockBatchBudget? = nil, + rectangularDenseBudget: MiMoV26RectangularDenseBudget? = nil, + nativeQuiescentCleanup: (@Sendable () -> Void)? = nil ) { + self.nativeShutdownState = nativeShutdownState + self.blockBatchBudget = blockBatchBudget + self.rectangularDenseBudget = rectangularDenseBudget + self.nativeQuiescentCleanup = nativeQuiescentCleanup self.model = model self.layerKinds = layerKinds self.backend = backend @@ -899,6 +1129,7 @@ public final class EngineLoopV2: @unchecked Sendable { self.mtp = mtp self.config = config self.gauges = gauges + engineQueue.setSpecific(key: nativePrefixQueueKey, value: 1) // MTP: the scheduler consults the loop for 1+k decode assignments. // `unowned` is safe (and cycle-free): the loop owns the scheduler // and both live exactly as long as the engine. @@ -917,6 +1148,8 @@ public final class EngineLoopV2: @unchecked Sendable { func start() { engineQueue.async { [self] in + guard nativeShutdownState?.mayExecute != false else { return } + nativeShutdownState?.captureStreams() guard !running else { return } running = true startWatchdog() @@ -934,6 +1167,10 @@ public final class EngineLoopV2: @unchecked Sendable { /// are marked for cancellation (cleaned up if the loop ever resumes), /// and `drain()` returns — the wedged step may still be executing. func drain() async { + if nativeShutdownState != nil { + _ = await drainReportingNativeCompletion() + return + } await withCheckedContinuation { (c: CheckedContinuation) in let waiter = CBv2DrainWaiter(c) watchdogQueue.asyncAfter(deadline: .now() + config.shutdownTimeout) { [weak self] in @@ -966,6 +1203,285 @@ public final class EngineLoopV2: @unchecked Sendable { } } + func drainReportingNativeCompletion() async -> CBv2NativeShutdownOutcome { + guard let tracking = nativeShutdownState else { + preconditionFailure("reporting is available only on tracked loops") + } + return await withCheckedContinuation { continuation in + guard tracking.register(continuation) else { return } + watchdogQueue.asyncAfter(deadline: .now() + config.shutdownTimeout) { [weak self] in + guard let self else { return } + if tracking.fail(.shutdownTimedOut) { self.forceFinishStreamsOnShutdownTimeout() } + } + engineQueue.async { [self] in + guard tracking.mayExecute else { return } + tracking.captureStreams() + beginNativeCompletePrefixStoreClose() + // The short commit arbitrates metadata/ownership retirement + // against timeout. No native wait is performed under its lock. + guard + tracking.commitIfHealthy({ + draining = true + let nanos = DispatchTime.now().uptimeNanoseconds + let now = config.clock.now() + for rec in scheduler.waiting { + finishRequest(rec.id, reason: .cancelled, nowNanos: nanos, now: now) + } + publishGauges() + }) + else { return } + completeDrainIfReady() + } + } + } + + /// Register real roots BEFORE eval/asyncEval. Even a result delivered after + /// a winning fault remains retained; requireWork then vetoes further work. + @discardableResult + @inline(__always) + func retainNativeWork( + _ arrays: @autoclosure () -> [MLXArray], owners: @autoclosure () -> [AnyObject] = [] + ) -> UInt64? { + guard let tracking = nativeShutdownState else { return nil } + tracking.captureStreams() + return tracking.retain(arrays(), owners: owners()) + } + func requireNativeWork() throws { try nativeShutdownState?.requireWork() } + func nativeWorkSubmitted() throws { + try nativeShutdownState?.didSubmit() + if nativeShutdownState != nil { try nativeSubmittedWorkFailureForTesting?() } + } + func failNativeCompletion(_ reason: CBv2NativeShutdownFault.Reason) { + if nativeShutdownState?.fail(reason) == true { forceFinishStreamsOnShutdownTimeout() } + } + /// Wrap the already-required readback, without adding an evaluation or a + /// stream fence. A native error cannot become cleanup authority. + func completedNativeReadback(_ body: () -> Void) -> Bool { + guard let tracking = nativeShutdownState else { + body() + return true + } + guard tracking.mayExecute else { return false } + do { + try withError { error in + body() + try error.check() + } + return tracking.mayExecute + } catch { + if tracking.fail(.nativeWorkFailed) { forceFinishStreamsOnShutdownTimeout() } + return false + } + } + @discardableResult + func nativeCommit(_ body: () -> Void) -> Bool { + if let tracking = nativeShutdownState { return tracking.commitIfHealthy(body) } + body() + return true + } + func nativeCommitThrowing(_ body: () throws -> Void) throws -> Bool { + if let tracking = nativeShutdownState { return try tracking.commitIfHealthyThrowing(body) } + try body() + return true + } + func nativeDiagnosticLoanEnded(_ id: UUID?) { + guard let id, let tracking = nativeShutdownState else { return } + tracking.endLoan(id) + engineQueue.async { [weak self] in self?.completeDrainIfReady() } + } + + // MARK: Exact native complete-prefix consumers + + func configureNativeCompletePrefix(contract: CBv2NativeExecutionContract) { + guard let capture = completeCheckpointCapture, nativeShutdownState != nil, + capture.store is any CBv2NativeCompletePrefixCache + else { + failNativeCompletion(.unsupportedExecutionContract) + return + } + do { try contract.validateCompletePrefix(store: capture.store, codec: capture.codec) } catch + { + failNativeCompletion(.unsupportedExecutionContract) + return + } + nativeCompletePrefixContract = contract + capture.nativeFailure = { [weak self] in self?.failNativeCompletion(.nativeWorkFailed) } + capture.nativeWorkFactory = { [weak self] requestID in + guard let self else { throw CBv2NativeShutdownError.operationClosed } + let operationStreams = [StreamOrDevice.cpu.stream, StreamOrDevice.default.stream] + // Capture runs on this engine queue; deferred retirement can call + // from another queue. Never synchronously dispatch onto ourselves. + if DispatchQueue.getSpecific(key: self.nativePrefixQueueKey) == 1 { + return try self.makeNativeCompletePrefixWork( + purpose: .discard, + requestID: requestID, operationStreams: operationStreams) + } + return try self.onEngineQueueSync { + try self.makeNativeCompletePrefixWork( + purpose: .discard, + requestID: requestID, operationStreams: operationStreams) + } + } + } + + /// Engine queue only. The import factory arrives here BEFORE allocation. + func makeNativeCompletePrefixWork( + purpose: CBv2NativeCompletePrefixPurpose, + request: CBv2Request? = nil, requestID: CBv2RequestID? = nil, + operationStreams: [MLX.Stream] = [] + ) throws -> CBv2NativeCompletePrefixWork { + guard let tracking = nativeShutdownState, let contract = nativeCompletePrefixContract, + let capture = completeCheckpointCapture, + let store = capture.store as? any CBv2NativeCompletePrefixCache + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try contract.validateCompletePrefix(store: store, codec: capture.codec) + if let request { + guard request.multimodal == nil, request.positionState == nil, + request.maxTokens > 0, request.promptTokens.count > 1, request.prefixCacheEnabled, + request.prefixCacheReceiptID != nil + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + } + let id = requestID ?? request?.id + let streams = + tracking.streamsForPrefixWork + operationStreams + + [StreamOrDevice.cpu.stream, StreamOrDevice.default.stream] + let work = try CBv2NativeCompletePrefixWork( + tracking: tracking, + codec: capture.codec, store: store, request: request, + purpose: purpose, + streams: streams, duringDrain: purpose != .importing, + queue: capture.queue, completionQueue: engineQueue, + wake: { [weak self] in + guard let self else { return } + if let id, let count = self.nativePrefixPendingByRequest[id] { + if count == 1 { + self.nativePrefixPendingByRequest.removeValue(forKey: id) + } else { + self.nativePrefixPendingByRequest[id] = count - 1 + } + } + self.acknowledgeNativeRetirements() + self.completeDrainIfReady() + }, + failure: { [weak self] in self?.forceFinishStreamsOnShutdownTimeout() }, + validateBinding: { + try contract.validateCompletePrefix(store: store, codec: capture.codec) + }) + if let id { nativePrefixPendingByRequest[id, default: 0] += 1 } + return work + } + + private func beginNativeCompletePrefixStoreClose() { + guard nativeCompletePrefixContract != nil, !nativePrefixStoreCloseStarted, + let tracking = nativeShutdownState, let capture = completeCheckpointCapture, + let store = capture.store as? any CBv2NativeCompletePrefixCache + else { return } + nativePrefixStoreCloseStarted = true + capture.close() // no new captures/donations; existing jobs still retire. + let join = CBv2NativeCompletePrefixStoreCloseJoin(store: store) + nativePrefixStoreCloseJoin = join + do { + let loan = try tracking.beginLoan(owner: join, duringDrain: true) + join.start { [weak self] in + guard let self else { return } + self.engineQueue.async { [weak self] in + guard let self, tracking.mayExecute else { return } + self.nativePrefixStoreCloseFinished = true + self.nativePrefixStoreCloseJoin = nil + tracking.endLoan(loan) + self.completeDrainIfReady() + } + } + } catch { failNativeCompletion(.nativeWorkFailed) } + } + + private func finishAfterCompletePrefixPublication( + _ id: CBv2RequestID, + ownership: CBv2OutputStream?, terminal: (() -> Void)? + ) { + if nativeShutdownState != nil, let ownership { + retireStream( + id, matching: ownership, afterRetirement: terminal, + waitsForTerminalConsumer: terminal != nil) + } else { + if let ownership { retireStream(id, matching: ownership) } + terminal?() + } + } + + private func beginNativeCompletePrefixRetirement(_ entry: CBv2NativeCompletePrefixRetiredRows) { + guard let capture = completeCheckpointCapture else { + failNativeCompletion(.unsupportedExecutionContract) + return + } + do { + let work = try makeNativeCompletePrefixWork( + purpose: .publication, + requestID: entry.requestID) + try work.retain(owners: [entry]) + pendingDonationReleaseCount += 1 + let completed: @Sendable ([Int]) -> Void = { [weak self, entry] positions in + guard let self else { return } + self.engineQueue.async { [weak self, entry] in + guard let self, let tracking = self.nativeShutdownState else { return } + var authorized = false + guard + tracking.commitIfHealthy({ + authorized = + self.nativePrefixRetiredRows.removeValue(forKey: entry.id) === entry + }), authorized + else { return } + // Real donor/source consumers have drained and their aliases + // have unwound. Accounting is outside the outcome lock. + entry.releaseRowsAndReservation(backend: self.backend) + self.pendingDonationReleaseCount -= 1 + if let intent = entry.intent { + capture.reportPublication(receiptID: intent.receiptID, positions: positions) + } + entry.complete() + self.publishGauges() + self.completeDrainIfReady() + } + } + if let intent = entry.intent { + capture.publish( + intent: intent, state: entry.state, + nativeWork: work, completion: completed) + } else { + work.finishAfterDroppingConsumers { completed([]) } + } + } catch { failNativeCompletion(.nativeWorkFailed) } + } + + /// Host-only detokenization is a counted SDK consumer. Its queue must join + /// the barrier even though it submits no MLX work under the native profile. + func enqueueDetokenization(owner: AnyObject? = nil, _ body: @escaping () -> Void) { + // The closure is transferred once to the serial detokenization queue, + // not made concurrently callable. Passthrough push/flush all use that + // queue; stop-string flush transfers only after engine-thread pushes + // have finished. The mutable detokenizer itself is not Sendable. + let handoff = CBv2Handoff(value: body) + guard let tracking = nativeShutdownState else { + detokQueue.async { handoff.value() } + return + } + guard let loan = try? tracking.beginLoan(owner: owner, duringDrain: true) else { return } + let completionQueue = engineQueue + detokQueue.async { [weak self] in + handoff.value() + // Host-only body no longer needs an engine owner. Retire its loan + // on the engine queue, without a delayed strong loop/model alias. + completionQueue.async { [weak self] in + tracking.endLoan(loan) + self?.completeDrainIfReady() + } + } + } + /// Shutdown-timeout path (watchdog queue): the engine queue is not /// making progress, so touch ONLY lock-protected state and the /// (thread-safe) streams — the same discipline as `watchdogTick()`. @@ -1012,8 +1528,35 @@ public final class EngineLoopV2: @unchecked Sendable { /// instead of waiting for another polling step. private func completeDrainIfReady() { guard draining, !scheduler.hasWork, inFlight == nil, - pendingDonationReleaseCount == 0 + pendingDonationReleaseCount == 0, nativePrefixRetiredRows.isEmpty, + buildingMiMoKeyRangeWork.isEmpty, pendingMiMoKeyRangeByRequest.isEmpty, + nativePrefixReservations.isEmpty, + nativeCompletePrefixContract == nil || nativePrefixStoreCloseFinished else { return } + if let tracking = nativeShutdownState { + let loansReady = + nativePagedBinding.map { + $0.poolRetired ? !tracking.hasLoans : $0.canStartPoolRetirement + } ?? !tracking.hasLoans + guard tracking.mayExecute, loansReady, !gauges.hasPendingSubmissions, + nativePendingRetirements.isEmpty, pendingNativePagedByRequest.isEmpty + else { return } + do { + try tracking.fenceCapturedStreams() + if let binding = nativePagedBinding, !binding.poolRetired { + try (backend as? PagedKVBackend)?.pool.retireIssuedNativePool() + } + } catch { + if tracking.fail(.capturedFenceFailed) { forceFinishStreamsOnShutdownTimeout() } + return + } + guard !tracking.hasLoans else { return } + tracking.completeQuiescent { + completeStop() + nativeQuiescentCleanup?() + } + return + } completeStop() let waiters = drainWaiters drainWaiters = [] @@ -1062,6 +1605,18 @@ public final class EngineLoopV2: @unchecked Sendable { _ operation: CBv2FirstTokenDeadlineOperation, for id: CBv2RequestID ) -> Bool { + // The stream is already registered, but no enqueue/adoption/native work + // for this generation can start before this operation is accepted. + // Outcome -> stateLock matches submit/commit ordering. Either insertion + // wins and the fault snapshot finds this waiter, or the sealed outcome + // wins and this exact never-enqueued generation is refused below. + if let tracking = nativeShutdownState { + guard tracking.beginCommit() else { + refuseUnregisteredDeadlineAdmission(operation, for: id) + return false + } + } + defer { nativeShutdownState?.endCommit() } stateLock.lock() precondition( deadlineAdmissionOperations[id] == nil, @@ -1098,6 +1653,37 @@ public final class EngineLoopV2: @unchecked Sendable { return true } + /// Cold loss of native registration only, not cleanup of admitted work. + /// No scheduler/backend/retained group owner exists for this operation: + /// enqueue is scheduled only after registerDeadlineAdmissionOperation wins. + /// Keep unrelated/faulted generations and every native fault owner intact. + private func refuseUnregisteredDeadlineAdmission( + _ operation: CBv2FirstTokenDeadlineOperation, + for id: CBv2RequestID + ) { + let refused: CBv2OutputStream? + stateLock.lock() + if deadlineAdmissionOperations[id] == nil, + streamGenerations[id] == operation.generation + { + refused = streams.removeValue(forKey: id) + streamGenerations.removeValue(forKey: id) + if pendingCancels[id] == operation.generation { + pendingCancels.removeValue(forKey: id) + } + } else { + refused = nil + } + stateLock.unlock() + refused?.releaseEngineOwnership() + refused?.finish( + reason: .error("engine is shutting down"), + usage: CBv2Usage(promptTokens: 0, completionTokens: 0)) + // The real waiter balances pendingSubmits once, outside stateLock. + // It never issues an admitted/retirement result for a cold refusal. + operation.waiter.resume(returning: .capacityRejected) + } + private enum DeadlineAdmissionStart: Equatable { case execute case cancellationRequested @@ -1141,7 +1727,11 @@ public final class EngineLoopV2: @unchecked Sendable { /// and acknowledge cancellation instead. private func commitDeadlineAdmission( _ operation: CBv2FirstTokenDeadlineOperation, - for id: CBv2RequestID + for id: CBv2RequestID, + preparedMedia: ( + token: CBv2PreparedNativeMediaToken, + value: CBv2ResolvedMultimodal + )? = nil ) -> DeadlineAdmissionCommit { stateLock.lock() defer { stateLock.unlock() } @@ -1152,6 +1742,16 @@ public final class EngineLoopV2: @unchecked Sendable { } switch operation.phase { case .executing: + if let preparedMedia { + guard let stream = streams[id], preparedMedia.token.stream == nil else { + return .notCurrent + } + // This same healthy admission commit owns the actual stream + // generation and already-evaluated features. Cold refusal + // never binds a token that its cleanup cannot retire. + preparedMedia.token.stream = stream + multimodalByID[id] = preparedMedia.value + } operation.phase = .completed deadlineAdmissionOperations.removeValue(forKey: id) return .admitted @@ -1239,6 +1839,31 @@ public final class EngineLoopV2: @unchecked Sendable { operation.waiter.resume(returning: outcome) } + func setDeadlineAdmissionBeforeRegistrationHookForTesting( + _ hook: (@Sendable (CBv2RequestID) -> Void)? + ) { + stateLock.lock() + deadlineAdmissionBeforeRegistrationHookForTesting = hook + stateLock.unlock() + } + + var deadlineAdmissionRegistrationSnapshotForTesting: (operationCount: Int, legacyHealthy: Bool) + { + stateLock.lock() + defer { stateLock.unlock() } + return (deadlineAdmissionOperations.count, _healthy) + } + + private func invokeDeadlineAdmissionBeforeRegistrationHookForTesting( + _ id: CBv2RequestID + ) { + stateLock.lock() + let hook = deadlineAdmissionBeforeRegistrationHookForTesting + deadlineAdmissionBeforeRegistrationHookForTesting = nil + stateLock.unlock() + hook?(id) + } + func setDeadlineAdmissionInitialGuardHookForTesting( _ hook: (@Sendable (CBv2RequestID) -> Void)? ) { @@ -1409,6 +2034,15 @@ public final class EngineLoopV2: @unchecked Sendable { if enqueueStartDelayForTesting > 0 { Thread.sleep(forTimeInterval: enqueueStartDelayForTesting) } + // Suffix/native page preparation must not run under the outcome + // lock. The same serial frame publishes or refuses its maps below. + if running, !draining, nativeShutdownState?.mayExecute != false { + do { + try prepareNativePagedCompletePrefix(prefixLookup.adoption, request: request) + } catch { prefixLookup.adoption?.completeCheckpoint?.close() } + } + if let tracking = nativeShutdownState { guard tracking.beginCommit() else { return } } + defer { nativeShutdownState?.endCommit() } prefixUsageByID[request.id] = CBv2PrefixUsage( outcome: prefixLookup.outcome, tier: nil, @@ -1531,12 +2165,29 @@ public final class EngineLoopV2: @unchecked Sendable { let operation = CBv2FirstTokenDeadlineOperation( generation: submissionGeneration, waiter: waiter) + invokeDeadlineAdmissionBeforeRegistrationHookForTesting(request.id) guard registerDeadlineAdmissionOperation(operation, for: request.id) else { releaseAbandonedAdoption(prefixLookup.adoption) return } engineQueue.async { [self] in + var nativeCommitHeld = false + func releaseNativeAdmissionCommit() { + if nativeCommitHeld { + nativeShutdownState?.endCommit() + nativeCommitHeld = false + } + } + func acquireNativeAdmissionCommit() -> Bool { + if let tracking = nativeShutdownState { + guard tracking.beginCommit() else { return false } + nativeCommitHeld = true + } + return true + } + guard acquireNativeAdmissionCommit() else { return } + defer { releaseNativeAdmissionCommit() } func complete( _ outcome: CBv2FirstTokenDeadlineEnqueueOutcome ) { @@ -1568,7 +2219,27 @@ public final class EngineLoopV2: @unchecked Sendable { // scheduler/prefix state exists yet. Cancellation in this // exact window used to remove the stream and let a reused // ID race the stale closure. + releaseNativeAdmissionCommit() invokeDeadlineAdmissionInitialGuardHookForTesting(request.id) + var preparedMedia: + ( + token: CBv2PreparedNativeMediaToken, + value: CBv2ResolvedMultimodal + )? + var mediaError: (any Error)? + if let input = request.multimodal { + do { + guard let token = input.nativeMediaToken else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + preparedMedia = ( + token, try validatedUnboundPreparedMedia(token, request: request) + ) + } catch { + mediaError = error + } + } + guard acquireNativeAdmissionCommit() else { return } if let interruption = deadlineAdmissionInterruption( operation, for: request.id) { @@ -1578,6 +2249,11 @@ public final class EngineLoopV2: @unchecked Sendable { ? .cancelled : .capacityRejected) return } + if let mediaError { + releaseAbandonedAdoption(prefixLookup.adoption) + complete(.mediaRejected(mediaError)) + return + } prefixUsageByID[request.id] = CBv2PrefixUsage( outcome: prefixLookup.outcome, @@ -1684,6 +2360,49 @@ public final class EngineLoopV2: @unchecked Sendable { return } + if !useResident, + prefixLookup.adoption?.completeCheckpoint?.usesPagedBacking == true, + prefixLookup.adoption?.completeCheckpoint?.hasNativeTracking == true + { + // The projection was accepted, but no target/head + // state is installed. Native preparation/fencing is + // outside the commit and includes no queue yield. + releaseNativeAdmissionCommit() + var prefixPreparationFailed = false + do { + try prepareNativePagedCompletePrefix( + prefixLookup.adoption, request: request) + } catch { prefixPreparationFailed = true } + guard acquireNativeAdmissionCommit() else { return } + if let interruption = deadlineAdmissionInterruption( + operation, for: request.id) + { + releaseAbandonedAdoption(prefixLookup.adoption) + discardDeadlineRejectedRequest(request.id) + complete( + interruption == .cancellationRequested + ? .cancelled : .capacityRejected) + return + } + if prefixPreparationFailed { + releaseAbandonedAdoption(prefixLookup.adoption) + discardDeadlineRejectedRequest(request.id) + complete(.capacityRejected) + return + } + // Real preparation time consumed the ORIGINAL + // absolute deadline; never silently use nil/reset it. + let now = config.clock.now() + guard case .bounded(_, let duration) = projectedWork, + now < admission.deadline, duration <= admission.deadline - now + else { + releaseAbandonedAdoption(prefixLookup.adoption) + discardDeadlineRejectedRequest(request.id) + complete(.deadlineUnreachable(projectedWork)) + return + } + } + if let residentPrefixProbe { residentPrefixCursorByID[request.id] = CBv2PagedPrefixCursor( hasher: residentPrefixProbe.hasher, @@ -1717,10 +2436,22 @@ public final class EngineLoopV2: @unchecked Sendable { return } - switch commitDeadlineAdmission(operation, for: request.id) { + switch commitDeadlineAdmission( + operation, for: request.id, + preparedMedia: preparedMedia) + { case .admitted: let admittedAt = config.clock.now() + releaseNativeAdmissionCommit() invokeDeadlineAdmissionCommittedHookForTesting(request.id) + guard acquireNativeAdmissionCommit() else { + // Commit already won. Transfer the genuine + // registered stream/retirement, never pretend a + // post-commit fault was cold capacity rejection. + waiter.resume( + returning: .admitted(projectedWork, admittedAt: admittedAt)) + return + } armLease(for: request) detokenizers[request.id] = detokenizerFactory.makeDetokenizer( @@ -1841,8 +2572,8 @@ public final class EngineLoopV2: @unchecked Sendable { rec.stampKVAllocated(nowNanos: adoptionEndedNanos) } } - let transfersPagedStage = adoption.completeCheckpoint?.usesPagedBacking == true - if !transfersPagedStage, let capacity { + let transfersDestinationStage = adoption.completeCheckpoint?.usesDestinationTransfer == true + if !transfersDestinationStage, let capacity { do { // Frozen replay physically owns full K/V through M from the // instant adoption publishes, even though its logical cursor @@ -1894,7 +2625,7 @@ public final class EngineLoopV2: @unchecked Sendable { } return true } catch { - if !transfersPagedStage { + if !transfersDestinationStage { capacity?.unreserve( id: requestID, tokens: adoption.plan.capacityReservationTokens, @@ -1937,6 +2668,28 @@ public final class EngineLoopV2: @unchecked Sendable { /// rolling retirements, so shutdown cannot release its slot grant early. func discardHybridCheckpoints(_ id: CBv2RequestID) { if let capture = completeCheckpointCapture { + if nativeCompletePrefixContract != nil { + guard capture.hasCheckpoints(requestID: id) else { return } + do { + let work = try makeNativeCompletePrefixWork( + purpose: .discard, + requestID: id) + pendingDonationReleaseCount += 1 + let queued = capture.drop(requestID: id, nativeWork: work) { [self] in + engineQueue.async { [self] in + guard nativeShutdownState?.mayExecute == true else { return } + pendingDonationReleaseCount -= 1 + publishGauges() + completeDrainIfReady() + } + } + if !queued { + pendingDonationReleaseCount -= 1 + work.finishAfterDroppingConsumers() + } + } catch { failNativeCompletion(.nativeWorkFailed) } + return // Hybrid/resident caches are excluded by this profile. + } pendingDonationReleaseCount += 1 let queued = capture.drop(requestID: id) { [self] in engineQueue.async { [self] in @@ -2011,6 +2764,8 @@ public final class EngineLoopV2: @unchecked Sendable { func setPaused(_ id: CBv2RequestID, _ paused: Bool) { engineQueue.async { [self] in + if let tracking = nativeShutdownState { guard tracking.beginCommit() else { return } } + defer { nativeShutdownState?.endCommit() } let now = config.clock.now() if paused { scheduler.pause(id) @@ -2038,6 +2793,8 @@ public final class EngineLoopV2: @unchecked Sendable { private func engineStep() { guard running else { return } + guard nativeShutdownState?.mayExecute != false else { return } + nativeShutdownState?.captureStreams() if let suspendedAt = suspendStepExecutionAtCountForTesting, stepCount >= suspendedAt { @@ -2064,6 +2821,22 @@ public final class EngineLoopV2: @unchecked Sendable { // exactly one step apart (never widened by extra clock reads). let stepNow = config.clock.now() boundaryClockNanos = 0 // see `boundaryFinishNanos` + var nativeCommitHeld = false + func releaseNativeCommit() { + if nativeCommitHeld { + nativeShutdownState?.endCommit() + nativeCommitHeld = false + } + } + func acquireNativeCommit() -> Bool { + if let tracking = nativeShutdownState { + guard tracking.beginCommit() else { return false } + nativeCommitHeld = true + } + return true + } + guard acquireNativeCommit() else { return } + defer { releaseNativeCommit() } processCancellations(now: stepNow) processLeaseExpiry(now: stepNow) @@ -2105,14 +2878,23 @@ public final class EngineLoopV2: @unchecked Sendable { CBv2PagedWriteBoundary(pool: $0.pool) } let next: CBv2InFlightStep + let nativeMark = nativeShutdownState?.rootMark + releaseNativeCommit() // graph submission/readback never holds the outcome lock do { next = try launchChainedDecode(plan, feeding: previous.sampledTokens!) } catch { - handlePagedWriteFailure(error, plan: plan, boundary: boundary, now: stepNow) + handlePagedWriteFailure( + error, plan: plan, boundary: boundary, now: stepNow, + nativeRootMark: nativeMark) + guard acquireNativeCommit() else { return } publishGauges() scheduleNextStep() return } + if let handle = retainNativeWork([], owners: [next]) { + next.nativeRootIDs.append(handle) + } + guard acquireNativeCommit() else { return } attachMTPMeasurement(measurement, to: next, chained: true) if var previousMeasurement = previous.mtpMeasurement { // The previous step's finalize-to-launch interval now @@ -2124,7 +2906,9 @@ public final class EngineLoopV2: @unchecked Sendable { inFlight = next chainedStepCount += 1 stepCount += 1 + releaseNativeCommit() finalize(previous, now: stepNow) + guard acquireNativeCommit() else { return } publishGauges() scheduleNextStep() return @@ -2174,7 +2958,9 @@ public final class EngineLoopV2: @unchecked Sendable { // the plan sees confirmed tokens and post-stop membership. if let previous = inFlight { inFlight = nil + releaseNativeCommit() finalize(previous, now: stepNow) + guard acquireNativeCommit() else { return } } // Apply the rollback path's deferred lease rewinds now that the // victims' in-flight samples are confirmed: markPreempted must be the @@ -2200,8 +2986,10 @@ public final class EngineLoopV2: @unchecked Sendable { (cacheProvider as? CBv2CompositionInvalidating)?.releaseBoundRows() publishGauges() if draining { + releaseNativeCommit() completeDrainIfReady() if !running { return } + guard acquireNativeCommit() else { return } } scheduleIdleRecheck() return @@ -2230,10 +3018,19 @@ public final class EngineLoopV2: @unchecked Sendable { // predicate are structurally wrong for speculative tokens. let measurement = mtpMeasurement(for: plan) let boundary = (backend as? PagedKVBackend).map { CBv2PagedWriteBoundary(pool: $0.pool) } + let nativeMark = nativeShutdownState?.rootMark + releaseNativeCommit() do { - inFlight = try (mtpRoundNeeded(plan) ? executeMTPRound(plan) : executeMixed(plan)) + let launched = try (mtpRoundNeeded(plan) ? executeMTPRound(plan) : executeMixed(plan)) + if let launched, let handle = retainNativeWork([], owners: [launched]) { + launched.nativeRootIDs.append(handle) + } + guard acquireNativeCommit() else { return } + inFlight = launched } catch { - handlePagedWriteFailure(error, plan: plan, boundary: boundary, now: stepNow) + handlePagedWriteFailure( + error, plan: plan, boundary: boundary, now: stepNow, nativeRootMark: nativeMark) + guard acquireNativeCommit() else { return } } attachMTPMeasurement(measurement, to: inFlight, chained: false) stepCount += 1 @@ -2257,36 +3054,234 @@ public final class EngineLoopV2: @unchecked Sendable { func checkedModelForward(phase: CBv2ForwardPhase = .decode, _ body: () -> Result) throws -> Result { + try requireNativeWork() + nativeShutdownState?.captureStreams() + if CBv2StepProfiler.enabled && !reportedFirstCheckedForwardStream { + reportedFirstCheckedForwardStream = true + let stream = StreamOrDevice.default + var device = mlx_device_new() + defer { mlx_device_free(device) } + var kind = MLX_CPU + let streamResult = mlx_stream_get_device(&device, stream.ctx) + let deviceResult = streamResult == 0 ? mlx_device_get_type(&kind, device) : -1 + let deviceName = + streamResult == 0 && deviceResult == 0 + ? (kind == MLX_GPU ? "gpu" : kind == MLX_CPU ? "cpu" : "other") : "unknown" + let engineID = nativeShutdownState?.engineID.uuidString ?? "untracked" + let line = + "CBV2_STEP_PROFILE first_checked_forward engine=\(engineID)" + + " phase=\(phase) stream=\(stream) device=\(deviceName)" + + " stream_status=\(streamResult) device_status=\(deviceResult)\n" + FileHandle.standardError.write(Data(line.utf8)) + } let validation = (backend as? PagedKVBackend)?.pool.writeValidation try validation?.check() - let value = CBv2ForwardShapeObservation.dispatch( - step: buildingForwardShapes, phase: phase, body) + let rangeContext: MiMoV26NAXKeyRangeContext? + if phase == .prefill, let budget = blockBatchBudget, + let admission = capacity as? AdmissionV2, let tracking = nativeShutdownState + { + rangeContext = .init(budget: budget, admission: admission, tracking: tracking) { + [self] in + try makeMiMoKeyRangeWork() + } + } else { + rangeContext = nil + } + let denseBudget = + phase == .mtpVerification + && nativeShutdownState?.mayExecute == true + && rectangularDenseBudget?.engineID == nativeShutdownState?.engineID + ? rectangularDenseBudget : nil + let value = MiMoV26RectangularDenseAdmission.withBudget(denseBudget) { + MiMoV26BlockBatchAttention.withBudget(phase == .prefill ? blockBatchBudget : nil) { + MiMoV26NAXKeyRangeNative.withContext(rangeContext) { + CBv2ForwardShapeObservation.dispatch( + step: buildingForwardShapes, phase: phase, body) + } + } + } + try rangeContext?.close() try validation?.check() return value } + /// Called before start(), after the exact ticket was consumed. Its private + /// lifetime loan prevents ARC disposal from masquerading as pool retirement. + func configureNativePaged(binding: CBv2NativePagedModelBinding, retaining engine: AnyObject) { + do { + guard let tracking = nativeShutdownState, tracking.supported, + nativePagedBinding == nil, + (backend as? PagedKVBackend)?.nativeModelBinding === binding + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try binding.installRuntime( + tracking, retaining: engine, queue: engineQueue, + onFailure: { [weak self] in self?.forceFinishStreamsOnShutdownTimeout() }, + onRetirement: { [weak self] in + self?.engineQueue.async { [weak self] in + self?.acknowledgeNativeRetirements() + self?.completeDrainIfReady() + } + }, + onWorkCreated: { [weak self] requests in + guard let self else { return } + for id in requests { pendingNativePagedByRequest[id, default: 0] += 1 } + }, + onWorkRetired: { [weak self] requests in + guard let self, nativeShutdownState?.mayExecute == true else { return } + for id in requests { + guard let count = pendingNativePagedByRequest[id], count > 0 else { + preconditionFailure("native paged work retirement underflow") + } + if count == 1 { + pendingNativePagedByRequest.removeValue(forKey: id) + } else { + pendingNativePagedByRequest[id] = count - 1 + } + } + }) + nativePagedBinding = binding + } catch { failNativeCompletion(.unsupportedExecutionContract) } + } + + private func makeMiMoKeyRangeWork() throws -> MiMoV26NAXKeyRangeWork { + guard let tracking = nativeShutdownState, let budget = blockBatchBudget, + budget.engineID == tracking.engineID, + (capacity as? AdmissionV2)?.hasProcessMemoryOwner == true + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try tracking.requireWork() + let work = try MiMoV26NAXKeyRangeWork( + tracking: tracking, queue: engineQueue, + didRetire: { [weak self] work in self?.didRetireMiMoKeyRangeWork(work) }, + failure: { [weak self] in self?.forceFinishStreamsOnShutdownTimeout() }) + tracking.captureStreams() + let id = tracking.retain(owners: [work]) + work.bindRoot(id) + buildingMiMoKeyRangeWork[id] = work + mimoKeyRangeWorkCreatedForTesting?(work) + return work + } + + private func takeMiMoKeyRangeWork(rootIDs: [UInt64], requests: Set) + -> [MiMoV26NAXKeyRangeWork] + { + var result: [MiMoV26NAXKeyRangeWork] = [] + for id in rootIDs { + guard let work = buildingMiMoKeyRangeWork.removeValue(forKey: id) else { continue } + work.bindRequests(requests) + for request in requests { pendingMiMoKeyRangeByRequest[request, default: 0] += 1 } + result.append(work) + } + return result + } + + private func didRetireMiMoKeyRangeWork(_ work: MiMoV26NAXKeyRangeWork) { + // The actual selected-stream completion, alias detach and explicit + // scratch release precede this same-engine-queue callback. + guard nativeShutdownState?.mayExecute == true, work.released else { return } + for id in work.requestIDs { + guard let count = pendingMiMoKeyRangeByRequest[id] else { continue } + if count == 1 { + pendingMiMoKeyRangeByRequest.removeValue(forKey: id) + } else { + pendingMiMoKeyRangeByRequest[id] = count - 1 + } + } + acknowledgeNativeRetirements() + completeDrainIfReady() + } + /// Rare runtime-contract failure. Model/recurrent/MTP graph construction may /// already have advanced different layers by different amounts, so retire /// the entire planned cohort rather than pretending cursor rewind repairs it. private func handlePagedWriteFailure( _ error: Error, plan: CBv2StepPlan, boundary: CBv2PagedWriteBoundary?, - now: ContinuousClock.Instant + now: ContinuousClock.Instant, nativeRootMark: UInt64? = nil ) { + var nativeCommitHeld = false + var nativeGroupEntered = false + var failedRangeWork: [MiMoV26NAXKeyRangeWork] = [] + if let tracking = nativeShutdownState { + guard tracking.mayExecute else { return } + do { + try tracking.fenceCapturedStreams() + if nativePagedBinding != nil { + boundary?.discardFailedGraphAfterSynchronization() + attentionMetadata?.discardPendingForward() + attentionPacket?.discardPendingForward() + (cacheProvider as? CBv2CompositionInvalidating)?.releaseBoundRows() + eagerCompositionStale = true + (backend as? PagedKVBackend)?.pool.discardUnpublishedAttentionWorkAfterDrain() + try tracking.requireWork() + } + if let nativeRootMark { + failedRangeWork = takeMiMoKeyRangeWork( + rootIDs: tracking.rootIDs(since: nativeRootMark), + requests: Set(plan.assignments.map(\.id))) + // Actual drain, NEVER evaluation of failed graph roots. + for work in failedRangeWork { try work.discardAfterDrain() } + } + } catch { + for work in failedRangeWork { work.failCompletion() } + (backend as? PagedKVBackend)?.pool.failUnpublishedAttentionWorkCompletion() + failNativeCompletion(.capturedFenceFailed) + return + } + guard tracking.beginCommit() else { return } + nativeCommitHeld = true + nativeRetirementGroupDepth += 1 + nativeGroupEntered = true + } + defer { if nativeCommitHeld { nativeShutdownState?.endCommit() } } + defer { if nativeGroupEntered { nativeRetirementGroupDepth -= 1 } } // MTP can submit assistant work before target verification, and chained // decode has a prior valid step in flight. Synchronize submitted work // only; never evaluate the failed forward's placeholders/write fences. - Stream.gpu.synchronize() - Stream.cpu.synchronize() - boundary?.discardFailedGraphAfterSynchronization() - attentionMetadata?.discardPendingForward() - attentionPacket?.discardPendingForward() - (cacheProvider as? CBv2CompositionInvalidating)?.releaseBoundRows() - eagerCompositionStale = true + if nativeShutdownState == nil { + if let pool = (backend as? PagedKVBackend)?.pool, pool.usesStepOwnedAttention { + do { + try withError { fault in + Stream.gpu.synchronize() + Stream.cpu.synchronize() + try fault.check() + } + } catch { + pool.attentionWorkEngineRefusal = + "paged attention completion failed; rebuild the engine" + pool.failUnpublishedAttentionWorkCompletion() + } + } else { + Stream.gpu.synchronize() + Stream.cpu.synchronize() + } + } + if nativePagedBinding == nil { + boundary?.discardFailedGraphAfterSynchronization() + attentionMetadata?.discardPendingForward() + attentionPacket?.discardPendingForward() + (cacheProvider as? CBv2CompositionInvalidating)?.releaseBoundRows() + eagerCompositionStale = true + (backend as? PagedKVBackend)?.pool.discardUnpublishedAttentionWorkAfterDrain() + } scheduler.rollback(plan) if let previous = inFlight { previous.discard.formUnion(plan.assignments.map(\.id)) inFlight = nil + if let handle = retainNativeWork([], owners: [previous]) { + previous.nativeRootIDs.append(handle) + } + if nativeCommitHeld { + nativeShutdownState?.endCommit() + nativeCommitHeld = false + } finalize(previous, now: now) + if let tracking = nativeShutdownState { + guard tracking.beginCommit() else { return } + nativeCommitHeld = true + } // The chained caller also retains this step. Its transactions // retain their input arrays even after rollback; drain those // aliases before releasing request state and refunding capacity. @@ -2302,13 +3297,32 @@ public final class EngineLoopV2: @unchecked Sendable { releaseRecurrentState(recurrent) } if let state = kvStates.removeValue(forKey: assignment.id) { - backend.release(state) + if nativeShutdownState != nil { + nativeRetiredRowOwners[assignment.id, default: []].append(state) + } else { + backend.release(state) + } } - // finishRequest now sees no native payload; its capacity refund - // follows actual target/recurrent/assistant alias retirement. + // Untracked cleanup has released the payload. Tracked cleanup keeps + // these exact rows/backend charges until the failed group's roots + // are retired below; finishRequest only queues its acknowledgement. finishRequest(assignment.id, reason: .error(String(describing: error)), now: now) } (backend as? PagedKVBackend)?.pool.writeValidation.clearAfterRetirement() + if nativeShutdownState != nil { + if nativeCommitHeld { + nativeShutdownState?.endCommit() + nativeCommitHeld = false + } + nativeRetirementBoundaryForTesting?("beforeFailedRootRetirement", nil) + guard nativeShutdownState?.beginCommit() == true else { return } + nativeCommitHeld = true + } + if let tracking = nativeShutdownState, let nativeRootMark { + tracking.retireCompleted(tracking.rootIDs(since: nativeRootMark)) + } + for work in failedRangeWork { work.retireCompletedGraph() } + releaseCompletedNativeRetiredRows() } // MARK: Step execution @@ -2653,6 +3667,14 @@ public final class EngineLoopV2: @unchecked Sendable { promptTokens: [Int], continuation: [Int], diagnostic: CBv2TeacherForcedScoreCollector? = nil ) throws -> [Int] { + try requireNativeWork() + if nativePagedBinding != nil { throw CBv2NativeShutdownError.unsupportedConsumer } + if nativeShutdownState != nil, diagnostic != nil { + throw CBv2NativeShutdownError.unsupportedConsumer + } + nativeShutdownState?.captureStreams() + let nativeMark = nativeShutdownState?.rootMark ?? 0 + var nativeCompleted = false guard running, !draining else { throw CBv2TeacherForcingError.engineNotRunning } guard !scheduler.hasWork else { throw CBv2TeacherForcingError.engineBusy( @@ -2665,13 +3687,14 @@ public final class EngineLoopV2: @unchecked Sendable { layerKinds: layerKinds, promptLength: promptTokens.count, maxLength: promptTokens.count + continuation.count) + retainNativeWork([], owners: state.compactMap { $0.map { $0 as AnyObject } }) let writeBoundary = (backend as? PagedKVBackend).map { CBv2PagedWriteBoundary(pool: $0.pool) } var recurrent: CBv2RecurrentRequestState? var recurrentEvaluation: CBv2RecurrentStateEvaluation? var recurrentReservation: CBv2CheckpointReservation? - defer { + func cleanupTeacherState() { if let recurrent { Stream.gpu.synchronize() Stream.cpu.synchronize() @@ -2693,6 +3716,21 @@ public final class EngineLoopV2: @unchecked Sendable { (backend as? PagedKVBackend)?.pool.writeValidation.clearAfterRetirement() recurrentReservation?.release() } + defer { + if let tracking = nativeShutdownState { + if !nativeCompleted, tracking.mayExecute { + do { try tracking.fenceCapturedStreams() } catch { + failNativeCompletion(.capturedFenceFailed) + } + } + _ = tracking.commitIfHealthy { + cleanupTeacherState() + tracking.retireCompleted(tracking.rootIDs(since: nativeMark)) + } + } else { + cleanupTeacherState() + } + } if (model as? any CBv2RecurrentSteppableModel)?.recurrentStateSpec != nil { guard let admission = capacity as? AdmissionV2 else { throw CBv2KVError.backendIneligible( @@ -2733,6 +3771,8 @@ public final class EngineLoopV2: @unchecked Sendable { } func finishForward(_ arrays: [MLXArray]) throws { + retainNativeWork(arrays) + try requireNativeWork() if let evaluation = recurrentEvaluation { eval(arrays) StreamOrDevice.default.stream.synchronize() @@ -2741,6 +3781,7 @@ public final class EngineLoopV2: @unchecked Sendable { } else { asyncEval(arrays) } + try nativeWorkSubmitted() } // One lazy [1] argmax per continuation position; the forwards never @@ -2811,8 +3852,15 @@ public final class EngineLoopV2: @unchecked Sendable { } let scored = top1.count == 1 ? top1[0] : concatenated(top1, axis: 0) - let result = scored.asArray(Int32.self).map(Int.init) + retainNativeWork([scored]) + try requireNativeWork() + var result: [Int] = [] + guard completedNativeReadback({ result = scored.asArray(Int32.self).map(Int.init) }) else { + throw CBv2NativeShutdownError.operationClosed + } try diagnostic?.finish(top1: result) + try requireNativeWork() + nativeCompleted = true return result } @@ -2820,12 +3868,20 @@ public final class EngineLoopV2: @unchecked Sendable { private func launchChainedDecode( _ plan: CBv2StepPlan, feeding lazyTokens: MLXArray ) throws -> CBv2InFlightStep { + try requireNativeWork() + let nativeMark = nativeShutdownState?.rootMark ?? 0 let shapes = beginForwardShapeStep() defer { endForwardShapeStep(shapes) } let wallStartedNanos = DispatchTime.now().uptimeNanoseconds let buildStart = CBv2StepProfiler.enabled ? CFAbsoluteTimeGetCurrent() : 0 let ids = plan.assignments.map(\.id) let rowStates = ids.map { kvStates[$0]! } // presence pre-checked + let attentionWork = try (backend as? PagedKVBackend)?.prepareAttentionWork( + assignments: plan.assignments.map { assignment in + let end = scheduler.record(for: assignment.id)!.numComputedTokens + return (assignment.id, (end - assignment.numTokens) ..< end) + }, states: kvStates) + defer { (backend as? PagedKVBackend)?.pool.endAttentionConstruction(attentionWork) } var params: [CBv2SamplingParams] = [] params.reserveCapacity(ids.count) for id in ids { params.append(scheduler.record(for: id)!.request.sampling) } @@ -2899,7 +3955,22 @@ public final class EngineLoopV2: @unchecked Sendable { "v2.deferredFill", seconds: CFAbsoluteTimeGetCurrent() - fillStart) } let evalStart = CBv2StepProfiler.enabled ? CFAbsoluteTimeGetCurrent() : 0 - asyncEval(toEval) + if let attentionWork { + try attentionWork.seal() + toEval.append(contentsOf: attentionWork.evaluationTargets) + } + retainNativeWork( + toEval, owners: rowStates.flatMap { $0.compactMap { $0.map { $0 as AnyObject } } }) + try requireNativeWork() + if attentionWork != nil { + try withError { fault in + asyncEval(toEval) + try fault.check() + } + } else { + asyncEval(toEval) + } + try nativeWorkSubmitted() if CBv2StepProfiler.enabled { let now = CFAbsoluteTimeGetCurrent() CBv2StepProfiler.record("v2.asyncEval.submit", seconds: now - evalStart) @@ -2920,7 +3991,10 @@ public final class EngineLoopV2: @unchecked Sendable { step.attentionPacket = rawAttention step.recurrentEvaluations = recurrent step.chained = true + attentionWork?.publish() + step.pagedAttentionWork = attentionWork step.forwardShapes = shapes + step.nativeRootIDs = nativeShutdownState?.rootIDs(since: nativeMark) ?? [] shapes?.attach() return step } @@ -2931,6 +4005,8 @@ public final class EngineLoopV2: @unchecked Sendable { /// `executeMTPRound` (this function's `rec.tokens` slicing and /// `samples` predicate are structurally wrong for speculative tokens). func executeMixed(_ plan: CBv2StepPlan) throws -> CBv2InFlightStep? { + try requireNativeWork() + let nativeMark = nativeShutdownState?.rootMark ?? 0 let shapes = beginForwardShapeStep() defer { endForwardShapeStep(shapes) } let wallStartedNanos = DispatchTime.now().uptimeNanoseconds @@ -2969,6 +4045,10 @@ public final class EngineLoopV2: @unchecked Sendable { RowWork(rec: rec, start: start, count: n, samples: samples, isDecode: isDecode)) } guard !work.isEmpty else { return nil } + let attentionWork = try (backend as? PagedKVBackend)?.prepareAttentionWork( + assignments: work.map { ($0.rec.id, $0.start ..< ($0.start + $0.count)) }, + states: kvStates) + defer { (backend as? PagedKVBackend)?.pool.endAttentionConstruction(attentionWork) } // Lazy offset/KV chains of every eager cache touched this step; ride // the step's asyncEval so the `+ L` offset advance can't accumulate @@ -3339,7 +4419,20 @@ public final class EngineLoopV2: @unchecked Sendable { uniqueKeysWithValues: work.map { ($0.rec.id, $0.rec.plannedPrefillChunkSize) }) } toEval.append(contentsOf: try prepareHistoricalCheckpoints(step)) - if step.historicalCheckpoints.isEmpty { + if let attentionWork { + try attentionWork.seal() + toEval.append(contentsOf: attentionWork.evaluationTargets) + } + retainNativeWork(toEval, owners: [step]) + try requireNativeWork() + if let attentionWork { + try withError { fault in + asyncEval(toEval) + try fault.check() + } + attentionWork.publish() + step.pagedAttentionWork = attentionWork + } else if step.historicalCheckpoints.isEmpty { asyncEval(toEval) } else { do { try withError { asyncEval(toEval) } } catch { @@ -3350,6 +4443,8 @@ public final class EngineLoopV2: @unchecked Sendable { throw error } } + try nativeWorkSubmitted() + step.nativeRootIDs = nativeShutdownState?.rootIDs(since: nativeMark) ?? [] step.forwardShapes = shapes shapes?.attach() return step @@ -3507,18 +4602,97 @@ public final class EngineLoopV2: @unchecked Sendable { // MARK: Finalization (deferred stop detection) private func finalize(_ step: CBv2InFlightStep, now: ContinuousClock.Instant) { + if nativeShutdownState != nil { nativeRetirementGroupDepth += 1 } + defer { if nativeShutdownState != nil { nativeRetirementGroupDepth -= 1 } } + // Associate real range work before any completion/retirement decision. + // All range arrays/reservations were already native-root/loan retained + // before encoding; this only binds request acknowledgement lifetimes. + step.mimoKeyRangeWork.append( + contentsOf: takeMiMoKeyRangeWork( + rootIDs: step.nativeRootIDs, requests: step.participants)) + // Keep the in-flight owner before any blocking read. Existing successful + // array/future readbacks supply baseline completion; extra state has + // its own required completion below, never an inferred empty counter. + if let handle = retainNativeWork([], owners: [step]) { step.nativeRootIDs.append(handle) } + guard nativeShutdownState?.mayExecute != false else { return } // THE host sync — overlapped with the successor step's GPU work when // chained. All-prefill steps block on their eval targets instead so // graph pipelining stays bounded at two steps. let readbackStart = CBv2StepProfiler.enabled ? CFAbsoluteTimeGetCurrent() : 0 var host: [Int32] = [] - if let tokens = step.sampledTokens { - host = tokens.asArray(Int32.self) - CBv2CoreInstrumentation.recordHostSync() - } else if !step.evalTargets.isEmpty { - eval(step.evalTargets) - CBv2CoreInstrumentation.recordHostSync() + func readback() { + if let tokens = step.sampledTokens { + host = tokens.asArray(Int32.self) + CBv2CoreInstrumentation.recordHostSync() + } else if !step.evalTargets.isEmpty { + eval(step.evalTargets) + CBv2CoreInstrumentation.recordHostSync() + } } + var pagedAttentionFailure: Error? + if let work = step.pagedAttentionWork { + do { + if nativeShutdownState != nil { + guard completedNativeReadback(readback) else { + work.failCompletion() + return + } + } else { + try withError { fault in + readback() + try fault.check() + } + } + try work.finishEvaluation() + } catch { + work.failCompletion() + if nativeShutdownState != nil { + failNativeCompletion(.nativeWorkFailed) + return + } + pagedAttentionFailure = error + step.discard.formUnion(step.participants) + host = Array(repeating: Int32(0), count: step.sampledRows.count) + } + } else { + guard completedNativeReadback(readback) else { return } + } + do { + // Outside beginCommit. Required roots include otherwise-unused + // custom outputs/sentinels, not merely the sampled scalar. + for work in step.mimoKeyRangeWork { try work.finishEvaluation() } + } catch { + for work in step.mimoKeyRangeWork { work.failCompletion() } + failNativeCompletion(.nativeWorkFailed) + return + } + do { try step.nativePagedMTPWork?.finishEvaluation() } catch { + step.nativePagedMTPWork?.fail() + failNativeCompletion(.nativeWorkFailed) + return + } + finishStatefulMTPEvaluation(step) + do { try captureSettledHistoricalAssistants(step) } catch { + if nativeShutdownState != nil { + failNativeCompletion(.nativeWorkFailed) + return + } + step.discard.formUnion(step.historicalCheckpoints.keys) + } + if nativeCompletePrefixContract != nil { + guard nativeShutdownState?.mayExecute == true else { return } + do { try nativeHistoricalMTPCaptureBeforeCommit?(step) } catch { + failNativeCompletion(.nativeWorkFailed) + return + } + guard finishHistoricalCheckpointCopiesForNative(step) else { return } + } + var nativeCommitHeld = false + if let tracking = nativeShutdownState { + guard tracking.beginCommit() else { return } + nativeCommitHeld = true + } + defer { if nativeCommitHeld { nativeShutdownState?.endCommit() } } if CBv2StepProfiler.enabled { CBv2StepProfiler.record( "v2.readback.wait", seconds: CFAbsoluteTimeGetCurrent() - readbackStart) @@ -3560,6 +4734,18 @@ public final class EngineLoopV2: @unchecked Sendable { let historicalFailure = commitHistoricalCheckpoints(step) captureRecurrentCheckpoints(step) + // Pre-eviction window views are step-scoped, not paused/retired request + // state. Sharing layers and historical copies have consumed them now. + // Exact offsets protect any already-launched chained successor; staged + // MTP rows keep their own rollback/commit lifetime instead. + for (id, range) in step.computedRanges { + let rows = step.deferredReleases.first { $0.id == id }?.state ?? kvStates[id] + for row in rows ?? [] { + (row as? CBv2WindowedSequenceKV)? + .retireBorrowableChunkViews(afterFencedPosition: range.upperBound) + } + } + // Publish only the exact work THIS finalized step launched. In the // chained path scheduler.numComputedTokens already includes N+1 here, // so consulting scheduler state would expose in-flight KV. MTP verify @@ -3683,15 +4869,34 @@ public final class EngineLoopV2: @unchecked Sendable { // reservation's own lock acquisition (measured in `emit`). stream?.reserveEmission( firstEmissionArmedNanos: firstToken ? readbackDoneNanos : 0) - detokQueue.async { + let trackedLoop = nativeShutdownState == nil ? nil : self + enqueueDetokenization(owner: detokenizer) { let text = isStopToken ? "" : (detokenizer?.push([token]) ?? "") - stream?.emit( - .delta(text: text, tokens: [token], logprobs: logprobs), - consumingReservation: true) + let publish: () -> Void = { + stream?.emit( + .delta(text: text, tokens: [token], logprobs: logprobs), + consumingReservation: true) + } + if let trackedLoop { _ = trackedLoop.nativeCommit(publish) } else { publish() } } } else { let detokStart = CBv2StepProfiler.enabled ? CFAbsoluteTimeGetCurrent() : 0 + var hostLoan: UUID? + if let tracking = nativeShutdownState { + guard let loan = try? tracking.beginLoan(owner: detokenizer, duringDrain: true) + else { return } + hostLoan = loan + if nativeCommitHeld { + tracking.endCommit() + nativeCommitHeld = false + } + } let text = isStopToken ? "" : (detokenizer?.push([token]) ?? "") + if let tracking = nativeShutdownState { + guard tracking.beginCommit() else { return } // fault retains the actual host owner/loan + nativeCommitHeld = true + if let hostLoan { tracking.endLoan(hostLoan) } + } if CBv2StepProfiler.enabled { CBv2StepProfiler.record( "v2.detok.push", seconds: CFAbsoluteTimeGetCurrent() - detokStart) @@ -3725,7 +4930,19 @@ public final class EngineLoopV2: @unchecked Sendable { // asyncEval), AFTER the plain loop above (seed bonus tokens are // confirmed there) and BEFORE the fenced frees below. if step.mtpRound != nil { + // MTP has its own existing readbacks; never wait under this lock. + if nativeCommitHeld { + nativeShutdownState?.endCommit() + nativeCommitHeld = false + } + if nativeShutdownState != nil { + nativeRetirementBoundaryForTesting?("beforeMTPFinalization", step) + } finalizeMTPRound(step) + if let tracking = nativeShutdownState { + guard tracking.beginCommit() else { return } + nativeCommitHeld = true + } } mtp?.recordCommittedDecodeBaseline( measurement: step.mtpMeasurement, completedAtNanos: readbackDoneNanos, @@ -3791,15 +5008,22 @@ public final class EngineLoopV2: @unchecked Sendable { } let publicationDeferred = retire( state: state, donating: donation, hybridPublication: hybridPublication, + nativeRequestID: id, afterPublication: { [self] in - if let ownership { retireStream(id, matching: ownership) } - terminalDelivery?() + finishAfterCompletePrefixPublication( + id, ownership: ownership, terminal: terminalDelivery) }) releaseRecurrentState(recurrent) - if !publicationDeferred, let ownership { - retireStream(id, matching: ownership) + if !publicationDeferred { + if nativeShutdownState != nil, let ownership { + retireStream( + id, matching: ownership, afterRetirement: terminalDelivery, + waitsForTerminalConsumer: terminalDelivery != nil) + } else { + if let ownership { retireStream(id, matching: ownership) } + terminalDelivery?() + } } - if !publicationDeferred { terminalDelivery?() } } if let mtp { for state in step.mtpRound?.deferredAssistantReleases ?? [] { @@ -3831,6 +5055,28 @@ public final class EngineLoopV2: @unchecked Sendable { // already expired at the next boundary (PR#82 review). Progress is // confirmed NOW, after the sync. refreshProgressLeases(step, now: config.clock.now()) + if step.pagedAttentionWork != nil { + if let pagedAttentionFailure { + for id in step.participants where scheduler.record(for: id) != nil { + finishRequest( + id, reason: .error(String(describing: pagedAttentionFailure)), now: now) + } + } + // Drop only this completed SDK graph's holders after the final + // diagnostics/readers. Failed required completion remains sticky. + step.sampledTokens = nil + step.evalTargets.removeAll() + step.logprobSegments.removeAll() + step.logitDiagnostics.removeAll() + step.pagedAttentionWork?.closeGraph() + step.pagedAttentionWork = nil + } + let pagedMTPWork = step.nativePagedMTPWork + step.nativePagedMTPWork = nil + pagedMTPWork?.closeAfterStep() + nativeShutdownState?.retireCompleted(step.nativeRootIDs) + for work in step.mimoKeyRangeWork { work.retireCompletedGraph() } + releaseCompletedNativeRetiredRows() } /// Refresh each live participant's progress lease and its reconciled usage @@ -3873,6 +5119,8 @@ public final class EngineLoopV2: @unchecked Sendable { _ id: CBv2RequestID, reason: CBv2FinishReason, nowNanos: UInt64? = nil, now: ContinuousClock.Instant? = nil ) { + if let tracking = nativeShutdownState { guard tracking.beginCommit() else { return } } + defer { nativeShutdownState?.endCommit() } // Ids are legally reusable after finish: drop the per-id capacity // requeue count on EVERY finish path (including the error-finish // that exhausted it), or a reused id inherits the previous @@ -3903,6 +5151,12 @@ public final class EngineLoopV2: @unchecked Sendable { return } let usage = takePrefixUsage(requestID: id, promptTokens: 0, completionTokens: 0) + if nativeShutdownState != nil, let stream = stream(for: id) { + retireStream( + id, matching: stream, + afterRetirement: { stream.finish(reason: reason, usage: usage) }) + return + } takeStream(id)?.finish(reason: reason, usage: usage) return } @@ -3912,6 +5166,17 @@ public final class EngineLoopV2: @unchecked Sendable { if holdsCompleteExportReservation { hybridPublication?.retiredReservation = completeCheckpointCapture?.codec.admission .detachReservation(id: id) + } else if nativeCompletePrefixContract != nil, let capture = completeCheckpointCapture { + // Even cancellation/no-donation keeps target C until actual row + // and prefix consumers retire. IDs cannot refund an older owner. + nativePrefixReservations[id] = capture.codec.admission.detachReservation(id: id) + } else if rectangularDenseBudget != nil || nativePagedBinding?.supportsSerialMTP == true, + nativeShutdownState != nil, + let admission = capacity as? AdmissionV2 + { + // Target scratch / actual paged MTP head promises must outlive + // finishRequest's row/step aliases. Keep the exact detached lease. + nativePrefixReservations[id] = admission.detachReservation(id: id) } else { capacity?.releaseAll(id: id) } @@ -3963,7 +5228,35 @@ public final class EngineLoopV2: @unchecked Sendable { let usesAsyncDetokenization = rec.request.stopStrings.isEmpty if !usesAsyncDetokenization { usage.timing = exportedTiming } // the ONE box let terminalQueue = detokQueue + let trackedLoop = nativeShutdownState == nil ? nil : self let terminalDelivery: () -> Void = { [usage, exportedTiming] in + if let trackedLoop { + // Stop-string flush can call an arbitrary host tokenizer too. + // Count/retain it, compute outside the outcome lock, then + // revalidate before terminal publication. No native fence. + trackedLoop.enqueueDetokenization(owner: detokenizer) { + let trailing = detokenizer?.flush() ?? "" + trackedLoop.engineQueue.async { + _ = trackedLoop.nativeCommit { + guard let currentStream = stream, + trackedLoop.completeNativeRetirement(id, matching: currentStream) + else { return } + if !trailing.isEmpty { + currentStream.emit( + .delta(text: trailing, tokens: [], logprobs: nil)) + } + var delivered = usage + if usesAsyncDetokenization { + var timing = exportedTiming + timing.detokDelayFirstNanos = currentStream.firstEmissionDelayNanos + delivered.timing = timing + } + currentStream.finish(reason: reason, usage: delivered) + } + } + } + return + } // Passthrough requests emit deltas on the detok queue; the // trailing flush + terminal MUST ride the same queue so they land // AFTER those deltas (FIFO ordering). Stop-string requests stay @@ -3971,7 +5264,7 @@ public final class EngineLoopV2: @unchecked Sendable { // stream (its own lock) at delivery time — after the deferred // first emit by FIFO — never from the scheduler record. if usesAsyncDetokenization { - terminalQueue.async { + let deliver: () -> Void = { let trailing = detokenizer?.flush() ?? "" if !trailing.isEmpty { stream?.emit(.delta(text: trailing, tokens: [], logprobs: nil)) @@ -3982,6 +5275,8 @@ public final class EngineLoopV2: @unchecked Sendable { delivered.timing = timing // the ONE box stream?.finish(reason: reason, usage: delivered) } + let handoff = CBv2Handoff(value: deliver) + terminalQueue.async { handoff.value() } } else { let trailing = detokenizer?.flush() ?? "" if !trailing.isEmpty { @@ -4014,30 +5309,37 @@ public final class EngineLoopV2: @unchecked Sendable { } else { ownershipReleaseDeferred = retire( state: state, donating: donation, hybridPublication: hybridPublication, + nativeRequestID: id, afterPublication: { [self] in - if let stream { retireStream(id, matching: stream) } - terminalDelivery() + finishAfterCompletePrefixPublication( + id, ownership: stream, terminal: terminalDelivery) }) releaseRecurrentState(recurrentStates.removeValue(forKey: id)) } } else { releaseRecurrentState(recurrentStates.removeValue(forKey: id)) - if holdsCompleteExportReservation { + if holdsCompleteExportReservation || nativePrefixReservations[id] != nil { ownershipReleaseDeferred = retire( state: [], donating: nil, hybridPublication: hybridPublication, + nativeRequestID: id, afterPublication: { [self] in - if let stream { retireStream(id, matching: stream) } - terminalDelivery() + finishAfterCompletePrefixPublication( + id, ownership: stream, terminal: terminalDelivery) }) } } - if !ownershipReleaseDeferred, let stream { - retireStream(id, matching: stream) - } if !ownershipReleaseDeferred { - terminalDelivery() + if nativeShutdownState != nil, let stream { + retireStream( + id, matching: stream, afterRetirement: terminalDelivery, + waitsForTerminalConsumer: true) + } else { + if let stream { retireStream(id, matching: stream) } + terminalDelivery() + } } + if nativeRetirementGroupDepth == 0 { releaseCompletedNativeRetiredRows() } } // MARK: Prefix-cache donation (engine thread → donation queue) @@ -4087,8 +5389,26 @@ public final class EngineLoopV2: @unchecked Sendable { private func retire( state: [CBv2SequenceKV?], donating donation: CBv2DonationIntent?, hybridPublication: CBv2DonationIntent? = nil, + nativeRequestID: CBv2RequestID? = nil, afterPublication: @escaping () -> Void = {} ) -> Bool { + if nativeCompletePrefixContract != nil, let nativeRequestID { + let retired = CBv2NativeCompletePrefixRetiredRows( + requestID: nativeRequestID, state: state, intent: hybridPublication, + reservation: nativePrefixReservations.removeValue(forKey: nativeRequestID), + completion: afterPublication) + nativePrefixRetiredRows[retired.id] = retired + // Publication begins only after the OUTER completed native group. + // Its callback, not this stack, authorizes stream/shared C retirement. + return true + } + if nativeShutdownState != nil, let nativeRequestID { + // The tracked profile has no publication consumers. Keep actual + // row objects AND their backend charge through the whole completed + // eval group, including mixed-MTP and nested error finalization. + nativeRetiredRowOwners[nativeRequestID, default: []].append(state) + return false + } if let capture = completeCheckpointCapture, let intent = hybridPublication { pendingDonationReleaseCount += 1 let retired = CBv2CompleteCheckpointRetiredState(state: state) @@ -4322,6 +5642,7 @@ public final class EngineLoopV2: @unchecked Sendable { // MARK: Boundary housekeeping private func processCancellations(now: ContinuousClock.Instant) { + guard nativeShutdownState?.mayExecute != false else { return } stateLock.lock() let cancels = pendingCancels stateLock.unlock() @@ -4443,6 +5764,7 @@ public final class EngineLoopV2: @unchecked Sendable { /// preempted row awaiting re-admission is bounded only by the absolute /// safety ceiling, never faulted as a stall. private func processLeaseExpiry(now: ContinuousClock.Instant) { + guard nativeShutdownState?.mayExecute != false else { return } var expired: [(CBv2RequestID, CBv2TerminalCause)] = [] for rec in scheduler.running { if let cause = leasesByID[rec.id]?.expiredCause( @@ -4482,6 +5804,8 @@ public final class EngineLoopV2: @unchecked Sendable { } private func handlePreemptions(_ ids: [CBv2RequestID], now: ContinuousClock.Instant) { + if let tracking = nativeShutdownState { guard tracking.beginCommit() else { return } } + defer { nativeShutdownState?.endCommit() } // Preemption only happens on the non-chained path, where the // previous step was finalized first — no in-flight step can // reference these states, so the release is immediate. The @@ -4522,6 +5846,11 @@ public final class EngineLoopV2: @unchecked Sendable { /// for room. Bounded by `maxCapacityRequeues` (then error-finish) and by /// the request deadline. Other failures error-finish as before. func ensureKVState(_ rec: CBv2ScheduledRequest) -> [CBv2SequenceKV?]? { + if nativePagedBinding != nil { return ensureIssuedNativePagedKVState(rec) } + // The authorized contiguous backend creates lazy empty row objects + // here, not an evaluated graph. Keep admission/refund metadata atomic. + if let tracking = nativeShutdownState { guard tracking.beginCommit() else { return nil } } + defer { nativeShutdownState?.endCommit() } if let state = kvStates[rec.id] { return state } do { let maxLength = rec.request.promptTokens.count + max(rec.request.maxTokens, 1) @@ -4587,6 +5916,84 @@ public final class EngineLoopV2: @unchecked Sendable { } } + /// Page growth evaluates real native storage; unlike contiguous lazy-row + /// creation it must run OUTSIDE beginCommit and retain partial results. + private func ensureIssuedNativePagedKVState(_ rec: CBv2ScheduledRequest) -> [CBv2SequenceKV?]? { + guard let binding = nativePagedBinding, let tracking = nativeShutdownState else { + return nil + } + if let state = kvStates[rec.id] { return state } + var operation: CBv2NativePagedOperation? + do { + let held = try binding.beginWork(requests: [rec.id]) + operation = held + let maxLength = rec.request.promptTokens.count + max(rec.request.maxTokens, 1) + let state = try held.withConstruction { + try backend.makeSequenceState( + layerKinds: layerKinds, + promptLength: rec.tokens.count, maxLength: maxLength) + } + // Backend registered and retained actual rows before returning. + try held.requiredDrain() + guard tracking.beginCommit() else { return nil } + defer { tracking.endCommit() } + kvStates[rec.id] = state + capacityRequeues.removeValue(forKey: rec.id) + rec.stampKVAllocated( + nowNanos: launchClockNanos != 0 + ? launchClockNanos : DispatchTime.now().uptimeNanoseconds) + held.enqueueRetirement { held.finish() } + return state + } catch let kvError as CBv2KVError { + guard tracking.mayExecute else { return nil } + if let operation { operation.enqueueRetirement { operation.finish(unstarted: true) } } + guard tracking.beginCommit() else { return nil } + defer { tracking.endCommit() } + if case .capacityExhausted = kvError { + let attempts = capacityRequeues[rec.id, default: 0] + if attempts < Self.maxCapacityRequeues, scheduler.requeueOnCapacity(rec.id) { + capacityRequeues[rec.id] = attempts + 1 + capacityRequeueCount += 1 + rec.timing.capacityRequeues &+= 1 + mtp?.invalidateCarry(rec.id) // preempted-style restart + // Preempted-style lease reset too: requeueOnCapacity + // rewound numComputedTokens to zero, so rewind the + // progress watermark and grant a fresh prefill window + // (admission stays permanently cleared). Without this a + // capacity wait longer than the prefill lease leaves the + // stale progress deadline expired and the newly + // re-admitted row is killed as .prefillStall before its + // first healthy chunk finalizes (PR#82 review). No + // pending finalize can include this row's sample here — + // it was being admitted this step, not running — so the + // rollback-path deferral does not apply. + if var lease = leasesByID[rec.id] { + lease.markPreempted(now: config.clock.now()) + leasesByID[rec.id] = lease + } + return nil + } + // Terminal capacity exhaustion is retryable (the backend is + // full, not broken): finish with the canonical prefix so + // bridges surface a capacity error, never a server error. + finishRequest( + rec.id, + reason: .error( + CBv2KVError.capacityExhaustedFinishPrefix + "\(kvError)")) + return nil + } + finishRequest(rec.id, reason: .error("KV allocation failed: \(kvError)")) + return nil + } catch { + guard tracking.mayExecute else { return nil } + if let operation { operation.enqueueRetirement { operation.finish(unstarted: true) } } + guard tracking.beginCommit() else { return nil } + defer { tracking.endCommit() } + finishRequest(rec.id, reason: .error("KV allocation failed: \(error)")) + return nil + } + } + private func makeRecurrentRequestState() throws -> CBv2RecurrentRequestState? { guard let spec = (model as? any CBv2RecurrentSteppableModel)?.recurrentStateSpec else { return nil @@ -4636,8 +6043,122 @@ public final class EngineLoopV2: @unchecked Sendable { /// from removing a later generation if invariants are violated elsewhere. private func retireStream( _ id: CBv2RequestID, - matching expected: CBv2OutputStream + matching expected: CBv2OutputStream, + afterRetirement terminal: (() -> Void)? = nil, + waitsForTerminalConsumer: Bool = false ) { + if nativeShutdownState != nil { + if let index = nativePendingRetirements.firstIndex(where: { + $0.id == id && $0.stream === expected + }) { + if nativePendingRetirements[index].terminal == nil { + nativePendingRetirements[index].terminal = terminal + nativePendingRetirements[index].terminalIsConsumer = waitsForTerminalConsumer + } + } else { + nativePendingRetirements.append( + (id, expected, terminal, waitsForTerminalConsumer, false)) + } + guard !nativeRetirementAcknowledgementQueued else { return } + nativeRetirementAcknowledgementQueued = true + // The callback runs only after the current launch/finalize/error + // stack (including its temporary step/row aliases) has unwound. + engineQueue.async { [weak self] in self?.acknowledgeNativeRetirements() } + return + } + retireStreamImmediately(id, matching: expected) + terminal?() + } + + private func acknowledgeNativeRetirements() { + nativeRetirementAcknowledgementQueued = false + guard let tracking = nativeShutdownState, tracking.mayExecute else { return } + nativeRetirementBoundaryForTesting?("beforeAcknowledgement", nil) + guard + tracking.commitIfHealthy({ + let ready = nativePendingRetirements.filter { pending in + scheduler.record(for: pending.id) == nil && kvStates[pending.id] == nil + && inFlight?.participants.contains(pending.id) != true + && nativeRetiredRowOwners[pending.id] == nil + && nativePrefixPendingByRequest[pending.id] == nil + && pendingMiMoKeyRangeByRequest[pending.id] == nil + && pendingNativePagedByRequest[pending.id] == nil + && !nativePrefixRetiredRows.values.contains(where: { + $0.requestID == pending.id + }) + && !pending.terminalStarted + } + guard !ready.isEmpty else { return } + // The previous eager binding can retain retired rows after backend + // accounting is zero. This is metadata-only unbinding, not a fence + // or model operation. Already-submitted live-row graphs retain + // their own evaluation targets; the next eager use rebinds normally. + (cacheProvider as? CBv2CompositionInvalidating)?.releaseBoundRows() + for entry in ready { + if entry.terminalIsConsumer { + if let index = nativePendingRetirements.firstIndex(where: { + $0.id == entry.id && $0.stream === entry.stream + }) { + nativePendingRetirements[index].terminalStarted = true + } + // Scheduling/loan registration only. The actual host flush + // occurs on detokQueue, then atomically acknowledges and + // publishes while healthy. Keep this stream reachable by + // the watchdog until that consumer completes. + } else { + _ = completeNativeRetirement(entry.id, matching: entry.stream) + } + entry.terminal?() + } + }) + else { return } + // May fence at a true shutdown boundary; never under the commit lock. + completeDrainIfReady() + } + + /// Caller is on the engine queue and holds the healthy first-winner commit. + /// The host terminal consumer dispatches publication back here after flush; + /// its counted loan is not released until the following queued callback. + private func completeNativeRetirement(_ id: CBv2RequestID, matching expected: CBv2OutputStream) + -> Bool + { + guard nativePendingRetirements.contains(where: { $0.id == id && $0.stream === expected }) + else { return false } + nativePendingRetirements.removeAll { $0.id == id && $0.stream === expected } + if rectangularDenseBudget != nil || nativePagedBinding?.supportsSerialMTP == true, + nativeCompletePrefixContract == nil + { + // Same queued boundary already proved no in-flight step, retired + // row roots or bound-cache aliases for this exact stream generation. + // A failed required completion cannot enter this healthy commit. + nativePrefixReservations.removeValue(forKey: id)?.release() + } + retireStreamImmediately(id, matching: expected) + return true + } + + /// Called only after the outer completed group's root retirement (or a + /// no-in-flight request cleanup). Never release an outer error group's + /// owners from its nested previous-step finalizer. All callers hold the + /// healthy commit; no new native wait or model operation occurs here. + private func releaseCompletedNativeRetiredRows() { + guard nativeShutdownState?.mayExecute == true, nativeRetirementGroupDepth <= 1 else { + return + } + let retired = nativeRetiredRowOwners + nativeRetiredRowOwners = [:] + for states in retired.values { + for state in states { backend.release(state) } + } + // This local dictionary/its row aliases die before the separate + // queue acknowledgement can release the host's shared C wait. + for entry in nativePrefixRetiredRows.values where !entry.started { + entry.started = true + beginNativeCompletePrefixRetirement(entry) + } + } + + private func retireStreamImmediately(_ id: CBv2RequestID, matching expected: CBv2OutputStream) { stateLock.lock() let retired: CBv2OutputStream? if streams[id] === expected { @@ -4647,7 +6168,17 @@ public final class EngineLoopV2: @unchecked Sendable { retired = nil } stateLock.unlock() - retired?.releaseEngineOwnership() + if let retired, + let token = nativePreparedMedia.values.first(where: { $0.stream === retired }) + { + // Called from a short first-winner commit. Defer host accounting + // and alias destruction until that frame/lock has unwound. + engineQueue.async { [self, token, retired] in + finishPreparedMedia(token, acknowledging: retired) + } + } else { + retired?.releaseEngineOwnership() + } } // MARK: Reconciled-usage snapshots (watchdog-readable) @@ -4733,7 +6264,9 @@ public final class EngineLoopV2: @unchecked Sendable { stepsExecuted: stepCount, stepWallNanosTotal: stepWallNanosTotal, decodeRowsTotal: decodeRowsTotal, - pagedStorage: (backend as? PagedKVBackend)?.pool.segmentStorageSnapshot)) + pagedStorage: (backend as? PagedKVBackend)?.pool.segmentStorageSnapshot, + hasUnmeasuredAssistantResidency: mtp?.hasUnmeasuredAssistantResidency( + detachedStates: detachedAssistantStates) ?? false)) } static func saturatingAdd(_ lhs: Int, _ rhs: Int) -> Int { @@ -4766,10 +6299,11 @@ public final class EngineLoopV2: @unchecked Sendable { } private func markStepEnded() { + let nativeIncomplete = nativeShutdownState?.isIncomplete == true stateLock.lock() stepStartedNanos = 0 wedgeReported = false - _healthy = true + _healthy = !nativeIncomplete stateLock.unlock() } @@ -4830,6 +6364,7 @@ public final class EngineLoopV2: @unchecked Sendable { // Signal BEFORE erroring the streams: a consumer woken by the // terminal event must be able to observe the wedge side effects // (health metric, telemetry) immediately. + _ = nativeShutdownState?.fail(.stepWatchdog) onStepWedge?(elapsed) let message = "engine step exceeded \(Int(config.stepTimeout))s watchdog" for (id, stream) in liveStreams { diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift index ab4d6daea4..13a954e7df 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift @@ -33,8 +33,10 @@ final class CBv2EngineGauges: @unchecked Sendable { private var snapshot: CBv2CapacitySnapshot private var pendingSubmits = 0 - init(kvBytesCapacity: Int, kvBytesBackendCapacity: Int = 0, kvBytesReserved: Int = 0, - pagedStorage: PagedKVStorageSnapshot? = nil) { + init( + kvBytesCapacity: Int, kvBytesBackendCapacity: Int = 0, kvBytesReserved: Int = 0, + pagedStorage: PagedKVStorageSnapshot? = nil + ) { // Seed backend truth at construction: heartbeats read `capacity()` // on IDLE engines (zero steps published), and a paged slot must // report its pool ceiling from the first beat, not after the @@ -76,6 +78,8 @@ final class CBv2EngineGauges: @unchecked Sendable { lock.unlock() } + var hasPendingSubmissions: Bool { lock.withLock { pendingSubmits != 0 } } + /// Point update for runtime KV-capacity changes: an idle engine /// publishes no step snapshots, so `capacity()` must reflect a /// re-sliced ceiling and the backend's post-resize truth — @@ -112,9 +116,34 @@ final class CBv2EngineGauges: @unchecked Sendable { /// (lock + queue hop), resident-prefix preflight (index lock, advisory only), /// `cancel` (lock), `capacity()` (lock), and `shutdown()` /// (queue-synchronized drain). -public final class EngineV2: CBv2Engine, @unchecked Sendable { +public final class EngineV2: CBv2Engine, CBv2NativeWorkShutdownReporting, @unchecked Sendable { + public let nativeShutdownEngineID: UUID + /// Nil for untracked engines; metadata only, available before shutdown so + /// a host can reject foreign registration without draining that engine. + public var nativeShutdownExecutionContractID: UUID? { nativeShutdownState?.contractID } + /// A sealed failure only, never a positive drain/refund assertion. Allows + /// the existing host fault registry to refuse other native admissions + /// immediately after a failed warm preparation, without another fence. + public var nativeCompletionFault: CBv2NativeShutdownFault? { + if case .incomplete(let fault)? = nativeShutdownState?.outcome { return fault } + return nil + } + private let nativeShutdownState: CBv2NativeShutdownState? + /// Module-only read-only tracking presence for split checkpoint extensions. + /// Contract ID alone is insufficient: an unsupported tracked engine may + /// have no issued ID and still must reject untracked checkpoint consumers. + var hasNativeCompletionTracking: Bool { nativeShutdownState != nil } + private let issuedNativeExecutionContract: CBv2NativeExecutionContract? private let loop: EngineLoopV2 private let admission: AdmissionV2 + + /// Reports the actual admission owner, not a provider capability marker. + public var usesProcessMemoryOwner: Bool { admission.hasProcessMemoryOwner } + + /// Exact identity is required before delegating the bridge's request charge. + public func usesProcessMemoryOwner(_ expected: any CBv2ProcessMemoryOwner) -> Bool { + admission.usesProcessMemoryOwner(expected) + } /// Retained for runtime KV re-slicing (`updateKVBytesCapacity`); all /// step-path access goes through the loop. private let backend: CBv2KVBackend @@ -140,10 +169,21 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { public let completePrefixCache: (any CBv2CompletePrefixCache)? let completeCheckpointCodec: CBv2CompleteCheckpointCodec? let completeCheckpointCapture: CBv2CompleteCheckpointCapture? + private let nativeCompletePrefixContract: CBv2NativeExecutionContract? /// Exact fixed per-request charge after recurrent/MTP capability /// resolution. Shared/global budget bridges must use this value rather /// than recomputing the base recurrent peak from the model spec. public let resolvedFixedBytesPerRequest: Int + /// Nil preserves the legacy drafter accounting contract. A bounded value + /// replaces ONLY its inferred variable term; its fixed amount is already + /// included above. Providers must consume this same resolution. + public let resolvedMTPAdmission: CBv2MTPAdmissionResolution? + /// Metadata only, not completed grouped-kernel execution or memory credit. + private let rectangularDenseBudget: MiMoV26RectangularDenseBudget? + package var rectangularDenseSubmittedCalls: Int { rectangularDenseBudget?.submittedCalls ?? 0 } + package let rectangularDenseScratchBytes: Int + public let groupedPrefillScratchBytes: Int + public let groupedPrefillInactiveReason: String? private let stateLock = NSLock() private var rejectingSubmissions = false @@ -194,6 +234,20 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { /// Construction-time reason MTP is inactive. nil means the driver is /// active. Providers can surface this alongside the nil metrics snapshot. public let mtpInactiveReason: String? + /// Source-only step-owned paging stays opt-in; refusal is recoverable at + /// submit and available to the production assembler before publication. + public var pagedAttentionWorkInactiveReason: String? { + guard let pool = (backend as? PagedKVBackend)?.pool, pool.usesStepOwnedAttention else { + return nil + } + return pool.attentionWorkEngineRefusal + } + public var pagedAttentionWorkBytesReserved: Int { + guard let pool = (backend as? PagedKVBackend)?.pool, pool.usesStepOwnedAttention else { + return 0 + } + return pool.attentionWorkBytesReserved + } /// Internal test hook (engine-queue synchronized). var loopForTesting: EngineLoopV2 { loop } /// Internal test hook: the admission ledger, for asserting byte @@ -215,9 +269,18 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { completePrefixCache: (any CBv2CompletePrefixCache)? = nil, mtpDrafter: (any CBv2MTPDrafter)? = nil, mtpConfig: CBv2MTPConfig = CBv2MTPConfig(), - processMemoryOwner: (any CBv2ProcessMemoryOwner)? = nil + processMemoryOwner: (any CBv2ProcessMemoryOwner)? = nil, + nativeCompletionTracking: Bool = false, + nativeExecutionContract: CBv2NativeExecutionContract? = nil, + automaticMiMoPrefill: Bool = false ) { - self.schedulerConfig = schedulerConfig + // Explicit SDK scheduler choices stay unchanged unless the native + // factory requests this optional default profile. Commit a wider copy + // only after repricing and genuine budget installation below. + var schedulerConfig = schedulerConfig + let nativeID = UUID() + self.nativeShutdownEngineID = nativeID + self.issuedNativeExecutionContract = nativeExecutionContract self.loopConfig = loopConfig self.layerKinds = layerKinds self.requiredPositionAxisCount = @@ -271,7 +334,36 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { mtpDriver = nil } + // One construction-time metadata read for the explicit new codec. + // This does not enable a model, backend or store by default. + let contiguousCheckpointTypes: [DType]? = { + guard schedulerConfig.enablePrefixCache, completePrefixCache != nil, + layerKinds.contains(where: { $0.headDim != $0.valueHeadDim }), + backend is any CBv2ContiguousHistoricalBackend, + mtpDriver == nil + || (mtpDriver?.tracksPersistentHistory == true + && mtpDriver?.drafter is any CBv2HistoricalMTPPrefixCheckpointCoding), + (model as? any CBv2HistoricalAttentionCheckpointProviding)? + .cbv2SupportsHistoricalAttentionCheckpoint == true, + (model as? any CBv2RecurrentSteppableModel)?.recurrentStateSpec == nil, + let types = (model as? any CBv2CompleteCheckpointKVTypeProviding)? + .cbv2CompleteCheckpointKVDTypes, + (try? CBv2HistoricalAttentionLayout( + layerKinds: layerKinds, dtypes: types, allowAsymmetric: true)) != nil + else { return nil } + return types + }() var admissionConfig = admissionConfig + if let types = contiguousCheckpointTypes { + let requested = admissionConfig.layerElementBytes + let requestedDefault = admissionConfig.elementBytes + admissionConfig.layerElementBytes = types.enumerated().map { i, dtype in + // Native storage can raise an underspecified two-byte ledger; + // never reduce a caller's conservative existing byte reserve. + let old = requested?.count == types.count ? requested![i] : requestedDefault + return max(old, dtype.size) + } + } if let paged = backend as? PagedKVBackend { // Native storage and the token ledger consume the same resolved // table, including mixed BF16/FP32 layers after RoPE promotion. @@ -279,30 +371,48 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { } // Capture allocator policy once, outside Admission. Failed projection // makes capacity unavailable instead of admitting logical-only bytes. + let fixedTargetOnly = + mtpDriver?.config.fixedDraftTokens == 0 + || mtpDriver?.config.maxDraftTokens == 0 + let boundedDrafter = + fixedTargetOnly + ? nil + : (mtpDriver?.drafter as? any CBv2MTPBoundedAllocationProviding) + let callerFixedBytes = admissionConfig.fixedBytesPerRequest let pricesAllocatorFootprints = (backend as? PagedKVBackend)?.pool.segmentGrant != nil - let allocationPolicy = pricesAllocatorFootprints ? Memory.allocationFootprintPolicy() : nil + // The bounded contract always prices independent allocations, including + // the actual contiguous backend. Legacy drafters do not add a query. + let allocationPolicy = + (pricesAllocatorFootprints || boundedDrafter != nil) + ? Memory.allocationFootprintPolicy() : nil if pricesAllocatorFootprints && allocationPolicy == nil { admissionConfig.fixedBytesPerRequest = Int.max } else if let recurrent = (model as? any CBv2RecurrentSteppableModel)?.recurrentStateSpec { let perGeneration: Int if let allocationPolicy { - perGeneration = (try? recurrent.allocationBytesPerGeneration(policy: allocationPolicy)) ?? Int.max + perGeneration = + (try? recurrent.allocationBytesPerGeneration(policy: allocationPolicy)) + ?? Int.max } else { perGeneration = (try? recurrent.fixedBytesPerRequest()) ?? Int.max } let usesCompactRectangularReplay = modelCapabilities.supportsCompactRecurrentMTPReplay && (mtpDriver.map { $0.config.verificationMode != .serialTarget } ?? false) - let recurrentDepth = mtpDriver?.config.fixedDraftTokens ?? mtpDriver?.config.maxDraftTokens ?? 0 + let recurrentDepth = + mtpDriver?.config.fixedDraftTokens ?? mtpDriver?.config.maxDraftTokens ?? 0 let compactContinuationHeadroom = usesCompactRectangularReplay && recurrentDepth >= 2 - let capturedContinuationHeadroom = !usesCompactRectangularReplay && recurrentDepth > 0 + let capturedContinuationHeadroom = + !usesCompactRectangularReplay && recurrentDepth > 0 && mtpDriver?.config.verificationMode != .serialTarget - && (model as? any CBv2RecurrentMTPSteppableModel)?.supportsCapturedVerifyWindow == true + && (model as? any CBv2RecurrentMTPSteppableModel)?.supportsCapturedVerifyWindow + == true let extraGenerations: Int if compactContinuationHeadroom { // One strict-prefix tape can survive into its successor. extraGenerations = 1 - } else if mtpDriver?.usesRequestStatefulDrafter == true && !usesCompactRectangularReplay { + } else if mtpDriver?.usesRequestStatefulDrafter == true && !usesCompactRectangularReplay + { // The base three generations cover seed plus depth one. extraGenerations = max(0, recurrentDepth - 1) } else { @@ -323,26 +433,52 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { } let (bytes, byteOverflow) = perGeneration.multipliedReportingOverflow(by: generations) admissionConfig.fixedBytesPerRequest = countOverflow || byteOverflow ? Int.max : bytes + if boundedDrafter != nil { + // Keep caller-owned fixed state as well as the resolved target + // recurrence generations. No old-drafter behavior changes. + admissionConfig.fixedBytesPerRequest = + CBv2MTPBoundedAdmission.add( + admissionConfig.fixedBytesPerRequest, callerFixedBytes) ?? Int.max + } } - let fixedTargetOnly = - mtpDriver?.config.fixedDraftTokens == 0 - || mtpDriver?.config.maxDraftTokens == 0 - admissionConfig.auxiliaryBytesPerToken = - fixedTargetOnly ? 0 : (mtpDriver?.drafter.requestStateBytesPerToken ?? 0) - admissionConfig.auxiliaryTokenGranularity = - fixedTargetOnly ? 1 : (mtpDriver?.drafter.requestStateTokenGranularity ?? 1) - admissionConfig.auxiliaryTokenAllocationPadding = - fixedTargetOnly ? 0 : (mtpDriver?.drafter.requestStateTokenAllocationPadding ?? 0) - if let allocationPolicy, admissionConfig.auxiliaryBytesPerToken > 0 { + var boundedResolution: CBv2MTPAdmissionResolution? + if let boundedDrafter { + // SchedulerV2.config is an immutable value copy. Neither runtime + // KV re-slicing nor the optional mixed-step cap can grow this work + // budget. Larger max-batched/solo stripes require engine rebuild. + let limits = CBv2MTPAllocationLimits( + maximumPrefillTokens: max( + schedulerConfig.maxBatchedTokensPerStep, + schedulerConfig.soloPrefillStripeTokens ?? 0), + maximumDraftTokens: mtpDriver?.config.fixedDraftTokens + ?? mtpDriver?.config.maxDraftTokens ?? 0) + let resolution = CBv2MTPBoundedAdmission.resolve( + spec: boundedDrafter.boundedRequestAllocation(limits: limits), + limits: limits, policy: allocationPolicy) + boundedResolution = CBv2MTPBoundedAdmission.apply(resolution, to: &admissionConfig) + CBv2MTPBoundedAdmission.preserveCallerProjectionForTarget( + model: model, config: &admissionConfig) + } else { + admissionConfig.auxiliaryBytesPerToken = + fixedTargetOnly ? 0 : (mtpDriver?.drafter.requestStateBytesPerToken ?? 0) + admissionConfig.auxiliaryTokenGranularity = + fixedTargetOnly ? 1 : (mtpDriver?.drafter.requestStateTokenGranularity ?? 1) + admissionConfig.auxiliaryTokenAllocationPadding = + fixedTargetOnly ? 0 : (mtpDriver?.drafter.requestStateTokenAllocationPadding ?? 0) + } + if boundedDrafter == nil, let allocationPolicy, admissionConfig.auxiliaryBytesPerToken > 0 { // Unknown stateful drafters get the conservative one-byte fragmented // envelope until they declare their independent allocation geometry. - let specs = mtpDriver?.drafter.requestStateAllocationSpecs ?? [ - CBv2AuxiliaryAllocationSpec( - bytesPerToken: 1, allocationCount: admissionConfig.auxiliaryBytesPerToken, - tokenGranularity: admissionConfig.auxiliaryTokenGranularity, - tokenPadding: admissionConfig.auxiliaryTokenAllocationPadding, partitioned: true) - ] - if let projection = CBv2AuxiliaryAllocationProjection(policy: allocationPolicy, buffers: specs), + let specs = + mtpDriver?.drafter.requestStateAllocationSpecs ?? [ + CBv2AuxiliaryAllocationSpec( + bytesPerToken: 1, allocationCount: admissionConfig.auxiliaryBytesPerToken, + tokenGranularity: admissionConfig.auxiliaryTokenGranularity, + tokenPadding: admissionConfig.auxiliaryTokenAllocationPadding, + partitioned: true) + ] + if let projection = CBv2AuxiliaryAllocationProjection( + policy: allocationPolicy, buffers: specs), !specs.isEmpty { admissionConfig.auxiliaryAllocationProjection = projection @@ -352,7 +488,142 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { } CBv2TargetAuxiliaryAdmission.apply( model: model, config: &admissionConfig, policy: allocationPolicy, - draftSpecs: fixedTargetOnly ? [] : mtpDriver?.drafter.requestStateAllocationSpecs) + draftSpecs: boundedDrafter != nil + ? nil + : (fixedTargetOnly ? [] : mtpDriver?.drafter.requestStateAllocationSpecs)) + // Optional grouping uses the same admission and exact cache owner. + // Wider defaults are tentative scalar copies until the final install; + // every refusal retains the original scheduler and all original charges. + var blockBatchBudget: MiMoV26BlockBatchBudget? + var blockBatchReason: String? = "not_requested" + if MiMoV26BlockBatchAttention.requested { + blockBatchReason = "unsupported_model_or_policy" + if MiMoV26NAXAttention.requested, CBv2AttentionV1.queryBlockSize == 128, + let owner = model as? any MiMoV26BlockBatchAllocatingModel, + let layers = owner.cbv2MiMoBlockBatchLayerCount + { + blockBatchReason = "unsupported_device" + if MiMoV26NAXGatherQMM.gpuStream(.default), MiMoV26NAXGatherQMM.naxAvailable { + blockBatchReason = "unavailable_scratch_bound" + if let policy = allocationPolicy ?? Memory.allocationFootprintPolicy() { + let originalWidth = max( + schedulerConfig.prefillChunkSize, + max( + schedulerConfig.maxBatchedTokensPerStep, + schedulerConfig.soloPrefillStripeTokens ?? 0)) + // Paging/checkpoint profiles keep their issued envelope. + // A genuine managed-media engine may widen TEXT requests; + // its actual media requests retain their previous stripe + // through the shared scheduler/projection ceiling below. + let mayWiden = + automaticMiMoPrefill && nativeExecutionContract != nil + && !(backend is PagedKVBackend) + && !schedulerConfig.enablePrefixCache && prefixCache == nil + && hybridPrefixCache == nil && completePrefixCache == nil + && (mtpDriver == nil || fixedTargetOnly || boundedDrafter != nil) + let maximum = (model as? any MiMoV26PrefillDefaultProviding)? + .cbv2MiMoAutomaticPrefillMaximumTokens + let wider = MiMoV26PrefillPolicy.widerWidths( + requested: mayWiden, naxAvailable: true, + physicalMemoryBytes: ProcessInfo.processInfo.physicalMemory, + maximumTokens: maximum, originalWidth: originalWidth) + for width in wider + [originalWidth] { + var candidateScheduler = schedulerConfig + var candidateAdmission = admissionConfig + var candidateResolution = boundedResolution + if width > originalWidth { + candidateScheduler.soloPrefillStripeTokens = width + if let boundedDrafter { + guard case .bounded(let previous)? = boundedResolution else { + continue + } + let limits = CBv2MTPAllocationLimits( + maximumPrefillTokens: max( + candidateScheduler.maxBatchedTokensPerStep, + candidateScheduler.soloPrefillStripeTokens ?? 0), + maximumDraftTokens: mtpDriver?.config.fixedDraftTokens + ?? mtpDriver?.config.maxDraftTokens ?? 0) + let resolution = CBv2MTPBoundedAdmission.resolve( + spec: boundedDrafter.boundedRequestAllocation( + limits: limits), + limits: limits, policy: allocationPolicy) + guard case .bounded(let replacement) = resolution, + let fixed = MiMoV26PrefillPolicy.replacingMTPCharge( + current: candidateAdmission.fixedBytesPerRequest, + previous: previous.fixedBytesPerRequest, + replacement: replacement.fixedBytesPerRequest) + else { continue } + candidateAdmission.fixedBytesPerRequest = fixed + candidateResolution = resolution + } + } + guard + let candidate = try? MiMoV26BlockBatchBudget( + engineID: nativeID, + model: model, backend: backend, cacheProvider: cacheProvider, + maximumQueries: width, layerCount: layers, policy: policy), + let charged = MiMoV26PrefillPolicy.addingGroupedCharge( + to: candidateAdmission, + scratchBytes: candidate.fixedRequestBytes, + capacityBytes: backend.bytesCapacity) + else { continue } + guard owner.cbv2TryInstallBlockBatchBudget(candidate) else { + blockBatchReason = "unassociated_or_already_bound_resources" + break + } + if width > originalWidth { + // Install succeeded. Capture the actual previous + // media policy, including nil/plain and an existing + // stricter ceiling, before publishing the text width. + candidateScheduler.soloPrefillStripeMediaCeiling = + schedulerConfig.resolvedSoloPrefillStripeTokens( + isMultimodal: true) + ?? schedulerConfig.prefillChunkSize + } + schedulerConfig = candidateScheduler + admissionConfig = charged + boundedResolution = candidateResolution + blockBatchBudget = candidate + blockBatchReason = nil + break + } + } + } + } + } + self.schedulerConfig = schedulerConfig + // MiMo target-only EXTRA scratch is independent of the assistant bound. + // Charge every request conservatively; only a real admitted verification + // scope can use it. Direct adapters/untracked engines remain unarmed. + var rectangularDenseBudget: MiMoV26RectangularDenseBudget? + if nativeCompletionTracking, + mtpDriver?.config.verificationMode == .rectangular, + nativeExecutionContract?.mtpVerificationMode == .rectangular, + let owner = model as? any MiMoV26RectangularDenseAllocatingModel, + let spec = owner.cbv2MiMoRectangularDenseScratch, + let policy = allocationPolicy ?? Memory.allocationFootprintPolicy(), + let candidate = try? MiMoV26RectangularDenseBudget( + engineID: nativeID, + model: model, backend: backend, cacheProvider: cacheProvider, + spec: spec, policy: policy), + let total = CBv2MTPBoundedAdmission.add( + admissionConfig.fixedBytesPerRequest, + candidate.fixedRequestBytes), + total < backend.bytesCapacity + { + admissionConfig.fixedBytesPerRequest = total + rectangularDenseBudget = candidate + } + self.rectangularDenseBudget = rectangularDenseBudget + self.rectangularDenseScratchBytes = rectangularDenseBudget?.fixedRequestBytes ?? 0 + self.groupedPrefillScratchBytes = blockBatchBudget?.fixedRequestBytes ?? 0 + self.groupedPrefillInactiveReason = blockBatchReason + if boundedResolution != nil, admissionConfig.fixedBytesPerRequest == Int.max { + if case .bounded? = boundedResolution { + boundedResolution = .unavailable(.chargeOverflow) + } + } + self.resolvedMTPAdmission = boundedResolution self.resolvedFixedBytesPerRequest = admissionConfig.fixedBytesPerRequest let admission = AdmissionV2( layerKinds: layerKinds, bytesCapacity: backend.bytesCapacity, @@ -360,9 +631,57 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { processMemoryOwner: processMemoryOwner) self.admission = admission let segmentedPool = (backend as? PagedKVBackend)?.pool + let nativePagedSerialMTP = + nativeCompletionTracking + && nativeExecutionContract?.supportsNativePagedSerialMTP == true + && (backend as? PagedKVBackend)?.nativeModelBinding?.supportsSerialMTP == true + && mtpDriver?.config.verificationMode == .serialTarget + && mtpConfig.verificationMode == .serialTarget + && mtpConfig.maxSpeculativeBatch == 1 && (1 ... 3).contains(mtpConfig.maxDraftTokens) + let nativePagedPrefixBinding: CBv2NativePagedModelBinding? = { + guard nativeCompletionTracking, schedulerConfig.enablePrefixCache, + nativeExecutionContract?.supportsNativePagedTarget == true, + nativeExecutionContract?.supportsNativeCompletePrefix == true, + mtpDrafter == nil || nativePagedSerialMTP, + let store = completePrefixCache as? any CBv2NativeCompletePrefixCache, + let binding = (backend as? PagedKVBackend)?.nativeModelBinding + else { return nil } + do { + try binding.validateCompletePrefix( + store: store, identity: store.identity, + assistant: mtpDrafter.map { $0 as AnyObject }, + processMemoryOwner: processMemoryOwner) + return binding + } catch { return nil } + }() if segmentedPool?.segmentGrant != nil { segmentedPool?.bindAdmission(admission) } + if let pool = segmentedPool, pool.usesStepOwnedAttention { + let maximumQuery = max( + schedulerConfig.maxBatchedTokensPerStep, + schedulerConfig.soloPrefillStripeTokens ?? 0) + if processMemoryOwner == nil { + pool.attentionWorkEngineRefusal = + "step-owned paging requires a real native process-memory owner" + } else if let limits = pool.config.gatheredAttention, + schedulerConfig.maxConcurrentRequests <= limits.maximumBatchSize, + maximumQuery <= limits.maximumQueryTokens, + layerKinds.allSatisfy({ $0.headDim != $0.valueHeadDim }), + mtpDrafter == nil || nativePagedSerialMTP, + nativePagedPrefixBinding != nil + || (!schedulerConfig.enablePrefixCache && completePrefixCache == nil), + prefixCache == nil, hybridPrefixCache == nil, + pool.attentionWorkCaches.count == layerKinds.count + { + // Both scheduler envelopes are immutable copies. A larger + // batch/solo stripe requires rebuilding and re-resolving. + pool.attentionWorkEnginePrepared = pool.attentionWorkEngineRefusal == nil + } else { + pool.attentionWorkEngineRefusal = + "step-owned paging envelope/cache bank or MTP/prefix composition is unqualified" + } + } let gauges = CBv2EngineGauges( kvBytesCapacity: backend.bytesCapacity, kvBytesBackendCapacity: backend.bytesCapacity, @@ -400,14 +719,15 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { scheduler.reserveFullSequenceTokens = segmentedPool?.segmentGrant != nil if schedulerConfig.mixedStepPrefillTokenCap == nil, let raw = ProcessInfo.processInfo.environment[ - "DARKBLOOM_CBV2_MIXED_PREFILL_CAP"], + "DARKBLOOM_CBV2_MIXED_PREFILL_CAP"], let cap = Int(raw), cap >= 0 { scheduler.mixedStepPrefillTokenCap = cap log.info( "CBv2 mixed-step prefill cap: \(cap, privacy: .public) tokens") } - let fullRecurrentCheckpointEligible = modelCapabilities.supportsRecurrentCheckpointReuse + let fullRecurrentCheckpointEligible = + modelCapabilities.supportsRecurrentCheckpointReuse && (model as? any CBv2RecurrentSteppableModel)?.recurrentStateSpec != nil && !layerKinds.isEmpty && layerKinds.allSatisfy { kind in @@ -417,22 +737,26 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { && (!(mtpDriver?.tracksPersistentHistory ?? false) || mtpDriver?.drafter is any CBv2MTPPrefixCheckpointDrafter) && schedulerConfig.enablePrefixCache - let hybridEligible = fullRecurrentCheckpointEligible + let hybridEligible = + fullRecurrentCheckpointEligible && backend.prefixReuseBackend == .contiguousUnquantized && !backend.requiresMaterializedSnapshots let pagedCheckpointConfig = segmentedPool.flatMap { pool -> PagedKVPoolConfig? in guard pool.segmentGrant != nil, pool.config.layerDTypes != nil else { return nil } return pool.config } - self.hybridPrefixCache = hybridEligible + self.hybridPrefixCache = + hybridEligible ? hybridPrefixCache.flatMap { $0.isValid ? CBv2HybridPrefixCache(config: $0) : nil } : nil if fullRecurrentCheckpointEligible, hybridEligible || pagedCheckpointConfig != nil, let completePrefixCache, let recurrentSpec = (model as? any CBv2RecurrentSteppableModel)?.recurrentStateSpec, - let kvDTypes = (model as? any CBv2CompleteCheckpointKVTypeProviding)?.cbv2CompleteCheckpointKVDTypes, + let kvDTypes = (model as? any CBv2CompleteCheckpointKVTypeProviding)? + .cbv2CompleteCheckpointKVDTypes, kvDTypes.count == layerKinds.count, - let qwen4Geometries = Self.checkpointQwen4Geometries(model: model, layerKinds: layerKinds), + let qwen4Geometries = Self.checkpointQwen4Geometries( + model: model, layerKinds: layerKinds), pagedCheckpointConfig == nil || kvDTypes == segmentedPool?.layerDTypes, !(mtpDriver?.tracksPersistentHistory ?? false) || mtpDriver?.drafter is any CBv2MTPPrefixCheckpointCoding @@ -442,15 +766,41 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { recurrentSpec: recurrentSpec, kvDTypes: kvDTypes, assistant: mtpDriver?.tracksPersistentHistory == true ? mtpDriver?.drafter as? any CBv2MTPPrefixCheckpointCoding : nil, - admission: admission, pagedConfig: pagedCheckpointConfig, qwen4Geometries: qwen4Geometries) + admission: admission, pagedConfig: pagedCheckpointConfig, + qwen4Geometries: qwen4Geometries) + self.completePrefixCache = completePrefixCache + self.completeCheckpointCodec = codec + self.completeCheckpointCapture = .init(codec: codec, store: completePrefixCache) + } else if let types = contiguousCheckpointTypes, let completePrefixCache { + let codec = CBv2CompleteCheckpointCodec( + identity: completePrefixCache.identity, layerKinds: layerKinds, + recurrentSpec: nil, kvDTypes: types, + assistant: mtpDriver?.tracksPersistentHistory == true + ? mtpDriver?.drafter as? any CBv2HistoricalMTPPrefixCheckpointCoding : nil, + admission: admission) + self.completePrefixCache = completePrefixCache + self.completeCheckpointCodec = codec + self.completeCheckpointCapture = .init(codec: codec, store: completePrefixCache) + } else if let nativePagedPrefixBinding, let completePrefixCache, + let pagedCheckpointConfig, let segmentedPool + { + let codec = CBv2CompleteCheckpointCodec( + identity: completePrefixCache.identity, + layerKinds: layerKinds, recurrentSpec: nil, kvDTypes: segmentedPool.layerDTypes, + assistant: mtpDriver?.tracksPersistentHistory == true + ? mtpDriver?.drafter as? any CBv2HistoricalMTPPrefixCheckpointCoding : nil, + admission: admission, pagedConfig: pagedCheckpointConfig, + nativePagedBinding: nativePagedPrefixBinding) self.completePrefixCache = completePrefixCache self.completeCheckpointCodec = codec self.completeCheckpointCapture = .init(codec: codec, store: completePrefixCache) } else if schedulerConfig.enablePrefixCache, - (model as? any CBv2HistoricalAttentionCheckpointProviding)?.cbv2SupportsHistoricalAttentionCheckpoint == true, + (model as? any CBv2HistoricalAttentionCheckpointProviding)? + .cbv2SupportsHistoricalAttentionCheckpoint == true, !(mtpDriver?.tracksPersistentHistory ?? false), let completePrefixCache, let pagedCheckpointConfig, let segmentedPool, - (try? CBv2HistoricalAttentionLayout(layerKinds: layerKinds, dtypes: segmentedPool.layerDTypes)) != nil + (try? CBv2HistoricalAttentionLayout( + layerKinds: layerKinds, dtypes: segmentedPool.layerDTypes)) != nil { // The caller explicitly supplied a durable store. Observed native // storage dtypes, including borrower rows, define this loaded codec. @@ -466,6 +816,71 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { self.completeCheckpointCodec = nil self.completeCheckpointCapture = nil } + let nativePrefix = + nativeCompletionTracking + && nativeExecutionContract?.supportsNativeCompletePrefix == true + && completePrefixCache is any CBv2NativeCompletePrefixCache + && self.completeCheckpointCodec != nil && self.completeCheckpointCapture != nil + && schedulerConfig.enablePrefixCache + self.nativeCompletePrefixContract = nativePrefix ? nativeExecutionContract : nil + let nativePagedTarget = + nativeCompletionTracking + && nativeExecutionContract?.supportsNativePagedTarget == true + && (backend as? PagedKVBackend)?.nativeModelBinding != nil + && (mtpDrafter == nil || nativePagedSerialMTP) + && ((nativePrefix && nativePagedPrefixBinding != nil) + || (!schedulerConfig.enablePrefixCache && completePrefixCache == nil)) + && prefixCache == nil && hybridPrefixCache == nil + && processMemoryOwner != nil + let nativeState: CBv2NativeShutdownState? + if nativeCompletionTracking { + // The package-issued contract binds the actual strict-loaded MiMo + // model/assistant/backend/cache bank, not names or a generic marker. + // Tokenizer/detokenizer and policy callbacks must remain host-only. + let consumersSupported = + prefixCache == nil && hybridPrefixCache == nil + && (nativePrefix + || (completePrefixCache == nil && !schedulerConfig.enablePrefixCache)) + && (!(backend is PagedKVBackend) || nativePagedTarget) + && (nativePrefix || nativePagedTarget || processMemoryOwner == nil) + && !(model is any CBv2RecurrentSteppableModel) + && (cacheProvider is CBv2LayerCacheBank + || nativeExecutionContract?.supportsManagedDecodedMedia == true) + && (sampler is CBv2DefaultSampler || sampler is CBv2GreedySampler) + && (detokenizerFactory is CBv2NullDetokenizerFactory + || detokenizerFactory is CBv2TextDetokenizerFactory) + && (mtpDrafter == nil + || (mtpDrafter is any CBv2NativeMTPCompletionSplitting + && mtpDriver != nil + && (mtpConfig.verificationMode == .serialTarget + || mtpConfig.verificationMode == .rectangular) + && mtpDriver?.config.verificationMode == mtpConfig.verificationMode + && nativeExecutionContract?.mtpVerificationMode + == mtpConfig.verificationMode + && mtpConfig.maxSpeculativeBatch == 1 + && (1 ... 3).contains(mtpConfig.maxDraftTokens))) + let exact = + consumersSupported + && (nativeExecutionContract?.consume( + model: model, + backend: backend, cacheProvider: cacheProvider, + assistant: mtpDrafter.map { $0 as AnyObject }, + mtpVerificationMode: mtpDrafter == nil + ? .serialTarget : mtpConfig.verificationMode, + completePrefixCache: nativePrefix ? completePrefixCache : nil, + processMemoryOwner: processMemoryOwner) ?? false) + nativeState = .init( + engineID: nativeID, contractID: nativeExecutionContract?.id, supported: exact) + } else { + nativeState = nil + } + self.nativeShutdownState = nativeState + let nativeCleanup: (@Sendable () -> Void)? + if nativeState != nil { + nativeCleanup = { admission.closeProcessMemoryOwner() } + } else { + nativeCleanup = nil + } self.loop = EngineLoopV2( model: model, layerKinds: layerKinds, @@ -483,7 +898,18 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { nominalFullKVBytesPerToken: admission.fullKVBytesPerToken, mtp: mtpDriver, config: loopConfig, - gauges: gauges) + gauges: gauges, + nativeShutdownState: nativeState, + blockBatchBudget: blockBatchBudget, + rectangularDenseBudget: rectangularDenseBudget, + nativeQuiescentCleanup: nativeCleanup) + nativeState?.installEngine(self) + if nativePagedTarget, let binding = (backend as? PagedKVBackend)?.nativeModelBinding { + loop.configureNativePaged(binding: binding, retaining: self) + } + if let contract = self.nativeCompletePrefixContract { + loop.configureNativeCompletePrefix(contract: contract) + } loop.start() } @@ -529,7 +955,8 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { paged.pool.config.segmentSizeBytes != nil, paged.pool.config.layerDTypes != nil else { - return "EngineV2: model requires segmented paged KV with observed native layer dtypes" + return + "EngineV2: model requires segmented paged KV with observed native layer dtypes" } } return nil @@ -546,6 +973,12 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { } private func requireAcceptingSubmissions() throws { + if nativeShutdownState?.isIncomplete == true { + throw CBv2NativeShutdownError.operationClosed + } + if let reason = pagedAttentionWorkInactiveReason { + throw CBv2KVError.backendIneligible(reason: reason) + } let rejecting = stateLock.withLock { rejectingSubmissions } guard !rejecting else { throw CBv2KVError.capacityExhausted(needed: 1, available: 0) @@ -576,6 +1009,28 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { } private func validateRequest(_ request: CBv2Request) throws { + if nativeShutdownState != nil, + request.positionState != nil || request.tokenConstraint != nil + || request.sampling.topLogprobs != 0 + { + throw CBv2NativeShutdownError.unsupportedConsumer + } + if nativeShutdownState != nil, request.multimodal != nil { + guard issuedNativeExecutionContract?.supportsManagedDecodedMedia == true, + let token = request.multimodal?.nativeMediaToken + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try loop.onEngineQueueSync { + guard token.stream == nil, token.matches(request, engineID: nativeShutdownEngineID) + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + } + } else if request.multimodal?.nativeMediaToken != nil { + // SDK-owned roots may never escape into an untracked engine. + throw CBv2NativeShutdownError.unsupportedConsumer + } if let positions = request.positionState { guard positions.promptLength == request.promptTokens.count else { throw CBv2MultimodalError.invalidSpans( @@ -597,7 +1052,10 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { "request-owned positions require positioned model forwarding") } } - if request.multimodal?.attention == .causal, request.positionState == nil { + if request.multimodal?.attention == .causal, request.positionState == nil, + (loop.model as? any CBv2MultimodalSteppableModel)?.causalPositionRequirement + != .scalarCacheOffset + { throw CBv2MultimodalError.invalidSpans( "causal multimodal input requires request-owned position state") } @@ -627,17 +1085,24 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { private func requireRequestCanEverFit(_ request: CBv2Request) throws { let pool = (backend as? PagedKVBackend)?.pool - let completion = pool?.segmentGrant != nil ? max(request.maxTokens, 1) : max(request.maxTokens, 0) + let completion = + pool?.segmentGrant != nil ? max(request.maxTokens, 1) : max(request.maxTokens, 0) let (tokens, overflow) = request.promptTokens.count.addingReportingOverflow(completion) let overhead: Int if let pool, pool.segmentGrant != nil { - overhead = overflow ? Int.max : (pool.minimumSegmentedOverhead( - tokens: tokens, layerKinds: layerKinds) ?? Int.max) - } else { overhead = 0 } - guard !overflow, admission.canEverFit( - promptTokens: request.promptTokens.count, - maxTokens: completion, - additionalBackendBytes: overhead) + overhead = + overflow + ? Int.max + : (pool.minimumSegmentedOverhead( + tokens: tokens, layerKinds: layerKinds) ?? Int.max) + } else { + overhead = 0 + } + guard !overflow, + admission.canEverFit( + promptTokens: request.promptTokens.count, + maxTokens: completion, + additionalBackendBytes: overhead) else { let allocated = overflow ? Int.max : admission.allocatedBytes(forTokens: tokens) let (needed, sumOverflow) = allocated.addingReportingOverflow(overhead) @@ -648,6 +1113,18 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { } private func registerSubmission(_ request: CBv2Request) throws -> CBv2OutputStream { + if let tracking = nativeShutdownState { + guard tracking.beginCommit() else { throw CBv2NativeShutdownError.operationClosed } + } + defer { nativeShutdownState?.endCommit() } + if nativeShutdownState != nil { + // Recheck at registration: shutdown may have started after the + // public submit preflight. This prevents a new pending owner after + // the reporting barrier inspected the queue. + guard !stateLock.withLock({ rejectingSubmissions }) else { + throw CBv2NativeShutdownError.operationClosed + } + } guard gauges.beginSubmit(maxWaiting: schedulerConfig.maxWaiting) else { throw CBv2KVError.capacityExhausted(needed: 1, available: 0) } @@ -670,6 +1147,37 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { // MARK: CBv2Engine + /// Package producer only: exact issued owner/processor, never conformance + /// or caller model spelling. Does not reopen native construction. + package func prepareNativeMedia( + processor: AnyObject, loadedOwner: AnyObject, + _ body: (CBv2NativeMediaPreparation) throws -> CBv2Request + ) throws -> CBv2Request { + try requireAcceptingSubmissions() + guard let contract = issuedNativeExecutionContract, + contract.matchesMedia(processor: processor, owner: loadedOwner), + nativeShutdownState?.supported == true + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + return try loop.prepareNativeMedia(processor: processor, owner: loadedOwner, body) + } + package func requireNativeMediaCanEverFit(promptTokens: [Int], maximumOutputTokens: Int) throws + { + try requireAcceptingSubmissions() + try requireRequestCanEverFit( + .init(id: .init(0), promptTokens: promptTokens, maxTokens: maximumOutputTokens)) + } + + /// Cold refusal/cancellation cleanup only. A bound stream is deliberately + /// untouched; its actual request retirement owns disposal. Incomplete work + /// retains the exact loan/roots and cannot be retried into a healthy refund. + public func discardUnsubmittedNativeMedia(_ input: CBv2MultimodalInput) { + guard let token = input.nativeMediaToken, token.work.engineID == nativeShutdownEngineID + else { return } + loop.discardPreparedMedia(token) + } + /// Submit a request; events stream until `.finished`. Throws /// `CBv2KVError.capacityExhausted` when truthful admission fails (worst /// case could never fit), the waiting queue is full, or the engine is @@ -678,18 +1186,58 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { /// live: the duplicate is rejected BEFORE any stream registration, so /// the original request's stream is never touched (PR#62 review). public func submit(_ request: CBv2Request) throws -> AsyncStream { + try submitOrdinary(request).events + } + + /// Ordinary scheduling plus the actual registered stream generation's + /// ownership acknowledgement. Only the tracked native profile may expose + /// this serving guarantee. Terminal delivery/caller cancellation alone is + /// not retirement; an incomplete native shutdown can leave wait() pending + /// permanently. The host must transfer that wait and its real shared C + /// owner to fault cleanup, never replace it with an acknowledged handle. + public func submitWithNativeRetirement(_ request: CBv2Request) throws + -> (events: AsyncStream, retirement: CBv2RequestRetirement) + { + guard let tracking = nativeShutdownState, tracking.supported else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try tracking.requireWork() + let submitted = try submitOrdinary(request) + return ( + submitted.events, + submitted.registeredStream.map { CBv2RequestRetirement(stream: $0) } + ?? .acknowledged + ) + } + + /// One normalization/admission/registration/scheduling body for both + /// ordinary APIs. Nil means the genuine zero-work immediate path: no + /// stream generation, scheduler row, native work or request KV was owned. + private func submitOrdinary(_ request: CBv2Request) throws + -> (events: AsyncStream, registeredStream: CBv2OutputStream?) + { let request = normalizedRequest(request) try requireAcceptingSubmissions() + if request.multimodal?.nativeMediaToken != nil + || (nativeShutdownState != nil && request.multimodal != nil) + { + try validateRequest(request) + } // Degenerate requests: uniform event surface, no engine round-trip. if request.maxTokens <= 0 { - return Self.immediateStream( - reason: .length, - usage: CBv2Usage(promptTokens: request.promptTokens.count, completionTokens: 0)) + return ( + Self.immediateStream( + reason: .length, + usage: CBv2Usage(promptTokens: request.promptTokens.count, completionTokens: 0)), + nil + ) } if request.promptTokens.isEmpty { - return Self.immediateStream( - reason: .error("empty prompt"), - usage: CBv2Usage(promptTokens: 0, completionTokens: 0)) + return ( + Self.immediateStream( + reason: .error("empty prompt"), + usage: CBv2Usage(promptTokens: 0, completionTokens: 0)), nil + ) } try validateRequest(request) @@ -721,8 +1269,12 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { var multimodal: CBv2ResolvedMultimodal? = nil if let input = request.multimodal { do { - multimodal = try CBv2MultimodalPlan.materialize( - input, blocks: multimodalBlocks, model: loop.model) + if let token = input.nativeMediaToken { + multimodal = try loop.bindPreparedMedia(token, request: request, stream: stream) + } else { + multimodal = try CBv2MultimodalPlan.materialize( + input, blocks: multimodalBlocks, model: loop.model) + } } catch { loop.unregister(request.id) gauges.endSubmit() @@ -735,7 +1287,7 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { prefixLookup: makePrefixLookup(for: request), residentPrefixProbe: makeResidentPrefixProbe(for: request), multimodal: multimodal) - return stream.makeStream() + return (stream.makeStream(), stream) } /// Submit only when the authoritative engine-queue projection can reach @@ -744,14 +1296,23 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { /// The caller owns the anchored deadline and conservative phase rates; the /// verdict subtracts elapsed time only inside the serialized engine-queue /// closure, so waiting for that closure never resets the budget. - /// Multimodal requests fail closed before image materialization because - /// image-tower work is not representable by scheduled token count. + /// Raw multimodal requests fail closed before image materialization. + /// Native sealed causal features have already completed that work under + /// their retained loan; only their remaining target tokens are projected. + /// The engine queue revalidates and binds the seal only at admission. public func submit( _ request: CBv2Request, firstTokenDeadline: CBv2FirstTokenDeadlineAdmission ) async throws -> CBv2FirstTokenDeadlineResult { let request = normalizedRequest(request) try requireAcceptingSubmissions() + // An invalidated/mutated seal is not a zero-work success, including + // when payload mutation has removed the token from a native request. + if request.multimodal?.nativeMediaToken != nil + || (nativeShutdownState != nil && request.multimodal != nil) + { + try validateRequest(request) + } let zeroWork = CBv2FirstTokenProjectedWork.bounded( work: CBv2FirstTokenScheduledWork( @@ -784,7 +1345,9 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { if request.multimodal != nil { _ = try validatedMultimodalBlocks(for: request) - return .deadlineUnreachable(projectedWork: .unbounded) + guard request.multimodal?.nativeMediaToken != nil else { + return .deadlineUnreachable(projectedWork: .unbounded) + } } guard loop.isHealthy else { throw CBv2KVError.capacityExhausted(needed: 1, available: 0) @@ -819,6 +1382,8 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { throw CancellationError() case .schedulerRejected(let error): throw error + case .mediaRejected(let error): + throw error case .capacityRejected: throw CBv2KVError.capacityExhausted(needed: 1, available: 0) } @@ -975,8 +1540,7 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { public func residentPrefixCandidate( for request: CBv2Request ) -> CBv2ResidentPrefixCandidate? { - if let hybridPrefixCache, request.permitsHybridCheckpoint(layerKinds: layerKinds) - { + if let hybridPrefixCache, request.permitsHybridCheckpoint(layerKinds: layerKinds) { return hybridPrefixCache.candidate( tokens: request.promptTokens, cacheSalt: request.checkpointCacheSalt, maximumChunkSize: max( @@ -1027,9 +1591,12 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { /// admissions fail (`capacityExhausted`) until the pool drains below /// the new ceiling; grow admits immediately. public func updateKVBytesCapacity(_ bytes: Int) { + if let tracking = nativeShutdownState { guard tracking.beginCommit() else { return } } + defer { nativeShutdownState?.endCommit() } let total = max(0, bytes) - let hybridReservation = hybridPrefixCache?.resizeReservation( - to: min(hybridPrefixCache?.config.maximumBytes ?? 0, total / 4)) ?? 0 + let hybridReservation = + hybridPrefixCache?.resizeReservation( + to: min(hybridPrefixCache?.config.maximumBytes ?? 0, total / 4)) ?? 0 let clamped = max(0, total - hybridReservation) if clamped < admission.bytesCapacity { admission.updateBytesCapacity(clamped) @@ -1043,12 +1610,48 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { gauges.updateKVBytesCapacity(clamped, backendCapacity: backend.bytesCapacity) } + /// Metadata-only factory handed to the separately validated import plan. + /// The closure rechecks exact store/codec/loaded generation at allocation. + /// No raw model/bank/array crosses the provider's asynchronous I/O boundary. + func nativeCompletePrefixWorkFactory( + store: any CBv2CompletePrefixCache, + codec: CBv2CompleteCheckpointCodec, request: CBv2Request + ) + throws -> (@Sendable () throws -> CBv2NativeCompletePrefixWork)? + { + guard nativeShutdownState != nil else { return nil } + guard let contract = nativeCompletePrefixContract, + completePrefixCache === store, completeCheckpointCodec === codec, + request.multimodal == nil, request.positionState == nil, + request.maxTokens > 0, request.promptTokens.count > 1, request.prefixCacheEnabled, + request.prefixCacheReceiptID != nil + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try loop.onEngineQueueSync { + try contract.validateCompletePrefix(store: store, codec: codec) + } + return { [weak loop] in + guard let loop else { throw CBv2NativeShutdownError.operationClosed } + let streams = [StreamOrDevice.cpu.stream, StreamOrDevice.default.stream] + return try loop.onEngineQueueSync { + try loop.makeNativeCompletePrefixWork( + purpose: .importing, + request: request, operationStreams: streams) + } + } + } + /// Graceful drain: new submissions are rejected, waiting requests are /// cancelled, running requests finish naturally, then the loop stops. /// Bounded by `CBv2EngineLoopConfig.shutdownTimeout` (default 10 s): if /// the engine queue is wedged, live streams are force-finished with /// `.error` and this returns instead of hanging forever. public func shutdown() async { + if nativeShutdownState != nil { + _ = await shutdownReportingNativeCompletion() + return // Never run legacy post-timeout cleanup for a tracked engine. + } beginRejectingSubmissions() completeCheckpointCapture?.close() completePrefixCache?.close() @@ -1057,6 +1660,17 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { admission.closeProcessMemoryOwner() } + public func shutdownReportingNativeCompletion() async -> CBv2NativeShutdownOutcome { + guard nativeShutdownState != nil else { + return .incomplete( + .init(engineID: nativeShutdownEngineID, generation: 1, reason: .notTracked)) + } + beginRejectingSubmissions() + // Admission close is part of the loop's one post-fence commit, not a + // repeated/unconditional action by each concurrent shutdown waiter. + return await loop.drainReportingNativeCompletion() + } + /// Synchronous helper: `NSLock` is not async-safe to hold across /// suspension points, so the flag flip lives outside the async context. private func beginRejectingSubmissions() { @@ -1101,7 +1715,9 @@ extension EngineV2 { /// `.nothingToScore` for an empty prompt or continuation, and /// `CBv2KVError.capacityExhausted` when the pool cannot seat the row. public func teacherForcedTop1(promptTokens: [Int], continuation: [Int]) throws -> [Int] { - try loop.teacherForcedTop1(promptTokens: promptTokens, continuation: continuation) + let loan = try nativeShutdownState?.beginLoan() + defer { loop.nativeDiagnosticLoanEnded(loan) } + return try loop.teacherForcedTop1(promptTokens: promptTokens, continuation: continuation) } /// Bounded numerical observation of ordinary teacher-forced target logits. @@ -1110,7 +1726,9 @@ extension EngineV2 { public func teacherForcedScores(_ request: CBv2TeacherForcedScoreRequest) throws -> CBv2TeacherForcedScoreSnapshot { - try loop.teacherForcedScores(request) + // Rich diagnostic packet consumers need their own root/loan audit. + if nativeShutdownState != nil { throw CBv2NativeShutdownError.unsupportedConsumer } + return try loop.teacherForcedScores(request) } /// Cumulative evidence that the scoring above drove real engine @@ -1205,6 +1823,8 @@ extension EngineV2 { let probeID = Self.nextDigestProbeID() let box = CBv2FrontierLogitBox() + let loan = try nativeShutdownState?.beginLoan(owner: box) + defer { loop.nativeDiagnosticLoanEnded(loan) } loop.setPrefillFrontierCapture { id, logits in guard id == probeID else { return } box.deliver(logits) @@ -1233,13 +1853,39 @@ extension EngineV2 { // node over the same slabs a live step may still be writing, and MLX // graph work is not safe to run beside the step thread. return try loop.onEngineQueueSync { - try Self.digest(frontierLogits: captured) + try loop.requireNativeWork() + let mark = nativeShutdownState?.rootMark ?? 0 + loop.retainNativeWork([captured], owners: [box]) + do { + let result: CBv2PrefillLogitDigest + if let tracking = nativeShutdownState { + result = try withError { + try Self.digest(frontierLogits: captured, retaining: tracking) + } + } else { + result = try Self.digest(frontierLogits: captured) + } + try loop.requireNativeWork() + if let tracking = nativeShutdownState { + tracking.retireCompleted(tracking.rootIDs(since: mark)) + } + return result + } catch { + if let tracking = nativeShutdownState, tracking.mayExecute { + do { + try tracking.fenceCapturedStreams() + tracking.retireCompleted(tracking.rootIDs(since: mark)) + } catch { loop.failNativeCompletion(.capturedFenceFailed) } + } + throw error + } } } /// Metadata-only benchmark diagnostic. Requires idle, MTP-off, full-attention owners. @_spi(Diagnostics) public func configureAttentionMetadata(_ configuration: CBv2AttentionMetadataConfig?) throws { + if nativeShutdownState != nil { throw CBv2NativeShutdownError.unsupportedConsumer } try loop.configureAttentionMetadata(configuration) } @@ -1251,6 +1897,7 @@ extension EngineV2 { /// One owner's native attention bytes, retained only through its existing step fence. @_spi(Diagnostics) public func configureAttentionPacket(_ configuration: CBv2AttentionPacketConfig?) throws { + if nativeShutdownState != nil { throw CBv2NativeShutdownError.unsupportedConsumer } try loop.configureAttentionPacket(configuration) } @@ -1263,6 +1910,7 @@ extension EngineV2 { /// idle; nil leaves the serving path without diagnostic tensor work. @_spi(Diagnostics) public func configureLogitDiagnostic(_ configuration: CBv2LogitDiagnosticConfig?) throws { + if nativeShutdownState != nil { throw CBv2NativeShutdownError.unsupportedConsumer } try loop.configureLogitDiagnostic(configuration) } @@ -1277,15 +1925,27 @@ extension EngineV2 { /// produced. No `asType`: an upcast here would make a bf16 arm and an /// fp32 arm hash identically for values that differ below fp16 /// precision, which is exactly the drift this seam has to see. - static func digest(frontierLogits: MLXArray) throws -> CBv2PrefillLogitDigest { + static func digest(frontierLogits: MLXArray, retaining tracking: CBv2NativeShutdownState? = nil) + throws -> CBv2PrefillLogitDigest + { let vector: MLXArray switch frontierLogits.ndim { case 1: vector = frontierLogits case 2 where frontierLogits.dim(0) == 1: vector = frontierLogits[0] default: throw CBv2PrefillLogitDigestError.unexpectedLogitShape(frontierLogits.shape) } - let maxAbs = MLX.abs(vector).max().item(Float.self) + let maxAbs: Float + if let tracking { + tracking.captureStreams() + let maximum = MLX.abs(vector).max() + tracking.retain([vector, maximum]) + try tracking.requireWork() + maxAbs = maximum.item(Float.self) + } else { + maxAbs = MLX.abs(vector).max().item(Float.self) + } let raw = vector.asData(access: .copy) + try tracking?.requireWork() var hasher = SHA256() hasher.update(data: raw.data) let hex = hasher.finalize().reduce(into: "") { $0 += String(format: "%02x", $1) } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/FirstTokenDeadlineAdmissionV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/FirstTokenDeadlineAdmissionV2.swift index 82e1aba3f0..3690f8e88d 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/FirstTokenDeadlineAdmissionV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/FirstTokenDeadlineAdmissionV2.swift @@ -181,6 +181,7 @@ private struct CBv2ProjectionRow { let id: CBv2RequestID let promptTokens: Int let maxTokens: Int + let isMultimodal: Bool let isPaused: Bool let cancelRequested: Bool let prefixReusePlan: CBv2PrefixReusePlan? @@ -334,6 +335,7 @@ extension SchedulerV2 { id: rec.id, promptTokens: rec.request.promptTokens.count, maxTokens: max(0, rec.request.maxTokens), + isMultimodal: rec.request.multimodal != nil, isPaused: rec.isPaused, cancelRequested: rec.cancelRequested, prefixReusePlan: rec.prefixReusePlan, @@ -739,7 +741,11 @@ extension SchedulerV2 { else { return nil } - return (candidateID, stripe) + guard + let selectedStripe = config.resolvedSoloPrefillStripeTokens( + isMultimodal: candidate.isMultimodal) + else { return nil } + return (candidateID, selectedStripe) }() var budget = max(baseBudget, soloStripe?.tokens ?? 0) diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/KVGeometryV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/KVGeometryV2.swift new file mode 100644 index 0000000000..4cf115273d --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/KVGeometryV2.swift @@ -0,0 +1,46 @@ +import Foundation + +/// Native attention storage geometry. K and V share a dtype and head count, +/// but their feature widths are independent. No allocation or MLX dependency. +public struct CBv2KVGeometry: Sendable, Equatable { + public let kvHeads: Int + public let keyHeadDim: Int + public let valueHeadDim: Int + + public init?(kvHeads: Int, keyHeadDim: Int, valueHeadDim: Int) { + guard [kvHeads, keyHeadDim, valueHeadDim].allSatisfy({ $0 > 0 && $0 <= Int(Int32.max) }) + else { + return nil + } + self.kvHeads = kvHeads + self.keyHeadDim = keyHeadDim + self.valueHeadDim = valueHeadDim + } + + /// Returns nil for invalid element widths or overflowing arithmetic. + /// Extra storage is already bytes; it is not multiplied by tensor dtype. + public func bytesPerToken(elementBytes: Int, extraBytes: Int = 0) -> Int? { + guard elementBytes > 0, extraBytes >= 0, + let width = Self.add(keyHeadDim, valueHeadDim), + let elements = Self.multiply(kvHeads, width), + let bytes = Self.multiply(elements, elementBytes) + else { return nil } + return Self.add(bytes, extraBytes) + } + + public func storageBytes(tokens: Int, elementBytes: Int, extraBytesPerToken: Int = 0) -> Int? { + guard tokens >= 0, + let bytes = bytesPerToken(elementBytes: elementBytes, extraBytes: extraBytesPerToken) + else { return nil } + return Self.multiply(tokens, bytes) + } + + static func add(_ a: Int, _ b: Int) -> Int? { + let result = a.addingReportingOverflow(b) + return result.overflow ? nil : result.partialValue + } + static func multiply(_ a: Int, _ b: Int) -> Int? { + let result = a.multipliedReportingOverflow(by: b) + return result.overflow ? nil : result.partialValue + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/LastQueryPrefillV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/LastQueryPrefillV2.swift index cb5d4e6975..a09358fbfb 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/LastQueryPrefillV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/LastQueryPrefillV2.swift @@ -8,7 +8,7 @@ // from that one row and discards the rest (see PrefillOutputV2.swift). // // `updateAndAttendLastQuery` expresses exactly that: commit the full -// `[B, heads, L, D]` K/V rectangle, then evaluate attention for a single +// K `[B, heads, L, Dk]` and V `[B, heads, L, Dv]`, then evaluate attention for a single // query row. Because the newest causal query can see every key the chunk // just wrote, its result is bit-equivalent to the final row of ordinary // chunk attention — no mask is needed, and a bound vision-span overlay @@ -33,7 +33,9 @@ import MLX public protocol CBv2LastQueryPrefillLayerCache: CBv2AttendingLayerCache { /// - queries: `[B, queryHeads, 1, headDim]` — the frontier row only, /// already RoPE'd at the chunk's LAST absolute position. - /// - keys/values: `[B, kvHeads, L, headDim]` — the COMPLETE chunk. + /// - keys: `[B, kvHeads, L, headDim]` — the COMPLETE chunk. + /// - values: `[B, kvHeads, L, valueHeadDim]` — the COMPLETE chunk. + /// - Returns `[B, queryHeads, 1, valueHeadDim]`. /// Advances per-row offsets by `L` (the K/V length). func updateAndAttendLastQuery( queries: MLXArray, keys: MLXArray, values: MLXArray, diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/LayerCacheV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/LayerCacheV2.swift index 59f2696b85..a2d8454ab1 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/LayerCacheV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/LayerCacheV2.swift @@ -49,8 +49,8 @@ public final class CBv2LayerCache: CBv2AttendingLayerCache { /// MTP-only verification policy. When true, an L>1 update still projects /// and stores the whole rectangle once, but attention evaluates each /// query with the canonical L=1 SDPA path and its exact visible KV prefix. - var mtpSerializesRectangularAttention = false - var mtpBatchesRectangularAttention = false + package var mtpSerializesRectangularAttention = false + package var mtpBatchesRectangularAttention = false /// Times `positionOffsets` was rebuilt from host integers. Tests assert /// this only moves on membership changes — never inside the step loop. @@ -61,6 +61,9 @@ public final class CBv2LayerCache: CBv2AttendingLayerCache { /// config — identical plumbing on both backends (`PagedLayerCache` takes /// the same parameter); never part of the per-call contract surface. public let attentionSoftcap: Float? + let mimoV26NAXAttention: Bool + // Installed only on caches from the exact SDK-issued MiMo bundle. + package var mimoV26BlockBatchBudget: MiMoV26BlockBatchBudget? /// Optional vision span context for each CURRENT prefill row. The engine /// binds this array immediately before graph construction and clears it @@ -77,7 +80,7 @@ public final class CBv2LayerCache: CBv2AttendingLayerCache { public init( layerIndex: Int, kind: CBv2LayerKind, rows: [CBv2SequenceKV] = [], - attentionSoftcap: Float? = nil + attentionSoftcap: Float? = nil, mimoV26NAXAttention: Bool = false ) { precondition( kind.sharesKVWithLayer == nil || rows.isEmpty, @@ -86,6 +89,7 @@ public final class CBv2LayerCache: CBv2AttendingLayerCache { self.kind = kind self.rows = rows self.attentionSoftcap = attentionSoftcap + self.mimoV26NAXAttention = mimoV26NAXAttention self.cachedPositionOffsets = Self.buildPositionOffsets(rows) } @@ -145,7 +149,9 @@ public final class CBv2LayerCache: CBv2AttendingLayerCache { queries: queries, keys: keys, values: values, scale: scale, sinks: sinks, softcap: attentionSoftcap, spanContexts: boundSpanContexts, - serializeQueries: mtpSerializesRectangularAttention, metadata: metadata, packet: packet) + serializeQueries: mtpSerializesRectangularAttention, metadata: metadata, packet: packet, + mimoV26NAXAttention: mimoV26NAXAttention, + mimoV26BlockBatchBudget: mimoV26BlockBatchBudget) // Advance offsets ON-DEVICE. Decode and packed prefill are // rectangular, so L is uniform across every bound row. cachedPositionOffsets = cachedPositionOffsets + Int32(queries.dim(2)) diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/CBv2MTPBoundedAdmission.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/CBv2MTPBoundedAdmission.swift new file mode 100644 index 0000000000..eae9df63d4 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/CBv2MTPBoundedAdmission.swift @@ -0,0 +1,187 @@ +import MLX + +/// Immutable execution envelope, not a request or advertised context limit. +/// EngineV2 and SchedulerV2 copy their value-type configuration into let +/// properties. Raising either work limit therefore requires a new engine and +/// a new resolution before any work can use the larger envelope. +public struct CBv2MTPAllocationLimits: Sendable, Equatable { + public let maximumPrefillTokens: Int + public let maximumDraftTokens: Int + + public init(maximumPrefillTokens: Int, maximumDraftTokens: Int) { + self.maximumPrefillTokens = maximumPrefillTokens + self.maximumDraftTokens = maximumDraftTokens + } +} + +/// Independent allocations of the same maximum logical extent. The allocator +/// bound is applied to ONE buffer, then multiplied by allocationCount. +public struct CBv2MTPFixedBufferSpec: Sendable, Equatable { + public let logicalBytes: Int + public let allocationCount: Int + + public init(logicalBytes: Int, allocationCount: Int = 1) { + self.logicalBytes = logicalBytes + self.allocationCount = allocationCount + } +} + +public struct CBv2MTPBoundedAllocationSpec: Sendable, Equatable { + public let resident: [CBv2MTPFixedBufferSpec] + public let working: [CBv2MTPFixedBufferSpec] + public let hostBytes: Int + + public init( + resident: [CBv2MTPFixedBufferSpec], working: [CBv2MTPFixedBufferSpec], hostBytes: Int + ) { + self.resident = resident + self.working = working + self.hostBytes = hostBytes + } +} + +/// Opt-in only. Nil refuses admission; it is not a fallback to an unpriced +/// state. The declaration covers request-owned roots and source-visible work, +/// not weights, target-forward activations or opaque kernel scratch. Existing +/// host activation/scratch safety reserves must remain in force. +public protocol CBv2MTPBoundedAllocationProviding: CBv2MTPDrafter { + func boundedRequestAllocation(limits: CBv2MTPAllocationLimits) -> CBv2MTPBoundedAllocationSpec? +} + +public struct CBv2ResolvedMTPAdmission: Sendable, Equatable { + public let limits: CBv2MTPAllocationLimits + public let residentBytes: Int + public let workingBytes: Int + public let hostBytes: Int + /// This amount is already included in EngineV2.resolvedFixedBytesPerRequest. + /// Consumers must replace the legacy MTP variable term, never add it twice. + public let fixedBytesPerRequest: Int + public var auxiliaryBytesPerToken: Int { 0 } + public var auxiliaryTokenGranularity: Int { 1 } + public var auxiliaryTokenAllocationPadding: Int { 0 } +} + +public enum CBv2MTPAdmissionRefusal: Error, Sendable, Equatable { + case invalidLimits + case missingDeclaration + case invalidDeclaration + case allocatorPolicyUnavailable + case unrepresentableAllocation + case invalidExistingCharge + case chargeOverflow +} + +public enum CBv2MTPAdmissionResolution: Sendable, Equatable { + case bounded(CBv2ResolvedMTPAdmission) + case unavailable(CBv2MTPAdmissionRefusal) +} + +/// Construction-only arithmetic. No request-token loop, allocation, native +/// evaluation or materialization credit. Both backend policies consume the +/// resulting fixed charge through AdmissionV2's common non-backend ledger. +enum CBv2MTPBoundedAdmission { + static func resolve( + spec: CBv2MTPBoundedAllocationSpec?, limits: CBv2MTPAllocationLimits, + policy: AllocationFootprintPolicy? + ) -> CBv2MTPAdmissionResolution { + guard let policy else { return .unavailable(.allocatorPolicyUnavailable) } + return resolve(spec: spec, limits: limits, upperBound: policy.upperBound(byteCount:)) + } + + // Scalar injection is internal and used only by arithmetic tests. Public + // consumers receive the engine's captured real allocator resolution. + static func resolve( + spec: CBv2MTPBoundedAllocationSpec?, limits: CBv2MTPAllocationLimits, + upperBound: (Int) -> Int? + ) -> CBv2MTPAdmissionResolution { + guard limits.maximumPrefillTokens > 0, limits.maximumDraftTokens > 0 else { + return .unavailable(.invalidLimits) + } + guard let spec else { return .unavailable(.missingDeclaration) } + guard !spec.resident.isEmpty, !spec.working.isEmpty, spec.hostBytes >= 0, + (spec.resident + spec.working).allSatisfy({ + $0.logicalBytes > 0 && $0.allocationCount > 0 + }) + else { + return .unavailable(.invalidDeclaration) + } + func project(_ buffers: [CBv2MTPFixedBufferSpec]) -> Int? { + var total = 0 + for buffer in buffers { + guard let bound = upperBound(buffer.logicalBytes), bound >= buffer.logicalBytes + else { return nil } + let (all, multiplyOverflow) = bound.multipliedReportingOverflow( + by: buffer.allocationCount) + guard !multiplyOverflow, let sum = add(total, all) else { return nil } + total = sum + } + return total + } + guard let resident = project(spec.resident), let working = project(spec.working) else { + return .unavailable(.unrepresentableAllocation) + } + guard let device = add(resident, working), let total = add(device, spec.hostBytes) else { + return .unavailable(.chargeOverflow) + } + return .bounded( + .init( + limits: limits, residentBytes: resident, workingBytes: working, + hostBytes: spec.hostBytes, fixedBytesPerRequest: total)) + } + + @discardableResult + static func apply(_ resolution: CBv2MTPAdmissionResolution, to config: inout AdmissionV2.Config) + -> CBv2MTPAdmissionResolution + { + guard case .bounded(let value) = resolution else { + config.fixedBytesPerRequest = Int.max + return resolution + } + guard config.fixedBytesPerRequest >= 0, config.auxiliaryBytesPerToken >= 0, + config.auxiliaryTokenGranularity > 0, config.auxiliaryTokenAllocationPadding >= 0 + else { + config.fixedBytesPerRequest = Int.max + return .unavailable(.invalidExistingCharge) + } + guard let total = add(config.fixedBytesPerRequest, value.fixedBytesPerRequest) else { + config.fixedBytesPerRequest = Int.max + return .unavailable(.chargeOverflow) + } + config.fixedBytesPerRequest = total + // Existing scalar/projection fields are CALLER charges in this branch; + // the inferred legacy drafter rate was never installed. Preserve them. + return resolution + } + + /// TargetAuxiliaryAdmission owns a single projection slot. Without target + /// extras leave the caller's exact projection untouched. With extras, use + /// its documented maximum one-token growth G as a conservative scalar + /// floor: P(0)=0 and P(n)-P(n-1)<=G imply P(n)<=n*G for all representable + /// nonnegative n. This includes padded first allocation and block crossings. + /// Admission checks each product at query time; overflow refuses work. + static func preserveCallerProjectionForTarget( + model: any CBv2SteppableModel, config: inout AdmissionV2.Config + ) { + guard let target = model as? any CBv2TargetAuxiliaryAllocationProviding, + let specs = target.cbv2TargetAuxiliaryAllocationSpecs, !specs.isEmpty, + let projection = config.auxiliaryAllocationProjection + else { return } + // The current projection has zero base. Keep this explicit so a future + // nonzero-base implementation is charged, not silently discarded. + guard let base = projection.bytes(forTokens: 0), base >= 0, + projection.maximumGrowthBytes >= 0, + let fixed = add(config.fixedBytesPerRequest, base) + else { + config.fixedBytesPerRequest = Int.max + return + } + config.fixedBytesPerRequest = fixed + config.auxiliaryBytesPerToken = max( + config.auxiliaryBytesPerToken, projection.maximumGrowthBytes) + } + + static func add(_ a: Int, _ b: Int) -> Int? { + let (sum, overflow) = a.addingReportingOverflow(b) + return a >= 0 && b >= 0 && !overflow ? sum : nil + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/CBv2MTPRoundDriver.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/CBv2MTPRoundDriver.swift index 3772a0ab43..d35693a3bd 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/CBv2MTPRoundDriver.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/CBv2MTPRoundDriver.swift @@ -16,6 +16,13 @@ import Foundation import MLX +/// Explicit attention-only opt-in: while native request-stateful text MTP is +/// installed, media rows can use this SAME target's ordinary causal path. This +/// does not qualify media drafting or change other models' cohort policy. +public protocol CBv2MTPRequestScopedMediaFallback: + CBv2MultimodalSteppableModel, CBv2MTPSteppableModel +{} + // MARK: - Drafter carry /// One row's drafter carry: the newest confirmed-but-unfed token (the round @@ -50,6 +57,17 @@ struct CBv2MTPCarry { let kvOffset: Int } +/// Scalar-only observation of an actual stored carry. No arrays, state owners +/// or replacement values escape through this test seam. +struct CBv2MTPCarryObservationForTesting { + let id: CBv2RequestID + let token: Int + let previousTopTwoMargin: Double? + let tokensCount: Int + let kvOffset: Int + let hiddenShape: [Int] +} + // MARK: - In-flight round payload /// MTP payload riding a `CBv2InFlightStep`. Its presence marks the step as @@ -114,14 +132,16 @@ final class CBv2MTPRoundInFlight { /// nil when this round only seeded (no row had a valid carry yet). let verify: Verify? - /// Seed rows: (request, row index into the step's decode batch). Their + /// Seed rows: (request, row index into seedHidden/seedPolicyTopTwoValues). + /// The opt-in media fallback compacts these to REAL hidden-producing text + /// rows; ordinary legacy cohorts retain their original decode indices. Their /// bonus token rides the step's normal `sampledTokens`; the carry hidden /// is sliced from `seedHidden` at finalize. let seedRows: [(id: CBv2RequestID, decodeIndex: Int)] - /// Lazy [B_decode, 1, H] pre-norm hidden of the step's decode batch + /// Lazy [B_hidden, 1, H] native target hidden (MiMo: post-final-norm). /// (non-nil iff `seedRows` is non-empty). let seedHidden: MLXArray? - /// Lazy float32 [B_decode, 1, 2] policy values for adaptive seed and + /// Lazy float32 [B_hidden, 1, 2] policy values for adaptive seed and /// temporary depth-zero carries. let seedPolicyTopTwoValues: MLXArray? /// Plain prompt/decode target observations whose request-owned assistant @@ -238,6 +258,9 @@ final class CBv2MTPRoundDriver { // Engine-thread confined. private var carries: [CBv2RequestID: CBv2MTPCarry] = [:] private var assistantStates: [CBv2RequestID: any CBv2MTPRequestState] = [:] + /// Immutable request-lifetime exclusion, not the lifetime of evaluated + /// feature arrays. Kept through preemption; cleared at actual finish. + private var targetOnlyMediaRequests: Set = [] /// Qwen acceptance is request-owned; raw nonchained wall cost is shared /// only within a compatible decode-row bucket. private var requestAcceptance: [CBv2RequestID: CBv2MTPRequestAcceptanceState] = [:] @@ -264,6 +287,14 @@ final class CBv2MTPRoundDriver { private var metrics = CBv2MTPMetrics() private var pendingSeedCosts = CBv2MTPSeedCostLedger() + /// Install on the engine queue before submitting requests. Called only + /// after the real carry assignment; never performs an evaluation itself. + var carryStoredObserverForTesting: ((CBv2MTPCarryObservationForTesting) -> Void)? + /// Numeric-test-only, never lifecycle/residency/timing evidence. A test may + /// retain at most one genuine seed carry view and compare it AFTER engine + /// drain. The callback must not eval/read back/copy arrays or mutate state. + /// Nil in ordinary tests and production; no parameter/eligibility override. + var carryHiddenObserverForTesting: ((CBv2RequestID, MLXArray) -> Void)? private init( config: CBv2MTPConfig, drafter: any CBv2MTPDrafter, @@ -337,18 +368,21 @@ final class CBv2MTPRoundDriver { guard config.effectiveEnabled, let drafter else { return nil } guard let mtpModel = model as? (any CBv2MTPSteppableModel) else { return nil } let stateful = drafter is any CBv2MTPRequestStatefulDrafter - let recurrent = - (model as? any CBv2RecurrentMTPSteppableModel)?.recurrentStateSpec != nil + let recurrentTarget = model as? any CBv2RecurrentMTPSteppableModel + let recurrent = recurrentTarget?.recurrentStateSpec != nil let captureLayers = mtpModel.mtpCaptureLayers - guard (stateful && recurrent && mtpModel.supportsRequestStatefulMTP) - || (!stateful && !recurrent && captureLayers != nil) + guard + (stateful && mtpModel.supportsRequestStatefulMTP + && (recurrentTarget == nil || recurrent)) + || (!stateful && !recurrent && captureLayers != nil) else { return nil } guard let modelTarget = mtpModel.mtpTargetIdentity, let drafterTarget = drafter.mtpTargetIdentity, modelTarget == drafterTarget else { return nil } var config = config - let effectiveVerification = drafter.requiredVerificationMode + let effectiveVerification = + drafter.requiredVerificationMode ?? config.verificationMode if stateful, effectiveVerification != .serialTarget, !supportsRectangularCacheBank @@ -483,12 +517,17 @@ final class CBv2MTPRoundDriver { metricsLock.unlock() } - func markRound(_ id: CBv2RequestID, k: Int) { roundMarks[id] = k } - func markSeed(_ id: CBv2RequestID) { seedMarks.insert(id) } + func markRound(_ id: CBv2RequestID, k: Int) { + guard !targetOnlyMediaRequests.contains(id) else { return } + roundMarks[id] = k + } + func markSeed(_ id: CBv2RequestID) { + guard !targetOnlyMediaRequests.contains(id) else { return } + seedMarks.insert(id) + } func roundMark(for id: CBv2RequestID) -> Int? { roundMarks[id] } func isSeedMarked(_ id: CBv2RequestID) -> Bool { seedMarks.contains(id) } - func forceSynchronizedSeed() { forceSeedPlan = true } @@ -507,6 +546,7 @@ final class CBv2MTPRoundDriver { /// Pure check (no mutation) — the chained-path pre-check uses it. func hasValidCarry(for rec: CBv2ScheduledRequest) -> Bool { + guard !targetOnlyMediaRequests.contains(rec.id) else { return false } guard let carry = carries[rec.id] else { return false } return carryMatches(carry, rec: rec) } @@ -514,6 +554,7 @@ final class CBv2MTPRoundDriver { /// Validate and return the row's carry; a stale carry is removed here /// (invalidate-on-mismatch — one seed step re-establishes it). func validatedCarry(for rec: CBv2ScheduledRequest) -> CarryStatus { + guard !targetOnlyMediaRequests.contains(rec.id) else { return .none } guard let carry = carries[rec.id] else { return .none } guard carryMatches(carry, rec: rec) else { carries.removeValue(forKey: rec.id) @@ -532,7 +573,8 @@ final class CBv2MTPRoundDriver { /// Take the row's carry for a launching round (a fresh one is stored at /// the round's finalize, or the row seeds again). func consumeCarry(for id: CBv2RequestID) -> CBv2MTPCarry? { - carries.removeValue(forKey: id) + guard !targetOnlyMediaRequests.contains(id) else { return nil } + return carries.removeValue(forKey: id) } func storeCarry( @@ -541,6 +583,7 @@ final class CBv2MTPRoundDriver { needsHistoryTransition: Bool = false, tokensCount: Int, kvOffset: Int ) { + guard !targetOnlyMediaRequests.contains(id) else { return } if tracksPersistentHistory, let stateful = drafter as? any CBv2MTPRequestStatefulDrafter, assistantStates[id] == nil @@ -552,6 +595,13 @@ final class CBv2MTPRoundDriver { previousTopTwoMargin: previousTopTwoMargin, needsHistoryTransition: needsHistoryTransition, tokensCount: tokensCount, kvOffset: kvOffset) + if let observer = carryStoredObserverForTesting { + observer( + .init( + id: id, token: token, previousTopTwoMargin: previousTopTwoMargin, + tokensCount: tokensCount, kvOffset: kvOffset, hiddenShape: hidden.shape)) + } + carryHiddenObserverForTesting?(id, hidden) } var tracksPersistentHistory: Bool { @@ -559,16 +609,45 @@ final class CBv2MTPRoundDriver { && usesRequestStatefulDrafter && config.fixedDraftTokens != 0 } + var supportsRequestScopedMediaFallback: Bool { + model is any CBv2MTPRequestScopedMediaFallback && usesRequestStatefulDrafter + && (model as? any CBv2RecurrentMTPSteppableModel)?.recurrentStateSpec == nil + } + func requiresTargetOnlyMedia(_ request: CBv2Request) -> Bool { + supportsRequestScopedMediaFallback && request.multimodal?.spans.isEmpty == false + } + func registerTargetOnlyMedia(_ request: CBv2Request) { + guard requiresTargetOnlyMedia(request) else { return } + if targetOnlyMediaRequests.insert(request.id).inserted { + precondition( + assistantStates[request.id] == nil && carries[request.id] == nil, + "immutable media request acquired unobserved assistant history") + } + } + func isTargetOnlyMediaForTesting(_ id: CBv2RequestID) -> Bool { + targetOnlyMediaRequests.contains(id) + } + func takeOrMakeAssistantState( - for id: CBv2RequestID, maximumSequenceLength: Int + for id: CBv2RequestID, maximumSequenceLength: Int, + historicalPrefixPromptTokens: [Int]? = nil ) throws -> (any CBv2MTPRequestState)? { - guard tracksPersistentHistory, + guard !targetOnlyMediaRequests.contains(id), tracksPersistentHistory, let stateful = drafter as? any CBv2MTPRequestStatefulDrafter else { return nil } - let state = assistantStates.removeValue(forKey: id) ?? stateful.makeRequestState() + let existing = assistantStates.removeValue(forKey: id) + let state = existing ?? stateful.makeRequestState() do { try stateful.configureRequestState( state, maximumSequenceLength: maximumSequenceLength) + if existing == nil, let historicalPrefixPromptTokens { + guard let historical = drafter as? any CBv2HistoricalMTPPrefixCheckpointCoding + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try historical.installPrefixCaptureContext( + requestState: state, promptTokens: historicalPrefixPromptTokens) + } } catch { // Configuration detached an existing owner from the map. Put it // back before propagating so the fenced cohort retirement path @@ -584,7 +663,6 @@ final class CBv2MTPRoundDriver { && usesRequestStatefulDrafter && config.fixedDraftTokens == nil } - var shouldApplyMarginalPolicyToPlan: Bool { usesMarginalPolicy && !planDecision.isExploration } @@ -593,6 +671,9 @@ final class CBv2MTPRoundDriver { observation: CBv2MTPCommittedTargetObservation, detachedState: any CBv2MTPRequestState ) { + precondition( + !targetOnlyMediaRequests.contains(id), + "media must never observe trained assistant state") guard let stateful = drafter as? any CBv2MTPRequestStatefulDrafter else { preconditionFailure("CBv2 MTP committed observation reached a stateless drafter") } @@ -646,6 +727,7 @@ final class CBv2MTPRoundDriver { } func pendingHistoryCarry(for id: CBv2RequestID) -> CBv2MTPCarry? { + guard !targetOnlyMediaRequests.contains(id) else { return nil } guard let carry = carries[id], carry.needsHistoryTransition else { return nil } return carry } @@ -657,10 +739,17 @@ final class CBv2MTPRoundDriver { func restoreAssistantState( _ state: any CBv2MTPRequestState, for id: CBv2RequestID ) { + precondition( + !targetOnlyMediaRequests.contains(id), "media must never restore assistant state") precondition(assistantStates[id] == nil, "duplicate CBv2 MTP assistant state") assistantStates[id] = state } + func canInstallHistoricalAssistant(for id: CBv2RequestID) -> Bool { + tracksPersistentHistory && !targetOnlyMediaRequests.contains(id) + && assistantStates[id] == nil && carries[id] == nil + } + func releaseDetachedAssistantState(_ state: any CBv2MTPRequestState) { (drafter as? any CBv2MTPRequestStatefulDrafter)?.releaseRequestState(state) } @@ -688,6 +777,14 @@ final class CBv2MTPRoundDriver { drafter is any CBv2MTPRequestStatefulDrafter } + func hasUnmeasuredAssistantResidency( + detachedStates: [any CBv2MTPRequestState] = [] + ) -> Bool { + (Array(assistantStates.values) + detachedStates).contains { + ($0 as? any CBv2MTPRequestResidencyReporting)?.hasUnmeasuredResidency == true + } + } + private func releaseAssistantState(_ id: CBv2RequestID) { guard let state = assistantStates.removeValue(forKey: id), let stateful = drafter as? any CBv2MTPRequestStatefulDrafter @@ -708,6 +805,7 @@ final class CBv2MTPRoundDriver { /// The request left the engine for good — ids are legally reusable, so /// every per-id trace must go (a reused id must never inherit a carry). func requestDidFinish(_ id: CBv2RequestID) { + targetOnlyMediaRequests.remove(id) if goodputPlanRows.contains(id) { invalidateWorkload() } carries.removeValue(forKey: id) releaseAssistantState(id) @@ -843,15 +941,20 @@ final class CBv2MTPRoundDriver { hasChainedSuccessor: Bool ) { guard depthController.usesCommittedDecodeBaseline, - acceptsWorkloadMeasurement(measurement) else { return } - let eligible = measurement.map { - $0.costEligible && $0.chained && !$0.seedOnly - && $0.actualDepth == 0 && $0.decision.depth == 0 - && $0.decision.decodeRowBucket == CBv2MTPDepthController.decodeRowBucket(sampledRows.count) - } == true && hasChainedSuccessor && sampledRows.count == finalizedPlainRowCount - guard let elapsed = committedDecodeClock.observe( - completedAtNanos: completedAtNanos, rowIDs: sampledRows, eligible: eligible), - let measurement else { return } + acceptsWorkloadMeasurement(measurement) + else { return } + let eligible = + measurement.map { + $0.costEligible && $0.chained && !$0.seedOnly + && $0.actualDepth == 0 && $0.decision.depth == 0 + && $0.decision.decodeRowBucket + == CBv2MTPDepthController.decodeRowBucket(sampledRows.count) + } == true && hasChainedSuccessor && sampledRows.count == finalizedPlainRowCount + guard + let elapsed = committedDecodeClock.observe( + completedAtNanos: completedAtNanos, rowIDs: sampledRows, eligible: eligible), + let measurement + else { return } depthController.observeCommittedDecodeInterval( decodeRowBucket: measurement.decision.decodeRowBucket, wallTimeNanos: elapsed) } @@ -896,7 +999,8 @@ final class CBv2MTPRoundDriver { } metricsLock.lock() // Warmup is real work even when excluded from steady EWMA. - metrics.totalRoundWallTimeNanos &+= sample?.wallTimeNanos + metrics.totalRoundWallTimeNanos &+= + sample?.wallTimeNanos ?? (wallTimeNanos &+ claimedSeedCostNanos) refreshControllerMetricsLocked() metricsLock.unlock() diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTP.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTP.swift index 9061e85191..e7553d578f 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTP.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTP.swift @@ -13,6 +13,8 @@ extension EngineLoopV2 { /// decodes, frozen-KV drafting, target-authoritative verification, ordinary /// decode neighbors, and per-request prefill chunks. func executeMTPRound(_ plan: CBv2StepPlan) throws -> CBv2InFlightStep? { + try requireNativeWork() + let nativeMark = nativeShutdownState?.rootMark ?? 0 guard let mtp else { return try executeMixed(plan) } let shapes = beginForwardShapeStep() defer { endForwardShapeStep(shapes) } @@ -38,65 +40,95 @@ extension EngineLoopV2 { guard !work.isEmpty else { // Undo optimistic scheduler advances before pending samples can // block waiting admission. - scheduler.rollback(plan) + _ = nativeCommit { scheduler.rollback(plan) } return nil } - // Timing stamps mirror `executeMixed`: admission was stamped in - // `mtpPrepareRoundWork` (before `ensureKVState`); solo prefill - // chunks are stamped inside `mtpBuildRoundGraph`, where each row's - // multimodal input is already bound (MTP rounds never pack). Only - // the decode-shaped one-token prompt chunk is stamped here: one - // compare per decode row, no lookup, no allocation. - for row in work where row.isDecode && row.start < row.rec.request.promptTokens.count { - row.rec.stampPrefillChunkLaunch( - tokens: 1, packed: false, vision: false, stripe: false, - launchNanos: wallStartedNanos) - } + let pagedMTPWork = try CBv2NativePagedMTPWork.make( + backend: backend, states: kvStates, work: work, driver: mtp) + do { + // Timing stamps mirror `executeMixed`: admission was stamped in + // `mtpPrepareRoundWork` (before `ensureKVState`); solo prefill + // chunks are stamped inside `mtpBuildRoundGraph`, where each row's + // multimodal input is already bound (MTP rounds never pack). Only + // the decode-shaped one-token prompt chunk is stamped here: one + // compare per decode row, no lookup, no allocation. + for row in work where row.isDecode && row.start < row.rec.request.promptTokens.count { + row.rec.stampPrefillChunkLaunch( + tokens: 1, packed: false, vision: false, stripe: false, + launchNanos: wallStartedNanos) + } - let graph = try mtpBuildRoundGraph(work, driver: mtp, launchNanos: wallStartedNanos) - scheduler.markPendingSamples(ids: graph.sampledRows) - if let verify = graph.verify { - scheduler.markPendingSamples( - counts: verify.rows.map { (id: $0.id, count: 1 + verify.k) }) - } - mtp.recordSeedSteps(graph.seedRows.count) + let graph = try CBv2NativePagedMTPWork.withConstruction(pagedMTPWork) { + try mtpBuildRoundGraph(work, driver: mtp, launchNanos: wallStartedNanos) + } + scheduler.markPendingSamples(ids: graph.sampledRows) + if let verify = graph.verify { + scheduler.markPendingSamples( + counts: verify.rows.map { (id: $0.id, count: 1 + verify.k) }) + } + mtp.recordSeedSteps(graph.seedRows.count) - asyncEval(graph.asyncEvalTargets) - if CBv2StepProfiler.enabled { - CBv2StepProfiler.record( - "v2.mtp.launch.total", seconds: CFAbsoluteTimeGetCurrent() - buildStart) - } - - let step = CBv2InFlightStep( - assignments: work.map { (id: $0.rec.id, numTokens: $0.count) }, - participants: Set(work.map(\.rec.id)), - sampledRows: graph.sampledRows, - sampledTokens: graph.sampledTokens, - evalTargets: graph.prefillEvalTargets, - computedRanges: Dictionary( - uniqueKeysWithValues: work.map { - ($0.rec.id, $0.start ..< ($0.start + $0.count)) - }), - wallStartedNanos: wallStartedNanos) - step.logprobSegments = graph.logprobSegments - step.logitDiagnostics = graph.diagnostics - step.recurrentEvaluations = graph.recurrentEvaluations - if hybridPrefixCache != nil || completeCheckpointCapture != nil { - step.recurrentCheckpointChunkSizes = Dictionary( - uniqueKeysWithValues: work.map { ($0.rec.id, $0.rec.plannedPrefillChunkSize) }) - } - if graph.verify != nil || !graph.seedRows.isEmpty - || !graph.committedObservationRows.isEmpty - { - step.mtpRound = CBv2MTPRoundInFlight( - verify: graph.verify, - seedRows: graph.seedRows, - seedHidden: graph.seedHidden, - seedPolicyTopTwoValues: graph.seedPolicyTopTwoValues, - committedObservationRows: graph.committedObservationRows) + let step = CBv2InFlightStep( + assignments: work.map { (id: $0.rec.id, numTokens: $0.count) }, + participants: Set(work.map(\.rec.id)), + sampledRows: graph.sampledRows, + sampledTokens: graph.sampledTokens, + evalTargets: graph.prefillEvalTargets, + computedRanges: Dictionary( + uniqueKeysWithValues: work.map { + ($0.rec.id, $0.start ..< ($0.start + $0.count)) + }), + wallStartedNanos: wallStartedNanos) + step.logprobSegments = graph.logprobSegments + step.logitDiagnostics = graph.diagnostics + step.recurrentEvaluations = graph.recurrentEvaluations + if hybridPrefixCache != nil || completeCheckpointCapture != nil { + step.recurrentCheckpointChunkSizes = Dictionary( + uniqueKeysWithValues: work.map { ($0.rec.id, $0.rec.plannedPrefillChunkSize) }) + } + if graph.verify != nil || !graph.seedRows.isEmpty + || !graph.committedObservationRows.isEmpty + { + step.mtpRound = CBv2MTPRoundInFlight( + verify: graph.verify, + seedRows: graph.seedRows, + seedHidden: graph.seedHidden, + seedPolicyTopTwoValues: graph.seedPolicyTopTwoValues, + committedObservationRows: graph.committedObservationRows) + } + step.forwardShapes = shapes + step.nativePagedMTPWork = pagedMTPWork + // Capture historical target windows before any later step can mutate + // their rings. The settled assistant is attached after its real + // observation fence; this boundary never snapshots speculative state. + let historicalRoots = try prepareHistoricalCheckpoints(step) + let evaluationTargets = + graph.asyncEvalTargets + historicalRoots + (pagedMTPWork?.evaluationTargets ?? []) + retainNativeWork( + evaluationTargets, + owners: [step] + + graph.committedObservationRows.map { $0.assistantState as AnyObject } + + (graph.verify?.rows.compactMap { $0.assistantState.map { $0 as AnyObject } } + ?? [])) + try requireNativeWork() + try withError { fault in + asyncEval(evaluationTargets) + try fault.check() + } + pagedMTPWork?.publish() + try nativeWorkSubmitted() + if CBv2StepProfiler.enabled { + CBv2StepProfiler.record( + "v2.mtp.launch.total", seconds: CFAbsoluteTimeGetCurrent() - buildStart) + } + step.nativeRootIDs = nativeShutdownState?.rootIDs(since: nativeMark) ?? [] + shapes?.attach() + return step + } catch { + // The graph-build/submission scope has unwound. Retire only after + // actual drain; a failed required fence keeps all native owners. + pagedMTPWork?.discardAfterBuildFailure() + throw error } - step.forwardShapes = shapes - shapes?.attach() - return step } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift index 0ebafa79a1..b0f13ce046 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift @@ -64,11 +64,27 @@ extension EngineLoopV2 { demoteAllRounds: Bool, launchNanos: UInt64 ) -> [CBv2MTPRowWork] { + // Native page growth evaluates real buffers. Resolve it BEFORE the + // metadata commit, then classify only successful rows under that lock. + var preparedNativeRows: Set? + if (backend as? PagedKVBackend)?.nativeModelBinding != nil { + var ready = Set() + for (id, _) in plan.assignments { + guard let rec = scheduler.record(for: id) else { continue } + rec.stampAdmission(launchNanos: launchNanos) + if ensureKVState(rec) != nil { ready.insert(id) } + } + preparedNativeRows = ready + } + if let tracking = nativeShutdownState { guard tracking.beginCommit() else { return [] } } + defer { nativeShutdownState?.endCommit() } var work: [CBv2MTPRowWork] = [] work.reserveCapacity(plan.assignments.count) for (id, assignedTokens) in plan.assignments { + if let preparedNativeRows, !preparedNativeRows.contains(id) { continue } guard let rec = scheduler.record(for: id) else { continue } + mtp.registerTargetOnlyMedia(rec.request) // Admission stamp BEFORE `ensureKVState`, mirroring // `executeMixed`: a capacity-requeued row is then already // stamped, so its next waiting→running crossing counts as a @@ -145,8 +161,10 @@ extension EngineLoopV2 { if !observationsTransferred { // Keep detached owners alive until the engine fences already // submitted work, then retires the failed cohort explicitly. - for observation in committedObservationRows { - mtp.restoreAssistantState(observation.assistantState, for: observation.id) + _ = nativeCommit { + for observation in committedObservationRows { + mtp.restoreAssistantState(observation.assistantState, for: observation.id) + } } } } @@ -158,8 +176,22 @@ extension EngineLoopV2 { let state = try mtp.takeOrMakeAssistantState( for: row.rec.id, maximumSequenceLength: row.rec.request.promptTokens.count - + max(row.rec.request.maxTokens, 1)) + + max(row.rec.request.maxTokens, 1), + historicalPrefixPromptTokens: row.rec.request.prefixCacheEnabled + && completeCheckpointCapture?.codec.assistant + is any CBv2HistoricalMTPPrefixCheckpointCoding + ? row.rec.request.promptTokens : nil) else { return } + retainNativeWork([], owners: [state]) + let observationDrafter = mtp.drafter as? any CBv2MTPRequestStatefulDrafter + func retainObservationFence() { + if let observationDrafter, + observationDrafter.requiresCommittedObservationFence + { + committedObservationEvalTargets.append( + contentsOf: observationDrafter.evaluationTargets(for: state)) + } + } if let carry = row.historyCarry { mtp.observeCommittedTarget( id: row.rec.id, @@ -167,6 +199,7 @@ extension EngineLoopV2 { tokens: MLXArray([Int32(carry.token)]).reshaped([1, 1]), hidden: carry.hidden), detachedState: state) + retainObservationFence() committedObservationEvalTargets.append(carry.hidden) } mtp.observeCommittedTarget( @@ -174,6 +207,7 @@ extension EngineLoopV2 { observation: CBv2MTPCommittedTargetObservation( tokens: tokens, hidden: hidden), detachedState: state) + retainObservationFence() committedObservationRows.append( .init(id: row.rec.id, assistantState: state)) committedObservationEvalTargets.append(hidden) @@ -181,14 +215,70 @@ extension EngineLoopV2 { if !decodeRows.isEmpty { let inputs = MLXArray(decodeRows.map { Int32($0.rec.tokens[$0.start]) }) .reshaped([decodeRows.count, 1]) - let caches = eagerCaches(rowStates: decodeRows.map { kvStates[$0.rec.id]! }) - let diagnosticOffsets = logitDiagnostic == nil ? nil : decodeRows.map { - Self.positionOffset(kvStates[$0.rec.id]!) - } + var caches = eagerCaches(rowStates: decodeRows.map { kvStates[$0.rec.id]! }) + let diagnosticOffsets = + logitDiagnostic == nil + ? nil + : decodeRows.map { + Self.positionOffset(kvStates[$0.rec.id]!) + } var diagnosticTopTwo: (ids: MLXArray, values: MLXArray)? let logits: MLXArray - let hidden: MLXArray - if let recurrentModel = mtp.model as? any CBv2RecurrentMTPSteppableModel, + let hidden: MLXArray? + // Real hidden rows only. In the opt-in mixed path media uses the + // ordinary target forward, then logits return to ORIGINAL sampler + // row order. No zero/duplicate media hidden-state placeholders. + let hiddenSourceIndices = decodeRows.indices.filter { + !mtp.requiresTargetOnlyMedia(decodeRows[$0].rec.request) + } + let hiddenIndex = Dictionary( + uniqueKeysWithValues: + hiddenSourceIndices.enumerated().map { ($0.element, $0.offset) }) + if hiddenSourceIndices.count != decodeRows.count { + var rowLogits = [MLXArray?](repeating: nil, count: decodeRows.count) + if !hiddenSourceIndices.isEmpty { + let rows = hiddenSourceIndices.map { decodeRows[$0] } + let selected = inputs[MLXArray(hiddenSourceIndices.map(Int32.init))] + let groupCaches = eagerCaches(rowStates: rows.map { kvStates[$0.rec.id]! }) + let output = try checkedModelForward( + phase: rows.allSatisfy { $0.start < $0.rec.request.promptTokens.count } + ? .prefill + : (rows.allSatisfy { $0.start >= $0.rec.request.promptTokens.count } + ? .decode : .mixedFrontier) + ) { mtp.model.forwardWithHidden(tokens: selected, caches: groupCaches) } + hidden = output.lastHidden + for (index, source) in hiddenSourceIndices.enumerated() { + rowLogits[source] = output.logits[index ..< index + 1, 0..., 0...] + } + cacheInnerState.append(contentsOf: eagerCacheInnerState(groupCaches)) + } else { + hidden = nil + } + let mediaIndices = decodeRows.indices.filter { hiddenIndex[$0] == nil } + let rows = mediaIndices.map { decodeRows[$0] } + let selected = inputs[MLXArray(mediaIndices.map(Int32.init))] + let groupCaches = eagerCaches(rowStates: rows.map { kvStates[$0.rec.id]! }) + let output = try checkedModelForward( + phase: rows.allSatisfy { $0.start < $0.rec.request.promptTokens.count } + ? .prefill + : (rows.allSatisfy { $0.start >= $0.rec.request.promptTokens.count } + ? .decode : .mixedFrontier) + ) { model.forward(tokens: selected, caches: groupCaches) } + for (index, source) in mediaIndices.enumerated() { + rowLogits[source] = output[index ..< index + 1, 0..., 0...] + } + cacheInnerState.append(contentsOf: eagerCacheInnerState(groupCaches)) + let ordered = rowLogits.map { value -> MLXArray in + guard let value else { + preconditionFailure("missing target-only media sampler row") + } + return value + } + logits = ordered.count == 1 ? ordered[0] : concatenated(ordered, axis: 0) + // Providers may vend different views per call. Rebind the full + // cohort only after retaining both groups' actual state roots. + caches = eagerCaches(rowStates: decodeRows.map { kvStates[$0.rec.id]! }) + } else if let recurrentModel = mtp.model as? any CBv2RecurrentMTPSteppableModel, recurrentModel.recurrentStateSpec != nil { let evaluations = decodeRows.map { row -> CBv2RecurrentStateEvaluation in @@ -205,11 +295,20 @@ extension EngineLoopV2 { let output = try withQwen4PositionScope( ids: decodeRows.map(\.rec.id), positionIds: positionIds ) { - try checkedModelForward(phase: decodeRows.allSatisfy { $0.start < $0.rec.request.promptTokens.count } - ? .prefill : (decodeRows.allSatisfy { $0.start >= $0.rec.request.promptTokens.count } - ? .decode : .mixedFrontier)) { recurrentModel.forwardWithHidden( - tokens: inputs, caches: caches, recurrentState: evaluations, - positionIds: positionIds) } + try checkedModelForward( + phase: decodeRows.allSatisfy { + $0.start < $0.rec.request.promptTokens.count + } + ? .prefill + : (decodeRows.allSatisfy { + $0.start >= $0.rec.request.promptTokens.count + } + ? .decode : .mixedFrontier) + ) { + recurrentModel.forwardWithHidden( + tokens: inputs, caches: caches, recurrentState: evaluations, + positionIds: positionIds) + } } logits = output.logits hidden = output.lastHidden @@ -222,9 +321,12 @@ extension EngineLoopV2 { recurrentEvaluations[row.rec.id] = evaluation } } else { - let output = try checkedModelForward(phase: decodeRows.allSatisfy { $0.start < $0.rec.request.promptTokens.count } - ? .prefill : (decodeRows.allSatisfy { $0.start >= $0.rec.request.promptTokens.count } - ? .decode : .mixedFrontier)) { mtp.model.forwardWithHidden(tokens: inputs, caches: caches) } + let output = try checkedModelForward( + phase: decodeRows.allSatisfy { $0.start < $0.rec.request.promptTokens.count } + ? .prefill + : (decodeRows.allSatisfy { $0.start >= $0.rec.request.promptTokens.count } + ? .decode : .mixedFrontier) + ) { mtp.model.forwardWithHidden(tokens: inputs, caches: caches) } logits = output.logits hidden = output.lastHidden } @@ -240,7 +342,10 @@ extension EngineLoopV2 { logprobSegments.append(stepLogprobs) } for (index, row) in decodeRows.enumerated() where row.isSeed { - seedRows.append((id: row.rec.id, decodeIndex: index)) + guard let source = hiddenIndex[index] else { + preconditionFailure("target-only media was incorrectly seed-marked") + } + seedRows.append((id: row.rec.id, decodeIndex: source)) } if !seedRows.isEmpty { seedHidden = hidden } if mtp.usesMarginalPolicy, !seedRows.isEmpty { @@ -253,35 +358,42 @@ extension EngineLoopV2 { if logitDiagnostic != nil { diagnosticTopTwo = ( topTwo.ids.reshaped([decodeRows.count, 2]), - topTwo.values.reshaped([decodeRows.count, 2])) + topTwo.values.reshaped([decodeRows.count, 2]) + ) } - seedPolicyTopTwoValues = topTwo.values - .reshaped([decodeRows.count, 1, 2]) - .asType(.float32) + let values = topTwo.values.reshaped([decodeRows.count, 1, 2]).asType(.float32) + seedPolicyTopTwoValues = + hiddenSourceIndices.count == decodeRows.count + ? values : values[MLXArray(hiddenSourceIndices.map(Int32.init))] } if let diagnosticOffsets, let diagnostic = logitDiagnostic { for (index, row) in decodeRows.enumerated() where row.rec.id.raw == diagnostic.configuration.requestID - && row.rec.generatedTokenCount == diagnostic.configuration.outputIndex { + && row.rec.generatedTokenCount == diagnostic.configuration.outputIndex + { let retainedTopTwo = diagnosticTopTwo.map { (ids: $0.ids[index], values: $0.values[index]) } if let packet = makeLogitDiagnostic( logits: logits[index, -1], requestID: row.rec.id, outputIndex: row.rec.generatedTokenCount, - phase: row.start < row.rec.request.promptTokens.count ? "prefill" + phase: row.start < row.rec.request.promptTokens.count + ? "prefill" : row.isSeed ? "seed" : "plain", batchIndex: index, batchSize: decodeRows.count, seedToken: row.rec.tokens[row.start], cacheOffset: diagnosticOffsets[index], policyTopTwo: retainedTopTwo) - { diagnostics.append(packet) } + { + diagnostics.append(packet) + } } } for (index, row) in decodeRows.enumerated() { + guard let hidden, let source = hiddenIndex[index] else { continue } try observeCommittedTarget( row: row, tokens: inputs[index ..< index + 1, 0...], - hidden: hidden[index ..< index + 1, 0..., 0...]) + hidden: hidden[source ..< source + 1, 0..., 0...]) } } @@ -293,7 +405,8 @@ extension EngineLoopV2 { let slice = rec.tokens[row.start ..< row.start + row.count] let inputs = MLXArray(slice.map(Int32.init)).reshaped([1, row.count]) let caches = eagerCaches(rowStates: [kvStates[rec.id]!]) - let diagnosticOffset = logitDiagnostic == nil ? 0 : Self.positionOffset(kvStates[rec.id]!) + let diagnosticOffset = + logitDiagnostic == nil ? 0 : Self.positionOffset(kvStates[rec.id]!) let requirement: CBv2PrefillRequirement = row.samples ? .lastPositionLogits : .evaluationOnly let output: MLXArray @@ -318,6 +431,12 @@ extension EngineLoopV2 { recurrentEvaluations.merge(forward.recurrent) { _, _ in preconditionFailure("duplicate recurrent evaluation") } + } else if mtp.requiresTargetOnlyMedia(rec.request) { + // Text chunks/tails of a media request are ordinary target + // work too; they cannot start a partial assistant history. + output = try prefillOutput( + tokens: inputs, inputEmbeddings: nil, caches: caches, + requirement: requirement) } else if mtp.tracksPersistentHistory, let recurrentModel = mtp.model as? any CBv2RecurrentMTPSteppableModel, recurrentModel.recurrentStateSpec != nil @@ -332,9 +451,11 @@ extension EngineLoopV2 { let positions = rec.request.positionState?.promptSlice( row.start ..< row.start + row.count) let forward = try withQwen4PositionScope(ids: [rec.id], positionIds: positions) { - try checkedModelForward(phase: .prefill) { recurrentModel.forwardWithHiddenForPrefill( - tokens: inputs, caches: caches, recurrentState: [evaluation], - positionIds: positions, requirement: requirement) } + try checkedModelForward(phase: .prefill) { + recurrentModel.forwardWithHiddenForPrefill( + tokens: inputs, caches: caches, recurrentState: [evaluation], + positionIds: positions, requirement: requirement) + } } output = narrowPrefillOutput(forward.logits, requirement: requirement) observedHidden = forward.lastHidden @@ -359,8 +480,20 @@ extension EngineLoopV2 { preconditionFailure("duplicate recurrent evaluation") } } else if mtp.tracksPersistentHistory { - let forward = try checkedModelForward(phase: .prefill) { mtp.model.forwardWithHidden(tokens: inputs, caches: caches) } - output = narrowPrefillOutput(forward.logits, requirement: requirement) + let prefill = mtp.model as? any CBv2MTPPrefillSteppableModel + let forward = try checkedModelForward(phase: .prefill) { + if let prefill { + return prefill.forwardWithHiddenForPrefill( + tokens: inputs, caches: caches, requirement: requirement) + } + return mtp.model.forwardWithHidden(tokens: inputs, caches: caches) + } + // The opt-in seam projects only the required rows already. + // Legacy targets still return full [B,L,vocab] logits. + output = + prefill == nil + ? narrowPrefillOutput(forward.logits, requirement: requirement) + : forward.logits observedHidden = forward.lastHidden } else { output = try prefillOutput( @@ -377,7 +510,9 @@ extension EngineLoopV2 { logits: output[0], requestID: rec.id, outputIndex: rec.generatedTokenCount, phase: "prefill", batchIndex: 0, batchSize: 1, seedToken: slice.last, cacheOffset: diagnosticOffset) - { diagnostics.append(packet) } + { + diagnostics.append(packet) + } prefillSampled[rec.id] = sampler.sample( logits: output, params: [rec.request.sampling], @@ -393,6 +528,7 @@ extension EngineLoopV2 { } } + try CBv2NativePagedMTPWork.current?.finishOrdinaryConstruction() let verifyRows = work.filter { $0.carry != nil } let verify = try mtpBuildVerifyGraph( verifyRows, driver: mtp, cacheInnerState: &cacheInnerState) @@ -477,9 +613,11 @@ extension EngineLoopV2 { // Draft column zero may already be evaluating. Restore its // owner before unwinding; request retirement synchronizes and // calls releaseRequestState before returning capacity. - for row in rowMetadata { - if let state = row.assistantState { - mtp.restoreAssistantState(state, for: row.id) + _ = nativeCommit { + for row in rowMetadata { + if let state = row.assistantState { + mtp.restoreAssistantState(state, for: row.id) + } } } } @@ -530,6 +668,7 @@ extension EngineLoopV2 { if let assistantState = rowMetadata.last?.assistantState, let stateful = mtp.drafter as? any CBv2MTPRequestStatefulDrafter { + retainNativeWork([], owners: [assistantState]) try stateful.configureRequestState( assistantState, maximumSequenceLength: row.rec.request.promptTokens.count @@ -542,7 +681,7 @@ extension EngineLoopV2 { let includesAssistantPrefill = rowMetadata.contains { $0.assistantState?.hasPendingPrefillForCostAccounting == true } - mtpFreezeCaptures(captured) + try mtpFreezeCaptures(captured) let seedColumn = MLXArray(seedTokens).reshaped([batch, 1]) var draftSteps: [MLXArray] = [] draftSteps.reserveCapacity(k) @@ -580,7 +719,13 @@ extension EngineLoopV2 { // constructing a deeper generation. This is nonblocking and // joins the round's sole finalize fence. if draftIndex == 0 { + retainNativeWork( + stepEvalTargets, + owners: rowMetadata.compactMap { $0.assistantState.map { $0 as AnyObject } } + ) + try requireNativeWork() asyncEval(stepEvalTargets) + try nativeWorkSubmitted() mtp.recordEarlyDraftSubmission() } assistantEvalTargets.append(contentsOf: stepEvalTargets) @@ -601,7 +746,10 @@ extension EngineLoopV2 { // this token through the acceptance packet. At depth one, // nextHidden is unused and need not be materialized. if draftIndex == 0 && mtp.drafter.supportsEarlyDraftSubmission { + retainNativeWork([next, nextHidden]) + try requireNativeWork() asyncEval(next) + try nativeWorkSubmitted() mtp.recordEarlyDraftSubmission() } draftSteps.append(next) @@ -618,6 +766,7 @@ extension EngineLoopV2 { // Windowed rows stage provisional writes; other supported storage // backends implement the transaction hooks as exact no-ops/rollback. let verifyStart = CBv2StepProfiler.enabled ? CFAbsoluteTimeGetCurrent() : 0 + try CBv2NativePagedMTPWork.current?.beginVerification(rowMetadata, depth: k) for metadata in rowMetadata { for sequence in metadata.storageRows { sequence.beginSpeculativeWrite() } } @@ -656,7 +805,7 @@ extension EngineLoopV2 { /// for the hazard and the mechanism. private func mtpFreezeCaptures( _ captured: [(row: CBv2SequenceKV, keys: MLXArray, values: MLXArray)] - ) { + ) throws { // Contiguous rows are ARC-owned by their views and need nothing. // `requiresMaterializedSnapshots` is the bit that already documents // exactly this recyclable-storage hazard: true for `PagedKVBackend`, @@ -665,7 +814,10 @@ extension EngineLoopV2 { let unfenceable = CBv2MTPCaptureFence.publish(captured) if !unfenceable.isEmpty { // The fence contract's blunt fallback: one host sync, counted. + retainNativeWork(unfenceable) + try requireNativeWork() eval(unfenceable) + try nativeWorkSubmitted() CBv2CoreInstrumentation.recordHostSync() } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPFinalize.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPFinalize.swift index 882864a8ed..d95a145379 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPFinalize.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPFinalize.swift @@ -6,6 +6,87 @@ import Foundation import MLX extension EngineLoopV2 { + /// Runs before ordinary token finalization and any deferred request frees. + /// Sample-token readback alone need not fence independent assistant roots + /// submitted later. Only explicitly opted-in drafters pay this extra fence. + func finishStatefulMTPEvaluation(_ step: CBv2InFlightStep) { + guard let mtp, let round = step.mtpRound, + let stateful = mtp.drafter as? any CBv2MTPRequestStatefulDrafter, + stateful.requiresCommittedObservationFence + else { return } + let observations = round.committedObservationRows.map { ($0.id, $0.assistantState) } + let verifying = (round.verify?.rows ?? []).compactMap { row in + row.assistantState.map { (row.id, $0) } + } + var seen = Set() + for (id, state) in observations + verifying { + guard seen.insert(ObjectIdentifier(state)).inserted else { continue } + var requiredCompletionFinished = false + var requiredFailureReason: CBv2NativeShutdownFault.Reason = .nativeWorkFailed + do { + let roots = stateful.evaluationTargets(for: state) + if let handle = retainNativeWork(roots, owners: [state]) { + step.nativeRootIDs.append(handle) + } + try requireNativeWork() + if !roots.isEmpty { + try withError { error in + eval(roots) + try error.check() + } + CBv2CoreInstrumentation.recordHostSync() + } + if nativeShutdownState != nil { + try requireNativeWork() + guard let split = stateful as? any CBv2NativeMTPCompletionSplitting else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + // The exact same existing assistant construction fence. + // Never hold the first-winner lock while synchronizing. + requiredFailureReason = .capturedFenceFailed + try nativeRequiredAssistantFenceForTesting?(state) + try split.fenceRequestStateForNativeCompletion(state) + requiredCompletionFinished = true + nativeShutdownState?.afterAssistantFenceForTesting?(state) + guard + try nativeCommitThrowing({ + try split.commitRequestStateNativeCompletion(state) + }) + else { return } + } else { + try stateful.requestStateDidFinishEvaluation(state) + } + } catch { + if let tracking = nativeShutdownState { + guard tracking.mayExecute else { return } + guard requiredCompletionFinished else { + // A failed REQUIRED eval/fence cannot be rehabilitated + // by a later successful general cleanup fence. Preserve + // the original failure and every real owner permanently. + failNativeCompletion(requiredFailureReason) + return + } + // Only post-completion metadata/measurement refusal reaches + // the existing drained error-cleanup path below. + do { try tracking.fenceCapturedStreams() } catch { + failNativeCompletion(.capturedFenceFailed) + return + } + guard tracking.beginCommit() else { return } + } + defer { nativeShutdownState?.endCommit() } + // A recoverable graph/ownership failure must not return capacity + // while earlier submitted work can still reference the state. + if nativeShutdownState == nil { + Stream.gpu.synchronize() + Stream.cpu.synchronize() + } + step.discard.insert(id) + finishRequest(id, reason: .error("assistant evaluation ownership: \(error)")) + } + } + } + /// Minimum target top-K probability mass (parts-per-million) at the /// carry position before the next draft may score only the shortlist /// rows. Below this the shortlist would too often miss the token the @@ -19,6 +100,12 @@ extension EngineLoopV2 { /// rows finalize and before deferred KV releases. func finalizeMTPRound(_ step: CBv2InFlightStep) { guard let mtp, let round = step.mtpRound else { return } + var nativeCommitHeld = false + if let tracking = nativeShutdownState { + guard tracking.beginCommit() else { return } + nativeCommitHeld = true + } + defer { if nativeCommitHeld { nativeShutdownState?.endCommit() } } // Plain prompt/decode observations may own request-state arrays that // the just-fenced target graph referenced. Restore or release them @@ -37,9 +124,21 @@ extension EngineLoopV2 { // The ordinary finalize loop has confirmed each seed row's bonus. if let seedHidden = round.seedHidden { - let seedPolicyTopTwo = - round.seedPolicyTopTwoValues?.asArray(Float.self) + if nativeCommitHeld { + nativeShutdownState?.endCommit() + nativeCommitHeld = false + } + var seedPolicyTopTwo: [Float]? + guard + completedNativeReadback({ + seedPolicyTopTwo = round.seedPolicyTopTwoValues?.asArray(Float.self) + }) + else { return } if seedPolicyTopTwo != nil { CBv2CoreInstrumentation.recordHostSync() } + if let tracking = nativeShutdownState { + guard tracking.beginCommit() else { return } + nativeCommitHeld = true + } for (id, decodeIndex) in round.seedRows { guard !step.discard.contains(id), let rec = scheduler.record(for: id) @@ -68,10 +167,24 @@ extension EngineLoopV2 { // three readbacks (`CBv2Logprobs.assemble`); a round whose capture // could not be fenced adds one blocking eval (`CBv2MTPCaptureFence` // fallback in `EngineLoopV2+MTPExecution`). - let host = verify.acceptancePacket.asArray(Int32.self) - CBv2CoreInstrumentation.recordHostSync() - let policyTopTwoHost = verify.policyTopTwoValues?.asArray(Float.self) + if nativeCommitHeld { + nativeShutdownState?.endCommit() + nativeCommitHeld = false + } + var host: [Int32] = [] + var policyTopTwoHost: [Float]? + guard + completedNativeReadback({ + host = verify.acceptancePacket.asArray(Int32.self) + CBv2CoreInstrumentation.recordHostSync() + policyTopTwoHost = verify.policyTopTwoValues?.asArray(Float.self) + }) + else { return } if policyTopTwoHost != nil { CBv2CoreInstrumentation.recordHostSync() } + if let tracking = nativeShutdownState { + guard tracking.beginCommit() else { return } + nativeCommitHeld = true + } let draftCount = verify.rows.count * k let targetWidth = 1 + k var anyRejected = false @@ -176,7 +289,25 @@ extension EngineLoopV2 { break } if hasStopStrings { - textPieces.append(detokenizer?.push([token]) ?? "") + var hostLoan: UUID? + if let tracking = nativeShutdownState { + guard + let loan = try? tracking.beginLoan( + owner: detokenizer, duringDrain: true) + else { return } + hostLoan = loan + if nativeCommitHeld { + tracking.endCommit() + nativeCommitHeld = false + } + } + let text = detokenizer?.push([token]) ?? "" + if let tracking = nativeShutdownState { + guard tracking.beginCommit() else { return } + nativeCommitHeld = true + if let hostLoan { tracking.endLoan(hostLoan) } + } + textPieces.append(text) if detokenizer?.matchedStopString == true { finishReason = .stop break @@ -278,11 +409,15 @@ extension EngineLoopV2 { let endsWithStopToken = finishReason == .stop let pushTokens = endsWithStopToken ? Array(kept.dropLast()) : kept let allTokens = kept - detokQueue.async { + let trackedLoop = nativeShutdownState == nil ? nil : self + enqueueDetokenization(owner: detokenizer) { let text = pushTokens.isEmpty ? "" : (detokenizer?.push(pushTokens) ?? "") - stream?.emit( - .delta(text: text, tokens: allTokens, logprobs: nil), - consumingReservation: true) + let publish: () -> Void = { + stream?.emit( + .delta(text: text, tokens: allTokens, logprobs: nil), + consumingReservation: true) + } + if let trackedLoop { _ = trackedLoop.nativeCommit(publish) } else { publish() } } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPPlanning.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPPlanning.swift index 800539df7e..148fadeffd 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPPlanning.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPPlanning.swift @@ -17,6 +17,10 @@ extension EngineLoopV2 { /// per-position transforms the verify pre-sampler does not reproduce, /// and stop strings need the serial detokenizer walk. func mtpBasicEligible(_ rec: CBv2ScheduledRequest) -> Bool { + // Opted-in native media is target-only for its complete immutable + // request lifetime, including text tails, preemption and recompute. + mtp?.registerTargetOnlyMedia(rec.request) + if mtp?.requiresTargetOnlyMedia(rec.request) == true { return false } let sampling = rec.request.sampling let samplingEligible = sampling.temperature == 0 @@ -51,6 +55,20 @@ extension EngineLoopV2 { !hasSpans || !tracksPersistentHistory } + /// Only the explicit native fallback may remove media/ineligible rows from + /// the head batch count, and only in a cohort actually containing media. + /// All-row target costs, token/KV headroom and reservations stay unchanged. + /// With no opt-in/media, return the historical cohort verbatim. + private func mtpDraftBatchRows(_ rows: [CBv2ScheduledRequest]) -> [CBv2ScheduledRequest] { + guard let mtp, rows.contains(where: { mtp.requiresTargetOnlyMedia($0.request) }) else { + return rows + } + return rows.filter { rec in + guard mtpBasicEligible(rec), let state = kvStates[rec.id] else { return false } + return Self.mtpStorageEligible(state) + } + } + /// Every storage-owning row must support value-exact multi-token writes /// and rollback. Kept internal for backend contract tests. static func mtpStorageEligible(_ state: [CBv2SequenceKV?]) -> Bool { @@ -123,9 +141,13 @@ extension EngineLoopV2 { if mtp.config.fixedDraftTokens == 0, mtp.usesRequestStatefulDrafter { return false } - let withinBatchGate = ids.count <= mtp.config.maxSpeculativeBatch - let canSpeculate = withinBatchGate && rows.count == ids.count - && mtpRowsCanSpeculate(rows) + let batchRows = mtpDraftBatchRows(rows) + // Preserve the old ids.count guard for unresolved/stale ids too. + let withinBatchGate = + batchRows.count + (ids.count - rows.count) <= mtp.config.maxSpeculativeBatch + let canSpeculate = + withinBatchGate && rows.count == ids.count + && mtpRowsCanSpeculate(batchRows) let decision = mtp.previewDecision( plannedDecodeRows: ids.count, canSpeculate: canSpeculate) let eligible = rows.filter { rec in @@ -177,8 +199,9 @@ extension EngineLoopV2 { let rows = scheduler.running.filter { !$0.isPaused && !$0.cancelRequested && $0.isDecodeReady } - let withinBatchGate = rows.count <= mtp.config.maxSpeculativeBatch - let canSpeculate = withinBatchGate && mtpRowsCanSpeculate(rows) + let batchRows = mtpDraftBatchRows(rows) + let withinBatchGate = batchRows.count <= mtp.config.maxSpeculativeBatch + let canSpeculate = withinBatchGate && mtpRowsCanSpeculate(batchRows) mtp.beginPlan( plannedDecodeRows: rows.count, canSpeculate: canSpeculate, rowIDs: rows.map(\.id)) @@ -187,7 +210,6 @@ extension EngineLoopV2 { return Self.mtpStorageEligible(state) } - if mtp.shouldApplyMarginalPolicyToPlan, mtp.planDepth > 0, !eligibleRows.isEmpty { @@ -252,15 +274,16 @@ extension EngineLoopV2 { } } if !rows.isEmpty, !withinBatchGate { - for _ in rows { mtp.recordSkip("batch_gate") } + for _ in batchRows { mtp.recordSkip("batch_gate") } } } private func mtpRowsCanSpeculate(_ rows: [CBv2ScheduledRequest]) -> Bool { - !rows.isEmpty && rows.allSatisfy { rec in - guard mtpBasicEligible(rec), let state = kvStates[rec.id] else { return false } - return Self.mtpStorageEligible(state) - } + !rows.isEmpty + && rows.allSatisfy { rec in + guard mtpBasicEligible(rec), let state = kvStates[rec.id] else { return false } + return Self.mtpStorageEligible(state) + } } /// True when this scheduler plan carries seed or verify work. diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPTargetVerification.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPTargetVerification.swift index 57a6d7ab81..2c011b4a14 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPTargetVerification.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPTargetVerification.swift @@ -46,9 +46,12 @@ extension EngineLoopV2 { var recurrent: [CBv2RequestID: [CBv2RecurrentStateEvaluation]] = [:] var capturedInnerState: [MLXArray] = [] var diagnostics: [CBv2LogitDiagnosticPacket] = [] - let diagnosticOffsets = logitDiagnostic == nil ? nil : rows.map { - Self.positionOffset(kvStates[$0.rec.id]!) - } + let diagnosticOffsets = + logitDiagnostic == nil + ? nil + : rows.map { + Self.positionOffset(kvStates[$0.rec.id]!) + } let recurrentModel = (mtp.model as? any CBv2RecurrentMTPSteppableModel).flatMap { model in @@ -96,7 +99,10 @@ extension EngineLoopV2 { let localColumn = column - columnOffset guard localColumn >= 0, localColumn < logits.dim(1) else { continue } let retainedTopTwo = topTwo.map { - (ids: $0.ids[batchIndex, localColumn], values: $0.values[batchIndex, localColumn]) + ( + ids: $0.ids[batchIndex, localColumn], + values: $0.values[batchIndex, localColumn] + ) } if let packet = makeLogitDiagnostic( logits: logits[batchIndex, localColumn], requestID: row.rec.id, @@ -105,16 +111,19 @@ extension EngineLoopV2 { verificationWidth: columns.count, draftDepth: columns.count - 1, seedToken: row.carry?.token, cacheOffset: diagnosticOffsets[batchIndex], policyTopTwo: retainedTopTwo) - { diagnostics.append(packet) } + { + diagnostics.append(packet) + } } } - var useRectangular = switch mtp.config.verificationMode { - case .serialTarget: false - case .rectangular, .rectangularExact: true - case .automatic: - columns.count * columns[0].dim(0) <= mtp.config.maxAutomaticRectangularTokens - } + var useRectangular = + switch mtp.config.verificationMode { + case .serialTarget: false + case .rectangular, .rectangularExact: true + case .automatic: + columns.count * columns[0].dim(0) <= mtp.config.maxAutomaticRectangularTokens + } // A recurrent target may only verify rectangularly through the // captured-window seam. Stateful production never falls back to @@ -124,7 +133,8 @@ extension EngineLoopV2 { { if mtp.usesRequestStatefulDrafter { preconditionFailure( - "CBv2 production request-stateful MTP requires captured rectangular verification") + "CBv2 production request-stateful MTP requires captured rectangular verification" + ) } mtp.recordControllerFallback("captured_verify_unsupported") useRectangular = false @@ -153,7 +163,8 @@ extension EngineLoopV2 { if serializingCaches.count != caches.count { if mtp.usesRequestStatefulDrafter, recurrentModel != nil { preconditionFailure( - "CBv2 production request-stateful MTP cache lacks rectangular serialization") + "CBv2 production request-stateful MTP cache lacks rectangular serialization" + ) } mtp.recordControllerFallback("rectangular_cache_unsupported") useRectangular = false @@ -167,6 +178,8 @@ extension EngineLoopV2 { scoreColumnsAccum.reserveCapacity(columns.count) hiddenColumns.reserveCapacity(columns.count) for (columnIndex, column) in columns.enumerated() { + let nativePagedWork = CBv2NativePagedMTPWork.current + let columnWork = try nativePagedWork?.prepareColumn(columnIndex) precondition(column.dim(1) == 1, "CBv2 MTP: serial target column must have L=1") let output: (logits: MLXArray, lastHidden: MLXArray) var recurrentArrays: [MLXArray] = [] @@ -184,10 +197,14 @@ extension EngineLoopV2 { let positionIds = CBv2PositionState.decodePositionIds( states: rows.map(\.rec.request.positionState), cacheOffsets: rows.map { Self.positionOffset(kvStates[$0.rec.id]!) }) - output = try withQwen4PositionScope(ids: rows.map(\.rec.id), positionIds: positionIds) { - try checkedModelForward(phase: .mtpVerification) { recurrentModel.forwardWithHidden( - tokens: column, caches: caches, recurrentState: evaluations, - positionIds: positionIds) } + output = try withQwen4PositionScope( + ids: rows.map(\.rec.id), positionIds: positionIds + ) { + try checkedModelForward(phase: .mtpVerification) { + recurrentModel.forwardWithHidden( + tokens: column, caches: caches, recurrentState: evaluations, + positionIds: positionIds) + } } for (row, evaluation) in zip(rows, evaluations) { do { recurrentArrays.append(contentsOf: try evaluation.evaluate()) } catch { @@ -197,7 +214,9 @@ extension EngineLoopV2 { recurrent[row.rec.id, default: []].append(evaluation) } } else { - output = try checkedModelForward(phase: .mtpVerification) { mtp.model.forwardWithHidden(tokens: column, caches: caches) } + output = try checkedModelForward(phase: .mtpVerification) { + mtp.model.forwardWithHidden(tokens: column, caches: caches) + } } captureDiagnostics( output.logits, columnOffset: columnIndex, phase: "serial_verify") @@ -206,11 +225,18 @@ extension EngineLoopV2 { // let mutable KV buffers observe a later version. Complete // each canonical target step before constructing the next. var evaluationTargets = - [columnScores, output.lastHidden] + eagerCacheInnerState(caches) + recurrentArrays + [columnScores, output.lastHidden] + eagerCacheInnerState(caches) + + recurrentArrays for packet in diagnostics where packet.column == columnIndex { evaluationTargets.append(contentsOf: packet.evaluationTargets) } + retainNativeWork(evaluationTargets) + try requireNativeWork() eval(evaluationTargets) + try nativeWorkSubmitted() + if let nativePagedWork, let columnWork { + try nativePagedWork.completeColumn(columnWork) + } // One blocking evaluation per serial verify column, counted. CBv2CoreInstrumentation.recordHostSync() scoreColumnsAccum.append(columnScores) @@ -222,7 +248,8 @@ extension EngineLoopV2 { } else { for cache in serializingCaches { cache.mtpSerializesRectangularAttention = true - cache.mtpBatchesRectangularAttention = mtp.drafter.prefersBatchedRectangularAttention + cache.mtpBatchesRectangularAttention = + mtp.drafter.prefersBatchedRectangularAttention } defer { for cache in serializingCaches { @@ -252,10 +279,14 @@ extension EngineLoopV2 { states: rows.map(\.rec.request.positionState), cacheOffsets: rows.map { Self.positionOffset(kvStates[$0.rec.id]!) }, length: tokens.dim(1)) - output = try withQwen4PositionScope(ids: rows.map(\.rec.id), positionIds: positionIds) { - try checkedModelForward(phase: .mtpVerification) { recurrentModel.forwardWithHiddenCaptured( - tokens: tokens, caches: caches, recurrentState: evaluations, - positionIds: positionIds) } + output = try withQwen4PositionScope( + ids: rows.map(\.rec.id), positionIds: positionIds + ) { + try checkedModelForward(phase: .mtpVerification) { + recurrentModel.forwardWithHiddenCaptured( + tokens: tokens, caches: caches, recurrentState: evaluations, + positionIds: positionIds) + } } for (row, evaluation) in zip(rows, evaluations) { precondition( @@ -270,7 +301,9 @@ extension EngineLoopV2 { recurrent[row.rec.id] = [evaluation] } } else { - output = try checkedModelForward(phase: .mtpVerification) { mtp.model.forwardWithHidden(tokens: tokens, caches: caches) } + output = try checkedModelForward(phase: .mtpVerification) { + mtp.model.forwardWithHidden(tokens: tokens, caches: caches) + } } if mtp.usesRequestStatefulDrafter { guard let provider = mtp.model as? any CBv2MTPPolicyTopTwoProviding else { @@ -284,7 +317,8 @@ extension EngineLoopV2 { let topTwo = provider.cbv2MTPTopTwo(flat) policyTopTwo = ( topTwo.ids.reshaped([batch, width, 2]).asType(.int32), - topTwo.values.reshaped([batch, width, 2]).asType(.float32)) + topTwo.values.reshaped([batch, width, 2]).asType(.float32) + ) } if useTargetPrefix { scores = scoreColumns(output.logits, columnOffset: 0) @@ -310,7 +344,8 @@ extension EngineLoopV2 { return ( scores, hidden, shortlist, policyTopTwo, - eagerCacheInnerState(caches) + capturedInnerState, diagnostics, recurrent) + eagerCacheInnerState(caches) + capturedInnerState, diagnostics, recurrent + ) } /// Top-`size` token ids per verify position plus their probability mass diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/HistoricalMTPPrefixCheckpoint.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/HistoricalMTPPrefixCheckpoint.swift new file mode 100644 index 0000000000..56ba4409a1 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/HistoricalMTPPrefixCheckpoint.swift @@ -0,0 +1,21 @@ +import Foundation + +/// Package-only complete historical-assistant capability. Target KV alone is +/// not an assistant checkpoint, and a generic recurrent codec cannot opt in. +/// The request's existing bounded admission must cover the context's complete +/// retained host/native storage before installation; this is not a new lease. +package protocol CBv2HistoricalMTPPrefixCheckpointCoding: CBv2MTPPrefixCheckpointCoding { + /// Install once on a fresh current-owner/generation state before observing + /// any target input. Capture subsequently requires a settled interior prompt + /// boundary, exact observed token evidence, and no pending/round/carry state. + func installPrefixCaptureContext( + requestState: any CBv2MTPRequestState, promptTokens: [Int] + ) throws + + /// Retention only, not an admission grant. Authenticated import binds its + /// actual charged backing before exposing the decoded checkpoint. Capture + /// values must refuse this operation to avoid an owner/checkpoint cycle. + func bindImportedPrefixCheckpointOwner( + _ checkpoint: any CBv2MTPPrefixCheckpoint, owner: AnyObject + ) throws +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift index c3e7d329e3..f9b8ca615e 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift @@ -130,15 +130,18 @@ public protocol CBv2MTPSteppableModel: CBv2SteppableModel { /// nil when the underlying model cannot drive MTP (adapters over /// arbitrary models answer at runtime). var mtpCaptureLayers: CBv2MTPCaptureLayers? { get } - /// True only when the target has the recurrent hidden/state transaction - /// seam required by a request-stateful assistant. + /// True only when this exact target implements the hidden/history contract + /// required by its request-stateful assistant. Attention-only targets may + /// opt in; recurrent targets still require their separate transaction seam. var supportsRequestStatefulMTP: Bool { get } /// Identity of the exact target instance that owns verification logits, /// hidden states, and KV. nil means compatibility cannot be proven and /// must fail safe to plain decode. var mtpTargetIdentity: ObjectIdentifier? { get } - /// Forward returning logits [B, L, vocab] and pre-norm last hidden - /// [B, L, hidden]. Same cache/attention semantics as `forward`. + /// Forward returning logits [B, L, vocab] and target hidden [B, L, hidden] + /// at the trained boundary agreed with this exact drafter (for example, + /// MiMo next-N consumes post-final-norm features). Existing families retain + /// their original boundary. Same cache/attention semantics as `forward`. func forwardWithHidden(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> (logits: MLXArray, lastHidden: MLXArray) } @@ -148,6 +151,19 @@ extension CBv2MTPSteppableModel { public var supportsRequestStatefulMTP: Bool { false } } +/// Optional attention-only prefill refinement. Preserve every hidden row needed +/// by the assistant while projecting only the vocabulary rows requested by the +/// engine. Nonconforming targets keep their existing full-logit fallback. +/// The logits result is already narrowed: `[B, 1]` for evaluation-only and +/// `[B, vocab]` for last-position logits. Hidden rows remain `[B, L, hidden]`. +/// Consumers must not apply the full `[B, L, vocab]` fallback slicing again. +public protocol CBv2MTPPrefillSteppableModel: CBv2MTPSteppableModel { + func forwardWithHiddenForPrefill( + tokens: MLXArray, caches: [CBv2AttendingLayerCache], + requirement: CBv2PrefillRequirement + ) -> (logits: MLXArray, lastHidden: MLXArray) +} + /// Engine-facing recurrent hidden-capture refinement. A recurrent MTP target /// is only activated when this seam and request-owned recurrent state are both /// present, so no call can silently fall through to the stateless forward. @@ -182,8 +198,9 @@ extension CBv2RecurrentMTPSteppableModel { recurrentState: [CBv2RecurrentStateEvaluation], positionIds: MLXArray?, requirement: CBv2PrefillRequirement ) -> (logits: MLXArray, lastHidden: MLXArray) { - forwardWithHidden(tokens: tokens, caches: caches, recurrentState: recurrentState, - positionIds: positionIds) + forwardWithHidden( + tokens: tokens, caches: caches, recurrentState: recurrentState, + positionIds: positionIds) } /// Fail-safe defaults for first-generation recurrent targets: no @@ -319,6 +336,9 @@ public protocol CBv2MTPRequestState: AnyObject { var committedInputCount: Int { get } var stagedInputCount: Int { get } /// Actual materialized device-array residency currently owned by this state. + /// A state refining CBv2MTPRequestResidencyReporting may expose a measured + /// retained subset during lazy transitions, but MUST set its unknown flag. + /// This telemetry is not process-ledger materialization credit. var materializedBytes: Int { get } /// Before drafting: true when queued history requires preparation beyond /// a normal steady decode round. Accounting only; never suppresses work. @@ -330,7 +350,15 @@ extension CBv2MTPRequestState { public var hasPendingPrefillForCostAccounting: Bool { false } } -/// Trusted target inputs and their corresponding pre-norm hidden rows. +/// Explicit precision for assistants that retain measured old backing while a +/// new lazy generation is in flight. Never present a partial measurement as the +/// full current residency or use it to reduce conservative admission reserves. +public protocol CBv2MTPRequestResidencyReporting: CBv2MTPRequestState { + var hasUnmeasuredResidency: Bool { get } +} + +/// Trusted target inputs and corresponding hidden rows at the target/drafter's +/// declared trained boundary. No cross-family normalization is performed here. /// Both arrays remain lazy and device-resident until the engine's existing /// finalize fence. public struct CBv2MTPCommittedTargetObservation { @@ -347,6 +375,11 @@ public struct CBv2MTPCommittedTargetObservation { /// Calls are row-local so histories and assistant-cache offsets may differ; /// the target verifier may still batch the resulting columns as `[B,1]`. public protocol CBv2MTPRequestStatefulDrafter: CBv2MTPDrafter { + /// Opt in only when observation builds lazy assistant-state mutations that + /// must join the current target-step fence. Default false preserves existing + /// drafters' scheduling. The engine retains evaluation roots after EACH + /// observation, including a preceding carry, before another mutation occurs. + var requiresCommittedObservationFence: Bool { get } func makeRequestState() -> any CBv2MTPRequestState /// Bind the admitted request's complete logical bound before the state /// allocates request-owned storage. Stateful assistants whose allocator @@ -379,6 +412,12 @@ public protocol CBv2MTPRequestStatefulDrafter: CBv2MTPDrafter { /// Device arrays that make assistant-cache mutation part of the round's /// evaluation fence. func evaluationTargets(for requestState: any CBv2MTPRequestState) -> [MLXArray] + /// Opt-in observation-fenced assistants receive this after all current + /// evaluationTargets have completed, before finalization/retirement. A + /// model may drain its retained construction stream and reconcile measured + /// owners here, never in telemetry getters. Errors terminate that request + /// recoverably after the native work drains. Default is a no-op. + func requestStateDidFinishEvaluation(_ requestState: any CBv2MTPRequestState) throws /// Complete one staged round. The drafter stages the seed plus every /// proposal it consumes while chaining; `confirmedInputTokens` is the /// exact prefix of those inputs that became canonical target history. @@ -394,7 +433,9 @@ public protocol CBv2MTPRequestStatefulDrafter: CBv2MTPDrafter { } extension CBv2MTPRequestStatefulDrafter { + public var requiresCommittedObservationFence: Bool { false } public var draftShortlistSize: Int? { nil } + public func requestStateDidFinishEvaluation(_ requestState: any CBv2MTPRequestState) throws {} public func configureRequestState( _ requestState: any CBv2MTPRequestState, maximumSequenceLength: Int ) throws {} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MultimodalV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MultimodalV2.swift index 68c5a681c5..3cac9b61b2 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MultimodalV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MultimodalV2.swift @@ -78,6 +78,23 @@ public protocol CBv2PackedSpanMaskBinding: CBv2SpanMaskBinding { // MARK: - Model surfaces +/// Position contract for causal embedding substitution. Most existing causal +/// VLMs require request-owned positions (for example Qwen M-RoPE). A model whose +/// native position semantics are the ordinary per-row scalar cache offset may +/// explicitly select that requirement instead. This is a model property, never +/// a request flag, execution ticket, or permission for tracked native media. +public enum CBv2CausalPositionRequirement: Sendable, Equatable { + case requestOwned + case scalarCacheOffset +} + +/// Optional attention-specific backend admission. A native causal-only owner +/// can accept embedding substitution without pretending to implement a +/// bidirectional span-mask setter. Existing providers retain the old gate. +public protocol CBv2MultimodalAttentionCapabilityProviding: CBv2LayerCacheProvider { + func supportsMultimodalPrefill(attention: CBv2MultimodalAttention) -> Bool +} + /// Steppable models that can prefill from spliced input embeddings. /// Additive refinement of `CBv2SteppableModel`; models that do not conform /// (or conform with `supportsMultimodalPrefill == false`) reject multimodal @@ -86,6 +103,8 @@ public protocol CBv2MultimodalSteppableModel: CBv2SteppableModel { /// True when the underlying model actually supports the embedding /// forward (adapters over arbitrary models answer at runtime). var supportsMultimodalPrefill: Bool { get } + /// Default preserves the required-position gate for existing causal VLMs. + var causalPositionRequirement: CBv2CausalPositionRequirement { get } func supportsMultimodalPrefill(attention: CBv2MultimodalAttention) -> Bool /// The scaled text-token embeddings exactly as the model's trunk would /// compute before layer 0 (`embed(tokens) * embedScale` for Gemma-class @@ -138,7 +157,6 @@ public protocol CBv2PositionedEmbeddingSteppableModel: CBv2MultimodalSteppableMo ) -> MLXArray } - /// Optional request-owned refinement for models whose embedding forward also /// needs recurrent transactions and/or explicit model positions. public protocol CBv2PositionedMultimodalSteppableModel: CBv2MultimodalSteppableModel { @@ -153,6 +171,7 @@ public protocol CBv2PositionedMultimodalSteppableModel: CBv2MultimodalSteppableM extension CBv2MultimodalSteppableModel { public var supportsMultimodalPrefill: Bool { true } + public var causalPositionRequirement: CBv2CausalPositionRequirement { .requestOwned } public func supportsMultimodalPrefill(attention: CBv2MultimodalAttention) -> Bool { supportsMultimodalPrefill } @@ -216,12 +235,10 @@ public protocol CBv2PositionedEmbeddingForwardable: CBv2EmbeddingForwardable { ) -> MLXArray } - extension CBv2EmbeddingForwardable { public var supportsCausalVisionPrefill: Bool { false } } - /// Model-level embedding forward with request-owned recurrent state and /// explicit positions. Recurrent hybrids use this; Gemma remains legacy. public protocol CBv2PositionedRecurrentEmbeddingForwardable: CBv2EmbeddingForwardable { @@ -300,7 +317,8 @@ struct CBv2ResolvedMultimodal: @unchecked Sendable { let relativeHi = hi - span.tokenOffset return ( CBv2ImageSpan(tokenOffset: lo, length: hi - lo), - embedding[0..., relativeLo ..< relativeHi, 0...]) + embedding[0..., relativeLo ..< relativeHi, 0...] + ) } } @@ -385,7 +403,11 @@ enum CBv2MultimodalPlan { // tokens need no span-mask binding, but retaining the backend gate // keeps the media path's compact/position semantics off unproven // paged caches until an explicit paged VLM test exists. - guard cacheProvider.supportsMultimodalSpans else { + let backendSupportsInput = + (cacheProvider as? any CBv2MultimodalAttentionCapabilityProviding)? + .supportsMultimodalPrefill(attention: input.attention) + ?? cacheProvider.supportsMultimodalSpans + guard backendSupportsInput else { throw CBv2MultimodalError.unsupportedBackend( "\(type(of: cacheProvider)) cannot honor multimodal prefill") } @@ -412,7 +434,8 @@ enum CBv2MultimodalPlan { previousEnd = span.end } - let blocks = input.attention == .bidirectionalSpans + let blocks = + input.attention == .bidirectionalSpans ? coalescedBlocks(spans: spans) : [] if let oversized = blocks.first(where: { $0.length > maxBatchedTokensPerStep }) { throw CBv2MultimodalError.spanTooLong( @@ -456,7 +479,8 @@ enum CBv2MultimodalPlan { let provided = try input.embeddings() let providedDeepstack = try input.deepstackEmbeddings?() ?? [] let hidden = mmModel.embedPromptTokens( - MLXArray(Int32(0)).reshaped([1, 1])).dim(-1) + MLXArray(Int32(0)).reshaped([1, 1]) + ).dim(-1) func normalize(_ arrays: [MLXArray], label: String) throws -> [MLXArray] { guard arrays.count == spans.count else { @@ -471,15 +495,18 @@ enum CBv2MultimodalPlan { case 3 where array.dim(0) == 1: shaped = array default: throw CBv2MultimodalError.embeddingMismatch( - "\(label) span \(i) has shape \(array.shape); expected [length, hidden] or [1, length, hidden]") + "\(label) span \(i) has shape \(array.shape); expected [length, hidden] or [1, length, hidden]" + ) } guard shaped.dim(1) == span.length else { throw CBv2MultimodalError.embeddingMismatch( - "\(label) span \(i) covers \(shaped.dim(1)) tokens; span length is \(span.length)") + "\(label) span \(i) covers \(shaped.dim(1)) tokens; span length is \(span.length)" + ) } guard shaped.dim(2) == hidden else { throw CBv2MultimodalError.embeddingMismatch( - "\(label) span \(i) hidden dim \(shaped.dim(2)) != model hidden dim \(hidden)") + "\(label) span \(i) hidden dim \(shaped.dim(2)) != model hidden dim \(hidden)" + ) } return shaped } @@ -493,7 +520,8 @@ enum CBv2MultimodalPlan { (model as? CBv2DeepstackMultimodalSteppableModel)?.deepstackLayerCount ?? 0 guard normalizedDeepstack.count == expectedDeepstackLayers else { throw CBv2MultimodalError.embeddingMismatch( - "DeepStack returned \(normalizedDeepstack.count) layers; model expects \(expectedDeepstackLayers)") + "DeepStack returned \(normalizedDeepstack.count) layers; model expects \(expectedDeepstackLayers)" + ) } if !normalizedDeepstack.isEmpty, !(model is CBv2DeepstackMultimodalSteppableModel) diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/NativeKVTypeProbe.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/NativeKVTypeProbe.swift index dcd91b62a1..f7a3392b2a 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/NativeKVTypeProbe.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/NativeKVTypeProbe.swift @@ -29,70 +29,138 @@ public enum CBv2NativeKVTypeProbe { /// supplied caches. The returned value contains no native array aliases. public static func run( model: any CBv2SteppableModel, layerKinds: [CBv2LayerKind], - caches: [any CBv2AttendingLayerCache], token: Int32 = 0 + caches: [any CBv2AttendingLayerCache], token: Int32 = 0, + retaining work: NativeConstructionScope? = nil + ) throws -> Result { + if let work { + return try work.withPhase(.nativeKVProbe) { + // The tracked baseline is attention-only. Do not claim that + // arbitrary recurrent transactions' private cleanup is tracked. + guard !(model is any CBv2RecurrentSteppableModel) else { + throw invalid("tracked construction requires an attention-only model") + } + try work.retainValue(model) + try work.retainValue(caches) + try work.capture(StreamOrDevice.cpu.stream) + try work.capture(StreamOrDevice.default.stream) + return try runInScope( + model: model, layerKinds: layerKinds, + caches: caches, token: token, work: work) + } + } + return try runInScope( + model: model, layerKinds: layerKinds, + caches: caches, token: token, work: nil) + } + + private static func runInScope( + model: any CBv2SteppableModel, layerKinds: [CBv2LayerKind], + caches: [any CBv2AttendingLayerCache], token: Int32, + work: NativeConstructionScope? ) throws -> Result { guard token >= 0, !layerKinds.isEmpty, caches.count == layerKinds.count, - layerKinds.allSatisfy({ $0.kvHeads > 0 && $0.headDim > 0 }), + layerKinds.allSatisfy({ + $0.kvGeometry != nil && $0.queryHeads > 0 + && $0.queryHeads.isMultiple(of: $0.kvHeads) + }), zip(caches, layerKinds).allSatisfy({ $0.0.rows.isEmpty && $0.0.kind == $0.1 }) else { throw invalid("probe requires fresh matching model caches") } + // Reject invalid ownership before binding rows or calling the model. + // Attention's nonthrowing borrowing seam has programmer preconditions; + // this public throwing probe must not defer metadata validation until + // after that seam has already run (and possibly mutated an owner row). + for (index, kind) in layerKinds.enumerated() { + guard let source = kind.sharesKVWithLayer else { continue } + guard layerKinds.indices.contains(source), layerKinds[source].sharesKVWithLayer == nil, + layerKinds[source].kvHeads == kind.kvHeads, + layerKinds[source].headDim == kind.headDim, + layerKinds[source].valueHeadDim == kind.valueHeadDim, + layerKinds[source].attention == kind.attention + else { throw invalid("layer \(index) has an invalid KV owner") } + } let recorders = layerKinds.enumerated().map { index, kind -> RecordingRow? in guard kind.sharesKVWithLayer == nil else { return nil } - return RecordingRow(index: index, kind: kind) + return RecordingRow(index: index, kind: kind, captureProjections: work != nil) } + for case let row? in recorders { try work?.retainOwner(row) } for index in layerKinds.indices { caches[index].setRows(recorders[index].map { [$0] } ?? []) } - defer { for cache in caches { cache.setRows([]) } } + var completedForCleanup = work == nil + defer { if completedForCleanup { for cache in caches { cache.setRows([]) } } } let recurrentModel = model as? any CBv2RecurrentSteppableModel - let recurrent = try recurrentModel?.recurrentStateSpec.map(CBv2RecurrentRequestState.init(spec:)) + let recurrent = try recurrentModel?.recurrentStateSpec.map( + CBv2RecurrentRequestState.init(spec:)) defer { try? recurrent?.release() } - var observations: [Observation] = [] - for phase: Phase in [.prefill, .decode] { - let count = phase == .prefill ? 2 : 1 - for case let row? in recorders { row.begin(phase: phase, count: count) } - try withError { error in - let tokens = MLXArray(Array(repeating: token, count: count)).reshaped([1, count]) - try error.check() - let transaction = try recurrent?.bind() - defer { try? transaction?.rollback() } - let output: MLXArray - if let transaction, let recurrentModel { - output = recurrentModel.forward( - tokens: tokens, caches: caches, recurrentState: [transaction]) - } else { - output = model.forward(tokens: tokens, caches: caches) + do { + var observations: [Observation] = [] + for phase: Phase in [.prefill, .decode] { + let count = phase == .prefill ? 2 : 1 + for case let row? in recorders { row.begin(phase: phase, count: count) } + try withError { error in + let tokens = MLXArray(Array(repeating: token, count: count)).reshaped([ + 1, count, + ]) + try work?.retain(tokens) + try work?.capture(StreamOrDevice.default.stream) + // Model forward may have synchronizing native validation. + try work?.willSubmit() + try error.check() + let transaction = try recurrent?.bind() + defer { try? transaction?.rollback() } + let output: MLXArray + if let transaction, let recurrentModel { + output = recurrentModel.forward( + tokens: tokens, caches: caches, recurrentState: [transaction]) + } else { + output = model.forward(tokens: tokens, caches: caches) + } + try work?.retain(output) + try work?.checkpoint("probe.forward." + phase.rawValue) + try error.check() + // Validate before allocating/evaluating the forward's graph. + // Shapes and dtypes are graph metadata, not tensor readbacks. + for case let row? in recorders { observations.append(try row.observation()) } + let recurrentRoots = try transaction?.evaluate() ?? [] + let roots = recorders.compactMap { $0 }.flatMap { $0.cbv2InnerState() } + try work?.retain(arrays: recurrentRoots + roots) + eval([output] + recurrentRoots + roots) + try work?.checkpoint("probe.evaluated." + phase.rawValue) + try error.check() + try transaction?.commit() } - try error.check() - // Validate before allocating/evaluating the forward's graph. - // Shapes and dtypes are graph metadata, not tensor readbacks. - for case let row? in recorders { observations.append(try row.observation()) } - let recurrentRoots = try transaction?.evaluate() ?? [] - let roots = recorders.compactMap { $0 }.flatMap { $0.cbv2InnerState() } - eval([output] + recurrentRoots + roots) - try error.check() - try transaction?.commit() } - } - var types = Array(repeating: nil, count: layerKinds.count) - for observation in observations { - let index = observation.storageIndex - if let previous = types[index], previous != observation.keysDType { - throw invalid("layer \(index) changes KV dtype between prefill and decode") + var types = [DType?](repeating: nil, count: layerKinds.count) + for observation in observations { + let index = observation.storageIndex + if let previous = types[index], previous != observation.keysDType { + throw invalid("layer \(index) changes KV dtype between prefill and decode") + } + types[index] = observation.keysDType } - types[index] = observation.keysDType - } - for (index, kind) in layerKinds.enumerated() { - guard let source = kind.sharesKVWithLayer else { continue } - guard types.indices.contains(source), layerKinds[source].sharesKVWithLayer == nil, - layerKinds[source].kvHeads == kind.kvHeads, - layerKinds[source].headDim == kind.headDim, - layerKinds[source].attention == kind.attention - else { throw invalid("layer \(index) has an invalid KV owner") } - types[index] = types[source] + for (index, kind) in layerKinds.enumerated() { + guard let source = kind.sharesKVWithLayer else { continue } + types[index] = types[source] + } + guard types.allSatisfy({ $0 != nil }) else { + throw invalid("probe did not observe every KV owner") + } + try work?.fence(cause: "native KV probe completion") + completedForCleanup = true + return Result(layerDTypes: types.map { $0! }, observations: observations) + } catch { + let original = error + if let work { + // No unbind on failed completion. The preinstalled scope holds + // the actual caches, recorders and graph roots after throw. + if !work.snapshot.isRetainedFault { + try work.fence(cause: String(describing: original)) + completedForCleanup = true + } + } + throw original } - guard types.allSatisfy({ $0 != nil }) else { throw invalid("probe did not observe every KV owner") } - return Result(layerDTypes: types.map { $0! }, observations: observations) } private static func invalid(_ reason: String) -> CBv2KVError { @@ -110,12 +178,17 @@ public enum CBv2NativeKVTypeProbe { private var count = 0 private var observed: Observation? private var violation: String? + private var nativeDType: DType? + private let captureProjections: Bool + private var projectionRoots: [MLXArray] = [] - init(index: Int, kind: CBv2LayerKind) { + init(index: Int, kind: CBv2LayerKind, captureProjections: Bool) { + self.captureProjections = captureProjections self.index = index self.kind = kind - storage = CBv2FullSequenceKV(promptLength: 2, maxLength: 3, - kvHeads: kind.kvHeads, headDim: kind.headDim) + storage = CBv2FullSequenceKV( + promptLength: 2, maxLength: 3, + kvHeads: kind.kvHeads, headDim: kind.headDim, valueHeadDim: kind.valueHeadDim) } func begin(phase: Phase, count: Int) { @@ -126,18 +199,28 @@ public enum CBv2NativeKVTypeProbe { } func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + // Keep incoming graph roots even if validation/storage subsequently + // faults before the forward returns its output to the caller. + if captureProjections { projectionRoots += [keys, values] } guard observed == nil, violation == nil else { violation = "layer \(index) updated more than once during \(phase.rawValue)" return (keys, values) } let shape = [1, kind.kvHeads, count, kind.headDim] - guard keys.shape == shape, values.shape == shape, + let valueShape = [1, kind.kvHeads, count, kind.valueHeadDim] + guard keys.shape == shape, values.shape == valueShape, keys.dtype == values.dtype, [.float16, .bfloat16, .float32].contains(keys.dtype) else { - violation = "layer \(index) has unsupported or asymmetric native K/V: \(keys.dtype)/\(values.dtype), \(keys.shape)/\(values.shape)" + violation = + "layer \(index) has incompatible native K/V shape or dtype: \(keys.dtype)/\(values.dtype), \(keys.shape)/\(values.shape)" return (keys, values) } + if let nativeDType, nativeDType != keys.dtype { + violation = "layer \(index) changes KV dtype between prefill and decode" + return (keys, values) + } + nativeDType = keys.dtype observed = Observation( storageIndex: index, modelLayerIndex: kind.modelLayerIndex ?? index, phase: phase, keysDType: keys.dtype, valuesDType: values.dtype, @@ -147,7 +230,9 @@ public enum CBv2NativeKVTypeProbe { func observation() throws -> Observation { if let violation { throw invalid(violation) } - guard let observed else { throw invalid("layer \(index) did not update during \(phase.rawValue)") } + guard let observed else { + throw invalid("layer \(index) did not update during \(phase.rawValue)") + } return observed } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/NativePagedMTPWork.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/NativePagedMTPWork.swift new file mode 100644 index 0000000000..f88cab7355 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/NativePagedMTPWork.swift @@ -0,0 +1,327 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX + +/// One genuine serial-MTP engine step. Composes existing Admission-backed +/// attention owners and the existing native operation loan; owns no new ledger, +/// success receipt, reservation discount, or alternative assistant cache. +final class CBv2NativePagedMTPWork { + private final class Frame: @unchecked Sendable { + let work: CBv2NativePagedMTPWork + let thread = ObjectIdentifier(Thread.current) + private let lock = NSLock() + private var open = true + init(_ work: CBv2NativePagedMTPWork) { self.work = work } + func close() { lock.withLock { open = false } } + var active: Bool { lock.withLock { open && thread == ObjectIdentifier(Thread.current) } } + } + @TaskLocal private static var frame: Frame? + static var current: CBv2NativePagedMTPWork? { + guard let frame, frame.active else { return nil } + return frame.work + } + + private let backend: PagedKVBackend + private let binding: CBv2NativePagedModelBinding + private var states: [CBv2RequestID: [CBv2SequenceKV?]] + private var ordinary: [(id: CBv2RequestID, range: Range)] + private var verification: [(id: CBv2RequestID, range: Range)] + private var hostReservation: CBv2CheckpointReservation? + private var operation: CBv2NativePagedOperation? + private var owners: [CBv2PagedAttentionStepOwner] = [] + private var ordinaryOwner: CBv2PagedAttentionStepOwner? + private var begunRows: Set = [] + private var expectedRows: [UInt64: (row: PagedSequenceKV, range: Range)] = [:] + private var ordinaryClosed = false + private var graphClosed = false + private var verifiedWidth = 0 + private var evaluationFinished = false + private var retirementQueued = false + private(set) var completedColumns = 0 + + private init( + backend: PagedKVBackend, binding: CBv2NativePagedModelBinding, + states: [CBv2RequestID: [CBv2SequenceKV?]], work: [CBv2MTPRowWork], + hostReservation: CBv2CheckpointReservation + ) { + self.backend = backend + self.binding = binding + self.states = states + self.hostReservation = hostReservation + ordinary = work.filter { $0.carry == nil }.map { + ($0.rec.id, $0.start ..< ($0.start + $0.count)) + } + verification = work.filter { $0.carry != nil }.map { + ($0.rec.id, $0.start ..< ($0.start + $0.count)) + } + } + + static func make( + backend: CBv2KVBackend, states: [CBv2RequestID: [CBv2SequenceKV?]], + work: [CBv2MTPRowWork], driver: CBv2MTPRoundDriver + ) throws -> CBv2NativePagedMTPWork? { + guard let backend = backend as? PagedKVBackend, let binding = backend.nativeModelBinding + else { return nil } + guard binding.supportsSerialMTP, driver.config.verificationMode == .serialTarget, + driver.config.maxSpeculativeBatch == 1, + (1 ... 3).contains(driver.config.maxDraftTokens), + work.lazy.filter({ $0.carry != nil }).count <= 1, + !work.isEmpty, let limits = backend.pool.config.gatheredAttention, + work.count <= limits.maximumBatchSize, + work.allSatisfy({ + $0.start >= 0 && $0.count > 0 + && CBv2KVGeometry.add($0.start, $0.count).map({ + $0 <= binding.maximumContextTokens + }) == true + }), + work.allSatisfy({ + $0.rec.request.multimodal == nil && $0.rec.request.positionState == nil + }) + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try binding.requireEngineQueue() + try binding.validateAssistant(driver.drafter as AnyObject) + guard let admission = backend.pool.memoryAdmission, + let entries = CBv2KVGeometry.multiply(work.count, backend.layerKinds.count), + let tables = CBv2KVGeometry.multiply(entries, 512), + let hostBytes = CBv2KVGeometry.add(64 << 10, tables) + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + // Acquire the extra round metadata/table obligation BEFORE allocating + // private maps or taking any native operation loan. No reserve discount. + let host = try admission.reserveTransient(bytes: hostBytes) + var result: CBv2NativePagedMTPWork? + do { + var selected: [CBv2RequestID: [CBv2SequenceKV?]] = [:] + for row in work { + guard selected[row.rec.id] == nil, let state = states[row.rec.id], + state.count == backend.layerKinds.count + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + selected[row.rec.id] = state + } + let created = CBv2NativePagedMTPWork( + backend: backend, binding: binding, + states: selected, work: work, hostReservation: host) + result = created + created.operation = try binding.beginWork( + requests: Set(work.map { $0.rec.id }), nativeData: false) + created.operation?.retain(owner: created) // complete owner before any later veto + if !created.ordinary.isEmpty { + created.ordinaryOwner = try backend.prepareAttentionWork( + assignments: created.ordinary, states: selected) + guard let owner = created.ordinaryOwner else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + created.owners.append(owner) + } + return created + } catch { + if let result, result.operation != nil { + result.discardAfterBuildFailure() + } else { + // Proven cold: no native operation/attention owner exists. + result?.states.removeAll() + result?.ordinary.removeAll() + result?.verification.removeAll() + result?.hostReservation = nil + host.release() + } + throw error + } + } + + static func withConstruction( + _ work: CBv2NativePagedMTPWork?, + _ body: () throws -> Result + ) throws -> Result { + guard let work else { return try $frame.withValue(nil, operation: body) } + try work.binding.requireEngineQueue() + guard !work.graphClosed, Self.current == nil else { + throw CBv2NativeShutdownError.operationClosed + } + let frame = Frame(work) + defer { + frame.close() + work.graphClosed = true + } + return try $frame.withValue(frame, operation: body) + } + + func finishOrdinaryConstruction() throws { + try binding.requireEngineQueue() + guard Self.current === self, !ordinaryClosed else { + throw CBv2NativeShutdownError.operationClosed + } + if let ordinaryOwner { + try ordinaryOwner.seal() + backend.pool.endAttentionConstruction(ordinaryOwner) + } + ordinaryClosed = true + } + + /// All rows/cohorts preflight before ANY row begins a transaction. + func beginVerification(_ rows: [CBv2MTPRoundInFlight.VerifyRow], depth: Int) throws { + try binding.requireEngineQueue() + guard Self.current === self, ordinaryClosed, expectedRows.isEmpty, + rows.count == verification.count, rows.count == 1, (1 ... 3).contains(depth) + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + var checked: [UInt64: (row: PagedSequenceKV, range: Range)] = [:] + for (item, planned) in zip(rows, verification) { + guard item.id == planned.id, planned.range.count == depth + 1, + let original = states[item.id], original.count == item.storageRows.count + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + for (index, value) in item.storageRows.enumerated() { + guard let row = value as? PagedSequenceKV, original[index] === row, + row.pool === backend.pool, !row.isReleased, row.speculativeBase == nil, + row.absoluteOffset == planned.range.lowerBound, + row.maxLength >= planned.range.upperBound, + row.speculativeHeadroom >= CBv2PagedSpeculation.maxSpeculativeSpan, + checked[row.serial] == nil + else { throw CBv2NativeShutdownError.unsupportedConsumer } + _ = try binding.metadata(row: row, layer: index) + checked[row.serial] = (row, planned.range) + } + } + expectedRows = checked + verifiedWidth = depth + 1 + } + + func authorizeBegin(_ row: PagedSequenceKV) -> Bool { + guard (try? binding.requireEngineQueue()) != nil else { return false } + guard Self.current === self, !graphClosed, let expected = expectedRows[row.serial], + expected.row === row, row.speculativeBase == nil, + row.absoluteOffset == expected.range.lowerBound, + begunRows.insert(row.serial).inserted + else { return false } + return true + } + + /// Called by the existing actual-range planner, not by model/cache callers. + func permitsPlannedColumn(_ row: PagedSequenceKV, range: Range) -> Bool { + guard (try? binding.requireEngineQueue()) != nil else { return false } + guard Self.current === self, !graphClosed, let expected = expectedRows[row.serial], + expected.row === row, begunRows.contains(row.serial), + row.speculativeBase == expected.range.lowerBound, + range.count == 1, range.lowerBound == expected.range.lowerBound + completedColumns, + range.upperBound <= expected.range.upperBound + else { return false } + return true + } + + func prepareColumn(_ index: Int) throws -> CBv2PagedAttentionStepOwner { + try binding.requireEngineQueue() + guard Self.current === self, ordinaryClosed, index == completedColumns, + index < verifiedWidth, begunRows.count == expectedRows.count, + !expectedRows.isEmpty + else { throw CBv2NativeShutdownError.unsupportedConsumer } + let assignments = verification.map { + ( + id: $0.id, + range: ($0.range.lowerBound + index) ..< ($0.range.lowerBound + index + 1) + ) + } + guard let owner = try backend.prepareAttentionWork(assignments: assignments, states: states) + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + owners.append(owner) + return owner + } + + func completeColumn(_ owner: CBv2PagedAttentionStepOwner) throws { + guard Self.current === self, owners.last === owner, !owner.completed else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try owner.seal() + // The canonical serial target already evaluated its scores/hidden/KV. + // This additionally proves every owned transfer/output/sentinel root. + try owner.finishEvaluation() + owner.publish() + backend.pool.endAttentionConstruction(owner) + completedColumns += 1 + } + + var evaluationTargets: [MLXArray] { owners.flatMap(\.evaluationTargets) } + func publish() { for owner in owners { owner.publish() } } + + func finishEvaluation() throws { + guard graphClosed, ordinaryClosed, + verification.isEmpty || completedColumns == verifiedWidth + else { + fail() + throw CBv2NativeShutdownError.operationClosed + } + do { + for owner in owners { try owner.finishEvaluation() } + try operation?.requiredDrain() + evaluationFinished = true + } catch { + fail() + throw error + } + } + + /// Finalizer metadata only, AFTER the genuine required completion above. + func permitsFinalization(_ row: PagedSequenceKV) -> Bool { + guard evaluationFinished, let operation, operation.tracking.mayExecute, + expectedRows[row.serial]?.row === row, begunRows.contains(row.serial) + else { return false } + do { + try binding.requireEngineQueue() + return true + } catch { return false } + } + + func fail() { + operation?.fail() + for owner in owners { owner.failCompletion() } + } + + /// Failed graph locals must have unwound before the caller invokes this. + /// No failed graph is evaluated. A failed REQUIRED fence remains sticky. + func discardAfterBuildFailure() { + guard let operation, operation.tracking.mayExecute else { return } + backend.pool.endAttentionConstruction(backend.pool.activeAttentionWork) + do { + for owner in owners { try owner.discardAfterDrain() } + try operation.requiredDrain() + evaluationFinished = true + closeAfterStep() + } catch { fail() } + } + + func closeAfterStep() { + guard evaluationFinished, !retirementQueued, let operation else { return } + retirementQueued = true + for owner in owners { owner.closeGraph() } + // Individual owners enqueue their true alias/charge retirement first. + // No new native wait is performed under finalize's commit lock. + operation.enqueueRetirement { [self, operation] in + guard operation.tracking.mayExecute else { return } + guard owners.allSatisfy(\.released) else { + fail() + return + } + operation.finish { + owners.removeAll() + ordinaryOwner = nil + expectedRows.removeAll() + begunRows.removeAll() + states.removeAll() + ordinary.removeAll() + verification.removeAll() + hostReservation?.release() + hostReservation = nil + self.operation = nil + } + } + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/NativePagedModelBinding.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/NativePagedModelBinding.swift new file mode 100644 index 0000000000..fb028697c0 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/NativePagedModelBinding.swift @@ -0,0 +1,540 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX + +/// SDK producer only; validates the genuine strict-loaded generation without +/// arrays, provider callbacks, model traversal or a new completion authority. +package protocol CBv2NativePagedModelValidating: AnyObject { + func validateNativePagedModel() throws +} + +/// Metadata returned only after exact pool/row/cohort validation. No snapshot, +/// gather, allocation or stream operation is needed to check a MiMo row. +package struct CBv2NativePagedRowMetadata { + package let request: UUID + package let offset, retainedCount, maximumLength, oldestValidPosition: Int + package let keyWidth, valueWidth, kvHeads: Int + package let window: Int? + package let dtype: DType +} + +/// Owns one actual host-map generation's conservative allowance on the SAME +/// Admission/process owner. It carries no native arrays or materialization +/// credit. Installed maps and private replacement maps may coexist; their +/// actual holders retain this object until those aliases are gone. +final class CBv2NativePagedHostMetadataGeneration { + let bindingID: UUID + let admissionID: ObjectIdentifier + let boundBytes: Int + private let reservation: CBv2CheckpointReservation + init(bindingID: UUID, admission: AdmissionV2, boundBytes: Int) throws { + self.bindingID = bindingID + admissionID = ObjectIdentifier(admission) + self.boundBytes = boundBytes + reservation = try admission.reserveTransient(bytes: boundBytes) + } + deinit { reservation.release() } +} + +/// One protected constructor's immutable association after seal(). Existing +/// PagedKVBackend constructors do not install one. Its callbacks are the +/// already-existing MiMo row ledger, not public registration or a second ledger. +package final class CBv2NativePagedModelBinding { + package let ownerID = UUID() + let constructionOwnerID: UUID + let constructionEpoch: UInt64 + let layerKinds: [CBv2LayerKind] + let layerDTypes: [DType] + let maximumContextTokens: Int + private weak var model: AnyObject? + private weak var assistant: AnyObject? + let supportsSerialMTP: Bool + private weak var loadedOwner: AnyObject? + private weak var actualBackend: PagedKVBackend? + private weak var actualBank: CBv2LayerCacheBank? + private weak var processOwner: (any CBv2ProcessMemoryOwner)? + private weak var completePrefixStore: (any CBv2NativeCompletePrefixCache)? + private let completePrefixValidator: (any CBv2NativeCompletePrefixBindingValidating)? + let completePrefixIdentity: CBv2CompleteCheckpointIdentity? + private let validator: any CBv2NativePagedModelValidating + private let registerRows: ([CBv2SequenceKV?], UUID) throws -> Void + private let rowRequest: (any CBv2SequenceKV, Int) throws -> UUID + private let removeRows: ([CBv2SequenceKV?], UUID) throws -> Void + private var sealed = false + private var runtime: CBv2NativeShutdownState? + private var lifetimeLoan: UUID? + private var engineQueue: DispatchQueue? + private let queueKey = DispatchSpecificKey() + private var onFailure: (() -> Void)? + private var onRetirement: (() -> Void)? + private var onWorkCreated: ((Set) -> Void)? + private var onWorkRetired: ((Set) -> Void)? + private(set) var poolRetired = false + private var hostMetadata: CBv2NativePagedHostMetadataGeneration? + var hostMetadataBytesForTesting: Int { hostMetadata?.boundBytes ?? 0 } + + /// No initial-soft-grant clamp. Price the checked prospective address + /// extent each time before growth; ordinary reslicing remains supported. + func reserveHostMetadata(addressPages: Int) throws -> CBv2NativePagedHostMetadataGeneration? { + guard completePrefixIdentity != nil else { return nil } + try requireEngineQueue() + guard addressPages >= 0, let admission = actualBackend?.pool.memoryAdmission, + admission.hasProcessMemoryOwner, + let pages = CBv2KVGeometry.multiply(addressPages, 512), + let total = CBv2KVGeometry.add(pages, (64 << 10) + layerKinds.count * 4096) + else { + throw CBv2CompleteCheckpointError.invalidManifest + } + try completePrefixValidator?.validateNativeCompletePrefixBinding() + return try .init(bindingID: ownerID, admission: admission, boundBytes: total) + } + + func installHostMetadata(_ generation: CBv2NativePagedHostMetadataGeneration?) + -> CBv2NativePagedHostMetadataGeneration? + { + guard let generation else { + precondition(completePrefixIdentity == nil) + return nil + } + precondition(generation.bindingID == ownerID) + guard let admission = actualBackend?.pool.memoryAdmission else { + preconditionFailure("issued host-map generation lost its actual admission") + } + precondition(generation.admissionID == ObjectIdentifier(admission)) + let previous = hostMetadata + hostMetadata = generation + return previous // caller drops old allowance OUTSIDE grant/outcome locks + } + + package var hasSealedNativeResources: Bool { + guard sealed, !poolRetired, actualBackend != nil, actualBank != nil else { return false } + do { + try validator.validateNativePagedModel() + return true + } catch { return false } + } + + package init( + model: AnyObject, loadedOwner: AnyObject, assistant: AnyObject? = nil, + layerKinds: [CBv2LayerKind], layerDTypes: [DType], maximumContextTokens: Int, + processMemoryOwner: any CBv2ProcessMemoryOwner, + validator: any CBv2NativePagedModelValidating, construction: NativeConstructionScope, + completePrefixCache: (any CBv2NativeCompletePrefixCache)? = nil, + completePrefixValidator: (any CBv2NativeCompletePrefixBindingValidating)? = nil, + registerRows: @escaping ([CBv2SequenceKV?], UUID) throws -> Void, + rowRequest: @escaping (any CBv2SequenceKV, Int) throws -> UUID, + removeRows: @escaping ([CBv2SequenceKV?], UUID) throws -> Void + ) throws { + try construction.requireImmutableLoadedOwner(loadedOwner) + try validator.validateNativePagedModel() + guard (completePrefixCache != nil) == (completePrefixValidator != nil) else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try completePrefixValidator?.validateNativeCompletePrefixBinding() + let origin = construction.snapshot + guard case .active = origin.disposition, origin.epoch > 0, + !layerKinds.isEmpty, layerKinds.count <= 48, layerKinds.count == layerDTypes.count, + maximumContextTokens > 0, maximumContextTokens <= Int(Int32.max), + layerKinds.allSatisfy({ + $0.sharesKVWithLayer == nil + && $0.headDim == 192 && $0.valueHeadDim == 128 + && $0.queryHeads == 64 && [4, 8].contains($0.kvHeads) + && ($0.attention == .full || $0.attention == .slidingWindow(128)) + }), + layerDTypes.allSatisfy({ $0 == .bfloat16 || $0 == .float16 }) + else { + throw CBv2KVError.backendIneligible(reason: "unqualified native MiMo paged geometry") + } + self.model = model + self.loadedOwner = loadedOwner + self.assistant = assistant + supportsSerialMTP = assistant != nil + self.layerKinds = layerKinds + self.layerDTypes = layerDTypes + self.maximumContextTokens = maximumContextTokens + self.processOwner = processMemoryOwner + self.validator = validator + self.completePrefixStore = completePrefixCache + self.completePrefixValidator = completePrefixValidator + completePrefixIdentity = completePrefixCache?.identity + constructionOwnerID = origin.ownerID + constructionEpoch = origin.epoch + self.registerRows = registerRows + self.rowRequest = rowRequest + self.removeRows = removeRows + try validateAssistant(assistant) + } + + /// Actual loaded assistant/target pairing, never an operator flag. MiMo's + /// heads keep their own existing request histories; only target KV is paged. + func validateAssistant(_ candidate: AnyObject?) throws { + guard supportsSerialMTP == (candidate != nil), assistant === candidate else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + guard let candidate else { return } + guard let target = model as? any CBv2MTPSteppableModel, + target.supportsRequestStatefulMTP, let targetID = target.mtpTargetIdentity, + let drafter = candidate as? any CBv2MTPRequestStatefulDrafter, + candidate is any CBv2NativeMTPCompletionSplitting, + candidate is any CBv2MTPBoundedAllocationProviding, + drafter.mtpTargetIdentity == targetID, + drafter.requiredVerificationMode == .serialTarget, + drafter.maximumDraftTokens == 3, drafter.maximumSpeculativeBatch == 1 + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + } + + /// The actual immutable loaded tuple grants this permission. A historical + /// model marker, layout name or enabled scheduler flag does not. + func validateCompletePrefix( + store: any CBv2CompletePrefixCache, + identity: CBv2CompleteCheckpointIdentity, assistant: AnyObject?, + processMemoryOwner: (any CBv2ProcessMemoryOwner)? + ) throws { + guard sealed, !poolRetired, actualBackend != nil, actualBank != nil, + loadedOwner != nil, let completePrefixStore, + completePrefixStore === store, completePrefixStore.identity == identity, + completePrefixIdentity == identity, processOwner != nil, + processOwner === processMemoryOwner, let completePrefixValidator + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try validator.validateNativePagedModel() + try completePrefixValidator.validateNativeCompletePrefixBinding() + try validateAssistant(assistant) + guard assistant == nil || assistant is any CBv2HistoricalMTPPrefixCheckpointCoding else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + } + + func validatesCompletePrefixCodec( + identity: CBv2CompleteCheckpointIdentity, + layerKinds: [CBv2LayerKind], layerDTypes: [DType], assistant: AnyObject? + ) -> Bool { + guard let completePrefixStore, self.layerKinds == layerKinds, + self.layerDTypes == layerDTypes + else { return false } + do { + try validateCompletePrefix( + store: completePrefixStore, identity: identity, + assistant: assistant, processMemoryOwner: processOwner) + return true + } catch { return false } + } + + func attach(_ backend: PagedKVBackend) throws { + guard actualBackend == nil, !sealed, backend.layerKinds == layerKinds, + backend.pool.layerDTypes == layerDTypes, + backend.pool.usesStepOwnedAttention, backend.pool.segmentGrant != nil, + backend.pool.bytesReserved == 0, backend.pool.bytesMaterialized == 0, + backend.residentPrefixIndex == nil, + backend.pool.config.gatheredAttention?.maximumContextTokens == maximumContextTokens + else { + throw CBv2KVError.backendIneligible( + reason: "native paged binding requires fresh exact segmented backing") + } + try validator.validateNativePagedModel() + actualBackend = backend + } + + package func seal(bank: CBv2LayerCacheBank, caches: [PagedLayerCache]) throws { + guard !sealed, actualBank == nil, let backend = actualBackend, + caches.count == layerKinds.count + else { + throw CBv2KVError.backendIneligible( + reason: "native paged binding already sealed or incomplete") + } + for (index, cache) in caches.enumerated() { + guard cache.pool === backend.pool, cache.layerIndex == index, + cache.kind == layerKinds[index], + backend.pool.attentionWorkCaches[index]?.value === cache + else { + throw CBv2KVError.backendIneligible(reason: "foreign native paged layer cache") + } + } + try validator.validateNativePagedModel() + actualBank = bank + sealed = true + } + + func validate( + model: AnyObject, backend: AnyObject, bank: AnyObject, + assistant: AnyObject? = nil, + processMemoryOwner: (any CBv2ProcessMemoryOwner)?, + constructionOwnerID: UUID, constructionEpoch: UInt64 + ) throws { + guard sealed, !poolRetired, self.model === model, actualBackend === backend, + actualBank === bank, loadedOwner != nil, + processOwner != nil, processOwner === processMemoryOwner, + self.constructionOwnerID == constructionOwnerID, + self.constructionEpoch == constructionEpoch + else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try validator.validateNativePagedModel() + try validateAssistant(assistant) + } + + func installRuntime( + _ tracking: CBv2NativeShutdownState, retaining engine: AnyObject, + queue: DispatchQueue, + onFailure: @escaping () -> Void, onRetirement: @escaping () -> Void, + onWorkCreated: @escaping (Set) -> Void, + onWorkRetired: @escaping (Set) -> Void + ) throws { + guard runtime == nil, sealed, tracking.supported, tracking.mayExecute, + actualBackend != nil, actualBank != nil + else { throw CBv2NativeShutdownError.unsupportedConsumer } + try validator.validateNativePagedModel() + lifetimeLoan = try tracking.beginLoan(owner: engine) + runtime = tracking + engineQueue = queue + self.onFailure = onFailure + self.onRetirement = onRetirement + self.onWorkCreated = onWorkCreated + self.onWorkRetired = onWorkRetired + queue.setSpecific(key: queueKey, value: 1) + } + + func requireEngineQueue() throws { + guard DispatchQueue.getSpecific(key: queueKey) == 1, !poolRetired, + let runtime + else { throw CBv2NativeShutdownError.unsupportedConsumer } + try runtime.requireWork() + try validator.validateNativePagedModel() + } + + func preflightCreation(backend: PagedKVBackend, kinds: [CBv2LayerKind], maximumLength: Int) + throws + { + try requireEngineQueue() + guard actualBackend === backend, kinds == layerKinds, + CBv2NativePagedOperation.constructing?.tracking === runtime, + maximumLength > 0, maximumLength <= maximumContextTokens + else { + throw CBv2KVError.backendIneligible( + reason: "native paged target layout/context mismatch") + } + } + + /// Complete all checks before publishing ANY entry. Called only by the + /// actual backend after its full cold row construction succeeded. + func register(_ rows: [CBv2SequenceKV?], backend: PagedKVBackend) throws { + try requireEngineQueue() + try preflightRows(rows, backend: backend, requireCohort: false) + try registerRows(rows, ownerID) + } + + /// Existing target-only profile does not authorize import. The future + /// complete-checkpoint transaction must call a separate typed adoption seam. + func refuseImport() throws { + throw CBv2KVError.backendIneligible( + reason: "native paged COMPLETE prefix is not issued by target-only profile") + } + + func remove(_ rows: [CBv2SequenceKV?], backend: PagedKVBackend) throws { + try requireEngineQueue() + try preflightRows(rows, backend: backend, requireCohort: true) + try removeRows(rows, ownerID) // existing ledger itself validates all before removal + } + + private func preflightRows( + _ rows: [CBv2SequenceKV?], backend: PagedKVBackend, + requireCohort: Bool + ) throws { + guard actualBackend === backend, rows.count == layerKinds.count else { + throw CBv2KVError.backendIneligible( + reason: "native paged release requires its whole actual request") + } + var seen = Set() + var request: UUID? + for (index, item) in rows.enumerated() { + guard let row = item as? PagedSequenceKV, row.pool === backend.pool, + !row.isReleased, seen.insert(row.serial).inserted, + row.groupKey == backend.pool.groupKey(forLayer: index), + row.maxLength <= maximumContextTokens, + row.windowSize == expectedWindow(at: index) + else { + throw CBv2KVError.backendIneligible( + reason: "foreign, aliased, released or wrong-layer native paged row") + } + if requireCohort { + let actual = try rowRequest(row, index) + guard request == nil || request == actual else { + throw CBv2KVError.backendIneligible( + reason: "mixed native paged request cohorts") + } + request = actual + } + } + } + + package func metadata(row: any CBv2SequenceKV, layer: Int) throws -> CBv2NativePagedRowMetadata + { + try requireEngineQueue() + guard layerKinds.indices.contains(layer), let backend = actualBackend, + let row = row as? PagedSequenceKV, row.pool === backend.pool, !row.isReleased, + row.groupKey == backend.pool.groupKey(forLayer: layer), + row.windowSize == expectedWindow(at: layer), + row.groupKey.dtype == layerDTypes[layer] + else { + throw CBv2KVError.backendIneligible(reason: "foreign native paged metadata row") + } + let request = try rowRequest(row, layer) + return .init( + request: request, offset: row.absoluteOffset, retainedCount: row.retainedCount, + maximumLength: row.maxLength, oldestValidPosition: row.oldestValidPosition, + keyWidth: row.groupKey.headDim, valueWidth: row.groupKey.valueHeadDim, + kvHeads: row.groupKey.kvHeads, window: row.windowSize, dtype: row.groupKey.dtype) + } + + private func expectedWindow(at layer: Int) -> Int? { + if case .slidingWindow(let window) = layerKinds[layer].attention { return window } + return nil + } + + func beginWork(requests: Set = [], nativeData: Bool = true) throws + -> CBv2NativePagedOperation + { + try requireEngineQueue() + if nativeData { + guard MiMoV26NAXGatherQMM.gpuStream(.default), + StreamOrDevice.default.stream == MLX.Stream.gpu + else { + throw CBv2KVError.backendIneligible( + reason: "native paged construction requires its actual GPU stream") + } + } + guard let runtime, let queue = engineQueue else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + let operation = try CBv2NativePagedOperation( + tracking: runtime, queue: queue, + onFailure: { [weak self] in self?.onFailure?() }, + onRetirement: { [weak self] in + self?.onWorkRetired?(requests) + self?.onRetirement?() + }) + onWorkCreated?(requests) + return operation + } + + func markPoolRetired(after operation: CBv2NativePagedOperation) throws { + try requireEngineQueue() + guard operation.completed, !operation.failed, operation.tracking === runtime else { + throw CBv2NativeShutdownError.operationClosed + } + poolRetired = true + } + + /// Excludes ONLY this exact issued lifetime loan. A media/import/work or + /// foreign/unrelated loan can never be mistaken for idle pool ownership. + var canStartPoolRetirement: Bool { + guard let runtime, let lifetimeLoan, !poolRetired else { return false } + return runtime.hasOnlyNativeLoan(lifetimeLoan) + } + + func finishPoolLifetime() { + precondition(poolRetired) + if completePrefixIdentity != nil { + precondition(actualBackend?.pool.groups.isEmpty == true) + hostMetadata = nil // actual pool host maps were explicitly dropped first + } + if let runtime, let lifetimeLoan { runtime.endLoan(lifetimeLoan) } + lifetimeLoan = nil + } + +} + +/// Existing NativeState operation loan, not an accounting/receipt framework. +/// Used by conditional page growth and the existing paged attention owner. +final class CBv2NativePagedOperation: @unchecked Sendable { + @TaskLocal static var constructing: CBv2NativePagedOperation? + let tracking: CBv2NativeShutdownState + let queue: DispatchQueue + private let onFailure: () -> Void, onRetirement: () -> Void + private let streams: [MLX.Stream] + private var arrays: [MLXArray] = [] + private var owners: [AnyObject] = [] + private var loan: UUID? + private(set) var failed = false + private(set) var completed = false + private var finished = false + var hasArrays: Bool { !arrays.isEmpty } + + init( + tracking: CBv2NativeShutdownState, queue: DispatchQueue, + onFailure: @escaping () -> Void, onRetirement: @escaping () -> Void + ) throws { + self.tracking = tracking + self.queue = queue + self.onFailure = onFailure + self.onRetirement = onRetirement + let actual = StreamOrDevice.default.stream + streams = actual == MLX.Stream.cpu ? [actual] : [actual, MLX.Stream.cpu] + loan = try tracking.beginLoan(owner: self, duringDrain: true) + tracking.captureStreams() + } + func retain(_ array: MLXArray) { arrays.append(array) } + func retain(owner: AnyObject) { owners.append(owner) } + func withConstruction(_ body: () throws -> Result) rethrows -> Result { + try Self.$constructing.withValue(self, operation: body) + } + func requireWork() throws { try tracking.requireWork() } + private final class SameQueueAction: @unchecked Sendable { + let body: () -> Void + init(_ body: @escaping () -> Void) { self.body = body } + } + /// Transfer ONLY back to the captured engine queue; the actual native + /// loan already retains its consumer. Not a detached task/completion proof. + func enqueueRetirement(_ body: @escaping () -> Void) { + let action = SameQueueAction(body) + queue.async { action.body() } + } + func fail() { + failed = true + if tracking.fail(.nativeWorkFailed) { onFailure() } + } + func requiredDrain() throws { + guard !failed else { throw CBv2NativeShutdownError.operationClosed } + do { + try tracking.requireWork() + for stream in streams { + try tracking.beforeFenceForTesting?(stream) + try withError { errors in + stream.synchronize() + try errors.check() + } + } + try tracking.requireWork() + completed = true + } catch { + fail() + throw error + } + } + /// Only after actual successful drain, or a positively unstarted operation. + /// Completion callbacks must be scalar/accounting only; no native waits. + @discardableResult + func finish(unstarted: Bool = false, _ release: () -> Void = {}) -> Bool { + guard !finished, !failed, completed || (unstarted && arrays.isEmpty && owners.isEmpty) + else { return false } + var detached: ([MLXArray], [AnyObject])? + guard + tracking.commitIfHealthy({ + finished = true + detached = (arrays, owners) + arrays = [] + owners = [] + }), var held = detached + else { return false } + detached = nil + held.0.removeAll() + held.1.removeAll() + release() + if let loan { tracking.endLoan(loan) } + onRetirement() + return true + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedAsymmetricTransfers.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedAsymmetricTransfers.swift new file mode 100644 index 0000000000..a2cdbcc535 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedAsymmetricTransfers.swift @@ -0,0 +1,174 @@ +import MLX +import MLXFast + +/// Role-addressed copies only. No attention math and no padding/truncation. +/// Equal-width callers continue through their original kernels. +enum PagedAsymmetricTransfers { + private static let fixedWrite = MLXFast.metalKernel( + name: "cbv2_asymmetric_fixed_write", + inputNames: ["keys", "values", "kslab", "vslab", "slots", "previous"], + outputNames: ["fence"], + source: """ + const int d = int(thread_position_in_grid.x); + const int h = int(thread_position_in_grid.y); + const int r = int(thread_position_in_grid.z); + const int n = keys_shape[1]; + const int page = slots[r] / S, slot = slots[r] % S; + if (page > 0) { + const size_t row = ((size_t)page * H + h) * S + slot; + if (d < DK) { device T* dst = kslab; dst[row * DK + d] = keys[((size_t)h * n + r) * DK + d]; } + if (d < DV) { device T* dst = vslab; dst[row * DV + d] = values[((size_t)h * n + r) * DV + d]; } + } + if (d == 0 && h == 0 && r == 0) fence[0] = previous[0] + 1; + """, ensureRowContiguous: true, mutableInputs: ["kslab", "vslab"]) + + private static let segmentWrite = MLXFast.metalKernel( + name: "cbv2_asymmetric_segment_write", + inputNames: ["keys", "values", "storage", "records", "previous"], + outputNames: ["fence"], + source: """ + const int d = int(thread_position_in_grid.x); + const int h = int(thread_position_in_grid.y); + const int r = int(thread_position_in_grid.z); + const int token = records[r * 3], page = records[r * 3 + 1], slot = records[r * 3 + 2]; + const int n = keys_shape[1]; + if (page > 0) { + const size_t row = ((size_t)page * H + h) * S + slot; + device T* dst = storage; + if (d < DK) dst[row * DK + d] = keys[((size_t)h * n + token) * DK + d]; + if (d < DV) dst[VBASE + row * DV + d] = values[((size_t)h * n + token) * DV + d]; + } + if (d == 0 && h == 0 && r == 0) fence[0] = previous[0] + 1; + """, ensureRowContiguous: true, mutableInputs: ["storage"]) + + private static let segmentRead = MLXFast.metalKernel( + name: "cbv2_asymmetric_segment_read", + inputNames: ["storage", "records", "keys", "values", "previous"], + outputNames: ["fence"], + source: """ + const int d = int(thread_position_in_grid.x); + const int h = int(thread_position_in_grid.y); + const int r = int(thread_position_in_grid.z); + const int token = records[r * 3], page = records[r * 3 + 1], slot = records[r * 3 + 2]; + const size_t row = ((size_t)page * H + h) * S + slot; + const size_t target = (size_t)h * N + token; + if (d < DK) { device T* dst = keys; dst[target * DK + d] = storage[row * DK + d]; } + if (d < DV) { device T* dst = values; dst[target * DV + d] = storage[VBASE + row * DV + d]; } + if (d == 0 && h == 0 && r == 0) fence[0] = previous[0] + 1; + """, ensureRowContiguous: true, mutableInputs: ["keys", "values"]) + + private static let complete = MLXFast.metalKernel( + name: "cbv2_asymmetric_transfer_complete", inputNames: ["previous"], + outputNames: ["witness"], + source: "witness[0] = previous[0] + 1;", ensureRowContiguous: true) + + private static func arguments(_ group: PagedKVGroup) -> [(String, any KernelTemplateArg)] { + [ + ("T", group.dtype), ("H", group.key.kvHeads), ("DK", group.key.headDim), + ("DV", group.key.valueHeadDim), ("S", group.pageSize), + ] + } + + private static func validate( + group: PagedKVGroup, slots: [Int32], keys: MLXArray, values: MLXArray + ) -> Bool { + guard group.writeValidation.validate(keys: keys, values: values, expected: group.dtype), + group.writeValidation.validateShape( + keys: keys, values: values, group: group.key, + rank: 3, batch: nil, tokens: slots.count) + else { return false } + guard Set(slots).count == slots.count, + slots.allSatisfy({ slot in + slot >= 0 && group.isAllocatable(slot / Int32(group.pageSize)) + && group.refCounts[Int(slot / Int32(group.pageSize))] > 0 + }) + else { + return group.writeValidation.refuse( + "invalid or duplicate asymmetric write destination", expected: group.dtype) + } + return true + } + + static func writeFixed(group: PagedKVGroup, slots: [Int32], keys: MLXArray, values: MLXArray) { + guard !slots.isEmpty, validate(group: group, slots: slots, keys: keys, values: values) + else { return } + let width = max(group.key.headDim, group.key.valueHeadDim) + let padded = slots + Array(repeating: Int32(0), count: max(0, 8 - slots.count)) + group.writeFence = + fixedWrite( + [keys, values, group.kSlab, group.vSlab, MLXArray(padded), group.writeFence], + template: arguments(group), grid: (width, group.key.kvHeads, slots.count), + threadGroup: (min(256, width), 1, 1), outputShapes: [[1]], outputDTypes: [.int32])[ + 0] + } + + static func writeSegmented( + group: PagedKVGroup, slots: [Int32], keys: MLXArray, values: MLXArray, + work: CBv2PagedAttentionStepOwner? = nil + ) { + guard !slots.isEmpty, validate(group: group, slots: slots, keys: keys, values: values) + else { return } + let width = max(group.key.headDim, group.key.valueHeadDim) + for (segment, triples) in PagedSegmentTransfers.buckets(group: group, slots: slots) { + let records = PagedSegmentTransfers.records(triples) + group.writeFence = + segmentWrite( + [keys, values, segment.storage, records, group.writeFence], + template: arguments(group) + [("VBASE", segment.valueOffset)], + grid: (width, group.key.kvHeads, triples.count / 3), + threadGroup: (min(256, width), 1, 1), + outputShapes: [[1]], outputDTypes: [.int32])[0] + work?.retainRoots([segment.storage, keys, values, records, group.writeFence]) + } + } + + static func gatherSegmented( + group: PagedKVGroup, pages: [Int32], firstSlot: Int, count: Int, + work: CBv2PagedAttentionStepOwner? = nil, + publishReadFence: Bool = true, stream: StreamOrDevice = .default + ) + -> (keys: MLXArray, values: MLXArray) + { + let h = group.key.kvHeads + let dk = group.key.headDim + let dv = group.key.valueHeadDim + precondition(count >= 0) + let keys = MLXArray.zeros([1, h, count, dk], dtype: group.dtype, stream: stream) + let values = MLXArray.zeros([1, h, count, dv], dtype: group.dtype, stream: stream) + guard count > 0 else { return (keys, values) } + precondition( + firstSlot >= 0 && firstSlot < group.pageSize + && pages.count * group.pageSize >= firstSlot + count) + let slots = (0 ..< count).map { token -> Int32 in + let offset = firstSlot + token + return pages[offset / group.pageSize] * Int32(group.pageSize) + + Int32(offset % group.pageSize) + } + let width = max(dk, dv) + var fence = group.writeFence + for (segment, triples) in PagedSegmentTransfers.buckets(group: group, slots: slots) { + let records = PagedSegmentTransfers.records(triples) + fence = + segmentRead( + [segment.storage, records, keys, values, fence], + template: arguments(group) + [("VBASE", segment.valueOffset), ("N", count)], + grid: (width, h, triples.count / 3), threadGroup: (min(256, width), 1, 1), + outputShapes: [[1]], outputDTypes: [.int32], stream: stream)[0] + work?.retainRoots([segment.storage, records, fence]) + } + // A real final consumer supplies the read barrier before any later + // in-place overwrite. Depends alone is only an alias dependency. + fence = + complete( + [fence], grid: (1, 1, 1), threadGroup: (1, 1, 1), outputShapes: [[1]], + outputDTypes: [.int32], stream: stream)[0] + // Historical copies are owned/fenced by their step before successors; + // a failed private copy must not replace the live serving write fence. + if publishReadFence { group.writeFence = fence } + work?.retainRoots([keys, values, fence]) + return ( + depends(input: keys, dependencies: [fence]), + depends(input: values, dependencies: [fence]) + ) + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedAttentionWorkReservation.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedAttentionWorkReservation.swift new file mode 100644 index 0000000000..2b65437130 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedAttentionWorkReservation.swift @@ -0,0 +1,676 @@ +import Foundation +import MLX + +/// Opt-in source envelope, not a measured peak or a paging capability claim. +/// The implementation fingerprint must be repinned with any native-core change. +public enum CBv2PagedAttentionWorkProfile: String, Sendable { + case pinnedMetal +} + +/// One independently allocated buffer, or a partition family whose bound is +/// sum(logical bytes) + allocationCount * allocator.maximumExtraBytes. +/// The latter is necessary for page-to-segment bucket partitions not yet chosen. +struct CBv2PagedAttentionAllocation: Equatable { + let role: String + let logicalBytes: Int + let allocationCount: Int + let upperBoundBytes: Int + let maximumLogicalBufferBytes: Int +} + +enum CBv2PagedWorkMath { + static func add(_ a: Int, _ b: Int) throws -> Int { + guard a >= 0, b >= 0, let value = CBv2KVGeometry.add(a, b) else { + throw CBv2KVError.backendIneligible(reason: "paged attention work addition overflow") + } + return value + } + static func product(_ factors: [Int]) throws -> Int { + try factors.reduce(1) { a, b in + guard b >= 0, let value = CBv2KVGeometry.multiply(a, b) else { + throw CBv2KVError.backendIneligible(reason: "paged attention work product overflow") + } + return value + } + } +} + +struct CBv2PagedAttentionBlock: Equatable { + let queryOffset: Int + let queryCount: Int + let visibleStart: Int + let visibleEnd: Int +} + +final class CBv2PagedAttentionWeakRow { + weak var value: PagedSequenceKV? + init(_ value: PagedSequenceKV?) { self.value = value } +} + +struct CBv2PagedAttentionRowDescriptor { + let requestID: CBv2RequestID + let row: CBv2PagedAttentionWeakRow + let rowSerial: UInt64 + let layerIndex: Int + let ownerLayerIndex: Int + let range: Range + let baseOffset: Int + let frozenHighWater: Int + let gatheredRange: Range? + let keyStart: Int + let keyCount: Int + let blocks: [CBv2PagedAttentionBlock] + let softcap: Bool + var writes: Bool { layerIndex == ownerLayerIndex } +} + +/// Immutable execution inputs. Environment overrides are not silently clamped: +/// the first profile covers the pinned backend defaults only. +struct CBv2PagedAttentionWorkEnvironment: Equatable { + let queryBlockSize: Int + let sdpaBlocks: String? + + static func capture() -> Self { + .init( + queryBlockSize: CBv2AttentionV1.queryBlockSize, + sdpaBlocks: ProcessInfo.processInfo.environment["MLX_SDPA_BLOCKS"]) + } + + func requireSupported() throws { + guard queryBlockSize >= 0, sdpaBlocks == nil else { + throw CBv2KVError.backendIneligible( + reason: "step-owned paging requires the pinned default MLX_SDPA_BLOCKS profile") + } + } +} + +/// Source-derived upper bounds for one actual layer/row call. Sum every block +/// and both possible native dispatch families; no max-across-layers discount. +enum CBv2PagedAttentionWorkProjection { + static func allocations( + kind: CBv2LayerKind, dtype: DType, descriptor d: CBv2PagedAttentionRowDescriptor, + pageSize: Int, policy: AllocationFootprintPolicy + ) throws -> [CBv2PagedAttentionAllocation] { + guard pageSize > 0, let extra = policy.maximumExtraBytes, + kind.queryHeads > 0, kind.kvHeads > 0, + kind.queryHeads % kind.kvHeads == 0, + [.float16, .bfloat16, .float32].contains(dtype) + else { + throw CBv2KVError.backendIneligible(reason: "unbound paged work allocator/geometry") + } + let h = kind.queryHeads + let hk = kind.kvHeads + let dk = kind.headDim + let dv = kind.valueHeadDim + let q = d.range.count + var result: [CBv2PagedAttentionAllocation] = [] + func buffer(_ role: String, _ factors: [Int], bytes: Int = 4, copies: Int = 1) throws { + let logical = try CBv2PagedWorkMath.product(factors + [bytes]) + guard copies > 0, let bound = policy.upperBound(byteCount: logical) else { + throw CBv2KVError.backendIneligible(reason: "paged work allocation bound overflow") + } + // Keep the independent allocation multiplicity, not one B-sized pad. + result.append( + .init( + role: role, + logicalBytes: try CBv2PagedWorkMath.product([logical, copies]), + allocationCount: copies, + upperBoundBytes: try CBv2PagedWorkMath.product([bound, copies]), + maximumLogicalBufferBytes: logical)) + } + func batchPartition(_ role: String, _ factors: [Int], bytes: Int) throws { + let logical = try CBv2PagedWorkMath.product(factors + [bytes]) + // This row can belong to one larger batch allocation. For any + // grouping B(total)<=sum(logical)+extra; charging extra per row + // does not assume subadditivity of allocator rounding. + result.append( + .init( + role: role, logicalBytes: logical, allocationCount: 1, + upperBoundBytes: try CBv2PagedWorkMath.add(logical, extra), + maximumLogicalBufferBytes: logical)) + } + func transfers(_ role: String, count: Int, start: Int, writes: Bool) throws { + guard count > 0 else { return } + let span = try CBv2PagedWorkMath.add(start % pageSize, count) + let pages = try CBv2PagedWorkMath.add(span, pageSize - 1) / pageSize + // A bucket owns <= all tokens; every bucket has >=24 Int32 entries. + // For any partition, sum max(24,3*n_i) <= 3*N + 24*bucketCount. + // Each independent native record allocation pays its own extra. + let logical = try CBv2PagedWorkMath.add( + CBv2PagedWorkMath.product([count, 3, 4]), + CBv2PagedWorkMath.product([pages, 24, 4])) + result.append( + .init( + role: role + ".records", logicalBytes: logical, + allocationCount: pages, + upperBoundBytes: try CBv2PagedWorkMath.add( + logical, + CBv2PagedWorkMath.product([pages, extra])), + maximumLogicalBufferBytes: logical)) + try buffer( + role + ".fences", [1], copies: try CBv2PagedWorkMath.add(pages, writes ? 0 : 1)) + if writes { + // ensureRowContiguous may copy EACH bucket's projected inputs. + // Broadcast syntax does not prove these native copies absent. + try buffer(role + ".keyContiguous", [hk, q, dk], bytes: dtype.size, copies: pages) + try buffer( + role + ".valueContiguous", [hk, q, dv], bytes: dtype.size, copies: pages) + } + } + if let gathered = d.gatheredRange { + try buffer("gather.keys", [hk, gathered.count, dk], bytes: dtype.size) + try buffer("gather.values", [hk, gathered.count, dv], bytes: dtype.size) + try transfers( + "gather", count: gathered.count, start: gathered.lowerBound, writes: false) + } + if d.writes && d.range.lowerBound >= d.frozenHighWater { + try transfers("write", count: q, start: d.range.lowerBound, writes: true) + } + if q > 1 && d.writes && d.frozenHighWater <= d.range.lowerBound { + // Both history-concat and no-history retained projection paths get + // compact owner outputs. Their parents never escape the step. + try buffer("prefill.keys", [hk, d.keyCount, dk], bytes: dtype.size) + try buffer("prefill.values", [hk, d.keyCount, dv], bytes: dtype.size) + } + try batchPartition("position.offsetBind", [1], bytes: 4) + try batchPartition("position.offsetAdvance", [1], bytes: 4) + try buffer("control.rowScalars", [1], copies: 8) + if q > 1 { + try buffer("position.queries", [q]) + try buffer("position.keys", [d.keyCount]) + } + if kind.hasSinks { try buffer("sinks", [h], copies: 2) } + + for (index, block) in d.blocks.enumerated() { + let n = block.visibleEnd - block.visibleStart + let bq = block.queryCount + let p = "block\(index)" + // scale, where floor, optional cap divide/multiply/window offset, + // and cast/fill control inputs. Independent scalar buffers too. + try buffer(p + ".scalars", [1], copies: 8) + let withSink = try CBv2PagedWorkMath.add(n, kind.hasSinks ? 1 : 0) + let collapsedRows = try CBv2PagedWorkMath.product([h, bq]) + let columns = max(withSink, max(dk, dv)) + let rowTiles = try CBv2PagedWorkMath.add(collapsedRows, 15) / 16 + let columnTiles = try CBv2PagedWorkMath.add(columns, 15) / 16 + // Matmul's branch-selection scalars are Int32 even when tensor + // byte sizes are UInt64: bound its worst batch collapse, 3*max, + // and tile product. Do NOT cap tensor elements to Int32. + guard collapsedRows <= Int(Int32.max) / 3, columns <= Int(Int32.max) / 3, + try CBv2PagedWorkMath.product([bq, columns]) <= Int(Int32.max), + try CBv2PagedWorkMath.product([rowTiles, columnTiles]) <= Int(Int32.max) + else { + throw CBv2KVError.backendIneligible( + reason: "actual attention shape overflows pinned native dispatch scalars") + } + if q > 1 { + try buffer(p + ".mask.causal", [bq, n], bytes: 1) + if case .slidingWindow = kind.attention { + try buffer(p + ".mask.window", [bq, n], bytes: 1, copies: 2) + try buffer(p + ".mask.queryShift", [bq]) + } + } + // Ordinary fast.cpp fallback: grouped GQA is views, NOT repeat. + // Softcap's Swift composed route really casts and repeats K/V. + try buffer(p + ".scaledQuery", [h, bq, dk], copies: d.softcap ? 2 : 1) + if d.softcap { + try buffer(p + ".castKeys", [hk, n, dk]) + try buffer(p + ".castValues", [hk, n, dv]) + if h > hk { + try buffer(p + ".repeatKeys", [h, n, dk]) + try buffer(p + ".repeatValues", [h, n, dv]) + } + } + try buffer(p + ".scores", [h, bq, n], copies: d.softcap ? 4 : 1) + if q > 1 { try buffer(p + ".maskedScores", [h, bq, n]) } + if kind.hasSinks { try buffer(p + ".augmentedScores", [h, bq, withSink]) } + // softmax.cpp either allocates or copies one output; do not assume donation. + try buffer(p + ".probabilities", [h, bq, withSink]) + try buffer(p + ".output", [h, bq, dv], copies: d.softcap ? 2 : 1) + + // matmul.cpp check_transpose can copy each *broadcasted* operand. + // These are backend contingencies, not fictitious source repeat ops. + try buffer(p + ".qk.copyQ", [h, bq, dk]) + try buffer(p + ".qk.copyK", [h, n, dk]) + try buffer(p + ".pv.copyP", [h, bq, n]) + try buffer(p + ".pv.copyV", [h, n, dv]) + // Split-K is only reachable with batch_size_out==1. If heads + // collapse at all, Matmul collapses the whole batch into M=Hq*q. + // Price both hardware alternatives ONLY when their pinned branch + // predicates can hold; a small DK cannot split a huge QK matrix. + for (name, inner, columns) in [("qk", dk, n), ("pv", n, dv)] { + let maximum = max(collapsedRows, columns) + let tiles = try CBv2PagedWorkMath.product([ + CBv2PagedWorkMath.add(collapsedRows, 15) / 16, + CBv2PagedWorkMath.add(columns, 15) / 16, + ]) + if min(collapsedRows, columns) > 1 && tiles <= 2048 && inner / 16 >= 8 + && inner >= maximum + { + try buffer(p + "." + name + ".simdSplitK", [collapsedRows, columns, 32]) + } + let triple = try CBv2PagedWorkMath.product([maximum, 3]) + let double = try CBv2PagedWorkMath.product([maximum, 2]) + if min(collapsedRows, columns) > 1 + && (inner >= triple || (maximum <= 1024 && inner > double)) + { + let stride = + inner <= 1024 + ? inner / 2 : (inner <= 2048 ? 1024 : (inner <= 4096 ? 2048 : 4096)) + guard stride > 0 else { + throw CBv2KVError.backendIneligible(reason: "invalid native split-K stride") + } + let partitions = try CBv2PagedWorkMath.add(inner, stride - 1) / stride + try buffer(p + "." + name + ".naxSplitK", [collapsedRows, columns, partitions]) + } + } + if h == 1 && bq == 1 && (n == 1 || dv == 1) { + let inner = max(n == 1 ? dk : 0, dv == 1 ? n : 0) + let partials = try CBv2PagedWorkMath.add(inner, 16383) / 16384 + try buffer(p + ".dotPartials", [partials], copies: 2) + try buffer(p + ".dotResult", [1], copies: 2) + } + + if !d.softcap && dk == 192 && dv == 128 && bq <= 8 + && bq <= 32 / (h / hk) && bq <= n + { + // Pinned SDPA vector dispatch defaults choose at most1024 blocks. + // A nonnil MLX_SDPA_BLOCKS was refused/revalidated separately. + // Price all copy candidates and all three FP32 temporaries, + // for shapes which can actually select this asymmetric vector route. + try buffer(p + ".fused.copyQ", [h, bq, dk], bytes: dtype.size) + try buffer(p + ".fused.copyK", [hk, n, dk], bytes: dtype.size) + try buffer(p + ".fused.copyV", [hk, n, dv], bytes: dtype.size) + if q > 1 { try buffer(p + ".fused.copyMask", [bq, n], bytes: 1) } + if n >= 1024 { + let partitions = n <= 8192 ? 128 : (n < 16384 ? 256 : (n < 65536 ? 512 : 1024)) + try buffer(p + ".fused.partials", [h, bq, partitions, dv]) + try buffer(p + ".fused.sumsMaxs", [h, bq, partitions], copies: 2) + } + } + } + if d.blocks.count > 1 { try buffer("output.blockConcat", [h, q, dv], bytes: dtype.size) } + // The final batch concat exists only for packed rows, but pricing one + // per row is a partition-safe upper bound, including allocator padding. + try batchPartition("output.batchConcat", [h, q, dv], bytes: dtype.size) + return result + } +} + +struct CBv2PagedAttentionTicketKey: Hashable { + let layer: Int + let serial: UInt64 +} + +/// This owner has C only. BufferInfo is validation, never an allocation ID/M credit. +/// Mutable state is confined to the engine queue; it is intentionally not Sendable. +final class CBv2PagedAttentionStepOwner { + let generation: UInt64 + let poolIdentity: ObjectIdentifier + let environment: CBv2PagedAttentionWorkEnvironment + let descriptors: [CBv2PagedAttentionTicketKey: CBv2PagedAttentionRowDescriptor] + let allocations: [CBv2PagedAttentionAllocation] + let reservedBytes: Int + let constructionStream: MLX.Stream + private let allocationPolicy: AllocationFootprintPolicy + private var reservation: CBv2CheckpointReservation? + private var nativeOperation: CBv2NativePagedOperation? + private var nativeRetirementQueued = false + private var roots: [MLXArray] = [] + private var compactRoots: [MLXArray] = [] + private var consumed: Set = [] + private var writes: Set = [] + private var reads: Set = [] + private var loans = 0 + private var graphClosed = false + private(set) var completionFailed = false + private(set) var completed = false + private(set) var released = false + private(set) var published = false + private var sealed = false + weak var pool: PagedKVPool? + /// Per-owner failure-order witness, nil in production; never substitutes a + /// successful completion receipt or grants permission to refund. + var beforeCompletionDrainForTesting: (() throws -> Void)? + + init( + generation: UInt64, pool: PagedKVPool, + environment: CBv2PagedAttentionWorkEnvironment, + descriptors: [CBv2PagedAttentionTicketKey: CBv2PagedAttentionRowDescriptor], + allocations: [CBv2PagedAttentionAllocation], bytes: Int, + reservation: CBv2CheckpointReservation, allocationPolicy: AllocationFootprintPolicy, + nativeOperation: CBv2NativePagedOperation? = nil + ) { + self.generation = generation + self.pool = pool + poolIdentity = ObjectIdentifier(pool) + self.environment = environment + self.descriptors = descriptors + self.allocations = allocations + reservedBytes = bytes + self.reservation = reservation + constructionStream = StreamOrDevice.default.stream + self.allocationPolicy = allocationPolicy + self.nativeOperation = nativeOperation + } + + func consume(layer: Int, rows: [PagedSequenceKV], queries: Int, softcap: Bool) -> Bool { + guard !sealed, !graphClosed, environment == .capture(), + constructionStream == StreamOrDevice.default.stream, + !rows.isEmpty + else { return false } + let keys = rows.map { CBv2PagedAttentionTicketKey(layer: layer, serial: $0.serial) } + guard Set(keys).count == keys.count else { return false } + for (row, key) in zip(rows, keys) { + guard let d = descriptors[key], !consumed.contains(key), + d.row.value === row, !row.isReleased, + ObjectIdentifier(row.pool) == poolIdentity, + d.range.count == queries, d.softcap == softcap, + d.baseOffset == row.baseOffset, d.frozenHighWater == row.frozenHighWater, + row.absoluteOffset == (d.writes ? d.range.lowerBound : d.range.upperBound) + else { return false } + } + consumed.formUnion(keys) + return true + } + + func authorizeWrite(layer: Int, row: PagedSequenceKV, count: Int) -> Bool { + let key = CBv2PagedAttentionTicketKey(layer: layer, serial: row.serial) + guard !published, !graphClosed, environment == .capture(), + let d = descriptors[key], d.writes, consumed.contains(key), + !writes.contains(key), d.row.value === row, d.range.count == count, + row.absoluteOffset == d.range.lowerBound + else { return false } + writes.insert(key) + return true + } + + func authorizeRead(layer: Int, row: PagedSequenceKV, start: Int, count: Int) -> Bool { + let key = CBv2PagedAttentionTicketKey(layer: layer, serial: row.serial) + guard !published, !graphClosed, environment == .capture(), + let d = descriptors[key], consumed.contains(key), !reads.contains(key), + d.row.value === row, let range = d.gatheredRange, + range.lowerBound == start, range.count == count + else { return false } + reads.insert(key) + return true + } + + func retainRoots(_ arrays: [MLXArray]) { + roots.append(contentsOf: arrays) + for array in arrays { nativeOperation?.retain(array) } + } + func retainCompactRoots(_ arrays: [MLXArray]) { + compactRoots.append(contentsOf: arrays) + roots.append(contentsOf: arrays) + for array in arrays { nativeOperation?.retain(array) } + } + var evaluationTargets: [MLXArray] { roots } + + func seal() throws { + guard consumed.count == descriptors.count, + descriptors.allSatisfy({ key, d in + (!d.writes || writes.contains(key)) + && (d.gatheredRange == nil || reads.contains(key)) + }), environment == .capture() + else { + throw CBv2KVError.backendIneligible( + reason: "paged attention step did not consume its exact sealed work") + } + sealed = true + } + + func publish() { published = true } + + func makeLoan( + keys: MLXArray, values: MLXArray, layer: Int, serial: UInt64, + range: Range + ) -> CBv2PagedAttentionLoan { + loans += 1 + return .init( + owner: self, keys: keys, values: values, + layer: layer, serial: serial, range: range) + } + + /// Fence every registered transfer/output root and drain the exact stream. + /// This ends future work, not physical ownership: callback-retained buffers + /// remain in allocator active/cache accounting. Never issue M credit here. + /// On error, do not drop roots, completion state, or C. + func finishEvaluation() throws { + guard !completionFailed else { + throw CBv2KVError.backendIneligible( + reason: "paged attention completion previously failed") + } + guard !completed else { return } + do { + try withError { fault in + eval(roots) + CBv2CoreInstrumentation.recordHostSync() + try beforeCompletionDrainForTesting?() + constructionStream.synchronize() + CBv2CoreInstrumentation.recordHostSync() + try fault.check() + } + try nativeOperation?.requiredDrain() + for root in compactRoots { + guard let info = try root.evaluatedBufferInfo(), info.dataOffset == 0, + info.isRowContiguous, info.dataElements == root.nbytes / root.dtype.size, + let bound = allocationPolicy.upperBound(byteCount: root.nbytes), + info.allocatedBytes <= bound + else { + throw CBv2KVError.backendIneligible( + reason: "retained paged producer root is not a bounded compact destination") + } + } + completed = true + compactRoots.removeAll() + roots.removeAll() + releaseIfFinished() + } catch { + failCompletion() + throw error + } + } + + /// Failed graph locals must already have unwound, its group fences restored, + /// and its cache bindings dropped. NEVER evaluate the failed graph here. + func discardAfterDrain() throws { + guard !completionFailed else { + throw CBv2KVError.backendIneligible( + reason: "paged attention completion previously failed") + } + guard !completed else { return } + do { + try withError { fault in + try beforeCompletionDrainForTesting?() + constructionStream.synchronize() + CBv2CoreInstrumentation.recordHostSync() + Stream.cpu.synchronize() + CBv2CoreInstrumentation.recordHostSync() + try fault.check() + } + try nativeOperation?.requiredDrain() + roots.removeAll() + compactRoots.removeAll() + completed = true + graphClosed = true + releaseIfFinished() + } catch { + failCompletion() + throw error + } + } + + func failCompletion() { + completionFailed = true + nativeOperation?.fail() + pool?.attentionWorkEngineRefusal = "paged attention completion failed; rebuild the engine" + } + + func closeGraph() { + graphClosed = true + releaseIfFinished() + } + + fileprivate func closeLoan() { + precondition(loans > 0) + loans -= 1 + releaseIfFinished() + } + + private func releaseIfFinished() { + guard !completionFailed, completed, graphClosed, loans == 0, !released else { return } + if let nativeOperation { + guard !nativeRetirementQueued else { return } + nativeRetirementQueued = true + // closeGraph can be called under finalize's metadata commit. + // Queue the actual detach/refund on the SAME engine queue. + nativeOperation.enqueueRetirement { [self, nativeOperation] in + guard !completionFailed, completed, graphClosed, loans == 0, !released else { + return + } + nativeOperation.finish { + released = true + roots.removeAll() + compactRoots.removeAll() + let lease = reservation + reservation = nil + lease?.release() + pool?.forgetAttentionWork(generation) + self.nativeOperation = nil + } + } + return + } + released = true + let lease = reservation + reservation = nil + roots.removeAll() + lease?.release() + pool?.forgetAttentionWork(generation) + } + + deinit { + // A failed/unknown stream is not a refund signal. Keep the typed permit + // and native roots alive even if its engine/pool is being destroyed. + if let reservation { + CBv2PagedAttentionQuarantine.retain( + reservation: reservation, roots: roots + compactRoots) + } + } +} + +/// Owns its arrays explicitly so they are disposed BEFORE releasing the loan. +/// Borrower graphs are also retained by the step until its completion fence. +final class CBv2PagedAttentionLoan { + private var owner: CBv2PagedAttentionStepOwner? + private(set) var keys: MLXArray? + private(set) var values: MLXArray? + let generation: UInt64 + let layer: Int + let serial: UInt64 + let range: Range + + fileprivate init( + owner: CBv2PagedAttentionStepOwner, keys: MLXArray, values: MLXArray, + layer: Int, serial: UInt64, range: Range + ) { + self.owner = owner + self.keys = keys + self.values = values + generation = owner.generation + self.layer = layer + self.serial = serial + self.range = range + } + + func close() { + keys = nil + values = nil + let old = owner + owner = nil + old?.closeLoan() + } + + deinit { close() } +} + +/// Rare fault containment, not a timer or reusable admission credit. Unknown +/// completion is intentionally retained until process teardown. All access to +/// this global escape hatch is locked; owners themselves stay queue-confined. +private enum CBv2PagedAttentionQuarantine { + private struct Entry { + let reservation: CBv2CheckpointReservation + let roots: [MLXArray] + } + private static let lock = NSLock() + nonisolated(unsafe) private static var entries: [Entry] = [] + static func retain(reservation: CBv2CheckpointReservation, roots: [MLXArray]) { + lock.withLock { entries.append(.init(reservation: reservation, roots: roots)) } + } +} + +final class CBv2PagedAttentionWeakCache { + weak var value: PagedLayerCache? + init(_ value: PagedLayerCache) { self.value = value } +} + +extension PagedKVPool { + func forgetAttentionWork(_ generation: UInt64) { + attentionWorkOwners.removeValue(forKey: generation) + publishAttentionWorkCharge() + } + + func endAttentionConstruction(_ owner: CBv2PagedAttentionStepOwner?) { + guard let owner, activeAttentionWork === owner else { return } + activeAttentionLayer = nil + activeAttentionWork = nil + } + + /// Called only after the existing failure boundary restored group fences, + /// dropped cache aliases and unwound the failed model-call locals. + func failUnpublishedAttentionWorkCompletion() { + for owner in attentionWorkOwners.values where !owner.published { owner.failCompletion() } + } + + /// A failed required drain is sticky; no later successful wait can refund it. + func discardUnpublishedAttentionWorkAfterDrain() { + activeAttentionLayer = nil + activeAttentionWork = nil + for owner in Array(attentionWorkOwners.values) where !owner.published { + // A failed drain deliberately leaves this owner in the registry; + // pool teardown transfers it to the fail-closed quarantine. + try? owner.discardAfterDrain() + } + } + + func authorizeAttentionWrite(row: PagedSequenceKV, count: Int) -> Bool { + guard usesStepOwnedAttention else { return true } + guard let layer = activeAttentionLayer, let work = activeAttentionWork, + work.authorizeWrite(layer: layer, row: row, count: count) + else { + return writeValidation.refuse( + "missing/stale/duplicate step-owned paged write ticket", + expected: row.groupKey.dtype) + } + return true + } + + func authorizeAttentionRead(row: PagedSequenceKV, start: Int, count: Int) -> Bool { + guard usesStepOwnedAttention else { return true } + guard let layer = activeAttentionLayer, let work = activeAttentionWork, + work.authorizeRead(layer: layer, row: row, start: start, count: count) + else { + return writeValidation.refuse( + "missing/stale/duplicate step-owned paged read ticket", + expected: row.groupKey.dtype) + } + return true + } + + func refuseUnplannedAttentionMutation(_ operation: String, dtype: DType) -> Bool { + guard usesStepOwnedAttention else { return false } + writeValidation.refuse("step-owned paging does not permit " + operation, expected: dtype) + return true + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedGatheredAttentionPolicy.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedGatheredAttentionPolicy.swift new file mode 100644 index 0000000000..62f9d0cfe0 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedGatheredAttentionPolicy.swift @@ -0,0 +1,162 @@ +import Foundation +import MLX + +public enum CBv2PagedGatheredAttentionAdmissionMode: Sendable, Equatable { + case poolLifetime + case stepOwned(CBv2PagedAttentionWorkProfile) +} + +/// Explicit correctness-first page-backed attention limits. This selects +/// native page gather + ordinary MLX SDPA, NOT a fused asymmetric page kernel. +/// Bounds are checked, never silently substituted for model context length. +public struct CBv2PagedGatheredAttentionLimits: Sendable, Equatable { + public let maximumBatchSize: Int + public let maximumQueryTokens: Int + public let maximumContextTokens: Int + public let maximumInFlightGraphs: Int + public let maximumScratchBytes: Int + public let admissionMode: CBv2PagedGatheredAttentionAdmissionMode + + public init( + maximumBatchSize: Int, maximumQueryTokens: Int, maximumContextTokens: Int, + maximumInFlightGraphs: Int, maximumScratchBytes: Int, + admissionMode: CBv2PagedGatheredAttentionAdmissionMode = .poolLifetime + ) throws { + // EngineV2 may build one chained successor before finalizing its + // predecessor. One graph is therefore not a valid serving envelope. + guard maximumBatchSize > 0, maximumBatchSize <= Int(Int32.max), maximumQueryTokens > 0, + maximumContextTokens >= maximumQueryTokens, + maximumContextTokens <= Int(Int32.max), + (2 ... 8).contains(maximumInFlightGraphs), maximumScratchBytes > 0 + else { + throw CBv2KVError.backendIneligible( + reason: "invalid explicit asymmetric gathered-attention limits") + } + self.maximumBatchSize = maximumBatchSize + self.maximumQueryTokens = maximumQueryTokens + self.maximumContextTokens = maximumContextTokens + self.maximumInFlightGraphs = maximumInFlightGraphs + self.maximumScratchBytes = maximumScratchBytes + self.admissionMode = admissionMode + } + + /// Conservative reservation, not measured live usage. Sum all potentially + /// coexisting layer graphs and one retained borrower-prefill generation. + /// Each buffer gets its allocator bound before multiplicity is applied. + public func scratchUpperBound(layerKinds: [CBv2LayerKind], pageSize: Int) throws -> Int { + guard pageSize > 0 else { throw CBv2CompleteCheckpointError.invalidManifest } + var bytes = 64 << 10 // bounded Swift control/table envelope + func addBuffer(_ factors: [Int], itemBytes: Int = 4, copies: Int = 1) throws { + var logical = itemBytes + for value in factors { + guard value >= 0, let next = CBv2KVGeometry.multiply(logical, value) else { + throw CBv2KVError.backendIneligible( + reason: "asymmetric attention scratch projection overflow") + } + logical = next + } + let allocation = try Memory.allocationFootprintUpperBound(byteCount: max(1, logical)) + guard let total = CBv2KVGeometry.multiply(allocation, copies), + let next = CBv2KVGeometry.add(bytes, total) + else { + throw CBv2KVError.backendIneligible( + reason: "asymmetric attention scratch projection overflow") + } + bytes = next + } + for kind in layerKinds where kind.headDim != kind.valueHeadDim { + guard kind.kvGeometry != nil, kind.queryHeads > 0, + kind.queryHeads % kind.kvHeads == 0 + else { + throw CBv2KVError.backendIneligible( + reason: "invalid asymmetric attention scratch geometry") + } + let visible: Int + if case .slidingWindow(let window) = kind.attention { + guard let exposure = CBv2KVGeometry.add(window, maximumQueryTokens), window > 0 + else { + throw CBv2CompleteCheckpointError.invalidManifest + } + visible = min(maximumContextTokens, exposure) + } else { + visible = maximumContextTokens + } + guard let padding = CBv2KVGeometry.multiply(2, pageSize), + let padded = CBv2KVGeometry.add(visible, padding), + let sinkWidth = CBv2KVGeometry.add(visible, 1) + else { + throw CBv2CompleteCheckpointError.invalidManifest + } + let b = maximumBatchSize + let q = maximumQueryTokens + let h = kind.queryHeads + // Independent K/V gather, transpose/contiguous conversion, concat, + // dtype/GQA conversion and graph temporaries. Price at FP32. + for width in [kind.headDim, kind.valueHeadDim] { + try addBuffer([b, h, padded, width], copies: 8) + try addBuffer([b, h, q, width], copies: 4) + } + // Full unblocked score/softmax/mask envelope: query blocking may + // reduce a peak but is not relied upon for admission correctness. + try addBuffer([b, h, q, sinkWidth], copies: 8) + try addBuffer([b, h, q, sinkWidth], itemBytes: 1, copies: 4) + try addBuffer([b, padded, 32], copies: 2) // padded transfer records/positions + let segments = padded / pageSize + 2 + guard let rows = CBv2KVGeometry.multiply(b, segments), + let witnesses = CBv2KVGeometry.multiply(rows, 4) + else { + throw CBv2CompleteCheckpointError.invalidManifest + } + try addBuffer([1], copies: witnesses) // write/read/completion witnesses + } + guard let envelope = CBv2KVGeometry.multiply(bytes, maximumInFlightGraphs + 1), + envelope <= maximumScratchBytes + else { + throw CBv2KVError.backendIneligible( + reason: + "explicit asymmetric gathered-attention scratch ceiling is too small; context/query limits are not reduced automatically" + ) + } + return envelope + } +} + +extension PagedKVPool { + var hasAsymmetricLayers: Bool { layerKinds.contains { $0.headDim != $0.valueHeadDim } } + + /// Acquire once before publishing a serving row. C remains held through + /// pool/cache lifetime, including graph/copy coexistence. No M credit. + func prepareGatheredAttention(maximumSequenceLength: Int) throws { + guard hasAsymmetricLayers else { return } + guard segmentGrant != nil, let limits = config.gatheredAttention, + let admission = memoryAdmission, maximumSequenceLength > 0, + maximumSequenceLength <= limits.maximumContextTokens + else { + throw CBv2KVError.backendIneligible( + reason: + "asymmetric paging requires a bound segmented Admission owner and explicit sufficient gathered-attention limits" + ) + } + if usesStepOwnedAttention { + guard admission.hasProcessMemoryOwner, attentionWorkEngineRefusal == nil, + attentionWorkEnginePrepared + else { + throw CBv2KVError.backendIneligible( + reason: attentionWorkEngineRefusal + ?? "step-owned paging requires its real process owner and sealed engine envelope" + ) + } + return + } + if gatheredAttentionReservation == nil { + gatheredAttentionReservation = try admission.reserveTransient( + bytes: gatheredAttentionScratchBound) + } + } + + var gatheredAttentionIsPrepared: Bool { + usesStepOwnedAttention + ? attentionWorkEnginePrepared && attentionWorkEngineRefusal == nil + : gatheredAttentionReservation != nil + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVBackend.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVBackend.swift index 2bef439cdb..367bb89024 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVBackend.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVBackend.swift @@ -43,11 +43,17 @@ import Foundation import MLX +private final class PagedGatheredRequestOwner { + weak var row: PagedSequenceKV? + init(_ row: PagedSequenceKV) { self.row = row } +} + public final class PagedKVBackend: CBv2KVBackend { public var prefixReuseBackend: CBv2PrefixReuseBackend { .pagedFP16 } public let pool: PagedKVPool /// The model's per-layer structure this backend was built for. public let layerKinds: [CBv2LayerKind] + package private(set) var nativeModelBinding: CBv2NativePagedModelBinding? /// Non-owning physical-page prefix index. nil preserves the historical /// paged backend byte-for-byte; the engine discovers the optional native /// capability without changing the snapshot-cache contract. @@ -60,6 +66,23 @@ public final class PagedKVBackend: CBv2KVBackend { /// Fixed-reference commitment flag. Segmented pools instead track each /// live buffer and may retire it after the final request releases it. private(set) var slabsAreWired = false + private var gatheredRequestOwners: [PagedGatheredRequestOwner] = [] + private var gatheredPendingReservations = 0 + private var attentionRowLayers: [UInt64: Int] = [:] + + private func preflightGatheredRequest(reserved: Bool) throws { + guard pool.hasAsymmetricLayers, let limits = pool.config.gatheredAttention else { return } + gatheredRequestOwners.removeAll { $0.row == nil || $0.row!.isReleased } + guard !reserved || gatheredPendingReservations > 0, + gatheredRequestOwners.count + (reserved ? 0 : gatheredPendingReservations) + < limits.maximumBatchSize + else { + throw CBv2KVError.backendIneligible( + reason: + "explicit asymmetric gathered-attention maximum live request/batch bound exceeded" + ) + } + } /// The only writer of `slabsAreWired`; `private(set)` keeps the flag out /// of reach of everything except `commitSlabs()`, which lives in the /// other file. @@ -72,6 +95,22 @@ public final class PagedKVBackend: CBv2KVBackend { residentPrefixCache: CBv2PagedPrefixCacheConfig? = nil ) throws { for (index, kind) in layerKinds.enumerated() { + guard kind.kvGeometry != nil else { + throw CBv2KVError.backendIneligible( + reason: "layer \(index): invalid native K/V geometry") + } + if kind.valueHeadDim != kind.headDim { + guard config.segmentSizeBytes != nil, config.gatheredAttention != nil, + kind.headDim <= 512, kind.valueHeadDim <= 512, + kind.qwen4IndexerCompressRatio == nil, !kind.isBidirectional, + residentPrefixCache == nil, slabCommitment != .atConstruction + else { + throw CBv2KVError.backendIneligible( + reason: + "layer \(index): asymmetric serving requires explicit segmented native-gathered policy; fixed/fused/indexed/bidirectional/resident-prefix/eager paths are not qualified" + ) + } + } if let source = kind.sharesKVWithLayer { guard source >= 0, source < layerKinds.count, layerKinds[source].sharesKVWithLayer == nil @@ -81,6 +120,7 @@ public final class PagedKVBackend: CBv2KVBackend { } let src = layerKinds[source] guard src.kvHeads == kind.kvHeads, src.headDim == kind.headDim, + src.valueHeadDim == kind.valueHeadDim, src.attention == kind.attention else { throw CBv2KVError.backendIneligible( @@ -88,7 +128,7 @@ public final class PagedKVBackend: CBv2KVBackend { + "\(source)") } } - guard kind.kvHeads > 0, kind.queryHeads % kind.kvHeads == 0 else { + guard kind.kvHeads > 0, kind.queryHeads > 0, kind.queryHeads % kind.kvHeads == 0 else { throw CBv2KVError.backendIneligible( reason: "layer \(index): queryHeads \(kind.queryHeads) not a multiple " + "of kvHeads \(kind.kvHeads)") @@ -98,8 +138,9 @@ public final class PagedKVBackend: CBv2KVBackend { // that will dispatch paged attention — including KV-shared // layers, which borrow storage but launch with their own GQA. // One over-budget layer makes the whole model ineligible. - if let reason = PagedAttentionKernel.ineligibilityReason( - headDim: kind.headDim, gqa: kind.queryHeads / kind.kvHeads) + if kind.valueHeadDim == kind.headDim, + let reason = PagedAttentionKernel.ineligibilityReason( + headDim: kind.headDim, gqa: kind.queryHeads / kind.kvHeads) { throw CBv2KVError.backendIneligible(reason: "layer \(index): \(reason)") } @@ -140,6 +181,20 @@ public final class PagedKVBackend: CBv2KVBackend { } } + /// Protected MiMo constructor only. Ordinary public construction remains + /// byte-for-byte nil-binding policy; no caller can replace the association. + package convenience init( + layerKinds: [CBv2LayerKind], config: PagedKVPoolConfig, + nativeModelBinding: CBv2NativePagedModelBinding + ) throws { + try self.init( + layerKinds: layerKinds, config: config, + slabCommitment: .atFirstAdmission, residentPrefixCache: nil) + try nativeModelBinding.attach(self) + self.nativeModelBinding = nativeModelBinding + pool.nativeModelBinding = nativeModelBinding + } + // MARK: - Admission-time reservation (Codex P2) /// Reserve the worst-case page demand for a request of `maxLength` tokens @@ -155,7 +210,15 @@ public final class PagedKVBackend: CBv2KVBackend { /// the per-row `reservedPages` bookkeeping exactly once. Balance an /// admission that never materializes with `unreserve(layerKinds:maxLength:)`. public func reserve(layerKinds: [CBv2LayerKind], maxLength: Int) throws { + try nativeModelBinding?.preflightCreation( + backend: self, kinds: layerKinds, maximumLength: maxLength) precondition(maxLength > 0) + guard layerKinds == self.layerKinds else { + throw CBv2KVError.backendIneligible( + reason: "paged reservation layout differs from its owner") + } + try preflightGatheredRequest(reserved: false) + try pool.prepareGatheredAttention(maximumSequenceLength: maxLength) let needs = pageNeeds(layerKinds: layerKinds, maxLength: maxLength) try pool.reserve(needs) // The charge succeeded, so this pool is no longer idle. Wire the @@ -165,11 +228,16 @@ public final class PagedKVBackend: CBv2KVBackend { // GUARANTEE would be a daemon abort under load. do { try commitSlabs() + if pool.hasAsymmetricLayers { gatheredPendingReservations += 1 } } catch { // A refused commit must leave the pool exactly as it found it: // unwind the page charge so the rejected admission leaves no // residue and the retry re-charges from a clean ledger. - pool.unreserve(needs) + if nativeModelBinding == nil + || CBv2NativePagedOperation.constructing?.tracking.mayExecute == true + { + pool.unreserve(needs) + } throw error } } @@ -178,6 +246,9 @@ public final class PagedKVBackend: CBv2KVBackend { /// `makeSequenceState` (rejected, superseded, or shut down). public func unreserve(layerKinds: [CBv2LayerKind], maxLength: Int) { pool.unreserve(pageNeeds(layerKinds: layerKinds, maxLength: maxLength)) + if pool.hasAsymmetricLayers { + gatheredPendingReservations = max(0, gatheredPendingReservations - 1) + } } // MARK: - CBv2KVBackend @@ -197,7 +268,14 @@ public final class PagedKVBackend: CBv2KVBackend { public func makeSequenceState( layerKinds: [CBv2LayerKind], promptLength: Int, maxLength: Int, reserved: Bool ) throws -> [CBv2SequenceKV?] { + try nativeModelBinding?.preflightCreation( + backend: self, kinds: layerKinds, maximumLength: maxLength) precondition(maxLength >= promptLength && maxLength > 0) + guard layerKinds == self.layerKinds else { + throw CBv2KVError.backendIneligible(reason: "paged row layout differs from its owner") + } + try preflightGatheredRequest(reserved: reserved) + try pool.prepareGatheredAttention(maximumSequenceLength: maxLength) let needs = pageNeeds(layerKinds: layerKinds, maxLength: maxLength) if !reserved { try pool.reserve(needs) @@ -210,7 +288,12 @@ public final class PagedKVBackend: CBv2KVBackend { do { try commitSlabs() } catch { - if !reserved { pool.unreserve(needs) } + if !reserved, + nativeModelBinding == nil + || CBv2NativePagedOperation.constructing?.tracking.mayExecute == true + { + pool.unreserve(needs) + } throw error } var states: [CBv2SequenceKV?] = [] @@ -227,6 +310,28 @@ public final class PagedKVBackend: CBv2KVBackend { maxLength: maxLength, reservedPages: reserved)) } } + if let binding = nativeModelBinding { + // Retain every actual partial row before the throwing ledger edge. + // Failed native publication must not refund another live promise. + for row in states.compactMap({ $0 }) { + CBv2NativePagedOperation.constructing?.retain(owner: row) + } + do { try binding.register(states, backend: self) } catch { + CBv2NativePagedOperation.constructing?.fail() + throw error + } + } + if pool.hasAsymmetricLayers { + if reserved { gatheredPendingReservations -= 1 } + if let row = states.compactMap({ $0 as? PagedSequenceKV }).first { + gatheredRequestOwners.append(.init(row)) + } + } + if pool.usesStepOwnedAttention { + for (index, state) in states.enumerated() { + if let row = state as? PagedSequenceKV { attentionRowLayers[row.serial] = index } + } + } return states } @@ -266,6 +371,16 @@ public final class PagedKVBackend: CBv2KVBackend { plan: CBv2PrefixReusePlan, layerKinds: [CBv2LayerKind], maxLength: Int ) throws -> [CBv2SequenceKV?] { + guard layerKinds == self.layerKinds else { + throw CBv2KVError.backendIneligible( + reason: "paged restore layout differs from its owner") + } + try nativeModelBinding?.refuseImport() + guard !pool.usesStepOwnedAttention else { + throw CBv2KVError.backendIneligible( + reason: "step-owned paging prefix adoption requires separate transfer qualification" + ) + } guard plan.backend == .pagedFP16 else { throw CBv2KVError.backendIneligible( reason: "paged adoption received \(plan.backend.rawValue) prefix plan") @@ -275,7 +390,8 @@ public final class PagedKVBackend: CBv2KVBackend { reason: "prefix count \(prefix.count) != layer count \(layerKinds.count)") } guard layerKinds.count == pool.layerDTypes.count else { - throw CBv2KVError.backendIneligible(reason: "prefix layer count does not match paged pool") + throw CBv2KVError.backendIneligible( + reason: "prefix layer count does not match paged pool") } // Snapshot import is a throwing boundary, unlike model forward. // Reject all source dtypes before reserving/mutating any destination; @@ -283,9 +399,32 @@ public final class PagedKVBackend: CBv2KVBackend { try pool.writeValidation.check() for (index, entry) in prefix.enumerated() { guard let entry else { continue } + let kind = layerKinds[index] + guard kind.sharesKVWithLayer == nil, entry.offset > 0, + entry.keys.ndim == 3 || entry.keys.ndim == 4, + entry.values.ndim == entry.keys.ndim, + entry.keys.ndim != 4 || (entry.keys.dim(0) == 1 && entry.values.dim(0) == 1) + else { + throw CBv2KVError.backendIneligible( + reason: "invalid paged source snapshot owner/rank") + } + let k = Self.rowShaped(entry.keys) + let v = Self.rowShaped(entry.values) + guard k.dim(0) == kind.kvHeads, v.dim(0) == kind.kvHeads, + k.dim(2) == kind.headDim, v.dim(2) == kind.valueHeadDim, + k.dim(1) == v.dim(1), k.dim(1) > 0 + else { + throw CBv2KVError.backendIneligible( + reason: "paged source snapshot role geometry mismatch") + } + if case .full = kind.attention, k.dim(1) != entry.offset { + throw CBv2KVError.backendIneligible( + reason: "paged source snapshot does not cover its full boundary") + } let expected = pool.layerDTypes[index] guard entry.keys.dtype == expected, entry.values.dtype == expected else { - throw CBv2PagedKVWriteError(layerIndex: index, expected: expected, + throw CBv2PagedKVWriteError( + layerIndex: index, expected: expected, keys: entry.keys.dtype, values: entry.values.dtype) } } @@ -302,12 +441,13 @@ public final class PagedKVBackend: CBv2KVBackend { var matched = 0 for (index, entry) in prefix.enumerated() { guard let entry else { continue } - precondition( - layerKinds[index].sharesKVWithLayer == nil, - "prefix donated to a KV-shared layer \(index)") - precondition( - matched == 0 || matched == entry.offset, - "non-uniform prefix offsets (\(entry.offset) vs \(matched))") + guard layerKinds[index].sharesKVWithLayer == nil, + case .full = layerKinds[index].attention, + matched == 0 || matched == entry.offset + else { + throw CBv2KVError.backendIneligible( + reason: "ordinary paged restore has invalid owner/window/nonuniform boundary") + } matched = entry.offset } guard matched == plan.restoredFullTokens, matched == plan.replayStart else { @@ -424,7 +564,7 @@ public final class PagedKVBackend: CBv2KVBackend { let values = Self.rowShaped(entry.values) guard keys.ndim == 3, values.ndim == 3, keys.dim(0) == kind.kvHeads, values.dim(0) == kind.kvHeads, - keys.dim(2) == kind.headDim, values.dim(2) == kind.headDim, + keys.dim(2) == kind.headDim, values.dim(2) == kind.valueHeadDim, keys.dim(1) == matched, values.dim(1) == matched else { throw CBv2KVError.backendIneligible( @@ -446,7 +586,7 @@ public final class PagedKVBackend: CBv2KVBackend { guard entry.keys.ndim == 4, let snapshot = CBv2PagedWindowSnapshot( keys: entry.keys, values: entry.values, - base: entry.offset - entry.keys.dim(2)) + base: entry.offset - entry.keys.dim(2), valueHeadDim: kind.valueHeadDim) else { throw CBv2KVError.backendIneligible( reason: "windowed prefix at layer \(index) is not a well-formed " @@ -464,7 +604,7 @@ public final class PagedKVBackend: CBv2KVBackend { guard snapshot.keys.dim(1) == kind.kvHeads, snapshot.keys.dim(3) == kind.headDim, snapshot.values.dim(1) == kind.kvHeads, - snapshot.values.dim(3) == kind.headDim + snapshot.values.dim(3) == kind.valueHeadDim else { throw CBv2KVError.backendIneligible( reason: "windowed prefix at layer \(index) has the wrong KV geometry") @@ -565,13 +705,77 @@ public final class PagedKVBackend: CBv2KVBackend { array.ndim == 4 && array.dim(0) == 1 ? array.squeezed(axis: 0) : array } + /// A recoverable all-row ownership check for package-native callers/tests. + /// A refusal has not removed any ledger entry or freed any pool page. + package func releaseNativeValidated(_ state: [CBv2SequenceKV?]) throws { + guard let nativeModelBinding else { + throw CBv2KVError.backendIneligible(reason: "no issued native paged binding") + } + try nativeModelBinding.remove(state, backend: self) + releaseRowsAfterValidation(state) + } + + /// Fresh page-prefix rows are registered through the SAME backend and + /// MiMo cohort ledger as cold rows, before atomic pool publication. + /// The private preparation proves its actual required completion. + func registerPreparedNativeCheckpoint( + _ state: [CBv2SequenceKV?], + preparation: CBv2PreparedNativePagedCheckpoint + ) throws { + guard let nativeModelBinding, preparation.authorizesRegistration(state, backend: self), + state.count == layerKinds.count, + state.enumerated().allSatisfy({ index, item in + guard let row = item as? PagedSequenceKV else { return false } + return row.pool === pool && row.table.isEmpty && row.absoluteOffset == 0 + && !row.isReleased && attentionRowLayers[row.serial] == nil + && row.groupKey == pool.groupKey(forLayer: index) + }) + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + try preflightGatheredRequest(reserved: false) + try nativeModelBinding.register(state, backend: self) + if let first = state.first.flatMap({ $0 as? PagedSequenceKV }) { + gatheredRequestOwners.append(.init(first)) + } + for (index, item) in state.enumerated() { + attentionRowLayers[(item as! PagedSequenceKV).serial] = index + } + } + + /// Refusal before publication owns no pool pages. Remove only that exact + /// fresh cohort; do not call releaseStorage/unreserve for uninstalled rows. + func rollbackPreparedNativeCheckpointRegistration( + _ state: [CBv2SequenceKV?], + preparation: CBv2PreparedNativePagedCheckpoint + ) throws { + guard let nativeModelBinding, preparation.authorizesRegistration(state, backend: self), + state.allSatisfy({ ($0 as? PagedSequenceKV)?.table.isEmpty == true }) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try nativeModelBinding.remove(state, backend: self) + let serials = Set(state.compactMap { ($0 as? PagedSequenceKV)?.serial }) + for serial in serials { attentionRowLayers.removeValue(forKey: serial) } + gatheredRequestOwners.removeAll { $0.row.map { serials.contains($0.serial) } ?? true } + } + public func release(_ state: [CBv2SequenceKV?]) { + if nativeModelBinding != nil { + do { try releaseNativeValidated(state) } catch { + preconditionFailure("native MiMo paged owned release invariant: \(error)") + } + return + } + releaseRowsAfterValidation(state) + } + + private func releaseRowsAfterValidation(_ state: [CBv2SequenceKV?]) { for entry in state { guard let entry else { continue } guard let paged = entry as? PagedSequenceKV else { fatalError("[PagedKVBackend] release of a foreign sequence state") } paged.releaseStorage() + attentionRowLayers.removeValue(forKey: paged.serial) } } @@ -613,4 +817,185 @@ public final class PagedKVBackend: CBv2KVBackend { attentionSoftcap: attentionSoftcap) } } + + /// Scalar planning and real Admission acquisition precede every forward. + /// Row serials are pool-issued routing identities, never allocation IDs. + func prepareAttentionWork( + assignments: [(id: CBv2RequestID, range: Range)], + states: [CBv2RequestID: [CBv2SequenceKV?]] + ) throws -> CBv2PagedAttentionStepOwner? { + guard pool.usesStepOwnedAttention else { return nil } + guard pool.attentionWorkEnginePrepared, pool.attentionWorkEngineRefusal == nil, + pool.activeAttentionWork == nil, !assignments.isEmpty, + let limits = pool.config.gatheredAttention, + let admission = pool.memoryAdmission, admission.hasProcessMemoryOwner, + let policy = Memory.allocationFootprintPolicy(), + StreamOrDevice.default.stream == Stream.gpu, + assignments.count <= limits.maximumBatchSize, + pool.attentionWorkOwners.values.filter({ !$0.completed }).count + < limits.maximumInFlightGraphs, + Set(assignments.map(\.id)).count == assignments.count + else { + throw CBv2KVError.backendIneligible( + reason: pool.attentionWorkEngineRefusal + ?? "step-owned paging has no valid engine/process/stream preparation") + } + let environment = CBv2PagedAttentionWorkEnvironment.capture() + try environment.requireSupported() + var descriptors: [CBv2PagedAttentionTicketKey: CBv2PagedAttentionRowDescriptor] = [:] + var allocations: [CBv2PagedAttentionAllocation] = [] + var rowRequests: [UInt64: CBv2RequestID] = [:] + var possibleBatchBuffers: [String: Int] = [:] + for assignment in assignments { + guard let rows = states[assignment.id], rows.count == layerKinds.count, + !assignment.range.isEmpty, assignment.range.lowerBound >= 0, + assignment.range.upperBound <= limits.maximumContextTokens, + assignment.range.count <= limits.maximumQueryTokens + else { + throw CBv2KVError.backendIneligible( + reason: "invalid actual paged attention work range") + } + for (index, kind) in layerKinds.enumerated() { + let owner = kind.sharesKVWithLayer ?? index + guard kind.headDim != kind.valueHeadDim, + let row = rows[owner] as? PagedSequenceKV, + row.pool === pool, !row.isReleased, + row.speculativeBase == nil + || CBv2NativePagedMTPWork.current? + .permitsPlannedColumn(row, range: assignment.range) == true, + attentionRowLayers[row.serial] == owner, + row.absoluteOffset == assignment.range.lowerBound, + row.maxLength >= assignment.range.upperBound, + row.windowSize == nil || assignment.range.count <= pool.config.maxPrefillChunk, + row.groupKey == pool.groupKey(forLayer: owner), + let cache = pool.attentionWorkCaches[index]?.value, + cache.pool === pool, cache.kind == kind, + row.frozenHighWater <= assignment.range.lowerBound + || assignment.range.upperBound <= row.frozenHighWater + else { + throw CBv2KVError.backendIneligible( + reason: "paged work row/cache identity, generation or frozen range mismatch" + ) + } + if let previous = rowRequests[row.serial], previous != assignment.id { + throw CBv2KVError.backendIneligible( + reason: "paged work aliases one row across requests") + } + rowRequests[row.serial] = assignment.id + let q = assignment.range.count + let start = assignment.range.lowerBound + let frozen = row.frozenHighWater > start + let keyStart: Int + if q == 1 { + keyStart = + row.windowSize.map { max(row.baseOffset, assignment.range.upperBound - $0) } + ?? row.baseOffset + } else { + keyStart = + row.windowSize.map { max(row.baseOffset, start - $0 + 1) } + ?? row.baseOffset + } + let keyCount = assignment.range.upperBound - keyStart + let gather: Range? + if q == 1 || (owner == index && frozen) { + gather = keyStart ..< assignment.range.upperBound + } else if owner == index && keyStart < start { + gather = keyStart ..< start + } else { + gather = nil + } + var blocks: [CBv2PagedAttentionBlock] = [] + if q > 1 && environment.queryBlockSize > 0 && q > environment.queryBlockSize { + var offset = 0 + while offset < q { + let count = min(environment.queryBlockSize, q - offset) + let bounds = CBv2AttentionV1.queryBlockBounds( + historyCount: start - keyStart, offset: offset, count: count, + window: row.windowSize) + blocks.append( + .init( + queryOffset: offset, queryCount: count, + visibleStart: bounds.visibleStart, visibleEnd: bounds.visibleEnd)) + offset += count + } + } else { + blocks = [ + .init(queryOffset: 0, queryCount: q, visibleStart: 0, visibleEnd: keyCount) + ] + } + let descriptor = CBv2PagedAttentionRowDescriptor( + requestID: assignment.id, row: .init(row), rowSerial: row.serial, + layerIndex: index, ownerLayerIndex: owner, range: assignment.range, + baseOffset: row.baseOffset, frozenHighWater: row.frozenHighWater, + gatheredRange: gather, keyStart: keyStart, keyCount: keyCount, + blocks: blocks, softcap: cache.attentionSoftcap != nil) + descriptors[.init(layer: index, serial: row.serial)] = descriptor + let rowAllocations = try CBv2PagedAttentionWorkProjection.allocations( + kind: kind, dtype: pool.layerDTypes[index], descriptor: descriptor, + pageSize: pool.config.pageSize, policy: policy) + for allocation in rowAllocations { + guard allocation.maximumLogicalBufferBytes <= pool.config.maxBufferLength else { + throw CBv2KVError.backendIneligible( + reason: + "actual attention workspace exceeds native maximum buffer length") + } + if allocation.role == "output.batchConcat" + || allocation.role.hasPrefix("position.offset") + { + let key = "\(index):\(allocation.role)" + possibleBatchBuffers[key] = try CBv2PagedWorkMath.add( + possibleBatchBuffers[key] ?? 0, allocation.logicalBytes) + guard possibleBatchBuffers[key]! <= pool.config.maxBufferLength else { + throw CBv2KVError.backendIneligible( + reason: + "actual packed workspace exceeds native maximum buffer length") + } + } + } + allocations += rowAllocations + } + } + let bytes = try allocations.reduce(64 << 10) { + try CBv2PagedWorkMath.add($0, $1.upperBoundBytes) + } + let coexistence = try CBv2PagedWorkMath.add(pool.attentionWorkBytesReserved, bytes) + guard coexistence <= limits.maximumScratchBytes else { + throw CBv2KVError.capacityExhausted( + needed: bytes, + available: max(0, limits.maximumScratchBytes - pool.attentionWorkBytesReserved)) + } + let (generation, overflow) = pool.attentionWorkGeneration.addingReportingOverflow(1) + guard !overflow else { + throw CBv2KVError.backendIneligible(reason: "paged work generation exhausted") + } + let nativeOperation = try nativeModelBinding?.beginWork( + requests: Set(assignments.map(\.id))) + do { + let reservation = try admission.reserveTransient(bytes: bytes) + nativeOperation?.retain(owner: reservation) // before any late veto + let work = CBv2PagedAttentionStepOwner( + generation: generation, pool: pool, + environment: environment, descriptors: descriptors, allocations: allocations, + bytes: bytes, reservation: reservation, allocationPolicy: policy, + nativeOperation: nativeOperation) + nativeOperation?.retain(owner: work) + try nativeOperation?.requireWork() + pool.attentionWorkGeneration = generation + pool.attentionWorkOwners[generation] = work + pool.publishAttentionWorkCharge() + pool.activeAttentionWork = work + return work + } catch { + if let nativeOperation { + if nativeOperation.tracking.mayExecute { + // Only a reserveTransient refusal can reach this healthy + // catch before a work/reservation owner was installed. + nativeOperation.finish(unstarted: true) + } else { + nativeOperation.fail() + } + } + throw error + } + } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVGroup.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVGroup.swift index 7bf5124e14..704320272a 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVGroup.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVGroup.swift @@ -13,8 +13,14 @@ final class PagedKVGroup { /// in place by the write kernels, never replaced (see file header). private let fixedK: MLXArray? private let fixedV: MLXArray? - var kSlab: MLXArray { precondition(segmentLayout == nil); return fixedK! } - var vSlab: MLXArray { precondition(segmentLayout == nil); return fixedV! } + var kSlab: MLXArray { + precondition(segmentLayout == nil) + return fixedK! + } + var vSlab: MLXArray { + precondition(segmentLayout == nil) + return fixedV! + } private(set) var segmentLayout: PagedKVSegmentLayout? private(set) var segments: [Int: PagedKVSegment] = [:] var committedUsablePages: Int { @@ -57,9 +63,13 @@ final class PagedKVGroup { /// Bytes of ONE slab (K or V alone), poison page included — the unit /// `materializeSlabs` allocates and tracks. - var slabBytes: Int { + var keySlabBytes: Int { pageCount * key.kvHeads * pageSize * key.headDim * dtype.size } + var valueSlabBytes: Int { pageCount * key.kvHeads * pageSize * key.valueHeadDim * dtype.size } + /// Legacy equal-width diagnostic surface. Role-aware accounting uses the + /// two explicit properties above, never this value for an asymmetric pair. + var slabBytes: Int { keySlabBytes } /// Local page zero is inert and pinned in every backing buffer. Fixed /// slabs use global page zero; segmented kernels translate invalid/padded @@ -72,12 +82,14 @@ final class PagedKVGroup { /// Bytes of ONE page counting both K and V slabs. var pageBytes: Int { - 2 * key.kvHeads * pageSize * key.headDim * dtype.size + key.geometry!.storageBytes(tokens: pageSize, elementBytes: dtype.size)! } - init(key: PagedKVGroupKey, pageCount: Int, pageSize: Int, dtype: DType, - segmentLayout: PagedKVSegmentLayout? = nil, - writeValidation: CBv2PagedKVWriteValidation = CBv2PagedKVWriteValidation()) { + init( + key: PagedKVGroupKey, pageCount: Int, pageSize: Int, dtype: DType, + segmentLayout: PagedKVSegmentLayout? = nil, + writeValidation: CBv2PagedKVWriteValidation = CBv2PagedKVWriteValidation() + ) { self.writeValidation = writeValidation precondition( segmentLayout != nil || pageCount >= 2, @@ -87,9 +99,10 @@ final class PagedKVGroup { self.dtype = dtype self.fixedPageCount = pageCount let shape = [pageCount, key.kvHeads, pageSize, key.headDim] + let valueShape = [pageCount, key.kvHeads, pageSize, key.valueHeadDim] self.segmentLayout = segmentLayout self.fixedK = segmentLayout == nil ? MLXArray.zeros(shape, dtype: dtype) : nil - self.fixedV = segmentLayout == nil ? MLXArray.zeros(shape, dtype: dtype) : nil + self.fixedV = segmentLayout == nil ? MLXArray.zeros(valueShape, dtype: dtype) : nil self.writeFence = MLXArray.zeros([1], dtype: .int32) // Initial FIFO order is ascending ids, so fresh allocations remain // physically consecutive (enables run-coalesced writes). The poison @@ -116,7 +129,8 @@ final class PagedKVGroup { /// True when `page` is a page a sequence row can own. The poison page /// and out-of-range ids are not. func isAllocatable(_ page: Int32) -> Bool { - segmentLayout?.isUsable(page) ?? (page != Self.poisonPage && page >= 0 && Int(page) < pageCount) + segmentLayout?.isUsable(page) + ?? (page != Self.poisonPage && page >= 0 && Int(page) < pageCount) } func currentHandle(_ page: Int32) -> PagedKVPageHandle { @@ -225,7 +239,8 @@ final class PagedKVGroup { func segment(for page: Int32) -> PagedKVSegment { precondition(isAllocatable(page)) - guard let layout = segmentLayout, let segment = segments[layout.segmentIndex(page: page)] else { + guard let layout = segmentLayout, let segment = segments[layout.segmentIndex(page: page)] + else { preconditionFailure("page has no committed segment") } return segment @@ -259,11 +274,14 @@ final class PagedKVGroup { guard !overflow else { throw CBv2CompleteCheckpointError.invalidManifest } physical = next } - return GrowthPlan(layout: planned.layout, segmentIDs: planned.segmentIDs, physicalBytes: physical) + return GrowthPlan( + layout: planned.layout, segmentIDs: planned.segmentIDs, physicalBytes: physical) } - func prepareGrowth(_ plan: GrowthPlan, evaluate: (MLXArray) throws -> Void, - admission: AdmissionV2? = nil) throws + func prepareGrowth( + _ plan: GrowthPlan, evaluate: (MLXArray) throws -> Void, + admission: AdmissionV2? = nil + ) throws -> PreparedGrowth { var replacement = segments @@ -284,8 +302,9 @@ final class PagedKVGroup { counts[segment.pages.lowerBound] = 1 for page in segment.pages.dropFirst() { queue.append(Int32(page)) } } - return PreparedGrowth(layout: plan.layout, segments: replacement, - refCounts: counts, generations: versions, freeQueue: queue) + return PreparedGrowth( + layout: plan.layout, segments: replacement, + refCounts: counts, generations: versions, freeQueue: queue) } /// Only complete ownership swaps occur here. Preparation already performed @@ -316,8 +335,10 @@ final class PagedKVGroup { /// Rebase only the staged M pages. Existing free backing supplies the /// remaining full-N promise before this planner creates any new segments. - func planImport(_ source: CBv2PagedCheckpointStorage.Group, - additionalReservedPages: Int) throws -> ImportPlan { + func planImport( + _ source: CBv2PagedCheckpointStorage.Group, + additionalReservedPages: Int + ) throws -> ImportPlan { guard let current = segmentLayout, current.pageBytes == source.layout.pageBytes, current.maximumUsablePages == source.layout.maximumUsablePages, @@ -349,24 +370,30 @@ final class PagedKVGroup { usablePages: needed, excluding: Set(segments.keys).union(imported.segmentIDs)) var physical = committedSegmentBytes + importedBytes for id in grown.segmentIDs { - let (next, overflow) = physical.addingReportingOverflow(try grown.layout.allocationBytes(forSegment: id)) + let (next, overflow) = physical.addingReportingOverflow( + try grown.layout.allocationBytes(forSegment: id)) guard !overflow else { throw CBv2CompleteCheckpointError.invalidManifest } physical = next } return ImportPlan( layout: grown.layout, importedIDs: imported.segmentIDs, sourceIDs: sourceIDs, growthIDs: grown.segmentIDs, physicalBytes: physical, - additionalReservedPages: additionalReservedPages, pages: try source.pages.map { - guard let page = pageMap[$0] else { throw CBv2CompleteCheckpointError.invalidManifest } + additionalReservedPages: additionalReservedPages, + pages: try source.pages.map { + guard let page = pageMap[$0] else { + throw CBv2CompleteCheckpointError.invalidManifest + } return page }) } /// All replacement dictionaries, tables and free queues are prepared /// before grant publication. Only missing suffix buffers allocate/evaluate. - func prepareImport(_ plan: ImportPlan, source: CBv2PagedCheckpointStorage.Group, - evaluate: (MLXArray) throws -> Void, - admission: AdmissionV2? = nil) throws -> PreparedImport { + func prepareImport( + _ plan: ImportPlan, source: CBv2PagedCheckpointStorage.Group, + evaluate: (MLXArray) throws -> Void, + admission: AdmissionV2? = nil + ) throws -> PreparedImport { var replacement = segments var counts = refCounts var versions = generations @@ -399,8 +426,9 @@ final class PagedKVGroup { for page in segment.pages.dropFirst() { queue.append(Int32(page)) } } return PreparedImport( - growth: PreparedGrowth(layout: plan.layout, segments: replacement, - refCounts: counts, generations: versions, freeQueue: queue), + growth: PreparedGrowth( + layout: plan.layout, segments: replacement, + refCounts: counts, generations: versions, freeQueue: queue), pagesInUse: pagesInUse + plan.pages.count, pagesReserved: pagesReserved + plan.additionalReservedPages) } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVPool+Segments.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVPool+Segments.swift index bab69575ea..9f847c9eb0 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVPool+Segments.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVPool+Segments.swift @@ -25,10 +25,13 @@ extension PagedKVPool { guard pages >= 0 else { throw CBv2KVError.backendIneligible(reason: "negative paged reservation") } - let (extra, multiplyOverflow) = pages.multipliedReportingOverflow(by: group(key).pageBytes) + let (extra, multiplyOverflow) = pages.multipliedReportingOverflow( + by: group(key).pageBytes) let (total, addOverflow) = logical.addingReportingOverflow(extra) guard !multiplyOverflow, !addOverflow, total <= reuseCeiling else { - throw CBv2KVError.capacityExhausted(needed: multiplyOverflow || addOverflow ? Int.max : extra, available: max(0, reuseCeiling - logical)) + throw CBv2KVError.capacityExhausted( + needed: multiplyOverflow || addOverflow ? Int.max : extra, + available: max(0, reuseCeiling - logical)) } logical = total } @@ -37,7 +40,8 @@ extension PagedKVPool { let g = group(key) var target = g.pagesReserved + needs[key, default: 0] if eager { - let product = UInt64(grant.bytes).multipliedFullWidth(by: UInt64(groupDemandBytes[key]!)) + let product = UInt64(grant.bytes).multipliedFullWidth( + by: UInt64(groupDemandBytes[key]!)) let bytes = UInt64(totalDemandBytes).dividingFullWidth(product).quotient let pages = Int(bytes) / g.pageBytes target = max(target, g.segmentLayout!.usablePages(fittingPhysicalPages: pages)) @@ -66,9 +70,12 @@ extension PagedKVPool { var requested: [PagedKVGroupKey: Int] = [:] for count in tokens where count > 0 { for (index, kind) in layerKinds.enumerated() where kind.sharesKVWithLayer == nil { - guard let rows = residency.residentRows(layer: kind, tokens: count) else { return nil } + guard let rows = residency.residentRows(layer: kind, tokens: count) else { + return nil + } let key = groupKey(forLayer: index) - let (total, overflow) = requested[key, default: 0].addingReportingOverflow(rows / config.pageSize) + let (total, overflow) = requested[key, default: 0].addingReportingOverflow( + rows / config.pageSize) guard !overflow else { return nil } requested[key] = total } @@ -80,17 +87,21 @@ extension PagedKVPool { /// fits nominal pages but cannot fit its minimum poison overhead must not /// enter an endless allocate/preempt loop. This allocates no page map. func minimumSegmentedOverhead(tokens: Int, layerKinds: [CBv2LayerKind]) -> Int? { - guard segmentGrant != nil, let pages = requestedPages(tokens: [tokens], layerKinds: layerKinds) else { return nil } + guard segmentGrant != nil, + let pages = requestedPages(tokens: [tokens], layerKinds: layerKinds) + else { return nil } var overhead = 0 for (key, count) in pages { // Geometry was checked at construction; the token-dependent // products below still use checked arithmetic. - let pageBytes = 2 * key.kvHeads * config.pageSize * key.headDim * key.dtype.size - guard let layout = try? PagedKVSegmentLayout( - pageBytes: pageBytes, - targetBytes: config.segmentSizeBytes ?? PagedKVSegmentLayout.defaultTargetBytes, - maximumBufferBytes: config.maxBufferLength, - maximumAddressPages: Int(Int32.max) / config.pageSize), + guard + let pageBytes = key.geometry?.storageBytes( + tokens: config.pageSize, elementBytes: key.dtype.size), + let layout = try? PagedKVSegmentLayout( + pageBytes: pageBytes, + targetBytes: config.segmentSizeBytes ?? PagedKVSegmentLayout.defaultTargetBytes, + maximumBufferBytes: config.maxBufferLength, + maximumAddressPages: Int(Int32.max) / config.pageSize), let physical = layout.allocationBytes(addingUsablePages: count) else { return nil } let (nominal, multiplyOverflow) = count.multipliedReportingOverflow(by: pageBytes) @@ -115,7 +126,8 @@ extension PagedKVPool { for (key, pages) in requested { let group = group(key) let extra = max(0, pages - group.committedUsablePages) - guard let additional = group.segmentLayout?.allocationBytes(addingUsablePages: extra) else { return nil } + guard let additional = group.segmentLayout?.allocationBytes(addingUsablePages: extra) + else { return nil } let (next, overflow) = physical.addingReportingOverflow(additional) guard !overflow else { return nil } physical = next @@ -127,28 +139,37 @@ extension PagedKVPool { /// Reserve logical pages against the exact physical growth plan. A later /// commitment rechecks the grant before publishing any native buffers. func reserveSegments(_ needs: [PagedKVGroupKey: Int]) throws { - let grant = segmentGrant!.snapshot() - let plans: [SegmentGrowth] - do { plans = try planSegments(additional: needs, grant: grant) } - catch { - if let error = error as? CBv2KVError, case .capacityExhausted = error { - PagedKVStorageTelemetry.increment(&storageTelemetry.grantRefusals) + // Pure planning creates private host layout maps but no native data. + // Keep its real allowance through the inner scope's last map alias. + let hostMetadata = try nativePrefixHostMetadataPreparation(additional: needs) + try withExtendedLifetime(hostMetadata) { + let grant = segmentGrant!.snapshot() + let plans: [SegmentGrowth] + do { plans = try planSegments(additional: needs, grant: grant) } catch { + if let error = error as? CBv2KVError, case .capacityExhausted = error { + PagedKVStorageTelemetry.increment(&storageTelemetry.grantRefusals) + } + throw error + } + let physical = try physicalBytes(plans) + let accepted = segmentGrant!.publish( + expected: grant, physicalBytes: physical, existingPhysicalBytes: bytesMaterialized + ) { + for (key, pages) in needs { group(key).pagesReserved += pages } + } + storageTelemetry.record(accepted) + guard accepted == .installed else { + throw CBv2KVError.capacityExhausted( + needed: physical, available: segmentGrant!.snapshot().bytes) } - throw error - } - let physical = try physicalBytes(plans) - let accepted = segmentGrant!.publish( - expected: grant, physicalBytes: physical, existingPhysicalBytes: bytesMaterialized) { - for (key, pages) in needs { group(key).pagesReserved += pages } - } - storageTelemetry.record(accepted) - guard accepted == .installed else { - throw CBv2KVError.capacityExhausted( - needed: physical, available: segmentGrant!.snapshot().bytes) } } func materializeSegments(all: Bool) throws { + if let binding = nativeModelBinding { + try materializeIssuedNativeSegments(all: all, binding: binding) + return + } let grant = segmentGrant!.snapshot() let plans = try planSegments(eager: all, grant: grant) // Existing promises survive a shrink. With no allocation to publish, @@ -162,8 +183,7 @@ extension PagedKVPool { let previousPhysicalBytes = bytesMaterialized // The plan contains all old backing plus every private new segment. // Admission charges the peak before the first native allocation. - do { try physicalLease?.resize(to: physical) } - catch { + do { try physicalLease?.resize(to: physical) } catch { PagedKVStorageTelemetry.increment(&storageTelemetry.admissionRefusals) throw error } @@ -171,8 +191,12 @@ extension PagedKVPool { var preparing = true do { for item in plans where !item.plan.segmentIDs.isEmpty { - prepared.append((item.group, try item.group.prepareGrowth( - item.plan, evaluate: slabEval, admission: memoryAdmission))) + prepared.append( + ( + item.group, + try item.group.prepareGrowth( + item.plan, evaluate: slabEval, admission: memoryAdmission) + )) } preparing = false let actual = prepared.reduce(bytesMaterialized) { total, entry in @@ -226,3 +250,125 @@ extension PagedKVPool { grantEpochRetries: storageTelemetry.grantEpochRetries) } } + +extension PagedKVPool { + /// Checked scalar upper bound before any replacement map is constructed. + /// A fresh segment has at most one poison page per usable page. Reused + /// address ranges only reduce this bound. Soft grant changes are NOT a + /// new immutable capacity limit, and shrink never refunds retained maps. + func nativePrefixHostMetadataPreparation(additional: [PagedKVGroupKey: Int] = [:]) + throws -> CBv2NativePagedHostMetadataGeneration? + { + guard let binding = nativeModelBinding, binding.completePrefixIdentity != nil else { + return nil + } + var addresses = 0 + var grows = false + for group in groups.values { + guard additional[group.key, default: 0] >= 0, + let promised = CBv2KVGeometry.add( + group.pagesReserved, additional[group.key, default: 0]) + else { + throw CBv2CompleteCheckpointError.invalidManifest + } + let missing = max(0, promised - group.committedUsablePages) + grows = grows || missing > 0 + guard let extra = CBv2KVGeometry.multiply(missing, 2), + let total = CBv2KVGeometry.add(group.pageCount, extra), + let next = CBv2KVGeometry.add(addresses, total) + else { + throw CBv2CompleteCheckpointError.invalidManifest + } + addresses = next + } + return grows ? try binding.reserveHostMetadata(addressPages: addresses) : nil + } + + private func materializeIssuedNativeSegments( + all: Bool, + binding: CBv2NativePagedModelBinding + ) throws { + try binding.requireEngineQueue() + guard !all else { + throw CBv2KVError.backendIneligible( + reason: "native paged profile does not authorize eager slabs") + } + let operation = try binding.beginWork() + let previous = bytesMaterialized + var grewFloor = false + var hostMetadata: CBv2NativePagedHostMetadataGeneration? + var retiringHostMetadata: CBv2NativePagedHostMetadataGeneration? + defer { withExtendedLifetime(retiringHostMetadata) {} } + do { + hostMetadata = try nativePrefixHostMetadataPreparation() + if let hostMetadata { operation.retain(owner: hostMetadata) } + let grant = segmentGrant!.snapshot() + let plans = try planSegments(eager: false, grant: grant) + guard plans.contains(where: { !$0.plan.segmentIDs.isEmpty }) else { + if hostMetadata != nil { try operation.requiredDrain() } + operation.finish(unstarted: hostMetadata == nil) + return + } + let physical = try physicalBytes(plans) + guard physical <= grant.bytes else { + throw CBv2KVError.capacityExhausted(needed: physical, available: grant.bytes) + } + try physicalLease?.resize(to: physical) + grewFloor = true + var prepared: [(PagedKVGroup, PagedKVGroup.PreparedGrowth)] = [] + try operation.withConstruction { + for item in plans where !item.plan.segmentIDs.isEmpty { + prepared.append( + ( + item.group, + try item.group.prepareGrowth( + item.plan, evaluate: slabEval, admission: memoryAdmission) + )) + } + } + // Slab eval/actual constructor fences and this captured-stream + // completion are outside the native metadata commit. + try operation.requiredDrain() + let actual = prepared.reduce(bytesMaterialized) { total, entry in + total - entry.0.committedSegmentBytes + + entry.1.segments.values.reduce(0) { $0 + $1.allocatedBytes } + } + guard + try operation.tracking.commitIfHealthyThrowing({ + let accepted = segmentGrant!.publish(expected: grant, physicalBytes: actual) { + for (group, replacement) in prepared { group.installGrowth(replacement) } + if hostMetadata != nil { + retiringHostMetadata = binding.installHostMetadata(hostMetadata) + } + } + storageTelemetry.record(accepted) + guard accepted == .installed else { + throw CBv2KVError.capacityExhausted(needed: actual, available: grant.bytes) + } + }) + else { throw CBv2NativeShutdownError.operationClosed } + operation.finish { physicalLease?.release(to: actual) } + } catch { + if operation.hasArrays || operation.failed || !operation.tracking.mayExecute { + // Even a late grant/cancellation failure retains actual + // partial buffers/backing AND the full previously paid peak. + operation.fail() + } else { + // Actual typed cold scope: no array was created/submitted. + // The old live pool has not been changed. + // Host-only planning owners still need an honest completion + // boundary before the operation can detach them. + if hostMetadata != nil { + do { try operation.requiredDrain() } catch { + operation.fail() + throw error + } + } + operation.finish(unstarted: hostMetadata == nil) { + if grewFloor { physicalLease?.release(to: previous) } + } + } + throw error + } + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVPool.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVPool.swift index 95c1a0928d..e6e6169a6f 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVPool.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVPool.swift @@ -37,6 +37,9 @@ public struct PagedKVPoolConfig: Sendable { /// build-time forward probe must validate this table before serving. nil /// preserves the uniform fixed-reference policy. public var layerDTypes: [DType]? + /// Explicit correctness-first asymmetric paging policy. nil preserves + /// legacy fused eligibility; no model/provider default opts into this. + public var gatheredAttention: CBv2PagedGatheredAttentionLimits? /// Explicit foundation opt-in. nil retains the fixed-slab reference. /// Segments grow under the same byte grant; this is not a total-pool cap. public var segmentSizeBytes: Int? @@ -80,12 +83,14 @@ public struct PagedKVPoolConfig: Sendable { maxBufferLength: Int = MLX.GPU.deviceInfo().maxBufferSize, prefixSharingBlockSize: Int? = nil, segmentSizeBytes: Int? = nil, - layerDTypes: [DType]? = nil + layerDTypes: [DType]? = nil, + gatheredAttention: CBv2PagedGatheredAttentionLimits? = nil ) { self.pageSize = pageSize self.capacityBytes = capacityBytes self.dtype = dtype self.layerDTypes = layerDTypes + self.gatheredAttention = gatheredAttention self.maxPrefillChunk = maxPrefillChunk self.nominalMaxSequenceLength = nominalMaxSequenceLength self.maxBufferLength = maxBufferLength @@ -116,6 +121,33 @@ public final class PagedKVPool { /// segments. Only this pool's nominal request KV can offset its floor. var physicalLease: CBv2BackendPhysicalLease? var memoryAdmission: AdmissionV2? + var nativeModelBinding: CBv2NativePagedModelBinding? + public let gatheredAttentionScratchBound: Int + var gatheredAttentionReservation: CBv2CheckpointReservation? + var attentionWorkEnginePrepared = false + private let attentionWorkSnapshotLock = NSLock() + private var attentionWorkRefusalSnapshot: String? + private var attentionWorkChargeSnapshot = 0 + var attentionWorkEngineRefusal: String? { + get { attentionWorkSnapshotLock.withLock { attentionWorkRefusalSnapshot } } + set { attentionWorkSnapshotLock.withLock { attentionWorkRefusalSnapshot = newValue } } + } + var attentionWorkGeneration: UInt64 = 0 + var attentionWorkOwners: [UInt64: CBv2PagedAttentionStepOwner] = [:] + var attentionWorkCaches: [Int: CBv2PagedAttentionWeakCache] = [:] + var activeAttentionWork: CBv2PagedAttentionStepOwner? + var activeAttentionLayer: Int? + var usesStepOwnedAttention: Bool { + if case .stepOwned? = config.gatheredAttention?.admissionMode { return true } + return false + } + var attentionWorkBytesReserved: Int { + attentionWorkSnapshotLock.withLock { attentionWorkChargeSnapshot } + } + func publishAttentionWorkCharge() { + let bytes = attentionWorkOwners.values.reduce(0) { $0 + $1.reservedBytes } + attentionWorkSnapshotLock.withLock { attentionWorkChargeSnapshot = bytes } + } var storageTelemetry = PagedKVStorageTelemetry() let writeValidation = CBv2PagedKVWriteValidation() /// Deterministic failure-order observer; production leaves this unset. @@ -280,8 +312,14 @@ public final class PagedKVPool { self.config = config self.layerDTypes = resolvedTypes self.layerGroupKeys = groupKeys + self.gatheredAttentionScratchBound = + config.gatheredAttention?.admissionMode == .poolLifetime + && layerKinds.contains { $0.headDim != $0.valueHeadDim } + ? try config.gatheredAttention?.scratchUpperBound( + layerKinds: layerKinds, pageSize: config.pageSize) ?? 0 : 0 self.kernelSource = source - self.segmentGrant = config.segmentSizeBytes == nil ? nil : PagedKVGrant(bytes: config.capacityBytes) + self.segmentGrant = + config.segmentSizeBytes == nil ? nil : PagedKVGrant(bytes: config.capacityBytes) var demandTokens: [PagedKVGroupKey: Int] = [:] for (index, kind) in layerKinds.enumerated() where kind.sharesKVWithLayer == nil { @@ -295,9 +333,10 @@ public final class PagedKVPool { var demandBytes: [PagedKVGroupKey: Int] = [:] var totalDemand = 0 for (key, tokens) in demandTokens { - let bytesPerToken = try Self.checkedMultiply( - [2, key.kvHeads, key.headDim, key.dtype.size], - context: "bytes per token") + guard let bytesPerToken = key.geometry?.bytesPerToken(elementBytes: key.dtype.size) + else { + throw CBv2KVError.backendIneligible(reason: "paged K/V byte-rate overflow") + } let bytes = try Self.checkedMultiply( [tokens, bytesPerToken], context: "group byte demand") @@ -312,9 +351,12 @@ public final class PagedKVPool { self.groupDemandBytes = demandBytes self.totalDemandBytes = totalDemand for (key, bytes) in demandBytes { - let pageBytes = try Self.checkedMultiply( - [2, key.kvHeads, config.pageSize, key.headDim, key.dtype.size], - context: "page bytes") + guard + let pageBytes = key.geometry?.storageBytes( + tokens: config.pageSize, elementBytes: key.dtype.size) + else { + throw CBv2KVError.backendIneligible(reason: "paged K/V page-byte overflow") + } if let target = config.segmentSizeBytes { let layout = try PagedKVSegmentLayout( pageBytes: pageBytes, targetBytes: target, @@ -331,14 +373,19 @@ public final class PagedKVPool { let pageCount = groupBytes / pageBytes guard pageCount >= 2 else { throw CBv2KVError.capacityExhausted( - needed: try Self.checkedMultiply([2, pageBytes], context: "minimum group bytes"), + needed: try Self.checkedMultiply( + [2, pageBytes], context: "minimum group bytes"), available: groupBytes) } guard pageCount <= Int(Int32.max) else { - throw CBv2KVError.backendIneligible(reason: "paged group exceeds Int32 page-table limit") + throw CBv2KVError.backendIneligible( + reason: "paged group exceeds Int32 page-table limit") } let slabBytes = try Self.checkedMultiply( - [pageCount, key.kvHeads, config.pageSize, key.headDim, key.dtype.size], + [ + pageCount, key.kvHeads, config.pageSize, max(key.headDim, key.valueHeadDim), + key.dtype.size, + ], context: "slab bytes") guard slabBytes <= config.maxBufferLength else { throw CBv2KVError.backendIneligible( @@ -694,6 +741,9 @@ public final class PagedKVPool { /// Retire free native segments after reservation/row release. Fixed pools /// retain their reference behavior until segmented execution is promoted. func trimFreeSegments() { + // Issued native pools keep reusable segments AND their truthful floor + // until actual engine quiescence. No native wait/refund under commit. + if nativeModelBinding != nil { return } guard config.segmentSizeBytes != nil else { return } let previousBytes = bytesMaterialized for key in groupKeys { @@ -719,6 +769,11 @@ public final class PagedKVPool { } groups.removeAll() physicalLease?.close() + gatheredAttentionReservation?.release() + // Unknown work owners quarantine their roots and C on destruction; + // successfully completed owners have already closed their permits. + activeAttentionWork = nil + attentionWorkOwners.removeAll() } // MARK: - Page lifecycle @@ -817,11 +872,32 @@ public final class PagedKVPool { ) { guard !slots.isEmpty else { return } let g = group(key) - guard writeValidation.validate(keys: keys, values: values, expected: g.dtype) else { return } + guard writeValidation.validate(keys: keys, values: values, expected: g.dtype) else { + return + } + guard + writeValidation.validateShape( + keys: keys, values: values, group: key, + rank: 3, batch: nil, tokens: slots.count) + else { return } + if usesStepOwnedAttention { + guard activeAttentionWork != nil, activeAttentionLayer != nil, key.isAsymmetric else { + writeValidation.refuse("unplanned low-level paged write", expected: g.dtype) + return + } + PagedAsymmetricTransfers.writeSegmented( + group: g, slots: slots, keys: keys, values: values, + work: activeAttentionWork) + return + } if g.segmentLayout != nil { PagedSegmentTransfers.write(group: g, slots: slots, keys: keys, values: values) return } + if key.isAsymmetric { + PagedAsymmetricTransfers.writeFixed(group: g, slots: slots, keys: keys, values: values) + return + } precondition(keys.dim(1) == slots.count && values.dim(1) == slots.count) let k = keys let v = values @@ -887,15 +963,29 @@ public final class PagedKVPool { group key: PagedKVGroupKey, pages: [Int32], firstSlot: Int, count: Int ) -> (keys: MLXArray, values: MLXArray) { let g = group(key) + if usesStepOwnedAttention { + guard activeAttentionWork != nil, activeAttentionLayer != nil, key.isAsymmetric else { + writeValidation.refuse("unplanned low-level paged gather", expected: g.dtype) + return ( + MLXArray.zeros([1, key.kvHeads, 0, key.headDim], dtype: g.dtype), + MLXArray.zeros([1, key.kvHeads, 0, key.valueHeadDim], dtype: g.dtype) + ) + } + return PagedAsymmetricTransfers.gatherSegmented( + group: g, pages: pages, + firstSlot: firstSlot, count: count, work: activeAttentionWork) + } if g.segmentLayout != nil { - return PagedSegmentTransfers.gather(group: g, pages: pages, firstSlot: firstSlot, count: count) + return PagedSegmentTransfers.gather( + group: g, pages: pages, firstSlot: firstSlot, count: count) } let h = g.key.kvHeads let d = g.key.headDim + let vd = g.key.valueHeadDim let s = g.pageSize guard count > 0 else { let empty = MLXArray.zeros([1, h, 0, d], dtype: g.dtype) - return (empty, empty) + return (empty, d == vd ? empty : MLXArray.zeros([1, h, 0, vd], dtype: g.dtype)) } precondition(firstSlot < s) precondition(pages.count * s >= firstSlot + count, "gather range exceeds page list") @@ -904,15 +994,17 @@ public final class PagedKVPool { // barrier it induces) is what orders this gather after every prior // bulk write of the group. let idx = MLXArray(pages) + g.writeFence * 0 - func assemble(_ slab: MLXArray) -> MLXArray { + func assemble(_ slab: MLXArray, width: Int) -> MLXArray { // [np, H, S, D] -> [H, np, S, D] -> [H, np*S, D] -> slice -> [1, H, count, D] take(slab, idx, axis: 0) .transposed(1, 0, 2, 3) - .reshaped([h, pages.count * s, d])[0..., firstSlot ..< (firstSlot + count), 0...] + .reshaped([h, pages.count * s, width])[ + 0..., firstSlot ..< (firstSlot + count), 0... + ] .expandedDimensions(axis: 0) } - let keys = assemble(g.kSlab) - let values = assemble(g.vSlab) + let keys = assemble(g.kSlab, width: d) + let values = assemble(g.vSlab, width: vd) // The back-edge. ONE element of each is enough: MLX schedules whole // primitives, so a dependency on any slice of the gather forces the // gather itself. (`CBv2MTPCaptureFence` publishes the identical edge @@ -960,8 +1052,8 @@ public final class PagedKVPool { return max(0, segmentGrant.snapshot().bytes - bytesMaterialized) } return groups.values.reduce(0) { - $0 + ($1.kSlabMaterialized ? 0 : $1.slabBytes) - + ($1.vSlabMaterialized ? 0 : $1.slabBytes) + $0 + ($1.kSlabMaterialized ? 0 : $1.keySlabBytes) + + ($1.vSlabMaterialized ? 0 : $1.valueSlabBytes) } } @@ -1017,3 +1109,66 @@ public final class PagedKVPool { } } + +extension PagedKVPool { + /// Called only outside the native outcome commit, with no remaining row, + /// step, import, media or unrelated operation loan. Its lifetime loan still + /// retains the real engine/pool until actual backing and C are detached. + func retireIssuedNativePool() throws { + guard let binding = nativeModelBinding else { return } + if binding.poolRetired { return } + guard binding.canStartPoolRetirement, activeAttentionWork == nil, + attentionWorkOwners.isEmpty, + groups.values.allSatisfy({ + $0.pagesReserved == 0 && $0.pagesInUse == 0 + && $0.deferredFrees.isEmpty + }), + residentPrefixQuarantineIsAbsent + else { + throw CBv2NativeShutdownError.operationClosed + } + let operation = try binding.beginWork(nativeData: false) + retainNativePoolBacking(in: operation) + do { + try operation.requiredDrain() + guard + try operation.tracking.commitIfHealthyThrowing({ + try binding.markPoolRetired(after: operation) + }) + else { throw CBv2NativeShutdownError.operationClosed } + // Backing references remain on the genuine operation while these + // metadata maps and actual M coverage are detached OUTSIDE commit. + for group in groups.values { group.trimSegments { _ in } } + guard bytesMaterialized == 0 else { throw CBv2NativeShutdownError.operationClosed } + if binding.completePrefixIdentity != nil { + // No remaining request/work/import/export loan can retain a + // map generation here. Retire actual address/refcount/free-page + // maps before releasing their pool-owned host allowance. + groups.removeAll(keepingCapacity: false) + } + operation.finish { + physicalLease?.release(to: 0) + physicalLease?.close() + physicalLease = nil + binding.finishPoolLifetime() + } + } catch { + operation.fail() + throw error + } + } + + private var residentPrefixQuarantineIsAbsent: Bool { + // The constructor refuses a resident prefix index for this profile. + pageReuseObserver == nil + } + + private func retainNativePoolBacking(in operation: CBv2NativePagedOperation) { + for group in groups.values { + for segment in group.segments.values { + operation.retain(segment.storage) + operation.retain(owner: segment.backing) + } + } + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVSegments.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVSegments.swift index 3f056b5ba6..ebc497f571 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVSegments.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVSegments.swift @@ -13,10 +13,13 @@ struct PagedKVSegmentLayout: Sendable { private(set) var ranges: [Range] = [] private var segmentForPage: [Int32] = [] - init(pageBytes: Int, targetBytes: Int, maximumBufferBytes: Int, - maximumAddressPages: Int = Int(Int32.max)) throws { + init( + pageBytes: Int, targetBytes: Int, maximumBufferBytes: Int, + maximumAddressPages: Int = Int(Int32.max) + ) throws { guard pageBytes > 0, targetBytes > 0, maximumBufferBytes > 0, - maximumAddressPages >= 2, maximumAddressPages <= Int(Int32.max) else { + maximumAddressPages >= 2, maximumAddressPages <= Int(Int32.max) + else { throw CBv2KVError.backendIneligible(reason: "invalid paged segment geometry") } let physical = min(targetBytes, maximumBufferBytes) / pageBytes @@ -31,8 +34,9 @@ struct PagedKVSegmentLayout: Sendable { /// Eager geometry used by diagnostics. Runtime pools start empty instead. init(pageCount: Int, pageBytes: Int, targetBytes: Int, maximumBufferBytes: Int) throws { - try self.init(pageBytes: pageBytes, targetBytes: targetBytes, - maximumBufferBytes: maximumBufferBytes) + try self.init( + pageBytes: pageBytes, targetBytes: targetBytes, + maximumBufferBytes: maximumBufferBytes) guard pageCount >= 2 else { throw CBv2KVError.backendIneligible(reason: "invalid paged segment page count") } @@ -68,7 +72,8 @@ struct PagedKVSegmentLayout: Sendable { /// one poison page. Used by submit/deadline probes before any allocation. func physicalBytes(addingUsablePages usable: Int) -> Int? { guard usable >= 0 else { return nil } - let segments = usable / maximumUsablePages + let segments = + usable / maximumUsablePages + (usable % maximumUsablePages).nonzeroBitCount let (pages, pageOverflow) = usable.addingReportingOverflow(segments) let (bytes, byteOverflow) = pages.multipliedReportingOverflow(by: pageBytes) @@ -92,7 +97,8 @@ struct PagedKVSegmentLayout: Sendable { var remaining = usable % maximumUsablePages while remaining > 0 { let count = Self.sizeClass(atMost: remaining) - let (next, overflow) = total.addingReportingOverflow(try allocationBytes(usablePages: count)) + let (next, overflow) = total.addingReportingOverflow( + try allocationBytes(usablePages: count)) guard !overflow else { return nil } total = next remaining -= count @@ -234,19 +240,34 @@ final class PagedKVSegment { self.byteCount = source.byteCount } - init(index: Int, layout: PagedKVSegmentLayout, key: PagedKVGroupKey, - pageSize: Int, dtype: DType, evaluate: (MLXArray) throws -> Void, - admission: AdmissionV2? = nil) throws { + init( + index: Int, layout: PagedKVSegmentLayout, key: PagedKVGroupKey, + pageSize: Int, dtype: DType, evaluate: (MLXArray) throws -> Void, + admission: AdmissionV2? = nil + ) throws { self.index = index let pages = layout.range(index) + guard let geometry = key.geometry, dtype == key.dtype, + geometry.storageBytes(tokens: pageSize, elementBytes: dtype.size) == layout.pageBytes, + let logicalBytes = CBv2KVGeometry.multiply(pages.count, layout.pageBytes), + !key.isAsymmetric || logicalBytes / dtype.size <= Int(Int32.max), + let keyElements = CBv2KVGeometry.multiply(pages.count, key.kvHeads), + let keyRows = CBv2KVGeometry.multiply(keyElements, pageSize), + let keyCount = CBv2KVGeometry.multiply(keyRows, key.headDim) + else { + throw CBv2KVError.backendIneligible(reason: "invalid segmented native K/V byte layout") + } self.pages = pages - self.valueOffset = pages.count * key.kvHeads * pageSize * key.headDim - self.byteCount = pages.count * layout.pageBytes + self.valueOffset = keyCount + self.byteCount = logicalBytes let allocationStream = StreamOrDevice.default let storage = try withError { fault in let array = MLXArray.zeros( - [2, pages.count, key.kvHeads, pageSize, key.headDim], dtype: dtype, + key.isAsymmetric + ? [logicalBytes / dtype.size] + : [2, pages.count, key.kvHeads, pageSize, key.headDim], dtype: dtype, stream: allocationStream) + CBv2NativePagedOperation.constructing?.retain(array) do { try fault.check() try evaluate(array) @@ -263,6 +284,7 @@ final class PagedKVSegment { } self.backing = try PagedKVSegmentBacking( storage, allocationBound: layout.allocationBytes(forSegment: index)) + CBv2NativePagedOperation.constructing?.retain(owner: backing) if let admission { try backing.cover(using: admission, bytes: byteCount) } } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVSlabCommitment.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVSlabCommitment.swift index 443251bb6a..40d2853425 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVSlabCommitment.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVSlabCommitment.swift @@ -30,6 +30,10 @@ extension PagedKVBackend { /// Thread-affinity is the pool's: the engine queue. public func commitSlabs() throws { if pool.config.segmentSizeBytes != nil { + if nativeModelBinding != nil { + try pool.materializeReservedSegments() // preserve typed native completion failure + return + } do { try pool.materializeReservedSegments() } catch { diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVStorageLayout.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVStorageLayout.swift index 2007d19991..f096b4ac63 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVStorageLayout.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVStorageLayout.swift @@ -6,12 +6,17 @@ import MLX public struct PagedKVGroupKey: Hashable, Sendable, CustomStringConvertible { public let kvHeads: Int public let headDim: Int + public let valueHeadDim: Int public let dtype: DType public let windowSize: Int? - public init(kvHeads: Int, headDim: Int, dtype: DType = .float16, windowSize: Int? = nil) { + public init( + kvHeads: Int, headDim: Int, dtype: DType = .float16, windowSize: Int? = nil, + valueHeadDim: Int? = nil + ) { self.kvHeads = kvHeads self.headDim = headDim + self.valueHeadDim = valueHeadDim ?? headDim self.dtype = dtype self.windowSize = windowSize } @@ -23,12 +28,20 @@ public struct PagedKVGroupKey: Hashable, Sendable, CustomStringConvertible { } else { window = nil } - self.init(kvHeads: kind.kvHeads, headDim: kind.headDim, dtype: dtype, windowSize: window) + self.init( + kvHeads: kind.kvHeads, headDim: kind.headDim, dtype: dtype, windowSize: window, + valueHeadDim: kind.valueHeadDim) } - var sortKey: (Int, Int, String, Int) { (headDim, kvHeads, String(describing: dtype), windowSize ?? 0) } + var geometry: CBv2KVGeometry? { + .init(kvHeads: kvHeads, keyHeadDim: headDim, valueHeadDim: valueHeadDim) + } + var isAsymmetric: Bool { headDim != valueHeadDim } + var sortKey: (Int, Int, String, Int, Int) { + (headDim, kvHeads, String(describing: dtype), windowSize ?? 0, valueHeadDim) + } public var description: String { - "kv\(kvHeads)xd\(headDim)-\(dtype)-\(windowSize.map { "w\($0)" } ?? "full")" + "kv\(kvHeads)xd\(headDim)\(isAsymmetric ? "v\(valueHeadDim)" : "")-\(dtype)-\(windowSize.map { "w\($0)" } ?? "full")" } } @@ -38,18 +51,25 @@ enum PagedKVStorageLayout { guard types.count == layerKinds.count, types.allSatisfy({ [.float16, .bfloat16, .float32].contains($0) }) else { - throw CBv2KVError.backendIneligible(reason: "paged native dtype table is missing or unsupported") + throw CBv2KVError.backendIneligible( + reason: "paged native dtype table is missing or unsupported") } for (index, kind) in layerKinds.enumerated() { + guard kind.kvGeometry != nil else { + throw CBv2KVError.backendIneligible( + reason: "paged layer \(index) has invalid native K/V geometry") + } guard let source = kind.sharesKVWithLayer else { continue } guard source >= 0, source < layerKinds.count, source != index, layerKinds[source].sharesKVWithLayer == nil, layerKinds[source].kvHeads == kind.kvHeads, layerKinds[source].headDim == kind.headDim, + layerKinds[source].valueHeadDim == kind.valueHeadDim, layerKinds[source].attention == kind.attention, types[source] == types[index] else { - throw CBv2KVError.backendIneligible(reason: "paged borrowed layer \(index) has a different native layout") + throw CBv2KVError.backendIneligible( + reason: "paged borrowed layer \(index) has a different native layout") } } return types diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVWriteValidation.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVWriteValidation.swift index a258467dca..29e46e9d49 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVWriteValidation.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedKVWriteValidation.swift @@ -7,9 +7,25 @@ public struct CBv2PagedKVWriteError: Error, Sendable, CustomStringConvertible { public let expected: DType public let keys: DType public let values: DType + public let reason: String? + + public init( + layerIndex: Int?, expected: DType, keys: DType, values: DType, reason: String? = nil + ) { + self.layerIndex = layerIndex + self.expected = expected + self.keys = keys + self.values = values + self.reason = reason + } public var description: String { - "paged KV dtype mismatch at layer \(layerIndex.map(String.init) ?? "unknown"): expected \(expected), keys \(keys), values \(values)" + if let reason { + return + "paged KV contract mismatch at layer \(layerIndex.map(String.init) ?? "unknown"): \(reason)" + } + return + "paged KV dtype mismatch at layer \(layerIndex.map(String.init) ?? "unknown"): expected \(expected), keys \(keys), values \(values)" } } @@ -22,7 +38,8 @@ final class CBv2PagedKVWriteValidation { var isFaulted: Bool { fault != nil } @discardableResult - func validate(keys: MLXArray, values: MLXArray, expected: DType, layerIndex: Int? = nil) -> Bool { + func validate(keys: MLXArray, values: MLXArray, expected: DType, layerIndex: Int? = nil) -> Bool + { guard fault == nil else { return false } guard keys.dtype == expected, values.dtype == expected else { fault = CBv2PagedKVWriteError( @@ -33,6 +50,37 @@ final class CBv2PagedKVWriteValidation { } func record(_ error: CBv2PagedKVWriteError) { if fault == nil { fault = error } } + @discardableResult + func refuse(_ reason: String, expected: DType, layerIndex: Int? = nil) -> Bool { + record( + .init( + layerIndex: layerIndex, expected: expected, keys: expected, values: expected, + reason: reason)) + return false + } + + @discardableResult + func validateShape( + keys: MLXArray, values: MLXArray, group: PagedKVGroupKey, + rank: Int, batch: Int?, tokens: Int? = nil, layerIndex: Int? = nil + ) -> Bool { + guard fault == nil else { return false } + guard rank == 3 || rank == 4, keys.ndim == rank, values.ndim == rank else { + return refuse( + "invalid projected K/V rank", expected: group.dtype, layerIndex: layerIndex) + } + let count = tokens ?? keys.dim(rank - 2) + let prefix = + rank == 4 ? [batch ?? keys.dim(0), group.kvHeads, count] : [group.kvHeads, count] + guard count >= 0, keys.shape == prefix + [group.headDim], + values.shape == prefix + [group.valueHeadDim] + else { + return refuse( + "projected K/V shape differs from native role geometry", expected: group.dtype, + layerIndex: layerIndex) + } + return true + } func check() throws { if let fault { throw fault } } func clearAfterRetirement() { fault = nil } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedLayerCache.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedLayerCache.swift index 957b3f6aac..2604ac2e26 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedLayerCache.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedLayerCache.swift @@ -63,6 +63,11 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { /// `updateAndAttend` signature, so it is layer-cache configuration /// (from model config) instead. public let attentionSoftcap: Float? + /// Dispatch identity, not a performance or parity qualification claim. + public var nativeAttentionPath: String { + kind.headDim != kind.valueHeadDim + ? "paged_native_gathered" : "paged_native_fused_or_existing_fallback" + } private var pagedRows: [PagedSequenceKV] = [] @@ -107,8 +112,8 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { /// each column is bit-identical to that column run as a standalone /// `L == 1` decode. The engine sets it for the duration of an MTP /// verification round and clears it in a `defer`. - var mtpSerializesRectangularAttention = false - var mtpBatchesRectangularAttention = false + package var mtpSerializesRectangularAttention = false + package var mtpBatchesRectangularAttention = false private(set) var mtpBatchedAttentionCalls = 0 /// WS-1.2. The KV a KV-shared sibling needs in order to attend THIS @@ -141,6 +146,17 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { /// of them for both supported models, so neither pays a byte. private var retainsChunkForBorrowers = true + /// Engine-queue-only observation of the ACTUAL retained source state. + /// Scalars only: no array/view, evaluation, loan close or accounting change. + package var retainedSourceChunkWitnessForTesting: + (retainsForBorrowers: Bool, chunks: Int, workLoans: Int) + { + ( + retainsChunkForBorrowers, retainedPrefillKV.count, + retainedPrefillKV.reduce(0) { $0 + ($1.workLoan == nil ? 0 : 1) } + ) + } + /// WS-2.2 (`CBv2SpanMaskBinding`). The bidirectional image spans of the /// ONE vision prefill chunk currently being built, in ABSOLUTE token /// coordinates — the same coordinates this file's masks already live in, @@ -164,6 +180,14 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { self.kind = kind self.pool = pool self.attentionSoftcap = attentionSoftcap + if pool.usesStepOwnedAttention { + if pool.attentionWorkCaches[layerIndex]?.value != nil { + pool.attentionWorkEngineRefusal = + "step-owned paging requires one exact cache per layer" + } else { + pool.attentionWorkCaches[layerIndex] = .init(self) + } + } } // MARK: - Rows @@ -174,6 +198,21 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { /// join = append a row object, leave = drop it — no storage moves. /// (Contract `CBv2AttendingLayerCache.setRows` — the canonical binding.) public func setRows(_ rows: [CBv2SequenceKV]) { + if kind.headDim != kind.valueHeadDim { + let valid = rows.allSatisfy { row in + guard let row = row as? PagedSequenceKV else { return false } + return row.pool === pool && !row.isReleased + && row.groupKey == pool.groupKey(forLayer: layerIndex) + } + guard valid, Set(rows.map(ObjectIdentifier.init)).count == rows.count, + rows.count <= (pool.config.gatheredAttention?.maximumBatchSize ?? 0) + else { + pool.writeValidation.refuse( + "invalid/released/aliased asymmetric row binding or explicit batch limit", + expected: pool.layerDTypes[layerIndex], layerIndex: layerIndex) + return + } + } precondition( kind.sharesKVWithLayer == nil || rows.isEmpty, "KV-shared layers own no rows; attention borrows via attendBorrowing") @@ -190,7 +229,8 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { return paged } if nextRows.count != pagedRows.count - || !zip(nextRows, pagedRows).allSatisfy({ $0.serial == $1.serial }) { + || !zip(nextRows, pagedRows).allSatisfy({ $0.serial == $1.serial }) + { segmentDispatchCache.clear() } pagedRows = nextRows @@ -217,15 +257,99 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { // MARK: - Attention + private func faultOutput(_ queries: MLXArray) -> MLXArray { + // Preserve the legacy dtype-fault identity contract for uniform rows. + if kind.headDim == kind.valueHeadDim { return queries } + return MLXArray.zeros( + [ + queries.ndim == 4 ? queries.dim(0) : max(1, pagedRows.count), + kind.queryHeads, queries.ndim == 4 ? queries.dim(2) : 1, kind.valueHeadDim, + ], dtype: queries.dtype) + } + + /// Scalar/shape checks only; no eval, item, page allocation or cursor edit. + private func validateGatheredCall( + queries: MLXArray, rows: [PagedSequenceKV], + writing: Bool, sinks: MLXArray? + ) -> Bool { + guard kind.headDim != kind.valueHeadDim else { return true } + guard !pool.writeValidation.isFaulted else { return false } + guard let limits = pool.config.gatheredAttention, pool.gatheredAttentionIsPrepared, + pool.segmentGrant != nil, boundSpanContext == nil, + !mtpSerializesRectangularAttention, !mtpBatchesRectangularAttention, + attentionMetadata == nil, attentionPacket == nil + else { + return pool.writeValidation.refuse( + "asymmetric gathered attention owner is unprepared or optional MTP/span/packet path is unqualified", + expected: pool.layerDTypes[layerIndex], layerIndex: layerIndex) + } + guard queries.ndim == 4, queries.dim(0) == rows.count, !rows.isEmpty, + rows.count <= limits.maximumBatchSize, queries.dim(1) == kind.queryHeads, + queries.dim(2) > 0, queries.dim(2) <= limits.maximumQueryTokens, + queries.dim(3) == kind.headDim, + [.float16, .bfloat16, .float32].contains(queries.dtype), + queries.dtype == pool.layerDTypes[layerIndex], + Set(rows.map(\.serial)).count == rows.count, + rows.allSatisfy({ row in + guard row.pool === pool, !row.isReleased, + let end = CBv2KVGeometry.add(row.absoluteOffset, writing ? queries.dim(2) : 0) + else { return false } + return row.groupKey == pool.groupKey(forLayer: layerIndex) + && end <= row.maxLength && end <= limits.maximumContextTokens + && (!writing || row.windowSize == nil + || queries.dim(2) <= pool.config.maxPrefillChunk) + && (!writing || row.absoluteOffset >= row.frozenHighWater + || end <= row.frozenHighWater) + && (writing || queries.dim(2) <= row.absoluteOffset) + }), + !kind.hasSinks || sinks == nil + || (sinks!.shape == [kind.queryHeads] + && [.float16, .bfloat16, .float32].contains(sinks!.dtype) + && (queries.dtype == .float32 || sinks!.dtype == queries.dtype)) + else { + return pool.writeValidation.refuse( + "asymmetric query/row/sink geometry or explicit execution bound exceeded", + expected: pool.layerDTypes[layerIndex], layerIndex: layerIndex) + } + return true + } + + private func beginAttentionWork(queries: MLXArray, rows: [PagedSequenceKV]) -> Bool { + guard pool.usesStepOwnedAttention else { return true } + guard pool.activeAttentionLayer == nil, + pool.activeAttentionWork?.consume( + layer: layerIndex, rows: rows, + queries: queries.dim(2), softcap: attentionSoftcap != nil) == true + else { + return pool.writeValidation.refuse( + "missing/stale/repeated attention cache ticket", + expected: pool.layerDTypes[layerIndex], layerIndex: layerIndex) + } + pool.activeAttentionLayer = layerIndex + return true + } + + private func finishAttentionCall(_ output: MLXArray) -> MLXArray { + pool.activeAttentionWork?.retainRoots([output, cachedPositionOffsets]) + return output + } + /// Append already-projected trusted K/V without evaluating attention. /// This is used by embedded assistants when authoritative target history /// advances their private paged cache. It deliberately shares the same /// native write validation and page ownership as `updateAndAttend`. public func appendTrusted(keys: MLXArray, values: MLXArray) -> [MLXArray] { - guard pool.writeValidation.validate( - keys: keys, values: values, expected: pool.layerDTypes[layerIndex], - layerIndex: layerIndex) + guard + pool.writeValidation.validate( + keys: keys, values: values, expected: pool.layerDTypes[layerIndex], + layerIndex: layerIndex) else { return [keys, values] } + guard kind.headDim == kind.valueHeadDim else { + pool.writeValidation.refuse( + "asymmetric assistant trusted-append path is not qualified", + expected: pool.layerDTypes[layerIndex], layerIndex: layerIndex) + return [] + } precondition(kind.sharesKVWithLayer == nil && pagedRows.count == keys.dim(0)) precondition(keys.ndim == 4 && values.shape == keys.shape) var roots: [MLXArray] = [] @@ -251,10 +375,25 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { queries: MLXArray, keys: MLXArray, values: MLXArray, scale: Float, sinks: MLXArray? ) -> MLXArray { - guard pool.writeValidation.validate( - keys: keys, values: values, expected: pool.layerDTypes[layerIndex], layerIndex: layerIndex) - else { return queries } + guard + pool.writeValidation.validate( + keys: keys, values: values, expected: pool.layerDTypes[layerIndex], + layerIndex: layerIndex) + else { return faultOutput(queries) } + guard + pool.writeValidation.validateShape( + keys: keys, values: values, + group: pool.groupKey(forLayer: layerIndex), rank: 4, batch: pagedRows.count, + tokens: queries.ndim == 4 ? queries.dim(2) : nil, layerIndex: layerIndex), + validateGatheredCall(queries: queries, rows: pagedRows, writing: true, sinks: sinks) + else { + return faultOutput(queries) + } precondition(kind.sharesKVWithLayer == nil, "shared layers must call attendBorrowing") + guard beginAttentionWork(queries: queries, rows: pagedRows) else { + return faultOutput(queries) + } + defer { if pool.usesStepOwnedAttention { pool.activeAttentionLayer = nil } } let b = queries.dim(0) let l = queries.dim(2) precondition(b == pagedRows.count, "queries batch \(b) != rows \(pagedRows.count)") @@ -271,7 +410,7 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { let output: MLXArray if l == 1 { retainedPrefillKV = [] - if usesQwen4ExactPagedDecode { + if usesGatheredNativeDecode { output = decodeExactSDPA( queries: queries, keys: keys, values: values, rows: pagedRows, scale: scale, sinks: effectiveSinks) @@ -285,7 +424,8 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { newKeys: keys.squeezed(axis: 2), newValues: values.squeezed(axis: 2), writeTargets: targets, - rows: pagedRows, scale: scale, sinks: effectiveSinks, metadata: metadata, packet: packet) + rows: pagedRows, scale: scale, sinks: effectiveSinks, metadata: metadata, + packet: packet) } } else if mtpSerializesRectangularAttention { // MTP rectangular verification: the round batches the @@ -344,9 +484,10 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { let chunkSinks = prefillSinks(effectiveSinks, queryDType: queries.dtype) output = CBv2AttentionV1.packedPerRow(batch: b) { index, slice in let row = pagedRows[index] - let kv = prefillKVWritingChunk( + let rawKV = prefillKVWritingChunk( row: row, chunkKeys: slice(keys), chunkValues: slice(values), dtype: queries.dtype) + let kv = prepareRetainedWork(rawKV, row: row) views.append(kv) return prefillAttend( queries: slice(queries), kv: kv, scale: scale, sinks: chunkSinks) @@ -359,7 +500,7 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { // advanced their absolute counters by exactly L, so the cached // device array tracks them without a per-step host rebuild. cachedPositionOffsets = cachedPositionOffsets + Int32(l) - return output + return finishAttentionCall(output) } /// Write K/V without leftover dense SDPA so gathered QSA can attend the @@ -367,10 +508,17 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { public func updateKVAndAdvanceOffsets( keys: MLXArray, values: MLXArray ) -> [(keys: MLXArray, values: MLXArray)] { + guard kind.headDim == kind.valueHeadDim else { + pool.writeValidation.refuse( + "asymmetric Qwen selected/last-query specialization is unqualified", + expected: pool.layerDTypes[layerIndex], layerIndex: layerIndex) + return [] + } precondition( kind.sharesKVWithLayer == nil, "PagedLayerCache: KV-shared layer \(layerIndex) owns no storage") - precondition(pagedRows.count == keys.dim(0), "PagedLayerCache: K/V batch does not match rows") + precondition( + pagedRows.count == keys.dim(0), "PagedLayerCache: K/V batch does not match rows") var views: [(keys: MLXArray, values: MLXArray)] = [] views.reserveCapacity(pagedRows.count) let length = keys.dim(2) @@ -397,11 +545,12 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { public func qwen4CanGatherSelectedKV(keys: MLXArray, values: MLXArray) -> Bool { guard !pool.writeValidation.isFaulted, pagedRows.count == 1, kind.sharesKVWithLayer == nil, - !retainsChunkForBorrowers, boundSpanContext == nil, - // Five chained drafts plus the target seed use six columns. - keys.ndim == 4, keys.dim(0) == 1, (1...6).contains(keys.dim(2)), - keys.shape == values.shape, keys.dtype == values.dtype, - pagedRows[0].supportsQwen4SelectedGather else { return false } + !retainsChunkForBorrowers, boundSpanContext == nil, + // Five chained drafts plus the target seed use six columns. + keys.ndim == 4, keys.dim(0) == 1, (1 ... 6).contains(keys.dim(2)), + keys.shape == values.shape, keys.dtype == values.dtype, + pagedRows[0].supportsQwen4SelectedGather + else { return false } let group = pool.group(pagedRows[0].groupKey) return keys.dtype == group.dtype && keys.dim(1) == group.key.kvHeads && keys.dim(3) == group.key.headDim @@ -421,11 +570,32 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { source: CBv2AttendingLayerCache, queries: MLXArray, scale: Float, sinks: MLXArray? ) -> MLXArray { - guard !pool.writeValidation.isFaulted else { return queries } + guard !pool.writeValidation.isFaulted else { return faultOutput(queries) } + if kind.headDim != kind.valueHeadDim { + // A shared storage group proves geometry, not model-layer ownership. + // Refuse the wrong producer before gathering or borrowing chunk views. + guard let owner = kind.sharesKVWithLayer, + let source = source as? PagedLayerCache, source.pool === pool, + source.layerIndex == owner, source.kind.sharesKVWithLayer == nil, + source.kind.headDim == kind.headDim, source.kind.valueHeadDim == kind.valueHeadDim, + source.kind.kvHeads == kind.kvHeads, source.kind.attention == kind.attention, + validateGatheredCall( + queries: queries, rows: source.pagedRows, writing: false, sinks: sinks) + else { + pool.writeValidation.refuse( + "invalid asymmetric borrower/source binding", + expected: pool.layerDTypes[layerIndex], layerIndex: layerIndex) + return faultOutput(queries) + } + } precondition(kind.sharesKVWithLayer != nil, "attendBorrowing requires a KV-shared layer") guard let src = source as? PagedLayerCache else { fatalError("[PagedLayerCache] can only borrow from another PagedLayerCache") } + guard beginAttentionWork(queries: queries, rows: src.pagedRows) else { + return faultOutput(queries) + } + defer { if pool.usesStepOwnedAttention { pool.activeAttentionLayer = nil } } precondition( kind.attention == src.kind.attention, "KV-shared layer must share the source layer's attention type") @@ -433,10 +603,11 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { // Same sink gate as updateAndAttend, keyed on THIS layer's kind. let effectiveSinks = kind.hasSinks ? sinks : nil if l == 1 { - if usesQwen4ExactPagedDecode { - return decodeExactSDPA( - queries: queries, keys: nil, values: nil, - rows: src.pagedRows, scale: scale, sinks: effectiveSinks) + if usesGatheredNativeDecode { + return finishAttentionCall( + decodeExactSDPA( + queries: queries, keys: nil, values: nil, + rows: src.pagedRows, scale: scale, sinks: effectiveSinks)) } return dispatchDecode( queries: queries, rows: src.pagedRows, scale: scale, sinks: effectiveSinks, @@ -466,6 +637,12 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { // retained views means the bank wired the KV-sharing graph // wrong. guard src.retainedPrefillKV.count == b else { + if pool.usesStepOwnedAttention { + pool.writeValidation.refuse( + "sealed borrower has no producer chunk loan", + expected: pool.layerDTypes[layerIndex], layerIndex: layerIndex) + return faultOutput(queries) + } fatalError( "[PagedLayerCache] layer \(layerIndex) borrows from layer " + "\(src.layerIndex), which retained \(src.retainedPrefillKV.count) " @@ -474,14 +651,28 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { } // Same shared batch-axis decomposition as the owning path. let chunkSinks = prefillSinks(effectiveSinks, queryDType: queries.dtype) - return CBv2AttentionV1.packedPerRow(batch: b) { index, slice in + let output = CBv2AttentionV1.packedPerRow(batch: b) { index, slice in let kv = src.retainedPrefillKV[index] + if pool.usesStepOwnedAttention { + let row = src.pagedRows[index] + guard let work = pool.activeAttentionWork, let loan = kv.workLoan, + loan.generation == work.generation, loan.layer == src.layerIndex, + loan.serial == row.serial, + loan.range == (kv.queryStart ..< (kv.queryStart + l)) + else { + pool.writeValidation.refuse( + "borrowed prefill loan does not match the sealed producer generation/range", + expected: pool.layerDTypes[layerIndex], layerIndex: layerIndex) + return faultOutput(slice(queries)) + } + } precondition( kv.queryCount == l, "borrowed chunk is \(kv.queryCount) tokens, queries are \(l)") return prefillAttend( queries: slice(queries), kv: kv, scale: scale, sinks: chunkSinks) } + return finishAttentionCall(output) } } @@ -490,10 +681,11 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { /// Flash-Next QSA: page write + gather + contiguous SDPA. The segmented /// Metal decode kernel is still native paging, but it is not 1K-exact /// on this artifact. Default stays on the exact path. - private var usesQwen4ExactPagedDecode: Bool { - kind.qwen4IndexerCompressRatio != nil - && attentionSoftcap == nil - && !kind.isBidirectional + private var usesGatheredNativeDecode: Bool { + kind.headDim != kind.valueHeadDim + || (kind.qwen4IndexerCompressRatio != nil + && attentionSoftcap == nil + && !kind.isBidirectional) } /// Write (when this layer owns KV), gather the visible page range, and @@ -506,7 +698,7 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { precondition((keys == nil) == (values == nil)) let b = queries.dim(0) precondition(b == rows.count, "exact paged decode batch \(b) != rows \(rows.count)") - let querySinks = CBv2AttentionV1.sdpaSinks(sinks, queryDType: queries.dtype) + let querySinks = prefillSinks(sinks, queryDType: queries.dtype) var outputs: [MLXArray] = [] outputs.reserveCapacity(b) for index in 0 ..< b { @@ -521,12 +713,21 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { let (gatheredKeys, gatheredValues) = row.gatherRange( start: range.start, count: range.length) let query = queries[index ..< index + 1] - outputs.append( - MLXFast.scaledDotProductAttention( - queries: query, - keys: cast(gatheredKeys, to: query.dtype), - values: cast(gatheredValues, to: query.dtype), - scale: scale, mask: .none, sinks: querySinks)) + if let softcap = attentionSoftcap { + outputs.append( + PagedAttentionReference.composedAttention( + queries: query, + keys: cast(gatheredKeys, to: query.dtype), + values: cast(gatheredValues, to: query.dtype), + scale: scale, sinks: querySinks, softcap: softcap)) + } else { + outputs.append( + MLXFast.scaledDotProductAttention( + queries: query, + keys: cast(gatheredKeys, to: query.dtype), + values: cast(gatheredValues, to: query.dtype), + scale: scale, mask: .none, sinks: querySinks)) + } } return outputs.count == 1 ? outputs[0] : concatenated(outputs, axis: 0) } @@ -608,6 +809,12 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { precondition((newKeys == nil) == (writeTargets == nil)) let provider = tableProvider ?? self let group = pool.group(rows[0].groupKey) + guard !group.key.isAsymmetric else { + pool.writeValidation.refuse( + "asymmetric direct fused dispatch is unqualified", expected: group.dtype, + layerIndex: layerIndex) + return faultOutput(queries) + } if group.segmentLayout != nil { let descriptors = rows.enumerated().map { index, row in PagedSegmentDispatchPlan.Row( @@ -623,7 +830,8 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { group: group, rows: descriptors, sinks: preparedSinks(sinks), params: params(scale: scale), softcap: attentionSoftcap != nil, source: pool.kernelSource, - dispatchCache: segmentDispatchCache).expandedDimensions(axis: 2) + dispatchCache: segmentDispatchCache + ).expandedDimensions(axis: 2) let output = result.dtype == queries.dtype ? result : result.asType(queries.dtype) metadata?.finishPaged( group: group, kernelOutputDType: result.dtype, output: output, @@ -729,7 +937,7 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { "rectangular verification needs one row per query batch entry") let l = queries.dim(2) var outputs: [MLXArray] = [] - if usesQwen4ExactPagedDecode { + if usesGatheredNativeDecode { if let fused = decodeExactRectangularSDPA( queries: queries, keys: keys, values: values, rows: rows, scale: scale, sinks: sinks) @@ -757,12 +965,15 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { return outputs.count == 1 ? outputs[0] : concatenated(outputs, axis: 2) } if mtpBatchesRectangularAttention, PagedMTPBatchedColumns.enabled, rows.count == 1, - let keys, let values { + let keys, let values + { let group = pool.group(rows[0].groupKey) if PagedMTPBatchedColumns.eligible(queries: queries, row: rows[0], group: group) { mtpBatchedAttentionCalls += 1 - return PagedMTPBatchedColumns.attend(queries: queries, keys: keys, values: values, - row: rows[0], group: group, sinks: preparedSinks(sinks), params: params(scale: scale), + return PagedMTPBatchedColumns.attend( + queries: queries, keys: keys, values: values, + row: rows[0], group: group, sinks: preparedSinks(sinks), + params: params(scale: scale), softcap: attentionSoftcap != nil, source: pool.kernelSource, dispatchCache: segmentDispatchCache) } @@ -898,6 +1109,7 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { /// Absolute position of the chunk's first query, which is also the /// first key column contributed by the chunk itself. let queryStart: Int + var workLoan: CBv2PagedAttentionLoan? = nil /// Keys that predate the chunk — the index of the first query /// within `keys`, and the offset every block bound is shifted by. @@ -905,6 +1117,29 @@ public final class PagedLayerCache: CBv2AttendingLayerCache { var queryCount: Int { keys.dim(2) - historyCount } } + private func prepareRetainedWork(_ value: PrefillKV, row: PagedSequenceKV) -> PrefillKV { + guard let owner = pool.activeAttentionWork else { return value } + // An H=0 direct projection may be a tiny view of a much larger parent. + // Detach its raw bits so a cache loan never retains that unknown parent + // beyond this producer step. History concat/gather already owns a fresh + // exact role-shaped destination. No dtype or attention math changes. + func compact(_ input: MLXArray) -> MLXArray { + let dtype: DType = input.dtype.size == 2 ? .uint16 : .uint32 + let bits = input.view(dtype: dtype) + return MLX.where(MLXArray(true), bits, bits).view(dtype: input.dtype) + } + let direct = value.historyCount == 0 && row.frozenHighWater <= value.queryStart + let keys = direct ? compact(value.keys) : value.keys + let values = direct ? compact(value.values) : value.values + owner.retainCompactRoots([keys, values]) + var result = PrefillKV( + keys: keys, values: values, start: value.start, queryStart: value.queryStart) + result.workLoan = owner.makeLoan( + keys: keys, values: values, layer: layerIndex, + serial: row.serial, range: value.queryStart ..< (value.queryStart + value.queryCount)) + return result + } + /// Write this chunk into `row` and return exactly the KV it attends. /// /// The write lives in here rather than at the call site because the two @@ -1202,7 +1437,9 @@ extension PagedLayerCache: KVCache { guard kind.sharesKVWithLayer == nil, !pagedRows.isEmpty else { return [cachedPositionOffsets] } - var arrays = [cachedPositionOffsets, pool.group(pool.groupKey(forLayer: layerIndex)).writeFence] + var arrays = [ + cachedPositionOffsets, pool.group(pool.groupKey(forLayer: layerIndex)).writeFence, + ] if pagedRows.count > 1 { arrays.append(contentsOf: pagedRows.flatMap(CBv2Qwen4IndexerFrontier.evaluationState)) } @@ -1259,7 +1496,8 @@ extension PagedLayerCache: CBv2Qwen4GatheredCache { public var qwen4HasWriteFault: Bool { pool.writeValidation.isFaulted } public func qwen4ValidateProjectedKV(keys: MLXArray, values: MLXArray) -> Bool { pool.writeValidation.validate( - keys: keys, values: values, expected: pool.layerDTypes[layerIndex], layerIndex: layerIndex) + keys: keys, values: values, expected: pool.layerDTypes[layerIndex], + layerIndex: layerIndex) } public var qwen4SerializesRectangularAttention: Bool { mtpSerializesRectangularAttention } } @@ -1281,7 +1519,8 @@ extension PagedLayerCache: CBv2Qwen4BatchScopeProviding { return view } return CBv2Qwen4BatchScope(rows: owners, caches: views) { [self] length in - precondition(pagedRows.count == owners.count && zip(pagedRows, owners).allSatisfy { $0 === $1 }) + precondition( + pagedRows.count == owners.count && zip(pagedRows, owners).allSatisfy { $0 === $1 }) cachedPositionOffsets = cachedPositionOffsets + Int32(length) retainedPrefillKV = retainsChunkForBorrowers ? views.flatMap(\.retainedPrefillKV) : [] clearQwen4IndexerState() @@ -1367,6 +1606,6 @@ extension PagedLayerCache: CBv2MultimodalSpanCapableCache { } public var honorsSpanMaskContexts: Bool { - Self.honorsSpanMaskContextsByConstruction + !pool.usesStepOwnedAttention && Self.honorsSpanMaskContextsByConstruction } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSeamContract.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSeamContract.swift index 5664bdbe55..8492c92c5a 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSeamContract.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSeamContract.swift @@ -264,7 +264,7 @@ public enum CBv2PagedRingGeometry { /// /// Callers MUST degrade to serial verification for a cache that does not /// conform, and MUST NOT trap. -protocol CBv2MTPRectangularSerializing: AnyObject { +package protocol CBv2MTPRectangularSerializing: AnyObject { /// While `true`, attention is computed one query position at a time. /// Set for the duration of a rectangular verification round and cleared /// in a `defer`. @@ -429,14 +429,15 @@ public struct CBv2PagedWindowSnapshot { /// probe is a concrete cast on the CONTIGUOUS row. Nothing on the paged /// side conforms to anything here — a donated window reaches this type /// as three loose arrays through `makeSequenceState(adopting:)`. - public init?(keys: MLXArray, values: MLXArray, base: Int) { + public init?(keys: MLXArray, values: MLXArray, base: Int, valueHeadDim: Int? = nil) { guard base >= 0, keys.ndim == 4, values.ndim == 4, keys.dim(0) == 1, values.dim(0) == 1, keys.dim(1) == values.dim(1), keys.dim(2) == values.dim(2), - keys.dim(3) == values.dim(3), - keys.dim(2) > 0 + keys.dim(3) > 0, values.dim(3) == (valueHeadDim ?? keys.dim(3)), + values.dim(3) > 0, + keys.dim(2) > 0, base <= Int.max - keys.dim(2) else { return nil } self.keys = keys self.values = values diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSegmentTransfers.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSegmentTransfers.swift index fee377291a..f4c44a465d 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSegmentTransfers.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSegmentTransfers.swift @@ -68,13 +68,13 @@ enum PagedSegmentTransfers { } } - private static func records(_ triples: [Int32]) -> MLXArray { + static func records(_ triples: [Int32]) -> MLXArray { precondition(triples.count % 3 == 0) return MLXArray(triples + Array(repeating: 0, count: max(0, 24 - triples.count))) } /// Each record is (input/output token index, local page, slot). - private static func buckets(group: PagedKVGroup, slots: [Int32]) -> [(PagedKVSegment, [Int32])] { + static func buckets(group: PagedKVGroup, slots: [Int32]) -> [(PagedKVSegment, [Int32])] { let layout = group.segmentLayout! var records: [Int: [Int32]] = [:] for (token, position) in slots.enumerated() { @@ -83,7 +83,8 @@ enum PagedSegmentTransfers { precondition(group.isAllocatable(page)) let index = layout.segmentIndex(page: page) records[index, default: []].append(contentsOf: [ - Int32(token), Int32(layout.localPage(page)), position % Int32(group.pageSize)]) + Int32(token), Int32(layout.localPage(page)), position % Int32(group.pageSize), + ]) } return records.keys.sorted().map { index in guard let segment = group.segments[index] else { @@ -94,26 +95,44 @@ enum PagedSegmentTransfers { } static func write(group: PagedKVGroup, slots: [Int32], keys: MLXArray, values: MLXArray) { - guard group.writeValidation.validate(keys: keys, values: values, expected: group.dtype) else { return } + guard group.writeValidation.validate(keys: keys, values: values, expected: group.dtype) + else { return } + guard + group.writeValidation.validateShape( + keys: keys, values: values, group: group.key, + rank: 3, batch: nil, tokens: slots.count) + else { return } + if group.key.isAsymmetric { + PagedAsymmetricTransfers.writeSegmented( + group: group, slots: slots, keys: keys, values: values) + return + } precondition(keys.shape == [group.key.kvHeads, slots.count, group.key.headDim]) precondition(values.shape == keys.shape) let k = keys let v = values for (segment, triples) in buckets(group: group, slots: slots) { - group.writeFence = kernel(reading: false, dtype: group.dtype)( - [k, v, segment.storage, records(triples), group.writeFence], - template: [("T", group.dtype), ("H", group.key.kvHeads), - ("D", group.key.headDim), ("S", group.pageSize), - ("VBASE", segment.valueOffset)], - grid: (group.key.headDim, group.key.kvHeads, triples.count / 3), - threadGroup: (min(256, group.key.headDim), 1, 1), - outputShapes: [[1]], outputDTypes: [.int32])[0] + group.writeFence = + kernel(reading: false, dtype: group.dtype)( + [k, v, segment.storage, records(triples), group.writeFence], + template: [ + ("T", group.dtype), ("H", group.key.kvHeads), + ("D", group.key.headDim), ("S", group.pageSize), + ("VBASE", segment.valueOffset), + ], + grid: (group.key.headDim, group.key.kvHeads, triples.count / 3), + threadGroup: (min(256, group.key.headDim), 1, 1), + outputShapes: [[1]], outputDTypes: [.int32])[0] } } static func gather(group: PagedKVGroup, pages: [Int32], firstSlot: Int, count: Int) -> (keys: MLXArray, values: MLXArray) { + if group.key.isAsymmetric { + return PagedAsymmetricTransfers.gatherSegmented( + group: group, pages: pages, firstSlot: firstSlot, count: count) + } let ordered = gatherCombined(group: group, pages: pages, firstSlot: firstSlot, count: count) return (ordered[0], ordered[1]) } @@ -123,9 +142,14 @@ enum PagedSegmentTransfers { /// before calling and keeps its charge until the captured owner retires. /// `publishReadFence: false` requires the owning engine step to block all /// successor writes until the private read has completed or drained. - static func gatherCombined(group: PagedKVGroup, pages: [Int32], firstSlot: Int, count: Int, - publishReadFence: Bool = true, stream: StreamOrDevice = .default) -> MLXArray { - let h = group.key.kvHeads, d = group.key.headDim + static func gatherCombined( + group: PagedKVGroup, pages: [Int32], firstSlot: Int, count: Int, + publishReadFence: Bool = true, stream: StreamOrDevice = .default + ) -> MLXArray { + precondition( + !group.key.isAsymmetric, "legacy combined gather cannot represent asymmetric roles") + let h = group.key.kvHeads + let d = group.key.headDim guard count > 0 else { return MLXArray.zeros([2, 1, h, 0, d], dtype: group.dtype, stream: stream) } @@ -139,16 +163,20 @@ enum PagedSegmentTransfers { let output = MLXArray.zeros([2, 1, h, count, d], dtype: group.dtype, stream: stream) var fence = group.writeFence for (segment, triples) in buckets(group: group, slots: slots) { - fence = kernel(reading: true, dtype: group.dtype)( - [segment.storage, records(triples), output, fence], - template: [("T", group.dtype), ("H", h), ("D", d), - ("S", group.pageSize), ("VBASE", segment.valueOffset)], - grid: (d, h, triples.count / 3), threadGroup: (min(256, d), 1, 1), - outputShapes: [[1]], outputDTypes: [.int32], stream: stream)[0] + fence = + kernel(reading: true, dtype: group.dtype)( + [segment.storage, records(triples), output, fence], + template: [ + ("T", group.dtype), ("H", h), ("D", d), + ("S", group.pageSize), ("VBASE", segment.valueOffset), + ], + grid: (d, h, triples.count / 3), threadGroup: (min(256, d), 1, 1), + outputShapes: [[1]], outputDTypes: [.int32], stream: stream)[0] } - fence = completionKernel( - [fence], grid: (1, 1, 1), threadGroup: (1, 1, 1), - outputShapes: [[1]], outputDTypes: [.int32], stream: stream)[0] + fence = + completionKernel( + [fence], grid: (1, 1, 1), threadGroup: (1, 1, 1), + outputShapes: [[1]], outputDTypes: [.int32], stream: stream)[0] // Keep the final destination; no second whole-gather allocation. if publishReadFence { group.writeFence = fence } // MLX Depends inherits its input primitive stream (ops.cpp); host diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSequenceKV.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSequenceKV.swift index a8fea71f36..7f4303b23a 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSequenceKV.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSequenceKV.swift @@ -93,6 +93,7 @@ public final class PagedSequenceKV: CBv2SequenceKV, CBv2PagedSpeculativeRow, CBv private(set) var speculativeBase: Int? private var released = false + var isReleased: Bool { released } init( pool: PagedKVPool, kind: CBv2LayerKind, groupKey: PagedKVGroupKey, @@ -192,8 +193,23 @@ public final class PagedSequenceKV: CBv2SequenceKV, CBv2PagedSpeculativeRow, CBv /// substitutable for the contiguous row, and the heavy row-level test /// coverage of ring behaviour runs through here. public func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + if pool.refuseUnplannedAttentionMutation( + "direct row update outside the cache ticket", dtype: groupKey.dtype) + { + return (keys, values) + } + guard !released else { + pool.writeValidation.refuse( + "write through a released paged row", expected: groupKey.dtype) + return (keys, values) + } guard pool.writeValidation.validate(keys: keys, values: values, expected: groupKey.dtype) else { return (keys, values) } + guard + pool.writeValidation.validateShape( + keys: keys, values: values, group: groupKey, + rank: keys.ndim, batch: 1) + else { return (keys, values) } var k = keys var v = values if k.ndim == 4 { @@ -279,10 +295,26 @@ public final class PagedSequenceKV: CBv2SequenceKV, CBv2PagedSpeculativeRow, CBv /// bound coupled: raise the span past what the ring reserves and rows go /// INELIGIBLE, instead of silently corrupting confirmed history. public var supportsSpeculativeWrites: Bool { - speculativeHeadroom >= CBv2PagedSpeculation.maxSpeculativeSpan + (!pool.usesStepOwnedAttention || pool.nativeModelBinding?.supportsSerialMTP == true) + && speculativeHeadroom >= CBv2PagedSpeculation.maxSpeculativeSpan } + private weak var nativeSpeculationOwner: CBv2NativePagedMTPWork? + public func beginSpeculativeWrite() { + if pool.usesStepOwnedAttention { + guard pool.nativeModelBinding?.supportsSerialMTP == true else { + _ = pool.refuseUnplannedAttentionMutation( + "speculative row transactions", dtype: groupKey.dtype) + return + } + guard let owner = CBv2NativePagedMTPWork.current, owner.authorizeBegin(self) else { + _ = pool.refuseUnplannedAttentionMutation( + "unowned speculative row transaction", dtype: groupKey.dtype) + return + } + nativeSpeculationOwner = owner + } precondition( speculativeBase == nil, "[PagedSequenceKV] beginSpeculativeWrite while already armed") @@ -291,7 +323,14 @@ public final class PagedSequenceKV: CBv2SequenceKV, CBv2PagedSpeculativeRow, CBv public func commitSpeculativeWrite() { guard speculativeBase != nil else { return } + if pool.usesStepOwnedAttention, nativeSpeculationOwner?.permitsFinalization(self) != true { + nativeSpeculationOwner?.fail() + _ = pool.refuseUnplannedAttentionMutation( + "uncompleted speculative commit", dtype: groupKey.dtype) + return + } speculativeBase = nil + nativeSpeculationOwner = nil // Pages `rollback` took out of the table were only QUEUED: the // round's gathers are lazy and still name those physical pages, so // handing them back before the round closes lets another row @@ -347,6 +386,14 @@ public final class PagedSequenceKV: CBv2SequenceKV, CBv2PagedSpeculativeRow, CBv } public func rollback(_ n: Int) { + if pool.usesStepOwnedAttention, speculativeBase != nil, + nativeSpeculationOwner?.permitsFinalization(self) != true + { + nativeSpeculationOwner?.fail() + _ = pool.refuseUnplannedAttentionMutation( + "uncompleted speculative rollback", dtype: groupKey.dtype) + return + } precondition(n >= 0 && n <= absoluteOffset - baseOffset, "rollback past written tokens") precondition( absoluteOffset - n >= frozenHighWater, @@ -413,8 +460,19 @@ public final class PagedSequenceKV: CBv2SequenceKV, CBv2PagedSpeculativeRow, CBv func write(keys: MLXArray, values: MLXArray) { guard pool.writeValidation.validate(keys: keys, values: values, expected: groupKey.dtype) else { return } + guard !released else { + pool.writeValidation.refuse( + "write through a released paged row", expected: groupKey.dtype) + return + } + guard + pool.writeValidation.validateShape( + keys: keys, values: values, + group: groupKey, rank: 3, batch: nil) + else { return } let n = keys.dim(1) guard n > 0 else { return } + guard pool.authorizeAttentionWrite(row: self, count: n) else { return } if absoluteOffset + n <= frozenHighWater { // Frozen replay (`adoptFrozen`): storage below M is the adopted // prefix and must stay byte-exact, so the cursor advances and @@ -458,6 +516,11 @@ public final class PagedSequenceKV: CBv2SequenceKV, CBv2PagedSpeculativeRow, CBv /// the tile in place (fused write, see PagedAttentionKernel.decode). /// Host Int math only; never a device sync. func prepareDecodeWrite() -> (page: Int32, slot: Int) { + if pool.refuseUnplannedAttentionMutation( + "cursor-only fused decode writes", dtype: groupKey.dtype) + { + return (0, 0) + } precondition( absoluteOffset + 1 <= maxLength, "write past maxLength (\(absoluteOffset) + 1 > \(maxLength))") @@ -512,7 +575,8 @@ public final class PagedSequenceKV: CBv2SequenceKV, CBv2PagedSpeculativeRow, CBv } var supportsQwen4SelectedGather: Bool { - !released && windowSize == nil && baseOffset == 0 && frozenHighWater == 0 + !groupKey.isAsymmetric && !released && windowSize == nil && baseOffset == 0 + && frozenHighWater == 0 } func gatherSelected(_ indices: MLXArray) -> (keys: MLXArray, values: MLXArray) { @@ -586,6 +650,13 @@ public final class PagedSequenceKV: CBv2SequenceKV, CBv2PagedSpeculativeRow, CBv /// are byte-exact. `CBv2PagedGatherRangeGuardTests` pins both halves, /// including the 66-page / 1,026-token case at gemma-4 geometry. func gatherRange(start: Int, count: Int) -> (keys: MLXArray, values: MLXArray) { + guard pool.authorizeAttentionRead(row: self, start: start, count: count) else { + return ( + MLXArray.zeros([1, groupKey.kvHeads, 0, groupKey.headDim], dtype: groupKey.dtype), + MLXArray.zeros( + [1, groupKey.kvHeads, 0, groupKey.valueHeadDim], dtype: groupKey.dtype) + ) + } guard count > 0 else { return pool.gather(group: groupKey, pages: [], firstSlot: 0, count: 0) } @@ -667,6 +738,11 @@ public final class PagedSequenceKV: CBv2SequenceKV, CBv2PagedSpeculativeRow, CBv /// recomputes the trailing window tokens for windowed layers, and those /// recomputed tokens must land at their true absolute positions. public func fastForward(to offset: Int) { + if pool.refuseUnplannedAttentionMutation( + "unpriced prefix fast-forward", dtype: groupKey.dtype) + { + return + } precondition(windowSize != nil, "fastForward is only for windowed layers") precondition( table.isEmpty && absoluteOffset == 0 && baseOffset == 0, @@ -773,6 +849,10 @@ public final class PagedSequenceKV: CBv2SequenceKV, CBv2PagedSpeculativeRow, CBv /// Windowed rows are refused outright, so nothing here interacts with the /// ring: `ringPages` is nil for every row that can reach this. func adoptFrozen(keys: MLXArray, values: MLXArray, replayStart: Int) { + if pool.refuseUnplannedAttentionMutation("unpriced prefix adoption", dtype: groupKey.dtype) + { + return + } precondition(windowSize == nil, "frozen adoption is only for full-attention rows") precondition( table.isEmpty && absoluteOffset == 0 && baseOffset == 0, diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PreparedNativePagedCheckpoint.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PreparedNativePagedCheckpoint.swift new file mode 100644 index 0000000000..08675aef85 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PreparedNativePagedCheckpoint.swift @@ -0,0 +1,365 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX + +/// One actual stage + suffix preparation, not a ledger or a capability marker. +/// Creation, preparation and publication stay in ONE engine-queue turn. +/// Only metadata publication runs under the native outcome commit. +final class CBv2PreparedNativePagedCheckpoint { + private struct Group { + let value: PagedKVGroup + let plan: PagedKVGroup.ImportPlan + let prepared: PagedKVGroup.PreparedImport + } + private let backend: PagedKVBackend + private let binding: CBv2NativePagedModelBinding + private let work: CBv2NativeCompletePrefixWork + private let operation: CBv2NativePagedOperation + let requestID: CBv2RequestID + let streamGeneration: UInt64 + let maximumTokens: Int + private let promptLength: Int + private var owner: CBv2PagedCheckpointOwner? + private var groups: [Group] = [] + private var rows: [PagedSequenceKV] = [] + private var tables: [[Int32]] = [] + private var grant: PagedKVGrant.Snapshot? + private var previousPhysicalBytes = 0 + private var actualPhysicalBytes = 0 + private var ready = false + private var adopted = false + private var retired = false + private var nativeFinished = false + private var registered = false + private var hostMetadata: CBv2NativePagedHostMetadataGeneration? + private var retiringHostMetadata: CBv2NativePagedHostMetadataGeneration? + private(set) var addedHostBytes = 0 + private(set) var addedTargetBound = 0 + + init( + backend: PagedKVBackend, codec: CBv2CompleteCheckpointCodec, + work: CBv2NativeCompletePrefixWork, request: CBv2Request, + streamGeneration: UInt64, maximumTokens: Int + ) throws { + let maximum = request.promptTokens.count.addingReportingOverflow(max(1, request.maxTokens)) + guard let binding = backend.nativeModelBinding, + codec.nativePagedBinding === binding, codec.isNativePagedHistorical, + work.purpose == .importing, work.codecIdentity == codec.identity, + codec.layerKinds == backend.layerKinds, + codec.admission === backend.pool.memoryAdmission, + codec.admission.hasProcessMemoryOwner, + request.prefixCacheEnabled, request.multimodal == nil, request.positionState == nil, + request.prefixCacheReceiptID != nil, streamGeneration > 0, + !maximum.overflow, maximumTokens == maximum.partialValue, + maximumTokens > request.promptTokens.count, + maximumTokens <= binding.maximumContextTokens + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try binding.requireEngineQueue() + self.backend = backend + self.binding = binding + self.work = work + self.requestID = request.id + self.streamGeneration = streamGeneration + self.maximumTokens = maximumTokens + promptLength = request.promptTokens.count + operation = try binding.beginWork(requests: [request.id]) + } + + /// The containing import owner attaches this object BEFORE invoking this. + /// No prepared page table or suffix allocation exists before its real + /// upward extension of the original typed stage. + func prepare(frame: CBv2PagedCheckpointFrame, admission: AdmissionV2) throws { + try binding.requireEngineQueue() + guard owner == nil, !ready, !adopted, !retired else { + throw CBv2CompleteCheckpointError.closed + } + let owner = try frame.consume() + self.owner = owner + let pool = backend.pool + let storage = owner.storage + let checkpoint = owner.storage.plan + guard let segmentGrant = pool.segmentGrant, let physical = pool.physicalLease, + admission === owner.lease.admission, admission === pool.memoryAdmission, + physical.bytes == pool.bytesMaterialized, + checkpoint.pageSize == pool.config.pageSize, + checkpoint.position < promptLength, + checkpoint.ownerMap == Array(backend.layerKinds.indices), + checkpoint.layers.map(\.modelIndex) == Array(backend.layerKinds.indices), + checkpoint.groups.count == pool.groups.count + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + var needs: [PagedKVGroupKey: Int] = [:] + var rowNeeds: [Int] = [] + for layer in checkpoint.layers { + let kind = backend.layerKinds[layer.modelIndex] + guard kind.sharesKVWithLayer == nil, + layer.key == pool.groupKey(forLayer: layer.modelIndex), + layer.key + == PagedKVGroupKey( + kind, dtype: pool.layerDTypes[layer.modelIndex], separateWindow: true), + layer.tokenStart + == (layer.key.windowSize.map { max(0, checkpoint.position - $0) } ?? 0) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let count = PagedKVPool.pageDemand( + kind: kind, maxLength: maximumTokens, config: pool.config) + guard layer.pageCount <= count else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + needs[layer.key] = try CBv2CheckpointAllocationFootprint.add( + needs[layer.key, default: 0], count) + rowNeeds.append(count) + } + let snapshot = segmentGrant.snapshot() + var growthBound = 0 + var addressBound = 0 + // Scalar bound: creates no replacement dictionary, page-address map + // or native array. Existing immutable stage metadata remains charged. + for key in pool.groupKeys { + let group = pool.group(key) + guard let source = storage.groups[key], let layout = group.segmentLayout, + source.segments.values.allSatisfy({ $0.backing.belongs(to: admission) }) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let demand = try CBv2CheckpointAllocationFootprint.add( + group.pagesReserved, needs[key, default: 0]) + let available = try CBv2CheckpointAllocationFootprint.add( + group.committedUsablePages, source.pages.count) + let missing = max(0, demand - available) + guard let bound = layout.allocationBytes(addingUsablePages: missing), + let growthAddresses = CBv2KVGeometry.multiply(missing, 2) + else { + throw CBv2CompleteCheckpointError.invalidManifest + } + growthBound = try CBv2CheckpointAllocationFootprint.add(growthBound, bound) + addressBound = try CBv2CheckpointAllocationFootprint.add( + addressBound, + CBv2CheckpointAllocationFootprint.add( + group.pageCount, + CBv2CheckpointAllocationFootprint.add(source.layout.pageCount, growthAddresses)) + ) + } + let totalBound = try CBv2CheckpointAllocationFootprint.add( + pool.bytesMaterialized, + CBv2CheckpointAllocationFootprint.add(storage.allocatedBytes, growthBound)) + guard totalBound <= snapshot.bytes else { + throw CBv2KVError.capacityExhausted(needed: totalBound, available: snapshot.bytes) + } + // A real map-generation owner moves with the published pool maps. + // The stage now prices only this helper's private control/row wrappers, + // not a duplicate reservation for those same replacement maps. + hostMetadata = try binding.reserveHostMetadata(addressPages: addressBound) + guard let hostMetadata else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + try work.retain(owners: [hostMetadata]) + operation.retain(owner: hostMetadata) + let host = try CBv2CheckpointAllocationFootprint.add( + 64 << 10, checkpoint.layers.count * 512) + try owner.lease.extendForNativePagedPreparation( + targetBytes: growthBound, auxiliaryBytes: host) + addedTargetBound = growthBound + addedHostBytes = host + previousPhysicalBytes = pool.bytesMaterialized + grant = snapshot + try work.captureCurrentStreams() + do { + try operation.withConstruction { + for key in pool.groupKeys { + let group = pool.group(key) + let source = storage.groups[key]! + let plan = try group.planImport( + source, additionalReservedPages: needs[key, default: 0]) + let prepared = try group.prepareImport( + plan, source: source, + evaluate: pool.slabEval, admission: admission) + groups.append(.init(value: group, plan: plan, prepared: prepared)) + } + } + // The same complete private plans are used at commit. Do not build + // a second host page map or mutate any live group here. + for (index, layer) in checkpoint.layers.enumerated() { + guard let group = groups.first(where: { $0.value.key == layer.key }), + layer.firstPage <= group.plan.pages.count, + layer.pageCount <= group.plan.pages.count - layer.firstPage + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + tables.append( + Array(group.plan.pages[layer.firstPage ..< layer.firstPage + layer.pageCount])) + rows.append( + PagedSequenceKV( + pool: pool, kind: backend.layerKinds[layer.modelIndex], + groupKey: layer.key, maxLength: maximumTokens, + reservedPages: rowNeeds[index])) + } + actualPhysicalBytes = try groups.reduce(0) { total, group in + try group.prepared.growth.segments.values.reduce(total) { + try CBv2CheckpointAllocationFootprint.add($0, $1.allocatedBytes) + } + } + guard actualPhysicalBytes >= previousPhysicalBytes, + actualPhysicalBytes <= totalBound + else { + throw CBv2CompleteCheckpointError.allocationFailed + } + try operation.requiredDrain() + try work.fenceForProtectedPromotion() + try owner.lease.settleDestinationAfterEvaluation( + targetBytes: actualPhysicalBytes - previousPhysicalBytes, + auxiliaryBytes: owner.lease.auxiliaryBytes) + ready = true + } catch { + // An actual partial suffix allocation/evaluation is a required + // native failure. The two real loans keep all roots and stage C. + if operation.hasArrays || error is MLXError { + operation.fail() + work.requiredCompletionFailed() + } + throw error + } + } + + var scalarWitness: (ready: Bool, rows: Int, targetBound: Int, hostBound: Int) { + ( + ready && operation.completed && work.hasProtectedPromotionCompletion, + rows.count, addedTargetBound, addedHostBytes + ) + } + + func authorizesRegistration(_ candidate: [CBv2SequenceKV?], backend expected: PagedKVBackend) + -> Bool + { + backend === expected && backend.nativeModelBinding === binding && ready && !adopted + && !retired + && operation.completed && !operation.failed && work.hasProtectedPromotionCompletion + && candidate.count == rows.count + && zip(candidate, rows).allSatisfy { $0.0 === $0.1 } + } + + /// Native outcome lock is held by enqueue. Every fallible assistant check + /// precedes this method. No array operation, evaluation or fence occurs. + func publish(admission: AdmissionV2, streamGeneration: UInt64) throws -> [CBv2SequenceKV?] { + try binding.requireEngineQueue() + guard ready, !adopted, !retired, !registered, operation.completed, !operation.failed, + work.hasProtectedPromotionCompletion, self.streamGeneration == streamGeneration, + let owner, let grant, let segmentGrant = backend.pool.segmentGrant, + let physical = backend.pool.physicalLease, owner.lease.admission === admission, + physical.bytes == previousPhysicalBytes, + backend.pool.bytesMaterialized == previousPhysicalBytes + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let state: [CBv2SequenceKV?] = rows.map { $0 } + try backend.registerPreparedNativeCheckpoint(state, preparation: self) + registered = true + let reservation: CBv2CheckpointAdoptionReservation + do { + reservation = try physical.transferCheckpoint( + to: actualPhysicalBytes, admission: admission + ) { previous in + try admission.transferCheckpointStage( + owner.lease, requestID: requestID, + maximumTokens: maximumTokens, previousPhysicalBytes: previous, + physicalBytes: actualPhysicalBytes, retainingNativeAuxiliaryStage: true) + } + } catch { + do { + try backend.rollbackPreparedNativeCheckpointRegistration(state, preparation: self) + } catch { + operation.fail() + work.requiredCompletionFailed() + throw error + } + registered = false + throw error + } + let result = segmentGrant.publish(expected: grant, physicalBytes: actualPhysicalBytes) { + for group in groups { group.value.installImport(group.prepared) } + retiringHostMetadata = binding.installHostMetadata(hostMetadata) + for (index, row) in rows.enumerated() { + let layer = owner.storage.plan.layers[index] + if layer.ringPages != nil { + row.adoptHistoricalWindowPages( + tables[index], retainedStart: layer.tokenStart, + storedThrough: owner.storage.plan.position) + } else { + row.adoptExclusiveCheckpointPages( + tables[index], storedThrough: owner.storage.plan.position) + } + } + } + backend.pool.storageTelemetry.record(result) + guard result == .installed else { + // Same engine-queue turn: no ordinary mutation intervened. Target + // bytes return to the private stage, NEVER to free capacity while + // the actual immutable buffers/loan are still retained. + reservation.rollbackAfterDroppingOwners() + do { + try backend.rollbackPreparedNativeCheckpointRegistration(state, preparation: self) + } catch { + operation.fail() + work.requiredCompletionFailed() + throw error + } + registered = false + throw CBv2KVError.capacityExhausted( + needed: actualPhysicalBytes, available: segmentGrant.snapshot().bytes) + } + reservation.commit() + adopted = true + backend.pool.storageTelemetry.recordSettlement( + bound: previousPhysicalBytes + owner.lease.targetBytes, actual: actualPhysicalBytes) + rows.removeAll() + tables.removeAll() + return state + } + + /// Executed by the containing import owner's real post-fence callback on + /// this engine queue. A failed operation cannot be mistaken for completion. + func retireAfterCompletion() throws { + try binding.requireEngineQueue() + if nativeFinished { return } + // A refused host-only preparation may own map allowances but have + // submitted no suffix array. Fence its actual streams; do not mint an + // unstarted success while a retained owner still exists. + if !operation.completed && !operation.failed && !operation.hasArrays { + do { try operation.requiredDrain() } catch { + work.requiredCompletionFailed() + throw error + } + } + guard !operation.failed, + operation.finish(unstarted: !operation.hasArrays) + else { + throw CBv2NativeShutdownError.operationClosed + } + nativeFinished = true + } + + /// All duplicate imported arrays/checkpoint aliases are dropped first by + /// the containing owner. Only then may this stage release its remaining + /// auxiliary/host/scratch charge. Active pool/request ownership is separate. + func closeAfterNativeCompletion() { + precondition(nativeFinished && !retired) + retired = true + if !adopted { + precondition(!registered) + for row in rows { row.discardUninstalledCheckpointRow() } + } + rows.removeAll() + tables.removeAll() + groups.removeAll() + hostMetadata = nil + retiringHostMetadata = nil + owner?.close() + owner = nil + } + + deinit { + assert(retired, "native paged prefix preparation bypassed actual retirement") + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CheckpointAllocationFootprint.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CheckpointAllocationFootprint.swift index a208b54ea3..fe3940171e 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CheckpointAllocationFootprint.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CheckpointAllocationFootprint.swift @@ -8,13 +8,14 @@ enum CBv2CheckpointAllocationFootprint { } static func freshBytes(_ arrays: [MLXArray]) throws -> (bound: Int, actual: Int) { - var bound = 0, actual = 0 + var bound = 0 + var actual = 0 for array in arrays { let upper = try Self.bound(array.nbytes) guard let info = try array.evaluatedBufferInfo(), info.isUnique, - info.isRowContiguous, info.dataOffset == 0, - info.dataElements == array.size, - info.allocatedBytes >= array.nbytes, info.allocatedBytes <= upper + info.isRowContiguous, info.dataOffset == 0, + info.dataElements == array.size, + info.allocatedBytes >= array.nbytes, info.allocatedBytes <= upper else { throw CBv2CompleteCheckpointError.allocationFailed } bound = try add(bound, upper) actual = try add(actual, info.allocatedBytes) @@ -50,7 +51,9 @@ enum CBv2CheckpointAllocationFootprint { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } charge = try retainedBytes(ssm) - case .keys, .values: + case .keys, .values, .assistantKeys, .assistantValues, .assistantCacheMetadata: + // Historical attention/MTP copies use their dedicated complete + // layout and bound; the generic recurrent helper cannot price them. throw CBv2CompleteCheckpointError.incompatibleCheckpoint } total = try add(total, charge) @@ -60,7 +63,9 @@ enum CBv2CheckpointAllocationFootprint { static func add(_ lhs: Int, _ rhs: Int) throws -> Int { let (sum, overflow) = lhs.addingReportingOverflow(rhs) - guard lhs >= 0, rhs >= 0, !overflow else { throw CBv2CompleteCheckpointError.invalidManifest } + guard lhs >= 0, rhs >= 0, !overflow else { + throw CBv2CompleteCheckpointError.invalidManifest + } return sum } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointCapture.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointCapture.swift index 40fc571d38..9e21d4f9d7 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointCapture.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointCapture.swift @@ -8,6 +8,11 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { let store: any CBv2CompletePrefixCache let queue = DispatchQueue(label: "cbv2.complete-checkpoint-retirement", qos: .utility) var staged: [CBv2RequestID: [CBv2CapturedCompleteCheckpoint]] = [:] + var makeContiguousCheckpoint: + (CBv2CompleteCheckpointCodec, Int, Int, [CBv2SequenceKV?]) throws -> + CBv2ContiguousHistoricalCheckpoint = { + try .init(codec: $0, position: $1, chunkSize: $2, state: $3) + } /// Every donor keeps at most the first boundary, the coordinator's fork /// target and the rolling latest (`CBv2CheckpointRetention`): a /// historical donor on the 1,024-token stride, a recurrent donor on @@ -60,7 +65,8 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { /// (`CBv2InFlightStep.permitsChainedSuccessor`), so every candidate is /// committed or closed before the next step prepares and resets this. var inFlightHistoricalBytes = 0 - var historicalCheckpointStrideTokens = CBv2RecurrentCheckpointGeometry.historicalCheckpointStrideTokens + var historicalCheckpointStrideTokens = CBv2RecurrentCheckpointGeometry + .historicalCheckpointStrideTokens /// A fork target within this many tokens of the final deepest boundary /// is dropped at publication, for every layout. Test seam. var targetAdjacencyTokens = CBv2CheckpointRetention.defaultTargetAdjacencyTokens @@ -72,6 +78,39 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { private let handlerLock = NSLock() private var publicationHandler: (@Sendable (CBv2RequestID, [Int]) -> Void)? private var closed = false + // Installed once by the exact issued native profile before the loop starts. + var nativeWorkFactory: ((CBv2RequestID?) throws -> CBv2NativeCompletePrefixWork)? + var nativeFailure: (() -> Void)? + private var nativeFaultOwners: [AnyObject] = [] + var hasNativeTracking: Bool { nativeWorkFactory != nil } + + func retainAfterNativeFailure(_ owner: AnyObject) { + handlerLock.withLock { nativeFaultOwners.append(owner) } + nativeFailure?() + } + + /// All rolling/rejected captures use the same tracked completion owner. + /// Legacy/untracked cleanup remains byte-for-byte the old behavior. + func retireCaptured( + _ candidate: CBv2CapturedCompleteCheckpoint, + requestID: CBv2RequestID? + ) { + guard let factory = nativeWorkFactory else { + queue.async { candidate.finishEvaluationAndClose() } + return + } + do { + let work = try factory(requestID) + try work.retain(arrays: candidate.evaluationRoots, owners: [candidate]) + queue.async { + do { + try work.captureCurrentStreams() + try candidate.finishEvaluationForRetirement() + work.finishAfterDroppingConsumers { candidate.closeAfterCompletedEvaluation() } + } catch { work.requiredCompletionFailed() } + } + } catch { retainAfterNativeFailure(candidate) } + } init(codec: CBv2CompleteCheckpointCodec, store: any CBv2CompletePrefixCache) { self.codec = codec @@ -117,8 +156,10 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { func retention( requestID: CBv2RequestID, stride: Int?, hintTokens: Int?, resumedAt: Int ) -> CBv2CheckpointRetention { - retentions[requestID] ?? .init(stride: stride, hintTokens: hintTokens, resumedAt: resumedAt, - targetAdjacencyTokens: targetAdjacencyTokens) + retentions[requestID] + ?? .init( + stride: stride, hintTokens: hintTokens, resumedAt: resumedAt, + targetAdjacencyTokens: targetAdjacencyTokens) } /// Reserve before any checkpoint copy graph is constructed. The extra @@ -154,24 +195,29 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { mediaIdentity: CBv2HybridPrefixIdentity? = nil, mediaTargetOnly: Bool = false, hintTokens: Int? = nil, resumedAt: Int = 0 ) -> [MLXArray] { - guard !isClosed, position > 1, chunkSize > 1, + guard codec.contiguousLayout == nil, !codec.isNativePagedHistorical, !isClosed, + position > 1, chunkSize > 1, CBv2RecurrentCheckpointGeometry.isRecurrentBoundary(position, chunkSize: chunkSize), !mediaTargetOnly || mediaIdentity != nil, !(staged[requestID]?.contains { $0.checkpoint?.position == position } ?? false) else { return [] } do { let qwen4 = try codec.qwen4Snapshots(rows: rowStates, position: position) - let logical = CBv2RecurrentCheckpoint(position: position, chunkSize: chunkSize, + let logical = CBv2RecurrentCheckpoint( + position: position, chunkSize: chunkSize, layers: [:], byteCount: 0, qwen4: qwen4) - let descriptors = try codec.tensorDescriptors(position: position, qwen4: codec.qwen4Descriptors(logical), - mediaTargetOnly: mediaTargetOnly) + let descriptors = try codec.tensorDescriptors( + position: position, qwen4: codec.qwen4Descriptors(logical), + mediaTargetOnly: mediaTargetOnly) var packedBytes = 0 for descriptor in descriptors { let (next, overflow) = packedBytes.addingReportingOverflow(descriptor.byteCount) guard !overflow else { return [] } packedBytes = next } - guard store.acceptsCheckpoint(position: position, packedBytes: packedBytes) else { return [] } + guard store.acceptsCheckpoint(position: position, packedBytes: packedBytes) else { + return [] + } let stateDescriptors = descriptors.filter { $0.role != .keys && $0.role != .values } for spec in codec.recurrentSpec?.layers ?? [] { guard let state = layers[spec.modelLayerIndex], @@ -180,13 +226,15 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { ssm.shape == spec.ssmShape, ssm.dtype == spec.ssmDType else { return [] } } - let bytes = try CBv2CheckpointAllocationFootprint.captureBytes(stateDescriptors, layers: layers) + let bytes = try CBv2CheckpointAllocationFootprint.captureBytes( + stateDescriptors, layers: layers) let reservation = try codec.admission.reserveTransient(bytes: bytes) let checkpoint = try withError { error in var assistant: (any CBv2MTPPrefixCheckpoint)? if let drafter = codec.assistant, !mediaTargetOnly { guard let assistantState, - let captured = drafter.capturePrefixCheckpoint(requestState: assistantState, targetInputCount: position) + let captured = drafter.capturePrefixCheckpoint( + requestState: assistantState, targetInputCount: position) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } assistant = captured } @@ -200,16 +248,18 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { try error.check() return CBv2RecurrentCheckpoint( position: position, chunkSize: chunkSize, layers: copies, - byteCount: stateDescriptors.reduce(0) { $0 + $1.byteCount }, assistant: assistant, + byteCount: stateDescriptors.reduce(0) { $0 + $1.byteCount }, + assistant: assistant, qwen4: try codec.compactQwen4(qwen4), mediaIdentity: mediaIdentity, mediaTargetOnly: mediaTargetOnly) } - let captured = CBv2CapturedCompleteCheckpoint(checkpoint: checkpoint, reservation: reservation) + let captured = CBv2CapturedCompleteCheckpoint( + checkpoint: checkpoint, reservation: reservation) var verdicts = self.retention( requestID: requestID, stride: nil, hintTokens: hintTokens, resumedAt: resumedAt) let retired = Set(verdicts.commit(position)) guard !retired.contains(position) else { - queue.async { captured.finishEvaluationAndClose() } + retireCaptured(captured, requestID: requestID) return [] } var checkpoints = staged[requestID] ?? [] @@ -218,9 +268,7 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { checkpoints.append(captured) staged[requestID] = checkpoints retentions[requestID] = verdicts - if !retiring.isEmpty { - queue.async { retiring.forEach { $0.finishEvaluationAndClose() } } - } + for previous in retiring { retireCaptured(previous, requestID: requestID) } return checkpoint.evaluationRoots } catch { return [] @@ -229,9 +277,28 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { /// A final queued drop follows that request's rolling retirement copies. /// The engine counts this callback in its existing shutdown drain barrier. - func drop(requestID: CBv2RequestID, completion: @escaping @Sendable () -> Void) -> Bool { + func drop( + requestID: CBv2RequestID, nativeWork: CBv2NativeCompletePrefixWork? = nil, + completion: @escaping @Sendable () -> Void + ) -> Bool { retentions.removeValue(forKey: requestID) guard let captures = staged.removeValue(forKey: requestID) else { return false } + if let nativeWork { + do { + try nativeWork.retain(arrays: captures.flatMap(\.evaluationRoots), owners: captures) + } catch { return true } // loan already retains the late actual roots. + queue.async { + do { + try nativeWork.captureCurrentStreams() + for capture in captures { try capture.finishEvaluation() } + nativeWork.finishAfterDroppingConsumers { + captures.forEach { $0.closeAfterCompletedEvaluation() } + completion() + } + } catch { nativeWork.requiredCompletionFailed() } + } + return true + } queue.async { captures.forEach { $0.finishEvaluationAndClose() } completion() @@ -239,11 +306,13 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { return true } - /// Always completes. Call on the engine queue with retired KV owners; - /// their backend/request reservation remains live until completion. + /// Legacy callers always complete. A tracked native failure retains its + /// operation and poisons the outcome instead of invoking a success-shaped + /// retirement callback. Donor backend/request C stays live until completion. func publish( intent: CBv2DonationIntent, state: [CBv2SequenceKV?], + nativeWork: CBv2NativeCompletePrefixWork? = nil, completion: @escaping @Sendable ([Int]) -> Void ) { // Every donor publishes deepest first, then the fork target, then the @@ -258,19 +327,59 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { let retiring = captures.filter { $0.position.map(dropped.contains) ?? false } captures.removeAll { $0.position.map(dropped.contains) ?? false } captures.sort { ($0.position ?? 0) > ($1.position ?? 0) } - if !retiring.isEmpty { - queue.async { retiring.forEach { $0.finishEvaluationAndClose() } } + for previous in retiring { retireCaptured(previous, requestID: intent.requestID) } + if let nativeWork { + do { + try nativeWork.retain(arrays: captures.flatMap(\.evaluationRoots), owners: captures) + } catch { return } } var exports: [CBv2CompleteCheckpointExport] = [] for capture in captures where intent.allowsCompletePublication { - if let checkpoint = capture.historical { + if let nativeWork { + do { + let source: CBv2CompleteCheckpointExport + if let checkpoint = capture.contiguous { + source = try checkpoint.export( + codec: codec, state: state, + tokens: intent.tokens, cacheSalt: intent.cacheSalt) + } else if let checkpoint = capture.historical { + source = try codec.exportHistorical( + checkpoint: checkpoint, state: state, + tokens: intent.tokens, cacheSalt: intent.cacheSalt) + } else if let checkpoint = capture.checkpoint { + source = try codec.export( + checkpoint: checkpoint, state: state, + tokens: intent.tokens, cacheSalt: intent.cacheSalt) + } else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try nativeWork.retain(owners: [source]) + try source.bindNativeCompletePrefixWork(nativeWork) + exports.append(source) + } catch { + nativeWork.requiredCompletionFailed() + return + } + continue + } + if let checkpoint = capture.contiguous { + if let source = try? checkpoint.export( + codec: codec, state: state, tokens: intent.tokens, cacheSalt: intent.cacheSalt) + { + exports.append(source) + } + } else if let checkpoint = capture.historical { if let source = try? codec.exportHistorical( - checkpoint: checkpoint, state: state, tokens: intent.tokens, cacheSalt: intent.cacheSalt) { + checkpoint: checkpoint, state: state, tokens: intent.tokens, + cacheSalt: intent.cacheSalt) + { exports.append(source) } } else if let checkpoint = capture.checkpoint { if let source = try? codec.export( - checkpoint: checkpoint, state: state, tokens: intent.tokens, cacheSalt: intent.cacheSalt) { + checkpoint: checkpoint, state: state, tokens: intent.tokens, + cacheSalt: intent.cacheSalt) + { exports.append(source) } } @@ -279,7 +388,9 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { var onRetired: (@Sendable () -> Void)? if publishingBytes > 0 { let requestID = intent.requestID - publishingLock.withLock { publishingHistoricalBytes[requestID, default: 0] += publishingBytes } + publishingLock.withLock { + publishingHistoricalBytes[requestID, default: 0] += publishingBytes + } onRetired = { [self] in publishingLock.withLock { let remaining = (publishingHistoricalBytes[requestID] ?? 0) - publishingBytes @@ -294,20 +405,50 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { let batch = CBv2CompleteCheckpointPublication( captures: captures, exports: exports, receiptID: intent.receiptID, tokens: intent.tokens, cacheSalt: intent.cacheSalt, - onRetired: onRetired, completion: completion) + nativeWork: nativeWork, onRetired: onRetired, completion: completion) queue.async { [self] in + if let nativeWork { + do { + try nativeWork.retain(owners: [batch]) + try nativeWork.captureCurrentStreams() + } catch { return } + // Even a closed store must complete/drop already-created + // native captures truthfully; no swallowed required fence. + let prepared = batch.prepare() + guard !nativeWork.debugIsFailed else { return } + guard !isClosed, prepared, + let scratch = try? codec.admission.reserveTransient( + bytes: codec.exportScratchBytes + + (codec.admission.hasProcessMemoryOwner + ? 0 : CBv2CompleteCheckpointManifest.maximumProviderScratchBytes)) + else { + batch.close() + return + } + batch.scratch = scratch + do { try nativeWork.retain(owners: [scratch]) } catch { return } + publishNext(batch) + return + } guard !isClosed, batch.prepare(), let scratch = try? codec.admission.reserveTransient( - bytes: codec.exportScratchBytes + (codec.admission.hasProcessMemoryOwner - ? 0 : CBv2CompleteCheckpointManifest.maximumProviderScratchBytes)) - else { batch.close(); return } + bytes: codec.exportScratchBytes + + (codec.admission.hasProcessMemoryOwner + ? 0 : CBv2CompleteCheckpointManifest.maximumProviderScratchBytes)) + else { + batch.close() + return + } batch.scratch = scratch publishNext(batch) } } private func publishNext(_ batch: CBv2CompleteCheckpointPublication) { - guard !isClosed, let source = batch.nextSource else { batch.close(); return } + guard !isClosed, let source = batch.nextSource else { + batch.close() + return + } store.donate( source, requestID: batch.receiptID, tokens: batch.tokens, cacheSalt: batch.cacheSalt ) { [self, batch, source] positions in @@ -322,8 +463,12 @@ final class CBv2CompleteCheckpointCapture: @unchecked Sendable { final class CBv2CapturedCompleteCheckpoint: @unchecked Sendable { private(set) var checkpoint: CBv2RecurrentCheckpoint? private(set) var historical: CBv2HistoricalCompleteCheckpoint? - var evaluationRoots: [MLXArray] { checkpoint?.evaluationRoots ?? historical?.evaluationRoots ?? [] } - var position: Int? { checkpoint?.position ?? historical?.position } + private(set) var contiguous: CBv2ContiguousHistoricalCheckpoint? + var evaluationRoots: [MLXArray] { + contiguous?.evaluationRoots ?? checkpoint?.evaluationRoots ?? historical?.evaluationRoots + ?? [] + } + var position: Int? { contiguous?.position ?? checkpoint?.position ?? historical?.position } /// Transient admission bytes this staged historical capture holds. var stagedHistoricalBytes: Int { historical?.reservedBytes ?? 0 } private var reservation: CBv2CheckpointReservation? @@ -334,14 +479,38 @@ final class CBv2CapturedCompleteCheckpoint: @unchecked Sendable { } init(historical: CBv2HistoricalCompleteCheckpoint) { self.historical = historical } + init(contiguous: CBv2ContiguousHistoricalCheckpoint) { self.contiguous = contiguous } func finishEvaluation() throws { - if let historical { try historical.finishEvaluation() } - else { try withError { eval(evaluationRoots) } } + if let contiguous { + try contiguous.finishEvaluation() + } else if let historical { + try historical.finishEvaluation() + } else { + try withError { eval(evaluationRoots) } + } } func finishEvaluationAndClose() { try? finishEvaluation() + closeAfterCompletedEvaluation() + } + + func finishEvaluationForRetirement() throws { + if let contiguous { + try contiguous.finishEvaluationForRetirement() + } else if let historical { + try historical.finishEvaluationForRetirement() + } else { + try finishEvaluation() + } + } + + // Tracked callers invoke this only inside their actual work's post-fence + // retirement callback; a caught failure must never arrive here. + func closeAfterCompletedEvaluation() { + contiguous?.close() + contiguous = nil historical = nil checkpoint = nil reservation?.release() @@ -362,10 +531,13 @@ private final class CBv2CompleteCheckpointPublication: @unchecked Sendable { let tokens: [Int] let cacheSalt: String? var scratch: CBv2CheckpointReservation? + private let nativeWork: CBv2NativeCompletePrefixWork? + private var nativeFailure = false init( captures: [CBv2CapturedCompleteCheckpoint], exports: [CBv2CompleteCheckpointExport], receiptID: CBv2RequestID?, tokens: [Int], cacheSalt: String?, + nativeWork: CBv2NativeCompletePrefixWork?, onRetired: (@Sendable () -> Void)? = nil, completion: @escaping @Sendable ([Int]) -> Void ) { @@ -376,6 +548,7 @@ private final class CBv2CompleteCheckpointPublication: @unchecked Sendable { self.cacheSalt = cacheSalt self.onRetired = onRetired self.completion = completion + self.nativeWork = nativeWork } func prepare() -> Bool { @@ -384,7 +557,13 @@ private final class CBv2CompleteCheckpointPublication: @unchecked Sendable { try capture.finishEvaluation() } return !exports.isEmpty - } catch { return false } + } catch { + if let nativeWork { + nativeFailure = true + nativeWork.requiredCompletionFailed() + } + return false + } } var nextSource: CBv2CompleteCheckpointExport? { cursor < exports.count ? exports[cursor] : nil } @@ -400,9 +579,24 @@ private final class CBv2CompleteCheckpointPublication: @unchecked Sendable { } func close() { + if let nativeWork { + guard !nativeFailure else { return } + // The callback-held source aliases have unwound before this queued + // work's real fence; keep captures and scratch until that fence. + nativeWork.finishAfterDroppingConsumers { [self] in closeAfterNativeCompletion() } + return + } + closeAfterNativeCompletion() + } + + private func closeAfterNativeCompletion() { exports.forEach { $0.close() } exports.removeAll() - captures.forEach { $0.finishEvaluationAndClose() } + if nativeWork != nil { + captures.forEach { $0.closeAfterCompletedEvaluation() } + } else { + captures.forEach { $0.finishEvaluationAndClose() } + } captures.removeAll() let retired = onRetired onRetired = nil diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointCodec.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointCodec.swift index 17e5154604..7812972802 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointCodec.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointCodec.swift @@ -3,9 +3,13 @@ import MLX /// Immutable loaded-model validation; safe to use from the provider's staging /// queue. It never executes a model or changes assistant request state. -final class CBv2CompleteCheckpointCodec: @unchecked Sendable { +package final class CBv2CompleteCheckpointCodec: @unchecked Sendable { let identity: CBv2CompleteCheckpointIdentity let layerKinds: [CBv2LayerKind] + /// Legacy/unissued paged entries keep refusing asymmetry. Only a validated + /// contiguous layout or the actual package-issued page/store/assistant + /// binding grants its distinct complete format. + let unsupportedAsymmetricGeometry: Bool let recurrentSpec: CBv2RecurrentStateSpec? let kvDTypes: [DType] let assistant: (any CBv2MTPPrefixCheckpointCoding)? @@ -14,10 +18,29 @@ final class CBv2CompleteCheckpointCodec: @unchecked Sendable { /// Copied immutable layout only. Planning/staging never reads live pool maps. let pagedConfig: PagedKVPoolConfig? let historicalLayout: CBv2HistoricalAttentionLayout? - var targetTensorCount: Int { (historicalLayout?.owningIndices.count ?? layerKinds.count) * 2 } + let contiguousLayout: CBv2HistoricalAttentionLayout? + /// Present only after the actual package-issued bank/store/assistant tuple + /// validates. Untracked asymmetric page codecs remain refused. + let nativePagedBinding: CBv2NativePagedModelBinding? + var isNativePagedHistorical: Bool { nativePagedBinding != nil && historicalLayout != nil } + var targetTensorCount: Int { + (contiguousLayout?.owningIndices.count ?? historicalLayout?.owningIndices.count + ?? layerKinds.count) * 2 + } var backendLayout: String { + if contiguousLayout != nil { + return assistant == nil + ? CBv2CompleteCheckpointManifest.contiguousAsymmetricLayout + : CBv2CompleteCheckpointManifest.contiguousAsymmetricMTPLayout + } + if isNativePagedHistorical { + return assistant == nil + ? CBv2CompleteCheckpointManifest.pagedAsymmetricLayout + : CBv2CompleteCheckpointManifest.pagedAsymmetricMTPLayout + } if recurrentSpec == nil { return CBv2CompleteCheckpointManifest.historicalAttentionLayout } - return pagedConfig == nil ? CBv2CompleteCheckpointManifest.layout : CBv2CompleteCheckpointManifest.pagedLayout + return pagedConfig == nil + ? CBv2CompleteCheckpointManifest.layout : CBv2CompleteCheckpointManifest.pagedLayout } var exportScratchBytes: Int { // Paged export copies shared native backing straight into the @@ -30,28 +53,72 @@ final class CBv2CompleteCheckpointCodec: @unchecked Sendable { recurrentSpec: CBv2RecurrentStateSpec?, kvDTypes: [DType], assistant: (any CBv2MTPPrefixCheckpointCoding)?, admission: AdmissionV2, pagedConfig: PagedKVPoolConfig? = nil, - qwen4Geometries: [CBv2Qwen4CheckpointGeometry] = [] + qwen4Geometries: [CBv2Qwen4CheckpointGeometry] = [], + nativePagedBinding: CBv2NativePagedModelBinding? = nil ) { self.identity = identity self.layerKinds = layerKinds + let asymmetric = layerKinds.contains { $0.valueHeadDim != $0.headDim } + self.unsupportedAsymmetricGeometry = asymmetric self.recurrentSpec = recurrentSpec self.kvDTypes = kvDTypes self.assistant = assistant self.qwen4Geometries = qwen4Geometries self.admission = admission self.pagedConfig = pagedConfig - self.historicalLayout = recurrentSpec == nil && pagedConfig != nil && assistant == nil - ? try? .init(layerKinds: layerKinds, dtypes: kvDTypes) : nil + let historicalAssistant = + assistant == nil || assistant is any CBv2HistoricalMTPPrefixCheckpointCoding + let issuedPaged = + asymmetric && recurrentSpec == nil && pagedConfig != nil + && qwen4Geometries.isEmpty && historicalAssistant + && nativePagedBinding?.validatesCompletePrefixCodec( + identity: identity, + layerKinds: layerKinds, layerDTypes: kvDTypes, + assistant: assistant.map { $0 as AnyObject }) == true + self.nativePagedBinding = issuedPaged ? nativePagedBinding : nil + self.historicalLayout = + issuedPaged + ? try? .init(layerKinds: layerKinds, dtypes: kvDTypes, allowAsymmetric: true) + : (!asymmetric && recurrentSpec == nil && pagedConfig != nil && assistant == nil + ? try? .init(layerKinds: layerKinds, dtypes: kvDTypes) : nil) + self.contiguousLayout = + asymmetric && recurrentSpec == nil && pagedConfig == nil && historicalAssistant + && qwen4Geometries.isEmpty + ? try? .init(layerKinds: layerKinds, dtypes: kvDTypes, allowAsymmetric: true) : nil } - func tensorDescriptors(position: Int, qwen4: [CBv2CheckpointTensorDescriptor] = [], - mediaTargetOnly: Bool = false) throws -> [CBv2CheckpointTensorDescriptor] { + func tensorDescriptors( + position: Int, qwen4: [CBv2CheckpointTensorDescriptor] = [], + mediaTargetOnly: Bool = false + ) throws -> [CBv2CheckpointTensorDescriptor] { + if let completeLayout = contiguousLayout + ?? (isNativePagedHistorical ? historicalLayout : nil) + { + guard identity.isValid, position > 1, qwen4.isEmpty, !mediaTargetOnly else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + var descriptors = try completeLayout.tensorDescriptors(position: position) + if let assistant { + guard assistant is any CBv2HistoricalMTPPrefixCheckpointCoding, + let auxiliary = assistant.prefixCheckpointTensorDescriptors( + targetInputCount: position), + !auxiliary.isEmpty + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + descriptors.append(contentsOf: auxiliary) + } + return descriptors + } + guard !unsupportedAsymmetricGeometry else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } guard !mediaTargetOnly || !qwen4Geometries.isEmpty else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } try validateQwen4Descriptors(qwen4, position: position) if let historicalLayout { - guard identity.isValid, position > 1 else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + guard identity.isValid, position > 1 else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } return try historicalLayout.tensorDescriptors(position: position) } guard kvDTypes.count == layerKinds.count, recurrentSpec?.layers.isEmpty == false, @@ -64,23 +131,30 @@ final class CBv2CompleteCheckpointCodec: @unchecked Sendable { let kvDType = CBv2CheckpointDType(kvDTypes[index]), kvDType.isFloatingPoint else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } for role in [CBv2CheckpointTensorRole.keys, .values] { - result.append(try .init( - role: role, layer: kind.modelLayerIndex ?? index, - shape: [1, kind.kvHeads, position, kind.headDim], dtype: kvDType)) + result.append( + try .init( + role: role, layer: kind.modelLayerIndex ?? index, + shape: [1, kind.kvHeads, position, kind.headDim], dtype: kvDType)) } } for spec in recurrentSpec?.layers ?? [] { guard let conv = CBv2CheckpointDType(spec.convDType), let ssm = CBv2CheckpointDType(spec.ssmDType) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } - result.append(try .init( - role: .convolution, layer: spec.modelLayerIndex, shape: spec.convShape, dtype: conv)) - result.append(try .init( - role: .recurrent, layer: spec.modelLayerIndex, shape: spec.ssmShape, dtype: ssm)) + result.append( + try .init( + role: .convolution, layer: spec.modelLayerIndex, shape: spec.convShape, + dtype: conv)) + result.append( + try .init( + role: .recurrent, layer: spec.modelLayerIndex, shape: spec.ssmShape, dtype: ssm) + ) } result.append(contentsOf: qwen4) if let assistant, !mediaTargetOnly { - guard let descriptors = assistant.prefixCheckpointTensorDescriptors(targetInputCount: position) + guard + let descriptors = assistant.prefixCheckpointTensorDescriptors( + targetInputCount: position) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } result.append(contentsOf: descriptors) } @@ -90,8 +164,13 @@ final class CBv2CompleteCheckpointCodec: @unchecked Sendable { func plan( manifest: CBv2CompleteCheckpointManifest, request: CBv2Request ) throws -> CBv2CompleteCheckpointImportPlan { + guard !unsupportedAsymmetricGeometry || contiguousLayout != nil || isNativePagedHistorical + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } _ = try manifest.validateStructure() - let (maximumLength, overflow) = request.promptTokens.count.addingReportingOverflow(max(1, request.maxTokens)) + let (maximumLength, overflow) = request.promptTokens.count.addingReportingOverflow( + max(1, request.maxTokens)) guard !overflow, request.permitsHybridCheckpoint(layerKinds: layerKinds), manifest.identity == identity, manifest.backendLayout == backendLayout, @@ -104,10 +183,13 @@ final class CBv2CompleteCheckpointCodec: @unchecked Sendable { // chunking (`completeCheckpointLookup`); the recorded `chunkSize` // is provenance and position alignment, never a stride this // engine must be able to schedule. - manifest.assistantCodecID == (manifest.mediaTargetOnly ? nil : assistant?.prefixCheckpointCodecID), - manifest.attentionLayers == historicalLayout?.layers, - manifest.tensors == (try tensorDescriptors(position: manifest.position, qwen4: qwen4Descriptors(in: manifest), - mediaTargetOnly: manifest.mediaTargetOnly)) + manifest.assistantCodecID + == (manifest.mediaTargetOnly ? nil : assistant?.prefixCheckpointCodecID), + manifest.attentionLayers == (contiguousLayout?.layers ?? historicalLayout?.layers), + manifest.tensors + == (try tensorDescriptors( + position: manifest.position, qwen4: qwen4Descriptors(in: manifest), + mediaTargetOnly: manifest.mediaTargetOnly)) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } return try .init(codec: self, manifest: manifest, maximumSequenceLength: maximumLength) } @@ -119,13 +201,21 @@ final class CBv2CompleteCheckpointCodec: @unchecked Sendable { kv: [(keys: MLXArray, values: MLXArray, offset: Int)?], tokens: [Int], cacheSalt: String? ) throws -> CBv2CompleteCheckpointExport { - guard pagedConfig == nil, checkpoint.position < tokens.count, kv.count == layerKinds.count else { + if contiguousLayout != nil { + return try exportContiguousV2( + checkpoint: checkpoint, kv: kv, tokens: tokens, cacheSalt: cacheSalt) + } + guard !unsupportedAsymmetricGeometry, pagedConfig == nil, + checkpoint.position < tokens.count, kv.count == layerKinds.count + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } - let metadataPermit = try CBv2CheckpointManifestMemory.Permit(admission: admission, position: checkpoint.position) + let metadataPermit = try CBv2CheckpointManifestMemory.Permit( + admission: admission, position: checkpoint.position) return try withExtendedLifetime(metadataPermit) { - try makeContiguousExport(checkpoint: checkpoint, kv: kv, tokens: tokens, - cacheSalt: cacheSalt, metadataPermit: metadataPermit) + try makeContiguousExport( + checkpoint: checkpoint, kv: kv, tokens: tokens, + cacheSalt: cacheSalt, metadataPermit: metadataPermit) } } @@ -133,8 +223,9 @@ final class CBv2CompleteCheckpointCodec: @unchecked Sendable { checkpoint: CBv2RecurrentCheckpoint, kv: [(keys: MLXArray, values: MLXArray, offset: Int)?], tokens: [Int], cacheSalt: String?, metadataPermit: CBv2CheckpointManifestMemory.Permit ) throws -> CBv2CompleteCheckpointExport { - let descriptors = try tensorDescriptors(position: checkpoint.position, qwen4: qwen4Descriptors(checkpoint), - mediaTargetOnly: checkpoint.mediaTargetOnly) + let descriptors = try tensorDescriptors( + position: checkpoint.position, qwen4: qwen4Descriptors(checkpoint), + mediaTargetOnly: checkpoint.mediaTargetOnly) var arrays: [MLXArray] = [] for entry in kv { guard let entry, entry.offset >= checkpoint.position else { @@ -165,37 +256,68 @@ final class CBv2CompleteCheckpointCodec: @unchecked Sendable { else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } let manifest = CBv2CompleteCheckpointManifest( schemaVersion: CBv2CompleteCheckpointManifest.currentSchemaVersion, identity: identity, - backendLayout: backendLayout, position: checkpoint.position, chunkSize: checkpoint.chunkSize, - cacheSalt: cacheSalt, assistantCodecID: checkpoint.mediaTargetOnly ? nil : assistant?.prefixCheckpointCodecID, + backendLayout: backendLayout, position: checkpoint.position, + chunkSize: checkpoint.chunkSize, + cacheSalt: cacheSalt, + assistantCodecID: checkpoint.mediaTargetOnly ? nil : assistant?.prefixCheckpointCodecID, mediaIdentity: checkpoint.mediaIdentity, mediaTargetOnly: checkpoint.mediaTargetOnly, - metadata: .init(tokens: Array(tokens.prefix(checkpoint.position)), tensors: descriptors, permit: metadataPermit)) + metadata: .init( + tokens: Array(tokens.prefix(checkpoint.position)), tensors: descriptors, + permit: metadataPermit)) _ = try manifest.validateStructure() - return .init(manifest: manifest, arrays: arrays, usesProcessMemoryOwner: admission.hasProcessMemoryOwner) + return .init( + manifest: manifest, arrays: arrays, + usesProcessMemoryOwner: admission.hasProcessMemoryOwner) } func export( checkpoint: CBv2RecurrentCheckpoint, state: [CBv2SequenceKV?], tokens: [Int], cacheSalt: String? ) throws -> CBv2CompleteCheckpointExport { + if contiguousLayout != nil { + try validateContiguousRows(state, position: checkpoint.position, exactWindow: true) + return try exportContiguousV2( + checkpoint: checkpoint, kv: state.map { $0?.snapshot() }, + tokens: tokens, cacheSalt: cacheSalt, + retainedOwners: state.compactMap { $0.map { $0 as AnyObject } }) + } + guard !unsupportedAsymmetricGeometry else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } if pagedConfig != nil { - return try exportPaged(checkpoint: checkpoint, state: state, tokens: tokens, cacheSalt: cacheSalt) + return try exportPaged( + checkpoint: checkpoint, state: state, tokens: tokens, cacheSalt: cacheSalt) } - return try export(checkpoint: checkpoint, kv: state.map { $0?.snapshot() }, - tokens: tokens, cacheSalt: cacheSalt) + return try export( + checkpoint: checkpoint, kv: state.map { $0?.snapshot() }, + tokens: tokens, cacheSalt: cacheSalt) } func preparedState( - manifest: CBv2CompleteCheckpointManifest, arrays: [MLXArray], maximumSequenceLength: Int + manifest: CBv2CompleteCheckpointManifest, arrays: [MLXArray], maximumSequenceLength: Int, + contiguousBacking: CBv2ContiguousCheckpointBacking? = nil ) throws -> CBv2PreparedCompleteCheckpoint { + if contiguousLayout != nil { + guard let contiguousBacking else { + throw CBv2CompleteCheckpointError.incompleteTransfer + } + return try preparedContiguousV2( + manifest: manifest, arrays: arrays, + maximumSequenceLength: maximumSequenceLength, backing: contiguousBacking) + } + guard !unsupportedAsymmetricGeometry else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } guard pagedConfig == nil, arrays.count == manifest.tensors.count else { throw CBv2CompleteCheckpointError.incompleteTransfer } var rows: [CBv2SequenceKV?] = [] for (index, kind) in layerKinds.enumerated() { - rows.append(try CBv2FullSequenceKV( - restoredKeys: arrays[index * 2], restoredValues: arrays[index * 2 + 1], - offset: manifest.position, maxLength: maximumSequenceLength, - kvHeads: kind.kvHeads, headDim: kind.headDim)) + rows.append( + try CBv2FullSequenceKV( + restoredKeys: arrays[index * 2], restoredValues: arrays[index * 2 + 1], + offset: manifest.position, maxLength: maximumSequenceLength, + kvHeads: kind.kvHeads, headDim: kind.headDim)) } let checkpoint = try recurrentCheckpoint( manifest: manifest, auxiliary: Array(arrays.dropFirst(targetTensorCount))) @@ -209,24 +331,37 @@ final class CBv2CompleteCheckpointCodec: @unchecked Sendable { manifest: CBv2CompleteCheckpointManifest, auxiliary: [MLXArray] ) throws -> CBv2RecurrentCheckpoint { defer { withExtendedLifetime(manifest) {} } - guard recurrentSpec != nil else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + guard + recurrentSpec != nil + || ((contiguousLayout != nil || isNativePagedHistorical) + && assistant is any CBv2HistoricalMTPPrefixCheckpointCoding) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } let descriptors = Array(manifest.tensors.dropFirst(targetTensorCount)) - guard manifest.tensors == (try tensorDescriptors(position: manifest.position, qwen4: qwen4Descriptors(in: manifest), - mediaTargetOnly: manifest.mediaTargetOnly)), - auxiliary.count == descriptors.count, - zip(auxiliary, descriptors).allSatisfy({ $0.0.shape == $0.1.shape && $0.0.dtype == $0.1.dtype.mlxDType }) + guard + manifest.tensors + == (try tensorDescriptors( + position: manifest.position, qwen4: qwen4Descriptors(in: manifest), + mediaTargetOnly: manifest.mediaTargetOnly)), + auxiliary.count == descriptors.count, + zip(auxiliary, descriptors).allSatisfy({ + $0.0.shape == $0.1.shape && $0.0.dtype == $0.1.dtype.mlxDType + }) else { throw CBv2CompleteCheckpointError.incompleteTransfer } var layers: [Int: CBv2RecurrentLayerState] = [:] - var cursor = 0, checkpointBytes = 0 + var cursor = 0 + var checkpointBytes = 0 for spec in recurrentSpec?.layers ?? [] { - layers[spec.modelLayerIndex] = .init(conv: auxiliary[cursor], ssm: auxiliary[cursor + 1]) + layers[spec.modelLayerIndex] = .init( + conv: auxiliary[cursor], ssm: auxiliary[cursor + 1]) checkpointBytes += auxiliary[cursor].nbytes + auxiliary[cursor + 1].nbytes cursor += 2 } var qwen4Snapshots: [Int: CBv2Qwen4IndexerSnapshot] = [:] for geometry in qwen4Geometries { let side = qwen4Descriptors(in: manifest).filter { $0.layer == geometry.layer } - let values = Array(auxiliary[cursor.. Int { defer { withExtendedLifetime(metadata) {} } guard schemaVersion == Self.currentSchemaVersion, identity.isValid, - (backendLayout == Self.layout || backendLayout == Self.pagedLayout - || backendLayout == Self.historicalAttentionLayout || backendLayout == Self.diffusionBlockLayout), - (backendLayout == Self.historicalAttentionLayout + backendLayout == Self.layout || backendLayout == Self.pagedLayout + || backendLayout == Self.historicalAttentionLayout + || backendLayout == Self.diffusionBlockLayout + || backendLayout == Self.contiguousAsymmetricLayout + || backendLayout == Self.contiguousAsymmetricMTPLayout + || backendLayout == Self.pagedAsymmetricLayout + || backendLayout == Self.pagedAsymmetricMTPLayout, + backendLayout == Self.historicalAttentionLayout + || backendLayout == Self.contiguousAsymmetricLayout + || backendLayout == Self.contiguousAsymmetricMTPLayout + || backendLayout == Self.pagedAsymmetricLayout + || backendLayout == Self.pagedAsymmetricMTPLayout ? attentionLayers?.isEmpty == false && attentionLayers!.count <= 2048 - : attentionLayers == nil), + : attentionLayers == nil, position > 1, // A chunk of 1 would put every position on a chunk end; only the // diffusion block layout, which sits on its media identity rather // than on a chunk, may record one. - (backendLayout == Self.diffusionBlockLayout ? chunkSize > 0 : chunkSize > 1), + backendLayout == Self.diffusionBlockLayout ? chunkSize > 0 : chunkSize > 1, // Historical and diffusion layouts sit on their recorded stride; // a recurrent checkpoint sits on any 256-token boundary (its // `chunkSize` is the chunk that ended there, provenance only) or, // for files written under the earlier uniform-chunk rule, on a // multiple of that chunk. - ((backendLayout == Self.diffusionBlockLayout && mediaIdentity != nil) + (backendLayout == Self.diffusionBlockLayout && mediaIdentity != nil) || position % chunkSize == 0 || ((backendLayout == Self.layout || backendLayout == Self.pagedLayout) - && position % CBv2RecurrentCheckpointGeometry.recurrentCheckpointStrideTokens == 0)), + && position % CBv2RecurrentCheckpointGeometry.recurrentCheckpointStrideTokens + == 0), prefixTokens.count == position, position <= Self.maximumEncodedBytes / 2, prefixTokens.allSatisfy({ $0 >= 0 && $0 <= Int(Int32.max) }), @@ -214,6 +233,8 @@ public struct CBv2CompleteCheckpointManifest: Codable, Sendable, Equatable { } var total = 0 var roles = Set() + var keyDescriptors: [Int: CBv2CheckpointTensorDescriptor] = [:] + var valueDescriptors: [Int: CBv2CheckpointTensorDescriptor] = [:] for tensor in tensors { try tensor.validate() guard roles.insert("\(tensor.role.rawValue):\(tensor.layer ?? -1)").inserted else { @@ -222,6 +243,58 @@ public struct CBv2CompleteCheckpointManifest: Codable, Sendable, Equatable { let (next, overflow) = total.addingReportingOverflow(tensor.byteCount) guard !overflow else { throw CBv2CompleteCheckpointError.invalidManifest } total = next + let layer = tensor.layer ?? -1 + if tensor.role == .keys { keyDescriptors[layer] = tensor } + if tensor.role == .values { valueDescriptors[layer] = tensor } + } + if backendLayout == Self.contiguousAsymmetricLayout + || backendLayout == Self.contiguousAsymmetricMTPLayout + || backendLayout == Self.pagedAsymmetricLayout + || backendLayout == Self.pagedAsymmetricMTPLayout + { + let includesAssistant = + backendLayout == Self.contiguousAsymmetricMTPLayout + || backendLayout == Self.pagedAsymmetricMTPLayout + guard includesAssistant ? assistantCodecID?.isEmpty == false : assistantCodecID == nil, + mediaIdentity == nil, !mediaTargetOnly, + let layers = attentionLayers, + layers.contains(where: { $0.headDim != $0.valueHeadDim }) + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + let kinds = layers.enumerated().map { index, layer in + CBv2LayerKind( + attention: layer.window.map { .slidingWindow($0) } ?? .full, + sharesKVWithLayer: layer.owner == index ? nil : layer.owner, + hasSinks: layer.hasSinks, + headDim: layer.headDim, valueHeadDim: layer.valueHeadDim, + kvHeads: layer.kvHeads, queryHeads: layer.queryHeads, + modelLayerIndex: layer.modelLayer) + } + let layout = try CBv2HistoricalAttentionLayout( + layerKinds: kinds, + dtypes: layers.map { $0.dtype.mlxDType }, allowAsymmetric: true) + let target = try layout.tensorDescriptors(position: position) + guard layout.layers == layers, tensors.prefix(target.count).elementsEqual(target) else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + if includesAssistant { + try validateHistoricalAssistantStructure(targetTensorCount: target.count) + } else if tensors != target { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + return total + } + guard attentionLayers?.allSatisfy({ $0.headDim == $0.valueHeadDim }) ?? true else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + // Old persistent layouts continue to require equal K/V widths. + // Partial descriptor sets are used by metadata-only ownership probes. + // Complete model codecs independently require their exact tensor set. + for (layer, keys) in keyDescriptors { + if let values = valueDescriptors[layer], + keys.shape != values.shape || keys.dtype != values.dtype + { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } } return total } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointImportPlan.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointImportPlan.swift index 85bd67ca8e..866292f158 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointImportPlan.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointImportPlan.swift @@ -1,23 +1,57 @@ import Foundation import MLX -/// Plan without native tensor allocation. Its retained manifest has a host -/// metadata owner. With a shared process owner, native destination and -/// scratch belong to Admission; the provider reserves its host I/O only. Without -/// one, the provider also maintains its historical global envelope. The callback -/// remains attached until cancellation or transfer to charged request storage. +/// Mutable only at explicit transfer/retirement boundaries. A native loan +/// owns this box before a public plan can retain its codec/assistant; clearing +/// a public handle therefore never relies on incidental ARC release order. +final class CBv2CompleteCheckpointCodecOwner: @unchecked Sendable { + private let lock = NSLock() + private var value: CBv2CompleteCheckpointCodec? + init(_ codec: CBv2CompleteCheckpointCodec) { value = codec } + func borrow() throws -> CBv2CompleteCheckpointCodec { + try lock.withLock { + guard let value else { throw CBv2CompleteCheckpointError.closed } + return value + } + } + func dropNativeReferences() { + let retired = lock.withLock { + let old = value + value = nil + return old + } + withExtendedLifetime(retired) {} // release outside the box lock + } +} + +/// A native plan owns a counted loan from public creation, then moves the +/// same work into Import. Retained consumed/closed native plan aliases contain +/// metadata only. Untracked plans preserve their prior multi-allocation API. public final class CBv2CompleteCheckpointImportPlan: @unchecked Sendable { public let manifest: CBv2CompleteCheckpointManifest public let maximumSequenceLength: Int + /// Native target plus native auxiliary destinations ONLY. public let nativeDestinationBytes: Int + public let nativeTargetBytes: Int + public let nativeAuxiliaryBytes: Int + public let checkpointHostBytes: Int public let usesProcessMemoryOwner: Bool let pagedStoragePlan: CBv2PagedCheckpointStoragePlan? let auxiliaryBytes: Int public let scratchBytes: Int - let codec: CBv2CompleteCheckpointCodec + private let stateLock = NSLock() + private var legacyCodec: CBv2CompleteCheckpointCodec? + private var nativeCodecOwner: CBv2CompleteCheckpointCodecOwner? + private var nativeWork: CBv2NativeCompletePrefixWork? + private var nativeBound = false + private var nativeMovedOrClosed = false + // Legacy internal consumers only. Native consumers must take the actual + // one-shot owner/work pair before borrowing a codec. + var codec: CBv2CompleteCheckpointCodec { + precondition(!nativeBound, "native plan codec requires its actual counted owner") + return legacyCodec! + } private(set) var destinationShapes: [[Int]] - /// Internal deterministic allocation-fault seam. Production uses scoped - /// MLX error collection; no failed allocation reaches a raw pointer read. var evaluateDestinations: ([MLXArray]) throws -> Void = { arrays in try withError { eval(arrays) } } @@ -26,65 +60,188 @@ public final class CBv2CompleteCheckpointImportPlan: @unchecked Sendable { codec: CBv2CompleteCheckpointCodec, manifest: CBv2CompleteCheckpointManifest, maximumSequenceLength: Int ) throws { - self.codec = codec + legacyCodec = codec self.manifest = try manifest.owningMetadata(admission: codec.admission) self.maximumSequenceLength = maximumSequenceLength - self.usesProcessMemoryOwner = codec.admission.hasProcessMemoryOwner + usesProcessMemoryOwner = codec.admission.hasProcessMemoryOwner let paged = try codec.pagedConfig.map { - try CBv2PagedCheckpointStoragePlan(layerKinds: codec.layerKinds, config: $0, position: manifest.position, - historicalLayout: codec.historicalLayout, maximumSequenceLength: maximumSequenceLength) + try CBv2PagedCheckpointStoragePlan( + layerKinds: codec.layerKinds, config: $0, position: manifest.position, + historicalLayout: codec.historicalLayout, + maximumSequenceLength: maximumSequenceLength) } - self.pagedStoragePlan = paged - let destinations = paged == nil ? manifest.tensors + pagedStoragePlan = paged + let destinations = + paged == nil + ? manifest.tensors : Array(manifest.tensors.dropFirst(codec.targetTensorCount)) var shapes: [[Int]] = [] - var bytes = 0, initializationScratch = 0 + var target = 0 + var auxiliary = 0 + var initializationScratch = 0 for tensor in destinations { + let isTarget = tensor.role == .keys || tensor.role == .values var shape = tensor.shape - if tensor.role == .keys || tensor.role == .values { shape[2] = maximumSequenceLength } - let count = try CBv2CheckpointTensorDescriptor.checkedByteCount(shape: shape, dtype: tensor.dtype.mlxDType) - bytes = try CBv2CheckpointAllocationFootprint.add(bytes, CBv2CheckpointAllocationFootprint.bound(count)) - // MLX zeros constructs one same-dtype scalar before its Full - // destination. These batch-created scalars coexist until eval. + if isTarget { + shape[2] = + codec.contiguousLayout?.layers.first(where: { + $0.modelLayer == tensor.layer + })?.window ?? maximumSequenceLength + } + let count = try CBv2CheckpointTensorDescriptor.checkedByteCount( + shape: shape, dtype: tensor.dtype.mlxDType) + let bound = try CBv2CheckpointAllocationFootprint.bound(count) + if isTarget { + target = try CBv2CheckpointAllocationFootprint.add(target, bound) + } else { + auxiliary = try CBv2CheckpointAllocationFootprint.add(auxiliary, bound) + } initializationScratch = try CBv2CheckpointAllocationFootprint.add( - initializationScratch, CBv2CheckpointAllocationFootprint.bound(tensor.dtype.mlxDType.size)) + initializationScratch, + CBv2CheckpointAllocationFootprint.bound(tensor.dtype.mlxDType.size)) shapes.append(shape) } - self.destinationShapes = shapes - // Native page buffers are initialized and evaluated sequentially, - // before constructing the auxiliary batch. Only one page-fill scalar - // overlaps at a time; provider Data has its own I/O owner. + destinationShapes = shapes var pageInitializationScratch = 0 for group in paged?.groups ?? [] { - pageInitializationScratch = max(pageInitializationScratch, + pageInitializationScratch = max( + pageInitializationScratch, try CBv2CheckpointAllocationFootprint.bound(group.key.dtype.size)) } - self.scratchBytes = max(initializationScratch, pageInitializationScratch) - self.auxiliaryBytes = paged == nil ? 0 : bytes - let (total, overflow) = bytes.addingReportingOverflow(paged?.nativeBytes ?? 0) - guard !overflow else { throw CBv2CompleteCheckpointError.invalidManifest } - self.nativeDestinationBytes = total + scratchBytes = max(initializationScratch, pageInitializationScratch) + let totalTarget = try CBv2CheckpointAllocationFootprint.add(target, paged?.nativeBytes ?? 0) + nativeTargetBytes = totalTarget + nativeAuxiliaryBytes = auxiliary + nativeDestinationBytes = try CBv2CheckpointAllocationFootprint.add(totalTarget, auxiliary) + // The native complete-MTP schema is distinct from target-only v2. + // This is retained host witness capacity, never measured native bytes. + var retainedHostBytes = 0 + if manifest.backendLayout == CBv2CompleteCheckpointManifest.contiguousAsymmetricMTPLayout + || manifest.backendLayout == CBv2CompleteCheckpointManifest.pagedAsymmetricMTPLayout + { + let (tokens, overflow) = manifest.position.multipliedReportingOverflow(by: 8) + guard !overflow else { throw CBv2CompleteCheckpointError.invalidManifest } + retainedHostBytes = try CBv2CheckpointAllocationFootprint.add(tokens, 64 << 10) + } + if codec.isNativePagedHistorical, let paged { + // Private segment/page maps and owner/control entries. This + // conservative host allowance creates no map, native credit or + // second owner; it stays on the original stage through retirement. + let pages = try paged.layers.reduce(0) { + try CBv2CheckpointAllocationFootprint.add($0, $1.pageCount) + } + guard let pageBytes = CBv2KVGeometry.multiply(pages, 512) else { + throw CBv2CompleteCheckpointError.invalidManifest + } + retainedHostBytes = try CBv2CheckpointAllocationFootprint.add( + retainedHostBytes, + CBv2CheckpointAllocationFootprint.add( + 64 << 10, + CBv2CheckpointAllocationFootprint.add(pageBytes, paged.layers.count * 512))) + } + checkpointHostBytes = retainedHostBytes + auxiliaryBytes = auxiliary + } + + /// Engine starts the real loan BEFORE codec.plan(), then binds here before + /// returning the public plan. No closure supplied by a provider can mint it. + func bindNativeCompletePrefixWork( + _ work: CBv2NativeCompletePrefixWork, + store: any CBv2CompletePrefixCache, request: CBv2Request, engineID: UUID + ) throws { + guard let codec = stateLock.withLock({ legacyCodec }), + work.purpose == .importing, work.codecIdentity == manifest.identity, + (codec.contiguousLayout != nil && pagedStoragePlan == nil) + || (codec.isNativePagedHistorical && pagedStoragePlan != nil) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try work.validate(store: store, codec: codec, request: request, engineID: engineID) + let owner = CBv2CompleteCheckpointCodecOwner(codec) + try work.retain(owners: [owner]) + try stateLock.withLock { + guard !nativeBound, !nativeMovedOrClosed, legacyCodec === codec else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + nativeBound = true + nativeCodecOwner = owner + nativeWork = work + legacyCodec = nil + } } - public func allocate(onRelease: @escaping @Sendable () -> Void) throws -> CBv2CompleteCheckpointImport { + public func allocate(onRelease: @escaping @Sendable () -> Void) throws + -> CBv2CompleteCheckpointImport + { let providerReservation = CBv2CheckpointReservation(onRelease: onRelease) + let native: + ( + CBv2CompleteCheckpointCodecOwner, CBv2NativeCompletePrefixWork, + ([MLXArray]) throws -> Void + )? do { - let scratch = try CBv2CheckpointAllocationFootprint.add(scratchBytes, - usesProcessMemoryOwner ? 0 : CBv2CompleteCheckpointManifest.maximumProviderScratchBytes) + native = try stateLock.withLock { + guard nativeBound else { return nil } + guard !nativeMovedOrClosed, let owner = nativeCodecOwner, let work = nativeWork + else { + throw CBv2CompleteCheckpointError.closed + } + let evaluate = evaluateDestinations + nativeMovedOrClosed = true + nativeCodecOwner = nil + nativeWork = nil + // A retained consumed plan must not keep a test evaluator's + // captures or any model/codecs behind the transferred loan. + evaluateDestinations = { arrays in try withError { eval(arrays) } } + return (owner, work, evaluate) + } + } catch { + providerReservation.release() + throw error + } + if let native { + // This initializer registers an actual owner box on work BEFORE + // reserve/allocate/eval, including every late-returned root. + return try CBv2CompleteCheckpointImport( + plan: self, nativeCodecOwner: native.0, + nativeWork: native.1, evaluate: native.2, reservation: providerReservation) + } + + // Original untracked allocation path. Native handling never falls + // through to this destructor/refund behavior. + do { + let codec = self.codec + let scratch = try CBv2CheckpointAllocationFootprint.add( + scratchBytes, + usesProcessMemoryOwner + ? 0 : CBv2CompleteCheckpointManifest.maximumProviderScratchBytes) + if codec.contiguousLayout != nil { + let aux = try CBv2CheckpointAllocationFootprint.add( + nativeAuxiliaryBytes, checkpointHostBytes) + let stage = try codec.admission.reserveCheckpointStage( + targetBytes: nativeTargetBytes, + auxiliaryBytes: aux, scratchBytes: scratch) + do { + return try .init( + plan: self, reservation: providerReservation, stageLease: stage) + } catch { + stage.closeAfterDroppingOwners() + throw error + } + } if let pagedStoragePlan { let stage = try codec.admission.reserveCheckpointStage( - targetBytes: pagedStoragePlan.nativeBytes, auxiliaryBytes: auxiliaryBytes, scratchBytes: scratch) + targetBytes: pagedStoragePlan.nativeBytes, auxiliaryBytes: auxiliaryBytes, + scratchBytes: scratch) do { - return try .init(plan: self, reservation: providerReservation, stageLease: stage) + return try .init( + plan: self, reservation: providerReservation, stageLease: stage) } catch { - // Failed initializer locals and segment owners have - // unwound before this native charge is returned. stage.closeAfterDroppingOwners() throw error } } - let (bytes, overflow) = nativeDestinationBytes.addingReportingOverflow(scratch) - guard !overflow else { throw CBv2CompleteCheckpointError.invalidManifest } + let bytes = try CBv2CheckpointAllocationFootprint.add(nativeDestinationBytes, scratch) let engineReservation = try codec.admission.reserveTransient(bytes: bytes) let reservation = CBv2CheckpointReservation { engineReservation.release() @@ -97,9 +254,27 @@ public final class CBv2CompleteCheckpointImportPlan: @unchecked Sendable { } } + /// Explicitly abandon a deferred native plan. Untracked behavior is + /// unchanged. A closed alias remains readable metadata, never a live codec. + public func close() { + let retired = stateLock.withLock { + () -> (CBv2CompleteCheckpointCodecOwner, CBv2NativeCompletePrefixWork)? in + guard nativeBound, !nativeMovedOrClosed, let owner = nativeCodecOwner, + let work = nativeWork + else { return nil } + nativeMovedOrClosed = true + nativeCodecOwner = nil + nativeWork = nil + evaluateDestinations = { arrays in try withError { eval(arrays) } } + return (owner, work) + } + if let (owner, work) = retired { + work.finishAfterDroppingConsumers { owner.dropNativeReferences() } + } + } + deinit { - // Auxiliary shapes may alias descriptor arrays. Retire those aliases - // before automatic destruction can release the manifest's permit. + close() destinationShapes.removeAll(keepingCapacity: false) } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTensorSource.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTensorSource.swift index 341618ea1b..f6278031c0 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTensorSource.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTensorSource.swift @@ -20,16 +20,20 @@ enum CBv2CompleteCheckpointTensorSource { } func readSegment( - descriptor: CBv2CheckpointTensorDescriptor, byteOffset: Int, maximumBytes: Int + descriptor: CBv2CheckpointTensorDescriptor, byteOffset: Int, maximumBytes: Int, + nativeWork: CBv2NativeCompletePrefixWork? = nil ) throws -> Data { - guard maximumBytes > 0, maximumBytes <= CBv2CompleteCheckpointManifest.maximumSegmentBytes else { + guard maximumBytes > 0, maximumBytes <= CBv2CompleteCheckpointManifest.maximumSegmentBytes + else { throw CBv2CompleteCheckpointError.invalidSegment } if case .historicalWindow(let source) = self { - return try source.readSegment(byteOffset: byteOffset, maximumBytes: maximumBytes) + return try source.readSegment( + byteOffset: byteOffset, maximumBytes: maximumBytes, nativeWork: nativeWork) } if case .paged(let source) = self { - return try source.readSegment(byteOffset: byteOffset, maximumBytes: maximumBytes) + return try source.readSegment( + byteOffset: byteOffset, maximumBytes: maximumBytes, nativeWork: nativeWork) } guard case .array(let array) = self else { throw CBv2CompleteCheckpointError.closed } let itemSize = descriptor.dtype.mlxDType.size @@ -38,8 +42,28 @@ enum CBv2CompleteCheckpointTensorSource { } let count = min(maximumBytes - maximumBytes % itemSize, descriptor.byteCount - byteOffset) guard count > 0 else { throw CBv2CompleteCheckpointError.invalidSegment } - try withError { eval(array) } - guard let pointer = mlx_array_data_uint8(array.ctx), let nativeStrides = mlx_array_strides(array.ctx) else { + if let nativeWork { + guard nativeWork.purpose == .publication else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try nativeWork.captureCurrentStreams() + try nativeWork.retain(arrays: [array]) + do { + try withError { fault in + eval(array) + try fault.check() + } + } catch { + nativeWork.requiredCompletionFailed() + throw error + } + } else { + try withError { eval(array) } + } + guard let pointer = mlx_array_data_uint8(array.ctx), + let nativeStrides = mlx_array_strides(array.ctx) + else { + nativeWork?.requiredCompletionFailed() throw CBv2CompleteCheckpointError.allocationFailed } let strides = descriptor.shape.indices.map { Int(nativeStrides[$0]) } @@ -53,6 +77,10 @@ enum CBv2CompleteCheckpointTensorSource { from: UnsafeRawPointer(pointer).advanced(by: physicalOffset), byteCount: length) } } + // This helper allocates provider Data only, not a native packing + // temporary. The source array remains a whole-operation root. Do not + // remove donor roots via retireReadbackTemporaries([]) or add a useless + // per-segment fence; any future actual pack array must use that seam. return result } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTransfer.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTransfer.swift index d3c0cdf6f1..b72477a23e 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTransfer.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTransfer.swift @@ -11,26 +11,68 @@ public final class CBv2CompleteCheckpointExport: @unchecked Sendable { public let usesProcessMemoryOwner: Bool private let lock = NSLock() private var sources: [CBv2CompleteCheckpointTensorSource]? + private var retainedOwners: [AnyObject] + private weak var nativeWork: CBv2NativeCompletePrefixWork? + private var nativeBound = false - convenience init(manifest: CBv2CompleteCheckpointManifest, arrays: [MLXArray], - usesProcessMemoryOwner: Bool = false) { - self.init(manifest: manifest, sources: arrays.map { .array($0) }, - usesProcessMemoryOwner: usesProcessMemoryOwner) + convenience init( + manifest: CBv2CompleteCheckpointManifest, arrays: [MLXArray], + usesProcessMemoryOwner: Bool = false, retainedOwners: [AnyObject] = [] + ) { + self.init( + manifest: manifest, sources: arrays.map { .array($0) }, + usesProcessMemoryOwner: usesProcessMemoryOwner, retainedOwners: retainedOwners) } - init(manifest: CBv2CompleteCheckpointManifest, sources: [CBv2CompleteCheckpointTensorSource], - usesProcessMemoryOwner: Bool = false) { + init( + manifest: CBv2CompleteCheckpointManifest, sources: [CBv2CompleteCheckpointTensorSource], + usesProcessMemoryOwner: Bool = false, retainedOwners: [AnyObject] = [] + ) { self.manifest = manifest self.sources = sources self.usesProcessMemoryOwner = usesProcessMemoryOwner + self.retainedOwners = retainedOwners + } + + func bindNativeCompletePrefixWork(_ work: CBv2NativeCompletePrefixWork) throws { + try lock.withLock { + guard !nativeBound, let sources, work.purpose == .publication, + manifest.identity == work.codecIdentity + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + // Non-array sources need the actual issued page-native codec. + // Their immutable map/window owners are retained independently of + // this public closeable wrapper before any readback can run. + var arrays: [MLXArray] = [] + for source in sources { + switch source { + case .array(let array): arrays.append(array) + case .paged(let value): try value.retainForNativeExport(work) + case .historicalWindow(let value): try value.retainForNativeExport(work) + } + } + try work.retain(arrays: arrays, owners: retainedOwners) + nativeWork = work + nativeBound = true + } } public func readSegment(tensorIndex: Int, byteOffset: Int, maximumBytes: Int) throws -> Data { try lock.withLock { guard let sources else { throw CBv2CompleteCheckpointError.closed } - guard sources.indices.contains(tensorIndex) else { throw CBv2CompleteCheckpointError.invalidSegment } + guard sources.indices.contains(tensorIndex) else { + throw CBv2CompleteCheckpointError.invalidSegment + } + if nativeBound { + guard let nativeWork else { throw CBv2CompleteCheckpointError.closed } + return try sources[tensorIndex].readSegment( + descriptor: manifest.tensors[tensorIndex], + byteOffset: byteOffset, maximumBytes: maximumBytes, nativeWork: nativeWork) + } return try sources[tensorIndex].readSegment( - descriptor: manifest.tensors[tensorIndex], byteOffset: byteOffset, maximumBytes: maximumBytes) + descriptor: manifest.tensors[tensorIndex], byteOffset: byteOffset, + maximumBytes: maximumBytes) } } @@ -38,8 +80,245 @@ public final class CBv2CompleteCheckpointExport: @unchecked Sendable { lock.withLock { sources?.forEach { $0.close() } sources = nil + retainedOwners.removeAll() + nativeWork = nil // shared batch work is finished by Capture, never Export.close + } + } + deinit { close() } +} + +/// One actual native transfer payload. Work retains this box BEFORE any +/// reservation/allocation. Neither a failed initializer nor public close can +/// deinitialize its native roots or callbacks ahead of required completion. +final class CBv2NativeCompleteCheckpointImportOwner: @unchecked Sendable { + let plan: CBv2CompleteCheckpointImportPlan + let codecOwner: CBv2CompleteCheckpointCodecOwner + var arrays: [MLXArray] = [] + var backing: CBv2ContiguousCheckpointBacking? + var pagedStorage: CBv2PagedCheckpointStorage? + var stageLease: CBv2CheckpointStageLease? + var prepared: CBv2PreparedCompleteCheckpoint? + var reservation: CBv2CheckpointReservation? + var evaluate: (([MLXArray]) throws -> Void)? + var tensorIndex = 0 + var byteOffset = 0 + var nativeDestinationBytes = 0 + + init( + plan: CBv2CompleteCheckpointImportPlan, codecOwner: CBv2CompleteCheckpointCodecOwner, + reservation: CBv2CheckpointReservation, evaluate: @escaping ([MLXArray]) throws -> Void + ) { + self.plan = plan + self.codecOwner = codecOwner + self.reservation = reservation + self.evaluate = evaluate + } + + func allocate(work: CBv2NativeCompletePrefixWork) throws { + try work.captureCurrentStreams() + let codec = try codecOwner.borrow() + guard + (codec.contiguousLayout != nil && plan.pagedStoragePlan == nil) + || (codec.isNativePagedHistorical && plan.pagedStoragePlan != nil) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let scratch = try CBv2CheckpointAllocationFootprint.add( + plan.scratchBytes, + plan.usesProcessMemoryOwner + ? 0 : CBv2CompleteCheckpointManifest.maximumProviderScratchBytes) + let auxiliary = try CBv2CheckpointAllocationFootprint.add( + plan.nativeAuxiliaryBytes, plan.checkpointHostBytes) + let lease = try codec.admission.reserveCheckpointStage( + targetBytes: plan.nativeTargetBytes, + auxiliaryBytes: auxiliary, scratchBytes: scratch) + stageLease = lease + try work.retain(owners: [lease]) + let stream = StreamOrDevice.default + do { + try withError { fault in + if let storagePlan = plan.pagedStoragePlan { + guard stream.stream == MLX.Stream.gpu else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + pagedStorage = try .init( + plan: storagePlan, + evaluate: { [self] array in + try work.retain(arrays: [array]) + guard let evaluate else { throw CBv2CompleteCheckpointError.closed } + try evaluate([array]) + }, admission: codec.admission, nativeWork: work) + if let pagedStorage { try work.retain(owners: [pagedStorage]) } + } + let descriptors = + plan.pagedStoragePlan == nil + ? plan.manifest.tensors + : Array(plan.manifest.tensors.dropFirst(codec.targetTensorCount)) + for (shape, descriptor) in zip(plan.destinationShapes, descriptors) { + let value = MLXArray.zeros( + shape, dtype: descriptor.dtype.mlxDType, stream: stream) + arrays.append(value) + try work.retain(arrays: [value]) // includes a late value after first-winner failure + try fault.check() + } + guard let evaluate else { throw CBv2CompleteCheckpointError.closed } + try evaluate(arrays) + try fault.check() + } + try work.fenceForProtectedPromotion() + } catch { + // This is required native construction/evaluation/completion, not + // a later metadata/accounting refusal. Never retry into health. + work.requiredCompletionFailed() + throw error + } + guard arrays.allSatisfy({ mlx_array_data_uint8($0.ctx) != nil }) else { + work.requiredCompletionFailed() + throw CBv2CompleteCheckpointError.allocationFailed + } + let footprint = try CBv2CheckpointAllocationFootprint.freshBytes(arrays) + nativeDestinationBytes = try CBv2CheckpointAllocationFootprint.add( + footprint.actual, pagedStorage?.allocatedBytes ?? 0) // native only + if plan.pagedStoragePlan == nil { + backing = try .init( + lease: lease, codec: codec, + arrays: Array(arrays.prefix(codec.targetTensorCount)), + expectedBound: plan.nativeTargetBytes, + auxiliaryArrays: Array(arrays.dropFirst(codec.targetTensorCount)), + hostBytes: plan.checkpointHostBytes, position: plan.manifest.position) + if let backing { try work.retain(owners: [backing]) } + } + } + + func append( + tensorIndex: Int, byteOffset: Int, data: Data, + work: CBv2NativeCompletePrefixWork + ) throws { + try work.captureCurrentStreams() + guard tensorIndex == self.tensorIndex, byteOffset == self.byteOffset, + plan.manifest.tensors.indices.contains(tensorIndex), !data.isEmpty, + data.count <= CBv2CompleteCheckpointManifest.maximumSegmentBytes + else { + throw CBv2CompleteCheckpointError.invalidSegment + } + let descriptor = plan.manifest.tensors[tensorIndex] + let size = descriptor.dtype.mlxDType.size + guard data.count % size == 0, data.count <= descriptor.byteCount - byteOffset else { + throw CBv2CompleteCheckpointError.invalidSegment + } + let codec = try codecOwner.borrow() + let isTarget = descriptor.role == .keys || descriptor.role == .values + if let pagedStorage, isTarget { + try pagedStorage.append( + layerIndex: tensorIndex / 2, values: descriptor.role == .values, + byteOffset: byteOffset, data: data) + self.byteOffset += data.count + if self.byteOffset == descriptor.byteCount { + self.tensorIndex += 1 + self.byteOffset = 0 + } + return + } + let arrayIndex = pagedStorage == nil ? tensorIndex : tensorIndex - codec.targetTensorCount + guard arrays.indices.contains(arrayIndex), + let pointer = mlx_array_data_uint8(arrays[arrayIndex].ctx) + else { + work.requiredCompletionFailed() + throw CBv2CompleteCheckpointError.allocationFailed + } + let ring = + isTarget + ? codec.contiguousLayout?.layers.first { + $0.modelLayer == descriptor.layer && $0.window != nil + } : nil + let destination = UnsafeMutableRawPointer(mutating: pointer) + let strides = CBv2CheckpointByteLayout.contiguousStrides(plan.destinationShapes[arrayIndex]) + data.withUnsafeBytes { source in + if let ring, let window = ring.window { + CBv2CheckpointByteLayout.copyRing( + shape: descriptor.shape, window: window, + firstPosition: ring.tokenStart(at: plan.manifest.position), itemSize: size, + byteOffset: byteOffset, count: data.count + ) { physical, packed, length in + destination.advanced(by: physical).copyMemory( + from: source.baseAddress!.advanced(by: packed), byteCount: length) + } + } else { + CBv2CheckpointByteLayout.copy( + shape: descriptor.shape, strides: strides, itemSize: size, + byteOffset: byteOffset, count: data.count + ) { physical, packed, length in + destination.advanced(by: physical).copyMemory( + from: source.baseAddress!.advanced(by: packed), byteCount: length) + } + } + } + self.byteOffset += data.count + if self.byteOffset == descriptor.byteCount { + self.tensorIndex += 1 + self.byteOffset = 0 + } + } + + func prepare(work: CBv2NativeCompletePrefixWork) throws { + guard tensorIndex == plan.manifest.tensors.count, byteOffset == 0 else { + throw CBv2CompleteCheckpointError.incompleteTransfer + } + try work.captureCurrentStreams() + do { + let codec = try codecOwner.borrow() + try withError { fault in + if let pagedStorage, let stageLease { + let frame = try CBv2PagedCheckpointFrame( + storage: pagedStorage, auxiliary: arrays, + lease: stageLease, hostBytes: plan.checkpointHostBytes) + prepared = .init(pagedFrame: frame) + if codec.assistant == nil { + prepared?.checkpoint = .init( + position: plan.manifest.position, + chunkSize: plan.manifest.chunkSize, layers: [:], byteCount: 0) + } else { + prepared?.checkpoint = try codec.recurrentCheckpoint( + manifest: plan.manifest, auxiliary: arrays) + } + } else { + prepared = try codec.preparedState( + manifest: plan.manifest, arrays: arrays, + maximumSequenceLength: plan.maximumSequenceLength, + contiguousBacking: backing) + } + if let prepared { try work.retain(owners: [prepared]) } + try fault.check() + } + try work.fenceForProtectedPromotion() + } catch { + if error is MLXError { work.requiredCompletionFailed() } + throw error } } + + /// Invoked ONLY by work's queued post-completion callback. Mutate the + /// actual shared box, so retained closed public wrappers keep no model or + /// native state merely because ARC chose a later destruction point. + func retireAfterCompletion() throws { + // The paged suffix operation has its own actual loan/coverage roots. + // Failure here keeps this whole callback/owner retained by prefix work. + try prepared?.nativePagedPreparation?.retireAfterCompletion() + arrays.removeAll(keepingCapacity: false) + pagedStorage?.close() + pagedStorage = nil + backing = nil + prepared?.clear() + prepared = nil + evaluate = nil + codecOwner.dropNativeReferences() + let lease = stageLease + stageLease = nil + let provider = reservation + reservation = nil + lease?.closeAfterDroppingOwners() + provider?.release() + } } /// Filled on one staging queue, before any array is exposed to GPU consumers. @@ -56,17 +335,47 @@ public final class CBv2CompleteCheckpointImport: @unchecked Sendable { private var tensorIndex = 0 private var byteOffset = 0 private var nativeDestinationBytes = 0 + private var contiguousBacking: CBv2ContiguousCheckpointBacking? + private var nativeOwner: CBv2NativeCompleteCheckpointImportOwner? + private var nativeWork: CBv2NativeCompletePrefixWork? - init(plan: CBv2CompleteCheckpointImportPlan, reservation: CBv2CheckpointReservation, - stageLease: CBv2CheckpointStageLease? = nil) throws { + init( + plan: CBv2CompleteCheckpointImportPlan, nativeCodecOwner: CBv2CompleteCheckpointCodecOwner, + nativeWork: CBv2NativeCompletePrefixWork, evaluate: @escaping ([MLXArray]) throws -> Void, + reservation: CBv2CheckpointReservation + ) throws { + self.plan = plan + let owner = CBv2NativeCompleteCheckpointImportOwner( + plan: plan, codecOwner: nativeCodecOwner, + reservation: reservation, evaluate: evaluate) + self.nativeOwner = owner + self.nativeWork = nativeWork + do { + try nativeWork.retain(owners: [owner]) + try owner.allocate(work: nativeWork) + } catch { + self.nativeOwner = nil + self.nativeWork = nil + nativeWork.finishAfterDroppingConsumers { try owner.retireAfterCompletion() } + throw error + } + } + + init( + plan: CBv2CompleteCheckpointImportPlan, reservation: CBv2CheckpointReservation, + stageLease: CBv2CheckpointStageLease? = nil + ) throws { self.plan = plan self.reservation = reservation self.stageLease = stageLease if let storagePlan = plan.pagedStoragePlan { pagedStorage = try CBv2PagedCheckpointStorage( - plan: storagePlan, evaluate: { try plan.evaluateDestinations([$0]) }, admission: plan.codec.admission) + plan: storagePlan, evaluate: { try plan.evaluateDestinations([$0]) }, + admission: plan.codec.admission) } - let destinationDescriptors = plan.pagedStoragePlan == nil ? plan.manifest.tensors + let destinationDescriptors = + plan.pagedStoragePlan == nil + ? plan.manifest.tensors : Array(plan.manifest.tensors.dropFirst(plan.codec.targetTensorCount)) let allocationStream = StreamOrDevice.default let destinations = try withError { fault in @@ -95,12 +404,26 @@ public final class CBv2CompleteCheckpointImport: @unchecked Sendable { let footprint = try CBv2CheckpointAllocationFootprint.freshBytes(destinations) nativeDestinationBytes = try CBv2CheckpointAllocationFootprint.add( footprint.actual, pagedStorage?.allocatedBytes ?? 0) + if plan.codec.contiguousLayout != nil { + guard let stageLease else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + contiguousBacking = try .init( + lease: stageLease, codec: plan.codec, + arrays: Array(destinations.prefix(plan.codec.targetTensorCount)), + expectedBound: plan.nativeTargetBytes, + auxiliaryArrays: Array(destinations.dropFirst(plan.codec.targetTensorCount)), + hostBytes: plan.checkpointHostBytes, position: plan.manifest.position) + } arrays = destinations } public func appendSegment(tensorIndex: Int, byteOffset: Int, data: Data) throws { lock.lock() defer { lock.unlock() } + if let nativeOwner, let nativeWork { + try nativeOwner.append( + tensorIndex: tensorIndex, byteOffset: byteOffset, data: data, work: nativeWork) + return + } guard let arrays else { throw CBv2CompleteCheckpointError.closed } guard tensorIndex == self.tensorIndex, byteOffset == self.byteOffset, plan.manifest.tensors.indices.contains(tensorIndex), !data.isEmpty, @@ -113,8 +436,9 @@ public final class CBv2CompleteCheckpointImport: @unchecked Sendable { } let kvTensorCount = plan.codec.targetTensorCount if let pagedStorage, tensorIndex < kvTensorCount { - try pagedStorage.append(layerIndex: tensorIndex / 2, values: tensorIndex % 2 == 1, - byteOffset: byteOffset, data: data) + try pagedStorage.append( + layerIndex: tensorIndex / 2, values: tensorIndex % 2 == 1, + byteOffset: byteOffset, data: data) } else { let index = pagedStorage == nil ? tensorIndex : tensorIndex - kvTensorCount guard let pointer = mlx_array_data_uint8(arrays[index].ctx) else { @@ -124,7 +448,25 @@ public final class CBv2CompleteCheckpointImport: @unchecked Sendable { // pointer never escapes or survives the move performed by finish. let destination = UnsafeMutableRawPointer(mutating: pointer) let strides = CBv2CheckpointByteLayout.contiguousStrides(plan.destinationShapes[index]) + let isTarget = descriptor.role == .keys || descriptor.role == .values + let ring = + isTarget + ? plan.codec.contiguousLayout?.layers.first { + $0.modelLayer == descriptor.layer && $0.window != nil + } : nil data.withUnsafeBytes { source in + if let ring, let window = ring.window { + CBv2CheckpointByteLayout.copyRing( + shape: descriptor.shape, window: window, + firstPosition: ring.tokenStart(at: plan.manifest.position), + itemSize: itemSize, + byteOffset: byteOffset, count: data.count + ) { physicalOffset, packedOffset, length in + destination.advanced(by: physicalOffset).copyMemory( + from: source.baseAddress!.advanced(by: packedOffset), byteCount: length) + } + return + } CBv2CheckpointByteLayout.copy( shape: descriptor.shape, strides: strides, itemSize: itemSize, byteOffset: byteOffset, count: data.count @@ -144,20 +486,33 @@ public final class CBv2CompleteCheckpointImport: @unchecked Sendable { public func finish() throws -> CBv2StagedCompleteCheckpoint { lock.lock() defer { lock.unlock() } + if let nativeOwner, let nativeWork { + try nativeOwner.prepare(work: nativeWork) + let result = CBv2StagedCompleteCheckpoint( + nativeOwner: nativeOwner, nativeWork: nativeWork) + self.nativeOwner = nil + self.nativeWork = nil + return result + } guard let arrays, let reservation else { throw CBv2CompleteCheckpointError.closed } guard tensorIndex == plan.manifest.tensors.count, byteOffset == 0 else { throw CBv2CompleteCheckpointError.incompleteTransfer } let prepared: CBv2PreparedCompleteCheckpoint if let pagedStorage, let stageLease { - prepared = .init(pagedFrame: try .init(storage: pagedStorage, auxiliary: arrays, lease: stageLease)) + prepared = .init( + pagedFrame: try .init(storage: pagedStorage, auxiliary: arrays, lease: stageLease)) } else { prepared = try plan.codec.preparedState( - manifest: plan.manifest, arrays: arrays, maximumSequenceLength: plan.maximumSequenceLength) + manifest: plan.manifest, arrays: arrays, + maximumSequenceLength: plan.maximumSequenceLength, + contiguousBacking: contiguousBacking) } - let result = CBv2StagedCompleteCheckpoint(plan: plan, prepared: prepared, + let result = CBv2StagedCompleteCheckpoint( + plan: plan, prepared: prepared, nativeDestinationBytes: nativeDestinationBytes, reservation: reservation) self.arrays = nil + self.contiguousBacking = nil self.pagedStorage = nil self.stageLease = nil self.reservation = nil @@ -166,7 +521,15 @@ public final class CBv2CompleteCheckpointImport: @unchecked Sendable { public func close() { lock.lock() + if let nativeOwner, let nativeWork { + self.nativeOwner = nil + self.nativeWork = nil + lock.unlock() + nativeWork.finishAfterDroppingConsumers { try nativeOwner.retireAfterCompletion() } + return + } arrays = nil + contiguousBacking = nil pagedStorage?.close() pagedStorage = nil let stageLease = self.stageLease @@ -188,35 +551,195 @@ public final class CBv2StagedCompleteCheckpoint: @unchecked Sendable { public let manifest: CBv2CompleteCheckpointManifest public let maximumSequenceLength: Int public let nativeDestinationBytes: Int - let codec: CBv2CompleteCheckpointCodec - var usesPagedBacking: Bool { codec.pagedConfig != nil } + private let legacyCodec: CBv2CompleteCheckpointCodec? + /// Native code must borrow the codec together with validated work below. + /// The existing paged/untracked adoption API retains its original access. + var codec: CBv2CompleteCheckpointCodec { + precondition(!hasNativeTracking, "native stage requires its counted work") + return legacyCodec! + } + let usesPagedBacking: Bool + let usesDestinationTransfer: Bool + let hasNativeTracking: Bool private let lock = NSLock() private var prepared: CBv2PreparedCompleteCheckpoint? private var reservation: CBv2CheckpointReservation? + private var nativeOwner: CBv2NativeCompleteCheckpointImportOwner? + private var nativeWork: CBv2NativeCompletePrefixWork? init( plan: CBv2CompleteCheckpointImportPlan, prepared: CBv2PreparedCompleteCheckpoint, - nativeDestinationBytes: Int, - reservation: CBv2CheckpointReservation + nativeDestinationBytes: Int, reservation: CBv2CheckpointReservation ) { - self.manifest = plan.manifest - self.maximumSequenceLength = plan.maximumSequenceLength + manifest = plan.manifest + maximumSequenceLength = plan.maximumSequenceLength self.nativeDestinationBytes = nativeDestinationBytes - self.codec = plan.codec + legacyCodec = plan.codec + let paged = plan.codec.pagedConfig != nil + usesPagedBacking = paged + usesDestinationTransfer = paged || plan.codec.contiguousLayout != nil + hasNativeTracking = false self.prepared = prepared self.reservation = reservation } - func consumePreparedState( - _ adopt: (CBv2PreparedCompleteCheckpoint) throws -> Result + init( + nativeOwner: CBv2NativeCompleteCheckpointImportOwner, + nativeWork: CBv2NativeCompletePrefixWork + ) { + manifest = nativeOwner.plan.manifest + maximumSequenceLength = nativeOwner.plan.maximumSequenceLength + nativeDestinationBytes = nativeOwner.nativeDestinationBytes + legacyCodec = nil + usesPagedBacking = nativeOwner.plan.pagedStoragePlan != nil + usesDestinationTransfer = true + hasNativeTracking = true + self.nativeOwner = nativeOwner + self.nativeWork = nativeWork + } + + /// Lookup-only native preparation, before enqueue/deadline beginCommit. + /// Serialize with close, but never hold an outcome/commit lock here. + func prepareNativeHistoricalAssistant( + store: any CBv2CompletePrefixCache, + request: CBv2Request, engineID: UUID, expectedCodec: CBv2CompleteCheckpointCodec + ) throws { + try lock.withLock { + guard hasNativeTracking, let nativeOwner, let nativeWork, + let prepared = nativeOwner.prepared + else { + throw CBv2CompleteCheckpointError.closed + } + let codec = try nativeOwner.codecOwner.borrow() + guard codec === expectedCodec else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try nativeWork.validate( + store: store, codec: codec, request: request, engineID: engineID) + // No restoration or extra fence for target-only imports. + guard codec.assistant != nil else { return } + if prepared.historicalAssistantRestoration?.settled == true { return } + try nativeWork.retain(owners: [prepared]) + try prepared.prepareHistoricalAssistant( + codec: codec, request: request, work: nativeWork) + guard nativeWork.hasProtectedPromotionCompletion else { + throw CBv2CompleteCheckpointError.incompleteTransfer + } + } + } + + /// Metadata-only validated borrow. close cannot detach this owner while + /// lookup is using it. The callback must not return native/model aliases. + func withValidatedNativeCodec( + store: any CBv2CompletePrefixCache, request: CBv2Request, engineID: UUID, + expectedCodec: CBv2CompleteCheckpointCodec, + _ body: (CBv2CompleteCheckpointCodec) throws -> Result + ) throws -> Result { + try lock.withLock { + guard hasNativeTracking, let nativeOwner, let nativeWork else { + throw CBv2CompleteCheckpointError.closed + } + let codec = try nativeOwner.codecOwner.borrow() + guard codec === expectedCodec else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try nativeWork.validate( + store: store, codec: codec, request: request, engineID: engineID) + guard nativeWork.hasProtectedPromotionCompletion else { + throw CBv2CompleteCheckpointError.incompleteTransfer + } + return try body(codec) + } + } + + /// Engine queue, outside the outcome commit. It MUST be followed by + /// publication/refusal in this same turn, without letting another request + /// mutate the pool's replacement-map inputs. + func prepareNativePagedTargets( + store: any CBv2CompletePrefixCache, + request: CBv2Request, engineID: UUID, expectedCodec: CBv2CompleteCheckpointCodec, + backend: PagedKVBackend, streamGeneration: UInt64 + ) throws -> CBv2PreparedNativePagedCheckpoint { + try lock.withLock { + guard hasNativeTracking, usesPagedBacking, let nativeOwner, let nativeWork, + let prepared = nativeOwner.prepared, let frame = prepared.pagedFrame, + prepared.nativePagedPreparation == nil + else { + throw CBv2CompleteCheckpointError.closed + } + let codec = try nativeOwner.codecOwner.borrow() + guard codec === expectedCodec, codec.isNativePagedHistorical else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try nativeWork.validate( + store: store, codec: codec, request: request, engineID: engineID) + let candidate = try CBv2PreparedNativePagedCheckpoint( + backend: backend, codec: codec, + work: nativeWork, request: request, streamGeneration: streamGeneration, + maximumTokens: maximumSequenceLength) + prepared.nativePagedPreparation = candidate // owns failed/late partial preparation + try nativeWork.retain(owners: [candidate]) + try candidate.prepare(frame: frame, admission: codec.admission) + prepared.pagedFrame = nil // consumed frame has no arrays/lease to refund + return candidate + } + } + + /// Move the actual import owner/work exactly once. The callback performs + /// the engine target+assistant adoption transaction. It receives the + /// same loan so any new native restoration roots are retained BEFORE eval. + func consumeNativePreparedState( + store: any CBv2CompletePrefixCache, request: CBv2Request, engineID: UUID, + expectedCodec: CBv2CompleteCheckpointCodec, + _ adopt: ( + CBv2PreparedCompleteCheckpoint, CBv2CompleteCheckpointCodec, + CBv2NativeCompletePrefixWork + ) throws -> Result ) throws -> Result { + // Refuse a foreign/repeated caller BEFORE moving the original owner. + // Validation is metadata-only; no eval/fence runs under this lock. + let moved = try lock.withLock { + () -> ( + CBv2NativeCompleteCheckpointImportOwner, + CBv2NativeCompletePrefixWork + ) in + guard hasNativeTracking, let owner = nativeOwner, let work = nativeWork else { + throw CBv2CompleteCheckpointError.closed + } + let codec = try owner.codecOwner.borrow() + guard codec === expectedCodec else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try work.validate(store: store, codec: codec, request: request, engineID: engineID) + guard work.hasProtectedPromotionCompletion, owner.prepared != nil else { + throw CBv2CompleteCheckpointError.incompleteTransfer + } + nativeOwner = nil + nativeWork = nil + return (owner, work) + } + let (owner, work) = moved + defer { work.finishAfterDroppingConsumers { try owner.retireAfterCompletion() } } + let codec = try owner.codecOwner.borrow() + guard let prepared = owner.prepared else { + throw CBv2CompleteCheckpointError.incompleteTransfer + } + // This callback is metadata-only under the native commit. A backend + // admission/registration veto is ordinary even if a test wraps it as + // MLXError; all real native completion failures were sealed in the + // off-side preparation phase, before this point. + return try adopt(prepared, codec, work) + } + + func consumePreparedState(_ adopt: (CBv2PreparedCompleteCheckpoint) throws -> Result) + throws -> Result + { + guard !hasNativeTracking else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } lock.lock() guard let prepared else { lock.unlock() throw CBv2CompleteCheckpointError.closed } - // Move the payload out before work. Concurrent close sees an empty - // handle and cannot refund a destination while adoption consumes it. self.prepared = nil let reservation = self.reservation self.reservation = nil @@ -230,6 +753,13 @@ public final class CBv2StagedCompleteCheckpoint: @unchecked Sendable { public func close() { lock.lock() + if let nativeOwner, let nativeWork { + self.nativeOwner = nil + self.nativeWork = nil + lock.unlock() + nativeWork.finishAfterDroppingConsumers { try nativeOwner.retireAfterCompletion() } + return + } prepared?.clear() prepared = nil let reservation = self.reservation @@ -237,7 +767,6 @@ public final class CBv2StagedCompleteCheckpoint: @unchecked Sendable { lock.unlock() reservation?.release() } - deinit { close() } } @@ -277,6 +806,27 @@ final class CBv2CheckpointReservation: @unchecked Sendable { /// Map a logical packed span onto contiguous runs in strided native storage. /// All products were checked while validating the descriptor/allocation plan. enum CBv2CheckpointByteLayout { + /// Checked rank-four destination geometry belongs to the immutable import + /// plan. Split at feature boundaries so head/temporal wrap cannot alias. + static func copyRing( + shape: [Int], window: Int, firstPosition: Int, itemSize: Int, + byteOffset: Int, count: Int, run: (Int, Int, Int) -> Void + ) { + let width = shape[3] + let tokens = shape[2] + var element = byteOffset / itemSize + var copied = 0 + while copied < count { + let feature = element % width + let token = (element / width) % tokens + let head = element / (width * tokens) + let slot = (firstPosition + token) % window + let length = min((width - feature) * itemSize, count - copied) + run(((head * window + slot) * width + feature) * itemSize, copied, length) + copied += length + element += length / itemSize + } + } static func contiguousStrides(_ shape: [Int]) -> [Int] { var result = Array(repeating: 1, count: shape.count) for index in stride(from: shape.count - 2, through: 0, by: -1) { diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/ContiguousCompleteCheckpointCodec.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/ContiguousCompleteCheckpointCodec.swift new file mode 100644 index 0000000000..5dc5d33714 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/ContiguousCompleteCheckpointCodec.swift @@ -0,0 +1,320 @@ +import MLX + +extension CBv2CompleteCheckpointCodec { + /// Validate every slot before reserving metadata, constructing copy graphs + /// or registering a restored row. Borrowers never own a second allocation. + func validateContiguousRows(_ state: [CBv2SequenceKV?], position: Int, exactWindow: Bool) throws + { + guard let layout = contiguousLayout, state.count == layout.layers.count, position > 1 else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + var owners = Set() + for (i, layer) in layout.layers.enumerated() { + if layer.owner != i { + guard state[i] == nil else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + continue + } + guard let row = state[i], owners.insert(ObjectIdentifier(row)).inserted, + row.absoluteOffset >= position + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + if let window = layer.window { + guard let row = row as? CBv2WindowedSequenceKV, row.window == window, + row.kvHeads == layer.kvHeads, row.headDim == layer.headDim, + row.valueHeadDim == layer.valueHeadDim, + !exactWindow || row.absoluteOffset == position, + row.retainedCount == min(row.absoluteOffset, window) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + } else { + guard row is CBv2FullSequenceKV || row is CBv2FrozenReplayFullSequenceKV else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + } + let snapshot = row.snapshot() + let count = layer.window.map { min(snapshot.offset, $0) } ?? snapshot.offset + guard snapshot.keys.shape == [1, layer.kvHeads, count, layer.headDim], + snapshot.values.shape == [1, layer.kvHeads, count, layer.valueHeadDim], + snapshot.keys.dtype == layer.dtype.mlxDType, + snapshot.values.dtype == layer.dtype.mlxDType + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + } + } + + func exportContiguousV2( + checkpoint: CBv2RecurrentCheckpoint, + kv: [(keys: MLXArray, values: MLXArray, offset: Int)?], tokens: [Int], cacheSalt: String?, + retainedOwners: [AnyObject] = [] + ) throws + -> CBv2CompleteCheckpointExport + { + guard let layout = contiguousLayout, checkpoint.layers.isEmpty, + (assistant == nil) == (checkpoint.assistant == nil), + checkpoint.qwen4.isEmpty, checkpoint.mediaIdentity == nil, !checkpoint.mediaTargetOnly, + checkpoint.position < tokens.count, kv.count == layerKinds.count + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let descriptors = try tensorDescriptors(position: checkpoint.position) + let assistantArrays: [MLXArray] + if let assistant { + guard assistant is any CBv2HistoricalMTPPrefixCheckpointCoding, + let state = checkpoint.assistant, state.targetInputCount == checkpoint.position, + let encoded = assistant.encodePrefixCheckpoint(state) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let expected = Array(descriptors.dropFirst(targetTensorCount)) + guard encoded.count == expected.count, + zip(encoded, expected).allSatisfy({ + $0.0.shape == $0.1.shape && $0.0.dtype == $0.1.dtype.mlxDType + }) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + assistantArrays = encoded + } else { + assistantArrays = [] + } + // Complete metadata preflight before permit and before slicing any row. + for (i, layer) in layout.layers.enumerated() { + if layer.owner != i { + guard kv[i] == nil else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + continue + } + guard let entry = kv[i], entry.offset >= checkpoint.position, + layer.window == nil || entry.offset == checkpoint.position + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let count = layer.window.map { min(entry.offset, $0) } ?? entry.offset + guard entry.keys.shape == [1, layer.kvHeads, count, layer.headDim], + entry.values.shape == [1, layer.kvHeads, count, layer.valueHeadDim], + entry.keys.dtype == layer.dtype.mlxDType, entry.values.dtype == layer.dtype.mlxDType + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + } + let validation = CBv2CompleteCheckpointManifest( + identity: identity, position: checkpoint.position, + chunkSize: checkpoint.chunkSize, + prefixTokens: Array(tokens.prefix(checkpoint.position)), + cacheSalt: cacheSalt, assistantCodecID: assistant?.prefixCheckpointCodecID, + tensors: descriptors, backendLayout: backendLayout, + attentionLayers: layout.layers) + _ = try validation.validateStructure() + let manifest = try validation.owningMetadata(admission: admission) + var arrays: [MLXArray] = [] + for i in layout.owningIndices { + let entry = kv[i]! + let count = checkpoint.position - layout.layers[i].tokenStart(at: checkpoint.position) + arrays.append(entry.keys[.ellipsis, .. CBv2PreparedCompleteCheckpoint { + _ = try manifest.validateStructure() + guard let layout = contiguousLayout, manifest.backendLayout == backendLayout, + manifest.identity == identity, + manifest.attentionLayers == layout.layers, maximumSequenceLength > manifest.position, + manifest.assistantCodecID == assistant?.prefixCheckpointCodecID, + manifest.tensors == (try tensorDescriptors(position: manifest.position)), + arrays.count == manifest.tensors.count + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + for (cursor, i) in layout.owningIndices.enumerated() { + let layer = layout.layers[i] + let capacity = layer.window ?? maximumSequenceLength + guard arrays[2 * cursor].shape == [1, layer.kvHeads, capacity, layer.headDim], + arrays[2 * cursor + 1].shape == [1, layer.kvHeads, capacity, layer.valueHeadDim], + arrays[2 * cursor].dtype == layer.dtype.mlxDType, + arrays[2 * cursor + 1].dtype == layer.dtype.mlxDType + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + } + var rows = [CBv2SequenceKV?](repeating: nil, count: layerKinds.count) + for (cursor, i) in layout.owningIndices.enumerated() { + let l = layout.layers[i] + let k = arrays[cursor * 2] + let v = arrays[cursor * 2 + 1] + if let window = l.window { + rows[i] = try CBv2WindowedSequenceKV( + restoredKeys: k, restoredValues: v, offset: manifest.position, + window: window, kvHeads: l.kvHeads, headDim: l.headDim, + valueHeadDim: l.valueHeadDim, checkpointBacking: backing) + } else { + rows[i] = try CBv2FullSequenceKV( + restoredKeys: k, restoredValues: v, offset: manifest.position, + maxLength: maximumSequenceLength, kvHeads: l.kvHeads, headDim: l.headDim, + valueHeadDim: l.valueHeadDim, checkpointBacking: backing) + } + } + let checkpoint: CBv2RecurrentCheckpoint + if let assistant { + guard let historical = assistant as? any CBv2HistoricalMTPPrefixCheckpointCoding else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + checkpoint = try recurrentCheckpoint( + manifest: manifest, auxiliary: Array(arrays.dropFirst(targetTensorCount))) + guard let value = checkpoint.assistant else { + throw CBv2CompleteCheckpointError.incompleteTransfer + } + // Import backing contains no checkpoint/arrays, so this creates no + // owner cycle. Target AND assistant aliases keep its full debt. + try historical.bindImportedPrefixCheckpointOwner(value, owner: backing) + } else { + guard arrays.count == targetTensorCount else { + throw CBv2CompleteCheckpointError.incompleteTransfer + } + checkpoint = .init( + position: manifest.position, chunkSize: manifest.chunkSize, layers: [:], + byteCount: 0) + } + return .init(state: rows, checkpoint: checkpoint) + } + + func contiguousReusePlan(position: Int, maximumSequenceLength: Int) throws + -> CBv2PrefixReusePlan + { + guard let layout = contiguousLayout, maximumSequenceLength > position else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + var rate = 0 + for i in layout.owningIndices where layout.layers[i].window == nil { + let l = layout.layers[i] + let k = try CBv2CheckpointTensorDescriptor.checkedByteCount( + shape: [l.kvHeads, l.headDim], dtype: l.dtype.mlxDType) + let v = try CBv2CheckpointTensorDescriptor.checkedByteCount( + shape: [l.kvHeads, l.valueHeadDim], dtype: l.dtype.mlxDType) + rate = try CBv2CheckpointAllocationFootprint.add( + rate, CBv2CheckpointAllocationFootprint.add(k, v)) + } + let (bytes, overflow) = rate.multipliedReportingOverflow(by: position) + guard !overflow else { throw CBv2CompleteCheckpointError.invalidManifest } + return .init( + backend: .contiguousUnquantized, strategy: .direct, matchedBoundary: position, + replayStart: position, replayTokens: 0, prefillTokensSaved: position, + restoredFullTokens: position, + capacityReservationTokens: maximumSequenceLength, + nominalFullKVBytesPerToken: admission.fullKVBytesPerToken, + fullKVBytesPerToken: rate, + additionalFullKVBytesPerToken: max(0, rate - admission.fullKVBytesPerToken), + initialAdditionalCapacityBytes: 0, fullCapacityTokensReserved: maximumSequenceLength, + stagedFullKVBytes: bytes, residentFullKVBytes: bytes) + } +} + +/// A bounded native allocation lease, shared only by this imported row set and +/// its authorized exports. No native array/row is retained by the lease itself. +/// Mutable contiguous storage does NOT receive evaluated materialization credit: +/// later same-shape updates may replace backing. C retains the allocator bound. +final class CBv2ContiguousCheckpointBacking: @unchecked Sendable { + let lease: CBv2CheckpointStageLease + let allocationBoundsByLayer: [Int?] + let measuredBytesByLayer: [Int?] + let auxiliaryNativeBound: Int + let retainedHostBytes: Int + private(set) var requestID: CBv2RequestID? + private var rollback: CBv2CheckpointAdoptionReservation? + + init( + lease: CBv2CheckpointStageLease, codec: CBv2CompleteCheckpointCodec, + arrays: [MLXArray], expectedBound: Int, auxiliaryArrays: [MLXArray] = [], + hostBytes: Int = 0, position: Int? = nil + ) throws { + guard let layout = codec.contiguousLayout, arrays.count == layout.owningIndices.count * 2 + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + var bounds = [Int?](repeating: nil, count: layout.layers.count) + var actual = bounds + var total = 0 + for (cursor, layer) in layout.owningIndices.enumerated() { + let footprint = try CBv2CheckpointAllocationFootprint.freshBytes( + Array(arrays[(cursor * 2) ..< (cursor * 2 + 2)])) + bounds[layer] = footprint.bound + actual[layer] = footprint.actual + total = try CBv2CheckpointAllocationFootprint.add(total, footprint.bound) + } + let auxiliary: Int + if let assistant = codec.assistant { + guard assistant is any CBv2HistoricalMTPPrefixCheckpointCoding, let position, + hostBytes + == (try CBv2HistoricalMTPCheckpointFootprint.retainedHostBytes( + position: position)) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let expected = Array( + try codec.tensorDescriptors(position: position).dropFirst(codec.targetTensorCount)) + guard auxiliaryArrays.count == expected.count, + zip(auxiliaryArrays, expected).allSatisfy({ + $0.0.shape == $0.1.shape && $0.0.dtype == $0.1.dtype.mlxDType + }) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let footprint = try CBv2CheckpointAllocationFootprint.freshBytes(auxiliaryArrays) + auxiliary = try CBv2HistoricalMTPCheckpointFootprint.nativeDestinationBound(expected) + guard footprint.bound == auxiliary, footprint.actual <= auxiliary else { + throw CBv2CompleteCheckpointError.allocationFailed + } + } else { + guard auxiliaryArrays.isEmpty, hostBytes == 0 else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + auxiliary = 0 + } + let retainedAuxiliary = try CBv2CheckpointAllocationFootprint.add(auxiliary, hostBytes) + guard total == expectedBound, lease.targetBytes == expectedBound, + lease.auxiliaryBytes == retainedAuxiliary + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + self.lease = lease + allocationBoundsByLayer = bounds + measuredBytesByLayer = actual + auxiliaryNativeBound = auxiliary + retainedHostBytes = hostBytes + // Seal the verified bound rather than refunding padding that a later + // same-shape contiguous allocation is still permitted to need. + try lease.settleDestinationAfterEvaluation( + targetBytes: total, auxiliaryBytes: retainedAuxiliary) + } + + func arm(requestID: CBv2RequestID) { + precondition(self.requestID == nil) + self.requestID = requestID + } + func finishAdoption() { lease.closeAfterDroppingOwners() } // transferred => scratch only + func abandonAdoption(_ ticket: CBv2CheckpointAdoptionReservation) { + rollback = ticket + // Unpublish the request ID without refunding any still-borrowed array. + // The deferred ticket resolves only when this backing owner dies. + if let requestID { lease.admission.releaseAll(id: requestID) } + } + deinit { + lease.closeAfterDroppingOwners() + rollback?.rollbackAfterDroppingOwners() + if let requestID { + lease.admission.retireContiguousCheckpointRows(id: requestID, owner: lease.identity) + } + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/ContiguousHistoricalBackend.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/ContiguousHistoricalBackend.swift new file mode 100644 index 0000000000..bbc1595f66 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/ContiguousHistoricalBackend.swift @@ -0,0 +1,26 @@ +import MLX + +/// Package-only owner seam for historical full+window checkpoints. This grants +/// neither ordinary frozen/block adoption nor access to a facade's allocator. +package protocol CBv2ContiguousHistoricalBackend: CBv2KVBackend { + func adoptContiguousHistoricalState( + _ state: [CBv2SequenceKV?], codec: CBv2CompleteCheckpointCodec, + layerKinds: [CBv2LayerKind], position: Int, + requestID: CBv2RequestID, maximumSequenceLength: Int + ) throws +} + +extension CBv2ContiguousKVBackend: CBv2ContiguousHistoricalBackend { + package func adoptContiguousHistoricalState( + _ state: [CBv2SequenceKV?], codec: CBv2CompleteCheckpointCodec, + layerKinds: [CBv2LayerKind], position: Int, + requestID: CBv2RequestID, maximumSequenceLength: Int + ) throws { + guard codec.contiguousLayout != nil, codec.layerKinds == layerKinds else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try adoptPreparedCheckpoint( + state, codec: codec, position: position, + requestID: requestID, maximumSequenceLength: maximumSequenceLength) + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/ContiguousHistoricalCheckpointCapture.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/ContiguousHistoricalCheckpointCapture.swift new file mode 100644 index 0000000000..19cefcd80d --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/ContiguousHistoricalCheckpointCapture.swift @@ -0,0 +1,329 @@ +import Foundation +import MLX + +private final class CBv2WeakCheckpointRow { + weak var row: (any CBv2SequenceKV)? + init(_ row: any CBv2SequenceKV) { self.row = row } +} + +/// Shared immutable copy owner. Explicit capture.close only drops one owner; +/// exported tensor sources retain this same lease until their aliases retire. +private final class CBv2ContiguousWindowBacking { + var windows: [Int: (MLXArray, MLXArray)] = [:] + var assistant: (any CBv2MTPPrefixCheckpoint)? + let reservation: CBv2CheckpointReservation + let allocationBound: Int + var measuredBytes: Int? + init(reservation: CBv2CheckpointReservation, allocationBound: Int) { + self.reservation = reservation + self.allocationBound = allocationBound + } + deinit { + windows.removeAll() + assistant = nil + reservation.release() + } +} + +/// A failed required completion cannot refund its buffers through ARC. This +/// rare process-lifetime quarantine retains the actual owner, not a byte claim. +private final class CBv2ContiguousCaptureQuarantine: @unchecked Sendable { + static let shared = CBv2ContiguousCaptureQuarantine() + private let lock = NSLock() + private var owners: [CBv2ContiguousWindowBacking] = [] + func retain(_ owner: CBv2ContiguousWindowBacking) { lock.withLock { owners.append(owner) } } +} + +/// Private historical SWA copies, never an alias to a mutable donor ring. +/// Full rows remain with the donor's existing retirement owner. +final class CBv2ContiguousHistoricalCheckpoint { + let position: Int + let chunkSize: Int + let requiresAssistant: Bool + private weak var capturingCodec: CBv2CompleteCheckpointCodec? + private let stream: StreamOrDevice + private var backing: CBv2ContiguousWindowBacking? + private var owners: [Int: CBv2WeakCheckpointRow] = [:] + private enum Evaluation { case pending, ready, failed } + private var evaluation = Evaluation.pending + private var submitted = false + private var drained = false + private(set) var completionFailed = false + private var closed = false + // Failure-only observer; cannot supply a successful native completion. + var beforeRequiredDrainForTesting: (() throws -> Void)? + var evaluate: ([MLXArray]) throws -> Void = { arrays in try withError { eval(arrays) } } + var evaluationRoots: [MLXArray] { + guard let backing else { return [] } + return backing.windows.values.flatMap { [$0.0, $0.1] } + + (backing.assistant?.evaluationTargets ?? []) + } + var compactAllocationEvidence: (bound: Int, actual: Int)? { + guard let backing, let actual = backing.measuredBytes else { return nil } + return (backing.allocationBound, actual) + } + + init( + codec: CBv2CompleteCheckpointCodec, position: Int, chunkSize: Int, state: [CBv2SequenceKV?] + ) throws { + guard let layout = codec.contiguousLayout, chunkSize > 1, position % chunkSize == 0 else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try codec.validateContiguousRows(state, position: position, exactWindow: true) + self.position = position + self.chunkSize = chunkSize + requiresAssistant = codec.assistant != nil + capturingCodec = codec + let descriptors = try codec.tensorDescriptors(position: position) + // Wrap concatenation and compact copies can coexist. Include the bool + // scalar for each Where and a conservative host owner/table envelope. + // Two bounded dictionaries, weak owner boxes and array/control entries; + // this is a conservative host envelope, not measured Swift heap bytes. + var bytes = (64 << 10) + layout.layers.count * 512 + var allocationBound = 0 + for descriptor in descriptors + where (descriptor.role == .keys || descriptor.role == .values) + && layout.layers.contains(where: { + $0.modelLayer == descriptor.layer && $0.window != nil + }) + { + let copy = try CBv2CheckpointAllocationFootprint.bound(descriptor.byteCount) + allocationBound = try CBv2CheckpointAllocationFootprint.add(allocationBound, copy) + bytes = try CBv2CheckpointAllocationFootprint.add( + bytes, + CBv2CheckpointAllocationFootprint.add( + CBv2CheckpointAllocationFootprint.add(copy, copy), + CBv2CheckpointAllocationFootprint.bound(1))) + } + if requiresAssistant { + guard codec.assistant is any CBv2HistoricalMTPPrefixCheckpointCoding else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let auxiliary = Array(descriptors.dropFirst(codec.targetTensorCount)) + allocationBound = try CBv2CheckpointAllocationFootprint.add( + allocationBound, + CBv2HistoricalMTPCheckpointFootprint.nativeDestinationBound(auxiliary)) + bytes = try CBv2CheckpointAllocationFootprint.add( + bytes, + CBv2HistoricalMTPCheckpointFootprint.captureBytes( + position: position, descriptors: auxiliary)) + } + backing = .init( + reservation: try codec.admission.reserveTransient(bytes: bytes), + allocationBound: allocationBound) + stream = .default + do { + try withError { fault in + for i in layout.owningIndices { + owners[i] = CBv2WeakCheckpointRow(state[i]!) + guard layout.layers[i].window != nil else { continue } + let s = state[i]!.snapshot() + // Selection copies preserve NaN payloads and signed zero; + // arithmetic identity operations would not do so. + backing!.windows[i] = ( + MLX.where(MLXArray(true), s.keys, s.keys, stream: stream), + MLX.where(MLXArray(true), s.values, s.values, stream: stream) + ) + } + try fault.check() + } + } catch { + close() + throw error + } + } + + func markSubmitted() { submitted = true } + + /// Target windows were copied before a successor could overwrite them. + /// The assistant is attached only after the actual committed observation + /// fence, outside native commit locks and under this pre-reserved owner. + func captureSettledAssistant(requestState: any CBv2MTPRequestState) throws { + guard !closed, !completionFailed, case .pending = evaluation, + requiresAssistant, let backing, backing.assistant == nil, + let codec = capturingCodec, + let assistant = codec.assistant as? any CBv2HistoricalMTPPrefixCheckpointCoding + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + submitted = true + drained = false + try withError { fault in + guard + let captured = assistant.capturePrefixCheckpoint( + requestState: requestState, targetInputCount: position), + captured.targetInputCount == position + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + // Retain before checking a native error signalled during copy graph + // construction; cleanup must not lose the actual partial owner. + backing.assistant = captured + try fault.check() + let expected = Array( + try codec.tensorDescriptors(position: position).dropFirst(codec.targetTensorCount)) + guard let arrays = assistant.encodePrefixCheckpoint(captured), + arrays.count == expected.count, + zip(arrays, expected).allSatisfy({ + $0.0.shape == $0.1.shape && $0.0.dtype == $0.1.dtype.mlxDType + }) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + } + } + + func finishEvaluation() throws { + guard !closed else { throw CBv2CompleteCheckpointError.closed } + switch evaluation { + case .ready: return + case .failed: throw CBv2CompleteCheckpointError.allocationFailed + case .pending: break + } + guard !requiresAssistant || backing?.assistant != nil else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + submitted = true + do { + try evaluate(evaluationRoots) + try requiredDrain() + let footprint = try CBv2CheckpointAllocationFootprint.freshBytes(evaluationRoots) + guard let backing, footprint.bound == backing.allocationBound, + footprint.actual <= backing.allocationBound + else { throw CBv2CompleteCheckpointError.allocationFailed } + // Unique, row-contiguous, offset-zero, exact-extent native backing + // proved by freshBytes. A view/oversized-parent result fails closed. + backing.measuredBytes = footprint.actual + evaluation = .ready + } catch { + // The owning step may have partially submitted these roots. + // Drain issued work, never evaluate/retry a failed graph on close. + do { if !drained { try requiredDrain() } } catch { + evaluation = .failed + throw error + } + evaluation = .failed + throw error + } + } + + /// Discard is not publication. A cancelled interior capture can lack its + /// assistant payload, but its already-submitted target copies still need + /// real completion before any reservation is released. + func finishEvaluationForRetirement() throws { + guard !closed, !completionFailed else { throw CBv2CompleteCheckpointError.allocationFailed } + if case .pending = evaluation { + submitted = true + do { try evaluate(evaluationRoots) } catch { + evaluation = .failed + throw error + } + } + if submitted && !drained { try requiredDrain() } + } + + private func requiredDrain() throws { + guard !completionFailed else { throw CBv2CompleteCheckpointError.allocationFailed } + do { + try beforeRequiredDrainForTesting?() + try withError { fault in + stream.stream.synchronize() + try fault.check() + } + drained = true + } catch { + completionFailed = true + throw error + } + } + + func export( + codec: CBv2CompleteCheckpointCodec, state: [CBv2SequenceKV?], + tokens: [Int], cacheSalt: String? + ) throws -> CBv2CompleteCheckpointExport { + guard !closed, case .ready = evaluation, let backing, + capturingCodec === codec, backing.measuredBytes != nil, + let layout = codec.contiguousLayout, state.count == layout.layers.count + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + var kv = [(keys: MLXArray, values: MLXArray, offset: Int)?]( + repeating: nil, count: state.count) + var seen = Set() + for (i, layer) in layout.layers.enumerated() { + if layer.owner != i { + guard state[i] == nil else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + continue + } + guard let row = state[i], owners[i]?.row === row, + seen.insert(ObjectIdentifier(row)).inserted, row.absoluteOffset >= position + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + if let window = layer.window { + guard let ring = row as? CBv2WindowedSequenceKV, ring.window == window, + ring.kvHeads == layer.kvHeads, ring.headDim == layer.headDim, + ring.valueHeadDim == layer.valueHeadDim, + ring.retainedCount >= 0, ring.retainedCount <= min(ring.absoluteOffset, window) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + // Plain deferred rollback can leave W-1 (or zero) CURRENT rows + // after overwrite. Export the exact earlier immutable copy, + // never revive discarded history or inspect empty placeholders. + guard let pair = backing.windows[i] else { + throw CBv2CompleteCheckpointError.closed + } + kv[i] = (pair.0, pair.1, position) + } else { + guard row is CBv2FullSequenceKV || row is CBv2FrozenReplayFullSequenceKV else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + kv[i] = row.snapshot() + } + } + // Unchanged export validation checks the ACTUAL captured SWA shape, + // dtype and boundary plus every still-available full prefix, before + // reserving manifest metadata or slicing. Capture's native compact/ + // independent-backing proof and shared lifetime owner remain in force. + return try codec.exportContiguousV2( + checkpoint: .init( + position: position, chunkSize: chunkSize, + layers: [:], byteCount: backing.assistant?.materializedBytes ?? 0, + assistant: backing.assistant), kv: kv, tokens: tokens, cacheSalt: cacheSalt, + retainedOwners: [backing] + state.compactMap { $0.map { $0 as AnyObject } }) + } + + func close() { + guard !closed else { return } + closed = true + if submitted && !drained { + if !completionFailed { try? requiredDrain() } + if !drained, let backing { CBv2ContiguousCaptureQuarantine.shared.retain(backing) } + } + owners.removeAll() + backing = nil + } + deinit { close() } +} + +extension CBv2CompleteCheckpointCapture { + func prepareContiguous(position: Int, chunkSize: Int, state: [CBv2SequenceKV?]) throws + -> CBv2CapturedCompleteCheckpoint? + { + guard !isClosed, codec.contiguousLayout != nil else { return nil } + do { + let descriptors = try codec.tensorDescriptors(position: position) + let bytes = try descriptors.reduce(0) { + try CBv2CheckpointAllocationFootprint.add($0, $1.byteCount) + } + guard store.acceptsCheckpoint(position: position, packedBytes: bytes) else { + return nil + } + return .init( + contiguous: try makeContiguousCheckpoint(codec, position, chunkSize, state)) + } catch let error as MLXError { throw error } catch { return nil } + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineLoopV2+CompleteCheckpoint.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineLoopV2+CompleteCheckpoint.swift index 535b95d465..c8f7714928 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineLoopV2+CompleteCheckpoint.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineLoopV2+CompleteCheckpoint.swift @@ -13,14 +13,56 @@ extension EngineLoopV2 { func adoptCompleteCheckpoint(_ staged: CBv2StagedCompleteCheckpoint, requestID: CBv2RequestID) throws -> [CBv2SequenceKV?] { - if staged.usesPagedBacking { return try adoptPagedCompleteCheckpoint(staged, requestID: requestID) } - guard let contiguous = backend as? CBv2ContiguousKVBackend else { + if staged.hasNativeTracking { + guard let capture = completeCheckpointCapture, let tracking = nativeShutdownState, + let request = scheduler.record(for: requestID)?.request + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + return try staged.consumeNativePreparedState( + store: capture.store, request: request, + engineID: tracking.engineID, expectedCodec: capture.codec + ) { prepared, codec, work in + // Native graphs/fences were completed during staged lookup. + // This helper performs the metadata-only atomic move + // under the existing outer native commit. + if codec.isNativePagedHistorical { + return try adoptPreparedNativePagedHistoricalState( + prepared, codec: codec, + requestID: requestID, maximumSequenceLength: staged.maximumSequenceLength) + } + return try adoptPreparedContiguousHistoricalState( + prepared, codec: codec, + requestID: requestID, maximumSequenceLength: staged.maximumSequenceLength) + } + } + guard nativeShutdownState == nil else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + if staged.usesPagedBacking { + return try adoptPagedCompleteCheckpoint(staged, requestID: requestID) + } return try staged.consumePreparedState { prepared in guard let checkpoint = prepared.checkpoint else { throw CBv2CompleteCheckpointError.incompleteTransfer } + if staged.codec.contiguousLayout != nil { + guard let contiguous = backend as? any CBv2ContiguousHistoricalBackend, + staged.codec === completeCheckpointCapture?.codec, checkpoint.layers.isEmpty, + checkpoint.assistant == nil, !(mtp?.tracksPersistentHistory ?? false), + recurrentStates[requestID] == nil + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + try contiguous.adoptContiguousHistoricalState( + prepared.state, codec: staged.codec, + layerKinds: layerKinds, position: staged.manifest.position, + requestID: requestID, maximumSequenceLength: staged.maximumSequenceLength) + recurrentCheckpointGeometry[requestID] = .init( + position: checkpoint.position, chunkSize: checkpoint.chunkSize) + return prepared.state + } + guard let contiguous = backend as? CBv2ContiguousKVBackend else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } try contiguous.adoptPreparedCheckpoint(prepared.state) do { try adoptRecurrentCheckpoint(checkpoint, requestID: requestID) diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineLoopV2+ContiguousHistoricalAdoption.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineLoopV2+ContiguousHistoricalAdoption.swift new file mode 100644 index 0000000000..90440cfd2f --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineLoopV2+ContiguousHistoricalAdoption.swift @@ -0,0 +1,56 @@ +import MLX + +extension EngineLoopV2 { + /// Metadata-only transaction under the existing native enqueue/deadline + /// commit. Mutable assistant restoration/evaluation MUST have completed in + /// staged lookup; there is no model call, eval, or stream fence here. + func adoptPreparedContiguousHistoricalState( + _ prepared: CBv2PreparedCompleteCheckpoint, + codec: CBv2CompleteCheckpointCodec, requestID: CBv2RequestID, + maximumSequenceLength: Int + ) throws -> [CBv2SequenceKV?] { + guard let checkpoint = prepared.checkpoint, + let contiguous = backend as? any CBv2ContiguousHistoricalBackend, + codec === completeCheckpointCapture?.codec, codec.contiguousLayout != nil, + checkpoint.layers.isEmpty, recurrentStates[requestID] == nil, + kvStates[requestID] == nil, + let request = scheduler.record(for: requestID)?.request, + checkpoint.position < request.promptTokens.count + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let restored: (any CBv2MTPRequestState)? + if checkpoint.assistant != nil { + guard let mtp, mtp.canInstallHistoricalAssistant(for: requestID), + let expected = codec.assistant, + expected as AnyObject === mtp.drafter as AnyObject, + let restoration = prepared.historicalAssistantRestoration, + restoration.settled, let state = restoration.state + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + restored = state + } else { + guard codec.assistant == nil, !(mtp?.tracksPersistentHistory ?? false), + prepared.historicalAssistantRestoration == nil + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + restored = nil + } + // Backend validates the fresh-row ledger and transfers its actual + // Admission lease before publishing. It rolls back on registration + // failure. All fallible assistant checks preceded this mutation. + try contiguous.adoptContiguousHistoricalState( + prepared.state, codec: codec, + layerKinds: layerKinds, position: checkpoint.position, + requestID: requestID, maximumSequenceLength: maximumSequenceLength) + if let restored { + _ = prepared.historicalAssistantRestoration?.takeSettledState() + mtp!.restoreAssistantState(restored, for: requestID) + } + recurrentCheckpointGeometry[requestID] = .init( + position: checkpoint.position, chunkSize: checkpoint.chunkSize) + return prepared.state + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineLoopV2+HistoricalCheckpoint.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineLoopV2+HistoricalCheckpoint.swift index cf4e153103..7fec781325 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineLoopV2+HistoricalCheckpoint.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineLoopV2+HistoricalCheckpoint.swift @@ -24,34 +24,49 @@ extension CBv2CompleteCheckpointCapture { /// itself gives up first; without one the candidate only fits in free room. func prepareHistorical( position: Int, chunkSize: Int, state: [CBv2SequenceKV?], - allowance: CBv2HistoricalStagingAllowance? = nil + allowance: CBv2HistoricalStagingAllowance? = nil, + nativeWork: CBv2NativeCompletePrefixWork? = nil ) throws -> CBv2CapturedCompleteCheckpoint? { + if codec.contiguousLayout != nil { + return try prepareContiguous(position: position, chunkSize: chunkSize, state: state) + } guard !isClosed, let layout = codec.historicalLayout, - state.count == layout.layers.count else { return nil } + state.count == layout.layers.count + else { return nil } do { // Scalar policy projection first; no descriptor/page/token table // is built merely to ask the store whether this boundary fits. - var packedBytes = 0 - for layer in layout.layers.enumerated() where layer.element.owner == layer.offset { - let item = layer.element - let bytes = try CBv2CheckpointTensorDescriptor.checkedByteCount( - shape: [2, item.kvHeads, position - item.tokenStart(at: position), item.headDim], - dtype: item.dtype.mlxDType) - let (next, overflow) = packedBytes.addingReportingOverflow(bytes) - guard !overflow else { return nil } - packedBytes = next + let descriptors = try codec.tensorDescriptors(position: position) + let packedBytes = try descriptors.reduce(0) { + try CBv2CheckpointAllocationFootprint.add($0, $1.byteCount) + } + guard store.acceptsCheckpoint(position: position, packedBytes: packedBytes) else { + return nil } - guard store.acceptsCheckpoint(position: position, packedBytes: packedBytes) else { return nil } var owners: [(index: Int, row: PagedSequenceKV)] = [] var windowBytes = 0 + if codec.isNativePagedHistorical { + guard let nativeWork, nativeWork.codecIdentity == codec.identity else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + windowBytes = try CBv2CheckpointAllocationFootprint.add( + 64 << 10, layout.layers.count * 512) + if codec.assistant != nil { + windowBytes = try CBv2CheckpointAllocationFootprint.add( + windowBytes, + CBv2HistoricalMTPCheckpointFootprint.captureBytes( + position: position, + descriptors: Array(descriptors.dropFirst(codec.targetTensorCount)))) + } + } for (index, layer) in layout.layers.enumerated() { if layer.owner != index { guard state[index] == nil else { return nil } continue } guard let row = state[index] as? PagedSequenceKV, - row.absoluteOffset >= position, row.pool.layerKinds == codec.layerKinds, - row.groupKey.dtype == layer.dtype.mlxDType + row.absoluteOffset >= position, row.pool.layerKinds == codec.layerKinds, + row.groupKey.dtype == layer.dtype.mlxDType else { return nil } guard layer.window != nil else { continue } // Allocation-free: the same figure the window reserves. @@ -61,30 +76,49 @@ extension CBv2CompleteCheckpointCapture { windowBytes = next owners.append((index, row)) } - let shed = allowance.flatMap { staged[$0.requestID] }.map { captures in - (allowance?.sheddable ?? []).compactMap { position in - captures.first { $0.position == position } - } - } ?? [] - guard let displaced = CBv2HistoricalStagingCap.displaced( - candidateBytes: windowBytes, - slotBytes: stagedHistoricalBytes + max(0, inFlightHistoricalBytes), - replacingBytes: allowance?.replacingBytes ?? 0, - sheddable: shed.map(\.stagedHistoricalBytes), cap: historicalSlotStagedByteCap) + let shed = + allowance.flatMap { staged[$0.requestID] }.map { captures in + (allowance?.sheddable ?? []).compactMap { position in + captures.first { $0.position == position } + } + } ?? [] + guard + let displaced = CBv2HistoricalStagingCap.displaced( + candidateBytes: windowBytes, + slotBytes: stagedHistoricalBytes + max(0, inFlightHistoricalBytes), + replacingBytes: allowance?.replacingBytes ?? 0, + sheddable: shed.map(\.stagedHistoricalBytes), cap: historicalSlotStagedByteCap) else { return nil } - var windows: [Int: CBv2HistoricalWindow] = [:] - for owner in owners { - windows[owner.index] = try makeHistoricalWindow(owner.row, position, codec.admission) + let candidate: CBv2CapturedCompleteCheckpoint + if codec.isNativePagedHistorical, let nativeWork { + let history = try CBv2HistoricalCompleteCheckpoint( + codec: codec, + position: position, chunkSize: chunkSize, state: state) + candidate = .init(historical: history) + // Partial window construction is already loan-owned. A later + // required native failure cannot fall into the legacy deinit. + try nativeWork.retain(owners: [candidate]) + for owner in owners { + let window = try makeHistoricalWindow(owner.row, position, codec.admission) + try history.installWindow(window, layer: owner.index) + try nativeWork.retain(arrays: window.evaluationRoots, owners: [window]) + } + } else { + var windows: [Int: CBv2HistoricalWindow] = [:] + for owner in owners { + windows[owner.index] = try makeHistoricalWindow( + owner.row, position, codec.admission) + } + candidate = .init( + historical: .init(position: position, chunkSize: chunkSize, windows: windows)) } - let candidate = CBv2CapturedCompleteCheckpoint( - historical: .init(position: position, chunkSize: chunkSize, windows: windows)) - inFlightHistoricalBytes += candidate.stagedHistoricalBytes - (allowance?.replacingBytes ?? 0) + inFlightHistoricalBytes += + candidate.stagedHistoricalBytes - (allowance?.replacingBytes ?? 0) if let allowance, displaced > 0 { release(Array(shed.prefix(displaced)), requestID: allowance.requestID) } return candidate - } catch let error as MLXError { throw error } - catch { return nil } + } catch let error as MLXError { throw error } catch { return nil } } /// Give up staged boundaries of one donor. Whenever the candidate that @@ -116,9 +150,11 @@ extension CBv2CompleteCheckpointCapture { // The stored verdicts, which earlier attempts of this range may // have changed by displacing a boundary. let current = retentions[requestID] ?? retention - var result = CBv2HistoricalStagingAllowance(requestID: requestID, sheddable: current.sheddable(for: role)) + var result = CBv2HistoricalStagingAllowance( + requestID: requestID, sheddable: current.sheddable(for: role)) if role == .latest, let replaced = current.replaceableLatest { - result.replacingBytes = staged[requestID]? + result.replacingBytes = + staged[requestID]? .first { $0.position == replaced }?.stagedHistoricalBytes ?? 0 } return result @@ -127,9 +163,11 @@ extension CBv2CompleteCheckpointCapture { var prepared: [CBv2CapturedCompleteCheckpoint] = [] var latest: Int? for position in positions.reversed() { - guard let candidate = try prepareHistorical( - position: position, chunkSize: stride, state: state, - allowance: allowance(.latest)) else { continue } + guard + let candidate = try prepareHistorical( + position: position, chunkSize: stride, state: state, + allowance: allowance(.latest)) + else { continue } prepared.append(candidate) latest = position break @@ -137,8 +175,8 @@ extension CBv2CompleteCheckpointCapture { guard let latest else { return [] } let below = positions.filter { $0 < latest } if let target = retention.plannedTarget, below.contains(target), - let candidate = try prepareHistorical( - position: target, chunkSize: stride, state: state, allowance: allowance(.target)) + let candidate = try prepareHistorical( + position: target, chunkSize: stride, state: state, allowance: allowance(.target)) { prepared.append(candidate) } @@ -146,9 +184,11 @@ extension CBv2CompleteCheckpointCapture { // The first is the lowest boundary that lands, the target included. let lowest = prepared.compactMap(\.position).min() ?? latest for position in below where position < lowest { - guard let candidate = try prepareHistorical( - position: position, chunkSize: stride, state: state, - allowance: allowance(.first)) else { continue } + guard + let candidate = try prepareHistorical( + position: position, chunkSize: stride, state: state, + allowance: allowance(.first)) + else { continue } prepared.append(candidate) break } @@ -173,18 +213,26 @@ extension CBv2CompleteCheckpointCapture { _ candidate: CBv2CapturedCompleteCheckpoint, requestID: CBv2RequestID, hintTokens: Int? = nil, resumedAt: Int = 0 ) { + if codec.contiguousLayout != nil { + commitContiguousHistorical(candidate, requestID: requestID) + return + } // Staged or closed, the candidate is no longer in flight. inFlightHistoricalBytes = max(0, inFlightHistoricalBytes - candidate.stagedHistoricalBytes) guard !isClosed, let position = candidate.position, - !(staged[requestID]?.contains { $0.position == position } ?? false) - else { candidate.finishEvaluationAndClose(); return } + !(staged[requestID]?.contains { $0.position == position } ?? false) + else { + candidate.finishEvaluationAndClose() + return + } var retention = retention( requestID: requestID, stride: historicalCheckpointStrideTokens, hintTokens: hintTokens, resumedAt: resumedAt) var retired = Set(retention.commit(position)) var checkpoints = (staged[requestID] ?? []) + [candidate] let bytesByPosition = Dictionary( - checkpoints.map { ($0.position ?? 0, $0.stagedHistoricalBytes) }, uniquingKeysWith: { $0 + $1 }) + checkpoints.map { ($0.position ?? 0, $0.stagedHistoricalBytes) }, + uniquingKeysWith: { $0 + $1 }) var bytes = checkpoints.reduce(0) { $0 + (retired.contains($1.position ?? 0) ? 0 : $1.stagedHistoricalBytes) } @@ -208,34 +256,113 @@ extension CBv2CompleteCheckpointCapture { queue.async { retiring.forEach { $0.finishEvaluationAndClose() } } } } + + @discardableResult + func commitContiguousHistorical( + _ candidate: CBv2CapturedCompleteCheckpoint, requestID: CBv2RequestID, + nativeWork: CBv2NativeCompletePrefixWork? = nil + ) -> Bool { + if codec.isNativePagedHistorical { + inFlightHistoricalBytes = max( + 0, inFlightHistoricalBytes - candidate.stagedHistoricalBytes) + } + guard !isClosed, + !(staged[requestID]?.contains { $0.position == candidate.position } ?? false) + else { + if let nativeWork { + nativeWork.finishAfterDroppingConsumers { + candidate.closeAfterCompletedEvaluation() + } + } else if hasNativeTracking { + retireCaptured(candidate, requestID: requestID) + } else { + candidate.finishEvaluationAndClose() + } + return false + } + if staged[requestID, default: []].count == 2 { + let previous = staged[requestID]!.removeLast() + retireCaptured(previous, requestID: requestID) + } + staged[requestID, default: []].append(candidate) + return true + } } extension EngineLoopV2 { - /// Exact scalar geometry advances on launch. It belongs to that immutable - /// step; scheduler cursors and mutable windows may already be ahead when - /// finalize runs. Preemption/packed history disarms this generation; the - /// chunk cap is not part of the historical rule (see - /// `CBv2RecurrentCheckpointGeometry.recordHistorical`). + /// Paged historical donors follow upstream's independent stride and + /// retention policy. Contiguous native checkpoints retain their actual + /// committed-frontier contract; no older assistant state is fabricated. func prepareHistoricalCheckpoints(_ step: CBv2InFlightStep) throws -> [MLXArray] { - guard let capture = completeCheckpointCapture, capture.codec.historicalLayout != nil else { return [] } + guard let capture = completeCheckpointCapture, + capture.codec.historicalLayout != nil || capture.codec.contiguousLayout != nil + else { return [] } let stride = capture.historicalCheckpointStrideTokens - // Every candidate of the previous capturing step was committed or - // closed before this one could launch. capture.inFlightHistoricalBytes = 0 for (id, range) in step.computedRanges { guard let rec = scheduler.record(for: id), rec.request.prefixCacheEnabled, - rec.request.multimodal == nil, rec.request.positionState == nil, rec.preemptionCount == 0, - let state = kvStates[id] + rec.request.multimodal == nil, rec.request.positionState == nil, + rec.preemptionCount == 0, + let state = kvStates[id] else { continue } var geometry = recurrentCheckpointGeometry[id] ?? .init() - let positions = geometry.recordHistorical(range: range, + if capture.codec.contiguousLayout != nil || capture.codec.isNativePagedHistorical { + guard let cap = step.recurrentCheckpointChunkSizes[id], + cap >= scheduler.config.prefillChunkSize, + CBv2AttentionV1.queryBlockSize <= 0 || cap % CBv2AttentionV1.queryBlockSize == 0 + else { continue } + // Preserve the existing uniform complete-chunk rule for the + // exact-frontier target/head capture. Upstream recurrent state + // can use the newer chunk-agnostic rule independently. + let eligible = + geometry.isArmed && !step.packedPrefixRows.contains(id) + && cap > 1 && range.lowerBound == geometry.position + && range.upperBound <= rec.request.promptTokens.count + && range.count == cap && range.lowerBound % cap == 0 + && (geometry.chunkSize == nil || geometry.chunkSize == cap) + if eligible { + geometry.position = range.upperBound + geometry.chunkSize = cap + } else { + geometry.isArmed = false + } + recurrentCheckpointGeometry[id] = geometry + guard eligible, range.upperBound % cap == 0, + range.upperBound < rec.request.promptTokens.count + else { continue } + if capture.codec.assistant != nil { + guard + step.mtpRound?.committedObservationRows.contains(where: { $0.id == id }) + == true + else { continue } + } + let work = try capture.nativeWorkFactory?(id) + do { + try work?.captureCurrentStreams() + guard + let candidate = try capture.prepareHistorical( + position: range.upperBound, chunkSize: cap, state: state, + nativeWork: work) + else { + work?.finishAfterDroppingConsumers() + continue + } + step.historicalCheckpoints[id] = [candidate] + if let work { + step.nativeHistoricalCheckpointWork[id] = work + try work.retain(arrays: candidate.evaluationRoots, owners: [candidate]) + } + } catch { + work?.requiredCompletionFailed() + throw error + } + continue + } + let positions = geometry.recordHistorical( + range: range, promptLength: rec.request.promptTokens.count, packed: step.packedPrefixRows.contains(id), stride: stride) recurrentCheckpointGeometry[id] = geometry - // Interior positions are exact while every sliding ring still holds - // `[p - W, p)`; `CBv2HistoricalWindow` refuses the rest, and the - // gathers land in this step's own asyncEval before any successor - // may write the ring (`permitsChainedSuccessor`). let capturable = positions.filter { $0 < rec.request.promptTokens.count } guard !capturable.isEmpty else { continue } let retention = capture.retention( @@ -247,20 +374,117 @@ extension EngineLoopV2 { } let candidates = step.historicalCheckpoints.values.flatMap { $0 } let roots = candidates.flatMap(\.evaluationRoots) - for candidate in candidates { candidate.historical?.markSubmitted() } + for candidate in candidates { + candidate.historical?.markSubmitted() + candidate.contiguous?.markSubmitted() + } return roots } + /// Runs after the actual observation fence and before the native commit. + func captureSettledHistoricalAssistants(_ step: CBv2InFlightStep) throws { + for (id, candidates) in step.historicalCheckpoints { + for candidate in candidates { + guard + candidate.contiguous?.requiresAssistant == true + || candidate.historical?.requiresAssistant == true + else { continue } + guard !step.discard.contains(id), scheduler.record(for: id)?.preemptionCount == 0 + else { continue } + guard + let observation = step.mtpRound?.committedObservationRows.first(where: { + $0.id == id + }) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let work = step.nativeHistoricalCheckpointWork[id] + do { + try work?.captureCurrentStreams() + try work?.retain(owners: [observation.assistantState]) + if let contiguous = candidate.contiguous { + try contiguous.captureSettledAssistant( + requestState: observation.assistantState) + } else if let historical = candidate.historical { + try historical.captureSettledAssistant( + requestState: observation.assistantState) + } else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try work?.retain(arrays: candidate.evaluationRoots, owners: [candidate]) + } catch { + work?.requiredCompletionFailed() + throw error + } + } + } + } + + /// All required native evaluation/fences remain outside beginCommit. + func finishHistoricalCheckpointCopiesForNative(_ step: CBv2InFlightStep) -> Bool { + guard let capture = completeCheckpointCapture, + let factory = capture.nativeWorkFactory + else { return true } + for (id, candidates) in step.historicalCheckpoints { + var work = step.nativeHistoricalCheckpointWork[id] + do { + if work == nil { + work = try factory(id) + step.nativeHistoricalCheckpointWork[id] = work + } + guard let work else { throw CBv2NativeShutdownError.unsupportedConsumer } + try work.retain(arrays: candidates.flatMap(\.evaluationRoots), owners: candidates) + try work.captureCurrentStreams() + for candidate in candidates { + if step.discard.contains(id) || scheduler.record(for: id)?.preemptionCount != 0 + { + try candidate.finishEvaluationForRetirement() + } else { + try candidate.finishEvaluation() + } + } + try work.fenceForProtectedPromotion() + } catch { + if let work { + work.requiredCompletionFailed() + } else { + candidates.forEach { capture.retainAfterNativeFailure($0) } + } + return false + } + } + return true + } + func commitHistoricalCheckpoints(_ step: CBv2InFlightStep) -> MLXError? { guard let capture = completeCheckpointCapture else { return nil } var nativeFailure: MLXError? for (id, candidates) in step.historicalCheckpoints { + if capture.hasNativeTracking { + guard let active = step.nativeHistoricalCheckpointWork[id], + active.hasProtectedPromotionCompletion, + capture.codec.contiguousLayout != nil || capture.codec.isNativePagedHistorical, + candidates.count == 1, let candidate = candidates.first + else { + candidates.forEach { capture.retainAfterNativeFailure($0) } + return nil + } + if step.discard.contains(id) || scheduler.record(for: id)?.preemptionCount != 0 { + active.finishAfterDroppingConsumers { + candidate.closeAfterCompletedEvaluation() + } + } else if capture.commitContiguousHistorical( + candidate, requestID: id, nativeWork: active) + { + active.finishAfterDroppingConsumers() + } + continue + } for candidate in candidates { - // This step's sample can finish before its final gather witness. - // Wait for the already submitted roots before promotion/retirement. do { try candidate.finishEvaluation() - if step.discard.contains(id) || scheduler.record(for: id)?.preemptionCount != 0 { + if step.discard.contains(id) || scheduler.record(for: id)?.preemptionCount != 0 + { capture.discardHistorical(candidate) } else { let rec = scheduler.record(for: id) @@ -276,6 +500,7 @@ extension EngineLoopV2 { } } step.historicalCheckpoints.removeAll() + step.nativeHistoricalCheckpointWork.removeAll() if nativeFailure != nil { step.discard.formUnion(step.participants) } return nativeFailure } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineV2+CompleteCheckpoint.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineV2+CompleteCheckpoint.swift index 82bcc48ae2..71e645f371 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineV2+CompleteCheckpoint.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/EngineV2+CompleteCheckpoint.swift @@ -1,11 +1,34 @@ import Foundation extension EngineV2 { + /// Native historical capture still proves the donor's complete-chunk + /// execution shape. Keep its scheduler bound until partition-independent + /// target/head continuation is independently qualified. + private func validateContiguousCheckpointChunk( + _ manifest: CBv2CompleteCheckpointManifest, codec: CBv2CompleteCheckpointCodec + ) throws { + guard codec.contiguousLayout != nil || codec.isNativePagedHistorical else { return } + guard manifest.chunkSize >= schedulerConfig.prefillChunkSize, + manifest.chunkSize + <= max( + schedulerConfig.prefillChunkSize, + schedulerConfig.soloPrefillStripeTokens ?? 0), + CBv2AttentionV1.queryBlockSize <= 0 + || manifest.chunkSize % CBv2AttentionV1.queryBlockSize == 0 + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + } + /// Charge the first manifest decrypt before the provider has a validated /// import plan. This shares the slot's admission ceiling, including when /// the caller has no provider-wide budget. No file or model work occurs. public func reserveCompleteCheckpointReadScratch() throws -> CBv2CompleteCheckpointIOLease { - guard let completeCheckpointCodec else { + guard let completeCheckpointCodec, + !completeCheckpointCodec.unsupportedAsymmetricGeometry + || completeCheckpointCodec.contiguousLayout != nil + || completeCheckpointCodec.isNativePagedHistorical + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } if completeCheckpointCodec.admission.hasProcessMemoryOwner { @@ -14,8 +37,9 @@ extension EngineV2 { return CBv2CompleteCheckpointIOLease( reservation: .init(onRelease: {}), usesProcessMemoryOwner: true) } - return CBv2CompleteCheckpointIOLease(reservation: try completeCheckpointCodec.admission.reserveTransient( - bytes: CBv2CompleteCheckpointManifest.maximumProviderScratchBytes)) + return CBv2CompleteCheckpointIOLease( + reservation: try completeCheckpointCodec.admission.reserveTransient( + bytes: CBv2CompleteCheckpointManifest.maximumProviderScratchBytes)) } /// Called from the asynchronous provider stage path; no model execution, @@ -26,7 +50,30 @@ extension EngineV2 { guard let completeCheckpointCodec else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } - return try completeCheckpointCodec.plan(manifest: manifest, request: request) + try validateContiguousCheckpointChunk(manifest, codec: completeCheckpointCodec) + let work: CBv2NativeCompletePrefixWork? + if let completePrefixCache { + let factory = try nativeCompletePrefixWorkFactory( + store: completePrefixCache, + codec: completeCheckpointCodec, request: request) + work = try factory?() // counted BEFORE the plan retains codec/assistant + } else if hasNativeCompletionTracking { + throw CBv2NativeShutdownError.unsupportedConsumer + } else { + work = nil + } + do { + let plan = try completeCheckpointCodec.plan(manifest: manifest, request: request) + if let work, let completePrefixCache { + try plan.bindNativeCompletePrefixWork( + work, store: completePrefixCache, + request: request, engineID: nativeShutdownEngineID) + } + return plan + } catch { + work?.finishAfterDroppingConsumers() + throw error + } } public func setCompletePrefixPublicationHandler( @@ -39,38 +86,98 @@ extension EngineV2 { guard request.permitsHybridCheckpoint(layerKinds: layerKinds), let receiptID = request.prefixCacheReceiptID, let completePrefixCache else { return .init(adoption: nil, outcome: .skippedPolicy, matchedTokens: 0) } - let (maximumLength, overflow) = request.promptTokens.count.addingReportingOverflow(max(1, request.maxTokens)) - guard !overflow else { return .init(adoption: nil, outcome: .skippedPolicy, matchedTokens: 0) } - guard let staged = completePrefixCache.takeStaged( - requestID: receiptID, tokens: request.promptTokens, cacheSalt: request.checkpointCacheSalt, - maximumSequenceLength: maximumLength) + let (maximumLength, overflow) = request.promptTokens.count.addingReportingOverflow( + max(1, request.maxTokens)) + guard !overflow else { + return .init(adoption: nil, outcome: .skippedPolicy, matchedTokens: 0) + } + guard + let staged = completePrefixCache.takeStaged( + requestID: receiptID, tokens: request.promptTokens, + cacheSalt: request.checkpointCacheSalt, + maximumSequenceLength: maximumLength) else { return .init(adoption: nil, outcome: .miss, matchedTokens: 0) } do { + if staged.hasNativeTracking { + guard let completeCheckpointCodec, hasNativeCompletionTracking, + staged.maximumSequenceLength == maximumLength + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + try validateContiguousCheckpointChunk( + staged.manifest, codec: completeCheckpointCodec) + try staged.prepareNativeHistoricalAssistant( + store: completePrefixCache, + request: request, engineID: nativeShutdownEngineID, + expectedCodec: completeCheckpointCodec) + return try staged.withValidatedNativeCodec( + store: completePrefixCache, + request: request, engineID: nativeShutdownEngineID, + expectedCodec: completeCheckpointCodec + ) { codec in + // Validation stays inside the stage's actual loan; do not + // create a second public deferred-plan loan just to check it. + _ = try codec.plan(manifest: staged.manifest, request: request) + let matched = staged.manifest.position + var plan = + codec.isNativePagedHistorical + ? try codec.historicalReusePlan( + position: matched, maximumSequenceLength: maximumLength) + : try codec.contiguousReusePlan( + position: matched, maximumSequenceLength: maximumLength) + plan.recurrentChunkSize = staged.manifest.chunkSize + plan.recurrentPromptLength = request.promptTokens.count + return .init( + adoption: .init( + requestID: receiptID, tokens: request.promptTokens, + matched: matched, plan: plan, prefix: [], + cacheSalt: request.checkpointCacheSalt, + completeCheckpoint: staged), outcome: .adoptionFailed, + matchedTokens: matched) + } + } + // A tracked engine must never adopt an untracked/foreign stage. + guard !hasNativeCompletionTracking else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } _ = try planCompleteCheckpointImport(manifest: staged.manifest, request: request) guard staged.maximumSequenceLength == maximumLength, - staged.codec === completeCheckpointCodec else { + staged.codec === completeCheckpointCodec + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } let matched = staged.manifest.position var plan: CBv2PrefixReusePlan - if staged.codec.historicalLayout != nil { - plan = try staged.codec.historicalReusePlan(position: matched, maximumSequenceLength: maximumLength) + if staged.codec.contiguousLayout != nil { + plan = try staged.codec.contiguousReusePlan( + position: matched, maximumSequenceLength: maximumLength) + } else if staged.codec.historicalLayout != nil { + plan = try staged.codec.historicalReusePlan( + position: matched, maximumSequenceLength: maximumLength) } else { let exactKVBytes = staged.manifest.tensors.reduce(0) { total, tensor in - total + ((tensor.role == .keys || tensor.role == .values) ? tensor.byteCount : 0) + total + + ((tensor.role == .keys || tensor.role == .values) ? tensor.byteCount : 0) } - let reuseBackend: CBv2PrefixReuseBackend = staged.usesPagedBacking ? .pagedFP16 : .contiguousUnquantized - let capability = CBv2PrefixReuseCapability.derive(layerKinds: layerKinds, backend: reuseBackend) - guard let recurrentPlan = capability.plan( - matchedBoundary: matched, exactStagedFullKVBytes: exactKVBytes, - maximumSequenceLength: maximumLength, - nominalFullKVBytesPerToken: staged.codec.admission.fullKVBytesPerToken, - reserveFullSequenceTokens: true), + let reuseBackend: CBv2PrefixReuseBackend = + staged.usesPagedBacking ? .pagedFP16 : .contiguousUnquantized + let capability = CBv2PrefixReuseCapability.derive( + layerKinds: layerKinds, backend: reuseBackend) + guard + let recurrentPlan = capability.plan( + matchedBoundary: matched, exactStagedFullKVBytes: exactKVBytes, + maximumSequenceLength: maximumLength, + nominalFullKVBytesPerToken: staged.codec.admission.fullKVBytesPerToken, + reserveFullSequenceTokens: true), recurrentPlan.strategy == .direct, recurrentPlan.replayStart == matched else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } plan = recurrentPlan } - // Every complete-checkpoint adopter resumes at `matched` under + if staged.codec.contiguousLayout != nil { + plan.recurrentChunkSize = staged.manifest.chunkSize + plan.recurrentPromptLength = request.promptTokens.count + } + // Chunk-agnostic complete-checkpoint adopters resume at `matched` under // ordinary scheduling: solo stripes, plain chunks and the // first-token projection all apply, and no bounded geometry wait // can cold-restart it. A recurrent adopter no longer continues @@ -86,11 +193,13 @@ extension EngineV2 { return .init( adoption: .init( requestID: receiptID, tokens: request.promptTokens, matched: matched, - plan: plan, prefix: [], cacheSalt: request.checkpointCacheSalt, completeCheckpoint: staged), + plan: plan, prefix: [], cacheSalt: request.checkpointCacheSalt, + completeCheckpoint: staged), outcome: .adoptionFailed, matchedTokens: matched) } catch { staged.close() - return .init(adoption: nil, outcome: .adoptionFailed, matchedTokens: staged.manifest.position) + return .init( + adoption: nil, outcome: .adoptionFailed, matchedTokens: staged.manifest.position) } } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalAttentionLayout.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalAttentionLayout.swift index 605144a45f..0dfe6dd47d 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalAttentionLayout.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalAttentionLayout.swift @@ -15,15 +15,90 @@ public struct CBv2CheckpointAttentionLayer: Codable, Sendable, Equatable { public let window: Int? public let kvHeads: Int public let headDim: Int + private let explicitValueHeadDim: Int? + public var valueHeadDim: Int { explicitValueHeadDim ?? headDim } public let queryHeads: Int public let hasSinks: Bool public let dtype: CBv2CheckpointDType + init( + modelLayer: Int, owner: Int, window: Int?, kvHeads: Int, headDim: Int, + valueHeadDim: Int? = nil, queryHeads: Int, hasSinks: Bool, dtype: CBv2CheckpointDType + ) { + self.modelLayer = modelLayer + self.owner = owner + self.window = window + self.kvHeads = kvHeads + self.headDim = headDim + explicitValueHeadDim = valueHeadDim == headDim ? nil : valueHeadDim + self.queryHeads = queryHeads + self.hasSinks = hasSinks + self.dtype = dtype + } + + private enum CodingKeys: String, CodingKey { + case modelLayer, owner, window, kvHeads, headDim, valueHeadDim, queryHeads, hasSinks, dtype + } + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + self.init( + modelLayer: try c.decode(Int.self, forKey: .modelLayer), + owner: try c.decode(Int.self, forKey: .owner), + window: try c.decodeIfPresent(Int.self, forKey: .window), + kvHeads: try c.decode(Int.self, forKey: .kvHeads), + headDim: try c.decode(Int.self, forKey: .headDim), + valueHeadDim: try c.decodeIfPresent(Int.self, forKey: .valueHeadDim), + queryHeads: try c.decode(Int.self, forKey: .queryHeads), + hasSinks: try c.decode(Bool.self, forKey: .hasSinks), + dtype: try c.decode(CBv2CheckpointDType.self, forKey: .dtype)) + } + public func encode(to encoder: any Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(modelLayer, forKey: .modelLayer) + try c.encode(owner, forKey: .owner) + try c.encodeIfPresent(window, forKey: .window) + try c.encode(kvHeads, forKey: .kvHeads) + try c.encode(headDim, forKey: .headDim) + try c.encodeIfPresent(explicitValueHeadDim, forKey: .valueHeadDim) + try c.encode(queryHeads, forKey: .queryHeads) + try c.encode(hasSinks, forKey: .hasSinks) + try c.encode(dtype, forKey: .dtype) + } + /// Provider identity must use the same owner map as native staging. public static func resolve(layerKinds: [CBv2LayerKind], dtypes: [DType]) throws -> [Self] { try CBv2HistoricalAttentionLayout(layerKinds: layerKinds, dtypes: dtypes).layers } + /// The distinct contiguous-asymmetric v2 format uses this exact map. + /// Do not broaden the legacy equal-width historical resolver. + public static func resolveContiguousAsymmetric(layerKinds: [CBv2LayerKind], dtypes: [DType]) + throws -> [Self] + { + guard layerKinds.contains(where: { $0.headDim != $0.valueHeadDim }) else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + return try CBv2HistoricalAttentionLayout( + layerKinds: layerKinds, dtypes: dtypes, + allowAsymmetric: true + ).layers + } + + /// Scalar identity only for the distinct page-native asymmetric format. + /// Native permission still requires the package-issued loaded/page/store + /// tuple. Never broadens the legacy equal-width resolver. + public static func resolvePagedAsymmetric(layerKinds: [CBv2LayerKind], dtypes: [DType]) throws + -> [Self] + { + guard layerKinds.contains(where: { $0.headDim != $0.valueHeadDim }) else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + return try CBv2HistoricalAttentionLayout( + layerKinds: layerKinds, dtypes: dtypes, + allowAsymmetric: true + ).layers + } + func tokenStart(at position: Int) -> Int { window.map { max(0, position - $0) } ?? 0 } } @@ -31,17 +106,31 @@ struct CBv2HistoricalAttentionLayout: Sendable { let layers: [CBv2CheckpointAttentionLayer] var owningIndices: [Int] { layers.indices.filter { layers[$0].owner == $0 } } - init(layerKinds: [CBv2LayerKind], dtypes: [DType]) throws { + init(layerKinds: [CBv2LayerKind], dtypes: [DType], allowAsymmetric: Bool = false) throws { guard !layerKinds.isEmpty, layerKinds.count <= 2048, layerKinds.count == dtypes.count else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + // The new contiguous table covers target attention KV only. Do not + // silently discard learned indexer or any other non-KV side state. + if allowAsymmetric { + guard + layerKinds.allSatisfy({ + $0.qwen4IndexerCompressRatio == nil && $0.extraStorageBytesPerToken == 0 + }) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + } var result: [CBv2CheckpointAttentionLayer] = [] var modelIndices = Set() for (index, kind) in layerKinds.enumerated() { guard !kind.isBidirectional, kind.kvHeads > 0, kind.headDim >= 64, - kind.queryHeads > 0, kind.queryHeads % kind.kvHeads == 0, - (kind.modelLayerIndex ?? index) >= 0, let dtype = CBv2CheckpointDType(dtypes[index]), dtype.isFloatingPoint, - modelIndices.insert(kind.modelLayerIndex ?? index).inserted + kind.valueHeadDim > 0, kind.kvGeometry != nil, + allowAsymmetric || kind.valueHeadDim == kind.headDim, + kind.queryHeads > 0, kind.queryHeads % kind.kvHeads == 0, + (kind.modelLayerIndex ?? index) >= 0, + let dtype = CBv2CheckpointDType(dtypes[index]), dtype.isFloatingPoint, + modelIndices.insert(kind.modelLayerIndex ?? index).inserted else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } let window: Int? switch kind.attention { @@ -53,15 +142,20 @@ struct CBv2HistoricalAttentionLayout: Sendable { let owner = kind.sharesKVWithLayer ?? index if owner != index { guard owner >= 0, owner < index, result[owner].owner == owner, - result[owner].window == window, result[owner].kvHeads == kind.kvHeads, - result[owner].headDim == kind.headDim, result[owner].dtype == dtype + result[owner].window == window, result[owner].kvHeads == kind.kvHeads, + result[owner].headDim == kind.headDim, + result[owner].valueHeadDim == kind.valueHeadDim, + result[owner].dtype == dtype else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } } else if kind.sharesKVWithLayer != nil { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } - result.append(.init(modelLayer: kind.modelLayerIndex ?? index, owner: owner, - window: window, kvHeads: kind.kvHeads, headDim: kind.headDim, - queryHeads: kind.queryHeads, hasSinks: kind.hasSinks, dtype: dtype)) + result.append( + .init( + modelLayer: kind.modelLayerIndex ?? index, owner: owner, + window: window, kvHeads: kind.kvHeads, headDim: kind.headDim, + valueHeadDim: kind.valueHeadDim, queryHeads: kind.queryHeads, + hasSinks: kind.hasSinks, dtype: dtype)) } layers = result } @@ -70,9 +164,13 @@ struct CBv2HistoricalAttentionLayout: Sendable { try owningIndices.flatMap { index in let layer = layers[index] return try [CBv2CheckpointTensorRole.keys, .values].map { - try CBv2CheckpointTensorDescriptor(role: $0, layer: layer.modelLayer, - shape: [1, layer.kvHeads, position - layer.tokenStart(at: position), layer.headDim], - dtype: layer.dtype) + try CBv2CheckpointTensorDescriptor( + role: $0, layer: layer.modelLayer, + shape: [ + 1, layer.kvHeads, position - layer.tokenStart(at: position), + $0 == .keys ? layer.headDim : layer.valueHeadDim, + ], + dtype: layer.dtype) } } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalCompleteCheckpoint.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalCompleteCheckpoint.swift index dcdcea5108..45413cebc4 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalCompleteCheckpoint.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalCompleteCheckpoint.swift @@ -1,17 +1,205 @@ +import Foundation import MLX +private final class CBv2HistoricalPagedWeakRow { + weak var value: (any CBv2SequenceKV)? + init(_ value: any CBv2SequenceKV) { self.value = value } +} + +/// Export and capture share this actual payload owner, not a copied byte claim. +/// A tracked capture/work keeps it until its required native completion. +private final class CBv2HistoricalPagedAssistantBacking { + var checkpoint: (any CBv2MTPPrefixCheckpoint)? + let reservation: CBv2CheckpointReservation + let reservedBytes: Int + let destinationBound: Int + init(reservation: CBv2CheckpointReservation, bytes: Int, destinationBound: Int) { + self.reservation = reservation + reservedBytes = bytes + self.destinationBound = destinationBound + } + deinit { + checkpoint = nil + reservation.release() + } +} + /// Request-local exact boundary. Window owners were copied at launch; full /// pages remain with the donor until its existing retirement/donation barrier. -struct CBv2HistoricalCompleteCheckpoint { +final class CBv2HistoricalCompleteCheckpoint { let position: Int let chunkSize: Int - let windows: [Int: CBv2HistoricalWindow] - var evaluationRoots: [MLXArray] { windows.values.compactMap(\.evaluationRoot) } - /// Staged transient bytes: window copies only; full pages stay with the donor. - var reservedBytes: Int { windows.values.reduce(0) { $0 + $1.reservedBytes } } + private(set) var windows: [Int: CBv2HistoricalWindow] + let requiresAssistant: Bool + private weak var codec: CBv2CompleteCheckpointCodec? + private var sourceRows: [Int: CBv2HistoricalPagedWeakRow] = [:] + private var assistantBacking: CBv2HistoricalPagedAssistantBacking? + private var ready = false + private var failed = false + private let stream: StreamOrDevice + var evaluationRoots: [MLXArray] { + windows.values.flatMap(\.evaluationRoots) + + (assistantBacking?.checkpoint?.evaluationTargets ?? []) + } + /// Copies and their host witnesses; full pages stay with the actual donor. + var reservedBytes: Int { + windows.values.reduce(assistantBacking?.reservedBytes ?? 0) { $0 + $1.reservedBytes } + } + var assistantCheckpoint: (any CBv2MTPPrefixCheckpoint)? { assistantBacking?.checkpoint } + var assistantRetainedOwners: [AnyObject] { assistantBacking.map { [$0] } ?? [] } + + // Legacy target-only callers keep their existing construction contract. + init(position: Int, chunkSize: Int, windows: [Int: CBv2HistoricalWindow]) { + self.position = position + self.chunkSize = chunkSize + self.windows = windows + requiresAssistant = false + stream = .default + } + + /// Native preparation creates/retains this owner BEFORE constructing any + /// window copy. Actual row-ledger identities bind all captured full pages. + init( + codec: CBv2CompleteCheckpointCodec, position: Int, chunkSize: Int, + state: [CBv2SequenceKV?] + ) throws { + guard codec.isNativePagedHistorical, let binding = codec.nativePagedBinding, + let layout = codec.historicalLayout, position > 1, chunkSize > 1, + position % chunkSize == 0, state.count == layout.layers.count + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + self.position = position + self.chunkSize = chunkSize + windows = [:] + requiresAssistant = codec.assistant != nil + self.codec = codec + stream = .default + var cohort: UUID? + for index in layout.owningIndices { + guard let row = state[index] else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let actual = try binding.metadata(row: row, layer: index) + guard actual.offset == position, cohort == nil || actual.request == cohort else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + cohort = actual.request + } + let descriptors = try codec.tensorDescriptors(position: position) + let auxiliary = Array(descriptors.dropFirst(codec.targetTensorCount)) + let host = try CBv2CheckpointAllocationFootprint.add(64 << 10, layout.layers.count * 512) + let bytes = + requiresAssistant + ? try CBv2CheckpointAllocationFootprint.add( + host, + CBv2HistoricalMTPCheckpointFootprint.captureBytes( + position: position, descriptors: auxiliary)) + : host + let destination = + requiresAssistant + ? try CBv2HistoricalMTPCheckpointFootprint.nativeDestinationBound(auxiliary) : 0 + assistantBacking = .init( + reservation: try codec.admission.reserveTransient(bytes: bytes), + bytes: bytes, destinationBound: destination) + for index in layout.owningIndices { sourceRows[index] = .init(state[index]!) } + } + + func installWindow(_ window: CBv2HistoricalWindow, layer: Int) throws { + guard codec != nil, !ready, !failed, windows[layer] == nil, window.position == position + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + windows[layer] = window + } + + func validatesSourceRows( + _ state: [CBv2SequenceKV?], codec expected: CBv2CompleteCheckpointCodec + ) -> Bool { + guard expected.isNativePagedHistorical else { return codec == nil } + guard codec === expected, let layout = expected.historicalLayout, ready, !failed, + state.count == layout.layers.count + else { return false } + return layout.owningIndices.allSatisfy { sourceRows[$0]?.value === state[$0] } + } + + func captureSettledAssistant(requestState: any CBv2MTPRequestState) throws { + guard !ready, !failed, requiresAssistant, let backing = assistantBacking, + backing.checkpoint == nil, let codec, + let assistant = codec.assistant as? any CBv2HistoricalMTPPrefixCheckpointCoding + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + do { + try withError { fault in + guard + let value = assistant.capturePrefixCheckpoint( + requestState: requestState, + targetInputCount: position), value.targetInputCount == position + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + backing.checkpoint = value // keep the actual partial copy before inspecting errors + try fault.check() + let expected = Array( + try codec.tensorDescriptors(position: position).dropFirst( + codec.targetTensorCount)) + guard let arrays = assistant.encodePrefixCheckpoint(value), + arrays.count == expected.count, + zip(arrays, expected).allSatisfy({ + $0.0.shape == $0.1.shape && $0.0.dtype == $0.1.dtype.mlxDType + }) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + } + } catch { + failed = true + throw error + } + } + func markSubmitted() { for window in windows.values { window.markSubmitted() } } func finishEvaluation() throws { - for window in windows.values { try window.finishEvaluation() } + guard !failed else { throw CBv2CompleteCheckpointError.allocationFailed } + if ready { return } + guard !requiresAssistant || assistantBacking?.checkpoint != nil else { + throw CBv2CompleteCheckpointError.incompleteTransfer + } + do { + try finishEvaluationForRetirement() + if let backing = assistantBacking, let checkpoint = backing.checkpoint { + let footprint = try CBv2CheckpointAllocationFootprint.freshBytes( + checkpoint.evaluationTargets) + guard footprint.bound == backing.destinationBound else { + throw CBv2CompleteCheckpointError.allocationFailed + } + } + ready = true + } catch { + failed = true + throw error + } + } + + /// Cancelled pre-observation captures may have no head copy. Their actual + /// submitted target copies must still finish; no assistant is synthesized. + func finishEvaluationForRetirement() throws { + guard !failed else { throw CBv2CompleteCheckpointError.allocationFailed } + do { + for window in windows.values { try window.finishEvaluation() } + if let checkpoint = assistantBacking?.checkpoint { + try withError { fault in + eval(checkpoint.evaluationTargets) + try fault.check() + stream.stream.synchronize() + try fault.check() + } + } + } catch { + failed = true + throw error + } } } @@ -19,14 +207,20 @@ extension CBv2CompleteCheckpointCodec { /// The stage transfers complete target state, including exact windows. /// This is a direct resume contract; attention-only replay capability is /// intentionally not used to infer a historical window that it never owns. - func historicalReusePlan(position: Int, maximumSequenceLength: Int) throws -> CBv2PrefixReusePlan { + func historicalReusePlan(position: Int, maximumSequenceLength: Int) throws + -> CBv2PrefixReusePlan + { guard let layout = historicalLayout, position > 1, maximumSequenceLength > position else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } var bytesPerToken = 0 - for (index, layer) in layout.layers.enumerated() where layer.owner == index && layer.window == nil { - let bytes = try CBv2CheckpointTensorDescriptor.checkedByteCount( - shape: [2, layer.kvHeads, layer.headDim], dtype: layer.dtype.mlxDType) + for (index, layer) in layout.layers.enumerated() + where layer.owner == index && layer.window == nil { + let keyBytes = try CBv2CheckpointTensorDescriptor.checkedByteCount( + shape: [layer.kvHeads, layer.headDim], dtype: layer.dtype.mlxDType) + let valueBytes = try CBv2CheckpointTensorDescriptor.checkedByteCount( + shape: [layer.kvHeads, layer.valueHeadDim], dtype: layer.dtype.mlxDType) + let bytes = try CBv2CheckpointAllocationFootprint.add(keyBytes, valueBytes) let (next, overflow) = bytesPerToken.addingReportingOverflow(bytes) guard !overflow else { throw CBv2CompleteCheckpointError.invalidManifest } bytesPerToken = next @@ -49,12 +243,14 @@ extension CBv2CompleteCheckpointCodec { tokens: [Int], cacheSalt: String? ) throws -> CBv2CompleteCheckpointExport { guard let layout = historicalLayout, checkpoint.position < tokens.count, - state.count == layerKinds.count + state.count == layerKinds.count, checkpoint.validatesSourceRows(state, codec: self) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } - let permit = try CBv2CheckpointManifestMemory.Permit(admission: admission, position: checkpoint.position) + let permit = try CBv2CheckpointManifestMemory.Permit( + admission: admission, position: checkpoint.position) return try withExtendedLifetime(permit) { - try makeHistoricalExport(checkpoint: checkpoint, state: state, layout: layout, - tokens: tokens, cacheSalt: cacheSalt, permit: permit) + try makeHistoricalExport( + checkpoint: checkpoint, state: state, layout: layout, + tokens: tokens, cacheSalt: cacheSalt, permit: permit) } } @@ -63,38 +259,59 @@ extension CBv2CompleteCheckpointCodec { layout: CBv2HistoricalAttentionLayout, tokens: [Int], cacheSalt: String?, permit: CBv2CheckpointManifestMemory.Permit ) throws -> CBv2CompleteCheckpointExport { - let descriptors = try layout.tensorDescriptors(position: checkpoint.position) + let descriptors = try tensorDescriptors(position: checkpoint.position) var sources: [CBv2CompleteCheckpointTensorSource] = [] for index in layout.owningIndices { guard let row = state[index] as? PagedSequenceKV, - row.pool.layerKinds == layerKinds, row.groupKey.dtype == kvDTypes[index], - row.groupKey == row.pool.groupKey(forLayer: index) + row.pool.layerKinds == layerKinds, row.groupKey.dtype == kvDTypes[index], + row.groupKey == row.pool.groupKey(forLayer: index) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } if layout.layers[index].window != nil { - guard let window = checkpoint.windows[index], window.position == checkpoint.position, - window.start == layout.layers[index].tokenStart(at: checkpoint.position) + guard let window = checkpoint.windows[index], + window.position == checkpoint.position, + window.start == layout.layers[index].tokenStart(at: checkpoint.position) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } sources.append(.historicalWindow(.init(window: window, values: false))) sources.append(.historicalWindow(.init(window: window, values: true))) } else { - let map = try CBv2PagedCheckpointPageMap(row: row, position: checkpoint.position, admission: admission) + let map = try CBv2PagedCheckpointPageMap( + row: row, position: checkpoint.position, admission: admission) sources.append(.paged(try .init(pageMap: map, values: false))) sources.append(.paged(try .init(pageMap: map, values: true))) } } for index in layout.layers.indices where layout.layers[index].owner != index { - guard state[index] == nil else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + guard state[index] == nil else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } } - guard zip(sources, descriptors).allSatisfy({ $0.0.matches($0.1) }) else { + if let assistant { + guard isNativePagedHistorical, let checkpoint = checkpoint.assistantCheckpoint, + let arrays = assistant.encodePrefixCheckpoint(checkpoint) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + sources.append(contentsOf: arrays.map { .array($0) }) + } else if checkpoint.assistantCheckpoint != nil { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + guard sources.count == descriptors.count, + zip(sources, descriptors).allSatisfy({ $0.0.matches($0.1) }) + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } let manifest = CBv2CompleteCheckpointManifest( schemaVersion: CBv2CompleteCheckpointManifest.currentSchemaVersion, identity: identity, - backendLayout: backendLayout, position: checkpoint.position, chunkSize: checkpoint.chunkSize, - cacheSalt: cacheSalt, assistantCodecID: nil, - metadata: .init(tokens: Array(tokens.prefix(checkpoint.position)), tensors: descriptors, - attentionLayers: layout.layers, permit: permit)) + backendLayout: backendLayout, position: checkpoint.position, + chunkSize: checkpoint.chunkSize, + cacheSalt: cacheSalt, assistantCodecID: assistant?.prefixCheckpointCodecID, + metadata: .init( + tokens: Array(tokens.prefix(checkpoint.position)), tensors: descriptors, + attentionLayers: layout.layers, permit: permit)) _ = try manifest.validateStructure() - return .init(manifest: manifest, sources: sources, usesProcessMemoryOwner: admission.hasProcessMemoryOwner) + return .init( + manifest: manifest, sources: sources, + usesProcessMemoryOwner: admission.hasProcessMemoryOwner, + retainedOwners: checkpoint.assistantRetainedOwners) } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalMTPCheckpointFootprint.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalMTPCheckpointFootprint.swift new file mode 100644 index 0000000000..f2045aef35 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalMTPCheckpointFootprint.swift @@ -0,0 +1,41 @@ +/// Conservative additional ownership for an historical assistant checkpoint. +/// This is an admission promise, never measured backing or refundable credit. +enum CBv2HistoricalMTPCheckpointFootprint { + static func retainedHostBytes(position: Int) throws -> Int { + guard position >= 4 else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + let value = position.multipliedReportingOverflow(by: 8) + guard !value.overflow else { throw CBv2CompleteCheckpointError.invalidManifest } + return try CBv2CheckpointAllocationFootprint.add(value.partialValue, 64 << 10) + } + + static func nativeDestinationBound(_ descriptors: [CBv2CheckpointTensorDescriptor]) throws + -> Int + { + guard !descriptors.isEmpty, descriptors.count <= 4096 else { + throw CBv2CompleteCheckpointError.invalidManifest + } + return try descriptors.reduce(0) { total, descriptor in + try descriptor.validate() + return try CBv2CheckpointAllocationFootprint.add( + total, + CBv2CheckpointAllocationFootprint.bound(descriptor.byteCount)) + } + } + + /// Source views, compact destination and a temporary copy generation may + /// coexist. The donor's request reservation separately retains its complete + /// native backing until this copy's real completion; no max-layer discount. + static func captureBytes(position: Int, descriptors: [CBv2CheckpointTensorDescriptor]) throws + -> Int + { + let native = try nativeDestinationBound(descriptors) + let generations = native.multipliedReportingOverflow(by: 3) + guard !generations.overflow else { throw CBv2CompleteCheckpointError.invalidManifest } + let scalar = try CBv2CheckpointAllocationFootprint.bound(1) + let controls = scalar.multipliedReportingOverflow(by: descriptors.count * 2) + guard !controls.overflow else { throw CBv2CompleteCheckpointError.invalidManifest } + return try CBv2CheckpointAllocationFootprint.add( + CBv2CheckpointAllocationFootprint.add(generations.partialValue, controls.partialValue), + retainedHostBytes(position: position)) + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalMTPCheckpointManifest.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalMTPCheckpointManifest.swift new file mode 100644 index 0000000000..7eca80fbf1 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalMTPCheckpointManifest.swift @@ -0,0 +1,40 @@ +extension CBv2CompleteCheckpointManifest { + /// Structural validation only. The loaded assistant codec still must match + /// every descriptor, decode the exact metadata/token witness, and authorize + /// restoration into its current request owner. No arrays are allocated here. + func validateHistoricalAssistantStructure(targetTensorCount: Int) throws { + let auxiliary = Array(tensors.dropFirst(targetTensorCount)) + let allowed: Set = [ + .assistantKeys, .assistantValues, .assistantCacheMetadata, + .assistantHidden, .assistantTokens, .assistantFrontier, + ] + guard !auxiliary.isEmpty, auxiliary.allSatisfy({ allowed.contains($0.role) }), + auxiliary.contains(where: { $0.role == .assistantHidden && $0.dtype.isFloatingPoint }), + auxiliary.contains(where: { + $0.role == .assistantTokens && $0.dtype == .int32 + && $0.layer == nil && $0.shape == [1, position] + }), + auxiliary.contains(where: { + $0.role == .assistantCacheMetadata + && ($0.dtype == .int32 || $0.dtype == .int64) + }) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let keys = auxiliary.filter { $0.role == .assistantKeys } + let values = auxiliary.filter { $0.role == .assistantValues } + guard !keys.isEmpty, keys.count == values.count else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + for key in keys { + guard let head = key.layer, key.shape.count == 4, key.shape[0] == 1, + key.dtype.isFloatingPoint, + let value = values.first(where: { $0.layer == head }), + value.shape.count == 4, value.dtype == key.dtype, + Array(value.shape.prefix(3)) == Array(key.shape.prefix(3)) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + } + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalWindowCapture.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalWindowCapture.swift index b3e36af64d..724c8cd314 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalWindowCapture.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/HistoricalWindowCapture.swift @@ -2,18 +2,22 @@ import Cmlx import Foundation import MLX -/// One immutable [2,1,H,W,D] output captured before any successor graph writes -/// its donor ring. No materialization credit is inferred from aliases/nbytes. -/// Its conservative native allocation charge survives all export K/V sources. +/// Immutable native-byte copy before a successor writes its donor ring. +/// Equal widths keep the original [2,1,H,W,D] allocation; asymmetric roles own +/// separate [1,H,W,Dk/Dv] buffers. No materialization credit comes from aliases. +/// The conservative charge survives the last exported K/V source. final class CBv2HistoricalWindow: @unchecked Sendable { let start: Int let position: Int let heads: Int let headDim: Int + let valueHeadDim: Int let dtype: DType /// Transient admission bytes charged for this window until retirement. let reservedBytes: Int private var combined: MLXArray? + private var asymmetricKeys: MLXArray? + private var asymmetricValues: MLXArray? private var reservation: CBv2CheckpointReservation? private enum Evaluation { case pending, ready, failed } private var evaluation = Evaluation.pending @@ -24,11 +28,19 @@ final class CBv2HistoricalWindow: @unchecked Sendable { let copyStream: StreamOrDevice private let synchronize: (StreamOrDevice) throws -> Void private let evaluate: (MLXArray) throws -> Void + // Preserve the legacy one-root observation for equal-width captures. var evaluationRoot: MLXArray? { combined } + // Each Depends result must itself be observed as evaluated, even though + // both roots reach the same final copy fence. No whole-output concat/cast. + var evaluationRoots: [MLXArray] { + if let combined { return [combined] } + return [asymmetricKeys, asymmetricValues].compactMap { $0 } + } static func reservationBytes(row: PagedSequenceKV, position: Int) throws -> Int { guard let window = row.windowSize, row.pool.segmentGrant != nil, - position <= row.absoluteOffset, position > 1 else { + position <= row.absoluteOffset, position > 1, position <= Int(Int32.max) + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } // An interior position (behind the frontier) is exact only while the @@ -41,33 +53,60 @@ final class CBv2HistoricalWindow: @unchecked Sendable { guard position - count >= row.oldestValidPosition else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } - let bytes = try CBv2CheckpointTensorDescriptor.checkedByteCount( - shape: [2, 1, row.groupKey.kvHeads, count, row.groupKey.headDim], dtype: row.groupKey.dtype) - let pageSpan = (count + row.pool.config.pageSize - 2) / row.pool.config.pageSize + 1 + let key = row.groupKey + func add(_ a: Int, _ b: Int) throws -> Int { + try CBv2CheckpointAllocationFootprint.add(a, b) + } + func multiply(_ a: Int, _ b: Int) throws -> Int { + guard let value = CBv2KVGeometry.multiply(a, b) else { + throw CBv2CompleteCheckpointError.invalidManifest + } + return value + } + func bound(_ bytes: Int) throws -> Int { + try Memory.allocationFootprintUpperBound(byteCount: bytes) + } + let output: Int + let scalar: Int + if key.isAsymmetric { + let keys = try CBv2CheckpointTensorDescriptor.checkedByteCount( + shape: [1, key.kvHeads, count, key.headDim], dtype: key.dtype) + let values = try CBv2CheckpointTensorDescriptor.checkedByteCount( + shape: [1, key.kvHeads, count, key.valueHeadDim], dtype: key.dtype) + // Distinct output/zero-scalar allocations: never bound the sum as + // if it were a single buffer or discount V to the K width. + output = try add(bound(keys), bound(values)) + scalar = try multiply(2, bound(key.dtype.size)) + } else { + let bytes = try CBv2CheckpointTensorDescriptor.checkedByteCount( + shape: [2, 1, key.kvHeads, count, key.headDim], dtype: key.dtype) + output = try bound(bytes) + scalar = try bound(key.dtype.size) + } + let numerator = try add(count - 1, row.pool.config.pageSize - 1) + let pageSpan = numerator / row.pool.config.pageSize + 1 let segments = min(pageSpan, row.pool.group(row.groupKey).segments.count) - func bound(_ bytes: Int) throws -> Int { try Memory.allocationFootprintUpperBound(byteCount: bytes) } // Each bucket has <=count records. Bound separately because cached // buffers may be larger than logical sizes; a total-byte bound is wrong. - let output = try bound(bytes) - let records = try bound(max(24, count * 3) * MemoryLayout.stride) + let records = try bound(multiply(max(24, multiply(count, 3)), MemoryLayout.stride)) let fence = try bound(MemoryLayout.stride) - // The zeros scalar and prospective completion witness are distinct. - let scalar = try bound(row.groupKey.dtype.size) - let host = (64 << 10) + 4 * (count * 4 * MemoryLayout.stride + pageSpan * MemoryLayout.stride) - let (transfer, multiplyOverflow) = segments.multipliedReportingOverflow(by: records + fence) - let (total, overflow) = transfer.addingReportingOverflow(output + scalar + fence + host) - guard !multiplyOverflow, !overflow else { throw CBv2CompleteCheckpointError.invalidManifest } - return total + let hostRecords = try multiply(multiply(count, 4), MemoryLayout.stride) + let hostPages = try multiply(pageSpan, MemoryLayout.stride) + let host = try add(64 << 10, multiply(4, add(hostRecords, hostPages))) + let transfer = try multiply(segments, add(records, fence)) + return try add(transfer, add(output, add(scalar, add(fence, host)))) } - init(row: PagedSequenceKV, position: Int, admission: AdmissionV2, - stream: StreamOrDevice = .default, - beforeAllocation: () throws -> Void = {}, - afterConstruction: (MLXArray) throws -> Void = { _ in }, - evaluate: @escaping (MLXArray) throws -> Void = { array in try withError { eval(array) } }, - synchronize: @escaping (StreamOrDevice) throws -> Void = { stream in - try withError { stream.stream.synchronize() } - }) throws { + init( + row: PagedSequenceKV, position: Int, admission: AdmissionV2, + stream: StreamOrDevice = .default, + beforeAllocation: () throws -> Void = {}, + afterConstruction: (MLXArray) throws -> Void = { _ in }, + evaluate: @escaping (MLXArray) throws -> Void = { array in try withError { eval(array) } }, + synchronize: @escaping (StreamOrDevice) throws -> Void = { stream in + try withError { stream.stream.synchronize() } + } + ) throws { let bytes = try Self.reservationBytes(row: row, position: position) let permit = try admission.reserveTransient(bytes: bytes) self.position = position @@ -75,6 +114,7 @@ final class CBv2HistoricalWindow: @unchecked Sendable { start = max(0, position - row.windowSize!) heads = row.groupKey.kvHeads headDim = row.groupKey.headDim + valueHeadDim = row.groupKey.valueHeadDim dtype = row.groupKey.dtype reservation = permit self.evaluate = evaluate @@ -89,11 +129,21 @@ final class CBv2HistoricalWindow: @unchecked Sendable { let pages = (start / pageSize ... (position - 1) / pageSize).map { row.table[$0 % row.ringPages!] } - combined = PagedSegmentTransfers.gatherCombined( - group: row.pool.group(row.groupKey), pages: pages, - firstSlot: start % pageSize, count: position - start, publishReadFence: false, - stream: copyStream) - if let combined { try afterConstruction(combined) } + let group = row.pool.group(row.groupKey) + if row.groupKey.isAsymmetric { + let copied = PagedAsymmetricTransfers.gatherSegmented( + group: group, pages: pages, firstSlot: start % pageSize, + count: position - start, publishReadFence: false, stream: copyStream) + asymmetricKeys = copied.keys + asymmetricValues = copied.values + } else { + combined = PagedSegmentTransfers.gatherCombined( + group: group, pages: pages, + firstSlot: start % pageSize, count: position - start, + publishReadFence: false, + stream: copyStream) + } + for root in evaluationRoots { try afterConstruction(root) } } } catch { // Construction submits no copy work and never publishes a group @@ -101,6 +151,8 @@ final class CBv2HistoricalWindow: @unchecked Sendable { // retain this destination after the output is dropped. evaluation = .failed combined = nil + asymmetricKeys = nil + asymmetricValues = nil reservation = nil throw error } @@ -116,10 +168,13 @@ final class CBv2HistoricalWindow: @unchecked Sendable { case .failed: throw CBv2CompleteCheckpointError.allocationFailed case .pending: break } - guard let combined else { throw CBv2CompleteCheckpointError.closed } + let roots = evaluationRoots + guard roots.count == (headDim == valueHeadDim ? 1 : 2) else { + throw CBv2CompleteCheckpointError.closed + } do { submitted = true - try evaluate(combined) + for root in roots { try evaluate(root) } evaluation = .ready } catch { // asyncEval may already have submitted part of the private copy. @@ -135,20 +190,26 @@ final class CBv2HistoricalWindow: @unchecked Sendable { } func read(values: Bool, byteOffset: Int, maximumBytes: Int) throws -> Data { - guard let combined else { throw CBv2CompleteCheckpointError.closed } - let bytes = heads * (position - start) * headDim * dtype.size + guard let array = combined ?? (values ? asymmetricValues : asymmetricKeys) else { + throw CBv2CompleteCheckpointError.closed + } + let bytes = try CBv2CheckpointTensorDescriptor.checkedByteCount( + shape: [1, heads, position - start, values ? valueHeadDim : headDim], dtype: dtype) guard byteOffset >= 0, byteOffset < bytes, byteOffset % dtype.size == 0, - maximumBytes >= dtype.size, maximumBytes <= CBv2CompleteCheckpointManifest.maximumSegmentBytes + maximumBytes >= dtype.size, + maximumBytes <= CBv2CompleteCheckpointManifest.maximumSegmentBytes else { throw CBv2CompleteCheckpointError.invalidSegment } // Launch submitted the completion edge on the engine's sole evaluator. // Readback here only waits for that already detached immutable output. try finishEvaluation() - guard let info = try combined.evaluatedBufferInfo(), info.isRowContiguous, - info.dataElements == combined.size, - let pointer = mlx_array_data_uint8(combined.ctx) + guard let info = try array.evaluatedBufferInfo(), info.isRowContiguous, + info.dataOffset == 0, info.dataElements == array.size, + let pointer = mlx_array_data_uint8(array.ctx) else { throw CBv2CompleteCheckpointError.allocationFailed } let count = min(maximumBytes - maximumBytes % dtype.size, bytes - byteOffset) - return Data(bytes: UnsafeRawPointer(pointer).advanced(by: (values ? bytes : 0) + byteOffset), count: count) + let roleOffset = values && combined != nil ? bytes : 0 + return Data( + bytes: UnsafeRawPointer(pointer).advanced(by: roleOffset + byteOffset), count: count) } deinit { @@ -161,6 +222,8 @@ final class CBv2HistoricalWindow: @unchecked Sendable { try? synchronize(copyStream) } combined = nil + asymmetricKeys = nil + asymmetricValues = nil reservation?.release() reservation = nil } @@ -169,18 +232,49 @@ final class CBv2HistoricalWindow: @unchecked Sendable { final class CBv2HistoricalWindowTensorSource { private var window: CBv2HistoricalWindow? private let values: Bool - init(window: CBv2HistoricalWindow, values: Bool) { self.window = window; self.values = values } + init(window: CBv2HistoricalWindow, values: Bool) { + self.window = window + self.values = values + } func matches(_ descriptor: CBv2CheckpointTensorDescriptor) -> Bool { guard let window else { return false } return descriptor.role == (values ? .values : .keys) && descriptor.dtype.mlxDType == window.dtype - && descriptor.shape == [1, window.heads, window.position - window.start, window.headDim] + && descriptor.shape == [ + 1, window.heads, window.position - window.start, + values ? window.valueHeadDim : window.headDim, + ] + } + + func retainForNativeExport(_ work: CBv2NativeCompletePrefixWork) throws { + try work.requireNativePagedSources() + guard let window else { throw CBv2CompleteCheckpointError.closed } + try work.retain(arrays: window.evaluationRoots, owners: [self, window]) } func readSegment(byteOffset: Int, maximumBytes: Int) throws -> Data { + try readSegment(byteOffset: byteOffset, maximumBytes: maximumBytes, nativeWork: nil) + } + + func readSegment( + byteOffset: Int, maximumBytes: Int, + nativeWork: CBv2NativeCompletePrefixWork? + ) throws -> Data { guard let window else { throw CBv2CompleteCheckpointError.closed } - return try window.read(values: values, byteOffset: byteOffset, maximumBytes: maximumBytes) + if let nativeWork { + try retainForNativeExport(nativeWork) + try nativeWork.captureCurrentStreams() + } + do { + return try window.read( + values: values, byteOffset: byteOffset, maximumBytes: maximumBytes) + } catch { + if error is MLXError || (error as? CBv2CompleteCheckpointError) == .allocationFailed { + nativeWork?.requiredCompletionFailed() + } + throw error + } } func close() { window = nil } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/NativeCompletePrefixCache.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/NativeCompletePrefixCache.swift new file mode 100644 index 0000000000..6fe9d63d7b --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/NativeCompletePrefixCache.swift @@ -0,0 +1,8 @@ +/// Optional native-profile store contract. A plain close() acknowledgement is +/// not proof that queued authenticated imports, exports and callbacks drained. +/// No default implementation: the real store must join its actual operations. +/// This capability is necessary, but does not itself grant a native work loan +/// or establish model/engine/store identity or successful GPU completion. +public protocol CBv2NativeCompletePrefixCache: CBv2CompletePrefixCache { + func closeAndWait() async +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointFrame.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointFrame.swift index 1de9b88da4..3384fdcd2f 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointFrame.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointFrame.swift @@ -8,14 +8,19 @@ final class CBv2PagedCheckpointFrame: @unchecked Sendable { private let lock = NSLock() private var owner: CBv2PagedCheckpointOwner? - init(storage: CBv2PagedCheckpointStorage, auxiliary: [MLXArray], - lease: CBv2CheckpointStageLease) throws { + init( + storage: CBv2PagedCheckpointStorage, auxiliary: [MLXArray], + lease: CBv2CheckpointStageLease, hostBytes: Int = 0 + ) throws { let bytes = try CBv2CheckpointAllocationFootprint.freshBytes(auxiliary) - guard storage.plan.nativeBytes == lease.targetBytes, bytes.bound == lease.auxiliaryBytes, + guard hostBytes >= 0, storage.plan.nativeBytes == lease.targetBytes, + try CBv2CheckpointAllocationFootprint.add(bytes.bound, hostBytes) + == lease.auxiliaryBytes, storage.allocatedBytes <= storage.plan.nativeBytes else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } try lease.settleDestinationAfterEvaluation( - targetBytes: storage.allocatedBytes, auxiliaryBytes: bytes.actual) + targetBytes: storage.allocatedBytes, + auxiliaryBytes: CBv2CheckpointAllocationFootprint.add(bytes.actual, hostBytes)) owner = CBv2PagedCheckpointOwner(storage: storage, auxiliary: auxiliary, lease: lease) } @@ -48,7 +53,9 @@ final class CBv2PagedCheckpointOwner { var auxiliary: [MLXArray] let lease: CBv2CheckpointStageLease - init(storage: CBv2PagedCheckpointStorage, auxiliary: [MLXArray], lease: CBv2CheckpointStageLease) { + init( + storage: CBv2PagedCheckpointStorage, auxiliary: [MLXArray], lease: CBv2CheckpointStageLease + ) { self.storage = storage self.auxiliary = auxiliary self.lease = lease @@ -73,8 +80,10 @@ final class CBv2PagedCheckpointAdoption { private let modelIndices: [Int] private let stateCount: Int - init(rows: [PagedSequenceKV], auxiliary: [MLXArray], modelIndices: [Int]? = nil, - stateCount: Int? = nil, releaseAdmission: @escaping () -> Void) { + init( + rows: [PagedSequenceKV], auxiliary: [MLXArray], modelIndices: [Int]? = nil, + stateCount: Int? = nil, releaseAdmission: @escaping () -> Void + ) { self.modelIndices = modelIndices ?? Array(rows.indices) self.stateCount = stateCount ?? rows.count self.rows = rows @@ -87,7 +96,9 @@ final class CBv2PagedCheckpointAdoption { /// charge and its request reservation; the temporary result cannot refund it. /// A throwing restorer must drop every candidate state alias before returning. func moveToActiveRequest(_ restore: ([MLXArray]) throws -> Void) throws -> [CBv2SequenceKV?] { - guard releaseAdmission != nil, !rows.isEmpty else { throw CBv2CompleteCheckpointError.closed } + guard releaseAdmission != nil, !rows.isEmpty else { + throw CBv2CompleteCheckpointError.closed + } do { try restore(auxiliary) } catch { release() throw error diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointStorage.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointStorage.swift index 31ef4bae01..a9722547ad 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointStorage.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointStorage.swift @@ -31,16 +31,24 @@ struct CBv2PagedCheckpointStoragePlan: Sendable { let nativeBytes: Int let ownerMap: [Int] - init(layerKinds: [CBv2LayerKind], config: PagedKVPoolConfig, position: Int, - historicalLayout: CBv2HistoricalAttentionLayout? = nil, maximumSequenceLength: Int? = nil) throws { + init( + layerKinds: [CBv2LayerKind], config: PagedKVPoolConfig, position: Int, + historicalLayout: CBv2HistoricalAttentionLayout? = nil, maximumSequenceLength: Int? = nil + ) throws { guard position > 1, position <= Int(Int32.max), config.pageSize > 0, let targetBytes = config.segmentSizeBytes, config.layerDTypes != nil else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } let types = try PagedKVStorageLayout.resolve(layerKinds: layerKinds, config: config) if let historicalLayout { - guard historicalLayout.layers == (try CBv2HistoricalAttentionLayout(layerKinds: layerKinds, dtypes: types)).layers, - let maximumSequenceLength, maximumSequenceLength >= position, - maximumSequenceLength <= Int(Int32.max) + // Physical IO may represent either width. The enclosing codec + // still grants the distinct format and native adoption permission. + let asymmetric = historicalLayout.layers.contains { $0.headDim != $0.valueHeadDim } + guard + historicalLayout.layers + == (try CBv2HistoricalAttentionLayout( + layerKinds: layerKinds, dtypes: types, allowAsymmetric: asymmetric)).layers, + let maximumSequenceLength, maximumSequenceLength >= position, + maximumSequenceLength <= Int(Int32.max) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } } let pages = (position - 1) / config.pageSize + 1 @@ -48,10 +56,12 @@ struct CBv2PagedCheckpointStoragePlan: Sendable { var demand: [PagedKVGroupKey: Int] = [:] let ownerMap = historicalLayout?.layers.map(\.owner) ?? Array(layerKinds.indices) guard ownerMap.count == layerKinds.count, - historicalLayout == nil || maximumSequenceLength.map({ $0 >= position }) == true + historicalLayout == nil || maximumSequenceLength.map({ $0 >= position }) == true else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } for (index, kind) in layerKinds.enumerated() where ownerMap[index] == index { - let start: Int, ring: Int?, count: Int + let start: Int + let ring: Int? + let count: Int if let historicalLayout { guard historicalLayout.layers[index].dtype.mlxDType == types[index] else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint @@ -61,28 +71,40 @@ struct CBv2PagedCheckpointStoragePlan: Sendable { ring = PagedKVPool.ringPageCount(window: window, config: config) // Dense canonical ring slots, including speculative margin. // Missing slots would change modulo addressing after resume. - count = PagedKVPool.pageDemand(kind: kind, maxLength: maximumSequenceLength!, config: config) - } else { ring = nil; count = pages } + count = PagedKVPool.pageDemand( + kind: kind, maxLength: maximumSequenceLength!, config: config) + } else { + ring = nil + count = pages + } } else { guard case .full = kind.attention, kind.sharesKVWithLayer == nil, - kind.kvHeads > 0, kind.headDim >= 64 + kind.kvHeads > 0, kind.headDim >= 64 else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } - start = 0; ring = nil; count = pages + start = 0 + ring = nil + count = pages } let key = PagedKVGroupKey(kind, dtype: types[index], separateWindow: true) let first = demand[key, default: 0] let (next, overflow) = first.addingReportingOverflow(count) guard !overflow else { throw CBv2CompleteCheckpointError.invalidManifest } - layers.append(Layer(modelIndex: index, tokenStart: start, tokenCount: position - start, - ringPages: ring, key: key, firstPage: first, pageCount: count)) + layers.append( + Layer( + modelIndex: index, tokenStart: start, tokenCount: position - start, + ringPages: ring, key: key, firstPage: first, pageCount: count)) demand[key] = next } guard !layers.isEmpty else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } var groups: [Group] = [] var total = 0 for key in demand.keys.sorted(by: { $0.sortKey < $1.sortKey }) { - let pageBytes = try CBv2CheckpointTensorDescriptor.checkedByteCount( - shape: [2, key.kvHeads, config.pageSize, key.headDim], dtype: key.dtype) + guard + let pageBytes = key.geometry?.storageBytes( + tokens: config.pageSize, elementBytes: key.dtype.size) + else { + throw CBv2CompleteCheckpointError.invalidManifest + } let layout = try PagedKVSegmentLayout( pageBytes: pageBytes, targetBytes: targetBytes, maximumBufferBytes: config.maxBufferLength, @@ -125,8 +147,10 @@ final class CBv2PagedCheckpointStorage { } } - init(plan: CBv2PagedCheckpointStoragePlan, evaluate: (MLXArray) throws -> Void, - admission: AdmissionV2? = nil) throws { + init( + plan: CBv2PagedCheckpointStoragePlan, evaluate: (MLXArray) throws -> Void, + admission: AdmissionV2? = nil, nativeWork: CBv2NativeCompletePrefixWork? = nil + ) throws { self.plan = plan for group in plan.groups { let prepared = try group.layout.adding(usablePages: group.usablePages, excluding: []) @@ -138,6 +162,10 @@ final class CBv2PagedCheckpointStorage { index: index, layout: prepared.layout, key: group.key, pageSize: plan.pageSize, dtype: group.key.dtype, evaluate: evaluate, admission: admission) + // The evaluator already retained the raw root before native + // execution. Keep its actual coverage/backing owner as well, + // including a late result after a concurrent native veto. + try nativeWork?.retain(arrays: [segment.storage], owners: [segment]) guard mlx_array_data_uint8(segment.storage.ctx) != nil else { throw CBv2CompleteCheckpointError.allocationFailed } @@ -156,8 +184,9 @@ final class CBv2PagedCheckpointStorage { } let layer = plan.layers[layerIndex] guard let group = groups[layer.key] else { throw CBv2CompleteCheckpointError.closed } + let roleWidth = values ? layer.key.valueHeadDim : layer.key.headDim let bytes = try CBv2CheckpointTensorDescriptor.checkedByteCount( - shape: [1, layer.key.kvHeads, layer.tokenCount, layer.key.headDim], dtype: layer.key.dtype) + shape: [1, layer.key.kvHeads, layer.tokenCount, roleWidth], dtype: layer.key.dtype) let width = layer.key.dtype.size guard byteOffset >= 0, byteOffset < bytes, byteOffset % width == 0, !data.isEmpty, data.count <= CBv2CompleteCheckpointManifest.maximumSegmentBytes, @@ -165,8 +194,9 @@ final class CBv2PagedCheckpointStorage { else { throw CBv2CompleteCheckpointError.invalidSegment } try data.withUnsafeBytes { source in try CBv2PagedCheckpointByteLayout.runs( - headDim: layer.key.headDim, position: layer.tokenCount, pageSize: plan.pageSize, - tokenStart: layer.tokenStart, ringPages: layer.ringPages, itemSize: width, byteOffset: byteOffset, count: data.count + headDim: roleWidth, position: layer.tokenCount, pageSize: plan.pageSize, + tokenStart: layer.tokenStart, ringPages: layer.ringPages, itemSize: width, + byteOffset: byteOffset, count: data.count ) { logicalPage, head, slot, feature, packedOffset, count in let page = group.pages[layer.firstPage + logicalPage] let segment = group.segments[group.layout.segmentIndex(page: page)]! @@ -174,8 +204,9 @@ final class CBv2PagedCheckpointStorage { throw CBv2CompleteCheckpointError.allocationFailed } let localPage = group.layout.localPage(page) - let element = ((localPage * layer.key.kvHeads + head) * plan.pageSize + slot) - * layer.key.headDim + feature + (values ? segment.valueOffset : 0) + let element = + ((localPage * layer.key.kvHeads + head) * plan.pageSize + slot) + * roleWidth + feature + (values ? segment.valueOffset : 0) UnsafeMutableRawPointer(mutating: pointer).advanced(by: element * width).copyMemory( from: source.baseAddress!.advanced(by: packedOffset), byteCount: count) } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointTensorSource.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointTensorSource.swift index e9e9c4074f..8c93ef1fc6 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointTensorSource.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointTensorSource.swift @@ -11,15 +11,21 @@ final class CBv2PagedCheckpointTensorSource { private let pageSize: Int private let position: Int private let values: Bool + private var roleWidth: Int { values ? key.valueHeadDim : key.headDim } private var pageMap: CBv2PagedCheckpointPageMap? let byteCount: Int - convenience init(row: PagedSequenceKV, position: Int, values: Bool, admission: AdmissionV2) throws { - try self.init(pageMap: .init(row: row, position: position, admission: admission), values: values) + convenience init(row: PagedSequenceKV, position: Int, values: Bool, admission: AdmissionV2) + throws + { + try self.init( + pageMap: .init(row: row, position: position, admission: admission), values: values) } - convenience init(storage: CBv2PagedCheckpointStorage, layerIndex: Int, values: Bool, - admission: AdmissionV2) throws { + convenience init( + storage: CBv2PagedCheckpointStorage, layerIndex: Int, values: Bool, + admission: AdmissionV2 + ) throws { guard storage.plan.layers.indices.contains(layerIndex) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } @@ -27,12 +33,16 @@ final class CBv2PagedCheckpointTensorSource { guard layer.ringPages == nil, layer.tokenStart == 0 else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } - guard let group = storage.groups[layer.key] else { throw CBv2CompleteCheckpointError.closed } - try self.init(pageMap: .init( - key: layer.key, pageSize: storage.plan.pageSize, position: storage.plan.position, - table: group.pages[layer.firstPage ..< layer.firstPage + layer.pageCount], - layout: group.layout, segments: group.segments, previous: MLXArray.zeros([1], dtype: .int32), - admission: admission), values: values) + guard let group = storage.groups[layer.key] else { + throw CBv2CompleteCheckpointError.closed + } + try self.init( + pageMap: .init( + key: layer.key, pageSize: storage.plan.pageSize, position: storage.plan.position, + table: group.pages[layer.firstPage ..< layer.firstPage + layer.pageCount], + layout: group.layout, segments: group.segments, + previous: MLXArray.zeros([1], dtype: .int32), + admission: admission), values: values) } init(pageMap: CBv2PagedCheckpointPageMap, values: Bool) throws { @@ -42,12 +52,13 @@ final class CBv2PagedCheckpointTensorSource { self.values = values self.pageMap = pageMap self.byteCount = try CBv2CheckpointTensorDescriptor.checkedByteCount( - shape: [1, key.kvHeads, position, key.headDim], dtype: key.dtype) + shape: [1, key.kvHeads, position, values ? key.valueHeadDim : key.headDim], + dtype: key.dtype) } func matches(_ descriptor: CBv2CheckpointTensorDescriptor) -> Bool { descriptor.byteCount == byteCount && descriptor.dtype.mlxDType == key.dtype - && descriptor.shape == [1, key.kvHeads, position, key.headDim] + && descriptor.shape == [1, key.kvHeads, position, roleWidth] && descriptor.role == (values ? .values : .keys) } @@ -55,7 +66,20 @@ final class CBv2PagedCheckpointTensorSource { /// allocator exposes shared CPU-readable storage, so only the returned /// provider-owned Data is allocated. No full backing view or GPU gather is /// constructed; the page map pins every source throughout the copy. + func retainForNativeExport(_ work: CBv2NativeCompletePrefixWork) throws { + try work.requireNativePagedSources() + guard let pageMap else { throw CBv2CompleteCheckpointError.closed } + try work.retain(arrays: [pageMap.previous], owners: [self, pageMap]) + } + func readSegment(byteOffset: Int, maximumBytes: Int) throws -> Data { + try readSegment(byteOffset: byteOffset, maximumBytes: maximumBytes, nativeWork: nil) + } + + func readSegment( + byteOffset: Int, maximumBytes: Int, + nativeWork: CBv2NativeCompletePrefixWork? + ) throws -> Data { guard let pageMap else { throw CBv2CompleteCheckpointError.closed } let width = key.dtype.size guard byteOffset >= 0, byteOffset < byteCount, byteOffset % width == 0, @@ -63,18 +87,36 @@ final class CBv2PagedCheckpointTensorSource { else { throw CBv2CompleteCheckpointError.invalidSegment } let count = min(byteCount - byteOffset, maximumBytes - maximumBytes % width) guard count > 0 else { throw CBv2CompleteCheckpointError.invalidSegment } - try pageMap.prepareForReading() + if let nativeWork { + try retainForNativeExport(nativeWork) + try nativeWork.captureCurrentStreams() + try pageMap.prepareForReading { array in + do { + try withError { fault in + eval(array) + try fault.check() + } + } catch { + nativeWork.requiredCompletionFailed() + throw error + } + } + } else { + try pageMap.prepareForReading() + } var result = Data(count: count) try result.withUnsafeMutableBytes { destination in try CBv2PagedCheckpointByteLayout.runs( - headDim: key.headDim, position: position, pageSize: pageSize, + headDim: roleWidth, position: position, pageSize: pageSize, itemSize: width, byteOffset: byteOffset, count: count ) { logicalPage, head, slot, feature, packedOffset, length in let page = pageMap[logicalPage] let segment = page.segment - let source = ((page.localPage * key.kvHeads + head) * pageSize + slot) - * key.headDim + feature + (values ? segment.valueOffset : 0) + let source = + ((page.localPage * key.kvHeads + head) * pageSize + slot) + * roleWidth + feature + (values ? segment.valueOffset : 0) guard let pointer = mlx_array_data_uint8(segment.storage.ctx) else { + nativeWork?.requiredCompletionFailed() throw CBv2CompleteCheckpointError.allocationFailed } destination.baseAddress!.advanced(by: packedOffset).copyMemory( diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCompleteCheckpointAdoption.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCompleteCheckpointAdoption.swift index a6db2b37e1..f5a840eb9e 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCompleteCheckpointAdoption.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCompleteCheckpointAdoption.swift @@ -3,15 +3,92 @@ import MLX // Engine-queue only: stage transfer and restoration must finish before any // request reservation can detach or any target/assistant forward can run. extension EngineLoopV2 { + /// Before beginCommit, in the same engine-queue turn as the eventual + /// publication/refusal. No prepared live-pool map crosses an await. + func prepareNativePagedCompletePrefix( + _ adoption: CBv2PrefixAdoption?, + request: CBv2Request + ) throws { + guard let staged = adoption?.completeCheckpoint, staged.hasNativeTracking, + staged.usesPagedBacking + else { return } + guard let capture = completeCheckpointCapture, capture.codec.isNativePagedHistorical, + let backend = backend as? PagedKVBackend, let tracking = nativeShutdownState, + let generation = registeredStreamGeneration(for: request.id) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let prepared = try staged.prepareNativePagedTargets( + store: capture.store, request: request, + engineID: tracking.engineID, expectedCodec: capture.codec, backend: backend, + streamGeneration: generation) + nativePagedPrefixPreparedForTesting?(request.id, prepared) + } + + /// Atomic metadata-only target+assistant move. Every native root and the + /// actual restored assistant were evaluated/fenced before this commit. + func adoptPreparedNativePagedHistoricalState( + _ prepared: CBv2PreparedCompleteCheckpoint, + codec: CBv2CompleteCheckpointCodec, requestID: CBv2RequestID, + maximumSequenceLength: Int + ) throws -> [CBv2SequenceKV?] { + guard codec.isNativePagedHistorical, codec === completeCheckpointCapture?.codec, + let checkpoint = prepared.checkpoint, checkpoint.layers.isEmpty, + let pages = prepared.nativePagedPreparation, + pages.maximumTokens == maximumSequenceLength, + pages.requestID == requestID, kvStates[requestID] == nil, + recurrentStates[requestID] == nil, + let request = scheduler.record(for: requestID)?.request, + checkpoint.position < request.promptTokens.count, + let generation = registeredStreamGeneration(for: requestID), + generation == pages.streamGeneration + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let restored: (any CBv2MTPRequestState)? + if checkpoint.assistant != nil { + guard let mtp, mtp.canInstallHistoricalAssistant(for: requestID), + let assistant = codec.assistant, + assistant as AnyObject === mtp.drafter as AnyObject, + let restoration = prepared.historicalAssistantRestoration, + restoration.settled, let actual = restoration.state + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + restored = actual + } else { + guard codec.assistant == nil, !(mtp?.tracksPersistentHistory ?? false), + prepared.historicalAssistantRestoration == nil + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + restored = nil + } + let state = try pages.publish(admission: codec.admission, streamGeneration: generation) + // All fallible checks precede pool/row publication. No carry or missing + // head state is synthesized; the first real suffix observation resumes. + if let restored { + _ = prepared.historicalAssistantRestoration?.takeSettledState() + mtp!.restoreAssistantState(restored, for: requestID) + } + recurrentCheckpointGeometry[requestID] = .init( + position: checkpoint.position, + chunkSize: checkpoint.chunkSize) + nativePagedPrefixAdoptedForTesting?(requestID, state, restored) + return state + } + func adoptPagedCompleteCheckpoint( _ staged: CBv2StagedCompleteCheckpoint, requestID: CBv2RequestID ) throws -> [CBv2SequenceKV?] { guard let paged = backend as? PagedKVBackend, - staged.codec === completeCheckpointCapture?.codec, - recurrentStates[requestID] == nil + staged.codec === completeCheckpointCapture?.codec, + recurrentStates[requestID] == nil else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } return try staged.consumePreparedState { prepared in - guard let frame = prepared.pagedFrame else { throw CBv2CompleteCheckpointError.incompleteTransfer } + guard let frame = prepared.pagedFrame else { + throw CBv2CompleteCheckpointError.incompleteTransfer + } prepared.pagedFrame = nil let adopted = try paged.pool.importCheckpoint( frame, admission: staged.codec.admission, requestID: requestID, @@ -28,7 +105,8 @@ extension EngineLoopV2 { // Gemma's stateless drafter seeds from the next target // round. No persistent assistant history is fabricated. recurrentCheckpointGeometry[requestID] = .init( - position: staged.manifest.position, chunkSize: staged.manifest.chunkSize) + position: staged.manifest.position, chunkSize: staged.manifest.chunkSize + ) return } let checkpoint = try staged.codec.recurrentCheckpoint( diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCompleteCheckpointCodec.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCompleteCheckpointCodec.swift index e907d06b65..78f15c5fea 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCompleteCheckpointCodec.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCompleteCheckpointCodec.swift @@ -7,55 +7,71 @@ extension CBv2CompleteCheckpointCodec { checkpoint: CBv2RecurrentCheckpoint, state: [CBv2SequenceKV?], tokens: [Int], cacheSalt: String? ) throws -> CBv2CompleteCheckpointExport { + guard !unsupportedAsymmetricGeometry else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } guard checkpoint.position < tokens.count, state.count == layerKinds.count else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } - let metadataPermit = try CBv2CheckpointManifestMemory.Permit(admission: admission, position: checkpoint.position) + let metadataPermit = try CBv2CheckpointManifestMemory.Permit( + admission: admission, position: checkpoint.position) return try withExtendedLifetime(metadataPermit) { - try makePagedExport(checkpoint: checkpoint, state: state, tokens: tokens, - cacheSalt: cacheSalt, metadataPermit: metadataPermit) + try makePagedExport( + checkpoint: checkpoint, state: state, tokens: tokens, + cacheSalt: cacheSalt, metadataPermit: metadataPermit) } } private func makePagedExport( - checkpoint: CBv2RecurrentCheckpoint, state: [CBv2SequenceKV?], tokens: [Int], cacheSalt: String?, + checkpoint: CBv2RecurrentCheckpoint, state: [CBv2SequenceKV?], tokens: [Int], + cacheSalt: String?, metadataPermit: CBv2CheckpointManifestMemory.Permit ) throws -> CBv2CompleteCheckpointExport { - let descriptors = try tensorDescriptors(position: checkpoint.position, qwen4: qwen4Descriptors(checkpoint), - mediaTargetOnly: checkpoint.mediaTargetOnly) + let descriptors = try tensorDescriptors( + position: checkpoint.position, qwen4: qwen4Descriptors(checkpoint), + mediaTargetOnly: checkpoint.mediaTargetOnly) var sources: [CBv2CompleteCheckpointTensorSource] = [] for (index, entry) in state.enumerated() { guard let row = entry as? PagedSequenceKV, - row.groupKey.dtype == kvDTypes[index], row.pool.layerKinds == layerKinds, - row.groupKey == row.pool.groupKey(forLayer: index) + row.groupKey.dtype == kvDTypes[index], row.pool.layerKinds == layerKinds, + row.groupKey == row.pool.groupKey(forLayer: index) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } - let pageMap = try CBv2PagedCheckpointPageMap(row: row, position: checkpoint.position, admission: admission) + let pageMap = try CBv2PagedCheckpointPageMap( + row: row, position: checkpoint.position, admission: admission) sources.append(.paged(try .init(pageMap: pageMap, values: false))) sources.append(.paged(try .init(pageMap: pageMap, values: true))) } for spec in recurrentSpec?.layers ?? [] { - guard let layer = checkpoint.layers[spec.modelLayerIndex], let conv = layer.conv, let ssm = layer.ssm + guard let layer = checkpoint.layers[spec.modelLayerIndex], let conv = layer.conv, + let ssm = layer.ssm else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } sources.append(contentsOf: [.array(conv), .array(ssm)]) } sources.append(contentsOf: try qwen4Arrays(checkpoint).map { .array($0) }) if let assistant, !checkpoint.mediaTargetOnly { - guard let state = checkpoint.assistant, let encoded = assistant.encodePrefixCheckpoint(state) + guard let state = checkpoint.assistant, + let encoded = assistant.encodePrefixCheckpoint(state) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } sources.append(contentsOf: encoded.map { .array($0) }) } else if checkpoint.assistant != nil { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } guard sources.count == descriptors.count, - zip(sources, descriptors).allSatisfy({ $0.0.matches($0.1) }) + zip(sources, descriptors).allSatisfy({ $0.0.matches($0.1) }) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } let manifest = CBv2CompleteCheckpointManifest( schemaVersion: CBv2CompleteCheckpointManifest.currentSchemaVersion, identity: identity, - backendLayout: backendLayout, position: checkpoint.position, chunkSize: checkpoint.chunkSize, - cacheSalt: cacheSalt, assistantCodecID: checkpoint.mediaTargetOnly ? nil : assistant?.prefixCheckpointCodecID, + backendLayout: backendLayout, position: checkpoint.position, + chunkSize: checkpoint.chunkSize, + cacheSalt: cacheSalt, + assistantCodecID: checkpoint.mediaTargetOnly ? nil : assistant?.prefixCheckpointCodecID, mediaIdentity: checkpoint.mediaIdentity, mediaTargetOnly: checkpoint.mediaTargetOnly, - metadata: .init(tokens: Array(tokens.prefix(checkpoint.position)), tensors: descriptors, permit: metadataPermit)) + metadata: .init( + tokens: Array(tokens.prefix(checkpoint.position)), tensors: descriptors, + permit: metadataPermit)) _ = try manifest.validateStructure() - return .init(manifest: manifest, sources: sources, usesProcessMemoryOwner: admission.hasProcessMemoryOwner) + return .init( + manifest: manifest, sources: sources, + usesProcessMemoryOwner: admission.hasProcessMemoryOwner) } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PreparedHistoricalAssistant.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PreparedHistoricalAssistant.swift new file mode 100644 index 0000000000..8db85833f4 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PreparedHistoricalAssistant.swift @@ -0,0 +1,107 @@ +import MLX + +/// Off-to-the-side restoration. The existing import work owns this value and +/// its temporary promise through the actual fence/retirement callback. It is +/// never installed into a live driver before target adoption also succeeds. +final class CBv2PreparedHistoricalAssistant { + private let assistant: any CBv2MTPRequestStatefulDrafter + private var reservation: CBv2CheckpointReservation? + private(set) var state: (any CBv2MTPRequestState)? + private(set) var settled = false + + init(assistant: any CBv2MTPRequestStatefulDrafter, reservation: CBv2CheckpointReservation) { + self.assistant = assistant + self.reservation = reservation + } + + func retain(_ state: any CBv2MTPRequestState) { self.state = state } + func markSettled() { settled = true } + + func takeSettledState() -> (any CBv2MTPRequestState)? { + guard settled, let state else { return nil } + self.state = nil + return state + } + + /// Only the containing import owner's post-native-completion cleanup may + /// call this. On failed required completion that callback never runs. + func closeAfterNativeCompletion() { + if let state { assistant.releaseRequestState(state) } + state = nil + reservation?.release() + reservation = nil + } +} + +extension CBv2PreparedCompleteCheckpoint { + /// Run during staged lookup, before enqueue/deadline admission acquires + /// the native metadata commit lock. Repeated validated lookup is inert. + func prepareHistoricalAssistant( + codec: CBv2CompleteCheckpointCodec, + request: CBv2Request, + work: CBv2NativeCompletePrefixWork + ) throws { + if let historicalAssistantRestoration { + guard historicalAssistantRestoration.settled else { + throw CBv2CompleteCheckpointError.incompleteTransfer + } + return + } + guard let checkpoint else { throw CBv2CompleteCheckpointError.incompleteTransfer } + guard let encoded = checkpoint.assistant else { + guard codec.assistant == nil else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + return + } + guard codec.contiguousLayout != nil || codec.isNativePagedHistorical, + let historical = codec.assistant as? any CBv2HistoricalMTPPrefixCheckpointCoding, + let stateful = codec.assistant as? any CBv2MTPRequestStatefulDrafter, + let split = codec.assistant as? any CBv2NativeMTPCompletionSplitting, + checkpoint.position < request.promptTokens.count, + let descriptors = historical.prefixCheckpointTensorDescriptors( + targetInputCount: checkpoint.position) + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + let (maximum, overflow) = request.promptTokens.count.addingReportingOverflow( + max(request.maxTokens, 1)) + guard !overflow else { throw CBv2CompleteCheckpointError.invalidManifest } + // Restored mutable copies coexist with the immutable imported payload. + // Reserve their bounded native copies plus the full prompt witness + // before construction. This is not physical-memory/free-space credit. + let bytes = try CBv2HistoricalMTPCheckpointFootprint.captureBytes( + position: maximum, descriptors: descriptors) + let owner = CBv2PreparedHistoricalAssistant( + assistant: stateful, + reservation: try codec.admission.reserveTransient(bytes: bytes)) + historicalAssistantRestoration = owner + try work.retain(owners: [owner]) + try work.captureCurrentStreams() + do { + try withError { fault in + guard let restored = historical.restorePrefixCheckpoint(encoded) else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + owner.retain(restored) + try work.retain(owners: [restored]) + try fault.check() + try stateful.configureRequestState(restored, maximumSequenceLength: maximum) + try historical.installPrefixCaptureContext( + requestState: restored, + promptTokens: request.promptTokens) + let roots = stateful.evaluationTargets(for: restored) + try work.retain(arrays: roots) + eval(roots) + try fault.check() + try split.fenceRequestStateForNativeCompletion(restored) + try fault.check() + try work.fenceForProtectedPromotion() + try work.commitPreparedAssistant(split, state: restored) + owner.markSettled() + } + } catch { + // Never refund a possibly submitted restoration on an error path. + work.requiredCompletionFailed() + throw error + } + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/PrefixReusePlan.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/PrefixReusePlan.swift index d50055714f..5b40cfbda9 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/PrefixReusePlan.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/PrefixReusePlan.swift @@ -81,7 +81,9 @@ public struct CBv2PrefixReuseCapability: Sendable, Equatable { var fullKVBytesPerToken = 0 for (index, kind) in layerKinds.enumerated() { - guard kind.headDim > 0, kind.kvHeads > 0, kind.queryHeads > 0 else { + guard kind.kvGeometry != nil, kind.queryHeads > 0, + kind.queryHeads.isMultiple(of: kind.kvHeads) + else { return unsupported(backend: backend, reason: .invalidLayout) } if let source = kind.sharesKVWithLayer { @@ -89,7 +91,8 @@ public struct CBv2PrefixReuseCapability: Sendable, Equatable { layerKinds[source].sharesKVWithLayer == nil, layerKinds[source].attention == kind.attention, layerKinds[source].kvHeads == kind.kvHeads, - layerKinds[source].headDim == kind.headDim + layerKinds[source].headDim == kind.headDim, + layerKinds[source].valueHeadDim == kind.valueHeadDim else { return unsupported(backend: backend, reason: .invalidLayout) } @@ -105,12 +108,11 @@ public struct CBv2PrefixReuseCapability: Sendable, Equatable { case .full: guard kind.sharesKVWithLayer == nil else { continue } if sawWindowed { hasOwningFullAfterWindow = true } - let (elements, elementsOverflow) = kind.kvHeads.multipliedReportingOverflow( - by: kind.headDim) - let (kvElements, kvOverflow) = elements.multipliedReportingOverflow(by: 2) - let (bytes, bytesOverflow) = kvElements.multipliedReportingOverflow(by: 2) + guard let bytes = kind.kvGeometry?.bytesPerToken(elementBytes: 2) else { + return unsupported(backend: backend, reason: .accountingOverflow) + } let (sum, sumOverflow) = fullKVBytesPerToken.addingReportingOverflow(bytes) - guard !elementsOverflow, !kvOverflow, !bytesOverflow, !sumOverflow else { + guard !sumOverflow else { return unsupported(backend: backend, reason: .accountingOverflow) } fullKVBytesPerToken = sum @@ -265,7 +267,8 @@ public struct CBv2PrefixReuseCapability: Sendable, Equatable { // Stateful hybrid adoption prepays the entire logical sequence so // AdmissionV2 also reserves its block-rounded auxiliary MTP state. // Progress and replay still start at the actual matched checkpoint. - let capacityReservationTokens = reserveFullSequenceTokens + let capacityReservationTokens = + reserveFullSequenceTokens ? fullCapacityTokens : restoredFullTokens guard let exactFullCapacityBytes = Self.multiply( @@ -383,12 +386,12 @@ public struct CBv2PrefixReusePlan: Sendable, Equatable { public let fullCapacityTokensReserved: Int public let stagedFullKVBytes: Int public let residentFullKVBytes: Int - /// A forced prefill chunk for a recurrent adopter. Nil for every - /// adoption since capture became chunk-agnostic: resident-bank and + /// A forced prefill chunk for a shape-bound adopter. Nil for + /// chunk-agnostic adoption: resident-bank and /// complete-checkpoint adopters both resume under ordinary chunking /// (`hybridPrefixLookup`, `completeCheckpointLookup`). The scheduler's /// chunk-wait and deadline-projection handling for a non-nil value is - /// kept for now and has no producer. + /// retained for the separately issued native contiguous checkpoint profile. public var recurrentChunkSize: Int? = nil public var recurrentPromptLength: Int? = nil /// Keeps this adopted row out of rectangular packed prefill. A complete diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/SchedulerV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/SchedulerV2.swift index 9608edfc6b..6c9e3e725a 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/SchedulerV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/SchedulerV2.swift @@ -114,9 +114,12 @@ public final class CBv2ScheduledRequest { self.submittedAt = submittedAt self.enqueuedNanos = enqueuedNanos self.tokens = request.promptTokens - let (maximum, overflow) = request.promptTokens.count.addingReportingOverflow(max(1, request.maxTokens)) - self.fullSequenceCapacityTokens = reserveFullSequenceTokens ? (overflow ? Int.max : maximum) : nil - self.multimodalBlocks = request.multimodal?.attention == .bidirectionalSpans + let (maximum, overflow) = request.promptTokens.count.addingReportingOverflow( + max(1, request.maxTokens)) + self.fullSequenceCapacityTokens = + reserveFullSequenceTokens ? (overflow ? Int.max : maximum) : nil + self.multimodalBlocks = + request.multimodal?.attention == .bidirectionalSpans ? CBv2MultimodalPlan.coalescedBlocks(spans: request.multimodal?.spans ?? []) : [] } @@ -341,8 +344,8 @@ public final class SchedulerV2 { // Solo-prefill stripe (`CBv2SchedulerConfig.soloPrefillStripeTokens`). // Armed ONLY when this plan cannot delay anyone else's work: exactly // one live request exists across running+waiting (paused rows count — - // they resume), it is text-only (multimodal block snapping keeps its - // own budget-bounded contract), it is prefilling (not decode-ready), + // they resume), it has no bidirectional blocks (causal media follows + // its optional preserved stripe ceiling), it is prefilling (not decode-ready), // and it is not itself paused. Solo also means raising the step // budget to the stripe cannot starve a decode row — there is none. let soloStripe: (tokens: Int, id: CBv2RequestID)? = { @@ -376,7 +379,11 @@ public final class SchedulerV2 { solo.multimodalBlocks.isEmpty, solo.remainingTokens > 1 else { return nil } - return (tokens: stripe, id: solo.id) + guard + let selectedStripe = config.resolvedSoloPrefillStripeTokens( + isMultimodal: solo.request.multimodal != nil) + else { return nil } + return (tokens: selectedStripe, id: solo.id) }() let soloStripeTokens = soloStripe?.tokens // The stripe belongs to ONE armed request. A successor admitted in @@ -385,7 +392,8 @@ public final class SchedulerV2 { // chunk delays the striped row's own sample — defeating the very // TTFT the stripe exists for. func prefillChunkCap(for rec: CBv2ScheduledRequest) -> Int { - let cap = rec.prefixReusePlan?.recurrentChunkSize + let cap = + rec.prefixReusePlan?.recurrentChunkSize ?? (soloStripe?.id == rec.id ? soloStripe!.tokens : config.prefillChunkSize) rec.plannedPrefillChunkSize = cap return cap @@ -582,14 +590,16 @@ public final class SchedulerV2 { // before the preemption machinery may run. Text-only by the solo // gate, so re-snapping is a no-op and the shrink cannot split a // multimodal block. - var striped = soloStripeTokens != nil && n > config.prefillChunkSize + var striped = + soloStripeTokens != nil && n > config.prefillChunkSize && rec.prefixReusePlan?.recurrentChunkSize == nil var reservationTokens = rec.capacityTokensForChunk( start: rec.numComputedTokens, count: n) - var reservationBytes = rec.prefixReusePlan?.capacityBytesForChunk( - start: rec.numComputedTokens, - count: n) ?? 0 + var reservationBytes = + rec.prefixReusePlan?.capacityBytesForChunk( + start: rec.numComputedTokens, + count: n) ?? 0 var reserved = capacity == nil || (reservationTokens == 0 && reservationBytes == 0) while !reserved { @@ -606,9 +616,10 @@ public final class SchedulerV2 { reservationTokens = rec.capacityTokensForChunk( start: rec.numComputedTokens, count: n) - reservationBytes = rec.prefixReusePlan?.capacityBytesForChunk( - start: rec.numComputedTokens, - count: n) ?? 0 + reservationBytes = + rec.prefixReusePlan?.capacityBytesForChunk( + start: rec.numComputedTokens, + count: n) ?? 0 continue } // Speculative slack must never trigger the preemption @@ -619,9 +630,10 @@ public final class SchedulerV2 { reservationTokens = rec.capacityTokensForChunk( start: rec.numComputedTokens, count: n) - reservationBytes = rec.prefixReusePlan?.capacityBytesForChunk( - start: rec.numComputedTokens, - count: n) ?? 0 + reservationBytes = + rec.prefixReusePlan?.capacityBytesForChunk( + start: rec.numComputedTokens, + count: n) ?? 0 speculationFallbacks[rec.id] = .kvHeadroom continue } @@ -707,7 +719,8 @@ public final class SchedulerV2 { // surplus: they are bounded by what remains of the ORDINARY // step limit. The armed row itself (admission-path solo // striping) keeps the raised budget. - let normalHeadroom = soloStripe?.id == rec.id + let normalHeadroom = + soloStripe?.id == rec.id ? budget : max(0, config.maxBatchedTokensPerStep - totalAssignedTokens) var chunk = min( @@ -731,16 +744,18 @@ public final class SchedulerV2 { // KV limiter cannot hold falls back to the plain chunk // size once (text-only by the solo gate — no block to // split) before admission gives up for this step. - var striped = soloStripeTokens != nil && chunk > config.prefillChunkSize + var striped = + soloStripeTokens != nil && chunk > config.prefillChunkSize && rec.prefixReusePlan?.recurrentChunkSize == nil var reservedAdmission = false while !reservedAdmission { let reservationTokens = rec.capacityTokensForChunk( start: rec.numComputedTokens, count: chunk) - let reservationBytes = rec.prefixReusePlan?.capacityBytesForChunk( - start: rec.numComputedTokens, - count: chunk) ?? 0 + let reservationBytes = + rec.prefixReusePlan?.capacityBytesForChunk( + start: rec.numComputedTokens, + count: chunk) ?? 0 do { if reservationTokens > 0 || reservationBytes > 0 { try capacity.reserve( @@ -806,9 +821,10 @@ public final class SchedulerV2 { let reservationTokens = rec.capacityTokensForChunk( start: rec.numComputedTokens, count: chunk) - let reservationBytes = rec.prefixReusePlan?.capacityBytesForChunk( - start: rec.numComputedTokens, - count: chunk) ?? 0 + let reservationBytes = + rec.prefixReusePlan?.capacityBytesForChunk( + start: rec.numComputedTokens, + count: chunk) ?? 0 do { if reservationTokens > 0 || reservationBytes > 0 { try capacity.reserve( @@ -844,9 +860,10 @@ public final class SchedulerV2 { let reservationTokens = rec.capacityTokensForChunk( start: start, count: n) - let reservationBytes = rec.prefixReusePlan?.capacityBytesForChunk( - start: start, - count: n) ?? 0 + let reservationBytes = + rec.prefixReusePlan?.capacityBytesForChunk( + start: start, + count: n) ?? 0 rec.numComputedTokens = start capacity?.unreserve( id: id, tokens: reservationTokens, bytes: reservationBytes) @@ -891,9 +908,10 @@ public final class SchedulerV2 { let reservationTokens = rec.capacityTokensForChunk( start: start, count: n) - let reservationBytes = rec.prefixReusePlan?.capacityBytesForChunk( - start: start, - count: n) ?? 0 + let reservationBytes = + rec.prefixReusePlan?.capacityBytesForChunk( + start: start, + count: n) ?? 0 rec.numComputedTokens = start capacity?.unreserve( id: id, tokens: reservationTokens, bytes: reservationBytes) diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/ContiguousKVBackend.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/ContiguousKVBackend.swift index 82706d6c3c..af96e331fe 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/ContiguousKVBackend.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/ContiguousKVBackend.swift @@ -31,8 +31,9 @@ public struct CBv2ContiguousBackendConfig: Sendable { /// /// Thread-safe: the live-row registry is lock-protected (`makeSequenceState` /// runs on the admission path while `release` runs on the engine loop). -/// `bytesInUse` is truthful — it sums the ACTUAL allocated bytes of live -/// rows (which grow by doubling), not a worst-case estimate. +/// `bytesInUse` sums live logical array extents. `bytesReserved` additionally +/// retains v2 imported allocator bounds; logical nbytes are not a physical +/// allocator receipt or materialization credit. /// /// Admission RESERVES: rows allocate lazily (`byteCount == 0` until their /// first update), so judging capacity against `bytesInUse` alone would let @@ -59,6 +60,8 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { /// at runtime (`updateBytesCapacity`). Lock-protected: the atomic /// admit-and-register check reads it inside its critical section. private var liveBytesCapacity: Int + // Deterministic failure seam after ledger transfer, before row publication. + var checkpointBeforeRegistration: (() throws -> Void)? public init(config: CBv2ContiguousBackendConfig) { self.config = config @@ -85,7 +88,7 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { public var bytesInUse: Int { lock.lock() defer { lock.unlock() } - return live.values.reduce(0) { $0 + $1.byteCount } + return live.values.reduce(0) { CBv2KVGeometry.add($0, $1.byteCount) ?? Int.max } } /// Actual bytes plus outstanding admission reservations — what the @@ -100,18 +103,20 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { layerKinds: [CBv2LayerKind], promptLength: Int, maxLength: Int ) throws -> [CBv2SequenceKV?] { try validate(layerKinds: layerKinds) - guard promptLength <= maxLength else { + guard promptLength >= 0, maxLength > 0, maxLength <= Int(Int32.max), + promptLength <= maxLength + else { throw CBv2KVError.backendIneligible( reason: "promptLength \(promptLength) exceeds maxLength \(maxLength)") } - + let estimates = try rowEstimates( + layerKinds: layerKinds, promptLength: promptLength, maxLength: maxLength) let state = layerKinds.map { kind -> CBv2SequenceKV? in makeRow(kind: kind, promptLength: promptLength, maxLength: maxLength) } try registerReserving( state, - estimates: rowEstimates( - layerKinds: layerKinds, promptLength: promptLength, maxLength: maxLength)) + estimates: estimates) return state } @@ -121,6 +126,9 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { layerKinds: [CBv2LayerKind], maxLength: Int ) throws -> [CBv2SequenceKV?] { try validate(layerKinds: layerKinds) + guard maxLength > 0, maxLength <= Int(Int32.max) else { + throw CBv2KVError.backendIneligible(reason: "invalid prefix maximum length") + } guard prefix.count == layerKinds.count else { throw CBv2KVError.backendIneligible( reason: "prefix count \(prefix.count) != layer count \(layerKinds.count)") @@ -129,7 +137,8 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { guard plan.backend == prefixReuseBackend else { throw CBv2KVError.backendIneligible( reason: - "prefix plan backend \(plan.backend.rawValue) != \(prefixReuseBackend.rawValue)") + "prefix plan backend \(plan.backend.rawValue) != \(prefixReuseBackend.rawValue)" + ) } guard plan.matchedBoundary <= maxLength, plan.replayStart >= 0, @@ -142,6 +151,11 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { // Full snapshots use either C (ordinary safe-layout replay) or M // (frozen-full replay). Every owning full row must agree. let expectedSnapshotOffset = plan.restoredFullTokens + guard expectedSnapshotOffset >= 0, expectedSnapshotOffset <= maxLength, + plan.strategy != .frozenFullReplay || plan.replayStart < expectedSnapshotOffset + else { + throw CBv2KVError.backendIneligible(reason: "invalid frozen/full snapshot boundary") + } var sawOwningFull = false for (index, entry) in prefix.enumerated() { let kind = layerKinds[index] @@ -181,9 +195,15 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { "prefix offset \(entry.offset) != planned \(expectedSnapshotOffset) at layer \(index)" ) } - guard entry.keys.dim(2) == entry.offset, entry.values.dim(2) == entry.offset else { + guard entry.keys.shape == [1, kind.kvHeads, entry.offset, kind.headDim], + entry.values.shape == [1, kind.kvHeads, entry.offset, kind.valueHeadDim], + entry.keys.dtype == entry.values.dtype, + [.float16, .bfloat16, .float32].contains(entry.keys.dtype) + else { throw CBv2KVError.backendIneligible( - reason: "full prefix snapshot at layer \(index) does not exactly cover its offset") + reason: + "full prefix snapshot at layer \(index) has incompatible shape, dtype or offset" + ) } } guard sawOwningFull else { @@ -191,6 +211,8 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { reason: "prefix replay requires at least one storage-owning full layer") } + let estimates = try adoptionRowEstimates( + prefix: prefix, layerKinds: layerKinds, maxLength: maxLength) let state = layerKinds.enumerated().map { index, kind -> CBv2SequenceKV? in guard kind.sharesKVWithLayer == nil else { return nil } switch kind.attention { @@ -198,6 +220,7 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { // Sliding rows always start empty at C and rebuild through R. return CBv2WindowedSequenceKV( window: window, kvHeads: kind.kvHeads, headDim: kind.headDim, + valueHeadDim: kind.valueHeadDim, initialOffset: plan.replayStart) case .full: let entry = prefix[index]! @@ -207,7 +230,7 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { replayStart: plan.replayStart, maxLength: maxLength, kvHeads: kind.kvHeads, - headDim: kind.headDim) + headDim: kind.headDim, valueHeadDim: kind.valueHeadDim) } let row = makeRow( kind: kind, @@ -219,10 +242,7 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { } try registerReserving( state, - estimates: adoptionRowEstimates( - prefix: prefix, - layerKinds: layerKinds, - maxLength: maxLength)) + estimates: estimates) return state } @@ -246,6 +266,72 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { try registerReserving(state, estimates: state.map { $0?.byteCount }) } + /// New layout only. Legacy adoption remains unchanged and full-row-only. + func adoptPreparedCheckpoint( + _ state: [CBv2SequenceKV?], codec: CBv2CompleteCheckpointCodec, position: Int, + requestID: CBv2RequestID, maximumSequenceLength: Int + ) throws { + try codec.validateContiguousRows(state, position: position, exactWindow: true) + func backing(_ row: CBv2SequenceKV) -> CBv2ContiguousCheckpointBacking? { + (row as? CBv2FullSequenceKV)?.checkpointBacking + ?? (row as? CBv2WindowedSequenceKV)?.checkpointBacking + } + guard let owner = state.compactMap({ $0 }).first.flatMap(backing), owner.requestID == nil, + owner.lease.admission === codec.admission, + owner.allocationBoundsByLayer.count == state.count, + state.compactMap({ $0 }).allSatisfy({ + $0.absoluteOffset == position && backing($0) === owner + }) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + lock.lock() + defer { lock.unlock() } + var total = 0 + for (i, row) in state.enumerated() { + guard let row else { + guard owner.allocationBoundsByLayer[i] == nil else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + continue + } + guard live[ObjectIdentifier(row)] == nil, let bound = owner.allocationBoundsByLayer[i], + bound >= row.byteCount, + let sum = CBv2KVGeometry.add(total, bound) + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + if let full = row as? CBv2FullSequenceKV { + guard full.maxLength == maximumSequenceLength else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + } + total = sum + } + let available = max(0, liveBytesCapacity - accountedBytesLocked()) + guard total <= available else { + throw CBv2KVError.capacityExhausted(needed: total, available: available) + } + let ticket = try codec.admission.transferContiguousCheckpointStage( + owner.lease, + requestID: requestID, maximumTokens: maximumSequenceLength) + owner.arm(requestID: requestID) + do { + try checkpointBeforeRegistration?() + for (i, row) in state.enumerated() { + guard let row else { continue } + let key = ObjectIdentifier(row) + live[key] = row + reservations[key] = owner.allocationBoundsByLayer[i]! + } + ticket.commit() + owner.finishAdoption() + } catch { + // No row was published. The owner retains C through any remaining + // prepare/diagnostic aliases, then resolves rollback exactly once. + owner.abandonAdoption(ticket) + throw error + } + } + // MARK: - Private /// Bytes currently charged against capacity: each live row counts for @@ -255,7 +341,8 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { /// Caller holds `lock`. private func accountedBytesLocked() -> Int { live.reduce(0) { total, entry in - total + max(entry.value.byteCount, reservations[entry.key] ?? 0) + CBv2KVGeometry.add(total, max(entry.value.byteCount, reservations[entry.key] ?? 0)) + ?? Int.max } } @@ -263,13 +350,27 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { /// write share one critical section so N same-step admissions cannot /// collectively overshoot `bytesCapacity` (the pre-fix bug — rows report /// `byteCount == 0` until first update). - private func registerReserving(_ state: [CBv2SequenceKV?], estimates: [Int?]) throws { + private func registerReserving( + _ state: [CBv2SequenceKV?], estimates: [Int?], requireFreshOwnership: Bool = false + ) throws { precondition(state.count == estimates.count, "estimate/state count mismatch") lock.lock() defer { lock.unlock() } - let needed = zip(state, estimates).reduce(0) { total, pair in - guard let row = pair.0 else { return total } - return total + max(row.byteCount, pair.1 ?? 0) + if requireFreshOwnership { + let identifiers = state.compactMap { $0 }.map(ObjectIdentifier.init) + guard Set(identifiers).count == identifiers.count, + identifiers.allSatisfy({ live[$0] == nil }) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + } + var needed = 0 + for (row, estimate) in zip(state, estimates) { + guard let row else { continue } + guard let sum = CBv2KVGeometry.add(needed, max(row.byteCount, estimate ?? 0)) else { + throw CBv2KVError.backendIneligible(reason: "contiguous reservation overflow") + } + needed = sum } let available = liveBytesCapacity - accountedBytesLocked() guard needed <= available else { @@ -290,17 +391,31 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { switch kind.attention { case .slidingWindow(let window): return CBv2WindowedSequenceKV( - window: window, kvHeads: kind.kvHeads, headDim: kind.headDim) + window: window, kvHeads: kind.kvHeads, headDim: kind.headDim, + valueHeadDim: kind.valueHeadDim) case .full: return CBv2FullSequenceKV( promptLength: promptLength, maxLength: maxLength, - kvHeads: kind.kvHeads, headDim: kind.headDim) + kvHeads: kind.kvHeads, headDim: kind.headDim, valueHeadDim: kind.valueHeadDim) } } private func validate(layerKinds: [CBv2LayerKind]) throws { + guard config.bytesCapacity >= 0, [.float16, .bfloat16, .float32].contains(config.kvDType) + else { + throw CBv2KVError.backendIneligible( + reason: "invalid contiguous native dtype or capacity") + } for (index, kind) in layerKinds.enumerated() { - if case .slidingWindow(let window) = kind.attention, window <= 0 { + guard kind.kvGeometry != nil, kind.queryHeads > 0, kind.queryHeads <= Int(Int32.max), + kind.queryHeads.isMultiple(of: kind.kvHeads) + else { + throw CBv2KVError.backendIneligible( + reason: "layer \(index): invalid native K/V geometry") + } + if case .slidingWindow(let window) = kind.attention, + window <= 0 || window > Int(Int32.max) + { throw CBv2KVError.backendIneligible( reason: "layer \(index): non-positive window \(window)") } @@ -314,6 +429,13 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { reason: "layer \(index): KV-share source \(source) is itself a shared layer") } + let owner = layerKinds[source] + guard owner.kvHeads == kind.kvHeads, owner.headDim == kind.headDim, + owner.valueHeadDim == kind.valueHeadDim, owner.attention == kind.attention + else { + throw CBv2KVError.backendIneligible( + reason: "layer \(index): KV borrower geometry differs from owner") + } } // The v1 contiguous backend attends through MLXFast SDPA, which // supports attention sinks natively — sink models are eligible. @@ -327,17 +449,28 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { /// against capacity at admission. private func rowEstimates( layerKinds: [CBv2LayerKind], promptLength: Int, maxLength: Int - ) -> [Int?] { + ) throws -> [Int?] { let itemSize = config.kvDType.size - return layerKinds.map { kind -> Int? in + return try layerKinds.map { kind -> Int? in guard kind.sharesKVWithLayer == nil else { return nil } + let slots: Int + let maximumStoredTokens: Int switch kind.attention { case .slidingWindow(let window): - return window * kind.kvHeads * kind.headDim * itemSize * 2 + slots = window + maximumStoredTokens = window case .full: - let slots = min(maxLength, max(1, promptLength + CBv2FullSequenceKV.initialSlack)) - return slots * kind.kvHeads * kind.headDim * itemSize * 2 + slots = min(maxLength, max(1, promptLength + CBv2FullSequenceKV.initialSlack)) + maximumStoredTokens = maxLength + } + // Prove both initial and eventual row allocations representable. + guard let geometry = kind.kvGeometry, + geometry.storageBytes(tokens: maximumStoredTokens, elementBytes: itemSize) != nil, + let bytes = geometry.storageBytes(tokens: slots, elementBytes: itemSize) + else { + throw CBv2KVError.backendIneligible(reason: "contiguous row byte geometry overflow") } + return bytes } } @@ -349,17 +482,28 @@ public final class CBv2ContiguousKVBackend: CBv2KVBackend { prefix: [(keys: MLXArray, values: MLXArray, offset: Int)?], layerKinds: [CBv2LayerKind], maxLength: Int - ) -> [Int?] { - layerKinds.enumerated().map { index, kind in + ) throws -> [Int?] { + try layerKinds.enumerated().map { index, kind in guard kind.sharesKVWithLayer == nil else { return nil } + let tokens: Int + let elementBytes: Int switch kind.attention { case .slidingWindow(let window): - return window * kind.kvHeads * kind.headDim * config.kvDType.size * 2 + tokens = window + elementBytes = config.kvDType.size case .full: guard let entry = prefix[index] else { return 0 } - return maxLength * kind.kvHeads * kind.headDim - * (entry.keys.dtype.size + entry.values.dtype.size) + tokens = maxLength + elementBytes = entry.keys.dtype.size + } + guard + let bytes = kind.kvGeometry?.storageBytes( + tokens: tokens, elementBytes: elementBytes) + else { + throw CBv2KVError.backendIneligible( + reason: "contiguous adopted row byte geometry overflow") } + return bytes } } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/FrozenReplayFullSequenceKV.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/FrozenReplayFullSequenceKV.swift index e237010046..294452a13e 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/FrozenReplayFullSequenceKV.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/FrozenReplayFullSequenceKV.swift @@ -22,6 +22,7 @@ public final class CBv2FrozenReplayFullSequenceKV: CBv2SequenceKV, CBv2InnerStat let kvHeads: Int let headDim: Int + let valueHeadDim: Int private var keys: MLXArray private var values: MLXArray @@ -34,7 +35,7 @@ public final class CBv2FrozenReplayFullSequenceKV: CBv2SequenceKV, CBv2InnerStat replayStart: Int, maxLength: Int, kvHeads: Int, - headDim: Int + headDim: Int, valueHeadDim: Int? = nil ) { precondition(replayStart >= 0, "frozen replay start must be non-negative") precondition(snapshot.offset > replayStart, "frozen replay requires C < M") @@ -47,13 +48,14 @@ public final class CBv2FrozenReplayFullSequenceKV: CBv2SequenceKV, CBv2InnerStat && snapshot.values.dim(2) == snapshot.offset, "frozen snapshot must exactly cover [0, M)") precondition( - snapshot.keys.dim(3) == headDim && snapshot.values.dim(3) == headDim, + snapshot.keys.dim(3) == headDim && snapshot.values.dim(3) == (valueHeadDim ?? headDim), "frozen snapshot head dimension mismatch") self.absoluteOffset = replayStart self.frozenHighWater = snapshot.offset self.maxLength = maxLength self.kvHeads = kvHeads self.headDim = headDim + self.valueHeadDim = valueHeadDim ?? headDim // Ownership transfer: retain the staged arrays directly. No adoption // copy, append buffer, rotation, or reallocation occurs before M. self.keys = snapshot.keys @@ -142,12 +144,13 @@ public final class CBv2FrozenReplayFullSequenceKV: CBv2SequenceKV, CBv2InnerStat } private func validateUpdate(keys newKeys: MLXArray, values newValues: MLXArray) { + precondition(newKeys.ndim == 4 && newValues.ndim == 4) let count = newKeys.dim(2) precondition(count > 0, "frozen replay update must be non-empty") precondition(newKeys.dim(0) == 1 && newValues.dim(0) == 1) precondition(newKeys.dim(1) == kvHeads && newValues.dim(1) == kvHeads) precondition(newValues.dim(2) == count) - precondition(newKeys.dim(3) == headDim && newValues.dim(3) == headDim) + precondition(newKeys.dim(3) == headDim && newValues.dim(3) == valueHeadDim) precondition( newKeys.dtype == keys.dtype && newValues.dtype == values.dtype, "frozen replay K/V dtype changed across the matched boundary") @@ -178,7 +181,7 @@ public final class CBv2FrozenReplayFullSequenceKV: CBv2SequenceKV, CBv2InnerStat values = concatenated( [ values, - MLXArray.zeros([1, kvHeads, growth, headDim], dtype: valueTemplate.dtype), + MLXArray.zeros([1, kvHeads, growth, valueHeadDim], dtype: valueTemplate.dtype), ], axis: 2) capacity = newCapacity diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/FullSequenceKV.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/FullSequenceKV.swift index 9010076bd2..b6e871cd9e 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/FullSequenceKV.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/FullSequenceKV.swift @@ -75,7 +75,8 @@ protocol CBv2InnerStateProviding { /// donates the input buffer when refcount permits, so an append is O(n), not /// O(cache). `update` returns temporal-order zero-copy strided views /// `[..., 0.. 0, "CBv2FullSequenceKV: maxLength must be > 0") precondition( promptLength <= maxLength, @@ -117,6 +124,7 @@ public final class CBv2FullSequenceKV: CBv2SequenceKV, CBv2InnerStateProviding, self.maxLength = maxLength self.kvHeads = kvHeads self.headDim = headDim + self.valueHeadDim = valueHeadDim ?? headDim self.capacity = min(maxLength, max(1, promptLength + Self.initialSlack)) } @@ -128,30 +136,59 @@ public final class CBv2FullSequenceKV: CBv2SequenceKV, CBv2InnerStateProviding, /// No prefix copy or lazy assignment may retain the staging buffers. init( restoredKeys: MLXArray, restoredValues: MLXArray, offset: Int, - maxLength: Int, kvHeads: Int, headDim: Int + maxLength: Int, kvHeads: Int, headDim: Int, valueHeadDim: Int? = nil, + checkpointBacking: CBv2ContiguousCheckpointBacking? = nil ) throws { let shape = [1, kvHeads, maxLength, headDim] + let valueWidth = valueHeadDim ?? headDim + let valueShape = [1, kvHeads, maxLength, valueWidth] guard maxLength > 0, offset > 0, offset <= maxLength, - restoredKeys.shape == shape, restoredValues.shape == shape, - restoredKeys.dtype == restoredValues.dtype + CBv2KVGeometry(kvHeads: kvHeads, keyHeadDim: headDim, valueHeadDim: valueWidth) != nil, + restoredKeys.shape == shape, restoredValues.shape == valueShape, + restoredKeys.dtype == restoredValues.dtype, + [.float16, .bfloat16, .float32].contains(restoredKeys.dtype) else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } self.maxLength = maxLength self.kvHeads = kvHeads self.headDim = headDim + self.valueHeadDim = valueWidth self.capacity = maxLength self.absoluteOffset = offset self.keys = restoredKeys self.values = restoredValues + self.checkpointBacking = checkpointBacking + } + + deinit { + keys = nil + values = nil + checkpointBacking = nil } public func update(keys newKeys: MLXArray, values newValues: MLXArray) -> (MLXArray, MLXArray) { + precondition( + newKeys.ndim == 4 && newValues.ndim == 4, + "CBv2FullSequenceKV: K/V must be rank four") let n = newKeys.dim(2) - precondition(newKeys.dim(0) == 1 && newValues.dim(0) == 1, + precondition( + newKeys.dim(0) == 1 && newValues.dim(0) == 1, "CBv2FullSequenceKV holds ONE sequence; got batch \(newKeys.dim(0))") - precondition(newKeys.dim(1) == kvHeads, + precondition( + newKeys.dim(1) == kvHeads && newValues.dim(1) == kvHeads, "CBv2FullSequenceKV: kvHeads mismatch (\(newKeys.dim(1)) != \(kvHeads))") - precondition(newValues.dim(2) == n, + precondition( + newValues.dim(2) == n, "CBv2FullSequenceKV: keys/values token count mismatch") + precondition( + newKeys.dim(3) == headDim && newValues.dim(3) == valueHeadDim, + "CBv2FullSequenceKV: K/V head width mismatch") + // Existing rows retain their allocation dtype; slice assignment casts + // appended pairs as before. Model phase drift is checked by the native + // type probe, not by tightening this general-purpose row contract. + precondition( + newKeys.dtype == newValues.dtype + && [.float16, .bfloat16, .float32].contains(newKeys.dtype), + "CBv2FullSequenceKV: native K/V dtype mismatch") precondition( absoluteOffset + n <= maxLength, "CBv2FullSequenceKV: append past maxLength (\(absoluteOffset) + \(n) > \(maxLength)) — admission bug" @@ -173,7 +210,7 @@ public final class CBv2FullSequenceKV: CBv2SequenceKV, CBv2InnerStateProviding, guard let keys, let values else { return ( MLXArray.zeros([1, kvHeads, 0, headDim], dtype: .float16), - MLXArray.zeros([1, kvHeads, 0, headDim], dtype: .float16), + MLXArray.zeros([1, kvHeads, 0, valueHeadDim], dtype: .float16), absoluteOffset ) } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/WindowedSequenceKV.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/WindowedSequenceKV.swift index 10c924ce60..495153e5c0 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/WindowedSequenceKV.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/WindowedSequenceKV.swift @@ -67,9 +67,11 @@ public final class CBv2WindowedSequenceKV: CBv2SequenceKV, CBv2InnerStateProvidi let kvHeads: Int let headDim: Int + let valueHeadDim: Int private var keys: MLXArray? private var values: MLXArray? + var checkpointBacking: CBv2ContiguousCheckpointBacking? /// Step-scoped PRE-EVICTION views captured by the most recent MULTI-token /// `update()` (`retainedHistory ++ chunk`, up to `window - 1 + n` entries). @@ -77,10 +79,9 @@ public final class CBv2WindowedSequenceKV: CBv2SequenceKV, CBv2InnerStateProvidi /// of the post-eviction ring, so a chunk's earliest queries still see /// their full window — the ring writes have already destroyed those /// entries (slot aliasing at distance `window`). nil after a decode - /// update, rollback, or before any update. Retaining these views keeps - /// the pre-write buffer alive only until the next `update()` replaces - /// them (bounded: one extra window-sized buffer between a chunk update - /// and the following update). + /// update, rollback, or before any update. The engine also retires plain + /// views at their completed step fence: waiting for another update could + /// retain history+chunk backing indefinitely on a paused/finished row. private var borrowableChunkViews: (keys: MLXArray, values: MLXArray)? /// Transaction opened by `beginSpeculativeWrite()` and closed by commit. @@ -99,12 +100,15 @@ public final class CBv2WindowedSequenceKV: CBv2SequenceKV, CBv2InnerStateProvidi /// when a prefix-cache hit starts finite-window replay at C. The row /// starts empty at C while owning full rows may retain immutable K/V /// through M; absolute RoPE positions therefore remain aligned. - public init(window: Int, kvHeads: Int, headDim: Int, initialOffset: Int = 0) { + public init( + window: Int, kvHeads: Int, headDim: Int, valueHeadDim: Int? = nil, initialOffset: Int = 0 + ) { precondition(window > 0, "CBv2WindowedSequenceKV: window must be > 0") precondition(initialOffset >= 0, "CBv2WindowedSequenceKV: negative initialOffset") self.window = window self.kvHeads = kvHeads self.headDim = headDim + self.valueHeadDim = valueHeadDim ?? headDim self.absoluteOffset = initialOffset self.oldestValidPosition = initialOffset } @@ -116,15 +120,75 @@ public final class CBv2WindowedSequenceKV: CBv2SequenceKV, CBv2InnerStateProvidi + (staged.map { $0.keys.nbytes + $0.values.nbytes } ?? 0) } + /// All sharing-layer and historical-capture consumers of this exact step + /// must have completed. Do not clear a chained successor's generation or + /// speculative transaction: its accept/rollback path owns that lifetime. + /// This only drops the row's temporary read aliases, never mutates ring + /// bytes/cursor or returns the row's allocation/admission reservation. + func retireBorrowableChunkViews(afterFencedPosition position: Int) { + guard absoluteOffset == position, !speculativeWriteArmed, staged == nil else { return } + borrowableChunkViews = nil + } + + /// Adopt final physical modulo-ring storage filled by the complete codec. + /// No rotations, copies or allocations occur here. + init( + restoredKeys: MLXArray, restoredValues: MLXArray, offset: Int, + window: Int, kvHeads: Int, headDim: Int, valueHeadDim: Int, + checkpointBacking: CBv2ContiguousCheckpointBacking? = nil + ) throws { + guard window > 0, offset > 0, kvHeads > 0, headDim > 0, valueHeadDim > 0, + restoredKeys.shape == [1, kvHeads, window, headDim], + restoredValues.shape == [1, kvHeads, window, valueHeadDim], + restoredKeys.dtype == restoredValues.dtype, + [.float16, .bfloat16, .float32].contains(restoredKeys.dtype) + else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + self.window = window + self.kvHeads = kvHeads + self.headDim = headDim + self.valueHeadDim = valueHeadDim + absoluteOffset = offset + oldestValidPosition = max(0, offset - window) + keys = restoredKeys + values = restoredValues + self.checkpointBacking = checkpointBacking + } + + deinit { + keys = nil + values = nil + staged = nil + borrowableChunkViews = nil + checkpointBacking = nil + } + public func update(keys newKeys: MLXArray, values newValues: MLXArray) -> (MLXArray, MLXArray) { + precondition( + newKeys.ndim == 4 && newValues.ndim == 4, + "CBv2WindowedSequenceKV: K/V must be rank four") let n = newKeys.dim(2) - precondition(newKeys.dim(0) == 1 && newValues.dim(0) == 1, + precondition( + newKeys.dim(0) == 1 && newValues.dim(0) == 1, "CBv2WindowedSequenceKV holds ONE sequence; got batch \(newKeys.dim(0))") - precondition(newKeys.dim(1) == kvHeads, + precondition( + newKeys.dim(1) == kvHeads && newValues.dim(1) == kvHeads, "CBv2WindowedSequenceKV: kvHeads mismatch (\(newKeys.dim(1)) != \(kvHeads))") - precondition(newValues.dim(2) == n, + precondition( + newValues.dim(2) == n, "CBv2WindowedSequenceKV: keys/values token count mismatch") precondition(n > 0, "CBv2WindowedSequenceKV: empty update") + precondition( + newKeys.dim(3) == headDim && newValues.dim(3) == valueHeadDim, + "CBv2WindowedSequenceKV: K/V head width mismatch") + // Preserve native slice-update casts and temporary concatenation + // promotion for existing callers; the model type probe owns phase + // dtype consistency. Do not pre-cast attention inputs here. + precondition( + newKeys.dtype == newValues.dtype + && [.float16, .bfloat16, .float32].contains(newKeys.dtype), + "CBv2WindowedSequenceKV: native K/V dtype mismatch") if speculativeWriteArmed { return stageSpeculativeUpdate(newKeys: newKeys, newValues: newValues, count: n) @@ -233,7 +297,8 @@ public final class CBv2WindowedSequenceKV: CBv2SequenceKV, CBv2InnerStateProvidi staged = ( concatenated([existingKeys, newKeys], axis: 2), concatenated([existingValues, newValues], axis: 2), - existing.basePosition) + existing.basePosition + ) } else { staged = (newKeys, newValues, absoluteOffset) } @@ -311,7 +376,7 @@ public final class CBv2WindowedSequenceKV: CBv2SequenceKV, CBv2InnerStateProvidi guard let keys, let values, retainedCount > 0 else { return ( MLXArray.zeros([1, kvHeads, 0, headDim], dtype: .float16), - MLXArray.zeros([1, kvHeads, 0, headDim], dtype: .float16), + MLXArray.zeros([1, kvHeads, 0, valueHeadDim], dtype: .float16), absoluteOffset ) } @@ -346,7 +411,7 @@ public final class CBv2WindowedSequenceKV: CBv2SequenceKV, CBv2InnerStateProvidi guard !kParts.isEmpty else { return ( MLXArray.zeros([1, kvHeads, 0, headDim], dtype: .float16), - MLXArray.zeros([1, kvHeads, 0, headDim], dtype: .float16), + MLXArray.zeros([1, kvHeads, 0, valueHeadDim], dtype: .float16), absoluteOffset ) } diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26BlockBatchAttention.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26BlockBatchAttention.swift new file mode 100644 index 0000000000..9761eb726f --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26BlockBatchAttention.swift @@ -0,0 +1,300 @@ +// Copyright © 2026 Eigen Labs. +// SPDX-License-Identifier: Apache-2.0 AND MIT +// Block-batch intent: oMLX #3972/#3994 and Fusion31/32. Arithmetic is the +// unchanged native-rounded attention_nax_bdv, not upstream online softmax. +import Foundation +import MLX +import MLXFast + +/// Engine-installed bound only; no public caller may assert scratch admission. +/// Root integration must charge fixedRequestBytes on the SAME real per-request +/// admission before installing this immutable value in the MiMo cache path. +package final class MiMoV26BlockBatchBudget: Sendable { + package let engineID: UUID + package let modelIdentity, backendIdentity, cacheProviderIdentity: ObjectIdentifier + package let maximumQueries: Int + package let layerCount: Int + package let allocationPolicy: AllocationFootprintPolicy + package let fixedRequestBytes: Int + package init( + engineID: UUID, model: AnyObject, backend: AnyObject, cacheProvider: AnyObject, + maximumQueries: Int, layerCount: Int, policy: AllocationFootprintPolicy + ) throws { + self.engineID = engineID + modelIdentity = ObjectIdentifier(model) + backendIdentity = ObjectIdentifier(backend) + cacheProviderIdentity = ObjectIdentifier(cacheProvider) + self.maximumQueries = maximumQueries + self.layerCount = layerCount + self.allocationPolicy = policy + fixedRequestBytes = try MiMoV26BlockBatchAttention.fixedRequestScratchBytes( + maximumQueries: maximumQueries, layerCount: layerCount, policy: policy) + } +} + +public enum MiMoV26BlockBatchAttention { + public static let environmentKey = "DARKBLOOM_MIMO_BLOCK_BATCH_PREFILL" + static let requested = MiMoV26PrefillPolicy.isEnabled( + ProcessInfo.processInfo.environment[environmentKey]) + static let blockSize = 128 + static let maximumBlocksPerDispatch = 4 + public enum Refusal: Error { case invalidBound, overflow } + + /// Conservative ADDITIVE workspace, not KV or a measured physical peak. + /// Prices all layer graphs and two simultaneous forwards independently: + /// native scaled-Q/output, original+packed masks, descriptors and page slack. + /// No subtraction from the existing host activation/OS/KV reserve. + public static func fixedRequestScratchBytes( + maximumQueries q: Int, layerCount layers: Int, + policy: AllocationFootprintPolicy + ) throws -> Int { + guard let extra = policy.maximumExtraBytes else { throw Refusal.invalidBound } + return try scratchBytes( + maximumQueries: q, layerCount: layers, maximumExtraBytes: extra, + upperBound: policy.upperBound(byteCount:)) + } + static func scratchBytes( + maximumQueries q: Int, layerCount layers: Int, maximumExtraBytes: Int, + upperBound: (Int) -> Int? + ) throws -> Int { + guard (256 ... 8192).contains(q), (1 ... 48).contains(layers) else { + throw Refusal.invalidBound + } + func mul(_ a: Int, _ b: Int) throws -> Int { + let r = a.multipliedReportingOverflow(by: b) + guard a >= 0, b >= 0, !r.overflow else { throw Refusal.overflow } + return r.partialValue + } + func add(_ a: Int, _ b: Int) throws -> Int { + let r = a.addingReportingOverflow(b) + guard a >= 0, b >= 0, !r.overflow else { throw Refusal.overflow } + return r.partialValue + } + let blocks = (q + 127) / 128 + guard maximumExtraBytes >= 0 else { throw Refusal.invalidBound } + // Bound all partitions: each actual allocation's excess over logical + // size is <=maximumExtraBytes from the captured allocator policy. + func project(_ totalLogical: Int, _ maximumAllocations: Int) throws -> Int { + guard maximumAllocations > 0, let one = upperBound(totalLogical), one >= totalLogical + else { + throw Refusal.invalidBound + } + return try add(one, mul(maximumAllocations - 1, maximumExtraBytes)) + } + let scaledQ = try project(mul(mul(q, 64), 192 * 2), blocks) + let outputs = try project(mul(mul(q, 64), 128 * 2 * 2), blocks + 1) + let masks = try project(mul(q, 2 * 255), mul(blocks, 2)) + let descriptors = try project(mul(blocks, 18 * 4), blocks) + let small = try project(mul(blocks, 8 * 512), mul(blocks, 8)) + let device = try add(try add(scaledQ, outputs), try add(masks, try add(descriptors, small))) + let host = try add(mul(blocks, 18 * 4 * 2), 16_384) + return try mul(mul(try add(device, host), layers), 2) + } + + struct Descriptor: Equatable, Sendable { + let queryStart, queryCount, keyStart, keyCount: Int + let causal: Bool + var alignedQuery: Bool { queryCount % 64 == 0 } + var alignedKey: Bool { keyCount % 32 == 0 } + func sameVariant(_ other: Self) -> Bool { + causal == other.causal && alignedQuery == other.alignedQuery + && alignedKey == other.alignedKey + } + } + struct Plan: Sendable { + let queryCount, keyCount, heads, kvHeads: Int + let window: Int? + let groups: [[Descriptor]] + } + + /// Scalar shape validation only; no lazy strides/data read or GPU query. + static func layout( + queries: Int, keys: Int, heads: Int, kvHeads: Int, + window: Int?, admittedMaximumQueries: Int + ) -> Plan? { + guard (256 ... 8192).contains(admittedMaximumQueries), + queries > 128, queries <= admittedMaximumQueries, + keys >= queries, keys <= 1_048_576, + (1 ... 64).contains(heads), kvHeads > 0, heads.isMultiple(of: kvHeads), + window == nil || window == 128 + else { return nil } + let history = keys - queries + var groups: [[Descriptor]] = [] + var offset = 0 + while offset < queries { + let count = min(128, queries - offset) + // <=8-row tails must retain their original stock fallback. The + // whole call declines before allocation; no partially built result. + guard count > 8 else { return nil } + let end = history + offset + count + let start = window.map { max(0, history + offset + 1 - $0) } ?? 0 + let d = Descriptor( + queryStart: offset, queryCount: count, keyStart: start, + keyCount: end - start, causal: window == nil || end - start <= window!) + if let last = groups.last, last.count < maximumBlocksPerDispatch, + last.last!.sameVariant(d) + { + groups[groups.count - 1].append(d) + } else { + groups.append([d]) + } + offset += count + } + // At least one genuinely aggregated launch; not a renamed scalar loop. + guard groups.contains(where: { $0.count > 1 }) else { return nil } + return .init( + queryCount: queries, keyCount: keys, heads: heads, kvHeads: kvHeads, window: window, + groups: groups) + } + + static func makePlan( + queries q: MLXArray, keys k: MLXArray, values v: MLXArray, + scale: Float, sinks: MLXArray?, window: Int?, maximumQueries: Int, production: Bool + ) -> Plan? { + guard q.ndim == 4, k.ndim == 4, v.ndim == 4, q.dim(0) == 1, k.dim(0) == 1, v.dim(0) == 1, + q.dtype == .bfloat16 || q.dtype == .float16, k.dtype == q.dtype, v.dtype == q.dtype, + q.dim(3) == 192, k.dim(3) == 192, v.dim(3) == 128, + Array(k.shape.prefix(3)) == Array(v.shape.prefix(3)), + scale.isFinite, scale > 0 + else { return nil } + if production && (q.dim(1) != 64 || ![4, 8].contains(k.dim(1))) { return nil } + if let sinks, sinks.shape != [q.dim(1)] || sinks.dtype != q.dtype { return nil } + return layout( + queries: q.dim(2), keys: k.dim(2), heads: q.dim(1), kvHeads: k.dim(1), + window: window, admittedMaximumQueries: maximumQueries) + } + + private static let lock = NSLock() + nonisolated(unsafe) private static var encodings = 0 + public static func encodedDispatches() -> Int { lock.withLock { encodings } } + /// Encoded range launches only, not GPU completion or qualification. + public static func keyRangeEncodedDispatches() -> Int { + MiMoV26NAXAttentionKeyRanges.encodedGroupedDispatches() + } + + // A narrow synchronous graph-build binding, like existing position scopes. + // The engine installs its exact immutable charged capability; no arrays, + // tasks, receipts or lifecycle authority live in this scope. + @TaskLocal private static var activeBudget: MiMoV26BlockBatchBudget? + static func withBudget( + _ budget: MiMoV26BlockBatchBudget?, + _ body: () throws -> Result + ) rethrows -> Result { + try $activeBudget.withValue(budget, operation: body) + } + static func matchesCurrentBudget(_ budget: MiMoV26BlockBatchBudget?) -> Bool { + guard let budget else { return false } + return activeBudget === budget + } + + /// Only the root-composed authenticated MiMo cache passes a charged budget. + /// Non-NAX, nil budget, changed global block width and every unsupported + /// shape decline before grouped native work. No private stream/eval/fence. + static func tryAttention( + queries: MLXArray, keys: MLXArray, values: MLXArray, + scale: Float, sinks: MLXArray?, window: Int?, queryBlockSize: Int, + budget: MiMoV26BlockBatchBudget?, layerIndex: Int? = nil, + enabled: Bool = requested + ) -> MLXArray? { + guard enabled, MiMoV26NAXAttention.requested, queryBlockSize == blockSize, let budget, + matchesCurrentBudget(budget), + let plan = makePlan( + queries: queries, keys: keys, values: values, scale: scale, + sinks: sinks, window: window, maximumQueries: budget.maximumQueries, + production: true) + else { return nil } + let stream = StreamOrDevice.default + guard MiMoV26NAXGatherQMM.gpuStream(stream), MiMoV26NAXGatherQMM.naxAvailable else { + return nil + } + // Whole-layer EXTRA scratch is admitted before any range array exists. + // Nil preserves the existing grouped body exactly. + let ranges = MiMoV26NAXKeyRangeNative.prepareLayer( + budget: budget, layerIndex: layerIndex, plan: plan) + let value = launch( + queries: queries, keys: keys, values: values, scale: scale, sinks: sinks, + plan: plan, stream: stream, keyRanges: ranges) + let rangeGroups = ranges?.groups ?? [:] + let launches = + plan.groups.count - rangeGroups.count + + rangeGroups.values.reduce(0) { $0 + $1.dispatches } + lock.withLock { encodings += launches } + return value + } + + private static let kernel = MLXFast.metalKernel( + name: "mimo_v26_exact_block_batch_attention", + inputNames: ["q", "k", "v", "mask", "sinks", "descriptors"], outputNames: ["out"], + source: MiMoV26BlockBatchMetalSources.source, + header: MiMoV26NAXMetalSources.mlxHeader + "\n" + MiMoV26NAXAttentionMetalSources.header + + "\n", + ensureRowContiguous: false) + + /// Numerical test seam. Native arrays remain under the caller's real + /// evaluation owner; this function never reports completion or admission. + static func launch( + queries: MLXArray, keys: MLXArray, values: MLXArray, + scale: Float, sinks: MLXArray?, plan: Plan, stream: StreamOrDevice = .default, + keyRanges: MiMoV26NAXKeyRangeLayer? = nil + ) -> MLXArray { + let nativeSinks = + sinks.map { contiguous($0, stream: stream) } + ?? MLXArray.zeros([1], dtype: queries.dtype) + var outputs: [MLXArray] = [] + for (groupIndex, group) in plan.groups.enumerated() { + if let keyRanges, let schedule = keyRanges.groups[groupIndex] { + outputs.append( + MiMoV26NAXAttentionKeyRanges.launchGrouped( + queries: queries, keys: keys, values: values, scale: scale, sinks: sinks, + window: plan.window, schedule: schedule, layer: keyRanges, stream: stream)) + continue + } + let first = group.first! + let end = group.last!.queryStart + group.last!.queryCount + let length = end - first.queryStart + let scaled = + queries[0..., 0..., first.queryStart ..< end, 0...] + * MLXArray(scale).asType(queries.dtype) + var words: [Int32] = [] + var masks: [MLXArray] = [] + var maskOffset = 0 + for d in group { + // Exact same mask builder and physical key length as the old loop. + let mode = CBv2AttentionV1.maskMode( + L: d.queryCount, kL: d.keyCount, window: plan.window) + if case .array(let mask) = mode { + masks.append(mask.reshaped([-1])) + } + // Original56byte AttnParams followed by4offset words. K/V + // offsets address ORIGINAL row.update arrays; no key gathering. + words += [ + 1, Int32(plan.heads), 192, Int32(d.queryCount), Int32(d.keyCount), + Int32(plan.heads / plan.kvHeads), Int32(bitPattern: scale.bitPattern), + Int32((d.queryCount + 63) / 64), Int32((d.keyCount + 31) / 32), + Int32(d.queryCount / 64), Int32(d.keyCount / 32), Int32(d.queryCount % 64), + Int32(d.keyCount % 32), Int32(d.keyCount - d.queryCount), + Int32(d.queryStart - first.queryStart), Int32(d.keyStart), Int32(maskOffset), 0, + ] + if !d.causal { maskOffset += d.queryCount * d.keyCount } + } + let mask = + masks.isEmpty + ? MLXArray.zeros([1], dtype: .bool) + : (masks.count == 1 ? masks[0] : concatenated(masks)) + let result = kernel( + [scaled, keys, values, mask, nativeSinks, MLXArray(words)], + template: [ + ("T", queries.dtype), ("ALIGN_Q", first.alignedQuery), + ("ALIGN_K", first.alignedKey), + ("HAS_MASK", !first.causal), ("DO_CAUSAL", first.causal), + ("HAS_SINKS", sinks != nil), + ], + grid: (2 * 128, plan.heads, group.count), threadGroup: (128, 1, 1), + outputShapes: [[1, length, plan.heads, 128]], outputDTypes: [queries.dtype], + stream: stream) + precondition(result.count == 1) + outputs.append(result[0].transposed(0, 2, 1, 3)) + } + return outputs.count == 1 ? outputs[0] : concatenated(outputs, axis: 2) + } +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26BlockBatchMetalSources.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26BlockBatchMetalSources.swift new file mode 100644 index 0000000000..5b6a4237a1 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26BlockBatchMetalSources.swift @@ -0,0 +1,30 @@ +// Copyright © 2026 Eigen Labs. +// SPDX-License-Identifier: Apache-2.0 AND MIT +// Wrapper only. No edit/copy of the shared ordinary attention_nax_bdv body. +enum MiMoV26BlockBatchMetalSources { + static let source = #""" + const uint block = threadgroup_position_in_grid.z; + const device int* row = descriptors + block * 18; + const device omlx_nax::AttnParams* params = + reinterpret_cast(row); + // Uniform for the entire threadgroup, before any shared-body barrier. + if (threadgroup_position_in_grid.x >= uint(params->NQ)) return; + const int q_offset = row[14]; + const int k_offset = row[15]; + const int mask_offset = row[16]; + const int64_t qs[4] = {q_strides[0],q_strides[1],q_strides[2],q_strides[3]}; + const int64_t ks[4] = {k_strides[0],k_strides[1],k_strides[2],k_strides[3]}; + const int64_t vs[4] = {v_strides[0],v_strides[1],v_strides[2],v_strides[3]}; + // Original masks are head-broadcast rank2 Boolean arrays, packed by block. + const int64_t ms[4] = {0,0,params->kL,1}; + const uint3 local_tid(threadgroup_position_in_grid.x,threadgroup_position_in_grid.y,0); + omlx_nax::attention_nax_bdv< + T,64,32,192,128,4,1,ALIGN_Q,ALIGN_K,HAS_MASK,DO_CAUSAL,HAS_SINKS,bool,float>( + q + int64_t(q_offset)*qs[2], + k + int64_t(k_offset)*ks[2], + v + int64_t(k_offset)*vs[2], + out + int64_t(q_offset)*params->H*128, + params,qs,ks,vs,ms,mask + mask_offset,sinks, + simdgroup_index_in_threadgroup,local_tid); + """# +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26DecodeExpertMetal.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26DecodeExpertMetal.swift new file mode 100644 index 0000000000..c9f109f7a2 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26DecodeExpertMetal.swift @@ -0,0 +1,219 @@ +// SPDX-License-Identifier: Apache-2.0 +// Adapted from jundot/omlx #3990 moe_decode.py at +// e58cab4d5db6c3ca27742a45a50ab6287b1b1bcb. +// MXFP4 arithmetic derived from MLX, Copyright © 2024 Apple Inc. +// Swift adaptation Copyright © 2026 Eigen Labs. +// See docs/mimo-v26/DECODE-EXPERT-ATTRIBUTION.md. + +enum MiMoV26DecodeExpertMetal { + static let header = """ + // MXFP4 e2m1 nibble -> float exactly like MLX's fp4_e2m1 (via half). + inline float omlx_fp4(uint v) { + uint b = v & 0xF; + half c = as_type(ushort((b & 7) << 9)); + c *= 16384.0; + return static_cast((b & 8) ? -c : c); + } + + // e8m0 scale -> float like MLX's fp8_e8m0. + inline float omlx_e8m0(uint8_t s) { + uint out = (s == 0 ? 0x400000u : (static_cast(s) << 23)); + return as_type(out); + } + + // MLX fp_quantized.h qdot on 8 packed bytes (4 x uint16). + inline float omlx_qdot16(uint2 w, thread const float* x, float scale) { + ushort ws[4] = {ushort(w.x & 0xFFFF), ushort(w.x >> 16), ushort(w.y & 0xFFFF), ushort(w.y >> 16)}; + float accum = 0; + for (int i = 0; i < 4; i++) { + accum += + (x[4 * i] * omlx_fp4(ws[i]) + x[4 * i + 1] * omlx_fp4(ws[i] >> 4) + + x[4 * i + 2] * omlx_fp4(ws[i] >> 8) + + x[4 * i + 3] * omlx_fp4(ws[i] >> 12)); + } + return scale * accum; + } + + // Pinned compiled.cpp writes each primitive to its declared dtype. + // This matches unary_ops.h Sigmoid, applied in activation precision. + struct OmlxSigmoid { + template + U operator()(U x) thread { + auto y = 1 / (1 + metal::exp(metal::abs(x))); + return (x < 0) ? y : 1 - y; + } + }; + template + inline T mimo_swiglu(T gate, T up) { + T sig = OmlxSigmoid{}(gate); + T activated = gate * sig; + return activated * up; + } + """ + + static let gateUp = """ + constexpr int VPT = 16; + uint pid = threadgroup_position_in_grid.x; + uint rb = threadgroup_position_in_grid.y; + uint sgid = simdgroup_index_in_threadgroup; + uint lane = thread_index_in_simdgroup; + uint e = inds[pid]; + for (uint q = 0; q < pid; q++) { + if (inds[q] == e) { + return; + } + } + uint members[MAXDUP]; + int nm = 0; + // One representative per token row; duplicate slots in that row have + // identical inputs. Thus nm <= ROWS even when all NPAIRS slots repeat. + for (uint q = pid; q < NPAIRS; q++) { + if (inds[q] == e) { + bool seen_row = false; + for (int j = 0; j < nm; j++) { + seen_row = seen_row || members[j] / TOPK == q / TOPK; + } + if (!seen_row) { + members[nm++] = q; + } + } + } + const int n0 = (rb * NSG + sgid) * RPS; + constexpr int KW = KDIM / 8; // uint32 per weight row + constexpr int KS = KDIM / 32; // scales per row + const device uint32_t* gw = wg + (size_t(e) * GROWS + n0) * KW + lane * 2; + const device uint8_t* gs = sg + (size_t(e) * GROWS + n0) * KS + lane / 2; + const device uint32_t* uw = wu + (size_t(e) * UROWS + UOFF + n0) * KW + lane * 2; + const device uint8_t* us = su + (size_t(e) * UROWS + UOFF + n0) * KS + lane / 2; + + float rg[MAXDUP][RPS]; + float ru[MAXDUP][RPS]; + for (int j = 0; j < MAXDUP; j++) { + for (int r = 0; r < RPS; r++) { + rg[j][r] = 0; + ru[j][r] = 0; + } + } + for (int b = 0; b < KDIM / 512; b++) { + uint2 wgv[RPS]; + uint2 wuv[RPS]; + float sgv[RPS]; + float suv[RPS]; + for (int r = 0; r < RPS; r++) { + wgv[r] = *(const device uint2*)(gw + r * KW + b * 64); + wuv[r] = *(const device uint2*)(uw + r * KW + b * 64); + sgv[r] = omlx_e8m0(gs[r * KS + b * 16]); + suv[r] = omlx_e8m0(us[r * KS + b * 16]); + } + for (int j = 0; j < MAXDUP; j++) { + if (j < nm) { + const device T* xp = x + size_t(members[j] / TOPK) * KDIM + b * 512 + lane * VPT; + float xt[VPT]; + for (int i = 0; i < VPT; i++) { + xt[i] = static_cast(xp[i]); + } + for (int r = 0; r < RPS; r++) { + rg[j][r] += omlx_qdot16(wgv[r], xt, sgv[r]); + ru[j][r] += omlx_qdot16(wuv[r], xt, suv[r]); + } + } + } + } + for (int j = 0; j < MAXDUP; j++) { + if (j < nm) { + for (int r = 0; r < RPS; r++) { + float g = simd_sum(rg[j][r]); + float u = simd_sum(ru[j][r]); + if (lane == 0) { + T gt = static_cast(g); + T ut = static_cast(u); + T value = mimo_swiglu(gt, ut); + uint first = (members[j] / TOPK) * TOPK; + for (uint q = first; q < first + TOPK; q++) { + if (inds[q] == e) { + act[size_t(q) * NOUT + n0 + r] = value; + } + } + } + } + } + } + """ + + static let down = """ + constexpr int VPT = 16; + uint pid = threadgroup_position_in_grid.x; + uint rb = threadgroup_position_in_grid.y; + uint sgid = simdgroup_index_in_threadgroup; + uint lane = thread_index_in_simdgroup; + uint e = inds[pid]; + for (uint q = 0; q < pid; q++) { + if (inds[q] == e) { + return; + } + } + uint members[MAXDUP]; + int nm = 0; + // One representative per token row; duplicate slots in that row have + // identical inputs. Thus nm <= ROWS even when all NPAIRS slots repeat. + for (uint q = pid; q < NPAIRS; q++) { + if (inds[q] == e) { + bool seen_row = false; + for (int j = 0; j < nm; j++) { + seen_row = seen_row || members[j] / TOPK == q / TOPK; + } + if (!seen_row) { + members[nm++] = q; + } + } + } + const int n0 = (rb * NSG + sgid) * RPS; + constexpr int KW = KDIM / 8; + constexpr int KS = KDIM / 32; + const device uint32_t* dw = w + (size_t(e) * NOUT + n0) * KW + lane * 2; + const device uint8_t* ds = s + (size_t(e) * NOUT + n0) * KS + lane / 2; + + float acc[MAXDUP][RPS]; + for (int j = 0; j < MAXDUP; j++) { + for (int r = 0; r < RPS; r++) { + acc[j][r] = 0; + } + } + for (int b = 0; b < KDIM / 512; b++) { + uint2 wv[RPS]; + float sv[RPS]; + for (int r = 0; r < RPS; r++) { + wv[r] = *(const device uint2*)(dw + r * KW + b * 64); + sv[r] = omlx_e8m0(ds[r * KS + b * 16]); + } + for (int j = 0; j < MAXDUP; j++) { + if (j < nm) { + const device T* xp = a + size_t(members[j]) * KDIM + b * 512 + lane * VPT; + float xt[VPT]; + for (int i = 0; i < VPT; i++) { + xt[i] = static_cast(xp[i]); + } + for (int r = 0; r < RPS; r++) { + acc[j][r] += omlx_qdot16(wv[r], xt, sv[r]); + } + } + } + } + for (int j = 0; j < MAXDUP; j++) { + if (j < nm) { + for (int r = 0; r < RPS; r++) { + float v = simd_sum(acc[j][r]); + if (lane == 0) { + T value = static_cast(v); + uint first = (members[j] / TOPK) * TOPK; + for (uint q = first; q < first + TOPK; q++) { + if (inds[q] == e) { + y[size_t(q) * NOUT + n0 + r] = value; + } + } + } + } + } + } + """ +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26DecodeExperts.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26DecodeExperts.swift new file mode 100644 index 0000000000..f50fe7010e --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26DecodeExperts.swift @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: Apache-2.0 +// Adapted from jundot/omlx #3990 moe_decode.py at +// e58cab4d5db6c3ca27742a45a50ab6287b1b1bcb. +// Swift adaptation Copyright © 2026 Eigen Labs. +// See docs/mimo-v26/DECODE-EXPERT-ATTRIBUTION.md. + +import Cmlx +import Foundation +import MLX + +/// Paired gate/up/SwiGLU and down projection. Sharing is per distinct expert +/// and token row; every routed slot is written, including duplicate slots. +enum MiMoV26DecodeExperts { + static let requested = + ProcessInfo.processInfo.environment["DARKBLOOM_MIMO_DECODE_EXPERTS"] == "1" + + struct Matrix { + let weight: MLXArray + let scales: MLXArray + } + + struct Result { + let activation: MLXArray + let output: MLXArray + } + + static func gpuStream(_ stream: StreamOrDevice) -> Bool { + var device = mlx_device_new() + defer { mlx_device_free(device) } + var type = MLX_CPU + return mlx_stream_get_device(&device, stream.ctx) == 0 + && mlx_device_get_type(&type, device) == 0 && type == MLX_GPU + } + + static func supports( + rows: Int, hidden: Int, intermediate: Int, experts: Int, + topK: Int, dtype: DType + ) -> Bool { + (1 ... 7).contains(rows) && topK == 8 && (8 ... 256).contains(experts) + && (512 ... 4096).contains(hidden) && hidden % 512 == 0 + && (512 ... 4096).contains(intermediate) && intermediate % 512 == 0 + && (dtype == .bfloat16 || dtype == .float16) + } + + private static func matrix(_ layer: SwitchLinear) -> Matrix? { + guard let quantized = layer as? QuantizedSwitchLinear, + ObjectIdentifier(type(of: quantized)) == ObjectIdentifier(QuantizedSwitchLinear.self), + quantized.mode == .mxfp4, quantized.bits == 4, quantized.groupSize == 32, + quantized.bias == nil, quantized.biases == nil + else { return nil } + return Matrix(weight: quantized.weight, scales: quantized.scales) + } + + /// SwitchLayers calls this before its normal projection. + /// No dtype conversion, CPU synchronization, tensor cache or layout memo. + static func tryProject( + _ x: MLXArray, indices: MLXArray, glu: SwitchGLU, + enabled: Bool + ) -> Result? { + guard enabled, glu.weightedReductionProfile == .mimoV26FP32, + ObjectIdentifier(type(of: glu)) == ObjectIdentifier(SwitchGLU.self), + glu.activationProduct != nil, glu.isSiluActivation, + MLXHardwareInfo.isCompiledDecodeSupported, + let down = matrix(glu.downProj) + else { return nil } + if let fused = glu.gateUpProj { + guard let gateUp = matrix(fused) else { return nil } + return project( + x, indices: indices, gate: gateUp, up: gateUp, down: down, + upOffset: glu.hiddenDims) + } + guard let gate = glu.gateProj, let up = glu.upProj, + let gateMatrix = matrix(gate), let upMatrix = matrix(up) + else { return nil } + return project(x, indices: indices, gate: gateMatrix, up: upMatrix, down: down) + } + + /// Internal raw packed-matrix seam also permits bounded synthetic fixtures. + /// Production calls reach it only through the stock MiMo module gate above. + static func project( + _ x: MLXArray, indices: MLXArray, gate: Matrix, up: Matrix, + down: Matrix, upOffset: Int = 0 + ) -> Result? { + let stream = StreamOrDevice.default + guard gpuStream(stream), x.ndim == 3, x.dim(0) == 1, + indices.ndim == 3, indices.shape == [1, x.dim(1), 8], + indices.dtype == .uint32, down.weight.ndim == 3, + down.scales.ndim == 3 + else { return nil } + let rows = x.dim(1) + let hidden = x.dim(2) + let intermediate = down.weight.dim(2) * 8 + let count = down.weight.dim(0) + guard + supports( + rows: rows, hidden: hidden, intermediate: intermediate, + experts: count, topK: 8, dtype: x.dtype), + down.weight.shape == [count, hidden, intermediate / 8], + down.scales.shape == [count, hidden, intermediate / 32], + upOffset == 0 || upOffset == intermediate + else { return nil } + let gateRows = upOffset == 0 ? intermediate : 2 * intermediate + guard gate.weight.shape == [count, gateRows, hidden / 8], + up.weight.shape == [count, gateRows, hidden / 8], + gate.scales.shape == [count, gateRows, hidden / 32], + up.scales.shape == [count, gateRows, hidden / 32], + [gate, up, down].allSatisfy({ $0.weight.dtype == .uint32 && $0.scales.dtype == .uint8 }) + else { return nil } + let pairs = rows * 8 + let activation = gateUpKernel( + [x, indices, gate.weight, gate.scales, up.weight, up.scales], + template: [ + ("T", x.dtype), ("KDIM", hidden), ("NOUT", intermediate), + ("GROWS", gateRows), ("UROWS", gateRows), ("UOFF", upOffset), + ("TOPK", 8), ("NPAIRS", pairs), ("MAXDUP", rows), ("NSG", 2), ("RPS", 4), + ], + grid: (32 * pairs, 2 * (intermediate / 8), 1), threadGroup: (32, 2, 1), + outputShapes: [[1, rows, 8, intermediate]], outputDTypes: [x.dtype], stream: stream)[0] + let output = downKernel( + [activation, indices, down.weight, down.scales], + template: [ + ("T", x.dtype), ("KDIM", intermediate), ("NOUT", hidden), + ("TOPK", 8), ("NPAIRS", pairs), ("MAXDUP", rows), ("NSG", 2), ("RPS", 4), + ], + grid: (32 * pairs, 2 * (hidden / 8), 1), threadGroup: (32, 2, 1), + outputShapes: [[1, rows, 8, hidden]], outputDTypes: [x.dtype], stream: stream)[0] + return Result(activation: activation, output: output) + } + + private static let gateUpKernel = MLXFast.metalKernel( + name: "mimo_v26_mxfp4_decode_gate_up", inputNames: ["x", "inds", "wg", "sg", "wu", "su"], + outputNames: ["act"], source: MiMoV26DecodeExpertMetal.gateUp, + header: MiMoV26DecodeExpertMetal.header, ensureRowContiguous: true) + + private static let downKernel = MLXFast.metalKernel( + name: "mimo_v26_mxfp4_decode_down", inputNames: ["a", "inds", "w", "s"], + outputNames: ["y"], source: MiMoV26DecodeExpertMetal.down, + header: MiMoV26DecodeExpertMetal.header, ensureRowContiguous: true) +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26DecodeRows.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26DecodeRows.swift new file mode 100644 index 0000000000..f8d4586c52 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26DecodeRows.swift @@ -0,0 +1,148 @@ +// Copyright © 2026 Eigen Labs. +// SPDX-License-Identifier: Apache-2.0 +// oMLX #4033 multi-row vector attention, adapted to the pinned core's +// FP32 partials and this engine's SINGLE-ROW serial authority. +import Foundation +import MLX +import MLXFast + +enum MiMoV26DecodeRows { + static let requested = + ProcessInfo.processInfo.environment[ + "DARKBLOOM_MIMO_V26_DECODE_ROWS"] == "1" + + /// The source core consumes partials in 32-block groups. This is a + /// refusal bound for this optional specialization, not an operator cap. + static func blocks(keys: Int, simds: Int, deviceClass: Character, override: Int = 0) -> Int? { + guard keys > 0, simds > 0, simds <= 32 else { return nil } + let base: Int + if deviceClass == "s" { + base = + keys > 1024 && simds > 4 + ? (keys <= 8192 ? 128 : keys <= 32768 ? 256 : keys <= 65536 ? 512 : 1024) + : 64 + } else if deviceClass == "d" { + base = + simds <= 2 && keys > 8192 + ? 256 + : simds >= 6 && keys >= 65536 + ? 1024 + : simds >= 6 && keys >= 16384 ? 512 : 128 + } else { + base = simds >= 4 ? 64 : 32 + } + guard override <= 4096 else { return nil } + return override > 0 ? ((override + 31) / 32) * 32 : base + } + + /// Compare EVERY native scalar call, not oMLX's different two-row grouping. + /// Crossing a single-pass or block-count boundary preserves the old path. + static func serialBlocks( + rows: Int, keys: Int, heads: Int = 64, kvHeads: Int = 4, + deviceClass: Character, override: Int = 0 + ) -> Int? { + guard (2 ... 4).contains(rows), keys >= rows, heads == 64, kvHeads == 4 else { return nil } + let gqa = heads / kvHeads + var selected: Int? + for row in 0 ..< rows { + let visible = keys - rows + row + 1 + guard + ((deviceClass == "d" || deviceClass == "s") && visible >= 1024) + || (kvHeads < heads && visible >= 4096), + let value = blocks( + keys: visible, simds: gqa, + deviceClass: deviceClass, override: override) + else { return nil } + if let selected, selected != value { return nil } + selected = value + } + return selected + } + + private static var deviceClass: Character? { + #if os(macOS) || os(iOS) || os(tvOS) || os(visionOS) + let name = GPU.deviceInfo().architecture + guard name.hasPrefix("applegpu_") else { return nil } + return name.last + #else + return nil + #endif + } + + private static let first = MLXFast.metalKernel( + name: "mimo_fp32partial_rows_pass1", + inputNames: ["queries", "keys", "values", "scale", "mask", "sinks"], + outputNames: ["partials", "sums", "maxs"], + source: MiMoV26DecodeRowsMetalSources.pass1, ensureRowContiguous: false) + private static let second = MLXFast.metalKernel( + name: "mimo_fp32partial_rows_pass2", + inputNames: ["partials", "sums", "maxs"], outputNames: ["out"], + source: MiMoV26DecodeRowsMetalSources.pass2, ensureRowContiguous: true) + + /// Only genuine singleton, full-causal native MiMo verification calls. + /// SWA, spans, softcap, arbitrary masks, batching and unknown devices use + /// the original path. No host stride inspection or native evaluation here. + static func tryAttention( + queries q: MLXArray, keys k: MLXArray, values v: MLXArray, + scale: Float, sinks: MLXArray? + ) -> MLXArray? { + guard requested, q.ndim == 4, k.ndim == 4, v.ndim == 4, + q.dim(0) == 1, q.dim(1) == 64, q.dim(3) == 192, + k.dim(0) == 1, k.dim(1) == 4, k.dim(3) == 192, + v.shape == [1, 4, k.dim(2), 128], k.dim(2) <= 1_048_576, + q.dtype == .bfloat16 || q.dtype == .float16, + k.dtype == q.dtype, v.dtype == q.dtype, scale.isFinite, scale > 0, + MiMoV26NAXGatherQMM.gpuStream(.default), let deviceClass + else { return nil } + if let sinks { guard sinks.shape == [64], sinks.dtype == q.dtype else { return nil } } + let raw = + ProcessInfo.processInfo.environment["MLX_SDPA_BLOCKS"]? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + guard + let blocks = serialBlocks( + rows: q.dim(2), keys: k.dim(2), + deviceClass: deviceClass, override: Int(raw) ?? 0) + else { return nil } + return launch(queries: q, keys: k, values: v, scale: scale, sinks: sinks, blocks: blocks) + } + + /// Internal oracle seam. The caller owns actual evaluation/error handling. + static func launch( + queries q: MLXArray, keys k: MLXArray, values v: MLXArray, + scale: Float, sinks: MLXArray?, blocks: Int, + stream: StreamOrDevice = .default + ) -> MLXArray { + let rows = q.dim(2) + let heads = q.dim(1) + let kvHeads = k.dim(1) + let batch = q.dim(0) + precondition((2 ... 4).contains(rows) && batch == 1 && heads == 64 && kvHeads == 4) + precondition(blocks > 0 && blocks <= 4096 && blocks.isMultiple(of: 32)) + let preparedSinks = + sinks.map { contiguous($0, stream: stream) } + ?? MLXArray.zeros([1], dtype: q.dtype) + let partials = first( + [q, k, v, MLXArray([scale]), MLXArray.zeros([1], dtype: .bool), preparedSinks], + template: [ + ("T", q.dtype), ("MT", DType.bool), ("D", 192), ("V", 128), + ("G", heads / kvHeads), ("NKV", kvHeads), ("ROWS", rows), + ("BLOCKS", blocks), ("CAUSAL", true), ("MASK_KIND", 0), + ("HAS_SINKS", sinks != nil), + ], + grid: (32 * kvHeads, (heads / kvHeads) * batch, blocks), + threadGroup: (32, heads / kvHeads, 1), + outputShapes: [ + [batch * heads * rows, blocks, 128], + [batch * heads * rows, blocks], [batch * heads * rows, blocks], + ], + outputDTypes: [.float32, .float32, .float32], stream: stream) + let result = second( + partials, + template: [ + ("T", q.dtype), ("V", 128), ("NQ", heads), ("ROWS", rows), ("BLOCKS", blocks), + ], + grid: (1024 * batch * heads, rows, 1), threadGroup: (1024, 1, 1), + outputShapes: [[batch, rows, heads * 128]], outputDTypes: [q.dtype], stream: stream) + return result[0].reshaped([batch, rows, heads, 128]).transposed(0, 2, 1, 3) + } +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26DecodeRowsMetalSources.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26DecodeRowsMetalSources.swift new file mode 100644 index 0000000000..d8063b0fd4 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26DecodeRowsMetalSources.swift @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: Apache-2.0 AND MIT +// oMLX PR #4033, c10e4ad57b180fa1aa88bf40532cba4362b6851a. +// Modified for the selected DarkBloom core: partial outputs remain FP32, +// matching sdpa_vector_2pass_fp32partials, rather than upstream BF16 partials. +// Apple/MIT notice is preserved in MiMoV26NAXMetalSources.swift; +// oMLX Apache notice/license is docs/mimo-v26/LICENSE-OMLX. +enum MiMoV26DecodeRowsMetalSources { + static let pass1 = #""" + + constexpr int BD = 32; + constexpr int QK = D / BD; + constexpr int VP = V / BD; + typedef float U; + + const int kv_head_idx = threadgroup_position_in_grid.x; + const int batch_idx = threadgroup_position_in_grid.y; + const int block_idx = threadgroup_position_in_grid.z; + const int g = simdgroup_index_in_threadgroup; + const int simd_lid = thread_index_in_simdgroup; + const int N = keys_shape[2]; + const int num_q_heads = NKV * G; + const int q_head_idx = G * kv_head_idx + g; + const int q_batch_head_idx = batch_idx * num_q_heads + q_head_idx; + + U q[ROWS][QK]; + U o[ROWS][VP]; + U max_score[ROWS]; + U sum_exp_score[ROWS]; + const U sc = scale[0]; + for (int r = 0; r < ROWS; r++) { + const device T* qp = queries + batch_idx * queries_strides[0] + + q_head_idx * queries_strides[1] + r * queries_strides[2] + + simd_lid * QK * queries_strides[3]; + for (int i = 0; i < QK; i++) { + q[r][i] = static_cast(sc) * qp[i * queries_strides[3]]; + } + for (int i = 0; i < VP; i++) { + o[r][i] = 0; + } + max_score[r] = Limits::finite_min; + sum_exp_score[r] = 0; + if (HAS_SINKS && block_idx == 0) { + max_score[r] = static_cast(sinks[q_head_idx]); + sum_exp_score[r] = 1; + } + } + + const int64_t ks = keys_strides[2]; + const int64_t vs = values_strides[2]; + const int64_t k3 = keys_strides[3]; + const int64_t v3 = values_strides[3]; + const device T* kp = keys + batch_idx * keys_strides[0] + + kv_head_idx * keys_strides[1] + block_idx * ks + simd_lid * QK * k3; + const device T* vp = values + batch_idx * values_strides[0] + + kv_head_idx * values_strides[1] + block_idx * vs + simd_lid * VP * v3; + auto mp = mask + (MASK_KIND ? (size_t(batch_idx) * ROWS * N) : 0); + + #define ROW_STEP(KR, VR, KEY) \ + for (int r = 0; r < ROWS; r++) { \ + bool use_key = true; \ + if (CAUSAL) { \ + use_key = (KEY) <= (N - ROWS + r); \ + } else if (MASK_KIND == 1) { \ + use_key = mp[r * N + (KEY)]; \ + } else if (MASK_KIND == 2) { \ + use_key = (mp[r * N + (KEY)] >= Limits::finite_min); \ + } \ + if (use_key) { \ + U score = 0; \ + for (int j = 0; j < QK; j++) { \ + score += q[r][j] * KR[j]; \ + } \ + score = simd_sum(score); \ + if (MASK_KIND == 2) { \ + score += mp[r * N + (KEY)]; \ + } \ + U new_max = max(max_score[r], score); \ + U factor = fast::exp(max_score[r] - new_max); \ + U exp_score = fast::exp(score - new_max); \ + max_score[r] = new_max; \ + sum_exp_score[r] = sum_exp_score[r] * factor + exp_score; \ + for (int j = 0; j < VP; j++) { \ + o[r][j] = o[r][j] * factor + exp_score * VR[j]; \ + } \ + } \ + } + + #define LOAD_KV(KR, VR, K3, V3) \ + for (int j = 0; j < QK; j++) { \ + KR[j] = kp[j * (K3)]; \ + } \ + for (int j = 0; j < VP; j++) { \ + VR[j] = vp[j * (V3)]; \ + } + + // Next key of the block loaded while the current one is processed. + #define PASS1_LOOP(K3, V3) \ + { \ + T ka[QK], kb[QK]; \ + T va[VP], vb[VP]; \ + int key = block_idx; \ + if (n_iter > 0) { \ + LOAD_KV(ka, va, K3, V3) \ + } \ + int it = 0; \ + for (; it + 1 < n_iter; it += 2) { \ + kp += BLOCKS * ks; \ + vp += BLOCKS * vs; \ + LOAD_KV(kb, vb, K3, V3) \ + ROW_STEP(ka, va, key) \ + key += BLOCKS; \ + if (it + 2 < n_iter) { \ + kp += BLOCKS * ks; \ + vp += BLOCKS * vs; \ + LOAD_KV(ka, va, K3, V3) \ + } \ + ROW_STEP(kb, vb, key) \ + key += BLOCKS; \ + } \ + if (it < n_iter) { \ + ROW_STEP(ka, va, key) \ + } \ + } + + const int n_iter = block_idx < N ? (N - 1 - block_idx) / BLOCKS + 1 : 0; + if (k3 == 1 && v3 == 1) { + PASS1_LOOP(1, 1) + } else { + PASS1_LOOP(k3, v3) + } + + for (int r = 0; r < ROWS; r++) { + const int o_offset = q_batch_head_idx * ROWS + r; + if (simd_lid == 0) { + sums[o_offset * BLOCKS + block_idx] = sum_exp_score[r]; + maxs[o_offset * BLOCKS + block_idx] = max_score[r]; + } + device float* op = partials + (size_t(o_offset) * BLOCKS + block_idx) * V + simd_lid * VP; + for (int j = 0; j < VP; j++) { + op[j] = o[r][j]; + } + } + + """# + static let pass2 = #""" + + constexpr int BN = 32; + constexpr int BD = 32; + constexpr int elem_per_thread = V / BD; + typedef float U; + + thread U o[elem_per_thread] = {0}; + threadgroup U outputs[BN * BD]; + + const int head_idx = threadgroup_position_in_grid.x; + const int q_seq_idx = threadgroup_position_in_grid.y; + const int simd_gid = simdgroup_index_in_threadgroup; + const int simd_lid = thread_index_in_simdgroup; + const int q_offset = head_idx * ROWS + q_seq_idx; + const device float* pp = partials + size_t(q_offset) * BLOCKS * V + simd_gid * V + + simd_lid * elem_per_thread; + const device float* sp = sums + q_offset * BLOCKS; + const device float* mp = maxs + q_offset * BLOCKS; + const int bi = head_idx / NQ; + const int hi = head_idx % NQ; + device T* op = out + ((size_t(bi) * ROWS + q_seq_idx) * NQ + hi) * V + + simd_gid * elem_per_thread; + + U sum_exp_score = 0.0; + U max_score = Limits::finite_min; + + for (int b = 0; b < BLOCKS / BN; ++b) { + max_score = max(max_score, mp[simd_lid + BN * b]); + } + max_score = simd_max(max_score); + + for (int b = 0; b < BLOCKS / BN; ++b) { + U factor = fast::exp(mp[simd_lid + BN * b] - max_score); + sum_exp_score += factor * sp[simd_lid + BN * b]; + } + sum_exp_score = simd_sum(sum_exp_score); + + for (int b = 0; b < BLOCKS / BN; ++b) { + U factor = fast::exp(mp[simd_gid] - max_score); + for (int i = 0; i < elem_per_thread; i++) { + o[i] += factor * static_cast(pp[i]); + } + mp += BN; + sp += BN; + pp += BN * V; + } + + for (int i = 0; i < elem_per_thread; i++) { + outputs[simd_lid * BD + simd_gid] = o[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + o[i] = simd_sum(outputs[simd_gid * BD + simd_lid]); + o[i] = sum_exp_score == 0 ? o[i] : (o[i] / sum_exp_score); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + if (simd_lid == 0) { + for (int i = 0; i < elem_per_thread; i++) { + op[i] = static_cast(o[i]); + } + } + + """# +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26FP32WeightedReduction.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26FP32WeightedReduction.swift new file mode 100644 index 0000000000..364531884b --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26FP32WeightedReduction.swift @@ -0,0 +1,102 @@ +// Copyright © 2026 Eigen Labs. +// Isolated, OFF-by-default native MiMo experiment. Not a losslessness claim. +import Foundation +import MLX + +public enum MiMoV26FP32WeightedReduction { + public static let envFlag = "DARKBLOOM_MIMO_FP32_WEIGHTED_REDUCE" + public static func isEnabled( + environment: [String: String] = ProcessInfo.processInfo.environment + ) -> Bool { + let value = environment[envFlag]?.trimmingCharacters(in: .whitespacesAndNewlines) + .lowercased() + return value == "1" || value == "true" || value == "on" + } +} + +public enum MiMoV26FP32WeightedReductionRoute: String, Sendable, Equatable { + case fused, disabled, unsupportedProfile, unsupportedActivation, notPrefill + case unsupportedShape, unsupportedTopK, unsupportedDType, notSorted, unsupportedStream +} + +/// Native-local graph result. Scalar route is selection evidence only, never +/// completion authority, physical residency credit or a numerical qualification. +public struct MiMoV26FP32WeightedReductionResult { + public let output: MLXArray + public let route: MiMoV26FP32WeightedReductionRoute + package init(output: MLXArray, route: MiMoV26FP32WeightedReductionRoute) { + self.output = output + self.route = route + } +} + +/// Metadata-only gate. inverseOrder must be the genuine SwitchGLU argsort +/// inverse, not a caller-provided unchecked index buffer. This internal helper +/// does not perform a synchronizing index readback or create another projection. +func mimoV26FP32WeightedUnsortRefusal( + sortedOutputs: MLXArray, inverseOrder: MLXArray, weights: MLXArray +) -> MiMoV26FP32WeightedReductionRoute? { + guard sortedOutputs.ndim == 2, weights.ndim == 3, inverseOrder.ndim == 1, + sortedOutputs.dim(1) > 0, sortedOutputs.dim(1).isMultiple(of: 64), + weights.dim(0) > 0, weights.dim(1) > 1, + sortedOutputs.dim(0) == weights.size, inverseOrder.size == weights.size, + sortedOutputs.size <= Int(Int32.max), weights.size <= Int(Int32.max) + else { + return .unsupportedShape + } + guard weights.dim(2) == 6 || weights.dim(2) == 8 else { return .unsupportedTopK } + guard sortedOutputs.dtype == .bfloat16 || sortedOutputs.dtype == .float16, + weights.dtype == .float32, inverseOrder.dtype == .uint32 + else { return .unsupportedDType } + guard weights.size >= 64 else { return .notSorted } + #if os(macOS) || os(iOS) || os(tvOS) || os(visionOS) + // Initial profile deliberately excludes CPU and private/nondefault streams. + guard StreamOrDevice.default.stream == MLX.Stream.gpu else { return .unsupportedStream } + return nil + #else + return .unsupportedStream + #endif +} + +private let mimoFP32WeightedUnsortKernel = MLXFast.metalKernel( + name: "mimo_v26_fp32_weighted_unsort", + inputNames: ["sorted_outputs", "inverse_order", "weights"], + outputNames: ["output"], + source: """ + #pragma clang fp contract(off) + uint feature = thread_position_in_grid.x; + uint token = thread_position_in_grid.y; + const uint base = token * (uint)K; + float accumulator = 0.0f; + for (uint slot = 0; slot < (uint)K; ++slot) { + const uint row = inverse_order[base + slot]; + const float product = float(sorted_outputs[row * (uint)D + feature]) * weights[base + slot]; + // Keep both the product and reduction FP32. The extra +0 mirrors + // the pinned small-column reducer's per-slot initial accumulation. + const float partial = product + 0.0f; + accumulator = partial + accumulator; + } + output[token * (uint)D + feature] = accumulator; + """, + ensureRowContiguous: true +) + +/// Called only after the gate and the real sort. FP32 output leaves the original +/// MiMo final cast at its original caller. No BF16 per-product/accumulator cast. +/// This is a candidate: compiler contraction, dispatch/reduction order and final +/// bytes still require exact comparison with the original unfused expression. +func mimoV26FP32WeightedUnsort( + sortedOutputs: MLXArray, inverseOrder: MLXArray, weights: MLXArray +) -> MLXArray { + precondition( + mimoV26FP32WeightedUnsortRefusal( + sortedOutputs: sortedOutputs, inverseOrder: inverseOrder, weights: weights) == nil) + let hidden = sortedOutputs.dim(1) + let topK = weights.dim(2) + return mimoFP32WeightedUnsortKernel( + [sortedOutputs, inverseOrder, weights], template: [("K", topK), ("D", hidden)], + grid: (hidden, weights.size / topK, 1), threadGroup: (64, 1, 1), + outputShapes: [[weights.dim(0), weights.dim(1), hidden]], outputDTypes: [.float32], + stream: .gpu + )[0] +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXAttention.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXAttention.swift new file mode 100644 index 0000000000..eeb7f369b3 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXAttention.swift @@ -0,0 +1,156 @@ +// Copyright © 2026 Eigen Labs. +// SPDX-License-Identifier: Apache-2.0 +// Swift port of oMLX #3994, head 1c487861d1c1d4c82a2b2920dd69c064eec85e18. + +import Foundation +import MLX +import MLXFast + +/// Narrow MiMo prefill route. Results preserve the input/output dtype and +/// depend on the caller's existing step roots; this helper never evaluates. +public enum MiMoV26NAXAttention { + // Default policy permits the existing native-rounded route; actual + // geometry/device/dtype gates below remain authoritative. Explicit 0 rolls back. + static let requested = MiMoV26PrefillPolicy.isEnabled( + ProcessInfo.processInfo.environment[MiMoV26PrefillPolicy.attentionEnvironmentKey]) + + private static let lock = NSLock() + nonisolated(unsafe) private static var encodings = 0 + + /// Graph encodings only, not a claim of completed kernel execution. + public static func encodedCalls() -> Int { + lock.lock() + defer { lock.unlock() } + return encodings + } + + struct Plan { + let batch: Int + let heads: Int + let kvHeads: Int + let queries: Int + let keys: Int + let causal: Bool + let mask: MLXArray? + let sinks: MLXArray? + } + + static func makePlan( + queries q: MLXArray, keys k: MLXArray, values v: MLXArray, + scale: Float, mask: MLXFast.ScaledDotProductAttentionMaskMode, + sinks: MLXArray?, production: Bool + ) -> Plan? { + guard q.ndim == 4, k.ndim == 4, v.ndim == 4, + q.dtype == .bfloat16 || q.dtype == .float16, + k.dtype == q.dtype, v.dtype == q.dtype, + q.dim(3) == 192, k.dim(3) == 192, v.dim(3) == 128, + q.dim(0) > 0, q.dim(0) <= 64, q.dim(0) == k.dim(0), + Array(v.shape.prefix(3)) == Array(k.shape.prefix(3)), + q.dim(1) > 0, q.dim(1) <= 64, k.dim(1) > 0, + q.dim(1) % k.dim(1) == 0, + q.dim(2) > 8, k.dim(2) >= q.dim(2), k.dim(2) <= 1_048_576, + scale.isFinite, scale > 0 + else { return nil } + if production && (q.dim(1) != 64 || ![4, 8].contains(k.dim(1))) { return nil } + if let sinks { + guard sinks.shape == [q.dim(1)], sinks.dtype == q.dtype else { return nil } + } + let causal: Bool + let arrayMask: MLXArray? + switch mask { + case .none: + causal = false + arrayMask = nil + case .causal: + causal = true + arrayMask = nil + case .array(let array): + guard array.dtype == .bool, array.ndim >= 1, array.ndim <= 4 else { return nil } + let padded = Array(repeating: 1, count: 4 - array.ndim) + array.shape + let target = [q.dim(0), q.dim(1), q.dim(2), k.dim(2)] + guard zip(padded, target).allSatisfy({ $0.0 == 1 || $0.0 == $0.1 }) else { return nil } + causal = false + arrayMask = array + case .arrays: + return nil + } + return Plan( + batch: q.dim(0), heads: q.dim(1), kvHeads: k.dim(1), + queries: q.dim(2), keys: k.dim(2), causal: causal, + mask: arrayMask, sinks: sinks) + } + + /// Called only by ordinary MiMo attention and MiMo-owned contiguous caches. + /// Span overlays, softcaps, serialized MTP and <=8-row calls stay outside. + public static func tryAttention( + queries: MLXArray, keys: MLXArray, values: MLXArray, + scale: Float, mask: MLXFast.ScaledDotProductAttentionMaskMode, + sinks: MLXArray? + ) -> MLXArray? { + guard requested, + let plan = makePlan( + queries: queries, keys: keys, values: values, + scale: scale, mask: mask, sinks: sinks, production: true) + else { return nil } + let stream = StreamOrDevice.default + guard MiMoV26NAXGatherQMM.gpuStream(stream), + MiMoV26NAXGatherQMM.naxAvailable + else { return nil } + let result = launch( + queries: queries, keys: keys, values: values, + scale: scale, plan: plan, stream: stream) + lock.lock() + encodings += 1 + lock.unlock() + return result + } + + private static let kernel = MLXFast.metalKernel( + name: "mimo_v26_nax_attention_192_128", + inputNames: ["q", "k", "v", "mask", "sinks", "params"], + outputNames: ["out"], + source: MiMoV26NAXAttentionMetalSources.source, + header: MiMoV26NAXMetalSources.mlxHeader + "\n" + + MiMoV26NAXAttentionMetalSources.header + "\n", + ensureRowContiguous: false) + + /// Internal numerical-oracle seam. The caller owns all execution and errors. + static func launch( + queries: MLXArray, keys: MLXArray, values: MLXArray, + scale: Float, plan: Plan, stream: StreamOrDevice = .default + ) -> MLXArray { + let nq = (plan.queries + 63) / 64 + let nk = (plan.keys + 31) / 32 + // Matches the 56-byte C struct: six int32, float32, seven int32. + let words: [Int32] = [ + Int32(plan.batch), Int32(plan.heads), 192, Int32(plan.queries), + Int32(plan.keys), Int32(plan.heads / plan.kvHeads), + Int32(bitPattern: scale.bitPattern), Int32(nq), Int32(nk), + Int32(plan.queries / 64), Int32(plan.keys / 32), + Int32(plan.queries % 64), Int32(plan.keys % 32), + Int32(plan.keys - plan.queries), + ] + let mask = + plan.mask.map { + broadcast($0, to: [plan.batch, plan.heads, plan.queries, plan.keys]) + } ?? MLXArray.zeros([1], dtype: .bool) + // Reading sinks[head] requires contiguous storage; values are not cast. + let sinks = + plan.sinks.map { contiguous($0, stream: stream) } + ?? MLXArray.zeros([1], dtype: queries.dtype) + // Match fast.cpp: native-dtype scale constant and rounded scaled Q. + let scaledQueries = queries * MLXArray(scale).asType(queries.dtype) + let outputs = kernel( + [scaledQueries, keys, values, mask, sinks, MLXArray(words)], + template: [ + ("T", queries.dtype), ("ALIGN_Q", plan.queries % 64 == 0), + ("ALIGN_K", plan.keys % 32 == 0), ("HAS_MASK", plan.mask != nil), + ("DO_CAUSAL", plan.causal), ("HAS_SINKS", plan.sinks != nil), + ], + grid: (nq * 128, plan.heads, plan.batch), threadGroup: (128, 1, 1), + outputShapes: [[plan.batch, plan.queries, plan.heads, 128]], + outputDTypes: [queries.dtype], stream: stream) + precondition(outputs.count == 1) + return outputs[0].transposed(0, 2, 1, 3) + } +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXAttentionKeyRanges.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXAttentionKeyRanges.swift new file mode 100644 index 0000000000..b626d45c95 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXAttentionKeyRanges.swift @@ -0,0 +1,502 @@ +// Copyright © 2026 Eigen Labs. +// SPDX-License-Identifier: Apache-2.0 +// Ordered ranges adapted from oMLX #4032 @12e5084f8cf888bb6e846147929419f044802343. +// Modified: three native-rounded score phases, no online softmax or head split. + +import Foundation +import MLX +import MLXFast + +/// Ordered component encoder plus the genuine grouped native prefill entry. +/// The legacy single-call byte limit remains a component bound, NEVER admission. +/// Managed grouping requires MiMoV26NAXKeyRangeNative's real phase/step owner. +enum MiMoV26NAXAttentionKeyRanges { + struct Schedule: Equatable { + let batch: Int + let heads: Int + let queries: Int + let keys: Int + let edges: [Int] + let stateElements: Int + let stateBufferBytes: Int + let fullStateBuffers: Int + let dispatches: Int + /// All distinct array payloads, retaining every lazy dispatch result. + /// Excludes caller-owned inputs, allocator padding and compiler/driver + /// workspace; this is not measured peak or process admission authority. + let arrayPayloadBytes: Int + } + + struct Encoding { + let output: MLXArray + /// Retain through actual completion; on an uncertain drain the native + /// fault owner must retain these and the corresponding charge. + let retainedArrays: [MLXArray] + let schedule: Schedule + } + + // Match Python round-to-even for the reference's balanced ~8192-key + // dispatch policy. All positions are absolute 32-key block indices. + static func balancedEdges( + batch: Int, heads: Int, queries: Int, keys: Int, + preferredKeys: Int = 8192, + minimumThreadgroups: Int = 512 + ) -> [Int]? { + guard validDimensions(batch, heads, queries, keys), + preferredKeys >= 0, minimumThreadgroups >= 0 + else { return nil } + let nq = (queries + 63) / 64 + let nk = (keys + 31) / 32 + guard preferredKeys > 0, batch * heads * nq >= minimumThreadgroups else { + return [0, nk] + } + let rounded = (Double(nk * 32) / Double(preferredKeys)).rounded(.toNearestOrEven) + let count = max(1, min(nk, Int(rounded))) + // Bound host graph size; unsupported fragmentation keeps old fallback. + guard count <= 128 else { return nil } + return (0 ... count).map { ($0 * nk) / count } + } + + private static func validDimensions(_ b: Int, _ h: Int, _ q: Int, _ k: Int) -> Bool { + b > 0 && b <= 64 && h > 0 && h <= 64 && q > 8 && q <= k && k <= 1_048_576 + } + + /// No arrays/strides/evaluation needed. Each of three passes has R + /// dispatches; 3R-1 full states stay live until the caller's real fence. + static func makeSchedule( + batch: Int, heads: Int, queries: Int, keys: Int, + edges: [Int], maximumPayloadBytes: Int + ) -> Schedule? { + guard validDimensions(batch, heads, queries, keys), maximumPayloadBytes > 0, + edges.count >= 2, edges.count <= 129, edges.first == 0, + edges.last == (keys + 31) / 32, + zip(edges, edges.dropFirst()).allSatisfy({ $0.0 < $0.1 }) + else { return nil } + func product(_ values: [Int]) -> Int? { + var result = 1 + for value in values { + let next = result.multipliedReportingOverflow(by: value) + guard !next.overflow else { return nil } + result = next.partialValue + } + return result + } + func sum(_ values: [Int]) -> Int? { + var result = 0 + for value in values { + let next = result.addingReportingOverflow(value) + guard !next.overflow else { return nil } + result = next.partialValue + } + return result + } + let dispatches = 3 * (edges.count - 1) + let fullStates = dispatches - 1 + guard let stateElements = product([batch, heads, (queries + 63) / 64, 64, 130]), + stateElements <= Int(Int32.max), // Flattened custom-output shape ABI. + let stateBytes = product([stateElements, 4]), + let allStates = product([stateBytes, fullStates]), + let scaledQ = product([batch, heads, queries, 192, 2]), + let finalOutput = product([batch, heads, queries, 128, 2]), + let payload = sum([ + allStates, scaledQ, finalOutput, + 2 * fullStates, // Unused native-dtype out scalar per non-final dispatch. + 8, // Initial state + final unused state scalar (float32). + 64 * dispatches, // Distinct 16-word scalar parameter arrays. + 2 * heads, // Worst-case contiguous sinks (or smaller dummy). + 1, // Missing boolean-mask placeholder (broadcast masks are views). + 6, // float scale scalar + native-dtype cast. + ]), + payload <= maximumPayloadBytes + else { return nil } + return Schedule( + batch: batch, heads: heads, queries: queries, keys: keys, + edges: edges, stateElements: stateElements, stateBufferBytes: stateBytes, + fullStateBuffers: fullStates, dispatches: dispatches, arrayPayloadBytes: payload) + } + + private static let kernel = MLXFast.metalKernel( + name: "mimo_v26_nax_attention_key_ranges_192_128", + inputNames: ["q", "k", "v", "mask", "sinks", "state", "params"], + outputNames: ["out", "state_out"], + source: #""" + omlx_nax::attention_nax_bdv_impl< + T, 64, 32, 192, 128, 4, 1, + ALIGN_Q, ALIGN_K, HAS_MASK, DO_CAUSAL, HAS_SINKS, + true, FIRST_RANGE, LAST_RANGE, SCORE_PASS, bool, float>( + q, k, v, out, + reinterpret_cast(params), + q_strides, k_strides, v_strides, mask_strides, + mask, sinks, state, state_out, params[14], params[15], + simdgroup_index_in_threadgroup, + threadgroup_position_in_grid); + """#, + header: MiMoV26NAXMetalSources.mlxHeader + "\n" + + MiMoV26NAXAttentionMetalSources.header + "\n", + ensureRowContiguous: false) + + /// Never evaluates/synchronizes or changes stream/device. Not a production + /// opt-in API: caller owns exclusive native execution and real completion. + /// Returns nil before custom encoding for invalid geometry, CPU/non-NAX, + /// schedule mismatch or a refused bounded payload. + static func launch( + queries: MLXArray, keys: MLXArray, values: MLXArray, + scale: Float, mask: MLXFast.ScaledDotProductAttentionMaskMode, + sinks: MLXArray?, schedule: Schedule, + maximumPayloadBytes: Int, stream: StreamOrDevice = .default, + retain: ([MLXArray]) -> Void + ) -> Encoding? { + guard MiMoV26NAXGatherQMM.gpuStream(stream), MiMoV26NAXGatherQMM.naxAvailable, + let plan = MiMoV26NAXAttention.makePlan( + queries: queries, keys: keys, values: values, + scale: scale, mask: mask, sinks: sinks, production: false), + let checked = makeSchedule( + batch: plan.batch, heads: plan.heads, + queries: plan.queries, keys: plan.keys, edges: schedule.edges, + maximumPayloadBytes: maximumPayloadBytes), + checked == schedule + else { return nil } + let nq = (plan.queries + 63) / 64 + let nk = (plan.keys + 31) / 32 + let mask = + plan.mask.map { + broadcast($0, to: [plan.batch, plan.heads, plan.queries, plan.keys]) + } ?? MLXArray.zeros([1], dtype: .bool) + let sinks = + plan.sinks.map { contiguous($0, stream: stream) } + ?? MLXArray.zeros([1], dtype: queries.dtype) + // Same native-dtype scale and multiplication as the original launcher. + let scaledQueries = queries * MLXArray(scale).asType(queries.dtype) + var state = MLXArray.zeros([1], dtype: .float32) + var roots = [scaledQueries, mask, sinks, state] + retain(roots) + var output: MLXArray? + // The state edge enforces complete phase 0 -> phase 1 -> phase 2. + // No max, exponential, sum or PV operation is added at a boundary. + for pass in 0 ..< 3 { + for index in 0 ..< (schedule.edges.count - 1) { + let first = index == 0 + let last = index == schedule.edges.count - 2 + let final = pass == 2 && last + let words: [Int32] = [ + Int32(plan.batch), Int32(plan.heads), 192, Int32(plan.queries), + Int32(plan.keys), Int32(plan.heads / plan.kvHeads), + Int32(bitPattern: scale.bitPattern), Int32(nq), Int32(nk), + Int32(plan.queries / 64), Int32(plan.keys / 32), + Int32(plan.queries % 64), Int32(plan.keys % 32), + Int32(plan.keys - plan.queries), + Int32(schedule.edges[index]), Int32(schedule.edges[index + 1]), + ] + let params = MLXArray(words) + retain([params]) + let outputs = kernel( + [scaledQueries, keys, values, mask, sinks, state, params], + template: [ + ("T", queries.dtype), ("ALIGN_Q", plan.queries % 64 == 0), + ("ALIGN_K", plan.keys % 32 == 0), ("HAS_MASK", plan.mask != nil), + ("DO_CAUSAL", plan.causal), ("HAS_SINKS", plan.sinks != nil), + ("FIRST_RANGE", first), ("LAST_RANGE", last), ("SCORE_PASS", pass), + ], + grid: (nq * 128, plan.heads, plan.batch), threadGroup: (128, 1, 1), + outputShapes: [ + final ? [plan.batch, plan.queries, plan.heads, 128] : [1], + final ? [1] : [schedule.stateElements], + ], + outputDTypes: [queries.dtype, .float32], stream: stream) + precondition(outputs.count == 2) + retain(outputs) + roots.append(params) + roots.append(contentsOf: outputs) + state = outputs[1] + if final { output = outputs[0].transposed(0, 2, 1, 3) } + } + } + guard let output else { preconditionFailure("validated nonempty range schedule") } + return Encoding(output: output, retainedArrays: roots, schedule: schedule) + } +} + +// MARK: Native grouped descriptors (shared score body, independent state) +extension MiMoV26NAXAttentionKeyRanges { + struct GroupedSchedule { + let descriptors: [MiMoV26BlockBatchAttention.Descriptor] + let schedules: [Schedule] + let stateOffsets: [Int] + let stateElements: Int + let queryStart: Int + let queryCount: Int + var dispatches: Int { schedules[0].dispatches } + var fullStateBuffers: Int { dispatches - 1 } + } + + /// Exactly the reference rounding rule, before allocating an edge table. + /// Group eligibility below supplies the real512-threadgroup geometry. + private static func rangeCount(_ keys: Int) -> Int? { + guard keys > 0, keys <= 1_048_576 else { return nil } + let blocks = (keys + 31) / 32 + let rounded = (Double(blocks * 32) / 8192).rounded(.toNearestOrEven) + let count = max(1, min(blocks, Int(rounded))) + return count <= 128 ? count : nil + } + + private static func groupedCount( + _ group: [MiMoV26BlockBatchAttention.Descriptor], + heads: Int + ) -> Int? { + guard group.count == 4, heads == 64, let first = group.first, + group.allSatisfy({ $0.queryCount == 128 && $0.sameVariant(first) }), + heads * group.reduce(0, { $0 + ($1.queryCount + 63) / 64 }) >= 512, + let count = rangeCount(first.keyCount), count >= 2, + group.allSatisfy({ rangeCount($0.keyCount) == count }) + else { return nil } + return count + } + + private static func validGroupedPlan(_ plan: MiMoV26BlockBatchAttention.Plan) -> Bool { + guard (129 ... 8192).contains(plan.queryCount), plan.keyCount >= plan.queryCount, + plan.keyCount <= 1_048_576, plan.heads == 64, [4, 8].contains(plan.kvHeads), + plan.window == nil || plan.window == 128, !plan.groups.isEmpty, + plan.groups.count <= (plan.queryCount + 127) / 128 + else { return false } + let history = plan.keyCount - plan.queryCount + var cursor = 0 + for group in plan.groups { + guard (1 ... 4).contains(group.count), let first = group.first else { return false } + for d in group { + guard (9 ... 128).contains(d.queryCount), d.queryStart == cursor, + d.queryCount <= plan.queryCount - cursor, d.sameVariant(first) + else { return false } + let bounds = CBv2AttentionV1.queryBlockBounds( + historyCount: history, + offset: cursor, count: d.queryCount, window: plan.window) + guard d.keyStart == bounds.visibleStart, + d.keyCount == bounds.visibleEnd - bounds.visibleStart, + d.causal == (plan.window == nil || d.keyCount <= plan.window!) + else { return false } + cursor += d.queryCount + } + } + return cursor == plan.queryCount + } + + /// Scalar, checked projection over the existing block descriptor arrays. + /// It allocates no extra MLX arrays and no range tables before real reserve. + /// Every actual group buffer has its own allocator bound and multiplicity. + static func projectedGroupedBytes( + plan: MiMoV26BlockBatchAttention.Plan, + maximumBufferBytes: Int, upperBound: (Int) -> Int? + ) -> Int? { + guard maximumBufferBytes > 0, validGroupedPlan(plan) else { return nil } + func add(_ a: Int, _ b: Int) -> Int? { + let x = a.addingReportingOverflow(b) + return a >= 0 && b >= 0 && !x.overflow ? x.partialValue : nil + } + func mul(_ a: Int, _ b: Int) -> Int? { + let x = a.multipliedReportingOverflow(by: b) + return a >= 0 && b >= 0 && !x.overflow ? x.partialValue : nil + } + var total = 0 + var accepted = 0 + func buffer(_ logical: Int, _ copies: Int = 1) -> Bool { + guard logical > 0, copies > 0, let bound = upperBound(logical), + bound >= logical, bound <= maximumBufferBytes, + let all = mul(bound, copies), let next = add(total, all) + else { return false } + total = next + return true + } + for group in plan.groups { + guard let ranges = groupedCount(group, heads: plan.heads) else { continue } + // Actual grid z is four independent original q128 descriptors. + // Each carries its own K prefix; there is no full-key hoist. + let queryCount = group.reduce(0) { $0 + $1.queryCount } + let stateElements = group.count * plan.heads * 2 * 64 * 130 + guard stateElements <= Int(Int32.max), let stateBytes = mul(stateElements, 4) else { + return nil + } + let dispatches = 3 * ranges + let fullStates = dispatches - 1 + let scaledQ = queryCount * plan.heads * 192 * 2 + let output = queryCount * plan.heads * 128 * 2 + guard buffer(stateBytes, fullStates), + buffer(scaledQ), buffer(output), + buffer(group.count * 2, fullStates), // separate unused out slot/descriptor + buffer(group.count * 4, 2), // initial/final unused state slots + buffer(group.count * 20 * 4, dispatches), + buffer(plan.heads * 2), buffer(1), // sinks/absent-mask placeholder + buffer(4), buffer(2) + else { return nil } // actual native scale inputs + if !group[0].causal { + // The real MiMo128 window has one range and declines above. + // Keep a conservative exact packed-mask envelope for the helper. + var maskBytes = 0 + for d in group { + guard let bytes = mul(d.queryCount, d.keyCount), + let next = add(maskBytes, bytes), buffer(bytes, 4) + else { return nil } + maskBytes = next + } + guard buffer(maskBytes) else { return nil } + } + // Bounded host/control storage: arrays/primitive descriptors, + // all parameter words and separate edge/state-offset tables. + // Conservative source allowance, not measured Swift/driver heap. + guard let nodes = mul(dispatches * 3 + 24, 1024), + let edges = mul(group.count * (ranges + 1), 16), + let metadata = add(nodes, edges), + let host = add(metadata, 65_536), + let next = add(total, host) + else { return nil } + total = next + accepted += 1 + } + return accepted > 0 ? total : nil + } + + /// Called only AFTER the exact whole-layer projection has been admitted. + static func groupedSchedules(plan: MiMoV26BlockBatchAttention.Plan) + -> [Int: GroupedSchedule]? + { + guard validGroupedPlan(plan) else { return nil } + var result: [Int: GroupedSchedule] = [:] + for (index, group) in plan.groups.enumerated() { + guard groupedCount(group, heads: plan.heads) != nil else { continue } + var schedules: [Schedule] = [] + var offsets: [Int] = [] + var elements = 0 + for descriptor in group { + // B here is the REAL dispatch's independent descriptor count, + // not a fictional increase to one query block's occupancy. + guard + let edges = balancedEdges( + batch: group.count, heads: plan.heads, + queries: descriptor.queryCount, keys: descriptor.keyCount), + let item = makeSchedule( + batch: 1, heads: plan.heads, + queries: descriptor.queryCount, keys: descriptor.keyCount, + edges: edges, maximumPayloadBytes: Int.max) + else { return nil } + offsets.append(elements) + let next = elements.addingReportingOverflow(item.stateElements) + guard !next.overflow, next.partialValue <= Int(Int32.max) else { return nil } + elements = next.partialValue + schedules.append(item) + } + guard let first = group.first, let last = group.last else { return nil } + result[index] = .init( + descriptors: group, schedules: schedules, stateOffsets: offsets, + stateElements: elements, queryStart: first.queryStart, + queryCount: last.queryStart + last.queryCount - first.queryStart) + } + return result + } + + private static let groupedKernel = MLXFast.metalKernel( + name: "mimo_v26_native_grouped_key_ranges_192_128", + inputNames: ["q", "k", "v", "mask", "sinks", "state", "params"], + outputNames: ["out", "state_out"], + source: MiMoV26NAXKeyRangeGroupedMetalSources.source, + header: MiMoV26NAXMetalSources.mlxHeader + "\n" + + MiMoV26NAXAttentionMetalSources.header + "\n", + ensureRowContiguous: false) + + private static let groupedCounterLock = NSLock() + nonisolated(unsafe) private static var groupedEncodings = 0 + static func encodedGroupedDispatches() -> Int { + groupedCounterLock.withLock { groupedEncodings } + } + + /// No byte-limit authority is accepted here. The exact admitted layer + /// owner retains every returned array through its actual completion. + static func launchGrouped( + queries: MLXArray, keys: MLXArray, values: MLXArray, + scale: Float, sinks: MLXArray?, window: Int?, + schedule: GroupedSchedule, layer: MiMoV26NAXKeyRangeLayer, + stream: StreamOrDevice = .default + ) -> MLXArray { + let descriptors = schedule.descriptors + let first = descriptors[0] + let heads = schedule.schedules[0].heads + let scaleInput = MLXArray(scale) + let nativeScale = scaleInput.asType(queries.dtype) + let scaled = + queries[ + 0..., 0..., schedule.queryStart ..< (schedule.queryStart + schedule.queryCount), + 0...] + * nativeScale + let nativeSinks = + sinks.map { contiguous($0, stream: stream) } + ?? MLXArray.zeros([1], dtype: queries.dtype) + var masks: [MLXArray] = [] + var maskOffsets: [Int] = [] + var maskElements = 0 + for d in descriptors { + maskOffsets.append(maskElements) + if case .array(let mask) = CBv2AttentionV1.maskMode( + L: d.queryCount, kL: d.keyCount, window: window) + { + masks.append(mask.reshaped([-1])) + maskElements += d.queryCount * d.keyCount + } + } + let mask = + masks.isEmpty + ? MLXArray.zeros([1], dtype: .bool) + : (masks.count == 1 ? masks[0] : concatenated(masks)) + var state = MLXArray.zeros([descriptors.count], dtype: .float32) + layer.retain([scaleInput, nativeScale, scaled, nativeSinks, mask, state] + masks) + // Borrowed K/V remain with the existing native request/step and + // kernel dependency graph. Do not retain extra slice descriptors here: + // extending them past normal evaluation can force full-KV COW on the + // next append. This reservation prices newly emitted scratch only. + var result: MLXArray? + let ranges = schedule.schedules[0].edges.count - 1 + for pass in 0 ..< 3 { + for range in 0 ..< ranges { + let final = pass == 2 && range == ranges - 1 + var words: [Int32] = [] + words.reserveCapacity(descriptors.count * 20) + for (block, d) in descriptors.enumerated() { + let item = schedule.schedules[block] + words += [ + 1, Int32(heads), 192, Int32(d.queryCount), Int32(d.keyCount), + Int32(heads / keys.dim(1)), Int32(bitPattern: scale.bitPattern), + Int32((d.queryCount + 63) / 64), Int32((d.keyCount + 31) / 32), + Int32(d.queryCount / 64), Int32(d.keyCount / 32), + Int32(d.queryCount % 64), Int32(d.keyCount % 32), + Int32(d.keyCount - d.queryCount), + Int32(d.queryStart - schedule.queryStart), Int32(d.keyStart), + Int32(maskOffsets[block]), Int32(schedule.stateOffsets[block]), + Int32(item.edges[range]), Int32(item.edges[range + 1]), + ] + } + let params = MLXArray(words) + layer.retain([params]) + let output = groupedKernel( + [scaled, keys, values, mask, nativeSinks, state, params], + template: [ + ("T", queries.dtype), ("ALIGN_Q", first.alignedQuery), + ("ALIGN_K", first.alignedKey), ("HAS_MASK", !first.causal), + ("DO_CAUSAL", first.causal), ("HAS_SINKS", sinks != nil), + ("FIRST_RANGE", range == 0), ("LAST_RANGE", range == ranges - 1), + ("SCORE_PASS", pass), + ], + grid: (2 * 128, heads, descriptors.count), threadGroup: (128, 1, 1), + outputShapes: [ + final ? [1, schedule.queryCount, heads, 128] : [descriptors.count], + final ? [descriptors.count] : [schedule.stateElements], + ], + outputDTypes: [queries.dtype, .float32], stream: stream) + layer.retain(output) + precondition(output.count == 2) + state = output[1] + if final { + result = output[0].transposed(0, 2, 1, 3) + layer.retain([result!]) + } + groupedCounterLock.withLock { groupedEncodings += 1 } + } + } + return result! + } +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXAttentionMetalSources.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXAttentionMetalSources.swift new file mode 100644 index 0000000000..fd26ba6e45 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXAttentionMetalSources.swift @@ -0,0 +1,627 @@ +// SPDX-License-Identifier: Apache-2.0 AND MIT +// Copyright 2025 oMLX contributors; Copyright © 2024-2025 Apple Inc. +// Adapted from PR #3994 head 1c487861d1c1d4c82a2b2920dd69c064eec85e18. +// Modified: native-rounded, three-pass baseline arithmetic; runtime inner-head strides. +// Ordered phase/range FP32 save/restore adapted from #4032 +// 12e5084f8cf888bb6e846147929419f044802343; no online-softmax/head split. +// Apple/MIT primitive header and license: MiMoV26NAXMetalSources.swift. +// oMLX license: docs/mimo-v26/LICENSE-OMLX. + +enum MiMoV26NAXAttentionMetalSources { + static let header = #""" + using namespace mlx::steel; + #define OMLX_NAX_UNROLL STEEL_PRAGMA_UNROLL + namespace omlx_nax { + + // Scalar parameters of one attention call (MLX's AttnParams without the + // strides, which the kernel reads from the inputs' own stride vectors). + struct AttnParams { + int B; + int H; + int D; + int qL; + int kL; + int gqa_factor; + float scale; + int NQ; + int NK; + int NQ_aligned; + int NK_aligned; + int qL_rem; + int kL_rem; + int qL_off; + }; + + struct MaxOp { + template + METAL_FUNC static constexpr T apply(T x, T y) { + return metal::max(x, y); + } + }; + + struct SumOp { + template + METAL_FUNC static constexpr T apply(T x, T y) { + return x + y; + } + }; + + struct MulOp { + template + METAL_FUNC static constexpr T apply(T x, T y) { + return x * y; + } + }; + + struct ExpSubOp { + template + METAL_FUNC static constexpr T apply(T x, T y) { + return fast::exp(x - y); + } + }; + + + // Unlike the Python wrapper, this accepts runtime inner-dimension strides. + // MLX lazy-array strides must not be read on the host before evaluation. + template + METAL_FUNC void load_head_rows( + thread Tile& tile, const device T* src, int row_stride, + int64_t head_stride, short live_rows) { + if (head_stride == 1) { + if (live_rows >= Tile::kRows) { + tile.load(src, row_stride); + } else { + tile.load_rows(src, row_stride, live_rows); + } + return; + } + STEEL_PRAGMA_UNROLL + for (short i = 0; i < Tile::kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < Tile::kTileCols; ++j) { + using Frag = typename Tile::NAXFrag_t; + Frag::load_rows( + tile.frag_at(i, j), src, row_stride, head_stride, + live_rows, i * Tile::kFragRows, j * Tile::kFragCols); + } + } + } + + // MLX's attention_nax with a value head dim BDV <= BD. Only the parameter + // plumbing differs: strides come from the inputs, the output is written as + // [B, qL, H, BDV] rows (MLX's SDPA output layout), function constants are + // template arguments, and the mask column stride is honoured. + template < + typename T, + int BQ, + int BK, + int BD, + int BDV, + int WM, + int WN, + bool align_Q, + bool align_K, + bool has_mask, + bool do_causal, + bool has_sinks, + bool KEY_RANGES, + bool FIRST_RANGE, + bool LAST_RANGE, + short SCORE_PASS, + typename MaskType, + typename AccumType, + typename StridePtr, + typename MaskPtr, + typename SinkPtr, + typename StatePtr> + METAL_FUNC void attention_nax_bdv_impl( + const device T* Q, + const device T* K, + const device T* V, + device T* O, + const device AttnParams* params, + StridePtr q_str, + StridePtr k_str, + StridePtr v_str, + StridePtr m_str, + MaskPtr mask, + SinkPtr sinks, + StatePtr Sin, + device float* Sout, + int range_begin, + int range_end, + uint simd_group_id, + uint3 tid) { + ulong3 tidl{tid.x, tid.y, tid.z}; + + const int64_t Q_strides[3] = {q_str[0], q_str[1], q_str[2]}; + const int64_t K_strides[3] = {k_str[0], k_str[1], k_str[2]}; + const int64_t V_strides[3] = {v_str[0], v_str[1], v_str[2]}; + const int64_t O_strides[3] = { + int64_t(params->qL) * params->H * BDV, BDV, int64_t(params->H) * BDV}; + + Q += tidl.z * Q_strides[0] + // Batch + tidl.y * Q_strides[1] + // Head + tidl.x * BQ * Q_strides[2]; // Sequence + + ulong kv_head_idx = int(tid.y) / params->gqa_factor; + K += tidl.z * K_strides[0] + // Batch + kv_head_idx * K_strides[1]; // Head + + V += tidl.z * V_strides[0] + // Batch + kv_head_idx * V_strides[1]; // Head + + if constexpr (!KEY_RANGES || (SCORE_PASS == 2 && LAST_RANGE)) { + O += tidl.z * O_strides[0] + // Batch + tidl.y * O_strides[1] + // Head + tidl.x * BQ * O_strides[2]; // Sequence + } + + if (has_mask) { + mask += tidl.z * m_str[0] + // Batch + tidl.y * m_str[1]; // Head + } + + + // Prepare MMA tiles + constexpr short kU = 16; + + constexpr int kNWarps = WM * WN; + static_assert( + BQ >= (kNWarps * kU) && BQ % (kNWarps * kU) == 0, + "Each simdgroup must host atleast 1 simdgroup matrix along Q sequence."); + + // Q seq frags per warp + constexpr int TQ = BQ / (kNWarps * kU); + // HeadDim frags (all warps load the same frags) + constexpr int TD = BD / kU; + // Value head dim frags + constexpr int TDV = BDV / kU; + // KV seq frags per warp + constexpr short TK = BK / kU; + + static_assert(TQ == 1, "Check TQ"); + static_assert(BDV % (2 * kU) == 0, "BDV must be a multiple of 32"); + using otile_t = NAXTile; + otile_t Otile; + + Otile.clear(); + + // Prepare mma tile offsets + const short tm = kU * TQ * simd_group_id; + Q += tm * int(Q_strides[2]); + + const short2 simd_coord = otile_t::NAXFrag_t::get_coord(); + const short sm = simd_coord.y; + const short sn = simd_coord.x; + + // Init row reduction variables + constexpr short kRowsPT = otile_t::kRowsPerThread; + + metal::vec max_score; + metal::vec sum_score{0}; + + // Init to -Inf + OMLX_NAX_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + max_score[i] = Limits::finite_min; + } + + if (has_sinks) { + OMLX_NAX_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + max_score[i] = static_cast(sinks[tidl.y]); + } + } + + // Every padded row has its own full FP32 state. Loading/storing performs + // no arithmetic or native-dtype conversion, including phase transitions. + constexpr int kSW = BDV + 2; + const int64_t srow0 = + (int64_t(tid.z) * params->H + tid.y) * (int64_t(params->NQ) * BQ) + + int64_t(tid.x) * BQ + tm; + if constexpr (KEY_RANGES && !(SCORE_PASS == 0 && FIRST_RANGE)) { + Otile.load(Sin + srow0 * kSW, kSW); + OMLX_NAX_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + const int64_t r = srow0 + sm + i * otile_t::kFragRowsJump; + max_score[i] = Sin[r * kSW + BDV]; + sum_score[i] = Sin[r * kSW + BDV + 1]; + } + } + + const int kb_begin = KEY_RANGES ? range_begin : 0; + int kb_lim = KEY_RANGES ? range_end : params->NK; + int kb_min_causal = params->NK; + + // Keep all real keys: the baseline's boolean mask uses finite T minimum. + kb_min_causal = 0; + + const bool is_last_bq = int(tid.x) == (params->NQ_aligned); + const bool is_last_q = is_last_bq; + + const short lim_rows_q = params->qL_rem - tm; + const short lim_rows_k = params->kL_rem; + + const device T* const k_start = K; + const device T* const v_start = V; + // Three score passes preserve global-max exp arguments and the native + // probability rounding before P @ V without a materialized score matrix. + for (short pass = KEY_RANGES ? SCORE_PASS : 0; + pass < (KEY_RANGES ? SCORE_PASS + 1 : 3); ++pass) { + K = k_start; + V = v_start; + if constexpr (KEY_RANGES) { + K += int64_t(kb_begin) * BK * K_strides[2]; + V += int64_t(kb_begin) * BK * V_strides[2]; + } + if (pass == 1 && has_sinks && (!KEY_RANGES || FIRST_RANGE)) { + OMLX_NAX_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + sum_score[i] = fast::exp(AccumType(sinks[tidl.y]) - max_score[i]); + } + } + // Loop over KV seq length + for (int kb = kb_begin; kb < kb_lim; kb++) { + const int is_last_k = (kb == (params->NK_aligned)); + + // Do S = Q @ K.T + using stile_t = NAXTile; + stile_t Stile; + + Stile.clear(); + + OMLX_NAX_UNROLL + for (short iq = 0; iq < TQ; iq++) { + OMLX_NAX_UNROLL + for (short ik = 0; ik < TK; ik += 2) { + #pragma clang loop unroll_count(4) + for (short id = 0; id < TD; id++) { + NAXTile Qtile; + NAXTile Ktile; + + const int64_t Q_load_off = iq * kU * Q_strides[2] + id * kU * q_str[3]; + const int64_t K_load_off = ik * kU * K_strides[2] + id * kU * k_str[3]; + + if (!align_Q && is_last_q) { + load_head_rows(Qtile, + Q + Q_load_off, int(Q_strides[2]), q_str[3], lim_rows_q - iq * kU); + } else { + load_head_rows(Qtile, Q + Q_load_off, int(Q_strides[2]), q_str[3], kU); + } + + if (!align_K && is_last_k) { + load_head_rows(Ktile, + K + K_load_off, int(K_strides[2]), k_str[3], lim_rows_k - ik * kU); + } else { + load_head_rows(Ktile, K + K_load_off, int(K_strides[2]), k_str[3], 2 * kU); + } + + stile_t::NAXFrag_t::mma( + Stile.frag_at(iq, ik), + Stile.frag_at(iq, ik + 1), + Qtile.frag_at(0, 0), + metal::false_type{}, + Ktile.frag_at(0, 0), + Ktile.frag_at(1, 0), + metal::true_type{}); + } + } + } + + // Q is pre-scaled in native dtype by the host, exactly as fast.cpp. + // The fallback materializes QK in native dtype before softmax. + // Round at the same boundary here. + // Round S + OMLX_NAX_UNROLL + for (short ii = 0; ii < stile_t::kElemsPerTile; ii++) { + Stile.elems()[ii] = AccumType(T(Stile.elems()[ii])); + } + + // Mask out length sequence + if (!align_K && is_last_k) { + constexpr auto neg_inf = Limits::finite_min; + + OMLX_NAX_UNROLL + for (short iq = 0; iq < TQ; iq++) { + OMLX_NAX_UNROLL + for (short ik = 0; ik < TK; ik++) { + const short col_pos = ik * kU + sn; + + thread auto& fg = Stile.frag_at(iq, ik); + + OMLX_NAX_UNROLL + for (short ii = 0; ii < stile_t::kFragThrRows; ii++) { + OMLX_NAX_UNROLL + for (short jj = 0; jj < stile_t::kFragThrCols; jj++) { + const auto loc = ii * stile_t::kFragThrCols + jj; + fg[loc] = ((col_pos + jj) < params->kL_rem) ? fg[loc] : neg_inf; + } + } + } + } + } + + // Mask out if causal + if (do_causal && kb >= kb_min_causal) { + constexpr auto neg_inf = AccumType(Limits::finite_min); + + const int base_row = tid.x * BQ + params->qL_off + tm; + const int base_col = kb * BK; + + OMLX_NAX_UNROLL + for (short iq = 0; iq < TQ; iq++) { + OMLX_NAX_UNROLL + for (short ik = 0; ik < TK; ik++) { + thread auto& fg = Stile.frag_at(iq, ik); + + OMLX_NAX_UNROLL + for (short ii = 0; ii < stile_t::kFragThrRows; ii++) { + OMLX_NAX_UNROLL + for (short jj = 0; jj < stile_t::kFragThrCols; jj++) { + const auto r = + base_row + iq * kU + ii * stile_t::kFragRowsJump + sm; + const auto c = base_col + ik * kU + jj + sn; + const auto loc = ii * stile_t::kFragThrCols + jj; + fg[loc] = (r < c) ? neg_inf : fg[loc]; + } + } + } + } + } + + // Other masking as needed + if (has_mask) { + constexpr auto neg_inf = AccumType(Limits::finite_min); + + const int base_row = tid.x * BQ + tm; + const int base_col = kb * BK; + + constexpr bool is_bool = is_same_v; + using melem_t = typename metal::conditional_t; + using mtile_t = NAXTile; + using mfrag_t = typename mtile_t::frag_type; + + if (base_row + BQ <= params->qL && base_col + BK <= params->kL) { + for (short iq = 0; iq < TQ; iq++) { + OMLX_NAX_UNROLL + for (short ik = 0; ik < TK; ik++) { + const int row_pos = base_row + iq * kU; + const int col_pos = base_col + ik * kU; + + mfrag_t mfrag; + mtile_t::NAXFrag_t::load( + mfrag, + mask, + int64_t(m_str[2]), + int64_t(m_str[3]), + row_pos, + col_pos); + + thread auto& fg = Stile.frag_at(iq, ik); + + OMLX_NAX_UNROLL + for (short jj = 0; jj < mtile_t::kElemsPerFrag; jj++) { + if constexpr (is_bool) { + fg[jj] = mfrag[jj] ? fg[jj] : neg_inf; + } else { + fg[jj] += AccumType(mfrag[jj]); + } + } + } + } + } else { + OMLX_NAX_UNROLL + for (short iq = 0; iq < TQ; iq++) { + OMLX_NAX_UNROLL + for (short ik = 0; ik < TK; ik++) { + const int row_pos = base_row + iq * kU; + const int col_pos = base_col + ik * kU; + + mfrag_t mfrag; + mtile_t::NAXFrag_t::load_safe( + mfrag, + mask, + int64_t(m_str[2]), + int64_t(m_str[3]), + params->qL, + params->kL, + row_pos, + col_pos); + + thread auto& fg = Stile.frag_at(iq, ik); + + OMLX_NAX_UNROLL + for (short jj = 0; jj < mtile_t::kElemsPerFrag; jj++) { + if constexpr (is_bool) { + fg[jj] = mfrag[jj] ? fg[jj] : neg_inf; + } else { + fg[jj] += AccumType(mfrag[jj]); + } + } + } + } + } + } + + // Exclude padded K columns after applying real-key masks. + if (!align_K && is_last_k) { + OMLX_NAX_UNROLL + for (short iq = 0; iq < TQ; ++iq) { + OMLX_NAX_UNROLL + for (short ik = 0; ik < TK; ++ik) { + auto& frag = Stile.frag_at(iq, ik); + OMLX_NAX_UNROLL + for (short r = 0; r < stile_t::kFragThrRows; ++r) { + OMLX_NAX_UNROLL + for (short c = 0; c < stile_t::kFragThrCols; ++c) { + if (ik * kU + sn + c >= params->kL_rem) { + frag[r * stile_t::kFragThrCols + c] = -INFINITY; + } + } + } + } + } + } + if (pass == 0) { + Stile.template row_reduce(max_score); + } else if (pass == 1) { + Stile.template row_bin_op(max_score); + Stile.template row_reduce(sum_score); + } else { + Stile.template row_bin_op(max_score); + metal::vec reciprocal_sum; + OMLX_NAX_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + reciprocal_sum[i] = 1.f / sum_score[i]; + } + Stile.template row_bin_op(reciprocal_sum); + NAXTile Ptile; + OMLX_NAX_UNROLL + for (short i = 0; i < stile_t::kElemsPerTile; ++i) { + Ptile.elems()[i] = T(Stile.elems()[i]); + } + simdgroup_barrier(mem_flags::mem_none); + + // Do O = P @ V + OMLX_NAX_UNROLL + for (short iq = 0; iq < TQ; iq++) { + OMLX_NAX_UNROLL + for (short id = 0; id < TDV; id += 2) { + if constexpr (BDV == 128) { + if (id == 4) { + threadgroup_barrier(mem_flags::mem_none); + } + } + + OMLX_NAX_UNROLL + for (short ik = 0; ik < TK; ik++) { + NAXTile Vtile; + + const int64_t V_load_off = ik * kU * V_strides[2] + id * kU * v_str[3]; + + if (!align_K && is_last_k) { + load_head_rows(Vtile, + V + V_load_off, int(V_strides[2]), v_str[3], lim_rows_k - ik * kU); + } else { + load_head_rows(Vtile, V + V_load_off, int(V_strides[2]), v_str[3], kU); + } + + otile_t::NAXFrag_t::mma( + Otile.frag_at(iq, id), + Otile.frag_at(iq, id + 1), + Ptile.frag_at(iq, ik), + metal::false_type{}, + Vtile.frag_at(0, 0), + Vtile.frag_at(0, 1), + metal::false_type{}); + } + } + } + + } // normalized native-dtype probability / value product + // Prepare for next iteration + K += BK * int(K_strides[2]); + V += BK * int(V_strides[2]); + } + + } // score passes + threadgroup_barrier(mem_flags::mem_none); + + if constexpr (KEY_RANGES && !(SCORE_PASS == 2 && LAST_RANGE)) { + // Unique O fragment stores; only the first column lane stores each + // replicated row reduction. Ragged Q padding is initialized too. + Otile.store(Sout + srow0 * kSW, kSW); + if (sn == 0) { + OMLX_NAX_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + const int64_t r = srow0 + sm + i * otile_t::kFragRowsJump; + Sout[r * kSW + BDV] = max_score[i]; + Sout[r * kSW + BDV + 1] = sum_score[i]; + } + } + // Both outputs are bound by custom-kernel ABI; initialize the unused + // scalar, not an out-of-range B/H/Q address. + if (tid.x == 0 && tid.y == 0 && tid.z == 0 && + simd_group_id == 0 && sm == 0 && sn == 0) { + O[0] = T(0); + } + return; + } + if constexpr (KEY_RANGES) { + if (tid.x == 0 && tid.y == 0 && tid.z == 0 && + simd_group_id == 0 && sm == 0 && sn == 0) { + Sout[0] = 0.f; + } + } + + // Store results + O += tm * int(O_strides[2]); + + if (!align_Q && is_last_q) { + if (lim_rows_q <= 0) + return; + + Otile.store_rows(O, int(O_strides[2]), lim_rows_q); + } else { + Otile.store(O, int(O_strides[2])); + } + } + + // Keep the original single-dispatch entry contract for ordinary callers and + // independently owned per-block descriptors. Disabled range code adds no + // floating-point operations, allocation, key truncation or state dereference. + template < + typename T, + int BQ, + int BK, + int BD, + int BDV, + int WM, + int WN, + bool align_Q, + bool align_K, + bool has_mask, + bool do_causal, + bool has_sinks, + typename MaskType, + typename AccumType, + typename StridePtr, + typename MaskPtr, + typename SinkPtr> + METAL_FUNC void attention_nax_bdv( + const device T* Q, + const device T* K, + const device T* V, + device T* O, + const device AttnParams* params, + StridePtr q_str, + StridePtr k_str, + StridePtr v_str, + StridePtr m_str, + MaskPtr mask, + SinkPtr sinks, + uint simd_group_id, + uint3 tid) { + attention_nax_bdv_impl( + Q, K, V, O, params, q_str, k_str, v_str, m_str, mask, sinks, + Q, nullptr, 0, 0, simd_group_id, tid); + } + + } // namespace omlx_nax + """# + + static let source = #""" + omlx_nax::attention_nax_bdv< + T, 64, 32, 192, 128, 4, 1, + ALIGN_Q, ALIGN_K, HAS_MASK, DO_CAUSAL, HAS_SINKS, bool, float>( + q, k, v, out, + reinterpret_cast(params), + q_strides, k_strides, v_strides, mask_strides, + mask, sinks, + simdgroup_index_in_threadgroup, + threadgroup_position_in_grid); + """# +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXGateUp.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXGateUp.swift new file mode 100644 index 0000000000..6a7026c378 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXGateUp.swift @@ -0,0 +1,246 @@ +// Copyright © 2026 Eigen Labs. +// SPDX-License-Identifier: Apache-2.0 +// Joint native MXFP4 gate/up experiment; no checkpoint or module mutation. + +import Foundation +import MLX +import MLXFast + +enum MiMoV26NAXGateUp { + static let requested: Bool = { + let value = ProcessInfo.processInfo.environment["DARKBLOOM_MIMO_V26_NAX_GATE_UP"]? + .trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + return ["1", "true", "yes", "on"].contains(value ?? "") + }() + + /// Separate opt-in until the epilogue is qualified on the actual NAX host. + static let activationRequested = + ProcessInfo.processInfo.environment[ + "DARKBLOOM_MIMO_V26_NAX_SWIGLU"] == "1" + static let rowMapRequested = + ProcessInfo.processInfo.environment[ + "DARKBLOOM_MIMO_V26_NAX_ROW_MAP"] == "1" + + private static let lock = NSLock() + nonisolated(unsafe) private static var encodings = 0 + + static func encodedCalls() -> Int { + lock.lock() + defer { lock.unlock() } + return encodings + } + + static func tryProjection( + x: MLXArray, indices: MLXArray, gate: SwitchLinear, up: SwitchLinear, + sorted: Bool + ) -> (gate: MLXArray, up: MLXArray)? { + guard + let (gate, up, plan, stream) = eligibleProjection( + x: x, indices: indices, gate: gate, up: up, sorted: sorted) + else { return nil } + let result = launch( + x: x, indices: indices, + gateWeight: gate.weight, gateScales: gate.scales, + upWeight: up.weight, upScales: up.scales, plan: plan, stream: stream) + lock.lock() + encodings += 1 + lock.unlock() + return result + } + + /// Only the caller's known default SiLU product may use this path. + /// It never substitutes an unknown/custom activation or changes weights. + static func tryActivation( + x: MLXArray, indices: MLXArray, gate: SwitchLinear, up: SwitchLinear, + sorted: Bool, rowMap: MLXArray? = nil + ) -> MLXArray? { + guard activationRequested, MLXHardwareInfo.isCompiledDecodeSupported, + rowMap == nil || rowMapRequested, + let (gate, up, plan, stream) = eligibleProjection( + x: x, indices: indices, gate: gate, up: up, sorted: sorted, rowMap: rowMap) + else { return nil } + let result = launchActivation( + x: x, indices: indices, + gateWeight: gate.weight, gateScales: gate.scales, + upWeight: up.weight, upScales: up.scales, plan: plan, stream: stream, rowMap: rowMap) + lock.lock() + encodings += 1 + lock.unlock() + return result + } + + private static func eligibleProjection( + x: MLXArray, indices: MLXArray, gate: SwitchLinear, up: SwitchLinear, + sorted: Bool, rowMap: MLXArray? = nil + ) -> (QuantizedSwitchLinear, QuantizedSwitchLinear, MiMoV26NAXGatherQMM.Plan, StreamOrDevice)? { + let sortedRows = rowMap?.size ?? (x.ndim > 0 ? x.dim(0) : 0) + if let rowMap { + guard rowMap.ndim == 1, rowMap.dtype == .uint32, x.ndim == 3, x.dim(0) > 0 + else { return nil } + } + guard requested, sorted, + let gate = gate as? QuantizedSwitchLinear, let up = up as? QuantizedSwitchLinear, + ObjectIdentifier(type(of: gate)) == ObjectIdentifier(QuantizedSwitchLinear.self), + ObjectIdentifier(type(of: up)) == ObjectIdentifier(QuantizedSwitchLinear.self), + gate.bias == nil, up.bias == nil, gate.biases == nil, up.biases == nil, + gate.mode == .mxfp4, up.mode == .mxfp4, + gate.bits == 4, up.bits == 4, gate.groupSize == 32, up.groupSize == 32, + x.ndim == 3, x.dim(1) == 1, x.dim(2) == 4096, + x.dtype == .bfloat16 || x.dtype == .float16, + indices.shape == [sortedRows], indices.dtype == .uint32, + gate.weight.shape == [256, 2048, 512], up.weight.shape == gate.weight.shape, + gate.weight.dtype == .uint32, up.weight.dtype == .uint32, + gate.scales.shape == [256, 2048, 128], up.scales.shape == gate.scales.shape, + gate.scales.dtype == .uint8, up.scales.dtype == .uint8, + let plan = MiMoV26NAXGatherQMM.Plan.production( + rows: sortedRows, experts: 256, input: 4096, output: 2048) + else { return nil } + let stream = StreamOrDevice.default + guard MiMoV26NAXGatherQMM.gpuStream(stream), MiMoV26NAXGatherQMM.naxAvailable + else { return nil } + return (gate, up, plan, stream) + } + + private static let scan = MLXFast.metalKernel( + name: "mimo_v26_mxfp4_gate_up_tile_scan", + inputNames: ["idx", "params"], outputNames: ["tiles", "tile_count"], + source: MiMoV26NAXMetalSources.scanSource, + header: MiMoV26NAXMetalSources.scanHeader + "\n", ensureRowContiguous: true) + + private static func makeKernel(tileRows: Int, activation: Bool = false, rowMap: Bool = false) + -> MLXFast.MLXFastKernel + { + let single = MiMoV26NAXMetalSources.matmulHeader + .replacingOccurrences( + of: "STEEL_CONST int kBM = 64;", + with: "STEEL_CONST int kBM = \(tileRows);" + ) + .replacingOccurrences( + of: "STEEL_CONST int kWM = 2;", + with: "STEEL_CONST int kWM = \(tileRows / 32);") + var source = + activation + ? MiMoV26NAXGateUpMetalSources.source + .replacingOccurrences( + of: "gather_gate_up(", with: "gather_gate_up(" + ) + .replacingOccurrences(of: "gate_y, up_y", with: "activation_y, activation_y") + : MiMoV26NAXGateUpMetalSources.source + if rowMap { + precondition(activation) + source = + source + .replacingOccurrences( + of: "gather_gate_up(", with: "gather_gate_up(" + ) + .replacingOccurrences( + of: "gate_q, up_q, tiles, tiles,", with: "gate_q, up_q, tiles, row_map,") + } + return MLXFast.metalKernel( + name: "mimo_v26_mxfp4_gate_up_bm\(tileRows)" + (activation ? "_silu" : "") + + (rowMap ? "_mapped" : ""), + inputNames: [ + "x", "gate_w", "gate_scales", "up_w", "up_scales", + "tiles", "tile_count", "params", + ] + (rowMap ? ["row_map"] : []), + outputNames: activation ? ["activation_y"] : ["gate_y", "up_y"], source: source, + header: MiMoV26NAXMetalSources.mlxHeader + "\n" + single + "\n" + + MiMoV26NAXGateUpMetalSources.header + "\n", + ensureRowContiguous: true) + } + + private static let kernel64 = makeKernel(tileRows: 64) + private static let kernel128 = makeKernel(tileRows: 128) + private static let activationKernel64 = makeKernel(tileRows: 64, activation: true) + private static let activationKernel128 = makeKernel(tileRows: 128, activation: true) + private static let mappedKernel64 = makeKernel(tileRows: 64, activation: true, rowMap: true) + private static let mappedKernel128 = makeKernel(tileRows: 128, activation: true, rowMap: true) + + /// Internal test seam, aligned dimensions only; caller owns GPU execution. + static func launch( + x: MLXArray, indices: MLXArray, + gateWeight: MLXArray, gateScales: MLXArray, + upWeight: MLXArray, upScales: MLXArray, + plan: MiMoV26NAXGatherQMM.Plan, stream: StreamOrDevice = .default, + tileRows: Int? = nil + ) -> (gate: MLXArray, up: MLXArray) { + let result = launchOutputs( + x: x, indices: indices, gateWeight: gateWeight, + gateScales: gateScales, upWeight: upWeight, upScales: upScales, + plan: plan, stream: stream, tileRows: tileRows, activation: false, rowMap: nil) + return (gate: result[0], up: result[1]) + } + + /// Test seam shares the exact projection/tiling path with the separate outputs. + static func launchActivation( + x: MLXArray, indices: MLXArray, + gateWeight: MLXArray, gateScales: MLXArray, + upWeight: MLXArray, upScales: MLXArray, + plan: MiMoV26NAXGatherQMM.Plan, stream: StreamOrDevice = .default, + tileRows: Int? = nil, rowMap: MLXArray? = nil + ) -> MLXArray { + launchOutputs( + x: x, indices: indices, gateWeight: gateWeight, + gateScales: gateScales, upWeight: upWeight, upScales: upScales, + plan: plan, stream: stream, tileRows: tileRows, activation: true, rowMap: rowMap)[0] + } + + private static func launchOutputs( + x: MLXArray, indices: MLXArray, + gateWeight: MLXArray, gateScales: MLXArray, + upWeight: MLXArray, upScales: MLXArray, + plan: MiMoV26NAXGatherQMM.Plan, stream: StreamOrDevice, + tileRows: Int?, activation: Bool, rowMap: MLXArray? + ) -> [MLXArray] { + let bm = tileRows ?? plan.tileRows + precondition(bm == 64 || bm == 128) + precondition(plan.experts > 0 && plan.experts <= 256 && plan.rows >= 8) + precondition( + plan.input > 0 && plan.input % 64 == 0 + && plan.output > 0 && plan.output % 64 == 0) + precondition( + x.ndim == 3 && x.dim(1) == 1 && x.dim(2) == plan.input + && (rowMap == nil ? x.dim(0) == plan.rows : x.dim(0) > 0) + && (x.dtype == .bfloat16 || x.dtype == .float16)) + if let rowMap { + precondition(activation && rowMap.shape == [plan.rows] && rowMap.dtype == .uint32) + } + precondition(indices.shape == [plan.rows] && indices.dtype == .uint32) + for weight in [gateWeight, upWeight] { + precondition( + weight.shape == [plan.experts, plan.output, plan.input / 8] + && weight.dtype == .uint32) + } + for scales in [gateScales, upScales] { + precondition( + scales.shape == [plan.experts, plan.output, plan.input / 32] + && scales.dtype == .uint8) + } + let maxTiles = (plan.rows + bm - 1) / bm + min(plan.experts, plan.rows) + let descriptors = scan( + [indices, MLXArray([Int32(plan.rows), Int32(plan.experts), Int32(maxTiles)])], + template: [("BM", bm), ("MAXE", 256)], + grid: (1024, 1, 1), threadGroup: (1024, 1, 1), + outputShapes: [[maxTiles * 4], [1]], outputDTypes: [.uint32, .uint32], + stream: stream) + precondition(descriptors.count == 2) + let kernel = + rowMap != nil + ? (bm == 128 ? mappedKernel128 : mappedKernel64) + : activation + ? (bm == 128 ? activationKernel128 : activationKernel64) + : (bm == 128 ? kernel128 : kernel64) + let result = kernel( + [ + x, gateWeight, gateScales, upWeight, upScales, descriptors[0], descriptors[1], + MLXArray([Int32(plan.output), Int32(plan.input)]), + ] + (rowMap.map { [$0] } ?? []), + template: [("T", x.dtype)], + grid: ((plan.output / 64) * 32, maxTiles * 2, bm / 32), + threadGroup: (32, 2, bm / 32), + outputShapes: Array(repeating: [plan.rows, 1, plan.output], count: activation ? 1 : 2), + outputDTypes: Array(repeating: x.dtype, count: activation ? 1 : 2), stream: stream) + precondition(result.count == (activation ? 1 : 2)) + return result + } +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXGateUpMetalSources.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXGateUpMetalSources.swift new file mode 100644 index 0000000000..771c02f4a3 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXGateUpMetalSources.swift @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: Apache-2.0 AND MIT +// Adapted from oMLX #3995, 47876fbc310fbb311cd382c4eba8572ec4368308, +// to implement #3993's joint-projection intent without concatenating weights. +// Modified: independent gate/up inputs and accumulators; one activation load. +// SwiGLU epilogue intent from oMLX #4022, d6dbc9970c6df99b6a8589746e6ff8ddc38c33ff. +// Preserve the independent GEMM K order and native rounded elementwise stages. +// Apple/MIT primitive notices: MiMoV26NAXMetalSources.swift. +// oMLX notice/license: docs/mimo-v26/LICENSE-OMLX. + +enum MiMoV26NAXGateUpMetalSources { + static let header = #""" + namespace omlx_gqmm { + + // Exact pinned MLX unary_ops.h / binary_ops.h implementations, renamed to + // avoid collisions with the surrounding generated-kernel header. Their MIT + // notice is preserved in MiMoV26NAXMetalSources.swift. + struct MiMoGateUpSigmoid { + template + T operator()(T x) thread { + auto y = 1 / (1 + metal::exp(metal::abs(x))); + return (x < 0) ? y : 1 - y; + } + }; + struct MiMoGateUpMultiply { + template + T operator()(T x, T y) thread { return x * y; } + }; + + // Aligned native MXFP4 gate/up. The two independent output accumulators + // follow the same per-element K sequence as gather_seg. + template + METAL_FUNC void gather_gate_up( + const device T* x, + const device uint8_t* gate_w, + const device uint8_t* up_w, + thread Q& gate_q, + thread Q& up_q, + const device uint32_t* tiles, + const device uint32_t* row_map, + device T* gate_y, + device T* up_y, + const int N, + const int K, + threadgroup typename Q::WT* gate_ws, + threadgroup typename Q::WT* up_ws, + const uint3 tid, + const uint sgid, + const uint lane) { + using WT = typename Q::WT; + constexpr int BKP = kBK + 16 / sizeof(WT); + const uint4 desc = *((const device uint4*)tiles + tid.y); + const int row_start = int(desc.x); + const uint32_t expert = desc.y; + const int rows = int(desc.z); + const int K_w = K * Q::kBits / 8; + const int K_g = K / Q::kGroup; + const int y_col = int(tid.x) * kBN; + const size_t w_row = size_t(expert) * N + y_col; + + gate_q.advance(w_row * K_g); + up_q.advance(w_row * K_g); + TileLoader gate_loader(gate_w + w_row * K_w, K, gate_q, sgid * 32 + lane); + TileLoader up_loader(up_w + w_row * K_w, K, up_q, sgid * 32 + lane); + + if constexpr (!ROW_MAP) { x += size_t(row_start) * K; } + gate_y += size_t(row_start) * N + y_col; + up_y += size_t(row_start) * N + y_col; + const short tm = kSM * short(sgid / kWN); + const short tn = kSN * short(sgid % kWN); + const short live_rows = short(min(int(kSM), max(0, rows - int(tm)))); + const device T* xn = x + (ROW_MAP ? 0 : tm * K); + // #4029: load the same token rows through the sort map, without writing + // their repeated copies. size_t preserves offsets beyond UInt32 elements. + size_t mapped_offsets[kTM][2]; + const short2 sc = BaseNAXFrag::get_coord(); + if constexpr (ROW_MAP) { + STEEL_PRAGMA_UNROLL + for (short mm = 0; mm < kTM; ++mm) { + STEEL_PRAGMA_UNROLL + for (short h = 0; h < 2; ++h) { + const int local_row = min(rows - 1, int(tm) + mm * 16 + h * 8 + sc.y); + mapped_offsets[mm][h] = size_t(row_map[row_start + local_row]) * K + sc.x; + } + } + } + + NAXTile gate_d; + NAXTile up_d; + gate_d.clear(); + up_d.clear(); + + for (int kb = 0; kb < K / kBK; ++kb) { + threadgroup_barrier(mem_flags::mem_threadgroup); + gate_loader.fetch(kb); + up_loader.fetch(kb); + gate_loader.store(gate_ws); + up_loader.store(up_ws); + threadgroup_barrier(mem_flags::mem_threadgroup); + + STEEL_PRAGMA_NO_UNROLL + for (short kk1 = 0; kk1 < kBK; kk1 += kSK) { + if (live_rows > 0) { + NAXTile gate_b; + NAXTile up_b; + gate_b.template load(gate_ws + tn * BKP + kk1); + up_b.template load(up_ws + tn * BKP + kk1); + STEEL_PRAGMA_UNROLL + for (short mm = 0; mm < kTM; ++mm) { + if (mm * 16 < live_rows) { + NAXTile a; + // This single device activation read feeds both independent GEMMs. + if constexpr (ROW_MAP) { + STEEL_PRAGMA_UNROLL + for (short h = 0; h < 2; ++h) { + STEEL_PRAGMA_UNROLL + for (short kk = 0; kk < kTK; ++kk) { + const vec v = *(const device vec*)( + xn + mapped_offsets[mm][h] + kk1 + kk * 16); + STEEL_PRAGMA_UNROLL + for (short c = 0; c < 4; ++c) { + a.frag_at(0, kk)[h * 4 + c] = + mm * 16 + h * 8 + sc.y < live_rows ? v[c] : T(0); + } + } + } + } else if (live_rows - mm * 16 >= 16) { + a.load(xn + mm * 16 * K + kk1, K); + } else { + a.load_safe(xn + mm * 16 * K + kk1, K, + short2(kSK, live_rows - mm * 16)); + } + STEEL_PRAGMA_UNROLL + for (short nn = 0; nn < kTN; nn += 2) { + STEEL_PRAGMA_UNROLL + for (short kk = 0; kk < kTK; ++kk) { + BaseNAXFrag::mma( + gate_d.frag_at(mm, nn), gate_d.frag_at(mm, nn + 1), + a.frag_at(0, kk), metal::bool_constant{}, + gate_b.frag_at(nn, kk), gate_b.frag_at(nn + 1, kk), + metal::bool_constant{}); + BaseNAXFrag::mma( + up_d.frag_at(mm, nn), up_d.frag_at(mm, nn + 1), + a.frag_at(0, kk), metal::bool_constant{}, + up_b.frag_at(nn, kk), up_b.frag_at(nn + 1, kk), + metal::bool_constant{}); + } + } + } + } + } + } + xn += kBK; + } + if constexpr (FUSE_ACTIVATION) { + // The two projections are rounded exactly where the separate stores + // round them. Each following functor returns T before the next op. + // Do not contract the FP32 accumulators directly into a different SiLU. + NAXTile activated; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(activated)::kNumFrags; ++i) { + STEEL_PRAGMA_UNROLL + for (short e = 0; e < decltype(activated)::kElemsPerFrag; ++e) { + const T g = static_cast(gate_d.val_frags[i][e]); + const T u = static_cast(up_d.val_frags[i][e]); + activated.val_frags[i][e] = MiMoGateUpMultiply()( + MiMoGateUpMultiply()(g, MiMoGateUpSigmoid()(g)), u); + } + } + if (live_rows == kSM) { + activated.store(gate_y + tm * N + tn, N); + } else if (live_rows > 0) { + activated.store_safe(gate_y + tm * N + tn, N, short2(kSN, live_rows)); + } + } else if (live_rows == kSM) { + gate_d.store(gate_y + tm * N + tn, N); + up_d.store(up_y + tm * N + tn, N); + } else if (live_rows > 0) { + gate_d.store_safe(gate_y + tm * N + tn, N, short2(kSN, live_rows)); + up_d.store_safe(up_y + tm * N + tn, N, short2(kSN, live_rows)); + } + } + } // namespace omlx_gqmm + """# + + static let source = #""" + if (threadgroup_position_in_grid.y >= tile_count[0]) { + return; + } + using Q = omlx_gqmm::Mxfp4Q<32>; + constexpr int BKP = omlx_gqmm::kBK + 16 / sizeof(bfloat); + // Two single buffers total 18432 bytes; no dual double buffering. + threadgroup bfloat gate_ws[omlx_gqmm::kBN * BKP]; + threadgroup bfloat up_ws[omlx_gqmm::kBN * BKP]; + Q gate_q{gate_scales, 0.0f}; + Q up_q{up_scales, 0.0f}; + omlx_gqmm::gather_gate_up( + x, (const device uint8_t*)gate_w, (const device uint8_t*)up_w, + gate_q, up_q, tiles, tiles, gate_y, up_y, params[0], params[1], + gate_ws, up_ws, threadgroup_position_in_grid, + simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + """# +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXGatherQMM.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXGatherQMM.swift new file mode 100644 index 0000000000..546e6cabe6 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXGatherQMM.swift @@ -0,0 +1,190 @@ +// Copyright © 2026 Eigen Labs. +// SPDX-License-Identifier: Apache-2.0 +// Host port of jundot/omlx PR #3995 at 47876fbc310fbb311cd382c4eba8572ec4368308. +// Experimental, OFF by default. See docs/mimo-v26/NAX-GATHER-PORT.md. + +import Cmlx +import Foundation +import MLX +import MLXFast + +/// Counts graph encodings, not completed GPU executions or benchmark samples. +public enum MiMoV26NAXGatherDiagnostics { + private static let lock = NSLock() + nonisolated(unsafe) private static var encodings = 0 + + public static func encodedCalls() -> Int { + lock.lock() + defer { lock.unlock() } + return encodings + } + + fileprivate static func recordEncoding() { + lock.lock() + encodings += 1 + lock.unlock() + } +} + +enum MiMoV26NAXGatherQMM { + static let requested: Bool = { + let value = ProcessInfo.processInfo.environment["DARKBLOOM_MIMO_V26_NAX_GATHER"]? + .trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + return ["1", "true", "yes", "on"].contains(value ?? "") + }() + + struct Plan: Equatable { + let rows: Int + let experts: Int + let input: Int + let output: Int + let tileRows: Int + let doubleBuffer: Bool + var maxTiles: Int { (rows + tileRows - 1) / tileRows + min(experts, rows) } + + init(rows: Int, experts: Int, input: Int, output: Int) { + self.rows = rows + self.experts = experts + self.input = input + self.output = output + tileRows = + rows > 64 * experts && rows <= 128 * experts && input >= 2048 + ? 128 : 64 + doubleBuffer = rows <= 128 * experts + } + + /// Only exact native MiMo gate, up, optional gate/up and down shapes. + static func production(rows: Int, experts: Int, input: Int, output: Int) -> Plan? { + guard experts == 256, rows >= 1024, rows <= Int(Int32.max) - 128, + (input == 4096 && (output == 2048 || output == 4096)) + || (input == 2048 && output == 4096) + else { return nil } + let plan = Plan(rows: rows, experts: experts, input: input, output: output) + guard plan.maxTiles <= Int(Int32.max) / 4 else { return nil } + return plan + } + } + + static func gpuStream(_ stream: StreamOrDevice) -> Bool { + var device = mlx_device_new() + defer { mlx_device_free(device) } + var type = MLX_CPU + return mlx_stream_get_device(&device, stream.ctx) == 0 + && mlx_device_get_type(&type, device) == 0 && type == MLX_GPU + } + + static let naxAvailable: Bool = { + #if os(macOS) || os(iOS) || os(tvOS) || os(visionOS) + // Uses the pinned core's real OS, architecture and NO_NAX-build gate. + return GPU.gemma4ExpertQMMDiagnostics().naxAvailable + #else + return false + #endif + }() + + static func tryProjection( + x: MLXArray, indices: MLXArray, weight: MLXArray, scales: MLXArray, + biases: MLXArray?, sorted: Bool, groupSize: Int, bits: Int, + mode: QuantizationMode + ) -> MLXArray? { + guard requested, sorted, x.ndim == 3, x.dim(1) == 1, + x.dtype == .bfloat16 || x.dtype == .float16, + indices.ndim == 1, indices.dtype == .uint32, + indices.size == x.dim(0), weight.ndim == 3, weight.dtype == .uint32, + mode == .mxfp4, bits == 4, groupSize == 32, biases == nil, + scales.dtype == .uint8, + let plan = Plan.production( + rows: x.dim(0), experts: weight.dim(0), + input: x.dim(2), output: weight.dim(1)), + weight.shape == [plan.experts, plan.output, plan.input / 8], + scales.shape == [plan.experts, plan.output, plan.input / 32] + else { return nil } + + let stream = StreamOrDevice.default + guard gpuStream(stream), naxAvailable else { return nil } + // The caller's gatherSort owns sortedness and bounds. No eval, canary, + // stream substitution, weight conversion or cached array enters forward. + let result = launch( + x: x, indices: indices, weight: weight, scales: scales, + plan: plan, stream: stream) + MiMoV26NAXGatherDiagnostics.recordEncoding() + return result + } + + private static let scan = MLXFast.metalKernel( + name: "mimo_v26_mxfp4_nax_tile_scan", + inputNames: ["idx", "params"], outputNames: ["tiles", "tile_count"], + source: MiMoV26NAXMetalSources.scanSource, + header: MiMoV26NAXMetalSources.scanHeader + "\n", + ensureRowContiguous: true) + + private static func makeMatmul(tileRows: Int) -> MLXFast.MLXFastKernel { + let header = MiMoV26NAXMetalSources.matmulHeader + .replacingOccurrences( + of: "STEEL_CONST int kBM = 64;", + with: "STEEL_CONST int kBM = \(tileRows);" + ) + .replacingOccurrences( + of: "STEEL_CONST int kWM = 2;", + with: "STEEL_CONST int kWM = \(tileRows / 32);") + return MLXFast.metalKernel( + name: "mimo_v26_mxfp4_nax_bm\(tileRows)", + inputNames: ["x", "w", "scales", "tiles", "tile_count", "params"], + outputNames: ["y"], source: MiMoV26NAXMetalSources.matmulSource, + header: MiMoV26NAXMetalSources.mlxHeader + "\n" + header + "\n", + ensureRowContiguous: true) + } + + private static let matmul64 = makeMatmul(tileRows: 64) + private static let matmul128 = makeMatmul(tileRows: 128) + + /// Internal test seam: synthetic aligned MXFP4 shapes use the same kernels. + /// Callers must own the GPU lane; it never performs an evaluation itself. + static func launch( + x: MLXArray, indices: MLXArray, weight: MLXArray, scales: MLXArray, + plan: Plan, stream: StreamOrDevice = .default, + tileRows: Int? = nil, doubleBuffer: Bool? = nil + ) -> MLXArray { + let bm = tileRows ?? plan.tileRows + let db = doubleBuffer ?? plan.doubleBuffer + precondition(bm == 64 || bm == 128) + precondition(plan.experts > 0 && plan.experts <= 256 && plan.rows >= 8) + precondition( + plan.input > 0 && plan.input % 64 == 0 + && plan.output > 0 && plan.output % 64 == 0) + precondition( + x.shape == [plan.rows, 1, plan.input] + && (x.dtype == .bfloat16 || x.dtype == .float16)) + precondition(indices.shape == [plan.rows] && indices.dtype == .uint32) + precondition( + weight.shape == [plan.experts, plan.output, plan.input / 8] + && weight.dtype == .uint32) + precondition( + scales.shape == [plan.experts, plan.output, plan.input / 32] + && scales.dtype == .uint8) + let maxTiles = (plan.rows + bm - 1) / bm + min(plan.experts, plan.rows) + let scanParams = MLXArray([Int32(plan.rows), Int32(plan.experts), Int32(maxTiles)]) + let descriptors = scan( + [indices, scanParams], template: [("BM", bm), ("MAXE", 256)], + grid: (1024, 1, 1), threadGroup: (1024, 1, 1), + outputShapes: [[maxTiles * 4], [1]], outputDTypes: [.uint32, .uint32], + stream: stream) + precondition(descriptors.count == 2) + let matmul = bm == 128 ? matmul128 : matmul64 + let output = matmul( + [ + x, weight, scales, descriptors[0], descriptors[1], + MLXArray([Int32(plan.output), Int32(plan.input)]), + ], + template: [ + ("T", x.dtype), ("GS", 32), ("SCHED", db ? 1 : 0), + ("ALIGN_N", true), ("ALIGN_K", true), + ], + grid: ((plan.output / 64) * 32, maxTiles * 2, bm / 32), + threadGroup: (32, 2, bm / 32), + outputShapes: [[plan.rows, 1, plan.output]], outputDTypes: [x.dtype], + stream: stream) + precondition(output.count == 1) + return output[0] + } +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXKeyRangeGroupedMetalSources.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXKeyRangeGroupedMetalSources.swift new file mode 100644 index 0000000000..f238bcb7ba --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXKeyRangeGroupedMetalSources.swift @@ -0,0 +1,57 @@ +// Copyright © 2026 Eigen Labs. +// SPDX-License-Identifier: Apache-2.0 AND MIT +// Grouped descriptor wrapper for oMLX #4032 @12e5084f8cf888bb6e846147929419f044802343. +// The shared native-rounded attention_nax_bdv_impl arithmetic is unchanged. +enum MiMoV26NAXKeyRangeGroupedMetalSources { + static let source = #""" + const uint block = threadgroup_position_in_grid.z; + const device int* row = params + block * 20; + const device omlx_nax::AttnParams* p = + reinterpret_cast(row); + // Uniform for this threadgroup, before any barrier in the shared body. + if (threadgroup_position_in_grid.x >= uint(p->NQ)) return; + const int query_offset = row[14]; + const int key_offset = row[15]; + const int mask_offset = row[16]; + const int state_offset = row[17]; + const int64_t qs[4] = {q_strides[0], q_strides[1], q_strides[2], q_strides[3]}; + const int64_t ks[4] = {k_strides[0], k_strides[1], k_strides[2], k_strides[3]}; + const int64_t vs[4] = {v_strides[0], v_strides[1], v_strides[2], v_strides[3]}; + const int64_t ms[4] = {0, 0, p->kL, 1}; + const uint3 local_tid(threadgroup_position_in_grid.x, + threadgroup_position_in_grid.y, 0); + // Preserve the generated input address space: tiny inputs may be constant + // pointers, while the full retained states are device pointers. + auto state_in = state + ((SCORE_PASS == 0 && FIRST_RANGE) + ? int(block) : state_offset); + device float* state_destination = state_out + + ((SCORE_PASS == 2 && LAST_RANGE) ? int(block) : state_offset); + device T* destination = out + ((SCORE_PASS == 2 && LAST_RANGE) + ? int64_t(query_offset) * p->H * 128 : int64_t(block)); + // Each descriptor owns its dummy output/state slot too. Passing local z=0 + // with one shared dummy would otherwise create same-address concurrent writes. + if constexpr (HAS_MASK) { + omlx_nax::attention_nax_bdv_impl< + T, 64, 32, 192, 128, 4, 1, ALIGN_Q, ALIGN_K, + true, DO_CAUSAL, HAS_SINKS, true, FIRST_RANGE, LAST_RANGE, + SCORE_PASS, bool, float>( + q + int64_t(query_offset) * q_strides[2], + k + int64_t(key_offset) * k_strides[2], + v + int64_t(key_offset) * v_strides[2], destination, p, + qs, ks, vs, ms, mask + mask_offset, sinks, + state_in, state_destination, row[18], row[19], + simdgroup_index_in_threadgroup, local_tid); + } else { + omlx_nax::attention_nax_bdv_impl< + T, 64, 32, 192, 128, 4, 1, ALIGN_Q, ALIGN_K, + false, DO_CAUSAL, HAS_SINKS, true, FIRST_RANGE, LAST_RANGE, + SCORE_PASS, bool, float>( + q + int64_t(query_offset) * q_strides[2], + k + int64_t(key_offset) * k_strides[2], + v + int64_t(key_offset) * v_strides[2], destination, p, + qs, ks, vs, ms, mask, sinks, + state_in, state_destination, row[18], row[19], + simdgroup_index_in_threadgroup, local_tid); + } + """# +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXKeyRangeWork.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXKeyRangeWork.swift new file mode 100644 index 0000000000..0c7bcbc1b9 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXKeyRangeWork.swift @@ -0,0 +1,282 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX + +/// One checked prefill scope over the already installed MiMo block budget. +/// This is not an admission assertion supplied by a model/caller. +enum MiMoV26NAXKeyRangeNative { + static let requested = + ProcessInfo.processInfo.environment[ + "DARKBLOOM_MIMO_V26_NAX_KEY_RANGES"] == "1" + @TaskLocal private static var current: MiMoV26NAXKeyRangeContext? + + static func withContext( + _ value: MiMoV26NAXKeyRangeContext?, + _ body: () throws -> Result + ) rethrows -> Result { + try $current.withValue(value, operation: body) + } + + static func prepareLayer( + budget: MiMoV26BlockBatchBudget, layerIndex: Int?, + plan: MiMoV26BlockBatchAttention.Plan + ) + -> MiMoV26NAXKeyRangeLayer? + { + guard requested, let current, current.budget === budget, + MiMoV26BlockBatchAttention.matchesCurrentBudget(budget), let layerIndex + else { return nil } + return current.prepareLayer(index: layerIndex, plan: plan) + } +} + +/// Engine-queue confined, bounded by the native model's actual layer count. +/// A child task retaining the TaskLocal cannot use it after the synchronous +/// forward closes. Only the engine creates its real work owner. +final class MiMoV26NAXKeyRangeContext: @unchecked Sendable { + let budget: MiMoV26BlockBatchBudget + private let admission: AdmissionV2 + private let tracking: CBv2NativeShutdownState + private let createWork: () throws -> MiMoV26NAXKeyRangeWork + private let stream: MLX.Stream + private let maximumBufferBytes: Int + private var work: MiMoV26NAXKeyRangeWork? + private var consumedLayers = Set() + private var closed = false + private var failure: Error? + + init?( + budget: MiMoV26BlockBatchBudget, admission: AdmissionV2, + tracking: CBv2NativeShutdownState, + createWork: @escaping () throws -> MiMoV26NAXKeyRangeWork + ) { + guard MiMoV26NAXKeyRangeNative.requested, admission.hasProcessMemoryOwner, + tracking.supported, tracking.engineID == budget.engineID, + MiMoV26NAXGatherQMM.gpuStream(.default), + StreamOrDevice.default.stream == MLX.Stream.gpu, + MiMoV26NAXGatherQMM.naxAvailable + else { return nil } + #if os(macOS) || os(iOS) || os(tvOS) || os(visionOS) + let maximum = GPU.deviceInfo().maxBufferSize + guard maximum > 0 else { return nil } + maximumBufferBytes = maximum + #else + return nil + #endif + self.budget = budget + self.admission = admission + self.tracking = tracking + self.createWork = createWork + stream = StreamOrDevice.default.stream + } + + func prepareLayer(index: Int, plan: MiMoV26BlockBatchAttention.Plan) + -> MiMoV26NAXKeyRangeLayer? + { + guard !closed, failure == nil, (0 ..< budget.layerCount).contains(index), + !consumedLayers.contains(index), tracking.mayExecute, + StreamOrDevice.default.stream == stream, + let bytes = MiMoV26NAXAttentionKeyRanges.projectedGroupedBytes( + plan: plan, maximumBufferBytes: maximumBufferBytes, + upperBound: budget.allocationPolicy.upperBound(byteCount:)), + bytes > 0 + else { return nil } + do { + let actual: MiMoV26NAXKeyRangeWork + if let work { + actual = work + } else { + actual = try createWork() + work = actual // native loan/root already installed before reserve + } + try tracking.requireWork() + let reservation: CBv2CheckpointReservation + do { reservation = try admission.reserveTransient(bytes: bytes) } catch { + // Optional additional C was refused BEFORE encoding. The + // unchanged grouped/scalar path was already admitted. + try tracking.requireWork() + return nil + } + actual.retain(reservation: reservation, bytes: bytes) + // Capture a late returned actual reservation before this veto. + try tracking.requireWork() + guard let groups = MiMoV26NAXAttentionKeyRanges.groupedSchedules(plan: plan), + !groups.isEmpty + else { + throw CBv2KVError.backendIneligible( + reason: "key-range projection changed after admission") + } + consumedLayers.insert(index) + actual.retainPlans(groups) + return .init(owner: actual, groups: groups) + } catch { + failure = error + work?.failCompletion() + return nil + } + } + + func close() throws { + closed = true + if let failure { throw failure } + try tracking.requireWork() + } +} + +struct MiMoV26NAXKeyRangeLayer { + let owner: MiMoV26NAXKeyRangeWork + let groups: [Int: MiMoV26NAXAttentionKeyRanges.GroupedSchedule] + func retain(_ arrays: [MLXArray]) { owner.retain(arrays: arrays) } +} + +/// One actual forward's extra state, using the existing native root+loan +/// machinery. All per-layer reservations are additive and explicitly released. +/// No destructor can authorize release: the native loan retains this owner +/// until the only successful post-fence retirement path ends that same loan. +final class MiMoV26NAXKeyRangeWork: @unchecked Sendable { + private let tracking: CBv2NativeShutdownState + private let queue: DispatchQueue + private let didRetire: (MiMoV26NAXKeyRangeWork) -> Void + private let failure: () -> Void + private let streams: [MLX.Stream] + private var loan: UUID? + private(set) var rootID: UInt64 = 0 + private(set) var requestIDs = Set() + private var reservations: [CBv2CheckpointReservation] = [] + private var arrays: [MLXArray] = [] + private var plans: [[Int: MiMoV26NAXAttentionKeyRanges.GroupedSchedule]] = [] + private(set) var reservedBytes = 0 + private(set) var completionFailed = false + private(set) var completed = false + private(set) var released = false + private var retirementQueued = false + // Failure/hold witness only, never a successful-completion replacement. + var beforeRequiredDrainForTesting: (() throws -> Void)? + + init( + tracking: CBv2NativeShutdownState, queue: DispatchQueue, + didRetire: @escaping (MiMoV26NAXKeyRangeWork) -> Void, + failure: @escaping () -> Void + ) throws { + self.tracking = tracking + self.queue = queue + self.didRetire = didRetire + self.failure = failure + let actual = StreamOrDevice.default.stream + streams = actual == Stream.cpu ? [actual] : [actual, Stream.cpu] + // Properties exist before self is retained by the actual native loan. + loan = try tracking.beginLoan(owner: self, duringDrain: true) + } + + func bindRoot(_ value: UInt64) { + precondition(rootID == 0 && value > 0) + rootID = value + } + func bindRequests(_ ids: Set) { + precondition(requestIDs.isEmpty) + requestIDs = ids + } + func retain(reservation: CBv2CheckpointReservation, bytes: Int) { + reservations.append(reservation) + let next = reservedBytes.addingReportingOverflow(bytes) + precondition(bytes > 0 && !next.overflow) + reservedBytes = next.partialValue + } + func retainPlans(_ value: [Int: MiMoV26NAXAttentionKeyRanges.GroupedSchedule]) { + plans.append(value) + } + func retain(arrays incoming: [MLXArray]) { arrays.append(contentsOf: incoming) } + var evaluationTargets: [MLXArray] { arrays } + var retainedArrayCount: Int { arrays.count } + + /// Called at the existing step completion boundary, before beginCommit. + /// Also covers custom-kernel outputs unused by the model's scalar readback. + func finishEvaluation() throws { + guard !completionFailed else { throw CBv2NativeShutdownError.operationClosed } + guard !completed else { return } + do { + try tracking.requireWork() + if arrays.isEmpty && reservations.isEmpty { + // A capacity-only refusal created no native arrays/encoding. + // Dispose only this genuine unstarted owner, not stock work. + completed = true + return + } + try withError { fault in + if !arrays.isEmpty { eval(arrays) } + try fault.check() + } + try requiredDrain() + completed = true + } catch { + failCompletion() + throw error + } + } + + /// Failed graph locals have unwound. Never evaluate a failed graph to + /// fabricate a successful completion; drain the actually captured streams. + func discardAfterDrain() throws { + guard !completionFailed else { throw CBv2NativeShutdownError.operationClosed } + guard !completed else { return } + do { + try requiredDrain() + completed = true + } catch { + failCompletion() + throw error + } + } + + private func requiredDrain() throws { + try tracking.requireWork() + try beforeRequiredDrainForTesting?() + for stream in streams { + try withError { fault in + stream.synchronize() + try fault.check() + } + } + try tracking.requireWork() + } + func failCompletion() { + completionFailed = true + if tracking.fail(.nativeWorkFailed) { failure() } + } + + /// The completed step has dropped its graph/native root holders. Queue on + /// that SAME engine queue so the enclosing metadata commit fully unwinds. + /// Actual array detach and reservation release occur outside the commit. + func retireCompletedGraph() { + guard completed, !completionFailed, !retirementQueued else { return } + retirementQueued = true + queue.async { [self] in + var detached: + ( + [MLXArray], [[Int: MiMoV26NAXAttentionKeyRanges.GroupedSchedule]], + [CBv2CheckpointReservation] + )? + guard + tracking.commitIfHealthy({ + // Claim metadata retirement atomically before a later fault + // can win. Moving references retains every actual owner; no + // array destructor/accounting runs inside this commit. + precondition(completed && !completionFailed && !released) + detached = (arrays, plans, reservations) + arrays = [] + plans = [] + reservations = [] + reservedBytes = 0 + released = true + }), var held = detached + else { return } + detached = nil // sever the second tuple/Array COW owner before credit + held.0.removeAll() + held.1.removeAll() + for reservation in held.2 { reservation.release() } + held.2.removeAll() + if let loan { tracking.endLoan(loan) } + didRetire(self) + } + } +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXMetalSources.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXMetalSources.swift new file mode 100644 index 0000000000..d73cee1fb5 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26NAXMetalSources.swift @@ -0,0 +1,1712 @@ +// SPDX-License-Identifier: Apache-2.0 AND MIT +// oMLX PR #3995, 47876fbc310fbb311cd382c4eba8572ec4368308. +// Modified for Swift: embedded pinned headers; MXFP4-only instantiations. +// Apple headers: MLX 3fa8f25e6451174d7b06be372c3a24272b77d88e. +/* +MIT License + +Copyright © 2023 Apple Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +enum MiMoV26NAXMetalSources { + static let scanHeader = #""" + using namespace metal; + + // Cuts the sorted rows into (row_start, expert, rows, 0) tiles of at most + // BM rows of one expert, expert-major (the tile order of mlx's segmented + // gather_qmm). One threadgroup: the run bounds of every expert are found in + // parallel over the rows, then a threadgroup scan of the per-expert tile + // counts gives each expert's first tile. At most max_tiles tiles are + // written (a guard for unsorted input, which the contract excludes). + template + METAL_FUNC void omlx_gqmm_tile_scan( + const device uint32_t* idx, + const constant int* params, + device uint32_t* tiles, + device uint32_t* tile_count, + threadgroup uint32_t* run_start, + threadgroup uint32_t* run_end, + threadgroup uint32_t* simd_tot, + const uint lid, + const uint tg_size, + const uint sg, + const uint lane) { + const int M = params[0]; + const int E = params[1]; + const uint32_t max_tiles = uint32_t(params[2]); + for (int e = int(lid); e < E; e += int(tg_size)) { + run_start[e] = 0; + run_end[e] = 0; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // Each thread walks 4 consecutive rows per step, with their neighbours + // (0xffffffff past either end, never a valid expert). + for (int g0 = 4 * int(lid); g0 < M; g0 += 4 * int(tg_size)) { + const int cnt = min(4, M - g0); + uint32_t v[6]; + v[0] = g0 > 0 ? idx[g0 - 1] : 0xffffffffu; + for (int j = 0; j < 4; j++) { + v[j + 1] = j < cnt ? idx[g0 + j] : 0xffffffffu; + } + v[5] = g0 + 4 < M ? idx[g0 + 4] : 0xffffffffu; + for (int j = 0; j < cnt; j++) { + const uint32_t e = v[j + 1]; + if (e < uint32_t(E)) { + if (v[j] != e) { + run_start[e] = uint32_t(g0 + j); + } + if (v[j + 2] != e) { + run_end[e] = uint32_t(g0 + j + 1); + } + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint n_simd = (tg_size + 31) / 32; + uint32_t running = 0; + for (int base = 0; base < E; base += int(tg_size)) { + const int e = base + int(lid); + uint32_t start = 0; + uint32_t cnt = 0; + if (e < E) { + start = run_start[e]; + const uint32_t end = run_end[e]; + cnt = end > start ? end - start : 0; + } + const uint32_t nt = (cnt + BM - 1) / BM; + const uint32_t local = simd_prefix_exclusive_sum(nt); + const uint32_t stot = simd_sum(nt); + if (lane == 0) { + simd_tot[sg] = stot; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + uint32_t prefix = 0; + uint32_t total = 0; + for (uint s = 0; s < n_simd; s++) { + const uint32_t v = simd_tot[s]; + prefix += (s < sg) ? v : 0; + total += v; + } + const uint32_t off = running + prefix + local; + for (uint32_t j = 0; j < nt && off + j < max_tiles; j++) { + const uint32_t r = start + j * BM; + *((device uint4*)tiles + off + j) = + uint4(r, uint32_t(e), min(uint32_t(BM), start + cnt - r), 0); + } + running += total; + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (lid == 0) { + tile_count[0] = min(running, max_tiles); + } + } + """# + + static let scanSource = #""" + threadgroup uint32_t run_start[MAXE]; + threadgroup uint32_t run_end[MAXE]; + threadgroup uint32_t simd_tot[32]; + omlx_gqmm_tile_scan( + idx, params, tiles, tile_count, run_start, run_end, simd_tot, + thread_index_in_threadgroup, threads_per_threadgroup.x, + simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + """# + + static let mlxHeader = #""" + // Copyright © 2025 Apple Inc. + + + #include + #include + #include + + // Copyright © 2024 Apple Inc. + + + #define STEEL_CONST static constant constexpr const + #define STEEL_PRAGMA_UNROLL _Pragma("clang loop unroll(full)") + #define STEEL_PRAGMA_NO_UNROLL _Pragma("clang loop unroll(disable)") + + // Copyright © 2024 Apple Inc. + + + #include + // Copyright © 2024 Apple Inc. + + + #include + + #pragma METAL internals : enable + + namespace metal { + + template + struct is_empty : metal::bool_constant<__is_empty(T)> {}; + + #ifdef __cpp_variable_templates + template + constexpr constant bool is_empty_v = is_empty::value; + #endif + + template + struct make_void { + typedef void type; + }; + + template + using void_t = typename make_void::type; + + template + struct is_static : metal::bool_constant>::value> {}; + + template + struct pointer_element {}; + + template + struct pointer_element { + using type = remove_cv_t; + }; + template + struct pointer_element { + using type = remove_cv_t; + }; + template + struct pointer_element { + using type = remove_cv_t; + }; + template + struct pointer_element { + using type = remove_cv_t; + }; + + template + using pointer_element_t = typename pointer_element>::type; + + } // namespace metal + + #pragma METAL internals : disable + + #pragma METAL internals : enable + + namespace mlx { + namespace steel { + + /////////////////////////////////////////////////////////////////////////////// + // Integral constant with casting + /////////////////////////////////////////////////////////////////////////////// + + template + struct integral_constant { + static constexpr constant T value = v; + using value_type = T; + using type = integral_constant; + + METAL_FUNC constexpr operator value_type() const thread noexcept { + return value; + } + }; + + template + using bool_constant = integral_constant; + using true_type = bool_constant; + using false_type = bool_constant; + + template + struct is_integral : bool_constant::value> {}; + + template + struct is_integral> + : bool_constant::value> {}; + + template + constexpr constant bool is_integral_v = is_integral::value; + + template + using Int = integral_constant; + + /////////////////////////////////////////////////////////////////////////////// + // Binary Operators on Integral constants + /////////////////////////////////////////////////////////////////////////////// + + #define integral_const_binop(__op__, __operator__) \ + template \ + METAL_FUNC constexpr auto __operator__( \ + integral_constant, integral_constant) { \ + constexpr auto res = tv __op__ uv; \ + using res_t = metal::remove_addrspace_t; \ + return integral_constant{}; \ + } + + integral_const_binop(+, operator+); + integral_const_binop(-, operator-); + integral_const_binop(*, operator*); + integral_const_binop(/, operator/); + + integral_const_binop(==, operator==); + integral_const_binop(!=, operator!=); + integral_const_binop(<, operator<); + integral_const_binop(>, operator>); + integral_const_binop(<=, operator<=); + integral_const_binop(>=, operator>=); + + integral_const_binop(&&, operator&&); + integral_const_binop(||, operator||); + + template >> + METAL_FUNC constexpr auto operator||(true_type, T) { + return true_type{}; + } + template >> + METAL_FUNC constexpr auto operator||(T, true_type) { + return true_type{}; + } + + template >> + METAL_FUNC constexpr auto operator&&(false_type, T) { + return false_type{}; + } + + template >> + METAL_FUNC constexpr auto operator&&(T, false_type) { + return false_type{}; + } + + // Dispatch utilities + template + void dispatch_bool(bool v, F f) { + if (v) { + f(true_type{}); + } else { + f(false_type{}); + } + } + + template + constexpr void const_for_loop(F f) { + if constexpr (start < stop) { + constexpr auto idx = Int{}; + f(idx); + const_for_loop(f); + } + } + + #undef integral_const_binop + + /////////////////////////////////////////////////////////////////////////////// + // Reduction operators + /////////////////////////////////////////////////////////////////////////////// + + template + METAL_FUNC constexpr T sum(T x) { + return x; + } + + template + METAL_FUNC constexpr auto sum(T x, Us... us) { + return x + sum(us...); + } + + } // namespace steel + } // namespace mlx + + #pragma METAL internals : disable + + + #include + + using namespace metal; + + /////////////////////////////////////////////////////////////////////////////// + // MMA helper + /////////////////////////////////////////////////////////////////////////////// + + namespace mlx { + namespace steel { + + /////////////////////////////////////////////////////////////////////////////// + // NAX Steel with new tiles + /////////////////////////////////////////////////////////////////////////////// + + struct BaseNAXFrag { + STEEL_CONST short kFragRows = 16; + STEEL_CONST short kFragCols = 16; + + STEEL_CONST short kElemsPerFrag = (kFragRows * kFragCols) / 32; + + STEEL_CONST short kElemRows = 2; + STEEL_CONST short kElemCols = 4; + + STEEL_CONST short kElemRowsJump = 8; + + static_assert( + kElemRows * kElemCols == kElemsPerFrag, + "MMAFrag shape is not consistent with MMAFrag size"); + + template + using dtype_frag_t = typename metal::vec; + + METAL_FUNC static short2 get_coord() { + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)); + const short fn = ((qid & 2) | (simd_lane_id & 1)) * 4; + return short2{fn, fm}; + } + + METAL_FUNC static short2 get_coord(short idx) { + const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort()); + const short qid = simd_lane_id >> 2; + const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)) + (idx >> 2) * 8; + const short fn = ((qid & 2) | (simd_lane_id & 1)) * 4 + idx % 4; + return short2{fn, fm}; + } + + template < + typename T, + typename SrcPtrType, + typename StrX, + typename StrY, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void load( + thread dtype_frag_t& dst, + SrcPtrType src, + StrX str_x, + StrY str_y, + OffX off_x = {}, + OffY off_y = {}) { + const short2 sc = get_coord(); + src += sc.y * str_x + sc.x * str_y; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + const auto r = off_x + i * kElemRowsJump; + const auto c = off_y; + + if constexpr (metal::is_same_v>) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[i * kElemCols + j] = static_cast(src[r * str_x + c + j]); + } + } else { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[i * kElemCols + j] = + static_cast(src[r * str_x + (c + j) * str_y]); + } + } + } + } + + template < + typename T, + typename SrcPtrType, + typename StrX, + typename StrY, + typename LimX, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void load_rows( + thread dtype_frag_t& dst, + SrcPtrType src, + StrX str_x, + StrY str_y, + LimX lim_x, + OffX off_x = {}, + OffY off_y = {}) { + const short2 sc = get_coord(); + src += sc.y * str_x + sc.x * str_y; + auto lx = lim_x - sc.y; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + const auto r = off_x + i * kElemRowsJump; + const auto c = off_y; + + if (r < lx) { + if constexpr (metal::is_same_v>) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[i * kElemCols + j] = static_cast(src[r * str_x + (c + j)]); + } + } else { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[i * kElemCols + j] = + static_cast(src[r * str_x + (c + j) * str_y]); + } + } + + } else { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[i * kElemCols + j] = T(0); + } + } + } + } + + template < + typename T, + typename SrcPtrType, + typename StrX, + typename StrY, + typename LimX, + typename LimY, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void load_safe( + thread dtype_frag_t& dst, + SrcPtrType src, + StrX str_x, + StrY str_y, + LimX lim_x, + LimY lim_y, + OffX off_x = {}, + OffY off_y = {}) { + const short2 sc = get_coord(); + src += sc.y * str_x + sc.x * str_y; + auto lx = lim_x - sc.y; + auto ly = lim_y - sc.x; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + const auto r = off_x + i * kElemRowsJump; + const auto c = off_y; + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + if ((r < lx) && ((c + j) < ly)) { + dst[i * kElemCols + j] = + static_cast(src[r * str_x + (c + j) * str_y]); + } else { + dst[i * kElemCols + j] = T(0); + } + } + } + } + + template < + typename T, + typename DstPtrType, + typename StrX, + typename StrY, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void store( + const thread dtype_frag_t& src, + DstPtrType dst, + StrX str_x, + StrY str_y, + OffX off_x = {}, + OffY off_y = {}) { + using U = pointer_element_t; + + const short2 sc = get_coord(); + dst += sc.y * str_x + sc.x * str_y; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + const auto r = off_x + i * kElemRowsJump; + const auto c = off_y; + + if constexpr (metal::is_same_v>) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[r * str_x + c + j] = static_cast(src[i * kElemCols + j]); + } + } else { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[r * str_x + (c + j) * str_y] = + static_cast(src[i * kElemCols + j]); + } + } + } + } + + template < + typename T, + typename DstPtrType, + typename StrX, + typename StrY, + typename LimX, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void store_rows( + const thread dtype_frag_t& src, + DstPtrType dst, + StrX str_x, + StrY str_y, + LimX lim_x, + OffX off_x = {}, + OffY off_y = {}) { + using U = pointer_element_t; + + const short2 sc = get_coord(); + dst += sc.y * str_x + sc.x * str_y; + auto lx = lim_x - sc.y; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + const auto r = off_x + i * kElemRowsJump; + const auto c = off_y; + + if (r < lx) { + if constexpr (metal::is_same_v>) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[r * str_x + c + j] = static_cast(src[i * kElemCols + j]); + } + } else { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + dst[r * str_x + (c + j) * str_y] = + static_cast(src[i * kElemCols + j]); + } + } + } + } + } + + template < + typename T, + typename DstPtrType, + typename StrX, + typename StrY, + typename LimX, + typename LimY, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void store_safe( + const thread dtype_frag_t& src, + DstPtrType dst, + StrX str_x, + StrY str_y, + LimX lim_x, + LimY lim_y, + OffX off_x = {}, + OffY off_y = {}) { + using U = pointer_element_t; + + const short2 sc = get_coord(); + dst += sc.y * str_x + sc.x * str_y; + auto lx = lim_x - sc.y; + auto ly = lim_y - sc.x; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + const auto r = off_x + i * kElemRowsJump; + const auto c = off_y; + + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + if (r < lx && (c + j) < ly) { + dst[r * str_x + (c + j) * str_y] = + static_cast(src[i * kElemCols + j]); + } + } + } + } + + template < + typename T, + typename DstPtrType, + typename StrX, + typename StrY, + typename StartX, + typename StopX, + typename StartY, + typename StopY, + typename OffX = Int<0>, + typename OffY = Int<0>> + METAL_FUNC static constexpr void store_slice( + const thread dtype_frag_t& src, + DstPtrType dst, + StrX str_x, + StrY str_y, + StartX start_x, + StopX stop_x, + StartY start_y, + StopY stop_y, + OffX off_x = Int<0>{}, + OffY off_y = Int<0>{}) { + using U = pointer_element_t; + + const short2 sc = get_coord(); + + const_for_loop<0, kElemRows, 1>([&](auto idx_row) { + const auto r = off_x + idx_row * Int{}; + if (r >= stop_x - sc.y || r < start_x - sc.y) { + return; + } + + const_for_loop<0, kElemCols, 1>([&](auto idx_col) { + const auto c = off_y + idx_col; + if (c >= stop_y - sc.x || c < start_y - sc.x) { + return; + } + + const auto src_idx = idx_row * Int{} + idx_col; + dst[(r + sc.y) * str_x + (c + sc.x) * str_y] = + static_cast(src[src_idx]); + }); + }); + } + + template + METAL_FUNC static constexpr void row_reduce( + thread const dtype_frag_t& inp_vals, + thread T* reduced_vals) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + T thr_reduce = Op::apply( + Op::apply(inp_vals[i * kElemCols + 0], inp_vals[i * kElemCols + 1]), + Op::apply(inp_vals[i * kElemCols + 2], inp_vals[i * kElemCols + 3])); + + T qgr_reduce = simd_shuffle_xor(thr_reduce, ushort(1)); + qgr_reduce = Op::apply(thr_reduce, qgr_reduce); + + T sgr_reduce = simd_shuffle_xor(qgr_reduce, ushort(8)); + sgr_reduce = Op::apply(qgr_reduce, sgr_reduce); + + reduced_vals[i] = Op::apply(reduced_vals[i], sgr_reduce); + } + } + + template + METAL_FUNC static constexpr void row_bin_op( + thread dtype_frag_t& inp_vals, + thread T* row_vals) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemRows; i++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kElemCols; j++) { + inp_vals[i * kElemCols + j] = + Op::apply(inp_vals[i * kElemCols + j], row_vals[i]); + } + } + } + + template < + typename CType, + typename AType, + typename BType, + bool transpose_a = false, + bool transpose_b = false> + METAL_FUNC static constexpr void mma( + thread dtype_frag_t& Cn0, + thread dtype_frag_t& Cn1, + const thread dtype_frag_t& A, + metal::bool_constant, + const thread dtype_frag_t& Bn0, + const thread dtype_frag_t& Bn1, + metal::bool_constant) { + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, + 32, + 16, + transpose_a, + transpose_b, + true, + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate); + + // Create matmul op + mpp::tensor_ops::matmul2d gemm_op; + + // Create matmul operands in registers + auto ct_a = + gemm_op + .template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + + // Create matmul output in register + auto ct_c = gemm_op.template get_destination_cooperative_tensor< + metal::remove_addrspace_t, + metal::remove_addrspace_t, + CType>(); + + // Load A in to left operand registers + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + ct_a[i] = A[i]; + } + + // Load B into right operand registers + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + ct_b[i] = Bn0[i]; + ct_b[kElemsPerFrag + i] = Bn1[i]; + } + + // Load C into output registers (op handles accumulation) + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + ct_c[i] = Cn0[i]; + ct_c[kElemsPerFrag + i] = Cn1[i]; + } + + // Do matmul + gemm_op.run(ct_a, ct_b, ct_c); + + // Copy out results + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + Cn0[i] = ct_c[i]; + Cn1[i] = ct_c[kElemsPerFrag + i]; + } + } + + template < + typename CType, + typename AType, + typename BType, + bool transpose_a = false, + bool transpose_b = false> + METAL_FUNC static constexpr void mma( + thread dtype_frag_t& Cm0, + thread dtype_frag_t& Cm1, + const thread dtype_frag_t& Am0, + const thread dtype_frag_t& Am1, + metal::bool_constant, + const thread dtype_frag_t& B, + metal::bool_constant) { + // Create Matmul descriptor + constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 16, + 32, + 16, + transpose_a, + transpose_b, + true, + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate); + + // Create matmul op + mpp::tensor_ops::matmul2d gemm_op; + + // Create matmul operands in registers + auto ct_a = + gemm_op + .template get_left_input_cooperative_tensor(); + auto ct_b = + gemm_op + .template get_right_input_cooperative_tensor(); + + // Create matmul output in register + auto ct_c = gemm_op.template get_destination_cooperative_tensor< + metal::remove_addrspace_t, + metal::remove_addrspace_t, + CType>(); + + // Load A in to left operand registers + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + ct_a[i] = Am0[i]; + ct_a[kElemsPerFrag + i] = Am1[i]; + } + + // Load B into right operand registers + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + ct_b[i] = B[i]; + } + + // Load C into output registers (op handles accumulation) + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + ct_c[i] = Cm0[i]; + ct_c[kElemsPerFrag + i] = Cm1[i]; + } + + // Do matmul + gemm_op.run(ct_a, ct_b, ct_c); + + // Copy out results + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kElemsPerFrag; i++) { + Cm0[i] = ct_c[i]; + Cm1[i] = ct_c[kElemsPerFrag + i]; + } + } + }; + + template < + typename T, + short kTileRows_, + short kTileCols_, + class NAXFrag_ = BaseNAXFrag> + struct NAXTile { + using NAXFrag_t = NAXFrag_; + using elem_type = T; + + STEEL_CONST short kFragRows = NAXFrag_t::kFragRows; + STEEL_CONST short kFragCols = NAXFrag_t::kFragCols; + STEEL_CONST short kElemsPerFrag = NAXFrag_t::kElemsPerFrag; + + STEEL_CONST short kTileRows = kTileRows_; + STEEL_CONST short kTileCols = kTileCols_; + + STEEL_CONST short kRows = kTileRows * kFragRows; + STEEL_CONST short kCols = kTileCols * kFragCols; + + STEEL_CONST short kNumFrags = kTileRows * kTileCols; + STEEL_CONST short kElemsPerTile = kNumFrags * kElemsPerFrag; + + STEEL_CONST short kFragThrRows = NAXFrag_t::kElemRows; + STEEL_CONST short kFragThrCols = NAXFrag_t::kElemCols; + STEEL_CONST short kFragRowsJump = NAXFrag_t::kElemRowsJump; + + STEEL_CONST short kRowsPerThread = kTileRows * NAXFrag_t::kElemRows; + STEEL_CONST short kColsPerThread = kTileCols * NAXFrag_t::kElemCols; + + typedef typename NAXFrag_t::template dtype_frag_t frag_type; + + frag_type val_frags[kNumFrags]; // = {frag_type(0)}; + + METAL_FUNC NAXTile() thread {} + + METAL_FUNC constexpr void clear() thread { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kNumFrags; ++i) { + val_frags[i] = frag_type(0); + } + } + + METAL_FUNC constexpr thread frag_type& frag_at(const short i, const short j) + thread { + return val_frags[i * kTileCols + j]; + } + + METAL_FUNC constexpr const thread frag_type& frag_at( + const short i, + const short j) const thread { + return val_frags[i * kTileCols + j]; + } + + template + METAL_FUNC constexpr thread frag_type& frag_at() thread { + return val_frags[i * kTileCols + j]; + } + + template + METAL_FUNC constexpr const thread frag_type& frag_at() const thread { + return val_frags[i * kTileCols + j]; + } + + template + METAL_FUNC constexpr thread frag_type& frag_at( + const short i, + const short j, + metal::bool_constant) thread { + if constexpr (transpose) { + return frag_at(j, i); + } else { + return frag_at(i, j); + } + } + + template + METAL_FUNC constexpr const thread frag_type& frag_at( + const short i, + const short j, + metal::bool_constant) const thread { + if constexpr (transpose) { + return frag_at(j, i); + } else { + return frag_at(i, j); + } + } + + template + METAL_FUNC constexpr thread frag_type& frag_at() thread { + if constexpr (transpose) { + return frag_at(); + } else { + return frag_at(); + } + } + + template + METAL_FUNC constexpr const thread frag_type& frag_at() const thread { + if constexpr (transpose) { + return frag_at(); + } else { + return frag_at(); + } + } + + METAL_FUNC thread elem_type* elems() thread { + return reinterpret_cast(val_frags); + } + + METAL_FUNC const thread elem_type* elems() const thread { + return reinterpret_cast(val_frags); + } + + template + METAL_FUNC void row_reduce( + thread metal::vec& vals) const thread { + auto vptr = (thread T*)(&vals); + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kTileCols; ++j) { + NAXFrag_t::template row_reduce( + frag_at(i, j), &vptr[i * kFragThrRows]); + } + } + } + + template + METAL_FUNC void row_bin_op( + thread metal::vec& vals) thread { + auto vptr = (thread T*)(&vals); + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kTileCols; ++j) { + NAXFrag_t::template row_bin_op( + frag_at(i, j), &vptr[i * kFragThrRows]); + } + } + } + + template + METAL_FUNC void load(const threadgroup U* src) thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::load( + frag_at(), + src, + Int{}, + Int{}, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void store(threadgroup U* dst) const thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::store( + frag_at(), + dst, + Int{}, + Int{}, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void load(const device U* src, const int ld) thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::load( + frag_at(), + src, + ld, + Int<1>{}, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void store(device U* dst, const int ld) const thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::store( + frag_at(), + dst, + ld, + Int<1>{}, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void + load_rows(const device U* src, const int ld, const short n_rows) thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::load_rows( + frag_at(), + src, + ld, + Int<1>{}, + n_rows, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void load_safe( + const device U* src, + const int ld, + const short2 src_tile_dims) thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::load_safe( + frag_at(), + src, + ld, + Int<1>{}, + src_tile_dims.y, + src_tile_dims.x, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void store_rows(device U* dst, const int ld, const short n_rows) + const thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::store_rows( + frag_at(), + dst, + ld, + Int<1>{}, + n_rows, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void store_safe( + device U* dst, + const int ld, + const short2 dst_tile_dims) const thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::store_safe( + frag_at(), + dst, + ld, + Int<1>{}, + dst_tile_dims.y, + dst_tile_dims.x, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + + template + METAL_FUNC void store_slice( + device U* dst, + const int ld, + const short2 start, + const short2 stop) const thread { + const_for_loop<0, kTileRows, 1>([&](auto idx_row) { + const_for_loop<0, kTileCols, 1>([&](auto idx_col) { + NAXFrag_t::store_slice( + frag_at(), + dst, + ld, + Int<1>{}, + start.y, + stop.y, + start.x, + stop.x, + idx_row * Int{}, + idx_col * Int{}); + }); + }); + } + }; + + template < + class CTile, + class ATile, + class BTile, + bool transpose_a, + bool transpose_b> + METAL_FUNC void tile_matmad_nax( + thread CTile& C, + thread ATile& A, + metal::bool_constant, + thread BTile& B, + metal::bool_constant) { + // Static checks + constexpr short TMa = transpose_a ? ATile::kTileCols : ATile::kTileRows; + constexpr short TM = CTile::kTileRows; + static_assert(TMa == TM, "MXU tile matmul: M dimensions do not match"); + + constexpr short TNb = transpose_b ? BTile::kTileRows : BTile::kTileCols; + constexpr short TN = CTile::kTileCols; + static_assert(TNb == TN, "MXU tile matmul: N dimensions do not match"); + + constexpr short TKa = transpose_a ? ATile::kTileRows : ATile::kTileCols; + constexpr short TK = transpose_b ? BTile::kTileCols : BTile::kTileRows; + static_assert(TKa == TK, "MXU tile matmul: K dimensions do not match"); + + constexpr auto ta = metal::bool_constant{}; + constexpr auto tb = metal::bool_constant{}; + + if constexpr (TN == 1 && TM % 2 == 0) { + STEEL_PRAGMA_UNROLL + for (short mm = 0; mm < TM; mm += 2) { + STEEL_PRAGMA_UNROLL + for (short nn = 0; nn < TN; ++nn) { + STEEL_PRAGMA_UNROLL + for (short kk = 0; kk < TK; ++kk) { + CTile::NAXFrag_t::mma( + C.frag_at(mm, nn), + C.frag_at(mm + 1, nn), + A.frag_at(mm, kk, ta), + A.frag_at(mm + 1, kk, ta), + metal::bool_constant{}, + B.frag_at(kk, nn, tb), + metal::bool_constant{}); + } + } + } + } else if constexpr (TN % 2 == 0) { + STEEL_PRAGMA_UNROLL + for (short mm = 0; mm < TM; ++mm) { + STEEL_PRAGMA_UNROLL + for (short nn = 0; nn < TN; nn += 2) { + STEEL_PRAGMA_UNROLL + for (short kk = 0; kk < TK; ++kk) { + CTile::NAXFrag_t::mma( + C.frag_at(mm, nn), + C.frag_at(mm, nn + 1), + A.frag_at(mm, kk, ta), + metal::bool_constant{}, + B.frag_at(kk, nn, tb), + B.frag_at(kk, nn + 1, tb), + metal::bool_constant{}); + } + } + } + } + } + + } // namespace steel + } // namespace mlx + + + constant constexpr float F8E4M3_MAX = 448.0f; + constant constexpr float F4E2M1_MAX = 6.0f; + + struct fp4_e2m1 { + fp4_e2m1(float x) thread { + if (metal::isnan(x)) { + bits = 0x7; + return; + } + + const uint8_t sign_bit = (metal::signbit(x)) ? 0x8 : 0x0; + x = metal::abs(x); + + if (x > 5.0f) { + bits = 0x7; + } else if (x >= 3.5f) { + bits = 0x6; + } else if (x > 2.5f) { + bits = 0x5; + } else if (x >= 1.75f) { + bits = 0x4; + } else if (x > 1.25f) { + bits = 0x3; + } else if (x >= 0.75f) { + bits = 0x2; + } else if (x > 0.25f) { + bits = 0x1; + } else { + bits = 0x0; + } + bits |= sign_bit; + } + + operator float16_t() thread { + half converted = as_type(ushort((bits & 7) << 9)); + converted *= 16384.0; + return bits & 8 ? -converted : converted; + } + + operator float() thread { + return static_cast(this->operator float16_t()); + } + + operator bfloat16_t() thread { + return static_cast(this->operator float16_t()); + } + + uint8_t bits; + }; + + struct fp8_e8m0 { + fp8_e8m0(float x) thread { + if (!metal::isfinite(x)) { + bits = 0xFF; + return; + } + if (x < 0.0f) { + bits = 0x00; + return; + } + float le = metal::log2(x); + int n = int(metal::round(le)); + + n = n < -127 ? -127 : n; + n = n > 127 ? 127 : n; + bits = static_cast(n + 127); + } + + operator bfloat16_t() thread { + uint16_t out = (bits == 0 ? 0x40 : (static_cast(bits) << 7)); + return as_type(out); + } + + operator float() thread { + uint32_t out = (bits == 0 ? 0x400000 : (static_cast(bits) << 23)); + return as_type(out); + } + + uint8_t bits; + }; + + + """# + + static let matmulHeader = #""" + using namespace metal; + using namespace mlx::steel; + + namespace omlx_gqmm { + + STEEL_CONST int kBM = 64; + STEEL_CONST int kBN = 64; + STEEL_CONST int kBK = 64; + STEEL_CONST int kWM = 2; + STEEL_CONST int kWN = 2; + STEEL_CONST int kThreads = kWM * kWN * 32; + STEEL_CONST short kSK = 32; + STEEL_CONST short kSM = kBM / kWM; + STEEL_CONST short kSN = kBN / kWN; + STEEL_CONST short kTM = kSM / 16; + STEEL_CONST short kTN = kSN / 16; + STEEL_CONST short kTK = kSK / 16; + // Every loader thread dequantizes kVPT consecutive values of one weight row + // (the split of mlx's QuantizedBlockLoader for a 64x64 tile). + STEEL_CONST int kVPT = kBN * kBK / kThreads; + STEEL_CONST int kTPR = kBK / kVPT; + + // MXFP4: e2m1 values times the e8m0 group scale, dequantized to bfloat like + // mlx's fp QuantizedBlockLoader (Wtype = bfloat). + template + struct Mxfp4Q { + using WT = bfloat; + STEEL_CONST int kBits = 4; + STEEL_CONST int kGroup = GS; + const device uint8_t* scales; + float s; + + METAL_FUNC void advance(const size_t n) thread { + scales += n; + } + METAL_FUNC void load_params(const int g) thread { + uint8_t sb = scales[g]; + s = float(static_cast(*(thread fp8_e8m0*)(&sb))); + } + METAL_FUNC WT dq(const uint32_t q) const thread { + uint8_t qb = uint8_t(q); + return static_cast(s * float(*(thread fp4_e2m1*)(&qb))); + } + }; + + // Weight-tile loader: thread lid owns row lid / kTPR of the BN x BK tile + // and the kVPT values from column (lid % kTPR) * kVPT. fetch() reads the + // packed words and group parameters of one K step, store() dequantizes + // them into threadgroup memory (row stride BKP). + template + struct TileLoader { + using WT = typename Q::WT; + STEEL_CONST int kBits = Q::kBits; + STEEL_CONST int kWords = kVPT * kBits / 32; + STEEL_CONST int kPer = 32 / kBits; + STEEL_CONST uint32_t kMask = (1u << kBits) - 1u; + static_assert(kWords * 32 == kVPT * kBits, "whole words per thread"); + static_assert(Q::kGroup % kVPT == 0, "one group per thread and K step"); + + const device uint32_t* src; + Q q; + const short row; + const short col; + uint32_t raw[kWords]; + + METAL_FUNC TileLoader( + const device uint8_t* w_tile, + const int K, + thread const Q& q_, + const uint lid) thread + : q(q_), row(short(lid / kTPR)), col(short((lid % kTPR) * kVPT)) { + src = (const device uint32_t*)(w_tile + size_t(row) * (K * kBits / 8) + + col * kBits / 8); + q.advance(size_t(row) * (K / Q::kGroup)); + } + + METAL_FUNC void fetch(const int kb) thread { + const device uint32_t* p = src + kb * (kBK * kBits / 32); + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kWords; i++) { + raw[i] = p[i]; + } + q.load_params((kb * kBK + col) / Q::kGroup); + } + + METAL_FUNC void store(threadgroup WT* Ws) const thread { + threadgroup WT* dst = Ws + row * (kBK + 16 / sizeof(WT)) + col; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kWords; i++) { + vec v; + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kPer; j++) { + v[j] = q.dq((raw[i] >> (kBits * j)) & kMask); + } + *(threadgroup vec*)(dst + i * kPer) = v; + } + } + + METAL_FUNC void zero(threadgroup WT* Ws) const thread { + threadgroup WT* dst = Ws + row * (kBK + 16 / sizeof(WT)) + col; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kVPT; i++) { + dst[i] = WT(0); + } + } + }; + + // seg: mlx's segmented sorted gather kernel (affine_gather_qmm_rhs_seg_nax / + // fp_gather_qmm_rhs_seg_nax): one single-expert BM x BN tile per + // threadgroup, the weight tile dequantized into threadgroup memory between + // two barriers per K step, then tile_matmad_nax. K tail: both operands are + // zero past K. N tail: weight rows past N are zero, stores are bounded. + template + METAL_FUNC void gather_seg( + const device T* x, + const device uint8_t* w, + thread Q& q, + const device uint32_t* tiles, + device T* y, + const int N, + const int K, + threadgroup typename Q::WT* Ws, + const uint3 tid, + const uint sgid, + const uint lane) { + using WT = typename Q::WT; + constexpr int BKP = kBK + 16 / sizeof(WT); + const uint4 desc = *((const device uint4*)tiles + tid.y); + const int row_start = int(desc.x); + const uint32_t expert = desc.y; + const int rows = int(desc.z); + + const int K_w = K * Q::kBits / 8; + const int K_g = K / Q::kGroup; + const int K_it = K / kBK; + const int y_col = int(tid.x) * kBN; + const short tgp_bn = ALIGN_N ? short(kBN) : short(min(kBN, N - y_col)); + const int k_remain = K - K_it * kBK; + + const size_t w_row = size_t(expert) * N + y_col; + q.advance(w_row * K_g); + TileLoader loader(w + w_row * K_w, K, q, sgid * 32 + lane); + const bool row_live = ALIGN_N || loader.row < tgp_bn; + + x += size_t(row_start) * K; + y += size_t(row_start) * N + y_col; + + const short tm = kSM * short(sgid / kWN); + const short tn = kSN * short(sgid % kWN); + const short sgp_sm = short(min(int(kSM), max(0, rows - int(tm)))); + const short sgp_sn = + ALIGN_N ? kSN : short(min(int(kSN), max(0, N - (y_col + tn)))); + const bool sg_active = sgp_sm > 0; + + NAXTile Dtile; + Dtile.clear(); + const device T* xn = x + tm * K; + + dispatch_bool(sgp_sm == kSM, [&](auto kAlignedM) { + for (int k = 0; k < K_it; k++) { + threadgroup_barrier(mem_flags::mem_threadgroup); + if (row_live) { + loader.fetch(k); + loader.store(Ws); + } else { + loader.zero(Ws); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + STEEL_PRAGMA_NO_UNROLL + for (int kk1 = 0; kk1 < kBK; kk1 += kSK) { + if (sg_active) { + NAXTile Btile; + if constexpr (kAlignedM.value) { + NAXTile Atile; + + volatile int compiler_barrier; + + Atile.load(xn + kk1, K); + Btile.template load(Ws + tn * BKP + kk1); + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); + + (void)compiler_barrier; + } else { + // Partial tile: skip the 16-row fragments without rows (the + // tensor ops of the others are the ones tile_matmad_nax issues). + Btile.template load(Ws + tn * BKP + kk1); + STEEL_PRAGMA_UNROLL + for (short mm = 0; mm < kTM; mm++) { + if (mm * 16 < sgp_sm) { + NAXTile Arow; + Arow.load_safe( + xn + mm * 16 * K + kk1, K, short2(kSK, sgp_sm - mm * 16)); + STEEL_PRAGMA_UNROLL + for (short nn = 0; nn < kTN; nn += 2) { + STEEL_PRAGMA_UNROLL + for (short kk = 0; kk < kTK; kk++) { + BaseNAXFrag::mma( + Dtile.frag_at(mm, nn), + Dtile.frag_at(mm, nn + 1), + Arow.frag_at(0, kk), + metal::bool_constant{}, + Btile.frag_at(nn, kk), + Btile.frag_at(nn + 1, kk), + metal::bool_constant{}); + } + } + } + } + } + } + } + xn += kBK; + } + + if (!ALIGN_K) { + threadgroup_barrier(mem_flags::mem_threadgroup); + if (row_live && loader.col < k_remain) { + loader.fetch(K_it); + loader.store(Ws); + } else { + loader.zero(Ws); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + STEEL_PRAGMA_NO_UNROLL + for (int kk1 = 0; kk1 < kBK; kk1 += kSK) { + if (sg_active) { + NAXTile Atile; + NAXTile Btile; + + volatile int compiler_barrier; + + const short psk = short(min(int(kSK), max(0, k_remain - kk1))); + Atile.load_safe(xn + kk1, K, short2(psk, sgp_sm)); + Btile.template load(Ws + tn * BKP + kk1); + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); + + (void)compiler_barrier; + } + } + } + + if (kAlignedM.value && sgp_sn == kSN) { + Dtile.store(y + tm * N + tn, N); + } else if (sg_active) { + Dtile.store_safe(y + tm * N + tn, N, short2(sgp_sn, sgp_sm)); + } + }); + } + + // db: the same tiles and arithmetic with double-buffered weight tiles: the + // packed words of step k + 1 are fetched before the tensor ops of step k and + // dequantized into the other buffer after them, so each K step has a single + // barrier. Activation fragments are read straight from device memory (rows + // past the tile are clamped to its last row and never stored) and 16-row + // fragments without rows of the tile are skipped. Requires K % 64 == 0 and + // N % 64 == 0. + template + METAL_FUNC void gather_db( + const device T* x, + const device uint8_t* w, + thread Q& q, + const device uint32_t* tiles, + device T* y, + const int N, + const int K, + threadgroup typename Q::WT* Ws, + const uint3 tid, + const uint sgid, + const uint lane) { + using WT = typename Q::WT; + constexpr int BKP = kBK + 16 / sizeof(WT); + constexpr int kTile = kBN * BKP; + const uint4 desc = *((const device uint4*)tiles + tid.y); + const int row_start = int(desc.x); + const uint32_t expert = desc.y; + const int tile_rows = int(desc.z); + + const int K_w = K * Q::kBits / 8; + const int K_g = K / Q::kGroup; + const int K_it = K / kBK; + const int y_col = int(tid.x) * kBN; + + const size_t w_row = size_t(expert) * N + y_col; + q.advance(w_row * K_g); + TileLoader loader(w + w_row * K_w, K, q, sgid * 32 + lane); + + const int m0 = kSM * int(sgid / kWN); + const int rows = min(int(kSM), tile_rows - m0); + const device T* xs = + x + size_t(row_start + max(0, min(m0, tile_rows - 1))) * K; + + const short2 sc = BaseNAXFrag::get_coord(); + int x_off[kTM][2]; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kTM; i++) { + STEEL_PRAGMA_UNROLL + for (short h = 0; h < 2; h++) { + const int r = min(int(i * 16 + sc.y + h * 8), max(rows, 1) - 1); + x_off[i][h] = r * K + sc.x; + } + } + const short m_frags = rows > 0 ? short((rows + 15) / 16) : short(0); + const threadgroup WT* wsg = Ws + (sgid % kWN) * kSN * BKP; + + NAXTile D; + D.clear(); + + loader.fetch(0); + loader.store(Ws); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int kb = 0; kb < K_it; kb++) { + const bool more = kb + 1 < K_it; + if (more) { + loader.fetch(kb + 1); + } + const threadgroup WT* wb = wsg + (kb & 1) * kTile; + STEEL_PRAGMA_UNROLL + for (short kk1 = 0; kk1 < kBK; kk1 += kSK) { + NAXTile Btile; + Btile.template load(wb + kk1); + const int k = kb * kBK + kk1; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < kTM; i++) { + if (i < m_frags) { + NAXTile Atile; + STEEL_PRAGMA_UNROLL + for (short h = 0; h < 2; h++) { + const device T* xp = xs + x_off[i][h] + k; + const vec a0 = *(const device vec*)(xp); + const vec a1 = *(const device vec*)(xp + 16); + STEEL_PRAGMA_UNROLL + for (short c = 0; c < 4; c++) { + Atile.frag_at(0, 0)[h * 4 + c] = a0[c]; + Atile.frag_at(0, 1)[h * 4 + c] = a1[c]; + } + } + STEEL_PRAGMA_UNROLL + for (short kk = 0; kk < 2; kk++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < kTN; j += 2) { + BaseNAXFrag::mma( + D.frag_at(i, j), + D.frag_at(i, j + 1), + Atile.frag_at(0, kk), + metal::bool_constant{}, + Btile.frag_at(j, kk), + Btile.frag_at(j + 1, kk), + metal::bool_constant{}); + } + } + } + } + } + if (more) { + loader.store(Ws + ((kb + 1) & 1) * kTile); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + device T* yb = y + size_t(row_start + m0) * N + y_col + kSN * (sgid % kWN); + if (rows >= kSM) { + D.store(yb, N); + } else if (rows > 0) { + D.store_safe(yb, N, short2(kSN, short(rows))); + } + } + + } // namespace omlx_gqmm + """# + + static let matmulSource = #""" + using Q = omlx_gqmm::Mxfp4Q; + constexpr int BKP = omlx_gqmm::kBK + 16 / sizeof(bfloat); + threadgroup bfloat Ws[(SCHED == 1 ? 2 : 1) * omlx_gqmm::kBN * BKP]; + if (threadgroup_position_in_grid.y >= tile_count[0]) { + return; + } + Q q{scales, 0.0f}; + if constexpr (SCHED == 1) { + omlx_gqmm::gather_db( + x, (const device uint8_t*)w, q, tiles, y, params[0], params[1], + Ws, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, + thread_index_in_simdgroup); + } else { + omlx_gqmm::gather_seg( + x, (const device uint8_t*)w, q, tiles, y, params[0], params[1], + Ws, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, + thread_index_in_simdgroup); + } + """# + +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26PrefillPolicy.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26PrefillPolicy.swift new file mode 100644 index 0000000000..ae91d36ff6 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26PrefillPolicy.swift @@ -0,0 +1,126 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX + +/// Policy only. Actual native geometry, device and owned scratch admission +/// remain mandatory at the existing attention/grouped dispatch boundaries. +public enum MiMoV26PrefillPolicy { + public static let attentionEnvironmentKey = "DARKBLOOM_MIMO_V26_NAX_ATTENTION" + public static let groupedEnvironmentKey = "DARKBLOOM_MIMO_BLOCK_BATCH_PREFILL" + + public enum ProcessControlMismatch: Error, Sendable, Equatable { + case incompatible(environmentKey: String, requested: Bool, latched: Bool) + } + + /// These are the exact cached constants read by kernel dispatch. They + /// intentionally do not resample ProcessInfo after a control is latched. + public static var latchedAttentionEnabled: Bool { MiMoV26NAXAttention.requested } + public static var latchedGroupingEnabled: Bool { MiMoV26BlockBatchAttention.requested } + + /// Injected per-factory dictionaries cannot reconfigure process-wide + /// kernels. Unset keys inherit the actual latches; contradictory explicit + /// controls fail recoverably instead of reporting a width-only rollback. + public static func validateProcessControls(environment: [String: String]) throws { + try validateInjectedControls( + environment: environment, + latchedAttention: latchedAttentionEnabled, latchedGrouping: latchedGroupingEnabled) + } + + // Scalar seam for the complete truth table. Production always supplies + // the real dispatch constants through validateProcessControls above. + static func validateInjectedControls( + environment: [String: String], + latchedAttention: Bool, latchedGrouping: Bool + ) throws { + for (key, latched) in [ + (attentionEnvironmentKey, latchedAttention), + (groupedEnvironmentKey, latchedGrouping), + ] { + guard let value = environment[key] else { continue } + let requested = isEnabled(value) + guard requested == latched else { + throw ProcessControlMismatch.incompatible( + environmentKey: key, requested: requested, latched: latched) + } + } + } + + public static func isEnabled(_ value: String?) -> Bool { + guard let value else { return true } + return ["1", "true", "yes", "on", "auto"].contains( + value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()) + } + + /// Caller must opt into a default profile. An explicit SDK scheduler + /// configuration is never widened merely by constructing an EngineV2. + static func widerWidths( + requested: Bool, naxAvailable: Bool, + physicalMemoryBytes: UInt64, maximumTokens: Int?, originalWidth: Int + ) -> [Int] { + guard requested, naxAvailable, physicalMemoryBytes >= 128 * 1024 * 1024 * 1024, + originalWidth > 0, let maximumTokens, + maximumTokens == 4096 || maximumTokens == 8192 + else { return [] } + return [8192, 4096].filter { $0 <= maximumTokens && $0 > originalWidth } + } + + /// Replaces only the previous authentic MTP fixed term. All caller, + /// target, projection and reserve charges remain in `current` untouched. + /// A wider declaration may not lower the old MTP charge. + static func replacingMTPCharge(current: Int, previous: Int, replacement: Int) -> Int? { + guard previous >= 0, current >= previous, replacement >= previous else { return nil } + let sum = (current - previous).addingReportingOverflow(replacement) + return sum.overflow ? nil : sum.partialValue + } + + /// Returns a new value only; refused candidates cannot change the + /// caller's prior Admission configuration or its MTP charge. + static func addingGroupedCharge( + to original: AdmissionV2.Config, + scratchBytes: Int, capacityBytes: Int + ) -> AdmissionV2.Config? { + guard original.fixedBytesPerRequest >= 0, scratchBytes > 0, + let total = CBv2MTPBoundedAdmission.add(original.fixedBytesPerRequest, scratchBytes), + total < capacityBytes + else { return nil } + var candidate = original + candidate.fixedBytesPerRequest = total + return candidate + } +} + +/// Immutable loaded-model metadata, not permission to allocate or to assert +/// scratch admission. The existing budget installer proves the cache owners. +package protocol MiMoV26PrefillDefaultProviding: AnyObject { + var cbv2MiMoAutomaticPrefillMaximumTokens: Int? { get } +} + +extension SwitchGLU { + /// The actual existing custom gather can cover all three expert + /// projections above 32768 sorted rows. No test eval or tensor copy. + package var mimoV26SupportsOversizedPrefillGather: Bool { + guard mimoV26NAXGather, MiMoV26NAXGatherQMM.requested, + inputDims == 4096, hiddenDims == 2048, numExperts == 256 + else { return false } + func matches(_ projection: SwitchLinear?, input: Int, output: Int) -> Bool { + guard let p = projection as? QuantizedSwitchLinear, + ObjectIdentifier(type(of: p)) == ObjectIdentifier(QuantizedSwitchLinear.self), + p.bias == nil, p.biases == nil, p.mode == .mxfp4, + p.bits == 4, p.groupSize == 32, p.weight.dtype == .uint32, + p.scales.dtype == .uint8, + p.weight.shape == [256, output, input / 8], + p.scales.shape == [256, output, input / 32] + else { return false } + return true + } + let gateUpMatches: Bool + if let gateUpProj { + gateUpMatches = matches(gateUpProj, input: 4096, output: 4096) + } else { + gateUpMatches = + matches(gateProj, input: 4096, output: 2048) + && matches(upProj, input: 4096, output: 2048) + } + return gateUpMatches && matches(downProj, input: 2048, output: 4096) + } +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26RectangularDenseAdmission.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26RectangularDenseAdmission.swift new file mode 100644 index 0000000000..a39bd2a89b --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26RectangularDenseAdmission.swift @@ -0,0 +1,104 @@ +// Copyright © 2026 Eigen Labs. +// MiMo-only target scratch; neither a new ledger nor a native completion owner. +import Foundation +import MLX + +package struct MiMoV26RectangularDenseScratchSpec: Sendable { + package let buffers: [CBv2MTPFixedBufferSpec] + package let hostBytes: Int + package init(buffers: [CBv2MTPFixedBufferSpec], hostBytes: Int) { + self.buffers = buffers + self.hostBytes = hostBytes + } +} + +package protocol MiMoV26RectangularDenseAllocatingModel: AnyObject { + /// Nil means the optional candidate is not requested/supported. + /// Metadata only: no allocation, native query, eval or model alias. + var cbv2MiMoRectangularDenseScratch: MiMoV26RectangularDenseScratchSpec? { get } +} + +/// Constructed only by EngineV2, after pricing all independent allocations. +/// The same fixed charge is added to actual Admission before requests exist. +/// Scalar identities do not retain a model/backend/cache alias. +// Lock protects the sole mutable diagnostic counter; all authority is immutable. +package final class MiMoV26RectangularDenseBudget: @unchecked Sendable { + package let engineID: UUID + package let modelIdentity, backendIdentity, cacheProviderIdentity: ObjectIdentifier + package let fixedRequestBytes: Int + private let lock = NSLock() + private var activationCount = 0 + package var submittedCalls: Int { lock.withLock { activationCount } } + fileprivate func didSubmit() { lock.withLock { activationCount += 1 } } + + init( + engineID: UUID, model: AnyObject, backend: AnyObject, cacheProvider: AnyObject, + spec: MiMoV26RectangularDenseScratchSpec, policy: AllocationFootprintPolicy + ) throws { + guard let bytes = Self.resolve(spec, upperBound: policy.upperBound(byteCount:)) else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + self.engineID = engineID + modelIdentity = ObjectIdentifier(model) + backendIdentity = ObjectIdentifier(backend) + cacheProviderIdentity = ObjectIdentifier(cacheProvider) + fixedRequestBytes = bytes + } + + /// Pure arithmetic injection is internal for bound tests, not authority. + static func resolve( + _ spec: MiMoV26RectangularDenseScratchSpec, + upperBound: (Int) -> Int? + ) -> Int? { + guard !spec.buffers.isEmpty, spec.hostBytes >= 0 else { return nil } + var total = spec.hostBytes + for buffer in spec.buffers { + guard buffer.logicalBytes > 0, buffer.allocationCount > 0, + let bound = upperBound(buffer.logicalBytes), + bound >= buffer.logicalBytes + else { return nil } + let (all, overflow) = bound.multipliedReportingOverflow(by: buffer.allocationCount) + let (next, sumOverflow) = total.addingReportingOverflow(all) + guard !overflow, !sumOverflow else { return nil } + total = next + } + return total > 0 ? total : nil + } +} + +/// Synchronous, engine-only graph-build scope. A captured TaskLocal cannot arm +/// work after return or on a different thread. It owns metadata, not arrays. +package enum MiMoV26RectangularDenseAdmission { + private final class Frame: @unchecked Sendable { + let budget: MiMoV26RectangularDenseBudget + let thread = ObjectIdentifier(Thread.current) + private let lock = NSLock() + private var open = true + init(_ budget: MiMoV26RectangularDenseBudget) { self.budget = budget } + func close() { lock.withLock { open = false } } + func matches(_ model: AnyObject) -> Bool { + lock.withLock { + open && thread == ObjectIdentifier(Thread.current) + && budget.modelIdentity == ObjectIdentifier(model) + } + } + } + @TaskLocal private static var current: Frame? + static func withBudget( + _ budget: MiMoV26RectangularDenseBudget?, + _ body: () throws -> Result + ) rethrows -> Result { + guard let budget else { return try $current.withValue(nil, operation: body) } + let frame = Frame(budget) + defer { frame.close() } + return try $current.withValue(frame, operation: body) + } + package static func isActive(for model: AnyObject) -> Bool { + current?.matches(model) == true + } + /// Activation only, not GPU completion or numerical qualification. + package static func recordSubmission(for model: AnyObject) { + guard let current, current.matches(model) else { return } + current.budget.didSubmit() + } +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26SplitKeyAttention.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26SplitKeyAttention.swift new file mode 100644 index 0000000000..c0ec9370b9 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26SplitKeyAttention.swift @@ -0,0 +1,194 @@ +// Copyright © 2026 Eigen Labs. +// SPDX-License-Identifier: Apache-2.0 AND MIT +// Narrow matrix-QK adaptation of oMLX #4033 @c10e4ad57b180fa1aa88bf40532cba4362b6851a. +// Source-only packet attribution: ATTRIBUTION.md, LICENSE-OMLX, LICENSE-MLX. +import Foundation +import MLX +import MLXFast + +/// NOT wired into managed attention. A future caller must admit these exact +/// step temporaries, retain evaluationRoots before submission and keep its +/// native loan through the existing completion/fault boundary. +enum MiMoV26SplitKeyAttention { + static let requested = + ProcessInfo.processInfo.environment[ + "DARKBLOOM_MIMO_V26_SPLITKEY_QK"] == "1" + + struct Plan: Equatable { + let rows: Int + let keys: Int + let blocks: Int + let elementBytes: Int + let hasSinks: Bool + var visibleKeys: [Int] { (0 ..< rows).map { keys - rows + $0 + 1 } } + var threads: Int { rows * 64 } // G16 / eight-head band *32 + var threadgroupBytes: Int { (8 * 200 + 8 * 136) * elementBytes + rows * 2 * 64 * 4 } + /// Independent allocations: FP32 numerator, sum, max; final native + /// output; scalar scale; contiguous sink (or one-element placeholder). + /// q/k/v are caller-owned borrowed inputs and must remain charged too. + var allocationByteCounts: [Int] { + let count = 64 * rows * blocks + return [ + count * 128 * 4, count * 4, count * 4, + 64 * rows * 128 * elementBytes, 4, (hasSinks ? 64 : 1) * elementBytes, + ] + } + var temporaryLogicalBytes: Int { allocationByteCounts.prefix(3).reduce(0, +) } + var totalLogicalBytes: Int { allocationByteCounts.reduce(0, +) } + /// Apply the existing allocator policy independently to every buffer. + /// This is admission metadata, NOT measured backing/materialization. + func boundedAllocationBytes(_ bound: (Int) throws -> Int) throws -> Int { + try allocationByteCounts.reduce(0) { total, bytes in + let allocated = try bound(bytes) + guard allocated >= bytes else { throw AllocationError.invalidBound } + let sum = total.addingReportingOverflow(allocated) + guard !sum.overflow else { throw AllocationError.overflow } + return sum.partialValue + } + } + } + enum AllocationError: Error { case invalidBound, overflow } + + /// Metadata-only refusal checks, including EVERY scalar reference row's + /// native block count. No new chunk-size heuristic or count-based widening. + static func plan( + rows: Int, keys: Int, elementBytes: Int, hasSinks: Bool, + deviceClass: Character, blockOverride: Int = 0 + ) -> Plan? { + guard (1 ... 4).contains(rows), keys >= rows, keys <= 1_048_576, + elementBytes == 2, Set(["g", "s", "d"]).contains(deviceClass), + blockOverride >= 0, blockOverride <= 4096 + else { return nil } + let blocks: Int? + if rows == 1 { + guard ((deviceClass == "d" || deviceClass == "s") && keys >= 1024) || keys >= 4096 + else { return nil } // selected core would use one pass + blocks = MiMoV26DecodeRows.blocks( + keys: keys, simds: 16, + deviceClass: deviceClass, override: blockOverride) + } else { + blocks = MiMoV26DecodeRows.serialBlocks( + rows: rows, keys: keys, + deviceClass: deviceClass, override: blockOverride) + } + guard let blocks else { return nil } + return .init( + rows: rows, keys: keys, blocks: blocks, + elementBytes: elementBytes, hasSinks: hasSinks) + } + + static func makePlan( + queries q: MLXArray, keys k: MLXArray, values v: MLXArray, + scale: Float, mask: MLXFast.ScaledDotProductAttentionMaskMode, + sinks: MLXArray?, deviceClass: Character, blockOverride: Int = 0 + ) -> Plan? { + guard q.ndim == 4, k.ndim == 4, v.ndim == 4, + q.dim(0) == 1, q.dim(1) == 64, q.dim(3) == 192, + k.dim(0) == 1, k.dim(1) == 4, k.dim(3) == 192, + v.shape == [1, 4, k.dim(2), 128], + q.dtype == .bfloat16 || q.dtype == .float16, + k.dtype == q.dtype, v.dtype == q.dtype, scale.isFinite, scale > 0 + else { return nil } + switch mask { + case .none: guard q.dim(2) == 1 else { return nil } + case .causal: break + case .array, .arrays: return nil // includes SWA/padding/bias/span masks + } + if let sinks { guard sinks.shape == [64], sinks.dtype == q.dtype else { return nil } } + return plan( + rows: q.dim(2), keys: k.dim(2), elementBytes: q.dtype.size, + hasSinks: sinks != nil, deviceClass: deviceClass, blockOverride: blockOverride) + } + + struct Encoding { + let output: MLXArray + /// Explicit ownership, not merely a graph dependency assumption. + /// No sync/eval/metadata probing/destructor refund occurs here. + let evaluationRoots: [MLXArray] + let plan: Plan + } + private static let first = MLXFast.metalKernel( + name: "mimo_splitkey_matrix_qk", + inputNames: ["queries", "keys", "values", "scale", "sinks"], + outputNames: ["partials", "sums", "maxs"], + source: MiMoV26SplitKeyAttentionMetalSources.pass1, ensureRowContiguous: false) + private static let second = MLXFast.metalKernel( + name: "mimo_splitkey_native_merge", + inputNames: ["partials", "sums", "maxs"], outputNames: ["out"], + // The already-qualified FP32-partial core merge is reused byte-for-byte. + source: MiMoV26DecodeRowsMetalSources.pass2, ensureRowContiguous: true) + + /// Optional encoding seam, not model/row eligibility or a reservation. + /// No production caller is installed by this packet. + static func tryEncode( + queries q: MLXArray, keys k: MLXArray, values v: MLXArray, + scale: Float, mask: MLXFast.ScaledDotProductAttentionMaskMode, + sinks: MLXArray?, stream: StreamOrDevice = .default + ) -> Encoding? { + guard requested, MiMoV26NAXGatherQMM.gpuStream(stream), + MiMoV26NAXGatherQMM.naxAvailable + else { return nil } + let architecture = GPU.deviceInfo().architecture + guard architecture.hasPrefix("applegpu_"), let deviceClass = architecture.last else { + return nil + } + let overrideText = + ProcessInfo.processInfo.environment["MLX_SDPA_BLOCKS"]? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + guard overrideText.isEmpty || Int(overrideText) != nil else { return nil } + guard + let plan = makePlan( + queries: q, keys: k, values: v, scale: scale, + mask: mask, sinks: sinks, deviceClass: deviceClass, + blockOverride: Int(overrideText) ?? 0) + else { return nil } + return encode( + queries: q, keys: k, values: v, scale: scale, + sinks: sinks, plan: plan, stream: stream) + } + + /// Native qualification seam. matrixScores=false uses the pinned scalar + /// QK sum within the SAME recurrence/layout, discriminating changes outside + /// matrix reduction. It is not a production fallback or a fake result. + static func encode( + queries q: MLXArray, keys k: MLXArray, values v: MLXArray, + scale: Float, sinks: MLXArray?, plan: Plan, + matrixScores: Bool = true, stream: StreamOrDevice = .default + ) -> Encoding { + precondition(q.shape == [1, 64, plan.rows, 192] && k.shape == [1, 4, plan.keys, 192]) + precondition(v.shape == [1, 4, plan.keys, 128] && k.dtype == q.dtype && v.dtype == q.dtype) + precondition( + (q.dtype == .bfloat16 || q.dtype == .float16) && (sinks != nil) == plan.hasSinks) + precondition(sinks == nil || (sinks!.shape == [64] && sinks!.dtype == q.dtype)) + precondition( + scale.isFinite && scale > 0 && plan.blocks > 0 && plan.blocks <= 4096 + && plan.blocks.isMultiple(of: 32) && (1 ... 4).contains(plan.rows)) + let scaleInput = MLXArray([scale]) + let sinkInput = + sinks.map { contiguous($0, stream: stream) } + ?? MLXArray.zeros([1], dtype: q.dtype, stream: stream) + let partials = first( + [q, k, v, scaleInput, sinkInput], + template: [ + ("T", q.dtype), ("ROWS", plan.rows), ("BLOCKS", plan.blocks), + ("HAS_SINKS", plan.hasSinks), ("MATRIX_QK", matrixScores), + ], + grid: (plan.threads * 4, 1, plan.blocks), threadGroup: (plan.threads, 1, 1), + outputShapes: [ + [64 * plan.rows, plan.blocks, 128], + [64 * plan.rows, plan.blocks], [64 * plan.rows, plan.blocks], + ], + outputDTypes: [.float32, .float32, .float32], stream: stream) + let result = second( + partials, + template: [ + ("T", q.dtype), ("V", 128), ("NQ", 64), + ("ROWS", plan.rows), ("BLOCKS", plan.blocks), + ], + grid: (1024 * 64, plan.rows, 1), threadGroup: (1024, 1, 1), + outputShapes: [[1, plan.rows, 64 * 128]], outputDTypes: [q.dtype], stream: stream)[0] + let output = result.reshaped([1, plan.rows, 64, 128]).transposed(0, 2, 1, 3) + return .init( + output: output, evaluationRoots: partials + [result, scaleInput, sinkInput], plan: plan) + } +} diff --git a/Libraries/MLXLMCommon/Models/MiMo/MiMoV26SplitKeyAttentionMetalSources.swift b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26SplitKeyAttentionMetalSources.swift new file mode 100644 index 0000000000..582d3b137c --- /dev/null +++ b/Libraries/MLXLMCommon/Models/MiMo/MiMoV26SplitKeyAttentionMetalSources.swift @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: Apache-2.0 AND MIT +// Matrix fragment layout/QK intent: oMLX #4033, c10e4ad57b180fa1aa88bf40532cba4362b6851a. +// Scalar recurrence/key blocks: Apple MLX core3fa8f25e6451174d7b06be372c3a24272b77d88e. +// Modified: native strided splits; per-key max/fast::exp/FP32 output recurrence; +// explicit float K fragments; no tile softmax, PV MMA, HS2 or partial downcast. +// Retained notices/full licenses are in this packet's ATTRIBUTION.md and +// LICENSE-OMLX / LICENSE-MLX; root must carry them when integrating. +enum MiMoV26SplitKeyAttentionMetalSources { + static let pass1 = #""" + constexpr int D = 192; + constexpr int V = 128; + constexpr int G = 16; + constexpr int NKV = 4; + constexpr int TILE = 8; + constexpr int BANDS = ROWS * G / 8; + constexpr int NT = BANDS * 32; + constexpr int KLD = D + 8; + constexpr int VLD = V + 8; + constexpr int DK = D / 8; + typedef float U; + + threadgroup T ktile[TILE * KLD]; + threadgroup T vtile[TILE * VLD]; + threadgroup U scores[BANDS * 64]; + const int kh = threadgroup_position_in_grid.x; + const int block = threadgroup_position_in_grid.z; + const int band = simdgroup_index_in_threadgroup; + const int lane = thread_index_in_simdgroup; + const int tid = thread_index_in_threadgroup; + const int N = keys_shape[2]; + const int row = band / (G / 8); + const int firstHead = kh * G + (band % (G / 8)) * 8; + // Metal 8x8 fragment mapping, same as pinned oMLX. No half accumulation. + const int qid = lane / 4; + const int fm = (qid & 4) + ((lane / 2) % 4); + const int fn = (qid & 2) * 2 + (lane % 2) * 2; + const U sc = scale[0]; + const int64_t qHeadStride = queries_strides[1]; + const int64_t qRowStride = queries_strides[2]; + const int64_t qDimStride = queries_strides[3]; + const int64_t kSeqStride = keys_strides[2]; + const int64_t kDimStride = keys_strides[3]; + const int64_t vSeqStride = values_strides[2]; + const int64_t vDimStride = values_strides[3]; + const device T* kp = keys + int64_t(kh) * keys_strides[1]; + const device T* vp = values + int64_t(kh) * values_strides[1]; + + simdgroup_matrix Q[DK]; + if (MATRIX_QK) { + const device T* qp = queries + int64_t(firstHead + fm) * qHeadStride + row * qRowStride; + for (int kd = 0; kd < DK; ++kd) { + // Scale BEFORE dot products in FP32, exactly like native vector Q. + reinterpret_cast&>(Q[kd].thread_elements()) = + vec(sc * U(qp[(kd * 8 + fn) * qDimStride]), + sc * U(qp[(kd * 8 + fn + 1) * qDimStride])); + } + } + + // Four lanes own one head's independent value dimensions. Their scalar + // online m/l updates are identical; value elements never cross-reduce. + const int headInBand = lane / 4; + const int valueLane = lane % 4; + const int head = firstHead + headInBand; + U numerator[V / 4] = {0}; + U maximum = Limits::finite_min; + U denominator = 0; + if (HAS_SINKS && block == 0) { + maximum = U(sinks[head]); + denominator = 1; + } + const int visible = N - ROWS + row + 1; + const int iterations = block < N ? (N - 1 - block) / BLOCKS + 1 : 0; + for (int base = 0; base < iterations; base += TILE) { + threadgroup_barrier(mem_flags::mem_threadgroup); + // Each native split is block, block+BLOCKS, ... in the original order. + // Ragged slots are zeroed before any matrix read and never enter softmax. + for (int c = tid; c < TILE * D; c += NT) { + const int r = c / D, d = c % D; + const int key = block + (base + r) * BLOCKS; + ktile[r * KLD + d] = key < N ? kp[int64_t(key) * kSeqStride + d * kDimStride] : T(0); + } + for (int c = tid; c < TILE * V; c += NT) { + const int r = c / V, d = c % V; + const int key = block + (base + r) * BLOCKS; + vtile[r * VLD + d] = key < N ? vp[int64_t(key) * vSeqStride + d * vDimStride] : T(0); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (MATRIX_QK) { + simdgroup_matrix first = simdgroup_matrix(0); + simdgroup_matrix second = simdgroup_matrix(0); + // Only QK reduction association differs from the native six-lane- + // elements + simd_sum tree. K is widened exactly, not requantized. + for (int kd = 0; kd < DK / 2; ++kd) { + simdgroup_matrix ka, kb; + reinterpret_cast&>(ka.thread_elements()) = + vec(U(ktile[fn * KLD + kd * 8 + fm]), + U(ktile[(fn + 1) * KLD + kd * 8 + fm])); + reinterpret_cast&>(kb.thread_elements()) = + vec(U(ktile[fn * KLD + (DK / 2 + kd) * 8 + fm]), + U(ktile[(fn + 1) * KLD + (DK / 2 + kd) * 8 + fm])); + simdgroup_multiply_accumulate(first, Q[kd], ka, first); + simdgroup_multiply_accumulate(second, Q[DK / 2 + kd], kb, second); + } + reinterpret_cast&>(first.thread_elements()) += + reinterpret_cast&>(second.thread_elements()); + simdgroup_store(first, scores + band * 64, 8); + } else { + // Qualification control: exact pinned vector-QK reduction, but the + // same staging, recurrence, partial layout and second pass as candidate. + for (int h = 0; h < 8; ++h) { + const device T* qp = queries + int64_t(firstHead + h) * qHeadStride + row * qRowStride; + U query[D / 32]; + for (int d = 0; d < D / 32; ++d) { + query[d] = sc * U(qp[(lane * (D / 32) + d) * qDimStride]); + } + for (int r = 0; r < TILE; ++r) { + U score = 0; + for (int d = 0; d < D / 32; ++d) { + score += query[d] * U(ktile[r * KLD + lane * (D / 32) + d]); + } + score = simd_sum(score); + if (lane == 0) { scores[band * 64 + h * TILE + r] = score; } + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (int r = 0; r < TILE; ++r) { + const int key = block + (base + r) * BLOCKS; + // Never replace prefix exclusion with a finite mask or p=0 product: + // future/padded V (including NaN) must not enter this row's recurrence. + if (key < visible) { + const U score = scores[band * 64 + headInBand * TILE + r]; + const U newMaximum = max(maximum, score); + const U factor = fast::exp(maximum - newMaximum); + const U exponential = fast::exp(score - newMaximum); + maximum = newMaximum; + denominator = denominator * factor + exponential; + for (int d = 0; d < V / 4; ++d) { + const int column = valueLane * (V / 4) + d; + numerator[d] = numerator[d] * factor + exponential * U(vtile[r * VLD + column]); + } + } + } + } + const size_t partial = (size_t(head) * ROWS + row) * BLOCKS + block; + if (valueLane == 0) { + sums[partial] = denominator; + maxs[partial] = maximum; + } + for (int d = 0; d < V / 4; ++d) { + partials[partial * V + valueLane * (V / 4) + d] = numerator[d]; + } + """# +} diff --git a/Libraries/MLXLMCommon/SwitchLayers.swift b/Libraries/MLXLMCommon/SwitchLayers.swift index b23b5021b7..940ac45cea 100644 --- a/Libraries/MLXLMCommon/SwitchLayers.swift +++ b/Libraries/MLXLMCommon/SwitchLayers.swift @@ -27,11 +27,13 @@ public let compiledSiluProduct: @Sendable (MLXArray, MLXArray) -> MLXArray = { /// Compiled weighted expert-output combine (`(outputs * weights[..., None]).sum(-2)`). /// Shared by MoE routers (e.g. Gemma 4) to fuse the scale + reduce. Upstream ef85ed0. -public let weightedExpertSum: @Sendable (MLXArray, MLXArray) -> MLXArray = cbv2ObservedCompiled(.weightedExpertSum, compile( - shapeless: true -) { outputs, weights in - (outputs * MLX.expandedDimensions(weights, axis: -1)).sum(axis: -2) -}) +public let weightedExpertSum: @Sendable (MLXArray, MLXArray) -> MLXArray = cbv2ObservedCompiled( + .weightedExpertSum, + compile( + shapeless: true + ) { outputs, weights in + (outputs * MLX.expandedDimensions(weights, axis: -1)).sum(axis: -2) + }) /// Effective-selection count for the direct sorted-expert reduction. Benchmark /// callers arm this after warmup and snapshot it only after the engine is idle. /// The unarmed hot path reads one plain Bool and performs no atomic operation, @@ -116,22 +118,22 @@ private let weightedExpertUnsortKernel: MLXFast.MLXFastKernel = MLXFast.metalKer inputNames: ["sorted_outputs", "inverse_order", "weights"], outputNames: ["output"], source: """ - uint feature = thread_position_in_grid.x; - uint token = thread_position_in_grid.y; - - T accumulator = (T)0; - const uint assignment_base = token * (uint)K; - for (uint slot = 0; slot < (uint)K; ++slot) { - const uint assignment = assignment_base + slot; - const uint sorted_row = (uint)inverse_order[assignment]; - // Preserve the legacy bfloat16 multiply-then-reduce rounding. - const T weighted = (T)( - (float)sorted_outputs[sorted_row * threads_per_grid.x + feature] - * (float)weights[assignment]); - accumulator = accumulator + weighted; - } - output[token * threads_per_grid.x + feature] = accumulator; - """, + uint feature = thread_position_in_grid.x; + uint token = thread_position_in_grid.y; + + T accumulator = (T)0; + const uint assignment_base = token * (uint)K; + for (uint slot = 0; slot < (uint)K; ++slot) { + const uint assignment = assignment_base + slot; + const uint sorted_row = (uint)inverse_order[assignment]; + // Preserve the legacy bfloat16 multiply-then-reduce rounding. + const T weighted = (T)( + (float)sorted_outputs[sorted_row * threads_per_grid.x + feature] + * (float)weights[assignment]); + accumulator = accumulator + weighted; + } + output[token * threads_per_grid.x + feature] = accumulator; + """, ensureRowContiguous: true ) @@ -181,7 +183,6 @@ public func weightedExpertUnsort( )[0] } - // MARK: - Compiled activation fusions (vMLX / osaurus-main port) /// Approximate (tanh) GELU written with `x * x * x` instead of the Power @@ -292,13 +293,14 @@ public enum Qwen4WeightedExpertUnsort: Sendable { /// one-point activation probe. public enum SwitchGLUWeightedReductionProfile: Sendable { case generic + /// Native MiMo only. The separate FP32 candidate is opt-in and unqualified. + case mimoV26FP32 case gemma4ProductionGeGLU case qwen35ProductionSwiGLU /// Flash-Next oQ4e: hidden 2560, expert width 640, 512 experts, top-10. case qwen4ProductionSwiGLU } - /// Safely row-concatenates split SwitchGLU gate/up checkpoint tensors. /// /// This is the model-neutral core of the Qwen3.5 gate/up load-time fusion: @@ -394,7 +396,8 @@ public func fuseSwitchGLUGateUpWeights( case (nil, nil): fusedMatches = true case (let gate?, let fused?): - fusedMatches = gate.groupSize == fused.groupSize + fusedMatches = + gate.groupSize == fused.groupSize && gate.bits == fused.bits && gate.mode == fused.mode default: fusedMatches = false @@ -487,6 +490,7 @@ public class SwitchGLU: Module { /// supplied (we then fall back to `activation(gate) * up`). Upstream ef85ed0. let activationProduct: (@Sendable (MLXArray, MLXArray) -> MLXArray)? let weightedReductionProfile: SwitchGLUWeightedReductionProfile + let mimoV26NAXGather: Bool /// Activation-type flags detected once at init from a tiny test input (vMLX /// approach — no per-token check). Only consulted when `activationProduct` is @@ -505,7 +509,8 @@ public class SwitchGLU: Module { numExperts: Int, bias: Bool = false, fuseGateUp: Bool = false, - weightedReductionProfile: SwitchGLUWeightedReductionProfile = .generic + weightedReductionProfile: SwitchGLUWeightedReductionProfile = .generic, + mimoV26NAXGather: Bool = false ) { self.inputDims = inputDims self.hiddenDims = hiddenDims @@ -513,6 +518,7 @@ public class SwitchGLU: Module { self.activation = MLXNN.silu self.activationProduct = compiledSiluProduct self.weightedReductionProfile = weightedReductionProfile + self.mimoV26NAXGather = mimoV26NAXGather // Default path is SiLU and `activationProduct` is non-nil, so these are // not consulted on the hot path; set them accurately for completeness // (and to avoid a needless probe eval at load for every MoE layer). @@ -545,7 +551,8 @@ public class SwitchGLU: Module { activation: @escaping (MLXArray) -> MLXArray, bias: Bool = false, fuseGateUp: Bool = false, - weightedReductionProfile: SwitchGLUWeightedReductionProfile = .generic + weightedReductionProfile: SwitchGLUWeightedReductionProfile = .generic, + mimoV26NAXGather: Bool = false ) { self.inputDims = inputDims self.hiddenDims = hiddenDims @@ -553,6 +560,7 @@ public class SwitchGLU: Module { self.activation = activation self.activationProduct = nil self.weightedReductionProfile = weightedReductionProfile + self.mimoV26NAXGather = mimoV26NAXGather // Detect SiLU/GELU once via a tiny test input (vMLX approach) so the hot // path can select the compiled fusion without a per-token check. Exact // equality is intentional: a match means the supplied closure computes @@ -603,6 +611,7 @@ public class SwitchGLU: Module { self.activation = other.activation self.activationProduct = other.activationProduct self.weightedReductionProfile = other.weightedReductionProfile + self.mimoV26NAXGather = other.mimoV26NAXGather self.isSiluActivation = other.isSiluActivation self.isGeluActivation = other.isGeluActivation @@ -646,6 +655,17 @@ public class SwitchGLU: Module { _ projection: SwitchLinear, _ x: MLXArray, _ indices: MLXArray, sortedIndices: Bool ) -> MLXArray { + if mimoV26NAXGather, + let quantized = projection as? QuantizedSwitchLinear, + ObjectIdentifier(type(of: quantized)) == ObjectIdentifier(QuantizedSwitchLinear.self), + quantized.bias == nil, + let result = MiMoV26NAXGatherQMM.tryProjection( + x: x, indices: indices, weight: quantized.weight, scales: quantized.scales, + biases: quantized.biases, sorted: sortedIndices, + groupSize: quantized.groupSize, bits: quantized.bits, mode: quantized.mode) + { + return result + } if weightedReductionProfile == .qwen4ProductionSwiGLU, let quantized = projection as? QuantizedSwitchLinear, ObjectIdentifier(type(of: quantized)) == ObjectIdentifier(QuantizedSwitchLinear.self) @@ -658,6 +678,35 @@ public class SwitchGLU: Module { private func projectExperts( _ x: MLXArray, _ indices: MLXArray ) -> (output: MLXArray, inverseOrder: MLXArray?, sorted: Bool) { + if let result = MiMoV26DecodeExperts.tryProject( + x, indices: indices, glu: self, enabled: MiMoV26DecodeExperts.requested) + { + return (MLX.expandedDimensions(result.output, axis: -2), nil, false) + } + + // #4029: same route sort/inverse as gatherSort, without materializing + // repeated activation rows. Fallback below retains the original graph. + if mimoV26NAXGather, MiMoV26NAXGateUp.rowMapRequested, + MiMoV26NAXGateUp.activationRequested, indices.size >= 64, + isSiluActivation, activationProduct != nil, gateUpProj == nil, + let gateProj, let upProj + { + let flat = indices.flattened() + let order = argSort(flat) + let sorted = flat[order] + let rowMap = order.floorDivide(indices.dim(-1)) + let tokenRows = x.reshaped([-1, 1, x.dim(-1)]) + if let activated = MiMoV26NAXGateUp.tryActivation( + x: tokenRows, indices: sorted, gate: gateProj, up: upProj, + sorted: true, rowMap: rowMap) + { + return ( + projectExpert(downProj, activated, sorted, sortedIndices: true), + argSort(order), true + ) + } + } + var x = MLX.expandedDimensions(x, axes: [-2, -3]) let doSort = indices.size >= 64 @@ -667,6 +716,19 @@ public class SwitchGLU: Module { (x, idx, inverseOrder) = gatherSort(x: x, indices: indices) } + // Native MiMo's known default SiLU only. Custom activations, fused + // stored projections and all non-NAX/unsupported layouts fall through. + if mimoV26NAXGather, isSiluActivation, activationProduct != nil, + gateUpProj == nil, let gateProj, let upProj, + let activated = MiMoV26NAXGateUp.tryActivation( + x: x, indices: idx, gate: gateProj, up: upProj, sorted: doSort) + { + return ( + projectExpert(downProj, activated, idx, sortedIndices: doSort), + doSort ? inverseOrder : nil, doSort + ) + } + let xGate: MLXArray let xUp: MLXArray if let gateUpProj { @@ -677,8 +739,16 @@ public class SwitchGLU: Module { guard let gateProj, let upProj else { preconditionFailure("SwitchGLU requires gate_up_proj or gate_proj/up_proj") } - xUp = projectExpert(upProj, x, idx, sortedIndices: doSort) - xGate = projectExpert(gateProj, x, idx, sortedIndices: doSort) + if mimoV26NAXGather, + let pair = MiMoV26NAXGateUp.tryProjection( + x: x, indices: idx, gate: gateProj, up: upProj, sorted: doSort) + { + xGate = pair.gate + xUp = pair.up + } else { + xUp = projectExpert(upProj, x, idx, sortedIndices: doSort) + xGate = projectExpert(gateProj, x, idx, sortedIndices: doSort) + } } let activated: MLXArray @@ -712,7 +782,7 @@ public class SwitchGLU: Module { _ x: MLXArray, _ indices: MLXArray, weights: MLXArray ) -> Bool { switch weightedReductionProfile { - case .generic: + case .generic, .mimoV26FP32: return false case .gemma4ProductionGeGLU: return inputDims == 2816 @@ -778,6 +848,70 @@ public class SwitchGLU: Module { return MLX.squeezed(projected.output, axis: -2) } + /// MiMo-only candidate. Refusals preserve its original UNCOMPILED combine, + /// not weightedExpertSum's compiled body or a BF16-weighted family profile. + /// The returned route describes this call's actual selected implementation; + /// it is not a completion, numerical-equivalence or memory receipt. + public func callAndMiMoFP32WeightedReduce( + _ x: MLXArray, _ indices: MLXArray, weights: MLXArray, enabled: Bool + ) -> MiMoV26FP32WeightedReductionResult { + func fallback(_ reason: MiMoV26FP32WeightedReductionRoute) + -> MiMoV26FP32WeightedReductionResult + { + let experts = callAsFunction(x, indices) + return .init( + output: (experts * weights[.ellipsis, .newAxis]).sum(axis: -2), route: reason) + } + guard enabled else { return fallback(.disabled) } + guard weightedReductionProfile == .mimoV26FP32 else { return fallback(.unsupportedProfile) } + guard activationProduct != nil, isSiluActivation else { + return fallback(.unsupportedActivation) + } + // Assignment count alone cannot distinguish prefill from a large decode + // cohort. Native MiMo carries explicit [B,L,H], with L>1 here. + guard x.ndim == 3, x.dim(1) > 1 else { return fallback(.notPrefill) } + guard indices.ndim == 3, Array(indices.shape.prefix(2)) == Array(x.shape.prefix(2)), + indices.dim(2) <= numExperts, weights.shape == indices.shape, + indices.dtype == .uint32 || indices.dtype == .int32 + else { + return fallback(.unsupportedShape) + } + guard indices.dim(2) == 6 || indices.dim(2) == 8 else { return fallback(.unsupportedTopK) } + guard x.dtype == .bfloat16 || x.dtype == .float16, weights.dtype == .float32 else { + return fallback(.unsupportedDType) + } + guard indices.size >= 64 else { return fallback(.notSorted) } + + // Project once. If the produced arrays fail the narrower kernel gate, + // restore the existing order and evaluate exactly the unfused expression. + let projected = projectExperts(x, indices) + guard projected.sorted, let inverseOrder = projected.inverseOrder, + projected.output.ndim == 3, projected.output.dim(-2) == 1 + else { + var experts = projected.output + if let inverse = projected.inverseOrder { + experts = scatterUnsort(x: experts, invOrder: inverse, shape: indices.shape) + } + return .init( + output: (MLX.squeezed(experts, axis: -2) * weights[.ellipsis, .newAxis]) + .sum(axis: -2), route: .unsupportedShape) + } + let sorted = MLX.squeezed(projected.output, axis: -2) + if let reason = mimoV26FP32WeightedUnsortRefusal( + sortedOutputs: sorted, inverseOrder: inverseOrder, weights: weights) + { + let experts = MLX.squeezed( + scatterUnsort( + x: projected.output, + invOrder: inverseOrder, shape: indices.shape), axis: -2) + return .init( + output: (experts * weights[.ellipsis, .newAxis]).sum(axis: -2), route: reason) + } + return .init( + output: mimoV26FP32WeightedUnsort( + sortedOutputs: sorted, inverseOrder: inverseOrder, weights: weights), route: .fused) + } + /// Always-called expert projection + weighted reduction entry point. /// /// When the experiment is enabled, only the exact sorted production Gemma @@ -803,7 +937,7 @@ public class SwitchGLU: Module { let inverseOrder = projected.inverseOrder, projected.output.ndim == 3, projected.output.dim(-2) == 1, - (projected.output.dim(-1) == 2816 || projected.output.dim(-1) == inputDims), + projected.output.dim(-1) == 2816 || projected.output.dim(-1) == inputDims, projected.output.dtype == .bfloat16 else { return legacyWeightedReduction(projected, indices: indices, weights: weights) @@ -982,7 +1116,8 @@ public class QuantizedSwitchLinear: SwitchLinear, Quantized { // row per gathered index (see doc comment). The Fusion tiled kernel // enforces `indices.size == assignments` itself and returns nil otherwise. let indexAligned = x.size == indices.size * x.dim(-2) * x.dim(-1) - let scales = mode == .affine + let scales = + mode == .affine ? (scaleCastCache.cachedCast(self.scales, to: x.dtype) ?? self.scales) : self.scales let biases = self.biases.map { offsets in @@ -991,16 +1126,17 @@ public class QuantizedSwitchLinear: SwitchLinear, Quantized { : offsets } var result: MLXArray - if nativeQwen4, let tiled = Qwen4ExpGatherQMM.tryMatmul( - x: x, - indices: indices, - weight: self.weight, - scales: self.scales, - affineBiases: self.biases, - sorted: sortedIndices, - bits: self.bits, - groupSize: self.groupSize, - mode: mode) + if nativeQwen4, + let tiled = Qwen4ExpGatherQMM.tryMatmul( + x: x, + indices: indices, + weight: self.weight, + scales: self.scales, + affineBiases: self.biases, + sorted: sortedIndices, + bits: self.bits, + groupSize: self.groupSize, + mode: mode) { result = tiled } else { diff --git a/Libraries/MLXLMCommon/Tool/Parsers/MiMo/MiMoV2ToolCallParser.swift b/Libraries/MLXLMCommon/Tool/Parsers/MiMo/MiMoV2ToolCallParser.swift new file mode 100644 index 0000000000..afde667e66 --- /dev/null +++ b/Libraries/MLXLMCommon/Tool/Parsers/MiMo/MiMoV2ToolCallParser.swift @@ -0,0 +1,157 @@ +// Copyright © 2026 Eigen Labs. +// MiMo native XML wire dialect. Template reference: XiaomiMiMo/ +// MiMo-V2.6-Flash-RL@5711b268169967567844e1e560e8a3966da959b1. +import Foundation + +/// Native mapping arguments are raw string spans or JSON nonstring values. +/// Neither a Qwen architecture alias nor its JSON/EOS-recovery dialect. +/// +/// A literal `` has no escape mechanism in the pinned template. +/// Its byte stream can be identical to a real delimiter followed by additional +/// structure. Such values are not generally representable losslessly: this +/// parser rejects malformed/duplicate structure, never guesses a repair, and +/// cannot infer the caller's intended value from an otherwise valid collision. +/// Declaration/schema/cardinality validation remains mandatory at the caller. +public struct MiMoV2ToolCallParser: ToolCallParser, Sendable { + public let startTag: String? = "" + public let endTag: String? = "" + public init() {} + + public func parse(content: String, tools: [[String: any Sendable]]?) -> ToolCall? { + let frame = Self.trimFramingWhitespace(content) + guard let startTag, let endTag, frame.unicodeScalars.starts(with: startTag.unicodeScalars), + let end = Qwen35ToolFrameScanner.endRange( + in: frame, startTag: startTag, endTag: endTag), + end.upperBound == frame.endIndex + else { return nil } + var body = frame[ + frame.unicodeScalars.index( + frame.unicodeScalars.startIndex, + offsetBy: startTag.unicodeScalars.count) ..< end.lowerBound] + body = Self.dropFramingWhitespace(body) + guard let function = Self.opening("".unicodeScalars) { + body = + body[ + body.unicodeScalars.index( + body.unicodeScalars.startIndex, + offsetBy: "".unicodeScalars.count)...] + guard body.unicodeScalars.allSatisfy(Self.isFramingWhitespace) else { return nil } + return ToolCall(function: .init(name: function, arguments: arguments)) + } + guard let parameter = Self.opening("") + else { return nil } + let raw = String(body[.. [ToolCall] { + guard let startTag, let endTag else { return [] } + var remaining = Self.trimFramingWhitespace(buffer) + var result: [ToolCall] = [] + while !remaining.isEmpty { + guard remaining.unicodeScalars.starts(with: startTag.unicodeScalars), + let end = Qwen35ToolFrameScanner.endRange( + in: remaining, startTag: startTag, endTag: endTag), + let call = parse(content: String(remaining[.. JSONValue? { + let properties = getParameterConfig(funcName: function, tools: tools) + guard let schema = properties[parameter] as? [String: any Sendable] else { + return .string(raw) // No type evidence: retain bytes; caller validates schema. + } + // Do not infer a type from a string-looking JSON literal or ambiguous + // union. The native template has no discriminator for string "1" vs1. + if schema["anyOf"] != nil || schema["oneOf"] != nil || schema["allOf"] != nil { return nil } + guard let type = schema["type"] as? String else { + return schema["type"] == nil ? .string(raw) : nil + } + if type == "string" { return .string(raw) } + guard ["integer", "number", "boolean", "object", "array", "null"].contains(type), + let decoded = try? JSONDecoder().decode(JSONValue.self, from: Data(raw.utf8)) + else { return nil } + switch (type, decoded) { + case ("integer", .int), ("number", .int), ("number", .double), + ("boolean", .bool), ("object", .object), ("array", .array), ("null", .null): + return decoded + default: return nil + } + } + + private static func declared(_ name: String, tools: [[String: any Sendable]]?) -> Bool { + guard let tools else { return true } + let matches = tools.filter { + ($0["function"] as? [String: any Sendable])?["name"] as? String == name + } + return matches.count == 1 + } + private static func opening(_ prefix: String, from body: inout Substring) -> String? { + // Native keys may begin with a combining scalar. Advancing a Character + // count can consume that scalar together with the ASCII '=' grapheme. + // Match and advance the exact delimiter scalars; never normalize keys. + guard body.unicodeScalars.starts(with: prefix.unicodeScalars) else { return nil } + body = + body[ + body.unicodeScalars.index( + body.unicodeScalars.startIndex, + offsetBy: prefix.unicodeScalars.count)...] + guard let angle = body.unicodeScalars.firstIndex(where: { $0.value == 62 }) else { + return nil + } + let name = String(body[.. Bool { + let bytes = name.utf8 + return (1 ... 64).contains(bytes.count) + && bytes.allSatisfy { + (48 ... 57).contains($0) || (65 ... 90).contains($0) || (97 ... 122).contains($0) + || $0 == 45 || $0 == 95 + } + } + private static func isFramingWhitespace(_ value: Unicode.Scalar) -> Bool { + [UInt32(0x20), 0x09, 0x0A, 0x0D].contains(value.value) + } + private static func dropFramingWhitespace(_ value: Substring) -> Substring { + var text = value + while let first = text.unicodeScalars.first, isFramingWhitespace(first) { + text = text[text.unicodeScalars.index(after: text.unicodeScalars.startIndex)...] + } + return text + } + private static func trimFramingWhitespace(_ value: String) -> String { + var text = dropFramingWhitespace(value[...]) + while let last = text.unicodeScalars.last, isFramingWhitespace(last) { + text = text[..kv` case glm4 @@ -156,9 +159,12 @@ public enum ToolCallFormat: String, Sendable, Codable, CaseIterable { case .xmlFunction: return XMLFunctionParser(startTag: "", endTag: "") case .nemotron: - return XMLFunctionParser(startTag: "", endTag: "", acceptBareFunction: true) + return XMLFunctionParser( + startTag: "", endTag: "", acceptBareFunction: true) case .qwen35: return Qwen35ToolCallParser(startTag: "", endTag: "") + case .mimoV2: + return MiMoV2ToolCallParser() case .glm4: return GLM4ToolCallParser() case .gemma: @@ -188,6 +194,9 @@ public enum ToolCallFormat: String, Sendable, Codable, CaseIterable { public static func infer(from modelType: String, configData: Data? = nil) -> ToolCallFormat? { let type = modelType.lowercased() + // Exact native config identity; no prefix/legacy-MiMo architecture alias. + if type == "mimo_v2" { return .mimoV2 } + // Llama family (need secondary signal for Llama 3 vs 1/2) if type == "llama" { guard let data = configData, diff --git a/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift b/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift index 3ceccfbaa5..76c6809a84 100644 --- a/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift +++ b/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift @@ -56,11 +56,16 @@ public class ToolCallProcessor { /// - Parameters: /// - format: The tool call format to use (defaults to `.json` for standard JSON format) /// - tools: Optional tool schemas for type-aware parsing - public init(format: ToolCallFormat = .json, tools: [[String: any Sendable]]? = nil, strictGemma: Bool = false) { + public init( + format: ToolCallFormat = .json, tools: [[String: any Sendable]]? = nil, + strictGemma: Bool = false + ) { self.strictGemma = strictGemma && format == .gemma self.parser = self.strictGemma ? GemmaFunctionParser(strict: true) : format.createParser() self.tools = tools - self.qwenStructuredFrames = format == .qwen35 + // MiMo shares only the structural XML frame scanner. Its payload + // parser/EOS policy remains a separate strict dialect. + self.qwenStructuredFrames = format == .qwen35 || format == .mimoV2 } // MARK: - Computed Properties @@ -278,7 +283,8 @@ public class ToolCallProcessor { state = .collectingToolCall fallthrough } else { - return qwenStructuredFrames && (leadingToken?.isEmpty == false) ? leadingToken : nil + return qwenStructuredFrames && (leadingToken?.isEmpty == false) + ? leadingToken : nil } } else { // Otherwise, return the collected text and reset the state @@ -344,7 +350,7 @@ public class ToolCallProcessor { private func separatePartialQwenStart(_ tags: [String]) -> String? { let maximum = min(toolCallBuffer.count, (tags.map(\.count).max() ?? 1) - 1) guard maximum > 0 else { return nil } - for count in (1...maximum).reversed() { + for count in (1 ... maximum).reversed() { let suffix = String(toolCallBuffer.suffix(count)) guard tags.contains(where: { $0.hasPrefix(suffix) }) else { continue } let split = toolCallBuffer.index(toolCallBuffer.endIndex, offsetBy: -count) @@ -355,17 +361,24 @@ public class ToolCallProcessor { return nil } - private func completedEndRange(_ endTags: [String], appendedChunk: String) -> Range? { + private func completedEndRange(_ endTags: [String], appendedChunk: String) -> Range< + String.Index + >? { if strictGemma, let start = parser.startTag, let end = parser.endTag { - let input = gemmaFrameScanner == nil ? toolCallBuffer.dropFirst(start.count) : appendedChunk[...] + let input = + gemmaFrameScanner == nil + ? toolCallBuffer.dropFirst(start.count) : appendedChunk[...] var scanner = gemmaFrameScanner ?? GemmaToolFrameScanner() let scalars = input.unicodeScalars for index in scalars.indices { if scanner.consume(scalars[index]) { - let remaining = scalars.distance(from: scalars.index(after: index), to: scalars.endIndex) - let upper = toolCallBuffer.unicodeScalars.index(toolCallBuffer.unicodeScalars.endIndex, offsetBy: -remaining) + let remaining = scalars.distance( + from: scalars.index(after: index), to: scalars.endIndex) + let upper = toolCallBuffer.unicodeScalars.index( + toolCallBuffer.unicodeScalars.endIndex, offsetBy: -remaining) gemmaFrameScanner = scanner - return toolCallBuffer.unicodeScalars.index(upper, offsetBy: -end.unicodeScalars.count).. NativeConstructionSnapshot { lock.withLock { value } } + func publish(_ value: NativeConstructionSnapshot) { lock.withLock { self.value = value } } +} +private final class NativeConstructionValue { + let value: Value + init(_ value: Value) { self.value = value } +} + +/// Actor-local opaque lifetime. The caller MUST keep it alive after failed +/// completion, stop using the affected native model, and retain it until process +/// restart. There is intentionally no recovery, reset, or credit-refund method. +/// Do not share this scope across concurrent calls or isolation domains. +public final class NativeConstructionScope { + private let ownerID = UUID() + private var epoch: UInt64 = 0 + private var phase = NativeConstructionPhase.idle + private var disposition = NativeConstructionDisposition.idle + private var depth = 0 + private var mayHaveSubmitted = false + private var arrays: [MLXArray] = [] + private var owners: [AnyObject] = [] + private var streams: [MLX.Stream] = [] + private var invalidations: [ObjectIdentifier: () -> Void] = [:] + private var immutableLoadedOwners = Set() + private let publish: (@Sendable (NativeConstructionSnapshot) -> Void)? + + // Deterministic fault boundaries for package tests. These may only refuse + // an operation/receipt, never replace native work with a successful result. + package var testingBoundary: ((String, NativeConstructionScope) throws -> Void)? + package var testingBeforeFence: ((MLX.Stream) throws -> Void)? + package var retainedArraysForTesting: [MLXArray] { arrays } + package var retainedOwnersForTesting: [AnyObject] { owners } + package var capturedStreamsForTesting: [MLX.Stream] { streams } + + public init() { publish = nil } + fileprivate init(publish: @escaping @Sendable (NativeConstructionSnapshot) -> Void) { + self.publish = publish + notify() + } + public var snapshot: NativeConstructionSnapshot { + .init( + ownerID: ownerID, epoch: epoch, phase: phase, disposition: disposition, + retainedArrayCount: arrays.count, retainedOwnerCount: owners.count, + capturedStreamCount: streams.count) + } + private func notify() { publish?(snapshot) } + + public func validate(_ receipt: NativeConstructionReceipt) throws { + guard disposition == .completed(receipt), receipt.ownerID == ownerID, + receipt.epoch == epoch + else { throw NativeConstructionError.staleReceipt } + } + + /// Nested SDK calls share their outer epoch. Only the outermost return may + /// discard temporary owners. A probe explicitly fences before unbinding rows. + package func withPhase( + _ nextPhase: NativeConstructionPhase, + _ body: () throws -> Value + ) throws -> Value { + if case .retainedFault(let fault) = disposition { + throw NativeConstructionError.retainedFault(fault) + } + let outermost = depth == 0 + let previousPhase = phase + if outermost { + let next = epoch.addingReportingOverflow(1) + guard !next.overflow else { throw NativeConstructionError.alreadyConsumed } + epoch = next.partialValue + disposition = .active + mayHaveSubmitted = false + } + phase = nextPhase + depth += 1 + notify() + defer { + depth -= 1 + if !outermost { + phase = previousPhase + notify() + } + } + do { + let value = try body() + if outermost { try complete(cause: "normal return") } + return value + } catch { + let original = error + if outermost && !snapshot.isRetainedFault { + try complete(cause: String(describing: original)) + } + throw original + } + } + + private func requireActive() throws { + guard depth > 0, disposition == .active else { + if case .retainedFault(let fault) = disposition { + throw NativeConstructionError.retainedFault(fault) + } + throw NativeConstructionError.inactiveScope + } + } + package func retain(_ array: MLXArray) throws { + try requireActive() + // Preserve the actual wrapper identity. No copied/duplicated storage. + if !arrays.contains(where: { $0 === array }) { arrays.append(array) } + notify() + } + package func retain(arrays values: S) throws where S.Element == MLXArray { + for value in values { try retain(value) } + } + package func retainOwner(_ owner: AnyObject) throws { + try requireActive() + if !owners.contains(where: { $0 === owner }) { owners.append(owner) } + notify() + } + package func retainValue(_ value: Value) throws { + try retainOwner(NativeConstructionValue(value)) + } + /// Only the strict native factory authorizes the fully materialized loaded + /// resources owner. An arbitrary active scope or successful target probe + /// does not establish the provenance of untouched assistant parameters. + package func authorizeImmutableLoadedOwner(_ owner: AnyObject) throws { + try retainOwner(owner) + immutableLoadedOwners.insert(ObjectIdentifier(owner)) + } + package func requireImmutableLoadedOwner(_ owner: AnyObject?) throws { + try requireActive() + guard let owner, immutableLoadedOwners.contains(ObjectIdentifier(owner)) else { + throw NativeConstructionError.unqualifiedNativeOwner + } + } + /// Logical invalidation only, on this exclusive native construction segment. + /// A later outer setup fence can fail after a nested probe already returned. + package func invalidateOnFailedCompletion(_ owner: AnyObject, _ action: @escaping () -> Void) + throws + { + try retainOwner(owner) + invalidations[ObjectIdentifier(owner)] = action + } + package func capture(_ stream: MLX.Stream) throws { + try requireActive() + if !streams.contains(stream) { streams.append(stream) } + notify() + } + package func willSubmit() throws { + try requireActive() + guard !streams.isEmpty else { throw NativeConstructionError.inactiveScope } + mayHaveSubmitted = true + } + package func checkpoint(_ name: String) throws { + try requireActive() + try testingBoundary?(name, self) + } + + /// Uses the captured streams, not whatever "default" means at unwind. + /// All streams are attempted; any failure permanently retains every owner. + package func fence(cause: String) throws { + try requireActive() + guard mayHaveSubmitted else { return } + var failures: [String] = [] + for stream in streams { + do { + try testingBeforeFence?(stream) + try withError { error in + stream.synchronize() + try error.check() + } + } catch { + failures.append("\(stream): \(error)") + } + } + guard failures.isEmpty else { + let fault = NativeConstructionFault( + phase: phase, cause: cause, + completionFailures: failures) + disposition = .retainedFault(fault) + for invalidate in invalidations.values { invalidate() } + invalidations.removeAll() + immutableLoadedOwners.removeAll() + testingBoundary = nil + testingBeforeFence = nil + notify() + throw NativeConstructionError.retainedFault(fault) + } + } + + private func complete(cause: String) throws { + try fence(cause: cause) + let completion: NativeConstructionCompletion = + mayHaveSubmitted ? .capturedStreamsCompleted : .noNativeSubmission + // The returned value or host container owns successful long-lived + // objects. Clear only this epoch's extra roots after successful fences. + arrays.removeAll() + owners.removeAll() + streams.removeAll() + invalidations.removeAll() + immutableLoadedOwners.removeAll() + testingBoundary = nil + testingBeforeFence = nil + disposition = .completed(.init(ownerID: ownerID, epoch: epoch, completion: completion)) + notify() + } +} + +/// Preinstall this opaque owner in a real host transaction BEFORE starting the +/// async factory. It stays reachable even if no model returns or a phase hangs. +/// Its mutex is held over the complete async operation, not actor-reentrant. +/// No member exposes an MLXArray, ModelContext, raw model, or mutable binding. +public final class NativeConstructionWork: Sendable { + private final class State { + let scope: NativeConstructionScope + var loadStarted = false + var pendingContainer: ModelContainer? + // Do not retain the host's successfully adopted container, but do not + // confuse a recyclable address with a still-live adopted identity. + weak var adoptedContainer: ModelContainer? + var sealed = false + init(scope: NativeConstructionScope) { self.scope = scope } + } + private let status: NativeConstructionStatus + private let state: SerialAccessContainer + + public init() { + let initial = NativeConstructionScope().snapshot + let status = NativeConstructionStatus(initial) + let scope = NativeConstructionScope(publish: { status.publish($0) }) + self.status = status + self.state = .init(State(scope: scope)) + } + public var snapshot: NativeConstructionSnapshot { status.read() } + + package func configureFailureForTesting( + _ configure: @escaping @Sendable (NativeConstructionScope) -> Void + ) async throws { + try await state.read { state in + guard !state.loadStarted, !state.sealed else { + throw NativeConstructionError.alreadyConsumed + } + configure(state.scope) + } + } + + /// Atomically wins against any not-yet-started managed load. A metadata-only + /// host failure can obtain a real no-submission receipt without assuming a + /// cancelled task will never resume and try to begin construction. + public func finishUnstartedConstruction() async throws -> NativeConstructionReceipt { + try await state.read { state in + guard !state.loadStarted, !state.sealed else { + throw NativeConstructionError.alreadyConsumed + } + state.loadStarted = true + state.sealed = true + try state.scope.withPhase(.modelFactory) {} + guard case .completed(let receipt) = state.scope.snapshot.disposition else { + throw NativeConstructionError.staleReceipt + } + return receipt + } + } + + public func validate(_ receipt: NativeConstructionReceipt) throws { + let current = snapshot + guard current.disposition == .completed(receipt), + receipt.ownerID == current.ownerID, receipt.epoch == current.epoch + else { + throw NativeConstructionError.staleReceipt + } + } + + package func constructContainer( + _ body: @escaping @Sendable (NativeConstructionScope) throws -> ModelContainer + ) async throws -> ModelContainer { + try await state.read { state in + guard !state.loadStarted, !state.sealed else { + throw NativeConstructionError.alreadyConsumed + } + state.loadStarted = true + let container = try body(state.scope) + // This write precedes the async return. If the caller is cancelled + // before registering its newcomer, the preinstalled owner survives. + state.pendingContainer = container + return container + } + } + + /// Host MUST already strongly own the identical raw container. This only + /// drops the pending-handoff alias; it does not complete future setup work. + public func acknowledgeContainerAdoption(_ container: ModelContainer) async throws { + try await state.read { state in + guard !state.sealed, state.pendingContainer === container, + case .completed = state.scope.snapshot.disposition + else { + throw NativeConstructionError.invalidContainerAdoption + } + state.adoptedContainer = container + state.pendingContainer = nil + } + } + + package func withContainer( + _ container: ModelContainer, + _ body: @escaping @Sendable (ModelContext, NativeConstructionScope) throws -> Result + ) async throws -> Result { + try await state.read { state in + guard !state.sealed, state.pendingContainer == nil, + state.adoptedContainer === container + else { + throw NativeConstructionError.invalidContainerAdoption + } + // Fixed lock order: work -> container. The scope is exclusively + // borrowed while the work mutex stays held across this await. + return try await container.perform(nonSendable: state.scope) { context, scope in + try scope.withPhase(.nativeSetup) { + try scope.retainValue(context.model) + try scope.capture(StreamOrDevice.cpu.stream) + try scope.capture(StreamOrDevice.default.stream) + return try body(context, scope) + } + } + } + } + + /// Prevent any later construction epoch before the host's no-await final + /// publication commit. This is not a host retirement/accounting receipt. + public func sealForPublication(_ receipt: NativeConstructionReceipt) async throws { + try await state.read { state in + guard !state.sealed, state.adoptedContainer != nil, + state.pendingContainer == nil + else { throw NativeConstructionError.invalidContainerAdoption } + try state.scope.validate(receipt) + state.sealed = true + } + } +} diff --git a/Libraries/MLXLMServer/Parsing/ServerToolParser.swift b/Libraries/MLXLMServer/Parsing/ServerToolParser.swift index a419fa8d25..a88255bac7 100644 --- a/Libraries/MLXLMServer/Parsing/ServerToolParser.swift +++ b/Libraries/MLXLMServer/Parsing/ServerToolParser.swift @@ -26,6 +26,8 @@ public enum ServerToolParser { } switch normalized { + case "mimo", "mimo_v2": + return .mimoV2 case "json", "default", "qwen3": return .json case "lfm2", "lfm2_5", "lfm25": diff --git a/Libraries/MLXLMServer/Protocol/OpenAIProtocol.swift b/Libraries/MLXLMServer/Protocol/OpenAIProtocol.swift index 20cdbdf5b5..94c02a4426 100644 --- a/Libraries/MLXLMServer/Protocol/OpenAIProtocol.swift +++ b/Libraries/MLXLMServer/Protocol/OpenAIProtocol.swift @@ -10,10 +10,23 @@ public enum OpenAIRole: String, Codable, Sendable { case tool } +/// Inline encoded input only. Decoding/admission belongs to the actual loaded +/// model path; this DTO does not fetch URLs, decode bytes or advertise support. +public struct OpenAIInputAudio: Codable, Sendable, Equatable { + public enum Format: String, Codable, Sendable { case wav, mp3 } + public let data: String + public let format: Format + public init(data: String, format: Format) { + self.data = data + self.format = format + } +} + public enum OpenAIContentPart: Codable, Sendable, Equatable { case text(String) case imageURL(String) case videoURL(String) + case inputAudio(OpenAIInputAudio) case unsupported(type: String) private enum CodingKeys: String, CodingKey { @@ -22,6 +35,7 @@ public enum OpenAIContentPart: Codable, Sendable, Equatable { case imageURL = "image_url" case fileID = "file_id" case videoURL = "video_url" + case inputAudio = "input_audio" case url } @@ -31,6 +45,7 @@ public enum OpenAIContentPart: Codable, Sendable, Equatable { case inputImage = "input_image" case imageURL = "image_url" case videoURL = "video_url" + case inputAudio = "input_audio" } public init(from decoder: Decoder) throws { @@ -55,6 +70,8 @@ public enum OpenAIContentPart: Codable, Sendable, Equatable { case PartType.videoURL.rawValue: let video = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .videoURL) self = .videoURL(try video.decode(String.self, forKey: .url)) + case PartType.inputAudio.rawValue: + self = .inputAudio(try container.decode(OpenAIInputAudio.self, forKey: .inputAudio)) default: self = .unsupported(type: type) } @@ -74,6 +91,9 @@ public enum OpenAIContentPart: Codable, Sendable, Equatable { try container.encode(PartType.videoURL.rawValue, forKey: .type) var video = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .videoURL) try video.encode(url, forKey: .url) + case .inputAudio(let audio): + try container.encode(PartType.inputAudio.rawValue, forKey: .type) + try container.encode(audio, forKey: .inputAudio) case .unsupported(let type): try container.encode(type, forKey: .type) } @@ -122,7 +142,7 @@ public enum OpenAIMessageContent: Codable, Sendable, Equatable { } } - /// True if any content part carries image or video media (which the + /// True if any content part carries image, video or audio media (which the /// text-only ``MLXModelContainerEngine`` cannot serve). ``text`` flattens /// content to its text parts only, so media would otherwise be silently /// dropped; engines use this to reject such requests instead. @@ -130,7 +150,7 @@ public enum OpenAIMessageContent: Codable, Sendable, Equatable { if case .parts(let parts) = self { return parts.contains { part in switch part { - case .imageURL, .videoURL: return true + case .imageURL, .videoURL, .inputAudio: return true case .text, .unsupported: return false } } diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioFrontend.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioFrontend.swift new file mode 100644 index 0000000000..7eb64d8326 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioFrontend.swift @@ -0,0 +1,182 @@ +// Copyright © 2026 Eigen Labs. +// Derived algorithm: pinned Torchaudio2.11 (BSD), SGLang67 (Apache-2.0). +// Decoded PCM only. No URL/file decoding, normalization or native execution at init. +import Foundation +import MLX +import MLXLLM + +public struct MiMoV26DecodedPCM: Sendable { + /// Channel-major planar samples. Swift value ownership prevents a caller + /// mutation of its original array from changing this captured PCM value. + public let samples: [Float] + public let descriptor: MiMoV26AudioPCMDescriptor + public init(samples: [Float], descriptor: MiMoV26AudioPCMDescriptor) throws { + guard descriptor.channels > 0, descriptor.frameCount > 0, + try MiMoV26AudioChecked.product( + [descriptor.channels, descriptor.frameCount], "PCM shape") == samples.count, + samples.allSatisfy(\.isFinite) + else { throw MiMoV26AudioInputError.input("PCM shape/nonfinite samples") } + self.samples = samples + self.descriptor = descriptor + } +} + +public struct MiMoV26PreparedMel { + public let values: MLXArray + public let clipIndex: Int + public let inputPlanIdentity: Data + // Only the frontend can label a tensor as this prepared PCM result. + fileprivate init(values: MLXArray, clipIndex: Int, inputPlanIdentity: Data) { + self.values = values + self.clipIndex = clipIndex + self.inputPlanIdentity = inputPlanIdentity + } +} + +public final class MiMoV26AudioFrontend { + public let configuration: MiMoV26AudioInputConfiguration + public init(configuration: MiMoV26AudioInputConfiguration) { + self.configuration = configuration + } + + /// Builds a lazy native graph. Caller retains its admitted input/work owner + /// through evaluation/drain. This method does not change global MLX state. + public func prepare( + pcm: MiMoV26DecodedPCM, plan: MiMoV26AudioInputPlan, clipIndex: Int, + isCancelled: () -> Bool = { false } + ) throws -> MiMoV26PreparedMel { + guard plan.configuration == configuration, let descriptors = plan.pcmDescriptors, + descriptors.indices.contains(clipIndex), descriptors[clipIndex] == pcm.descriptor, + plan.resampling.indices.contains(clipIndex) + else { + throw MiMoV26AudioInputError.input("PCM does not match its preparation plan") + } + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + let identity = try plan.preparationIdentityData() + let d = pcm.descriptor + let r = plan.resampling[clipIndex] + let coefficients = try Self.resampleCoefficients(r, isCancelled: isCancelled) + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + let wave = MLXArray(pcm.samples).reshaped(d.channels, d.frameCount) + let resampled = Self.resample(wave, plan: r, coefficients: coefficients) + // Order is intentional: filtering each channel precedes averaging. + let mono = mean(resampled, axis: 0) + let window = Self.periodicHann(configuration.fftSize) + let bank = Self.melBank(configuration) + var blocks: [MLXArray] = [] + let count = plan.melFrameCounts[clipIndex] + let block = plan.limits.frontendFrameBlockSize + for start in stride(from: 0, to: count, by: block) { + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + let n = min(block, count - start) + let indices = try Self.reflectFrameIndices( + samples: r.outputFrames, startFrame: start, count: n, + fftSize: configuration.fftSize, hop: configuration.hopLength) + let frames = take(mono, MLXArray(indices), axis: 0).reshaped(n, configuration.fftSize) + let spectrum = MLXFFT.rfft(frames * window, n: configuration.fftSize, axis: -1) + let magnitudes = abs(spectrum) // power1, no FFT/window normalization + blocks.append(log(maximum(matmul(magnitudes, bank), Float(1e-7)))) + } + let values = blocks.count == 1 ? blocks[0] : concatenated(blocks, axis: 0) + guard values.shape == [count, configuration.melBands], values.dtype == .float32 else { + throw MiMoV26AudioInputError.input("native frontend shape/dtype") + } + return .init(values: values, clipIndex: clipIndex, inputPlanIdentity: identity) + } + + static func resampleCoefficients( + _ p: MiMoV26AudioResamplePlan, + isCancelled: () -> Bool = { false } + ) throws -> [Float] { + guard !p.isIdentity else { return [] } + let base = Double(min(p.originalRatio, p.targetRatio)) * 0.99 + var output = [Float]() + output.reserveCapacity(p.coefficients) + for phase in 0 ..< p.targetRatio { + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + // torch.arange(integer)/q first rounds to the recorded default + // F32, then addition to the F64 index promotes it to Double. + let offset = Double(Float(-phase) / Float(p.targetRatio)) + for index in -p.width ..< (p.width + p.originalRatio) { + let t = min( + 6.0, max(-6.0, (offset + Double(index) / Double(p.originalRatio)) * base)) + let hann = cos((t * Double.pi / 6) / 2) + let angle = t * Double.pi + let sinc = angle == 0 ? 1 : sin(angle) / angle + let window = hann * hann + let scale = base / Double(p.originalRatio) + output.append(Float(sinc * (window * scale))) + } + } + guard output.count == p.coefficients, output.allSatisfy(\.isFinite) else { + throw MiMoV26AudioInputError.input("resample coefficient construction") + } + return output + } + + static func resample(_ wave: MLXArray, plan p: MiMoV26AudioResamplePlan, coefficients: [Float]) + -> MLXArray + { + if p.isIdentity { return wave } + let input = padded( + wave.expandedDimensions(axis: 2), + widths: [0, IntOrPair((p.width, p.width + p.originalRatio)), 0]) + let kernel = MLXArray(coefficients).reshaped(p.targetRatio, p.taps, 1) + // MLX NLC output is already [channels, coarse-time, phase], matching + // Torch's output.transpose(1,2).reshape before its exact trim. + let output = conv1d(input, kernel, stride: p.originalRatio).reshaped(wave.dim(0), -1) + return output[0..., 0 ..< p.outputFrames] + } + + static func periodicHann(_ size: Int) -> MLXArray { + let position = MLXArray(0 ..< size).asType(.float32) + // Torch TensorFactories.hann_window delegates to hamming(alpha=.5, + // beta=.5): multiply, cos, multiply(-.5), add(.5), in that order. + return cos(position * Float(2 * Double.pi / Double(size))) * Float(-0.5) + Float(0.5) + } + + static func reflectFrameIndices( + samples: Int, startFrame: Int, count: Int, + fftSize: Int, hop: Int + ) throws -> [Int32] { + guard samples > fftSize / 2, samples <= Int(Int32.max), startFrame >= 0, count > 0, + fftSize > 0, hop > 0 + else { throw MiMoV26AudioInputError.input("reflect/STFT geometry") } + guard startFrame <= samples / hop + 1, count <= samples / hop + 1 - startFrame else { + throw MiMoV26AudioInputError.input("FFT frame range") + } + let elements = try MiMoV26AudioChecked.product([count, fftSize], "frame indices") + guard elements <= Int(Int32.max) else { + throw MiMoV26AudioInputError.limit("flat native frame-index shape") + } + var result = [Int32]() + result.reserveCapacity(elements) + for frame in startFrame ..< (try MiMoV26AudioChecked.add(startFrame, count, "FFT frames")) { + let center = try MiMoV26AudioChecked.product([frame, hop], "frame center") + for feature in 0 ..< fftSize { + let position = center - fftSize / 2 + feature + let index = + position < 0 + ? -position : position >= samples ? 2 * samples - 2 - position : position + guard index >= 0, index < samples else { + throw MiMoV26AudioInputError.input("reflect frame exceeds declared waveform") + } + result.append(Int32(index)) + } + } + return result + } + + static func melBank(_ c: MiMoV26AudioInputConfiguration) -> MLXArray { + let frequency = MLXArray.linspace( + Float(0), Float(c.sampleRate / 2), count: c.fftSize / 2 + 1) + let maxMel = Float(2595 * log10(1 + Double(c.sampleRate / 2) / 700)) + let mel = MLXArray.linspace(Float(0), maxMel, count: c.melBands + 2) + let hz = Float(700) * (pow(Float(10), mel / Float(2595)) - Float(1)) + let differences = hz[1...] - hz[..<(c.melBands + 1)] + let slopes = hz.expandedDimensions(axis: 0) - frequency.expandedDimensions(axis: 1) + let down = -slopes[0..., 0 ..< c.melBands] / differences[0 ..< c.melBands] + let up = slopes[0..., 2...] / differences[1...] + return maximum(Float(0), minimum(down, up)) // no Slaney normalization + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioInput.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioInput.swift new file mode 100644 index 0000000000..275170b3ee --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioInput.swift @@ -0,0 +1,292 @@ +// Copyright © 2026 Eigen Labs. One stateless request; no provider activation. +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +public enum MiMoV26AudioWorkFailure: Error, Equatable, Sendable { + case drainFailed, invalidatedOwner, noFailedWork +} + +/// Host-owned physical reservation, distinct from numerical metadata. No +/// default permissive implementation. The source owner passed to encode must +/// retain the verified loaded codec and its actual load/source reservation. +public protocol MiMoV26AudioWorkReservation: AnyObject { + func validate(plan: MiMoV26AudioInputPlan, sourceIdentity: String, generation: UUID) throws + /// Transfer ALL failed work to host quarantine. Keep this bundle/lease + /// until genuine recovery or process exit; never refund after failed drain. + func retainAfterFailedDrain(_ work: MiMoV26FailedAudioWork) +} + +/// Opaque, non-serialized failed work. Original array references, not copies or +/// nbytes stand-ins, retain the graph roots submitted at every explicit fence. +public final class MiMoV26FailedAudioWork { + public let sourceIdentity: String + public let generation: UUID + public let inputPlanIdentity: Data + public private(set) var failedDrain = false + public var retainedRootCount: Int { roots.count } + private let stream: MLX.Stream + private var roots: [MLXArray] = [] + private var weights: MiMoV26AudioInputWeights? + private var clips: [MiMoV26DecodedPCM]? + private var sourceOwner: AnyObject? + private var reservation: (any MiMoV26AudioWorkReservation)? + private let managedWork: CBv2NativeMediaPreparation? + private(set) var managedRequiredCompletionFailed = false + var isManaged: Bool { managedWork != nil } + init( + weights: MiMoV26AudioInputWeights, clips: [MiMoV26DecodedPCM], plan: MiMoV26AudioInputPlan, + sourceOwner: AnyObject, reservation: any MiMoV26AudioWorkReservation, + managedWork: CBv2NativeMediaPreparation? = nil + ) throws { + self.weights = weights + self.clips = clips + self.sourceOwner = sourceOwner + self.reservation = reservation + self.managedWork = managedWork + sourceIdentity = weights.sourceIdentity + generation = weights.generation + inputPlanIdentity = try plan.preparationIdentityData() + stream = StreamOrDevice.default.stream + } + func track(_ values: [MLXArray]) { roots = values } + func trackManaged(_ values: [MLXArray]) throws { + roots = values + try managedWork?.beforeNativeWork(values) // actual inner roots before required ops + } + func markManagedRequiredFailure() { + guard let managedWork else { return } + managedWork.requiredCompletionFailed() // first winner BEFORE cleanup/callback + guard !managedRequiredCompletionFailed else { return } + managedRequiredCompletionFailed = true + reservation!.retainAfterFailedDrain(self) + } + func requiredCompletion(_ body: () throws -> T) throws -> T { + do { return try body() } catch { + markManagedRequiredFailure() + throw error + } + } + func drain(invalidate: () -> Void, synchronize: (() throws -> Void)? = nil) throws { + do { + if let synchronize { try synchronize() } else { try withError { stream.synchronize() } } + } catch { + failedDrain = true + invalidate() + if managedWork != nil { + markManagedRequiredFailure() + } else { + reservation!.retainAfterFailedDrain(self) + } + throw MiMoV26AudioWorkFailure.drainFailed + } + } + func verifyRecoveryDrain(synchronize: (() throws -> Void)? = nil) throws { + guard failedDrain else { throw MiMoV26AudioWorkFailure.noFailedWork } + if let synchronize { try synchronize() } else { try withError { stream.synchronize() } } + } + func releaseAfterSuccessfulDrain() { + guard !managedRequiredCompletionFailed, managedWork?.completionFailed != true else { + return + } + roots.removeAll() + clips = nil + weights = nil + sourceOwner = nil + reservation = nil + failedDrain = false + } + /// Caller keeps its native lane while recovering. A thrown synchronization + /// preserves every owner. Success releases once; a repeated call refuses. + public func recoverAndReleaseAfterDrain() throws { + guard failedDrain, managedWork == nil else { throw MiMoV26AudioWorkFailure.noFailedWork } + do { try verifyRecoveryDrain() } catch { throw MiMoV26AudioWorkFailure.drainFailed } + releaseAfterSuccessfulDrain() + } +} + +/// PCM→codes composition. It never cross-batches calls or changes the original +/// plan to fit memory. The provider owns encoded decoding, real process permits, source +/// materialization/revalidation, the existing patch encoder and prompt assembly. +public final class MiMoV26AudioInput { + public let weights: MiMoV26AudioInputWeights + public var configuration: MiMoV26AudioInputConfiguration { weights.configuration } + private var servingIsValid = true + enum ManagedRequiredPhase { + case frontendEval, frontendFinite, rvqEval, rvqFinite, codesReadback + } + // Per-instance refusal-only test hook; never substitutes evaluation/success. + // Untracked encode never invokes it. Runs outside the outcome lock. + #if DEBUG + var beforeManagedRequiredCompletionForTesting: ((ManagedRequiredPhase) throws -> Void)? + #endif + public init(weights: MiMoV26AudioInputWeights) { self.weights = weights } + + /// Mandatory real work/source owners. Weights must already be materialized + /// under the verified host load owner; this SDK does not authenticate it. + /// A failed drain faults this input object and transfers roots/owners to + /// host quarantine. Recovery does not silently reactivate this instance. + public func encode( + clips: [MiMoV26DecodedPCM], limits: MiMoV26AudioInputLimits, + retaining sourceOwner: AnyObject, + authorize: (MiMoV26AudioInputPlan) throws -> any MiMoV26AudioWorkReservation, + isCancelled: () -> Bool = { false } + ) throws -> [MiMoV26AudioCodeClip] { + try encodeOwned( + clips: clips, limits: limits, retaining: sourceOwner, + authorize: authorize, isCancelled: isCancelled, managedWork: nil) + } + /// Trusted SDK producer uses its existing engine-issued loan; no public + /// array callback, second loan/registry or successful-fence override. + package func encodeManaged( + clips: [MiMoV26DecodedPCM], limits: MiMoV26AudioInputLimits, + retaining sourceOwner: AnyObject, + authorize: (MiMoV26AudioInputPlan) throws -> any MiMoV26AudioWorkReservation, + isCancelled: () -> Bool, work: CBv2NativeMediaPreparation + ) throws -> [MiMoV26AudioCodeClip] { + try encodeOwned( + clips: clips, limits: limits, retaining: sourceOwner, + authorize: authorize, isCancelled: isCancelled, managedWork: work) + } + private func encodeOwned( + clips: [MiMoV26DecodedPCM], limits: MiMoV26AudioInputLimits, + retaining sourceOwner: AnyObject, + authorize: (MiMoV26AudioInputPlan) throws -> any MiMoV26AudioWorkReservation, + isCancelled: () -> Bool, managedWork: CBv2NativeMediaPreparation? + ) throws -> [MiMoV26AudioCodeClip] { + guard servingIsValid else { throw MiMoV26AudioWorkFailure.invalidatedOwner } + guard weights.encoder.loadedGeneration == weights.generation else { + throw MiMoV26AudioInputError.weightsNotLoaded + } + let plan = try MiMoV26AudioInputPlan.make( + clips: clips.map(\.descriptor), configuration: configuration, limits: limits) + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + guard !clips.isEmpty else { return [] } + let owner = try authorize(plan) + try owner.validate( + plan: plan, sourceIdentity: weights.sourceIdentity, generation: weights.generation) + let work = try MiMoV26FailedAudioWork( + weights: weights, clips: clips, plan: plan, sourceOwner: sourceOwner, + reservation: owner, managedWork: managedWork) + managedWork?.retain(work) // exact source/weights/PCM owner before graph creation + do { + let output = try withError { error in + let result = try admitted( + clips: clips, plan: plan, isCancelled: isCancelled, owner: owner, work: work, + errors: error) + try error.check() + return result + } + try work.drain(invalidate: { servingIsValid = false }) + work.releaseAfterSuccessfulDrain() + return output + } catch { + // Match outer managed classification BEFORE inner root cleanup. + // Successfully drained typed cancellation/admission stay ordinary. + if managedWork != nil, !(error is MiMoV26MultimodalError), + !(error is CancellationError), error as? MiMoV26AudioInputError != .cancelled + { + work.markManagedRequiredFailure() + } + if work.managedRequiredCompletionFailed || managedWork?.completionFailed == true { + servingIsValid = false + work.markManagedRequiredFailure() + throw MiMoV26AudioWorkFailure.drainFailed + } + if work.failedDrain { throw MiMoV26AudioWorkFailure.drainFailed } + try work.drain(invalidate: { servingIsValid = false }) + work.releaseAfterSuccessfulDrain() + throw error + } + } + + private func required( + _ phase: ManagedRequiredPhase, work: MiMoV26FailedAudioWork, + _ body: () throws -> T + ) throws -> T { + try work.requiredCompletion { + #if DEBUG + if work.isManaged { try beforeManagedRequiredCompletionForTesting?(phase) } + #endif + return try body() + } + } + + private func admitted( + clips: [MiMoV26DecodedPCM], plan: MiMoV26AudioInputPlan, + isCancelled: () -> Bool, owner: any MiMoV26AudioWorkReservation, + work: MiMoV26FailedAudioWork, errors: MLX.ErrorBox + ) throws -> [MiMoV26AudioCodeClip] { + let frontend = MiMoV26AudioFrontend(configuration: configuration) + var mels: [MiMoV26PreparedMel] = [] + for (index, clip) in clips.enumerated() { + mels.append( + try frontend.prepare( + pcm: clip, plan: plan, clipIndex: index, isCancelled: isCancelled)) + try work.trackManaged(mels.map(\.values)) + try errors.check() + } + var melFinite = MLXArray(true) + for mel in mels { melFinite = melFinite .&& all(isFinite(mel.values)) } + try work.trackManaged(mels.map(\.values) + [melFinite]) + try errors.check() + try owner.validate( + plan: plan, sourceIdentity: weights.sourceIdentity, generation: weights.generation) + // Explicit stage fence/readback, not a hidden property evaluation. + try required(.frontendEval, work: work) { + try withError { eval(mels.map(\.values) + [melFinite]) } + } + guard + try required( + .frontendFinite, work: work, { try withError { melFinite.item(Bool.self) } }) + else { throw MiMoV26AudioInputError.nonfiniteResult } + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + let encoded = try weights.encoder.encodeFeatures( + mels: mels, plan: plan, isCancelled: isCancelled) + try work.trackManaged([encoded.features]) + try errors.check() + guard encoded.generation == weights.generation, + encoded.inputPlanIdentity == (try plan.preparationIdentityData()) + else { + throw MiMoV26AudioInputError.weightsNotLoaded + } + let quantized = try weights.quantizer.quantize( + features: encoded.features, frameCounts: plan.codeFrameCounts, + tileFrames: plan.limits.rvqTileFrames, isCancelled: isCancelled) + try work.trackManaged([encoded.features, quantized.codes, quantized.allFinite]) + try errors.check() + try owner.validate( + plan: plan, sourceIdentity: weights.sourceIdentity, generation: weights.generation) + try required(.rvqEval, work: work) { + try withError { eval(quantized.codes, quantized.allFinite) } + } + guard + try required( + .rvqFinite, work: work, { try withError { quantized.allFinite.item(Bool.self) } }) + else { throw MiMoV26AudioInputError.nonfiniteResult } + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + let values = try required(.codesReadback, work: work) { + try withError { quantized.codes.asArray(Int32.self) } + } + let expected = try MiMoV26AudioChecked.product( + [plan.totalCodeFrames, configuration.quantizers], "host code count") + guard values.count == expected else { + throw MiMoV26AudioInputError.input("RVQ output accounting") + } + for (i, value) in values.enumerated() { + guard value >= 0, Int(value) < configuration.codebookSizes[i % configuration.quantizers] + else { + throw MiMoV26AudioInputError.input("RVQ emitted an invalid channel code") + } + } + var offset = 0 + return try plan.codeFrameCounts.map { frames in + let count = try MiMoV26AudioChecked.product( + [frames, configuration.quantizers], "clip code count") + defer { offset += count } + return MiMoV26AudioCodeClip( + codes: Array(values[offset ..< (offset + count)]), frameCount: frames) + } + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioPatch.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioPatch.swift new file mode 100644 index 0000000000..dc209e9504 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioPatch.swift @@ -0,0 +1,468 @@ +// Copyright © 2026 Eigen Labs. +// Derived from SGLang67bb6a58 mimo_audio.py (Apache-2.0), consuming Qwen2 +// from Transformers5.12.1/ddb849abe (Apache-2.0). Discrete codes only. +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +public enum MiMoV26AudioPatchError: Error, Equatable, Sendable { + case invalidConfiguration(String) + case invalidInput(String) + case executionLimit(String) + case invalidWeights(String) + case weightsNotLoaded +} + +/// One source code_list item/segment, in frame-major then channel-major order. +public struct MiMoV26AudioCodeClip: Equatable, Sendable { + public let codes: [Int32] + public let frameCount: Int + public init(codes: [Int32], frameCount: Int) { + self.codes = codes + self.frameCount = frameCount + } +} + +/// Caller-owned execution bounds; these do not declare model/API capacity. +public struct MiMoV26AudioPatchLimits: Equatable, Sendable { + public let maximumClips, maximumFrames, maximumPatches, maximumWorkingElements: Int + public init( + maximumClips: Int, maximumFrames: Int, maximumPatches: Int, maximumWorkingElements: Int + ) { + self.maximumClips = maximumClips + self.maximumFrames = maximumFrames + self.maximumPatches = maximumPatches + self.maximumWorkingElements = maximumWorkingElements + } +} + +private func audioProduct(_ values: [Int], _ name: String) throws -> Int { + var result = 1 + for value in values { + guard value >= 0 else { throw MiMoV26AudioPatchError.invalidConfiguration(name) } + let next = result.multipliedReportingOverflow(by: value) + guard !next.overflow else { + throw MiMoV26AudioPatchError.executionLimit(name + " overflow") + } + result = next.partialValue + } + return result +} +private func audioSum(_ values: [Int], _ name: String) throws -> Int { + var result = 0 + for value in values { + let next = result.addingReportingOverflow(value) + guard value >= 0 && !next.overflow else { + throw MiMoV26AudioPatchError.executionLimit(name + " overflow") + } + result = next.partialValue + } + return result +} + +private struct MiMoV26AudioShape { + let config: MiMoV26AudioConfiguration + let intermediate, projectionInput, projectionHidden: Int + let ropeTheta: Float + init(_ c: MiMoV26AudioConfiguration) throws { + config = c + func number(_ key: String) throws -> Decimal { + guard case .number(let value) = c.rawFields[key] else { + throw MiMoV26AudioPatchError.invalidConfiguration(key) + } + return value + } + func integer(_ key: String) throws -> Int { + let value = try number(key) + let i = NSDecimalNumber(decimal: value).int64Value + guard value == Decimal(i), let exact = Int(exactly: i), exact > 0, + exact <= Int(Int32.max) + else { + throw MiMoV26AudioPatchError.invalidConfiguration(key) + } + return exact + } + let headWidth = try audioProduct([c.queryHeads, c.headDim], "head geometry") + guard c.rawFields["input_full_attention"] == .bool(true), + c.rawFields["add_post_norm"] == .bool(true), + try integer("projection_layers") == 2, + try number("partial_rotary_factor") == 1, + try number("input_local_hidden_dropout") == 0, + c.groupSize == 4, c.headDim.isMultiple(of: 2), + c.hiddenSize == headWidth + else { + throw MiMoV26AudioPatchError.invalidConfiguration( + "requires full attention/full RoPE/post-norm/group4/two projections") + } + intermediate = try integer("input_local_intermediate_size") + projectionInput = try audioProduct([c.groupSize, c.hiddenSize], "projection input") + projectionHidden = try audioProduct([projectionInput, 4], "projection hidden") + ropeTheta = NSDecimalNumber(decimal: try number("rope_theta")).floatValue + let dimensions = [ + c.channels, c.hiddenSize, c.queryHeads, c.headDim, c.layers, + c.outputHiddenSize, c.speechVocabularySize, projectionInput, projectionHidden, + ] + guard ropeTheta.isFinite && ropeTheta > 0, + dimensions.allSatisfy({ $0 > 0 && $0 <= Int(Int32.max) }), + c.channels == 20, c.hiddenSize <= 1024, c.queryHeads <= 16, c.headDim <= 64, + c.layers <= 6, intermediate <= 4096, c.outputHiddenSize <= 4096, + c.speechVocabularySize <= 1280 + else { + throw MiMoV26AudioPatchError.invalidConfiguration("dimensions or RoPE theta") + } + // This component supports the authenticated audio-patch geometry and + // smaller diagnostic fixtures. Reject unknown larger architectures + // before constructing a parameter inventory or allocating modules. + for shape in tensorShapes().values { + guard try audioProduct(shape, "parameter geometry") <= Int(Int32.max) else { + throw MiMoV26AudioPatchError.invalidConfiguration( + "parameter exceeds MLX indexing range") + } + } + } + func tensorShapes() -> [String: [Int]] { + let c = config + let h = c.hiddenSize + var result: [String: [Int]] = [:] + for channel in 0 ..< c.channels { + result["speech_embeddings.\(channel).weight"] = [c.speechVocabularySize, h] + } + let prefix = "audio_encoder.input_local_transformer." + for layer in 0 ..< c.layers { + let p = prefix + "layers.\(layer)." + result[p + "input_layernorm.weight"] = [h] + result[p + "post_attention_layernorm.weight"] = [h] + for qkv in ["q_proj", "k_proj", "v_proj"] { + result[p + "self_attn.\(qkv).weight"] = [h, h] + result[p + "self_attn.\(qkv).bias"] = [h] + } + result[p + "self_attn.o_proj.weight"] = [h, h] + for projection in ["gate_proj", "up_proj"] { + result[p + "mlp.\(projection).weight"] = [intermediate, h] + } + result[p + "mlp.down_proj.weight"] = [h, intermediate] + } + result[prefix + "norm.weight"] = [h] + result["audio_encoder.projection.mlp.0.weight"] = [projectionHidden, projectionInput] + result["audio_encoder.projection.mlp.2.weight"] = [c.outputHiddenSize, projectionHidden] + return result + } +} + +/// Pure CPU preflight and repeat-last padding. Empty list is valid; an empty +/// item is invalid because the source requires audio[-1] for that item. +public struct MiMoV26AudioPatchPlan: Equatable, Sendable { + public let groupedCodes: [Int32] + public let clipPatchRanges: [Range] + public let patchCount, originalFrameCount, workingElements: Int + public static func make( + clips: [MiMoV26AudioCodeClip], configuration c: MiMoV26AudioConfiguration, + limits: MiMoV26AudioPatchLimits + ) throws -> Self { + let shape = try MiMoV26AudioShape(c) + guard + [ + limits.maximumClips, limits.maximumFrames, limits.maximumPatches, + limits.maximumWorkingElements, + ].allSatisfy({ $0 >= 0 }), + clips.count <= limits.maximumClips + else { throw MiMoV26AudioPatchError.executionLimit("clip limits") } + var frames = 0 + var patches = 0 + // Validate the complete request before allocating any derived arrays. + for clip in clips { + guard clip.frameCount > 0 else { + throw MiMoV26AudioPatchError.invalidInput("zero-frame item") + } + let elements = try audioProduct([clip.frameCount, c.channels], "code shape") + guard elements == clip.codes.count else { + throw MiMoV26AudioPatchError.invalidInput("exact frame/channel geometry") + } + guard clip.codes.allSatisfy({ $0 >= 0 && Int($0) < c.speechVocabularySize }) else { + throw MiMoV26AudioPatchError.invalidInput( + "speech code outside its embedding vocabulary") + } + frames = try audioSum([frames, clip.frameCount], "total frames") + let rounded = try audioSum([clip.frameCount, c.groupSize - 1], "padded frames") + patches = try audioSum([patches, rounded / c.groupSize], "patch count") + } + guard frames <= limits.maximumFrames, patches <= limits.maximumPatches, + patches <= Int(Int32.max) + else { throw MiMoV26AudioPatchError.executionLimit("frame/patch limit") } + let paddedFrames = try audioProduct([patches, c.groupSize], "padded frames") + let codeElements = try audioProduct([paddedFrames, c.channels], "padded codes") + let layerElements = try audioSum( + [ + audioProduct([5, c.hiddenSize], "attention work"), + audioProduct([3, shape.intermediate], "MLP work"), + ], "layer work") + let allHidden = try audioProduct( + [ + paddedFrames, + audioSum( + [ + 2 * c.hiddenSize, + audioProduct([c.layers, layerElements], "layer work"), + ], "hidden work"), + ], "hidden work") + let scores = try audioProduct( + [patches, c.queryHeads, c.groupSize, c.groupSize, c.layers], "attention scores") + let projection = try audioProduct( + [patches, audioSum([shape.projectionHidden, c.outputHiddenSize], "projection work")], + "projection work") + let working = try audioSum( + [codeElements, allHidden, scores, projection], "working elements") + guard working <= limits.maximumWorkingElements, codeElements <= Int(Int32.max) else { + throw MiMoV26AudioPatchError.executionLimit("working element limit") + } + var grouped: [Int32] = [] + var ranges: [Range] = [] + grouped.reserveCapacity(codeElements) + ranges.reserveCapacity(clips.count) + var offset = 0 + for clip in clips { + let n = (clip.frameCount + c.groupSize - 1) / c.groupSize + ranges.append(offset ..< (offset + n)) + offset += n + for frame in 0 ..< (n * c.groupSize) { + let start = min(frame, clip.frameCount - 1) * c.channels + grouped.append(contentsOf: clip.codes[start ..< (start + c.channels)]) + } + } + return .init( + groupedCodes: grouped, clipPatchRanges: ranges, patchCount: patches, + originalFrameCount: frames, workingElements: working) + } +} + +/// Preserve Qwen2's FP32 variance followed by input-dtype rounding BEFORE the +/// learned scale, rather than silently substituting a fused rounding policy. +private final class MiMoV26AudioRMSNorm: Module, UnaryLayer { + @ParameterInfo var weight: MLXArray + init(_ hidden: Int) { _weight.wrappedValue = MLXArray.ones([hidden]) } + func callAsFunction(_ x: MLXArray) -> MLXArray { + let f = x.asType(.float32) + return (f * rsqrt((f * f).mean(axis: -1, keepDims: true) + Float(1e-6))).asType(x.dtype) + * weight + } +} +private final class MiMoV26AudioAttention: Module { + @ModuleInfo(key: "q_proj") var q: Linear + @ModuleInfo(key: "k_proj") var k: Linear + @ModuleInfo(key: "v_proj") var v: Linear + @ModuleInfo(key: "o_proj") var output: Linear + let c: MiMoV26AudioConfiguration + init(_ c: MiMoV26AudioConfiguration) { + self.c = c + _q.wrappedValue = Linear(c.hiddenSize, c.hiddenSize, bias: true) + _k.wrappedValue = Linear(c.hiddenSize, c.hiddenSize, bias: true) + _v.wrappedValue = Linear(c.hiddenSize, c.hiddenSize, bias: true) + _output.wrappedValue = Linear(c.hiddenSize, c.hiddenSize, bias: false) + } + func callAsFunction(_ x: MLXArray, cosine: MLXArray, sine: MLXArray, mask: MLXArray) -> MLXArray + { + let batch = x.dim(0) + let half = c.headDim / 2 + func rotary(_ projected: MLXArray) -> MLXArray { + let t = projected.reshaped(batch, c.groupSize, c.queryHeads, c.headDim).transposed( + 0, 2, 1, 3) + let rotated = concatenated( + [-t[0..., 0..., 0..., half...], t[0..., 0..., 0..., .. MLXArray { down(silu(gate(x)) * up(x)) } +} +private final class MiMoV26AudioBlock: Module { + @ModuleInfo(key: "input_layernorm") var inputNorm: MiMoV26AudioRMSNorm + @ModuleInfo(key: "post_attention_layernorm") var postNorm: MiMoV26AudioRMSNorm + @ModuleInfo(key: "self_attn") var attention: MiMoV26AudioAttention + let mlp: MiMoV26AudioMLP + init(_ s: MiMoV26AudioShape) { + _inputNorm.wrappedValue = MiMoV26AudioRMSNorm(s.config.hiddenSize) + _postNorm.wrappedValue = MiMoV26AudioRMSNorm(s.config.hiddenSize) + _attention.wrappedValue = MiMoV26AudioAttention(s.config) + mlp = MiMoV26AudioMLP(s) + } + func callAsFunction(_ x: MLXArray, cosine: MLXArray, sine: MLXArray, mask: MLXArray) -> MLXArray + { + let h = x + attention(inputNorm(x), cosine: cosine, sine: sine, mask: mask) + return h + mlp(postNorm(h)) + } +} +private final class MiMoV26AudioLocalTransformer: Module { + let layers: [MiMoV26AudioBlock] + let norm: MiMoV26AudioRMSNorm + init(_ s: MiMoV26AudioShape) { + layers = (0 ..< s.config.layers).map { _ in MiMoV26AudioBlock(s) } + norm = MiMoV26AudioRMSNorm(s.config.hiddenSize) + } + func callAsFunction(_ input: MLXArray, cosine: MLXArray, sine: MLXArray, mask: MLXArray) + -> MLXArray + { + var x = input + for layer in layers { x = layer(x, cosine: cosine, sine: sine, mask: mask) } + return norm(x) + } +} +private final class MiMoV26AudioProjection: Module, UnaryLayer { + @ModuleInfo var mlp: (Linear, GELU, Linear) + init(_ s: MiMoV26AudioShape) { + _mlp.wrappedValue = ( + Linear(s.projectionInput, s.projectionHidden, bias: false), GELU(approximation: .none), + Linear(s.projectionHidden, s.config.outputHiddenSize, bias: false) + ) + } + func callAsFunction(_ x: MLXArray) -> MLXArray { mlp.2(mlp.1(mlp.0(x))) } +} +private final class MiMoV26AudioEncoderBody: Module { + @ModuleInfo(key: "input_local_transformer") var transformer: MiMoV26AudioLocalTransformer + let projection: MiMoV26AudioProjection + init(_ s: MiMoV26AudioShape) { + _transformer.wrappedValue = MiMoV26AudioLocalTransformer(s) + projection = MiMoV26AudioProjection(s) + } +} + +public struct MiMoV26AudioPatchOutput { + public let features: MLXArray + public let clipPatchRanges: [Range] +} + +public final class MiMoV26AudioPatchEncoder: Module { + public let configuration: MiMoV26AudioConfiguration + private let shape: MiMoV26AudioShape + @ModuleInfo(key: "speech_embeddings") private var embeddings: [Embedding] + @ModuleInfo(key: "audio_encoder") private var encoder: MiMoV26AudioEncoderBody + private var validatedWeightDType: DType? + + public init(configuration: MiMoV26AudioConfiguration) throws { + let shape = try MiMoV26AudioShape(configuration) + self.shape = shape + self.configuration = configuration + _embeddings.wrappedValue = (0 ..< configuration.channels).map { _ in + Embedding( + embeddingCount: configuration.speechVocabularySize, + dimensions: configuration.hiddenSize) + } + _encoder.wrappedValue = MiMoV26AudioEncoderBody(shape) + } + public static func expectedTensorShapes(configuration: MiMoV26AudioConfiguration) throws + -> [String: [Int]] + { + try MiMoV26AudioShape(configuration).tensorShapes() + } + public func loadNativeWeights(_ weights: [String: MLXArray], expectedDType: DType = .bfloat16) + throws + { + validatedWeightDType = nil + guard [.bfloat16, .float16, .float32].contains(expectedDType) else { + throw MiMoV26AudioPatchError.invalidWeights("unsupported dtype") + } + let expected = shape.tensorShapes() + guard Set(weights.keys) == Set(expected.keys) else { + throw MiMoV26AudioPatchError.invalidWeights("missing/unmapped audio tensors") + } + for (key, dimensions) in expected { + guard let value = weights[key], value.shape == dimensions, value.dtype == expectedDType + else { throw MiMoV26AudioPatchError.invalidWeights(key) } + } + try update( + parameters: ModuleParameters.unflattened(weights.map { ($0.key, $0.value) }), + verify: .all) + validatedWeightDType = expectedDType + } + + /// Called only after the complete published-layout plan has checked every + /// tensor and installed its declared packed module shells. + func loadPackedWeights(_ weights: [String: MLXArray], expectedDType: DType) throws { + validatedWeightDType = nil + guard expectedDType == .bfloat16 else { + throw MiMoV26AudioPatchError.invalidWeights("packed audio activation dtype") + } + let expected = Dictionary(uniqueKeysWithValues: parameters().flattened()) + guard Set(expected.keys) == Set(weights.keys) else { + throw MiMoV26AudioPatchError.invalidWeights("packed audio parameter closure") + } + for (key, parameter) in expected { + let value = weights[key]! + guard value.shape == parameter.shape, + value.dtype == (parameter.dtype == .uint32 ? .uint32 : expectedDType) + else { + throw MiMoV26AudioPatchError.invalidWeights(key) + } + } + try update(parameters: .unflattened(weights), verify: .all) + validatedWeightDType = expectedDType + } + @discardableResult public override func update( + parameters: ModuleParameters, verify: VerifyUpdate, + path: [String] = [], modulePath: [String] = [] + ) throws -> Self { + validatedWeightDType = nil + return try super.update( + parameters: parameters, verify: verify, path: path, modulePath: modulePath) + } + @discardableResult public override func update( + modules: ModuleChildren, verify: VerifyUpdate, + path: [String] = [], modulePath: [String] = [] + ) throws -> Self { + validatedWeightDType = nil + return try super.update( + modules: modules, verify: verify, path: path, modulePath: modulePath) + } + public func forward(clips: [MiMoV26AudioCodeClip], limits: MiMoV26AudioPatchLimits) throws + -> MiMoV26AudioPatchOutput + { + guard let dtype = validatedWeightDType else { + throw MiMoV26AudioPatchError.weightsNotLoaded + } + let plan = try MiMoV26AudioPatchPlan.make( + clips: clips, configuration: configuration, limits: limits) + let c = configuration + guard plan.patchCount > 0 else { + return .init( + features: MLXArray.zeros([0, c.outputHiddenSize], dtype: dtype), clipPatchRanges: [] + ) + } + let codes = MLXArray(plan.groupedCodes).reshaped(plan.patchCount, c.groupSize, c.channels) + var x = MLXArray.zeros([plan.patchCount, c.groupSize, c.hiddenSize], dtype: dtype) + for channel in 0 ..< c.channels { x = x + embeddings[channel](codes[0..., 0..., channel]) } + var angles: [Float] = [] + angles.reserveCapacity(c.groupSize * c.headDim / 2) + for position in 0 ..< c.groupSize { + for pair in 0 ..< (c.headDim / 2) { + angles.append( + Float(position) / pow(shape.ropeTheta, Float(2 * pair) / Float(c.headDim))) + } + } + let half = MLXArray(angles).reshaped(c.groupSize, c.headDim / 2) + let phase = concatenated([half, half], axis: -1).reshaped(1, 1, c.groupSize, c.headDim) + let cosine = cos(phase).asType(dtype) + let sine = sin(phase).asType(dtype) + let mask = MLXArray.ones([c.groupSize, c.groupSize], dtype: .bool) + x = encoder.transformer(x, cosine: cosine, sine: sine, mask: mask) + let features = encoder.projection(x.reshaped(plan.patchCount, shape.projectionInput)) + return .init(features: features, clipPatchRanges: plan.clipPatchRanges) + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioSidecarFile.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioSidecarFile.swift new file mode 100644 index 0000000000..b30592d823 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioSidecarFile.swift @@ -0,0 +1,328 @@ +// Copyright © 2026 Eigen Labs. +// Selected MiMo input-codec sidecar only; never a second root-model loader. + +import CryptoKit +import Foundation +import MLXLLM + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +public enum MiMoV26AudioSidecarError: Error, Equatable, Sendable { + case cancelled, unsafeFile, changedObject, shortRead, invalidHeader + case invalidConfiguration, wrongPayload, invalidBinding, overflow + case alreadyConsumed, insufficientReservation, unmaterializedTensor, invalidatedOwner +} + +func mimoAudioDigest(_ data: Data) -> String { + SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() +} + +func mimoAudioAdd(_ left: UInt64, _ right: UInt64) throws -> UInt64 { + let value = left.addingReportingOverflow(right) + guard !value.overflow else { throw MiMoV26AudioSidecarError.overflow } + return value.partialValue +} + +/// Audio-local FD owner. Children retain their opened directory ancestors; +/// payload bytes are always read from this exact FD, never reopened by path. +final class MiMoV26AudioSidecarDescriptor { + let url: URL + let state: MiMoV26FilesystemObjectState + private let parent: MiMoV26AudioSidecarDescriptor? + private let directory: Bool + private let handle: FileHandle + var fd: Int32 { handle.fileDescriptor } + + init(url: URL, directory: Bool, parent: MiMoV26AudioSidecarDescriptor? = nil) throws { + self.url = url + self.parent = parent + self.directory = directory + try parent?.validate() + var before = stat() + guard lstat(url.path, &before) == 0 else { throw MiMoV26AudioSidecarError.unsafeFile } + let expected = try Self.object(before, directory: directory) + let flags = O_RDONLY | O_CLOEXEC | O_NOFOLLOW | (directory ? O_DIRECTORY : 0) + let opened = + parent.map { openat($0.fd, url.lastPathComponent, flags) } ?? open(url.path, flags) + guard opened >= 0 else { throw MiMoV26AudioSidecarError.unsafeFile } + var actual = stat() + do { + guard fstat(opened, &actual) == 0, + try Self.object(actual, directory: directory) == expected + else { + throw MiMoV26AudioSidecarError.changedObject + } + state = expected + handle = FileHandle(fileDescriptor: opened, closeOnDealloc: true) + } catch { + close(opened) + throw error + } + try validate() + } + + private static func object(_ value: stat, directory: Bool) throws + -> MiMoV26FilesystemObjectState + { + guard mode_t(value.st_mode) & mode_t(S_IFMT) == mode_t(directory ? S_IFDIR : S_IFREG), + let bytes = Int(exactly: value.st_size), bytes >= 0 + else { + throw MiMoV26AudioSidecarError.unsafeFile + } + #if canImport(Darwin) + let modified = value.st_mtimespec + let changed = value.st_ctimespec + #else + let modified = value.st_mtim + let changed = value.st_ctim + #endif + return .init( + device: String(value.st_dev), inode: String(value.st_ino), bytes: bytes, + modifiedSeconds: Int64(modified.tv_sec), modifiedNanoseconds: Int64(modified.tv_nsec), + changedSeconds: Int64(changed.tv_sec), changedNanoseconds: Int64(changed.tv_nsec)) + } + + func validate() throws { + try parent?.validate() + var held = stat() + var named = stat() + guard fstat(fd, &held) == 0, lstat(url.path, &named) == 0, + try Self.object(held, directory: directory) == state, + try Self.object(named, directory: directory) == state + else { + throw MiMoV26AudioSidecarError.changedObject + } + } + + func read(offset: Int, count: Int, maximum: Int, isCancelled: () -> Bool) throws -> Data { + guard !isCancelled() else { throw MiMoV26AudioSidecarError.cancelled } + guard !directory, offset >= 0, count >= 0, maximum > 0, count <= maximum, + offset <= state.bytes, count <= state.bytes - offset + else { + throw MiMoV26AudioSidecarError.invalidHeader + } + try validate() + var result = Data(count: count) + var completed = 0 + try result.withUnsafeMutableBytes { bytes in + while completed < count { + guard !isCancelled() else { throw MiMoV26AudioSidecarError.cancelled } + try validate() + let amount = min(1 << 20, count - completed) + let readCount = pread( + fd, bytes.baseAddress!.advanced(by: completed), amount, + off_t(offset + completed)) + if readCount < 0 && errno == EINTR { continue } + guard readCount > 0 else { throw MiMoV26AudioSidecarError.shortRead } + completed += readCount + } + } + try validate() + return result + } + + /// Full-file authentication includes prefix, header and all unused payloads. + /// At most one1-MiB read buffer is live; cancellation does not publish a hash. + func authenticate( + expected: String, isCancelled: () -> Bool, + checkpoint: (Int) throws -> Void + ) throws -> String { + var hash = SHA256() + var offset = 0 + guard !isCancelled() else { throw MiMoV26AudioSidecarError.cancelled } + try validate() + try checkpoint(0) + while offset < state.bytes { + let count = min(1 << 20, state.bytes - offset) + let bytes = try read( + offset: offset, count: count, maximum: 1 << 20, isCancelled: isCancelled) + hash.update(data: bytes) + offset += count + if offset.isMultiple(of: 64 << 20) || offset == state.bytes { try checkpoint(offset) } + } + try validate() + guard !isCancelled() else { throw MiMoV26AudioSidecarError.cancelled } + let digest = hash.finalize().map { String(format: "%02x", $0) }.joined() + guard digest == expected else { throw MiMoV26AudioSidecarError.wrongPayload } + return digest + } +} + +/// Reject duplicate object keys before Foundation's dictionary decoding can +/// collapse them. Same bounded scanner policy as MiMoV26FilesystemWeights. +func mimoAudioUniqueKeys(_ data: Data) throws { + let bytes = [UInt8](data) + var stack: [Set?] = [] + var i = 0 + while i < bytes.count { + if bytes[i] == 123 || bytes[i] == 91 { + stack.append(bytes[i] == 123 ? Set() : nil) + guard stack.count <= 128 else { throw MiMoV26AudioSidecarError.invalidHeader } + } else if bytes[i] == 125 || bytes[i] == 93 { + guard !stack.isEmpty else { throw MiMoV26AudioSidecarError.invalidHeader } + stack.removeLast() + } else if bytes[i] == 34 { + let start = i + i += 1 + while i < bytes.count && bytes[i] != 34 { + if bytes[i] == 92 { i += 1 } + i += 1 + } + guard i < bytes.count else { throw MiMoV26AudioSidecarError.invalidHeader } + var next = i + 1 + while next < bytes.count && [9, 10, 13, 32].contains(bytes[next]) { next += 1 } + if next < bytes.count && bytes[next] == 58 { + guard let top = stack.indices.last, stack[top] != nil else { + throw MiMoV26AudioSidecarError.invalidHeader + } + let key = try JSONDecoder().decode(String.self, from: Data(bytes[start ... i])) + guard stack[top]!.insert(key).inserted else { + throw MiMoV26AudioSidecarError.invalidHeader + } + } + } + i += 1 + } + guard stack.isEmpty else { throw MiMoV26AudioSidecarError.invalidHeader } +} + +struct MiMoV26AudioSidecarHeader: Decodable { + struct Tensor: Decodable { + let dtype: MiMoV26AudioTensorType + let shape: [Int] + let data_offsets: [Int] + } + struct Key: CodingKey { + let stringValue: String + var intValue: Int? { nil } + init?(stringValue: String) { self.stringValue = stringValue } + init?(intValue: Int) { return nil } + } + let tensors: [String: Tensor] + init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: Key.self) + var result: [String: Tensor] = [:] + for key in container.allKeys { + if key.stringValue == "__metadata__" { + _ = try container.decode([String: String].self, forKey: key) + } else { + result[key.stringValue] = try container.decode(Tensor.self, forKey: key) + } + } + tensors = result + } + + static func parse(_ bytes: Data, tensorBytes: Int) throws -> Self { + guard !bytes.isEmpty, bytes.count <= 1 << 20, tensorBytes > 0 else { + throw MiMoV26AudioSidecarError.invalidHeader + } + try mimoAudioUniqueKeys(bytes) + let result = try JSONDecoder().decode(Self.self, from: bytes) + guard !result.tensors.isEmpty, result.tensors.count <= 828 else { + throw MiMoV26AudioSidecarError.invalidHeader + } + var cursor = 0 + for (_, tensor) in result.tensors.sorted(by: { + ($0.value.data_offsets.first ?? -1) < ($1.value.data_offsets.first ?? -1) + }) { + guard !tensor.shape.isEmpty, tensor.shape.count <= 8, + tensor.shape.allSatisfy({ $0 > 0 && $0 <= Int(Int32.max) }), + tensor.data_offsets.count == 2, tensor.data_offsets[0] == cursor + else { + throw MiMoV26AudioSidecarError.invalidHeader + } + var count: UInt64 = tensor.dtype == .bfloat16 ? 2 : 4 + for dimension in tensor.shape { + let next = count.multipliedReportingOverflow(by: UInt64(dimension)) + guard !next.overflow else { throw MiMoV26AudioSidecarError.overflow } + count = next.partialValue + } + guard let size = Int(exactly: count), size <= tensorBytes - cursor, + tensor.data_offsets[1] == cursor + size + else { throw MiMoV26AudioSidecarError.invalidHeader } + cursor += size + } + guard cursor == tensorBytes else { throw MiMoV26AudioSidecarError.invalidHeader } + return result + } +} + +final class MiMoV26AudioSidecarSource { + static let fileBytes = 1_872_618_384 + static let configurationSHA256 = + "e0702adae37947e0c980c38bae58ffa0d48bd492d523afe814aa4d73f008c7d1" + let root: URL + let configurationFile, payload: MiMoV26AudioSidecarDescriptor + let configuration: MiMoV26AudioInputConfiguration + let plan: MiMoV26AudioSidecarPlan + let header: MiMoV26AudioSidecarHeader + let headerSHA256: String + let headerBytes: Int + var payloadOffset: Int { 8 + headerBytes } + + init(root: URL, mainConfiguration: MiMoV26Configuration, isCancelled: () -> Bool) throws { + let canonical = root.resolvingSymlinksInPath().standardizedFileURL + guard canonical.isFileURL else { throw MiMoV26AudioSidecarError.unsafeFile } + let parent = try MiMoV26AudioSidecarDescriptor(url: canonical, directory: true) + let directory = try MiMoV26AudioSidecarDescriptor( + url: canonical.appendingPathComponent("audio_tokenizer"), directory: true, + parent: parent) + let configFile = try MiMoV26AudioSidecarDescriptor( + url: directory.url.appendingPathComponent("config.json"), directory: false, + parent: directory) + let payloadFile = try MiMoV26AudioSidecarDescriptor( + url: directory.url.appendingPathComponent("model.safetensors"), directory: false, + parent: directory) + guard configFile.state.bytes <= 1 << 20, payloadFile.state.bytes == Self.fileBytes else { + throw MiMoV26AudioSidecarError.invalidHeader + } + let data = try configFile.read( + offset: 0, count: configFile.state.bytes, + maximum: 1 << 20, isCancelled: isCancelled) + try mimoAudioUniqueKeys(data) + guard mimoAudioDigest(data) == Self.configurationSHA256 else { + throw MiMoV26AudioSidecarError.invalidConfiguration + } + let configuration = try MiMoV26AudioInputConfiguration( + sidecarJSON: data, mainConfiguration: mainConfiguration) + let prefix = try payloadFile.read(offset: 0, count: 8, maximum: 8, isCancelled: isCancelled) + let rawLength = prefix.enumerated().reduce(UInt64(0)) { + $0 | UInt64($1.element) << (8 * $1.offset) + } + guard let length = Int(exactly: rawLength), length > 0, length <= 1 << 20, + length < payloadFile.state.bytes - 8 + else { throw MiMoV26AudioSidecarError.invalidHeader } + let headerData = try payloadFile.read( + offset: 8, count: length, maximum: 1 << 20, isCancelled: isCancelled) + let header = try MiMoV26AudioSidecarHeader.parse( + headerData, tensorBytes: payloadFile.state.bytes - 8 - length) + var descriptors: [String: MiMoV26AudioTensorDescriptor] = [:] + for (name, tensor) in header.tensors { + descriptors[name] = .init( + shape: tensor.shape, dtype: tensor.dtype, + byteCount: tensor.data_offsets[1] - tensor.data_offsets[0]) + } + let plan = try MiMoV26AudioTokenizerWeights.preflight( + descriptors: descriptors, + configuration: configuration, + sourcePayloadSHA256: MiMoV26AudioTokenizerWeights.selectedPayloadSHA256) + self.root = canonical + self.configurationFile = configFile + self.payload = payloadFile + self.configuration = configuration + self.header = header + self.plan = plan + headerBytes = length + headerSHA256 = mimoAudioDigest(headerData) + try validate() + } + + func validate() throws { + try configurationFile.validate() + try payload.validate() + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioSidecarLoad.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioSidecarLoad.swift new file mode 100644 index 0000000000..3a57b4ee46 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioSidecarLoad.swift @@ -0,0 +1,293 @@ +// Copyright © 2026 Eigen Labs. Authenticated input-codec load, not serving activation. + +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +public struct MiMoV26AudioSidecarLoadRequest: Equatable, Encodable, Sendable { + public let sessionID: UUID + public let canonicalRoot, mainConfigurationSHA256, configurationSHA256, headerSHA256: String + public let payloadSHA256: String + public let configurationObject, payloadObject: MiMoV26FilesystemObjectState + public let fileBytes, headerBytes, inputStoredBytes, unusedStoredBytes, largestInputBytes: Int + public let inputTensorCount, unusedTensorCount: Int + public let requiredLoadBytes: UInt64 +} + +public protocol MiMoV26AudioSidecarLoadReservation: AnyObject { + var request: MiMoV26AudioSidecarLoadRequest { get } + var reservedLoadBytes: UInt64 { get } + /// Host implementation checks its actual registered lifecycle/ledger claim. + func validateActive() throws +} + +public enum MiMoV26AudioSidecarLoadPhase: String, Codable, Sendable { + case admitted, authenticating, authenticated, inputMaterialization, runtimeMaterialization, + complete +} + +public struct MiMoV26AudioSidecarLoadProgress: Encodable, Sendable { + public let phase: MiMoV26AudioSidecarLoadPhase + public let authenticatedFileBytes, inputTensorsCompleted, inputBytesCompleted, + runtimeRootsCompleted: Int +} + +public struct MiMoV26AudioSidecarLoadReceipt: Encodable, Sendable { + public let request: MiMoV26AudioSidecarLoadRequest + public let sourceIdentity: String + public let codecGeneration: UUID + public let authenticatedFileBytes, materializedInputTensors, materializedInputBytes, + runtimeRoots: Int + /// Serial eval completed, but the enclosing protected setup still owes its + /// actual construction fence before it can publish any serving contract. + public let requiresOuterConstructionCompletion = true +} + +private final class MiMoV26AudioSidecarLifetime { + let source: MiMoV26AudioSidecarSource + let reservation: any MiMoV26AudioSidecarLoadReservation + var valid = true + init(source: MiMoV26AudioSidecarSource, reservation: any MiMoV26AudioSidecarLoadReservation) { + self.source = source + self.reservation = reservation + } + func validate() throws { + guard valid else { throw MiMoV26AudioSidecarError.invalidatedOwner } + try source.validate() + try reservation.validateActive() + } +} + +/// Actual owned codec, never a Module or a second reflected target tree. +/// The codec retains its lifetime box; that box does not retain the codec. +public final class MiMoV26AudioSidecarLoaded { + public let receipt: MiMoV26AudioSidecarLoadReceipt + let codec: MiMoV26OwnedAudioCodec + private let lifetime: MiMoV26AudioSidecarLifetime + fileprivate init( + weights: MiMoV26AudioInputWeights, source: MiMoV26AudioSidecarSource, + reservation: any MiMoV26AudioSidecarLoadReservation, + mainConfiguration: MiMoV26Configuration, + receipt: MiMoV26AudioSidecarLoadReceipt + ) throws { + self.receipt = receipt + let lifetime = MiMoV26AudioSidecarLifetime(source: source, reservation: reservation) + let codec = try MiMoV26OwnedAudioCodec( + input: MiMoV26AudioInput(weights: weights), retaining: lifetime, + expectedSourceIdentity: receipt.sourceIdentity, + expectedGeneration: receipt.codecGeneration, + mainConfiguration: mainConfiguration) + self.lifetime = lifetime + self.codec = codec + } + public func validate() throws { + try lifetime.validate() + try codec.validate() + } + package func invalidate() { lifetime.valid = false } +} + +/// One-shot, non-Sendable source session. Async host transfer must use the same +/// consuming SendableBox pattern as the existing MiMo root serial session. +public final class MiMoV26AudioSidecarLoadSession { + public let request: MiMoV26AudioSidecarLoadRequest + let mainConfiguration: MiMoV26Configuration + private let source: MiMoV26AudioSidecarSource + private let lock = NSLock() + private var consumed = false + + public init( + root: URL, mainConfiguration: MiMoV26Configuration, + mainConfigurationSHA256: String, isCancelled: () -> Bool = { false } + ) throws { + guard mainConfigurationSHA256.utf8.count == 64, + mainConfigurationSHA256.utf8.allSatisfy({ + (48 ... 57).contains($0) || (97 ... 102).contains($0) + }) + else { + throw MiMoV26AudioSidecarError.invalidBinding + } + let source = try MiMoV26AudioSidecarSource( + root: root, mainConfiguration: mainConfiguration, + isCancelled: isCancelled) + let selected = source.plan.requiredInputNames.compactMap { source.plan.descriptors[$0] } + guard selected.count == 389, let largest = selected.map(\.byteCount).max() else { + throw MiMoV26AudioSidecarError.invalidHeader + } + // Three whole selected-subset copy families conservatively cover the + // retained read buffers, source arrays and transformed runtime roots. + // Also price one whole source file for IO/page-cache coexistence, the + // explicit BF16 table intermediate, largest read, per-object16-KiB slack + // and64MiB metadata. Unused weights still are never native tensors. + let input = UInt64(source.plan.inputStoredBytes) + let codebookBytes = source.plan.requiredInputNames.filter { + $0.hasPrefix("encoder.quantizer.") + } + .reduce(UInt64(0)) { $0 + UInt64(source.plan.descriptors[$1]!.byteCount) } + var total = try mimoAudioAdd(input, input) + for amount in [ + input, UInt64(source.payload.state.bytes), codebookBytes / 2, + UInt64(largest), UInt64(3 * 389 * 16_384), UInt64(64 << 20), + ] { + total = try mimoAudioAdd(total, amount) + } + self.source = source + self.mainConfiguration = mainConfiguration + request = .init( + sessionID: UUID(), canonicalRoot: source.root.path, + mainConfigurationSHA256: mainConfigurationSHA256, + configurationSHA256: MiMoV26AudioSidecarSource.configurationSHA256, + headerSHA256: source.headerSHA256, + payloadSHA256: MiMoV26AudioTokenizerWeights.selectedPayloadSHA256, + configurationObject: source.configurationFile.state, + payloadObject: source.payload.state, + fileBytes: source.payload.state.bytes, headerBytes: source.headerBytes + 8, + inputStoredBytes: source.plan.inputStoredBytes, + unusedStoredBytes: source.plan.retainedUnusedStoredBytes, + largestInputBytes: largest, inputTensorCount: selected.count, + unusedTensorCount: source.plan.descriptors.count - selected.count, + requiredLoadBytes: total) + } + + public func validateSource() throws { try source.validate() } + + public func load( + reservation: any MiMoV26AudioSidecarLoadReservation, + retaining work: NativeConstructionScope, + isCancelled: () -> Bool = { false }, + progress: (MiMoV26AudioSidecarLoadProgress) throws -> Void = { _ in } + ) throws + -> MiMoV26AudioSidecarLoaded + { + try work.withPhase(.serialLoad) { + try work.retainOwner(self) + try work.retainOwner(reservation) + try lock.withLock { + guard !consumed else { throw MiMoV26AudioSidecarError.alreadyConsumed } + consumed = true + } + var authenticated = 0 + var count = 0 + var bytes = 0 + var runtimeCount = 0 + func validate() throws { + guard !isCancelled(), !Task.isCancelled else { + throw MiMoV26AudioSidecarError.cancelled + } + guard reservation.request == request else { + throw MiMoV26AudioSidecarError.invalidBinding + } + guard reservation.reservedLoadBytes >= request.requiredLoadBytes else { + throw MiMoV26AudioSidecarError.insufficientReservation + } + try source.validate() + try reservation.validateActive() + } + func checkpoint(_ phase: MiMoV26AudioSidecarLoadPhase) throws { + try validate() + try progress( + .init( + phase: phase, authenticatedFileBytes: authenticated, + inputTensorsCompleted: count, inputBytesCompleted: bytes, + runtimeRootsCompleted: runtimeCount)) + try validate() + } + try checkpoint(.admitted) + let digest = try source.payload.authenticate( + expected: request.payloadSHA256, + isCancelled: { isCancelled() || Task.isCancelled } + ) { value in + authenticated = value + try checkpoint(.authenticating) + } + try checkpoint(.authenticated) + // Full-byte authentication is complete before constructing any + // tensor. Decoder/vocoder/training payloads are never instantiated. + var inputs: [String: MLXArray] = [:] + let ordered = source.plan.requiredInputNames.sorted { + source.header.tensors[$0]!.data_offsets[0] + < source.header.tensors[$1]!.data_offsets[0] + } + for name in ordered { + try checkpoint(.inputMaterialization) + let tensor = source.header.tensors[name]! + let size = tensor.data_offsets[1] - tensor.data_offsets[0] + let data = try source.payload.read( + offset: source.payloadOffset + tensor.data_offsets[0], + count: size, maximum: request.largestInputBytes, + isCancelled: { isCancelled() || Task.isCancelled }) + try validate() + // Retain raw Data until the enclosing actual construction fence + // as well as the native root. The three-copy charge includes it. + try work.retainValue(data) + try work.capture(Stream.cpu) + try work.capture(StreamOrDevice.default.stream) + try work.willSubmit() + let array = try withError { error in + // Explicit raw-byte initializer preserves BF16 storage bits; + // a numeric UInt16 conversion would corrupt the checkpoint. + let result = MLXArray(data, tensor.shape, dtype: tensor.dtype.dtype) + try work.retain(result) + try error.check() + eval(result) + try error.check() + return result + } + guard let info = try array.evaluatedBufferInfo(), info.allocatedBytes >= size, + info.isRowContiguous, array.nbytes == size + else { + throw MiMoV26AudioSidecarError.unmaterializedTensor + } + inputs[name] = array + count += 1 + bytes += size + try work.checkpoint("audioSidecar.sourceMaterialized") + } + guard count == request.inputTensorCount, bytes == request.inputStoredBytes else { + throw MiMoV26AudioSidecarError.invalidHeader + } + try validate() + let weights = try withError { error in + let result = try MiMoV26AudioTokenizerWeights.load( + plan: source.plan, inputWeights: inputs) + try work.retainValue(result) + try error.check() + return result + } + let roots = weights.materializationRoots + guard roots.count == request.inputTensorCount else { + throw MiMoV26AudioSidecarError.invalidBinding + } + for root in roots { + try checkpoint(.runtimeMaterialization) + try work.retain(root) + try work.capture(StreamOrDevice.default.stream) + try work.willSubmit() + try withError { error in + eval(root) + try error.check() + } + guard let info = try root.evaluatedBufferInfo(), info.allocatedBytes >= root.nbytes + else { + throw MiMoV26AudioSidecarError.unmaterializedTensor + } + runtimeCount += 1 + try work.checkpoint("audioSidecar.runtimeMaterialized") + } + try checkpoint(.complete) + let receipt = MiMoV26AudioSidecarLoadReceipt( + request: request, sourceIdentity: digest, + codecGeneration: weights.generation, authenticatedFileBytes: authenticated, + materializedInputTensors: count, materializedInputBytes: bytes, + runtimeRoots: runtimeCount) + let loaded = try MiMoV26AudioSidecarLoaded( + weights: weights, source: source, + reservation: reservation, mainConfiguration: mainConfiguration, receipt: receipt) + try work.retainOwner(loaded) + try work.invalidateOnFailedCompletion(loaded) { loaded.invalidate() } + try loaded.validate() + return loaded + } + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioTokenizerEncoder.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioTokenizerEncoder.swift new file mode 100644 index 0000000000..0c3697bacc --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioTokenizerEncoder.swift @@ -0,0 +1,285 @@ +// Copyright © 2026 Eigen Labs. +// Original source copyright 2026 Xiaomi Corporation and HuggingFace Inc. +// SPDX-License-Identifier: Apache-2.0 +// Adapted from Xiaomi/HuggingFace HF5711 modeling_mimo_v2.py (Apache-2.0). +import Foundation +import MLX +import MLXLLM +import MLXNN + +private final class MiMoV26CodecAttention: Module { + @ModuleInfo(key: "q_proj") var q: Linear + @ModuleInfo(key: "k_proj") var k: Linear + @ModuleInfo(key: "v_proj") var v: Linear + @ModuleInfo(key: "out_proj") var output: Linear + let heads, headDim, lookBack: Int + let local: Bool + init(_ c: MiMoV26AudioInputConfiguration, layer: Int) { + heads = c.heads + headDim = c.headDim + lookBack = c.localLookBack + local = c.usesLocalAttention(layer: layer) + _q.wrappedValue = Linear(c.hiddenSize, c.hiddenSize, bias: true) + _k.wrappedValue = Linear(c.hiddenSize, c.hiddenSize, bias: false) + _v.wrappedValue = Linear(c.hiddenSize, c.hiddenSize, bias: true) + _output.wrappedValue = Linear(c.hiddenSize, c.hiddenSize, bias: true) + } + func callAsFunction(_ x: MLXArray, lengths: [Int], cosine: MLXArray, sine: MLXArray) -> MLXArray + { + let count = x.dim(0) + let hidden = heads * headDim + func rotate(_ value: MLXArray) -> MLXArray { + let first = value[0..., 0..., 0 ..< (headDim / 2)] + let second = value[0..., 0..., (headDim / 2)...] + let half = concatenated([-second, first], axis: -1) + // Keep source BF16 intermediate multiplication/addition boundaries. + return value * cosine.expandedDimensions(axis: 1) + half + * sine.expandedDimensions(axis: 1) + } + let query = rotate(q(x).reshaped(count, heads, headDim)) + let key = rotate(k(x).reshaped(count, heads, headDim)) + let value = v(x).reshaped(count, heads, headDim) + var offset = 0 + var rows: [MLXArray] = [] + for length in lengths { + let end = offset + length + let positions = MLXArray(0 ..< length) + let delta = + positions.expandedDimensions(axis: 1) - positions.expandedDimensions(axis: 0) + var allowed = delta .>= Int32(0) + if local { allowed = allowed .&& (delta .<= Int32(lookBack)) } + let mask = MLX.where(allowed, Float(0), -Float.infinity).asType(.bfloat16) + let attended = MLXFast.scaledDotProductAttention( + queries: query[offset ..< end].transposed(1, 0, 2).expandedDimensions(axis: 0), + keys: key[offset ..< end].transposed(1, 0, 2).expandedDimensions(axis: 0), + values: value[offset ..< end].transposed(1, 0, 2).expandedDimensions(axis: 0), + scale: 1 / sqrt(Float(headDim)), mask: .array(mask)) + rows.append(attended.squeezed(axis: 0).transposed(1, 0, 2).reshaped(length, hidden)) + offset = end + } + return output(rows.count == 1 ? rows[0] : concatenated(rows, axis: 0)) + } +} + +private final class MiMoV26CodecBlock: Module { + @ModuleInfo(key: "self_attn") var attention: MiMoV26CodecAttention + @ModuleInfo(key: "self_attn_layer_norm") var beforeAttention: LayerNorm + @ModuleInfo(key: "final_layer_norm") var beforeFFN: LayerNorm + @ModuleInfo(key: "fc1") var up: Linear + @ModuleInfo(key: "fc2") var down: Linear + init(_ c: MiMoV26AudioInputConfiguration, layer: Int) { + _attention.wrappedValue = MiMoV26CodecAttention(c, layer: layer) + _beforeAttention.wrappedValue = LayerNorm(dimensions: c.hiddenSize, eps: 1e-5) + _beforeFFN.wrappedValue = LayerNorm(dimensions: c.hiddenSize, eps: 1e-5) + _up.wrappedValue = Linear(c.hiddenSize, c.ffnSize, bias: true) + _down.wrappedValue = Linear(c.ffnSize, c.hiddenSize, bias: true) + } + func callAsFunction(_ x: MLXArray, lengths: [Int], cosine: MLXArray, sine: MLXArray) -> MLXArray + { + let h = x + attention(beforeAttention(x), lengths: lengths, cosine: cosine, sine: sine) + return h + down(gelu(up(beforeFFN(h)))) + } +} + +private final class MiMoV26CodecBody: Module { + @ModuleInfo(key: "conv1") var first: Conv1d + @ModuleInfo(key: "conv2") var second: Conv1d + @ModuleInfo(key: "layers") var layers: [MiMoV26CodecBlock] + @ModuleInfo(key: "layer_norm") var finalNorm: LayerNorm + // The checkpoint's down_sample_layer.0.weight unflattens as an array. + // Register the same one-convolution list, not a module with a numeric key. + @ModuleInfo(key: "down_sample_layer") var pool: [Conv1d] + @ModuleInfo(key: "down_sample_norm") var poolNorm: LayerNorm + init(_ c: MiMoV26AudioInputConfiguration) { + _first.wrappedValue = Conv1d( + inputChannels: c.melBands, outputChannels: c.hiddenSize, kernelSize: 3, padding: 1, + bias: true) + _second.wrappedValue = Conv1d( + inputChannels: c.hiddenSize, outputChannels: c.hiddenSize, kernelSize: 3, stride: 2, + padding: 1, bias: true) + _layers.wrappedValue = (0 ..< c.layers).map { MiMoV26CodecBlock(c, layer: $0) } + _finalNorm.wrappedValue = LayerNorm(dimensions: c.hiddenSize, eps: 1e-5) + _pool.wrappedValue = [ + Conv1d( + inputChannels: c.hiddenSize, outputChannels: c.hiddenSize, kernelSize: 2, stride: 2, + bias: false) + ] + _poolNorm.wrappedValue = LayerNorm(dimensions: c.hiddenSize, eps: 1e-5) + } +} + +public struct MiMoV26AudioEncoderOutput { + public let features: MLXArray + public let inputPlanIdentity: Data + public let generation: UUID + fileprivate init(features: MLXArray, inputPlanIdentity: Data, generation: UUID) { + self.features = features + self.inputPlanIdentity = inputPlanIdentity + self.generation = generation + } +} + +public final class MiMoV26AudioTokenizerEncoder: Module { + public let configuration: MiMoV26AudioInputConfiguration + @ModuleInfo(key: "encoder") private var body: MiMoV26CodecBody + public private(set) var loadedGeneration: UUID? + public init(configuration: MiMoV26AudioInputConfiguration) { + self.configuration = configuration + _body.wrappedValue = MiMoV26CodecBody(configuration) + } + /// Metadata validation and graph installation only; no default evaluation. + public func loadNativeNetworkWeights(_ source: [String: MLXArray]) throws { + loadedGeneration = nil + let weights = try MiMoV26AudioTokenizerWeights.prepareNetwork( + source, configuration: configuration) + try update( + parameters: ModuleParameters.unflattened(weights.map { ($0.key, $0.value) }), + verify: .all) + loadedGeneration = UUID() + } + @discardableResult public override func update( + parameters: ModuleParameters, verify: VerifyUpdate, + path: [String] = [], modulePath: [String] = [] + ) throws -> Self { + loadedGeneration = nil + return try super.update( + parameters: parameters, verify: verify, path: path, modulePath: modulePath) + } + @discardableResult public override func update( + modules: ModuleChildren, verify: VerifyUpdate, + path: [String] = [], modulePath: [String] = [] + ) throws -> Self { + loadedGeneration = nil + return try super.update( + modules: modules, verify: verify, path: path, modulePath: modulePath) + } + + public func encodeFeatures( + mels: [MiMoV26PreparedMel], plan: MiMoV26AudioInputPlan, + isCancelled: () -> Bool = { false } + ) throws -> MiMoV26AudioEncoderOutput { + let identity = try plan.preparationIdentityData() + guard plan.pcmDescriptors != nil, mels.count == plan.melFrameCounts.count, + mels.enumerated().allSatisfy({ + $0.element.clipIndex == $0.offset && $0.element.inputPlanIdentity == identity + }) + else { + throw MiMoV26AudioInputError.input("prepared mel origin/order differs from plan") + } + return try encode(mels.map(\.values), plan: plan, isCancelled: isCancelled, trace: nil) + } + public func encodeMelFeatures( + mels: [MLXArray], plan: MiMoV26AudioInputPlan, + isCancelled: () -> Bool = { false } + ) throws -> MiMoV26AudioEncoderOutput { + guard plan.pcmDescriptors == nil else { + throw MiMoV26AudioInputError.input("precomputed mels cannot claim PCM preparation") + } + return try encode(mels, plan: plan, isCancelled: isCancelled, trace: nil) + } + + static func rotary(configuration c: MiMoV26AudioInputConfiguration, positions: [Int]) -> ( + inverse: MLXArray, cosine: MLXArray, sine: MLXArray + ) { + let exponent = + MLXArray(Array(stride(from: 0, to: c.headDim, by: 2))).asType(.float32) + / Float(c.headDim) + let inverse = (Float(1) / pow(c.ropeTheta, exponent)).asType(.bfloat16).asType(.float32) + let half = + MLXArray(positions).asType(.float32).expandedDimensions(axis: 1) + * inverse.expandedDimensions(axis: 0) + let phase = concatenated([half, half], axis: 1) + return (inverse, cos(phase).asType(.bfloat16), sin(phase).asType(.bfloat16)) + } + + /// Trace is internal/testing only: retaining intermediates is not a free + /// production diagnostic and must be separately budgeted by its caller. + func encode( + _ mels: [MLXArray], plan: MiMoV26AudioInputPlan, isCancelled: () -> Bool, + trace: ((String, MLXArray) -> Void)? + ) throws -> MiMoV26AudioEncoderOutput { + guard let generation = loadedGeneration else { + throw MiMoV26AudioInputError.weightsNotLoaded + } + guard plan.configuration == configuration, mels.count == plan.melFrameCounts.count, + zip(mels, plan.melFrameCounts).allSatisfy({ + $0.0.shape == [$0.1, configuration.melBands] && $0.0.dtype == .float32 + }) + else { + throw MiMoV26AudioInputError.input("mel geometry/dtype/configuration") + } + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + let identity = try plan.preparationIdentityData() + let c = configuration + var encodedGroups: [MLXArray] = [] + for (groupIndex, group) in plan.groups.enumerated() { + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + let segments = group.segmentIndices.map { plan.segments[$0] } + let rows = segments.map { segment -> MLXArray in + let x = mels[segment.clipIndex][ + segment.melStart ..< (segment.melStart + segment.melFrames)] + return padded( + x, widths: [IntOrPair((0, group.maximumMelFrames - segment.melFrames)), 0] + ).expandedDimensions(axis: 0) + } + let input = (rows.count == 1 ? rows[0] : concatenated(rows, axis: 0)).asType(.bfloat16) + let conv1 = gelu(body.first(input)) + let conv2 = gelu(body.second(conv1)) + trace?("group.\(groupIndex).conv1", conv1) + trace?("group.\(groupIndex).conv2", conv2) + let lengths = segments.map(\.convFrames) + var hidden = concatenated( + segments.enumerated().map { conv2[$0.offset, 0 ..< $0.element.convFrames, 0...] }, + axis: 0) + let rotary = Self.rotary( + configuration: c, positions: lengths.flatMap { Array(0 ..< $0) }) + trace?("group.\(groupIndex).inverse", rotary.inverse) + trace?("group.\(groupIndex).cosine", rotary.cosine) + trace?("group.\(groupIndex).sine", rotary.sine) + var saved: MLXArray? + for (i, layer) in body.layers.enumerated() { + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + hidden = layer(hidden, lengths: lengths, cosine: rotary.cosine, sine: rotary.sine) + if i == c.skipLayerIndex { saved = hidden } + trace?("group.\(groupIndex).layer.\(i)", hidden) + } + hidden = body.finalNorm(hidden + saved!) + trace?("group.\(groupIndex).normalized", hidden) + var offset = 0 + var paddedHidden: [MLXArray] = [] + for length in lengths { + let valid = hidden[offset ..< (offset + length)] + var row = valid + if length < group.maximumConvFrames { + let tail = broadcast( + valid[(length - 1) ..< length], + to: [group.maximumConvFrames - length, c.hiddenSize]) + row = concatenated([valid, tail], axis: 0) + } + if group.maximumConvFrames % 2 != 0 { + row = padded(row, widths: [IntOrPair((0, 1)), 0]) + } + paddedHidden.append(row.expandedDimensions(axis: 0)) + offset += length + } + let poolInput = + paddedHidden.count == 1 ? paddedHidden[0] : concatenated(paddedHidden, axis: 0) + trace?("group.\(groupIndex).pool_input", poolInput) + let pooled = gelu(body.pool[0](poolInput)) + let packed = concatenated( + segments.enumerated().map { pooled[$0.offset, 0 ..< $0.element.codeFrames, 0...] }, + axis: 0) + let output = body.poolNorm(packed) + trace?("group.\(groupIndex).features", output) + encodedGroups.append(output) + } + let features = + encodedGroups.isEmpty + ? MLXArray.zeros([0, c.hiddenSize], dtype: .bfloat16) + : encodedGroups.count == 1 ? encodedGroups[0] : concatenated(encodedGroups, axis: 0) + guard features.shape == [plan.totalCodeFrames, c.hiddenSize] else { + throw MiMoV26AudioInputError.input("encoder frame accounting") + } + return .init(features: features, inputPlanIdentity: identity, generation: generation) + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioTokenizerWeights.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioTokenizerWeights.swift new file mode 100644 index 0000000000..6a21aff96c --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26AudioTokenizerWeights.swift @@ -0,0 +1,254 @@ +// Copyright © 2026 Eigen Labs. Input-only strict maps for the retained sidecar. +import Foundation +import MLX +import MLXLLM + +public enum MiMoV26AudioTensorType: String, Codable, Sendable { + case bfloat16 = "BF16" + case float32 = "F32" + var dtype: DType { self == .bfloat16 ? .bfloat16 : .float32 } + var bytes: Int { self == .bfloat16 ? 2 : 4 } +} +public struct MiMoV26AudioTensorDescriptor: Codable, Equatable, Sendable { + public let shape: [Int] + public let dtype: MiMoV26AudioTensorType + public let byteCount: Int + public init(shape: [Int], dtype: MiMoV26AudioTensorType, byteCount: Int) { + self.shape = shape + self.dtype = dtype + self.byteCount = byteCount + } +} +public struct MiMoV26AudioSidecarPlan: Sendable { + public let configuration: MiMoV26AudioInputConfiguration + public let descriptors: [String: MiMoV26AudioTensorDescriptor] + public let requiredInputNames: Set + public let sourcePayloadSHA256: String + public let inputStoredBytes, retainedUnusedStoredBytes: Int + fileprivate init( + configuration: MiMoV26AudioInputConfiguration, + descriptors: [String: MiMoV26AudioTensorDescriptor], + requiredInputNames: Set, sourcePayloadSHA256: String, inputStoredBytes: Int, + retainedUnusedStoredBytes: Int + ) { + self.configuration = configuration + self.descriptors = descriptors + self.requiredInputNames = requiredInputNames + self.sourcePayloadSHA256 = sourcePayloadSHA256 + self.inputStoredBytes = inputStoredBytes + self.retainedUnusedStoredBytes = retainedUnusedStoredBytes + } +} +public struct MiMoV26AudioInputWeights { + public let encoder: MiMoV26AudioTokenizerEncoder + public let quantizer: MiMoV26ResidualVectorQuantizer + public let configuration: MiMoV26AudioInputConfiguration + public let sourceIdentity: String + public let generation: UUID + /// Transformed owners, NOT a source-file read-order or physical-byte receipt. + public var materializationRoots: [MLXArray] { + encoder.parameters().flattened().sorted { $0.0 < $1.0 }.map { $0.1 } + + quantizer.materializationRoots + } + fileprivate init( + encoder: MiMoV26AudioTokenizerEncoder, quantizer: MiMoV26ResidualVectorQuantizer, + configuration: MiMoV26AudioInputConfiguration, sourceIdentity: String, generation: UUID + ) { + self.encoder = encoder + self.quantizer = quantizer + self.configuration = configuration + self.sourceIdentity = sourceIdentity + self.generation = generation + } +} + +public enum MiMoV26AudioTokenizerWeights { + public static let selectedPayloadSHA256 = + "077033345d80eef3a315e8d394e0589667e80e4cdaba9bc5a7488410c6657265" + + public static func networkSourceShapes(configuration c: MiMoV26AudioInputConfiguration) + -> [String: [Int]] + { + var shapes: [String: [Int]] = [ + "encoder.conv1.weight": [c.hiddenSize, c.melBands, 3], + "encoder.conv1.bias": [c.hiddenSize], + "encoder.conv2.weight": [c.hiddenSize, c.hiddenSize, 3], + "encoder.conv2.bias": [c.hiddenSize], + "encoder.layer_norm.weight": [c.hiddenSize], "encoder.layer_norm.bias": [c.hiddenSize], + "encoder.down_sample_layer.0.weight": [c.hiddenSize, c.hiddenSize, 2], + "encoder.down_sample_norm.weight": [c.hiddenSize], + "encoder.down_sample_norm.bias": [c.hiddenSize], + ] + for i in 0 ..< c.layers { + layerShapes( + prefix: "encoder.layers.\(i)", width: c.hiddenSize, ffn: c.ffnSize, into: &shapes) + } + return shapes + } + public static func inputSourceShapes(configuration c: MiMoV26AudioInputConfiguration) + -> [String: [Int]] + { + var shapes = networkSourceShapes(configuration: c) + for (i, bins) in c.codebookSizes.enumerated() { + shapes[tableName(i)] = [bins, c.hiddenSize] + } + return shapes + } + static func tableName(_ index: Int) -> String { + "encoder.quantizer.vq.layers.\(index)._codebook.embed" + } + private static func layerShapes( + prefix: String, width: Int, ffn: Int, into shapes: inout [String: [Int]] + ) { + for name in ["q_proj", "k_proj", "v_proj", "out_proj"] { + shapes[prefix + ".self_attn." + name + ".weight"] = [width, width] + if name != "k_proj" { shapes[prefix + ".self_attn." + name + ".bias"] = [width] } + } + for name in ["self_attn_layer_norm", "final_layer_norm"] { + shapes[prefix + "." + name + ".weight"] = [width] + shapes[prefix + "." + name + ".bias"] = [width] + } + shapes[prefix + ".fc1.weight"] = [ffn, width] + shapes[prefix + ".fc1.bias"] = [ffn] + shapes[prefix + ".fc2.weight"] = [width, ffn] + shapes[prefix + ".fc2.bias"] = [width] + } + private static func retainedShapes(configuration c: MiMoV26AudioInputConfiguration) -> [String: + [Int]] + { + // Exact selected asset closure. These values are not instantiated as + // input modules or treated as proof of an audio-output capability. + var shapes: [String: [Int]] = [ + "decoder.dconv1.conv.bias": [1024], "decoder.dconv1.conv.weight": [1024, 1024, 2], + "decoder.dconv1.norm.bias": [1024], "decoder.dconv1.norm.weight": [1024], + "decoder.dconv2.conv.bias": [128], "decoder.dconv2.conv.weight": [1024, 128, 3], + "decoder.dconv2.norm.bias": [128], "decoder.dconv2.norm.weight": [128], + "decoder.layer_norm.bias": [1024], "decoder.layer_norm.weight": [1024], + "decoder.vocoder.istft.window": [960], "decoder.vocoder.out.bias": [962], + "decoder.vocoder.out.weight": [962, 128], + ] + for (i, pair) in [(481, 128), (241, 64), (121, 32)].enumerated() { + shapes["decoder.mel_loss_fn.mel_transforms.\(i).mel_scale.fb"] = [pair.0, pair.1] + shapes["decoder.mel_loss_fn.mel_transforms.\(i).spectrogram.window"] = [ + (pair.0 - 1) * 2 + ] + } + for i in 0 ..< 24 { + layerShapes(prefix: "decoder.layers.\(i)", width: 1024, ffn: 4096, into: &shapes) + } + for (i, bins) in c.codebookSizes.enumerated() { + let prefix = "encoder.quantizer.vq.layers.\(i)._codebook." + shapes[prefix + "embed_avg"] = [bins, c.hiddenSize] + shapes[prefix + "cluster_size"] = [bins] + shapes[prefix + "inited"] = [1] + } + return shapes + } + + /// The source digest is an owner-supplied reference, not hashing performed + /// here. Root's authenticated filesystem/load session verifies the bytes. + public static func preflight( + descriptors: [String: MiMoV26AudioTensorDescriptor], + configuration c: MiMoV26AudioInputConfiguration, sourcePayloadSHA256: String + ) throws -> MiMoV26AudioSidecarPlan { + guard sourcePayloadSHA256 == selectedPayloadSHA256, c.hiddenSize == 1024, c.layers == 24, + c.heads == 16, c.ffnSize == 4096, c.melBands == 128, + c.codebookSizes == [1024, 1024, 256] + Array(repeating: 128, count: 17) + else { + throw MiMoV26AudioInputError.weights("selected sidecar/profile identity") + } + let input = inputSourceShapes(configuration: c) + let retained = retainedShapes(configuration: c) + let expected = input.merging(retained) { _, _ in + preconditionFailure("duplicate sidecar descriptor") + } + guard expected.count == 828, input.count == 389, Set(descriptors.keys) == Set(expected.keys) + else { + throw MiMoV26AudioInputError.weights("missing/unclassified sidecar tensors") + } + var inputBytes = 0 + var retainedBytes = 0 + for (name, shape) in expected { + let d = descriptors[name]! + let type: MiMoV26AudioTensorType = + name.hasPrefix("encoder.") && !name.hasPrefix("encoder.quantizer.") + ? .bfloat16 : .float32 + let count = try MiMoV26AudioChecked.product(shape + [type.bytes], name) + guard d.shape == shape, d.dtype == type, d.byteCount == count else { + throw MiMoV26AudioInputError.weights(name) + } + if input[name] != nil { + inputBytes = try MiMoV26AudioChecked.add(inputBytes, count, "input weights") + } else { + retainedBytes = try MiMoV26AudioChecked.add( + retainedBytes, count, "retained asset weights") + } + } + guard inputBytes == 634_204_160, retainedBytes == 1_238_321_176 else { + throw MiMoV26AudioInputError.weights("sidecar byte closure") + } + return .init( + configuration: c, descriptors: descriptors, requiredInputNames: Set(input.keys), + sourcePayloadSHA256: sourcePayloadSHA256, + inputStoredBytes: inputBytes, retainedUnusedStoredBytes: retainedBytes) + } + + public static func load(plan: MiMoV26AudioSidecarPlan, inputWeights: [String: MLXArray]) throws + -> MiMoV26AudioInputWeights + { + guard Set(inputWeights.keys) == plan.requiredInputNames else { + throw MiMoV26AudioInputError.weights("input subset closure") + } + return try makeBundle( + configuration: plan.configuration, weights: inputWeights, + identity: plan.sourcePayloadSHA256) + } + static func fixtureBundle( + configuration: MiMoV26AudioInputConfiguration, weights: [String: MLXArray] + ) throws -> MiMoV26AudioInputWeights { + try makeBundle( + configuration: configuration, weights: weights, identity: "synthetic-hf5711-fixture") + } + private static func makeBundle( + configuration c: MiMoV26AudioInputConfiguration, weights: [String: MLXArray], + identity: String + ) throws -> MiMoV26AudioInputWeights { + let expected = inputSourceShapes(configuration: c) + guard Set(weights.keys) == Set(expected.keys) else { + throw MiMoV26AudioInputError.weights("input tensor keys") + } + for (name, shape) in expected { + let type: DType = name.hasPrefix("encoder.quantizer.") ? .float32 : .bfloat16 + guard weights[name]!.shape == shape, weights[name]!.dtype == type else { + throw MiMoV26AudioInputError.weights(name) + } + } + let encoder = MiMoV26AudioTokenizerEncoder(configuration: c) + try encoder.loadNativeNetworkWeights( + weights.filter { !$0.key.hasPrefix("encoder.quantizer.") }) + let quantizer = try MiMoV26ResidualVectorQuantizer( + configuration: c, sourceTables: c.codebookSizes.indices.map { weights[tableName($0)]! }) + return .init( + encoder: encoder, quantizer: quantizer, configuration: c, sourceIdentity: identity, + generation: encoder.loadedGeneration!) + } + static func prepareNetwork( + _ weights: [String: MLXArray], configuration c: MiMoV26AudioInputConfiguration + ) throws -> [String: MLXArray] { + let expected = networkSourceShapes(configuration: c) + guard Set(weights.keys) == Set(expected.keys) else { + throw MiMoV26AudioInputError.weights("network tensor closure") + } + for (name, shape) in expected { + guard weights[name]!.shape == shape, weights[name]!.dtype == .bfloat16 else { + throw MiMoV26AudioInputError.weights(name) + } + } + let convolutionNames: Set = [ + "encoder.conv1.weight", "encoder.conv2.weight", "encoder.down_sample_layer.0.weight", + ] + return weights.mapValues { $0 }.map { name, value in + (name, convolutionNames.contains(name) ? contiguous(value.transposed(0, 2, 1)) : value) + }.reduce(into: [:]) { $0[$1.0] = $1.1 } + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26ConvertedWeights.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26ConvertedWeights.swift new file mode 100644 index 0000000000..df5848d9b1 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26ConvertedWeights.swift @@ -0,0 +1,430 @@ +// Copyright © 2026 Eigen Labs. +// Strict in-memory loading for the authenticated native MiMo converted layout. +// No filesystem payload discovery, factory alias or quantization recipe change. +import CryptoKit +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +public enum MiMoV26ConvertedLoadError: Error, Equatable, Sendable { + case invalidConfiguration(String) + case invalidInventory(String) + case invalidTensor(String) + case invalidQuantization(String) + case incompatibleModule(String) + case invalidProvenance(String) +} + +public enum MiMoV26ConvertedScalarType: String, Codable, Sendable { + case bfloat16 = "BF16" + case float16 = "F16" + case float32 = "F32" + case uint32 = "U32" + case uint8 = "U8" + var dtype: DType { + switch self { + case .bfloat16: .bfloat16 + case .float16: .float16 + case .float32: .float32 + case .uint32: .uint32 + case .uint8: .uint8 + } + } + var bytes: Int { self == .uint8 ? 1 : (self == .float32 || self == .uint32 ? 4 : 2) } +} + +/// Describes a caller-owned tensor/header. It is not a payload-hash assertion. +public struct MiMoV26ConvertedTensorDescriptor: Codable, Equatable, Sendable { + public let shape: [Int] + public let dtype: MiMoV26ConvertedScalarType + public let file: String + public init(shape: [Int], dtype: MiMoV26ConvertedScalarType, file: String) { + self.shape = shape + self.dtype = dtype + self.file = file + } +} + +/// Descriptive provenance supplied by the owner. Hash-shaped receipt fields +/// bind references only; this seam does not independently verify their content. +public struct MiMoV26ConvertedProvenance: Equatable, Sendable { + public enum Layout: String, Codable, Sendable { case nativeConversion, mlxVLM } + public let layout: Layout + public let artifactID, sourceRepository, sourceRevision: String + public let conversionManifestSHA256: String + public let payloadVerificationReceiptSHA256: String? + public init( + artifactID: String, sourceRepository: String, sourceRevision: String, + conversionManifestSHA256: String, payloadVerificationReceiptSHA256: String? = nil, + layout: Layout = .nativeConversion + ) { + self.layout = layout + self.artifactID = artifactID + self.sourceRepository = sourceRepository + self.sourceRevision = sourceRevision + self.conversionManifestSHA256 = conversionManifestSHA256 + self.payloadVerificationReceiptSHA256 = payloadVerificationReceiptSHA256 + } +} + +public enum MiMoV26ConvertedComponent: String, Codable, CaseIterable, Sendable { + case target, vision, audioPatch, mtp +} + +func convertedHash(_ data: Data) -> String { + SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() +} +func convertedHex(_ value: String, count: Int) -> Bool { + value.utf8.count == count + && value.utf8.allSatisfy { (48 ... 57).contains($0) || (97 ... 102).contains($0) } +} +func convertedProduct(_ values: [Int], _ name: String) throws -> Int { + var n = 1 + for value in values { + let next = n.multipliedReportingOverflow(by: value) + guard value > 0 && !next.overflow else { + throw MiMoV26ConvertedLoadError.invalidInventory("overflow/nonpositive " + name) + } + n = next.partialValue + } + return n +} + +struct MiMoV26ConvertedIndex: Decodable { + struct Metadata: Decodable { + let totalSize: Int + enum CodingKeys: String, CodingKey { case totalSize = "total_size" } + } + let metadata: Metadata + let weightMap: [String: String] + enum CodingKeys: String, CodingKey { + case metadata + case weightMap = "weight_map" + } +} + +/// Complete root-bundle plan, made without constructing MLX modules/arrays. +/// Source-layout metadata remains unchanged; descriptors must prove split Q/K/V. +public struct MiMoV26ConvertedLoadPlan: Sendable { + public let configuration: MiMoV26Configuration + public let descriptors: [String: MiMoV26ConvertedTensorDescriptor] + public let components: [MiMoV26ConvertedComponent: Set] + public let targetExpertModulePaths: Set + /// Original file names stay in descriptors/components for source integrity. + /// Only this validated bijection renames handles at component installation. + public let parameterNames: [String: String] + let targetQuantizationPolicies: [String: MiMoV26Quantization.Policy] + let audioQuantizationPolicies: [String: MiMoV26Quantization.Policy] + let floatingMTP: Bool + public let configSHA256, indexSHA256, descriptorSHA256: String + public let rootFiles: Set + public let tensorBytes: Int + public let provenance: MiMoV26ConvertedProvenance + /// Separately packaged trained components are not claimed loaded by this seam. + public let externalRequiredComponents: [String] + let floatingType: MiMoV26ConvertedScalarType + + /// Payload already included in tensorBytes, not additional load/serving + /// credit. Inventory products and the total were overflow-checked by make. + public func tensorBytes(for component: MiMoV26ConvertedComponent) -> Int { + (components[component] ?? []).reduce(0) { total, key in + let descriptor = descriptors[key]! + return total + descriptor.shape.reduce(descriptor.dtype.bytes, *) + } + } + + public static func make( + configurationData: Data, indexData: Data, + descriptors: [String: MiMoV26ConvertedTensorDescriptor], + provenance: MiMoV26ConvertedProvenance + ) throws -> Self { + if provenance.layout == .mlxVLM { + return try MiMoV26MLXVLMPlan.make( + configurationData: configurationData, + indexData: indexData, descriptors: descriptors, provenance: provenance) + } + let c = try JSONDecoder().decode(MiMoV26Configuration.self, from: configurationData) + let index = try JSONDecoder().decode(MiMoV26ConvertedIndex.self, from: indexData) + guard !provenance.artifactID.isEmpty, + provenance.sourceRepository == "XiaomiMiMo/MiMo-V2.6-Flash-RL", + convertedHex(provenance.sourceRevision, count: 40), + convertedHex(provenance.conversionManifestSHA256, count: 64), + provenance.payloadVerificationReceiptSHA256.map({ convertedHex($0, count: 64) }) ?? true + else { + throw MiMoV26ConvertedLoadError.invalidProvenance("artifact/source/receipt identity") + } + guard c.numHiddenLayers <= 48, c.hiddenSize <= 4096, c.intermediateSize <= 16384, + c.moeIntermediateSize <= 2048, c.routedExpertCount <= 256, c.vocabularySize <= 152576, + c.numNextnPredictLayers == 3, !c.tieWordEmbeddings, !c.attentionBias, + c.sharedExpertCount == nil || c.sharedExpertCount == 0, + c.attentionDropout == 0, let vision = c.vision, let audio = c.audio, + vision.depth <= 28, vision.hiddenSize <= 1280, vision.intermediateSize <= 4608, + let mtp = c.embeddedMTP, mtp.numLayers == 3, + let policy = c.quantization.nativeDefault, policy.mode == "mxfp4", + policy.bits == 4, policy.groupSize == 32 + else { + throw MiMoV26ConvertedLoadError.invalidConfiguration( + "requires complete converted target/vision/audio/MTP geometry") + } + let dtype: MiMoV26ConvertedScalarType = + c.dtype == "bfloat16" ? .bfloat16 : (c.dtype == "float16" ? .float16 : .float32) + var expected: [String: (shape: [Int], dtype: MiMoV26ConvertedScalarType)] = [:] + var groups = Dictionary( + uniqueKeysWithValues: MiMoV26ConvertedComponent.allCases.map { ($0, Set()) }) + var experts = Set() + var mtpProjections = Set() + func add( + _ key: String, _ shape: [Int], _ type: MiMoV26ConvertedScalarType, + _ component: MiMoV26ConvertedComponent + ) throws { + guard expected[key] == nil, shape.allSatisfy({ $0 > 0 && $0 <= Int(Int32.max) }) else { + throw MiMoV26ConvertedLoadError.invalidInventory("duplicate/invalid shape: " + key) + } + _ = try convertedProduct(shape + [type.bytes], key) + expected[key] = (shape, type) + groups[component, default: []].insert(key) + } + try add("model.embed_tokens.weight", [c.vocabularySize, c.hiddenSize], dtype, .target) + try add("model.norm.weight", [c.hiddenSize], dtype, .target) + try add("lm_head.weight", [c.vocabularySize, c.hiddenSize], dtype, .target) + for layer in 0 ..< c.numHiddenLayers { + let p = "model.layers.\(layer)." + let g = try c.attentionGeometry(at: layer) + let q = try convertedProduct([g.queryHeads, g.headDim], "Q width") + let k = try convertedProduct([g.keyValueHeads, g.headDim], "K width") + let v = try convertedProduct([g.keyValueHeads, g.valueHeadDim], "V width") + let out = try convertedProduct([g.queryHeads, g.valueHeadDim], "O width") + for name in ["input_layernorm", "post_attention_layernorm"] { + try add(p + name + ".weight", [c.hiddenSize], dtype, .target) + } + for (name, width) in [("q_proj", q), ("k_proj", k), ("v_proj", v)] { + try add(p + "self_attn." + name + ".weight", [width, c.hiddenSize], dtype, .target) + } + try add(p + "self_attn.o_proj.weight", [c.hiddenSize, out], dtype, .target) + if g.hasSinks { + try add(p + "self_attn.attention_sink_bias", [g.queryHeads], dtype, .target) + } + if c.moeLayerFrequency[layer] == 1 { + try add( + p + "mlp.gate.weight", [c.routedExpertCount, c.hiddenSize], + c.moeRouterDType == "bfloat16" ? .bfloat16 : .float32, .target) + try add( + p + "mlp.gate.e_score_correction_bias", [c.routedExpertCount], .float32, .target + ) + for name in ["gate_proj", "up_proj", "down_proj"] { + let rows = name == "down_proj" ? c.hiddenSize : c.moeIntermediateSize + let cols = name == "down_proj" ? c.moeIntermediateSize : c.hiddenSize + guard cols.isMultiple(of: 32) else { + throw MiMoV26ConvertedLoadError.invalidQuantization("MXFP4 dimensions") + } + let module = p + "mlp.switch_mlp." + name + experts.insert(module) + try add( + module + ".weight", [c.routedExpertCount, rows, cols / 8], .uint32, .target) + try add( + module + ".scales", [c.routedExpertCount, rows, cols / 32], .uint8, .target) + } + } else { + for name in ["gate_proj", "up_proj"] { + try add( + p + "mlp." + name + ".weight", [c.intermediateSize, c.hiddenSize], dtype, + .target) + } + try add( + p + "mlp.down_proj.weight", [c.hiddenSize, c.intermediateSize], dtype, .target) + } + } + for (key, shape) in try MiMoV26VisionTower.expectedTensorShapes(configuration: vision) { + try add(key, shape, dtype, .vision) + } + for (key, shape) in try MiMoV26AudioPatchEncoder.expectedTensorShapes(configuration: audio) + { try add(key, shape, dtype, .audioPatch) } + let g = c.slidingAttention + for depth in 0 ..< 3 { + let p = "mtp.layers.\(depth)." + for norm in [ + "enorm", "hnorm", "input_layernorm", "pre_mlp_layernorm", "final_layernorm", + ] { try add(p + norm + ".weight", [c.hiddenSize], dtype, .mtp) } + if g.hasSinks { + try add(p + "self_attn.attention_sink_bias", [g.queryHeads], dtype, .mtp) + } + let matrices = [ + ( + "eh_proj", c.hiddenSize, + try convertedProduct([2, c.hiddenSize], "MTP concatenation") + ), + ( + "self_attn.q_proj", try convertedProduct([g.queryHeads, g.headDim], "MTP Q"), + c.hiddenSize + ), + ( + "self_attn.k_proj", + try convertedProduct([g.keyValueHeads, g.headDim], "MTP K"), c.hiddenSize + ), + ( + "self_attn.v_proj", + try convertedProduct([g.keyValueHeads, g.valueHeadDim], "MTP V"), c.hiddenSize + ), + ( + "self_attn.o_proj", c.hiddenSize, + try convertedProduct([g.queryHeads, g.valueHeadDim], "MTP O") + ), + ("mlp.gate_proj", c.intermediateSize, c.hiddenSize), + ("mlp.up_proj", c.intermediateSize, c.hiddenSize), + ("mlp.down_proj", c.hiddenSize, c.intermediateSize), + ] + for (name, rows, cols) in matrices { + let module = p + name + mtpProjections.insert(module) + guard cols.isMultiple(of: 64) else { + throw MiMoV26ConvertedLoadError.invalidQuantization("affine4/64 dimensions") + } + let a = c.quantization.nativeOverrides[module] + let b = c.quantization.nativeOverrides["language_model." + module] + if let a, let b, a != b { + throw MiMoV26ConvertedLoadError.invalidQuantization( + "conflicting MTP aliases: " + module) + } + guard let resolved = a ?? b, case .quantize(let policy) = resolved, + policy.mode == "affine", policy.bits == 4, policy.groupSize == 64 + else { + throw MiMoV26ConvertedLoadError.invalidQuantization( + "missing/wrong explicit MTP policy: " + module) + } + try add(module + ".weight", [rows, cols / 8], .uint32, .mtp) + for suffix in ["scales", "biases"] { + try add(module + "." + suffix, [rows, cols / 64], dtype, .mtp) + } + } + } + // Only aliases of an actual MTP projection or exact target expert path + // may override quantization. Dense modules never inherit root MXFP4. + for (path, override) in c.quantization.nativeOverrides { + let canonical = + path.hasPrefix("language_model.mtp.") + ? String(path.dropFirst("language_model.".count)) : path + if mtpProjections.contains(canonical) { continue } + guard experts.contains(path), case .quantize(let policy) = override, + policy.mode == "mxfp4", policy.bits == 4, policy.groupSize == 32 + else { + throw MiMoV26ConvertedLoadError.invalidQuantization( + "unmapped/incompatible override: " + path) + } + } + if case .object(let rawQuantization) = c.rawFields["quantization"] { + let allowed = Set(["mode", "bits", "group_size"]).union( + c.quantization.nativeOverrides.keys) + guard Set(rawQuantization.keys) == allowed else { + throw MiMoV26ConvertedLoadError.invalidQuantization( + "unmapped native quantization metadata") + } + } + guard Set(descriptors.keys) == Set(expected.keys), + Set(index.weightMap.keys) == Set(expected.keys) + else { + throw MiMoV26ConvertedLoadError.invalidInventory("missing/unmapped root tensors") + } + var total = 0 + for (key, spec) in expected { + let actual = descriptors[key]! + let file = actual.file + guard actual.shape == spec.shape, actual.dtype == spec.dtype, + file == index.weightMap[key], !file.isEmpty, + file == (file as NSString).lastPathComponent, + !file.contains("\\"), file.hasSuffix(".safetensors"), file != ".safetensors", + !groups[.mtp]!.contains(key) || file == mtp.file + else { + throw MiMoV26ConvertedLoadError.invalidInventory(key) + } + let bytes = try convertedProduct(actual.shape + [actual.dtype.bytes], key) + let sum = total.addingReportingOverflow(bytes) + guard !sum.overflow else { + throw MiMoV26ConvertedLoadError.invalidInventory("root byte overflow") + } + total = sum.partialValue + } + guard total == index.metadata.totalSize else { + throw MiMoV26ConvertedLoadError.invalidInventory("index tensor byte total") + } + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return .init( + configuration: c, descriptors: descriptors, components: groups, + targetExpertModulePaths: experts, + parameterNames: Dictionary(uniqueKeysWithValues: expected.keys.map { ($0, $0) }), + targetQuantizationPolicies: Dictionary( + uniqueKeysWithValues: experts.map { ($0, c.quantization.nativeDefault!) }), + audioQuantizationPolicies: [:], floatingMTP: false, + configSHA256: convertedHash(configurationData), indexSHA256: convertedHash(indexData), + descriptorSHA256: convertedHash(try encoder.encode(descriptors)), + rootFiles: Set(index.weightMap.values), + tensorBytes: total, provenance: provenance, + externalRequiredComponents: ["audio_tokenizer", "dflash"], floatingType: dtype) + } +} + +/// New components are published together only after complete validation/load. +/// The plan describes their loading event; callers must preserve component +/// ownership and cannot treat later arbitrary Module mutation as still verified. +public struct MiMoV26ConvertedBundle { + public let target: MiMoV26TextModel + public let vision: MiMoV26VisionTower + public let audioPatch: MiMoV26AudioPatchEncoder + public let mtp: MiMoV26MTP + public let plan: MiMoV26ConvertedLoadPlan +} + +public enum MiMoV26ConvertedWeights { + /// Caller supplies already-read tensor handles. Metadata inspection never + /// evaluates them; file streaming and payload digest verification are separate. + public static func load( + plan: MiMoV26ConvertedLoadPlan, + tensors: [String: MLXArray] + ) throws -> MiMoV26ConvertedBundle { + guard Set(tensors.keys) == Set(plan.descriptors.keys) else { + throw MiMoV26ConvertedLoadError.invalidTensor("missing/unmapped root tensor handles") + } + for (key, descriptor) in plan.descriptors { + let array = tensors[key]! + guard array.shape == descriptor.shape, array.dtype == descriptor.dtype.dtype else { + throw MiMoV26ConvertedLoadError.invalidTensor(key) + } + } + func component(_ type: MiMoV26ConvertedComponent) -> [String: MLXArray] { + Dictionary( + uniqueKeysWithValues: plan.components[type]!.map { + (plan.parameterNames[$0]!, tensors[$0]!) + }) + } + // Entire request validated before any model constructor/update. Fresh + // components remain private if construction or a strict load throws. + let target = try MiMoV26TextModel(plan.configuration) + try MiMoV26PackedModuleLoader.prepare(target, policies: plan.targetQuantizationPolicies) + let targetTensors = component(.target) + let constructed = Dictionary(uniqueKeysWithValues: target.parameters().flattened()) + guard Set(constructed.keys) == Set(targetTensors.keys), + constructed.allSatisfy({ targetTensors[$0.key]!.shape == $0.value.shape }) + else { + throw MiMoV26ConvertedLoadError.incompatibleModule("target parameter closure") + } + try target.update(parameters: .unflattened(targetTensors), verify: .all) + let vision = try MiMoV26VisionTower(configuration: plan.configuration.vision!) + try vision.loadNativeWeights( + component(.vision), expectedDType: plan.floatingType.dtype, + flattenedPatchStorage: plan.provenance.layout == .mlxVLM) + let audio = try MiMoV26AudioPatchEncoder(configuration: plan.configuration.audio!) + if plan.audioQuantizationPolicies.isEmpty { + try audio.loadNativeWeights( + component(.audioPatch), expectedDType: plan.floatingType.dtype) + } else { + try MiMoV26PackedModuleLoader.prepare(audio, policies: plan.audioQuantizationPolicies) + try audio.loadPackedWeights( + component(.audioPatch), expectedDType: plan.floatingType.dtype) + } + let mtp = try MiMoV26MTP(target: target, floatingProjections: plan.floatingMTP) + try mtp.loadConvertedWeights(component(.mtp)) + return .init(target: target, vision: vision, audioPatch: audio, mtp: mtp, plan: plan) + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26DecodedAudiovisual.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26DecodedAudiovisual.swift new file mode 100644 index 0000000000..5264fc9363 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26DecodedAudiovisual.swift @@ -0,0 +1,129 @@ +// Copyright © 2026 Eigen Labs. +// SGLang67bb6a58 mimo_v2.py945–1100: selected interleave0 unit contract. +// Decoded data and scalar planning only; no decoder, resampler or native work. +import Foundation + +public struct MiMoV26DecodedAudiovisual: Sendable { + /// Preserve the source scalar's arithmetic: default individual end is a + /// Float32 tensor; some metadata/partial paths carry Python Float64. + public enum SegmentEnd: Sendable, Equatable { + case float32(Float) + case float64(Double) + var value: Double { + switch self { + case .float32(let x): Double(x) + case .float64(let x): x + } + } + var scaledAudioIndex: Double { + switch self { + case .float32(let x): Double(x * Float(6.25)) + case .float64(let x): x * 6.25 + } + } + } + /// Complete, already sampled clip: no omitted-frame pixel-budget divisor. + public let frames: [MiMoV26Pixels.DecodedRGB] + public let timestamps: [Float] + public let wholeAudio: MiMoV26DecodedPCM + public let segmentEnd: SegmentEnd + public init( + frames: [MiMoV26Pixels.DecodedRGB], timestamps: [Float], + wholeAudio: MiMoV26DecodedPCM, segmentEnd: SegmentEnd + ) { + self.frames = frames + self.timestamps = timestamps + self.wholeAudio = wholeAudio + self.segmentEnd = segmentEnd + } +} + +/// Metadata is not admission or a model/codec ownership capability. +public enum MiMoV26AudiovisualLayout { + static let profileName = "sglang67-decoded-av-interleave0-whole-audio-v1" + public struct Unit: Equatable, Sendable { + public let visualGroup: Int + public let timestamp: Float + /// Indices in the WHOLE clip's final AudioPatch features, not RVQ codes. + public let audioRange: Range + } + public struct Plan: Equatable, Sendable { + public let units: [Unit] + public let alignedFrames, duplicatedFrames: Int + public let wholeAudioPatches, usedAudioPatches, unusedAudioPatches: Int + } + + public static func make( + timestamps: [Float], + segmentEnd: MiMoV26DecodedAudiovisual.SegmentEnd, + temporalPatchSize: Int, wholeAudioPatches: Int, maximumUnits: Int + ) throws -> Plan { + guard !timestamps.isEmpty, temporalPatchSize > 0, maximumUnits > 0, + wholeAudioPatches > 0, wholeAudioPatches <= Int(Int32.max), + segmentEnd.value.isFinite, segmentEnd.value > 0 + else { + throw MiMoV26MultimodalError.invalidInput("decoded AV temporal bounds") + } + var previous: Float = -1 + for time in timestamps { + guard time.isFinite, time >= 0, time > previous else { + throw MiMoV26MultimodalError.invalidInput("decoded AV source timestamps") + } + previous = time + } + guard segmentEnd.value > Double(timestamps[timestamps.count - 1]) else { + throw MiMoV26MultimodalError.invalidInput("decoded AV segment end") + } + let groups = + timestamps.count / temporalPatchSize + + (timestamps.count % temporalPatchSize == 0 ? 0 : 1) + guard groups <= maximumUnits else { + throw MiMoV26MultimodalError.limit("decoded AV unit count") + } + let aligned = groups.multipliedReportingOverflow(by: temporalPatchSize) + guard !aligned.overflow, aligned.partialValue <= Int(Int32.max) else { + throw MiMoV26MultimodalError.limit("decoded AV aligned frames") + } + func scaled(_ time: Float) -> Double { Double(time * Float(6.25)) } + func startIndex(_ value: Double) throws -> Int { + guard value.isFinite, value >= 0, value < Double(wholeAudioPatches) else { + throw MiMoV26MultimodalError.invalidInput( + "decoded AV audio begins beyond whole clip") + } + return Int(value) // nonnegative native int truncation, after Float32 multiplication + } + func clippedEnd(_ value: Double) throws -> Int { + guard value.isFinite, value >= 0 else { + throw MiMoV26MultimodalError.invalidInput("decoded AV nonrepresentable audio end") + } + // Equivalent to min(int(value),wholeAudioPatches), without unsafe + // Int conversion for a finite very large source segment end. + return value >= Double(wholeAudioPatches) ? wholeAudioPatches : Int(value) + } + var units: [Unit] = [] + units.reserveCapacity(groups) + var used = 0 + for group in 0 ..< groups { + let time = timestamps[group * temporalPatchSize] + let start = try startIndex(scaled(time)) + let next = + group + 1 < groups + ? scaled(timestamps[(group + 1) * temporalPatchSize]) : segmentEnd.scaledAudioIndex + let end = try clippedEnd(next) + guard end > start else { + throw MiMoV26MultimodalError.invalidInput( + "decoded AV empty or reversed native audio unit") + } + used += end - start // disjoint ordered ranges, bounded by wholeAudioPatches + units.append(.init(visualGroup: group, timestamp: time, audioRange: start ..< end)) + } + guard used <= wholeAudioPatches else { + throw MiMoV26MultimodalError.invalidInput("decoded AV overlapping units") + } + return .init( + units: units, alignedFrames: aligned.partialValue, + duplicatedFrames: aligned.partialValue - timestamps.count, + wholeAudioPatches: wholeAudioPatches, usedAudioPatches: used, + unusedAudioPatches: wholeAudioPatches - used) + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26EncodedAudioDecoder.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26EncodedAudioDecoder.swift new file mode 100644 index 0000000000..b96a8e721b --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26EncodedAudioDecoder.swift @@ -0,0 +1,176 @@ +// Copyright © 2026 Eigen Labs. +// Bounded transport decode only: mono24k WAV PCM16/IEEE Float32. No MLX, +// resampling, channel mixing, amplitude normalization, URL or file access. +import CryptoKit +import Foundation +import MLXLLM + +public enum MiMoV26EncodedAudioDecoder { + public enum Failure: Error, Equatable, Sendable { + case invalidWave, unsupportedEncoding, unsupportedChannels, unsupportedSampleRate + case nonfiniteSamples, limit, arithmeticOverflow + } + public struct Limits: Sendable { + public let maximumEncodedBytes, maximumFrames, maximumWorkingBytes, maximumChunks: Int + public init( + maximumEncodedBytes: Int, maximumFrames: Int, maximumWorkingBytes: Int, + maximumChunks: Int = 4096 + ) { + self.maximumEncodedBytes = maximumEncodedBytes + self.maximumFrames = maximumFrames + self.maximumWorkingBytes = maximumWorkingBytes + self.maximumChunks = maximumChunks + } + } + public struct Plan: Sendable { + public enum Encoding: Sendable, Equatable { case pcm16, float32 } + public let encoding: Encoding + public let frameCount: Int + public let sampleRate = 24000 + public let encodedByteCount, decodedByteBound: Int + public let sourceIdentity: String + fileprivate let data: Data + fileprivate let sampleOffset, sampleBytes: Int + fileprivate init( + data: Data, encoding: Encoding, frames: Int, offset: Int, + bytes: Int, decodedBytes: Int + ) { + self.data = data + self.encoding = encoding + frameCount = frames + sampleOffset = offset + sampleBytes = bytes + encodedByteCount = data.count + // Input-byte provenance, NOT model/codec-weight authentication. + sourceIdentity = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + decodedByteBound = decodedBytes + } + } + private static func add(_ a: Int, _ b: Int) throws -> Int { + let (n, overflow) = a.addingReportingOverflow(b) + guard a >= 0, b >= 0, !overflow else { throw Failure.arithmeticOverflow } + return n + } + private static func multiply(_ a: Int, _ b: Int) throws -> Int { + let (n, overflow) = a.multipliedReportingOverflow(by: b) + guard a >= 0, b >= 0, !overflow else { throw Failure.arithmeticOverflow } + return n + } + private static func u16(_ bytes: UnsafeRawBufferPointer, _ at: Int) throws -> UInt16 { + guard at >= 0, at <= bytes.count - 2 else { throw Failure.invalidWave } + return UInt16(bytes[at]) | (UInt16(bytes[at + 1]) << 8) + } + private static func u32(_ bytes: UnsafeRawBufferPointer, _ at: Int) throws -> UInt32 { + guard at >= 0, at <= bytes.count - 4 else { throw Failure.invalidWave } + return UInt32(bytes[at]) | (UInt32(bytes[at + 1]) << 8) + | (UInt32(bytes[at + 2]) << 16) | (UInt32(bytes[at + 3]) << 24) + } + + /// Header scan only; no Float buffer is allocated. Host reserves the + /// aggregate decodedByteBound before decode(), not after expansion. + public static func inspect(_ data: Data, limits: Limits) throws -> Plan { + try Task.checkCancellation() + guard limits.maximumEncodedBytes > 0, limits.maximumFrames > 0, + limits.maximumWorkingBytes > 0, limits.maximumChunks > 0, + data.count <= limits.maximumEncodedBytes + else { throw Failure.limit } + return try data.withUnsafeBytes { bytes in + guard bytes.count >= 12, try u32(bytes, 0) == 0x4646_4952, + try u32(bytes, 8) == 0x4556_4157 + else { throw Failure.invalidWave } // RIFF/WAVE + let end = try add(Int(u32(bytes, 4)), 8) + guard end == bytes.count else { throw Failure.invalidWave } + var cursor = 12 + var chunks = 0 + var format: (code: UInt16, bits: UInt16, block: Int)? + var samples: (offset: Int, bytes: Int)? + var factFrames: Int? + while cursor < end { + try Task.checkCancellation() + chunks += 1 + guard chunks <= limits.maximumChunks else { throw Failure.limit } + guard cursor <= end - 8 else { throw Failure.invalidWave } + let kind = try u32(bytes, cursor) + let size = try Int(u32(bytes, cursor + 4)) + let start = try add(cursor, 8) + let stop = try add(start, size) + guard stop <= end else { throw Failure.invalidWave } + switch kind { + case 0x2074_6d66: // fmt + guard format == nil, size == 16 || size == 18 else { throw Failure.invalidWave } + let code = try u16(bytes, start) + let channels = try u16(bytes, start + 2) + let rate = try u32(bytes, start + 4) + let byteRate = try u32(bytes, start + 8) + let block = try Int(u16(bytes, start + 12)) + let bits = try u16(bytes, start + 14) + guard channels == 1 else { throw Failure.unsupportedChannels } + guard rate == 24000 else { throw Failure.unsupportedSampleRate } + guard (code == 1 && bits == 16) || (code == 3 && bits == 32) else { + throw Failure.unsupportedEncoding + } + if size == 18 { + guard try u16(bytes, start + 16) == 0 else { + throw Failure.unsupportedEncoding + } + } + guard block == Int(bits / 8), byteRate == UInt32(24000 * block) else { + throw Failure.invalidWave + } + format = (code, bits, block) + case 0x6174_6164: // data + guard samples == nil, size > 0 else { throw Failure.invalidWave } + samples = (start, size) + case 0x7463_6166: // optional fact count; do not accept contradictory duration + guard factFrames == nil, size >= 4 else { throw Failure.invalidWave } + factFrames = try Int(u32(bytes, start)) + default: break // bounded unknown metadata; no recursive container/URL interpretation + } + cursor = try add(stop, size & 1) + guard cursor <= end else { throw Failure.invalidWave } // mandatory odd-chunk pad byte + } + guard cursor == end, let format, let samples, + samples.bytes % format.block == 0 + else { throw Failure.invalidWave } + let frames = samples.bytes / format.block + guard frames > 0, frames <= limits.maximumFrames else { throw Failure.limit } + guard factFrames == nil || factFrames == frames else { throw Failure.invalidWave } + // Additional Float storage plus fixed header/descriptor slack. + // The encoded owner is independently priced by the host promise. + let decodedBytes = try add(multiply(frames, MemoryLayout.stride), 1024) + guard decodedBytes <= limits.maximumWorkingBytes else { throw Failure.limit } + return Plan( + data: data, encoding: format.code == 1 ? .pcm16 : .float32, + frames: frames, offset: samples.offset, bytes: samples.bytes, + decodedBytes: decodedBytes) + } + } + + /// Preserves signed zero/Float32 values and exact PCM16 /32768 conversion. + /// No clipping, peak normalization, channel mixing or sample-rate conversion. + public static func decode(_ plan: Plan) throws -> MiMoV26DecodedPCM { + try Task.checkCancellation() + let values = try plan.data.withUnsafeBytes { bytes -> [Float] in + var values: [Float] = [] + values.reserveCapacity(plan.frameCount) + let step: Int = plan.encoding == .pcm16 ? 2 : 4 + for index in 0 ..< plan.frameCount { + if index.isMultiple(of: 1024) { try Task.checkCancellation() } + let at = plan.sampleOffset + index * step + let value: Float + switch plan.encoding { + case .pcm16: value = Float(Int16(bitPattern: try u16(bytes, at))) / 32768 + case .float32: value = Float(bitPattern: try u32(bytes, at)) + } + guard value.isFinite else { throw Failure.nonfiniteSamples } + values.append(value) + } + return values + } + return try MiMoV26DecodedPCM( + samples: values, + descriptor: .init( + sourceIdentity: plan.sourceIdentity, channels: 1, + frameCount: plan.frameCount, sampleRate: plan.sampleRate)) + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26EncodedAudiovisualDecoder.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26EncodedAudiovisualDecoder.swift new file mode 100644 index 0000000000..6f92e61333 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26EncodedAudiovisualDecoder.swift @@ -0,0 +1,318 @@ +// Copyright © 2026 Eigen Labs. +// Narrow encoded transport for SGLang67bb6a58's whole-audio/interleave0 input. +// No audio converter, resampler, channel mix, peak normalization, MLX or file IO. +@preconcurrency import AVFoundation +import AudioToolbox +import CoreMedia +import CryptoKit +import Foundation +import MLXLMCommon + +public enum MiMoV26EncodedAudiovisualDecoder { + public enum Failure: Error, Equatable, Sendable { + case missingAudio, unsupportedEncoding, unsupportedChannels, unsupportedSampleRate + case unsupportedTimeline, invalidAudio, nonfiniteSamples, limit, arithmeticOverflow + } + public struct Limits: Sendable { + public let maximumFrames, maximumWorkingBytes, maximumBuffers: Int + public init(maximumFrames: Int, maximumWorkingBytes: Int, maximumBuffers: Int = 4096) { + self.maximumFrames = maximumFrames + self.maximumWorkingBytes = maximumWorkingBytes + self.maximumBuffers = maximumBuffers + } + } + fileprivate enum Encoding: Equatable, Sendable { + case pcm16, float32 + var bytesPerFrame: Int { self == .pcm16 ? 2 : 4 } + } + public struct Plan: Sendable { + public let video: MiMoV26EncodedVisualDecoder.VideoPlan + public let frameCount, audioWorkingByteBound: Int + public let segmentEnd: MiMoV26DecodedAudiovisual.SegmentEnd + fileprivate let encoding: Encoding + fileprivate let trackID: CMPersistentTrackID + fileprivate let maximumBuffers: Int + fileprivate init( + video: MiMoV26EncodedVisualDecoder.VideoPlan, frames: Int, + bound: Int, encoding: Encoding, trackID: CMPersistentTrackID, + maximumBuffers: Int, end: Float + ) { + self.video = video + frameCount = frames + audioWorkingByteBound = bound + self.encoding = encoding + self.trackID = trackID + self.maximumBuffers = maximumBuffers + segmentEnd = .float32(end) + } + } + private static func product(_ a: Int, _ b: Int) throws -> Int { + let value = a.multipliedReportingOverflow(by: b) + guard a >= 0, b >= 0, !value.overflow else { throw Failure.arithmeticOverflow } + return value.partialValue + } + private static func sum(_ a: Int, _ b: Int) throws -> Int { + let value = a.addingReportingOverflow(b) + guard a >= 0, b >= 0, !value.overflow else { throw Failure.arithmeticOverflow } + return value.partialValue + } + private static func encoding(_ description: CMFormatDescription) throws -> Encoding { + guard CMFormatDescriptionGetMediaType(description) == kCMMediaType_Audio, + let pointer = CMAudioFormatDescriptionGetStreamBasicDescription(description) + else { + throw Failure.invalidAudio + } + let value = pointer.pointee + guard value.mChannelsPerFrame == 1 else { throw Failure.unsupportedChannels } + guard value.mSampleRate == 24000 else { throw Failure.unsupportedSampleRate } + guard value.mFormatID == kAudioFormatLinearPCM, value.mFramesPerPacket == 1 else { + throw Failure.unsupportedEncoding + } + let selected: Encoding + if value.mBitsPerChannel == 16, + value.mFormatFlags == (kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) + { + selected = .pcm16 + } else if value.mBitsPerChannel == 32, + value.mFormatFlags == (kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked) + { + selected = .float32 + } else { + throw Failure.unsupportedEncoding + } + guard value.mBytesPerFrame == UInt32(selected.bytesPerFrame), + value.mBytesPerPacket == UInt32(selected.bytesPerFrame) + else { throw Failure.unsupportedEncoding } + return selected + } + + /// Mirrors the two Float32 reciprocal operations in process_video, not the + /// simplified timestamp gap or asset duration (which can change a token end). + static func individualSegmentEnd(_ timestamps: [Float]) throws -> Float { + guard timestamps.count >= 2 else { throw Failure.unsupportedTimeline } + let gap = timestamps[1] - timestamps[0] + let sampledFPS: Float = 1 / gap + let step: Float = 1 / sampledFPS + let end = timestamps[timestamps.count - 1] + step + guard gap.isFinite, gap > 0, sampledFPS.isFinite, sampledFPS > 0, + end.isFinite, end > timestamps[timestamps.count - 1] + else { + throw Failure.unsupportedTimeline + } + return end + } + + /// Metadata only; no reader/PCM Float allocation. The provider must price + /// audioWorkingByteBound + video.decodeWorkingByteBound on the SAME actual + /// host reservation before calling decode. A Plan is not native admission. + public static func inspect( + _ video: MiMoV26EncodedVisualDecoder.VideoPlan, + limits: Limits + ) async throws -> Plan { + try Task.checkCancellation() + guard video.hasAudioTrack else { throw Failure.missingAudio } + guard limits.maximumFrames > 0, limits.maximumFrames <= Int(Int32.max), + limits.maximumWorkingBytes > 0, limits.maximumBuffers > 0 + else { throw Failure.limit } + let end = try individualSegmentEnd(video.timestamps) + return try await video.sourceOwner.withAsset { asset in + let tracks = try await asset.loadTracks(withMediaType: .audio) + guard tracks.count == 1, let track = tracks.first else { + throw Failure.unsupportedEncoding + } + let descriptions = try await track.load(.formatDescriptions) + guard descriptions.count == 1, let description = descriptions.first else { + throw Failure.unsupportedEncoding + } + let selected = try encoding(description) + let range = try await track.load(.timeRange) + let segments = try await track.load(.segments) + guard range.start.isNumeric, range.start == .zero, range.duration.isNumeric, + range.duration > .zero, segments.count == 1, let segment = segments.first, + !segment.isEmpty + else { throw Failure.unsupportedTimeline } + let mapping = segment.timeMapping + guard mapping.source.start == .zero, mapping.target.start == .zero, + mapping.source.duration == range.duration, + mapping.target.duration == range.duration + else { throw Failure.unsupportedTimeline } + let scaled = CMTimeConvertScale(range.duration, timescale: 24000, method: .default) + guard scaled.isNumeric, scaled == range.duration, scaled.value > 0, + scaled.value <= Int64(limits.maximumFrames), + let frames = Int(exactly: scaled.value) + else { throw Failure.limit } + // Raw PCM payload cannot exceed the retained immutable container. + guard try product(frames, selected.bytesPerFrame) <= video.sourceOwner.byteCount else { + throw Failure.invalidAudio + } + // Retained Float output + possible raw sample copy/reader storage, + // bounded metadata and fixed decoder slack. Conservative source + // accounting, not a measured peak or replacement native reserve. + let bound = try sum( + product(frames, 16), + sum(product(limits.maximumBuffers, 128), 1 << 20)) + guard bound <= limits.maximumWorkingBytes else { throw Failure.limit } + return Plan( + video: video, frames: frames, bound: bound, encoding: selected, + trackID: track.trackID, maximumBuffers: limits.maximumBuffers, end: end) + } + } + + public static func decode( + _ plan: Plan, videoLimits: MiMoV26EncodedVisualDecoder.Limits, + audioLimits: Limits + ) async throws -> MiMoV26DecodedAudiovisual { + guard plan.frameCount <= audioLimits.maximumFrames, + plan.audioWorkingByteBound <= audioLimits.maximumWorkingBytes, + plan.maximumBuffers <= audioLimits.maximumBuffers + else { throw Failure.limit } + guard plan.video.sourceOwner.byteCount <= videoLimits.maximumEncodedBytes, + videoLimits.maximumControlMarkers >= 0, + plan.video.codedPixels <= videoLimits.maximumPixels, + plan.video.sampledIndices.count <= videoLimits.maximumSampledFrames, + plan.video.sourceFrameCount <= videoLimits.maximumSourceFrames, + try plan.video.decodeWorkingByteBound() <= videoLimits.maximumWorkingBytes + else { + throw Failure.limit + } + try Task.checkCancellation() + let audio = try await decodeAudio(plan) + // Only this paired path can access frame decode for an audio-bearing + // clip. The public silentVideo entrypoint still rejects sound. + let video = try await MiMoV26EncodedVisualDecoder.audiovisualFrames( + plan.video, limits: videoLimits) + try Task.checkCancellation() + return .init( + frames: video.frames, timestamps: video.timestamps, + wholeAudio: audio, segmentEnd: plan.segmentEnd) + } + + /// Preserve this decoder's typed timeline/resource refusals for malformed + /// control buffers while sharing the actual no-media marker predicate. + static func consumeEmptyMarker( + _ sample: CMSampleBuffer, + count: inout Int, limit: Int + ) throws -> Bool { + do { + return try MiMoV26EncodedVisualDecoder.consumeEmptyMarker( + sample, count: &count, limit: limit) + } catch MiMoV26EncodedVisualDecoder.Failure.limit { + throw Failure.limit + } catch { + throw Failure.unsupportedTimeline + } + } + + private static func decodeAudio(_ plan: Plan) async throws -> MiMoV26DecodedPCM { + try await plan.video.sourceOwner.withAsset { asset in + let tracks = try await asset.loadTracks(withMediaType: .audio) + guard tracks.count == 1, let track = tracks.first, track.trackID == plan.trackID else { + throw Failure.invalidAudio + } + let reader = try AVAssetReader(asset: asset) + // Passthrough: no platform decoder/converter numerical contract. + let output = AVAssetReaderTrackOutput(track: track, outputSettings: nil) + guard reader.canAdd(output) else { throw Failure.invalidAudio } + reader.add(output) + guard reader.startReading() else { throw Failure.invalidAudio } + defer { reader.cancelReading() } + var values: [Float] = [] + values.reserveCapacity(plan.frameCount) + var digest = SHA256() + var buffers = 0 + var markerCount = 0 + while let sample = output.copyNextSampleBuffer() { + try Task.checkCancellation() + buffers += 1 + guard buffers <= plan.maximumBuffers else { throw Failure.limit } + if try consumeEmptyMarker(sample, count: &markerCount, limit: plan.maximumBuffers) { + continue + } + guard CMSampleBufferDataIsReady(sample), + let description = CMSampleBufferGetFormatDescription(sample), + try encoding(description) == plan.encoding, + CMGetAttachment( + sample, key: kCMSampleBufferAttachmentKey_TrimDurationAtStart, + attachmentModeOut: nil) == nil, + CMGetAttachment( + sample, key: kCMSampleBufferAttachmentKey_TrimDurationAtEnd, + attachmentModeOut: nil) == nil, + CMGetAttachment( + sample, key: kCMSampleBufferAttachmentKey_SpeedMultiplier, + attachmentModeOut: nil) == nil, + CMGetAttachment( + sample, key: kCMSampleBufferAttachmentKey_Reverse, + attachmentModeOut: nil) == nil, + CMGetAttachment( + sample, key: kCMSampleBufferAttachmentKey_EmptyMedia, + attachmentModeOut: nil) == nil + else { throw Failure.unsupportedTimeline } + let count = CMSampleBufferGetNumSamples(sample) + let next = try sum(values.count, count) + guard count > 0, next <= plan.frameCount else { throw Failure.limit } + // Reject gaps, overlap, edits, retiming or codec priming. No + // synthesized silence and no dropped/shifted audio samples. + let pts = CMSampleBufferGetPresentationTimeStamp(sample) + let duration = CMSampleBufferGetDuration(sample) + var timing = CMSampleTimingInfo() + var timingCount: CMItemCount = 0 + // A single descriptor applies to EVERY sample. Refuse a + // variable-timing buffer instead of trusting its total span. + guard + CMSampleBufferGetSampleTimingInfoArray( + sample, entryCount: 1, + arrayToFill: &timing, entriesNeededOut: &timingCount) == noErr, + timingCount == 1, timing.duration == CMTime(value: 1, timescale: 24000), + timing.presentationTimeStamp == pts + else { throw Failure.unsupportedTimeline } + guard pts.isNumeric, duration.isNumeric, + pts == CMTime(value: Int64(values.count), timescale: 24000), + duration == CMTime(value: Int64(count), timescale: 24000) + else { + throw Failure.unsupportedTimeline + } + let size = try product(count, plan.encoding.bytesPerFrame) + guard let block = CMSampleBufferGetDataBuffer(sample), + CMBlockBufferGetDataLength(block) == size + else { throw Failure.invalidAudio } + var bytes = Data(count: size) + let status = bytes.withUnsafeMutableBytes { + CMBlockBufferCopyDataBytes( + block, atOffset: 0, dataLength: size, + destination: $0.baseAddress!) + } + guard status == kCMBlockBufferNoErr else { throw Failure.invalidAudio } + digest.update(data: bytes) + try bytes.withUnsafeBytes { (raw: UnsafeRawBufferPointer) in + for index in 0 ..< count { + if index.isMultiple(of: 1024) { try Task.checkCancellation() } + let at = index * plan.encoding.bytesPerFrame + let low = UInt16(raw[at]) | UInt16(raw[at + 1]) << 8 + let value: Float + switch plan.encoding { + case .pcm16: value = Float(Int16(bitPattern: low)) / 32768 + case .float32: + value = Float( + bitPattern: UInt32(low) + | UInt32(raw[at + 2]) << 16 | UInt32(raw[at + 3]) << 24) + } + guard value.isFinite else { throw Failure.nonfiniteSamples } + values.append(value) + } + } + } + guard reader.status == .completed, values.count == plan.frameCount else { + throw Failure.invalidAudio + } + // Exact raw-track provenance, not codec weights/profile authority. + let identity = + "mimo-av-\(plan.encoding)-24k:" + + digest.finalize().map { String(format: "%02x", $0) }.joined() + return try .init( + samples: values, + descriptor: .init( + sourceIdentity: identity, + channels: 1, frameCount: plan.frameCount, sampleRate: 24000)) + } + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26EncodedVisualDecoder.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26EncodedVisualDecoder.swift new file mode 100644 index 0000000000..ec696922d0 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26EncodedVisualDecoder.swift @@ -0,0 +1,510 @@ +// Copyright © 2026 Eigen Labs. +// Native sampler derived from SGLang Apache-2.0, commit +// 67bb6a58d0dad4a39af80fa1b2bf86f0de0cb99b (qwen_vl.smart_nframes and +// mimo_v2._decode_frames_and_timestamps). No downloaded code is executed. +@preconcurrency import AVFoundation +import CoreGraphics +import CoreMedia +import CoreVideo +import Foundation +import ImageIO +import MLXLLM +import MLXLMCommon + +/// Encoded transport is separate from model pixel normalization. +/// No MLX arrays, remote URL, plaintext file, resize or mean/std operation. +public enum MiMoV26EncodedVisualDecoder { + public enum Failure: Error, Equatable, Sendable { + case invalidImage, invalidVideo, unsupportedRepresentation, + audioTrackRequiresAudiovisualProfile + case limit, arithmeticOverflow, inconsistentFrames + } + public struct Limits: Sendable { + public let maximumPixels, maximumWorkingBytes, maximumSourceFrames, + maximumSampledFrames: Int + /// Bound caller-owned compressed bytes before ImageIO or AVFoundation parses them. + public let maximumEncodedBytes: Int + /// Independent work/metadata ceiling for no-sample reader control markers. + public let maximumControlMarkers: Int + public init( + maximumPixels: Int, maximumWorkingBytes: Int, + maximumSourceFrames: Int, maximumSampledFrames: Int, + maximumEncodedBytes: Int? = nil, maximumControlMarkers: Int = 4096 + ) { + self.maximumPixels = maximumPixels + self.maximumWorkingBytes = maximumWorkingBytes + self.maximumSourceFrames = maximumSourceFrames + self.maximumSampledFrames = maximumSampledFrames + self.maximumEncodedBytes = maximumEncodedBytes ?? maximumWorkingBytes + self.maximumControlMarkers = maximumControlMarkers + } + } + public struct Sampling: Sendable { + public let fps: Double + public let minimumFrames, maximumFrames: Int + public init(configuration: MiMoV26Configuration) throws { + guard let values = configuration.processorFields else { throw Failure.invalidVideo } + func number(_ key: String, fallback: Double) throws -> Double { + guard let value = values[key], value != .null else { return fallback } + guard case .number(let number) = value else { throw Failure.invalidVideo } + let parsed = NSDecimalNumber(decimal: number).doubleValue + guard parsed.isFinite, parsed >= 0 else { throw Failure.invalidVideo } + return parsed == 0 ? fallback : parsed // native "or" fallback + } + let samplesPerSecond = try number("fps", fallback: 2) + let low = try number("min_frames", fallback: 8) + let high = try number("max_frames", fallback: 256) + guard low.rounded(.towardZero) == low, high.rounded(.towardZero) == high, + low < Double(Int.max), high < Double(Int.max), samplesPerSecond > 0 + else { throw Failure.invalidVideo } + try self.init(fps: samplesPerSecond, minimumFrames: Int(low), maximumFrames: Int(high)) + // MiMo passes "num_frames", but pinned smart_nframes consumes + // "nframes". No client sampling override is added here; follow + // the actually consumed fps/min/max fields, including that detail. + } + public init(fps: Double, minimumFrames: Int, maximumFrames: Int) throws { + guard fps.isFinite, fps > 0, minimumFrames > 0, minimumFrames < Int.max, + maximumFrames > 0 + else { throw Failure.invalidVideo } + let effectiveMinimum = (minimumFrames / 2 + minimumFrames % 2) * 2 + let effectiveMaximum = maximumFrames / 2 * 2 + guard effectiveMinimum <= effectiveMaximum else { throw Failure.invalidVideo } + self.fps = fps + self.minimumFrames = minimumFrames + self.maximumFrames = maximumFrames + } + public func indices(totalFrames: Int, averageFPS: Double, admissionLimit: Int) throws + -> [Int] + { + guard totalFrames >= 2, totalFrames <= 9_007_199_254_740_991, + averageFPS.isFinite, averageFPS > 0, admissionLimit > 0, + minimumFrames < Int.max + else { throw Failure.invalidVideo } + let minimum = (minimumFrames / 2 + minimumFrames % 2) * 2 + let maximum = maximumFrames / 2 * 2 + let estimate = Double(totalFrames) / averageFPS * fps + guard estimate.isFinite else { throw Failure.invalidVideo } + let chosen = min( + min(max(estimate, Double(minimum)), Double(maximum)), Double(totalFrames)) + let count = Int(floor(chosen / 2)) * 2 + guard count >= 2, count <= totalFrames else { throw Failure.invalidVideo } + // Resource refusal, NEVER a replacement sampler/max-frame clamp. + guard count <= admissionLimit else { throw Failure.limit } + let step = Double(totalFrames - 1) / Double(count - 1) + var result: [Int] = [] + result.reserveCapacity(count) + for index in 0 ..< count { + let value = index == count - 1 ? totalFrames - 1 : Int(floor(Double(index) * step)) + if result.last != value { result.append(value) } // np.unique + } + return result + } + } + public struct VideoPlan: Sendable { + public let sourceFrameCount: Int + public let averageFPS: Double + public let sampledIndices: [Int] + public let timestamps: [Float] + public let codedPixels: Int + public let hasAudioTrack: Bool + fileprivate let owner: MemoryBackedVideoAsset + fileprivate let maximumControlMarkers: Int + /// AV composition reuses identical owned bytes, never a second URL fetch + /// or a bare AVAsset escape. + package var sourceOwner: MemoryBackedVideoAsset { owner } + public func decodeWorkingByteBound() throws -> Int { + let sourceBuffers = try MiMoV26EncodedVisualDecoder.product( + sourceFrameCount, codedPixels, 32) + let retainedRGB = try MiMoV26EncodedVisualDecoder.product( + sampledIndices.count, codedPixels, 12) + let metadata = try MiMoV26EncodedVisualDecoder.product(sourceFrameCount, 64) + let markerMetadata = try MiMoV26EncodedVisualDecoder.product(maximumControlMarkers, 64) + var total = owner.byteCount + for value in [sourceBuffers, retainedRGB, metadata, markerMetadata, 1 << 20] { + let (next, overflow) = total.addingReportingOverflow(value) + guard !overflow else { throw Failure.arithmeticOverflow } + total = next + } + return total + } + fileprivate init( + owner: MemoryBackedVideoAsset, count: Int, fps: Double, + indices: [Int], pixels: Int, audio: Bool, maximumControlMarkers: Int + ) { + self.owner = owner + sourceFrameCount = count + averageFPS = fps + sampledIndices = indices + codedPixels = pixels + hasAudioTrack = audio + self.maximumControlMarkers = maximumControlMarkers + // Native Float32 tensor / weak scalar conversion, not actual PTS. + timestamps = indices.map { Float($0) / Float(fps) } + } + } + + private static func product(_ values: Int...) throws -> Int { + var result = 1 + for value in values { + let (next, overflow) = result.multipliedReportingOverflow(by: value) + guard value >= 0, !overflow else { throw Failure.arithmeticOverflow } + result = next + } + return result + } + private static func checked(_ limits: Limits) throws { + guard limits.maximumPixels > 0, limits.maximumWorkingBytes > 0, + limits.maximumEncodedBytes > 0, limits.maximumControlMarkers >= 0, + limits.maximumSourceFrames > 0, limits.maximumSampledFrames > 0 + else { throw Failure.limit } + } + + /// AVAssetReader may emit control markers without media samples. They do + /// not contribute a frame or duration, but still have a bounded work cost. + static func consumeEmptyMarker( + _ sample: CMSampleBuffer, + count: inout Int, limit: Int + ) throws -> Bool { + guard CMSampleBufferGetNumSamples(sample) == 0 else { return false } + let duration = CMSampleBufferGetDuration(sample) + let payloadBytes = CMSampleBufferGetDataBuffer(sample).map(CMBlockBufferGetDataLength) ?? 0 + guard CMSampleBufferIsValid(sample), CMSampleBufferDataIsReady(sample), + CMSampleBufferGetTotalSampleSize(sample) == 0, + payloadBytes == 0, CMSampleBufferGetImageBuffer(sample) == nil, + duration.isNumeric, duration == .zero, + CMGetAttachment( + sample, key: kCMSampleBufferAttachmentKey_TrimDurationAtStart, + attachmentModeOut: nil) == nil, + CMGetAttachment( + sample, key: kCMSampleBufferAttachmentKey_TrimDurationAtEnd, + attachmentModeOut: nil) == nil, + CMGetAttachment( + sample, key: kCMSampleBufferAttachmentKey_SpeedMultiplier, + attachmentModeOut: nil) == nil, + CMGetAttachment( + sample, key: kCMSampleBufferAttachmentKey_Reverse, + attachmentModeOut: nil) == nil + else { throw Failure.invalidVideo } + let (next, overflow) = count.addingReportingOverflow(1) + guard !overflow, next <= limit else { throw Failure.limit } + count = next + return true + } + + /// Application EXIF orientation is applied once. This preserves DarkBloom + /// ingest policy, not identity with SGLang's non-smart RGB/EXIF bypass. + /// Straight channels are preserved; alpha is discarded, never composited. + public static func image(_ data: Data, limits: Limits) throws -> MiMoV26Pixels.DecodedRGB { + try checked(limits) + try Task.checkCancellation() + guard data.count <= limits.maximumEncodedBytes else { throw Failure.limit } + guard + let source = CGImageSourceCreateWithData( + data as CFData, + [kCGImageSourceShouldCache: false] as CFDictionary), + let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], + let width = properties[kCGImagePropertyPixelWidth] as? Int, + let height = properties[kCGImagePropertyPixelHeight] as? Int, + width > 0, height > 0, try product(width, height) <= limits.maximumPixels + else { + throw Failure.invalidImage + } + let orientation = (properties[kCGImagePropertyOrientation] as? NSNumber)?.intValue ?? 1 + guard ((properties[kCGImagePropertyDepth] as? NSNumber)?.intValue ?? 8) <= 8 else { + throw Failure.unsupportedRepresentation + } + guard (1 ... 8).contains(orientation), + let image = CGImageSourceCreateImageAtIndex( + source, 0, + [kCGImageSourceShouldCache: false, kCGImageSourceShouldAllowFloat: false] + as CFDictionary) + else { + throw Failure.invalidImage + } + return try straightRGB(image, orientation: orientation, limits: limits) + } + + /// Copy actual straight raster channels without CGContext color matching, + /// premultiplication or a CIContext that may submit untracked Metal work. + static func straightRGB( + _ image: CGImage, orientation: Int, + limits: Limits + ) throws -> MiMoV26Pixels.DecodedRGB { + try checked(limits) + let width = image.width + let height = image.height + let pixels = try product(width, height) + let rawBytes = try product(image.bytesPerRow, height) + let floatBytes = try product(pixels, 3, MemoryLayout.stride) + let (working, overflow) = rawBytes.addingReportingOverflow(floatBytes) + guard !overflow, pixels <= limits.maximumPixels, working <= limits.maximumWorkingBytes, + image.bitsPerComponent == 8, let space = image.colorSpace, + [.rgb, .monochrome].contains(space.model), + let data = image.dataProvider?.data, CFDataGetLength(data) >= rawBytes, + let pointer = CFDataGetBytePtr(data) + else { throw Failure.unsupportedRepresentation } + let components = image.bitsPerPixel / 8 + let channels = space.model == .rgb ? 3 : 1 + let minimumRowBytes = try product(width, components) + guard image.bitsPerPixel % 8 == 0, components == channels || components == channels + 1, + image.bytesPerRow >= minimumRowBytes + else { throw Failure.unsupportedRepresentation } + let alpha = image.alphaInfo + guard components != channels || alpha == .none else { + throw Failure.unsupportedRepresentation + } + let first = alpha == .first || alpha == .premultipliedFirst || alpha == .noneSkipFirst + let premultiplied = alpha == .premultipliedFirst || alpha == .premultipliedLast + let order = image.bitmapInfo.intersection(.byteOrderMask) + let reverse = + (components == 4 && order == .byteOrder32Little) + || (components == 2 && order == .byteOrder16Little) + let oriented = orientation >= 5 + let outWidth = oriented ? height : width + let outHeight = oriented ? width : height + var output = [Float](repeating: 0, count: try product(pixels, 3)) + for y in 0 ..< outHeight { + try Task.checkCancellation() + for x in 0 ..< outWidth { + let sx: Int + let sy: Int + switch orientation { + case 1: (sx, sy) = (x, y) + case 2: (sx, sy) = (width - 1 - x, y) + case 3: (sx, sy) = (width - 1 - x, height - 1 - y) + case 4: (sx, sy) = (x, height - 1 - y) + case 5: (sx, sy) = (y, x) + case 6: (sx, sy) = (y, height - 1 - x) + case 7: (sx, sy) = (width - 1 - y, height - 1 - x) + case 8: (sx, sy) = (width - 1 - y, x) + default: throw Failure.invalidImage + } + let offset = sy * image.bytesPerRow + sx * components + func component(_ i: Int) -> UInt8 { + pointer[offset + (reverse ? components - 1 - i : i)] + } + // No heuristic division/white-compositing for a decoder that + // already lost the original straight channels. + if premultiplied, component(first ? 0 : components - 1) != 255 { + throw Failure.unsupportedRepresentation + } + let start = first ? 1 : 0 + let out = y * outWidth + x + for channel in 0 ..< 3 { + output[channel * pixels + out] = Float( + component(start + (channels == 1 ? 0 : channel))) + } + } + } + return .init(height: outHeight, width: outWidth, planarRGB: output) + } + + /// Complete compressed-sample enumeration provides actual frame count and + /// sample-duration average; no duration*nominal-fps estimate or AV seek. + /// Compressed output is decode-ordered; decoded output is presentation- + /// ordered. Source indices refer to the latter order, including VFR. + public static func inspectVideo( + _ owner: MemoryBackedVideoAsset, sampling: Sampling, + limits: Limits + ) async throws -> VideoPlan { + try checked(limits) + guard owner.byteCount <= limits.maximumEncodedBytes, + try product(limits.maximumControlMarkers, 64) <= limits.maximumWorkingBytes + else { throw Failure.limit } + return try await owner.withAsset { asset in + try Task.checkCancellation() + let tracks = try await asset.loadTracks(withMediaType: .video) + let audio = try await asset.loadTracks(withMediaType: .audio) + guard tracks.count == 1, let track = tracks.first else { + throw Failure.unsupportedRepresentation + } + let descriptions = try await track.load(.formatDescriptions) + var pixels = 0 + for description in descriptions { + let metadata = CMFormatDescriptionGetExtensions(description) as? [String: Any] + let transfer = + metadata?[kCMFormatDescriptionExtension_TransferFunction as String] as? String + guard transfer != (kCVImageBufferTransferFunction_SMPTE_ST_2084_PQ as String), + transfer != (kCVImageBufferTransferFunction_ITU_R_2100_HLG as String) + else { + throw Failure.unsupportedRepresentation // no implicit HDR tone mapping + } + let dimensions = CMVideoFormatDescriptionGetDimensions(description) + guard dimensions.width > 0, dimensions.height > 0 else { + throw Failure.invalidVideo + } + pixels = max(pixels, try product(Int(dimensions.width), Int(dimensions.height))) + } + guard pixels > 0, pixels <= limits.maximumPixels else { throw Failure.limit } + let reader = try AVAssetReader(asset: asset) + let output = AVAssetReaderTrackOutput(track: track, outputSettings: nil) + guard reader.canAdd(output) else { throw Failure.invalidVideo } + reader.add(output) + guard reader.startReading() else { throw Failure.invalidVideo } + // Apple's cancelReading contract stops background reads. This + // codec cleanup is not a fabricated MLX/native-shutdown receipt. + defer { reader.cancelReading() } + var count = 0 + var markerCount = 0 + var duration = CMTime.zero + while let sample = output.copyNextSampleBuffer() { + try Task.checkCancellation() + if try consumeEmptyMarker( + sample, count: &markerCount, limit: limits.maximumControlMarkers) + { + continue + } + let amount = CMSampleBufferGetNumSamples(sample) + let (next, overflow) = count.addingReportingOverflow(amount) + guard amount > 0, !overflow, next <= limits.maximumSourceFrames else { + throw Failure.limit + } + let span = CMSampleBufferGetDuration(sample) + guard span.isNumeric, span.seconds.isFinite, span > .zero else { + throw Failure.invalidVideo + } + duration = CMTimeAdd(duration, span) + count = next + guard duration.isNumeric, duration.seconds.isFinite else { + throw Failure.invalidVideo + } + } + guard reader.status == .completed, count >= 2, duration > .zero else { + throw Failure.invalidVideo + } + let fps = Double(count) / duration.seconds + let indices = try sampling.indices( + totalFrames: count, averageFPS: fps, + admissionLimit: limits.maximumSampledFrames) + return VideoPlan( + owner: owner, count: count, fps: fps, indices: indices, pixels: pixels, + audio: !audio.isEmpty, maximumControlMarkers: limits.maximumControlMarkers) + } + } + + /// A silent input remains distinct from VideoAudioInput. Sound is never + /// dropped; only the paired audiovisual decoder can consume both tracks. + public static func silentVideo(_ plan: VideoPlan, limits: Limits) async throws + -> MiMoV26SilentVideo + { + try checked(limits) + guard !plan.hasAudioTrack else { throw Failure.audioTrackRequiresAudiovisualProfile } + return try await decodedFrames(plan, limits: limits) + } + + package static func audiovisualFrames(_ plan: VideoPlan, limits: Limits) async throws + -> MiMoV26SilentVideo + { + guard plan.hasAudioTrack else { throw Failure.invalidVideo } + return try await decodedFrames(plan, limits: limits) + } + + private static func decodedFrames(_ plan: VideoPlan, limits: Limits) async throws + -> MiMoV26SilentVideo + { + try checked(limits) + guard plan.owner.byteCount <= limits.maximumEncodedBytes, + plan.codedPixels <= limits.maximumPixels, + plan.sampledIndices.count <= limits.maximumSampledFrames, + plan.sourceFrameCount <= limits.maximumSourceFrames, + try plan.decodeWorkingByteBound() <= limits.maximumWorkingBytes + else { throw Failure.limit } + // Reused plans stay within both the caller's current ceiling and the + // marker allowance included in the immutable plan's working-byte bound. + let markerLimit = min(plan.maximumControlMarkers, limits.maximumControlMarkers) + return try await plan.owner.withAsset { asset in + let tracks = try await asset.loadTracks(withMediaType: .video) + guard tracks.count == 1, let track = tracks.first else { throw Failure.invalidVideo } + let transform = try await track.load(.preferredTransform) + let reader = try AVAssetReader(asset: asset) + let output = AVAssetReaderTrackOutput( + track: track, + outputSettings: [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA + ]) + guard reader.canAdd(output) else { throw Failure.invalidVideo } + reader.add(output) + guard reader.startReading() else { throw Failure.invalidVideo } + defer { reader.cancelReading() } + var index = 0 + var selected = 0 + var markerCount = 0 + var frames: [MiMoV26Pixels.DecodedRGB] = [] + var lastPTS: CMTime? + while let sample = output.copyNextSampleBuffer() { + try Task.checkCancellation() + if try consumeEmptyMarker(sample, count: &markerCount, limit: markerLimit) { + continue + } + guard index < plan.sourceFrameCount, CMSampleBufferGetNumSamples(sample) == 1 else { + throw Failure.inconsistentFrames + } + let pts = CMSampleBufferGetPresentationTimeStamp(sample) + guard pts.isNumeric, lastPTS.map({ pts > $0 }) ?? true else { + throw Failure.inconsistentFrames + } + lastPTS = pts + if selected < plan.sampledIndices.count, index == plan.sampledIndices[selected] { + guard let pixel = CMSampleBufferGetImageBuffer(sample) else { + throw Failure.invalidVideo + } + frames.append(try frame(pixel, transform: transform, limits: limits)) + selected += 1 + } + index += 1 + } + guard reader.status == .completed, index == plan.sourceFrameCount, + selected == plan.sampledIndices.count, frames.count == plan.timestamps.count + else { + throw Failure.inconsistentFrames + } + return .init(frames: frames, timestamps: plan.timestamps) + } + } + + private static func frame( + _ buffer: CVPixelBuffer, transform: CGAffineTransform, + limits: Limits + ) throws -> MiMoV26Pixels.DecodedRGB { + guard CVPixelBufferGetPixelFormatType(buffer) == kCVPixelFormatType_32BGRA else { + throw Failure.unsupportedRepresentation + } + let width = CVPixelBufferGetWidth(buffer) + let height = CVPixelBufferGetHeight(buffer) + let pixels = try product(width, height) + let stride = CVPixelBufferGetBytesPerRow(buffer) + let minimumStride = try product(width, 4) + guard pixels <= limits.maximumPixels, + try product(pixels, 12) <= limits.maximumWorkingBytes, + stride >= minimumStride + else { throw Failure.limit } + // Exact orientation transforms only: no arbitrary affine resampling + // or guessed pixel-aspect correction. Translation normalizes to origin. + let shape = [transform.a, transform.b, transform.c, transform.d] + let orientations: [[CGFloat]] = [ + [1, 0, 0, 1], [-1, 0, 0, 1], [-1, 0, 0, -1], [1, 0, 0, -1], + [0, 1, 1, 0], [0, 1, -1, 0], [0, -1, -1, 0], [0, -1, 1, 0], + ] + guard let position = orientations.firstIndex(of: shape), + CVPixelBufferLockBaseAddress(buffer, .readOnly) == kCVReturnSuccess + else { + throw Failure.unsupportedRepresentation + } + defer { CVPixelBufferUnlockBaseAddress(buffer, .readOnly) } + guard let address = CVPixelBufferGetBaseAddress(buffer) else { throw Failure.invalidVideo } + let bytes = try product(stride, height) + guard bytes <= limits.maximumWorkingBytes else { throw Failure.limit } + let data = Data(bytes: address, count: bytes) + guard let provider = CGDataProvider(data: data as CFData), + let image = CGImage( + width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, + bytesPerRow: stride, space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue) + .union(.byteOrder32Little), provider: provider, decode: nil, + shouldInterpolate: false, intent: .defaultIntent) + else { + throw Failure.invalidVideo + } + return try straightRGB(image, orientation: position + 1, limits: limits) + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26FilesystemWeights.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26FilesystemWeights.swift new file mode 100644 index 0000000000..656bb99aca --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26FilesystemWeights.swift @@ -0,0 +1,688 @@ +// Copyright © 2026 Eigen Labs. +// MiMo-specific bounded local metadata gate over MLX.loadArrays(.cpu). +// Native arrays are lazy Load handles; this API never evaluates model payloads. +import CryptoKit +import Foundation +import MLX +import MLXLMCommon + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +public enum MiMoV26FilesystemError: Error, Equatable, Sendable { + case cancelled, invalidRoot + case unsafeFile(String) + case changedObject(String) + case limit(String) + case invalidMetadata(String) + case invalidHeader(String) + case nativeLoad(String) +} + +public struct MiMoV26FilesystemLimits: Sendable { + public let maximumShardBytes, maximumTotalFileBytes: Int + public let maximumConfigurationBytes, maximumIndexBytes, maximumHeaderBytes: Int + public let maximumMetadataBytes, maximumShards, maximumTensors: Int + public init( + maximumShardBytes: Int, maximumTotalFileBytes: Int, + maximumConfigurationBytes: Int = 1_048_576, maximumIndexBytes: Int = 4_194_304, + maximumHeaderBytes: Int = 1_048_576, maximumMetadataBytes: Int = 16_777_216, + maximumShards: Int = 64, maximumTensors: Int = 2048 + ) { + self.maximumShardBytes = maximumShardBytes + self.maximumTotalFileBytes = maximumTotalFileBytes + self.maximumConfigurationBytes = maximumConfigurationBytes + self.maximumIndexBytes = maximumIndexBytes + self.maximumHeaderBytes = maximumHeaderBytes + self.maximumMetadataBytes = maximumMetadataBytes + self.maximumShards = maximumShards + self.maximumTensors = maximumTensors + } +} + +/// Exact local identity/state, not a content hash. All timestamps retain ns. +public struct MiMoV26FilesystemObjectState: Codable, Equatable, Sendable { + public let device, inode: String + public let bytes: Int + public let modifiedSeconds, modifiedNanoseconds, changedSeconds, changedNanoseconds: Int64 + public init( + device: String, inode: String, bytes: Int, modifiedSeconds: Int64, + modifiedNanoseconds: Int64, changedSeconds: Int64, changedNanoseconds: Int64 + ) { + self.device = device + self.inode = inode + self.bytes = bytes + self.modifiedSeconds = modifiedSeconds + self.modifiedNanoseconds = modifiedNanoseconds + self.changedSeconds = changedSeconds + self.changedNanoseconds = changedNanoseconds + } +} + +public struct MiMoV26FilesystemExpectedFile: Codable, Sendable { + public let objectState: MiMoV26FilesystemObjectState? + public let headerSHA256: String? + /// Prior immutable digest reference only: payload hashing is not performed. + public let payloadSHA256: String? + public init( + objectState: MiMoV26FilesystemObjectState? = nil, headerSHA256: String? = nil, + payloadSHA256: String? = nil + ) { + self.objectState = objectState + self.headerSHA256 = headerSHA256 + self.payloadSHA256 = payloadSHA256 + } +} +public struct MiMoV26FilesystemExpectations: Codable, Sendable { + public let configurationSHA256, indexSHA256: String? + public let files: [String: MiMoV26FilesystemExpectedFile] + public init( + configurationSHA256: String? = nil, indexSHA256: String? = nil, + files: [String: MiMoV26FilesystemExpectedFile] = [:] + ) { + self.configurationSHA256 = configurationSHA256 + self.indexSHA256 = indexSHA256 + self.files = files + } +} + +public struct MiMoV26FilesystemShard: Codable, Sendable { + public let name: String + public let objectState: MiMoV26FilesystemObjectState + public let headerSHA256: String + public let headerBytes, tensorBytes: Int + public let tensorKeys: Set + public let tensorKeysInFileOrder: [String] + public let tensorLocations: [MiMoV26FilesystemTensorLocation] + public let suppliedPayloadSHA256: String? +} +public struct MiMoV26FilesystemTensorLocation: Codable, Sendable { + public let name: String + /// Absolute byte offset from the beginning of the safetensors file. + public let dataOffset, byteCount: Int +} +public struct MiMoV26FilesystemLoadPlan: Sendable { + public let canonicalRoot, configurationURL, indexURL: URL + public let configurationObject, indexObject: MiMoV26FilesystemObjectState + public let bundlePlan: MiMoV26ConvertedLoadPlan + public let shards: [MiMoV26FilesystemShard] + public let totalFileBytes, metadataBytesRead: Int + public let expectations: MiMoV26FilesystemExpectations + /// Known local names only; caller must independently bound/validate reads. + public var tokenizerURL: URL { canonicalRoot.appendingPathComponent("tokenizer.json") } + public var tokenizerConfigurationURL: URL { + canonicalRoot.appendingPathComponent("tokenizer_config.json") + } +} + +public enum MiMoV26FilesystemPhase: String, Codable, Sendable { + case configurationRead, indexRead, headerRead, preflightComplete + case willCreateShardHandles, shardHandlesCreated, willConstructBundle, bundleConstructed +} +public struct MiMoV26FilesystemProgress: Codable, Sendable { + public let phase: MiMoV26FilesystemPhase + public let currentFile: String? + public let completedShards, totalShards: Int + /// Actual bytes read by this preflight, excluding native reader internals. + public let metadataBytesRead: Int + /// Declared bytes represented by returned handles, NOT materialized bytes. + public let returnedHandleFileBytes, returnedHandleTensorBytes: Int + public let totalDeclaredFileBytes, totalDeclaredTensorBytes: Int +} +public struct MiMoV26FilesystemLoadReceipt: Encodable, Sendable { + public let canonicalRoot: URL + public let configSHA256, indexSHA256, descriptorSHA256: String + public let shards: [MiMoV26FilesystemShard] + public let metadataBytesRead, returnedHandleFileBytes, returnedHandleTensorBytes: Int + public let payloadDisposition = + "lazy native Load handles; no eval, residency or fresh payload-digest proof" + public let ownershipRequirement = + "caller retains immutable source files through materialization and retirement" +} +public struct MiMoV26FilesystemLoadResult { + public let bundle: MiMoV26ConvertedBundle + public let receipt: MiMoV26FilesystemLoadReceipt + fileprivate var materializationHandles: [MiMoV26FilesystemTensorHandle] + public var materializationHandleCount: Int { materializationHandles.count } + /// Transfers extra immutable source-handle references in shard/physical + /// offset order. No bytes are copied or evaluated. The caller drops this + /// array after explicit materialization; bundle parameters/views continue + /// owning their dependencies. These source names are not internal module + /// paths. Treat the arrays as read-only and do not copy this owner to retain + /// another source-handle collection accidentally. + public mutating func takeMaterializationHandles() -> [MiMoV26FilesystemTensorHandle] { + let handles = materializationHandles + materializationHandles = [] + return handles + } +} +public struct MiMoV26FilesystemTensorHandle { + public let name, shard: String + public let dataOffset, byteCount: Int + public let array: MLXArray +} + +private func fsHash(_ data: Data) -> String { + SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() +} +private func fsDigest(_ value: String?) -> Bool { + value.map { + $0.utf8.count == 64 + && $0.utf8.allSatisfy { (48 ... 57).contains($0) || (97 ... 102).contains($0) } + } ?? true +} +private func fsName(_ name: String) -> Bool { + !name.isEmpty && name != "." && name != ".." && !name.contains("/") && !name.contains("\\") + && !name.utf8.contains(0) +} +private func fsState(_ s: stat, _ name: String) throws -> MiMoV26FilesystemObjectState { + guard mode_t(s.st_mode) & mode_t(S_IFMT) == mode_t(S_IFREG), + let bytes = Int(exactly: s.st_size), bytes >= 0 + else { + throw MiMoV26FilesystemError.unsafeFile(name) + } + #if canImport(Darwin) + let m = s.st_mtimespec + let c = s.st_ctimespec + #else + let m = s.st_mtim + let c = s.st_ctim + #endif + return .init( + device: String(s.st_dev), inode: String(s.st_ino), bytes: bytes, + modifiedSeconds: Int64(m.tv_sec), modifiedNanoseconds: Int64(m.tv_nsec), + changedSeconds: Int64(c.tv_sec), changedNanoseconds: Int64(c.tv_nsec)) +} +private func fsCurrent(_ url: URL) throws -> MiMoV26FilesystemObjectState { + var s = stat() + guard url.isFileURL, lstat(url.path, &s) == 0 else { + throw MiMoV26FilesystemError.unsafeFile(url.lastPathComponent) + } + return try fsState(s, url.lastPathComponent) +} +private func fsSum(_ a: Int, _ b: Int, _ label: String) throws -> Int { + let result = a.addingReportingOverflow(b) + guard a >= 0, b >= 0, !result.overflow else { throw MiMoV26FilesystemError.limit(label) } + return result.partialValue +} + +/// Existing JSON decoders validate syntax but collapse duplicate object keys. +/// Reject those at every depth before decoding a config/index/header contract. +private func fsUniqueKeys(_ data: Data, _ name: String) throws { + let bytes = [UInt8](data) + var stack: [Set?] = [] + var i = 0 + while i < bytes.count { + let byte = bytes[i] + if byte == 123 || byte == 91 { + stack.append(byte == 123 ? Set() : nil) + guard stack.count <= 128 else { + throw MiMoV26FilesystemError.invalidMetadata("JSON nesting: " + name) + } + } else if byte == 125 || byte == 93 { + guard !stack.isEmpty else { throw MiMoV26FilesystemError.invalidMetadata(name) } + stack.removeLast() + } else if byte == 34 { + let start = i + i += 1 + while i < bytes.count && bytes[i] != 34 { + if bytes[i] == 92 { i += 1 } + i += 1 + } + guard i < bytes.count else { throw MiMoV26FilesystemError.invalidMetadata(name) } + var next = i + 1 + while next < bytes.count && [9, 10, 13, 32].contains(bytes[next]) { next += 1 } + if next < bytes.count && bytes[next] == 58 { + guard let top = stack.indices.last, stack[top] != nil else { + throw MiMoV26FilesystemError.invalidMetadata(name) + } + let key = try JSONDecoder().decode(String.self, from: Data(bytes[start ... i])) + guard stack[top]!.insert(key).inserted else { + throw MiMoV26FilesystemError.invalidMetadata("duplicate JSON key: " + name) + } + } + } + i += 1 + } + guard stack.isEmpty else { throw MiMoV26FilesystemError.invalidMetadata(name) } +} + +/// Opens only a regular non-symlink leaf. Metadata reads are bounded BEFORE IO. +private final class MiMoV26MetadataFile { + let url: URL + let handle: FileHandle + let state: MiMoV26FilesystemObjectState + init(_ url: URL) throws { + self.url = url + let before = try fsCurrent(url) + let descriptor = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) + guard descriptor >= 0 else { + throw MiMoV26FilesystemError.unsafeFile(url.lastPathComponent) + } + var s = stat() + guard fstat(descriptor, &s) == 0 else { + close(descriptor) + throw MiMoV26FilesystemError.unsafeFile(url.lastPathComponent) + } + do { + let actual = try fsState(s, url.lastPathComponent) + guard actual == before else { + throw MiMoV26FilesystemError.changedObject(url.lastPathComponent) + } + state = actual + handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true) + } catch { + close(descriptor) + throw error + } + } + func validate() throws { + var s = stat() + guard fstat(handle.fileDescriptor, &s) == 0, + try fsState(s, url.lastPathComponent) == state, try fsCurrent(url) == state + else { + throw MiMoV26FilesystemError.changedObject(url.lastPathComponent) + } + } + func read(_ count: Int, cancelled: () -> Bool) throws -> Data { + guard count >= 0, count <= state.bytes else { + throw MiMoV26FilesystemError.invalidMetadata(url.lastPathComponent) + } + var data = Data() + data.reserveCapacity(count) + while data.count < count { + if cancelled() { throw MiMoV26FilesystemError.cancelled } + try validate() + guard let chunk = try handle.read(upToCount: min(65536, count - data.count)), + !chunk.isEmpty + else { + throw MiMoV26FilesystemError.invalidMetadata("short read: " + url.lastPathComponent) + } + data.append(chunk) + } + try validate() + return data + } +} + +private struct MiMoV26FilesystemIndex: Decodable { + let weightMap: [String: String] + enum CodingKeys: String, CodingKey { case weightMap = "weight_map" } +} +private struct MiMoV26FilesystemTensor: Decodable { + let dtype: MiMoV26ConvertedScalarType + let shape, offsets: [Int] + enum CodingKeys: String, CodingKey { + case dtype, shape + case offsets = "data_offsets" + } +} +private struct MiMoV26FilesystemHeader: Decodable { + struct Key: CodingKey { + let stringValue: String + var intValue: Int? { nil } + init?(stringValue: String) { self.stringValue = stringValue } + init?(intValue: Int) { return nil } + } + let tensors: [String: MiMoV26FilesystemTensor] + init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: Key.self) + var result: [String: MiMoV26FilesystemTensor] = [:] + for key in c.allKeys { + if key.stringValue == "__metadata__" { + _ = try c.decode([String: String].self, forKey: key) + } else { + result[key.stringValue] = try c.decode(MiMoV26FilesystemTensor.self, forKey: key) + } + } + tensors = result + } +} + +public enum MiMoV26FilesystemWeights { + public static func preflight( + root: URL, provenance: MiMoV26ConvertedProvenance, + limits: MiMoV26FilesystemLimits, expectations: MiMoV26FilesystemExpectations = .init(), + isCancelled: () -> Bool = { false }, + progress: (MiMoV26FilesystemProgress) throws -> Void = { _ in } + ) throws -> MiMoV26FilesystemLoadPlan { + guard root.isFileURL else { throw MiMoV26FilesystemError.invalidRoot } + let canonical = root.standardizedFileURL.resolvingSymlinksInPath() + var directory = stat() + guard lstat(canonical.path, &directory) == 0, + mode_t(directory.st_mode) & mode_t(S_IFMT) == mode_t(S_IFDIR) + else { throw MiMoV26FilesystemError.invalidRoot } + guard + [ + limits.maximumShardBytes, limits.maximumTotalFileBytes, + limits.maximumConfigurationBytes, limits.maximumIndexBytes, + limits.maximumHeaderBytes, limits.maximumMetadataBytes, limits.maximumShards, + limits.maximumTensors, + ].allSatisfy({ $0 > 0 }), + limits.maximumConfigurationBytes <= 4_194_304, limits.maximumIndexBytes <= 16_777_216, + limits.maximumHeaderBytes <= 8_388_608, limits.maximumMetadataBytes <= 67_108_864, + limits.maximumShards <= 256, limits.maximumTensors <= 16_384, + fsDigest(expectations.configurationSHA256), fsDigest(expectations.indexSHA256) + else { + throw MiMoV26FilesystemError.limit("metadata limits or expected digest") + } + func check() throws { if isCancelled() { throw MiMoV26FilesystemError.cancelled } } + var metadataBytes = 0 + var totalFiles = 0 + var declaredTensorBytes = 0 + func emit(_ phase: MiMoV26FilesystemPhase, _ file: String?, _ done: Int, _ total: Int) + throws + { + try check() + try progress( + .init( + phase: phase, currentFile: file, completedShards: done, totalShards: total, + metadataBytesRead: metadataBytes, returnedHandleFileBytes: 0, + returnedHandleTensorBytes: 0, + totalDeclaredFileBytes: phase == .preflightComplete ? totalFiles : 0, + totalDeclaredTensorBytes: declaredTensorBytes)) + try check() + } + func readMetadata(_ name: String, maximum: Int) throws -> ( + Data, MiMoV26FilesystemObjectState + ) { + try check() + let file = try MiMoV26MetadataFile(canonical.appendingPathComponent(name)) + guard file.state.bytes <= maximum else { throw MiMoV26FilesystemError.limit(name) } + let sum = try fsSum(metadataBytes, file.state.bytes, "metadata budget") + guard sum <= limits.maximumMetadataBytes else { + throw MiMoV26FilesystemError.limit("metadata budget") + } + let data = try file.read(file.state.bytes, cancelled: isCancelled) + metadataBytes = sum + try fsUniqueKeys(data, name) + return (data, file.state) + } + let configURL = canonical.appendingPathComponent("config.json") + let indexURL = canonical.appendingPathComponent("model.safetensors.index.json") + let (config, configState) = try readMetadata( + "config.json", maximum: limits.maximumConfigurationBytes) + guard expectations.configurationSHA256.map({ $0 == fsHash(config) }) ?? true else { + throw MiMoV26FilesystemError.invalidMetadata("configuration digest") + } + try emit(.configurationRead, "config.json", 0, 0) + let (index, indexState) = try readMetadata( + "model.safetensors.index.json", maximum: limits.maximumIndexBytes) + guard expectations.indexSHA256.map({ $0 == fsHash(index) }) ?? true else { + throw MiMoV26FilesystemError.invalidMetadata("index digest") + } + let parsed = try JSONDecoder().decode(MiMoV26FilesystemIndex.self, from: index) + let names = Set(parsed.weightMap.values) + guard !parsed.weightMap.isEmpty, parsed.weightMap.count <= limits.maximumTensors, + !names.isEmpty, names.count <= limits.maximumShards, + names.allSatisfy({ fsName($0) && $0.hasSuffix(".safetensors") }), + Set(expectations.files.keys).isSubset(of: names) + else { + throw MiMoV26FilesystemError.invalidMetadata("root index/file inventory") + } + for expected in expectations.files.values { + guard fsDigest(expected.headerSHA256), fsDigest(expected.payloadSHA256) else { + throw MiMoV26FilesystemError.invalidMetadata("expected shard digest") + } + } + try rootWeights(canonical, expected: names) + try emit(.indexRead, "model.safetensors.index.json", 0, names.count) + var descriptors: [String: MiMoV26ConvertedTensorDescriptor] = [:] + var shards: [MiMoV26FilesystemShard] = [] + for name in names.sorted() { + try check() + let file = try MiMoV26MetadataFile(canonical.appendingPathComponent(name)) + guard file.state.bytes >= 8, file.state.bytes <= limits.maximumShardBytes else { + throw MiMoV26FilesystemError.limit(name) + } + totalFiles = try fsSum(totalFiles, file.state.bytes, "total declared file bytes") + guard totalFiles <= limits.maximumTotalFileBytes else { + throw MiMoV26FilesystemError.limit("total declared file bytes") + } + guard try fsSum(metadataBytes, 8, "header prefix") <= limits.maximumMetadataBytes else { + throw MiMoV26FilesystemError.limit("metadata budget") + } + let prefix = try file.read(8, cancelled: isCancelled) + let rawLength = prefix.enumerated().reduce(UInt64(0)) { + $0 | (UInt64($1.element) << ($1.offset * 8)) + } + guard rawLength > 0, rawLength <= UInt64(limits.maximumHeaderBytes), + let length = Int(exactly: rawLength), length <= file.state.bytes - 8 + else { + throw MiMoV26FilesystemError.invalidHeader(name) + } + let nextBytes = try fsSum( + metadataBytes, try fsSum(8, length, "header length"), "metadata budget") + guard nextBytes <= limits.maximumMetadataBytes else { + throw MiMoV26FilesystemError.limit("metadata budget") + } + let raw = try file.read(length, cancelled: isCancelled) + metadataBytes = nextBytes + let digest = fsHash(raw) + let expected = expectations.files[name] + guard expected?.objectState.map({ $0 == file.state }) ?? true, + expected?.headerSHA256.map({ $0 == digest }) ?? true + else { throw MiMoV26FilesystemError.changedObject(name) } + try fsUniqueKeys(raw, name) + let header = try JSONDecoder().decode(MiMoV26FilesystemHeader.self, from: raw) + guard !header.tensors.isEmpty, header.tensors.count <= limits.maximumTensors else { + throw MiMoV26FilesystemError.invalidHeader(name) + } + var spans: [(Int, Int)] = [] + var keys = Set() + var sum = 0 + for (key, tensor) in header.tensors { + guard descriptors[key] == nil, parsed.weightMap[key] == name, !tensor.shape.isEmpty, + tensor.shape.allSatisfy({ $0 > 0 && $0 <= Int(Int32.max) }), + tensor.offsets.count == 2, + tensor.offsets[0] >= 0, tensor.offsets[1] >= tensor.offsets[0] + else { throw MiMoV26FilesystemError.invalidHeader(key) } + var bytes = tensor.dtype.bytes + for dimension in tensor.shape { + let value = bytes.multipliedReportingOverflow(by: dimension) + guard !value.overflow else { throw MiMoV26FilesystemError.invalidHeader(key) } + bytes = value.partialValue + } + guard tensor.offsets[1] - tensor.offsets[0] == bytes, + tensor.offsets[1] <= file.state.bytes - 8 - length + else { throw MiMoV26FilesystemError.invalidHeader(key) } + spans.append((tensor.offsets[0], tensor.offsets[1])) + sum = try fsSum(sum, bytes, "tensor bytes") + keys.insert(key) + descriptors[key] = .init(shape: tensor.shape, dtype: tensor.dtype, file: name) + } + guard descriptors.count <= limits.maximumTensors else { + throw MiMoV26FilesystemError.limit("tensor count") + } + var end = 0 + for span in spans.sorted(by: { $0.0 < $1.0 }) { + guard span.0 == end else { + throw MiMoV26FilesystemError.invalidHeader("overlap/gap: " + name) + } + end = span.1 + } + guard end == file.state.bytes - 8 - length, + keys == Set(parsed.weightMap.filter { $0.value == name }.keys) + else { throw MiMoV26FilesystemError.invalidHeader("file closure: " + name) } + try file.validate() + let ordered = header.tensors.sorted { $0.value.offsets[0] < $1.value.offsets[0] } + let orderedKeys = ordered.map(\.key) + let locations = ordered.map { + MiMoV26FilesystemTensorLocation( + name: $0.key, + dataOffset: 8 + length + $0.value.offsets[0], + byteCount: $0.value.offsets[1] - $0.value.offsets[0]) + } + shards.append( + .init( + name: name, objectState: file.state, headerSHA256: digest, headerBytes: length, + tensorBytes: sum, + tensorKeys: keys, tensorKeysInFileOrder: orderedKeys, + tensorLocations: locations, suppliedPayloadSHA256: expected?.payloadSHA256)) + try emit(.headerRead, name, shards.count, names.count) + } + let bundlePlan = try MiMoV26ConvertedLoadPlan.make( + configurationData: config, indexData: index, descriptors: descriptors, + provenance: provenance) + declaredTensorBytes = bundlePlan.tensorBytes + let plan = MiMoV26FilesystemLoadPlan( + canonicalRoot: canonical, configurationURL: configURL, indexURL: indexURL, + configurationObject: configState, indexObject: indexState, bundlePlan: bundlePlan, + shards: shards, totalFileBytes: totalFiles, + metadataBytesRead: metadataBytes, expectations: expectations) + try emit(.preflightComplete, nil, shards.count, names.count) + try validateCurrentObjects(plan: plan, isCancelled: isCancelled) + return plan + } + + /// Recheck at caller materialization boundaries too: creating lazy handles + /// does not read or freeze payload bytes for later evaluation. + public static func validateCurrentObjects( + plan: MiMoV26FilesystemLoadPlan, + isCancelled: () -> Bool = { false } + ) throws { + if isCancelled() { throw MiMoV26FilesystemError.cancelled } + guard + plan.canonicalRoot.standardizedFileURL.resolvingSymlinksInPath() == plan.canonicalRoot, + try fsCurrent(plan.configurationURL) == plan.configurationObject, + try fsCurrent(plan.indexURL) == plan.indexObject + else { + throw MiMoV26FilesystemError.changedObject("root metadata") + } + try rootWeights(plan.canonicalRoot, expected: plan.bundlePlan.rootFiles) + for shard in plan.shards { + if isCancelled() { throw MiMoV26FilesystemError.cancelled } + guard + try fsCurrent(plan.canonicalRoot.appendingPathComponent(shard.name)) + == shard.objectState + else { + throw MiMoV26FilesystemError.changedObject(shard.name) + } + } + } + + public static func load( + plan: MiMoV26FilesystemLoadPlan, retaining work: NativeConstructionScope, + isCancelled: () -> Bool = { false }, + progress: (MiMoV26FilesystemProgress) throws -> Void = { _ in } + ) throws -> MiMoV26FilesystemLoadResult { + try work.withPhase(.filesystemLoad) { + try loadInScope(plan: plan, work: work, isCancelled: isCancelled, progress: progress) + } + } + + private static func loadInScope( + plan: MiMoV26FilesystemLoadPlan, work: NativeConstructionScope, + isCancelled: () -> Bool, + progress: (MiMoV26FilesystemProgress) throws -> Void + ) throws -> MiMoV26FilesystemLoadResult { + try validateCurrentObjects(plan: plan, isCancelled: isCancelled) + var tensors: [String: MLXArray] = [:] + var fileBytes = 0 + var tensorBytes = 0 + var completed = 0 + func emit(_ phase: MiMoV26FilesystemPhase, _ name: String?) throws { + if isCancelled() { throw MiMoV26FilesystemError.cancelled } + try progress( + .init( + phase: phase, currentFile: name, completedShards: completed, + totalShards: plan.shards.count, + metadataBytesRead: plan.metadataBytesRead, returnedHandleFileBytes: fileBytes, + returnedHandleTensorBytes: tensorBytes, + totalDeclaredFileBytes: plan.totalFileBytes, + totalDeclaredTensorBytes: plan.bundlePlan.tensorBytes)) + if isCancelled() { throw MiMoV26FilesystemError.cancelled } + } + for shard in plan.shards { + try emit(.willCreateShardHandles, shard.name) + let url = plan.canonicalRoot.appendingPathComponent(shard.name) + guard try fsCurrent(url) == shard.objectState else { + throw MiMoV26FilesystemError.changedObject(shard.name) + } + let values: [String: MLXArray] + // Pinned safetensors reader builds lazy Load nodes, not payload work. + // Capture the exact CPU stream and returned roots before any veto. + let sourceStream = StreamOrDevice.cpu + try work.capture(sourceStream.stream) + do { values = try loadArrays(url: url, stream: sourceStream) } catch { + throw MiMoV26FilesystemError.nativeLoad(shard.name) + } + try work.retain(arrays: values.values) + try work.checkpoint("filesystem.returnedSourceHandles") + guard try fsCurrent(url) == shard.objectState else { + throw MiMoV26FilesystemError.changedObject(shard.name) + } + guard Set(values.keys) == shard.tensorKeys else { + throw MiMoV26FilesystemError.invalidHeader("native key closure: " + shard.name) + } + for (key, value) in values { + guard let d = plan.bundlePlan.descriptors[key], value.shape == d.shape, + value.dtype == d.dtype.dtype, tensors[key] == nil + else { + throw MiMoV26FilesystemError.invalidHeader("native handle: " + key) + } + tensors[key] = value + } + completed += 1 + fileBytes = try fsSum(fileBytes, shard.objectState.bytes, "returned handles") + tensorBytes = try fsSum(tensorBytes, shard.tensorBytes, "returned tensor handles") + try emit(.shardHandlesCreated, shard.name) + } + try emit(.willConstructBundle, nil) + try validateCurrentObjects(plan: plan, isCancelled: isCancelled) + try work.capture(StreamOrDevice.default.stream) + let bundle = try MiMoV26ConvertedWeights.load(plan: plan.bundlePlan, tensors: tensors) + try work.retainOwner(bundle.target) + try work.retainOwner(bundle.vision) + try work.retainOwner(bundle.audioPatch) + try work.retainOwner(bundle.mtp) + try work.checkpoint("filesystem.constructedBundle") + try emit(.bundleConstructed, nil) + try validateCurrentObjects(plan: plan, isCancelled: isCancelled) + let handles = plan.shards.flatMap { shard in + shard.tensorLocations.map { location in + MiMoV26FilesystemTensorHandle( + name: location.name, shard: shard.name, dataOffset: location.dataOffset, + byteCount: location.byteCount, array: tensors[location.name]!) + } + } + return .init( + bundle: bundle, + receipt: .init( + canonicalRoot: plan.canonicalRoot, configSHA256: plan.bundlePlan.configSHA256, + indexSHA256: plan.bundlePlan.indexSHA256, + descriptorSHA256: plan.bundlePlan.descriptorSHA256, shards: plan.shards, + metadataBytesRead: plan.metadataBytesRead, returnedHandleFileBytes: fileBytes, + returnedHandleTensorBytes: tensorBytes), + materializationHandles: handles) + } + + private static func rootWeights(_ root: URL, expected: Set) throws { + guard + let entries = FileManager.default.enumerator( + at: root, includingPropertiesForKeys: nil, options: [.skipsSubdirectoryDescendants]) + else { + throw MiMoV26FilesystemError.invalidRoot + } + // Other tokenizer/processor/provenance files and separate subdirectories + // are outside the root weight-map scope. Any unindexed root payload + // format is rejected, not silently skipped by extension filtering. + var count = 0 + var payloads = Set() + while let url = entries.nextObject() as? URL { + count += 1 + guard count <= 4096 else { + throw MiMoV26FilesystemError.limit("root directory entries") + } + if ["safetensors", "npz", "bin", "pt", "pth"].contains(url.pathExtension.lowercased()) { + payloads.insert(url.lastPathComponent) + } + } + guard payloads == expected else { + throw MiMoV26FilesystemError.invalidMetadata("unindexed/missing root payload files") + } + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26LoadFootprint.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26LoadFootprint.swift new file mode 100644 index 0000000000..bddfd0d178 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26LoadFootprint.swift @@ -0,0 +1,202 @@ +// Copyright © 2026 Eigen Labs. +import Foundation + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +public enum MiMoV26LoadFootprintError: Error, Equatable, Sendable { + case unsupportedProfile + case invalidInventory + case overflow +} + +/// Source-bound estimate for the strict root-bundle loader followed by serial +/// source-handle materialization. This is NOT measured peak residency, a runtime +/// activation/KV reserve, or permission to bypass model-load admission. +/// +/// All root components remain resident, including vision/audio-patch/MTP. The +/// separately packaged audio tokenizer/DFlash/original-head assets are outside +/// this loader's root inventory; a consumer loading any of them must reserve +/// their additional residency/transients independently before allocation. +public enum MiMoV26LoadFootprint { + public static let contract = "mimo-v26-strict-root-serial-source-v1" + + public struct Estimate: Equatable, Encodable, Sendable { + public let contract: String + public let residentBytes: UInt64 + public let transientBytes: UInt64 + public let totalBytes: UInt64 + public let largestShardBytes: UInt64 + public let largestTensorBytes: UInt64 + public let largestExpertBlockBytes: UInt64 + public let auxiliaryCopyBytes: UInt64 + public let pageRoundingBytes: UInt64 + public let metadataAllowanceBytes: UInt64 + public let tensorCount: Int + public let configSHA256, indexSHA256, descriptorSHA256: String + } + + /// Use only the plan validated by MiMoV26FilesystemWeights. Recheck object + /// states now and again at the actual loader/materialization boundary. + public static func estimate(plan: MiMoV26FilesystemLoadPlan) throws -> Estimate { + #if os(macOS) && arch(arm64) + // The general reader accepts caller-selected wider limits; this + // smaller native allowance has its own explicit bounded profile. + guard plan.metadataBytesRead <= 16 * 1_048_576 else { + throw MiMoV26LoadFootprintError.unsupportedProfile + } + try MiMoV26FilesystemWeights.validateCurrentObjects(plan: plan) + let files = plan.shards.map { ($0.name, $0.objectState.bytes) } + let result = try estimateValidatedLayout( + plan.bundlePlan, files: files, allocationPageBytes: Int(getpagesize())) + guard UInt64(plan.totalFileBytes) == result.residentBytes else { + throw MiMoV26LoadFootprintError.invalidInventory + } + return result + #else + throw MiMoV26LoadFootprintError.unsupportedProfile + #endif + } + + /// Internal pure arithmetic seam for metadata-only positive/negative tests. + /// Public callers cannot replace filesystem validation with this function. + static func estimateValidatedLayout( + _ plan: MiMoV26ConvertedLoadPlan, + files: [(name: String, bytes: Int)], allocationPageBytes: Int + ) throws -> Estimate { + let config = plan.configuration + guard allocationPageBytes == 16_384, config.modelType == "mimo_v2", + config.dtype == "bfloat16", config.numNextnPredictLayers == 3, + config.quantization.nativeDefault?.bits == 4, + plan.provenance.layout == .nativeConversion + ? (config.quantization.nativeDefault?.mode == "mxfp4" + && config.quantization.nativeDefault?.groupSize == 32) + : (config.quantization.nativeDefault?.mode == "affine" + && config.quantization.nativeDefault?.groupSize == 64) + else { throw MiMoV26LoadFootprintError.unsupportedProfile } + guard files.count == plan.rootFiles.count, !files.isEmpty, + Set(files.map(\.name)) == plan.rootFiles, + plan.descriptors.count <= 2048, !plan.descriptors.isEmpty, + Set(plan.components.keys) == Set(MiMoV26ConvertedComponent.allCases) + else { throw MiMoV26LoadFootprintError.invalidInventory } + + var tensorBytes: [String: UInt64] = [:] + var perFile: [String: UInt64] = [:] + var totalTensorBytes: UInt64 = 0 + for (name, descriptor) in plan.descriptors { + guard !descriptor.shape.isEmpty, plan.rootFiles.contains(descriptor.file) else { + throw MiMoV26LoadFootprintError.invalidInventory + } + var bytes = UInt64(descriptor.dtype.bytes) + for dimension in descriptor.shape { + guard dimension > 0 else { throw MiMoV26LoadFootprintError.invalidInventory } + bytes = try multiply(bytes, UInt64(dimension)) + } + tensorBytes[name] = bytes + perFile[descriptor.file] = try add(perFile[descriptor.file, default: 0], bytes) + totalTensorBytes = try add(totalTensorBytes, bytes) + } + guard totalTensorBytes == UInt64(plan.tensorBytes) else { + throw MiMoV26LoadFootprintError.invalidInventory + } + var resident: UInt64 = 0 + var largestShard: UInt64 = 0 + for (name, rawBytes) in files { + guard rawBytes > 8, let payload = perFile[name], UInt64(rawBytes) > payload else { + throw MiMoV26LoadFootprintError.invalidInventory + } + resident = try add(resident, UInt64(rawBytes)) + largestShard = max(largestShard, UInt64(rawBytes)) + } + // This profile caps total preflight metadata in the public entrypoint; + // also bound the shard-header difference independently. Price actual + // file bytes, not only payloads; refuse unrelated oversized inventory. + guard resident >= totalTensorBytes, + resident - totalTensorBytes <= 16 * 1_048_576 + else { + throw MiMoV26LoadFootprintError.invalidInventory + } + + var seen = Set() + var auxiliaryCopies: UInt64 = 0 + for component in MiMoV26ConvertedComponent.allCases { + guard let names = plan.components[component], !names.isEmpty else { + throw MiMoV26LoadFootprintError.invalidInventory + } + for name in names { + guard seen.insert(name).inserted, let bytes = tensorBytes[name] else { + throw MiMoV26LoadFootprintError.invalidInventory + } + if component != .target { auxiliaryCopies = try add(auxiliaryCopies, bytes) } + } + } + guard seen == Set(tensorBytes.keys) else { + throw MiMoV26LoadFootprintError.invalidInventory + } + + var expertBlocks: [String: UInt64] = [:] + let sourceNames = Dictionary( + uniqueKeysWithValues: plan.parameterNames.map { ($0.value, $0.key) }) + for module in plan.targetExpertModulePaths { + let components = module.split(separator: ".") + guard components.count > 1 else { throw MiMoV26LoadFootprintError.invalidInventory } + let parent = components.dropLast().joined(separator: ".") + guard let weight = sourceNames[module + ".weight"], + let scale = sourceNames[module + ".scales"] + else { + throw MiMoV26LoadFootprintError.invalidInventory + } + guard let weightBytes = tensorBytes[weight], let scaleBytes = tensorBytes[scale], + plan.descriptors[weight]?.dtype == .uint32, + plan.descriptors[scale]?.dtype == .uint8 + else { + throw MiMoV26LoadFootprintError.invalidInventory + } + expertBlocks[parent] = try add( + expertBlocks[parent, default: 0], + try add(weightBytes, scaleBytes)) + } + let largestTensor = tensorBytes.values.max() ?? 0 + let largestExpert = expertBlocks.values.max() ?? 0 + let rounding = try multiply(try multiply(UInt64(tensorBytes.count), 2), 16_384) + let metadata: UInt64 = 1 << 30 + // Deliberately SUM, not max, the source-derived copy families: + // - one complete source shard, despite direct-to-final tensor reads; + // - one largest source tensor, despite no whole-tensor staging copy; + // - one whole packed expert block (all three projections); + // - complete vision/audio-patch/assistant copies (not only reshapes); + // - two sets of page-rounding allowances and1GiB for small loader state. + // A consumer using a different loader, dtype conversion or concurrent + // materialization cannot inherit this contract. Qualification must still + // measure phase peaks and retain unchanged OS/activation/KV safeguards. + var transient: UInt64 = 0 + for allowance in [ + largestShard, largestTensor, largestExpert, + auxiliaryCopies, rounding, metadata, + ] { + transient = try add(transient, allowance) + } + return Estimate( + contract: contract, residentBytes: resident, + transientBytes: transient, totalBytes: try add(resident, transient), + largestShardBytes: largestShard, largestTensorBytes: largestTensor, + largestExpertBlockBytes: largestExpert, auxiliaryCopyBytes: auxiliaryCopies, + pageRoundingBytes: rounding, metadataAllowanceBytes: metadata, + tensorCount: tensorBytes.count, configSHA256: plan.configSHA256, + indexSHA256: plan.indexSHA256, descriptorSHA256: plan.descriptorSHA256) + } + + private static func add(_ a: UInt64, _ b: UInt64) throws -> UInt64 { + let result = a.addingReportingOverflow(b) + guard !result.overflow else { throw MiMoV26LoadFootprintError.overflow } + return result.partialValue + } + private static func multiply(_ a: UInt64, _ b: UInt64) throws -> UInt64 { + let result = a.multipliedReportingOverflow(by: b) + guard !result.overflow else { throw MiMoV26LoadFootprintError.overflow } + return result.partialValue + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26LoadedModel.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26LoadedModel.swift new file mode 100644 index 0000000000..5a187b8e5d --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26LoadedModel.swift @@ -0,0 +1,520 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +/// Non-Module lifetime box. It retains the exact load receipt/reservation and +/// all root components without adding a second reflected parameter tree. +final class MiMoV26LoadedResources { + let loaded: MiMoV26SerialLoadResult + let prepared: MiMoV26ModelFactory.Prepared + let mediaGeneration = MiMoV26MediaGeneration() + let nativePrefixLifetime: MiMoV26NativePrefixLifetime + var nativePrefixValidator: MiMoV26NativeCompletePrefixValidator? + let nativePagedLifetime: MiMoV26NativePrefixLifetime + var nativePagedValidator: MiMoV26NativePagedValidator? + var audioSidecar: MiMoV26AudioSidecarLoaded? + var audioInstallation: (ownerID: UUID, epoch: UInt64)? + init(loaded: MiMoV26SerialLoadResult, prepared: MiMoV26ModelFactory.Prepared) { + self.loaded = loaded + self.prepared = prepared + nativePrefixLifetime = .init(loadSessionID: loaded.receipt.sessionID) + nativePagedLifetime = .init(loadSessionID: loaded.receipt.sessionID) + } +} + +/// Actor-local native serving handles. Both exported handles independently +/// retain the complete loaded owner; neither requires the wrapper to stay alive. +public struct MiMoV26CBv2Binding { + public let adapter: MiMoV26CBv2Adapter + public let assistant: MiMoV26MTPAssistant? + public let stopTokenIDs: Set + let mediaGeneration: MiMoV26MediaGeneration +} + +/// Native-local construction result; no second target and no Sendable raw +/// component escape. Only the protected loaded wrapper can issue this profile. +public struct MiMoV26ManagedMediaExecutionResources { + public let backend: MiMoV26CBv2Backend + public let cacheProvider: any CBv2LayerCacheProvider + public let contract: CBv2NativeExecutionContract +} + +/// Immutable loaded wrapper for ordinary ModelContext/ModelContainer ownership. +/// It registers each existing component exactly once, never reloads/quantizes, +/// and retains the loaded media towers. Generic iteration is still refused; +/// managed decoded media is a separate explicitly issued native profile. +/// Inherited Module mutation is outside the verified immutable-load contract. +public final class MiMoV26LoadedModel: Module, LanguageModel, GenericGenerationValidating { + let resources: MiMoV26LoadedResources + private let target: MiMoV26TextModel + private let vision: MiMoV26VisionTower + private let audioPatch: MiMoV26AudioPatchEncoder + private let mtp: MiMoV26MTP + // Native-only preparation remains under the real loaded wrapper while the + // provider registers its store using scalar metadata across an await. + var nativePagedPreparation: MiMoV26CBv2Binding? + var nativeCompletePrefixPreparation: + (metadata: MiMoV26NativeCompletePrefixMetadata, binding: MiMoV26CBv2Binding)? + var hasIssuedManagedMediaProfile: Bool { managedMedia != nil || managedAudio != nil } + private var managedMedia: (processor: MiMoV26MultimodalProcessor, binding: MiMoV26CBv2Binding)? + private var managedAudio: + ( + processor: MiMoV26MultimodalProcessor, + binding: MiMoV26CBv2Binding, contractID: UUID + )? + + init(loaded: MiMoV26SerialLoadResult, prepared: MiMoV26ModelFactory.Prepared) { + resources = .init(loaded: loaded, prepared: prepared) + target = loaded.bundle.target + vision = loaded.bundle.vision + audioPatch = loaded.bundle.audioPatch + mtp = loaded.bundle.mtp + super.init() + } + + public var nativeConfiguration: MiMoV26Configuration { target.configuration } + public var loadReceipt: MiMoV26SerialLoadReceipt { resources.loaded.receipt } + public var templateSHA256: String { resources.prepared.templateSHA256 } + public var stopTokenIDs: Set { resources.prepared.stopTokenIDs } + + /// Provider must perform the adapter's explicit native KV type probe before + /// creating a backend. MTP remains an explicit choice, disabled by default. + /// adapter.target is an existing borrowed lower-layer escape hatch: extracting + /// that raw target and dropping its adapter is not owner-guaranteed use. + public func makeCBv2Binding( + enableMTP: Bool = false, + verificationMode: CBv2MTPVerificationMode = .serialTarget + ) throws -> MiMoV26CBv2Binding { + guard enableMTP || verificationMode == .serialTarget else { + throw MiMoV26MTPError.unsupportedConfiguration( + "Rectangular verification requires the real loaded assistant") + } + let assistant = + enableMTP + ? try MiMoV26MTPAssistant( + target: target, predictor: mtp, + retaining: resources, verificationMode: verificationMode) : nil + let adapter = try MiMoV26CBv2Adapter( + target: target, assistant: assistant, retaining: resources) + return .init( + adapter: adapter, assistant: assistant, stopTokenIDs: stopTokenIDs, + mediaGeneration: resources.mediaGeneration) + } + + /// Native decoded-input entrypoint. The same loaded binding must own + /// the eventual EngineV2. Its real type probe still precedes backend/cache + /// provider construction. Installed text MTP uses the real request-scoped + /// target-only media fallback; this does not qualify media drafting. + public func makeMultimodalProcessor( + binding: MiMoV26CBv2Binding, + limits: MiMoV26MultimodalLimits, + audioCodec: MiMoV26OwnedAudioCodec? = nil + ) throws -> MiMoV26MultimodalProcessor { + guard binding.adapter.target === target, + binding.assistant === binding.adapter.assistant, + binding.adapter.supportsMultimodalPrefill(attention: .causal), + binding.mediaGeneration === resources.mediaGeneration + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + return try .init( + configuration: nativeConfiguration, tokenizer: resources.prepared.tokenizer, + chatTemplate: resources.prepared.processor.chatTemplate, templateSHA256: templateSHA256, + limits: limits, vision: vision, audioPatch: audioPatch, adapter: binding.adapter, + stopTokens: stopTokenIDs, generation: resources.mediaGeneration, retaining: resources, + audioCodec: audioCodec, + audioSidecar: resources.audioSidecar?.codec === audioCodec + ? resources.audioSidecar : nil) + } + + /// Setup only, inside the existing factory construction scope, after the + /// real KV probe. Warm requests never call this or reopen that scope. + public func makeManagedMediaExecutionResources( + binding: MiMoV26CBv2Binding, + bytesCapacity: Int, limits: MiMoV26MultimodalLimits, + retaining scope: NativeConstructionScope + ) throws -> MiMoV26ManagedMediaExecutionResources { + guard managedMedia == nil, managedAudio == nil else { + throw MiMoV26MultimodalError.incompatibleOwner + } + try resources.nativePrefixLifetime.requirePreparation() + try scope.requireImmutableLoadedOwner(resources) + let processor = try makeMultimodalProcessor(binding: binding, limits: limits) + try scope.retainOwner(processor) + let issued = try binding.adapter.makeNativeDecodedVisualResources( + bytesCapacity: bytesCapacity, processor: processor, loadedOwner: resources, + retaining: scope) + managedMedia = (processor, binding) + return .init( + backend: issued.backend, cacheProvider: issued.cacheProvider, contract: issued.contract) + } + + /// Load the separately admitted, authenticated input codec in the SAME + /// protected construction scope. Store its actual owner before any late + /// veto; never create a reflected Module or a second target/container. + public func installAudioSidecar( + session: MiMoV26AudioSidecarLoadSession, + reservation: any MiMoV26AudioSidecarLoadReservation, + retaining scope: NativeConstructionScope, isCancelled: () -> Bool + ) throws + -> MiMoV26AudioSidecarLoadReceipt + { + try scope.requireImmutableLoadedOwner(resources) + try resources.nativePrefixLifetime.requirePreparation() + guard resources.audioSidecar == nil, managedMedia == nil, managedAudio == nil, + session.request.canonicalRoot == loadReceipt.binding.canonicalRoot, + session.request.mainConfigurationSHA256 == loadReceipt.binding.configSHA256, + session.mainConfiguration == nativeConfiguration + else { + throw MiMoV26AudioSidecarError.invalidBinding + } + let loaded = try session.load( + reservation: reservation, retaining: scope, isCancelled: isCancelled) + resources.audioSidecar = loaded + resources.audioInstallation = (scope.snapshot.ownerID, scope.snapshot.epoch) + try scope.retainOwner(loaded) + try scope.authorizeImmutableLoadedOwner(loaded) + try scope.invalidateOnFailedCompletion(loaded) { loaded.invalidate() } + try loaded.validate() + return loaded.receipt + } + + /// Serialized installed-owner validation, with metadata-only return. No + /// sidecar/session/codec reference escapes the strict loaded wrapper. + public func validateInstalledAudioSidecar(expectedRequest: MiMoV26AudioSidecarLoadRequest) + throws + -> MiMoV26AudioSidecarLoadReceipt + { + guard let sidecar = resources.audioSidecar, sidecar.receipt.request == expectedRequest, + expectedRequest.canonicalRoot == loadReceipt.binding.canonicalRoot, + expectedRequest.mainConfigurationSHA256 == loadReceipt.binding.configSHA256 + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + try sidecar.validate() + return sidecar.receipt + } + + /// Cold setup only: a sidecar may have been installed before a later veto, + /// and no managed profile was issued; host also requires its exact engine + /// absent. The exact installation epoch must have + /// genuinely completed. Failed construction produces no admissible receipt. + /// The host still proves all enclosing Tasks/aliases and settles its own C. + public func releaseInstalledAudioAfterConstructionCompletion( + _ receipt: NativeConstructionReceipt + ) throws { + guard managedAudio == nil, managedMedia == nil else { + throw MiMoV26MultimodalError.incompatibleOwner + } + guard let sidecar = resources.audioSidecar else { + guard resources.audioInstallation == nil else { + throw MiMoV26MultimodalError.incompatibleOwner + } + return // no installed codec, not a native completion/credit assertion + } + guard let origin = resources.audioInstallation, receipt.ownerID == origin.ownerID, + receipt.epoch == origin.epoch, receipt.completion == .capturedStreamsCompleted + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + sidecar.invalidate() + resources.audioSidecar = nil + resources.audioInstallation = nil + } + + /// Setup only. Bare codec conformance/digest metadata cannot issue this + /// profile: the typed owner must come from installAudioSidecar above. + public func makeManagedAudioExecutionResources( + binding: MiMoV26CBv2Binding, + bytesCapacity: Int, limits: MiMoV26MultimodalLimits, + retaining scope: NativeConstructionScope + ) throws -> MiMoV26ManagedMediaExecutionResources { + guard managedMedia == nil, managedAudio == nil, let sidecar = resources.audioSidecar else { + throw MiMoV26MultimodalError.missingAudioCodec + } + try resources.nativePrefixLifetime.requirePreparation() + try scope.requireImmutableLoadedOwner(resources) + try sidecar.validate() + guard sidecar.receipt.request.canonicalRoot == loadReceipt.binding.canonicalRoot, + sidecar.receipt.request.mainConfigurationSHA256 == loadReceipt.binding.configSHA256, + sidecar.codec.generation == sidecar.receipt.codecGeneration, + sidecar.codec.sourceIdentity == sidecar.receipt.sourceIdentity + else { + throw MiMoV26AudioSidecarError.invalidBinding + } + // A loaded sidecar may survive an earlier successful setup epoch; + // reauthorize exactly this still-valid owner in the current scope. + try scope.retainOwner(sidecar) + try scope.authorizeImmutableLoadedOwner(sidecar) + try scope.invalidateOnFailedCompletion(sidecar) { sidecar.invalidate() } + let processor = try makeMultimodalProcessor( + binding: binding, limits: limits, audioCodec: sidecar.codec) + try scope.retainOwner(processor) + let issued = try binding.adapter.makeNativeDecodedAudioResources( + bytesCapacity: bytesCapacity, + processor: processor, loadedOwner: resources, audioOwner: sidecar, + audioSessionID: sidecar.receipt.request.sessionID, + audioSourceIdentity: sidecar.receipt.sourceIdentity, + audioGeneration: sidecar.receipt.codecGeneration, retaining: scope) + managedAudio = (processor, binding, issued.contract.id) + return .init( + backend: issued.backend, cacheProvider: issued.cacheProvider, contract: issued.contract) + } + + /// One setup-only profile for text complete-prefix plus real decoded + /// visual media. This never upgrades an already issued media/text-prefix + /// profile, and media requests keep their existing noncacheable seals. + public func makeManagedMediaCompletePrefixExecutionResources( + binding: MiMoV26CBv2Binding, + bytesCapacity: Int, expectedMetadata: MiMoV26NativeCompletePrefixMetadata, + completePrefixCache: any CBv2NativeCompletePrefixCache, + processMemoryOwner: any CBv2ProcessMemoryOwner, limits: MiMoV26MultimodalLimits, + retaining scope: NativeConstructionScope + ) throws -> MiMoV26ManagedMediaExecutionResources { + guard managedMedia == nil, managedAudio == nil else { + throw MiMoV26MultimodalError.incompatibleOwner + } + try resources.nativePrefixLifetime.requirePreparation() + try scope.requireImmutableLoadedOwner(resources) + let processor = try makeMultimodalProcessor(binding: binding, limits: limits) + try scope.retainOwner(processor) + let validator = try beginNativeCompletePrefixIssuance( + binding: binding, + expectedMetadata: expectedMetadata, retaining: scope) + do { + let issued = try binding.adapter.makeNativeManagedCompletePrefixResources( + bytesCapacity: bytesCapacity, processor: processor, loadedOwner: resources, + validator: validator, completePrefixCache: completePrefixCache, + processMemoryOwner: processMemoryOwner, retaining: scope) + try finishNativeCompletePrefixIssuance(issued.contract) + // All throwing validation precedes publishing the joint association. + managedMedia = (processor, binding) + return .init( + backend: issued.backend, cacheProvider: issued.cacheProvider, + contract: issued.contract) + } catch { + failNativeCompletePrefixIssuance() + throw error + } + } + + /// Same joint ticket with the genuine separately loaded/admitted sidecar. + /// No public codec, replacement target or second bank can be supplied. + public func makeManagedAudioCompletePrefixExecutionResources( + binding: MiMoV26CBv2Binding, + bytesCapacity: Int, expectedMetadata: MiMoV26NativeCompletePrefixMetadata, + completePrefixCache: any CBv2NativeCompletePrefixCache, + processMemoryOwner: any CBv2ProcessMemoryOwner, limits: MiMoV26MultimodalLimits, + retaining scope: NativeConstructionScope + ) throws -> MiMoV26ManagedMediaExecutionResources { + guard managedMedia == nil, managedAudio == nil, let sidecar = resources.audioSidecar else { + throw MiMoV26MultimodalError.missingAudioCodec + } + try resources.nativePrefixLifetime.requirePreparation() + try scope.requireImmutableLoadedOwner(resources) + try sidecar.validate() + guard sidecar.receipt.request.canonicalRoot == loadReceipt.binding.canonicalRoot, + sidecar.receipt.request.mainConfigurationSHA256 == loadReceipt.binding.configSHA256, + sidecar.codec.generation == sidecar.receipt.codecGeneration, + sidecar.codec.sourceIdentity == sidecar.receipt.sourceIdentity + else { + throw MiMoV26AudioSidecarError.invalidBinding + } + try scope.retainOwner(sidecar) + try scope.authorizeImmutableLoadedOwner(sidecar) + try scope.invalidateOnFailedCompletion(sidecar) { sidecar.invalidate() } + let processor = try makeMultimodalProcessor( + binding: binding, limits: limits, audioCodec: sidecar.codec) + try scope.retainOwner(processor) + let validator = try beginNativeCompletePrefixIssuance( + binding: binding, + expectedMetadata: expectedMetadata, retaining: scope) + do { + let issued = try binding.adapter.makeNativeManagedCompletePrefixResources( + bytesCapacity: bytesCapacity, processor: processor, loadedOwner: resources, + validator: validator, completePrefixCache: completePrefixCache, + processMemoryOwner: processMemoryOwner, audioOwner: sidecar, + audioSessionID: sidecar.receipt.request.sessionID, + audioSourceIdentity: sidecar.receipt.sourceIdentity, + audioGeneration: sidecar.receipt.codecGeneration, retaining: scope) + try sidecar.validate() + try finishNativeCompletePrefixIssuance(issued.contract) + managedAudio = (processor, binding, issued.contract.id) + return .init( + backend: issued.backend, cacheProvider: issued.cacheProvider, + contract: issued.contract) + } catch { + failNativeCompletePrefixIssuance() + throw error + } + } + + /// Decoded PCM (optionally mixed with ordered RGB/silent-video) uses the + /// existing warm engine loan and one-shot seal, never construction epochs. + public func prepareManagedDecodedAudioMedia( + _ input: MiMoV26MultimodalInput, engine: EngineV2, + authorize: (MiMoV26MultimodalPlan, Int) throws -> any MiMoV26MediaWorkReservation, + retire: @escaping (any MiMoV26MediaWorkReservation) throws -> Void, + isCancelled: () -> Bool + ) throws -> CBv2Request { + guard let audio = managedAudio, let sidecar = resources.audioSidecar, + audio.processor.audioSidecar === sidecar, + audio.processor.audioCodec === sidecar.codec, + engine.nativeShutdownExecutionContractID == audio.contractID + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + try sidecar.validate() + return try engine.prepareNativeMedia(processor: audio.processor, loadedOwner: resources) { + work in + if isCancelled() { throw MiMoV26MultimodalError.cancelled } + try sidecar.validate() + work.retain(sidecar) + let plan = try audio.processor.plan(input) + guard !plan.spans.isEmpty else { throw MiMoV26MultimodalError.incompatiblePlan } + try engine.requireNativeMediaCanEverFit( + promptTokens: plan.promptTokens, + maximumOutputTokens: plan.maximumOutputTokens) + let bytes = try audio.processor.managedAudioCommitmentBytes(plan) + let reservation = try authorize(plan, bytes) + work.retain(reservation) + work.afterRetirement { try retire(reservation) } + let prepared = try audio.processor.prepareManagedAudio( + plan, sidecar: sidecar, + authorize: { actual in + try reservation.validate(plan: actual) + return reservation + }, + isCancelled: isCancelled, work: work) + work.retain(prepared) + try work.validateAtBinding(prepared) + return try prepared.makeRequest(binding: audio.binding, id: .init(0)) + } + } + + /// Host calls only AFTER its real engine/bridge/consumer proof. The SDK + /// receipt must belong to the single-use contract issued by this wrapper. + /// Drops codec aliases only; separate sidecar ledger settlement stays host- + /// owned and is NOT inferred from this method or a physical-free claim. + public func releaseManagedAudioAfterNativeRetirement(_ receipt: CBv2NativeShutdownReceipt) + throws + { + guard let audio = managedAudio, receipt.executionContractID == audio.contractID, + receipt.generation == 1 + else { throw MiMoV26MultimodalError.incompatibleOwner } + invalidateMultimodalPreparation() + managedAudio = nil + resources.audioSidecar = nil + resources.audioInstallation = nil + } + + /// Published-serving decoded RGB/silent-video path. Raw native arrays never + /// cross the model/engine owner. The returned public closure refuses direct + /// access; only the issuing engine can consume its one-shot sealed token. + public func prepareManagedDecodedMedia( + _ input: MiMoV26MultimodalInput, engine: EngineV2, + authorize: (MiMoV26MultimodalPlan, Int) throws -> any MiMoV26MediaWorkReservation, + retire: @escaping (any MiMoV26MediaWorkReservation) throws -> Void, + isCancelled: () -> Bool + ) throws -> CBv2Request { + guard let media = managedMedia else { throw MiMoV26MultimodalError.incompatibleOwner } + return try engine.prepareNativeMedia(processor: media.processor, loadedOwner: resources) { + work in + if isCancelled() { throw MiMoV26MultimodalError.cancelled } + guard + !input.messages.contains(where: { message in + message.content.contains { + switch $0 { + case .audio, .audiovisual: true + default: false + } + } + }) + else { throw MiMoV26MultimodalError.missingAudioCodec } + let plan = try media.processor.plan(input) + guard !plan.spans.isEmpty else { throw MiMoV26MultimodalError.incompatiblePlan } + try engine.requireNativeMediaCanEverFit( + promptTokens: plan.promptTokens, + maximumOutputTokens: plan.maximumOutputTokens) + let bytes = try media.processor.managedVisualCommitmentBytes(plan) + let reservation = try authorize(plan, bytes) + // Installed before any pixel conversion/native work or later veto. + work.retain(reservation) + work.afterRetirement { try retire(reservation) } + let prepared = try media.processor.prepareManaged( + plan, + authorize: { actual in + try reservation.validate(plan: actual) + return reservation + }, isCancelled: isCancelled, work: work) + work.retain(prepared) + try work.validateAtBinding(prepared) + return try prepared.makeRequest(binding: media.binding, id: .init(0)) + } + } + + /// Call under the same serialized host owner before supported teardown or + /// mutation. Already prepared/queued media refuses its next handoff. This + /// does not replace draining an active engine before unloading weights. + public func invalidateMultimodalPreparation() { + resources.nativePagedLifetime.invalidate() + resources.mediaGeneration.invalidate() + resources.audioSidecar?.invalidate() + } + + @discardableResult + public override func update( + parameters: ModuleParameters, verify: VerifyUpdate, + path: [String] = [], modulePath: [String] = [] + ) throws -> Self { + resources.nativePrefixLifetime.invalidate() + invalidateMultimodalPreparation() + return try super.update( + parameters: parameters, verify: verify, path: path, modulePath: modulePath) + } + @discardableResult + public override func update( + modules: ModuleChildren, verify: VerifyUpdate, + path: [String] = [], modulePath: [String] = [] + ) throws -> Self { + resources.nativePrefixLifetime.invalidate() + invalidateMultimodalPreparation() + return try super.update( + modules: modules, verify: verify, path: path, modulePath: modulePath) + } + + /// Generic iterator cache quantization, context limits and policy integration + /// are not qualified by this factory slice. Reject through the standard + /// recoverable boundary before the iterator attempts a model step. + public func validateGenericGeneration() throws { + throw MiMoV26FactoryError.nativeCBv2Required + } + public func prepare(_ input: LMInput, cache: [KVCache], windowSize: Int?) throws + -> PrepareResult + { + guard input.image == nil, input.video == nil else { + throw MiMoV26FactoryError.unsupportedInput( + "loaded text entrypoint rejects prepared media") + } + try validateGenericGeneration() + throw MiMoV26FactoryError.nativeCBv2Required + } + public func newCache(parameters: GenerateParameters?) -> [KVCache] { target.newCache() } + + /// Direct native component diagnostic, with the target's real validation and + /// arithmetic. Serving uses makeCBv2Binding, not a fabricated AR implementation. + public func forwardText(inputIDs: MLXArray, cache: [KVCache]? = nil) throws -> MiMoV26TextOutput + { + try target.forward(inputIDs: inputIDs, cache: cache) + } + public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + do { return try forwardText(inputIDs: inputs, cache: cache).logits } catch { + preconditionFailure( + "MiMo native target contract bypassed: use throwing forwardText or native CBv2 (\(error))" + ) + } + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26MLXVLMPlan.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26MLXVLMPlan.swift new file mode 100644 index 0000000000..56baa4dc5e --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26MLXVLMPlan.swift @@ -0,0 +1,244 @@ +// Copyright © 2026 Eigen Labs. +// Metadata-only validation of the published MLX-VLM MiMo layout. No arrays, +// artifact rewrite, dequantization or synthetic conversion receipt is involved. +import Foundation +import MLXLLM + +enum MiMoV26MLXVLMPlan { + static func make( + configurationData: Data, indexData: Data, + descriptors: [String: MiMoV26ConvertedTensorDescriptor], + provenance: MiMoV26ConvertedProvenance + ) throws -> MiMoV26ConvertedLoadPlan { + let c = try JSONDecoder().decode(MiMoV26Configuration.self, from: configurationData) + let index = try JSONDecoder().decode(MiMoV26ConvertedIndex.self, from: indexData) + guard provenance.layout == .mlxVLM, !provenance.artifactID.isEmpty, + ["XiaomiMiMo/MiMo-V2.6-Flash-MOPD", "XiaomiMiMo/MiMo-V2.6-Flash-RL"].contains( + provenance.sourceRepository), + convertedHex(provenance.sourceRevision, count: 40), + convertedHex(provenance.conversionManifestSHA256, count: 64), + provenance.payloadVerificationReceiptSHA256.map({ convertedHex($0, count: 64) }) ?? true + else { + throw MiMoV26ConvertedLoadError.invalidProvenance("MLX-VLM artifact/source identity") + } + guard c.numHiddenLayers <= 48, c.hiddenSize <= 4096, c.intermediateSize <= 16384, + c.moeIntermediateSize <= 2048, c.routedExpertCount <= 256, c.vocabularySize <= 152576, + c.numNextnPredictLayers == 3, c.dtype == "bfloat16", !c.tieWordEmbeddings, + !c.attentionBias, c.attentionDropout == 0, + c.sharedExpertCount == nil || c.sharedExpertCount == 0, + let vision = c.vision, let audio = c.audio, + vision.depth <= 28, vision.hiddenSize <= 1280, vision.intermediateSize <= 4608, + c.quantization.nativeDefault?.mode == "affine", + c.quantization.nativeDefault?.bits == 4, c.quantization.nativeDefault?.groupSize == 64, + c.quantization.sourceMetadata == nil + else { + throw MiMoV26ConvertedLoadError.invalidConfiguration( + "MLX-VLM packed target/audio and floating vision/MTP geometry") + } + // Each trained parameter has one source name and one native name. Keep + // the source namespace in the filesystem plan for full hash/TOCTOU checks. + var expected: [String: (shape: [Int], dtype: MiMoV26ConvertedScalarType)] = [:] + var names: [String: String] = [:] + var canonicalNames = Set() + var groups = Dictionary( + uniqueKeysWithValues: MiMoV26ConvertedComponent.allCases.map { ($0, Set()) }) + var targetPolicies: [String: MiMoV26Quantization.Policy] = [:] + var audioPolicies: [String: MiMoV26Quantization.Policy] = [:] + var usedPolicies = Set() + var experts = Set() + func sourceName(_ key: String, _ component: MiMoV26ConvertedComponent) -> String { + switch component { + case .target: return "language_model." + key + case .vision: return "vision_tower." + key.dropFirst("visual.".count) + case .audioPatch: return key + case .mtp: return "language_model.model." + key + } + } + func add( + _ key: String, _ shape: [Int], _ dtype: MiMoV26ConvertedScalarType, + _ component: MiMoV26ConvertedComponent + ) throws { + let source = sourceName(key, component) + guard expected[source] == nil, canonicalNames.insert(key).inserted, + !shape.isEmpty, shape.allSatisfy({ $0 > 0 && $0 <= Int(Int32.max) }) + else { + throw MiMoV26ConvertedLoadError.invalidInventory( + "duplicate/invalid MLX-VLM parameter: " + key) + } + _ = try convertedProduct(shape + [dtype.bytes], source) + expected[source] = (shape, dtype) + names[source] = key + groups[component, default: []].insert(source) + } + func packed( + _ module: String, _ shape: [Int], _ component: MiMoV26ConvertedComponent, + expert: Bool = false + ) throws { + let source = sourceName(module, component) + guard let declared = c.quantization.nativeOverrides[source], + case .quantize(let policy) = declared, + policy.mode == (expert ? "mxfp4" : "affine"), policy.bits == (expert ? 4 : 8), + policy.groupSize == (expert ? 32 : 64), + let cols = shape.last, cols.isMultiple(of: policy.groupSize), + shape.count == (expert ? 3 : 2), usedPolicies.insert(source).inserted + else { + throw MiMoV26ConvertedLoadError.invalidQuantization( + "missing/incompatible explicit MLX-VLM policy: " + source) + } + let prefix = Array(shape.dropLast()) + try add(module + ".weight", prefix + [cols / (32 / policy.bits)], .uint32, component) + try add( + module + ".scales", prefix + [cols / policy.groupSize], expert ? .uint8 : .bfloat16, + component) + if !expert { + try add( + module + ".biases", prefix + [cols / policy.groupSize], .bfloat16, component) + } + if component == .target { + targetPolicies[module] = policy + } else if component == .audioPatch { + audioPolicies[module] = policy + } else { + throw MiMoV26ConvertedLoadError.invalidQuantization("unexpected packed component") + } + if expert { experts.insert(module) } + } + try packed("model.embed_tokens", [c.vocabularySize, c.hiddenSize], .target) + try add("model.norm.weight", [c.hiddenSize], .bfloat16, .target) + try packed("lm_head", [c.vocabularySize, c.hiddenSize], .target) + for layer in 0 ..< c.numHiddenLayers { + let p = "model.layers.\(layer)." + let g = try c.attentionGeometry(at: layer) + for norm in ["input_layernorm", "post_attention_layernorm"] { + try add(p + norm + ".weight", [c.hiddenSize], .bfloat16, .target) + } + for (name, width) in [ + ("q_proj", g.queryHeads * g.headDim), + ("k_proj", g.keyValueHeads * g.headDim), + ("v_proj", g.keyValueHeads * g.valueHeadDim), + ] { + try packed(p + "self_attn." + name, [width, c.hiddenSize], .target) + } + try packed( + p + "self_attn.o_proj", [c.hiddenSize, g.queryHeads * g.valueHeadDim], .target) + if g.hasSinks { + try add(p + "self_attn.attention_sink_bias", [g.queryHeads], .bfloat16, .target) + } + if c.moeLayerFrequency[layer] == 1 { + try add( + p + "mlp.gate.weight", [c.routedExpertCount, c.hiddenSize], + c.moeRouterDType == "bfloat16" ? .bfloat16 : .float32, .target) + try add( + p + "mlp.gate.e_score_correction_bias", [c.routedExpertCount], .float32, .target + ) + for name in ["gate_proj", "up_proj", "down_proj"] { + try packed( + p + "mlp.switch_mlp." + name, + [ + c.routedExpertCount, + name == "down_proj" ? c.hiddenSize : c.moeIntermediateSize, + name == "down_proj" ? c.moeIntermediateSize : c.hiddenSize, + ], .target, expert: true) + } + } else { + for name in ["gate_proj", "up_proj"] { + try packed(p + "mlp." + name, [c.intermediateSize, c.hiddenSize], .target) + } + try packed(p + "mlp.down_proj", [c.hiddenSize, c.intermediateSize], .target) + } + } + for (key, shape) in try MiMoV26VisionTower.expectedTensorShapes(configuration: vision) { + let stored = + key == "visual.patch_embed.proj.weight" + ? [vision.hiddenSize, try convertedProduct(Array(shape.dropFirst()), key)] : shape + try add(key, stored, .bfloat16, .vision) + } + for (key, shape) in try MiMoV26AudioPatchEncoder.expectedTensorShapes(configuration: audio) + { + if key.hasSuffix(".weight"), shape.count == 2 { + try packed(String(key.dropLast(".weight".count)), shape, .audioPatch) + } else { + try add(key, shape, .bfloat16, .audioPatch) + } + } + let g = c.slidingAttention + for depth in 0 ..< c.numNextnPredictLayers { + let p = "mtp.layers.\(depth)." + for norm in [ + "enorm", "hnorm", "input_layernorm", "pre_mlp_layernorm", "final_layernorm", + ] { + try add(p + norm + ".weight", [c.hiddenSize], .bfloat16, .mtp) + } + if g.hasSinks { + try add(p + "self_attn.attention_sink_bias", [g.queryHeads], .bfloat16, .mtp) + } + for (name, rows, cols) in [ + ("eh_proj", c.hiddenSize, 2 * c.hiddenSize), + ("self_attn.q_proj", g.queryHeads * g.headDim, c.hiddenSize), + ("self_attn.k_proj", g.keyValueHeads * g.headDim, c.hiddenSize), + ("self_attn.v_proj", g.keyValueHeads * g.valueHeadDim, c.hiddenSize), + ("self_attn.o_proj", c.hiddenSize, g.queryHeads * g.valueHeadDim), + ("mlp.gate_proj", c.intermediateSize, c.hiddenSize), + ("mlp.up_proj", c.intermediateSize, c.hiddenSize), + ("mlp.down_proj", c.hiddenSize, c.intermediateSize), + ] { try add(p + name + ".weight", [rows, cols], .bfloat16, .mtp) } + } + guard usedPolicies == Set(c.quantization.nativeOverrides.keys) else { + throw MiMoV26ConvertedLoadError.invalidQuantization( + "unmapped MLX-VLM policy; floating MTP/vision must not inherit root default") + } + for field in ["quantization", "quantization_config"] { + if case .object(let raw) = c.rawFields[field], + Set(raw.keys) != usedPolicies.union(["mode", "bits", "group_size"]) + { + throw MiMoV26ConvertedLoadError.invalidQuantization( + "unmapped native metadata: " + field) + } + } + guard Set(descriptors.keys) == Set(expected.keys), + Set(index.weightMap.keys) == Set(expected.keys) + else { + throw MiMoV26ConvertedLoadError.invalidInventory( + "missing/unmapped MLX-VLM root tensors") + } + var total = 0 + for (key, spec) in expected { + let actual = descriptors[key]! + let file = actual.file + guard actual.shape == spec.shape, actual.dtype == spec.dtype, + file == index.weightMap[key], !file.isEmpty, + file == (file as NSString).lastPathComponent, + !file.contains("\\"), file.hasSuffix(".safetensors"), file != ".safetensors" + else { + throw MiMoV26ConvertedLoadError.invalidInventory(key) + } + let sum = total.addingReportingOverflow( + try convertedProduct(actual.shape + [actual.dtype.bytes], key)) + guard !sum.overflow else { + throw MiMoV26ConvertedLoadError.invalidInventory("MLX-VLM byte overflow") + } + total = sum.partialValue + } + guard total == index.metadata.totalSize else { + throw MiMoV26ConvertedLoadError.invalidInventory("index tensor byte total") + } + if let embedded = c.embeddedMTP { + guard groups[.mtp]!.allSatisfy({ descriptors[$0]!.file == embedded.file }) else { + throw MiMoV26ConvertedLoadError.invalidInventory("embedded MTP file declaration") + } + } + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return .init( + configuration: c, descriptors: descriptors, components: groups, + targetExpertModulePaths: experts, + parameterNames: names, targetQuantizationPolicies: targetPolicies, + audioQuantizationPolicies: audioPolicies, floatingMTP: true, + configSHA256: convertedHash(configurationData), indexSHA256: convertedHash(indexData), + descriptorSHA256: convertedHash(try encoder.encode(descriptors)), + rootFiles: Set(index.weightMap.values), + tensorBytes: total, provenance: provenance, + externalRequiredComponents: ["audio_tokenizer"], + floatingType: .bfloat16) + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26ManagedAudioCommitment.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26ManagedAudioCommitment.swift new file mode 100644 index 0000000000..b947b03707 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26ManagedAudioCommitment.swift @@ -0,0 +1,78 @@ +// Copyright © 2026 Eigen Labs. Decoded-PCM work commitment, not measured residency. + +import Foundation +import MLXLLM + +/// Additional audio work only. The issued audio profile must add the existing +/// decoded/visual/features commitment, preserve the separate codec load charge, +/// and leave target KV and existing OS/activation reserves unchanged. +public enum MiMoV26ManagedAudioCommitment { + public static func additionalBytes( + input: MiMoV26AudioInputPlan, + patchConfiguration c: MiMoV26AudioConfiguration, + limits: MiMoV26AudioPatchLimits + ) throws -> Int { + guard let clips = input.pcmDescriptors, !clips.isEmpty, + input.codeFrameCounts.count == clips.count, + c.channels == input.configuration.quantizers, c.groupSize == 4, + c.hiddenSize > 0, c.hiddenSize <= 1024, c.layers > 0, c.layers <= 6, + c.queryHeads > 0, c.queryHeads <= 16, c.outputHiddenSize > 0, + c.outputHiddenSize <= 4096, clips.count <= limits.maximumClips, + input.limits.rvqTileFrames > 0 + else { throw MiMoV26AudioSidecarError.invalidBinding } + func add(_ a: Int, _ b: Int) throws -> Int { + try MiMoV26AudioChecked.add(a, b, "managed audio commitment") + } + func mul(_ values: Int...) throws -> Int { + try MiMoV26AudioChecked.product(values, "managed audio commitment") + } + guard case .number(let rawIntermediate) = c.rawFields["input_local_intermediate_size"] + else { + throw MiMoV26AudioSidecarError.invalidConfiguration + } + let value = NSDecimalNumber(decimal: rawIntermediate).int64Value + guard rawIntermediate == Decimal(value), let intermediate = Int(exactly: value), + intermediate > 0, intermediate <= 4096 + else { throw MiMoV26AudioSidecarError.invalidConfiguration } + let frames = try input.codeFrameCounts.reduce(0, add) + let patches = try input.codeFrameCounts.reduce(0) { + try add($0, MiMoV26AudioChecked.ceilDivide($1, c.groupSize)) + } + guard input.codeFrameCounts.allSatisfy({ $0 > 0 }), frames <= limits.maximumFrames, + patches == input.totalPatches, patches <= limits.maximumPatches + else { + throw MiMoV26AudioSidecarError.invalidBinding + } + // Same shape equations as AudioPatchPlan, without inventing code IDs. + let paddedFrames = try mul(patches, c.groupSize) + let codes = try mul(paddedFrames, c.channels) + let layer = try add(mul(5, c.hiddenSize), mul(3, intermediate)) + let hidden = try mul(paddedFrames, add(mul(2, c.hiddenSize), mul(c.layers, layer))) + let scores = try mul(patches, c.queryHeads, c.groupSize, c.groupSize, c.layers) + let projectionHidden = try mul(c.groupSize, c.hiddenSize, 4) + let projection = try mul(patches, add(projectionHidden, c.outputHiddenSize)) + let patchWork = try add(add(codes, hidden), add(scores, projection)) + guard patchWork <= limits.maximumWorkingElements else { + throw MiMoV26AudioSidecarError.insufficientReservation + } + + // Price all possible RVQ tiles, including retained lazy graph nodes; + // do not reinterpret the component's per-tile bound as a physical peak. + let tiles = try input.codeFrameCounts.reduce(0) { + try add($0, MiMoV26AudioChecked.ceilDivide($1, input.limits.rvqTileFrames)) + } + let tableRows = try input.configuration.codebookSizes.reduce(0, add) + let tableElements = try mul(tableRows, input.configuration.hiddenSize) + var bytes = try mul(input.workingElementUpperBound, max(1, tiles), 16) + bytes = try add(bytes, mul(tableElements, max(1, tiles), 16)) + bytes = try add(bytes, mul(patchWork, 16)) + bytes = try add(bytes, mul(try add(mul(frames, c.channels), codes), 8)) + // Conservative node/page slack for frontend, per-segment transformer, + // per-tile RVQ and vectorized patch graph. Qualification must measure it. + var nodes = try mul(clips.count, 1024) + nodes = try add(nodes, mul(input.segments.count, input.configuration.layers, 256)) + nodes = try add(nodes, mul(tiles, input.configuration.quantizers, 128)) + nodes = try add(nodes, add(mul(c.layers, 256), 512)) + return try add(bytes, mul(nodes, 16_384)) + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26MediaGeometry.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26MediaGeometry.swift new file mode 100644 index 0000000000..36193dd29b --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26MediaGeometry.swift @@ -0,0 +1,258 @@ +// Copyright © 2026 Eigen Labs. +// Native scalar contracts derived from SGLang (Apache-2.0), commit +// 67bb6a58d0dad4a39af80fa1b2bf86f0de0cb99b, multimodal/processors/mimo_v2.py. +// No pixel processing, media decoding, tokenization or model execution. +import Foundation + +public enum MiMoV26MediaGeometry { + public enum Failure: Error, Equatable, Sendable { + case invalidSettings(String) + case invalidGeometry(String) + case overflow(String) + case unusableResize + } + + /// Explicit effective settings, after native model/request precedence. + /// Sampling fps/min_frames/max_frames are a separate decoder contract. + public struct Settings: Codable, Equatable, Sendable { + public let patchSize, mergeSize, temporalPatchSize, temporalCompressionRatio: Int + public let imageMinPixels, imageMaxPixels: Int + public let videoMinPixels, videoMaxPixels, videoTotalMaxPixels: Int + + public init( + patchSize: Int, mergeSize: Int, temporalPatchSize: Int, + temporalCompressionRatio: Int, imageMinPixels: Int, imageMaxPixels: Int, + videoMinPixels: Int, videoMaxPixels: Int, videoTotalMaxPixels: Int + ) throws { + self.patchSize = patchSize + self.mergeSize = mergeSize + self.temporalPatchSize = temporalPatchSize + self.temporalCompressionRatio = temporalCompressionRatio + self.imageMinPixels = imageMinPixels + self.imageMaxPixels = imageMaxPixels + self.videoMinPixels = videoMinPixels + self.videoMaxPixels = videoMaxPixels + self.videoTotalMaxPixels = videoTotalMaxPixels + try validate() + } + + fileprivate func validate() throws { + guard patchSize > 0, mergeSize > 0, temporalPatchSize > 0, + temporalCompressionRatio > 0, imageMinPixels > 0, + imageMaxPixels >= imageMinPixels, videoMinPixels > 0, + videoMaxPixels >= videoMinPixels, videoTotalMaxPixels > 0 + else { + throw Failure.invalidSettings( + "positive dimensions and ordered pixel bounds required") + } + _ = try dimension(product([patchSize, mergeSize], "spatial factor"), "spatial factor") + _ = try dimension( + product([temporalPatchSize, temporalCompressionRatio], "temporal factor"), + "temporal factor") + _ = try dimension( + product([3, temporalPatchSize, patchSize, patchSize], "patch vector"), + "patch vector") + for limit in [ + imageMinPixels, imageMaxPixels, videoMinPixels, videoMaxPixels, videoTotalMaxPixels, + ] { + try exactDoubleInteger(limit, "pixel budget") + } + } + } + + /// Counts describe actual native rounding/padding, not admission success. + /// Video total_max_pixels is a soft resize budget: its minimum floor and + /// last-frame duplication can exceed it. Report that; never silently clamp. + public struct Plan: Codable, Equatable, Sendable { + public let height, width: Int + public let sampledFrames, segmentFrames, alignedFrames, duplicatedFrames: Int + public let gridT, gridH, gridW: Int + public let patchCount, patchVectorSize, patchElementCount: Int + public let mediaTokens, timestampCount, fixedWrapperTokens: Int + public let promptTokensExcludingTimestamps: Int + public let resizedPixelsPerFrame, alignedPixels, aggregateBudgetPixels: Int + public let effectiveMaxPixelsPerFrame: Int + public let exceedsPerFrameMaximum, belowPerFrameMinimum, exceedsAggregateBudget: Bool + } + + public static func image(height: Int, width: Int, settings: Settings) throws -> Plan { + try settings.validate() + let size = try resize( + height: height, width: width, + factor: product([settings.patchSize, settings.mergeSize], "spatial factor"), + minimum: settings.imageMinPixels, maximum: settings.imageMaxPixels) + // The native image flattener repeats a still image temporalPatchSize + // times; gridT stays one and image tokens have no temporal compression. + return try plan( + size: size, sampled: 1, segment: 1, + aligned: settings.temporalPatchSize, settings: settings, + minimum: settings.imageMinPixels, maximum: settings.imageMaxPixels, video: false) + } + + /// Dimensions describe decoded sampled frames. `sampledFrames` is the full + /// sampled clip count used for the native pixel budget, even when a smaller + /// temporal segment is selected. Frame selection/timestamps are upstream. + /// `sampledFrameLimit` is an optional explicit caller admission limit; it is + /// deliberately not inferred from native sampling min_frames/max_frames. + public static func video( + height: Int, width: Int, sampledFrames: Int, + segmentFrames: Int? = nil, sampledFrameLimit: Int? = nil, + settings: Settings + ) throws -> Plan { + try settings.validate() + _ = try dimension(sampledFrames, "sampled frames") + let segment = segmentFrames ?? sampledFrames + guard segment > 0, segment <= sampledFrames else { + throw Failure.invalidGeometry("segment frames must be within the sampled clip") + } + if let limit = sampledFrameLimit { + guard limit > 0, sampledFrames <= limit else { + throw Failure.invalidGeometry("explicit sampled-frame admission limit") + } + } + let temporal = try product( + [settings.temporalPatchSize, settings.temporalCompressionRatio], "temporal factor") + let numerator = try product( + [settings.videoTotalMaxPixels, temporal], "video budget numerator") + let perFrame = max( + settings.videoMinPixels, + min(numerator / sampledFrames, settings.videoMaxPixels)) + let groups = segment / temporal + (segment % temporal == 0 ? 0 : 1) + let aligned = try dimension( + product([groups, temporal], "aligned frames"), "aligned frames") + let size = try resize( + height: height, width: width, + factor: product([settings.patchSize, settings.mergeSize], "spatial factor"), + minimum: settings.videoMinPixels, maximum: perFrame) + return try plan( + size: size, sampled: sampledFrames, segment: segment, + aligned: aligned, settings: settings, + minimum: settings.videoMinPixels, maximum: perFrame, video: true) + } + + private static func resize( + height: Int, width: Int, factor: Int, + minimum: Int, maximum: Int + ) throws -> (Int, Int) { + _ = try dimension(height, "input height") + _ = try dimension(width, "input width") + try exactDoubleInteger(product([height, width], "input pixels"), "input pixels") + var h = height + var w = width + if min(h, w) < factor { + // Keep the reference's branch ordering: tiny axes are scaled first, + // so its >200 aspect refusal is NOT applied in this branch. + let scale = Double(factor) / Double(min(h, w)) + h = try roundedInteger(Double(h) * scale, .toNearestOrEven) + w = try roundedInteger(Double(w) * scale, .toNearestOrEven) + } else if Double(max(h, w)) / Double(min(h, w)) > 200 { + throw Failure.invalidGeometry("native aspect ratio exceeds 200") + } + let pixels = try product([h, w], "scaled input pixels") + try exactDoubleInteger(pixels, "scaled input pixels") + var targetH = try multiple(Double(h) / Double(factor), factor, .toNearestOrEven) + var targetW = try multiple(Double(w) / Double(factor), factor, .toNearestOrEven) + let roundedPixels = try product([targetH, targetW], "rounded pixels") + if roundedPixels > maximum { + let beta = sqrt(Double(pixels) / Double(maximum)) + targetH = try multiple(Double(h) / beta / Double(factor), factor, .down) + targetW = try multiple(Double(w) / beta / Double(factor), factor, .down) + } else if roundedPixels < minimum { + let beta = sqrt(Double(minimum) / Double(pixels)) + targetH = try multiple(Double(h) * beta / Double(factor), factor, .up) + targetW = try multiple(Double(w) * beta / Double(factor), factor, .up) + } + // The reference can produce a zero axis for extreme/budget-limited + // geometry. Refuse before allocation; do not invent a one-patch clamp. + guard targetH > 0, targetW > 0 else { throw Failure.unusableResize } + _ = try dimension(targetH, "output height") + _ = try dimension(targetW, "output width") + return (targetH, targetW) + } + + private static func plan( + size: (Int, Int), sampled: Int, segment: Int, aligned: Int, + settings: Settings, minimum: Int, maximum: Int, video: Bool + ) throws -> Plan { + let (height, width) = size + let gridT = aligned / settings.temporalPatchSize + let gridH = height / settings.patchSize + let gridW = width / settings.patchSize + let count = try dimension(product([gridT, gridH, gridW], "patch count"), "patch count") + let vector = try dimension( + product( + [ + 3, settings.temporalPatchSize, settings.patchSize, + settings.patchSize, + ], "patch vector"), "patch vector") + let elements = try product([count, vector], "patch elements") + let spatialMerge = try product([settings.mergeSize, settings.mergeSize], "merge area") + let compression = video ? settings.temporalCompressionRatio : 1 + let tokens = count / spatialMerge / compression + let stamps = video ? gridT / compression : 0 + let wrappers = + video ? try sum(product([2, stamps], "video wrappers"), 2, "video wrappers") : 2 + let totalTokens = try sum(tokens, wrappers, "prompt tokens") + let pixels = try product([height, width], "resized pixels") + let alignedPixels = try product([pixels, aligned], "aligned pixels") + let budgetPixels = alignedPixels / settings.temporalPatchSize / compression + return Plan( + height: height, width: width, sampledFrames: sampled, segmentFrames: segment, + alignedFrames: aligned, duplicatedFrames: aligned - segment, + gridT: gridT, gridH: gridH, gridW: gridW, + patchCount: count, patchVectorSize: vector, patchElementCount: elements, + mediaTokens: tokens, timestampCount: stamps, fixedWrapperTokens: wrappers, + promptTokensExcludingTimestamps: totalTokens, + resizedPixelsPerFrame: pixels, alignedPixels: alignedPixels, + aggregateBudgetPixels: budgetPixels, + effectiveMaxPixelsPerFrame: maximum, exceedsPerFrameMaximum: pixels > maximum, + belowPerFrameMinimum: pixels < minimum, + exceedsAggregateBudget: video && budgetPixels > settings.videoTotalMaxPixels) + } + + private static func dimension(_ value: Int, _ field: String) throws -> Int { + guard value > 0 else { throw Failure.invalidGeometry(field) } + guard value <= Int(Int32.max) else { throw Failure.overflow(field) } + return value + } + + private static func exactDoubleInteger(_ value: Int, _ field: String) throws { + guard value > 0, value <= 9_007_199_254_740_991 else { throw Failure.overflow(field) } + } + + private static func product(_ values: [Int], _ field: String) throws -> Int { + var result = 1 + for value in values { + guard value > 0 else { throw Failure.invalidGeometry(field) } + let next = result.multipliedReportingOverflow(by: value) + guard !next.overflow else { throw Failure.overflow(field) } + result = next.partialValue + } + return result + } + + private static func sum(_ lhs: Int, _ rhs: Int, _ field: String) throws -> Int { + let result = lhs.addingReportingOverflow(rhs) + guard !result.overflow else { throw Failure.overflow(field) } + return result.partialValue + } + + private static func roundedInteger(_ value: Double, _ rule: FloatingPointRoundingRule) throws + -> Int + { + let result = value.rounded(rule) + guard result.isFinite, result >= 0, result <= 9_007_199_254_740_991, + let integer = Int(exactly: result) + else { throw Failure.overflow("resize rounding") } + return integer + } + + private static func multiple( + _ value: Double, _ factor: Int, + _ rule: FloatingPointRoundingRule + ) throws -> Int { + let rounded = try roundedInteger(value, rule) + if rounded == 0 { return 0 } + return try product([rounded, factor], "rounded dimension") + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26ModelFactory.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26ModelFactory.swift new file mode 100644 index 0000000000..23c6c42ec0 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26ModelFactory.swift @@ -0,0 +1,442 @@ +// Copyright © 2026 Eigen Labs. +import CryptoKit +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +public enum MiMoV26FactoryError: Error, Equatable, LocalizedError, Sendable { + case invalidMetadata(String) + case incompatiblePreparation + case changedTokenizerAssets + case unsupportedInput(String) + case nativeCBv2Required + + public var errorDescription: String? { + switch self { + case .invalidMetadata(let reason): "Native MiMo factory metadata: \(reason)." + case .incompatiblePreparation: + "Tokenizer preparation does not belong to this exact native MiMo load session." + case .changedTokenizerAssets: + "Native MiMo tokenizer/template assets changed after preparation. Prepare a fresh load session." + case .unsupportedInput(let reason): "Native MiMo text input: \(reason)." + case .nativeCBv2Required: + "MiMo V2.6 generation requires MiMoV26LoadedModel.makeCBv2Binding() and the native CBv2 engine; this entrypoint does not enable the generic TokenIterator path." + } + } +} + +/// Explicit two-stage factory. It is deliberately absent from public registries +/// and has no downloader/directory-only overload that could bypass admission. +public enum MiMoV26ModelFactory { + /// Only factory-created metadata/tokenizer state crosses the async boundary. + /// No model, native reservation or non-Sendable owner is sent between tasks. + public struct Prepared: Sendable { + public let request: MiMoV26SerialLoadRequest + public let configuration: ResolvedModelConfiguration + public let nativeConfiguration: MiMoV26Configuration + public let templateSHA256: String + public let stopTokenIDs: Set + public let processor: MiMoV26TextProcessor + let tokenizer: any Tokenizer + let nativeEOS: Set + let metadata: Metadata + } + + struct Asset: Equatable, Sendable { + let name: String + let object: MiMoV26FilesystemObjectState + } + struct Metadata: Equatable, Sendable { + let root: URL + let assets: [Asset] + let configSHA256: String + let tokenizerConfigSHA256: String + let template: String + let templateSource: String + let generationSHA256: String? + let nativeEOS: Set + } + private static let assetNames = [ + "config.json", "generation_config.json", "chat_template.jinja", + "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "added_tokens.json", + "tokenizer.model", "merges.txt", "vocab.json", "vocab.txt", + ] + private static let maximumSmallMetadataBytes = 8 << 20 + + public static func prepare( + request: MiMoV26SerialLoadRequest, + configuration: ResolvedModelConfiguration, + tokenizerLoader: any TokenizerLoader + ) async throws -> Prepared { + try Task.checkCancellation() + let metadata = try readMetadata(request: request, configuration: configuration) + let native = try JSONDecoder().decode( + MiMoV26Configuration.self, + from: readSmall(metadata.root.appendingPathComponent("config.json"))) + guard configuration.eosTokenIds.isEmpty || configuration.eosTokenIds == metadata.nativeEOS + else { + throw MiMoV26FactoryError.invalidMetadata( + "resolved EOS IDs conflict with checkpoint EOS; use extraEOSTokens for explicit additions" + ) + } + // The protocol is explicitly local. No Downloader, alternate root, + // fallback architecture or tokenizer substitution is selected here. + let tokenizer = try await tokenizerLoader.load(from: metadata.root) + try Task.checkCancellation() + guard try readMetadata(request: request, configuration: configuration) == metadata else { + throw MiMoV26FactoryError.changedTokenizerAssets + } + let processor = try MiMoV26TextProcessor( + tokenizer: tokenizer, chatTemplate: metadata.template, + vocabularySize: native.vocabularySize, + maximumSequenceLength: native.maxPositionEmbeddings) + var stopIDs = metadata.nativeEOS + if let spelling = tokenizer.eosToken { + guard let eos = tokenizer.convertTokenToId(spelling) else { + throw MiMoV26FactoryError.invalidMetadata("tokenizer EOS spelling has no token ID") + } + stopIDs.insert(eos) + } + for spelling in configuration.extraEOSTokens { + guard let id = tokenizer.convertTokenToId(spelling) else { + throw MiMoV26FactoryError.invalidMetadata("unresolved explicit EOS token") + } + stopIDs.insert(id) + } + guard stopIDs.allSatisfy({ $0 >= 0 && $0 < native.vocabularySize }) else { + throw MiMoV26FactoryError.invalidMetadata("EOS outside the native vocabulary") + } + // Force template/tokenizer failures before consuming the native session. + // This verifies delegation/control response, not real tokenizer parity. + let unset = try processor.renderTokens(input: UserInput(prompt: "")) + let enabled = try processor.renderTokens( + input: UserInput(prompt: "", additionalContext: ["enable_thinking": true])) + let disabled = try processor.renderTokens( + input: UserInput(prompt: "", additionalContext: ["enable_thinking": false])) + guard unset == enabled, disabled != enabled else { + throw MiMoV26FactoryError.invalidMetadata( + "tokenizer/template does not preserve MiMo's default-on Boolean thinking contract") + } + try Task.checkCancellation() + guard try readMetadata(request: request, configuration: configuration) == metadata else { + throw MiMoV26FactoryError.changedTokenizerAssets + } + return .init( + request: request, configuration: configuration, nativeConfiguration: native, + templateSHA256: hash(Data(metadata.template.utf8)), stopTokenIDs: stopIDs, + processor: processor, tokenizer: tokenizer, nativeEOS: metadata.nativeEOS, + metadata: metadata) + } + + /// Synchronous actor-local construction. Retain work before calling and + /// keep it until process restart if any captured stream fails completion. + public static func load( + session: MiMoV26SerialLoadSession, + reservation: any MiMoV26SerialLoadReservation, + prepared: Prepared, retaining work: NativeConstructionScope, + isCancelled: () -> Bool = { false }, + progress: (MiMoV26SerialLoadProgress) throws -> Void = { _ in } + ) throws -> ModelContext { + try work.withPhase(.modelFactory) { + try work.retainOwner(reservation) + guard prepared.request == session.request, reservation.request == session.request else { + throw MiMoV26FactoryError.incompatiblePreparation + } + guard reservation.reservedLoadBytes >= session.request.requiredLoadBytes else { + throw MiMoV26SerialLoadError.insufficientReservation + } + guard !Task.isCancelled, !isCancelled() else { throw MiMoV26SerialLoadError.cancelled } + guard + try readMetadata(request: session.request, configuration: prepared.configuration) + == prepared.metadata + else { + throw MiMoV26FactoryError.changedTokenizerAssets + } + try work.capture(StreamOrDevice.default.stream) + let loaded = try session.load( + reservation: reservation, retaining: work, + isCancelled: { Task.isCancelled || isCancelled() }, progress: progress) + // The outer scope still owns the exact four-component bundle here. + try work.checkpoint("factory.beforePublication") + guard !Task.isCancelled else { throw MiMoV26SerialLoadError.cancelled } + guard + try readMetadata(request: session.request, configuration: prepared.configuration) + == prepared.metadata + else { + throw MiMoV26FactoryError.changedTokenizerAssets + } + let customCancelled = isCancelled() + guard !Task.isCancelled, !customCancelled else { + throw MiMoV26SerialLoadError.cancelled + } + let model = MiMoV26LoadedModel(loaded: loaded, prepared: prepared) + try work.retainOwner(model) + let config = ModelConfiguration( + directory: prepared.metadata.root, + defaultPrompt: prepared.configuration.defaultPrompt, + extraEOSTokens: prepared.configuration.extraEOSTokens, + eosTokenIds: prepared.nativeEOS, + toolCallFormat: prepared.configuration.toolCallFormat + ?? ToolCallFormat.infer(from: "mimo_v2")) + return ModelContext( + configuration: config, model: model, + processor: prepared.processor, tokenizer: prepared.tokenizer) + } + } + + /// The host preinstalls work in its strong transaction before this await. + /// The separately shared reservation must be genuinely synchronized. + public static func loadContainer( + session: consuming MiMoV26SerialLoadSession, + reservation: any MiMoV26SerialLoadReservation & Sendable, + prepared: Prepared, retaining work: NativeConstructionWork, + isCancelled: @escaping @Sendable () -> Bool = { false }, + progress: @escaping @Sendable (MiMoV26SerialLoadProgress) throws -> Void = { _ in } + ) async throws -> ModelContainer { + let session = SendableBox(session) + return try await work.constructContainer { scope in + ModelContainer( + context: try load( + session: session.consume(), reservation: reservation, + prepared: prepared, retaining: scope, isCancelled: isCancelled, + progress: progress)) + } + } + + /// Construction only, before an active engine exists. The fixed work -> + /// container lock order serializes the local model/scope across the await. + /// Return existing Sendable handles/metadata, never a raw model or binding. + public static func withNativeConstruction( + container: ModelContainer, retaining work: NativeConstructionWork, + _ body: @escaping @Sendable (MiMoV26LoadedModel, NativeConstructionScope) throws -> Result + ) async throws -> Result { + try await work.withContainer(container) { context, scope in + guard let model = context.model as? MiMoV26LoadedModel else { + throw MiMoV26FactoryError.incompatiblePreparation + } + try scope.authorizeImmutableLoadedOwner(model.resources) + return try body(model, scope) + } + } + + private static func readMetadata( + request: MiMoV26SerialLoadRequest, + configuration: ResolvedModelConfiguration + ) throws -> Metadata { + let root = configuration.modelDirectory.resolvingSymlinksInPath().standardizedFileURL + let tokenizerRoot = configuration.tokenizerDirectory.resolvingSymlinksInPath() + .standardizedFileURL + guard root.isFileURL, tokenizerRoot == root, root.path == request.binding.canonicalRoot + else { + throw MiMoV26FactoryError.invalidMetadata( + "model and tokenizer must use the exact bound local checkpoint root") + } + let assets = try captureAssets(root) + guard assets.contains(where: { $0.name == "tokenizer.json" }), + assets.contains(where: { $0.name == "tokenizer_config.json" }) + else { + throw MiMoV26FactoryError.invalidMetadata( + "native checkpoint tokenizer files are missing") + } + let data = try readSmall(root.appendingPathComponent("config.json")) + guard hash(data) == request.binding.configSHA256 else { + throw MiMoV26FactoryError.incompatiblePreparation + } + let config = try JSONDecoder().decode(MiMoV26Configuration.self, from: data) + let tokenizerData = try readSmall(root.appendingPathComponent("tokenizer_config.json")) + guard + let tokenizerConfig = try JSONSerialization.jsonObject(with: tokenizerData) + as? [String: Any] + else { + throw MiMoV26FactoryError.invalidMetadata("tokenizer_config.json requires an object") + } + let template: String + let source: String + if assets.contains(where: { $0.name == "chat_template.jinja" }) { + guard + let text = String( + data: try readSmall(root.appendingPathComponent("chat_template.jinja")), + encoding: .utf8) + else { + throw MiMoV26FactoryError.invalidMetadata("template is not UTF-8") + } + template = text + source = "chat_template.jinja" + } else if let text = tokenizerConfig["chat_template"] as? String { + template = text + source = "tokenizer_config.json:chat_template" + } else { + throw MiMoV26FactoryError.invalidMetadata( + "checkpoint has no unambiguous native chat template") + } + guard !template.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw MiMoV26FactoryError.invalidMetadata("checkpoint chat template is empty") + } + var eos = config.eosTokenIDs + var generationHash: String? + if assets.contains(where: { $0.name == "generation_config.json" }) { + let generation = try readSmall(root.appendingPathComponent("generation_config.json")) + generationHash = hash(generation) + if let explicit = try JSONDecoder().decode(GenerationConfigFile.self, from: generation) + .eosTokenIds + { + eos = Set(explicit.values) + } + } + guard eos.allSatisfy({ $0 >= 0 && $0 < config.vocabularySize }) else { + throw MiMoV26FactoryError.invalidMetadata("checkpoint EOS outside native vocabulary") + } + guard try captureAssets(root) == assets else { + throw MiMoV26FactoryError.changedTokenizerAssets + } + return .init( + root: root, assets: assets, configSHA256: hash(data), + tokenizerConfigSHA256: hash(tokenizerData), template: template, + templateSource: source, generationSHA256: generationHash, nativeEOS: eos) + } + + private static func captureAssets(_ root: URL) throws -> [Asset] { + try assetNames.compactMap { name in + let url = root.appendingPathComponent(name) + guard let object = try mimoFactoryCurrentObject(url, allowMissing: true) else { + return nil + } + return .init(name: name, object: object) + } + } + private static func readSmall(_ url: URL) throws -> Data { + try MiMoV26FactoryMetadataFile(url).read(maximumBytes: maximumSmallMetadataBytes) + } + private static func hash(_ data: Data) -> String { + SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + } +} + +// The existing filesystem gate's stat helpers are private. Reuse its public +// object-state representation with the same regular-file/ns-time semantics. +private func mimoFactoryObject(_ value: stat, name: String) throws -> MiMoV26FilesystemObjectState { + guard mode_t(value.st_mode) & mode_t(S_IFMT) == mode_t(S_IFREG), + let bytes = Int(exactly: value.st_size), bytes >= 0 + else { + throw MiMoV26FactoryError.invalidMetadata("non-regular tokenizer asset: \(name)") + } + #if canImport(Darwin) + let modified = value.st_mtimespec + let changed = value.st_ctimespec + #else + let modified = value.st_mtim + let changed = value.st_ctim + #endif + return .init( + device: String(value.st_dev), inode: String(value.st_ino), bytes: bytes, + modifiedSeconds: Int64(modified.tv_sec), modifiedNanoseconds: Int64(modified.tv_nsec), + changedSeconds: Int64(changed.tv_sec), changedNanoseconds: Int64(changed.tv_nsec)) +} + +private func mimoFactoryCurrentObject(_ url: URL, allowMissing: Bool = false) throws + -> MiMoV26FilesystemObjectState? +{ + guard url.isFileURL else { + throw MiMoV26FactoryError.invalidMetadata("tokenizer asset is not local") + } + var value = stat() + if lstat(url.path, &value) != 0 { + if allowMissing && errno == ENOENT { return nil } + throw MiMoV26FactoryError.invalidMetadata( + "unreadable tokenizer asset: \(url.lastPathComponent)") + } + guard url.resolvingSymlinksInPath().standardizedFileURL == url else { + throw MiMoV26FactoryError.invalidMetadata( + "unbound tokenizer asset: \(url.lastPathComponent)") + } + return try mimoFactoryObject(value, name: url.lastPathComponent) +} + +/// Internal bounded-reader seam. The only injection is a per-call test action +/// after validation and before the first bounded read; no global mutable hook. +final class MiMoV26FactoryMetadataFile { + private let url: URL + private let handle: FileHandle + let object: MiMoV26FilesystemObjectState + private(set) var bytesRead = 0 + private(set) var largestReadRequest = 0 + private var consumed = false + + init(_ url: URL) throws { + self.url = url + guard let before = try mimoFactoryCurrentObject(url) else { + throw MiMoV26FactoryError.changedTokenizerAssets + } + let descriptor = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) + guard descriptor >= 0 else { + throw MiMoV26FactoryError.invalidMetadata("cannot open tokenizer metadata") + } + do { + var value = stat() + guard fstat(descriptor, &value) == 0, + try mimoFactoryObject(value, name: url.lastPathComponent) == before, + try mimoFactoryCurrentObject(url) == before + else { + throw MiMoV26FactoryError.changedTokenizerAssets + } + object = before + handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true) + } catch { + close(descriptor) + throw error + } + } + + private func validate() throws { + var value = stat() + guard fstat(handle.fileDescriptor, &value) == 0, + try mimoFactoryObject(value, name: url.lastPathComponent) == object, + try mimoFactoryCurrentObject(url) == object + else { + throw MiMoV26FactoryError.changedTokenizerAssets + } + } + + func read(maximumBytes: Int, beforeFirstRead: () throws -> Void = {}) throws -> Data { + guard !consumed else { + throw MiMoV26FactoryError.invalidMetadata("metadata reader was reused") + } + consumed = true + guard maximumBytes >= 0, maximumBytes < Int.max, object.bytes <= maximumBytes else { + throw MiMoV26FactoryError.invalidMetadata( + "metadata exceeds bounded size or reader was reused") + } + var data = Data() + data.reserveCapacity(object.bytes) + var first = true + while data.count <= maximumBytes { + try validate() + if first { + first = false + try beforeFirstRead() + } + let requested = min(65_536, maximumBytes + 1 - data.count) + largestReadRequest = max(largestReadRequest, requested) + let chunk = try handle.read(upToCount: requested) ?? Data() + bytesRead += chunk.count + try validate() + guard chunk.count <= maximumBytes - data.count else { + throw MiMoV26FactoryError.invalidMetadata("metadata exceeds bounded size") + } + if chunk.isEmpty { break } + data.append(chunk) + } + try validate() + guard data.count == object.bytes else { + throw MiMoV26FactoryError.changedTokenizerAssets + } + return data + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26MultimodalInput.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26MultimodalInput.swift new file mode 100644 index 0000000000..460d6964b1 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26MultimodalInput.swift @@ -0,0 +1,743 @@ +// Copyright © 2026 Eigen Labs. +// Decoded-input contract; SGLang67bb6a58 native ordering, not an encoded-media API. +import CryptoKit +import Foundation +import Jinja +import MLXLLM +import MLXLMCommon + +public enum MiMoV26MultimodalError: Error, Equatable, Sendable { + case invalidInput(String) + case unsupportedProfile(String) + case limit(String) + case missingAudioCodec, incompatibleOwner, invalidatedOwner, incompatiblePlan + case cancelled, invalidFeatures, reservationRejected, drainFailed +} + +/// Data-only projection of ProviderCoreFoundation.PromptRenderDate. No caller +/// closure is stored or admitted. The provider passes the SAME resolved day +/// used by its ordinary prompt pipeline; the actual renderer stays Jinja. +public struct MiMoV26MediaRequestClock: Sendable, Equatable { + public let value: String + public init(utcGregorianDay value: String) throws { + let bytes = Array(value.utf8) + guard bytes.count == 10, bytes[4] == 45, bytes[7] == 45, + bytes.enumerated().allSatisfy({ index, byte in + index == 4 || index == 7 || (48 ... 57).contains(byte) + }) + else { throw MiMoV26MultimodalError.invalidInput("invalid request clock snapshot") } + let year = Int(value.prefix(4))! + let month = Int(String(value.dropFirst(5).prefix(2)))! + let day = Int(value.suffix(2))! + guard year > 0, (1 ... 12).contains(month) else { + throw MiMoV26MultimodalError.invalidInput("invalid request clock snapshot") + } + let leap = year.isMultiple(of: 4) && (!year.isMultiple(of: 100) || year.isMultiple(of: 400)) + let days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + guard (1 ... days[month - 1]).contains(day) else { + throw MiMoV26MultimodalError.invalidInput("invalid request clock snapshot") + } + self.value = value + } + // Mirrors the existing PromptRenderDate.function arity, kwargs and + // fallback exactly. Different ambient fallback clocks are NOT byte-parity + // evidence; only the supported literal day call is deterministic. + var templateValue: Jinja.Value { + .function { args, kwargs, environment in + if args.count == 1, kwargs.isEmpty, + case .string("%Y-%m-%d") = args[0] + { + return .string(value) + } + return try Globals.strftimeNow(args, kwargs, environment) + } + } +} + +/// Already sampled, complete, explicitly SILENT visual clip. Timestamps are +/// source FP32 seconds. No frame sampling, rotation, decoding or track removal. +public struct MiMoV26SilentVideo: Sendable { + public let frames: [MiMoV26Pixels.DecodedRGB] + public let timestamps: [Float] + public init(frames: [MiMoV26Pixels.DecodedRGB], timestamps: [Float]) { + self.frames = frames + self.timestamps = timestamps + } +} + +public enum MiMoV26MultimodalContent: Sendable { + case text(String) + case image(MiMoV26Pixels.DecodedRGB) + case silentVideo(MiMoV26SilentVideo) + case audio(MiMoV26DecodedPCM) + case audiovisual(MiMoV26DecodedAudiovisual) +} + +/// Fields have already passed the host's authoritative native normalization. +/// This layer preserves them; it does not repair history or tool arguments. +public struct MiMoV26MultimodalMessage: Sendable { + public let role: Chat.Message.Role + public let content: [MiMoV26MultimodalContent] + public let templateFields: [String: any Sendable] + public init( + role: Chat.Message.Role, content: [MiMoV26MultimodalContent], + templateFields: [String: any Sendable] = [:] + ) { + self.role = role + self.content = content + self.templateFields = templateFields + } +} + +public struct MiMoV26MultimodalInput: Sendable { + public let messages: [MiMoV26MultimodalMessage] + public let tools: [ToolSpec]? + public let additionalContext: [String: any Sendable]? + public let maximumOutputTokens: Int + public init( + messages: [MiMoV26MultimodalMessage], tools: [ToolSpec]? = nil, + additionalContext: [String: any Sendable]? = nil, maximumOutputTokens: Int + ) { + self.messages = messages + self.tools = tools + self.additionalContext = additionalContext + self.maximumOutputTokens = maximumOutputTokens + } +} + +/// Explicit request bounds, not model capacity or a physical-memory permit. +public struct MiMoV26MultimodalLimits: Sendable { + public let maximumMedia, maximumVideoFrames, maximumPromptTokens: Int + public let maximumMetadataBytes, maximumMetadataNodes, maximumMetadataDepth: Int + public let pixels: MiMoV26Pixels.Limits + public let vision: MiMoV26VisionLimits + public let audio: MiMoV26AudioInputLimits + public let audioPatch: MiMoV26AudioPatchLimits + public init( + maximumMedia: Int, maximumVideoFrames: Int, maximumPromptTokens: Int, + maximumMetadataBytes: Int, maximumMetadataNodes: Int, maximumMetadataDepth: Int, + pixels: MiMoV26Pixels.Limits, vision: MiMoV26VisionLimits, + audio: MiMoV26AudioInputLimits, audioPatch: MiMoV26AudioPatchLimits + ) { + self.maximumMedia = maximumMedia + self.maximumVideoFrames = maximumVideoFrames + self.maximumPromptTokens = maximumPromptTokens + self.maximumMetadataBytes = maximumMetadataBytes + self.maximumMetadataNodes = maximumMetadataNodes + self.maximumMetadataDepth = maximumMetadataDepth + self.pixels = pixels + self.vision = vision + self.audio = audio + self.audioPatch = audioPatch + } +} + +/// The host must return its actual request reservation and validate this exact +/// sealed plan. A conforming object/digest is NOT authentication by the SDK. +/// Its owner is retained through preparation drain and the queued request. +public protocol MiMoV26MediaWorkReservation: AnyObject { + func validate(plan: MiMoV26MultimodalPlan) throws + /// Mandatory ownership transfer, not a notification. Retain this opaque + /// bundle and the actual lease in the host's failed-work quarantine until + /// successful recovery or process exit. Fault/retire the serving lane. + func retainAfterFailedDrain(_ work: MiMoV26FailedMediaWork) +} + +public struct MiMoV26MultimodalSpan: Equatable, Sendable { + public enum Kind: String, Sendable { case image, video, audio } + public let kind: Kind + public let mediaIndex, featureOffset, tokenOffset, length: Int + public var engineSpan: CBv2ImageSpan { .init(tokenOffset: tokenOffset, length: length) } +} + +/// No public initializer or mutable fields: plans cannot be relabelled with a +/// different processor/owner or changed media after host admission. +public struct MiMoV26MultimodalPlan: Sendable { + public let promptTokens: [Int] + public let spans: [MiMoV26MultimodalSpan] + public let maximumOutputTokens: Int + public let preparationSHA256: String + public let profile: String + public let loadedOwnerIdentity: UUID + public let configurationSHA256, templateSHA256: String + /// Actual per-item geometry for host work admission, keyed by ordered media + /// index. Counts/buffer envelopes are not measured physical residency. + public let visionGeometryByMediaIndex: [Int: MiMoV26MediaGeometry.Plan] + public let audioPlan: MiMoV26AudioInputPlan? + public let decodedElements, patchElements, featureElements: Int + /// Logical retained-buffer counts only. Host must add real transient/Metal + /// bounds and existing reserves; these are not a measured peak or ledger. + public let logicalFeatureBytes: Int + let processorIdentity: UUID + let parts: [MiMoV26PlannedMedia] +} + +struct MiMoV26PlannedMedia: Sendable { + let content: MiMoV26MultimodalContent + let geometry: MiMoV26MediaGeometry.Plan? + let audioIndex: Int? +} + +struct MiMoV26MultimodalProfile { + static let name = "sglang67-decoded-rgb-silent-f32-timestamps-hf5711-pcm-v1" + static let spellings = [ + "vision_start_token_id": "<|vision_start|>", + "vision_end_token_id": "<|vision_end|>", "image_token_id": "<|image_pad|>", + "video_token_id": "<|video_pad|>", "video_start_token_id": "<|mimo_video_start|>", + "video_end_token_id": "<|mimo_video_end|>", "audio_start_token_id": "<|mimo_audio_start|>", + "audio_end_token_id": "<|mimo_audio_end|>", "audio_token_id": "<|audio_pad|>", + ] + let settings: MiMoV26MediaGeometry.Settings + let tokens: [String: Int] + init(configuration c: MiMoV26Configuration, tokenizer: any Tokenizer) throws { + guard let p = c.processorFields, let vision = c.vision, + p["rope_type"] == .string("rope"), p["use_video_timestamps"] == .bool(true), + p["use_per_grid_t_timestamps"] == .bool(false), + try Self.integer(p, "temporal_compression_ratio") == 1 + else { + throw MiMoV26MultimodalError.unsupportedProfile("native 1D causal profile") + } + settings = try .init( + patchSize: Self.integer(p, "patch_size"), mergeSize: Self.integer(p, "merge_size"), + temporalPatchSize: Self.integer(p, "temporal_patch_size"), temporalCompressionRatio: 1, + imageMinPixels: Self.integer(p, "image_min_pixels"), + imageMaxPixels: Self.integer(p, "image_max_pixels"), + videoMinPixels: Self.integer(p, "video_min_pixels"), + videoMaxPixels: Self.integer(p, "video_max_pixels"), + videoTotalMaxPixels: Self.integer(p, "video_total_max_pixels")) + guard settings.patchSize == vision.patchSize, settings.mergeSize == vision.spatialMergeSize, + settings.temporalPatchSize == vision.temporalPatchSize + else { + throw MiMoV26MultimodalError.unsupportedProfile("processor/tower geometry") + } + var resolved: [String: Int] = [:] + for (key, spelling) in Self.spellings { + let id = try Self.integer(p, key) + guard id >= 0, id < c.vocabularySize, tokenizer.convertTokenToId(spelling) == id, + tokenizer.convertIdToToken(id) == spelling, + c.tokenIDs[key] == nil || c.tokenIDs[key] == id + else { + throw MiMoV26MultimodalError.unsupportedProfile( + "tokenizer/processor token namespace") + } + resolved[key] = id + } + guard Set(resolved.values).count == resolved.count else { + throw MiMoV26MultimodalError.unsupportedProfile("aliased media token IDs") + } + tokens = resolved + } + static func integer(_ values: [String: MiMoV26JSONValue], _ key: String) throws -> Int { + guard case .number(let value) = values[key] else { + throw MiMoV26MultimodalError.unsupportedProfile(key) + } + let number = NSDecimalNumber(decimal: value).int64Value + guard Decimal(number) == value, let result = Int(exactly: number) else { + throw MiMoV26MultimodalError.unsupportedProfile(key) + } + return result + } + static func timestamp(_ value: Float) throws -> String { + guard value.isFinite, value >= 0, Double(value) < Double(Int.max) else { + throw MiMoV26MultimodalError.invalidInput("nonrepresentable timestamp") + } + let whole = Int(value) + let minutes = String(whole / 60) + let seconds = String(whole % 60) + let paddedMinutes = String(repeating: "0", count: max(0, 2 - minutes.count)) + minutes + let paddedSeconds = String(repeating: "0", count: max(0, 2 - seconds.count)) + seconds + return paddedMinutes + ":" + paddedSeconds + } +} + +enum MiMoV26MediaMetadata { + static func validate( + _ value: Any, limits: MiMoV26MultimodalLimits, + nodes: inout Int, bytes: inout Int, depth: Int = 0 + ) throws { + nodes = try MiMoV26AudioChecked.add(nodes, 1, "metadata nodes") + guard nodes <= limits.maximumMetadataNodes, depth <= limits.maximumMetadataDepth else { + throw MiMoV26MultimodalError.limit("metadata traversal") + } + if let native = value as? Jinja.Value { + switch native { + case .null, .boolean, .int: return + case .double(let number): + guard number.isFinite else { + throw MiMoV26MultimodalError.invalidInput("nonfinite template number") + } + return + case .string(let string): + bytes = try MiMoV26AudioChecked.add(bytes, string.utf8.count, "metadata bytes") + guard bytes <= limits.maximumMetadataBytes, + !MiMoV26MultimodalProfile.spellings.values.contains(where: string.contains) + else { + throw MiMoV26MultimodalError.invalidInput( + "metadata limit or ambiguous literal media marker") + } + return + case .array(let values): + for child in values { + try validate( + child, limits: limits, nodes: &nodes, bytes: &bytes, depth: depth + 1) + } + return + case .object(let values): + for (key, child) in values { + try validate( + key, limits: limits, nodes: &nodes, bytes: &bytes, depth: depth + 1) + try validate( + child, limits: limits, nodes: &nodes, bytes: &bytes, depth: depth + 1) + } + return + default: + throw MiMoV26MultimodalError.invalidInput("template fields must be JSON data") + } + } + if let string = value as? String { + bytes = try MiMoV26AudioChecked.add(bytes, string.utf8.count, "metadata bytes") + guard bytes <= limits.maximumMetadataBytes, + !MiMoV26MultimodalProfile.spellings.values.contains(where: string.contains) + else { + throw MiMoV26MultimodalError.invalidInput( + "metadata limit or ambiguous literal media marker") + } + } else if let array = value as? [Any] { + for child in array { + try validate(child, limits: limits, nodes: &nodes, bytes: &bytes, depth: depth + 1) + } + } else if let object = value as? [String: Any] { + for (key, child) in object { + try validate(key, limits: limits, nodes: &nodes, bytes: &bytes, depth: depth + 1) + try validate(child, limits: limits, nodes: &nodes, bytes: &bytes, depth: depth + 1) + } + } else if value is NSNull || value is Bool || value is Int || value is Int64 + || value is UInt64 + { + return + } else if let number = value as? Double, number.isFinite { + return + } else { + throw MiMoV26MultimodalError.invalidInput("non-JSON native template field") + } + } +} + +extension MiMoV26MultimodalProcessor { + /// Host-only planning. Does not allocate MLX arrays or execute a tower. + public func plan(_ input: MiMoV26MultimodalInput) throws -> MiMoV26MultimodalPlan { + try checkOwner() + let c = configuration + let l = limits + let p = profile + guard !input.messages.isEmpty, input.maximumOutputTokens > 0, + [ + l.maximumMedia, l.maximumVideoFrames, l.maximumPromptTokens, l.maximumMetadataBytes, + l.maximumMetadataNodes, l.maximumMetadataDepth, l.pixels.maximumInputElements, + l.pixels.maximumOutputElements, l.pixels.maximumWorkingBytes, + l.vision.maximumPatches, + l.vision.maximumAttentionScoreElements, l.audioPatch.maximumClips, + l.audioPatch.maximumFrames, + l.audioPatch.maximumPatches, l.audioPatch.maximumWorkingElements, + ].allSatisfy({ $0 > 0 }) + else { + throw MiMoV26MultimodalError.invalidInput("empty request or invalid limits") + } + guard l.maximumMetadataDepth <= 128, l.maximumMetadataNodes <= 1_000_000 else { + throw MiMoV26MultimodalError.limit("native metadata safety bounds") + } + var nodes = 0 + var bytes = 0 + var messages: [Message] = [] + var parts: [MiMoV26PlannedMedia] = [] + var clips: [MiMoV26DecodedPCM] = [] + var decoded = 0 + var patches = 0 + var hash = SHA256() + func hashInteger(_ n: Int) { + var v = UInt64(n).bigEndian + withUnsafeBytes(of: &v) { hash.update(data: Data($0)) } + } + func hashFloats(_ a: [Float]) { + // Bounded host scratch, not one allocation per pixel or an entire + // second raster. Explicit little-endian Float32 bit identity. + var words: [UInt32] = [] + words.reserveCapacity(4096) + for value in a { + words.append(value.bitPattern.littleEndian) + if words.count == 4096 { + words.withUnsafeBytes { hash.update(data: Data($0)) } + words.removeAll(keepingCapacity: true) + } + } + if !words.isEmpty { words.withUnsafeBytes { hash.update(data: Data($0)) } } + } + func validateFrame(_ frame: MiMoV26Pixels.DecodedRGB) throws { + guard frame.height > 0, frame.width > 0, + try MiMoV26AudioChecked.product([3, frame.height, frame.width], "RGB shape") + == frame.planarRGB.count, + frame.planarRGB.allSatisfy({ $0.isFinite && $0 >= 0 && $0 <= 255 }) + else { + throw MiMoV26MultimodalError.invalidInput("decoded planar RGB") + } + decoded = try MiMoV26AudioChecked.add( + decoded, frame.planarRGB.count, "decoded elements") + guard decoded <= l.pixels.maximumInputElements else { + throw MiMoV26MultimodalError.limit("aggregate RGB elements") + } + hashInteger(frame.height) + hashInteger(frame.width) + hashFloats(frame.planarRGB) + } + if let tools = input.tools { + try MiMoV26MediaMetadata.validate(tools, limits: l, nodes: &nodes, bytes: &bytes) + } + var renderContext = input.additionalContext + if var context = input.additionalContext { + if let clock = context.removeValue(forKey: "_darkbloom_request_clock") { + guard let snapshot = clock as? MiMoV26MediaRequestClock else { + throw MiMoV26MultimodalError.invalidInput( + "request clock requires a data-only snapshot") + } + try MiMoV26MediaMetadata.validate( + snapshot.value, limits: l, nodes: &nodes, bytes: &bytes) + renderContext?["_darkbloom_request_clock"] = snapshot.templateValue + } + guard Set(context.keys).isSubset(of: ["enable_thinking", "add_generation_prompt"]), + context.values.allSatisfy({ type(of: $0) == Bool.self }) + else { + throw MiMoV26MultimodalError.invalidInput("native Boolean render controls only") + } + try MiMoV26MediaMetadata.validate(context, limits: l, nodes: &nodes, bytes: &bytes) + } + for message in input.messages { + let structuralKeys: Set = [ + "role", "content", "image", "images", "image_url", "video", "videos", + "video_url", "audio", "audio_url", "input_audio", "audio_chunks", "pixel_values", + ] + guard Set(message.templateFields.keys).isDisjoint(with: structuralKeys) else { + throw MiMoV26MultimodalError.invalidInput( + "structured role/content override or unbound media field") + } + try MiMoV26MediaMetadata.validate( + message.templateFields, limits: l, nodes: &nodes, bytes: &bytes) + var native = message.templateFields + var content: [[String: any Sendable]] = [] + for item in message.content { + if case .text(let text) = item { + try MiMoV26MediaMetadata.validate(text, limits: l, nodes: &nodes, bytes: &bytes) + content.append(["type": "text", "text": text]) + continue + } + guard parts.count < l.maximumMedia else { + throw MiMoV26MultimodalError.limit("media count") + } + var geometry: MiMoV26MediaGeometry.Plan? + var audioIndex: Int? + switch item { + case .image(let frame): + try validateFrame(frame) + geometry = try MiMoV26MediaGeometry.image( + height: frame.height, width: frame.width, settings: p.settings) + content.append(["type": "image"]) + case .silentVideo(let video): + guard !video.frames.isEmpty, video.frames.count <= l.maximumVideoFrames, + video.frames.count == video.timestamps.count, + let first = video.frames.first + else { + throw MiMoV26MultimodalError.invalidInput("complete silent sampled video") + } + var previous: Float = -1 + for (frame, time) in zip(video.frames, video.timestamps) { + guard time.isFinite, time >= 0, time > previous, + frame.height == first.height, frame.width == first.width + else { + throw MiMoV26MultimodalError.invalidInput( + "video geometry or strictly increasing FP32 timestamps") + } + _ = try MiMoV26MultimodalProfile.timestamp(time) + previous = time + try validateFrame(frame) + } + hashFloats(video.timestamps) + geometry = try MiMoV26MediaGeometry.video( + height: first.height, width: first.width, + sampledFrames: video.frames.count, sampledFrameLimit: l.maximumVideoFrames, + settings: p.settings) + content.append(["type": "video"]) + case .audio(let clip): + guard audioCodec != nil else { throw MiMoV26MultimodalError.missingAudioCodec } + audioIndex = clips.count + clips.append(clip) + hashInteger(clip.descriptor.channels) + hashInteger(clip.descriptor.frameCount) + hashInteger(clip.descriptor.sampleRate) + hashFloats(clip.samples) + content.append(["type": "audio"]) + case .audiovisual(let av): + guard let codec = audioCodec else { + throw MiMoV26MultimodalError.missingAudioCodec + } + guard let fields = c.processorFields, + (fields["video_audio_interleave_length"] ?? .number(0)) == .number(0), + (fields["audio_input_id_per_second"] ?? .number(25)) == .number(25), + codec.input.configuration.groupSize == 4, + p.settings.temporalCompressionRatio == 1 + else { + throw MiMoV26MultimodalError.unsupportedProfile( + "decoded AV interleave0/6.25 patch rate") + } + guard !av.frames.isEmpty, av.frames.count <= l.maximumVideoFrames, + av.frames.count == av.timestamps.count, let first = av.frames.first + else { + throw MiMoV26MultimodalError.invalidInput( + "complete decoded AV sampled clip") + } + var previous: Float = -1 + for (frame, time) in zip(av.frames, av.timestamps) { + guard time.isFinite, time >= 0, time > previous, + frame.height == first.height, frame.width == first.width + else { + throw MiMoV26MultimodalError.invalidInput( + "decoded AV RGB/time geometry") + } + _ = try MiMoV26MultimodalProfile.timestamp(time) + previous = time + try validateFrame(frame) + } + hash.update(data: Data(MiMoV26AudiovisualLayout.profileName.utf8)) + hashFloats(av.timestamps) + switch av.segmentEnd { + case .float32(let end): + hashInteger(32) + hashFloats([end]) + case .float64(let end): + hashInteger(64) + var bits = end.bitPattern.littleEndian + withUnsafeBytes(of: &bits) { hash.update(data: Data($0)) } + } + geometry = try MiMoV26MediaGeometry.video( + height: first.height, width: first.width, + sampledFrames: av.frames.count, sampledFrameLimit: l.maximumVideoFrames, + settings: p.settings) + audioIndex = clips.count + clips.append(av.wholeAudio) + hashInteger(av.wholeAudio.descriptor.channels) + hashInteger(av.wholeAudio.descriptor.frameCount) + hashInteger(av.wholeAudio.descriptor.sampleRate) + hashFloats(av.wholeAudio.samples) + // One native video placeholder becomes linked AV units; + // never append an independent whole-audio message/span. + content.append(["type": "video"]) + case .text: preconditionFailure("handled above") + } + if let geometry { + patches = try MiMoV26AudioChecked.add( + patches, geometry.patchElementCount, "patch elements") + guard geometry.patchElementCount <= l.pixels.maximumOutputElements, + geometry.patchCount <= l.vision.maximumPatches + else { throw MiMoV26MultimodalError.limit("vision plan") } + let framePatches = try MiMoV26AudioChecked.product( + [geometry.gridH, geometry.gridW], "frame patches") + let scores = try MiMoV26AudioChecked.product( + [c.vision!.queryHeads, framePatches, framePatches], "attention scores") + guard scores <= l.vision.maximumAttentionScoreElements else { + throw MiMoV26MultimodalError.limit("vision attention") + } + } + parts.append(.init(content: item, geometry: geometry, audioIndex: audioIndex)) + } + native["role"] = message.role.rawValue + native["content"] = content + messages.append(native) + } + guard !parts.isEmpty else { + throw MiMoV26MultimodalError.invalidInput( + "use the native text processor for text-only input") + } + let audioPlan = + try clips.isEmpty + ? nil + : MiMoV26AudioInputPlan.make( + clips: clips.map(\.descriptor), + configuration: audioCodec!.input.configuration, limits: l.audio) + if let audioPlan { + guard clips.count <= l.audioPatch.maximumClips, + audioPlan.totalCodeFrames <= l.audioPatch.maximumFrames, + audioPlan.totalPatches <= l.audioPatch.maximumPatches + else { throw MiMoV26MultimodalError.limit("audio patch plan") } + hash.update(data: try audioPlan.preparationIdentityData()) + } + let symbolic = try tokenizer.applyChatTemplate( + messages: messages, chatTemplate: chatTemplate, + tools: input.tools, additionalContext: renderContext) + let reserved = Set(p.tokens.values) + var output: [Int] = [] + var spans: [MiMoV26MultimodalSpan] = [] + var slot = 0 + var index = 0 + var featureElements = 0 + func append(_ ids: [Int]) throws { + let count = try MiMoV26AudioChecked.add(output.count, ids.count, "expanded prompt") + guard count <= l.maximumPromptTokens, + count <= c.maxPositionEmbeddings - input.maximumOutputTokens, + ids.allSatisfy({ $0 >= 0 && $0 < c.vocabularySize }) + else { throw MiMoV26MultimodalError.limit("expanded native context/vocabulary") } + output.append(contentsOf: ids) + } + func span( + _ kind: MiMoV26MultimodalSpan.Kind, _ pad: Int, _ length: Int, _ featureOffset: Int + ) throws { + guard length > 0, length <= l.maximumPromptTokens - output.count, + length <= c.maxPositionEmbeddings - input.maximumOutputTokens - output.count + else { throw MiMoV26MultimodalError.limit("media span") } + spans.append( + .init( + kind: kind, mediaIndex: slot, featureOffset: featureOffset, + tokenOffset: output.count, length: length)) + featureElements = try MiMoV26AudioChecked.add( + featureElements, + MiMoV26AudioChecked.product([length, c.hiddenSize], "features"), "features") + try append(Array(repeating: pad, count: length)) + } + guard input.maximumOutputTokens < c.maxPositionEmbeddings else { + throw MiMoV26MultimodalError.limit("output context") + } + while index < symbolic.count { + let id = symbolic[index] + guard reserved.contains(id) else { + try append([id]) + index += 1 + continue + } + guard slot < parts.count, index + 2 < symbolic.count else { + throw MiMoV26MultimodalError.invalidInput("unbound media marker") + } + let item = parts[slot] + let start = p.tokens["vision_start_token_id"]! + let end = p.tokens["vision_end_token_id"]! + switch item.content { + case .image: + guard + Array(symbolic[index ..< (index + 3)]) == [ + start, p.tokens["image_token_id"]!, end, + ] + else { throw MiMoV26MultimodalError.invalidInput("ordered image marker") } + try append([start]) + try span(.image, p.tokens["image_token_id"]!, item.geometry!.mediaTokens, 0) + try append([end]) + case .silentVideo(let video): + guard + Array(symbolic[index ..< (index + 3)]) == [ + start, p.tokens["video_token_id"]!, end, + ] + else { throw MiMoV26MultimodalError.invalidInput("ordered video marker") } + let geometry = item.geometry! + let count = + geometry.gridH * geometry.gridW / (p.settings.mergeSize * p.settings.mergeSize) + try append([p.tokens["video_start_token_id"]!]) + for group in 0 ..< geometry.timestampCount { + let timestamp = video.timestamps[ + min(group * p.settings.temporalPatchSize, video.timestamps.count - 1)] + let timestampIDs = tokenizer.encode( + text: try MiMoV26MultimodalProfile.timestamp(timestamp), + addSpecialTokens: true) + guard !timestampIDs.isEmpty, reserved.isDisjoint(with: timestampIDs) else { + throw MiMoV26MultimodalError.invalidInput("timestamp tokenization") + } + try append(timestampIDs) + try append([start]) + try span(.video, p.tokens["video_token_id"]!, count, group * count) + try append([end]) + } + try append([p.tokens["video_end_token_id"]!]) + case .audio: + let a = p.tokens["audio_start_token_id"]! + let z = p.tokens["audio_end_token_id"]! + let pad = p.tokens["audio_token_id"]! + guard Array(symbolic[index ..< (index + 3)]) == [a, pad, z] else { + throw MiMoV26MultimodalError.invalidInput("ordered audio marker") + } + try append([a]) + try span(.audio, pad, audioPlan!.patchCounts[item.audioIndex!], 0) + try append([z]) + case .audiovisual(let av): + guard + Array(symbolic[index ..< (index + 3)]) == [ + start, p.tokens["video_token_id"]!, end, + ], + let geometry = item.geometry, let audioIndex = item.audioIndex, + let audioPlan + else { throw MiMoV26MultimodalError.invalidInput("ordered decoded AV marker") } + let layout = try MiMoV26AudiovisualLayout.make( + timestamps: av.timestamps, + segmentEnd: av.segmentEnd, temporalPatchSize: p.settings.temporalPatchSize, + wholeAudioPatches: audioPlan.patchCounts[audioIndex], + maximumUnits: l.maximumVideoFrames) + guard layout.units.count == geometry.timestampCount, + layout.alignedFrames == geometry.alignedFrames + else { throw MiMoV26MultimodalError.incompatiblePlan } + let count = + geometry.gridH * geometry.gridW / (p.settings.mergeSize * p.settings.mergeSize) + try append([p.tokens["video_start_token_id"]!]) + for unit in layout.units { + let stamp = tokenizer.encode( + text: try MiMoV26MultimodalProfile.timestamp(unit.timestamp), + addSpecialTokens: true) + guard !stamp.isEmpty, reserved.isDisjoint(with: stamp) else { + throw MiMoV26MultimodalError.invalidInput("timestamp tokenization") + } + try append(stamp) + try append([start]) + try span(.video, p.tokens["video_token_id"]!, count, unit.visualGroup * count) + try append([end]) + try append([p.tokens["audio_start_token_id"]!]) + try span( + .audio, p.tokens["audio_token_id"]!, unit.audioRange.count, + unit.audioRange.lowerBound) + try append([p.tokens["audio_end_token_id"]!]) + } + try append([p.tokens["video_end_token_id"]!]) + // Slices retain the FULL encoded/patch backing. Price unused + // prefix/tail features too; prompt tokens still use only spans. + featureElements = try MiMoV26AudioChecked.add( + featureElements, + MiMoV26AudioChecked.product( + [layout.unusedAudioPatches, c.hiddenSize], "whole AV audio backing"), + "whole AV audio backing") + case .text: preconditionFailure("text is not a media slot") + } + index += 3 + slot += 1 + } + guard slot == parts.count else { + throw MiMoV26MultimodalError.invalidInput("missing media placeholders") + } + hash.update(data: Data(profileIdentity().utf8)) + hashInteger(input.maximumOutputTokens) + hashInteger(parts.count) + for token in output { hashInteger(token) } + let totalDecoded = try clips.reduce(decoded) { + try MiMoV26AudioChecked.add($0, $1.samples.count, "total decoded elements") + } + return .init( + promptTokens: output, spans: spans, maximumOutputTokens: input.maximumOutputTokens, + preparationSHA256: hash.finalize().map { String(format: "%02x", $0) }.joined(), + profile: parts.contains(where: { + if case .audiovisual = $0.content { return true } + return false + }) + ? MiMoV26AudiovisualLayout.profileName : MiMoV26MultimodalProfile.name, + loadedOwnerIdentity: loadedOwnerIdentity, configurationSHA256: configurationSHA256, + templateSHA256: templateSHA256, + visionGeometryByMediaIndex: Dictionary( + uniqueKeysWithValues: parts.enumerated().compactMap { index, item in + item.geometry.map { (index, $0) } + }), + audioPlan: audioPlan, decodedElements: totalDecoded, patchElements: patches, + featureElements: featureElements, + logicalFeatureBytes: try MiMoV26AudioChecked.product( + [featureElements, configuration.dtype == "float32" ? 4 : 2], "feature bytes"), + processorIdentity: identity, parts: parts) + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26MultimodalProcessor.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26MultimodalProcessor.swift new file mode 100644 index 0000000000..bfcc1dd6a6 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26MultimodalProcessor.swift @@ -0,0 +1,654 @@ +// Copyright © 2026 Eigen Labs. Native owned decoded-media composition only. +import CryptoKit +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +/// Caller-supplied, already materialized codec plus its REAL load owner. Exact +/// metadata/generation checks are not source-byte authentication or admission: +/// the provider's verified load session remains responsible for those gates. +public final class MiMoV26OwnedAudioCodec { + let input: MiMoV26AudioInput + private let lifetimeOwner: AnyObject + public let sourceIdentity: String + public let generation: UUID + public init( + input: MiMoV26AudioInput, retaining owner: AnyObject, + expectedSourceIdentity: String, expectedGeneration: UUID, + mainConfiguration: MiMoV26Configuration + ) throws { + guard expectedSourceIdentity == MiMoV26AudioTokenizerWeights.selectedPayloadSHA256, + input.weights.sourceIdentity == expectedSourceIdentity, + input.weights.generation == expectedGeneration + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + let checked = try MiMoV26AudioInputConfiguration( + sidecarJSON: input.configuration.encodedSidecar(), + mainConfiguration: mainConfiguration) + guard checked == input.configuration else { throw MiMoV26MultimodalError.incompatibleOwner } + self.input = input + lifetimeOwner = owner + sourceIdentity = expectedSourceIdentity + generation = expectedGeneration + try validate() + } + func validate() throws { + guard input.weights.encoder.loadedGeneration == generation, + input.weights.generation == generation, input.weights.sourceIdentity == sourceIdentity + else { + throw MiMoV26MultimodalError.invalidatedOwner + } + } +} + +/// No Module inheritance: identity metadata never registers a target twice. +/// Access is serialized with the loaded owner, just like native module access. +final class MiMoV26MediaGeneration { + let identity = UUID() + private(set) var isValid = true + func invalidate() { isValid = false } + func validate() throws { + guard isValid else { throw MiMoV26MultimodalError.invalidatedOwner } + } +} + +/// Opaque failed-work ownership, NEVER serialized. Host quarantine owns this +/// box after a failed drain. It retains original root handles (no tensor +/// copies), decoded input, loaded resources, codec and the actual reservation. +/// No global SDK quarantine and no inference that a numeric byte credit owns +/// in-flight allocations. Recovery must run on the host's granted native lane. +public final class MiMoV26FailedMediaWork { + public let preparationSHA256: String + public let loadedOwnerIdentity: UUID + public let configurationSHA256, templateSHA256: String + public private(set) var failedDrain = false + public var retainedRootCount: Int { roots.count } + private let stream: MLX.Stream + private var roots: [MLXArray] = [] + private var plan: MiMoV26MultimodalPlan? + private var loadedOwner: AnyObject? + private var codec: MiMoV26OwnedAudioCodec? + private var audioSidecar: MiMoV26AudioSidecarLoaded? + private var reservation: (any MiMoV26MediaWorkReservation)? + private var audioFailures: [MiMoV26FailedAudioWork] = [] + private let managedWork: CBv2NativeMediaPreparation? + var managedAudioContext: CBv2NativeMediaPreparation? { managedWork } + var retainedAudioFailureRootCountsForTesting: [Int] { audioFailures.map(\.retainedRootCount) } + init( + plan: MiMoV26MultimodalPlan, owner: AnyObject, codec: MiMoV26OwnedAudioCodec?, + reservation: any MiMoV26MediaWorkReservation, + managedWork: CBv2NativeMediaPreparation? = nil, + audioSidecar: MiMoV26AudioSidecarLoaded? = nil + ) { + preparationSHA256 = plan.preparationSHA256 + loadedOwnerIdentity = plan.loadedOwnerIdentity + configurationSHA256 = plan.configurationSHA256 + templateSHA256 = plan.templateSHA256 + self.plan = plan + loadedOwner = owner + self.codec = codec + self.reservation = reservation + self.managedWork = managedWork + self.audioSidecar = audioSidecar + stream = StreamOrDevice.default.stream + } + func track(_ values: [MLXArray]) { roots = values } + func trackManaged(_ values: [MLXArray]) throws { + roots = values + try managedWork?.beforeNativeWork(values) + } + /// Preserve already-evaluated visual roots while arming the existing loan + /// BEFORE the inner audio frontend/encoder/RVQ can submit native work. + func beginManagedAudioPhase() throws { + try managedWork?.beforeNativeWork(roots) + } + func requiredAudioCompletionFailed() { managedWork?.requiredCompletionFailed() } + func requiredNativeCompletion(_ body: () throws -> T) throws -> T { + do { return try body() } catch { + managedWork?.requiredCompletionFailed() + throw error + } + } + func retainAudioFailure(_ audio: MiMoV26FailedAudioWork, generation: MiMoV26MediaGeneration) { + managedWork?.requiredCompletionFailed() + audioFailures.append(audio) + generation.invalidate() + if !failedDrain { + failedDrain = true + reservation!.retainAfterFailedDrain(self) + } + } + func drain(generation: MiMoV26MediaGeneration, synchronize: (() throws -> Void)? = nil) throws { + do { + if let synchronize { + try synchronize() + } else if let managedWork { + try managedWork.fencePreparation(stream) + } else { + try withError { stream.synchronize() } + } + } catch { + managedWork?.requiredCompletionFailed() + failedDrain = true + generation.invalidate() + reservation!.retainAfterFailedDrain(self) + throw MiMoV26MultimodalError.drainFailed + } + try managedWork?.completedPreparation() + } + func releaseAfterSuccessfulDrain() { + for audio in audioFailures { audio.releaseAfterSuccessfulDrain() } + audioFailures.removeAll() + roots.removeAll() + plan = nil + loadedOwner = nil + codec = nil + audioSidecar = nil + reservation = nil + } + /// Failed synchronization leaves ALL owners/roots in place. Only an actual + /// successful synchronization on the captured stream allows release. + func verifyRecoveryDrain(synchronize: (() throws -> Void)? = nil) throws { + guard failedDrain else { throw MiMoV26MultimodalError.incompatiblePlan } + if let synchronize { try synchronize() } else { try withError { stream.synchronize() } } + for audio in audioFailures { try audio.verifyRecoveryDrain() } + } + public func recoverAndReleaseAfterDrain() throws { + guard failedDrain, managedWork == nil else { throw MiMoV26MultimodalError.incompatiblePlan } + do { try verifyRecoveryDrain() } catch { throw MiMoV26MultimodalError.drainFailed } + releaseAfterSuccessfulDrain() + failedDrain = false + } +} + +/// Delegates the audio phase to the SAME real request lease. It introduces no +/// new admission credit, fake authentication or duplicate numerical pipeline. +private final class MiMoV26MediaAudioReservation: MiMoV26AudioWorkReservation { + let plan: MiMoV26MultimodalPlan + let audioPlan: MiMoV26AudioInputPlan + let codec: MiMoV26OwnedAudioCodec + let audioSidecar: MiMoV26AudioSidecarLoaded? + let reservation: any MiMoV26MediaWorkReservation + let work: MiMoV26FailedMediaWork + let generation: MiMoV26MediaGeneration + init( + plan: MiMoV26MultimodalPlan, audioPlan: MiMoV26AudioInputPlan, + codec: MiMoV26OwnedAudioCodec, + reservation: any MiMoV26MediaWorkReservation, work: MiMoV26FailedMediaWork, + generation: MiMoV26MediaGeneration, audioSidecar: MiMoV26AudioSidecarLoaded? = nil + ) { + self.plan = plan + self.audioPlan = audioPlan + self.codec = codec + self.reservation = reservation + self.work = work + self.generation = generation + self.audioSidecar = audioSidecar + } + func validate(plan: MiMoV26AudioInputPlan, sourceIdentity: String, generation: UUID) throws { + guard plan == audioPlan, sourceIdentity == codec.sourceIdentity, + generation == codec.generation + else { + throw MiMoV26MultimodalError.incompatiblePlan + } + try self.generation.validate() + try codec.validate() + if let audioSidecar { + guard audioSidecar.codec === codec else { + throw MiMoV26MultimodalError.incompatibleOwner + } + try audioSidecar.validate() + } + try reservation.validate(plan: self.plan) + } + func retainAfterFailedDrain(_ failed: MiMoV26FailedAudioWork) { + work.retainAudioFailure(failed, generation: generation) + } +} + +/// Created by the loaded wrapper, not a generic UserInputProcessor. Retains +/// exact private components/source owners without exposing tower aliases. +public final class MiMoV26MultimodalProcessor { + let configuration: MiMoV26Configuration + let tokenizer: any Tokenizer + let chatTemplate, templateSHA256: String + let limits: MiMoV26MultimodalLimits + let profile: MiMoV26MultimodalProfile + let identity = UUID() + let audioCodec: MiMoV26OwnedAudioCodec? + let audioSidecar: MiMoV26AudioSidecarLoaded? + private let vision: MiMoV26VisionTower + private let audioPatch: MiMoV26AudioPatchEncoder + private let adapter: MiMoV26CBv2Adapter + private let stopTokens: Set + private let generation: MiMoV26MediaGeneration + private let loadedOwner: AnyObject + let configurationSHA256: String + var loadedOwnerIdentity: UUID { generation.identity } + + init( + configuration: MiMoV26Configuration, tokenizer: any Tokenizer, chatTemplate: String, + templateSHA256: String, limits: MiMoV26MultimodalLimits, + vision: MiMoV26VisionTower, audioPatch: MiMoV26AudioPatchEncoder, + adapter: MiMoV26CBv2Adapter, stopTokens: Set, generation: MiMoV26MediaGeneration, + retaining owner: AnyObject, audioCodec: MiMoV26OwnedAudioCodec?, + audioSidecar: MiMoV26AudioSidecarLoaded? = nil + ) throws { + guard adapter.target.configuration.rawFields == configuration.rawFields, + adapter.supportsMultimodalPrefill(attention: .causal), + configuration.vision == vision.configuration, + configuration.audio == audioPatch.configuration, + Self.hash(Data(chatTemplate.utf8)) == templateSHA256 + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + self.configuration = configuration + self.tokenizer = tokenizer + self.chatTemplate = chatTemplate + self.templateSHA256 = templateSHA256 + self.limits = limits + profile = try .init(configuration: configuration, tokenizer: tokenizer) + self.vision = vision + self.audioPatch = audioPatch + self.adapter = adapter + self.stopTokens = stopTokens + self.generation = generation + loadedOwner = owner + self.audioCodec = audioCodec + self.audioSidecar = audioSidecar + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + configurationSHA256 = Self.hash(try encoder.encode(configuration.rawFields)) + if let audioCodec { + let checked = try MiMoV26AudioInputConfiguration( + sidecarJSON: audioCodec.input.configuration.encodedSidecar(), + mainConfiguration: configuration) + guard checked == audioCodec.input.configuration else { + throw MiMoV26MultimodalError.incompatibleOwner + } + } + try checkOwner() + } + static func hash(_ data: Data) -> String { + SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + } + func profileIdentity() -> String { + let codecIdentity = + audioCodec.map { $0.sourceIdentity + ":" + $0.generation.uuidString } ?? "no-codec" + return [ + MiMoV26MultimodalProfile.name, generation.identity.uuidString, + configurationSHA256, templateSHA256, codecIdentity, + ].joined(separator: ":") + } + func checkOwner() throws { + try generation.validate() + try audioCodec?.validate() + if let audioSidecar { + guard audioSidecar.codec === audioCodec else { + throw MiMoV26MultimodalError.incompatibleOwner + } + try audioSidecar.validate() // retained FD, separate load charge and invalidation flag + } + guard adapter.supportsMultimodalPrefill(attention: .causal) else { + throw MiMoV26MultimodalError.invalidatedOwner + } + } + + /// Conservative source-derived commitment, not measured residency: decoded + /// buffers, pixel working bound, retained patches/features, plus the entire + /// FP32 vision graph (all blocks, full-frame score upper bound even for + /// tiled local attention). Existing global/OS reserves remain additional. + /// Never represents target KV, which the bridge already charges. + func managedVisualCommitmentBytes(_ plan: MiMoV26MultimodalPlan) throws -> Int { + guard plan.audioPlan == nil else { + throw MiMoV26MultimodalError.incompatiblePlan + } + return try managedBaseCommitmentBytes(plan) + } + func managedAudioCommitmentBytes(_ plan: MiMoV26MultimodalPlan) throws -> Int { + try checkOwner() + guard let sidecar = audioSidecar, audioCodec === sidecar.codec else { + throw MiMoV26MultimodalError.missingAudioCodec + } + let base = try managedBaseCommitmentBytes(plan) + guard let input = plan.audioPlan else { return base } + guard let patch = configuration.audio else { throw MiMoV26MultimodalError.incompatiblePlan } + let audio = try MiMoV26ManagedAudioCommitment.additionalBytes( + input: input, + patchConfiguration: patch, limits: limits.audioPatch) + return try MiMoV26AudioChecked.add(base, audio, "managed decoded audio commitment") + } + private func managedBaseCommitmentBytes(_ plan: MiMoV26MultimodalPlan) throws -> Int { + guard let c = configuration.vision else { throw MiMoV26MultimodalError.incompatiblePlan } + func mul(_ a: Int, _ b: Int) throws -> Int { + try MiMoV26AudioChecked.product([a, b], "managed visual commitment") + } + func add(_ a: Int, _ b: Int) throws -> Int { + try MiMoV26AudioChecked.add(a, b, "managed visual commitment") + } + var bytes = try add(limits.pixels.maximumWorkingBytes, mul(plan.decodedElements, 4)) + bytes = try add(bytes, mul(plan.patchElements, 8)) + bytes = try add(bytes, mul(plan.featureElements, 16)) + for geometry in plan.visionGeometryByMediaIndex.values { + let n = geometry.patchCount + // Covers projection/rotary/normalization/gated-MLP/merger + // temporaries and layout indices with FP32 widths and slack. + let widths = try add(try mul(c.hiddenSize, 64), try mul(c.intermediateSize, 16)) + let activations = try mul(try mul(n, widths), 4) + let scores = try mul(try mul(try mul(n, n), c.queryHeads), 16) + bytes = try add(bytes, try mul(try add(activations, scores), try add(c.depth, 2))) + // 16-KiB native-load profile: reserve per-node rounding/slack in + // addition to logical tensor bytes. The reviewed vision expression + // graph has fewer than 256 non-tile nodes/block and 96 nodes/tile; + // full-frame attention uses fewer tiles than this local upper bound. + let framePatches = try mul(geometry.gridH, geometry.gridW) + let tiles = try mul(geometry.gridT, try add(framePatches, 127) / 128) + let nodes = try add(64, try mul(c.depth, try add(256, try mul(96, tiles)))) + bytes = try add(bytes, try mul(nodes, 16384)) + } + for part in plan.parts { + if case .audiovisual = part.content, let geometry = part.geometry { + // Two bounded view/node metadata allowances per AV unit; + // whole audio feature/data backing is separately kept above + // and in ManagedAudioCommitment, never priced as slice-only. + bytes = try add(bytes, try mul(geometry.timestampCount, 32768)) + } + } + return bytes + } + + /// Must run on the real host's serialized model lane. The mandatory + /// callback obtains admission BEFORE pixel/native work. No default permit, + /// network, source loading or regrouping is hidden inside this method. + public func prepare( + _ plan: MiMoV26MultimodalPlan, + authorize: (MiMoV26MultimodalPlan) throws -> any MiMoV26MediaWorkReservation, + isCancelled: () -> Bool = { false } + ) throws -> MiMoV26PreparedMultimodal { + try prepareOwned(plan, authorize: authorize, isCancelled: isCancelled, managedWork: nil) + } + package func prepareManaged( + _ plan: MiMoV26MultimodalPlan, + authorize: (MiMoV26MultimodalPlan) throws -> any MiMoV26MediaWorkReservation, + isCancelled: () -> Bool, work: CBv2NativeMediaPreparation + ) throws -> MiMoV26PreparedMultimodal { + guard plan.audioPlan == nil else { throw MiMoV26MultimodalError.missingAudioCodec } + return try prepareOwned( + plan, authorize: authorize, isCancelled: isCancelled, managedWork: work) + } + package func prepareManagedAudio( + _ plan: MiMoV26MultimodalPlan, sidecar: MiMoV26AudioSidecarLoaded, + authorize: (MiMoV26MultimodalPlan) throws -> any MiMoV26MediaWorkReservation, + isCancelled: () -> Bool, work: CBv2NativeMediaPreparation + ) throws -> MiMoV26PreparedMultimodal { + guard audioSidecar === sidecar, audioCodec === sidecar.codec else { + throw MiMoV26MultimodalError.incompatibleOwner + } + try sidecar.validate() + return try prepareOwned( + plan, authorize: authorize, isCancelled: isCancelled, managedWork: work) + } + private func prepareOwned( + _ plan: MiMoV26MultimodalPlan, + authorize: (MiMoV26MultimodalPlan) throws -> any MiMoV26MediaWorkReservation, + isCancelled: () -> Bool, managedWork: CBv2NativeMediaPreparation? + ) throws -> MiMoV26PreparedMultimodal { + try checkOwner() + guard plan.processorIdentity == identity else { + throw MiMoV26MultimodalError.incompatiblePlan + } + if isCancelled() { throw MiMoV26MultimodalError.cancelled } + let reservation = try authorize(plan) + try reservation.validate(plan: plan) + let work = MiMoV26FailedMediaWork( + plan: plan, owner: loadedOwner, codec: audioCodec, + reservation: reservation, managedWork: managedWork, audioSidecar: audioSidecar) + managedWork?.retain(work) + do { + let arrays = try withError { error in + let result = try admitted( + plan, isCancelled: isCancelled, reservation: reservation, work: work, + errors: error) + try error.check() + return result + } + try work.drain(generation: generation) + try checkOwner() + let result = MiMoV26PreparedMultimodal( + plan: plan, arrays: arrays, adapter: adapter, stopTokens: stopTokens, + generation: generation, retaining: loadedOwner, codec: audioCodec, + reservation: reservation, + audioSidecar: audioSidecar) + work.releaseAfterSuccessfulDrain() + return result + } catch { + if managedWork != nil, !(error is MiMoV26MultimodalError), !(error is CancellationError) + { + managedWork?.requiredCompletionFailed() + } + if work.failedDrain || managedWork?.completionFailed == true { + reservation.retainAfterFailedDrain(work) + throw MiMoV26MultimodalError.drainFailed + } + // Roots were recorded BEFORE each explicit evaluation/read, so + // admitted's Swift unwinding cannot drop failed issued work. + try work.drain(generation: generation) + work.releaseAfterSuccessfulDrain() + throw error + } + } + + private func admitted( + _ plan: MiMoV26MultimodalPlan, isCancelled: () -> Bool, + reservation: any MiMoV26MediaWorkReservation, + work: MiMoV26FailedMediaWork, errors: MLX.ErrorBox + ) throws -> [MLXArray] { + var features: [Int: MLXArray] = [:] + var audioFeatures: [Int: MLXArray] = [:] + let dtype: DType = configuration.dtype == "bfloat16" ? .bfloat16 : .float32 + func evaluate(_ array: MLXArray, count: Int) throws { + try errors.check() + guard array.shape == [count, configuration.hiddenSize], array.dtype == dtype else { + throw MiMoV26MultimodalError.invalidFeatures + } + let finite = all(isFinite(array)) + try work.trackManaged( + Array(features.values) + Array(audioFeatures.values) + [array, finite]) + try errors.check() + try work.requiredNativeCompletion { try withError { eval(array, finite) } } + guard try work.requiredNativeCompletion({ try withError { finite.item(Bool.self) } }) + else { + throw MiMoV26MultimodalError.invalidFeatures + } + if isCancelled() { throw MiMoV26MultimodalError.cancelled } + } + for (index, item) in plan.parts.enumerated() { + if isCancelled() { throw MiMoV26MultimodalError.cancelled } + try checkOwner() + try reservation.validate(plan: plan) + let pixels: MiMoV26Pixels.Prepared + switch item.content { + case .image(let frame): + pixels = try MiMoV26Pixels.image( + frame, settings: profile.settings, limits: limits.pixels) + case .silentVideo(let video): + pixels = try MiMoV26Pixels.video( + frames: video.frames, + sampledFrameCount: video.frames.count, settings: profile.settings, + limits: limits.pixels) + case .audiovisual(let av): + pixels = try MiMoV26Pixels.video( + frames: av.frames, + sampledFrameCount: av.frames.count, settings: profile.settings, + limits: limits.pixels) + case .audio: continue + case .text: throw MiMoV26MultimodalError.incompatiblePlan + } + guard let geometry = item.geometry, pixels.geometry == geometry else { + throw MiMoV26MultimodalError.incompatiblePlan + } + let patchArray = MLXArray( + pixels.patchValues, [geometry.patchCount, geometry.patchVectorSize]) + try work.trackManaged(Array(features.values) + [patchArray]) + try errors.check() + let feature = try vision.forward( + patches: patchArray, + grids: [ + .init(temporal: geometry.gridT, height: geometry.gridH, width: geometry.gridW) + ], limits: limits.vision) + try evaluate(feature, count: geometry.mediaTokens) + features[index] = feature + } + if let audioPlan = plan.audioPlan { + guard let codec = audioCodec else { throw MiMoV26MultimodalError.missingAudioCodec } + try checkOwner() + try codec.validate() + try reservation.validate(plan: plan) + let clips: [MiMoV26DecodedPCM] = plan.parts.compactMap { + switch $0.content { + case .audio(let clip): return clip + case .audiovisual(let av): return av.wholeAudio + default: return nil + } + } + try work.beginManagedAudioPhase() + let codes: [MiMoV26AudioCodeClip] + do { + let audioAuthorize: + (MiMoV26AudioInputPlan) throws -> any MiMoV26AudioWorkReservation = { actual in + guard actual == audioPlan else { + throw MiMoV26MultimodalError.incompatiblePlan + } + return MiMoV26MediaAudioReservation( + plan: plan, audioPlan: audioPlan, codec: codec, + reservation: reservation, work: work, generation: self.generation, + audioSidecar: self.audioSidecar) + } + if let native = work.managedAudioContext { + codes = try codec.input.encodeManaged( + clips: clips, limits: limits.audio, retaining: codec, + authorize: audioAuthorize, isCancelled: isCancelled, work: native) + } else { + codes = try codec.input.encode( + clips: clips, limits: limits.audio, retaining: codec, + authorize: audioAuthorize, isCancelled: isCancelled) + } + } catch MiMoV26AudioInputError.cancelled { + // encode returns this only before submission or after its + // real required drain succeeded. Outer preparation still owes + // its own captured-stream completion before retirement. + throw MiMoV26MultimodalError.cancelled + } catch MiMoV26AudioWorkFailure.drainFailed { + work.requiredAudioCompletionFailed() + throw MiMoV26AudioWorkFailure.drainFailed + } + guard codes.map(\.frameCount) == audioPlan.codeFrameCounts else { + throw MiMoV26MultimodalError.invalidFeatures + } + let output = try audioPatch.forward(clips: codes, limits: limits.audioPatch) + try evaluate(output.features, count: audioPlan.totalPatches) + guard output.clipPatchRanges.map(\.count) == audioPlan.patchCounts else { + throw MiMoV26MultimodalError.invalidFeatures + } + for (index, item) in plan.parts.enumerated() { + if let audioIndex = item.audioIndex { + audioFeatures[index] = output.features[output.clipPatchRanges[audioIndex], 0...] + } + } + } + let arrays = try plan.spans.map { span -> MLXArray in + // Linked AV has visual AND audio arrays at the same mediaIndex. + // The whole audio is encoded once, then sliced by final patch rows. + let selected = + span.kind == .audio ? audioFeatures[span.mediaIndex] : features[span.mediaIndex] + guard let feature = selected, span.featureOffset >= 0, + span.length > 0, span.featureOffset <= feature.dim(0) - span.length + else { + throw MiMoV26MultimodalError.invalidFeatures + } + return feature[span.featureOffset ..< (span.featureOffset + span.length), 0...] + } + try work.trackManaged(arrays) + try errors.check() + try work.requiredNativeCompletion { try withError { eval(arrays) } } + if isCancelled() { throw MiMoV26MultimodalError.cancelled } + return arrays + } +} + +/// One admitted request, with immutable evaluated features and a source/work +/// owner. No public array getters. The returned CBv2 request retains this box +/// until engine retirement; host must retire/drain the engine before teardown. +public final class MiMoV26PreparedMultimodal: CBv2NativeMediaBindingValidating { + public let plan: MiMoV26MultimodalPlan + private let arrays: [MLXArray] + private let adapter: MiMoV26CBv2Adapter + private let stopTokens: Set + private let generation: MiMoV26MediaGeneration + private let loadedOwner: AnyObject + private let codec: MiMoV26OwnedAudioCodec? + private let audioSidecar: MiMoV26AudioSidecarLoaded? + private let reservation: any MiMoV26MediaWorkReservation + private let lock = NSLock() + private var issued = false, consumed = false + init( + plan: MiMoV26MultimodalPlan, arrays: [MLXArray], adapter: MiMoV26CBv2Adapter, + stopTokens: Set, generation: MiMoV26MediaGeneration, retaining owner: AnyObject, + codec: MiMoV26OwnedAudioCodec?, reservation: any MiMoV26MediaWorkReservation, + audioSidecar: MiMoV26AudioSidecarLoaded? = nil + ) { + self.plan = plan + self.arrays = arrays + self.adapter = adapter + self.stopTokens = stopTokens + self.generation = generation + loadedOwner = owner + self.codec = codec + self.reservation = reservation + self.audioSidecar = audioSidecar + } + package func validateNativeMediaBinding() throws { try validate() } + private func validate() throws { + try generation.validate() + try codec?.validate() + try reservation.validate(plan: plan) + if let audioSidecar { + guard audioSidecar.codec === codec else { + throw MiMoV26MultimodalError.incompatibleOwner + } + try audioSidecar.validate() // again at actual engine bind, not just prepare + } + guard adapter.supportsMultimodalPrefill(attention: .causal) else { + throw MiMoV26MultimodalError.invalidatedOwner + } + } + /// Use the same binding to construct the engine. Hand-crafted raw requests + /// submitted to another engine are outside this owned producer contract. + public func makeRequest( + binding: MiMoV26CBv2Binding, id: CBv2RequestID, + sampling: CBv2SamplingParams = .init(), stopStrings: [String] = [] + ) throws -> CBv2Request { + try validate() + guard binding.adapter === adapter, binding.mediaGeneration === generation, + binding.assistant === adapter.assistant + else { throw MiMoV26MultimodalError.incompatibleOwner } + lock.lock() + defer { lock.unlock() } + guard !issued else { throw MiMoV26MultimodalError.incompatiblePlan } + issued = true + return CBv2Request( + id: id, promptTokens: plan.promptTokens, sampling: sampling, + maxTokens: plan.maximumOutputTokens, stopTokens: stopTokens, stopStrings: stopStrings, + prefixCacheEnabled: false, + multimodal: .init(spans: plan.spans.map(\.engineSpan), attention: .causal) { [self] in + try validate() + lock.lock() + defer { lock.unlock() } + guard !consumed else { throw MiMoV26MultimodalError.incompatiblePlan } + consumed = true + return arrays + }) + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26NativePagedProducer.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26NativePagedProducer.swift new file mode 100644 index 0000000000..2dcfd63689 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26NativePagedProducer.swift @@ -0,0 +1,318 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +/// Scalar two-scope metadata only. Session/generation never enter the durable +/// namespace; the host separately binds artifact/template/build/numerics. +/// No public initializer and no native handles cross the store-creation await. +public struct MiMoV26NativePagedPrefixMetadata: Sendable { + public let prefix: MiMoV26NativeCompletePrefixMetadata + public let pagedConfiguration: PagedKVPoolConfig + fileprivate func matches(_ other: Self) -> Bool { + let a = pagedConfiguration + let b = other.pagedConfiguration + return prefix == other.prefix && a.pageSize == b.pageSize + && a.capacityBytes == b.capacityBytes + && a.dtype == b.dtype && a.layerDTypes == b.layerDTypes + && a.gatheredAttention == b.gatheredAttention + && a.segmentSizeBytes == b.segmentSizeBytes + && a.maxPrefillChunk == b.maxPrefillChunk + && a.nominalMaxSequenceLength == b.nominalMaxSequenceLength + && a.maxBufferLength == b.maxBufferLength + && a.prefixSharingBlockSize == b.prefixSharingBlockSize + } +} + +/// Exact strict-loaded validator. Weak native references avoid a second weight +/// owner in an externally retained contract; real resources retain this object. +package final class MiMoV26NativePagedValidator: CBv2NativePagedModelValidating, + CBv2NativeCompletePrefixBindingValidating +{ + private weak var resources: MiMoV26LoadedResources? + private weak var adapter: MiMoV26CBv2Adapter? + private weak var assistant: MiMoV26MTPAssistant? + private let hasAssistant: Bool + private let sessionID, generation: UUID + private let types: [DType] + private let kinds: [CBv2LayerKind] + private let prefixMetadata: MiMoV26NativePagedPrefixMetadata? + init( + resources: MiMoV26LoadedResources, adapter: MiMoV26CBv2Adapter, types: [DType], + prefixMetadata: MiMoV26NativePagedPrefixMetadata? = nil + ) { + self.resources = resources + self.adapter = adapter + assistant = adapter.assistant + hasAssistant = adapter.assistant != nil + sessionID = resources.loaded.receipt.sessionID + generation = resources.nativePagedLifetime.generation + self.types = types + kinds = adapter.layerKinds + self.prefixMetadata = prefixMetadata + } + package func validateNativePagedModel() throws { + guard let resources, let adapter, + resources.loaded.receipt.sessionID == sessionID, + resources.prepared.request.sessionID == sessionID, + resources.nativePagedLifetime.generation == generation, + resources.loaded.receipt.binding == resources.prepared.request.binding, + adapter.target === resources.loaded.bundle.target, + hasAssistant == (adapter.assistant != nil), adapter.assistant === assistant, + !hasAssistant + || (adapter.supportsRequestStatefulMTP + && adapter.assistant?.verificationMode == .serialTarget), + adapter.layerKinds == kinds, adapter.cbv2CompleteCheckpointKVDTypes == types + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + try resources.nativePagedLifetime.requireBinding() + try adapter.validateNativePagedOwner(resources) + } + package func validateNativeCompletePrefixBinding() throws { + guard let expected = prefixMetadata?.prefix, let adapter, + expected.loadSessionID == sessionID, expected.loadedGeneration == generation, + expected.layerKinds == kinds, expected.layerDTypes == types, + expected.maximumContextTokens == adapter.target.configuration.maxPositionEmbeddings, + expected.assistantCodecID == adapter.nativeCompletePrefixAssistantCodecID, + expected.verificationMode == .serialTarget, + expected.backendLayout + == (hasAssistant + ? CBv2CompleteCheckpointManifest.pagedAsymmetricMTPLayout + : CBv2CompleteCheckpointManifest.pagedAsymmetricLayout) + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + // One actual page lifetime, including draining cleanup, owns BOTH + // permissions. No second generation or second process owner is minted. + try validateNativePagedModel() + } +} + +extension MiMoV26LoadedModel { + public func nativePagedCompletePrefixMetadata( + binding: MiMoV26CBv2Binding, + bytesCapacity: Int, maximumConcurrentRequests: Int, maximumQueryTokens: Int, + maximumPrefillChunk: Int, retaining scope: NativeConstructionScope + ) throws + -> MiMoV26NativePagedPrefixMetadata + { + let config = try nativePagedConfiguration( + binding: binding, bytesCapacity: bytesCapacity, + maximumConcurrentRequests: maximumConcurrentRequests, + maximumQueryTokens: maximumQueryTokens, + maximumPrefillChunk: maximumPrefillChunk, retaining: scope) + try binding.adapter.validateNativeCompletePrefixOwner(resources) + guard let types = binding.adapter.cbv2CompleteCheckpointKVDTypes else { + throw MiMoV26CBv2Error.nativeProbeRequired + } + let codec = binding.adapter.nativeCompletePrefixAssistantCodecID + guard (binding.assistant == nil) == (codec == nil) else { + throw MiMoV26MultimodalError.incompatibleOwner + } + let metadata = MiMoV26NativeCompletePrefixMetadata( + modelType: "mimo_v2", + loadSessionID: loadReceipt.sessionID, + loadBindingFingerprint: try loadReceipt.binding.fingerprint(), + loadedGeneration: resources.nativePagedLifetime.generation, + layerKinds: binding.adapter.layerKinds, layerDTypes: types, + maximumContextTokens: nativeConfiguration.maxPositionEmbeddings, + assistantCodecID: codec, + verificationMode: .serialTarget, + backendLayout: codec == nil + ? CBv2CompleteCheckpointManifest.pagedAsymmetricLayout + : CBv2CompleteCheckpointManifest.pagedAsymmetricMTPLayout) + try scope.retainOwner(binding.adapter) + try scope.invalidateOnFailedCompletion(resources.nativePagedLifetime) { + [weak lifetime = resources.nativePagedLifetime] in lifetime?.invalidate() + } + nativePagedPreparation = binding + return .init(prefix: metadata, pagedConfiguration: config) + } + + public func makeNativePagedCompletePrefixExecutionResources( + binding: MiMoV26CBv2Binding, + bytesCapacity: Int, maximumConcurrentRequests: Int, maximumQueryTokens: Int, + maximumPrefillChunk: Int, expectedMetadata: MiMoV26NativePagedPrefixMetadata, + completePrefixCache: any CBv2NativeCompletePrefixCache, + processMemoryOwner: any CBv2ProcessMemoryOwner, + retaining scope: NativeConstructionScope + ) throws -> MiMoV26CBv2NativePagedExecutionResources { + guard let previous = nativePagedPreparation, + expectedMetadata.prefix.loadSessionID == loadReceipt.sessionID, + expectedMetadata.prefix.loadedGeneration == resources.nativePagedLifetime.generation + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + let actual = try nativePagedCompletePrefixMetadata( + binding: binding, bytesCapacity: bytesCapacity, + maximumConcurrentRequests: maximumConcurrentRequests, + maximumQueryTokens: maximumQueryTokens, + maximumPrefillChunk: maximumPrefillChunk, retaining: scope) + guard actual.matches(expectedMetadata) else { + nativePagedPreparation = previous + throw MiMoV26MultimodalError.incompatibleOwner + } + return try issueNativePagedExecutionResources( + binding: binding, expectedAssistant: binding.assistant, + bytesCapacity: bytesCapacity, maximumConcurrentRequests: maximumConcurrentRequests, + maximumQueryTokens: maximumQueryTokens, maximumPrefillChunk: maximumPrefillChunk, + processMemoryOwner: processMemoryOwner, retaining: scope, + completePrefixCache: completePrefixCache, prefixMetadata: actual) + } + + /// Existing target-only issuer. A caller cannot upgrade its meaning by + /// handing it an MTP binding; the explicit serial-MTP issuer is separate. + /// All handles remain actor-local inside + /// the already owned protected assembly operation. + public func makeNativePagedExecutionResources( + binding: MiMoV26CBv2Binding, + bytesCapacity: Int, maximumConcurrentRequests: Int, maximumQueryTokens: Int, + maximumPrefillChunk: Int, processMemoryOwner: any CBv2ProcessMemoryOwner, + retaining scope: NativeConstructionScope + ) throws -> MiMoV26CBv2NativePagedExecutionResources { + guard binding.assistant == nil else { throw MiMoV26MultimodalError.incompatibleOwner } + return try issueNativePagedExecutionResources( + binding: binding, expectedAssistant: nil, + bytesCapacity: bytesCapacity, maximumConcurrentRequests: maximumConcurrentRequests, + maximumQueryTokens: maximumQueryTokens, maximumPrefillChunk: maximumPrefillChunk, + processMemoryOwner: processMemoryOwner, retaining: scope) + } + + /// Explicit genuine trained-head serialTarget composition. No Boolean or + /// requested profile string substitutes for this actual bound assistant. + public func makeNativePagedSerialMTPExecutionResources( + binding: MiMoV26CBv2Binding, + bytesCapacity: Int, maximumConcurrentRequests: Int, maximumQueryTokens: Int, + maximumPrefillChunk: Int, processMemoryOwner: any CBv2ProcessMemoryOwner, + retaining scope: NativeConstructionScope + ) throws -> MiMoV26CBv2NativePagedExecutionResources { + guard let assistant = binding.assistant, assistant.verificationMode == .serialTarget else { + throw MiMoV26MultimodalError.incompatibleOwner + } + return try issueNativePagedExecutionResources( + binding: binding, expectedAssistant: assistant, + bytesCapacity: bytesCapacity, maximumConcurrentRequests: maximumConcurrentRequests, + maximumQueryTokens: maximumQueryTokens, maximumPrefillChunk: maximumPrefillChunk, + processMemoryOwner: processMemoryOwner, retaining: scope) + } + + private func issueNativePagedExecutionResources( + binding: MiMoV26CBv2Binding, + expectedAssistant: MiMoV26MTPAssistant?, bytesCapacity: Int, + maximumConcurrentRequests: Int, maximumQueryTokens: Int, maximumPrefillChunk: Int, + processMemoryOwner: any CBv2ProcessMemoryOwner, + retaining scope: NativeConstructionScope, + completePrefixCache: (any CBv2NativeCompletePrefixCache)? = nil, + prefixMetadata: MiMoV26NativePagedPrefixMetadata? = nil + ) throws -> MiMoV26CBv2NativePagedExecutionResources { + guard binding.assistant === expectedAssistant, + (completePrefixCache != nil) == (prefixMetadata != nil) + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + let config = try nativePagedConfiguration( + binding: binding, bytesCapacity: bytesCapacity, + maximumConcurrentRequests: maximumConcurrentRequests, + maximumQueryTokens: maximumQueryTokens, + maximumPrefillChunk: maximumPrefillChunk, retaining: scope) + try resources.nativePagedLifetime.beginIssuance() + // The single paged lifetime owns the optional joint prefix. Contiguous + // media/prefix alternatives cannot issue a competing tuple afterward. + resources.nativePrefixLifetime.invalidate() + let validator = MiMoV26NativePagedValidator( + resources: resources, + adapter: binding.adapter, types: config.layerDTypes!, prefixMetadata: prefixMetadata) + resources.nativePagedValidator = validator + nativePagedPreparation = binding + do { + try scope.retainOwner(validator) + try scope.retainOwner(binding.adapter) + try scope.retainOwner(processMemoryOwner) + if let completePrefixCache { try scope.retainOwner(completePrefixCache) } + try scope.invalidateOnFailedCompletion(resources.nativePagedLifetime) { + [weak lifetime = resources.nativePagedLifetime] in lifetime?.invalidate() + } + let issued = try binding.adapter.makeNativePagedResources( + config: config, + processMemoryOwner: processMemoryOwner, loadedOwner: resources, + validator: validator, retaining: scope, + completePrefixCache: completePrefixCache, + completePrefixValidator: prefixMetadata == nil ? nil : validator) + try resources.nativePagedLifetime.recordContract(issued.contract.id) + return issued + } catch { + resources.nativePagedLifetime.invalidate() + throw error + } + } + + private func nativePagedConfiguration( + binding: MiMoV26CBv2Binding, + bytesCapacity: Int, maximumConcurrentRequests: Int, maximumQueryTokens: Int, + maximumPrefillChunk: Int, retaining scope: NativeConstructionScope + ) throws -> PagedKVPoolConfig { + try scope.requireImmutableLoadedOwner(resources) + try resources.nativePagedLifetime.requirePreparation() + try resources.nativePrefixLifetime.requirePreparation() + guard !hasIssuedManagedMediaProfile, nativeCompletePrefixPreparation == nil, + resources.audioSidecar == nil, + resources.loaded.receipt.sessionID == resources.prepared.request.sessionID, + resources.loaded.receipt.binding == resources.prepared.request.binding, + binding.adapter.target === resources.loaded.bundle.target, + binding.assistant === binding.adapter.assistant, + binding.assistant == nil + || (binding.adapter.supportsRequestStatefulMTP + && binding.assistant?.verificationMode == .serialTarget), + binding.mediaGeneration === resources.mediaGeneration, + let types = binding.adapter.cbv2CompleteCheckpointKVDTypes, + types.count == binding.adapter.layerKinds.count, + types.allSatisfy({ $0 == .bfloat16 || $0 == .float16 }), + bytesCapacity > 0, maximumConcurrentRequests > 0, + maximumPrefillChunk > 0, maximumQueryTokens >= maximumPrefillChunk, + maximumQueryTokens <= nativeConfiguration.maxPositionEmbeddings + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + if let previous = nativePagedPreparation { + try previous.adapter.validateNativePagedOwner(resources) + } + let maximumBuffer: Int + #if os(macOS) || os(iOS) || os(tvOS) || os(visionOS) + guard Device.defaultDevice().deviceType == .gpu, + StreamOrDevice.default.stream == MLX.Stream.gpu + else { + throw CBv2KVError.backendIneligible( + reason: "native paged target requires actual default GPU stream") + } + maximumBuffer = GPU.deviceInfo().maxBufferSize + guard maximumBuffer > 0 else { throw MiMoV26MultimodalError.incompatibleOwner } + #else + throw CBv2KVError.backendIneligible(reason: "native paged target requires Metal") + #endif + let limits = try CBv2PagedGatheredAttentionLimits( + maximumBatchSize: maximumConcurrentRequests, maximumQueryTokens: maximumQueryTokens, + maximumContextTokens: nativeConfiguration.maxPositionEmbeddings, + maximumInFlightGraphs: 2, maximumScratchBytes: bytesCapacity, + admissionMode: .stepOwned(.pinnedMetal)) + return PagedKVPoolConfig( + capacityBytes: bytesCapacity, dtype: types[0], + maxPrefillChunk: maximumPrefillChunk, + nominalMaxSequenceLength: nativeConfiguration.maxPositionEmbeddings, + maxBufferLength: maximumBuffer, prefixSharingBlockSize: nil, + segmentSizeBytes: min(64 << 20, maximumBuffer), layerDTypes: types, + gatheredAttention: limits) + } + + public func beginNativePagedRetirement(executionContractID: UUID) throws { + try resources.nativePagedLifetime.beginDrain(contract: executionContractID) + } + + public func releaseNativePagedAfterNativeRetirement(_ receipt: CBv2NativeShutdownReceipt) throws + { + try resources.nativePagedLifetime.retire(receipt) + nativePagedPreparation = nil + resources.nativePagedValidator = nil + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26NativePrefixProducer.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26NativePrefixProducer.swift new file mode 100644 index 0000000000..dce8937e4a --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26NativePrefixProducer.swift @@ -0,0 +1,262 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +/// Scalar, immutable two-scope revalidation only. Load-session/generation and +/// binding fingerprint MUST NOT become a durable prefix namespace. The provider +/// separately binds verified artifact/template/build/numerics/tenant identity. +public struct MiMoV26NativeCompletePrefixMetadata: Sendable, Equatable { + public let modelType: String + public let loadSessionID: UUID + public let loadBindingFingerprint: String + public let loadedGeneration: UUID + public let layerKinds: [CBv2LayerKind] + public let layerDTypes: [DType] + public let maximumContextTokens: Int + public let assistantCodecID: String? + public let verificationMode: CBv2MTPVerificationMode + public let backendLayout: String + // No public initializer: metadata comes from the actual strict-loaded + // owner and the adapter's completed native type probe, not caller claims. +} + +/// Only lifecycle scalars are synchronized here. No model, array, provider +/// callback, reservation or evaluator is stored in this lock. +final class MiMoV26NativePrefixLifetime { + let loadSessionID: UUID + let generation = UUID() + private enum Phase: Equatable { case active, draining, invalid, retired } + private let lock = NSLock() + private var phase = Phase.active + private var issuanceStarted = false + private var contractID: UUID? + + init(loadSessionID: UUID) { self.loadSessionID = loadSessionID } + func requirePreparation() throws { + try lock.withLock { + guard phase == .active, !issuanceStarted else { + throw MiMoV26MultimodalError.invalidatedOwner + } + } + } + func beginIssuance() throws { + try lock.withLock { + guard phase == .active, !issuanceStarted else { + throw MiMoV26MultimodalError.invalidatedOwner + } + issuanceStarted = true + } + } + func recordContract(_ id: UUID) throws { + try lock.withLock { + guard phase == .active, issuanceStarted, contractID == nil else { + throw MiMoV26MultimodalError.invalidatedOwner + } + contractID = id + } + } + func requireBinding() throws { + try lock.withLock { + // Common beginLoan(importing) refuses NEW imports once shutdown + // is requested. Existing owned work still needs cleanup validity. + guard issuanceStarted, phase == .active || phase == .draining else { + throw MiMoV26MultimodalError.invalidatedOwner + } + } + } + func beginDrain(contract: UUID) throws { + try lock.withLock { + guard contractID == contract, phase == .active || phase == .draining else { + throw MiMoV26MultimodalError.incompatibleOwner + } + phase = .draining + } + } + func retire(_ receipt: CBv2NativeShutdownReceipt) throws { + try lock.withLock { + guard receipt.executionContractID == contractID, receipt.generation == 1, + phase == .active || phase == .draining + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + phase = .retired + } + } + func invalidate() { lock.withLock { phase = .invalid } } +} + +/// Kept by the real loaded resources, not by a public callback or a standalone +/// marker. Both references are weak: the adapter already owns those resources, +/// and a completed external contract must not create a second weight owner. +package final class MiMoV26NativeCompletePrefixValidator: CBv2NativeCompletePrefixBindingValidating +{ + private weak var resources: MiMoV26LoadedResources? + private weak var adapter: MiMoV26CBv2Adapter? + private let expected: MiMoV26NativeCompletePrefixMetadata + + init( + resources: MiMoV26LoadedResources, adapter: MiMoV26CBv2Adapter, + expected: MiMoV26NativeCompletePrefixMetadata + ) { + self.resources = resources + self.adapter = adapter + self.expected = expected + } + package func validateNativeCompletePrefixBinding() throws { + guard let resources, let adapter, + resources.loaded.receipt.sessionID == expected.loadSessionID, + resources.prepared.request.sessionID == expected.loadSessionID, + resources.nativePrefixLifetime.loadSessionID == expected.loadSessionID, + resources.nativePrefixLifetime.generation == expected.loadedGeneration, + adapter.target === resources.loaded.bundle.target, + adapter.layerKinds == expected.layerKinds, + adapter.cbv2CompleteCheckpointKVDTypes == expected.layerDTypes, + adapter.nativeCompletePrefixAssistantCodecID == expected.assistantCodecID, + (adapter.assistant?.verificationMode ?? .serialTarget) == expected.verificationMode + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + try resources.nativePrefixLifetime.requireBinding() + // Checks actual current assistant/weight generation and completed KV + // probe metadata. No parameter traversal, array read or native call. + try adapter.validateNativeCompletePrefixOwner(resources) + } + func invalidate() { resources?.nativePrefixLifetime.invalidate() } +} + +extension MiMoV26LoadedModel { + /// First protected scope. Only this DTO may cross the provider's store + /// registration await. Native preparation remains with this loaded wrapper. + public func nativeCompletePrefixMetadata( + binding: MiMoV26CBv2Binding, + retaining scope: NativeConstructionScope + ) throws -> MiMoV26NativeCompletePrefixMetadata { + try resources.nativePrefixLifetime.requirePreparation() + try scope.requireImmutableLoadedOwner(resources) + if let previous = nativeCompletePrefixPreparation { + // A fresh adapter cannot conceal a stale trained-head generation + // in the preparation that crossed the host's registration await. + try previous.binding.adapter.validateNativeCompletePrefixOwner(resources) + } + guard !hasIssuedManagedMediaProfile, + binding.adapter.target === resources.loaded.bundle.target, + binding.assistant === binding.adapter.assistant, + binding.mediaGeneration === resources.mediaGeneration, + resources.loaded.receipt.sessionID == resources.prepared.request.sessionID, + resources.loaded.receipt.binding == resources.prepared.request.binding + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + try binding.adapter.validateNativeCompletePrefixOwner(resources) + guard let types = binding.adapter.cbv2CompleteCheckpointKVDTypes else { + throw MiMoV26CBv2Error.nativeProbeRequired + } + let codecID = binding.adapter.nativeCompletePrefixAssistantCodecID + guard (binding.assistant == nil) == (codecID == nil) else { + throw MiMoV26MultimodalError.incompatibleOwner + } + let metadata = MiMoV26NativeCompletePrefixMetadata( + modelType: "mimo_v2", + loadSessionID: loadReceipt.sessionID, + loadBindingFingerprint: try loadReceipt.binding.fingerprint(), + loadedGeneration: resources.nativePrefixLifetime.generation, + layerKinds: binding.adapter.layerKinds, layerDTypes: types, + maximumContextTokens: nativeConfiguration.maxPositionEmbeddings, + assistantCodecID: codecID, + verificationMode: binding.assistant?.verificationMode ?? .serialTarget, + backendLayout: codecID == nil + ? CBv2CompleteCheckpointManifest.contiguousAsymmetricLayout + : CBv2CompleteCheckpointManifest.contiguousAsymmetricMTPLayout) + try scope.retainOwner(binding.adapter) + try scope.invalidateOnFailedCompletion(resources.nativePrefixLifetime) { + [weak lifetime = resources.nativePrefixLifetime] in + lifetime?.invalidate() + } + nativeCompletePrefixPreparation = (metadata, binding) + return metadata + } + + /// Second protected scope, after the host registers the ACTUAL store and + /// process ledger owner. The caller assembles its engine locally; these + /// native handles are not Sendable and must not cross the provider await. + public func makeNativeCompletePrefixExecutionResources( + binding: MiMoV26CBv2Binding, + bytesCapacity: Int, expectedMetadata: MiMoV26NativeCompletePrefixMetadata, + completePrefixCache: any CBv2NativeCompletePrefixCache, + processMemoryOwner: any CBv2ProcessMemoryOwner, + retaining scope: NativeConstructionScope + ) throws -> MiMoV26CBv2NativeExecutionResources { + let validator = try beginNativeCompletePrefixIssuance( + binding: binding, + expectedMetadata: expectedMetadata, retaining: scope) + do { + let issued = try binding.adapter.makeNativeCompletePrefixResources( + bytesCapacity: bytesCapacity, + loadedOwner: resources, validator: validator, + completePrefixCache: completePrefixCache, + processMemoryOwner: processMemoryOwner, retaining: scope) + try finishNativeCompletePrefixIssuance(issued.contract) + return issued + } catch { + failNativeCompletePrefixIssuance() + throw error + } + } + + /// Shared only by the protected text and joint-media issuers. Metadata is + /// checked BEFORE the one-shot transition, so a foreign DTO cannot consume + /// a valid preparation. No raw owner or validator is publicly returned. + func beginNativeCompletePrefixIssuance( + binding: MiMoV26CBv2Binding, + expectedMetadata: MiMoV26NativeCompletePrefixMetadata, + retaining scope: NativeConstructionScope + ) throws -> MiMoV26NativeCompletePrefixValidator { + guard let prepared = nativeCompletePrefixPreparation, prepared.metadata == expectedMetadata + else { + throw MiMoV26MultimodalError.incompatibleOwner + } + let actual = try nativeCompletePrefixMetadata(binding: binding, retaining: scope) + guard actual == expectedMetadata else { + nativeCompletePrefixPreparation = prepared + throw MiMoV26MultimodalError.incompatibleOwner + } + try resources.nativePrefixLifetime.beginIssuance() + let validator = MiMoV26NativeCompletePrefixValidator( + resources: resources, + adapter: binding.adapter, expected: actual) + resources.nativePrefixValidator = validator + do { + try scope.retainOwner(validator) + try scope.invalidateOnFailedCompletion(validator) { [weak validator] in + validator?.invalidate() + } + return validator + } catch { + resources.nativePrefixLifetime.invalidate() + throw error + } + } + + func finishNativeCompletePrefixIssuance(_ contract: CBv2NativeExecutionContract) throws { + try resources.nativePrefixLifetime.recordContract(contract.id) + } + func failNativeCompletePrefixIssuance() { resources.nativePrefixLifetime.invalidate() } + + /// Host teardown notification only. Does not fence, free, stop an engine or + /// grant credit. The host must also start the real EngineV2 shutdown gate. + public func beginNativeCompletePrefixRetirement(executionContractID: UUID) throws { + try resources.nativePrefixLifetime.beginDrain(contract: executionContractID) + } + + /// An authentic one-use SDK contract receipt, AFTER host consumer proofs. + /// Dropping preparation/validator aliases is not physical memory credit. + public func releaseNativeCompletePrefixAfterNativeRetirement( + _ receipt: CBv2NativeShutdownReceipt + ) throws { + try resources.nativePrefixLifetime.retire(receipt) + nativeCompletePrefixPreparation = nil + resources.nativePrefixValidator = nil + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26PackedModuleLoader.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26PackedModuleLoader.swift new file mode 100644 index 0000000000..a98850b455 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26PackedModuleLoader.swift @@ -0,0 +1,50 @@ +// Copyright © 2026 Eigen Labs. +import MLXLLM +import MLXLMCommon +import MLXNN + +enum MiMoV26PackedModuleLoader { + /// Constructs packed module shells only. Their lazy initializer parameters + /// are replaced by authenticated checkpoint arrays before any evaluation. + static func prepare(_ model: Module, policies: [String: MiMoV26Quantization.Policy]) throws { + let leaves = Dictionary(uniqueKeysWithValues: model.leafModules().flattened()) + var parents = Dictionary(uniqueKeysWithValues: model.namedModules()) + parents[""] = model + var replacements: [String: [(String, Module)]] = [:] + for path in policies.keys.sorted() { + let policy = policies[path]! + guard let leaf = leaves[path], !(leaf is Quantized), + leaf is Linear || leaf is Embedding || leaf is SwitchLinear, + let replacement = quantizeSingle( + layer: leaf, groupSize: policy.groupSize, bits: policy.bits, + mode: policy.mode == "mxfp4" ? .mxfp4 : .affine) + else { + throw MiMoV26ConvertedLoadError.incompatibleModule(path) + } + // Start at the real containing Module, not a sparse root update + // through layers[0] when only later MoE layers change. Arrays such + // as all speech embeddings are grouped under their actual owner. + var pieces = path.split(separator: ".").map(String.init) + pieces.removeLast() + while !pieces.isEmpty && parents[pieces.joined(separator: ".")] == nil { + pieces.removeLast() + } + let parent = pieces.joined(separator: ".") + let relative = parent.isEmpty ? path : String(path.dropFirst(parent.count + 1)) + replacements[parent, default: []].append((relative, replacement)) + } + for parent in replacements.keys.sorted() { + do { + try parents[parent]!.update( + modules: .unflattened(replacements[parent]!), verify: .noUnusedKeys) + } catch { throw MiMoV26ConvertedLoadError.incompatibleModule(parent) } + } + let installed = Set( + model.leafModules().flattened().compactMap { path, module in + module is Quantized ? path : nil + }) + guard installed == Set(policies.keys) else { + throw MiMoV26ConvertedLoadError.incompatibleModule("quantized module closure") + } + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26Pixels.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26Pixels.swift new file mode 100644 index 0000000000..0671d8fd1f --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26Pixels.swift @@ -0,0 +1,226 @@ +// Copyright © 2026 Eigen Labs. +// Decoded-RGB scalar preparation derived from SGLang (Apache-2.0), commit +// 67bb6a58d0dad4a39af80fa1b2bf86f0de0cb99b, processors/mimo_v2.py. +// F.interpolate(float, mode="bilinear", align_corners=false, antialias=false), +// then native 0...255 ImageNet normalization and spatiotemporal patch ordering. +// No image codecs, alpha/EXIF policy, frame sampling, MLX arrays or model load. +import Foundation + +public enum MiMoV26Pixels { + public enum Failure: Error, Equatable, Sendable { + case invalidInput(String) + case resourceLimit(String) + case overflow(String) + } + + /// Already color/alpha/orientation-resolved RGB, planar CHW, range0...255. + /// A caller must not pass normalized0...1 values as though they were pixels. + public struct DecodedRGB: Sendable { + public let height, width: Int + public let planarRGB: [Float] + + public init(height: Int, width: Int, planarRGB: [Float]) { + self.height = height + self.width = width + self.planarRGB = planarRGB + } + } + + /// Explicit caller resource admission. Byte accounting bounds logical + /// buffers including retained inputs; it is not an allocator/RSS guarantee. + public struct Limits: Sendable { + public let maximumInputElements, maximumOutputElements, maximumWorkingBytes: Int + + public init(maximumInputElements: Int, maximumOutputElements: Int, maximumWorkingBytes: Int) + { + self.maximumInputElements = maximumInputElements + self.maximumOutputElements = maximumOutputElements + self.maximumWorkingBytes = maximumWorkingBytes + } + } + + public struct Prepared: Sendable { + public let geometry: MiMoV26MediaGeometry.Plan + /// Row-major[patchCount,patchVectorSize], Float32, ready for the native + /// patch projection. This is not a tensor allocation or a tower result. + public let patchValues: [Float] + public let inputElementCount, plannedWorkingBytes: Int + } + + private struct AxisSample { + let lower, upper: Int + let lowerWeight, upperWeight: Float + } + private static let means: [Float] = [123.675, 116.28, 103.53] + private static let deviations: [Float] = [58.395, 57.12, 57.375] + + public static func image( + _ frame: DecodedRGB, settings: MiMoV26MediaGeometry.Settings, + limits: Limits + ) throws -> Prepared { + let plan = try MiMoV26MediaGeometry.image( + height: frame.height, width: frame.width, settings: settings) + return try prepare(frames: [frame], plan: plan, settings: settings, limits: limits) + } + + /// `frames` contains the entire already-sampled clip. Segment selection, + /// timestamps and decoder sampling belong to a separate upstream boundary; + /// a mismatched divisor must not silently alter the native resize budget. + public static func video( + frames: [DecodedRGB], sampledFrameCount: Int, + settings: MiMoV26MediaGeometry.Settings, limits: Limits + ) throws -> Prepared { + guard !frames.isEmpty, frames.count == sampledFrameCount, let first = frames.first else { + throw Failure.invalidInput("sampled frame count must match the decoded clip") + } + let plan = try MiMoV26MediaGeometry.video( + height: first.height, width: first.width, + sampledFrames: sampledFrameCount, settings: settings) + return try prepare(frames: frames, plan: plan, settings: settings, limits: limits) + } + + private static func prepare( + frames: [DecodedRGB], plan: MiMoV26MediaGeometry.Plan, + settings: MiMoV26MediaGeometry.Settings, limits: Limits + ) throws -> Prepared { + guard limits.maximumInputElements > 0, limits.maximumOutputElements > 0, + limits.maximumWorkingBytes > 0, let first = frames.first + else { + throw Failure.invalidInput("invalid resource limits or empty frames") + } + let frameElements = try product([3, first.height, first.width], "input frame") + let inputElements = try product([frameElements, frames.count], "input clip") + guard inputElements <= limits.maximumInputElements, + plan.patchElementCount <= limits.maximumOutputElements + else { + throw Failure.resourceLimit("input/output element bound") + } + // Exact integer coordinates within Float's native input arithmetic. + // Larger decoded/resized axes need a separately qualified path. + guard + [first.height, first.width, plan.height, plan.width].allSatisfy({ + $0 > 0 && $0 <= 16_777_216 + }) + else { + throw Failure.invalidInput("pixel axis exceeds exact Float integer range") + } + let inputBytes = try product([inputElements, MemoryLayout.stride], "input bytes") + let outputBytes = try product( + [plan.patchElementCount, MemoryLayout.stride], "output bytes") + let axisEntries = try sum(plan.height, plan.width, "axis entries") + let axisBytes = try product([axisEntries, MemoryLayout.stride], "axis bytes") + let frameBytes = try product( + [frames.count, MemoryLayout.stride], "frame metadata") + // Include array/plan descriptors and a fixed allowance for stack/value + // descriptors. No resized, normalized, padded or copied-frame array is + // materialized; all pixel work writes directly into the final buffer. + let overhead = try sum(frameBytes, 1024, "metadata bytes") + let bytes = try sum( + try sum(inputBytes, outputBytes, "input/output bytes"), + try sum(axisBytes, overhead, "scratch bytes"), "working bytes") + guard bytes <= limits.maximumWorkingBytes else { + throw Failure.resourceLimit("planned working bytes") + } + for frame in frames { + guard frame.height == first.height, frame.width == first.width, + frame.planarRGB.count == frameElements + else { + throw Failure.invalidInput( + "all RGB frames must have matching complete CHW dimensions") + } + guard frame.planarRGB.allSatisfy({ $0.isFinite && $0 >= 0 && $0 <= 255 }) else { + throw Failure.invalidInput("decoded RGB must contain finite0...255 pixels") + } + } + + let horizontal = samples(input: first.width, output: plan.width) + let vertical = samples(input: first.height, output: plan.height) + var patches = [Float](repeating: 0, count: plan.patchElementCount) + var destination = 0 + let patch = settings.patchSize + let merge = settings.mergeSize + let temporal = settings.temporalPatchSize + let sourcePlane = first.height * first.width // Checked frame product. + // Reference view(Tgroup,Tinner,C,Hgroup,Hinner,Py,Wgroup,Winner,Px) + // permutes to(Tgroup,Hgroup,Wgroup,Hinner,Winner,C,Tinner,Py,Px). + for groupT in 0 ..< plan.gridT { + for groupH in 0 ..< (plan.gridH / merge) { + for groupW in 0 ..< (plan.gridW / merge) { + for innerH in 0 ..< merge { + for innerW in 0 ..< merge { + for channel in 0 ..< 3 { + for innerT in 0 ..< temporal { + let sourceFrame = min( + groupT * temporal + innerT, frames.count - 1) + let source = frames[sourceFrame].planarRGB + for patchY in 0 ..< patch { + let y = vertical[(groupH * merge + innerH) * patch + patchY] + for patchX in 0 ..< patch { + let x = horizontal[ + (groupW * merge + innerW) * patch + patchX] + let base = channel * sourcePlane + let top = + x.lowerWeight + * source[base + y.lower * first.width + x.lower] + + x.upperWeight + * source[base + y.lower * first.width + x.upper] + let bottom = + x.lowerWeight + * source[base + y.upper * first.width + x.lower] + + x.upperWeight + * source[base + y.upper * first.width + x.upper] + let resized = + y.lowerWeight * top + y.upperWeight * bottom + patches[destination] = + (resized - means[channel]) / deviations[channel] + destination += 1 + } + } + } + } + } + } + } + } + } + guard destination == plan.patchElementCount else { + throw Failure.invalidInput("internal patch accounting") + } + return Prepared( + geometry: plan, patchValues: patches, inputElementCount: inputElements, + plannedWorkingBytes: bytes) + } + + private static func samples(input: Int, output: Int) -> [AxisSample] { + let ratio = Float(input) / Float(output) + return (0 ..< output).map { index in + if input == output { + return AxisSample(lower: index, upper: index, lowerWeight: 1, upperWeight: 0) + } + // Native align_corners=false half-pixel coordinates, clipped at + // the left edge; the right neighbor is clamped to the last pixel. + let coordinate = max(Float(0), ratio * (Float(index) + 0.5) - 0.5) + let lower = min(Int(floor(coordinate)), input - 1) + let upper = min(lower + 1, input - 1) + let weight = min(max(coordinate - Float(lower), 0), 1) + return AxisSample( + lower: lower, upper: upper, lowerWeight: 1 - weight, upperWeight: weight) + } + } + + private static func product(_ values: [Int], _ field: String) throws -> Int { + var result = 1 + for value in values { + guard value > 0 else { throw Failure.invalidInput(field) } + let next = result.multipliedReportingOverflow(by: value) + guard !next.overflow else { throw Failure.overflow(field) } + result = next.partialValue + } + return result + } + private static func sum(_ lhs: Int, _ rhs: Int, _ field: String) throws -> Int { + let result = lhs.addingReportingOverflow(rhs) + guard !result.overflow else { throw Failure.overflow(field) } + return result.partialValue + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26ResidualVectorQuantizer.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26ResidualVectorQuantizer.swift new file mode 100644 index 0000000000..48446d2de3 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26ResidualVectorQuantizer.swift @@ -0,0 +1,88 @@ +// Copyright © 2026 Eigen Labs. HF5711 residual quantizer (Apache-2.0). +// Original source copyright 2026 Xiaomi Corporation and HuggingFace Inc. +// SPDX-License-Identifier: Apache-2.0 +import Foundation +import MLX +import MLXLLM + +public struct MiMoV26AudioQuantizedCodes { + public let codes: MLXArray + /// Must be evaluated and checked before any IDs are published. + public let allFinite: MLXArray + public let frameCounts: [Int] + fileprivate init(codes: MLXArray, allFinite: MLXArray, frameCounts: [Int]) { + self.codes = codes + self.allFinite = allFinite + self.frameCounts = frameCounts + } +} + +/// No EMA/init state and no decoder. Runtime tables hold F32 values after the +/// selected loader's BF16 roundtrip; source storage bytes remain untouched. +public final class MiMoV26ResidualVectorQuantizer { + public let configuration: MiMoV26AudioInputConfiguration + private let tables: [MLXArray] + public var materializationRoots: [MLXArray] { tables } + public init(configuration: MiMoV26AudioInputConfiguration, sourceTables: [MLXArray]) throws { + guard sourceTables.count == configuration.quantizers, + zip(sourceTables, configuration.codebookSizes).allSatisfy({ + $0.0.shape == [$0.1, configuration.hiddenSize] && $0.0.dtype == .float32 + }) + else { + throw MiMoV26AudioInputError.weights("RVQ source table shape/dtype/order") + } + self.configuration = configuration + tables = sourceTables.map { $0.asType(.bfloat16).asType(.float32) } + } + + public func quantize( + features: MLXArray, frameCounts: [Int], tileFrames: Int, + isCancelled: () -> Bool = { false } + ) throws -> MiMoV26AudioQuantizedCodes { + let frames = try frameCounts.reduce(0) { + try MiMoV26AudioChecked.add($0, $1, "RVQ frame sum") + } + guard frameCounts.allSatisfy({ $0 > 0 }), tileFrames > 0, tileFrames <= Int(Int32.max), + features.shape == [frames, configuration.hiddenSize], + [.bfloat16, .float32].contains(features.dtype) + else { + throw MiMoV26AudioInputError.input("RVQ feature/length/tile contract") + } + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + var valid = all(isFinite(features)) + var blocks: [MLXArray] = [] + for table in tables { valid = valid .&& all(isFinite(table)) } + for start in stride(from: 0, to: frames, by: tileFrames) { + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + let end = min(frames, start + tileFrames) + var residual = features[start ..< end].asType(.float32) + var indices: [MLXArray] = [] + for table in tables { + if isCancelled() { throw MiMoV26AudioInputError.cancelled } + // Python precedence is (2*x) @ embed, followed by the two + // additions/subtractions in this order, all F32. + let distance = + sum(residual * residual, axis: 1, keepDims: true) + - matmul(Float(2) * residual, table.transposed()) + + sum(table * table, axis: 1).expandedDimensions(axis: 0) + valid = valid .&& all(isFinite(distance)) + let best = min(distance, axis: 1, keepDims: true) + // Explicit first-index ties, independent of arg-reduction + // scheduling. Invalid rows use safe index0 but never publish. + let candidates = MLX.where( + distance .== best, MLXArray(0 ..< table.dim(0)), Int32.max) + let first = min(candidates, axis: 1) + let selected = MLX.where(isFinite(best.squeezed(axis: 1)), first, Int32(0)).asType( + .int32) + residual = residual - take(table, selected, axis: 0) + indices.append(selected) + } + blocks.append(stacked(indices, axis: 1)) + } + let codes = + blocks.isEmpty + ? MLXArray.zeros([0, configuration.quantizers], dtype: .int32) + : blocks.count == 1 ? blocks[0] : concatenated(blocks, axis: 0) + return .init(codes: codes, allFinite: valid, frameCounts: frameCounts) + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26SerialLoad.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26SerialLoad.swift new file mode 100644 index 0000000000..a2f4d096c3 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26SerialLoad.swift @@ -0,0 +1,321 @@ +// Copyright © 2026 Eigen Labs. +import CryptoKit +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +public enum MiMoV26SerialLoadError: Error, Equatable, Sendable { + case alreadyConsumed, reservationMismatch, insufficientReservation + case cancelled, invalidSourceHandles, unmaterializedSource, unsupportedScope +} + +/// Root-bundle identity only. External audio-tokenizer/DFlash/original-head +/// assets are not authorized by this request and have no loading entrypoint here. +public struct MiMoV26SerialLoadBinding: Equatable, Encodable, Sendable { + public struct Shard: Equatable, Encodable, Sendable { + public let name: String + public let object: MiMoV26FilesystemObjectState + public let headerSHA256: String + public let tensorBytes: Int + } + public let contract, scope, canonicalRoot: String + public let configurationObject, indexObject: MiMoV26FilesystemObjectState + public let configSHA256, indexSHA256, descriptorSHA256: String + public let sourceRepository, sourceRevision, conversionManifestSHA256: String + public let payloadVerificationReceiptSHA256: String? + public let shards: [Shard] + public let rootFileBytes, tensorBytes, metadataBytesRead: Int + public let estimate: MiMoV26LoadFootprint.Estimate + + fileprivate init(plan: MiMoV26FilesystemLoadPlan, estimate: MiMoV26LoadFootprint.Estimate) { + contract = MiMoV26LoadFootprint.contract + scope = "root-bundle-only" + canonicalRoot = plan.canonicalRoot.path + configurationObject = plan.configurationObject + indexObject = plan.indexObject + configSHA256 = plan.bundlePlan.configSHA256 + indexSHA256 = plan.bundlePlan.indexSHA256 + descriptorSHA256 = plan.bundlePlan.descriptorSHA256 + let provenance = plan.bundlePlan.provenance + sourceRepository = provenance.sourceRepository + sourceRevision = provenance.sourceRevision + conversionManifestSHA256 = provenance.conversionManifestSHA256 + payloadVerificationReceiptSHA256 = provenance.payloadVerificationReceiptSHA256 + shards = plan.shards.map { + .init( + name: $0.name, object: $0.objectState, + headerSHA256: $0.headerSHA256, tensorBytes: $0.tensorBytes) + } + rootFileBytes = plan.totalFileBytes + tensorBytes = plan.bundlePlan.tensorBytes + metadataBytesRead = plan.metadataBytesRead + self.estimate = estimate + } + + public func fingerprint() throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return SHA256.hash(data: try encoder.encode(self)).map { String(format: "%02x", $0) } + .joined() + } +} + +/// Created only by the serial transaction, never from an asserted policy name. +/// The nonce prevents a reservation for another session—even the same files— +/// from being silently reused. Hashes are prior evidence references, not a fresh +/// payload readback or a filesystem immutability guarantee. +public struct MiMoV26SerialLoadRequest: Equatable, Sendable { + public let sessionID: UUID + public let binding: MiMoV26SerialLoadBinding + public var requiredLoadBytes: UInt64 { binding.estimate.totalBytes } + fileprivate init(binding: MiMoV26SerialLoadBinding) { + sessionID = UUID() + self.binding = binding + } +} + +public enum MiMoV26SerialLoadPhase: String, Codable, Sendable { + case admitted, sourceHandles, sourceMaterialization, parameterMaterialization, complete +} +public struct MiMoV26SerialLoadProgress: Sendable { + public let phase: MiMoV26SerialLoadPhase + public let sourceTensorsCompleted, sourceTensorCount: Int + /// Owner-proven source payload already synchronously evaluated. This is + /// NOT process memory, allocator peak or an inferred global-memory delta. + public let materializedSourcePayloadBytes: UInt64 + public let parametersCompleted, parameterCount: Int + public let currentShard, currentTensor: String? +} + +/// Host-owned real allocation permit. The provider implementation must bind an +/// actual pending-load owner, current policy and activation/KV/other commitments; +/// a diagnostic implementation must label its narrower scope. Metadata alone +/// is never a permit. Validation is synchronous at safe native boundaries. +/// +/// The host retains/reconciles this owner through publication or actual resource +/// retirement. This SDK never releases host credit automatically. In particular +/// it must not infer materialization credit from unrelated MLX usage changes. +public protocol MiMoV26SerialLoadReservation: AnyObject { + var request: MiMoV26SerialLoadRequest { get } + var reservedLoadBytes: UInt64 { get } + func validateActive(progress: MiMoV26SerialLoadProgress) throws +} + +public struct MiMoV26SerialLoadReceipt: Encodable, Sendable { + public let sessionID: UUID + public let binding: MiMoV26SerialLoadBinding + public let sourceTensorCount, parameterCount: Int + public let materializedSourcePayloadBytes: UInt64 + public let payloadHashesRecomputed = false + public let externalComponentsLoaded = false + public let materializationPolicy = "serial-source-then-serial-verified-parameters" +} + +/// Transfer this owner intact into the factory/container until the host has +/// reconciled actual resident resources and published the slot. The models are +/// not Sendable; use the normal serial ModelContainer access rules. Arbitrary +/// subsequent Module mutation invalidates the loaded-generation contract. +public struct MiMoV26SerialLoadResult { + public let bundle: MiMoV26ConvertedBundle + public let receipt: MiMoV26SerialLoadReceipt + public let reservation: any MiMoV26SerialLoadReservation +} + +/// One-shot strict loader. No injected evaluator, dtype conversion, alternate +/// backend, parallel/bulk mode or external-sidecar loading is exposed. Models and +/// native handles remain private until all checked synchronous work completes. +/// Source files must remain exclusively immutable through load/retirement; stat +/// revalidation detects ordinary mutation, not privileged timestamp tampering. +public final class MiMoV26SerialLoadSession { + public let request: MiMoV26SerialLoadRequest + private let plan: MiMoV26FilesystemLoadPlan + private let lock = NSLock() + private var consumed = false + + public init(plan: MiMoV26FilesystemLoadPlan) throws { + let estimate = try MiMoV26LoadFootprint.estimate(plan: plan) + self.plan = plan + request = .init(binding: .init(plan: plan, estimate: estimate)) + } + + public func load( + reservation: any MiMoV26SerialLoadReservation, + retaining work: NativeConstructionScope, + isCancelled: () -> Bool = { false }, + progress: (MiMoV26SerialLoadProgress) throws -> Void = { _ in } + ) throws -> MiMoV26SerialLoadResult { + try work.withPhase(.serialLoad) { + try work.retainOwner(reservation) + return try loadInScope( + reservation: reservation, work: work, + isCancelled: isCancelled, progress: progress) + } + } + + private func loadInScope( + reservation: any MiMoV26SerialLoadReservation, work: NativeConstructionScope, + isCancelled: () -> Bool, + progress: (MiMoV26SerialLoadProgress) throws -> Void + ) throws -> MiMoV26SerialLoadResult { + try lock.withLock { + guard !consumed else { throw MiMoV26SerialLoadError.alreadyConsumed } + consumed = true + } + guard reservation.request == request else { + throw MiMoV26SerialLoadError.reservationMismatch + } + guard reservation.reservedLoadBytes >= request.requiredLoadBytes else { + throw MiMoV26SerialLoadError.insufficientReservation + } + var sourceCount = 0 + var sourceBytes: UInt64 = 0 + var parameterCount = 0 + var completedParameters = 0 + func checkpoint( + _ phase: MiMoV26SerialLoadPhase, shard: String? = nil, tensor: String? = nil + ) throws { + guard !isCancelled() else { throw MiMoV26SerialLoadError.cancelled } + let value = MiMoV26SerialLoadProgress( + phase: phase, + sourceTensorsCompleted: sourceCount, + sourceTensorCount: plan.bundlePlan.descriptors.count, + materializedSourcePayloadBytes: sourceBytes, + parametersCompleted: completedParameters, parameterCount: parameterCount, + currentShard: shard, currentTensor: tensor) + // Admission may have awaited or a callback may replace/revoke state. + // Recheck binding and permit on both sides of each host callback. + try revalidate( + reservation, isCancelled: isCancelled, + recomputeEstimate: phase == .admitted || phase == .complete) + try reservation.validateActive(progress: value) + try revalidate(reservation, isCancelled: isCancelled) + try progress(value) + try revalidate(reservation, isCancelled: isCancelled) + try reservation.validateActive(progress: value) + try revalidate(reservation, isCancelled: isCancelled) + } + try checkpoint(.admitted) + var loaded = try MiMoV26FilesystemWeights.load( + plan: plan, retaining: work, isCancelled: isCancelled + ) { value in + try checkpoint(.sourceHandles, shard: value.currentFile) + } + var handles = loaded.takeMaterializationHandles() + defer { handles.removeAll() } + guard loaded.materializationHandleCount == 0, + handles.count == plan.bundlePlan.descriptors.count, + Set(handles.map(\.name)) == Set(plan.bundlePlan.descriptors.keys) + else { + throw MiMoV26SerialLoadError.invalidSourceHandles + } + var expectedBytes: UInt64 = 0 + for handle in handles { + guard handle.byteCount > 0, handle.byteCount == handle.array.nbytes else { + throw MiMoV26SerialLoadError.invalidSourceHandles + } + let next = expectedBytes.addingReportingOverflow(UInt64(handle.byteCount)) + guard !next.overflow else { throw MiMoV26SerialLoadError.invalidSourceHandles } + expectedBytes = next.partialValue + } + guard expectedBytes == UInt64(plan.bundlePlan.tensorBytes) else { + throw MiMoV26SerialLoadError.invalidSourceHandles + } + for (left, right) in zip(handles, handles.dropFirst()) { + guard + left.shard < right.shard + || (left.shard == right.shard && left.dataOffset < right.dataOffset) + else { + throw MiMoV26SerialLoadError.invalidSourceHandles + } + } + var previousShard: String? + for (index, handle) in handles.enumerated() { + guard !isCancelled() else { throw MiMoV26SerialLoadError.cancelled } + if index.isMultiple(of: 64) || previousShard != handle.shard { + try checkpoint(.sourceMaterialization, shard: handle.shard, tensor: handle.name) + } + // Only exact native Load roots, never constructor/random expressions. + try work.retain(handle.array) + try work.capture(StreamOrDevice.default.stream) + try work.willSubmit() + try withError { error in + eval(handle.array) + try error.check() + } + try work.checkpoint("serial.sourceMaterialized") + guard let info = try handle.array.evaluatedBufferInfo(), + info.allocatedBytes >= handle.byteCount, info.dataOffset == 0, + info.isRowContiguous + else { throw MiMoV26SerialLoadError.unmaterializedSource } + sourceCount += 1 + sourceBytes += UInt64(handle.byteCount) + previousShard = handle.shard + } + // Keep the original roots distinct from sanitized parameter views. Eval + // verified final parameters serially while the load/copy permit is still + // held; do not defer their transforms until after releasing that permit. + let modules: [(String, Module)] = [ + ("target", loaded.bundle.target), + ("vision", loaded.bundle.vision), ("audioPatch", loaded.bundle.audioPatch), + ("mtp", loaded.bundle.mtp), + ] + let parameters = modules.flatMap { component, module in + module.parameters().flattened().map { (component + "." + $0.0, $0.1) } + }.sorted { $0.0 < $1.0 } + parameterCount = parameters.count + guard parameterCount == handles.count else { + throw MiMoV26SerialLoadError.invalidSourceHandles + } + for (index, item) in parameters.enumerated() { + guard !isCancelled() else { throw MiMoV26SerialLoadError.cancelled } + let (name, parameter) = item + if index.isMultiple(of: 64) { + try checkpoint(.parameterMaterialization, tensor: name) + } + try work.retain(parameter) + try work.capture(StreamOrDevice.default.stream) + try work.willSubmit() + try withError { error in + eval(parameter) + try error.check() + } + try work.checkpoint("serial.parameterMaterialized") + guard let info = try parameter.evaluatedBufferInfo(), + info.allocatedBytes >= parameter.nbytes + else { + throw MiMoV26SerialLoadError.unmaterializedSource + } + completedParameters += 1 + } + handles.removeAll() + try checkpoint(.complete) + return .init( + bundle: loaded.bundle, + receipt: .init( + sessionID: request.sessionID, + binding: request.binding, sourceTensorCount: sourceCount, + parameterCount: parameterCount, + materializedSourcePayloadBytes: sourceBytes), reservation: reservation) + } + + private func revalidate( + _ reservation: any MiMoV26SerialLoadReservation, + isCancelled: () -> Bool, recomputeEstimate: Bool = false + ) throws { + guard !isCancelled() else { throw MiMoV26SerialLoadError.cancelled } + guard reservation.request == request else { + throw MiMoV26SerialLoadError.reservationMismatch + } + guard reservation.reservedLoadBytes >= request.requiredLoadBytes else { + throw MiMoV26SerialLoadError.insufficientReservation + } + try MiMoV26FilesystemWeights.validateCurrentObjects(plan: plan, isCancelled: isCancelled) + if recomputeEstimate { + let estimate = try MiMoV26LoadFootprint.estimate(plan: plan) + guard MiMoV26SerialLoadBinding(plan: plan, estimate: estimate) == request.binding else { + throw MiMoV26SerialLoadError.reservationMismatch + } + } + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26TextProcessor.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26TextProcessor.swift new file mode 100644 index 0000000000..3f2b6047be --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26TextProcessor.swift @@ -0,0 +1,138 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX +import MLXLMCommon + +/// Native template-input boundary only. HTTP/OpenAI normalization, tool-history +/// repair and effort aliases belong upstream. This processor never silently +/// drops media or rewrites native thinking defaults. +public struct MiMoV26TextProcessor: UserInputProcessor { + public let chatTemplate: String + public let vocabularySize: Int + public let maximumSequenceLength: Int + private let tokenizer: any Tokenizer + private static let mediaKeys: Set = [ + "image", "images", "image_url", "video", "videos", "video_url", + "audio", "audio_url", "input_audio", "audio_chunks", + ] + + public init( + tokenizer: any Tokenizer, chatTemplate: String, + vocabularySize: Int, maximumSequenceLength: Int + ) throws { + guard !chatTemplate.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + vocabularySize > 0, vocabularySize <= Int(Int32.max), + maximumSequenceLength > 1, maximumSequenceLength <= Int(Int32.max) + else { + throw MiMoV26FactoryError.invalidMetadata( + "empty template or invalid token/context bounds") + } + self.tokenizer = tokenizer + self.chatTemplate = chatTemplate + self.vocabularySize = vocabularySize + self.maximumSequenceLength = maximumSequenceLength + } + + /// Returns host token IDs, allowing template/tokenizer preflight before any + /// native model/input allocation. Tools and reasoning fields pass unchanged. + public func renderTokens(input: UserInput) throws -> [Int] { + guard input.images.isEmpty, input.videos.isEmpty else { + throw MiMoV26FactoryError.unsupportedInput( + "native media processing is not qualified by the text entrypoint") + } + guard input.additionalContext?.keys.contains(where: Self.mediaKeys.contains) != true else { + throw MiMoV26FactoryError.unsupportedInput("render context contains unsupported media") + } + if let thinking = input.additionalContext?["enable_thinking"], + type(of: thinking) != Bool.self + { + throw MiMoV26FactoryError.unsupportedInput( + "enable_thinking must be a native Boolean; API aliases must be resolved upstream") + } + if let generation = input.additionalContext?["add_generation_prompt"], + type(of: generation) != Bool.self + { + throw MiMoV26FactoryError.unsupportedInput( + "add_generation_prompt must be a native Boolean") + } + let messages: [Message] + switch input.prompt { + case .text(let text): messages = [["role": "user", "content": text]] + case .messages(let raw): messages = raw + case .chat(let chat): + messages = try chat.map { message in + guard message.images.isEmpty, message.videos.isEmpty, + message.templateFields["role"] == nil, message.templateFields["content"] == nil + else { + throw MiMoV26FactoryError.unsupportedInput( + "chat contains media or overrides structured role/content") + } + // Preserve native per-message tools and future template fields; + // generic whitelist projection would silently remove them. + var raw = message.templateFields + raw["role"] = message.role.rawValue + raw["content"] = message.content + return raw + } + } + guard !messages.isEmpty else { + throw MiMoV26FactoryError.unsupportedInput("empty message list") + } + let textMessages = try messages.map(Self.prepareTextMessage) + let tokens = try tokenizer.applyChatTemplate( + messages: textMessages, chatTemplate: chatTemplate, + tools: input.tools, additionalContext: input.additionalContext) + guard !tokens.isEmpty, tokens.count < maximumSequenceLength, + tokens.allSatisfy({ $0 >= 0 && $0 < vocabularySize }) + else { + throw MiMoV26FactoryError.unsupportedInput( + "rendered tokens exceed native vocabulary/context") + } + return tokens + } + + public func prepare(input: UserInput) async throws -> LMInput { + try Task.checkCancellation() + let tokens = try renderTokens(input: input) + try Task.checkCancellation() + return LMInput(tokens: MLXArray(tokens.map(Int32.init))) + } + + private static func prepareTextMessage(_ message: Message) throws -> Message { + guard let role = message["role"] as? String, + ["system", "user", "assistant", "tool"].contains(role) + else { + throw MiMoV26FactoryError.unsupportedInput( + "native text message requires a supported role") + } + guard !mediaKeys.contains(where: { message[$0] != nil }) else { + throw MiMoV26FactoryError.unsupportedInput("message has image/video/audio fields") + } + let content = message["content"] + if content == nil || content is NSNull || (content as? MLXLMCommon.JSONValue) == .null { + // The selected native render_content macro renders absent/null + // bodies exactly like "". Canonicalize ONLY that body slot for the + // Swift-Jinja bridge; tool calls, arguments and reasoning remain + // untouched. Real pinned-template parity is a separate test gate. + var emptyBody = message + emptyBody["content"] = "" + return emptyBody + } + if content is String { return message } + // Preserve text content-part arrays without flattening/reordering them. + // Unknown parts are refused because the native template may omit them. + guard let parts = content as? [[String: any Sendable]] else { + throw MiMoV26FactoryError.unsupportedInput( + "content must be text or text-only native parts") + } + for part in parts { + guard part["type"] as? String == "text", part["text"] is String, + !mediaKeys.contains(where: { part[$0] != nil }) + else { + throw MiMoV26FactoryError.unsupportedInput( + "image/video/audio or unknown content part") + } + } + return message + } +} diff --git a/Libraries/MLXVLM/Models/MiMo/MiMoV26Vision.swift b/Libraries/MLXVLM/Models/MiMo/MiMoV26Vision.swift new file mode 100644 index 0000000000..f7da28d554 --- /dev/null +++ b/Libraries/MLXVLM/Models/MiMo/MiMoV26Vision.swift @@ -0,0 +1,486 @@ +// Copyright © 2026 Eigen Labs. +// Native contracts derived from SGLang (Apache-2.0), commit +// 67bb6a58d0dad4a39af80fa1b2bf86f0de0cb99b: models/mimo_vl.py, +// layers/attention/vision.py and models/qwen2_5_vl.py. +// Preprocessed-patch component only: no pixels, media ingestion or factory alias. +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +public enum MiMoV26VisionError: Error, Equatable, Sendable { + case invalidConfiguration(String) + case invalidInput(String) + case executionLimit(String) + case invalidWeights(String) + case weightsNotLoaded +} + +public struct MiMoV26VisionGrid: Equatable, Sendable { + public let temporal, height, width: Int + public init(temporal: Int, height: Int, width: Int) { + self.temporal = temporal + self.height = height + self.width = width + } +} + +/// Caller-owned component allocation limits, distinct from model capability. +public struct MiMoV26VisionLimits: Equatable, Sendable { + public let maximumPatches, maximumAttentionScoreElements: Int + public init(maximumPatches: Int, maximumAttentionScoreElements: Int) { + self.maximumPatches = maximumPatches + self.maximumAttentionScoreElements = maximumAttentionScoreElements + } +} + +/// CPU layout metadata. All arrays are request-owned. Sequence ranges are one +/// temporal grid each: neither global nor local attention crosses a frame. +public struct MiMoV26VisionLayout: Equatable, Sendable { + public let patchCount: Int + public let frames: [Range] + public let rowPositions, columnPositions: [Int] + public let columnPermutation, inverseColumnPermutation: [Int] + + public static func make( + grids: [MiMoV26VisionGrid], mergeSize: Int, + queryHeads: Int, limits: MiMoV26VisionLimits + ) throws -> Self { + guard !grids.isEmpty, mergeSize > 0, queryHeads > 0, + limits.maximumPatches > 0, limits.maximumAttentionScoreElements > 0 + else { + throw MiMoV26VisionError.invalidInput("empty grids or invalid layout limits") + } + let unit = try visionProduct([mergeSize, mergeSize], "merge area") + var total = 0 + for g in grids { + guard g.temporal > 0, g.height > 0, g.width > 0, + g.height.isMultiple(of: mergeSize), g.width.isMultiple(of: mergeSize) + else { + throw MiMoV26VisionError.invalidInput( + "grid must contain complete spatial merge groups") + } + let perFrame = try visionProduct([g.height, g.width], "frame patches") + let scores = try visionProduct([queryHeads, perFrame, perFrame], "attention scores") + guard scores <= limits.maximumAttentionScoreElements else { + throw MiMoV26VisionError.executionLimit("per-frame attention score bound") + } + let count = try visionProduct([g.temporal, perFrame], "grid patches") + let sum = total.addingReportingOverflow(count) + guard !sum.overflow, sum.partialValue <= limits.maximumPatches, + sum.partialValue <= Int(Int32.max) + else { + throw MiMoV26VisionError.executionLimit("total patch bound") + } + total = sum.partialValue + } + var rows: [Int] = [] + var columns: [Int] = [] + var permutation: [Int] = [] + var frames: [Range] = [] + rows.reserveCapacity(total) + columns.reserveCapacity(total) + permutation.reserveCapacity(total) + var start = 0 + for g in grids { + let groupsH = g.height / mergeSize + let groupsW = g.width / mergeSize + let perFrame = g.height * g.width // Checked above. + for _ in 0 ..< g.temporal { + frames.append(start ..< (start + perFrame)) + for groupH in 0 ..< groupsH { + for groupW in 0 ..< groupsW { + for localH in 0 ..< mergeSize { + for localW in 0 ..< mergeSize { + rows.append(groupH * mergeSize + localH) + columns.append(groupW * mergeSize + localW) + } + } + } + } + for groupW in 0 ..< groupsW { + for groupH in 0 ..< groupsH { + let group = (groupH * groupsW + groupW) * unit + permutation.append(contentsOf: (0 ..< unit).map { start + group + $0 }) + } + } + start += perFrame + } + } + var inverse = [Int](repeating: 0, count: total) + for (destination, source) in permutation.enumerated() { inverse[source] = destination } + return Self( + patchCount: total, frames: frames, rowPositions: rows, columnPositions: columns, + columnPermutation: permutation, inverseColumnPermutation: inverse) + } +} + +private func visionProduct(_ values: [Int], _ name: String) throws -> Int { + var result = 1 + for value in values { + guard value > 0 else { throw MiMoV26VisionError.invalidConfiguration(name) } + let next = result.multipliedReportingOverflow(by: value) + guard !next.overflow else { + throw MiMoV26VisionError.invalidConfiguration("overflow: " + name) + } + result = next.partialValue + } + return result +} + +private struct MiMoV26VisionShape { + let config: MiMoV26VisionConfiguration + let channels, headDim, qWidth, kvWidth, fusedWidth, patchWidth, mergeWidth: Int + + init(_ config: MiMoV26VisionConfiguration) throws { + self.config = config + func integer(_ key: String, default fallback: Int) throws -> Int { + guard let field = config.rawFields[key] else { return fallback } + guard case .number(let number) = field else { + throw MiMoV26VisionError.invalidConfiguration(key) + } + let value = NSDecimalNumber(decimal: number).int64Value + guard number == Decimal(value), let exact = Int(exactly: value), exact > 0, + exact <= Int(Int32.max) + else { throw MiMoV26VisionError.invalidConfiguration(key) } + return exact + } + channels = try integer("in_channels", default: 3) + if let declared = config.rawFields["in_chans"], declared != .number(Decimal(channels)) { + throw MiMoV26VisionError.invalidConfiguration( + "in_chans disagrees with consumed in_channels") + } + // MiMo's defaults are 64 even though hidden1280 / heads32 equals40. + headDim = try integer("qk_channels", default: 64) + let valueDim = try integer("kv_channels", default: 64) + guard headDim == valueDim, headDim.isMultiple(of: 4), + config.queryHeads.isMultiple(of: config.keyValueHeads), + config.windowAttentionTypes.last != 1 + else { + throw MiMoV26VisionError.invalidConfiguration("head geometry or final column ordering") + } + qWidth = try visionProduct([config.queryHeads, headDim], "query projection") + kvWidth = try visionProduct([config.keyValueHeads, headDim], "KV projection") + let kvPair = try visionProduct([2, kvWidth], "KV pair") + let fused = qWidth.addingReportingOverflow(kvPair) + guard !fused.overflow else { + throw MiMoV26VisionError.invalidConfiguration("QKV width overflow") + } + fusedWidth = fused.partialValue + patchWidth = try visionProduct( + [channels, config.temporalPatchSize, config.patchSize, config.patchSize], "patch width") + mergeWidth = try visionProduct( + [config.hiddenSize, config.spatialMergeSize, config.spatialMergeSize], "merger width") + let dimensions = [ + config.depth, config.hiddenSize, config.intermediateSize, config.outputHiddenSize, + qWidth, kvWidth, fusedWidth, patchWidth, mergeWidth, + ] + guard dimensions.allSatisfy({ $0 > 0 && $0 <= Int(Int32.max) }) else { + throw MiMoV26VisionError.invalidConfiguration("MLX dimension exceeds Int32") + } + _ = try visionProduct([config.hiddenSize, fusedWidth], "QKV tensor") + _ = try visionProduct([mergeWidth, mergeWidth], "merger tensor") + _ = try integer("visual_token_window_size", default: 64) + } + + var window: Int { + // Validated by integer() above; source config supplies an integer. + if case .number(let value) = config.rawFields["visual_token_window_size"] { + return NSDecimalNumber(decimal: value).intValue + } + return 64 + } + + func sourceShapes() -> [String: [Int]] { + let c = config + var shapes = [ + "visual.patch_embed.proj.weight": [ + c.hiddenSize, channels, c.temporalPatchSize, c.patchSize, c.patchSize, + ], + "visual.merger.ln_q.weight": [c.hiddenSize], + "visual.merger.mlp.0.weight": [mergeWidth, mergeWidth], + "visual.merger.mlp.2.weight": [c.outputHiddenSize, mergeWidth], + ] + for i in 0 ..< c.depth { + let p = "visual.blocks.\(i)." + shapes[p + "norm1.weight"] = [c.hiddenSize] + shapes[p + "norm2.weight"] = [c.hiddenSize] + shapes[p + "attn.qkv.weight"] = [fusedWidth, c.hiddenSize] + shapes[p + "attn.qkv.bias"] = [fusedWidth] + shapes[p + "attn.proj.weight"] = [c.hiddenSize, qWidth] + shapes[p + "attn.proj.bias"] = [c.hiddenSize] + for name in ["gate_proj", "up_proj"] { + shapes[p + "mlp.\(name).weight"] = [c.intermediateSize, c.hiddenSize] + shapes[p + "mlp.\(name).bias"] = [c.intermediateSize] + } + shapes[p + "mlp.down_proj.weight"] = [c.hiddenSize, c.intermediateSize] + shapes[p + "mlp.down_proj.bias"] = [c.hiddenSize] + if c.usesSinks && !c.fullAttentionBlocks.contains(i) { + shapes[p + "attn.sinks"] = [c.queryHeads] + } + } + return shapes + } +} + +private final class MiMoV26VisionPatchEmbedding: Module, UnaryLayer { + @ModuleInfo var proj: Linear + init(_ shape: MiMoV26VisionShape) { + _proj.wrappedValue = Linear(shape.patchWidth, shape.config.hiddenSize, bias: false) + } + func callAsFunction(_ x: MLXArray) -> MLXArray { proj(x) } +} + +private final class MiMoV26VisionMLP: Module, UnaryLayer { + @ModuleInfo(key: "gate_proj") var gate: Linear + @ModuleInfo(key: "up_proj") var up: Linear + @ModuleInfo(key: "down_proj") var down: Linear + init(_ c: MiMoV26VisionConfiguration) { + _gate.wrappedValue = Linear(c.hiddenSize, c.intermediateSize, bias: true) + _up.wrappedValue = Linear(c.hiddenSize, c.intermediateSize, bias: true) + _down.wrappedValue = Linear(c.intermediateSize, c.hiddenSize, bias: true) + } + func callAsFunction(_ x: MLXArray) -> MLXArray { down(silu(gate(x)) * up(x)) } +} + +private final class MiMoV26VisionAttention: Module { + @ModuleInfo var qkv: Linear + @ModuleInfo var proj: Linear + @ParameterInfo var sinks: MLXArray? + let shape: MiMoV26VisionShape + init(_ shape: MiMoV26VisionShape, full: Bool) { + self.shape = shape + _qkv.wrappedValue = Linear(shape.config.hiddenSize, shape.fusedWidth, bias: true) + _proj.wrappedValue = Linear(shape.qWidth, shape.config.hiddenSize, bias: true) + _sinks.wrappedValue = + shape.config.usesSinks && !full ? MLXArray.zeros([shape.config.queryHeads]) : nil + } + + func callAsFunction(_ x: MLXArray, angles: MLXArray, frames: [Range]) -> MLXArray { + let c = shape.config + let n = x.dim(0) + let fused = qkv(x) + var q = fused[0..., .. MLXArray { + let half = shape.headDim / 2 + let fp32 = input.asType(.float32) + let rotated = concatenated( + [-fp32[0..., 0..., half...], fp32[0..., 0..., ..= -shape.window) .&& (distance .<= shape.window)) + } else { + mask = .none + } + let result = MLXFast.scaledDotProductAttention( + queries: q[queryRange].transposed(1, 0, 2).expandedDimensions(axis: 0), + keys: k[keyRange].transposed(1, 0, 2).expandedDimensions(axis: 0), + values: v[keyRange].transposed(1, 0, 2).expandedDimensions(axis: 0), + scale: 1 / Float(shape.headDim).squareRoot(), mask: mask, sinks: sinks) + outputs.append(result[0].transposed(1, 0, 2).reshaped(end - start, shape.qWidth)) + } + } + return proj(concatenated(outputs, axis: 0)) + } +} + +private final class MiMoV26VisionBlock: Module { + @ModuleInfo var norm1: RMSNorm + @ModuleInfo var norm2: RMSNorm + let attn: MiMoV26VisionAttention + let mlp: MiMoV26VisionMLP + init(_ shape: MiMoV26VisionShape, index: Int, epsilon: Float) { + _norm1.wrappedValue = RMSNorm(dimensions: shape.config.hiddenSize, eps: epsilon) + _norm2.wrappedValue = RMSNorm(dimensions: shape.config.hiddenSize, eps: epsilon) + attn = MiMoV26VisionAttention(shape, full: shape.config.fullAttentionBlocks.contains(index)) + mlp = MiMoV26VisionMLP(shape.config) + } + func callAsFunction(_ x: MLXArray, angles: MLXArray, frames: [Range]) -> MLXArray { + let residual = x + attn(norm1(x), angles: angles, frames: frames) + return residual + mlp(norm2(residual)) + } +} + +private final class MiMoV26VisionMerger: Module, UnaryLayer { + @ModuleInfo(key: "ln_q") var norm: RMSNorm + @ModuleInfo var mlp: (Linear, GELU, Linear) + let width: Int + init(_ shape: MiMoV26VisionShape) { + width = shape.mergeWidth + _norm.wrappedValue = RMSNorm(dimensions: shape.config.hiddenSize, eps: 1e-6) + // The 364-tensor checkpoint contains no merger biases. SGLang's + // _post_init sets those runtime biases to zero; no trained value is + // synthesized here and strict loading requires only actual parameters. + _mlp.wrappedValue = ( + Linear(width, width, bias: false), GELU(approximation: .none), + Linear(width, shape.config.outputHiddenSize, bias: false) + ) + } + func callAsFunction(_ x: MLXArray) -> MLXArray { + mlp.2(mlp.1(mlp.0(norm(x).reshaped(-1, width)))) + } +} + +public final class MiMoV26VisionTower: Module { + public let configuration: MiMoV26VisionConfiguration + private let shape: MiMoV26VisionShape + @ModuleInfo(key: "patch_embed") private var patchEmbedding: MiMoV26VisionPatchEmbedding + private let blocks: [MiMoV26VisionBlock] + private let merger: MiMoV26VisionMerger + private var validatedWeightDType: DType? + + public init(configuration: MiMoV26VisionConfiguration, normEpsilon: Float = 1e-6) throws { + guard normEpsilon.isFinite && normEpsilon > 0 else { + throw MiMoV26VisionError.invalidConfiguration("normalization epsilon") + } + let shape = try MiMoV26VisionShape(configuration) + self.shape = shape + self.configuration = configuration + _patchEmbedding.wrappedValue = MiMoV26VisionPatchEmbedding(shape) + blocks = (0 ..< configuration.depth).map { + MiMoV26VisionBlock(shape, index: $0, epsilon: normEpsilon) + } + merger = MiMoV26VisionMerger(shape) + } + + public static func expectedTensorShapes(configuration: MiMoV26VisionConfiguration) throws + -> [String: [Int]] + { + try MiMoV26VisionShape(configuration).sourceShapes() + } + + /// Exact visual-only source/converted dictionary. Patch storage is O,C,T,H,W; + /// reshape preserves that byte order as the flattened Linear input. Every + /// other trained tensor retains its name/shape after removing `visual.`. + public func loadNativeWeights( + _ weights: [String: MLXArray], expectedDType: DType = .bfloat16, + flattenedPatchStorage: Bool = false + ) throws { + guard [.bfloat16, .float16, .float32].contains(expectedDType) else { + throw MiMoV26VisionError.invalidWeights("unsupported dtype") + } + var expected = shape.sourceShapes() + if flattenedPatchStorage { + expected["visual.patch_embed.proj.weight"] = [ + configuration.hiddenSize, shape.patchWidth, + ] + } + guard Set(weights.keys) == Set(expected.keys) else { + throw MiMoV26VisionError.invalidWeights("missing or unmapped visual tensors") + } + for (name, dimensions) in expected { + guard let value = weights[name], value.shape == dimensions, value.dtype == expectedDType + else { + throw MiMoV26VisionError.invalidWeights(name) + } + } + var mapped: [(String, MLXArray)] = [] + for (name, value) in weights { + let tensor = + name == "visual.patch_embed.proj.weight" + ? value.reshaped(configuration.hiddenSize, shape.patchWidth) : value + mapped.append((String(name.dropFirst("visual.".count)), tensor)) + } + try update(parameters: ModuleParameters.unflattened(mapped), verify: .all) + validatedWeightDType = expectedDType + } + + @discardableResult + public override func update( + parameters: ModuleParameters, verify: VerifyUpdate, + path: [String] = [], modulePath: [String] = [] + ) throws -> Self { + validatedWeightDType = nil + return try super.update( + parameters: parameters, verify: verify, path: path, modulePath: modulePath) + } + + @discardableResult + public override func update( + modules: ModuleChildren, verify: VerifyUpdate, + path: [String] = [], modulePath: [String] = [] + ) throws -> Self { + validatedWeightDType = nil + return try super.update( + modules: modules, verify: verify, path: path, modulePath: modulePath) + } + + public func forward( + patches: MLXArray, grids: [MiMoV26VisionGrid], + limits: MiMoV26VisionLimits + ) throws -> MLXArray { + guard let dtype = validatedWeightDType else { throw MiMoV26VisionError.weightsNotLoaded } + guard patches.ndim == 2, patches.dim(1) == shape.patchWidth, + [.bfloat16, .float16, .float32].contains(patches.dtype) + else { + throw MiMoV26VisionError.invalidInput("native flattened patch geometry/dtype") + } + let layout = try MiMoV26VisionLayout.make( + grids: grids, mergeSize: configuration.spatialMergeSize, + queryHeads: configuration.queryHeads, limits: limits) + guard patches.dim(0) == layout.patchCount else { + throw MiMoV26VisionError.invalidInput("patch count does not match grids") + } + let axisFrequencies = shape.headDim / 4 + let frequencyCount = try visionProduct( + [layout.patchCount, axisFrequencies, 2], "rotary table") + var frequencies: [Float] = [] + frequencies.reserveCapacity(frequencyCount) + for i in 0 ..< layout.patchCount { + for position in [layout.rowPositions[i], layout.columnPositions[i]] { + for j in 0 ..< axisFrequencies { + let inverse = 1 / pow(Float(10000), Float(j * 2) / Float(shape.headDim / 2)) + frequencies.append(Float(position) * inverse) + } + } + } + let rowAngles = MLXArray(frequencies).reshaped(layout.patchCount, shape.headDim / 2) + let columnIndex = MLXArray(layout.columnPermutation.map(Int32.init)) + let inverseIndex = MLXArray(layout.inverseColumnPermutation.map(Int32.init)) + let columnAngles = rowAngles[columnIndex] + var x = patchEmbedding(patches.asType(dtype)) + var columnOrder = false + for (i, block) in blocks.enumerated() { + let nextColumnOrder = configuration.windowAttentionTypes[i] == 1 + if nextColumnOrder != columnOrder { + x = x[nextColumnOrder ? columnIndex : inverseIndex] + } + columnOrder = nextColumnOrder + x = block(x, angles: columnOrder ? columnAngles : rowAngles, frames: layout.frames) + } + return merger(x) + } +} diff --git a/Package.swift b/Package.swift index 497adeffb4..89b2ef4194 100644 --- a/Package.swift +++ b/Package.swift @@ -42,12 +42,14 @@ let package = Package( targets: ["IntegrationTestHelpers"]), ], dependencies: [ - .package(url: "https://github.com/Layr-Labs/mlx-swift.git", - revision: "0f4fe403bef6899e8a72882bc6d4036a7a62ae31"), + .package( + url: "https://github.com/Layr-Labs/mlx-swift.git", + revision: "0f4fe403bef6899e8a72882bc6d4036a7a62ae31"), .package(url: "https://github.com/swiftlang/swift-syntax.git", "600.0.0" ..< "604.0.0"), .package(url: "https://github.com/hummingbird-project/hummingbird.git", from: "2.23.0"), .package(url: "https://github.com/huggingface/swift-huggingface.git", from: "0.9.0"), .package(url: "https://github.com/huggingface/swift-transformers.git", from: "1.3.2"), + .package(url: "https://github.com/huggingface/swift-jinja.git", exact: "2.3.6"), ], targets: [ .target( @@ -66,6 +68,7 @@ let package = Package( .target( name: "MLXVLM", dependencies: [ + .product(name: "Jinja", package: "swift-jinja"), "MLXLMCommon", "MLXLLM", .product(name: "MLX", package: "mlx-swift"), @@ -99,7 +102,7 @@ let package = Package( .copy("ContinuousBatchingV2/Paged/pagedattention.metal"), // Exact MLX preambles used by native Qwen4 JIT kernels. // Copy as text; SwiftPM must not compile these header fragments. - .copy("Resources/Qwen4Metal") + .copy("Resources/Qwen4Metal"), ] ), .target( diff --git a/README.md b/README.md index e342148d0b..2ef1c26e27 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ For some example applications and tools that use MLX Swift LM, check out [MLX Sw Developers can use these examples in their own programs -- just import the swift package! +- [Native MiMo V2.6](docs/mimo-v26/README.md): dedicated entry points, qualification boundaries and port attribution. - [Qwen 3.8 Next / native Qwen4](docs/qwen4/README.md): qualification, composition and attribution. - [Ternary Bonsai 2 27B](docs/bonsai2.md): packed checkpoint contract and native serving scope. - [Server request validation](docs/server-request-validation.md): output-token boundaries and early HTTP errors. diff --git a/Tests/MLXLMServerTests/MiMo/MiMoV2ToolCodecTests.swift b/Tests/MLXLMServerTests/MiMo/MiMoV2ToolCodecTests.swift new file mode 100644 index 0000000000..8fbe0babc9 --- /dev/null +++ b/Tests/MLXLMServerTests/MiMo/MiMoV2ToolCodecTests.swift @@ -0,0 +1,274 @@ +import Foundation +import MLXLMCommon +import MLXLMServer +import XCTest + +/// Prepared real parser/processor tests. No model, service or generated-output +/// capability is inferred from these wire fixtures; root executes the suite. +final class MiMoV2ToolCodecTests: XCTestCase { + private func frame(_ value: String, name: String = "record_text", key: String = "text") + -> String + { + "\(value)" + } + private func tools( + _ type: String = "string", name: String = "record_text", key: String = "text" + ) -> [[String: any Sendable]] { + let property: [String: any Sendable] = ["type": type] + let properties: [String: any Sendable] = [key: property] + let parameters: [String: any Sendable] = [ + "type": "object", "properties": properties, + "required": [key], "additionalProperties": false, + ] + let function: [String: any Sendable] = ["name": name, "parameters": parameters] + return [["type": "function", "function": function]] + } + private func text(_ call: ToolCall?, key: String = "text") throws -> String { + let call = try XCTUnwrap(call) + guard case .string(let value) = call.function.arguments[key] else { + XCTFail("expected raw string") + return "" + } + return value + } + private func pieces(_ value: String, width: Int) -> [String] { + let scalars = Array(value.unicodeScalars) + return stride(from: 0, to: scalars.count, by: width).map { + String(String.UnicodeScalarView(scalars[$0 ..< min($0 + width, scalars.count)])) + } + } + + func testExactNativeInferenceAndExplicitFormat() throws { + XCTAssertEqual(ToolCallFormat.infer(from: "mimo_v2"), .mimoV2) + for legacy in ["mimo", "mimo_v2_flash", "mimo_v2_extra", "qwen3"] { + XCTAssertNotEqual(ToolCallFormat.infer(from: legacy), .mimoV2, legacy) + } + XCTAssertEqual(try ServerToolParser.resolve(requested: nil, modelType: "mimo_v2"), .mimoV2) + XCTAssertEqual(try ServerToolParser.resolve(requested: "mimo", modelType: nil), .mimoV2) + XCTAssertEqual(try ServerToolParser.resolve(requested: "mimo-v2", modelType: nil), .mimoV2) + XCTAssertEqual(ToolCallFormat(rawValue: "mimo_v2"), .mimoV2) + } + + func testDirectRawStringsPreserveBytes() throws { + let values = [ + "\nKeep both boundary newlines.\n", " literal \\n and actual\nline; \\\\ \"quote\" ", + "café 雪 🌊 e\u{301}", "\u{301}leading combining mark", "null", + "\"quoted JSON-looking string\"", + "& < are literal bytes", "\u{00a0}non-XML whitespace\u{00a0}", + "literal thought and data ", + ] + let parser = MiMoV2ToolCallParser() + for value in values { + XCTAssertEqual( + Array(try text(parser.parse(content: frame(value), tools: tools())).utf8), + Array(value.utf8)) + } + } + + func testStrictTypedJSONValuesAndNoRepairs() throws { + let parser = MiMoV2ToolCallParser() + XCTAssertEqual( + parser.parse(content: frame("1"), tools: tools("integer"))?.function.arguments["text"], + .int(1)) + XCTAssertEqual( + parser.parse(content: frame("false"), tools: tools("boolean"))?.function.arguments[ + "text"], .bool(false)) + XCTAssertEqual( + parser.parse(content: frame("null"), tools: tools("null"))?.function.arguments["text"], + .null) + XCTAssertEqual( + parser.parse(content: frame("[0,1,true]"), tools: tools("array"))?.function.arguments[ + "text"], .array([.int(0), .int(1), .bool(true)])) + XCTAssertEqual( + parser.parse(content: frame(#"{"x":"\n","n":1}"#), tools: tools("object"))?.function + .arguments["text"], .object(["x": .string("\n"), "n": .int(1)])) + for (value, type) in [ + ("yes", "boolean"), ("garbage", "boolean"), ("01", "integer"), + ("1.5", "integer"), ("nan", "number"), ("{'x':1}", "object"), + ] { + XCTAssertNil(parser.parse(content: frame(value), tools: tools(type)), value) + } + XCTAssertEqual(try text(parser.parse(content: frame("null"), tools: tools())), "null") + } + + func testLeadingCombiningScalarParameterNameRemainsByteExact() throws { + let key = "\u{301}name" + let value = "literal data &\n" + let encoded = frame(value, key: key) + let declared = tools(key: key) + let parser = MiMoV2ToolCallParser() + let call = try XCTUnwrap(parser.parse(content: encoded, tools: declared)) + XCTAssertEqual(call.function.arguments.count, 1) + XCTAssertEqual( + Array(try XCTUnwrap(call.function.arguments.keys.first).utf8), Array(key.utf8)) + XCTAssertEqual(Array(try text(call, key: key).utf8), Array(value.utf8)) + XCTAssertNil(call.function.arguments["name"], "leading combining scalar must not disappear") + for width in [1, 2, 7, 4096] { + let processor = ToolCallProcessor(format: .mimoV2, tools: declared) + for chunk in pieces(encoded, width: width) { + XCTAssertNil(processor.processChunk(chunk)) + } + XCTAssertNil(processor.processEOS(returnBufferedText: true)) + XCTAssertEqual(processor.toolCalls.count, 1) + let streamed = try XCTUnwrap(processor.toolCalls.first) + XCTAssertEqual( + Array(try XCTUnwrap(streamed.function.arguments.keys.first).utf8), Array(key.utf8)) + XCTAssertEqual(Array(try text(streamed, key: key).utf8), Array(value.utf8)) + XCTAssertEqual(processor.parseFailureCount, 0) + } + // The shared lexer already consumes Unicode scalars and never removes + // a name prefix by Character count. Only the final OUTER marker closes. + let body = encoded.unicodeScalars.dropFirst("".unicodeScalars.count) + var scanner = Qwen35ToolFrameScanner() + var endPositions: [Int] = [] + for (index, scalar) in body.enumerated() { + if scanner.consume(scalar) { endPositions.append(index) } + } + XCTAssertEqual(endPositions, [body.count - 1]) + } + + func testUnknownFunctionAndEmptyDeclarationsReject() { + let parser = MiMoV2ToolCallParser() + XCTAssertNil(parser.parse(content: frame("x", name: "unknown"), tools: tools())) + XCTAssertNil(parser.parse(content: frame("x"), tools: [])) + XCTAssertNil(parser.parse(content: frame("x"), tools: tools() + tools())) + XCTAssertNotNil(parser.parse(content: frame("x"), tools: nil)) + } + + func testMissingTypeRetainsRawAndAmbiguousTypesRefuse() throws { + let parser = MiMoV2ToolCallParser() + XCTAssertEqual(try text(parser.parse(content: frame("123"), tools: nil)), "123") + for schema: [String: any Sendable] in [ + ["type": ["string", "integer"]], + ["anyOf": [["type": "string"], ["type": "integer"]]], + ["type": "unsupported"], + ] { + let properties: [String: any Sendable] = ["text": schema] + let parameters: [String: any Sendable] = ["properties": properties] + let function: [String: any Sendable] = [ + "name": "record_text", "parameters": parameters, + ] + let declared: [[String: any Sendable]] = [["function": function]] + XCTAssertNil(parser.parse(content: frame("123"), tools: declared)) + } + } + + func testNoExtraDialectsOrIncompleteEOS() { + let parser = MiMoV2ToolCallParser() + let complete = frame("Paris") + let invalid = [ + String(complete.dropLast("".count)), + String(complete.dropFirst("".count)), + #"{"name":"record_text","arguments":{"text":"Paris"}}"#, + #"{"name":"record_text","arguments":{"text":"Paris"}}"#, + "Paris", + complete + "trailing prose", "unrelated prefix" + complete, + ] + for value in invalid { + XCTAssertNil(parser.parse(content: value, tools: tools()), value) + XCTAssertTrue(parser.parseEOS(value, tools: tools()).isEmpty, value) + } + XCTAssertNotNil(parser.parse(content: "\r\n" + complete + "\t ", tools: tools())) + XCTAssertNil(parser.parse(content: "\u{00a0}" + complete, tools: tools())) + } + + func testDuplicateAndMalformedParametersReject() { + let parser = MiMoV2ToolCallParser() + for body in [ + "ab", + "unfinished", "aleftovers", + "a", + "literal still data", + ] { + XCTAssertNil( + parser.parse( + content: "" + body + "", + tools: tools())) + } + } + + func testActualProcessorRetainsRawArgumentsAtAllChunkWidths() throws { + let value = + "\n\u{301}café 雪 \\n literal fake data \n" + for width in [1, 2, 7, 4096] { + let processor = ToolCallProcessor(format: .mimoV2, tools: tools()) + var visible = "" + for chunk in pieces(frame(value), width: width) { + visible += processor.processChunk(chunk) ?? "" + } + visible += processor.processEOS(returnBufferedText: true) ?? "" + XCTAssertEqual(processor.toolCalls.count, 1) + XCTAssertEqual(Array(try text(processor.toolCalls.first).utf8), Array(value.utf8)) + XCTAssertEqual(processor.parseFailureCount, 0) + XCTAssertTrue(visible.isEmpty) + } + } + + func testActualHandlerAdjacentCallsAndDrainOrder() throws { + let output = ["Paris", "Tokyo", "Lima", "Oslo"].map { frame($0) }.joined() + for width in [1, 3, 17, 4096] { + let handler = BatchedToolStreamHandler(format: .mimoV2, tools: tools()) + for chunk in pieces(output, width: width) { XCTAssertNil(handler.processChunk(chunk)) } + let calls = handler.finish() + XCTAssertEqual(calls.count, 4) + XCTAssertEqual(try calls.map { try text($0) }, ["Paris", "Tokyo", "Lima", "Oslo"]) + XCTAssertEqual(handler.parseFailureCount, 0) + XCTAssertNil(handler.takeResidualText()) + } + let processor = ToolCallProcessor(format: .mimoV2, tools: tools()) + _ = processor.processChunk(output) + XCTAssertEqual(processor.drainToolCalls().count, 4) + XCTAssertTrue(processor.drainToolCalls().isEmpty) + } + + func testProcessorTrueEOSDoesNotRecoverMissingOuterClose() { + let unfinished = String(frame("Paris").dropLast("".count)) + for width in [1, 4096] { + let processor = ToolCallProcessor(format: .mimoV2, tools: tools()) + for chunk in pieces(unfinished, width: width) { + XCTAssertNil(processor.processChunk(chunk)) + } + XCTAssertEqual(processor.processEOS(returnBufferedText: true), unfinished) + XCTAssertTrue(processor.toolCalls.isEmpty) + XCTAssertEqual(processor.parseFailureCount, 1) + } + } + + func testDirectEOSRequiresEverySuppliedFrameComplete() { + let parser = MiMoV2ToolCallParser() + XCTAssertEqual(parser.parseEOS(frame("one") + frame("two"), tools: tools()).count, 2) + XCTAssertTrue( + parser.parseEOS(frame("one") + String(frame("two").dropLast()), tools: tools()).isEmpty) + } + + func testNativeParameterDelimiterCollisionIsExplicitlyUnrepresentable() throws { + // The official raw-value template maps two distinct argument objects to + // exactly these same bytes. No codec can recover original intent. This + // test proves the limitation; it is NOT a semantic-copy success claim. + let oneRawValue = "ab" + let encodedOne = frame(oneRawValue) + let encodedTwo = + "ab" + XCTAssertEqual(Array(encodedOne.utf8), Array(encodedTwo.utf8)) + let structural = try XCTUnwrap( + MiMoV2ToolCallParser().parse(content: encodedTwo, tools: nil)) + XCTAssertEqual( + structural.function.arguments, ["text": .string("a"), "other": .string("b")]) + XCTAssertNotEqual(Array(try text(structural).utf8), Array(oneRawValue.utf8)) + } + + func testOtherFamiliesRetainTheirPreviousPolicies() throws { + XCTAssertEqual(ToolCallFormat.infer(from: "qwen3_5"), .qwen35) + XCTAssertEqual(ToolCallFormat.infer(from: "qwen4_exp"), .qwen35) + XCTAssertEqual(ToolCallFormat.infer(from: "nemotron_h"), .nemotron) + let value = "\nraw\n" + let old = Qwen35ToolCallParser(startTag: "", endTag: "") + XCTAssertEqual(try text(old.parse(content: frame(value), tools: tools())), "raw") + XCTAssertEqual( + old.parseEOS(String(frame("x").dropLast("".count)), tools: tools()).count, 1 + ) + let bare = "x" + XCTAssertNotNil(ToolCallFormat.nemotron.createParser().parse(content: bare, tools: tools())) + XCTAssertNil(MiMoV2ToolCallParser().parse(content: bare, tools: tools())) + } +} diff --git a/Tests/MLXLMServerTests/ToolCallParserIntegrationTests.swift b/Tests/MLXLMServerTests/ToolCallParserIntegrationTests.swift index 938ddb353a..ab92d4f3d9 100644 --- a/Tests/MLXLMServerTests/ToolCallParserIntegrationTests.swift +++ b/Tests/MLXLMServerTests/ToolCallParserIntegrationTests.swift @@ -2,9 +2,10 @@ import Foundation import MLXLMCommon -@testable import MLXLMServer import Testing +@testable import MLXLMServer + // MARK: - BatchedToolStreamHandler Integration Tests /// Integration tests for the tool call parsing pipeline: @@ -111,19 +112,21 @@ struct ToolCallParserIntegrationTests { @Test("BatchedToolStreamHandler preserves comma-bearing Gemma string arguments") func batchedHandlerGemmaCommaBearingString() throws { - let tools: [[String: any Sendable]] = [[ - "type": "function", - "function": [ - "name": "get_current_weather", - "parameters": [ - "type": "object", - "properties": [ - "location": ["type": "string"] as [String: any Sendable], - "unit": ["type": "string"] as [String: any Sendable], + let tools: [[String: any Sendable]] = [ + [ + "type": "function", + "function": [ + "name": "get_current_weather", + "parameters": [ + "type": "object", + "properties": [ + "location": ["type": "string"] as [String: any Sendable], + "unit": ["type": "string"] as [String: any Sendable], + ] as [String: any Sendable], ] as [String: any Sendable], ] as [String: any Sendable], - ] as [String: any Sendable], - ]] + ] + ] let handler = BatchedToolStreamHandler(format: .gemma, tools: tools) for chunk in [ @@ -660,7 +663,8 @@ struct ToolCallParserIntegrationTests { #expect(try ServerToolParser.resolve(requested: "gemma_4", modelType: nil) == .gemma) #expect(try ServerToolParser.resolve(requested: "harmony", modelType: nil) == .harmony) #expect(try ServerToolParser.resolve(requested: "gpt_oss", modelType: nil) == .harmony) - #expect(try ServerToolParser.resolve(requested: "openai_harmony", modelType: nil) == .harmony) + #expect( + try ServerToolParser.resolve(requested: "openai_harmony", modelType: nil) == .harmony) #expect(try ServerToolParser.resolve(requested: "mistral", modelType: nil) == .mistral) #expect(try ServerToolParser.resolve(requested: "mistral_v11", modelType: nil) == .mistral) #expect(try ServerToolParser.resolve(requested: "llama3", modelType: nil) == .llama3) @@ -670,9 +674,11 @@ struct ToolCallParserIntegrationTests { #expect(try ServerToolParser.resolve(requested: "lfm2_5", modelType: nil) == .lfm2) #expect(try ServerToolParser.resolve(requested: "lfm25", modelType: nil) == .lfm2) #expect(try ServerToolParser.resolve(requested: "xml", modelType: nil) == .xmlFunction) - #expect(try ServerToolParser.resolve(requested: "xml_function", modelType: nil) == .xmlFunction) + #expect( + try ServerToolParser.resolve(requested: "xml_function", modelType: nil) == .xmlFunction) #expect(try ServerToolParser.resolve(requested: "qwen_xml", modelType: nil) == .xmlFunction) - #expect(try ServerToolParser.resolve(requested: "qwen3_coder", modelType: nil) == .xmlFunction) + #expect( + try ServerToolParser.resolve(requested: "qwen3_coder", modelType: nil) == .xmlFunction) #expect(try ServerToolParser.resolve(requested: "qwen3", modelType: nil) == .json) #expect(try ServerToolParser.resolve(requested: "qwen3_5", modelType: nil) == .qwen35) #expect(try ServerToolParser.resolve(requested: "qwen35", modelType: nil) == .qwen35) @@ -693,7 +699,8 @@ struct ToolCallParserIntegrationTests { #expect(try ServerToolParser.resolve(requested: nil, modelType: "gpt_oss") == .harmony) #expect(try ServerToolParser.resolve(requested: nil, modelType: "mistral3") == .mistral) #expect(try ServerToolParser.resolve(requested: nil, modelType: "qwen3_5") == .qwen35) - #expect(try ServerToolParser.resolve(requested: nil, modelType: "qwen3_next") == .xmlFunction) + #expect( + try ServerToolParser.resolve(requested: nil, modelType: "qwen3_next") == .xmlFunction) #expect(try ServerToolParser.resolve(requested: nil, modelType: "nemotron_h") == .nemotron) #expect(try ServerToolParser.resolve(requested: nil, modelType: "lfm2") == .lfm2) #expect(try ServerToolParser.resolve(requested: nil, modelType: "glm4") == .glm4) @@ -721,7 +728,8 @@ struct ToolCallParserIntegrationTests { func serverToolParserResolveNormalizesHyphens() throws { #expect(try ServerToolParser.resolve(requested: "kimi-k2", modelType: nil) == .kimiK2) #expect(try ServerToolParser.resolve(requested: "minimax-m2", modelType: nil) == .minimaxM2) - #expect(try ServerToolParser.resolve(requested: "xml-function", modelType: nil) == .xmlFunction) + #expect( + try ServerToolParser.resolve(requested: "xml-function", modelType: nil) == .xmlFunction) #expect(try ServerToolParser.resolve(requested: "llama3-json", modelType: nil) == .llama3) } @@ -825,7 +833,7 @@ struct ToolCallParserIntegrationTests { case .xmlFunction, .nemotron: #expect(parser.startTag == "") #expect(parser.endTag == "") - case .qwen35: + case .qwen35, .mimoV2: #expect(parser.startTag == "") #expect(parser.endTag == "") case .glm4: @@ -888,10 +896,12 @@ struct ToolCallParserIntegrationTests { let tc = try #require(toolCalls.first) #expect(tc.function.name == "search") #expect(tc.function.arguments["query"] == .string("swift, mlx")) - #expect(tc.function.arguments["filters"] == .object([ - "limit": .int(5), - "active": .bool(true), - ])) + #expect( + tc.function.arguments["filters"] + == .object([ + "limit": .int(5), + "active": .bool(true), + ])) } @Test("BatchedToolStreamHandler handles Harmony with nested JSON arguments") diff --git a/Tests/MLXLMTests/CBv2AsymmetricCompleteCheckpointTests.swift b/Tests/MLXLMTests/CBv2AsymmetricCompleteCheckpointTests.swift new file mode 100644 index 0000000000..5c966f3b76 --- /dev/null +++ b/Tests/MLXLMTests/CBv2AsymmetricCompleteCheckpointTests.swift @@ -0,0 +1,848 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLMCommon + +private final class AsymmetricReleaseCount: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + var value: Int { + lock.lock() + defer { lock.unlock() } + return count + } + func add() { + lock.lock() + count += 1 + lock.unlock() + } +} + +final class CBv2AsymmetricCompleteCheckpointTests: XCTestCase { + /// A real call boundary ends every export/plan/sink/stage manifest alias. + /// Returning Void cannot smuggle a metadata owner past the final-zero check. + @inline(never) + private func withManifestScope(_ body: () throws -> Void) rethrows { try body() } + + private func metadataBytes( + _ source: CBv2CompleteCheckpointExport, + codec: CBv2CompleteCheckpointCodec + ) throws -> Int { + // Independent expansion of the documented metadata envelope. On the + // failing run: Int=8, descriptor=48, attention=80, position=128 -> + // 2,361,344 bytes; two independently exported manifests -> 4,722,688. + let position = source.manifest.position + let expected = + 2 * position * MemoryLayout.stride + + 2 * 4096 + * (MemoryLayout.stride + 8 * MemoryLayout.stride + + 128) + + 2 * 2048 * MemoryLayout.stride + (64 << 10) + XCTAssertEqual( + try CBv2CheckpointManifestMemory.reservationBytes(position: position), expected) + let permit = try XCTUnwrap(source.manifest.metadata.permit) + XCTAssertEqual(permit.bytes, expected) + XCTAssertEqual(permit.admission, ObjectIdentifier(codec.admission)) + XCTAssertNil(permit.nativeOwner) + return expected + } + private let identity = CBv2CompleteCheckpointIdentity( + modelAggregateHash: "native", promptContractID: "template", + buildID: "build", numericsFingerprint: "native-types") + private var chunk: Int { max(32, CBv2AttentionV1.queryBlockSize) } + private func kinds(_ key: Int = 192, _ value: Int = 128, window: Int = 17) -> [CBv2LayerKind] { + [ + .init( + attention: .full, headDim: key, valueHeadDim: value, kvHeads: 2, queryHeads: 2, + modelLayerIndex: 3), + .init( + attention: .slidingWindow(window), headDim: key, valueHeadDim: value, kvHeads: 1, + queryHeads: 2, modelLayerIndex: 7), + .init( + attention: .full, sharesKVWithLayer: 0, headDim: key, valueHeadDim: value, + kvHeads: 2, queryHeads: 4, modelLayerIndex: 9), + ] + } + private func codec(_ kinds: [CBv2LayerKind], dtype: DType = .float32) + -> CBv2CompleteCheckpointCodec + { + .init( + identity: identity, layerKinds: kinds, recurrentSpec: nil, + kvDTypes: Array(repeating: dtype, count: kinds.count), + assistant: nil, + admission: .init( + layerKinds: kinds, bytesCapacity: 128 << 20, + config: .init(watermarkFraction: 0, elementBytes: dtype.size))) + } + private func tensor(heads: Int, start: Int, count: Int, width: Int, dtype: DType, bias: Float) + -> MLXArray + { + let values = (0 ..< heads * count * width).map { i in + bias + Float( + (i / (count * width)) * 1000 + start * 7 + (i / width) % count * 7 + i % width) / 32 + } + return MLXArray(values).reshaped([1, heads, count, width]).asType(dtype) + } + private func rows(_ kinds: [CBv2LayerKind], position: Int, dtype: DType = .float32) throws + -> [CBv2SequenceKV?] + { + kinds.map { k in + if k.sharesKVWithLayer != nil { return nil } + let row: CBv2SequenceKV + switch k.attention { + case .full: + row = CBv2FullSequenceKV( + promptLength: position, maxLength: position + 20, + kvHeads: k.kvHeads, headDim: k.headDim, valueHeadDim: k.valueHeadDim) + case .slidingWindow(let w): + row = CBv2WindowedSequenceKV( + window: w, kvHeads: k.kvHeads, + headDim: k.headDim, valueHeadDim: k.valueHeadDim) + } + let pair = row.update( + keys: tensor( + heads: k.kvHeads, start: 0, count: position, width: k.headDim, dtype: dtype, + bias: 0), + values: tensor( + heads: k.kvHeads, start: 0, count: position, width: k.valueHeadDim, + dtype: dtype, bias: -8)) + eval(pair.0, pair.1) + let s = row.snapshot() + eval(s.keys, s.values) + return row + } + } + private func request(_ position: Int) -> CBv2Request { + .init( + id: .init(1), promptTokens: Array(repeating: 1, count: position + 5), maxTokens: 7, + cacheSalt: "tenant") + } + private func export( + _ codec: CBv2CompleteCheckpointCodec, _ rows: [CBv2SequenceKV?], _ position: Int + ) throws -> CBv2CompleteCheckpointExport { + try codec.export( + checkpoint: .init(position: position, chunkSize: chunk, layers: [:], byteCount: 0), + state: rows, tokens: request(position).promptTokens, cacheSalt: "tenant") + } + private func transfer( + _ source: CBv2CompleteCheckpointExport, _ sink: CBv2CompleteCheckpointImport + ) throws { + for (i, descriptor) in source.manifest.tensors.enumerated() { + var offset = 0 + while offset < descriptor.byteCount { + let data = try source.readSegment( + tensorIndex: i, byteOffset: offset, maximumBytes: 258) + try sink.appendSegment(tensorIndex: i, byteOffset: offset, data: data) + offset += data.count + } + } + } + + func testLegacyUniformCanonicalEncodingIsByteIdentical() throws { + let layers = try CBv2CheckpointAttentionLayer.resolve( + layerKinds: [.init(attention: .full, headDim: 64, kvHeads: 2, queryHeads: 2)], + dtypes: [.float32]) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let expected = + #"[{"dtype":"float32","hasSinks":false,"headDim":64,"kvHeads":2,"modelLayer":0,"owner":0,"queryHeads":2}]"# + XCTAssertEqual(try encoder.encode(layers), Data(expected.utf8)) + let explicit = CBv2CheckpointAttentionLayer( + modelLayer: 0, owner: 0, window: nil, kvHeads: 2, headDim: 64, + valueHeadDim: 64, queryHeads: 2, hasSinks: false, dtype: .float32) + XCTAssertEqual(try encoder.encode([explicit]), Data(expected.utf8)) + XCTAssertEqual( + try JSONDecoder().decode( + [CBv2CheckpointAttentionLayer].self, from: Data(expected.utf8)), layers) + let descriptors = try [CBv2CheckpointTensorRole.keys, .values].map { + try CBv2CheckpointTensorDescriptor( + role: $0, layer: 0, shape: [1, 2, 32, 64], dtype: .float32) + } + let manifest = CBv2CompleteCheckpointManifest( + identity: identity, position: 32, chunkSize: 32, + prefixTokens: Array(repeating: 1, count: 32), cacheSalt: nil, assistantCodecID: nil, + tensors: descriptors) + let data = try encoder.encode(manifest) + let object = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + XCTAssertEqual( + Set(object.keys), + Set([ + "schemaVersion", "identity", "backendLayout", "position", "chunkSize", + "prefixTokens", "tensors", + ])) + XCTAssertEqual(object["backendLayout"] as? String, "native-contiguous-full-recurrent-v1") + // Frozen pre-v2 complete-manifest oracle, not an encoder round trip. + let legacy = + #"{"backendLayout":"native-contiguous-full-recurrent-v1","chunkSize":32,"identity":{"buildID":"build","modelAggregateHash":"native","numericsFingerprint":"native-types","promptContractID":"template"},"position":32,"prefixTokens":[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],"schemaVersion":1,"tensors":[{"byteCount":16384,"dtype":"float32","layer":0,"role":"keys","shape":[1,2,32,64]},{"byteCount":16384,"dtype":"float32","layer":0,"role":"values","shape":[1,2,32,64]}]}"# + XCTAssertEqual(data, Data(legacy.utf8)) + XCTAssertEqual( + try JSONDecoder().decode(CBv2CompleteCheckpointManifest.self, from: Data(legacy.utf8)), + manifest) + XCTAssertEqual( + try encoder.encode( + JSONDecoder().decode(CBv2CompleteCheckpointManifest.self, from: data)), data) + } + + func testNativeWidthsDTypesRingRestoreAdoptionAndContinuation() throws { + for (key, value) in [(192, 128), (64, 128)] { + for dtype: DType in [.float16, .bfloat16, .float32] { + let k = kinds(key, value) + let c = codec(k, dtype: dtype) + try withManifestScope { + let original = try rows(k, position: chunk, dtype: dtype) + let source = try export(c, original, chunk) + defer { source.close() } + let metadata = try metadataBytes(source, codec: c) + XCTAssertEqual( + source.manifest.backendLayout, + CBv2CompleteCheckpointManifest.contiguousAsymmetricLayout) + XCTAssertEqual( + source.manifest.tensors.map { $0.shape[3] }, [key, value, key, value]) + let plan = try c.plan(manifest: source.manifest, request: request(chunk)) + XCTAssertTrue(plan.manifest.metadata === source.manifest.metadata) + XCTAssertEqual( + plan.destinationShapes.map { $0[2] }, [chunk + 12, chunk + 12, 17, 17]) + let expectedBound = try plan.destinationShapes.reduce(0) { total, shape in + total + + (try Memory.allocationFootprintUpperBound( + byteCount: shape.reduce(dtype.size, *))) + } + XCTAssertEqual(plan.nativeDestinationBytes, expectedBound) + let release = AsymmetricReleaseCount() + let sink = try plan.allocate { release.add() } + try transfer(source, sink) + let staged = try sink.finish() + sink.close() + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 128 << 20, kvDType: dtype)) + var restored = try staged.consumePreparedState { prepared in + try backend.adoptPreparedCheckpoint( + prepared.state, codec: c, position: chunk, + requestID: request(chunk).id, + maximumSequenceLength: plan.maximumSequenceLength) + XCTAssertThrowsError( + try backend.adoptPreparedCheckpoint( + prepared.state, codec: c, position: chunk, + requestID: request(chunk).id, + maximumSequenceLength: plan.maximumSequenceLength)) + return prepared.state + } + XCTAssertEqual(release.value, 1) + XCTAssertNil(restored[2]) + XCTAssertEqual(backend.bytesReserved, expectedBound) + XCTAssertGreaterThanOrEqual( + c.admission.bytesReserved - metadata, staged.nativeDestinationBytes) + for i in [0, 1] { + XCTAssertEqual(restored[i]!.absoluteOffset, chunk) + XCTAssertEqual(restored[i]!.retainedCount, i == 0 ? chunk : 17) + for count in [1, 3] { + let start = original[i]!.absoluteOffset + let keys = tensor( + heads: k[i].kvHeads, start: start, count: count, width: key, + dtype: dtype, bias: 0) + let values = tensor( + heads: k[i].kvHeads, start: start, count: count, width: value, + dtype: dtype, bias: -8) + let expected = original[i]!.update(keys: keys, values: values) + let actual = restored[i]!.update(keys: keys, values: values) + eval(expected.0, expected.1, actual.0, actual.1) + XCTAssertEqual( + actual.0.asType(.float32).asArray(Float.self), + expected.0.asType(.float32).asArray(Float.self)) + XCTAssertEqual( + actual.1.asType(.float32).asArray(Float.self), + expected.1.asType(.float32).asArray(Float.self)) + } + } + backend.release(restored) + XCTAssertEqual(backend.bytesReserved, 0) + c.admission.releaseAll(id: request(chunk).id) + XCTAssertGreaterThanOrEqual( + c.admission.bytesReserved - metadata, expectedBound, + "caller row aliases still retain imported backing") + restored.removeAll() + withExtendedLifetime((source, plan, sink, staged)) { + XCTAssertTrue(staged.manifest.metadata === source.manifest.metadata) + XCTAssertEqual( + c.admission.bytesReserved, metadata, + "only the independently live manifest owner remains") + } + } + XCTAssertEqual(c.admission.bytesReserved, 0) + } + } + } + + func testAtomicAdoptionUsesOneAllocatorBoundAtTightCapacity() throws { + let k = kinds() + let c = codec(k) + let released = AsymmetricReleaseCount() + try withManifestScope { + let source = try export(c, rows(k, position: chunk), chunk) + defer { source.close() } + let metadata = try metadataBytes(source, codec: c) + let plan = try c.plan(manifest: source.manifest, request: request(chunk)) + XCTAssertTrue(plan.manifest.metadata === source.manifest.metadata) + let scratch = + plan.scratchBytes + CBv2CompleteCheckpointManifest.maximumProviderScratchBytes + let final = max( + plan.nativeDestinationBytes, + c.admission.allocatedBytes(forTokens: plan.maximumSequenceLength)) + // Metadata is independently alive. At the transfer boundary scratch + // is also still held: either destination fits, but double charge cannot. + let capacity = metadata + max(plan.nativeDestinationBytes, final) + scratch + XCTAssertLessThanOrEqual(metadata + plan.nativeDestinationBytes + scratch, capacity) + XCTAssertLessThanOrEqual(metadata + final + scratch, capacity) + XCTAssertGreaterThan(metadata + plan.nativeDestinationBytes + final + scratch, capacity) + c.admission.updateBytesCapacity(capacity) + let sink = try plan.allocate { released.add() } + try transfer(source, sink) + let stage = try sink.finish() + sink.close() + XCTAssertEqual( + c.admission.bytesReserved, metadata + plan.nativeDestinationBytes + scratch) + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: plan.nativeDestinationBytes, kvDType: .float32)) + var restored = try stage.consumePreparedState { prepared in + let owner = try XCTUnwrap( + (prepared.state[0] as? CBv2FullSequenceKV)?.checkpointBacking) + XCTAssertEqual( + owner.measuredBytesByLayer.compactMap { $0 }.reduce(0, +), + stage.nativeDestinationBytes) + XCTAssertEqual( + owner.allocationBoundsByLayer.compactMap { $0 }.reduce(0, +), + plan.nativeDestinationBytes) + XCTAssertGreaterThanOrEqual( + plan.nativeDestinationBytes, stage.nativeDestinationBytes) + try backend.adoptPreparedCheckpoint( + prepared.state, codec: c, position: chunk, + requestID: request(chunk).id, maximumSequenceLength: plan.maximumSequenceLength) + return prepared.state + } + XCTAssertEqual(released.value, 1) + XCTAssertEqual(c.admission.bytesReserved - metadata, final) + XCTAssertEqual(c.admission.transientBytesReserved - metadata, 0) + XCTAssertEqual(backend.bytesReserved, plan.nativeDestinationBytes) + c.admission.unreserve( + id: request(chunk).id, tokens: plan.maximumSequenceLength, bytes: Int.max) + XCTAssertEqual( + c.admission.bytesReserved - metadata, final, + "logical rollback cannot refund live native capacity") + backend.release(restored) + c.admission.releaseAll(id: request(chunk).id) + XCTAssertEqual(c.admission.bytesReserved - metadata, final) + restored.removeAll() + stage.close() + withExtendedLifetime((source, plan, sink, stage)) { + XCTAssertTrue(stage.manifest.metadata === source.manifest.metadata) + XCTAssertEqual(c.admission.bytesReserved, metadata) + XCTAssertEqual(c.admission.transientBytesReserved, metadata) + } + } + XCTAssertEqual(c.admission.bytesReserved, 0) + XCTAssertEqual(released.value, 1) + XCTAssertEqual(c.admission.transientBytesReserved, 0) + } + + func testAdmissionRefusalAndPostTransferFailureDoNotPublishOrRefundAliases() throws { + for failAfterTransfer in [false, true] { + let k = kinds() + let c = codec(k) + try withManifestScope { + let source = try export(c, rows(k, position: chunk), chunk) + defer { source.close() } + let metadata = try metadataBytes(source, codec: c) + let plan = try c.plan(manifest: source.manifest, request: request(chunk)) + let release = AsymmetricReleaseCount() + let sink = try plan.allocate { release.add() } + try transfer(source, sink) + let stage = try sink.finish() + sink.close() + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 128 << 20, kvDType: .float32)) + var aliases: [CBv2SequenceKV?] = [] + var oldGeneration: UUID? + if failAfterTransfer { + backend.checkpointBeforeRegistration = { + throw MLXError.caught("intentional pre-publication failure") + } + } else { + c.admission.updateBytesCapacity(0) + } + XCTAssertThrowsError( + try stage.consumePreparedState { prepared in + aliases = prepared.state + oldGeneration = + (prepared.state[0] as? CBv2FullSequenceKV)?.checkpointBacking?.lease + .identity + try backend.adoptPreparedCheckpoint( + prepared.state, codec: c, position: chunk, + requestID: request(chunk).id, + maximumSequenceLength: plan.maximumSequenceLength) + }) + stage.close() + stage.close() + XCTAssertEqual(release.value, 1) + XCTAssertEqual(backend.bytesReserved, 0) + XCTAssertEqual(backend.bytesInUse, 0) + XCTAssertGreaterThanOrEqual( + c.admission.bytesReserved - metadata, plan.nativeDestinationBytes) + c.admission.updateBytesCapacity(128 << 20) + try c.admission.reserve(id: request(chunk).id, additionalTokens: 1) + let replacement = c.admission.allocatedBytes(forTokens: 1) + // A failed generation must neither own nor refund the reused ID. + c.admission.releaseCheckpointRequest( + id: request(chunk).id, ownerIdentity: try XCTUnwrap(oldGeneration)) + aliases.removeAll() + XCTAssertEqual(c.admission.bytesReserved - metadata, replacement) + c.admission.releaseAll(id: request(chunk).id) + withExtendedLifetime((source, plan, sink, stage)) { + XCTAssertTrue(plan.manifest.metadata === source.manifest.metadata) + XCTAssertTrue(stage.manifest.metadata === source.manifest.metadata) + XCTAssertEqual(c.admission.bytesReserved, metadata) + } + } + XCTAssertEqual(c.admission.bytesReserved, 0) + } + } + + func testImportedBackingWaitsForBothRetirementLeaseAndExportAliases() throws { + for releaseLeaseFirst in [false, true] { + let k = kinds() + let c = codec(k) + try withManifestScope { + let source = try export(c, rows(k, position: chunk), chunk) + defer { source.close() } + let metadata = try metadataBytes(source, codec: c) + let plan = try c.plan(manifest: source.manifest, request: request(chunk)) + let sink = try plan.allocate {} + try transfer(source, sink) + let stage = try sink.finish() + sink.close() + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 128 << 20, kvDType: .float32)) + var restored = try stage.consumePreparedState { prepared in + try backend.adoptPreparedCheckpoint( + prepared.state, codec: c, position: chunk, + requestID: request(chunk).id, + maximumSequenceLength: plan.maximumSequenceLength) + return prepared.state + } + let outgoing = try export(c, restored, chunk) + let outgoingMetadata = try metadataBytes(outgoing, codec: c) + XCTAssertEqual(outgoingMetadata, metadata) + XCTAssertFalse(outgoing.manifest.metadata === source.manifest.metadata) + let charged = c.admission.bytesReserved + let retirement = c.admission.detachReservation(id: request(chunk).id) + backend.release(restored) + restored.removeAll() + XCTAssertEqual(backend.bytesReserved, 0) + XCTAssertEqual(c.admission.bytesReserved, charged) + if releaseLeaseFirst { retirement.release() } else { outgoing.close() } + XCTAssertEqual( + c.admission.bytesReserved, charged, + "both owners, in either destruction order, must retire") + if releaseLeaseFirst { outgoing.close() } else { retirement.release() } + outgoing.close() + retirement.release() + stage.close() + withExtendedLifetime((source, plan, sink, stage, outgoing)) { + XCTAssertTrue(plan.manifest.metadata === source.manifest.metadata) + XCTAssertTrue(stage.manifest.metadata === source.manifest.metadata) + XCTAssertEqual( + c.admission.bytesReserved, metadata + outgoingMetadata, + "both manifests remain valid after tensor/export retirement") + } + } + XCTAssertEqual(c.admission.bytesReserved, 0) + } + } + + func testCompactWindowPhysicalProofAndExportOwnCopyCharge() throws { + for dtype: DType in [.float16, .bfloat16, .float32] { + for window in [17, chunk + 3] { + let k = kinds(window: window) + let c = codec(k, dtype: dtype) + try withManifestScope { + let state = try rows(k, position: chunk, dtype: dtype) + let capture = try CBv2ContiguousHistoricalCheckpoint( + codec: c, position: chunk, chunkSize: chunk, state: state) + try capture.finishEvaluation() + let proof = try XCTUnwrap(capture.compactAllocationEvidence) + XCTAssertGreaterThan(proof.actual, 0) + XCTAssertGreaterThanOrEqual(proof.bound, proof.actual) + let measured = try capture.evaluationRoots.reduce(0) { total, array in + let info = try XCTUnwrap(array.evaluatedBufferInfo()) + XCTAssertTrue(info.isUnique) + XCTAssertTrue(info.isRowContiguous) + XCTAssertEqual(info.dataOffset, 0) + XCTAssertEqual(info.dataElements, array.size) + return total + info.allocatedBytes + } + XCTAssertEqual(proof.actual, measured) + let source = try capture.export( + codec: c, state: state, tokens: request(chunk).promptTokens, + cacheSalt: "tenant") + let metadata = try metadataBytes(source, codec: c) + let charged = c.admission.bytesReserved + capture.close() + capture.close() + XCTAssertEqual( + c.admission.bytesReserved, charged, "source still owns the immutable copies" + ) + XCTAssertFalse( + try source.readSegment(tensorIndex: 3, byteOffset: 0, maximumBytes: 256) + .isEmpty) + source.close() + source.close() + withExtendedLifetime((source, capture)) { + XCTAssertEqual( + c.admission.bytesReserved, metadata, + "closed export still owns its public manifest") + } + } + XCTAssertEqual(c.admission.bytesReserved, 0) + } + } + } + + func testCompactProofRejectsDonorAliasBeforePublication() throws { + let k = kinds() + let c = codec(k) + let state = try rows(k, position: chunk) + let capture = try CBv2ContiguousHistoricalCheckpoint( + codec: c, position: chunk, chunkSize: chunk, state: state) + capture.evaluate = { arrays in + let donor = state[0]!.snapshot() + let end = arrays[0].dim(2) + 1 + // Deliberate fault injection through MLX's exposed internal + // reference replacement, not a production cache operation. + arrays[0]._updateInternal(donor.keys[0 ..< 1, 0 ..< 1, 1 ..< end, 0...]) + arrays[1]._updateInternal(donor.values[0 ..< 1, 0 ..< 1, 1 ..< end, 0...]) + try withError { eval(arrays) } + } + XCTAssertThrowsError(try capture.finishEvaluation()) + XCTAssertNil(capture.compactAllocationEvidence) + XCTAssertThrowsError( + try capture.export( + codec: c, state: state, tokens: request(chunk).promptTokens, cacheSalt: "tenant")) + capture.close() + XCTAssertEqual(c.admission.bytesReserved, 0) + } + + func testManifestTamperingRefusedBeforeReservationOrNativeAllocation() throws { + let c = codec(kinds()) + let state = try rows(kinds(), position: chunk) + let source = try export(c, state, chunk) + defer { source.close() } + let data = try JSONEncoder().encode(source.manifest) + let mutations: [(inout [String: Any]) -> Void] = [ + { $0["backendLayout"] = CBv2CompleteCheckpointManifest.layout }, + { $0["backendLayout"] = CBv2CompleteCheckpointManifest.pagedLayout }, + { $0.removeValue(forKey: "attentionLayers") }, + { $0["assistantCodecID"] = "mtp" }, { $0["cacheSalt"] = "other" }, + { x in + var a = x["attentionLayers"] as! [[String: Any]] + a[0].removeValue(forKey: "valueHeadDim") + x["attentionLayers"] = a + }, + { x in + var a = x["attentionLayers"] as! [[String: Any]] + a[0]["valueHeadDim"] = 192 + x["attentionLayers"] = a + }, + { x in + var a = x["attentionLayers"] as! [[String: Any]] + a[0]["dtype"] = "float16" + x["attentionLayers"] = a + }, + { x in + var a = x["attentionLayers"] as! [[String: Any]] + for i in a.indices { a[i]["dtype"] = "float16" } + x["attentionLayers"] = a + var t = x["tensors"] as! [[String: Any]] + for i in t.indices { + t[i]["dtype"] = "float16" + t[i]["byteCount"] = (t[i]["byteCount"] as! Int) / 2 + } + x["tensors"] = t + }, + { x in + var a = x["attentionLayers"] as! [[String: Any]] + a[2]["owner"] = 1 + x["attentionLayers"] = a + }, + { x in + var a = x["tensors"] as! [[String: Any]] + a[1]["byteCount"] = 1 + x["tensors"] = a + }, + { x in + var a = x["tensors"] as! [[String: Any]] + a.removeLast() + x["tensors"] = a + }, + { x in + let a = x["tensors"] as! [[String: Any]] + x["tensors"] = a + [a[0]] + }, + ] + let reservation = c.admission.bytesReserved + StreamOrDevice.default.stream.synchronize() + let resources = Memory.numResources + for mutate in mutations { + var object = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + mutate(&object) + do { + let manifest = try JSONDecoder().decode( + CBv2CompleteCheckpointManifest.self, + from: JSONSerialization.data(withJSONObject: object)) + XCTAssertThrowsError(try c.plan(manifest: manifest, request: request(chunk))) + } catch { /* Decoding malformed structure is also a preallocation refusal. */ } + XCTAssertEqual(c.admission.bytesReserved, reservation) + } + XCTAssertLessThanOrEqual(Memory.numResources, resources) + } + + func testUnwrappedWindowRestoresPartialRingThenWraps() throws { + let k = kinds(window: chunk + 3) + let c = codec(k) + let original = try rows(k, position: chunk) + let source = try export(c, original, chunk) + defer { source.close() } + let plan = try c.plan(manifest: source.manifest, request: request(chunk)) + XCTAssertEqual(plan.destinationShapes[2], [1, 1, chunk + 3, 192]) + XCTAssertEqual(plan.destinationShapes[3], [1, 1, chunk + 3, 128]) + let sink = try plan.allocate {} + defer { sink.close() } + try transfer(source, sink) + let stage = try sink.finish() + defer { stage.close() } + try stage.consumePreparedState { prepared in + let restored = try XCTUnwrap(prepared.state[1]) + XCTAssertEqual(restored.retainedCount, chunk) + let keys = tensor( + heads: 1, start: chunk, count: 5, width: 192, dtype: .float32, bias: 0) + let values = tensor( + heads: 1, start: chunk, count: 5, width: 128, dtype: .float32, bias: -8) + let expected = original[1]!.update(keys: keys, values: values) + let actual = restored.update(keys: keys, values: values) + XCTAssertEqual(actual.0.asArray(Float.self), expected.0.asArray(Float.self)) + XCTAssertEqual(actual.1.asArray(Float.self), expected.1.asArray(Float.self)) + XCTAssertEqual(restored.retainedCount, chunk + 3) + XCTAssertEqual(restored.absoluteOffset, chunk + 5) + } + } + + func testHistoricalCopyPreservesFloatBitsAfterDonorOverwrite() throws { + for window in [17, chunk + 3] { + let k = kinds(window: window) + let c = codec(k) + let state = try rows(k, position: chunk) + let pattern: [Float] = [ + 0, -0.0, .infinity, -.infinity, Float(bitPattern: 0x7fc0_1234), 0.125, + ] + let v = MLXArray((0 ..< chunk * 128).map { pattern[$0 % pattern.count] }).reshaped([ + 1, 1, chunk, 128, + ]) + let special = CBv2WindowedSequenceKV( + window: window, kvHeads: 1, headDim: 192, valueHeadDim: 128) + _ = special.update( + keys: tensor( + heads: 1, start: 0, count: chunk, width: 192, dtype: .float32, bias: 0), + values: v) + var donor = state + donor[1] = special + let expected = special.snapshot().values.asArray(Float.self).map(\.bitPattern) + let capture = try CBv2ContiguousHistoricalCheckpoint( + codec: c, position: chunk, chunkSize: chunk, state: donor) + try capture.finishEvaluation() + _ = special.update( + keys: tensor( + heads: 1, start: chunk, count: window, width: 192, dtype: .float32, bias: 900), + values: tensor( + heads: 1, start: chunk, count: window, width: 128, dtype: .float32, bias: 900)) + let source = try capture.export( + codec: c, state: donor, tokens: request(chunk).promptTokens, cacheSalt: "tenant") + let data = try source.readSegment( + tensorIndex: 3, byteOffset: 0, maximumBytes: source.manifest.tensors[3].byteCount) + let actual = data.withUnsafeBytes { bytes in + (0 ..< expected.count).map { + bytes.loadUnaligned(fromByteOffset: $0 * 4, as: UInt32.self) + } + } + XCTAssertEqual(actual, expected) + source.close() + // Keep the original no-rollback oracle above. A chained successor + // may have overwritten the current ring before retirement rolls + // its unconfirmed token back; that cannot invalidate this capture. + let evidence = try XCTUnwrap(capture.compactAllocationEvidence) + XCTAssertEqual(special.retainedCount, window) + XCTAssertEqual(special.absoluteOffset, chunk + window) + for (rollback, remaining) in [(1, window - 1), (window - 1, 0)] { + special.rollback(rollback) // ordinary update above, NOT speculative staging + XCTAssertEqual(special.retainedCount, remaining) + XCTAssertEqual(special.absoluteOffset, chunk + remaining) + let before = c.admission.bytesReserved + XCTAssertThrowsError( + try c.validateContiguousRows(donor, position: chunk, exactWindow: false), + "The old historical guard rejects the shrunken current ring") + XCTAssertThrowsError( + try export(c, donor, chunk), + "Ordinary export must not pretend current history was restored") + XCTAssertEqual(c.admission.bytesReserved, before) + if remaining == 0 { + let empty = special.snapshot() + XCTAssertEqual(empty.values.shape, [1, 1, 0, 128]) + XCTAssertEqual( + empty.values.dtype, .float16, + "Empty live placeholders do not describe the captured FP32 window") + } + let rolled = try capture.export( + codec: c, state: donor, tokens: request(chunk).promptTokens, cacheSalt: "tenant" + ) + let bytes = try rolled.readSegment( + tensorIndex: 3, byteOffset: 0, + maximumBytes: rolled.manifest.tensors[3].byteCount) + let bits = bytes.withUnsafeBytes { raw in + (0 ..< expected.count).map { + raw.loadUnaligned(fromByteOffset: $0 * 4, as: UInt32.self) + } + } + XCTAssertEqual(bits, expected) + XCTAssertEqual(rolled.manifest.position, chunk) + XCTAssertEqual(rolled.manifest.tensors[3].shape, [1, 1, min(chunk, window), 128]) + XCTAssertEqual(capture.compactAllocationEvidence?.bound, evidence.bound) + XCTAssertEqual(capture.compactAllocationEvidence?.actual, evidence.actual) + rolled.close() + } + capture.close() + } + } + + func testInvalidRowsForeignCaptureOwnerAndPagedRefuseWithoutCharge() throws { + for learnedIndexer in [false, true] { + var unsupported = kinds() + if learnedIndexer { + unsupported[0].qwen4IndexerCompressRatio = 8 + } else { + unsupported[0].extraStorageBytesPerToken = 4 + } + let blocked = codec(unsupported) + XCTAssertNil(blocked.contiguousLayout) + XCTAssertThrowsError(try blocked.tensorDescriptors(position: chunk)) + XCTAssertEqual(blocked.admission.bytesReserved, 0) + } + let c = codec(kinds()) + let state = try rows(kinds(), position: chunk) + var invalid = state + invalid[2] = state[0] + XCTAssertThrowsError(try export(c, invalid, chunk)) + XCTAssertEqual(c.admission.bytesReserved, 0) + invalid = state + invalid[1] = state[0] + XCTAssertThrowsError(try export(c, invalid, chunk)) + XCTAssertEqual(c.admission.bytesReserved, 0) + let wrong = try rows(kinds(), position: chunk, dtype: .float16) + XCTAssertThrowsError(try export(c, wrong, chunk)) + XCTAssertEqual(c.admission.bytesReserved, 0) + let checkpoint = CBv2RecurrentCheckpoint( + position: chunk, chunkSize: chunk, layers: [:], byteCount: 0) + XCTAssertThrowsError( + try c.exportPaged( + checkpoint: checkpoint, state: state, tokens: request(chunk).promptTokens, + cacheSalt: "tenant")) + XCTAssertEqual(c.admission.bytesReserved, 0) + let capture = try CBv2ContiguousHistoricalCheckpoint( + codec: c, position: chunk, chunkSize: chunk, state: state) + try capture.finishEvaluation() + let foreign = try rows(kinds(), position: chunk) + let before = c.admission.bytesReserved + XCTAssertThrowsError( + try capture.export( + codec: c, state: foreign, tokens: request(chunk).promptTokens, cacheSalt: "tenant")) + XCTAssertEqual(c.admission.bytesReserved, before) + let foreignCodec = codec(kinds()) + XCTAssertEqual(foreignCodec.identity, c.identity) + XCTAssertThrowsError( + try capture.export( + codec: foreignCodec, state: state, tokens: request(chunk).promptTokens, + cacheSalt: "tenant"), + "Even matching metadata cannot move a capture to another loaded codec/Admission owner") + XCTAssertEqual(foreignCodec.admission.bytesReserved, 0) + invalid = state + invalid[2] = state[0] + XCTAssertThrowsError( + try capture.export( + codec: c, state: invalid, tokens: request(chunk).promptTokens, cacheSalt: "tenant")) + XCTAssertThrowsError( + try capture.export( + codec: c, state: Array(state.dropLast()), tokens: request(chunk).promptTokens, + cacheSalt: "tenant")) + state[0]!.rollback(1) + XCTAssertEqual(state[0]!.absoluteOffset, chunk - 1) + XCTAssertThrowsError( + try capture.export( + codec: c, state: state, tokens: request(chunk).promptTokens, cacheSalt: "tenant"), + "An immutable SWA copy does not authorize an unavailable full-attention prefix") + XCTAssertEqual(c.admission.bytesReserved, before) + capture.close() + XCTAssertEqual(c.admission.bytesReserved, 0) + } + + func testCancellationAndAllocationFailureReleaseExactlyOnce() throws { + let c = codec(kinds()) + let source = try export(c, rows(kinds(), position: chunk), chunk) + defer { source.close() } + let plan = try c.plan(manifest: source.manifest, request: request(chunk)) + let before = c.admission.bytesReserved + let releases = AsymmetricReleaseCount() + var sink: CBv2CompleteCheckpointImport? = try plan.allocate { releases.add() } + XCTAssertThrowsError(try sink!.finish()) + sink!.close() + sink!.close() + sink = nil + XCTAssertEqual(releases.value, 1) + XCTAssertEqual(c.admission.bytesReserved, before) + plan.evaluateDestinations = { _ in throw MLXError.caught("intentional allocation refusal") } + XCTAssertThrowsError(try plan.allocate { releases.add() }) + XCTAssertEqual(releases.value, 2) + XCTAssertEqual(c.admission.bytesReserved, before) + } + + func testRestoredFullRowSupportsFrozenReplayAndUnequalAppend() throws { + let k = kinds() + let c = codec(k) + let original = try rows(k, position: chunk) + let source = try export(c, original, chunk) + defer { source.close() } + let plan = try c.plan(manifest: source.manifest, request: request(chunk)) + let sink = try plan.allocate {} + defer { sink.close() } + try transfer(source, sink) + let stage = try sink.finish() + defer { stage.close() } + // Native snapshots borrow their row's lifetime; keep that owner while + // the frozen replay aliases its buffers, just like ordinary caches. + let restored = try stage.consumePreparedState { $0.state } + defer { withExtendedLifetime(restored) {} } + let snapshot = try XCTUnwrap(restored[0]).snapshot() + let frozen = CBv2FrozenReplayFullSequenceKV( + snapshot: snapshot, replayStart: chunk - 2, maxLength: chunk + 12, + kvHeads: 2, headDim: 192, valueHeadDim: 128) + _ = frozen.update( + keys: tensor( + heads: 2, start: chunk - 2, count: 2, width: 192, dtype: .float32, bias: 100), + values: tensor( + heads: 2, start: chunk - 2, count: 2, width: 128, dtype: .float32, bias: 100)) + XCTAssertEqual( + frozen.snapshot().values.asArray(Float.self), snapshot.values.asArray(Float.self)) + let key = tensor(heads: 2, start: chunk, count: 1, width: 192, dtype: .float32, bias: 0) + let value = tensor(heads: 2, start: chunk, count: 1, width: 128, dtype: .float32, bias: -8) + let actual = frozen.update(keys: key, values: value) + let expected = original[0]!.update(keys: key, values: value) + XCTAssertEqual(actual.1.shape, [1, 2, chunk + 1, 128]) + XCTAssertEqual(actual.1.asArray(Float.self), expected.1.asArray(Float.self)) + } +} diff --git a/Tests/MLXLMTests/CBv2AsymmetricContiguousTests.swift b/Tests/MLXLMTests/CBv2AsymmetricContiguousTests.swift new file mode 100644 index 0000000000..52c72674fc --- /dev/null +++ b/Tests/MLXLMTests/CBv2AsymmetricContiguousTests.swift @@ -0,0 +1,635 @@ +import Foundation +import MLX + +@testable import MLXLMCommon + +#if !ASYMMETRIC_CONTIGUOUS_PROBE + import XCTest +#endif + +private final class AsymmetricNativeProbeModel: CBv2SteppableModel { + let malformedValue: Bool + let mixedDType: Bool + private(set) var forwardCount = 0 + init(malformedValue: Bool = false, mixedDType: Bool = false) { + self.malformedValue = malformedValue + self.mixedDType = mixedDType + } + func forward(tokens: MLXArray, caches: [any CBv2AttendingLayerCache]) -> MLXArray { + forwardCount += 1 + let n = tokens.dim(1) + var result = MLXArray.zeros([1, n, 4]) + for cache in caches where cache.kind.sharesKVWithLayer == nil { + let kind = cache.kind + let q = MLXArray.ones([1, kind.queryHeads, n, kind.headDim]) + let k = MLXArray.ones([1, kind.kvHeads, n, kind.headDim]) + let v = MLXArray.ones( + [1, kind.kvHeads, n, kind.valueHeadDim + (malformedValue ? 1 : 0)], + dtype: mixedDType ? .float16 : .float32) + result = cache.updateAndAttend( + queries: q, keys: k, values: v, + scale: 0.25, sinks: nil) + } + return result + } +} + +private enum AsymmetricContiguousChecks { + struct Failure: Error { let message: String } + static func require(_ condition: Bool, _ message: String) throws { + if !condition { throw Failure(message: message) } + } + static func reject(_ body: () throws -> Void) throws { + do { + try body() + throw Failure(message: "invalid operation accepted") + } catch is CBv2KVError {} catch is CBv2CompleteCheckpointError {} + } + static func kind(window: Int? = nil, value: Int? = 4, shares: Int? = nil) -> CBv2LayerKind { + .init( + attention: window.map { .slidingWindow($0) } ?? .full, + sharesKVWithLayer: shares, hasSinks: true, + headDim: 8, valueHeadDim: value, kvHeads: 2, queryHeads: 4) + } + static func tile(_ range: Range, heads: Int = 2, width: Int, bias: Float = 0) -> MLXArray { + var data: [Float] = [] + data.reserveCapacity(heads * range.count * width) + for h in 0 ..< heads { + for t in range { + for d in 0 ..< width { + let position = Float(t) * 0.01 + let head = Float(h) * 0.1 + let dimension = Float(d) * 0.001 + data.append(bias + position + head + dimension) + } + } + } + return MLXArray(data, [1, heads, range.count, width]) + } + static func near(_ a: MLXArray, _ b: MLXArray, _ message: String) throws { + eval(a, b) + try require(a.shape == b.shape, message + " shape") + if a.size > 0 { + let error = abs(a - b).max().item(Float.self) + try require(error.isFinite && error < 3e-5, "\(message): error \(error)") + } + } + + // Scalar oracle never invokes the implementation's SDPA, mask or cache. + static func reference( + q: MLXArray, k: MLXArray, v: MLXArray, + firstPosition: Int, window: Int?, sinks: [Float], scale: Float + ) -> MLXArray { + let queries = q.asArray(Float.self) + let keys = k.asArray(Float.self) + let values = v.asArray(Float.self) + let qh = q.dim(1) + let kh = k.dim(1) + let count = q.dim(2) + let context = k.dim(2) + let dk = k.dim(3) + let dv = v.dim(3) + var result = [Float](repeating: 0, count: qh * count * dv) + for h in 0 ..< qh { + for t in 0 ..< count { + let position = firstPosition + t + let kvh = h / (qh / kh) + let start = window.map { max(0, position - $0 + 1) } ?? 0 + let end = min(position, context - 1) + var scores: [Float] = [] + for row in start ... end { + var dot: Float = 0 + for d in 0 ..< dk { + dot += + queries[(h * count + t) * dk + d] * keys[(kvh * context + row) * dk + d] + } + scores.append(dot * scale) + } + let maximum = max(scores.max()!, sinks[h]) + let probabilities = scores.map { exp($0 - maximum) } + let denominator = probabilities.reduce(0, +) + exp(sinks[h] - maximum) + for (index, row) in (start ... end).enumerated() { + for d in 0 ..< dv { + result[(h * count + t) * dv + d] += + probabilities[index] / denominator + * values[(kvh * context + row) * dv + d] + } + } + } + } + return MLXArray(result, [1, qh, count, dv]) + } + + static var identity: CBv2CompleteCheckpointIdentity { + .init( + modelAggregateHash: "fixture", promptContractID: "template", buildID: "probe", + numericsFingerprint: "fp32") + } + static func manifest(valueWidth: Int = 8) throws -> CBv2CompleteCheckpointManifest { + .init( + identity: identity, position: 8, chunkSize: 8, + prefixTokens: Array(repeating: 1, count: 8), + cacheSalt: nil, assistantCodecID: nil, + tensors: [ + try .init(role: .keys, layer: 0, shape: [1, 2, 8, 8], dtype: .float32), + try .init(role: .values, layer: 0, shape: [1, 2, 8, valueWidth], dtype: .float32), + ]) + } + + static func cases() -> [(String, () throws -> Void)] { + [ + ( + "uniform rows retain legacy cast-on-append storage and byte accounting", + { + let rows: [any CBv2SequenceKV] = [ + CBv2FullSequenceKV(promptLength: 2, maxLength: 12, kvHeads: 2, headDim: 8), + CBv2WindowedSequenceKV(window: 3, kvHeads: 2, headDim: 8), + ] + for row in rows { + _ = row.update( + keys: tile(0 ..< 2, width: 8), values: tile(0 ..< 2, width: 8, bias: 1)) + let allocated = row.byteCount + let k = tile(2 ..< 3, width: 8).asType(.float16) + let v = tile(2 ..< 3, width: 8, bias: 1).asType(.float16) + _ = row.update(keys: k, values: v) + let snapshot = row.snapshot() + try require( + snapshot.keys.dtype == .float32 && snapshot.values.dtype == .float32, + "legacy allocation dtype changed") + try require( + row.byteCount == allocated, + "same-capacity append changed reserved storage") + try near( + snapshot.keys[0..., 0..., 2 ..< 3, 0...], k.asType(.float32), + "legacy key cast") + try near( + snapshot.values[0..., 0..., 2 ..< 3, 0...], v.asType(.float32), + "legacy value cast") + } + } + ), + ( + "asymmetric full growth keeps the original storage dtype in both cast directions", + { + for (stored, incoming): (DType, DType) in [ + (.float32, .float16), (.float16, .float32), + ] { + let row = CBv2FullSequenceKV( + promptLength: 1, maxLength: 400, + kvHeads: 2, headDim: 8, valueHeadDim: 4) + _ = row.update( + keys: tile(0 ..< 1, width: 8).asType(stored), + values: tile(0 ..< 1, width: 4).asType(stored)) + let tailK = tile(1 ..< 258, width: 8).asType(incoming) + let tailV = tile(1 ..< 258, width: 4).asType(incoming) + _ = row.update(keys: tailK, values: tailV) + let snapshot = row.snapshot() + try require( + snapshot.keys.dtype == stored && snapshot.values.dtype == stored, + "growth changed the native allocation dtype") + try require( + row.byteCount == 400 * 2 * (8 + 4) * stored.size, "grown byte count") + try near( + snapshot.values[0..., 0..., 257 ..< 258, 0...].asType(.float32), + tailV[0..., 0..., 256 ..< 257, 0...].asType(stored).asType(.float32), + "grown cast values") + } + } + ), + ( + "window temporary promotion preserves the ring and charges speculative incoming bytes", + { + let row = CBv2WindowedSequenceKV( + window: 3, kvHeads: 2, headDim: 8, valueHeadDim: 4) + _ = row.update( + keys: tile(0 ..< 2, width: 8).asType(.float16), + values: tile(0 ..< 2, width: 4).asType(.float16)) + let result = row.update( + keys: tile(2 ..< 4, width: 8), values: tile(2 ..< 4, width: 4)) + try require( + result.0.dtype == .float32 && result.1.dtype == .float32, + "pre-eviction attention promotion changed") + try require( + row.snapshot().values.dtype == .float16 && row.byteCount == 3 * 2 * 12 * 2, + "temporary promotion changed ring residency") + row.beginSpeculativeWrite() + _ = row.update(keys: tile(4 ..< 6, width: 8), values: tile(4 ..< 6, width: 4)) + try require( + row.byteCount == 3 * 2 * 12 * 2 + 2 * 2 * 12 * 4, + "staged native-byte accounting") + row.rollback(1) + row.commitSpeculativeWrite() + let snapshot = row.snapshot() + eval(snapshot.keys, snapshot.values) + try require( + snapshot.values.dtype == .float16 && row.byteCount == 3 * 2 * 12 * 2, + "committed ring dtype or storage changed") + } + ), + ( + "implicit value width follows mutation and explicit equality is semantic", + { + var implicit = kind(value: nil) + var explicit = kind(value: 8) + try require(implicit == explicit, "implicit/explicit equal geometry differs") + implicit.headDim = 16 + explicit.headDim = 16 + try require( + implicit.valueHeadDim == 16 && explicit.valueHeadDim == 8, + "value override semantics") + explicit.valueHeadDim = 16 + try require(implicit == explicit, "resolved equality ignores value width") + try require( + kind().kvGeometry?.bytesPerToken(elementBytes: 4) == 96, "pair byte formula" + ) + try require( + kind().kvGeometry?.bytesPerToken(elementBytes: 4, extraBytes: 7) == 103, + "extra bytes multiplied by dtype") + } + ), + ( + "contiguous reservations and admission count both widths exactly once", + { + var full = kind() + full.extraStorageBytesPerToken = 17 + let kinds = [full, kind(window: 3)] + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 1 << 20, kvDType: .float32)) + let rows = try backend.makeSequenceState( + layerKinds: kinds, promptLength: 1, maxLength: 400) + try require( + backend.bytesReserved == (257 + 3) * 96 && backend.bytesInUse == 0, + "initial reservations") + let admission = AdmissionV2( + layerKinds: kinds, bytesCapacity: 1 << 20, + config: .init(watermarkFraction: 0, elementBytes: 4)) + try require( + admission.estimatedBytes(forTokens: 7) == (7 + 3) * 96, + "admission bytes or duplicate auxiliary charge") + backend.release(rows) + try require( + backend.bytesReserved == 0 && backend.bytesInUse == 0, + "retirement leaked reservation") + } + ), + ( + "invalid geometry overflow and borrower widths reject before registration", + { + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: Int.max / 4, kvDType: .float32)) + var invalid: [[CBv2LayerKind]] = [] + for width in [0, -1, Int.max] { + var bad = kind() + bad.valueHeadDim = width + invalid.append([bad]) + } + var badHeads = kind() + badHeads.queryHeads = 3 + invalid.append([badHeads]) + var overflow = kind() + overflow.headDim = Int(Int32.max) + overflow.valueHeadDim = Int(Int32.max) + overflow.kvHeads = Int(Int32.max) + overflow.queryHeads = Int(Int32.max) + invalid.append([overflow]) + invalid.append([kind(), kind(value: 8, shares: 0)]) + for kinds in invalid { + try reject { + _ = try backend.makeSequenceState( + layerKinds: kinds, promptLength: 1, maxLength: 8) + } + try require( + backend.bytesReserved == 0 && backend.bytesInUse == 0, + "invalid geometry registered rows") + } + try reject { + _ = try backend.makeSequenceState( + layerKinds: [kind()], promptLength: -1, maxLength: 8) + } + try reject { + _ = try backend.makeSequenceState( + layerKinds: [kind()], promptLength: 1, maxLength: Int.max) + } + } + ), + ( + "full cache empty snapshots growth rollback and restored destinations keep value width", + { + let row = CBv2FullSequenceKV( + promptLength: 1, maxLength: 400, kvHeads: 2, headDim: 8, valueHeadDim: 4) + try require( + row.snapshot().keys.shape == [1, 2, 0, 8] + && row.snapshot().values.shape == [1, 2, 0, 4], "empty shapes") + _ = row.update( + keys: tile(0 ..< 260, width: 8), values: tile(0 ..< 260, width: 4, bias: 1)) + try near( + row.snapshot().values, tile(0 ..< 260, width: 4, bias: 1), "grown values") + try require(row.byteCount == 260 * 96, "first allocation adopts required rows") + _ = row.update( + keys: tile(260 ..< 300, width: 8), + values: tile(260 ..< 300, width: 4, bias: 1)) + try require(row.byteCount == 400 * 96, "capped growth bytes") + row.rollback(3) + try near( + row.snapshot().values, tile(0 ..< 297, width: 4, bias: 1), "rollback values" + ) + let restored = try CBv2FullSequenceKV( + restoredKeys: tile(0 ..< 12, width: 8), + restoredValues: tile(0 ..< 12, width: 4, bias: 1), offset: 7, maxLength: 12, + kvHeads: 2, headDim: 8, valueHeadDim: 4) + try near( + restored.snapshot().values, tile(0 ..< 7, width: 4, bias: 1), + "restored values") + try reject { + _ = try CBv2FullSequenceKV( + restoredKeys: tile(0 ..< 12, width: 8), + restoredValues: tile(0 ..< 12, width: 8), offset: 7, maxLength: 12, + kvHeads: 2, headDim: 8, valueHeadDim: 4) + } + } + ), + ( + "window history retains unequal widths through wrap and speculative rollback", + { + let row = CBv2WindowedSequenceKV( + window: 3, kvHeads: 2, headDim: 8, valueHeadDim: 4) + try require(row.snapshot().values.shape == [1, 2, 0, 4], "empty window shape") + _ = row.update( + keys: tile(0 ..< 5, width: 8), values: tile(0 ..< 5, width: 4, bias: 1)) + try near( + row.snapshot().values, tile(2 ..< 5, width: 4, bias: 1), + "chunk greater than ring") + row.beginSpeculativeWrite() + _ = row.update( + keys: tile(5 ..< 8, width: 8), values: tile(5 ..< 8, width: 4, bias: 1)) + row.rollback(2) + row.commitSpeculativeWrite() + try near(row.snapshot().keys, tile(3 ..< 6, width: 8), "committed ring keys") + try near( + row.snapshot().values, tile(3 ..< 6, width: 4, bias: 1), + "committed ring values") + try require(row.byteCount == 3 * 96, "window allocation bytes") + } + ), + ( + "frozen replay preserves authoritative values then appends with independent widths", + { + let row = CBv2FrozenReplayFullSequenceKV( + snapshot: (tile(0 ..< 5, width: 8), tile(0 ..< 5, width: 4, bias: 1), 5), + replayStart: 2, maxLength: 12, kvHeads: 2, headDim: 8, valueHeadDim: 4) + let replay = row.update( + keys: tile(2 ..< 5, width: 8, bias: 99), + values: tile(2 ..< 5, width: 4, bias: 99)) + try near( + replay.1, tile(0 ..< 5, width: 4, bias: 1), + "poison replay did not alter stored values") + _ = row.update( + keys: tile(5 ..< 6, width: 8), values: tile(5 ..< 6, width: 4, bias: 1)) + try require(row.byteCount == 12 * 96, "frozen append capacity bytes") + row.rollback(1) + try near( + row.snapshot().values, tile(0 ..< 5, width: 4, bias: 1), + "frozen append rollback") + } + ), + ( + "in-memory prefix adoption validates role shapes and leaves no failed owners", + { + let kinds = [kind()] + let capability = CBv2PrefixReuseCapability.derive( + layerKinds: kinds, backend: .contiguousUnquantized) + guard + let plan = capability.plan( + matchedBoundary: 5, exactStagedFullKVBytes: 5 * 96, + maximumSequenceLength: 12) + else { throw Failure(message: "missing reuse plan") } + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 1 << 20, kvDType: .float32)) + for values in [ + tile(0 ..< 5, width: 8), tile(0 ..< 5, width: 4).asType(.float16), + MLXArray.zeros([1]), + ] { + try reject { + _ = try backend.makeSequenceState( + adopting: [(tile(0 ..< 5, width: 8), values, 5)], + plan: plan, layerKinds: kinds, maxLength: 12) + } + try require(backend.bytesReserved == 0, "invalid snapshot registered owner") + } + let rows = try backend.makeSequenceState( + adopting: [(tile(0 ..< 5, width: 8), tile(0 ..< 5, width: 4, bias: 1), 5)], + plan: plan, layerKinds: kinds, maxLength: 12) + try require(backend.bytesReserved == 12 * 96, "adopted native bytes") + try near( + rows[0]!.snapshot().values, tile(0 ..< 5, width: 4, bias: 1), + "adopted values") + backend.release(rows) + } + ), + ( + "full sliding and last-query attention output value width matches scalar oracle", + { + let count = 7 + let q = tile(0 ..< 7, heads: 4, width: 8, bias: 0.3) + let k = tile(0 ..< 7, width: 8) + let v = tile(0 ..< 7, width: 4, bias: 1) + let sinkValues: [Float] = [0, 0.5, -0.5, 1] + let sinks = MLXArray(sinkValues) + for window: Int? in [nil, 3] { + let kind = kind(window: window) + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 1 << 20, kvDType: .float32)) + let rows = try backend.makeSequenceState( + layerKinds: [kind], promptLength: count, maxLength: 12) + let output = CBv2AttentionV1.updateAndAttend( + rows: [rows[0]!], kind: kind, + queries: q, keys: k, values: v, scale: 0.25, sinks: sinks) + try near( + output, + reference( + q: q, k: k, v: v, firstPosition: 0, + window: window, sinks: sinkValues, scale: 0.25), + "asymmetric attention") + backend.release(rows) + } + let row = CBv2FullSequenceKV( + promptLength: count, maxLength: 12, kvHeads: 2, headDim: 8, valueHeadDim: 4) + let last = CBv2AttentionV1.updateAndAttendLastQuery( + rows: [row], kind: kind(), + queries: q[0..., 0..., 6 ..< 7, 0...], keys: k, values: v, scale: 0.25, + sinks: sinks) + try near( + last, + reference( + q: q[0..., 0..., 6 ..< 7, 0...], k: k, v: v, + firstPosition: 6, window: nil, sinks: sinkValues, scale: 0.25), + "last-query output") + try require( + last.shape == [1, 4, 1, 4] && row.absoluteOffset == count, + "last query committed wrong geometry") + } + ), + ( + "native probe observes separate widths and drains rejected shape or dtype state", + { + let kinds = [kind()] + func caches() -> [any CBv2AttendingLayerCache] { + [CBv2LayerCache(layerIndex: 0, kind: kinds[0])] + } + let goodCaches = caches() + let result = try CBv2NativeKVTypeProbe.run( + model: AsymmetricNativeProbeModel(), layerKinds: kinds, caches: goodCaches) + try require( + result.observations.count == 2 + && result.observations.allSatisfy { + $0.keysShape.last == 8 && $0.valuesShape.last == 4 + }, "probe dimensions") + try require(goodCaches.allSatisfy { $0.rows.isEmpty }, "probe retained owner") + for model in [ + AsymmetricNativeProbeModel(malformedValue: true), + AsymmetricNativeProbeModel(mixedDType: true), + ] { + let bound = caches() + try reject { + _ = try CBv2NativeKVTypeProbe.run( + model: model, layerKinds: kinds, caches: bound) + } + try require( + bound.allSatisfy { $0.rows.isEmpty }, "rejected probe retained owner") + } + } + ), + ( + "native probe rejects invalid borrower geometry before any forward or row binding", + { + let owner = kind() + for borrower in [ + kind(value: 8, shares: 0), kind(window: 3, shares: 0), + kind(shares: -1), kind(shares: 2), kind(shares: 1), + ] { + let kinds = [owner, borrower] + let caches: [any CBv2AttendingLayerCache] = kinds.enumerated().map { + CBv2LayerCache(layerIndex: $0.offset, kind: $0.element) + } + let model = AsymmetricNativeProbeModel() + try reject { + _ = try CBv2NativeKVTypeProbe.run( + model: model, layerKinds: kinds, caches: caches) + } + try require( + model.forwardCount == 0 && caches.allSatisfy { $0.rows.isEmpty }, + "invalid ownership reached model or retained probe rows") + } + } + ), + ( + "asymmetric paging refuses before constructing physical storage", + { + let asymmetric = CBv2LayerKind( + attention: .full, headDim: 192, valueHeadDim: 128, kvHeads: 4, + queryHeads: 64) + try reject { + _ = try PagedKVBackend( + layerKinds: [asymmetric], config: .init(capacityBytes: 1 << 20)) + } + } + ), + ( + "complete codec refuses every export import and historical route without reservation", + { + let kinds = [ + CBv2LayerKind( + attention: .full, headDim: 192, valueHeadDim: 128, kvHeads: 4, + queryHeads: 64) + ] + let admission = AdmissionV2(layerKinds: kinds, bytesCapacity: 1 << 20) + let checkpoint = CBv2RecurrentCheckpoint( + position: 8, chunkSize: 8, layers: [:], byteCount: 0) + let tokens = Array(repeating: 1, count: 9) + let request = CBv2Request(id: .init(1), promptTokens: tokens, maxTokens: 1) + let initial = admission.bytesReserved + for paged: PagedKVPoolConfig? in [nil, .init(capacityBytes: 1 << 20)] { + let codec = CBv2CompleteCheckpointCodec( + identity: identity, layerKinds: kinds, recurrentSpec: nil, + kvDTypes: [.float32], assistant: nil, admission: admission, + pagedConfig: paged) + try require( + codec.unsupportedAsymmetricGeometry, + "codec did not retain refusal state") + try reject { _ = try codec.tensorDescriptors(position: 8) } + try reject { _ = try codec.plan(manifest: manifest(), request: request) } + try reject { + _ = try codec.export( + checkpoint: checkpoint, kv: [nil], tokens: tokens, cacheSalt: nil) + } + try reject { + _ = try codec.export( + checkpoint: checkpoint, state: [nil], tokens: tokens, cacheSalt: nil + ) + } + try reject { + _ = try codec.exportPaged( + checkpoint: checkpoint, state: [nil], tokens: tokens, cacheSalt: nil + ) + } + try reject { + _ = try codec.historicalReusePlan(position: 8, maximumSequenceLength: 9) + } + try require( + admission.bytesReserved == initial + && admission.transientBytesReserved == 0 + && codec.historicalLayout == nil, + "refused codec obtained a reservation/owner") + } + } + ), + ( + "uniform manifest stays valid while asymmetric tensor descriptors are refused", + { + let uniform = try manifest() + try require( + try uniform.validateStructure() == 2 * 2 * 8 * 8 * 4, + "uniform manifest bytes changed") + let decoded = try JSONDecoder().decode( + CBv2CompleteCheckpointManifest.self, from: JSONEncoder().encode(uniform)) + try require(decoded == uniform, "uniform manifest roundtrip") + try reject { _ = try manifest(valueWidth: 4).validateStructure() } + } + ), + ] + } +} + +#if ASYMMETRIC_CONTIGUOUS_PROBE + @main + private struct AsymmetricContiguousProbe { + static func main() throws { + let cases = AsymmetricContiguousChecks.cases() + var failures = 0 + for (name, body) in cases { + do { + try body() + print("PASS \(name)") + } catch { + failures += 1 + print("FAIL \(name): \(error)") + } + } + print( + "RESULT discovered=\(cases.count) passed=\(cases.count-failures) failed=\(failures) skipped=0" + ) + if failures > 0 { + throw AsymmetricContiguousChecks.Failure( + message: "asymmetric contiguous probe failed") + } + } + } +#else + final class CBv2AsymmetricContiguousTests: XCTestCase { + func testAsymmetricContiguousContracts() throws { + for (name, body) in AsymmetricContiguousChecks.cases() { + do { try body() } catch { XCTFail("\(name): \(error)") } + } + } + } +#endif diff --git a/Tests/MLXLMTests/CBv2AsymmetricPagedAttentionTests.swift b/Tests/MLXLMTests/CBv2AsymmetricPagedAttentionTests.swift new file mode 100644 index 0000000000..a790302c63 --- /dev/null +++ b/Tests/MLXLMTests/CBv2AsymmetricPagedAttentionTests.swift @@ -0,0 +1,486 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLMCommon + +private final class AsymPagedEngineModel: CBv2SteppableModel { + func forward(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> MLXArray { + let b = tokens.dim(0) + let n = tokens.dim(1) + var hidden = tokens.asType(.float32).reshaped([b, 1, n, 1]) / Float(32) + for cache in caches { + let q = MLXArray.zeros([b, 2, n, cache.kind.headDim], dtype: .float32) + let k = broadcast(hidden, to: [b, 1, n, cache.kind.headDim]) + let v = broadcast(hidden, to: [b, 1, n, cache.kind.valueHeadDim]) + let output = cache.updateAndAttend( + queries: q, keys: k, values: v, scale: 0.125, sinks: nil) + hidden = mean(output, axes: [1, 3], keepDims: true) + } + let target = MLX.round(hidden.reshaped([b, n, 1]) * Float(128)).asType(.int32) % 31 + return MLX.where(MLXArray(Int32(0) ..< Int32(32)) .== target, Float(10), Float(-10)) + } +} + +private func asymPagedCollect(_ stream: AsyncStream) async -> ([Int], CBv2FinishReason?) +{ + let task = Task { () -> ([Int], CBv2FinishReason?) in + var tokens: [Int] = [] + for await event in stream { + switch event { + case .delta(_, let ids, _): tokens.append(contentsOf: ids) + case .finished(let reason, _): return (tokens, reason) + } + } + return (tokens, nil) + } + let watchdog = Task { + try? await Task.sleep(nanoseconds: 20_000_000_000) + task.cancel() + } + let result = await task.value + watchdog.cancel() + return result +} + +final class CBv2AsymmetricPagedAttentionTests: XCTestCase { + private func engine(paged: Bool) throws -> (EngineV2, CBv2KVBackend) { + let kinds = [asymPagedKind(window: 17), asymPagedKind()] + let backend: CBv2KVBackend + let bank: CBv2LayerCacheBank + if paged { + let limits = try CBv2PagedGatheredAttentionLimits( + maximumBatchSize: 2, maximumQueryTokens: 16, + maximumContextTokens: 128, maximumInFlightGraphs: 2, maximumScratchBytes: 512 << 20) + let value = try PagedKVBackend( + layerKinds: kinds, + config: .init( + capacityBytes: 512 << 20, dtype: .float32, + maxPrefillChunk: 16, nominalMaxSequenceLength: 128, maxBufferLength: 4 << 20, + segmentSizeBytes: 128 << 10, layerDTypes: [.float32, .float32], + gatheredAttention: limits)) + backend = value + bank = CBv2LayerCacheBank(caches: value.makeLayerCaches()) + } else { + backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 512 << 20, kvDType: .float32)) + bank = CBv2LayerCacheBank(layerKinds: kinds) + } + return ( + EngineV2( + model: AsymPagedEngineModel(), layerKinds: kinds, backend: backend, + cacheProvider: bank, sampler: CBv2DefaultSampler(fallbackSeed: 0), + schedulerConfig: .init( + maxConcurrentRequests: 2, maxBatchedTokensPerStep: 16, prefillChunkSize: 16, + maxWaiting: 4, enablePrefixCache: false), + admissionConfig: .init(watermarkFraction: 0, elementBytes: 4)), backend + ) + } + + func testRealEngineSegmentedGatheredTokensMatchOrdinaryAndRetirePages() async throws { + let request = CBv2Request( + id: .init(1), promptTokens: (0 ..< 41).map { ($0 * 7) % 29 }, + sampling: .init(temperature: 0, seed: 0), maxTokens: 5) + let (cold, _) = try engine(paged: false) + let (paged, backend) = try engine(paged: true) + let expected = await asymPagedCollect(try cold.submit(request)) + let actual = await asymPagedCollect(try paged.submit(request)) + XCTAssertEqual(expected.1, .length) + XCTAssertEqual(actual.1, .length) + XCTAssertEqual(actual.0, expected.0) + await cold.shutdown() + await paged.shutdown() + XCTAssertEqual(backend.bytesReserved, 0) + let pool = try XCTUnwrap((backend as? PagedKVBackend)?.pool) + XCTAssertEqual(pool.bytesMaterialized, 0) + XCTAssertEqual(paged.admissionForTesting.bytesReserved, pool.gatheredAttentionScratchBound) + } + + func testRealEngineCancellationDrainsPageWritesAndKeepsOnlyPoolScratch() async throws { + let (value, backend) = try engine(paged: true) + value.loopForTesting.onEngineQueueSync { + value.loopForTesting.suspendStepExecutionAtCountForTesting = 1 + } + let stream = try value.submit( + .init(id: .init(2), promptTokens: Array(repeating: 1, count: 64), maxTokens: 8)) + let deadline = Date().addingTimeInterval(5) + while value.stepCount < 1 && Date() < deadline { + try await Task.sleep(nanoseconds: 5_000_000) + } + XCTAssertEqual(value.stepCount, 1) + value.cancel(.init(2)) + value.loopForTesting.onEngineQueueSync { + value.loopForTesting.suspendStepExecutionAtCountForTesting = nil + } + let result = await asymPagedCollect(stream) + XCTAssertEqual(result.1, .cancelled) + await value.shutdown() + XCTAssertEqual(backend.bytesReserved, 0) + let pool = try XCTUnwrap((backend as? PagedKVBackend)?.pool) + XCTAssertEqual(pool.bytesMaterialized, 0) + XCTAssertEqual(value.admissionForTesting.bytesReserved, pool.gatheredAttentionScratchBound) + } + private func scalarOracle( + query: [Float], start: Int, count: Int, keyWidth: Int, valueWidth: Int, + dtype: DType, window: Int?, scale: Float, sinks: [Float] + ) -> [Float] { + var result = [Float](repeating: 0, count: 2 * count * valueWidth) + for h in 0 ..< 2 { + for t in 0 ..< count { + let end = start + t + 1 + let begin = window.map { max(0, end - $0) } ?? 0 + var scores: [Double] = [] + for token in begin ..< end { + var dot = Double(0) + for d in 0 ..< keyWidth { + let k = asymPagedRounded(Float(token) / 32 + Float(d) / 1024, dtype: dtype) + dot += Double(query[(h * count + t) * keyWidth + d]) * Double(k) + } + scores.append(dot * Double(scale)) + } + let sink = Double(asymPagedRounded(sinks[h], dtype: dtype)) + let maximum = max(scores.max()!, sink) + let weights = scores.map { exp($0 - maximum) } + let denominator = weights.reduce(0, +) + exp(sink - maximum) + for d in 0 ..< valueWidth { + var sum = Double(0) + for (i, token) in (begin ..< end).enumerated() { + let v = asymPagedRounded( + -4 + Float(token) / 32 + Float(d) / 1024, dtype: dtype) + sum += weights[i] * Double(v) + } + result[(h * count + t) * valueWidth + d] = Float(sum / denominator) + } + } + } + return result + } + + func testNativeGatheredAttentionMatchesIndependentScalarAndOrdinaryCache() throws { + for (dk, dv) in [(192, 128), (128, 192)] { + for dtype: DType in [.float16, .bfloat16, .float32] { + for window: Int? in [nil, 17] { + let kind = asymPagedKind(dk, dv, window: window, sinks: true) + let f = try AsymPagedFixture([kind], dtype: dtype) + let rows = try f.rows() + let cache = f.backend.makeLayerCaches()[0] + cache.setRows(rows.compactMap { $0 }) + XCTAssertEqual(cache.nativeAttentionPath, "paged_native_gathered") + let ordinary: CBv2SequenceKV = + window.map { + CBv2WindowedSequenceKV( + window: $0, kvHeads: 1, headDim: dk, valueHeadDim: dv) + as CBv2SequenceKV + } + ?? CBv2FullSequenceKV( + promptLength: 0, maxLength: 128, kvHeads: 1, headDim: dk, + valueHeadDim: dv) + let sinkValues: [Float] = [0.125, -0.25] + let sinks = MLXArray(sinkValues).asType(dtype) + var start = 0 + for count in [16, 1, 16, 1] { + let q = + (asymPagedTensor( + heads: 2, start: start, count: count, width: dk, dtype: dtype, + bias: 0.25) * Float(0.125)).asType(dtype) + let k = asymPagedTensor(start: start, count: count, width: dk, dtype: dtype) + let v = asymPagedTensor( + start: start, count: count, width: dv, dtype: dtype, bias: -4) + let output = cache.updateAndAttend( + queries: q, keys: k, values: v, scale: 0.03125, sinks: sinks) + let direct = CBv2AttentionV1.updateAndAttend( + rows: [ordinary], kind: kind, + queries: q, keys: k, values: v, scale: 0.03125, sinks: sinks) + eval([output, direct] + cache.innerState()) + try f.backend.pool.writeValidation.check() + XCTAssertEqual(output.shape, [1, 2, count, dv]) + XCTAssertEqual(output.dtype, dtype) + let expected = scalarOracle( + query: q.asType(.float32).asArray(Float.self), start: start, + count: count, + keyWidth: dk, valueWidth: dv, dtype: dtype, window: window, + scale: 0.03125, sinks: sinkValues) + let actual = output.asType(.float32).asArray(Float.self) + let contiguous = direct.asType(.float32).asArray(Float.self) + let tolerance: Float = + dtype == .float32 ? 0.0002 : (dtype == .float16 ? 0.008 : 0.06) + XCTAssertEqual(actual.count, expected.count) + for i in actual.indices { + XCTAssertEqual(actual[i], expected[i], accuracy: tolerance) + XCTAssertEqual(actual[i], contiguous[i], accuracy: tolerance) + } + start += count + } + } + } + } + } + + func testPackedRowsAndBorrowersAreIndependent() throws { + let kinds = [asymPagedKind(window: 17), asymPagedKind(window: 17, shares: 0)] + let f = try AsymPagedFixture(kinds) + let a = try f.rows() + let b = try f.rows() + let caches = f.backend.makeLayerCaches() + let source = caches[0] + let borrower = caches[1] + source.setRows([a[0]!, b[0]!]) + borrower.setRows([]) + let q = MLXArray.ones([2, 2, 16, 192], dtype: .float32) * Float(0.01) + let k0 = asymPagedTensor(start: 0, count: 16, width: 192, dtype: .float32) + let k = concatenated([k0, k0 + Float(3)], axis: 0) + let v0 = asymPagedTensor(start: 0, count: 16, width: 128, dtype: .float32, bias: -4) + let v = concatenated([v0, v0 + Float(9)], axis: 0) + let own = source.updateAndAttend(queries: q, keys: k, values: v, scale: 0.1, sinks: nil) + let borrowed = borrower.attendBorrowing(source: source, queries: q, scale: 0.1, sinks: nil) + eval([own, borrowed] + source.innerState() + borrower.innerState()) + XCTAssertEqual(own.asArray(Float.self), borrowed.asArray(Float.self)) + XCTAssertGreaterThan( + borrowed[1].mean().item(Float.self) - borrowed[0].mean().item(Float.self), 8) + XCTAssertNil(a[1]) + XCTAssertNil(b[1]) + XCTAssertEqual(a[0]!.absoluteOffset, 16) + source.setRows([b[0]!]) + let q1 = MLXArray.ones([1, 2, 1, 192]) * Float(0.01) + let next = source.updateAndAttend( + queries: q1, + keys: asymPagedTensor(start: 16, count: 1, width: 192, dtype: .float32, bias: 3), + values: asymPagedTensor(start: 16, count: 1, width: 128, dtype: .float32, bias: 5), + scale: 0.1, sinks: nil) + eval([next] + source.innerState()) + XCTAssertEqual(a[0]!.absoluteOffset, 16) + XCTAssertEqual(b[0]!.absoluteOffset, 17) + } + + /// Both owning layers intentionally share a geometry group, but contain + /// different values. Standalone caches retain chunk views by default, so + /// the wrong-source prefill would otherwise read valid but foreign views. + private func assertWrongOwnerRefusedBeforeRead(queryCount: Int) throws { + let kinds = [asymPagedKind(), asymPagedKind(), asymPagedKind(shares: 0)] + let f = try AsymPagedFixture(kinds, batch: 1, queries: 16) + let states = try f.rows() + let rows = try (0 ..< 2).map { try XCTUnwrap(states[$0] as? PagedSequenceKV) } + let caches = f.backend.makeLayerCaches() + let expectedSource = caches[0] + let wrongSource = caches[1] + let borrower = caches[2] + expectedSource.setRows([rows[0]]) + wrongSource.setRows([rows[1]]) + borrower.setRows([]) + XCTAssertEqual(rows[0].groupKey, rows[1].groupKey) + XCTAssertEqual(borrower.kind.sharesKVWithLayer, 0) + XCTAssertNotEqual(wrongSource.layerIndex, borrower.kind.sharesKVWithLayer) + let q = MLXArray.zeros([1, 2, queryCount, 192], dtype: .float32) + let k = MLXArray.zeros([1, 1, queryCount, 192], dtype: .float32) + let v0 = MLXArray.ones([1, 1, queryCount, 128], dtype: .float32) * Float(3) + let v1 = MLXArray.ones([1, 1, queryCount, 128], dtype: .float32) * Float(9) + let own0 = expectedSource.updateAndAttend( + queries: q, keys: k, values: v0, scale: 0.125, sinks: nil) + let own1 = wrongSource.updateAndAttend( + queries: q, keys: k, values: v1, scale: 0.125, sinks: nil) + let correct = borrower.attendBorrowing( + source: expectedSource, queries: q, scale: 0.125, sinks: nil) + eval([own0, own1, correct] + expectedSource.innerState() + wrongSource.innerState()) + StreamOrDevice.default.stream.synchronize() + try f.backend.pool.writeValidation.check() + XCTAssertEqual(correct.shape, [1, 2, queryCount, 128]) + for value in correct.asArray(Float.self) { XCTAssertEqual(value, 3, accuracy: 0.00001) } + for value in own1.asArray(Float.self) { XCTAssertEqual(value, 9, accuracy: 0.00001) } + + let group = f.backend.pool.group(rows[0].groupKey) + let fence = group.writeFence + let offsets = rows.map(\.absoluteOffset) + let tables = rows.map(\.table) + let versions = rows.map(\.tableVersion) + let bytes = rows.map(\.byteCount) + let reserved = f.backend.bytesReserved + let wired = f.backend.bytesWired + let backingBytes = Dictionary( + uniqueKeysWithValues: group.segments.map { + ($0.key, $0.value.storage.asData(access: .copy).data) + }) + let refused = borrower.attendBorrowing( + source: wrongSource, queries: q, scale: 0.125, sinks: nil) + XCTAssertThrowsError(try f.backend.pool.writeValidation.check()) + XCTAssertEqual(refused.shape, [1, 2, queryCount, 128]) + XCTAssertTrue( + group.writeFence === fence, "wrong owner must be rejected before a gather/read fence") + XCTAssertEqual(rows.map(\.absoluteOffset), offsets) + XCTAssertEqual(rows.map(\.table), tables) + XCTAssertEqual(rows.map(\.tableVersion), versions) + XCTAssertEqual(rows.map(\.byteCount), bytes) + XCTAssertEqual(f.backend.bytesReserved, reserved) + XCTAssertEqual(f.backend.bytesWired, wired) + XCTAssertEqual(Set(group.segments.keys), Set(backingBytes.keys)) + for (index, segment) in group.segments { + XCTAssertEqual(segment.storage.asData(access: .copy).data, backingBytes[index]) + } + // Never evaluate the refused output or clear its latch to keep serving. + // Fixture retirement drains the already completed valid work only. + } + + func testWrongLayerWithIdenticalGeometryRefusesBeforeDecodeGather() throws { + try assertWrongOwnerRefusedBeforeRead(queryCount: 1) + } + + func testWrongLayerWithIdenticalGeometryRefusesBeforeRetainedPrefillRead() throws { + try assertWrongOwnerRefusedBeforeRead(queryCount: 16) + } + + func testDTypeValueWidthQueryAndExecutionFaultsDoNotWrite() throws { + for fault in ["dtype", "value", "query", "querydtype", "sink", "limit", "mtp"] { + let dtype: DType = fault == "sink" ? .bfloat16 : .float32 + let f = try AsymPagedFixture( + [asymPagedKind(sinks: fault == "sink")], dtype: dtype, queries: 16) + let rows = try f.rows() + let cache = f.backend.makeLayerCaches()[0] + cache.setRows(rows.compactMap { $0 }) + let group = f.backend.pool.group(f.backend.pool.groupKey(forLayer: 0)) + let fence = group.writeFence + let count = fault == "limit" ? 17 : 1 + let q = MLXArray.ones( + [1, 2, count, fault == "query" ? 64 : 192], + dtype: fault == "querydtype" ? .float16 : dtype) + let k = MLXArray.ones([1, 1, count, 192], dtype: dtype) + let v = MLXArray.ones( + [1, 1, count, fault == "value" ? 192 : 128], + dtype: fault == "dtype" ? .float16 : dtype) + if fault == "mtp" { cache.mtpSerializesRectangularAttention = true } + let output = cache.updateAndAttend( + queries: q, keys: k, values: v, scale: 0.1, + sinks: fault == "sink" ? MLXArray.zeros([2], dtype: .float32) : nil) + XCTAssertThrowsError(try f.backend.pool.writeValidation.check()) + XCTAssertEqual(output.shape, [1, 2, count, 128]) + XCTAssertEqual(rows[0]!.absoluteOffset, 0) + XCTAssertEqual(rows[0]!.byteCount, 0) + XCTAssertTrue(group.writeFence === fence) + } + } + + func testForeignDuplicateAndReleasedRowsRefuseWithoutMutation() throws { + for scenario in ["foreign", "duplicate", "released"] { + let f = try AsymPagedFixture([asymPagedKind()]) + let other = try AsymPagedFixture([asymPagedKind()]) + let rows = try f.rows() + let foreign = try other.rows() + let cache = f.backend.makeLayerCaches()[0] + cache.setRows(rows.compactMap { $0 }) + let original = cache.rows.map(ObjectIdentifier.init) + if scenario == "foreign" { cache.setRows(foreign.compactMap { $0 }) } + if scenario == "duplicate" { cache.setRows([rows[0]!, rows[0]!]) } + if scenario == "released" { + f.backend.release(rows) + cache.setRows(rows.compactMap { $0 }) + } + XCTAssertThrowsError(try f.backend.pool.writeValidation.check()) + XCTAssertEqual(cache.rows.map(ObjectIdentifier.init), original) + XCTAssertEqual(foreign[0]!.absoluteOffset, 0) + } + } + + func testNativeFullAndWindowRestorePreservesBoundaryAndContinues() throws { + let kinds = [asymPagedKind(), asymPagedKind(window: 17)] + let f = try AsymPagedFixture(kinds) + let source = try f.rows() + for start in stride(from: 0, to: 48, by: 16) { + for row in source.compactMap({ $0 }) { + _ = row.update( + keys: asymPagedTensor(start: start, count: 16, width: 192, dtype: .float32), + values: asymPagedTensor( + start: start, count: 16, width: 128, dtype: .float32, bias: -4)) + } + } + let snapshots = source.map { $0?.snapshot() } + for s in snapshots.compactMap({ $0 }) { eval(s.keys, s.values) } + let plan = CBv2PrefixReusePlan( + backend: .pagedFP16, strategy: .frozenFullReplay, matchedBoundary: 48, + replayStart: 48, replayTokens: 0, prefillTokensSaved: 48, restoredFullTokens: 48, + capacityReservationTokens: 128, nominalFullKVBytesPerToken: 1280, + fullKVBytesPerToken: 1280, + additionalFullKVBytesPerToken: 0, initialAdditionalCapacityBytes: 0, + fullCapacityTokensReserved: 128, + stagedFullKVBytes: 48 * 1280, residentFullKVBytes: 48 * 1280) + let restored = try f.backend.makeSequenceState( + adopting: snapshots, plan: plan, layerKinds: kinds, maxLength: 128) + f.owned.append(restored) + for i in 0 ..< 2 { + XCTAssertEqual(restored[i]!.absoluteOffset, 48) + let current = restored[i]!.snapshot() + eval(current.keys, current.values) + XCTAssertEqual( + current.keys.asData(access: .copy).data, + snapshots[i]!.keys.asData(access: .copy).data) + XCTAssertEqual( + current.values.asData(access: .copy).data, + snapshots[i]!.values.asData(access: .copy).data) + let k = asymPagedTensor(start: 48, count: 1, width: 192, dtype: .float32) + let v = asymPagedTensor(start: 48, count: 1, width: 128, dtype: .float32, bias: -4) + let expected = source[i]!.update(keys: k, values: v) + let actual = restored[i]!.update(keys: k, values: v) + eval(expected.0, expected.1, actual.0, actual.1) + XCTAssertEqual(actual.0.asArray(Float.self), expected.0.asArray(Float.self)) + XCTAssertEqual(actual.1.asArray(Float.self), expected.1.asArray(Float.self)) + } + let before = f.backend.bytesReserved + var wrong = snapshots + wrong[1] = (snapshots[1]!.keys, MLXArray.zeros([1, 1, 17, 192]), 48) + XCTAssertThrowsError( + try f.backend.makeSequenceState( + adopting: wrong, plan: plan, layerKinds: kinds, maxLength: 128)) + XCTAssertEqual(f.backend.bytesReserved, before) + } + + func testUniformDefaultDispatchAndOutputRemainUnchanged() throws { + let kind = asymPagedKind(64, 64) + let backend = try PagedKVBackend( + layerKinds: [kind], + config: .init( + capacityBytes: 4 << 20, + maxPrefillChunk: 16, segmentSizeBytes: 32 << 10)) + XCTAssertEqual(backend.pool.gatheredAttentionScratchBound, 0) + let rows = try backend.makeSequenceState(layerKinds: [kind], promptLength: 0, maxLength: 32) + defer { + StreamOrDevice.default.stream.synchronize() + backend.release(rows) + } + let cache = backend.makeLayerCaches()[0] + cache.setRows(rows.compactMap { $0 }) + let q = MLXArray.ones([1, 2, 1, 64], dtype: .float16) + let k = MLXArray.ones([1, 1, 1, 64], dtype: .float16) + let output = cache.updateAndAttend( + queries: q, keys: k, values: k * Float(3), scale: 0.125, sinks: nil) + eval([output] + cache.innerState()) + XCTAssertEqual(output.shape, [1, 2, 1, 64]) + XCTAssertTrue(output.asType(.float32).asArray(Float.self).allSatisfy { abs($0 - 3) < 0.01 }) + XCTAssertNotEqual(cache.nativeAttentionPath, "paged_native_gathered") + } + + func testFullFrozenReplayDoesNotOverwriteAdoptedAsymmetricValues() throws { + let f = try AsymPagedFixture([asymPagedKind()]) + let source = try f.rows() + _ = source[0]!.update( + keys: asymPagedTensor(start: 0, count: 48, width: 192, dtype: .float32), + values: asymPagedTensor(start: 0, count: 48, width: 128, dtype: .float32, bias: -4)) + let snapshot = source[0]!.snapshot() + eval(snapshot.keys, snapshot.values) + let plan = CBv2PrefixReusePlan( + backend: .pagedFP16, strategy: .frozenFullReplay, matchedBoundary: 48, + replayStart: 32, replayTokens: 16, prefillTokensSaved: 32, restoredFullTokens: 48, + capacityReservationTokens: 128, nominalFullKVBytesPerToken: 1280, + fullKVBytesPerToken: 1280, + additionalFullKVBytesPerToken: 0, initialAdditionalCapacityBytes: 0, + fullCapacityTokensReserved: 128, + stagedFullKVBytes: 48 * 1280, residentFullKVBytes: 48 * 1280) + let restored = try f.backend.makeSequenceState( + adopting: [snapshot], plan: plan, layerKinds: f.kinds, maxLength: 128) + f.owned.append(restored) + XCTAssertEqual(restored[0]!.absoluteOffset, 32) + _ = restored[0]!.update( + keys: asymPagedTensor(start: 32, count: 16, width: 192, dtype: .float32, bias: 99), + values: asymPagedTensor(start: 32, count: 16, width: 128, dtype: .float32, bias: 99)) + let final = restored[0]!.snapshot() + eval(final.keys, final.values) + XCTAssertEqual( + final.values.asData(access: .copy).data, snapshot.values.asData(access: .copy).data) + } +} diff --git a/Tests/MLXLMTests/CBv2AsymmetricPagedStorageTests.swift b/Tests/MLXLMTests/CBv2AsymmetricPagedStorageTests.swift new file mode 100644 index 0000000000..1b2df0b97f --- /dev/null +++ b/Tests/MLXLMTests/CBv2AsymmetricPagedStorageTests.swift @@ -0,0 +1,421 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLMCommon + +// Shared native fixtures, no model files and no replacement storage/backend. +func asymPagedKind( + _ key: Int = 192, _ value: Int = 128, window: Int? = nil, + heads: Int = 1, queries: Int = 2, shares: Int? = nil, sinks: Bool = false +) -> CBv2LayerKind { + .init( + attention: window.map { .slidingWindow($0) } ?? .full, sharesKVWithLayer: shares, + hasSinks: sinks, + headDim: key, valueHeadDim: value, kvHeads: heads, queryHeads: queries) +} +func asymPagedValues(heads: Int, start: Int, count: Int, width: Int, bias: Float) -> [Float] { + (0 ..< heads * count * width).map { i in + bias + Float(i / (count * width)) / 4 + Float(start + (i / width) % count) / 32 + Float( + i % width) / 1024 + } +} +func asymPagedTensor( + heads: Int = 1, start: Int, count: Int, width: Int, dtype: DType, bias: Float = 0 +) -> MLXArray { + MLXArray(asymPagedValues(heads: heads, start: start, count: count, width: width, bias: bias)) + .reshaped([1, heads, count, width]).asType(dtype) +} +func asymPagedRounded(_ value: Float, dtype: DType) -> Float { + if dtype == .float16 { return Float(Float16(value)) } + if dtype == .bfloat16 { + let bits = value.bitPattern + return Float(bitPattern: (bits &+ 0x7fff &+ ((bits >> 16) & 1)) & 0xffff_0000) + } + return value +} +final class AsymPagedFixture { + let kinds: [CBv2LayerKind] + let backend: PagedKVBackend + let admission: AdmissionV2 + var owned: [[CBv2SequenceKV?]] = [] + init( + _ kinds: [CBv2LayerKind], dtype: DType = .float32, batch: Int = 2, + context: Int = 128, queries: Int = 32, capacity: Int = 512 << 20, + processOwner: (any CBv2ProcessMemoryOwner)? = nil + ) throws { + self.kinds = kinds + let limits = try CBv2PagedGatheredAttentionLimits( + maximumBatchSize: batch, maximumQueryTokens: queries, + maximumContextTokens: context, maximumInFlightGraphs: 2, maximumScratchBytes: 512 << 20) + let config = PagedKVPoolConfig( + capacityBytes: capacity, dtype: dtype, maxPrefillChunk: 32, + nominalMaxSequenceLength: context, maxBufferLength: 4 << 20, + segmentSizeBytes: 128 << 10, + layerDTypes: Array(repeating: dtype, count: kinds.count), gatheredAttention: limits) + backend = try PagedKVBackend(layerKinds: kinds, config: config) + admission = AdmissionV2( + layerKinds: kinds, bytesCapacity: capacity, + config: .init( + watermarkFraction: 0, elementBytes: dtype.size, + layerElementBytes: Array(repeating: dtype.size, count: kinds.count)), + residency: backend.kvResidency, processMemoryOwner: processOwner) + backend.pool.bindAdmission(admission) + } + func rows(maximum: Int = 128) throws -> [CBv2SequenceKV?] { + let value = try backend.makeSequenceState( + layerKinds: kinds, promptLength: 0, maxLength: maximum) + owned.append(value) + return value + } + deinit { + StreamOrDevice.default.stream.synchronize() + for rows in owned { backend.release(rows) } + owned.removeAll() + } +} + +/// Records calls from real Admission/physical backing owners; it does not +/// replace allocation, page storage or the engine's ledger arithmetic. +private final class AsymPagedProcessReceipt: CBv2ProcessMemoryOwner, @unchecked Sendable { + let maximum: UInt64 + private let lock = NSLock() + private var c: UInt64 = 0, m: UInt64 = 0 + var charge: UInt64 { lock.withLock { c } } + var coverage: UInt64 { lock.withLock { m } } + init(maximum: UInt64) { self.maximum = maximum } + func replaceCharge(_ bytes: UInt64) throws { + try lock.withLock { + guard bytes <= maximum, bytes >= m else { + throw MLXError.caught("intentional process reservation refusal") + } + c = bytes + } + } + func recordMaterialization(_ bytes: UInt64) throws { + try lock.withLock { + guard bytes <= c - m else { + throw MLXError.caught("materialization exceeded real charge") + } + m += bytes + } + } + func withdrawCoverage(_ bytes: UInt64) throws { + try lock.withLock { + guard bytes <= m else { throw MLXError.caught("duplicate materialization withdrawal") } + m -= bytes + } + } + func retire() { lock.withLock { c = 0 } } +} + +final class CBv2AsymmetricPagedStorageTests: XCTestCase { + func testGroupIdentityBytesAndLegacyDescription() throws { + let implicit = PagedKVGroupKey(kvHeads: 2, headDim: 64) + let explicit = PagedKVGroupKey(kvHeads: 2, headDim: 64, valueHeadDim: 64) + XCTAssertEqual(implicit, explicit) + XCTAssertEqual(implicit.description, "kv2xd64-float16-full") + let asymmetric = PagedKVGroupKey( + kvHeads: 2, headDim: 192, dtype: .bfloat16, valueHeadDim: 128) + XCTAssertNotEqual(asymmetric, PagedKVGroupKey(kvHeads: 2, headDim: 192, dtype: .bfloat16)) + XCTAssertEqual(asymmetric.geometry?.storageBytes(tokens: 16, elementBytes: 2), 20480) + XCTAssertTrue(asymmetric.description.contains("d192v128")) + for width in [0, -1, Int.max] { + XCTAssertThrowsError( + try PagedKVPool( + layerKinds: [asymPagedKind(192, width)], config: .init(capacityBytes: 1 << 20))) + } + } + + func testFixedAndSegmentedShuffledPageMappingBothWidthOrdersAndDTypes() throws { + for segmented in [false, true] { + for (dk, dv) in [(192, 128), (128, 192)] { + for dtype: DType in [.float16, .bfloat16, .float32] { + let kind = asymPagedKind(dk, dv, heads: 2, queries: 4) + let pageBytes = 2 * 16 * (dk + dv) * dtype.size + let pool = try PagedKVPool( + layerKinds: [kind], + config: .init( + capacityBytes: 4 << 20, dtype: dtype, + maxPrefillChunk: 32, nominalMaxSequenceLength: 128, + maxBufferLength: 4 << 20, + segmentSizeBytes: segmented ? pageBytes * 3 : nil)) + let key = pool.groupKey(forLayer: 0) + let group = pool.group(key) + try pool.reserve([key: 5]) + if segmented { + try pool.materializeReservedSegments() + } else { + try pool.materializeSlabs() + } + let allocated = (0 ..< 5).map { _ in pool.allocatePage(group: key) } + let pages = Array(allocated.reversed()) + defer { + StreamOrDevice.default.stream.synchronize() + pool.freePages(group: key, pages: allocated) + pool.unreserve([key: 5]) + } + let first = 3 + let count = 68 + let keys = asymPagedTensor( + heads: 2, start: 0, count: count, width: dk, dtype: dtype) + let values = asymPagedTensor( + heads: 2, start: 0, count: count, width: dv, dtype: dtype, bias: -4) + let slots = (0 ..< count).map { i in + pages[(first + i) / 16] * 16 + Int32((first + i) % 16) + } + pool.writeTokens( + group: key, slots: slots, keys: keys.squeezed(axis: 0), + values: values.squeezed(axis: 0)) + let read = pool.gather(group: key, pages: pages, firstSlot: first, count: count) + eval(read.keys, read.values) + XCTAssertEqual(read.keys.shape, [1, 2, count, dk]) + XCTAssertEqual(read.values.shape, [1, 2, count, dv]) + XCTAssertEqual( + read.keys.asData(access: .copy).data, keys.asData(access: .copy).data) + XCTAssertEqual( + read.values.asData(access: .copy).data, values.asData(access: .copy).data) + // Independent host address oracle checks physical regions, + // not another invocation of the gather implementation. + let segmentData = Dictionary( + uniqueKeysWithValues: group.segments.map { + ($0.key, $0.value.storage.asType(.float32).asArray(Float.self)) + }) + let fixedKeys = + segmented ? [] : group.kSlab.asType(.float32).asArray(Float.self) + let fixedValues = + segmented ? [] : group.vSlab.asType(.float32).asArray(Float.self) + for h in 0 ..< 2 { + for token in 0 ..< count { + let slot = Int(slots[token]) + let page = slot / 16 + let within = slot % 16 + let kRaw: [Float] + let vRaw: [Float] + let base: Int + let local: Int + if segmented { + let segment = group.segment(for: Int32(page)) + kRaw = segmentData[segment.index]! + vRaw = kRaw + base = segment.valueOffset + local = page - segment.pages.lowerBound + XCTAssertEqual(segment.storage.ndim, 1) + XCTAssertEqual(segment.byteCount, segment.pages.count * pageBytes) + XCTAssertGreaterThanOrEqual( + segment.allocatedBytes, segment.byteCount) + } else { + kRaw = fixedKeys + vRaw = fixedValues + base = 0 + local = page + } + for d in [0, dk - 1] { + let expected = Float(h) / 4 + Float(token) / 32 + Float(d) / 1024 + XCTAssertEqual( + kRaw[((local * 2 + h) * 16 + within) * dk + d], + asymPagedRounded(expected, dtype: dtype)) + } + for d in [0, dv - 1] { + let expected = + -Float(4) + Float(h) / 4 + Float(token) / 32 + Float(d) / 1024 + XCTAssertEqual( + vRaw[base + ((local * 2 + h) * 16 + within) * dv + d], + asymPagedRounded(expected, dtype: dtype)) + } + } + } + if segmented { + XCTAssertGreaterThan(group.segments.count, 1) + let firstSegment = group.segments[group.segments.keys.min()!]! + let rebaseLayout = try PagedKVSegmentLayout( + pageCount: firstSegment.pages.count * 2, + pageBytes: pageBytes, targetBytes: pageBytes * 3, + maximumBufferBytes: 4 << 20) + let rebased = PagedKVSegment( + rebasing: firstSegment, index: 1, layout: rebaseLayout) + XCTAssertTrue(rebased.backing === firstSegment.backing) + XCTAssertEqual(rebased.valueOffset, firstSegment.valueOffset) + XCTAssertEqual(rebased.allocatedBytes, firstSegment.allocatedBytes) + for segment in group.segments.values { + let raw = segmentData[segment.index]! + XCTAssertTrue(raw[0 ..< 2 * 16 * dk].allSatisfy { $0 == 0 }) + XCTAssertTrue( + raw[segment.valueOffset ..< segment.valueOffset + 2 * 16 * dv] + .allSatisfy { $0 == 0 }) + } + } else { + XCTAssertEqual( + group.keySlabBytes + group.valueSlabBytes, group.pageCount * pageBytes) + } + let empty = pool.gather(group: key, pages: [], firstSlot: 0, count: 0) + XCTAssertEqual(empty.keys.shape, [1, 2, 0, dk]) + XCTAssertEqual(empty.values.shape, [1, 2, 0, dv]) + } + } + } + } + + func testWindowWrapRollbackAndOverwriteFence() throws { + let f = try AsymPagedFixture([asymPagedKind(window: 17)]) + let rows = try f.rows() + let row = try XCTUnwrap(rows[0] as? PagedSequenceKV) + for start in stride(from: 0, to: 80, by: 16) { + _ = row.update( + keys: asymPagedTensor(start: start, count: 16, width: 192, dtype: .float32), + values: asymPagedTensor( + start: start, count: 16, width: 128, dtype: .float32, bias: -4)) + let s = row.snapshot() + eval(s.keys, s.values) + let count = min(start + 16, 17) + XCTAssertEqual( + s.values.asArray(Float.self), + asymPagedValues( + heads: 1, start: start + 16 - count, count: count, width: 128, bias: -4)) + } + let preserved = row.snapshot() + eval(preserved.keys, preserved.values) + let expected = preserved.values.asArray(Float.self) + row.beginSpeculativeWrite() + _ = row.update( + keys: asymPagedTensor(start: 80, count: 3, width: 192, dtype: .float32, bias: 5), + values: asymPagedTensor(start: 80, count: 3, width: 128, dtype: .float32, bias: 5)) + row.rollback(3) + row.commitSpeculativeWrite() + let restored = row.snapshot() + eval(restored.keys, restored.values) + XCTAssertEqual(row.absoluteOffset, 80) + XCTAssertEqual(restored.values.asArray(Float.self), expected) + // The gather's back-edge must preserve old data even when constructed + // lazily before a later page overwrite in the same evaluation graph. + let before = row.snapshot() + _ = row.update( + keys: asymPagedTensor(start: 80, count: 32, width: 192, dtype: .float32, bias: 8), + values: asymPagedTensor(start: 80, count: 32, width: 128, dtype: .float32, bias: 8)) + let after = row.snapshot() + eval(before.values, after.values) + XCTAssertEqual(before.values.asArray(Float.self), expected) + } + + func testWindowSnapshotExplicitValueWidthAndNativeBoundaryContract() throws { + let k = asymPagedTensor(start: 16, count: 17, width: 192, dtype: .float32) + let v = asymPagedTensor(start: 16, count: 17, width: 128, dtype: .float32) + XCTAssertNil(CBv2PagedWindowSnapshot(keys: k, values: v, base: 16)) + XCTAssertNil(CBv2PagedWindowSnapshot(keys: k, values: v, base: 16, valueHeadDim: 192)) + XCTAssertNil(CBv2PagedWindowSnapshot(keys: k, values: v, base: Int.max, valueHeadDim: 128)) + let snapshot = try XCTUnwrap( + CBv2PagedWindowSnapshot(keys: k, values: v, base: 16, valueHeadDim: 128)) + try snapshot.requireAdmissible(at: 33, window: 17) + XCTAssertThrowsError(try snapshot.requireAdmissible(at: 32, window: 17)) + XCTAssertThrowsError(try snapshot.requireAdmissible(at: 33, window: 18)) + } + + func testFixedAttentionMissingPolicyAndUnboundOwnerRefuse() throws { + let kind = asymPagedKind() + XCTAssertThrowsError( + try PagedKVBackend(layerKinds: [kind], config: .init(capacityBytes: 4 << 20))) + let limits = try CBv2PagedGatheredAttentionLimits( + maximumBatchSize: 1, maximumQueryTokens: 16, + maximumContextTokens: 64, maximumInFlightGraphs: 2, maximumScratchBytes: 128 << 20) + XCTAssertThrowsError( + try PagedKVBackend( + layerKinds: [kind], + config: .init(capacityBytes: 128 << 20, gatheredAttention: limits))) + let backend = try PagedKVBackend( + layerKinds: [kind], + config: .init( + capacityBytes: 128 << 20, + maxPrefillChunk: 16, segmentSizeBytes: 128 << 10, gatheredAttention: limits)) + XCTAssertThrowsError( + try backend.makeSequenceState(layerKinds: [kind], promptLength: 0, maxLength: 64)) + XCTAssertEqual(backend.bytesReserved, 0) + XCTAssertEqual(backend.bytesWired, 0) + XCTAssertThrowsError( + try CBv2PagedGatheredAttentionLimits( + maximumBatchSize: 1, maximumQueryTokens: 16, + maximumContextTokens: 64, maximumInFlightGraphs: 1, maximumScratchBytes: 128 << 20)) + } + + func testScratchRefusalLiveRequestBoundAndAllocationFailurePreserveOwners() throws { + let kind = asymPagedKind() + let tiny = try CBv2PagedGatheredAttentionLimits( + maximumBatchSize: 1, maximumQueryTokens: 16, + maximumContextTokens: 64, maximumInFlightGraphs: 2, maximumScratchBytes: 1) + XCTAssertThrowsError(try tiny.scratchUpperBound(layerKinds: [kind], pageSize: 16)) + let f = try AsymPagedFixture([kind], batch: 1) + XCTAssertThrowsError(try f.rows(maximum: 129)) + XCTAssertEqual(f.admission.bytesReserved, 0) + let rows = try f.rows() + let bound = f.backend.pool.gatheredAttentionScratchBound + XCTAssertGreaterThan(bound, 0) + XCTAssertGreaterThanOrEqual(f.admission.bytesReserved, bound + f.backend.bytesWired) + let before = f.admission.bytesReserved + XCTAssertThrowsError(try f.rows()) + XCTAssertEqual(f.admission.bytesReserved, before) + f.backend.release(rows) + XCTAssertEqual(f.backend.bytesReserved, 0) + XCTAssertEqual( + f.admission.bytesReserved, bound, + "pool-scoped scratch remains held, not reported as measured usage") + f.backend.pool.slabEval = { _ in + throw MLXError.caught("intentional asymmetric page allocation failure") + } + XCTAssertThrowsError(try f.rows()) + XCTAssertEqual(f.backend.bytesReserved, 0) + XCTAssertEqual(f.backend.bytesWired, 0) + XCTAssertEqual(f.admission.bytesReserved, bound) + } + + func testValueOnlyBorrowerMismatchRefusesBeforeNativeAllocation() throws { + let kinds = [asymPagedKind(), asymPagedKind(192, 64, shares: 0)] + let config = PagedKVPoolConfig(capacityBytes: 1 << 20, segmentSizeBytes: 128 << 10) + XCTAssertThrowsError(try PagedKVPool(layerKinds: kinds, config: config)) + XCTAssertNil(PagedAttentionKernel.ineligibilityReason(headDim: 128, gqa: 2)) + XCTAssertNotNil( + PagedAttentionKernel.ineligibilityReason(headDim: 192, gqa: 2), + "direct fused asymmetric support is not claimed") + } + + func testScratchLeaseDropsOnlyWithFinalPoolOwner() throws { + var fixture: AsymPagedFixture? = try AsymPagedFixture([asymPagedKind()]) + let admission = fixture!.admission + var rows = try fixture!.rows() + let bound = fixture!.backend.pool.gatheredAttentionScratchBound + fixture!.backend.release(rows) + fixture!.owned.removeAll() + fixture = nil + XCTAssertEqual( + admission.bytesReserved, bound, "released row aliases still retain their pool") + rows.removeAll() + XCTAssertEqual(admission.bytesReserved, 0) + } + + func testRealPhysicalReceiptsAndScratchShareProcessAdmissionWithoutInventedCoverage() throws { + let denied = AsymPagedProcessReceipt(maximum: 0) + do { + let f = try AsymPagedFixture([asymPagedKind()], processOwner: denied) + XCTAssertThrowsError(try f.rows()) + XCTAssertEqual(f.backend.bytesReserved, 0) + XCTAssertEqual(f.backend.bytesWired, 0) + XCTAssertEqual(denied.charge, 0) + XCTAssertEqual(denied.coverage, 0) + } + let owner = AsymPagedProcessReceipt(maximum: 512 << 20) + do { + let f = try AsymPagedFixture([asymPagedKind()], processOwner: owner) + let rows = try f.rows() + let actual = f.backend.pool.groupKeys.reduce(0) { + $0 + f.backend.pool.group($1).segments.values.reduce(0) { $0 + $1.allocatedBytes } + } + XCTAssertEqual(owner.coverage, UInt64(actual)) + XCTAssertEqual(owner.charge, UInt64(f.admission.bytesReserved)) + XCTAssertGreaterThanOrEqual( + owner.charge, UInt64(actual + f.backend.pool.gatheredAttentionScratchBound)) + f.backend.release(rows) + XCTAssertEqual(owner.coverage, 0) + XCTAssertEqual(owner.charge, UInt64(f.backend.pool.gatheredAttentionScratchBound)) + } + XCTAssertEqual(owner.coverage, 0) + XCTAssertEqual(owner.charge, 0) + } +} diff --git a/Tests/MLXLMTests/CBv2ContiguousCheckpointCompletionTests.swift b/Tests/MLXLMTests/CBv2ContiguousCheckpointCompletionTests.swift new file mode 100644 index 0000000000..3fb337e738 --- /dev/null +++ b/Tests/MLXLMTests/CBv2ContiguousCheckpointCompletionTests.swift @@ -0,0 +1,102 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLMCommon + +final class CBv2ContiguousCheckpointCompletionTests: XCTestCase { + private func fixture() throws -> ( + CBv2CompleteCheckpointCodec, CBv2ContiguousHistoricalCheckpoint + ) { + let chunk = max(32, CBv2AttentionV1.queryBlockSize) + let kinds: [CBv2LayerKind] = [ + .init( + attention: .slidingWindow(17), headDim: 192, valueHeadDim: 128, + kvHeads: 1, queryHeads: 2) + ] + let codec = CBv2CompleteCheckpointCodec( + identity: .init( + modelAggregateHash: "synthetic", promptContractID: "test", + buildID: "test", numericsFingerprint: "float32"), + layerKinds: kinds, recurrentSpec: nil, kvDTypes: [.float32], assistant: nil, + admission: .init( + layerKinds: kinds, bytesCapacity: 1 << 20, + config: .init(watermarkFraction: 0, elementBytes: 4))) + let row = CBv2WindowedSequenceKV(window: 17, kvHeads: 1, headDim: 192, valueHeadDim: 128) + let pair = row.update( + keys: MLXArray(Int32(0) ..< Int32(chunk * 192)).asType(.float32).reshaped([ + 1, 1, chunk, 192, + ]), + values: MLXArray(Int32(0) ..< Int32(chunk * 128)).asType(.float32).reshaped([ + 1, 1, chunk, 128, + ])) + try withError { eval(pair.0, pair.1) } + return (codec, try .init(codec: codec, position: chunk, chunkSize: chunk, state: [row])) + } + + func testFailedRequiredCompletionKeepsActualBuffersAndChargeAfterClose() throws { + var prepared: (CBv2CompleteCheckpointCodec, CBv2ContiguousHistoricalCheckpoint)? = + try fixture() + let codec = prepared!.0 + var capture: CBv2ContiguousHistoricalCheckpoint? = prepared!.1 + prepared = nil + weak var wrapper = capture + weak var actualRoot = capture?.evaluationRoots.first + let charge = codec.admission.bytesReserved + XCTAssertGreaterThan(charge, 0) + XCTAssertNotNil(actualRoot) + capture?.beforeRequiredDrainForTesting = { + throw MLXError.caught("intentional required-completion failure") + } + XCTAssertThrowsError(try capture!.finishEvaluation()) + XCTAssertTrue(capture!.completionFailed) + XCTAssertNil(capture!.compactAllocationEvidence) + capture!.close() + capture!.close() + capture = nil + XCTAssertNil(wrapper) + XCTAssertNotNil( + actualRoot, "a byte ledger alone cannot keep in-flight native buffers alive") + XCTAssertEqual( + codec.admission.bytesReserved, charge, + "uncertain required completion cannot refund the owner on close") + } + + func testRemovingFailureInjectionCannotRetryOrRefundFailedCompletion() throws { + let (codec, capture) = try fixture() + let charge = codec.admission.bytesReserved + var drainAttempts = 0 + capture.beforeRequiredDrainForTesting = { + drainAttempts += 1 + throw MLXError.caught("intentional required-completion failure") + } + XCTAssertThrowsError(try capture.finishEvaluation()) + XCTAssertEqual(drainAttempts, 1) + capture.beforeRequiredDrainForTesting = nil + XCTAssertThrowsError(try capture.finishEvaluation()) + capture.close() + XCTAssertTrue(capture.completionFailed) + XCTAssertEqual(codec.admission.bytesReserved, charge) + } + + func testUnsubmittedCloseReleasesWithoutInventingCompletion() throws { + let (codec, capture) = try fixture() + capture.beforeRequiredDrainForTesting = { + XCTFail("unsubmitted lazy copies have no submitted native work to drain") + throw MLXError.caught("unexpected drain") + } + XCTAssertGreaterThan(codec.admission.bytesReserved, 0) + capture.close() + XCTAssertFalse(capture.completionFailed) + XCTAssertEqual(codec.admission.bytesReserved, 0) + } + + func testSuccessfulNativeCompletionStillReleasesNormally() throws { + let (codec, capture) = try fixture() + try capture.finishEvaluation() + XCTAssertNotNil(capture.compactAllocationEvidence) + XCTAssertFalse(capture.completionFailed) + capture.close() + XCTAssertEqual(codec.admission.bytesReserved, 0) + } +} diff --git a/Tests/MLXLMTests/CBv2ContiguousHistoricalCheckpointTests.swift b/Tests/MLXLMTests/CBv2ContiguousHistoricalCheckpointTests.swift new file mode 100644 index 0000000000..4a002b88e3 --- /dev/null +++ b/Tests/MLXLMTests/CBv2ContiguousHistoricalCheckpointTests.swift @@ -0,0 +1,286 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLMCommon + +/// One-shot state is not a semaphore permit: consuming a value-1 semaphore +/// forever violates libdispatch's destruction invariant. +private final class HistoricalCaptureOnce: @unchecked Sendable { + private let lock = NSLock() + private var claimed = false + func claim() -> Bool { + lock.lock() + defer { lock.unlock() } + guard !claimed else { return false } + claimed = true + return true + } +} + +/// Synthetic inputs, real asymmetric attention/cache/EngineV2 paths. No model +/// payload or MiMo capability flag is involved in this component qualification. +private final class ContiguousHistoricalAttentionModel: CBv2SteppableModel, + CBv2HistoricalAttentionCheckpointProviding, CBv2CompleteCheckpointKVTypeProviding +{ + let cbv2SupportsHistoricalAttentionCheckpoint = true + let cbv2CompleteCheckpointKVDTypes: [DType]? = Array(repeating: .float32, count: 4) + func forward(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> MLXArray { + let b = tokens.dim(0) + let n = tokens.dim(1) + var hidden = tokens.asType(.float32).reshaped([b, 1, n, 1]) / Float(32) + for cache in caches { + let q = MLXArray.zeros([b, 2, n, cache.kind.headDim], dtype: .float32) + let result: MLXArray + if let owner = cache.kind.sharesKVWithLayer { + result = cache.attendBorrowing( + source: caches[owner], queries: q, scale: 0.125, sinks: nil) + } else { + let k = broadcast(hidden, to: [b, 1, n, cache.kind.headDim]) + let v = broadcast(hidden, to: [b, 1, n, cache.kind.valueHeadDim]) + result = cache.updateAndAttend( + queries: q, keys: k, values: v, scale: 0.125, sinks: nil) + } + hidden = mean(result, axes: [1, 3], keepDims: true) + } + let target = MLX.round(hidden.reshaped([b, n, 1]) * Float(128)).asType(.int32) % 31 + return MLX.where(MLXArray(Int32(0) ..< Int32(32)) .== target, Float(10), Float(-10)) + } +} + +final class CBv2ContiguousHistoricalCheckpointTests: XCTestCase { + private var chunk: Int { max(32, CBv2AttentionV1.queryBlockSize) } + private func engine(_ store: CompleteCheckpointFixtureStore, equalWidths: Bool = false) -> ( + EngineV2, CBv2ContiguousKVBackend + ) { + let key = equalWidths ? 128 : 192 + let kinds: [CBv2LayerKind] = [ + .init( + attention: .slidingWindow(17), headDim: key, valueHeadDim: 128, kvHeads: 1, + queryHeads: 2), + .init(attention: .full, headDim: key, valueHeadDim: 128, kvHeads: 1, queryHeads: 2), + .init( + attention: .slidingWindow(17), sharesKVWithLayer: 0, headDim: key, + valueHeadDim: 128, kvHeads: 1, queryHeads: 2), + .init( + attention: .full, sharesKVWithLayer: 1, headDim: key, valueHeadDim: 128, kvHeads: 1, + queryHeads: 2), + ] + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 128 << 20, kvDType: .float32)) + let engine = EngineV2( + model: ContiguousHistoricalAttentionModel(), layerKinds: kinds, backend: backend, + cacheProvider: CBv2LayerCacheBank(layerKinds: kinds), + sampler: CBv2DefaultSampler(fallbackSeed: 0), + schedulerConfig: .init( + maxConcurrentRequests: 2, maxBatchedTokensPerStep: chunk, prefillChunkSize: chunk, + maxWaiting: 4, enablePrefixCache: true), + admissionConfig: .init(watermarkFraction: 0), completePrefixCache: store) + return (engine, backend) + } + private func request(_ id: UInt64) -> CBv2Request { + .init( + id: .init(id), promptTokens: (0 ..< 3 * chunk + 1).map { ($0 * 7) % 29 }, + sampling: .init(temperature: 0, seed: 0), maxTokens: 4, cacheSalt: "tenant", + prefixCacheReceiptID: .init(id + 1000)) + } + + func testRealEngineEarlierWindowRestartMatchesColdTokens() async throws { + let store = CompleteCheckpointFixtureStore(segmentBytes: 258) + let (coldEngine, coldBackend) = engine(store) + XCTAssertEqual( + coldEngine.completeCheckpointCodec?.backendLayout, + CBv2CompleteCheckpointManifest.contiguousAsymmetricLayout) + XCTAssertEqual( + coldEngine.admissionForTesting.fullKVBytesPerToken, 1280, + "observed FP32 must raise the default two-byte ledger") + let cold = await cbv2SchedCollect(try coldEngine.submit(request(1))) + XCTAssertEqual(cold.finishReason, .length) + // Publication prioritizes the deepest boundary before the first checkpoint. + XCTAssertEqual(store.saved.map(\.manifest.position), [3 * chunk, chunk]) + XCTAssertEqual(coldBackend.bytesReserved, 0) + XCTAssertEqual(coldEngine.admissionForTesting.bytesReserved, 0) + await coldEngine.shutdown() + let reopened = CompleteCheckpointFixtureStore( + archives: store.saved.filter { $0.manifest.position == chunk }) + let (warmEngine, warmBackend) = engine(reopened) + let warmRequest = request(2) + XCTAssertTrue(try reopened.stage(engine: warmEngine, request: warmRequest)) + let warm = await cbv2SchedCollect(try warmEngine.submit(warmRequest)) + XCTAssertEqual(warm.tokens, cold.tokens) + XCTAssertEqual(warm.usage?.prefixCachePrefillTokensSaved, chunk) + XCTAssertEqual(warm.usage?.prefixCacheReplayTokens, 0) + XCTAssertEqual(warmBackend.bytesReserved, 0) + XCTAssertEqual(warmEngine.admissionForTesting.bytesReserved, 0) + await warmEngine.shutdown() + } + + func testPostTransferBackendRefusalFallsBackToColdTokensWithoutOrphans() async throws { + let seed = CompleteCheckpointFixtureStore() + let (cold, _) = engine(seed) + let expected = await cbv2SchedCollect(try cold.submit(request(40))) + await cold.shutdown() + let store = CompleteCheckpointFixtureStore( + archives: seed.saved.filter { $0.manifest.position == chunk }) + let (warm, backend) = engine(store) + let input = request(41) + XCTAssertTrue(try store.stage(engine: warm, request: input)) + backend.checkpointBeforeRegistration = { + throw MLXError.caught("intentional imported registration refusal") + } + let actual = await cbv2SchedCollect(try warm.submit(input)) + XCTAssertEqual(actual.finishReason, .length) + XCTAssertEqual(actual.tokens, expected.tokens) + XCTAssertEqual(store.releaseCount, 1) + await warm.shutdown() + XCTAssertEqual(backend.bytesReserved, 0) + XCTAssertEqual(warm.admissionForTesting.bytesReserved, 0) + } + + func testImportedNaturalFinishRetainsChargeWhilePublicationIsBlocked() async throws { + let seed = CompleteCheckpointFixtureStore() + let (cold, _) = engine(seed) + _ = await cbv2SchedCollect(try cold.submit(request(20))) + await cold.shutdown() + let gate = CheckpointPublicationGate() + let store = CompleteCheckpointFixtureStore( + archives: seed.saved.filter { $0.manifest.position == chunk }, gate: gate) + let (warm, backend) = engine(store) + let input = request(21) + XCTAssertTrue(try store.stage(engine: warm, request: input)) + let collection = Task { await cbv2SchedCollect(try warm.submit(input)) } + let entered = await Task.detached { gate.waitUntilEntered() }.value + XCTAssertTrue(entered) + XCTAssertEqual( + store.releaseCount, 1, + "the staging callback transferred, not retained as a second reservation") + XCTAssertGreaterThan(backend.bytesReserved, 0) + XCTAssertGreaterThan(warm.admissionForTesting.bytesReserved, 0) + warm.cancel(input.id) // late cancellation cannot refund publication's aliases + XCTAssertThrowsError(try warm.submit(input)) + await warm.shutdown() // store close unblocks publication and drains owners + let result = try await collection.value + XCTAssertEqual(result.finishReason, .length) + XCTAssertEqual(backend.bytesReserved, 0) + XCTAssertEqual(warm.admissionForTesting.bytesReserved, 0) + XCTAssertEqual(store.releaseCount, 1) + } + + func testImportedCancellationAndUnconsumedStageShutdownReleaseOnce() async throws { + let seed = CompleteCheckpointFixtureStore() + let (cold, _) = engine(seed) + _ = await cbv2SchedCollect(try cold.submit(request(30))) + await cold.shutdown() + for consume in [false, true] { + let store = CompleteCheckpointFixtureStore( + archives: seed.saved.filter { $0.manifest.position == chunk }) + let (warm, backend) = engine(store) + let input = request(31) + XCTAssertTrue(try store.stage(engine: warm, request: input)) + XCTAssertGreaterThan(warm.admissionForTesting.bytesReserved, 0) + if consume { + warm.loopForTesting.onEngineQueueSync { + warm.loopForTesting.suspendStepExecutionAtCountForTesting = 1 + } + let stream = try warm.submit(input) + let entered = await cbv2SchedWait { warm.stepCount >= 1 } + XCTAssertTrue(entered) + warm.cancel(input.id) + warm.loopForTesting.onEngineQueueSync { + warm.loopForTesting.suspendStepExecutionAtCountForTesting = nil + } + let result = await cbv2SchedCollect(stream) + XCTAssertEqual(result.finishReason, .cancelled) + } + await warm.shutdown() + XCTAssertEqual(store.releaseCount, 1) + XCTAssertEqual(backend.bytesReserved, 0) + XCTAssertEqual(warm.admissionForTesting.bytesReserved, 0) + } + } + + func testLegacyEqualWidthContiguousAttentionOnlyRemainsUnactivated() async { + let (value, _) = engine(CompleteCheckpointFixtureStore(), equalWidths: true) + XCTAssertNil(value.completeCheckpointCodec) + await value.shutdown() + } + + func testNativeCopyFailureTerminatesWithoutDonation() async throws { + for construction in [true, false] { + let store = CompleteCheckpointFixtureStore() + let (value, backend) = engine(store) + value.loopForTesting.onEngineQueueSync { + value.completeCheckpointCapture?.makeContiguousCheckpoint = { + codec, position, chunk, state in + if construction { + throw MLXError.caught("intentional contiguous construction failure") + } + let candidate = try CBv2ContiguousHistoricalCheckpoint( + codec: codec, position: position, chunkSize: chunk, state: state) + candidate.evaluate = { arrays in + try withError { eval(arrays) } + throw MLXError.caught("intentional contiguous copy failure") + } + return candidate + } + } + let result = await cbv2SchedCollect(try value.submit(request(3))) + if case .error? = result.finishReason { + } else { + XCTFail("copy error became an optional cache miss") + } + XCTAssertTrue(result.tokens.isEmpty) + XCTAssertTrue(store.saved.isEmpty) + await value.shutdown() + XCTAssertEqual(backend.bytesReserved, 0) + XCTAssertEqual(value.admissionForTesting.bytesReserved, 0) + } + } + + func testCancellationAndShutdownDrainCapturedWindowOwner() async throws { + for shutdown in [false, true] { + let store = CompleteCheckpointFixtureStore() + let (value, backend) = engine(store) + let entered = DispatchSemaphore(value: 0) + let release = DispatchSemaphore(value: 0) + let first = HistoricalCaptureOnce() + value.loopForTesting.onEngineQueueSync { + value.completeCheckpointCapture?.makeContiguousCheckpoint = { + codec, position, chunk, state in + let candidate = try CBv2ContiguousHistoricalCheckpoint( + codec: codec, position: position, chunkSize: chunk, state: state) + candidate.evaluate = { arrays in + if first.claim() { + entered.signal() + _ = release.wait(timeout: .now() + 10) + } + try withError { eval(arrays) } + } + return candidate + } + } + let stream = try value.submit(request(4)) + let collected = Task { await cbv2SchedCollect(stream) } + let blocked = await withCheckedContinuation { continuation in + DispatchQueue.global().async { + continuation.resume(returning: entered.wait(timeout: .now() + 5) == .success) + } + } + XCTAssertTrue(blocked) + XCTAssertEqual(value.stepCount, 1) + XCTAssertGreaterThan(value.admissionForTesting.bytesReserved, 0) + let drain = shutdown ? Task { await value.shutdown() } : nil + if !shutdown { value.cancel(.init(4)) } + release.signal() + let result = await collected.value + if let drain { + await drain.value + } else { + XCTAssertEqual(result.finishReason, .cancelled) + await value.shutdown() + } + XCTAssertEqual(backend.bytesReserved, 0) + XCTAssertEqual(value.admissionForTesting.bytesReserved, 0) + } + } +} diff --git a/Tests/MLXLMTests/CBv2HistoricalMTPManifestTests.swift b/Tests/MLXLMTests/CBv2HistoricalMTPManifestTests.swift new file mode 100644 index 0000000000..42effde675 --- /dev/null +++ b/Tests/MLXLMTests/CBv2HistoricalMTPManifestTests.swift @@ -0,0 +1,141 @@ +import Foundation +import XCTest + +@testable import MLXLMCommon + +/// Metadata-only format tests. These do not certify native assistant capture, +/// allocation ownership, atomic adoption or model-level MTP/cache exactness. +final class CBv2HistoricalMTPManifestTests: XCTestCase { + private let position = 128 + private func fixture() throws -> ( + target: [CBv2CheckpointTensorDescriptor], + assistant: [CBv2CheckpointTensorDescriptor], + layers: [CBv2CheckpointAttentionLayer] + ) { + let kinds: [CBv2LayerKind] = [ + .init(attention: .full, headDim: 192, valueHeadDim: 128, kvHeads: 4, queryHeads: 64), + .init( + attention: .slidingWindow(17), headDim: 192, valueHeadDim: 128, kvHeads: 8, + queryHeads: 64), + ] + let layout = try CBv2HistoricalAttentionLayout( + layerKinds: kinds, + dtypes: [.bfloat16, .bfloat16], allowAsymmetric: true) + var assistant: [CBv2CheckpointTensorDescriptor] = [] + for head in 0 ..< 3 { + assistant.append( + try .init( + role: .assistantKeys, layer: head, + shape: [1, 4, position - head - 1, 192], dtype: .bfloat16)) + assistant.append( + try .init( + role: .assistantValues, layer: head, + shape: [1, 4, position - head - 1, 128], dtype: .bfloat16)) + } + assistant.append(try .init(role: .assistantHidden, shape: [1, 3, 4096], dtype: .bfloat16)) + assistant.append(try .init(role: .assistantTokens, shape: [1, position], dtype: .int32)) + assistant.append(try .init(role: .assistantCacheMetadata, shape: [3, 7], dtype: .int64)) + return (try layout.tensorDescriptors(position: position), assistant, layout.layers) + } + private func manifest( + _ tensors: [CBv2CheckpointTensorDescriptor], + layers: [CBv2CheckpointAttentionLayer]?, + layout: String = CBv2CompleteCheckpointManifest.contiguousAsymmetricMTPLayout, + assistant: String? = "mimo-v26-three-head-swa-bf16-target-tail-v1" + ) -> CBv2CompleteCheckpointManifest { + .init( + identity: .init( + modelAggregateHash: "artifact", promptContractID: "template", + buildID: "test", numericsFingerprint: "native-bf16"), + position: position, chunkSize: position, + prefixTokens: Array(repeating: 7, count: position), + cacheSalt: "tenant", assistantCodecID: assistant, tensors: tensors, + backendLayout: layout, attentionLayers: layers) + } + + func testCompleteHistoricalAssistantHasDistinctRoundTrippableFormat() throws { + let f = try fixture() + let value = manifest(f.target + f.assistant, layers: f.layers) + XCTAssertEqual( + try value.validateStructure(), (f.target + f.assistant).reduce(0) { $0 + $1.byteCount }) + let restored = try JSONDecoder().decode( + CBv2CompleteCheckpointManifest.self, + from: JSONEncoder().encode(value)) + XCTAssertEqual(restored, value) + XCTAssertEqual(try restored.validateStructure(), try value.validateStructure()) + XCTAssertNotEqual( + value.backendLayout, CBv2CompleteCheckpointManifest.contiguousAsymmetricLayout) + } + + func testTargetOnlyFormatStillRejectsAssistantStateAndIdentity() throws { + let f = try fixture() + let old = CBv2CompleteCheckpointManifest.contiguousAsymmetricLayout + XCTAssertNoThrow( + try manifest(f.target, layers: f.layers, layout: old, assistant: nil) + .validateStructure()) + XCTAssertThrowsError( + try manifest(f.target, layers: f.layers, layout: old).validateStructure()) + XCTAssertThrowsError( + try manifest( + f.target + f.assistant, layers: f.layers, + layout: old, assistant: nil + ).validateStructure()) + XCTAssertThrowsError(try manifest(f.target, layers: f.layers).validateStructure()) + XCTAssertThrowsError( + try manifest(f.target + f.assistant, layers: f.layers, assistant: nil) + .validateStructure()) + XCTAssertThrowsError( + try manifest(f.target + f.assistant, layers: f.layers, assistant: "") + .validateStructure()) + } + + func testAssistantKVPairAndExactTokenWitnessAreMandatory() throws { + let f = try fixture() + for removed in [0, 1, 6, 7, 8] { + var assistant = f.assistant + assistant.remove(at: removed) + XCTAssertThrowsError( + try manifest(f.target + assistant, layers: f.layers).validateStructure()) + } + for wrong in [ + try CBv2CheckpointTensorDescriptor( + role: .assistantTokens, shape: [1, position - 1], dtype: .int32), + try CBv2CheckpointTensorDescriptor( + role: .assistantTokens, shape: [1, position], dtype: .int64), + try CBv2CheckpointTensorDescriptor( + role: .assistantTokens, layer: 0, shape: [1, position], dtype: .int32), + ] { + var assistant = f.assistant + assistant[7] = wrong + XCTAssertThrowsError( + try manifest(f.target + assistant, layers: f.layers).validateStructure()) + } + } + + func testMismatchedHeadsDtypesAndTargetReorderingAreRejected() throws { + let f = try fixture() + for wrong in [ + try CBv2CheckpointTensorDescriptor( + role: .assistantValues, layer: 0, shape: [1, 4, position - 2, 128], dtype: .bfloat16 + ), + try CBv2CheckpointTensorDescriptor( + role: .assistantValues, layer: 0, shape: [1, 4, position - 1, 128], dtype: .float16), + try CBv2CheckpointTensorDescriptor( + role: .assistantValues, layer: 7, shape: [1, 4, position - 1, 128], dtype: .bfloat16 + ), + try CBv2CheckpointTensorDescriptor( + role: .values, layer: 7, shape: [1, 4, position - 1, 128], dtype: .bfloat16), + ] { + var assistant = f.assistant + assistant[1] = wrong + XCTAssertThrowsError( + try manifest(f.target + assistant, layers: f.layers).validateStructure()) + } + var tensors = f.target + f.assistant + tensors.swapAt(0, 1) + XCTAssertThrowsError(try manifest(tensors, layers: f.layers).validateStructure()) + XCTAssertThrowsError( + try manifest(f.target + f.assistant + [f.assistant[0]], layers: f.layers) + .validateStructure()) + } +} diff --git a/Tests/MLXLMTests/CBv2MTPBoundedAdmissionTests.swift b/Tests/MLXLMTests/CBv2MTPBoundedAdmissionTests.swift new file mode 100644 index 0000000000..f17374cd91 --- /dev/null +++ b/Tests/MLXLMTests/CBv2MTPBoundedAdmissionTests.swift @@ -0,0 +1,574 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon + +private class BoundedAdmissionTarget: CBv2MTPSteppableModel { + var mtpCaptureLayers: CBv2MTPCaptureLayers? { nil } + var supportsRequestStatefulMTP: Bool { true } + var mtpTargetIdentity: ObjectIdentifier? { ObjectIdentifier(self) } + func forward(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> MLXArray { + preconditionFailure("admission fixture must never forward") + } + func forwardWithHidden(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) + -> (logits: MLXArray, lastHidden: MLXArray) + { + preconditionFailure("admission fixture must never forward") + } +} +private final class BoundedAdmissionTargetExtras: BoundedAdmissionTarget, + CBv2TargetAuxiliaryAllocationProviding +{ + let cbv2TargetAuxiliaryAllocationSpecs: [CBv2AuxiliaryAllocationSpec]? + init(_ specs: [CBv2AuxiliaryAllocationSpec]?) { cbv2TargetAuxiliaryAllocationSpecs = specs } +} +private final class BoundedAdmissionRecurrentTarget: BoundedAdmissionTarget, + CBv2RecurrentMTPSteppableModel +{ + var cbv2Capabilities: CBv2ModelCapabilities { + .init(supportsPrefixReuse: false, supportsMTP: true) + } + var recurrentStateSpec: CBv2RecurrentStateSpec? { + .init(layers: [ + .init( + modelLayerIndex: 0, convShape: [1, 8], convDType: .float32, + ssmShape: [1, 16], ssmDType: .float32) + ]) + } + func forward( + tokens: MLXArray, caches: [CBv2AttendingLayerCache], + recurrentState: [CBv2RecurrentStateEvaluation] + ) -> MLXArray { preconditionFailure("must not forward") } + func forwardWithHidden( + tokens: MLXArray, caches: [CBv2AttendingLayerCache], + recurrentState: [CBv2RecurrentStateEvaluation], positionIds: MLXArray? + ) + -> (logits: MLXArray, lastHidden: MLXArray) + { preconditionFailure("must not forward") } +} +private class BoundedAdmissionLegacyDrafter: CBv2MTPRequestStatefulDrafter { + final class Capture: CBv2MTPPreparedCapture {} + final class State: CBv2MTPRequestState { + var committedInputCount: Int { 0 } + var stagedInputCount: Int { 0 } + } + let target: BoundedAdmissionTarget + var stateCreations = 0 + init(_ target: BoundedAdmissionTarget) { self.target = target } + var mtpTargetIdentity: ObjectIdentifier? { target.mtpTargetIdentity } + var requiredVerificationMode: CBv2MTPVerificationMode? { .serialTarget } + var maximumDraftTokens: Int? { 3 } + var requestStateBytesPerToken: Int { 188_480 } + var requestStateTokenGranularity: Int { 256 } + var requestStateTokenAllocationPadding: Int { 12 } + func prepare(rows: [CBv2MTPRowCapture]) -> any CBv2MTPPreparedCapture { Capture() } + func draftStep(tokens: MLXArray, hidden: MLXArray, prepared: any CBv2MTPPreparedCapture) + -> (tokens: MLXArray, hidden: MLXArray) + { preconditionFailure("must not draft") } + func makeRequestState() -> any CBv2MTPRequestState { + stateCreations += 1 + return State() + } + func observeCommittedTarget( + _ observation: CBv2MTPCommittedTargetObservation, + requestState: any CBv2MTPRequestState + ) {} + func draftStep( + tokens: MLXArray, hidden: MLXArray, shortlist: MLXArray?, + requestState: any CBv2MTPRequestState + ) -> (tokens: MLXArray, hidden: MLXArray) { + preconditionFailure("must not draft") + } + func evaluationTargets(for requestState: any CBv2MTPRequestState) -> [MLXArray] { [] } + func finalizeRound( + requestState: any CBv2MTPRequestState, confirmedInputTokens: Int, + committedDraftTokens: MLXArray, committedTargetHidden: MLXArray + ) {} + func discardRound(requestState: any CBv2MTPRequestState) {} + func releaseRequestState(_ requestState: any CBv2MTPRequestState) {} +} +private final class BoundedAdmissionDrafter: BoundedAdmissionLegacyDrafter, + CBv2MTPBoundedAllocationProviding +{ + var declarations = 0 + var declaredSpec: CBv2MTPBoundedAllocationSpec? = .init( + resident: [.init(logicalBytes: 4096, allocationCount: 4)], + working: [.init(logicalBytes: 1024, allocationCount: 3)], hostBytes: 256) + func boundedRequestAllocation(limits: CBv2MTPAllocationLimits) -> CBv2MTPBoundedAllocationSpec? + { + declarations += 1 + return declaredSpec + } +} + +/// Charge-only process owner: it never grants materialization credit for these +/// projections. ProviderCore must separately test its scalar bridge and shared +/// process gate against EngineV2.resolvedMTPAdmission. +private final class BoundedAdmissionProcessOwner: CBv2ProcessMemoryOwner, @unchecked Sendable { + enum Failure: Error { case exceeded } + private let lock = NSLock() + private let limit: UInt64 + private var charged: UInt64 = 0 + private var observations = 0 + init(limit: UInt64) { self.limit = limit } + func replaceCharge(_ bytes: UInt64) throws { + try lock.withLock { + guard bytes <= limit else { throw Failure.exceeded } + charged = bytes + } + } + func recordMaterialization(_ bytes: UInt64) throws { lock.withLock { observations += 1 } } + func withdrawCoverage(_ bytes: UInt64) throws {} + func retire() {} + var charge: UInt64 { lock.withLock { charged } } + var materializationCalls: Int { lock.withLock { observations } } +} + +final class CBv2MTPBoundedAdmissionTests: XCTestCase { + private let counts = [1, 2, 3, 127, 128, 129, 1024, 262_144, 1_048_576] + private let limits = CBv2MTPAllocationLimits(maximumPrefillTokens: 2048, maximumDraftTokens: 3) + private var spec: CBv2MTPBoundedAllocationSpec { + .init( + resident: [ + .init(logicalBytes: 17, allocationCount: 4), + .init(logicalBytes: 1, allocationCount: 2), + ], + working: [.init(logicalBytes: 33, allocationCount: 3)], hostBytes: 64) + } + private func value( + _ resolution: CBv2MTPAdmissionResolution, + file: StaticString = #filePath, line: UInt = #line + ) throws -> CBv2ResolvedMTPAdmission { + guard case .bounded(let result) = resolution else { + XCTFail("unexpected refusal: \(resolution)", file: file, line: line) + throw BoundedAdmissionProcessOwner.Failure.exceeded + } + return result + } + + func testIndependentAllocatorPaddingAndContextInvariantBothResidencyLedgers() throws { + var calls: [Int] = [] + let resolution = CBv2MTPBoundedAdmission.resolve(spec: spec, limits: limits) { bytes in + calls.append(bytes) + return ((bytes + 15) / 16) * 16 + } + let resolved = try value(resolution) + XCTAssertEqual(calls, [17, 1, 33]) + XCTAssertEqual(resolved.residentBytes, 4 * 32 + 2 * 16) + XCTAssertEqual(resolved.workingBytes, 3 * 48) + XCTAssertEqual(resolved.fixedBytesPerRequest, 368) + XCTAssertEqual(resolved.auxiliaryBytesPerToken, 0) + XCTAssertEqual(resolved.auxiliaryTokenGranularity, 1) + XCTAssertEqual(resolved.auxiliaryTokenAllocationPadding, 0) + let kind = CBv2LayerKind(attention: .full, headDim: 1, kvHeads: 1, queryHeads: 1) + let paged = CBv2PagedKVResidency( + config: .init( + capacityBytes: 1 << 30, + maxBufferLength: 1 << 30, segmentSizeBytes: 1 << 16)) + for residency: any CBv2KVResidencyPolicy in [CBv2ContiguousKVResidency(), paged] { + var config = AdmissionV2.Config(watermarkFraction: 0, fixedBytesPerRequest: 123) + XCTAssertEqual(CBv2MTPBoundedAdmission.apply(resolution, to: &config), resolution) + let owner = BoundedAdmissionProcessOwner(limit: 1 << 30) + let admission = AdmissionV2( + layerKinds: [kind], bytesCapacity: 1 << 30, + config: config, residency: residency, processMemoryOwner: owner) + XCTAssertEqual(admission.allocatedBytes(forTokens: 0), 0) + for count in counts { + let target = 4 * (try XCTUnwrap(residency.residentRows(layer: kind, tokens: count))) + XCTAssertEqual( + admission.allocatedBytes(forTokens: count) - target, + 123 + resolved.fixedBytesPerRequest) + try admission.reserve(id: .init(1), additionalTokens: count) + XCTAssertEqual(admission.nonBackendBytesReserved, 491) + XCTAssertEqual(owner.charge, UInt64(admission.bytesReserved)) + if count > 1 { + admission.unreserve(id: .init(1), tokens: count - 1) + XCTAssertEqual(admission.nonBackendBytesReserved, 491) + } + admission.releaseAll(id: .init(1)) + XCTAssertEqual(admission.bytesReserved, 0) + XCTAssertEqual(owner.charge, 0) + } + XCTAssertEqual(owner.materializationCalls, 0) + XCTAssertEqual(admission.allocatedBytes(forTokens: Int.max), Int.max) + } + } + + func testInvalidLimitsDeclarationPolicyAndCheckedOverflowRefuse() throws { + XCTAssertEqual( + CBv2MTPBoundedAdmission.resolve(spec: spec, limits: limits, policy: nil), + .unavailable(.allocatorPolicyUnavailable)) + for bad in [0, -1] { + XCTAssertEqual( + CBv2MTPBoundedAdmission.resolve( + spec: spec, + limits: .init(maximumPrefillTokens: bad, maximumDraftTokens: 3), + upperBound: { $0 }), + .unavailable(.invalidLimits)) + XCTAssertEqual( + CBv2MTPBoundedAdmission.resolve( + spec: spec, + limits: .init(maximumPrefillTokens: 1, maximumDraftTokens: bad), + upperBound: { $0 }), + .unavailable(.invalidLimits)) + } + let malformed: [CBv2MTPBoundedAllocationSpec?] = [ + nil, + .init(resident: [], working: spec.working, hostBytes: 0), + .init(resident: spec.resident, working: [], hostBytes: 0), + .init(resident: [.init(logicalBytes: 0)], working: spec.working, hostBytes: 0), + .init( + resident: [.init(logicalBytes: 1, allocationCount: -1)], working: spec.working, + hostBytes: 0), + .init(resident: spec.resident, working: spec.working, hostBytes: -1), + .init( + resident: [.init(logicalBytes: Int.max, allocationCount: 2)], working: spec.working, + hostBytes: 0), + .init(resident: [.init(logicalBytes: Int.max)], working: spec.working, hostBytes: 0), + ] + for declaration in malformed { + let resolution = CBv2MTPBoundedAdmission.resolve( + spec: declaration, limits: limits, upperBound: { $0 }) + guard case .unavailable = resolution else { + return XCTFail("malformed declaration admitted") + } + var config = AdmissionV2.Config() + CBv2MTPBoundedAdmission.apply(resolution, to: &config) + XCTAssertEqual(config.fixedBytesPerRequest, Int.max) + } + for bound: (Int) -> Int? in [{ _ in nil }, { $0 - 1 }] { + XCTAssertEqual( + CBv2MTPBoundedAdmission.resolve(spec: spec, limits: limits, upperBound: bound), + .unavailable(.unrepresentableAllocation)) + } + let resolved = CBv2MTPBoundedAdmission.resolve( + spec: spec, limits: limits, upperBound: { $0 }) + var overflow = AdmissionV2.Config(fixedBytesPerRequest: Int.max) + XCTAssertEqual( + CBv2MTPBoundedAdmission.apply(resolved, to: &overflow), .unavailable(.chargeOverflow)) + var negative = AdmissionV2.Config(fixedBytesPerRequest: -1) + XCTAssertEqual( + CBv2MTPBoundedAdmission.apply(resolved, to: &negative), + .unavailable(.invalidExistingCharge)) + } + + func testTightNativeAndProcessCapsRejectWithoutLeakingCharge() throws { + let resolution = CBv2MTPBoundedAdmission.resolve( + spec: spec, limits: limits, upperBound: { $0 }) + var config = AdmissionV2.Config(watermarkFraction: 0) + CBv2MTPBoundedAdmission.apply(resolution, to: &config) + let fixed = config.fixedBytesPerRequest + let kind = CBv2LayerKind(attention: .full, headDim: 1, kvHeads: 1, queryHeads: 1) + for nativeTight in [false, true] { + let owner = BoundedAdmissionProcessOwner( + limit: UInt64(nativeTight ? fixed + 4 : fixed + 3)) + let admission = AdmissionV2( + layerKinds: [kind], bytesCapacity: nativeTight ? fixed + 3 : fixed + 4, + config: config, processMemoryOwner: owner) + XCTAssertThrowsError(try admission.reserve(id: .init(1), additionalTokens: 1)) + XCTAssertEqual(owner.charge, 0) + XCTAssertEqual(admission.bytesReserved, 0) + } + } + + func testCallerProjectionIsExactWithoutTargetAndConservativeSumWithTarget() throws { + let policy = try XCTUnwrap(Memory.allocationFootprintPolicy()) + let caller = try XCTUnwrap( + CBv2AuxiliaryAllocationProjection( + policy: policy, + buffers: [ + .init( + bytesPerToken: 13, allocationCount: 2, tokenGranularity: 128, + tokenPadding: 5) + ])) + XCTAssertEqual(caller.bytes(forTokens: 0), 0) // telescoping proof's required base + var previous = 0 + for n in 0 ... 2049 { + let current = try XCTUnwrap(caller.bytes(forTokens: n)) + XCTAssertGreaterThanOrEqual(current, previous) + XCTAssertLessThanOrEqual(current - previous, caller.maximumGrowthBytes) + XCTAssertLessThanOrEqual(current, n * caller.maximumGrowthBytes) + previous = current + } + var original = AdmissionV2.Config( + watermarkFraction: 0, elementBytes: 2, + layerElementBytes: nil, fixedBytesPerRequest: 123, auxiliaryBytesPerToken: 17, + auxiliaryTokenGranularity: 16, auxiliaryTokenAllocationPadding: 7) + original.auxiliaryAllocationProjection = caller + let resolution = CBv2MTPBoundedAdmission.resolve(spec: spec, limits: limits, policy: policy) + let fixed = try value(resolution).fixedBytesPerRequest + let extra = CBv2AuxiliaryAllocationSpec( + bytesPerToken: 31, allocationCount: 2, + tokenGranularity: 256, tokenPadding: 3) + let targetProjection = try XCTUnwrap( + CBv2AuxiliaryAllocationProjection(policy: policy, buffers: [extra])) + for hasTarget in [false, true] { + let target: BoundedAdmissionTarget = + hasTarget ? BoundedAdmissionTargetExtras([extra]) : BoundedAdmissionTarget() + var config = original + CBv2MTPBoundedAdmission.apply(resolution, to: &config) + CBv2MTPBoundedAdmission.preserveCallerProjectionForTarget( + model: target, config: &config) + CBv2TargetAuxiliaryAdmission.apply( + model: target, config: &config, policy: policy, draftSpecs: nil) + XCTAssertEqual(config.fixedBytesPerRequest, 123 + fixed) + let ledger = AdmissionV2(layerKinds: [], bytesCapacity: Int.max, config: config) + for n in counts + [120, 121, 122, 123, 124, 251, 252, 253, 255, 256, 257] { + let scalar = ((n + 7 + 15) / 16) * 16 * 17 + let callerBytes = max(scalar, try XCTUnwrap(caller.bytes(forTokens: n))) + let targetBytes = + hasTarget ? try XCTUnwrap(targetProjection.bytes(forTokens: n)) : 0 + let expected = 123 + fixed + callerBytes + targetBytes + if hasTarget { + XCTAssertGreaterThanOrEqual(ledger.allocatedBytes(forTokens: n), expected) + } else { + XCTAssertEqual(ledger.allocatedBytes(forTokens: n), expected) + } + } + if !hasTarget { + XCTAssertEqual(config.auxiliaryBytesPerToken, 17) + XCTAssertEqual(config.auxiliaryTokenGranularity, 16) + XCTAssertEqual(config.auxiliaryTokenAllocationPadding, 7) + } + } + } + + func testMiMoMetadataBoundRetainsFourBanksWithoutChangingContext() throws { + let config = try MiMoV26MTPChecks.config() + let small = try XCTUnwrap( + MiMoV26MTPAssistant.boundedRequestAllocation( + configuration: config, + limits: .init(maximumPrefillTokens: 8, maximumDraftTokens: 3))) + let large = try XCTUnwrap( + MiMoV26MTPAssistant.boundedRequestAllocation(configuration: config, limits: limits)) + XCTAssertEqual(small.resident, large.resident) + XCTAssertEqual(small.resident[0].allocationCount, 12) + XCTAssertEqual(small.resident[1].allocationCount, 12) + XCTAssertEqual(small.resident[0].logicalBytes, 1 * 3 * 4 * 4) + XCTAssertEqual(small.resident[1].logicalBytes, 1 * 3 * 2 * 4) + let a = try value( + CBv2MTPBoundedAdmission.resolve(spec: small, limits: limits, upperBound: { $0 })) + let b = try value( + CBv2MTPBoundedAdmission.resolve(spec: large, limits: limits, upperBound: { $0 })) + XCTAssertEqual(a.residentBytes, b.residentBytes) + XCTAssertGreaterThan(b.workingBytes, a.workingBytes) + XCTAssertEqual(config.maxPositionEmbeddings, 64) + XCTAssertNil( + MiMoV26MTPAssistant.boundedRequestAllocation( + configuration: config, + limits: .init(maximumPrefillTokens: Int.max, maximumDraftTokens: 3))) + XCTAssertNil( + MiMoV26MTPAssistant.boundedRequestAllocation( + configuration: config, + limits: .init(maximumPrefillTokens: 1, maximumDraftTokens: 4))) + } + + func testSchedulerRetainsConstructionEnvelopeWhenCallerChangesConfig() { + var caller = CBv2SchedulerConfig( + maxBatchedTokensPerStep: 128, + prefillChunkSize: 64, soloPrefillStripeTokens: 512) + let scheduler = SchedulerV2(config: caller) + caller.maxBatchedTokensPerStep = 4096 + caller.soloPrefillStripeTokens = 8192 + scheduler.mixedStepPrefillTokenCap = 32 // a lower secondary cap only + XCTAssertEqual(scheduler.config.maxBatchedTokensPerStep, 128) + XCTAssertEqual(scheduler.config.soloPrefillStripeTokens, 512) + } + + // Prepared native cells: coordinator's exclusive lane only. No native + // execution, allocator peak or speed claim is made by this source packet. + private func requireNativeLane() throws { + guard ProcessInfo.processInfo.environment["DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST"] == "1" + else { + throw XCTSkip("Requires coordinator's exclusive native lane") + } + } + + func testActualEngineConsumesBoundForContiguousAndSegmentedAndLeavesLegacyZeroAlone() + async throws + { + try requireNativeLane() + let target = BoundedAdmissionTarget() + let bounded = BoundedAdmissionDrafter(target) + let legacy = BoundedAdmissionLegacyDrafter(target) + let kinds = [CBv2LayerKind(attention: .full, headDim: 64, kvHeads: 1, queryHeads: 1)] + for paged in [false, true] { + for (drafter, depth) in [ + (bounded as BoundedAdmissionLegacyDrafter, 3), (legacy, 3), (bounded, 0), + ] { + // Each segmented pool owns one admission lease; never rebind + // the same native pool to successive engine instances. + let backend: any CBv2KVBackend + if paged { + backend = try PagedKVBackend( + layerKinds: kinds, + config: .init( + capacityBytes: 32 << 20, + maxPrefillChunk: 128, maxBufferLength: 32 << 20, + segmentSizeBytes: 64 << 10)) + } else { + backend = CBv2ContiguousKVBackend(config: .init(bytesCapacity: 32 << 20)) + } + let oldDeclarations = bounded.declarations + let engine = EngineV2( + model: target, layerKinds: kinds, backend: backend, + cacheProvider: CBv2LayerCacheBank(caches: []), + schedulerConfig: .init( + maxBatchedTokensPerStep: 64, prefillChunkSize: 32, + soloPrefillStripeTokens: 128), + admissionConfig: .init(watermarkFraction: 0, fixedBytesPerRequest: 123), + mtpDrafter: drafter, + mtpConfig: .init( + enabled: true, maxDraftTokens: 3, + fixedDraftTokens: depth, verificationMode: .serialTarget)) + let admission = try XCTUnwrap(engine.loopForTesting.capacity as? AdmissionV2) + let driver = try XCTUnwrap(engine.loopForTesting.mtp) + if drafter === bounded && depth > 0 { + let resolved = try value(XCTUnwrap(engine.resolvedMTPAdmission)) + XCTAssertEqual(resolved.limits.maximumPrefillTokens, 128) + XCTAssertEqual(resolved.limits.maximumDraftTokens, 3) + XCTAssertEqual( + engine.resolvedFixedBytesPerRequest, 123 + resolved.fixedBytesPerRequest) + XCTAssertEqual(admission.auxiliaryBytesPerToken, 0) + XCTAssertEqual(bounded.declarations, oldDeclarations + 1) + XCTAssertTrue(driver.tracksPersistentHistory) + engine.updateKVBytesCapacity(16 << 20) + XCTAssertEqual(engine.resolvedMTPAdmission, .bounded(resolved)) + try admission.reserve(id: .init(1), additionalTokens: 1) + XCTAssertEqual( + admission.nonBackendBytesReserved, engine.resolvedFixedBytesPerRequest) + admission.releaseAll(id: .init(1)) + } else { + XCTAssertNil(engine.resolvedMTPAdmission) + XCTAssertEqual(engine.resolvedFixedBytesPerRequest, 123) + XCTAssertEqual( + admission.auxiliaryBytesPerToken, + depth == 0 ? 0 : legacy.requestStateBytesPerToken) + XCTAssertEqual(admission.auxiliaryTokenGranularity, depth == 0 ? 1 : 256) + XCTAssertEqual(admission.auxiliaryTokenAllocationPadding, depth == 0 ? 0 : 12) + XCTAssertEqual(driver.tracksPersistentHistory, depth > 0) + XCTAssertEqual(bounded.declarations, oldDeclarations) + } + XCTAssertEqual(drafter.stateCreations, 0) + await engine.shutdown() + } + } + } + + func testActualBoundedEnginePreservesRecurrentAndCallerFixedAndRejectsMissingDeclaration() + async throws + { + try requireNativeLane() + let policy = try XCTUnwrap(Memory.allocationFootprintPolicy()) + let target = BoundedAdmissionRecurrentTarget() + let assistant = BoundedAdmissionDrafter(target) + let recurrent = try XCTUnwrap(target.recurrentStateSpec) + let generations = CBv2RecurrentStateSpec.maximumLiveGenerations + 2 // depth3 stateful serial target + let targetBytes = try recurrent.allocationBytesPerGeneration(policy: policy) * generations + for valid in [true, false] { + if !valid { assistant.declaredSpec = nil } + let backend = CBv2ContiguousKVBackend(config: .init(bytesCapacity: 32 << 20)) + let engine = EngineV2( + model: target, layerKinds: [], backend: backend, + cacheProvider: CBv2LayerCacheBank(caches: []), + admissionConfig: .init(watermarkFraction: 0, fixedBytesPerRequest: 123), + mtpDrafter: assistant, + mtpConfig: .init( + enabled: true, maxDraftTokens: 3, + fixedDraftTokens: 3, verificationMode: .serialTarget)) + if valid { + let resolved = try value(XCTUnwrap(engine.resolvedMTPAdmission)) + XCTAssertEqual( + engine.resolvedFixedBytesPerRequest, + targetBytes + 123 + resolved.fixedBytesPerRequest) + } else { + XCTAssertEqual(engine.resolvedMTPAdmission, .unavailable(.missingDeclaration)) + XCTAssertEqual(engine.resolvedFixedBytesPerRequest, Int.max) + let admission = try XCTUnwrap(engine.loopForTesting.capacity as? AdmissionV2) + XCTAssertThrowsError(try admission.reserve(id: .init(1), additionalTokens: 1)) + XCTAssertEqual(admission.bytesReserved, 0) + } + await engine.shutdown() + } + } + + func testActualDisabledAndAbsentDraftersRetainDefaultAccounting() async throws { + try requireNativeLane() + let target = BoundedAdmissionTarget() + let assistant = BoundedAdmissionDrafter(target) + for supplied in [false, true] { + let backend = CBv2ContiguousKVBackend(config: .init(bytesCapacity: 1 << 20)) + let engine = EngineV2( + model: target, layerKinds: [], backend: backend, + cacheProvider: CBv2LayerCacheBank(caches: []), + admissionConfig: .init(watermarkFraction: 0, fixedBytesPerRequest: 123), + mtpDrafter: supplied ? assistant : nil, mtpConfig: .init(enabled: false)) + let admission = try XCTUnwrap(engine.loopForTesting.capacity as? AdmissionV2) + XCTAssertNil(engine.resolvedMTPAdmission) + XCTAssertNil(engine.loopForTesting.mtp) + XCTAssertEqual(engine.resolvedFixedBytesPerRequest, 123) + XCTAssertEqual(admission.auxiliaryBytesPerToken, 0) + XCTAssertEqual(admission.auxiliaryTokenGranularity, 1) + XCTAssertEqual(admission.auxiliaryTokenAllocationPadding, 0) + XCTAssertEqual(assistant.declarations, 0) + XCTAssertEqual(assistant.stateCreations, 0) + await engine.shutdown() + } + } + + func testNativeMeasuredOldAndCurrentOwnersStayInsideFourBankBoundThroughRollbackAndCancel() + throws + { + try requireNativeLane() + let (target, predictor) = try MiMoV26MTPChecks.fixture() + let assistant = try MiMoV26MTPAssistant(target: target, predictor: predictor) + let policy = try XCTUnwrap(Memory.allocationFootprintPolicy()) + let envelope = CBv2MTPAllocationLimits(maximumPrefillTokens: 16, maximumDraftTokens: 3) + let resolved = try value( + CBv2MTPBoundedAdmission.resolve( + spec: assistant.boundedRequestAllocation(limits: envelope), limits: envelope, + policy: policy)) + let state = assistant.makeRequestState() as! MiMoV26MTPState + try assistant.configureRequestState(state, maximumSequenceLength: 64) + let tokens = MLXArray((1 ... 11).map(Int32.init), [1, 11]) + let output = try target.forward(inputIDs: tokens) + assistant.observeCommittedTarget( + .init(tokens: tokens, hidden: output.normalizedHiddenStates), requestState: state) + eval(assistant.evaluationTargets(for: state)) + try assistant.requestStateDidFinishEvaluation(state) + XCTAssertLessThanOrEqual(state.materializedBytes, resolved.residentBytes) + var token = MLXArray([Int32(7)], [1, 1]) + var hidden = output.normalizedHiddenStates[0..., (-1)..., 0...] + for _ in 0 ..< 3 { + let previous = state.materializedBytes + let proposal = assistant.draftStep( + tokens: token, hidden: hidden, shortlist: nil, requestState: state) + XCTAssertTrue(state.hasUnmeasuredResidency) + XCTAssertEqual(state.materializedBytes, previous) + eval([proposal.tokens, proposal.hidden] + assistant.evaluationTargets(for: state)) + StreamOrDevice.default.stream.synchronize() + // A sum of individual backing observations can double count shared + // old/current storage, so this is conservative, never a credit. + let current = try assistant.evaluationTargets(for: state).reduce(0) { + $0 + (try XCTUnwrap($1.evaluatedBufferInfo())).allocatedBytes + } + XCTAssertLessThanOrEqual(previous + current, resolved.residentBytes) + try assistant.requestStateDidFinishEvaluation(state) // actual uniqueness/compactness proof + XCTAssertFalse(state.hasUnmeasuredResidency) + XCTAssertLessThanOrEqual(state.materializedBytes, resolved.residentBytes) + token = proposal.tokens.reshaped([1, 1]) + hidden = proposal.hidden + } + assistant.discardRound(requestState: state) + eval(assistant.evaluationTargets(for: state)) + try assistant.requestStateDidFinishEvaluation(state) + XCTAssertEqual(state.stagedInputCount, 0) + XCTAssertLessThanOrEqual(state.materializedBytes, resolved.residentBytes) + assistant.releaseRequestState(state) + XCTAssertTrue(state.isReleased) + XCTAssertEqual(state.materializedBytes, 0) + XCTAssertEqual(state.measuredRootCount, 0) + } +} diff --git a/Tests/MLXLMTests/CBv2NativeCompleteCheckpointTransferTests.swift b/Tests/MLXLMTests/CBv2NativeCompleteCheckpointTransferTests.swift new file mode 100644 index 0000000000..ffeb271a60 --- /dev/null +++ b/Tests/MLXLMTests/CBv2NativeCompleteCheckpointTransferTests.swift @@ -0,0 +1,638 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLMCommon + +/// Real Common native graphs/rows/issuer/async store jobs, not a MiMo model or +/// artifact qualification. Strict-loaded MiMo factory and MTP codec tests are +/// separate integration gates. Every retained-fault selector needs a fresh process. +final class CBv2NativeCompleteCheckpointTransferTests: XCTestCase { + private enum Failure: Error { case invalidated, capacity, fence, noReceipt, adoption } + + private final class ProcessOwner: CBv2ProcessMemoryOwner, @unchecked Sendable { + private let lock = NSLock() + private var value: UInt64 = 0 + private var closed = false + private var materialized: UInt64 = 0 + var bytes: UInt64 { lock.withLock { value } } + var retired: Bool { lock.withLock { closed } } + func replaceCharge(_ bytes: UInt64) throws { + try lock.withLock { + guard !closed, bytes >= materialized, bytes <= 256 << 20 else { + throw Failure.capacity + } + value = bytes + } + } + func recordMaterialization(_ bytes: UInt64) throws { + try lock.withLock { + guard bytes >= materialized, bytes <= value else { throw Failure.capacity } + materialized = bytes + } + } + func withdrawCoverage(_ bytes: UInt64) throws { + try lock.withLock { + guard bytes <= materialized else { throw Failure.capacity } + materialized -= bytes + } + } + func retire() { + lock.withLock { + XCTAssertEqual(value, 0) + closed = true + } + } + } + + /// Same real asymmetric attention pattern used by the existing historical + /// checkpoint fixture, with immutable materialized native input and a + /// package-only generation validator. This is not an NSObject stand-in. + private final class Model: CBv2SteppableModel, CBv2HistoricalAttentionCheckpointProviding, + CBv2CompleteCheckpointKVTypeProviding, CBv2NativeCompletePrefixBindingValidating + { + let loadedScale = MLXArray(Float(1.0 / 32.0)) + private let lock = NSLock() + private var valid = true + var cbv2SupportsHistoricalAttentionCheckpoint: Bool { true } + var cbv2CompleteCheckpointKVDTypes: [DType]? { [.float32, .float32] } + func invalidate() { lock.withLock { valid = false } } + func validateNativeCompletePrefixBinding() throws { + if !lock.withLock({ valid }) { throw Failure.invalidated } + } + func forward(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> MLXArray { + let b = tokens.dim(0) + let n = tokens.dim(1) + var hidden = tokens.asType(.float32).reshaped([b, 1, n, 1]) * loadedScale + for cache in caches { + let q = MLXArray.zeros([b, 2, n, 192], dtype: .float32) + let k = broadcast(hidden, to: [b, 1, n, 192]) + let v = broadcast(hidden, to: [b, 1, n, 128]) + hidden = mean( + cache.updateAndAttend( + queries: q, keys: k, values: v, + scale: 0.125, sinks: nil), axes: [1, 3], keepDims: true) + } + let target = MLX.round(hidden.reshaped([b, n, 1]) * Float(128)).asType(.int32) % 31 + return MLX.where(MLXArray(Int32(0) ..< Int32(32)) .== target, Float(10), Float(-10)) + } + } + + private final class Flag: @unchecked Sendable { + private let lock = NSLock() + private var flag = false + var value: Bool { lock.withLock { flag } } + func set() { lock.withLock { flag = true } } + } + + private final class Gate: @unchecked Sendable { + let entered: XCTestExpectation + private let lock = NSLock() + private var first = true + private let resume = DispatchSemaphore(value: 0) + init(_ entered: XCTestExpectation) { self.entered = entered } + func hold() { + guard + lock.withLock({ + let old = first + first = false + return old + }) + else { return } + entered.fulfill() + _ = resume.wait(timeout: .now() + 8) + } + func release() { resume.signal() } + } + + private final class Store: CBv2NativeCompletePrefixCache, @unchecked Sendable { + let base: CompleteCheckpointFixtureStore + private let jobs = DispatchGroup() + private let lock = NSLock() + private var supplied: [CBv2RequestID: CBv2StagedCompleteCheckpoint] = [:] + var closeGate: Gate? + let closeJoined = Flag() + init( + writeGate: CheckpointPublicationGate? = nil, + archives: [CompleteCheckpointFixtureStore.Archive] = [] + ) { + base = .init(archives: archives, gate: writeGate, segmentBytes: 1 << 20) + } + var identity: CBv2CompleteCheckpointIdentity { base.identity } + func acceptsCheckpoint(position: Int, packedBytes: Int) -> Bool { + base.acceptsCheckpoint(position: position, packedBytes: packedBytes) + } + func takeStaged( + requestID: CBv2RequestID, tokens: [Int], cacheSalt: String?, + maximumSequenceLength: Int + ) -> CBv2StagedCompleteCheckpoint? { + if let actual = lock.withLock({ supplied.removeValue(forKey: requestID) }) { + return actual + } + return base.takeStaged( + requestID: requestID, tokens: tokens, cacheSalt: cacheSalt, + maximumSequenceLength: maximumSequenceLength) + } + func supplyActualForeignStage(_ stage: CBv2StagedCompleteCheckpoint, receipt: CBv2RequestID) + { + lock.withLock { + precondition(supplied[receipt] == nil) + supplied[receipt] = stage + } + } + func donate( + _ source: CBv2CompleteCheckpointExport, requestID: CBv2RequestID?, + tokens: [Int], cacheSalt: String?, + completion: @escaping @Sendable ([Int]) -> Void + ) { + jobs.enter() + base.donate(source, requestID: requestID, tokens: tokens, cacheSalt: cacheSalt) { + [self] positions in + completion(positions) + jobs.leave() // real underlying source read/close callback returned. + } + } + func close() { + let stages = lock.withLock { + let old = Array(supplied.values) + supplied = [:] + return old + } + stages.forEach { $0.close() } + base.close() + } + func closeAndWait() async { + closeGate?.hold() + close() + await withCheckedContinuation { continuation in + jobs.notify(queue: .global(qos: .utility)) { continuation.resume() } + } + closeJoined.set() + } + } + + private struct Fixture { + let engine: EngineV2 + let backend: CBv2ContiguousKVBackend + let model: Model + let process: ProcessOwner + let store: Store + let scope: NativeConstructionScope + } + private var chunk: Int { max(32, CBv2AttentionV1.queryBlockSize) } + + private func lane(fault: String? = nil) throws { + let env = ProcessInfo.processInfo.environment + guard env["DARKBLOOM_TEST_NATIVE_COMPLETE_PREFIX"] == "1" else { + throw XCTSkip("Requires an exclusively owned real native process") + } + guard env["DARKBLOOM_TEST_NATIVE_COMPLETE_PREFIX_FAULT"] == fault else { + throw XCTSkip("Retained fault cells run alone in fresh processes") + } + } + + private func fixture( + store: Store = Store(), shutdownTimeout: TimeInterval = 10, + beforeConsume: ( + ( + CBv2NativeExecutionContract, Model, CBv2ContiguousKVBackend, + CBv2LayerCacheBank, ProcessOwner + ) throws -> Void + )? = nil + ) throws -> Fixture { + let scope = NativeConstructionScope() + let model = Model() + let process = ProcessOwner() + let kinds: [CBv2LayerKind] = [ + .init( + attention: .slidingWindow(17), headDim: 192, valueHeadDim: 128, kvHeads: 1, + queryHeads: 2), + .init(attention: .full, headDim: 192, valueHeadDim: 128, kvHeads: 1, queryHeads: 2), + ] + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 128 << 20, kvDType: .float32)) + let bank = CBv2LayerCacheBank(layerKinds: kinds) + let engine = try scope.withPhase(.nativeSetup) { + try scope.capture(StreamOrDevice.cpu.stream) + try scope.capture(StreamOrDevice.default.stream) + try scope.retain(model.loadedScale) + try scope.willSubmit() + try withError { errors in + eval(model.loadedScale) + try errors.check() + } + try scope.authorizeImmutableLoadedOwner(model) + try scope.retainOwner(backend) + try scope.retainOwner(bank) + try scope.retainOwner(store) + let contract = try CBv2NativeExecutionContract( + model: model, backend: backend, + cacheProvider: bank, assistant: nil, construction: scope, loadedOwner: model, + completePrefixCache: store, completePrefixValidator: model, + prefixProcessMemoryOwner: process) + try beforeConsume?(contract, model, backend, bank, process) + let engine = EngineV2( + model: model, layerKinds: kinds, backend: backend, cacheProvider: bank, + schedulerConfig: .init( + maxConcurrentRequests: 2, maxBatchedTokensPerStep: chunk, + prefillChunkSize: chunk, enablePrefixCache: true), + loopConfig: .init( + stepTimeout: 60, watchdogInterval: 0.01, shutdownTimeout: shutdownTimeout), + admissionConfig: .init(watermarkFraction: 0), completePrefixCache: store, + processMemoryOwner: process, nativeCompletionTracking: true, + nativeExecutionContract: contract) + try scope.retainOwner(engine) + return engine + } + XCTAssertNil(engine.nativeCompletionFault) + return .init( + engine: engine, backend: backend, model: model, process: process, store: store, + scope: scope) + } + + private func request(_ id: UInt64) -> CBv2Request { + .init( + id: .init(id), promptTokens: (0 ..< (3 * chunk + 1)).map { ($0 * 7) % 29 }, + sampling: .init(temperature: 0), maxTokens: 3, cacheSalt: "isolated-tenant", + prefixCacheReceiptID: .init(id + 1000)) + } + + private func shutDown(_ f: Fixture) async throws { + guard case .quiescent = await f.engine.shutdownReportingNativeCompletion() else { + _ = Unmanaged.passRetained(f.engine) + throw Failure.noReceipt + } + XCTAssertTrue(f.store.closeJoined.value) + XCTAssertEqual(f.backend.bytesReserved, 0) + XCTAssertEqual(f.process.bytes, 0) + XCTAssertTrue(f.process.retired) + } + + private final class WeakArray: @unchecked Sendable { + weak var value: MLXArray? + init(_ value: MLXArray) { self.value = value } + } + private final class ArrayWitness: @unchecked Sendable { + private let lock = NSLock() + private var values: [WeakArray] = [] + func record(_ arrays: [MLXArray]) { lock.withLock { values = arrays.map(WeakArray.init) } } + var liveCount: Int { lock.withLock { values.filter { $0.value != nil }.count } } + } + private func tracking(_ f: Fixture) throws -> CBv2NativeShutdownState { + try XCTUnwrap(f.engine.loopForTesting.nativeShutdownState) + } + private func capturedArchive() async throws -> CompleteCheckpointFixtureStore.Archive { + let f = try fixture() + let submitted = try f.engine.submitWithNativeRetirement(request(800)) + let result = await cbv2SchedCollect(submitted.events) + guard result.finishReason == .length else { + _ = await f.engine.shutdownReportingNativeCompletion() + throw Failure.noReceipt + } + await submitted.retirement.wait() + let archive = try XCTUnwrap(f.store.base.saved.first { $0.manifest.position == chunk }) + try await shutDown(f) + return archive // encoded Data + wire-roundtripped manifest; no donor native aliases + } + private func importPlan( + _ f: Fixture, _ archive: CompleteCheckpointFixtureStore.Archive, + _ input: CBv2Request, retireGate: Gate? = nil, armed: Flag? = nil + ) + throws -> CBv2CompleteCheckpointImportPlan + { + let state = try tracking(f) + f.engine.loopForTesting.onEngineQueueSync { + state.beforeFenceForTesting = { _ in if armed?.value == true { retireGate?.hold() } } + } + defer { f.engine.loopForTesting.onEngineQueueSync { state.beforeFenceForTesting = nil } } + return try f.engine.planCompleteCheckpointImport(manifest: archive.manifest, request: input) + } + private func fill( + _ sink: CBv2CompleteCheckpointImport, archive: CompleteCheckpointFixtureStore.Archive + ) throws { + for piece in archive.chunks { + try sink.appendSegment( + tensorIndex: piece.tensor, byteOffset: piece.offset, data: piece.bytes) + } + } + + func testDeferredPlanOwnsRealLoanAndExplicitCloseLeavesRetainedAliasMetadataOnly() async throws + { + try lane() + let archive = try await capturedArchive() + let f = try fixture() + let entered = expectation(description: "deferred plan real retirement fence") + let gate = Gate(entered) + let armed = Flag() + var plan: CBv2CompleteCheckpointImportPlan? = try importPlan( + f, archive, request(801), + retireGate: gate, armed: armed) + XCTAssertTrue(try tracking(f).hasLoans) + armed.set() + plan!.close() + await fulfillment(of: [entered], timeout: 3) + XCTAssertTrue(try tracking(f).hasLoans, "queued completion is not retirement") + XCTAssertThrowsError(try plan!.allocate(onRelease: {})) + gate.release() + let nativeTracking = try tracking(f) + let loanEnded = await cbv2SchedWait { !nativeTracking.hasLoans } + XCTAssertTrue(loanEnded) + XCTAssertNotNil(plan, "public metadata alias remains, without a native codec loan") + plan = nil // metadata permit has its OWN lifetime; final-zero waits for it + try await shutDown(f) + } + + func testMoveStageCloseKeepsActualArraysAndChargeUntilQueuedFenceCompletes() async throws { + try lane() + let archive = try await capturedArchive() + let f = try fixture() + let entered = expectation(description: "import close real fence") + let gate = Gate(entered) + let armed = Flag() + let released = Flag() + let witness = ArrayWitness() + var plan: CBv2CompleteCheckpointImportPlan? = try importPlan( + f, archive, request(802), + retireGate: gate, armed: armed) + plan!.evaluateDestinations = { arrays in + witness.record(arrays) + try withError { eval(arrays) } + } + var sink: CBv2CompleteCheckpointImport? = try plan!.allocate { released.set() } + try fill(sink!, archive: archive) + var stage: CBv2StagedCompleteCheckpoint? = try sink!.finish() + sink!.close() // source wrapper no longer owns the moved stage + XCTAssertThrowsError(try plan!.allocate(onRelease: {}), "native plan is single use") + XCTAssertGreaterThan(witness.liveCount, 0) + let charge = f.process.bytes + armed.set() + stage!.close() + await fulfillment(of: [entered], timeout: 3) + XCTAssertFalse(released.value) + XCTAssertGreaterThan(witness.liveCount, 0) + XCTAssertEqual(f.process.bytes, charge) + XCTAssertTrue(try tracking(f).hasLoans) + gate.release() + let fullyRetired = await cbv2SchedWait { released.value && witness.liveCount == 0 } + XCTAssertTrue(fullyRetired) + XCTAssertFalse(try tracking(f).hasLoans) + XCTAssertNotNil(plan) + XCTAssertNotNil(sink) + XCTAssertNotNil(stage) + // Retained closed handles keep manifest/plan metadata, not native arrays. + stage = nil + sink = nil + plan = nil + try await shutDown(f) + } + + func testForeignNativeConsumptionDoesNotMoveAndActualBackendRefusalRetiresAfterFence() + async throws + { + try lane() + let archive = try await capturedArchive() + let f = try fixture() + let input = request(803) + let codec = try XCTUnwrap(f.engine.completeCheckpointCodec) + let entered = expectation(description: "failed adoption retires through real import fence") + let gate = Gate(entered) + let armed = Flag() + let released = Flag() + var plan: CBv2CompleteCheckpointImportPlan? = try importPlan( + f, archive, input, retireGate: gate, armed: armed) + var sink: CBv2CompleteCheckpointImport? = try plan!.allocate { released.set() } + try fill(sink!, archive: archive) + var stage: CBv2StagedCompleteCheckpoint? = try sink!.finish() + XCTAssertThrowsError( + try stage!.consumeNativePreparedState( + store: f.store, + request: input, engineID: UUID(), expectedCodec: codec + ) { _, _, _ in + XCTFail("foreign consumed") + return () + }) + XCTAssertNoThrow( + try stage!.withValidatedNativeCodec( + store: f.store, request: input, + engineID: f.engine.nativeShutdownEngineID, expectedCodec: codec + ) { _ in () }) + f.backend.checkpointBeforeRegistration = { throw Failure.adoption } + f.store.supplyActualForeignStage(stage!, receipt: try XCTUnwrap(input.prefixCacheReceiptID)) + let engine = f.engine + let nativeTracking = try tracking(f) + defer { gate.release() } + armed.set() + // Submission/collection can depend on this real retirement fence. + // Do not await them before observing and releasing the held gate. + let collector = Task { await cbv2SchedCollect(try engine.submit(input)) } + await fulfillment(of: [entered], timeout: 3) + XCTAssertFalse(released.value) + XCTAssertTrue(nativeTracking.hasLoans) + XCTAssertGreaterThan(f.process.bytes, 0) + XCTAssertNil(f.engine.nativeCompletionFault) + gate.release() + let result = try await collector.value + XCTAssertEqual( + result.finishReason, .length, + "ordinary metadata veto falls back, not a fabricated native fault") + XCTAssertEqual(result.usage?.prefixCachePrefillTokensSaved, 0) + let callbackReturned = await cbv2SchedWait { released.value } + XCTAssertTrue(callbackReturned) + stage = nil + sink = nil + plan = nil + try await shutDown(f) + } + + func testRequiredImportEvaluationFailureCannotBeRehabilitatedByLaterSuccessfulFence() + async throws + { + try lane(fault: "import-evaluation") + let archive = try await capturedArchive() + let f = try fixture() + let released = Flag() + let witness = ArrayWitness() + var plan: CBv2CompleteCheckpointImportPlan? = try f.engine.planCompleteCheckpointImport( + manifest: archive.manifest, request: request(804)) + plan!.evaluateDestinations = { arrays in + witness.record(arrays) + try withError { eval(arrays) } + throw Failure.fence // injected required-completion failure AFTER real native evaluation + } + XCTAssertThrowsError(try plan!.allocate { released.set() }) + let retainedCharge = f.process.bytes + XCTAssertGreaterThan(retainedCharge, 0) + XCTAssertGreaterThan(witness.liveCount, 0) + XCTAssertFalse(released.value) + XCTAssertNotNil(f.engine.nativeCompletionFault) + try withError { + StreamOrDevice.default.stream.synchronize() + StreamOrDevice.cpu.stream.synchronize() + } + plan!.close() + plan = nil + XCTAssertFalse(released.value) + XCTAssertGreaterThanOrEqual(f.process.bytes, retainedCharge) + XCTAssertGreaterThan(witness.liveCount, 0) + guard case .incomplete = await f.engine.shutdownReportingNativeCompletion() else { + return XCTFail("original required failure became quiescent") + } + _ = Unmanaged.passRetained(f.engine) + // Fresh-process retained-fault test, NOT a physical GPU-failure claim. + } + + func testActualStridedExportSegmentsKeepOnlyBoundedSourceRoots() async throws { + try lane() + let archive = try await capturedArchive() + let f = try fixture() + let codec = try XCTUnwrap(f.engine.completeCheckpointCodec) + let work = try f.engine.loopForTesting.onEngineQueueSync { + try f.engine.loopForTesting.makeNativeCompletePrefixWork( + purpose: .publication, requestID: .init(805)) + } + let permit = try codec.admission.reserveTransient(bytes: 8 << 20) + try work.retain(owners: [permit]) + try work.captureCurrentStreams() + var arrays: [MLXArray] = [] + var expected: [Data] = [] + for descriptor in archive.manifest.tensors { + let p = descriptor.shape[2] + let d = descriptor.shape[3] + let words = (0 ..< (p * d)).map { UInt32($0 % 1024) | 0x3f00_0000 } + let backing = MLXArray(words, [1, 1, d, p]) + let array = backing.view(dtype: .float32).transposed(0, 1, 3, 2) + try work.retain(arrays: [backing, array]) + arrays.append(array) + var bytes = Data() + for time in 0 ..< p { + for feature in 0 ..< d { + var word = words[feature * p + time].littleEndian + withUnsafeBytes(of: &word) { bytes.append(contentsOf: $0) } + } + } + expected.append(bytes) + } + try withError { eval(arrays) } + let source = CBv2CompleteCheckpointExport( + manifest: archive.manifest, arrays: arrays, + usesProcessMemoryOwner: true, retainedOwners: [permit]) + try work.retain(owners: [source]) + try source.bindNativeCompletePrefixWork(work) + let roots = work.debugRetainedArrayCount + let charge = f.process.bytes + for (index, descriptor) in archive.manifest.tensors.enumerated() { + var data = Data() + var offset = 0 + while offset < descriptor.byteCount { + let part = try source.readSegment( + tensorIndex: index, byteOffset: offset, maximumBytes: 260) + data.append(part) + offset += part.count + XCTAssertEqual( + work.debugRetainedArrayCount, roots, "no per-segment native packing allocation") + XCTAssertEqual( + f.process.bytes, charge, "no temporary-readback refund of whole work") + } + XCTAssertEqual(data, expected[index]) + } + source.close() + arrays.removeAll() + let retired = expectation(description: "publication operation and scratch retired") + XCTAssertTrue( + work.finishAfterDroppingConsumers { + permit.release() + retired.fulfill() + }) + await fulfillment(of: [retired], timeout: 3) + try await shutDown(f) + } + + func testRealAdmissionTransferKeepsFullTargetExcessAuxiliaryAndHostThroughDetach() throws { + try lane() + // Actual Admission + native evaluated buffers; this is accounting, + // not a trained-head or model numerical equivalence test. + for releaseLeaseFirst in [true, false] { + let process = ProcessOwner() + let position = 128 + let maximum = 256 + let kinds: [CBv2LayerKind] = [ + .init( + attention: .slidingWindow(17), headDim: 192, valueHeadDim: 128, kvHeads: 1, + queryHeads: 2), + .init(attention: .full, headDim: 192, valueHeadDim: 128, kvHeads: 1, queryHeads: 2), + ] + let fixed = 2 << 20 + let admission = AdmissionV2( + layerKinds: kinds, bytesCapacity: 32 << 20, + config: .init(watermarkFraction: 0, elementBytes: 2, fixedBytesPerRequest: fixed), + processMemoryOwner: process) + let targetShapes = [ + [1, 1, 17, 192], [1, 1, 17, 128], [1, 1, maximum, 192], [1, 1, maximum, 128], + ] + let targetSpecs: [([Int], DType)] = targetShapes.map { ($0, .bfloat16) } + let auxSpecs: [([Int], DType)] = + Array(repeating: ([1, 1, 17, 64], .bfloat16), count: 6) + + [([1, 3, 64], .bfloat16), ([1, position], .int32), ([3, 7], .int64)] + XCTAssertEqual(auxSpecs.count, 9) + func bound(_ specs: [([Int], DType)]) throws -> Int { + try specs.reduce(0) { total, spec in + try CBv2CheckpointAllocationFootprint.add( + total, + CBv2CheckpointAllocationFootprint.bound(spec.0.reduce(1, *) * spec.1.size)) + } + } + let target = try bound(targetSpecs) + let nativeAux = try bound(auxSpecs) + let host = 8 * position + (64 << 10) + let auxiliary = nativeAux + host + let scratch = 1 << 20 + let nominalTarget = (17 + maximum) * (192 + 128) * 2 + let ordinary = nominalTarget + fixed + XCTAssertEqual(admission.allocatedBytes(forTokens: maximum), ordinary) + let excess = target - nominalTarget + XCTAssertGreaterThan( + excess, 0, "Metal allocator-bound target padding must be discriminating") + XCTAssertLessThan( + auxiliary, fixed, "discounting aux against fixed state would erase this witness") + let stage = try admission.reserveCheckpointStage( + targetBytes: target, auxiliaryBytes: auxiliary, scratchBytes: scratch) + var arrays: [MLXArray]? = (targetSpecs + auxSpecs).map { + MLXArray.zeros($0.0, dtype: $0.1) + } + try withError { + eval(arrays!) + StreamOrDevice.default.stream.synchronize() + } + _ = try CBv2CheckpointAllocationFootprint.freshBytes(arrays!) + try stage.settleDestinationAfterEvaluation( + targetBytes: target, auxiliaryBytes: auxiliary) + let ticket = try admission.transferContiguousCheckpointStage( + stage, requestID: .init(806), maximumTokens: maximum) + ticket.commit() + XCTAssertEqual(admission.bytesReserved, ordinary + excess + auxiliary + scratch) + XCTAssertEqual(admission.nonBackendBytesReserved, fixed + auxiliary + scratch) + XCTAssertEqual( + admission.targetBytesReserved(partitionedBy: [.init(806)]).materialized, + nominalTarget + excess) + stage.closeAfterDroppingOwners() // destination moved; scratch only + XCTAssertEqual(admission.bytesReserved, ordinary + excess + auxiliary) + let detached = admission.detachReservation(id: .init(806)) + XCTAssertEqual(admission.nonBackendBytesReserved, fixed + auxiliary) + XCTAssertEqual(admission.bytesReserved, ordinary + excess + auxiliary) + if releaseLeaseFirst { + detached.release() + XCTAssertEqual(admission.bytesReserved, ordinary + excess + auxiliary) + arrays = nil + admission.retireContiguousCheckpointRows(id: .init(806), owner: stage.identity) + } else { + arrays = nil + admission.retireContiguousCheckpointRows(id: .init(806), owner: stage.identity) + XCTAssertEqual(admission.bytesReserved, ordinary + excess + auxiliary) + detached.release() + } + XCTAssertEqual(admission.bytesReserved, 0) + XCTAssertEqual(admission.nonBackendBytesReserved, 0) + XCTAssertEqual(process.bytes, 0) // fixture ledger zero, not physical-free proof + } + } +} diff --git a/Tests/MLXLMTests/CBv2NativeCompletePrefixOwnerTests.swift b/Tests/MLXLMTests/CBv2NativeCompletePrefixOwnerTests.swift new file mode 100644 index 0000000000..bddcc7fb4b --- /dev/null +++ b/Tests/MLXLMTests/CBv2NativeCompletePrefixOwnerTests.swift @@ -0,0 +1,721 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLMCommon + +/// Real Common native graphs/rows/issuer/async store jobs, not a MiMo model or +/// artifact qualification. Strict-loaded MiMo factory and MTP codec tests are +/// separate integration gates. Every retained-fault selector needs a fresh process. +final class CBv2NativeCompletePrefixOwnerTests: XCTestCase { + private enum Failure: Error { case invalidated, capacity, fence, noReceipt } + + private final class ProcessOwner: CBv2ProcessMemoryOwner, @unchecked Sendable { + private let lock = NSLock() + private var value: UInt64 = 0 + private var closed = false + private var materialized: UInt64 = 0 + var bytes: UInt64 { lock.withLock { value } } + var retired: Bool { lock.withLock { closed } } + func replaceCharge(_ bytes: UInt64) throws { + try lock.withLock { + guard !closed, bytes >= materialized, bytes <= 256 << 20 else { + throw Failure.capacity + } + value = bytes + } + } + func recordMaterialization(_ bytes: UInt64) throws { + try lock.withLock { + guard bytes >= materialized, bytes <= value else { throw Failure.capacity } + materialized = bytes + } + } + func withdrawCoverage(_ bytes: UInt64) throws { + try lock.withLock { + guard bytes <= materialized else { throw Failure.capacity } + materialized -= bytes + } + } + func retire() { + lock.withLock { + XCTAssertEqual(value, 0) + closed = true + } + } + } + + /// Same real asymmetric attention pattern used by the existing historical + /// checkpoint fixture, with immutable materialized native input and a + /// package-only generation validator. This is not an NSObject stand-in. + private final class Model: CBv2SteppableModel, CBv2HistoricalAttentionCheckpointProviding, + CBv2CompleteCheckpointKVTypeProviding, CBv2NativeCompletePrefixBindingValidating + { + let loadedScale = MLXArray(Float(1.0 / 32.0)) + private let lock = NSLock() + private var valid = true + var cbv2SupportsHistoricalAttentionCheckpoint: Bool { true } + var cbv2CompleteCheckpointKVDTypes: [DType]? { [.float32, .float32] } + func invalidate() { lock.withLock { valid = false } } + func validateNativeCompletePrefixBinding() throws { + if !lock.withLock({ valid }) { throw Failure.invalidated } + } + func forward(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> MLXArray { + let b = tokens.dim(0) + let n = tokens.dim(1) + var hidden = tokens.asType(.float32).reshaped([b, 1, n, 1]) * loadedScale + for cache in caches { + let q = MLXArray.zeros([b, 2, n, 192], dtype: .float32) + let k = broadcast(hidden, to: [b, 1, n, 192]) + let v = broadcast(hidden, to: [b, 1, n, 128]) + hidden = mean( + cache.updateAndAttend( + queries: q, keys: k, values: v, + scale: 0.125, sinks: nil), axes: [1, 3], keepDims: true) + } + let target = MLX.round(hidden.reshaped([b, n, 1]) * Float(128)).asType(.int32) % 31 + return MLX.where(MLXArray(Int32(0) ..< Int32(32)) .== target, Float(10), Float(-10)) + } + } + + /// Observation only: the actual owners below are a native MLXArray and a + /// native KV row. This box owns neither, and is not a completion receipt. + private final class RetirementRootWitness { + weak var array: MLXArray? + weak var row: CBv2WindowedSequenceKV? + init(array: MLXArray, row: CBv2WindowedSequenceKV) { + self.array = array + self.row = row + } + } + + /// A real function return ends every setup-local strong alias before the + /// queued finish begins. Do not return an array/row/tuple of strong roots. + @inline(never) + private func retainEvaluatedRetirementRoots(_ work: CBv2NativeCompletePrefixWork) throws + -> RetirementRootWitness + { + try work.captureCurrentStreams() + let array = (MLXArray(Int32(0) ..< Int32(1024)).asType(.float32) + Float(1)) + let row = CBv2WindowedSequenceKV(window: 17, kvHeads: 1, headDim: 192, valueHeadDim: 128) + // The real counted work owns both graph and row before evaluation. + try work.retain(arrays: [array], owners: [row]) + let pair = row.update( + keys: MLXArray.ones([1, 1, 3, 192], dtype: .float32), + values: MLXArray.ones([1, 1, 3, 128], dtype: .float32)) + try withError { errors in + eval(array, pair.0, pair.1) + try errors.check() + } + return .init(array: array, row: row) + } + + private final class Flag: @unchecked Sendable { + private let lock = NSLock() + private var flag = false + var value: Bool { lock.withLock { flag } } + func set() { lock.withLock { flag = true } } + } + + private final class Gate: @unchecked Sendable { + let entered: XCTestExpectation + private let lock = NSLock() + private var first = true + private let resume = DispatchSemaphore(value: 0) + init(_ entered: XCTestExpectation) { self.entered = entered } + func hold() { + guard + lock.withLock({ + let old = first + first = false + return old + }) + else { return } + entered.fulfill() + _ = resume.wait(timeout: .now() + 8) + } + func release() { resume.signal() } + } + + private final class Store: CBv2NativeCompletePrefixCache, @unchecked Sendable { + let base: CompleteCheckpointFixtureStore + private let jobs = DispatchGroup() + private let lock = NSLock() + private var supplied: [CBv2RequestID: CBv2StagedCompleteCheckpoint] = [:] + var closeGate: Gate? + let closeJoined = Flag() + init( + writeGate: CheckpointPublicationGate? = nil, + archives: [CompleteCheckpointFixtureStore.Archive] = [] + ) { + base = .init(archives: archives, gate: writeGate, segmentBytes: 1 << 20) + } + var identity: CBv2CompleteCheckpointIdentity { base.identity } + func acceptsCheckpoint(position: Int, packedBytes: Int) -> Bool { + base.acceptsCheckpoint(position: position, packedBytes: packedBytes) + } + func takeStaged( + requestID: CBv2RequestID, tokens: [Int], cacheSalt: String?, + maximumSequenceLength: Int + ) -> CBv2StagedCompleteCheckpoint? { + if let actual = lock.withLock({ supplied.removeValue(forKey: requestID) }) { + return actual + } + return base.takeStaged( + requestID: requestID, tokens: tokens, cacheSalt: cacheSalt, + maximumSequenceLength: maximumSequenceLength) + } + func supplyActualForeignStage(_ stage: CBv2StagedCompleteCheckpoint, receipt: CBv2RequestID) + { + lock.withLock { + precondition(supplied[receipt] == nil) + supplied[receipt] = stage + } + } + func donate( + _ source: CBv2CompleteCheckpointExport, requestID: CBv2RequestID?, + tokens: [Int], cacheSalt: String?, + completion: @escaping @Sendable ([Int]) -> Void + ) { + jobs.enter() + base.donate(source, requestID: requestID, tokens: tokens, cacheSalt: cacheSalt) { + [self] positions in + completion(positions) + jobs.leave() // real underlying source read/close callback returned. + } + } + func close() { + let stages = lock.withLock { + let old = Array(supplied.values) + supplied = [:] + return old + } + stages.forEach { $0.close() } + base.close() + } + func closeAndWait() async { + closeGate?.hold() + close() + await withCheckedContinuation { continuation in + jobs.notify(queue: .global(qos: .utility)) { continuation.resume() } + } + closeJoined.set() + } + } + + private struct Fixture { + let engine: EngineV2 + let backend: CBv2ContiguousKVBackend + let model: Model + let process: ProcessOwner + let store: Store + let scope: NativeConstructionScope + } + private var chunk: Int { max(32, CBv2AttentionV1.queryBlockSize) } + + private func lane(fault: String? = nil) throws { + let env = ProcessInfo.processInfo.environment + guard env["DARKBLOOM_TEST_NATIVE_COMPLETE_PREFIX"] == "1" else { + throw XCTSkip("Requires an exclusively owned real native process") + } + guard env["DARKBLOOM_TEST_NATIVE_COMPLETE_PREFIX_FAULT"] == fault else { + throw XCTSkip("Retained fault cells run alone in fresh processes") + } + } + + private func fixture( + store: Store = Store(), shutdownTimeout: TimeInterval = 10, + beforeConsume: ( + ( + CBv2NativeExecutionContract, Model, CBv2ContiguousKVBackend, + CBv2LayerCacheBank, ProcessOwner + ) throws -> Void + )? = nil + ) throws -> Fixture { + let scope = NativeConstructionScope() + let model = Model() + let process = ProcessOwner() + let kinds: [CBv2LayerKind] = [ + .init( + attention: .slidingWindow(17), headDim: 192, valueHeadDim: 128, kvHeads: 1, + queryHeads: 2), + .init(attention: .full, headDim: 192, valueHeadDim: 128, kvHeads: 1, queryHeads: 2), + ] + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 128 << 20, kvDType: .float32)) + let bank = CBv2LayerCacheBank(layerKinds: kinds) + let engine = try scope.withPhase(.nativeSetup) { + try scope.capture(StreamOrDevice.cpu.stream) + try scope.capture(StreamOrDevice.default.stream) + try scope.retain(model.loadedScale) + try scope.willSubmit() + try withError { errors in + eval(model.loadedScale) + try errors.check() + } + try scope.authorizeImmutableLoadedOwner(model) + try scope.retainOwner(backend) + try scope.retainOwner(bank) + try scope.retainOwner(store) + let contract = try CBv2NativeExecutionContract( + model: model, backend: backend, + cacheProvider: bank, assistant: nil, construction: scope, loadedOwner: model, + completePrefixCache: store, completePrefixValidator: model, + prefixProcessMemoryOwner: process) + try beforeConsume?(contract, model, backend, bank, process) + let engine = EngineV2( + model: model, layerKinds: kinds, backend: backend, cacheProvider: bank, + schedulerConfig: .init( + maxConcurrentRequests: 2, maxBatchedTokensPerStep: chunk, + prefillChunkSize: chunk, enablePrefixCache: true), + loopConfig: .init( + stepTimeout: 60, watchdogInterval: 0.01, shutdownTimeout: shutdownTimeout), + admissionConfig: .init(watermarkFraction: 0), completePrefixCache: store, + processMemoryOwner: process, nativeCompletionTracking: true, + nativeExecutionContract: contract) + try scope.retainOwner(engine) + return engine + } + XCTAssertNil(engine.nativeCompletionFault) + return .init( + engine: engine, backend: backend, model: model, process: process, store: store, + scope: scope) + } + + private func request(_ id: UInt64) -> CBv2Request { + .init( + id: .init(id), promptTokens: (0 ..< (3 * chunk + 1)).map { ($0 * 7) % 29 }, + sampling: .init(temperature: 0), maxTokens: 3, cacheSalt: "isolated-tenant", + prefixCacheReceiptID: .init(id + 1000)) + } + + private func shutDown(_ f: Fixture) async throws { + guard case .quiescent = await f.engine.shutdownReportingNativeCompletion() else { + _ = Unmanaged.passRetained(f.engine) + throw Failure.noReceipt + } + XCTAssertTrue(f.store.closeJoined.value) + XCTAssertEqual(f.backend.bytesReserved, 0) + XCTAssertEqual(f.process.bytes, 0) + XCTAssertTrue(f.process.retired) + } + + func testProtectedIssuedTicketRejectsForeignActualStoreAndProcessOwnerWithoutConsumption() + async throws + { + try lane() + let foreignStore = Store() + let foreignProcess = ProcessOwner() + let localStore = Store() + let f = try fixture(store: localStore) { contract, model, backend, bank, process in + XCTAssertFalse( + contract.consume( + model: model, backend: backend, cacheProvider: bank, + assistant: nil, completePrefixCache: foreignStore, processMemoryOwner: process)) + XCTAssertFalse( + contract.consume( + model: model, backend: backend, cacheProvider: bank, + assistant: nil, completePrefixCache: localStore, + processMemoryOwner: foreignProcess)) + XCTAssertFalse( + contract.consume( + model: model, backend: backend, cacheProvider: bank, + assistant: nil, completePrefixCache: Store(), processMemoryOwner: process)) + } + let result = await cbv2SchedCollect(try f.engine.submit(request(101))) + XCTAssertEqual(result.finishReason, .length) + XCTAssertEqual(result.tokens.count, 3) + XCTAssertFalse(f.store.base.saved.isEmpty) + try await shutDown(f) + } + + func testBlockedPublicationAndActualCloseJoinRetainRowsAndRequestRetirement() async throws { + try lane() + let writeGate = CheckpointPublicationGate() + let store = Store(writeGate: writeGate) + let closeEntered = expectation(description: "actual store close entered") + let closeGate = Gate(closeEntered) + store.closeGate = closeGate + let f = try fixture(store: store) + let submitted = try f.engine.submitWithNativeRetirement(request(102)) + let retired = Flag() + let retirement = Task { + await submitted.retirement.wait() + retired.set() + } + let collector = Task { await cbv2SchedCollect(submitted.events) } + XCTAssertTrue(writeGate.waitUntilEntered()) + XCTAssertGreaterThan(f.backend.bytesReserved, 0) + XCTAssertGreaterThan(f.process.bytes, 0) + XCTAssertFalse(retired.value) + let shutdownEngine = f.engine + let shutdown = Task { await shutdownEngine.shutdownReportingNativeCompletion() } + await fulfillment(of: [closeEntered], timeout: 3) + XCTAssertFalse(store.closeJoined.value) + XCTAssertFalse(retired.value) + XCTAssertGreaterThan(f.backend.bytesReserved, 0) + closeGate.release() // real close cancels/unblocks the pending store write. + let result = await collector.value + await retirement.value + XCTAssertEqual(result.finishReason, .length) + XCTAssertEqual(result.tokens.count, 3) + guard case .quiescent = await shutdown.value else { throw Failure.noReceipt } + XCTAssertTrue(store.closeJoined.value) + XCTAssertTrue(retired.value) + XCTAssertEqual(f.backend.bytesReserved, 0) + XCTAssertEqual(f.process.bytes, 0) + } + + func testIdleEngineWaitsForActualStoreCloseJoinBeforeQuiescentOutcome() async throws { + try lane() + let store = Store() + let entered = expectation(description: "idle store closeAndWait entered") + let gate = Gate(entered) + store.closeGate = gate + defer { gate.release() } + let f = try fixture(store: store) + let engine = f.engine + // Never submit a request: no publication/import/drop/terminal consumer + // can independently mask a missing store-close join. + try engine.loopForTesting.onEngineQueueSync { + let tracking = try XCTUnwrap(engine.loopForTesting.nativeShutdownState) + XCTAssertNil(tracking.outcome) + XCTAssertFalse(tracking.hasLoans) + XCTAssertEqual(tracking.debugRetainedRootCount, 0) + XCTAssertEqual(engine.stepCount, 0) + XCTAssertEqual(f.backend.bytesReserved, 0) + XCTAssertEqual(f.process.bytes, 0) + XCTAssertFalse(f.process.retired) + } + XCTAssertTrue(store.base.saved.isEmpty) + let shutdown = Task { await engine.shutdownReportingNativeCompletion() } + await fulfillment(of: [entered], timeout: 3) + // The first barrier follows the initial drain frame; the next also + // follows a completion callback queued by that frame. Inspect the + // actual outcome, not whether the awaiting test Task has resumed. + engine.loopForTesting.onEngineQueueSync {} + let held = try engine.loopForTesting.onEngineQueueSync { + let tracking = try XCTUnwrap(engine.loopForTesting.nativeShutdownState) + return ( + outcome: tracking.outcome, loan: tracking.hasLoans, + processRetired: f.process.retired + ) + } + XCTAssertNil(held.outcome, "closeAndWait is the only unfinished consumer") + XCTAssertTrue(held.loan, "the actual store-close native loan must remain live") + XCTAssertFalse(held.processRetired) + XCTAssertFalse(store.closeJoined.value) + XCTAssertEqual(f.backend.bytesReserved, 0) + XCTAssertEqual(f.process.bytes, 0) + gate.release() + let outcome = await shutdown.value + guard case .quiescent(let receipt) = outcome else { + _ = Unmanaged.passRetained(engine) + throw Failure.noReceipt + } + XCTAssertEqual(receipt.engineID, engine.nativeShutdownEngineID) + XCTAssertEqual( + receipt.executionContractID, try XCTUnwrap(engine.nativeShutdownExecutionContractID)) + XCTAssertTrue(store.closeJoined.value) + try engine.loopForTesting.onEngineQueueSync { + let tracking = try XCTUnwrap(engine.loopForTesting.nativeShutdownState) + XCTAssertEqual(tracking.outcome, outcome) + XCTAssertFalse(tracking.hasLoans) + XCTAssertEqual(tracking.debugRetainedRootCount, 0) + } + XCTAssertTrue(f.process.retired) + XCTAssertEqual(f.process.bytes, 0) + XCTAssertEqual(f.backend.bytesReserved, 0) + } + + func testCancellationAfterRealCaptureDrainReleasesOnlyAfterLoanCompletion() async throws { + try lane() + let f = try fixture() + let entered = expectation(description: "required capture drain") + let gate = Gate(entered) + f.engine.loopForTesting.onEngineQueueSync { + f.engine.loopForTesting.completeCheckpointCapture?.makeContiguousCheckpoint = { + codec, position, chunk, state in + let value = try CBv2ContiguousHistoricalCheckpoint( + codec: codec, position: position, + chunkSize: chunk, state: state) + value.beforeRequiredDrainForTesting = { gate.hold() } + return value + } + } + let submitted = try f.engine.submitWithNativeRetirement(request(103)) + let collector = Task { await cbv2SchedCollect(submitted.events) } + let retired = Flag() + let retirement = Task { + await submitted.retirement.wait() + retired.set() + } + await fulfillment(of: [entered], timeout: 3) + f.engine.cancel(.init(103)) + XCTAssertFalse(retired.value) + XCTAssertGreaterThan(f.process.bytes, 0) + gate.release() + let result = await collector.value + await retirement.value + XCTAssertEqual(result.finishReason, .cancelled) + XCTAssertEqual(f.store.base.saved.count, 0) + try await shutDown(f) + } + + func testImportOwnerRejectsForeignCodecRequestStoreAndStaleGenerationBeforeNativeAdoption() + async throws + { + try lane() + let a = try fixture() + let b = try fixture() + let req = request(104) + let codec = try XCTUnwrap(a.engine.completeCheckpointCodec) + let factory = try XCTUnwrap( + a.engine.nativeCompletePrefixWorkFactory( + store: a.store, codec: codec, request: req)) + let work = try factory() + try work.validate( + store: a.store, codec: codec, request: req, engineID: a.engine.nativeShutdownEngineID) + XCTAssertThrowsError( + try work.validate( + store: b.store, codec: codec, + request: req, engineID: a.engine.nativeShutdownEngineID)) + XCTAssertThrowsError( + try work.validate( + store: a.store, codec: XCTUnwrap(b.engine.completeCheckpointCodec), + request: req, engineID: a.engine.nativeShutdownEngineID)) + var changed = req + changed.promptTokens[0] += 1 + XCTAssertThrowsError( + try work.validate( + store: a.store, codec: codec, + request: changed, engineID: a.engine.nativeShutdownEngineID)) + changed = req + changed.prefixCacheReceiptID = .init(99999) + XCTAssertThrowsError( + try work.validate( + store: a.store, codec: codec, + request: changed, engineID: a.engine.nativeShutdownEngineID)) + let released = expectation(description: "real native-work retirement callback") + let reservation = try codec.admission.reserveTransient(bytes: 1 << 20) + var values: MLXArray? = MLXArray.zeros([1024], dtype: .float32) + try work.captureCurrentStreams() + try work.retain(arrays: [try XCTUnwrap(values)], owners: [reservation]) + try withError { errors in + eval(try XCTUnwrap(values)) + try errors.check() + } + a.model.invalidate() + XCTAssertThrowsError( + try work.validate( + store: a.store, codec: codec, + request: req, engineID: a.engine.nativeShutdownEngineID)) + values = nil + XCTAssertTrue( + work.finishAfterDroppingConsumers { + reservation.release() + released.fulfill() + }) + await fulfillment(of: [released], timeout: 3) + XCTAssertFalse(work.finishAfterDroppingConsumers()) + try await shutDown(a) + try await shutDown(b) + } + + func testActualForeignImportRefusesThenSameEngineArchiveRestoresExactContinuation() async throws + { + try lane() + let seed = try fixture() + let cold = await cbv2SchedCollect(try seed.engine.submit(request(200))) + XCTAssertEqual(cold.finishReason, .length) + let archives = seed.store.base.saved.filter { $0.manifest.position == chunk } + XCTAssertEqual(archives.count, 1) + try await shutDown(seed) + let a = try fixture(store: Store(archives: archives)) + let b = try fixture(store: Store(archives: archives)) + let foreignRequest = request(201) + XCTAssertTrue(try a.store.base.stage(engine: a.engine, request: foreignRequest)) + XCTAssertTrue( + a.engine.loopForTesting.onEngineQueueSync { + a.engine.loopForTesting.nativeShutdownState?.hasLoans == true + }, "actual staged native import must hold a native operation loan") + var foreignStage: CBv2StagedCompleteCheckpoint? = try XCTUnwrap( + a.store.takeStaged( + requestID: XCTUnwrap(foreignRequest.prefixCacheReceiptID), + tokens: foreignRequest.promptTokens, cacheSalt: foreignRequest.checkpointCacheSalt, + maximumSequenceLength: foreignRequest.promptTokens.count + foreignRequest.maxTokens) + ) + XCTAssertTrue( + try XCTUnwrap(foreignStage).withValidatedNativeCodec( + store: a.store, request: foreignRequest, engineID: a.engine.nativeShutdownEngineID, + expectedCodec: XCTUnwrap(a.engine.completeCheckpointCodec) + ) { codec in + codec === a.engine.completeCheckpointCodec + }) + b.store.supplyActualForeignStage( + try XCTUnwrap(foreignStage), + receipt: try XCTUnwrap(foreignRequest.prefixCacheReceiptID)) + let rejected = await cbv2SchedCollect(try b.engine.submit(foreignRequest)) + XCTAssertEqual(rejected.finishReason, .length) + XCTAssertEqual(rejected.tokens, cold.tokens) + XCTAssertEqual(rejected.usage?.prefixCachePrefillTokensSaved, 0) + let released = await cbv2SchedWait { a.store.base.releaseCount == 1 } + XCTAssertTrue(released, "actual foreign native stage callback must retire once") + let importLoanEnded = await cbv2SchedWait { + a.engine.loopForTesting.nativeShutdownState?.hasLoans == false + } + XCTAssertTrue(importLoanEnded) + // The native loan is retired, but this closed handle still owns its + // host manifest permit. End that lifetime before final-zero shutdown. + foreignStage = nil + let validRequest = request(202) + XCTAssertTrue(try a.store.base.stage(engine: a.engine, request: validRequest)) + XCTAssertTrue(a.engine.loopForTesting.nativeShutdownState?.hasLoans == true) + let accepted = await cbv2SchedCollect(try a.engine.submit(validRequest)) + XCTAssertEqual(accepted.tokens, cold.tokens) + XCTAssertEqual(accepted.usage?.prefixCachePrefillTokensSaved, chunk) + XCTAssertEqual(accepted.usage?.prefixCacheReplayTokens, 0) + try await shutDown(a) + try await shutDown(b) + } + + func testPublicationReadbackTemporariesStayBoundedUntilRealWholeWorkRetirement() async throws { + try lane() + let f = try fixture() + let work = try f.engine.loopForTesting.onEngineQueueSync { + try f.engine.loopForTesting.makeNativeCompletePrefixWork( + purpose: .publication, + requestID: .init(203)) + } + let codec = try XCTUnwrap(f.engine.completeCheckpointCodec) + let reservation = try codec.admission.reserveTransient(bytes: 1 << 20) + try work.retain(owners: [reservation]) + let held = f.process.bytes + for _ in 0 ..< 8 { + var temporary: MLXArray? = MLXArray.zeros([1024], dtype: .float32) + try work.captureCurrentStreams() + try work.retain(arrays: [try XCTUnwrap(temporary)]) + try withError { errors in + eval(try XCTUnwrap(temporary)) + _ = try XCTUnwrap(temporary).asData(access: .copy).data + try errors.check() + } + XCTAssertEqual(work.debugRetainedArrayCount, 1) + try work.retireReadbackTemporaries([try XCTUnwrap(temporary)]) + temporary = nil + XCTAssertEqual(work.debugRetainedArrayCount, 0) + XCTAssertEqual(f.process.bytes, held, "readback never refunds whole-work C") + } + let retired = expectation(description: "whole publication scratch retired") + XCTAssertTrue( + work.finishAfterDroppingConsumers { + reservation.release() + retired.fulfill() + }) + await fulfillment(of: [retired], timeout: 3) + try await shutDown(f) + } + + func testTypedRequiredFenceFailureRetainsActualRootsAndCreditAfterLaterDrain() async throws { + try lane(fault: "typed-fence") + let f = try fixture() + f.engine.loopForTesting.onEngineQueueSync { + f.engine.loopForTesting.completeCheckpointCapture?.makeContiguousCheckpoint = { + codec, position, chunk, state in + let value = try CBv2ContiguousHistoricalCheckpoint( + codec: codec, position: position, + chunkSize: chunk, state: state) + value.beforeRequiredDrainForTesting = { throw Failure.fence } + return value + } + } + let submitted = try f.engine.submitWithNativeRetirement(request(105)) + _ = await cbv2SchedCollect(submitted.events) + guard case .incomplete(let first) = await f.engine.shutdownReportingNativeCompletion() + else { + throw Failure.noReceipt + } + XCTAssertEqual(first.reason, .nativeWorkFailed) + XCTAssertGreaterThan(f.process.bytes, 0) + XCTAssertGreaterThan(f.backend.bytesReserved, 0) + try withError { errors in + Stream.cpu.synchronize() + Stream.gpu.synchronize() + try errors.check() + } + guard case .incomplete(let later) = await f.engine.shutdownReportingNativeCompletion() + else { + throw Failure.noReceipt + } + XCTAssertEqual(first, later) + XCTAssertGreaterThan(f.process.bytes, 0) + // The real retirement token must NOT be awaited/claimed complete. + _ = Unmanaged.passRetained(f.engine) + } + func testQueuedRetirementDropsActualArrayAndRowOwnerBeforeCreditCallback() async throws { + try lane() + let f = try fixture() + let engine = f.engine + let process = f.process + let work = try engine.loopForTesting.onEngineQueueSync { + try engine.loopForTesting.makeNativeCompletePrefixWork( + purpose: .publication, + requestID: .init(204)) + } + let codec = try XCTUnwrap(engine.completeCheckpointCodec) + let reservation = try codec.admission.reserveTransient(bytes: 1 << 20) + try work.retain(owners: [reservation]) + let witness: RetirementRootWitness + do { witness = try retainEvaluatedRetirementRoots(work) } catch { + work.requiredCompletionFailed() + _ = Unmanaged.passRetained(engine) + _ = Unmanaged.passRetained(work) + throw error + } + XCTAssertTrue(witness.array != nil) + XCTAssertTrue(witness.row != nil) + XCTAssertEqual(work.debugRetainedArrayCount, 1) + let charged = process.bytes + XCTAssertGreaterThan(charged, 0) + let returned = expectation(description: "actual queued work retirement callback returned") + let callbackReached = Flag() + XCTAssertTrue( + work.finishAfterDroppingConsumers { + // This executes on the actual completion/engine queue after the + // required stream fences, BEFORE this callback releases C and + // BEFORE finishAfterDroppingConsumers ends the native loan/wakes. + // No onEngineQueueSync here: it forbids self-queue dispatch. + let arrayGone = witness.array == nil + let rowGone = witness.row == nil + XCTAssertTrue( + arrayGone, "a cleared arrays.count cannot hide a detached COW root alias") + XCTAssertTrue( + rowGone, "the real native KV owner must be gone before retirement credit") + XCTAssertEqual(work.debugRetainedArrayCount, 0) + XCTAssertEqual( + process.bytes, charged, "credit is still owned at the weak-root observation") + XCTAssertTrue(engine.loopForTesting.nativeShutdownState?.hasLoans == true) + // An oracle failure must not release the genuine charge. The real + // work's existing throwing-retirement path keeps its owner/fault. + guard arrayGone, rowGone else { throw Failure.noReceipt } + reservation.release() + callbackReached.set() + returned.fulfill() + }) + await fulfillment(of: [returned], timeout: 3) + guard callbackReached.value else { + _ = Unmanaged.passRetained(engine) + _ = Unmanaged.passRetained(work) + throw Failure.noReceipt + } + XCTAssertTrue(witness.array == nil) + XCTAssertTrue(witness.row == nil) + XCTAssertFalse( + work.finishAfterDroppingConsumers(), "one-shot work cannot repeat retirement") + // Keep the actual work handle alive through the observation; success + // must come from explicit root movement, not the work object's deinit. + withExtendedLifetime(work) {} + try await shutDown(f) + } + +} diff --git a/Tests/MLXLMTests/CBv2NativeRequestRetirementTests.swift b/Tests/MLXLMTests/CBv2NativeRequestRetirementTests.swift new file mode 100644 index 0000000000..c01694f0f4 --- /dev/null +++ b/Tests/MLXLMTests/CBv2NativeRequestRetirementTests.swift @@ -0,0 +1,865 @@ +import Foundation +import MLX +import MLXLLM +import XCTest + +@_spi(Diagnostics) @testable import MLXLMCommon +@testable import MLXVLM + +/// Source-prepared. These tests load the real bounded BF16 component fixture, +/// run its actual native target/assistant and use the protected resource issuer. +/// The tokenizer controls factory setup only; it is not template parity proof. +final class CBv2NativeRequestRetirementTests: XCTestCase { + private enum Failure: Error { case fence, missingReceipt, submittedWork } + private final class Permit: MiMoV26SerialLoadReservation, Sendable { + let request: MiMoV26SerialLoadRequest + let reservedLoadBytes: UInt64 + init(_ request: MiMoV26SerialLoadRequest) { + self.request = request + reservedLoadBytes = request.requiredLoadBytes + } + func validateActive(progress: MiMoV26SerialLoadProgress) throws {} + } + private final class ControlTokenizer: Tokenizer, Sendable { + let decoderGate: DecodeGate? + init(_ decoderGate: DecodeGate? = nil) { self.decoderGate = decoderGate } + func encode(text: String, addSpecialTokens: Bool) -> [Int] { [6] } + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + decoderGate?.visit() + return tokenIds.map(String.init).joined() + } + func convertTokenToId(_ token: String) -> Int? { token == "<|im_end|>" ? 3 : nil } + func convertIdToToken(_ id: Int) -> String? { id == 3 ? "<|im_end|>" : nil } + var bosToken: String? { nil } + var eosToken: String? { "<|im_end|>" } + var unknownToken: String? { nil } + func applyChatTemplate( + messages: [Message], tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { + throw TokenizerError.missingChatTemplate + } + func applyChatTemplate(messages: [Message], chatTemplate: String) throws -> [Int] { + try applyChatTemplate( + messages: messages, chatTemplate: chatTemplate, tools: nil, additionalContext: nil) + } + func applyChatTemplate( + messages: [Message], chatTemplate: String, tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { + [1] + ((additionalContext?["enable_thinking"] as? Bool) == false ? [4, 5] : []) + [6] + } + } + private struct Loader: TokenizerLoader { + func load(from directory: URL) async throws -> any Tokenizer { ControlTokenizer() } + } + private final class OneShotGate: @unchecked Sendable { + let entered: XCTestExpectation + private let lock = NSLock() + private var enteredOnce = false + private let released = DispatchSemaphore(value: 0) + init(_ entered: XCTestExpectation) { self.entered = entered } + func holdOnce(_ beforeHold: () -> Void = {}) { + let first = lock.withLock { () -> Bool in + guard !enteredOnce else { return false } + enteredOnce = true + return true + } + guard first else { return } + beforeHold() + entered.fulfill() + released.wait() + } + func release() { released.signal() } + // No destructor waits; a one-shot signal is never consumed twice. + } + private final class DecodeGate: @unchecked Sendable { + let gate: OneShotGate + let targetCall: Int + private let lock = NSLock() + private var calls = 0 + init(_ gate: OneShotGate, targetCall: Int) { + self.gate = gate + self.targetCall = targetCall + } + func visit() { + let current = lock.withLock { + calls += 1 + return calls + } + if current == targetCall { gate.holdOnce() } + } + } + /// Test-control metadata only. Prevent a regression's unresolved Task from + /// making the test itself wait forever after its bounded expectation fails. + private final class SubmissionCompletion: @unchecked Sendable { + private let lock = NSLock() + private var finished = false + func markFinished() { lock.withLock { finished = true } } + var isFinished: Bool { lock.withLock { finished } } + } + + private func lane(fault: String? = nil) throws { + let env = ProcessInfo.processInfo.environment + guard env["MIMO_V26_SERIAL_NATIVE_TESTS"] == "1" else { + throw XCTSkip("Requires an authorized exclusive native test process") + } + guard env["MIMO_V26_REQUEST_RETIREMENT_FAULT_CASE"] == fault else { + throw XCTSkip( + "Run each retained-fault selector alone with its exact MIMO_V26_REQUEST_RETIREMENT_FAULT_CASE" + ) + } + } + private func engine( + tracked: Bool = true, mtp: Bool = false, text: Bool = false, + shutdownTimeout: TimeInterval = 10, + stepTimeout: TimeInterval = 60, decoderGate: DecodeGate? = nil, + serializedPrefill: Bool = false + ) async throws -> EngineV2 { + let fixtureRoot = URL( + fileURLWithPath: try XCTUnwrap( + ProcessInfo.processInfo.environment["MIMO_V26_SERIAL_LOAD_FIXTURES"])) + let root = fixtureRoot.appendingPathComponent( + "request-retirement-work-" + UUID().uuidString) + try FileManager.default.copyItem( + at: fixtureRoot.appendingPathComponent("tiny-bf16"), to: root) + try Data("{}".utf8).write(to: root.appendingPathComponent("tokenizer.json")) + try JSONSerialization.data(withJSONObject: ["eos_token": "<|im_end|>"]) + .write(to: root.appendingPathComponent("tokenizer_config.json")) + try Data("{{ messages }}{% if enable_thinking is false %}{% endif %}".utf8) + .write(to: root.appendingPathComponent("chat_template.jinja")) + let p = try XCTUnwrap( + JSONSerialization.jsonObject( + with: + Data(contentsOf: fixtureRoot.appendingPathComponent("provenance.json"))) + as? [String: String]) + let provenance = try MiMoV26ConvertedProvenance( + artifactID: XCTUnwrap(p["artifactID"]), + sourceRepository: XCTUnwrap(p["sourceRepository"]), + sourceRevision: XCTUnwrap(p["sourceRevision"]), + conversionManifestSHA256: XCTUnwrap(p["conversionManifestSHA256"])) + let plan = try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance, + limits: .init(maximumShardBytes: 1_048_576, maximumTotalFileBytes: 4_194_304)) + let session = try MiMoV26SerialLoadSession(plan: plan) + let prepared = try await MiMoV26ModelFactory.prepare( + request: session.request, + configuration: .init(directory: root), tokenizerLoader: Loader()) + let work = NativeConstructionWork() + let container = try await MiMoV26ModelFactory.loadContainer( + session: session, + reservation: Permit(session.request), prepared: prepared, retaining: work) + try await work.acknowledgeContainerAdoption(container) + let actual = try await MiMoV26ModelFactory.withNativeConstruction( + container: container, retaining: work + ) { model, scope in + let binding = try model.makeCBv2Binding(enableMTP: mtp) + _ = try binding.adapter.probeNativeKVTypes(retaining: scope) + let resources = try binding.adapter.makeNativeExecutionResources( + bytesCapacity: 32 << 20, retaining: scope) + let detokenizer: any CBv2DetokenizerFactory = + text + ? CBv2TextDetokenizerFactory(tokenizer: ControlTokenizer(decoderGate)) + : CBv2NullDetokenizerFactory() + let engine = EngineV2( + model: binding.adapter, layerKinds: binding.adapter.layerKinds, + backend: resources.backend, cacheProvider: resources.cacheProvider, + detokenizerFactory: detokenizer, + schedulerConfig: .init( + maxConcurrentRequests: 2, maxBatchedTokensPerStep: 16, + prefillChunkSize: 3, maxConcurrentPartialPrefills: serializedPrefill ? 1 : nil, + maxWaiting: 4, enablePrefixCache: false), + loopConfig: .init( + stepTimeout: stepTimeout, watchdogInterval: 0.01, + shutdownTimeout: shutdownTimeout), + mtpDrafter: binding.assistant, + mtpConfig: .init( + enabled: mtp, maxDraftTokens: 3, maxSpeculativeBatch: 1, + fixedDraftTokens: 3, verificationMode: .serialTarget), + nativeCompletionTracking: tracked, nativeExecutionContract: resources.contract) + try scope.retainOwner(engine) + return engine + } + guard case .completed(let setup) = work.snapshot.disposition else { + throw Failure.missingReceipt + } + try await work.sealForPublication(setup) + return actual + } + private func request(_ id: UInt64 = 1, budget: Int = 12, logprobs: Int = 0) -> CBv2Request { + .init( + id: .init(id), promptTokens: [1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12], + sampling: .init(temperature: 0, topLogprobs: logprobs), maxTokens: budget) + } + private func collect(_ engine: EngineV2, _ request: CBv2Request) async throws -> [Int] { + let result = await cbv2SchedCollect(try engine.submit(request)) + XCTAssertEqual(result.finishReason, .length) + XCTAssertEqual(result.tokens.count, request.maxTokens) + XCTAssertEqual(result.usage?.completionTokens, request.maxTokens) + return result.tokens + } + private func receipt(_ outcome: CBv2NativeShutdownOutcome, _ engine: EngineV2) throws + -> CBv2NativeShutdownReceipt + { + guard case .quiescent(let receipt) = outcome else { + XCTFail("not quiescent: \(outcome)") + throw Failure.missingReceipt + } + XCTAssertEqual(receipt.engineID, engine.nativeShutdownEngineID) + XCTAssertEqual(receipt.generation, 1) + XCTAssertEqual( + receipt.executionContractID, engine.loopForTesting.nativeShutdownState?.contractID) + XCTAssertGreaterThanOrEqual(receipt.capturedStreamCount, 2) + return receipt + } + + private func pausePlanning(_ engine: EngineV2) { + engine.loopForTesting.onEngineQueueSync { + engine.loopForTesting.suspendStepExecutionAtCountForTesting = + engine.loopForTesting.stepCount + } + } + private func resumePlanning(_ engine: EngineV2) { + engine.loopForTesting.onEngineQueueSync { + engine.loopForTesting.suspendStepExecutionAtCountForTesting = nil + } + } + private func output(_ engine: EngineV2, _ id: UInt64) throws -> CBv2OutputStream { + try engine.loopForTesting.onEngineQueueSync { + try XCTUnwrap(engine.loopForTesting.stream(for: .init(id))) + } + } + private func assertRetired(_ engine: EngineV2, _ output: CBv2OutputStream) { + engine.loopForTesting.onEngineQueueSync { + XCTAssertTrue(output.isEngineOwnershipReleased) + XCTAssertEqual(engine.loopForTesting.nativePendingRetirementCountForTesting, 0) + XCTAssertEqual(engine.loopForTesting.backend.bytesReserved, 0) + XCTAssertEqual(engine.loopForTesting.backend.bytesInUse, 0) + } + } + + func testNormalTerminalAndActualRetirementShareOneGenerationAndTokenPath() async throws { + try lane() + let actual = try await engine() + pausePlanning(actual) + let submission = try actual.submitWithNativeRetirement(request()) + let registered = try output(actual, 1) + XCTAssertFalse(registered.isEngineOwnershipReleased) + resumePlanning(actual) + let result = await cbv2SchedCollect(submission.events) + await submission.retirement.wait() + XCTAssertEqual(result.finishReason, .length) + XCTAssertEqual(result.tokens.count, 12) + XCTAssertEqual(result.usage?.completionTokens, 12) + assertRetired(actual, registered) + let ordinary = try await collect(actual, request(1)) // same now-reusable ID, ordinary API + XCTAssertEqual(result.tokens, ordinary) + _ = try receipt(await actual.shutdownReportingNativeCompletion(), actual) + } + + func testUntrackedRefusesNewAPIWithoutChangingOrdinarySubmission() async throws { + try lane() + let actual = try await engine(tracked: false) + let before = actual.stepCount + XCTAssertThrowsError(try actual.submitWithNativeRetirement(request())) { + XCTAssertTrue($0 is CBv2NativeShutdownError) + } + XCTAssertThrowsError(try actual.submitWithNativeRetirement(request(budget: 0))) + XCTAssertEqual(actual.stepCount, before) + XCTAssertEqual(actual.capacity().waitingRequests, 0) + _ = try await collect(actual, request()) + await actual.shutdown() + } + + func testZeroWorkIsAcknowledgedAndColdRefusalNeverRegisters() async throws { + try lane() + let actual = try await engine() + let before = actual.stepCount + let zero = try actual.submitWithNativeRetirement(request(budget: 0, logprobs: 1)) + let zeroResult = await cbv2SchedCollect(zero.events) + await zero.retirement.wait() + XCTAssertEqual(zeroResult.finishReason, .length) + XCTAssertEqual(zeroResult.usage?.completionTokens, 0) + var emptyRequest = request(2) + emptyRequest.promptTokens = [] + let empty = try actual.submitWithNativeRetirement(emptyRequest) + let emptyResult = await cbv2SchedCollect(empty.events) + await empty.retirement.wait() + XCTAssertEqual(emptyResult.finishReason, .error("empty prompt")) + XCTAssertEqual(actual.stepCount, before) + XCTAssertThrowsError(try actual.submitWithNativeRetirement(request(3, logprobs: 1))) + actual.loopForTesting.onEngineQueueSync { + XCTAssertNil(actual.loopForTesting.stream(for: .init(1))) + XCTAssertNil(actual.loopForTesting.stream(for: .init(2))) + XCTAssertNil(actual.loopForTesting.stream(for: .init(3))) + XCTAssertEqual(actual.loopForTesting.backend.bytesReserved, 0) + } + XCTAssertEqual(actual.capacity().waitingRequests, 0) + _ = try receipt(await actual.shutdownReportingNativeCompletion(), actual) + XCTAssertThrowsError(try actual.submitWithNativeRetirement(request(budget: 0))) + } + + func testDuplicateIDAndOldGenerationCannotRetireOrCancelItsSuccessor() async throws { + try lane() + let actual = try await engine() + pausePlanning(actual) + let first = try actual.submitWithNativeRetirement(request()) + let original = try output(actual, 1) + let oldGeneration = try XCTUnwrap( + actual.loopForTesting.registeredStreamGeneration(for: .init(1))) + XCTAssertThrowsError(try actual.submitWithNativeRetirement(request())) + XCTAssertTrue(try output(actual, 1) === original) + XCTAssertFalse(original.isEngineOwnershipReleased) + resumePlanning(actual) + let firstResult = await cbv2SchedCollect(first.events) + await first.retirement.wait() + XCTAssertEqual(firstResult.finishReason, .length) + pausePlanning(actual) + let second = try actual.submitWithNativeRetirement(request()) + let successor = try output(actual, 1) + XCTAssertFalse(successor === original) + let newGeneration = try XCTUnwrap( + actual.loopForTesting.registeredStreamGeneration(for: .init(1))) + XCTAssertNotEqual(oldGeneration, newGeneration) + await first.retirement.wait() + XCTAssertFalse(successor.isEngineOwnershipReleased) + actual.loopForTesting.requestCancel(.init(1), streamGeneration: oldGeneration) + resumePlanning(actual) + let secondResult = await cbv2SchedCollect(second.events) + await second.retirement.wait() + XCTAssertEqual(secondResult.finishReason, .length) + XCTAssertEqual(secondResult.tokens, firstResult.tokens) + assertRetired(actual, successor) + _ = try receipt(await actual.shutdownReportingNativeCompletion(), actual) + } + + func testExplicitCancellationWaitsForActualInFlightRowRetirement() async throws { + try lane() + let actual = try await engine() + pausePlanning(actual) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + let gate = OneShotGate(expectation(description: "actual submitted group held")) + defer { gate.release() } + actual.loopForTesting.onEngineQueueSync { + tracking.afterSubmissionForTesting = { gate.holdOnce() } + } + let submitted = try actual.submitWithNativeRetirement(request()) + let registered = try output(actual, 1) + resumePlanning(actual) + await fulfillment(of: [gate.entered], timeout: 10) + actual.cancel(.init(1)) + XCTAssertFalse(registered.isEngineOwnershipReleased) + XCTAssertGreaterThan(tracking.debugRetainedRootCount, 0) + gate.release() + let result = await cbv2SchedCollect(submitted.events) + await submitted.retirement.wait() + XCTAssertEqual(result.finishReason, .cancelled) + assertRetired(actual, registered) + _ = try receipt(await actual.shutdownReportingNativeCompletion(), actual) + } + + func testConsumerAbandonmentDoesNotAcknowledgeHeldNativeWork() async throws { + try lane() + let actual = try await engine() + pausePlanning(actual) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + let gate = OneShotGate( + expectation(description: "actual work held before consumer cancellation")) + let consuming = expectation(description: "real AsyncStream consumer started") + defer { gate.release() } + actual.loopForTesting.onEngineQueueSync { + tracking.afterSubmissionForTesting = { gate.holdOnce() } + } + let submitted = try actual.submitWithNativeRetirement(request()) + let registered = try output(actual, 1) + let pump = Task { + consuming.fulfill() + for await _ in submitted.events {} + } + resumePlanning(actual) + await fulfillment(of: [gate.entered, consuming], timeout: 10) + pump.cancel() + await pump.value + XCTAssertFalse(registered.isEngineOwnershipReleased) + gate.release() + await submitted.retirement.wait() + assertRetired(actual, registered) + _ = try receipt(await actual.shutdownReportingNativeCompletion(), actual) + } + + func testCompletedSubmissionErrorRetiresOnlyAfterItsRealGroupAndRows() async throws { + try lane() + let witness = try await exerciseCompletedSubmissionError() + XCTAssertNil(witness(), "healthy cleanup must not leave an engine/hook retention cycle") + } + + // Returning only a weak closure makes the lifetime assertion independent + // of extended locals in this async helper's execution frame. + private func exerciseCompletedSubmissionError() async throws -> (@Sendable () -> EngineV2?) { + let actual = try await engine() + defer { + actual.loopForTesting.onEngineQueueSync { + actual.loopForTesting.nativeSubmittedWorkFailureForTesting = nil + actual.loopForTesting.nativeRetirementBoundaryForTesting = nil + } + } + pausePlanning(actual) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + var registered: CBv2OutputStream? + var sawBoundary = false + actual.loopForTesting.onEngineQueueSync { + actual.loopForTesting.nativeSubmittedWorkFailureForTesting = { [weak actual] in + guard let actual else { throw Failure.missingReceipt } + actual.loopForTesting.nativeSubmittedWorkFailureForTesting = nil + throw Failure.submittedWork // AFTER real asyncEval, never fake successful work + } + actual.loopForTesting.nativeRetirementBoundaryForTesting = { [weak actual] name, _ in + guard let actual else { + return XCTFail("actual engine disappeared during owned work") + } + if name == "beforeFailedRootRetirement" { + sawBoundary = true + XCTAssertFalse(registered?.isEngineOwnershipReleased ?? true) + XCTAssertGreaterThan(actual.loopForTesting.backend.bytesReserved, 0) + XCTAssertGreaterThan(tracking.debugRetainedRootCount, 0) + } + } + } + let submitted = try actual.submitWithNativeRetirement(request()) + registered = try output(actual, 1) + resumePlanning(actual) + let result = await cbv2SchedCollect(submitted.events) + await submitted.retirement.wait() + guard case .error? = result.finishReason else { + XCTFail("missing actual submission error") + throw Failure.missingReceipt + } + XCTAssertTrue(sawBoundary) + assertRetired(actual, try XCTUnwrap(registered)) + XCTAssertNil(tracking.outcome, "proved error cleanup is not an unknown-completion fault") + _ = try await collect(actual, request(2)) // healthy drain, not forced success + _ = try receipt(await actual.shutdownReportingNativeCompletion(), actual) + return { [weak actual] in actual } + } + + func testIncompleteShutdownLeavesActualRetirementUnresolvedAfterLateReturn() async throws { + try lane(fault: "testIncompleteShutdownLeavesActualRetirementUnresolvedAfterLateReturn") + let actual = try await engine(shutdownTimeout: 0) + pausePlanning(actual) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + let gate = OneShotGate(expectation(description: "real work awaiting completion")) + defer { gate.release() } + actual.loopForTesting.onEngineQueueSync { + tracking.afterSubmissionForTesting = { gate.holdOnce() } + } + let submitted = try actual.submitWithNativeRetirement(request()) + let registered = try output(actual, 1) + resumePlanning(actual) + await fulfillment(of: [gate.entered], timeout: 10) + let fault = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let failure) = fault else { + return XCTFail("unknown work acknowledged") + } + XCTAssertEqual(failure.reason, .shutdownTimedOut) + _ = await cbv2SchedCollect(submitted.events) + XCTAssertFalse(registered.isEngineOwnershipReleased) + gate.release() + actual.loopForTesting.onEngineQueueSync { + XCTAssertFalse(registered.isEngineOwnershipReleased) + XCTAssertGreaterThan(actual.loopForTesting.backend.bytesReserved, 0) + XCTAssertGreaterThan(tracking.debugRetainedRootCount, 0) + } + let again = await actual.shutdownReportingNativeCompletion() + XCTAssertEqual(again, fault) + // submitted.retirement.wait() intentionally cannot complete; its actual + // OutputStream flag is the causal witness. Dedicated process exits. + } + + func testMixedPlainMTPTimeoutCannotAcknowledgeOrReleaseThePlainRowEarly() async throws { + try lane(fault: "testMixedPlainMTPTimeoutCannotAcknowledgeOrReleaseThePlainRowEarly") + let actual = try await engine(mtp: true, shutdownTimeout: 0) + XCTAssertNil(actual.mtpInactiveReason) + pausePlanning(actual) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + let gate = OneShotGate( + expectation(description: "plain completion before genuine MTP verify finalization")) + defer { gate.release() } + var plainOutput: CBv2OutputStream? + weak var plainRow: AnyObject? + actual.loopForTesting.onEngineQueueSync { + tracking.afterSubmissionForTesting = { + if plainRow == nil { + plainRow = actual.loopForTesting.kvStates[.init(1)]?.compactMap { $0 }.first + } + } + actual.loopForTesting.nativeRetirementBoundaryForTesting = { name, step in + guard name == "beforeMTPFinalization", step?.mtpRound?.verify != nil, + actual.loopForTesting.nativePendingRetirementCountForTesting > 0 + else { return } + gate.holdOnce { + XCTAssertTrue(step?.sampledRows.contains(.init(1)) ?? false) + XCTAssertFalse(plainOutput?.isEngineOwnershipReleased ?? true) + XCTAssertNotNil(plainRow) + XCTAssertGreaterThan(actual.loopForTesting.backend.bytesReserved, 0) + XCTAssertGreaterThan(tracking.debugRetainedRootCount, 0) + } + } + } + let plainRequest = CBv2Request( + id: .init(1), promptTokens: [1, 2, 4], + sampling: .init(temperature: 0), maxTokens: 3, + stopStrings: ["never-produced-by-null-detokenizer"]) + let mtpRequest = CBv2Request( + id: .init(2), promptTokens: [1, 2, 4], + sampling: .init(temperature: 0), maxTokens: 12) + let plain = try actual.submitWithNativeRetirement(plainRequest) + let speculative = try actual.submitWithNativeRetirement(mtpRequest) + plainOutput = try output(actual, 1) + let mtpOutput = try output(actual, 2) + resumePlanning(actual) + await fulfillment(of: [gate.entered], timeout: 20) + let result = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let fault) = result else { + return XCTFail("mixed unknown work acknowledged") + } + XCTAssertEqual(fault.reason, .shutdownTimedOut) + gate.release() + actual.loopForTesting.onEngineQueueSync { + XCTAssertFalse(plainOutput?.isEngineOwnershipReleased ?? true) + XCTAssertFalse(mtpOutput.isEngineOwnershipReleased) + XCTAssertNotNil(plainRow) + XCTAssertGreaterThan(actual.loopForTesting.backend.bytesReserved, 0) + XCTAssertGreaterThan(actual.loopForTesting.nativePendingRetirementCountForTesting, 0) + XCTAssertGreaterThan(tracking.debugRetainedRootCount, 0) + } + _ = await cbv2SchedCollect(plain.events) + _ = await cbv2SchedCollect(speculative.events) + } + + func testFailedGroupTimeoutRetainsRealRowsAndItsRetirementAcknowledgement() async throws { + try lane(fault: "testFailedGroupTimeoutRetainsRealRowsAndItsRetirementAcknowledgement") + let actual = try await engine(shutdownTimeout: 0) + pausePlanning(actual) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + let gate = OneShotGate( + expectation(description: "failed submitted group before root retirement")) + defer { gate.release() } + weak var row: AnyObject? + var registered: CBv2OutputStream? + actual.loopForTesting.onEngineQueueSync { + actual.loopForTesting.nativeSubmittedWorkFailureForTesting = { + row = actual.loopForTesting.kvStates[.init(1)]?.compactMap { $0 }.first + actual.loopForTesting.nativeSubmittedWorkFailureForTesting = nil + throw Failure.submittedWork + } + actual.loopForTesting.nativeRetirementBoundaryForTesting = { name, _ in + guard name == "beforeFailedRootRetirement" else { return } + gate.holdOnce { + XCTAssertNotNil(row) + XCTAssertFalse(registered?.isEngineOwnershipReleased ?? true) + XCTAssertGreaterThan(actual.loopForTesting.backend.bytesReserved, 0) + XCTAssertGreaterThan(tracking.debugRetainedRootCount, 0) + } + } + } + let submitted = try actual.submitWithNativeRetirement(request()) + registered = try output(actual, 1) + resumePlanning(actual) + await fulfillment(of: [gate.entered], timeout: 10) + let outcome = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let fault) = outcome else { + return XCTFail("failed group acknowledged early") + } + XCTAssertEqual(fault.reason, .shutdownTimedOut) + gate.release() + actual.loopForTesting.onEngineQueueSync { + XCTAssertNotNil(row) + XCTAssertFalse(registered?.isEngineOwnershipReleased ?? true) + XCTAssertGreaterThan(actual.loopForTesting.backend.bytesReserved, 0) + XCTAssertGreaterThan(tracking.debugRetainedRootCount, 0) + } + _ = await cbv2SchedCollect(submitted.events) + } + + func testOneShotRequiredAssistantFenceRefusalCannotBeRehabilitatedByCleanupFence() async throws + { + try lane( + fault: "testOneShotRequiredAssistantFenceRefusalCannotBeRehabilitatedByCleanupFence") + let actual = try await engine(mtp: true) + XCTAssertNil(actual.mtpInactiveReason) + pausePlanning(actual) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + var requiredAttempts = 0 + var cleanupAttempts = 0 + weak var state: MiMoV26MTPState? + actual.loopForTesting.onEngineQueueSync { + tracking.beforeFenceForTesting = { _ in cleanupAttempts += 1 } // allows real fence, if incorrectly retried + actual.loopForTesting.nativeRequiredAssistantFenceForTesting = { value in + requiredAttempts += 1 + state = value as? MiMoV26MTPState + if requiredAttempts == 1 { throw Failure.fence } + } + } + let submitted = try actual.submitWithNativeRetirement(request()) + let registered = try output(actual, 1) + resumePlanning(actual) + let terminal = await cbv2SchedCollect(submitted.events) + guard case .error? = terminal.finishReason else { + return XCTFail("missing failed completion terminal") + } + let outcome = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let fault) = outcome else { + return XCTFail("required fence failure was rehabilitated") + } + XCTAssertEqual(fault.reason, .capturedFenceFailed) + actual.loopForTesting.onEngineQueueSync { + XCTAssertEqual(requiredAttempts, 1) + XCTAssertEqual( + cleanupAttempts, 0, "later successful fences cannot replace original required proof" + ) + XCTAssertNotNil(state) + XCTAssertFalse(state?.isReleased ?? true) + XCTAssertFalse(registered.isEngineOwnershipReleased) + XCTAssertGreaterThan(actual.loopForTesting.backend.bytesReserved, 0) + XCTAssertGreaterThan(tracking.debugRetainedRootCount, 0) + } + let repeated = await actual.shutdownReportingNativeCompletion() + XCTAssertEqual(outcome, repeated) + } + + func testSubmissionCleanupFenceFailureTerminatesConsumerWithoutAcknowledging() async throws { + try lane(fault: "testSubmissionCleanupFenceFailureTerminatesConsumerWithoutAcknowledging") + let actual = try await engine() + pausePlanning(actual) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + actual.loopForTesting.onEngineQueueSync { + actual.loopForTesting.nativeSubmittedWorkFailureForTesting = { + actual.loopForTesting.nativeSubmittedWorkFailureForTesting = nil + throw Failure.submittedWork + } + tracking.beforeFenceForTesting = { _ in throw Failure.fence } + } + let submitted = try actual.submitWithNativeRetirement(request()) + let registered = try output(actual, 1) + resumePlanning(actual) + // No shutdown request yet: sealing a completion fault itself must + // finish the consumer, while keeping its ownership acknowledgement. + let result = await cbv2SchedCollect(submitted.events) + guard case .error? = result.finishReason else { + return XCTFail("sealed cleanup fault stranded the consumer") + } + let outcome = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let fault) = outcome else { + return XCTFail("failed cleanup acknowledged") + } + XCTAssertEqual(fault.reason, .capturedFenceFailed) + actual.loopForTesting.onEngineQueueSync { + XCTAssertFalse(registered.isEngineOwnershipReleased) + XCTAssertGreaterThan(actual.loopForTesting.backend.bytesReserved, 0) + XCTAssertGreaterThan(tracking.debugRetainedRootCount, 0) + } + } + + func testRealTextDetokenizerStopStringPreservesTokenAndSuppressionSemantics() async throws { + try lane() + let actual = try await engine(text: true) + let first = try actual.submitWithNativeRetirement(request(budget: 1)) + let reference = await cbv2SchedCollect(first.events) + await first.retirement.wait() + let token = try XCTUnwrap(reference.tokens.first) + XCTAssertEqual(reference.finishReason, .length) + XCTAssertEqual(reference.text, String(token)) + var stoppedRequest = request(2, budget: 4) + stoppedRequest.stopStrings = [String(token)] + let stopped = try actual.submitWithNativeRetirement(stoppedRequest) + let result = await cbv2SchedCollect(stopped.events) + await stopped.retirement.wait() + XCTAssertEqual(result.finishReason, .stop) + XCTAssertEqual(result.text, "") + XCTAssertEqual(result.tokens, [token]) + XCTAssertEqual(result.usage?.completionTokens, 1) + _ = try receipt(await actual.shutdownReportingNativeCompletion(), actual) + } + + func testHeldRealTextStopStringPushDoesNotBlockFaultArbitration() async throws { + try lane(fault: "testHeldRealTextStopStringPushDoesNotBlockFaultArbitration") + try await heldTextDecoder(targetCall: 1) + } + + func testHeldRealTextStopStringFlushRetainsLoanAndReachableStream() async throws { + try lane(fault: "testHeldRealTextStopStringFlushRetainsLoanAndReachableStream") + try await heldTextDecoder(targetCall: 2) + } + + private func heldTextDecoder(targetCall: Int) async throws { + let gate = OneShotGate( + expectation( + description: targetCall == 1 + ? "real SDK text push held" : "real SDK text flush held")) + let decoder = DecodeGate(gate, targetCall: targetCall) + defer { gate.release() } + let actual = try await engine(text: true, shutdownTimeout: 0, decoderGate: decoder) + pausePlanning(actual) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + var input = request(budget: 1) + input.stopStrings = ["not-a-decimal-token"] + let submitted = try actual.submitWithNativeRetirement(input) + let registered = try output(actual, 1) + resumePlanning(actual) + await fulfillment(of: [gate.entered], timeout: 10) + XCTAssertTrue(tracking.hasLoans, "the actual decoder must remain a counted owner") + XCTAssertFalse(registered.isEngineOwnershipReleased) + // Decoding is host-only, but must not hold the first-winner lock. + let outcome = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let fault) = outcome else { + return XCTFail("held decoder minted completion") + } + XCTAssertEqual(fault.reason, .shutdownTimedOut) + let terminal = await cbv2SchedCollect(submitted.events) + guard case .error? = terminal.finishReason else { + return XCTFail("watchdog lost the pending terminal stream") + } + gate.release() + actual.loopForTesting.onEngineQueueSync { + XCTAssertFalse(registered.isEngineOwnershipReleased) + XCTAssertTrue( + tracking.hasLoans, "late decoder return cannot drop its retained-fault owner") + } + let repeated = await actual.shutdownReportingNativeCompletion() + XCTAssertEqual(outcome, repeated) + } + + func testFaultBeforeDeadlineOperationRegistrationResolvesColdSubmitter() async throws { + try lane(fault: "testFaultBeforeDeadlineOperationRegistrationResolvesColdSubmitter") + let actual = try await engine(shutdownTimeout: 0, serializedPrefill: true) + // Keep legacy _healthy true: no engine step may overwrite it after the + // fault. The new native arbitration, not the old health guard, must win. + pausePlanning(actual) + let gate = OneShotGate( + expectation(description: "real stream before deadline operation registration")) + defer { + gate.release() + actual.loopForTesting.setDeadlineAdmissionBeforeRegistrationHookForTesting(nil) + } + actual.loopForTesting.setDeadlineAdmissionBeforeRegistrationHookForTesting { _ in + gate.holdOnce() + } + let input = request(budget: 1) + let admission = CBv2FirstTokenDeadlineAdmission( + deadline: .now.advanced(by: .seconds(60)), + conservativePrefillTokensPerSecond: 1000, conservativeDecodeTokensPerSecond: 1000) + let completion = SubmissionCompletion() + let completed = expectation(description: "cold refused submission actually returned") + let submission = Task { + defer { + completion.markFinished() + completed.fulfill() + } + return try await actual.submit(input, firstTokenDeadline: admission) + } + await fulfillment(of: [gate.entered], timeout: 10) + let registered = try XCTUnwrap(actual.loopForTesting.stream(for: input.id)) + XCTAssertFalse(registered.isEngineOwnershipReleased) + XCTAssertEqual( + actual.loopForTesting.deadlineAdmissionRegistrationSnapshotForTesting.operationCount, 0) + XCTAssertTrue(actual.loopForTesting.gauges.hasPendingSubmissions) + let outcome = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let fault) = outcome else { + return XCTFail("pending cold registration minted receipt") + } + XCTAssertEqual(fault.reason, .shutdownTimedOut) + XCTAssertTrue( + actual.loopForTesting.deadlineAdmissionRegistrationSnapshotForTesting.legacyHealthy, + "this must discriminate the native outcome from the unchanged legacy health flag") + gate.release() + await fulfillment(of: [completed], timeout: 10) + guard completion.isFinished else { + submission.cancel() + return XCTFail("fault-before-registration stranded the real admission waiter") + } + do { + _ = try await submission.value + XCTFail("cold faulted registration accepted") + } catch { XCTAssertTrue(error is CBv2KVError) } + XCTAssertTrue( + registered.isEngineOwnershipReleased, + "only this never-enqueued generation can retire cold") + XCTAssertNil(actual.loopForTesting.stream(for: input.id)) + XCTAssertNil(actual.loopForTesting.registeredStreamGeneration(for: input.id)) + XCTAssertEqual( + actual.loopForTesting.deadlineAdmissionRegistrationSnapshotForTesting.operationCount, 0) + XCTAssertFalse(actual.loopForTesting.gauges.hasPendingSubmissions) + actual.loopForTesting.onEngineQueueSync { + XCTAssertFalse(actual.loopForTesting.scheduler.hasWork) + XCTAssertEqual(actual.loopForTesting.backend.bytesReserved, 0) + XCTAssertEqual(actual.loopForTesting.nativeShutdownState?.debugRetainedRootCount, 0) + } + let repeated = await actual.shutdownReportingNativeCompletion() + XCTAssertEqual(repeated, outcome, "cold unwind must not rehabilitate the engine fault") + } + + func testHeldInitialDeadlineHookAllowsFaultAndColdRefusalWithoutNativeWork() async throws { + try lane(fault: "testHeldInitialDeadlineHookAllowsFaultAndColdRefusalWithoutNativeWork") + let actual = try await engine(shutdownTimeout: 0, serializedPrefill: true) + let gate = OneShotGate(expectation(description: "real deadline initial guard")) + defer { gate.release() } + actual.loopForTesting.setDeadlineAdmissionInitialGuardHookForTesting { _ in gate.holdOnce() + } + let input = request(budget: 1) + let admission = CBv2FirstTokenDeadlineAdmission( + deadline: .now.advanced(by: .seconds(60)), + conservativePrefillTokensPerSecond: 1000, conservativeDecodeTokensPerSecond: 1000) + let submission = Task { try await actual.submit(input, firstTokenDeadline: admission) } + await fulfillment(of: [gate.entered], timeout: 10) + // Converse ordering: registration won before fault, so its real waiter + // must be visible to the existing external-failure snapshot. + XCTAssertEqual( + actual.loopForTesting.deadlineAdmissionRegistrationSnapshotForTesting.operationCount, 1) + XCTAssertTrue(actual.loopForTesting.gauges.hasPendingSubmissions) + let outcome = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let fault) = outcome else { + return XCTFail("held admission minted receipt") + } + XCTAssertEqual(fault.reason, .shutdownTimedOut) + gate.release() + do { + _ = try await submission.value + XCTFail("uncommitted failed admission accepted") + } catch { XCTAssertTrue(error is CBv2KVError) } + XCTAssertFalse(actual.loopForTesting.gauges.hasPendingSubmissions) + actual.loopForTesting.onEngineQueueSync { + XCTAssertFalse(actual.loopForTesting.scheduler.hasWork) + XCTAssertEqual(actual.loopForTesting.backend.bytesReserved, 0) + XCTAssertEqual(actual.loopForTesting.nativeShutdownState?.debugRetainedRootCount, 0) + } + } + + func testHeldCommittedDeadlineHookTransfersRealRetirementAfterFault() async throws { + try lane(fault: "testHeldCommittedDeadlineHookTransfersRealRetirementAfterFault") + let actual = try await engine(shutdownTimeout: 0, serializedPrefill: true) + let gate = OneShotGate(expectation(description: "real deadline commit held")) + defer { gate.release() } + actual.loopForTesting.setDeadlineAdmissionCommittedHookForTesting { _ in gate.holdOnce() } + let input = request(budget: 1) + let admission = CBv2FirstTokenDeadlineAdmission( + deadline: .now.advanced(by: .seconds(60)), + conservativePrefillTokensPerSecond: 1000, conservativeDecodeTokensPerSecond: 1000) + let submission = Task { try await actual.submit(input, firstTokenDeadline: admission) } + await fulfillment(of: [gate.entered], timeout: 10) + let registered = try XCTUnwrap(actual.loopForTesting.stream(for: input.id)) // locked metadata; queue is held + let outcome = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let fault) = outcome else { + return XCTFail("held committed admission minted receipt") + } + XCTAssertEqual(fault.reason, .shutdownTimedOut) + gate.release() + guard case .admitted(let events, _, _, let retirement) = try await submission.value else { + return XCTFail("post-commit fault was converted to a cold refusal") + } + _ = await cbv2SchedCollect(events) + actual.loopForTesting.onEngineQueueSync { + XCTAssertFalse(registered.isEngineOwnershipReleased) + } + withExtendedLifetime(retirement) {} // never fabricate acknowledgement of this retained generation + } +} diff --git a/Tests/MLXLMTests/CBv2NativeShutdownOutcomeTests.swift b/Tests/MLXLMTests/CBv2NativeShutdownOutcomeTests.swift new file mode 100644 index 0000000000..9684ac79a0 --- /dev/null +++ b/Tests/MLXLMTests/CBv2NativeShutdownOutcomeTests.swift @@ -0,0 +1,461 @@ +import Foundation +import MLX +import MLXLLM +import XCTest + +@_spi(Diagnostics) @testable import MLXLMCommon +@testable import MLXVLM + +/// Source-prepared. These tests load the real bounded BF16 component fixture, +/// run its actual native target/assistant and use the protected resource issuer. +/// The tokenizer controls factory setup only; it is not template parity proof. +final class CBv2NativeShutdownOutcomeTests: XCTestCase { + private enum Failure: Error { case fence, missingReceipt } + private final class Permit: MiMoV26SerialLoadReservation, Sendable { + let request: MiMoV26SerialLoadRequest + let reservedLoadBytes: UInt64 + init(_ request: MiMoV26SerialLoadRequest) { + self.request = request + reservedLoadBytes = request.requiredLoadBytes + } + func validateActive(progress: MiMoV26SerialLoadProgress) throws {} + } + private final class ControlTokenizer: Tokenizer, Sendable { + func encode(text: String, addSpecialTokens: Bool) -> [Int] { [6] } + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + tokenIds.map(String.init).joined() + } + func convertTokenToId(_ token: String) -> Int? { token == "<|im_end|>" ? 3 : nil } + func convertIdToToken(_ id: Int) -> String? { id == 3 ? "<|im_end|>" : nil } + var bosToken: String? { nil } + var eosToken: String? { "<|im_end|>" } + var unknownToken: String? { nil } + func applyChatTemplate( + messages: [Message], tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { + throw TokenizerError.missingChatTemplate + } + func applyChatTemplate(messages: [Message], chatTemplate: String) throws -> [Int] { + try applyChatTemplate( + messages: messages, chatTemplate: chatTemplate, tools: nil, additionalContext: nil) + } + func applyChatTemplate( + messages: [Message], chatTemplate: String, tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { + [1] + ((additionalContext?["enable_thinking"] as? Bool) == false ? [4, 5] : []) + [6] + } + } + private struct Loader: TokenizerLoader { + func load(from directory: URL) async throws -> any Tokenizer { ControlTokenizer() } + } + private final class OneShotGate: @unchecked Sendable { + let entered: XCTestExpectation + private let lock = NSLock() + private var enteredOnce = false + private let released = DispatchSemaphore(value: 0) + init(_ entered: XCTestExpectation) { self.entered = entered } + func holdOnce(_ beforeHold: () -> Void = {}) { + let first = lock.withLock { () -> Bool in + guard !enteredOnce else { return false } + enteredOnce = true + return true + } + guard first else { return } + beforeHold() + entered.fulfill() + released.wait() + } + func release() { released.signal() } + // No destructor waits; a one-shot signal is never consumed twice. + } + + private func lane(fault: String? = nil) throws { + let env = ProcessInfo.processInfo.environment + guard env["MIMO_V26_SERIAL_NATIVE_TESTS"] == "1" else { + throw XCTSkip("Requires an authorized exclusive native test process") + } + guard env["MIMO_V26_SHUTDOWN_FAULT_CASE"] == fault else { + throw XCTSkip( + "Run each retained-fault selector alone with its exact MIMO_V26_SHUTDOWN_FAULT_CASE" + ) + } + } + private func engine( + tracked: Bool = true, mtp: Bool = false, text: Bool = false, + shutdownTimeout: TimeInterval = 10, + stepTimeout: TimeInterval = 60 + ) async throws -> EngineV2 { + let fixtureRoot = URL( + fileURLWithPath: try XCTUnwrap( + ProcessInfo.processInfo.environment["MIMO_V26_SERIAL_LOAD_FIXTURES"])) + let root = fixtureRoot.appendingPathComponent("shutdown-work-" + UUID().uuidString) + try FileManager.default.copyItem( + at: fixtureRoot.appendingPathComponent("tiny-bf16"), to: root) + try Data("{}".utf8).write(to: root.appendingPathComponent("tokenizer.json")) + try JSONSerialization.data(withJSONObject: ["eos_token": "<|im_end|>"]) + .write(to: root.appendingPathComponent("tokenizer_config.json")) + try Data("{{ messages }}{% if enable_thinking is false %}{% endif %}".utf8) + .write(to: root.appendingPathComponent("chat_template.jinja")) + let p = try XCTUnwrap( + JSONSerialization.jsonObject( + with: + Data(contentsOf: fixtureRoot.appendingPathComponent("provenance.json"))) + as? [String: String]) + let provenance = try MiMoV26ConvertedProvenance( + artifactID: XCTUnwrap(p["artifactID"]), + sourceRepository: XCTUnwrap(p["sourceRepository"]), + sourceRevision: XCTUnwrap(p["sourceRevision"]), + conversionManifestSHA256: XCTUnwrap(p["conversionManifestSHA256"])) + let plan = try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance, + limits: .init(maximumShardBytes: 1_048_576, maximumTotalFileBytes: 4_194_304)) + let session = try MiMoV26SerialLoadSession(plan: plan) + let prepared = try await MiMoV26ModelFactory.prepare( + request: session.request, + configuration: .init(directory: root), tokenizerLoader: Loader()) + let work = NativeConstructionWork() + let container = try await MiMoV26ModelFactory.loadContainer( + session: session, + reservation: Permit(session.request), prepared: prepared, retaining: work) + try await work.acknowledgeContainerAdoption(container) + let actual = try await MiMoV26ModelFactory.withNativeConstruction( + container: container, retaining: work + ) { model, scope in + let binding = try model.makeCBv2Binding(enableMTP: mtp) + _ = try binding.adapter.probeNativeKVTypes(retaining: scope) + let resources = try binding.adapter.makeNativeExecutionResources( + bytesCapacity: 32 << 20, retaining: scope) + let detokenizer: any CBv2DetokenizerFactory = + text + ? CBv2TextDetokenizerFactory(tokenizer: ControlTokenizer()) + : CBv2NullDetokenizerFactory() + let engine = EngineV2( + model: binding.adapter, layerKinds: binding.adapter.layerKinds, + backend: resources.backend, cacheProvider: resources.cacheProvider, + detokenizerFactory: detokenizer, + schedulerConfig: .init( + maxConcurrentRequests: 1, maxBatchedTokensPerStep: 16, + prefillChunkSize: 3, maxWaiting: 4, enablePrefixCache: false), + loopConfig: .init( + stepTimeout: stepTimeout, watchdogInterval: 0.01, + shutdownTimeout: shutdownTimeout), + mtpDrafter: binding.assistant, + mtpConfig: .init( + enabled: mtp, maxDraftTokens: 3, maxSpeculativeBatch: 1, + fixedDraftTokens: 3, verificationMode: .serialTarget), + nativeCompletionTracking: tracked, nativeExecutionContract: resources.contract) + try scope.retainOwner(engine) + return engine + } + guard case .completed(let setup) = work.snapshot.disposition else { + throw Failure.missingReceipt + } + try await work.sealForPublication(setup) + return actual + } + private func request(_ id: UInt64 = 1, budget: Int = 12, logprobs: Int = 0) -> CBv2Request { + .init( + id: .init(id), promptTokens: [1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12], + sampling: .init(temperature: 0, topLogprobs: logprobs), maxTokens: budget) + } + private func collect(_ engine: EngineV2, _ request: CBv2Request) async throws -> [Int] { + let result = await cbv2SchedCollect(try engine.submit(request)) + XCTAssertEqual(result.finishReason, .length) + XCTAssertEqual(result.tokens.count, request.maxTokens) + XCTAssertEqual(result.usage?.completionTokens, request.maxTokens) + return result.tokens + } + private func receipt(_ outcome: CBv2NativeShutdownOutcome, _ engine: EngineV2) throws + -> CBv2NativeShutdownReceipt + { + guard case .quiescent(let receipt) = outcome else { + XCTFail("not quiescent: \(outcome)") + throw Failure.missingReceipt + } + XCTAssertEqual(receipt.engineID, engine.nativeShutdownEngineID) + XCTAssertEqual(receipt.generation, 1) + XCTAssertEqual( + receipt.executionContractID, engine.loopForTesting.nativeShutdownState?.contractID) + XCTAssertGreaterThanOrEqual(receipt.capturedStreamCount, 2) + return receipt + } + + func testActualOFFAndONNaturalDrainPreserveTokensAndRetireRoots() async throws { + try lane() + var reference: [Int]? + var engineIDs = Set() + var contractIDs = Set() + for mtp in [false, true] { + let actual = try await engine(mtp: mtp, text: mtp) + if mtp { XCTAssertNil(actual.mtpInactiveReason) } + let tokens = try await collect(actual, request()) + if let reference { XCTAssertEqual(tokens, reference) } else { reference = tokens } + let first = await actual.shutdownReportingNativeCompletion() + let proof = try receipt(first, actual) + XCTAssertTrue(engineIDs.insert(proof.engineID).inserted) + XCTAssertTrue(contractIDs.insert(proof.executionContractID).inserted) + let again = await actual.shutdownReportingNativeCompletion() + XCTAssertEqual(first, again) + await actual.shutdown() // delegates the same result; no second cleanup + XCTAssertEqual(actual.loopForTesting.nativeShutdownState?.debugRetainedRootCount, 0) + actual.loopForTesting.onEngineQueueSync { + XCTAssertEqual(actual.loopForTesting.backend.bytesInUse, 0) + XCTAssertEqual(actual.loopForTesting.backend.bytesReserved, 0) + XCTAssertFalse(actual.loopForTesting.hasInFlightStepForTesting) + XCTAssertFalse(actual.loopForTesting.scheduler.hasWork) + } + XCTAssertThrowsError(try actual.submit(request(2))) + } + } + + func testUntrackedActualEngineKeepsLegacyVoidDrainAndCannotMintReceipt() async throws { + try lane() + let actual = try await engine(tracked: false) + XCTAssertNil(actual.loopForTesting.nativeShutdownState) + _ = try await collect(actual, request()) + let observation = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let fault) = observation else { return XCTFail("untracked success") } + XCTAssertEqual(fault.reason, .notTracked) + _ = try await collect(actual, request(2)) // observation did not shut down legacy engine + await actual.shutdown() + actual.loopForTesting.onEngineQueueSync { + XCTAssertEqual(actual.loopForTesting.backend.bytesInUse, 0) + XCTAssertEqual(actual.loopForTesting.backend.bytesReserved, 0) + } + } + + func testNaturalOutcomeDoesNotLeaveEngineOwnedByTimeoutTimer() async throws { + try lane() + var actual: EngineV2? = try await engine(shutdownTimeout: 60) + weak var engineWitness = actual + weak var loopWitness = actual?.loopForTesting + _ = try await collect(actual!, request()) + _ = try receipt(await actual!.shutdownReportingNativeCompletion(), actual!) + actual!.loopForTesting.onEngineQueueSync {} // join the reporting closure tail + actual = nil + XCTAssertNil(engineWitness) + XCTAssertNil(loopWitness, "pending watchdog must not retain a healthy model for 60 seconds") + } + + func testPendingCancelledShutdownWaiterStillRequiresActualFence() async throws { + try lane() + let actual = try await engine(shutdownTimeout: 60) + _ = try await collect(actual, request()) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + let gate = OneShotGate(expectation(description: "actual shutdown boundary reached")) + defer { gate.release() } + actual.loopForTesting.onEngineQueueSync { + tracking.beforeFenceForTesting = { _ in gate.holdOnce() } + } + let waiter = Task { await actual.shutdownReportingNativeCompletion() } + let concurrent = Task { await actual.shutdownReportingNativeCompletion() } + await fulfillment(of: [gate.entered], timeout: 10) + XCTAssertNil(tracking.outcome) + waiter.cancel() + XCTAssertNil(tracking.outcome, "caller cancellation is not a native completion fault") + gate.release() + let first = await waiter.value + _ = try receipt(first, actual) + let second = await concurrent.value + XCTAssertEqual(first, second) + } + + func testDiagnosticLoansAndUnsupportedConsumersRemainExplicit() async throws { + try lane() + let actual = try await engine() + let top = try actual.teacherForcedTop1(promptTokens: [1, 2, 4], continuation: [5, 6, 7]) + XCTAssertEqual(top.count, 3) + let digest = try actual.prefillLogitDigest([1, 2, 4]) + XCTAssertGreaterThan(digest.count, 0) + XCTAssertThrowsError(try actual.submit(request(logprobs: 1))) + XCTAssertThrowsError(try actual.configureAttentionMetadata(nil)) + XCTAssertThrowsError(try actual.configureAttentionPacket(nil)) + XCTAssertThrowsError(try actual.configureLogitDiagnostic(nil)) + _ = try receipt(await actual.shutdownReportingNativeCompletion(), actual) + XCTAssertEqual(actual.loopForTesting.nativeShutdownState?.debugRetainedRootCount, 0) + } + + func testTimeoutAfterActualSubmissionRetainsRowsAndRefusesLateRetirement() async throws { + try lane(fault: "testTimeoutAfterActualSubmissionRetainsRowsAndRefusesLateRetirement") + let actual = try await engine(shutdownTimeout: 0) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + let gate = OneShotGate(expectation(description: "real asyncEval submitted")) + defer { gate.release() } + weak var row: AnyObject? + actual.loopForTesting.onEngineQueueSync { + tracking.afterSubmissionForTesting = { + gate.holdOnce { + row = + actual.loopForTesting.kvStates.values.flatMap { $0 }.compactMap { $0 }.first + } + } + } + let stream = try actual.submit(request()) + await fulfillment(of: [gate.entered], timeout: 10) + XCTAssertNotNil(row) + let before = tracking.debugRetainedRootCount + XCTAssertGreaterThan(before, 0) + let outcome = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let fault) = outcome else { + return XCTFail("held queue minted success") + } + XCTAssertEqual(fault.reason, .shutdownTimedOut) + let terminal = await cbv2SchedCollect(stream) + guard case .error? = terminal.finishReason else { return XCTFail("missing client error") } + gate.release() + actual.loopForTesting.onEngineQueueSync { + XCTAssertNotNil(row) + XCTAssertGreaterThan(actual.loopForTesting.backend.bytesReserved, 0) + XCTAssertGreaterThanOrEqual(tracking.debugRetainedRootCount, before) + } + actual.updateKVBytesCapacity(0) + XCTAssertGreaterThan(actual.capacity().kvBytesCapacity, 0, "late shrink must be vetoed") + XCTAssertThrowsError(try actual.submit(request(2))) + await actual.shutdown() + let repeated = await actual.shutdownReportingNativeCompletion() + XCTAssertEqual(outcome, repeated) + // Do not reset/release fault roots: this selector runs alone and exits. + } + + func testCapturedFenceFailureAttemptsAllStreamsAndNeverIssuesLateSuccess() async throws { + try lane(fault: "testCapturedFenceFailureAttemptsAllStreamsAndNeverIssuesLateSuccess") + let actual = try await engine() + _ = try await collect(actual, request()) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + var attempted: [MLX.Stream] = [] + actual.loopForTesting.onEngineQueueSync { + tracking.beforeFenceForTesting = { stream in + attempted.append(stream) + if stream == StreamOrDevice.cpu.stream { throw Failure.fence } + } + } + let outcome = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let fault) = outcome else { + return XCTFail("failed fence minted receipt") + } + XCTAssertEqual(fault.reason, .capturedFenceFailed) + actual.loopForTesting.onEngineQueueSync { XCTAssertGreaterThanOrEqual(attempted.count, 2) } + let again = await actual.shutdownReportingNativeCompletion() + XCTAssertEqual(outcome, again) + XCTAssertThrowsError(try actual.submit(request(2))) + } + + func testStepWatchdogFirstWinnerRemainsIncompleteWithoutShutdownTimeout() async throws { + try lane(fault: "testStepWatchdogFirstWinnerRemainsIncompleteWithoutShutdownTimeout") + let actual = try await engine(shutdownTimeout: 60, stepTimeout: 1) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + let gate = OneShotGate( + expectation(description: "submitted work held for real step watchdog")) + let wedged = expectation(description: "watchdog reported actual held step") + defer { gate.release() } + actual.loopForTesting.onEngineQueueSync { + tracking.afterSubmissionForTesting = { gate.holdOnce() } + actual.loopForTesting.onStepWedge = { _ in wedged.fulfill() } + } + let stream = try actual.submit(request()) + await fulfillment(of: [gate.entered, wedged], timeout: 20) + guard case .incomplete(let fault)? = tracking.outcome else { + return XCTFail("watchdog did not seal fault") + } + XCTAssertEqual(fault.reason, .stepWatchdog) + let first = await actual.shutdownReportingNativeCompletion() + gate.release() + actual.loopForTesting.onEngineQueueSync { + XCTAssertGreaterThan(tracking.debugRetainedRootCount, 0) + XCTAssertGreaterThan(actual.loopForTesting.backend.bytesReserved, 0) + } + _ = await cbv2SchedCollect(stream) + let again = await actual.shutdownReportingNativeCompletion() + XCTAssertEqual(first, again) + } + + func testMTPFenceLateReturnCannotReplaceMeasuredOwnersAfterTimeout() async throws { + try lane(fault: "testMTPFenceLateReturnCannotReplaceMeasuredOwnersAfterTimeout") + let actual = try await engine(mtp: true, shutdownTimeout: 0) + XCTAssertNil(actual.mtpInactiveReason) + let tracking = try XCTUnwrap(actual.loopForTesting.nativeShutdownState) + let gate = OneShotGate( + expectation(description: "actual assistant fence completed before commit")) + defer { gate.release() } + weak var state: MiMoV26MTPState? + var measuredBytes = -1 + var measuredRoots = -1 + actual.loopForTesting.onEngineQueueSync { + tracking.afterAssistantFenceForTesting = { value in + gate.holdOnce { + state = value as? MiMoV26MTPState + measuredBytes = state?.materializedBytes ?? -1 + measuredRoots = state?.measuredRootCount ?? -1 + } + } + } + let stream = try actual.submit(request()) + await fulfillment(of: [gate.entered], timeout: 10) + XCTAssertNotNil(state) + let outcome = await actual.shutdownReportingNativeCompletion() + guard case .incomplete(let fault) = outcome else { + return XCTFail("held assistant minted receipt") + } + XCTAssertEqual(fault.reason, .shutdownTimedOut) + gate.release() + actual.loopForTesting.onEngineQueueSync { + XCTAssertNotNil(state) + XCTAssertFalse(state?.isReleased ?? true) + XCTAssertEqual(state?.materializedBytes, measuredBytes) + XCTAssertEqual(state?.measuredRootCount, measuredRoots) + XCTAssertGreaterThan(tracking.debugRetainedRootCount, 0) + XCTAssertGreaterThan(actual.loopForTesting.backend.bytesReserved, 0) + } + _ = await cbv2SchedCollect(stream) + let again = await actual.shutdownReportingNativeCompletion() + XCTAssertEqual(outcome, again) + } + + func testExecutionTicketRefusesWrongExpiredAndAlreadyConsumedIdentity() throws { + let model = NSObject() + let backend = NSObject() + let bank = NSObject() + let assistant = NSObject() + let scope = NativeConstructionScope() + XCTAssertThrowsError( + try CBv2NativeExecutionContract( + model: model, backend: backend, + cacheProvider: bank, assistant: assistant, construction: scope) + ) { + XCTAssertEqual($0 as? NativeConstructionError, .inactiveScope) + } + let contract = try scope.withPhase(.nativeSetup) { + try CBv2NativeExecutionContract( + model: model, backend: backend, + cacheProvider: bank, assistant: assistant, construction: scope) + } + XCTAssertEqual(contract.constructionOwnerID, scope.snapshot.ownerID) + XCTAssertEqual(contract.constructionEpoch, scope.snapshot.epoch) + XCTAssertFalse( + contract.consume( + model: model, backend: NSObject(), cacheProvider: bank, assistant: assistant)) + XCTAssertFalse( + contract.consume(model: model, backend: backend, cacheProvider: bank, assistant: nil)) + XCTAssertTrue( + contract.consume( + model: model, backend: backend, cacheProvider: bank, assistant: assistant)) + XCTAssertFalse( + contract.consume( + model: model, backend: backend, cacheProvider: bank, assistant: assistant)) + var temporary: NSObject? = NSObject() + let otherScope = NativeConstructionScope() + let expired = try otherScope.withPhase(.nativeSetup) { + try CBv2NativeExecutionContract( + model: temporary!, backend: backend, + cacheProvider: bank, assistant: nil, construction: otherScope) + } + XCTAssertNotEqual(expired.constructionOwnerID, contract.constructionOwnerID) + temporary = nil + XCTAssertFalse( + expired.consume( + model: NSObject(), backend: backend, cacheProvider: bank, assistant: nil)) + // This metadata-only test does not mint any successful engine receipt. + } +} diff --git a/Tests/MLXLMTests/CBv2PagedAttentionWorkReservationTests.swift b/Tests/MLXLMTests/CBv2PagedAttentionWorkReservationTests.swift new file mode 100644 index 0000000000..8f0525f26d --- /dev/null +++ b/Tests/MLXLMTests/CBv2PagedAttentionWorkReservationTests.swift @@ -0,0 +1,705 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLMCommon + +// Prepared only. Run serially under the exclusive synthetic native lane. +// These tests use real PagedKVBackend/Admission/Metal work, not model payloads. +// The synchronized process delegate records native contract calls; provider +// ProcessMemoryLedger integration requires a separate provider-level test. +private final class PagedWorkProcessOwner: CBv2ProcessMemoryOwner, @unchecked Sendable { + private let lock = NSLock() + private var c: UInt64 = 0, m: UInt64 = 0 + private var cap: UInt64 = 2 << 30 + var snapshot: (charge: UInt64, materialized: UInt64) { lock.withLock { (c, m) } } + func limit(_ value: UInt64) { lock.withLock { cap = value } } + func replaceCharge(_ bytes: UInt64) throws { + try lock.withLock { + guard bytes <= cap, bytes >= m else { + throw MLXError.caught("test process capacity refusal") + } + c = bytes + } + } + func recordMaterialization(_ bytes: UInt64) throws { + try lock.withLock { + guard bytes >= m, bytes <= c else { + throw MLXError.caught("test invalid materialization") + } + m = bytes + } + } + func withdrawCoverage(_ bytes: UInt64) throws { + try lock.withLock { + guard bytes <= m else { throw MLXError.caught("test duplicate coverage withdrawal") } + m -= bytes + } + } + func retire() {} // no artificial refund; real leases must remove their C/M +} + +private func workKind( + _ dk: Int = 192, _ dv: Int = 128, window: Int? = nil, + heads: Int = 1, gqa: Int = 2, shares: Int? = nil, sinks: Bool = false +) -> CBv2LayerKind { + .init( + attention: window.map { .slidingWindow($0) } ?? .full, + sharesKVWithLayer: shares, hasSinks: sinks, headDim: dk, valueHeadDim: dv, + kvHeads: heads, queryHeads: heads * gqa) +} + +private final class PagedWorkFixture { + let kinds: [CBv2LayerKind] + let backend: PagedKVBackend + let caches: [PagedLayerCache] + let bank: CBv2LayerCacheBank + let process: PagedWorkProcessOwner + let admission: AdmissionV2 + var states: [CBv2RequestID: [CBv2SequenceKV?]] = [:] + private var boundaries: [UInt64: CBv2PagedWriteBoundary] = [:] + init( + _ kinds: [CBv2LayerKind], dtype: DType = .float32, batch: Int = 2, + softcap: Float? = nil, bindAdmission: Bool = true + ) throws { + let process = PagedWorkProcessOwner() + let limits = try CBv2PagedGatheredAttentionLimits( + maximumBatchSize: batch, maximumQueryTokens: 129, maximumContextTokens: 1_048_576, + maximumInFlightGraphs: 2, maximumScratchBytes: 1 << 30, + admissionMode: .stepOwned(.pinnedMetal)) + let backend = try PagedKVBackend( + layerKinds: kinds, + config: .init( + capacityBytes: 1 << 30, dtype: dtype, maxPrefillChunk: 129, + nominalMaxSequenceLength: 1_048_576, maxBufferLength: 8 << 20, + segmentSizeBytes: 128 << 10, + layerDTypes: Array(repeating: dtype, count: kinds.count), + gatheredAttention: limits)) + let caches = backend.makeLayerCaches(attentionSoftcap: softcap) + let bank = CBv2LayerCacheBank(caches: caches) + let admission = AdmissionV2( + layerKinds: kinds, bytesCapacity: 1 << 30, + config: .init( + watermarkFraction: 0, elementBytes: dtype.size, + layerElementBytes: Array(repeating: dtype.size, count: kinds.count)), + residency: backend.kvResidency, processMemoryOwner: process) + self.kinds = kinds + self.backend = backend + self.caches = caches + self.bank = bank + self.admission = admission + self.process = process + if bindAdmission { backend.pool.bindAdmission(admission) } + // Component tests prepare the same mandatory owner; actual EngineV2 + // tests below exercise the production envelope binding instead. + backend.pool.attentionWorkEnginePrepared = bindAdmission + } + func add(_ id: CBv2RequestID = .init(1), maximum: Int = 512) throws { + states[id] = try backend.makeSequenceState( + layerKinds: kinds, promptLength: 0, maxLength: maximum) + } + func prepare(_ ids: [CBv2RequestID] = [.init(1)], count: Int) throws + -> CBv2PagedAttentionStepOwner + { + let ranges = ids.map { id -> (id: CBv2RequestID, range: Range) in + let start = states[id]!.compactMap { $0 }.first!.absoluteOffset + return (id, start ..< (start + count)) + } + let boundary = CBv2PagedWriteBoundary(pool: backend.pool) + let owner = try XCTUnwrap(backend.prepareAttentionWork(assignments: ranges, states: states)) + boundaries[owner.generation] = boundary + return owner + } + func forward(_ ids: [CBv2RequestID] = [.init(1)], count: Int) throws -> [MLXArray] { + var outputs: [MLXArray] = [] + for (index, cache) in caches.enumerated() { + let kind = kinds[index] + let dtype = backend.pool.layerDTypes[index] + let query = MLXArray.zeros( + [ids.count, kind.queryHeads, count, kind.headDim], dtype: dtype) + if let source = kind.sharesKVWithLayer { + outputs.append( + cache.attendBorrowing( + source: caches[source], queries: query, scale: 0.125, sinks: nil)) + } else { + cache.setRows(ids.map { states[$0]![index]! }) + let keys = MLXArray.zeros( + [ids.count, kind.kvHeads, count, kind.headDim], dtype: dtype) + let values = + MLXArray.ones( + [ids.count, kind.kvHeads, count, kind.valueHeadDim], dtype: dtype) + * Float(index + 3) + outputs.append( + cache.updateAndAttend( + queries: query, keys: keys, values: values, scale: 0.125, sinks: nil)) + } + } + try backend.pool.writeValidation.check() + return outputs + } + func publish(_ owner: CBv2PagedAttentionStepOwner, outputs: [MLXArray]) throws { + try owner.seal() + try withError { fault in + asyncEval(outputs + owner.evaluationTargets) + try fault.check() + } + owner.publish() + boundaries.removeValue(forKey: owner.generation) + backend.pool.endAttentionConstruction(owner) + } + func retire() { + StreamOrDevice.default.stream.synchronize() + for owner in backend.pool.attentionWorkOwners.values where !owner.published { + boundaries[owner.generation]?.discardFailedGraphAfterSynchronization() + } + boundaries.removeAll() + caches.forEach { $0.setRows([]) } + backend.pool.activeAttentionLayer = nil + backend.pool.activeAttentionWork = nil + backend.pool.discardUnpublishedAttentionWorkAfterDrain() + for owner in Array(backend.pool.attentionWorkOwners.values) where owner.completed { + owner.closeGraph() + } + for rows in states.values { backend.release(rows) } + states.removeAll() + } + deinit { retire() } +} + +private final class PagedWorkEngineModel: CBv2SteppableModel { + func forward(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> MLXArray { + let b = tokens.dim(0) + let n = tokens.dim(1) + var hidden = tokens.asType(.float32).reshaped([b, 1, n, 1]) / Float(32) + for cache in caches { + let q = MLXArray.zeros([b, cache.kind.queryHeads, n, cache.kind.headDim]) + let output: MLXArray + if let owner = cache.kind.sharesKVWithLayer { + output = cache.attendBorrowing( + source: caches[owner], queries: q, scale: 0.125, sinks: nil) + } else { + output = cache.updateAndAttend( + queries: q, + keys: broadcast(hidden, to: [b, cache.kind.kvHeads, n, cache.kind.headDim]), + values: broadcast( + hidden, to: [b, cache.kind.kvHeads, n, cache.kind.valueHeadDim]), + scale: 0.125, sinks: nil) + } + hidden = mean(output, axes: [1, 3], keepDims: true) + } + let target = MLX.round(hidden.reshaped([b, n, 1]) * Float(128)).asType(.int32) % 31 + return MLX.where(MLXArray(Int32(0) ..< Int32(32)) .== target, Float(10), Float(-10)) + } +} + +final class CBv2PagedAttentionWorkReservationTests: XCTestCase { + func testLegacyPolicyDefaultAndUniformBackendStayUnchanged() throws { + let limits = try CBv2PagedGatheredAttentionLimits( + maximumBatchSize: 1, maximumQueryTokens: 16, + maximumContextTokens: 128, maximumInFlightGraphs: 2, maximumScratchBytes: 512 << 20) + XCTAssertEqual(limits.admissionMode, .poolLifetime) + XCTAssertGreaterThan( + try limits.scratchUpperBound(layerKinds: [workKind()], pageSize: 16), 0) + let backend = try PagedKVBackend( + layerKinds: [workKind(64, 64)], + config: .init(capacityBytes: 4 << 20, maxPrefillChunk: 16, segmentSizeBytes: 32 << 10)) + XCTAssertFalse(backend.pool.usesStepOwnedAttention) + XCTAssertEqual(backend.pool.gatheredAttentionScratchBound, 0) + XCTAssertNil(try backend.prepareAttentionWork(assignments: [], states: [:])) + } + + func testShortActualRangeKeepsNativeMillionTokenMetadata() throws { + let f = try PagedWorkFixture([workKind(window: 128), workKind()]) + try f.add() + let baseline = f.admission.bytesReserved + let m = f.process.snapshot.materialized + let work = try f.prepare(count: 16) + XCTAssertEqual(f.backend.pool.config.nominalMaxSequenceLength, 1_048_576) + XCTAssertEqual(f.backend.pool.config.gatheredAttention?.maximumContextTokens, 1_048_576) + XCTAssertEqual(f.backend.pool.gatheredAttentionScratchBound, 0) + XCTAssertTrue( + work.descriptors.values.allSatisfy { $0.range == 0 ..< 16 && $0.keyCount == 16 }) + XCTAssertLessThan(work.reservedBytes, 32 << 20) + XCTAssertEqual(f.admission.bytesReserved - baseline, work.reservedBytes) + XCTAssertEqual(f.process.snapshot.charge, UInt64(f.admission.bytesReserved)) + XCTAssertEqual(f.process.snapshot.materialized, m, "future work grants no M") + f.backend.pool.endAttentionConstruction(work) + try work.discardAfterDrain() + XCTAssertEqual(f.admission.bytesReserved, baseline) + } + + func testProjectionSeparatesViewsCopiesSoftcapAndIndependentPadding() throws { + let policy = try XCTUnwrap(Memory.allocationFootprintPolicy()) + for (dk, dv) in [(192, 128), (128, 192)] { + for gqa in [1, 8, 16] { + for count in [1, 2, 4, 8, 9, 128, 129] { + for blockSize in [0, 128] { + for softcap in [false, true] { + let kind = workKind(dk, dv, heads: 1, gqa: gqa, sinks: true) + let history = 33 + let total = history + count + var blocks: [CBv2PagedAttentionBlock] = [] + var offset = 0 + while offset < count { + let n = min(blockSize == 0 ? count : blockSize, count - offset) + let range = CBv2AttentionV1.queryBlockBounds( + historyCount: history, offset: offset, count: n, window: nil) + blocks.append( + .init( + queryOffset: offset, queryCount: n, + visibleStart: range.visibleStart, + visibleEnd: range.visibleEnd)) + offset += n + } + let d = CBv2PagedAttentionRowDescriptor( + requestID: .init(1), row: .init(nil), rowSerial: 1, + layerIndex: 0, ownerLayerIndex: 0, + range: history ..< (history + count), + baseOffset: 0, frozenHighWater: 0, gatheredRange: 0 ..< history, + keyStart: 0, keyCount: total, blocks: blocks, softcap: softcap) + for dtype: DType in [.float16, .bfloat16, .float32] { + let allocations = try CBv2PagedAttentionWorkProjection.allocations( + kind: kind, dtype: dtype, descriptor: d, pageSize: 16, + policy: policy) + XCTAssertTrue( + allocations.allSatisfy { + $0.upperBoundBytes >= $0.logicalBytes + && $0.allocationCount > 0 + }) + XCTAssertEqual( + allocations.contains { $0.role.contains("repeatKeys") }, + softcap && gqa > 1) + XCTAssertTrue(allocations.contains { $0.role.contains("qk.copyK") }) + XCTAssertEqual( + allocations.first { $0.role == "gather.keys" }?.logicalBytes, + history * dk * dtype.size) + XCTAssertTrue(allocations.contains { $0.role == "gather.records" }) + XCTAssertTrue( + allocations.contains { $0.role == "output.blockConcat" } + == (blocks.count > 1)) + } + } + } + } + } + } + } + + func testCheckedOverflowAndUnsupportedWorkspaceProfileRefuse() throws { + XCTAssertThrowsError(try CBv2PagedWorkMath.add(Int.max, 1)) + XCTAssertThrowsError(try CBv2PagedWorkMath.product([Int.max, 2])) + XCTAssertThrowsError( + try CBv2PagedAttentionWorkEnvironment(queryBlockSize: 128, sdpaBlocks: "4097") + .requireSupported()) + XCTAssertThrowsError( + try CBv2PagedAttentionWorkEnvironment(queryBlockSize: 128, sdpaBlocks: "0") + .requireSupported()) + try CBv2PagedAttentionWorkEnvironment(queryBlockSize: 0, sdpaBlocks: nil).requireSupported() + } + + func testLocalAndProcessTightCapsRefuseBeforeAnyCursorPageOrFenceMutation() throws { + for processCap in [false, true] { + let f = try PagedWorkFixture([workKind(window: 17)]) + try f.add() + let work = try f.prepare(count: 16) + let needed = work.reservedBytes + f.backend.pool.endAttentionConstruction(work) + try work.discardAfterDrain() + let row = try XCTUnwrap(f.states[.init(1)]![0] as? PagedSequenceKV) + let before = f.admission.bytesReserved + let charge = f.process.snapshot.charge + let group = f.backend.pool.group(row.groupKey) + let fence = group.writeFence + let table = row.table + let version = row.tableVersion + if processCap { + f.process.limit(charge + UInt64(needed) - 1) + } else { + f.admission.updateBytesCapacity(before + needed - 1) + } + XCTAssertThrowsError(try f.prepare(count: 16)) + XCTAssertEqual(row.absoluteOffset, 0) + XCTAssertEqual(row.table, table) + XCTAssertEqual(row.tableVersion, version) + XCTAssertTrue(group.writeFence === fence) + XCTAssertEqual(f.admission.bytesReserved, before) + XCTAssertEqual(f.process.snapshot.charge, charge) + if processCap { + f.process.limit(charge + UInt64(needed)) + } else { + f.admission.updateBytesCapacity(before + needed) + } + let accepted = try f.prepare(count: 16) + XCTAssertEqual(accepted.reservedBytes, needed) + f.backend.pool.endAttentionConstruction(accepted) + try accepted.discardAfterDrain() + } + } + + func testMissingAndRepeatedCacheTicketsRefuseBeforeWrites() throws { + for repeated in [false, true] { + let f = try PagedWorkFixture([workKind()]) + try f.add() + let row = try XCTUnwrap(f.states[.init(1)]![0] as? PagedSequenceKV) + f.caches[0].setRows([row]) + if repeated { + _ = try f.prepare(count: 16) + _ = try f.forward(count: 16) + } + let offset = row.absoluteOffset + let table = row.table + let version = row.tableVersion + let group = f.backend.pool.group(row.groupKey) + let fence = group.writeFence + let q = MLXArray.zeros([1, 2, 16, 192]) + let k = MLXArray.zeros([1, 1, 16, 192]) + let v = MLXArray.zeros([1, 1, 16, 128]) + _ = f.caches[0].updateAndAttend( + queries: q, keys: k, values: v, scale: 0.125, sinks: nil) + XCTAssertThrowsError(try f.backend.pool.writeValidation.check()) + XCTAssertEqual(row.absoluteOffset, offset) + XCTAssertEqual(row.table, table) + XCTAssertEqual(row.tableVersion, version) + XCTAssertTrue(group.writeFence === fence) + // Never evaluate the refused output. + } + } + + func testDirectRowMutationCannotAdvanceCursorWithoutTicket() throws { + let f = try PagedWorkFixture([workKind()]) + try f.add() + let row = try XCTUnwrap(f.states[.init(1)]![0] as? PagedSequenceKV) + let k = MLXArray.zeros([1, 1, 1, 192]) + let v = MLXArray.zeros([1, 1, 1, 128]) + _ = row.update(keys: k, values: v) + XCTAssertThrowsError(try f.backend.pool.writeValidation.check()) + XCTAssertEqual(row.absoluteOffset, 0) + XCTAssertTrue(row.table.isEmpty) + f.backend.pool.writeValidation.clearAfterRetirement() + row.write(keys: k.squeezed(axis: 0), values: v.squeezed(axis: 0)) + XCTAssertThrowsError(try f.backend.pool.writeValidation.check()) + XCTAssertEqual(row.absoluteOffset, 0) + XCTAssertTrue(row.table.isEmpty) + } + + func testCoexistingGenerationsHaveIndependentChargesUntilBothComplete() throws { + let f = try PagedWorkFixture([workKind()]) + try f.add() + let baseline = f.admission.bytesReserved + let first = try f.prepare(count: 16) + let out1 = try f.forward(count: 16) + try f.publish(first, outputs: out1) + let second = try f.prepare(count: 1) + XCTAssertNotEqual(first.generation, second.generation) + XCTAssertEqual( + f.admission.bytesReserved, baseline + first.reservedBytes + second.reservedBytes) + let out2 = try f.forward(count: 1) + try f.publish(second, outputs: out2) + XCTAssertThrowsError( + try f.prepare(count: 1), + "a third unfinished native generation exceeds the sealed envelope") + XCTAssertEqual( + f.admission.bytesReserved, baseline + first.reservedBytes + second.reservedBytes) + try first.finishEvaluation() + first.closeGraph() + XCTAssertEqual(f.admission.bytesReserved, baseline + second.reservedBytes) + try second.finishEvaluation() + second.closeGraph() + XCTAssertEqual(f.admission.bytesReserved, baseline) + first.closeGraph() + second.closeGraph() + XCTAssertEqual(f.admission.bytesReserved, baseline, "idempotent retirement") + } + + func testBorrowedPrefillLoanSurvivesCompletionUntilCacheUnbind() throws { + let f = try PagedWorkFixture([workKind(window: 17), workKind(window: 17, shares: 0)]) + try f.add() + let baseline = f.admission.bytesReserved + let m = f.process.snapshot.materialized + let work = try f.prepare(count: 16) + let outputs = try f.forward(count: 16) + try f.publish(work, outputs: outputs) + try work.finishEvaluation() + work.closeGraph() + XCTAssertTrue(work.completed) + XCTAssertFalse(work.released) + XCTAssertEqual(outputs[0].asArray(Float.self), outputs[1].asArray(Float.self)) + XCTAssertEqual(f.admission.bytesReserved, baseline + work.reservedBytes) + XCTAssertEqual(f.process.snapshot.materialized, m) + f.caches[0].setRows([]) + XCTAssertTrue(work.released) + XCTAssertEqual(f.admission.bytesReserved, baseline) + } + + func testRequestIDReuseCannotSpendThePriorRowsTicket() throws { + let f = try PagedWorkFixture([workKind()]) + try f.add() + let oldRows = f.states[.init(1)]! + let old = try XCTUnwrap(oldRows[0] as? PagedSequenceKV) + let work = try f.prepare(count: 16) + f.backend.release(oldRows) + try f.add() + let replacement = try XCTUnwrap(f.states[.init(1)]![0] as? PagedSequenceKV) + XCTAssertNotEqual(old.serial, replacement.serial) + f.caches[0].setRows([replacement]) + _ = f.caches[0].updateAndAttend( + queries: MLXArray.zeros([1, 2, 16, 192]), + keys: MLXArray.zeros([1, 1, 16, 192]), values: MLXArray.zeros([1, 1, 16, 128]), + scale: 0.125, sinks: nil) + XCTAssertThrowsError(try f.backend.pool.writeValidation.check()) + XCTAssertEqual(replacement.absoluteOffset, 0) + XCTAssertTrue(replacement.table.isEmpty) + f.backend.pool.endAttentionConstruction(work) + } + + func testSameGeometryWrongBorrowerOwnerRefusesBeforeReadingOrChangingFence() throws { + for count in [1, 16] { + let f = try PagedWorkFixture([workKind(), workKind(), workKind(shares: 0)]) + try f.add() + let original = f.states[.init(1)]! + let charge = f.process.snapshot.charge + f.states[.init(1)] = [original[1], original[0], nil] + XCTAssertThrowsError(try f.prepare(count: count)) { error in + guard let failure = error as? CBv2KVError, + case .backendIneligible(let reason) = failure + else { + return XCTFail("expected sealed row-owner refusal, got \(error)") + } + XCTAssertTrue(reason.contains("row/cache identity")) + } + XCTAssertEqual(f.process.snapshot.charge, charge) + XCTAssertTrue(original.compactMap { $0 }.allSatisfy { $0.absoluteOffset == 0 }) + f.states[.init(1)] = original + let work = try f.prepare(count: count) + let q = MLXArray.zeros([1, 2, count, 192]) + let k = MLXArray.zeros([1, 1, count, 192]) + for index in 0 ..< 2 { + f.caches[index].setRows([f.states[.init(1)]![index]!]) + _ = f.caches[index].updateAndAttend( + queries: q, keys: k, + values: MLXArray.ones([1, 1, count, 128]) * Float(index == 0 ? 3 : 9), + scale: 0.125, sinks: nil) + } + let row = try XCTUnwrap(f.states[.init(1)]![0] as? PagedSequenceKV) + let group = f.backend.pool.group(row.groupKey) + let fence = group.writeFence + let cursor = row.absoluteOffset + let table = row.table + _ = f.caches[2].attendBorrowing( + source: f.caches[1], queries: q, scale: 0.125, sinks: nil) + XCTAssertThrowsError(try f.backend.pool.writeValidation.check()) + XCTAssertEqual(row.absoluteOffset, cursor) + XCTAssertEqual(row.table, table) + XCTAssertTrue(group.writeFence === fence) + XCTAssertThrowsError(try work.seal()) + f.backend.pool.endAttentionConstruction(work) + } + } + + func testPackedRowsWithDifferentActualRangesStayIndependent() throws { + let f = try PagedWorkFixture([workKind(window: 17)]) + try f.add() + let seed = try f.prepare(count: 16) + let seeded = try f.forward(count: 16) + try f.publish(seed, outputs: seeded) + try seed.finishEvaluation() + seed.closeGraph() + try f.add(.init(2)) + let work = try f.prepare([.init(1), .init(2)], count: 16) + XCTAssertEqual(Set(work.descriptors.values.map(\.range)), Set([16 ..< 32, 0 ..< 16])) + f.caches[0].setRows([f.states[.init(1)]![0]!, f.states[.init(2)]![0]!]) + let output = f.caches[0].updateAndAttend( + queries: MLXArray.zeros([2, 2, 16, 192]), + keys: MLXArray.zeros([2, 1, 16, 192]), + values: broadcast( + MLXArray([Float(3), Float(9)]).reshaped([2, 1, 1, 1]), to: [2, 1, 16, 128]), + scale: 0.125, sinks: nil) + try f.backend.pool.writeValidation.check() + try f.publish(work, outputs: [output]) + try work.finishEvaluation() + for value in output[0].asArray(Float.self) { XCTAssertEqual(value, 3, accuracy: 0.0001) } + for value in output[1].asArray(Float.self) { XCTAssertEqual(value, 9, accuracy: 0.0001) } + XCTAssertEqual(f.states[.init(1)]![0]!.absoluteOffset, 32) + XCTAssertEqual(f.states[.init(2)]![0]!.absoluteOffset, 16) + work.closeGraph() + } + + func testDisablingCacheLoanDoesNotRetireUncompletedBorrowerGraph() throws { + let f = try PagedWorkFixture([workKind(window: 17), workKind(window: 17, shares: 0)]) + try f.add() + let baseline = f.admission.bytesReserved + let work = try f.prepare(count: 16) + let outputs = try f.forward(count: 16) + try f.publish(work, outputs: outputs) + f.caches[0].setRetainsChunkForBorrowers(false) + work.closeGraph() + XCTAssertFalse(work.released) + XCTAssertEqual(f.admission.bytesReserved, baseline + work.reservedBytes) + try work.finishEvaluation() + XCTAssertEqual(outputs[0].asArray(Float.self), outputs[1].asArray(Float.self)) + XCTAssertTrue(work.released) + XCTAssertEqual(f.admission.bytesReserved, baseline) + } + + func testFailedCompletionKeepsRootsChargeAndNoMaterializationCredit() throws { + let f = try PagedWorkFixture([workKind()]) + try f.add() + let baseline = f.admission.bytesReserved + let m = f.process.snapshot.materialized + let work = try f.prepare(count: 16) + let outputs = try f.forward(count: 16) + try f.publish(work, outputs: outputs) + work.beforeCompletionDrainForTesting = { + throw MLXError.caught("injected completion refusal") + } + XCTAssertThrowsError(try work.finishEvaluation()) + work.closeGraph() + XCTAssertFalse(work.completed) + XCTAssertFalse(work.released) + XCTAssertFalse(work.evaluationTargets.isEmpty) + XCTAssertEqual(f.admission.bytesReserved, baseline + work.reservedBytes) + XCTAssertEqual(f.process.snapshot.materialized, m) + work.beforeCompletionDrainForTesting = nil + // A later successful stream wait cannot rehabilitate the failed + // required completion. Root ownership/credit remain quarantined. + XCTAssertThrowsError(try work.finishEvaluation()) + XCTAssertThrowsError(try work.discardAfterDrain()) + XCTAssertTrue(work.completionFailed) + XCTAssertFalse(work.released) + XCTAssertFalse(work.evaluationTargets.isEmpty) + XCTAssertEqual(f.admission.bytesReserved, baseline + work.reservedBytes) + } + + func testNativeBothWidthOrdersAndBF16FP32KeepScalarAttentionOracle() throws { + for (dk, dv) in [(192, 128), (128, 192)] { + for dtype: DType in [.bfloat16, .float32] { + for softcap: Float? in [nil, 20] { + let f = try PagedWorkFixture( + [workKind(dk, dv, window: 17, sinks: softcap != nil)], dtype: dtype, + softcap: softcap) + try f.add() + for count in [16, 1, 16, 1] { + let start = f.states[.init(1)]![0]!.absoluteOffset + let work = try f.prepare(count: count) + let outputs: [MLXArray] + if softcap != nil { + f.caches[0].setRows([f.states[.init(1)]![0]!]) + outputs = [ + f.caches[0].updateAndAttend( + queries: MLXArray.zeros([1, 2, count, dk], dtype: dtype), + keys: MLXArray.zeros([1, 1, count, dk], dtype: dtype), + values: MLXArray.ones([1, 1, count, dv], dtype: dtype) + * Float(3), + scale: 0.125, sinks: MLXArray.zeros([2], dtype: dtype)) + ] + try f.backend.pool.writeValidation.check() + } else { + outputs = try f.forward(count: count) + } + try f.publish(work, outputs: outputs) + try work.finishEvaluation() + XCTAssertEqual(outputs[0].shape, [1, 2, count, dv]) + for (index, value) in outputs[0].asType(.float32).asArray(Float.self) + .enumerated() + { + let visible = Float(min(17, start + (index / dv) % count + 1)) + let expected: Float = softcap == nil ? 3 : 3 * visible / (visible + 1) + XCTAssertEqual(value, expected, accuracy: 0.04) + } + work.closeGraph() + } + XCTAssertEqual(f.backend.pool.attentionWorkBytesReserved, 0) + } + } + } + } + + private func actualEngine(_ f: PagedWorkFixture) -> EngineV2 { + .init( + model: PagedWorkEngineModel(), layerKinds: f.kinds, backend: f.backend, + cacheProvider: f.bank, + schedulerConfig: .init( + maxConcurrentRequests: 2, + maxBatchedTokensPerStep: 16, prefillChunkSize: 16, maxWaiting: 4, + enablePrefixCache: false), + admissionConfig: .init(watermarkFraction: 0, elementBytes: 4), + processMemoryOwner: f.process) + } + + func testActualEngineTokensMatchContiguousAndRetireFutureWork() async throws { + let kinds = [workKind(window: 17), workKind()] + let f = try PagedWorkFixture(kinds, bindAdmission: false) + let paged = actualEngine(f) + XCTAssertNil(paged.pagedAttentionWorkInactiveReason) + let coldBackend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 1 << 30, kvDType: .float32)) + let cold = EngineV2( + model: PagedWorkEngineModel(), layerKinds: kinds, backend: coldBackend, + cacheProvider: CBv2LayerCacheBank(layerKinds: kinds), + schedulerConfig: .init( + maxConcurrentRequests: 2, maxBatchedTokensPerStep: 16, + prefillChunkSize: 16, maxWaiting: 4, enablePrefixCache: false), + admissionConfig: .init(watermarkFraction: 0, elementBytes: 4)) + let request = CBv2Request( + id: .init(80), promptTokens: (0 ..< 41).map { ($0 * 7) % 29 }, + sampling: .init(temperature: 0, seed: 0), maxTokens: 5) + let expected = await cbv2SchedCollect(try cold.submit(request)) + let result = await cbv2SchedCollect(try paged.submit(request)) + XCTAssertEqual(result.finishReason, .length) + XCTAssertEqual(result.tokens, expected.tokens) + await cold.shutdown() + await paged.shutdown() + XCTAssertEqual(paged.pagedAttentionWorkBytesReserved, 0) + XCTAssertEqual(paged.admissionForTesting.bytesReserved, 0) + XCTAssertEqual(f.process.snapshot.charge, 0) + XCTAssertEqual(f.process.snapshot.materialized, 0) + } + + func testActualEngineCancellationDrainsSubmittedOwner() async throws { + let f = try PagedWorkFixture([workKind(window: 17)], bindAdmission: false) + let engine = actualEngine(f) + engine.loopForTesting.onEngineQueueSync { + engine.loopForTesting.suspendStepExecutionAtCountForTesting = 1 + } + let id = CBv2RequestID(81) + let stream = try engine.submit( + .init(id: id, promptTokens: Array(repeating: 1, count: 64), maxTokens: 8)) + let launched = await cbv2SchedWait { engine.stepCount == 1 } + XCTAssertTrue(launched) + XCTAssertGreaterThan(engine.pagedAttentionWorkBytesReserved, 0) + engine.cancel(id) + engine.loopForTesting.onEngineQueueSync { + engine.loopForTesting.suspendStepExecutionAtCountForTesting = nil + } + let result = await cbv2SchedCollect(stream) + XCTAssertEqual(result.finishReason, .cancelled) + await engine.shutdown() + XCTAssertEqual(engine.pagedAttentionWorkBytesReserved, 0) + XCTAssertEqual(engine.admissionForTesting.bytesReserved, 0) + XCTAssertEqual(f.process.snapshot.charge, 0) + XCTAssertEqual(f.process.snapshot.materialized, 0) + } + + func testActualEngineMissingOwnerOrLargerSchedulerEnvelopeRefusesPublication() throws { + for scenario in ["owner", "batchGrowth", "stripeGrowth"] { + let f = try PagedWorkFixture([workKind()], bindAdmission: false) + let engine = EngineV2( + model: PagedWorkEngineModel(), layerKinds: f.kinds, backend: f.backend, + cacheProvider: f.bank, + schedulerConfig: .init( + maxConcurrentRequests: 2, + maxBatchedTokensPerStep: scenario == "batchGrowth" ? 130 : 16, + prefillChunkSize: 16, + soloPrefillStripeTokens: scenario == "stripeGrowth" ? 130 : nil, + enablePrefixCache: false), + processMemoryOwner: scenario == "owner" ? nil : f.process) + XCTAssertNotNil(engine.pagedAttentionWorkInactiveReason) + XCTAssertThrowsError( + try engine.submit(.init(id: .init(82), promptTokens: [1, 2], maxTokens: 1))) + XCTAssertEqual(engine.stepCount, 0) + XCTAssertEqual(f.backend.bytesReserved, 0) + XCTAssertEqual(engine.pagedAttentionWorkBytesReserved, 0) + XCTAssertEqual(f.backend.pool.config.gatheredAttention?.maximumContextTokens, 1_048_576) + } + } +} diff --git a/Tests/MLXLMTests/CBv2PositionedAdapterTests.swift b/Tests/MLXLMTests/CBv2PositionedAdapterTests.swift index 846b2314bf..820b9f8a1f 100644 --- a/Tests/MLXLMTests/CBv2PositionedAdapterTests.swift +++ b/Tests/MLXLMTests/CBv2PositionedAdapterTests.swift @@ -108,6 +108,79 @@ struct CBv2PositionedAdapterTests { admissionConfig: .init(watermarkFraction: 0)) } + @Test("Qwen-like and foreign adapters retain required causal positions before materialization") + func rejectsMissingCausalPositionsBeforeQwenOrForeignForward() async { + let models: [GemmaLikePositionlessModel] = [ + GemmaLikePositionlessModel(), QwenLikePositionedModel(), + ] + for model in models { + let adapter = CBv2SteppableLanguageModelAdapter(model) + #expect(adapter.causalPositionRequirement == .requestOwned) + let actual = engine(model) + var producerCalls = 0 + let media = CBv2MultimodalInput( + spans: [.init(tokenOffset: 1, length: 1)], attention: .causal + ) { + producerCalls += 1 + return [MLXArray.ones([1, 1, 1])] + } + do { + _ = try actual.submit( + CBv2Request( + id: .init(9103), promptTokens: [1, 7, 2], + maxTokens: 1, multimodal: media)) + Issue.record("missing causal positions were admitted") + } catch let error as CBv2MultimodalError { + guard case .invalidSpans(let detail) = error else { + Issue.record("wrong rejection: \(error)") + await actual.shutdown() + continue + } + #expect(detail == "causal multimodal input requires request-owned position state") + } catch { Issue.record("unexpected rejection: \(error)") } + #expect(producerCalls == 0) + #expect(model.forwardCount == 0) + await actual.shutdown() + } + } + + @Test("Qwen-like supplied positions still reject malformed length and axes before work") + func rejectsMalformedQwenPositionStateBeforeMaterialization() async { + for shape in [[3, 1, 2], [2, 1, 3]] { + let model = QwenLikePositionedModel() + let actual = engine(model) + var producerCalls = 0 + let positions = CBv2PositionState( + promptPositionIds: MLXArray.zeros(shape, dtype: .int32), + decodeDeltas: [0]) + let media = CBv2MultimodalInput( + spans: [.init(tokenOffset: 1, length: 1)], + attention: .causal, positionState: positions + ) { + producerCalls += 1 + return [MLXArray.ones([1, 1, 1])] + } + do { + _ = try actual.submit( + CBv2Request( + id: .init(9104), promptTokens: [1, 7, 2], + maxTokens: 1, multimodal: media)) + Issue.record("malformed supplied positions were admitted") + } catch let error as CBv2MultimodalError { + guard case .invalidSpans(let detail) = error else { + Issue.record("wrong rejection: \(error)") + await actual.shutdown() + continue + } + #expect(detail.contains(shape[0] == 2 ? "position axes" : "position length")) + } catch { Issue.record("unexpected rejection: \(error)") } + #expect(producerCalls == 0) + #expect(model.forwardCount == 0) + #expect(model.positionedShapes.isEmpty) + await actual.shutdown() + } + } + @Test("position state is typed-rejected when the wrapped model lacks positioned forwarding") func rejectsPositionStateBeforeGemmaLikeForward() async { let model = GemmaLikePositionlessModel() diff --git a/Tests/MLXLMTests/CBv2StatefulAttentionMTPActivationTests.swift b/Tests/MLXLMTests/CBv2StatefulAttentionMTPActivationTests.swift new file mode 100644 index 0000000000..6c189e0a9d --- /dev/null +++ b/Tests/MLXLMTests/CBv2StatefulAttentionMTPActivationTests.swift @@ -0,0 +1,192 @@ +import MLX +import XCTest + +@testable import MLXLMCommon + +/// Metadata-only driver admission. No forward, tensor, state allocation or +/// token-quality claim; actual native engine parity remains a separate suite. +final class CBv2StatefulAttentionMTPActivationTests: XCTestCase { + private final class Owner {} + private class Target: CBv2MTPSteppableModel { + let owner: Owner + let supported: Bool + var hasIdentity = true + init(_ owner: Owner, supported: Bool) { + self.owner = owner + self.supported = supported + } + var mtpCaptureLayers: CBv2MTPCaptureLayers? { nil } + var supportsRequestStatefulMTP: Bool { supported } + var mtpTargetIdentity: ObjectIdentifier? { hasIdentity ? ObjectIdentifier(owner) : nil } + func forward(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> MLXArray { + preconditionFailure("admission must not run target") + } + func forwardWithHidden(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) + -> (logits: MLXArray, lastHidden: MLXArray) + { + preconditionFailure("admission must not run target") + } + } + private final class MissingRecurrentSpec: Target, CBv2RecurrentMTPSteppableModel { + var cbv2Capabilities: CBv2ModelCapabilities { .initialRecurrentTarget } + var recurrentStateSpec: CBv2RecurrentStateSpec? { nil } + func forward( + tokens: MLXArray, caches: [CBv2AttendingLayerCache], + recurrentState: [CBv2RecurrentStateEvaluation] + ) -> MLXArray { + preconditionFailure("missing recurrent state cannot run") + } + func forwardWithHidden( + tokens: MLXArray, caches: [CBv2AttendingLayerCache], + recurrentState: [CBv2RecurrentStateEvaluation], positionIds: MLXArray? + ) + -> (logits: MLXArray, lastHidden: MLXArray) + { + preconditionFailure("missing recurrent state cannot run") + } + } + private final class State: CBv2MTPRequestState { + var committedInputCount: Int { 0 } + var stagedInputCount: Int { 0 } + } + private final class Capture: CBv2MTPPreparedCapture {} + private final class Drafter: CBv2MTPRequestStatefulDrafter { + let owner: Owner + var hasIdentity = true + var stateCreations = 0 + init(_ owner: Owner) { self.owner = owner } + var mtpTargetIdentity: ObjectIdentifier? { hasIdentity ? ObjectIdentifier(owner) : nil } + var requiredVerificationMode: CBv2MTPVerificationMode? { .serialTarget } + var maximumDraftTokens: Int? { 3 } + var maximumSpeculativeBatch: Int? { 1 } + func prepare(rows: [CBv2MTPRowCapture]) -> any CBv2MTPPreparedCapture { Capture() } + func draftStep(tokens: MLXArray, hidden: MLXArray, prepared: any CBv2MTPPreparedCapture) + -> (tokens: MLXArray, hidden: MLXArray) + { + preconditionFailure("admission must not draft") + } + func makeRequestState() -> any CBv2MTPRequestState { + stateCreations += 1 + return State() + } + func observeCommittedTarget( + _ observation: CBv2MTPCommittedTargetObservation, + requestState: any CBv2MTPRequestState + ) {} + func draftStep( + tokens: MLXArray, hidden: MLXArray, shortlist: MLXArray?, + requestState: any CBv2MTPRequestState + ) + -> (tokens: MLXArray, hidden: MLXArray) + { + preconditionFailure("admission must not draft") + } + func evaluationTargets(for requestState: any CBv2MTPRequestState) -> [MLXArray] { [] } + func finalizeRound( + requestState: any CBv2MTPRequestState, confirmedInputTokens: Int, + committedDraftTokens: MLXArray, committedTargetHidden: MLXArray + ) {} + func discardRound(requestState: any CBv2MTPRequestState) {} + func releaseRequestState(_ requestState: any CBv2MTPRequestState) {} + } + private var enabled: CBv2MTPConfig { + .init( + enabled: true, maxDraftTokens: 5, maxSpeculativeBatch: 4, + fixedDraftTokens: 5, verificationMode: .automatic) + } + + func testAttentionStatefulActivationRequiresExplicitNativeCapability() throws { + let owner = Owner() + let drafter = Drafter(owner) + XCTAssertNil( + CBv2MTPRoundDriver.build( + model: Target(owner, supported: false), + drafter: drafter, config: enabled)) + let driver = try XCTUnwrap( + CBv2MTPRoundDriver.build( + model: Target(owner, supported: true), drafter: drafter, config: enabled)) + XCTAssertTrue(driver.usesRequestStatefulDrafter) + XCTAssertEqual(driver.config.verificationMode, .serialTarget) + XCTAssertEqual(driver.config.maxDraftTokens, 3) + XCTAssertEqual(driver.config.fixedDraftTokens, 3) + XCTAssertEqual(driver.config.maxSpeculativeBatch, 1) + XCTAssertEqual(drafter.stateCreations, 0) + } + + func testForeignAndMissingTargetIdentityRemainRefused() { + let owner = Owner() + let target = Target(owner, supported: true) + let drafter = Drafter(owner) + XCTAssertNil( + CBv2MTPRoundDriver.build(model: target, drafter: Drafter(Owner()), config: enabled)) + target.hasIdentity = false + XCTAssertNil(CBv2MTPRoundDriver.build(model: target, drafter: drafter, config: enabled)) + target.hasIdentity = true + drafter.hasIdentity = false + XCTAssertNil(CBv2MTPRoundDriver.build(model: target, drafter: drafter, config: enabled)) + XCTAssertEqual(drafter.stateCreations, 0) + } + + func testMissingRecurrentSpecCannotMasqueradeAsAttentionOnly() { + let owner = Owner() + let drafter = Drafter(owner) + XCTAssertNil( + CBv2MTPRoundDriver.build( + model: MissingRecurrentSpec(owner, supported: true), + drafter: drafter, config: enabled)) + XCTAssertEqual(drafter.stateCreations, 0) + } + + func testDisabledOrMissingAssistantDoesNotActivate() { + let owner = Owner() + let target = Target(owner, supported: true) + let drafter = Drafter(owner) + var disabled = enabled + disabled.enabled = false + XCTAssertNil(CBv2MTPRoundDriver.build(model: target, drafter: drafter, config: disabled)) + XCTAssertNil(CBv2MTPRoundDriver.build(model: target, drafter: nil, config: enabled)) + XCTAssertEqual(drafter.stateCreations, 0) + } + + func testExistingDraftersDoNotOptIntoObservationFencingByDefault() { + XCTAssertFalse(Drafter(Owner()).requiresCommittedObservationFence) + XCTAssertNoThrow(try Drafter(Owner()).requestStateDidFinishEvaluation(State())) + } + + func testPartialAssistantResidencyRemainsExplicitAndDeduplicated() throws { + final class Measured: CBv2MTPRequestResidencyReporting { + var committedInputCount = 0, stagedInputCount = 0 + var materializedBytes = 4096 + var hasUnmeasuredResidency = true + } + let owner = Owner() + let drafter = Drafter(owner) + let driver = try XCTUnwrap( + CBv2MTPRoundDriver.build( + model: Target(owner, supported: true), drafter: drafter, config: enabled)) + let state = Measured() + driver.restoreAssistantState(state, for: .init(1)) + XCTAssertEqual(driver.materializedAssistantBytes(detachedStates: [state, state]), 4096) + XCTAssertTrue(driver.hasUnmeasuredAssistantResidency()) + state.hasUnmeasuredResidency = false + XCTAssertFalse(driver.hasUnmeasuredAssistantResidency(detachedStates: [state])) + _ = driver.takeAssistantState(for: .init(1)) + state.hasUnmeasuredResidency = true + XCTAssertFalse(driver.hasUnmeasuredAssistantResidency()) + XCTAssertTrue(driver.hasUnmeasuredAssistantResidency(detachedStates: [state])) + } + + func testCapacitySnapshotDoesNotSilentlyLabelPartialAssistantTotal() { + let legacy = CBv2CapacitySnapshot( + activeRequests: 0, waitingRequests: 0, + kvBytesInUse: 0, kvBytesCapacity: 8192, activeTokens: 0) + XCTAssertFalse(legacy.hasUnmeasuredAssistantResidency) + let transition = CBv2CapacitySnapshot( + activeRequests: 1, waitingRequests: 0, + kvBytesInUse: 4096, kvBytesCapacity: 8192, kvBytesReserved: 8192, + activeTokens: 1, hasUnmeasuredAssistantResidency: true) + XCTAssertTrue(transition.hasUnmeasuredAssistantResidency) + XCTAssertEqual(transition.kvBytesReserved, 8192) + XCTAssertEqual(transition.kvBytesInUse, 4096) + } +} diff --git a/Tests/MLXLMTests/CBv2WindowedStepRetirementTests.swift b/Tests/MLXLMTests/CBv2WindowedStepRetirementTests.swift new file mode 100644 index 0000000000..9798bd40cc --- /dev/null +++ b/Tests/MLXLMTests/CBv2WindowedStepRetirementTests.swift @@ -0,0 +1,351 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLMCommon + +// Source-only prepared native tests. Run serially in the exclusive synthetic +// lane: the active-memory delta below is an isolated retirement witness, never +// an allocation identity, process-reservation credit or a model qualification. +// Real helper dependencies: CBv2CompleteCheckpointEngineTests.swift supplies +// CompleteCheckpointFixtureStore; CBv2SchedulerTestSupport.swift supplies the +// actual stream collector/wait helpers. Neither helper file is modified. + +private final class CBv2WindowRetirementWeakPair { + weak var keys: MLXArray? + weak var values: MLXArray? + let positions: Int + let logicalBytes: Int + init(_ keys: MLXArray, _ values: MLXArray) { + self.keys = keys + self.values = values + positions = keys.dim(2) + logicalBytes = keys.nbytes + values.nbytes + } +} + +/// Only weak native/row references. The observation cannot keep the buffers +/// alive and accidentally manufacture the retention the test is checking. +private final class CBv2WindowRetirementProbe: @unchecked Sendable { + private let lock = NSLock() + private weak var row: CBv2WindowedSequenceKV? + private var pair: CBv2WindowRetirementWeakPair? + private var count = 0 + func record(_ row: CBv2WindowedSequenceKV) { + let views = row.borrowableViews() + lock.withLock { + self.row = row + pair = .init(views.keys, views.values) + count += 1 + } + } + func inspect(_ body: (CBv2WindowedSequenceKV?, CBv2WindowRetirementWeakPair?, Int) -> Void) { + lock.withLock { body(row, pair, count) } + } +} + +/// Real BF16 asymmetric attention and shared-KV borrowing. Only the checkpoint +/// store/inputs are synthetic; this never substitutes a mock cache or backend. +private final class CBv2WindowRetirementModel: CBv2SteppableModel, + CBv2HistoricalAttentionCheckpointProviding, CBv2CompleteCheckpointKVTypeProviding +{ + let cbv2SupportsHistoricalAttentionCheckpoint = true + let cbv2CompleteCheckpointKVDTypes: [DType]? = Array(repeating: .bfloat16, count: 4) + let probe: CBv2WindowRetirementProbe? + var pauseImportedChunk: (() -> Void)? + init(probe: CBv2WindowRetirementProbe? = nil) { self.probe = probe } + + func forward(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> MLXArray { + let batch = tokens.dim(0) + let length = tokens.dim(1) + var hidden = (tokens.asType(.float32).reshaped([batch, 1, length, 1]) / Float(32)).asType( + .bfloat16) + for cache in caches { + let queries = MLXArray.zeros([batch, 2, length, 128], dtype: .bfloat16) + let output: MLXArray + if let owner = cache.kind.sharesKVWithLayer { + output = cache.attendBorrowing( + source: caches[owner], queries: queries, scale: 0.125, sinks: nil) + } else { + let keys = broadcast(hidden, to: [batch, 1, length, 128]) + let values = broadcast(hidden, to: [batch, 1, length, 192]) + output = cache.updateAndAttend( + queries: queries, keys: keys, values: values, scale: 0.125, sinks: nil) + if cache.layerIndex == 0, length == 256, + let row = (cache as? CBv2LayerCache)?.rows.first as? CBv2WindowedSequenceKV, + row.absoluteOffset == 512, row.checkpointBacking != nil + { + probe?.record(row) + // Real backpressure scheduling API; enqueued on the engine + // queue before the next step can process the final suffix. + pauseImportedChunk?() + } + } + hidden = mean(output.asType(.float32), axes: [1, 3], keepDims: true).asType(.bfloat16) + } + let target = + MLX.round(hidden.asType(.float32).reshaped([batch, length, 1]) * Float(128)).asType( + .int32) % 31 + return MLX.where(MLXArray(Int32(0) ..< Int32(32)) .== target, Float(10), Float(-10)) + } +} + +final class CBv2WindowedStepRetirementTests: XCTestCase { + private func tensor(start: Int, count: Int, width: Int) -> MLXArray { + let values = (0 ..< (count * width)).map { index in + Float((start + index / width) % 31 + index % 7) / Float(16) + } + return MLXArray(values).reshaped([1, 1, count, width]).asType(.bfloat16) + } + + private func fence(_ arrays: [MLXArray]) throws { + try withError { fault in + eval(arrays) + StreamOrDevice.default.stream.synchronize() + try fault.check() + } + } + + private func restoredRow() throws -> CBv2WindowedSequenceKV { + let keys = tensor(start: 0, count: 257, width: 128) + let values = tensor(start: 0, count: 257, width: 192) + try fence([keys, values]) + return try .init( + restoredKeys: keys, restoredValues: values, offset: 256, + window: 257, kvHeads: 1, headDim: 128, valueHeadDim: 192) + } + + /// All strong references to the returned pair are scoped inside this + /// helper. Only the row itself may retain them when the caller observes it. + private func updateAndFence(_ row: CBv2WindowedSequenceKV, count: Int) throws + -> CBv2WindowRetirementWeakPair + { + let start = row.absoluteOffset + let pair = row.update( + keys: tensor(start: start, count: count, width: 128), + values: tensor(start: start, count: count, width: 192)) + let witness = CBv2WindowRetirementWeakPair(pair.0, pair.1) + try fence([pair.0, pair.1] + row.cbv2InnerState()) + XCTAssertNotNil(try pair.0.evaluatedBufferInfo()) + XCTAssertNotNil(try pair.1.evaluatedBufferInfo()) + return witness + } + + private func ringValues(_ row: CBv2WindowedSequenceKV) throws -> [[Float]] { + try autoreleasepool { + let snapshot = row.snapshot() + let keys = snapshot.keys.asType(.float32) + let values = snapshot.values.asType(.float32) + try fence([keys, values]) + return [keys.asArray(Float.self), values.asArray(Float.self)] + } + } + + private func borrowedValues(_ row: CBv2WindowedSequenceKV) throws -> [[Float]] { + try autoreleasepool { + let views = row.borrowableViews() + let keys = views.keys.asType(.float32) + let values = views.values.asType(.float32) + try fence([keys, values]) + return [keys.asArray(Float.self), values.asArray(Float.self)] + } + } + + func testRestoredBF16ChunkViewsRetireAfterFenceWithoutRetiringRing() throws { + let row = try restoredRow() + let witness = try updateAndFence(row, count: 256) + XCTAssertEqual(row.absoluteOffset, 512) + XCTAssertEqual(witness.positions, 512) + XCTAssertEqual(witness.logicalBytes, 512 * (128 + 192) * 2) + XCTAssertNotNil(witness.keys) + XCTAssertNotNil(witness.values) + let expected = try ringValues(row) + let ringBytes = row.byteCount + XCTAssertEqual(ringBytes, 257 * (128 + 192) * 2) + try fence(row.cbv2InnerState()) + let before = Memory.snapshot().activeMemory + + row.retireBorrowableChunkViews(afterFencedPosition: 512) + try withError { StreamOrDevice.default.stream.synchronize() } + let after = Memory.snapshot().activeMemory + XCTAssertNil(witness.keys) + XCTAssertNil(witness.values) + XCTAssertGreaterThanOrEqual( + before - after, witness.logicalBytes, + "completed isolated chunk backing must leave native active accounting, not merely its Swift wrapper" + ) + XCTAssertEqual(row.absoluteOffset, 512) + XCTAssertEqual(row.retainedCount, 257) + XCTAssertEqual( + row.byteCount, ringBytes, "temporary retirement must not refund/drop the ring") + XCTAssertEqual(try ringValues(row), expected) + XCTAssertEqual(row.borrowableViews().keys.dim(2), 257) + row.retireBorrowableChunkViews(afterFencedPosition: 512) // idempotent + XCTAssertEqual(try ringValues(row), expected) + } + + func testStaleAndSpeculativeFencesPreserveCurrentBorrowedMath() throws { + let row = try restoredRow() + let reference = try restoredRow() + let old = try updateAndFence(row, count: 256) + _ = try updateAndFence(reference, count: 256) + let expected = try borrowedValues(row) + + row.retireBorrowableChunkViews(afterFencedPosition: 256) // prior step generation + XCTAssertNotNil(old.keys) + XCTAssertNotNil(old.values) + XCTAssertEqual(try borrowedValues(row), expected) + row.beginSpeculativeWrite() // armed, but no staged write yet + row.retireBorrowableChunkViews(afterFencedPosition: 512) + XCTAssertNotNil(old.keys) + XCTAssertNotNil(old.values) + XCTAssertEqual(try borrowedValues(row), expected) + row.commitSpeculativeWrite() + row.retireBorrowableChunkViews(afterFencedPosition: 512) + XCTAssertNil(old.keys) + XCTAssertNil(old.values) + + row.beginSpeculativeWrite() + let speculative = try updateAndFence(row, count: 3) + let stagedMath = try borrowedValues(row) + XCTAssertEqual(row.absoluteOffset, 515) + row.retireBorrowableChunkViews(afterFencedPosition: 515) // exact offset but armed/staged + XCTAssertNotNil(speculative.keys) + XCTAssertNotNil(speculative.values) + XCTAssertEqual(try borrowedValues(row), stagedMath) + row.rollback(1) + row.commitSpeculativeWrite() + try fence(row.cbv2InnerState()) + _ = try updateAndFence(reference, count: 2) + XCTAssertEqual(row.absoluteOffset, 514) + XCTAssertEqual( + try ringValues(row), try ringValues(reference), + "refused cleanup must not change accepted-prefix rollback/commit math") + row.retireBorrowableChunkViews(afterFencedPosition: 514) + XCTAssertEqual(try ringValues(row), try ringValues(reference)) + } + + private func engine( + _ store: CompleteCheckpointFixtureStore, + model: CBv2WindowRetirementModel + ) -> (EngineV2, CBv2ContiguousKVBackend) { + let kinds: [CBv2LayerKind] = [ + .init( + attention: .slidingWindow(257), headDim: 128, valueHeadDim: 192, kvHeads: 1, + queryHeads: 2), + .init(attention: .full, headDim: 128, valueHeadDim: 192, kvHeads: 1, queryHeads: 2), + .init( + attention: .slidingWindow(257), sharesKVWithLayer: 0, headDim: 128, + valueHeadDim: 192, kvHeads: 1, queryHeads: 2), + .init( + attention: .full, sharesKVWithLayer: 1, headDim: 128, valueHeadDim: 192, kvHeads: 1, + queryHeads: 2), + ] + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 128 << 20, kvDType: .bfloat16)) + let engine = EngineV2( + model: model, layerKinds: kinds, backend: backend, + cacheProvider: CBv2LayerCacheBank(layerKinds: kinds), + sampler: CBv2DefaultSampler(fallbackSeed: 0), + schedulerConfig: .init( + maxConcurrentRequests: 1, maxBatchedTokensPerStep: 256, + prefillChunkSize: 256, maxWaiting: 2, enablePrefixCache: true), + admissionConfig: .init(watermarkFraction: 0), completePrefixCache: store) + return (engine, backend) + } + + func testRealImportedEnginePauseKeepsRowButRetiresCompletedChunkViews() async throws { + // A 512-token request cannot donate a boundary at512: the native cache + // reserves a final uncached token. Use the supported pause at512 before + // the last1-token suffix of a513-token/maxTokens1 request instead. Do + // not change prompt/export rules merely to force an I/O publication. + XCTAssertEqual(256 % CBv2AttentionV1.queryBlockSize, 0) + let prompt = (0 ..< 513).map { ($0 * 7) % 29 } + let seed = CompleteCheckpointFixtureStore(segmentBytes: 258) + let (cold, _) = engine(seed, model: .init()) + let coldRequest = CBv2Request( + id: .init(810), promptTokens: prompt, + sampling: .init(temperature: 0, seed: 0), maxTokens: 1, + cacheSalt: "window-retirement", prefixCacheReceiptID: .init(1810)) + let expected = await cbv2SchedCollect(try cold.submit(coldRequest)) + XCTAssertEqual(expected.finishReason, .length) + await cold.shutdown() + let earlier = seed.saved.filter { $0.manifest.position == 256 } + XCTAssertEqual(earlier.count, 1) + + let store = CompleteCheckpointFixtureStore(archives: earlier, segmentBytes: 258) + let probe = CBv2WindowRetirementProbe() + let model = CBv2WindowRetirementModel(probe: probe) + let (warm, backend) = engine(store, model: model) + let request = CBv2Request( + id: .init(811), promptTokens: prompt, + sampling: .init(temperature: 0, seed: 0), maxTokens: 1, + cacheSalt: "window-retirement", prefixCacheReceiptID: .init(1811)) + let loop = warm.loopForTesting + model.pauseImportedChunk = { [weak loop] in loop?.setPaused(request.id, true) } + XCTAssertTrue(try store.stage(engine: warm, request: request)) + // Counting is opt-in test instrumentation; it does not enable the + // production fence. Keep the exact fence/retirement assertions below. + let wasCounting = CBv2CoreInstrumentation.countingEnabled + CBv2CoreInstrumentation.countingEnabled = true + defer { CBv2CoreInstrumentation.countingEnabled = wasCounting } + let hostSyncsBefore = CBv2CoreInstrumentation.hostSyncs + let stream = try warm.submit(request) + let collected = Task { await cbv2SchedCollect(stream) } + let paused = await cbv2SchedWait { loop.pausedIDsSnapshot().contains(request.id) } + XCTAssertTrue(paused) + let retiredAtFence = await cbv2SchedWait(timeoutSeconds: 5) { + loop.onEngineQueueSync { + var ready = false + probe.inspect { row, pair, count in + ready = + CBv2CoreInstrumentation.hostSyncs > hostSyncsBefore + && count == 1 && row?.absoluteOffset == 512 + && pair != nil && pair?.keys == nil && pair?.values == nil + } + return ready + } + } + XCTAssertTrue( + retiredAtFence, + "the real finalize hook, not a later n1 update, must clear the weak views") + loop.onEngineQueueSync { + probe.inspect { row, pair, count in + XCTAssertEqual(count, 1) + XCTAssertNotNil(row, "actual imported/paused row must remain owned") + XCTAssertNotNil(row?.checkpointBacking) + XCTAssertEqual(row?.absoluteOffset, 512) + XCTAssertEqual(row?.byteCount, 257 * (128 + 192) * 2) + XCTAssertEqual(pair?.positions, 512) + XCTAssertEqual(pair?.logicalBytes, 512 * (128 + 192) * 2) + XCTAssertNil(pair?.keys) + XCTAssertNil(pair?.values) + XCTAssertEqual(row?.borrowableViews().keys.dim(2), 257) + for array in row?.cbv2InnerState() ?? [] { + XCTAssertNotNil( + try? array.evaluatedBufferInfo(), + "ring is already available; observation must not eval") + } + } + } + XCTAssertEqual( + warm.stepCount, 1, "no final1-token suffix or decode may mask the lifecycle defect") + XCTAssertEqual( + CBv2CoreInstrumentation.hostSyncs - hostSyncsBefore, 1, + "the exact imported256-token step completed its real host fence") + XCTAssertEqual(store.releaseCount, 1) + XCTAssertGreaterThan(backend.bytesReserved, 0) + XCTAssertGreaterThan(warm.admissionForTesting.bytesReserved, 0) + + loop.onEngineQueueSync { model.pauseImportedChunk = nil } + loop.setPaused(request.id, false) + let result = await collected.value + XCTAssertEqual(result.finishReason, .length) + XCTAssertEqual(result.tokens, expected.tokens) + XCTAssertEqual(result.usage?.prefixCachePrefillTokensSaved, 256) + await warm.shutdown() + XCTAssertEqual(backend.bytesReserved, 0) + XCTAssertEqual(warm.admissionForTesting.bytesReserved, 0) + XCTAssertEqual(store.releaseCount, 1) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26AudioFrontendTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26AudioFrontendTests.swift new file mode 100644 index 0000000000..d2d9201011 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26AudioFrontendTests.swift @@ -0,0 +1,139 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLLM +@testable import MLXVLM + +final class MiMoV26AudioFrontendTests: XCTestCase { + func testReflectIndicesAndPeriodicWindowAreNotEdgeOrSymmetricPadding() throws { + let indices = try MiMoV26AudioFrontend.reflectFrameIndices( + samples: 481, startFrame: 0, count: 1, fftSize: 960, hop: 240) + XCTAssertEqual(Array(indices.prefix(4)), [480, 479, 478, 477]) + XCTAssertEqual(indices[479], 1) + XCTAssertEqual(indices[480], 0) + XCTAssertEqual(indices[481], 1) + let end = try MiMoV26AudioFrontend.reflectFrameIndices( + samples: 481, startFrame: 2, count: 1, fftSize: 960, hop: 240) + XCTAssertEqual(end[480], 480) + XCTAssertEqual(end[481], 479) + XCTAssertEqual(end.last, 1) + try mimoAudioInputRequireNative() + let window = MiMoV26AudioFrontend.periodicHann(960).asArray(Float.self) + XCTAssertEqual(window[0], 0) + XCTAssertEqual(window[480], 1, accuracy: 0.000001) + XCTAssertGreaterThan(window[959], 0) + XCTAssertEqual(window[1], window[959], accuracy: 0.000001) + } + + func testPCMValidationAndCancelledPreparationBeforeGraph() throws { + let d = MiMoV26AudioPCMDescriptor( + sourceIdentity: "pcm", channels: 1, frameCount: 481, sampleRate: 24000) + XCTAssertThrowsError(try MiMoV26DecodedPCM(samples: [0], descriptor: d)) + var samples = Array(repeating: Float(0), count: 481) + samples[0] = .nan + XCTAssertThrowsError(try MiMoV26DecodedPCM(samples: samples, descriptor: d)) + let c = try MiMoV26AudioInputConfiguration.fixture(melBands: 128) + let plan = try MiMoV26AudioInputPlan.make( + clips: [d], configuration: c, limits: mimoAudioInputTestLimits()) + let pcm = try MiMoV26DecodedPCM(samples: Array(repeating: 0, count: 481), descriptor: d) + XCTAssertThrowsError( + try MiMoV26AudioFrontend(configuration: c).prepare( + pcm: pcm, plan: plan, clipIndex: 0, isCancelled: { true }) + ) { + XCTAssertEqual($0 as? MiMoV26AudioInputError, .cancelled) + } + } + + func testIdentitySilenceStereoCancellationAndAmplitudeAreNotNormalized() throws { + try mimoAudioInputRequireNative() + let c = try MiMoV26AudioInputConfiguration.fixture(melBands: 128) + let frontend = MiMoV26AudioFrontend(configuration: c) + func prepare(_ samples: [Float], channels: Int) throws -> [Float] { + let d = MiMoV26AudioPCMDescriptor( + sourceIdentity: "synthetic", channels: channels, + frameCount: samples.count / channels, sampleRate: 24000) + let p = try MiMoV26AudioInputPlan.make( + clips: [d], configuration: c, limits: mimoAudioInputTestLimits()) + return try frontend.prepare( + pcm: .init(samples: samples, descriptor: d), plan: p, clipIndex: 0 + ).values.asArray(Float.self) + } + let zeros = try prepare(Array(repeating: 0, count: 2400), channels: 1) + XCTAssertTrue(zeros.allSatisfy { abs($0 - log(Float(1e-7))) < 0.00001 }) + let tone = (0 ..< 2400).map { Float(sin(2 * Double.pi * 1000 * Double($0) / 24000)) } + let cancel = try prepare(tone + tone.map { -$0 }, channels: 2) + XCTAssertEqual(cancel, zeros) + let ordinary = try prepare(tone, channels: 1) + let loud = try prepare(tone.map { $0 * 2 }, channels: 1) + let active = ordinary.indices.filter { ordinary[$0] > -5 } + XCTAssertFalse(active.isEmpty) + for i in active { XCTAssertEqual(loud[i] - ordinary[i], log(Float(2)), accuracy: 0.001) } + } + + func testPinnedTorchFrontendOracleIntermediates() throws { + try mimoAudioInputRequireNative() + struct Fixture: Decodable { + let name: String + let rate, channels, frames: Int + let samples, resampled, kernel, mel, window, bank: [Float] + let spectrumReal, spectrumImaginary, magnitude: [Float] + let melFrames: Int + } + let root = try mimoAudioInputFixtureRoot() + let fixtures = try JSONDecoder().decode( + [Fixture].self, + from: Data(contentsOf: root.appendingPathComponent("frontend-oracle.json"))) + XCTAssertGreaterThanOrEqual(fixtures.count, 4) + let c = try MiMoV26AudioInputConfiguration.fixture(melBands: 128) + for f in fixtures { + let d = MiMoV26AudioPCMDescriptor( + sourceIdentity: f.name, channels: f.channels, frameCount: f.frames, + sampleRate: f.rate) + let p = try MiMoV26AudioInputPlan.make( + clips: [d], configuration: c, limits: mimoAudioInputTestLimits()) + XCTAssertEqual(p.melFrameCounts, [f.melFrames]) + let coefficients = try MiMoV26AudioFrontend.resampleCoefficients(p.resampling[0]) + XCTAssertEqual(coefficients.count, f.kernel.count) + for i in coefficients.indices { + XCTAssertEqual(coefficients[i], f.kernel[i], accuracy: 0.000001, f.name) + } + let wave = MLXArray(f.samples).reshaped(f.channels, f.frames) + let actualWave = MiMoV26AudioFrontend.resample( + wave, plan: p.resampling[0], coefficients: coefficients + ).asArray(Float.self) + XCTAssertEqual(actualWave.count, f.resampled.count) + for i in actualWave.indices { + XCTAssertEqual(actualWave[i], f.resampled[i], accuracy: 0.00002, f.name) + } + let window = MiMoV26AudioFrontend.periodicHann(960).asArray(Float.self) + for i in window.indices { + XCTAssertEqual(window[i], f.window[i], accuracy: 0.000001, f.name) + } + let indices = try MiMoV26AudioFrontend.reflectFrameIndices( + samples: f.resampled.count / f.channels, + startFrame: 0, count: 1, fftSize: 960, hop: 240) + let mono = mean(MLXArray(actualWave).reshaped(f.channels, -1), axis: 0) + let frame = + take(mono, MLXArray(indices), axis: 0) * MiMoV26AudioFrontend.periodicHann(960) + let spectrum = MLXFFT.rfft(frame, n: 960) + let real = spectrum.realPart().asArray(Float.self) + let imaginary = spectrum.imaginaryPart().asArray(Float.self) + let magnitude = abs(spectrum).asArray(Float.self) + XCTAssertEqual(real.count, 481) + for i in real.indices { + XCTAssertEqual(real[i], f.spectrumReal[i], accuracy: 0.0002, f.name) + XCTAssertEqual(imaginary[i], f.spectrumImaginary[i], accuracy: 0.0002, f.name) + XCTAssertEqual(magnitude[i], f.magnitude[i], accuracy: 0.0002, f.name) + } + let bank = MiMoV26AudioFrontend.melBank(c).asArray(Float.self) + XCTAssertEqual(bank.count, f.bank.count) + for i in bank.indices { XCTAssertEqual(bank[i], f.bank[i], accuracy: 0.00002, f.name) } + let actual = try MiMoV26AudioFrontend(configuration: c).prepare( + pcm: .init(samples: f.samples, descriptor: d), plan: p, clipIndex: 0 + ).values.asArray(Float.self) + XCTAssertEqual(actual.count, f.mel.count) + for i in actual.indices { XCTAssertEqual(actual[i], f.mel[i], accuracy: 0.003, f.name) } + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26AudioInputPlanTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26AudioInputPlanTests.swift new file mode 100644 index 0000000000..0f95710e7d --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26AudioInputPlanTests.swift @@ -0,0 +1,158 @@ +import Foundation +import XCTest + +@testable import MLXLLM + +func mimoAudioInputTestLimits(working: Int = 1 << 40, block: Int = 16, tile: Int = 8) + -> MiMoV26AudioInputLimits +{ + .init( + maximumClips: 64, maximumChannels: 8, maximumSampleRate: 192000, + maximumInputSamples: 8_000_000, maximumResampledSamples: 8_000_000, + maximumResampleCoefficients: 1_000_000, + maximumMelFrames: 1_000_000, maximumSegments: 512, maximumPaddedMelFrames: 4_000_000, + maximumWorkingElements: working, frontendFrameBlockSize: block, rvqTileFrames: tile) +} +func mimoAudioInputFixtureRoot() throws -> URL { + guard let path = ProcessInfo.processInfo.environment["MIMO_V26_AUDIO_INPUT_FIXTURES"] else { + throw XCTSkip("Set MIMO_V26_AUDIO_INPUT_FIXTURES to the prepared source/oracle fixtures") + } + return URL(fileURLWithPath: path, isDirectory: true) +} +func mimoAudioInputRequireNative() throws { + guard ProcessInfo.processInfo.environment["MIMO_V26_AUDIO_INPUT_NATIVE_TESTS"] == "1" else { + throw XCTSkip("Native audio-input component tests require the explicit resource lane") + } +} + +final class MiMoV26AudioInputPlanTests: XCTestCase { + func testSelectedSidecarAndUnknownRoundTripWithoutArchitectureAlias() throws { + let root = try mimoAudioInputFixtureRoot() + let main = try JSONDecoder().decode( + MiMoV26Configuration.self, + from: Data(contentsOf: root.appendingPathComponent("main-config.json"))) + var sidecar = try JSONDecoder().decode( + [String: MiMoV26JSONValue].self, + from: Data(contentsOf: root.appendingPathComponent("sidecar-config.json"))) + sidecar["future_metadata"] = .object([ + "large": .number(Decimal(string: "9007199254740993")!), "null": .null, + ]) + let encoded = try JSONEncoder().encode(sidecar) + let config = try MiMoV26AudioInputConfiguration( + sidecarJSON: encoded, mainConfiguration: main) + XCTAssertEqual(config.hiddenSize, 1024) + XCTAssertEqual(config.layers, 24) + XCTAssertEqual(config.skipLayerIndex, 2) + XCTAssertEqual(config.codebookSizes, [1024, 1024, 256] + Array(repeating: 128, count: 17)) + XCTAssertEqual( + try JSONDecoder().decode( + [String: MiMoV26JSONValue].self, from: config.encodedSidecar()), sidecar) + sidecar["encoder_causal"] = .bool(false) + XCTAssertThrowsError( + try MiMoV26AudioInputConfiguration( + sidecarJSON: JSONEncoder().encode(sidecar), mainConfiguration: main)) + } + + func testExactLocalEdgeAndHybridSchedule() throws { + let c = try MiMoV26AudioInputConfiguration.fixture(layers: 24, lookBack: 128) + XCTAssertEqual( + (0 ..< 24).filter(c.usesLocalAttention(layer:)), Array(stride(from: 0, to: 24, by: 2))) + XCTAssertTrue(c.allowsAttention(query: 128, key: 0, layer: 0)) + XCTAssertFalse(c.allowsAttention(query: 129, key: 0, layer: 0)) + XCTAssertTrue(c.allowsAttention(query: 129, key: 1, layer: 0)) + XCTAssertTrue(c.allowsAttention(query: 129, key: 0, layer: 1)) + XCTAssertFalse(c.allowsAttention(query: 0, key: 1, layer: 1)) + } + + func testOneSecondCountsAndResampleFloat32Trim() throws { + let c = try MiMoV26AudioInputConfiguration.fixture(melBands: 128) + let plan = try MiMoV26AudioInputPlan.make( + clips: [ + .init( + sourceIdentity: "one-second", channels: 1, frameCount: 24000, sampleRate: 24000) + ], + configuration: c, limits: mimoAudioInputTestLimits()) + XCTAssertEqual(plan.melFrameCounts, [101]) + XCTAssertEqual(plan.codeFrameCounts, [26]) + XCTAssertEqual(plan.patchCounts, [7]) + XCTAssertEqual(plan.totalPatches + 2, 9) + let resample = try MiMoV26AudioResamplePlan.make( + originalRate: 44100, frames: 294068, maximumCoefficients: 1_000_000) + XCTAssertEqual(resample.originalRatio, 147) + XCTAssertEqual(resample.targetRatio, 80) + XCTAssertEqual(resample.width, 12) + XCTAssertEqual(resample.taps, 171) + XCTAssertEqual(resample.outputFrames, 160037) + XCTAssertEqual(try MiMoV26AudioChecked.ceilDivide(80 * 294068, 147), 160038) + } + + func testOriginalGroupGeometryAndOddTailDistinguishAloneFromBatch() throws { + let c = try MiMoV26AudioInputConfiguration.fixture() + let limits = mimoAudioInputTestLimits() + func plan(_ lengths: [Int]) throws -> MiMoV26AudioInputPlan { + try .makeMelInputs( + frameCounts: lengths, sourceIdentities: lengths.indices.map { "clip-\($0)" }, + configuration: c, limits: limits) + } + let alone = try plan([5]) + let peer = try plan([5, 6]) + let remainder = try plan([6005]) + XCTAssertEqual(alone.groups[0].maximumMelFrames, 5) + XCTAssertEqual(peer.groups[0].maximumMelFrames, 6) + XCTAssertEqual(alone.groups[0].maximumConvFrames, 3) + XCTAssertEqual(peer.groups[0].maximumConvFrames, 3) + XCTAssertFalse(alone.groups[0].repeatsLastBeforePooling(segment: alone.segments[0])) + XCTAssertFalse(peer.groups[0].repeatsLastBeforePooling(segment: peer.segments[0])) + XCTAssertTrue(remainder.groups[0].repeatsLastBeforePooling(segment: remainder.segments[1])) + XCTAssertEqual(remainder.segments.map(\.melFrames), [6000, 5]) + XCTAssertEqual(remainder.codeFrameCounts, [1502]) + XCTAssertNotEqual(try alone.preparationIdentityData(), try peer.preparationIdentityData()) + } + + func testConsecutiveGroupsAndOriginalItemRejoin() throws { + let c = try MiMoV26AudioInputConfiguration.fixture() + let p = try MiMoV26AudioInputPlan.makeMelInputs( + frameCounts: Array(repeating: 6000, count: 43), + sourceIdentities: (0 ..< 43).map(String.init), configuration: c, + limits: mimoAudioInputTestLimits()) + XCTAssertEqual(p.groups.count, 2) + XCTAssertEqual(p.groups[0].validMelFrames, 252000) + XCTAssertEqual(p.groups[0].segmentIndices, Array(0 ..< 42)) + XCTAssertEqual(p.groups[1].segmentIndices, [42]) + XCTAssertEqual(p.codeFrameCounts, Array(repeating: 1500, count: 43)) + let q = try MiMoV26AudioInputPlan.makeMelInputs( + frameCounts: [6001, 12001], sourceIdentities: ["a", "b"], + configuration: c, limits: mimoAudioInputTestLimits()) + XCTAssertEqual(q.codeFrameCounts, [1501, 3001]) + XCTAssertEqual(q.patchCounts, [376, 751]) + } + + func testInvalidShortInputsAndNoSilentRegroupOrClamp() throws { + let c = try MiMoV26AudioInputConfiguration.fixture() + let limits = mimoAudioInputTestLimits() + XCTAssertThrowsError( + try MiMoV26AudioInputPlan.make( + clips: [ + .init(sourceIdentity: "short", channels: 1, frameCount: 480, sampleRate: 24000) + ], configuration: c, limits: limits)) + let p = try MiMoV26AudioInputPlan.make( + clips: [ + .init(sourceIdentity: "minimum", channels: 1, frameCount: 481, sampleRate: 24000) + ], configuration: c, limits: limits) + XCTAssertEqual(p.melFrameCounts, [3]) + XCTAssertThrowsError( + try MiMoV26AudioResamplePlan.make( + originalRate: 48001, frames: 48001, maximumCoefficients: 1_000_000)) + XCTAssertThrowsError(try MiMoV26AudioChecked.product([Int.max, 2], "overflow")) + XCTAssertThrowsError( + try MiMoV26AudioInputPlan.makeMelInputs( + frameCounts: [0], sourceIdentities: ["empty"], configuration: c, limits: limits)) + XCTAssertThrowsError( + try MiMoV26AudioInputPlan.makeMelInputs( + frameCounts: [6000, 5], sourceIdentities: ["a", "b"], configuration: c, + limits: mimoAudioInputTestLimits(working: 1))) + let empty = try MiMoV26AudioInputPlan.make(clips: [], configuration: c, limits: limits) + XCTAssertTrue(empty.groups.isEmpty) + XCTAssertEqual(empty.workingElementUpperBound, 0) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26AudioInputTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26AudioInputTests.swift new file mode 100644 index 0000000000..873d76ca8b --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26AudioInputTests.swift @@ -0,0 +1,210 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLLM +@testable import MLXVLM + +private final class MiMoAudioWorkLog { + var acquired = 0 + var released = 0 + var failed: MiMoV26FailedAudioWork? +} +private final class MiMoAudioTestWorkOwner: MiMoV26AudioWorkReservation { + let log: MiMoAudioWorkLog + let plan: MiMoV26AudioInputPlan + let sourceIdentity: String + let generation: UUID + init(_ log: MiMoAudioWorkLog, plan: MiMoV26AudioInputPlan, weights: MiMoV26AudioInputWeights) { + self.log = log + self.plan = plan + sourceIdentity = weights.sourceIdentity + generation = weights.generation + log.acquired += 1 + } + func validate(plan: MiMoV26AudioInputPlan, sourceIdentity: String, generation: UUID) throws { + guard plan == self.plan, sourceIdentity == self.sourceIdentity, + generation == self.generation + else { + throw MiMoV26AudioInputError.input("test reservation binding") + } + } + func retainAfterFailedDrain(_ work: MiMoV26FailedAudioWork) { log.failed = work } + deinit { log.released += 1 } +} + +final class MiMoV26AudioInputTests: XCTestCase { + private func bundle() throws -> MiMoV26AudioInputWeights { + let oracle = try mimoAudioCodecOracle() + let c = try MiMoV26AudioInputConfiguration.fixture() + return try MiMoV26AudioTokenizerWeights.fixtureBundle( + configuration: c, weights: oracle.weights.mapValues { $0.array() }) + } + private func clip(_ name: String, frames: Int, amplitude: Float = 0.25) throws + -> MiMoV26DecodedPCM + { + let samples = (0 ..< frames).map { amplitude * Float(sin(Double($0) * 0.1)) } + return try .init( + samples: samples, + descriptor: .init( + sourceIdentity: name, channels: 1, frameCount: frames, sampleRate: 24000)) + } + + func testPCMCompositionPreservesItemOrderAndRetiresWorkOwner() throws { + try mimoAudioInputRequireNative() + let weights = try bundle() + let input = MiMoV26AudioInput(weights: weights) + let log = MiMoAudioWorkLog() + let clips = [try clip("first", frames: 481), try clip("second", frames: 1200)] + var admitted: MiMoV26AudioInputPlan? + let codes = try input.encode( + clips: clips, limits: mimoAudioInputTestLimits(), retaining: input, + authorize: { plan in + admitted = plan + return MiMoAudioTestWorkOwner(log, plan: plan, weights: weights) + }) + let plan = try XCTUnwrap(admitted) + XCTAssertEqual(plan.sourceIdentities, ["first", "second"]) + XCTAssertEqual(codes.map(\.frameCount), plan.codeFrameCounts) + XCTAssertEqual(codes.count, 2) + for code in codes { + XCTAssertEqual(code.codes.count, code.frameCount * weights.configuration.quantizers) + XCTAssertTrue(code.codes.allSatisfy { $0 >= 0 && $0 < 4 }) + } + XCTAssertEqual(log.acquired, 1) + XCTAssertEqual(log.released, 1) + } + + func testAuthorizationRefusalHappensBeforeFrontendNativeArrays() throws { + try mimoAudioInputRequireNative() + let input = MiMoV26AudioInput(weights: try bundle()) + let clips = [try clip("denied", frames: 481)] + StreamOrDevice.default.stream.synchronize() + let resources = Memory.numResources + XCTAssertThrowsError( + try input.encode( + clips: clips, limits: mimoAudioInputTestLimits(), retaining: input, + authorize: { _ in + throw MiMoV26AudioInputError.limit("intentional real-owner refusal") + })) + XCTAssertEqual(Memory.numResources, resources) + } + + func testCancellationAfterFrontendDrainReturnsNoPartialCodesAndCanRetry() throws { + try mimoAudioInputRequireNative() + let input = MiMoV26AudioInput(weights: try bundle()) + let clips = [try clip("cancel", frames: 1200)] + let log = MiMoAudioWorkLog() + var polls = 0 + XCTAssertThrowsError( + try input.encode( + clips: clips, limits: mimoAudioInputTestLimits(), retaining: input, + authorize: { plan in + MiMoAudioTestWorkOwner(log, plan: plan, weights: input.weights) + }, + isCancelled: { + polls += 1 + return polls > 8 + }) + ) { + XCTAssertEqual($0 as? MiMoV26AudioInputError, .cancelled) + } + XCTAssertEqual(log.acquired, 1) + XCTAssertEqual(log.released, 1) + let retry = try input.encode( + clips: clips, limits: mimoAudioInputTestLimits(), retaining: input, + authorize: { MiMoAudioTestWorkOwner(log, plan: $0, weights: input.weights) }) + XCTAssertEqual(retry.count, 1) + XCTAssertEqual(log.acquired, 2) + XCTAssertEqual(log.released, 2) + } + + func testSupportedNetworkReloadInvalidatesPreviouslyComposedWeights() throws { + try mimoAudioInputRequireNative() + let weights = try bundle() + let input = MiMoV26AudioInput(weights: weights) + let oracle = try mimoAudioCodecOracle() + let old = weights.generation + try weights.encoder.loadNativeNetworkWeights( + oracle.weights.filter { !$0.key.hasPrefix("encoder.quantizer.") }.mapValues { + $0.array() + }) + XCTAssertNotEqual(weights.encoder.loadedGeneration, old) + var authorizations = 0 + XCTAssertThrowsError( + try input.encode( + clips: [try clip("stale", frames: 481)], limits: mimoAudioInputTestLimits(), + retaining: input, + authorize: { plan in + authorizations += 1 + return MiMoAudioTestWorkOwner(MiMoAudioWorkLog(), plan: plan, weights: weights) + }) + ) { XCTAssertEqual($0 as? MiMoV26AudioInputError, .weightsNotLoaded) } + XCTAssertEqual(authorizations, 0) + } + + func testFailedDrainRetainsOriginalRootsLoadedOwnerAndLeaseUntilRecovery() throws { + try mimoAudioInputRequireNative() + enum Failure: Error { case injected } + let weights = try bundle() + let clips = [try clip("quarantine", frames: 481)] + let plan = try MiMoV26AudioInputPlan.make( + clips: clips.map(\.descriptor), configuration: weights.configuration, + limits: mimoAudioInputTestLimits()) + let log = MiMoAudioWorkLog() + var source: NSObject? = NSObject() + weak var weakSource = source + var root: MLXArray? = MLXArray([Float(1), 2]) + weak var weakRoot = root + var lease: MiMoAudioTestWorkOwner? = .init(log, plan: plan, weights: weights) + var work: MiMoV26FailedAudioWork? = try .init( + weights: weights, clips: clips, plan: plan, sourceOwner: source!, reservation: lease!) + work!.track([root!]) + source = nil + root = nil + lease = nil + var invalidated = false + XCTAssertThrowsError( + try work!.drain( + invalidate: { invalidated = true }, synchronize: { throw Failure.injected }) + ) { + XCTAssertEqual($0 as? MiMoV26AudioWorkFailure, .drainFailed) + } + work = nil + XCTAssertTrue(invalidated) + XCTAssertEqual(log.failed?.retainedRootCount, 1) + XCTAssertNotNil(weakSource) + XCTAssertNotNil(weakRoot) + XCTAssertEqual(log.released, 0) + XCTAssertThrowsError( + try log.failed!.verifyRecoveryDrain(synchronize: { throw Failure.injected })) + XCTAssertNotNil(weakSource) + XCTAssertNotNil(weakRoot) + XCTAssertEqual(log.released, 0) + try log.failed!.recoverAndReleaseAfterDrain() + XCTAssertNil(weakSource) + XCTAssertNil(weakRoot) + XCTAssertEqual(log.released, 1) + XCTAssertThrowsError(try log.failed!.recoverAndReleaseAfterDrain()) + XCTAssertEqual(log.released, 1) + log.failed = nil + } + + func testAudioWorkReservationBindsFullPlanSourceAndGeneration() throws { + try mimoAudioInputRequireNative() + let weights = try bundle() + let clips = [try clip("bound", frames: 481)] + let plan = try MiMoV26AudioInputPlan.make( + clips: clips.map(\.descriptor), configuration: weights.configuration, + limits: mimoAudioInputTestLimits()) + let lease = MiMoAudioTestWorkOwner(MiMoAudioWorkLog(), plan: plan, weights: weights) + XCTAssertThrowsError( + try lease.validate( + plan: plan, sourceIdentity: "foreign", generation: weights.generation)) + XCTAssertThrowsError( + try lease.validate( + plan: plan, sourceIdentity: weights.sourceIdentity, generation: UUID())) + try lease.validate( + plan: plan, sourceIdentity: weights.sourceIdentity, generation: weights.generation) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26AudioPatchTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26AudioPatchTests.swift new file mode 100644 index 0000000000..23c85f660d --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26AudioPatchTests.swift @@ -0,0 +1,282 @@ +import Foundation +import MLX +import MLXLLM +import MLXNN +import MLXVLM +import XCTest + +/// Discrete-code component only. Native execution requires root's owned lane. +final class MiMoV26AudioPatchTests: XCTestCase { + private let limits = MiMoV26AudioPatchLimits( + maximumClips: 8, maximumFrames: 64, + maximumPatches: 32, maximumWorkingElements: 1_000_000) + + func testCPUPlanMatchesPerItemPaddingAndOrder() throws { + let corpus = try loadCorpus() + let c = try configuration(corpus) + XCTAssertEqual(c.rawFields["speech_vocab_size"], .string("7")) + XCTAssertEqual(c.rawFields["speech_zeroemb_idx"], .string("6")) + XCTAssertEqual(c.channels, 20) + for fixture in corpus.cases { + let p = try MiMoV26AudioPatchPlan.make( + clips: clips(fixture), configuration: c, limits: limits) + XCTAssertEqual(p.groupedCodes, fixture.groupedCodes, fixture.id) + XCTAssertEqual( + p.clipPatchRanges.map { [$0.lowerBound, $0.upperBound] }, fixture.clipPatchRanges, + fixture.id) + XCTAssertEqual(p.patchCount, fixture.outputShape[0], fixture.id) + XCTAssertEqual(p.originalFrameCount, fixture.clips.reduce(0) { $0 + $1.frameCount }) + } + let empty = try MiMoV26AudioPatchPlan.make( + clips: [], configuration: c, + limits: .init( + maximumClips: 0, maximumFrames: 0, maximumPatches: 0, maximumWorkingElements: 0)) + XCTAssertEqual(empty.groupedCodes, []) + XCTAssertEqual(empty.clipPatchRanges, []) + XCTAssertEqual(empty.workingElements, 0) + } + + func testCPUPreflightRejectsBadNamespacesShapesAndBounds() throws { + let c = try configuration(loadCorpus()) + let valid = MiMoV26AudioCodeClip(codes: [Int32](repeating: 0, count: 20), frameCount: 1) + let malformed = [ + MiMoV26AudioCodeClip(codes: [], frameCount: 0), + .init(codes: [], frameCount: -1), .init(codes: [], frameCount: Int.max), + .init(codes: [0], frameCount: 1), + .init(codes: [Int32](repeating: -1, count: 20), frameCount: 1), + .init(codes: [Int32](repeating: 7, count: 20), frameCount: 1), + // A text audio-placeholder ID is not a speech codebook index. + .init(codes: [Int32](repeating: 151669, count: 20), frameCount: 1), + ] + for clip in malformed { + XCTAssertThrowsError( + try MiMoV26AudioPatchPlan.make( + clips: [valid, clip], configuration: c, limits: limits)) + } + for restricted in [ + MiMoV26AudioPatchLimits( + maximumClips: 0, maximumFrames: 64, maximumPatches: 32, + maximumWorkingElements: 1_000_000), + .init( + maximumClips: 8, maximumFrames: 0, maximumPatches: 32, + maximumWorkingElements: 1_000_000), + .init( + maximumClips: 8, maximumFrames: 64, maximumPatches: 0, + maximumWorkingElements: 1_000_000), + .init( + maximumClips: 8, maximumFrames: 64, maximumPatches: 32, maximumWorkingElements: 0), + .init( + maximumClips: -1, maximumFrames: 64, maximumPatches: 32, + maximumWorkingElements: 1_000_000), + ] { + XCTAssertThrowsError( + try MiMoV26AudioPatchPlan.make(clips: [valid], configuration: c, limits: restricted) + ) + } + let p = try MiMoV26AudioPatchPlan.make(clips: [valid], configuration: c, limits: limits) + XCTAssertNoThrow( + try MiMoV26AudioPatchPlan.make( + clips: [valid], configuration: c, + limits: .init( + maximumClips: 1, maximumFrames: 1, maximumPatches: 1, + maximumWorkingElements: p.workingElements))) + XCTAssertThrowsError( + try MiMoV26AudioPatchPlan.make( + clips: [valid], configuration: c, + limits: .init( + maximumClips: 1, maximumFrames: 1, maximumPatches: 1, + maximumWorkingElements: p.workingElements - 1))) + } + + func testCPURefusesUnsupportedReferencePolicy() throws { + let corpus = try loadCorpus() + for (key, value) in [ + ("input_full_attention", MiMoV26JSONValue.bool(false)), ("add_post_norm", .bool(false)), + ("projection_layers", .number(1)), + ("partial_rotary_factor", .number(Decimal(string: "0.5")!)), + ("input_local_hidden_dropout", .number(Decimal(string: "0.1")!)), + ("input_local_layers", .number(7)), + ] { + var fields = try target(corpus).rawFields + guard case .object(var audio) = fields["audio_config"] else { + return XCTFail("missing audio") + } + audio[key] = value + fields["audio_config"] = .object(audio) + let changed = try MiMoV26Configuration(rawFields: fields) + XCTAssertThrowsError( + try MiMoV26AudioPatchEncoder.expectedTensorShapes( + configuration: XCTUnwrap(changed.audio)), key) + } + } + + func testAll95ArtifactTensorShapesAndDTypeReceipt() throws { + guard let path = ProcessInfo.processInfo.environment["MIMO_V26_OFFICIAL_CONFIG"], + let receiptPath = ProcessInfo.processInfo.environment["MIMO_V26_AUDIO_PATCH_COVERAGE"] + else { + throw XCTSkip( + "Set official config and audio-patch coverage paths for the95-tensor header gate") + } + let t = try JSONDecoder().decode( + MiMoV26Configuration.self, from: Data(contentsOf: URL(fileURLWithPath: path))) + let c = try XCTUnwrap(t.audio) + let expected = try MiMoV26AudioPatchEncoder.expectedTensorShapes(configuration: c) + let receipt = try JSONDecoder().decode( + Coverage.self, from: Data(contentsOf: URL(fileURLWithPath: receiptPath))) + XCTAssertEqual(expected.count, 95) + XCTAssertEqual(expected, receipt.expectedShapes) + XCTAssertEqual(expected.keys.filter { $0.hasPrefix("speech_embeddings.") }.count, 20) + XCTAssertEqual(expected.keys.filter { $0.hasPrefix("audio_encoder.") }.count, 75) + XCTAssertEqual(expected["audio_encoder.projection.mlp.0.weight"], [16384, 4096]) + XCTAssertEqual(expected["audio_encoder.projection.mlp.2.weight"], [4096, 16384]) + XCTAssertNil(expected["audio_encoder.input_local_transformer.embed_tokens.weight"]) + XCTAssertNil(expected["audio_encoder.projection.mlp.0.bias"]) + XCTAssertEqual(c.rawFields["speech_vocab_size"], .string("1280")) + XCTAssertEqual(c.rawFields["speech_zeroemb_idx"], .string("1024")) + } + + func testNativeTinyEncoderAgainstIndependentScalarOracle() throws { + try requireNativeLane() + let corpus = try loadCorpus() + let model = try MiMoV26AudioPatchEncoder(configuration: configuration(corpus)) + try model.loadNativeWeights(arrays(corpus), expectedDType: .float32) + XCTAssertEqual(corpus.cases.count, 6) + for fixture in corpus.cases { + let output = try model.forward(clips: clips(fixture), limits: limits) + eval(output.features) + XCTAssertEqual(output.features.shape, fixture.outputShape, fixture.id) + XCTAssertEqual( + output.clipPatchRanges.map { [$0.lowerBound, $0.upperBound] }, + fixture.clipPatchRanges) + // The pinned Swift MLX asArray bridge computes physicalSize using + // max(shape*stride), which is nonzero for[0,width], then wraps a + // nil zero-allocation pointer. Empty model output has no bytes to + // read: assert its logical size instead, without skipping the case. + XCTAssertEqual(output.features.size, fixture.expected.count, fixture.id) + let actual: [Float] = + output.features.size == 0 + ? [] : output.features.asType(.float32).asArray(Float.self) + XCTAssertEqual(actual.count, fixture.expected.count) + for (a, b) in zip(actual, fixture.expected) { + XCTAssertTrue(a.isFinite) + XCTAssertEqual(a, b, accuracy: 1e-4, fixture.id) + } + if fixture.id == "three-frame" { + XCTAssertGreaterThan(maxDifference(actual, fixture.causalCounterfactual), 0.01) + XCTAssertGreaterThan( + maxDifference(actual, fixture.wrongChannelCounterfactual), 0.01) + } + if fixture.id == "padding-code" { + XCTAssertGreaterThan(maxDifference(actual, fixture.zeroPaddingCounterfactual), 0.1) + } + } + // Request state and repeat-last padding cannot leak between calls. + let first = try XCTUnwrap(corpus.cases.first { $0.id == "three-frame" }) + let mixed = try XCTUnwrap(corpus.cases.first { $0.id == "two-segments" }) + let a = try model.forward(clips: clips(first), limits: limits).features + let b = try model.forward(clips: clips(mixed), limits: limits).features + eval(a, b) + for (value, expected) in zip(a.asArray(Float.self), b.asArray(Float.self).prefix(8)) { + XCTAssertEqual(value, expected, accuracy: 1e-5) + } + } + + func testNativeStrictLoadingAndMutationInvalidation() throws { + try requireNativeLane() + let corpus = try loadCorpus() + let model = try MiMoV26AudioPatchEncoder(configuration: configuration(corpus)) + let weights = arrays(corpus) + let fixture = try XCTUnwrap(corpus.cases.first) + XCTAssertThrowsError(try model.forward(clips: clips(fixture), limits: limits)) { + XCTAssertEqual($0 as? MiMoV26AudioPatchError, .weightsNotLoaded) + } + var missing = weights + missing.removeValue(forKey: "speech_embeddings.19.weight") + XCTAssertThrowsError(try model.loadNativeWeights(missing, expectedDType: .float32)) + for extra in [ + "audio_encoder.input_local_transformer.embed_tokens.weight", + "audio_encoder.projection.mlp.0.bias", + "speech_embeddings.20.weight", "audio_tokenizer.encoder.weight", + "model.embed_tokens.weight", + ] { + var changed = weights + changed[extra] = MLXArray.zeros([4]) + XCTAssertThrowsError( + try model.loadNativeWeights(changed, expectedDType: .float32), extra) + } + var badShape = weights + badShape["speech_embeddings.0.weight"] = MLXArray.zeros([7, 3]) + XCTAssertThrowsError(try model.loadNativeWeights(badShape, expectedDType: .float32)) + var badDType = weights + badDType["speech_embeddings.0.weight"] = weights["speech_embeddings.0.weight"]!.asType( + .int32) + XCTAssertThrowsError(try model.loadNativeWeights(badDType, expectedDType: .float32)) + try model.loadNativeWeights(weights, expectedDType: .float32) + XCTAssertThrowsError(try model.loadNativeWeights(missing, expectedDType: .float32)) + XCTAssertThrowsError(try model.forward(clips: clips(fixture), limits: limits)) { + XCTAssertEqual($0 as? MiMoV26AudioPatchError, .weightsNotLoaded) + } + try model.loadNativeWeights(weights, expectedDType: .float32) + try model.update(parameters: model.parameters(), verify: .all) + XCTAssertThrowsError(try model.forward(clips: clips(fixture), limits: limits)) { + XCTAssertEqual($0 as? MiMoV26AudioPatchError, .weightsNotLoaded) + } + try model.loadNativeWeights(weights, expectedDType: .float32) + eval(try model.forward(clips: clips(fixture), limits: limits).features) + } + + private func requireNativeLane() throws { + guard ProcessInfo.processInfo.environment["MIMO_V26_AUDIO_PATCH_NATIVE_TESTS"] == "1" else { + throw XCTSkip( + "Requires an exclusive native execution lane and MIMO_V26_AUDIO_PATCH_NATIVE_TESTS=1" + ) + } + } + private func loadCorpus() throws -> Corpus { + guard let path = ProcessInfo.processInfo.environment["MIMO_V26_AUDIO_PATCH_ORACLE"] else { + throw XCTSkip("Set MIMO_V26_AUDIO_PATCH_ORACLE to the generated scalar fixture") + } + return try JSONDecoder().decode( + Corpus.self, from: Data(contentsOf: URL(fileURLWithPath: path))) + } + private func target(_ corpus: Corpus) throws -> MiMoV26Configuration { + try JSONDecoder().decode( + MiMoV26Configuration.self, from: JSONEncoder().encode(corpus.configuration)) + } + private func configuration(_ corpus: Corpus) throws -> MiMoV26AudioConfiguration { + try XCTUnwrap(target(corpus).audio) + } + private func clips(_ fixture: Case) -> [MiMoV26AudioCodeClip] { + fixture.clips.map { .init(codes: $0.codes, frameCount: $0.frameCount) } + } + private func arrays(_ corpus: Corpus) -> [String: MLXArray] { + corpus.weights.mapValues { MLXArray($0.values).reshaped($0.shape) } + } + private func maxDifference(_ a: [Float], _ b: [Float]) -> Float { + zip(a, b).map { abs($0 - $1) }.max() ?? 0 + } + private struct Coverage: Decodable { let expectedShapes: [String: [Int]] } + private struct Clip: Decodable { + let frameCount: Int + let codes: [Int32] + } + private struct Tensor: Decodable { + let shape: [Int] + let values: [Float] + } + private struct Case: Decodable { + let id: String + let clips: [Clip] + let groupedCodes: [Int32] + let clipPatchRanges: [[Int]] + let outputShape: [Int] + let expected, causalCounterfactual, zeroPaddingCounterfactual, + wrongChannelCounterfactual: [Float] + } + private struct Corpus: Decodable { + let schemaVersion: Int + let configuration: MiMoV26JSONValue + let weights: [String: Tensor] + let cases: [Case] + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26AudioSidecarFileTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26AudioSidecarFileTests.swift new file mode 100644 index 0000000000..e170b289dc --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26AudioSidecarFileTests.swift @@ -0,0 +1,97 @@ +import Foundation +import XCTest + +@testable import MLXVLM + +final class MiMoV26AudioSidecarFileTests: XCTestCase { + private func temporary(_ body: (URL) throws -> Void) throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "mimo-audio-sidecar-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: root) } + try body(root) + } + + func testHeaderClosureRejectsHolesOverlapsTrailingAndDuplicateKeys() throws { + func parse(_ value: String, _ count: Int = 8) throws -> MiMoV26AudioSidecarHeader { + try .parse(Data(value.utf8), tensorBytes: count) + } + let good = + "{\"a\":{\"dtype\":\"BF16\",\"shape\":[2],\"data_offsets\":[0,4]},\"b\":{\"dtype\":\"F32\",\"shape\":[1],\"data_offsets\":[4,8]}}" + XCTAssertEqual(try parse(good).tensors.count, 2) + XCTAssertThrowsError(try parse(good.replacingOccurrences(of: "[4,8]", with: "[3,7]"))) + XCTAssertThrowsError(try parse(good.replacingOccurrences(of: "[4,8]", with: "[5,9]"))) + XCTAssertThrowsError(try parse(good, 9)) + XCTAssertThrowsError(try parse(good.replacingOccurrences(of: "\"b\":", with: "\"a\":"))) + XCTAssertThrowsError(try parse(good.replacingOccurrences(of: "\"BF16\"", with: "\"F64\""))) + XCTAssertThrowsError(try parse(good.replacingOccurrences(of: "[2]", with: "[0]"))) + } + + func testFullByteDigestIncludesUnusedSuffixAndReadsRemainBounded() throws { + try temporary { root in + let path = root.appendingPathComponent("payload") + let original = Data([1, 2, 3, 4, 91, 92, 93, 94]) + try original.write(to: path) + let file = try MiMoV26AudioSidecarDescriptor(url: path, directory: false) + var completed: [Int] = [] + XCTAssertEqual( + try file.authenticate( + expected: mimoAudioDigest(original), isCancelled: { false }, + checkpoint: { completed.append($0) }), mimoAudioDigest(original)) + XCTAssertEqual(completed, [0, 8]) + XCTAssertEqual( + try file.read(offset: 2, count: 3, maximum: 3, isCancelled: { false }), + Data([3, 4, 91])) + XCTAssertThrowsError( + try file.read(offset: 0, count: 8, maximum: 4, isCancelled: { false })) + XCTAssertThrowsError( + try file.read(offset: 7, count: 2, maximum: 2, isCancelled: { false })) + // A fresh source with changed unused bytes must fail the old full hash. + try Data([1, 2, 3, 4, 91, 92, 93, 95]).write(to: path) + let replaced = try MiMoV26AudioSidecarDescriptor(url: path, directory: false) + XCTAssertThrowsError( + try replaced.authenticate( + expected: mimoAudioDigest(original), + isCancelled: { false }, checkpoint: { _ in }) + ) { + XCTAssertEqual($0 as? MiMoV26AudioSidecarError, .wrongPayload) + } + XCTAssertThrowsError(try file.validate()) + } + } + + func testSymlinkAndReplacedInodeRefuseWithoutReopeningAuthenticatedSource() throws { + try temporary { root in + let payload = root.appendingPathComponent("payload") + try Data([1, 2, 3, 4]).write(to: payload) + let link = root.appendingPathComponent("link") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: payload) + XCTAssertThrowsError(try MiMoV26AudioSidecarDescriptor(url: link, directory: false)) + let held = try MiMoV26AudioSidecarDescriptor(url: payload, directory: false) + try FileManager.default.moveItem(at: payload, to: root.appendingPathComponent("old")) + try Data([1, 2, 3, 4]).write(to: payload) + XCTAssertThrowsError( + try held.read(offset: 0, count: 4, maximum: 4, isCancelled: { false }) + ) { + XCTAssertEqual($0 as? MiMoV26AudioSidecarError, .changedObject) + } + } + } + + func testCancellationCannotPublishDigest() throws { + try temporary { root in + let path = root.appendingPathComponent("payload") + let data = Data(repeating: 7, count: 2 << 20) + try data.write(to: path) + let held = try MiMoV26AudioSidecarDescriptor(url: path, directory: false) + XCTAssertThrowsError( + try held.authenticate( + expected: mimoAudioDigest(data), + isCancelled: { true }, + checkpoint: { _ in XCTFail("cancelled source reached checkpoint") }) + ) { + XCTAssertEqual($0 as? MiMoV26AudioSidecarError, .cancelled) + } + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26AudioSidecarLoadTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26AudioSidecarLoadTests.swift new file mode 100644 index 0000000000..c3614988ef --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26AudioSidecarLoadTests.swift @@ -0,0 +1,125 @@ +import CryptoKit +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import XCTest + +@testable import MLXVLM + +/// Component tests only. The native runner must separately own the real +/// physical lane/budget. TestReservation exercises SDK binding, not host C/M. +private final class AudioLoadTestReservation: MiMoV26AudioSidecarLoadReservation { + let request: MiMoV26AudioSidecarLoadRequest + let reservedLoadBytes: UInt64 + var revoked = false + init(_ request: MiMoV26AudioSidecarLoadRequest, bytes: UInt64? = nil) { + self.request = request + reservedLoadBytes = bytes ?? request.requiredLoadBytes + } + func validateActive() throws { + if revoked { throw MiMoV26AudioSidecarError.invalidatedOwner } + } +} + +final class MiMoV26AudioSidecarLoadTests: XCTestCase { + private enum Fault: Error { case injected } + private func fixture() throws -> MiMoV26AudioSidecarLoadSession { + guard ProcessInfo.processInfo.environment["MIMO_V26_AUDIO_SIDECAR_NATIVE_TESTS"] == "1", + let path = ProcessInfo.processInfo.environment["MIMO_V26_AUDIO_SIDECAR_FIXTURE_ROOT"] + else { + throw XCTSkip("Requires owned native lane and an immutable selected sidecar fixture") + } + let root = URL(fileURLWithPath: path) + let handle = try FileHandle(forReadingFrom: root.appendingPathComponent("config.json")) + defer { try? handle.close() } + let bytes = try XCTUnwrap(handle.read(upToCount: (1 << 20) + 1)) + guard bytes.count <= 1 << 20 else { throw MiMoV26AudioSidecarError.invalidConfiguration } + return try .init( + root: root, + mainConfiguration: JSONDecoder().decode(MiMoV26Configuration.self, from: bytes), + mainConfigurationSHA256: mimoAudioDigest(bytes)) + } + + func testSelectedSubsetMaterializesWithAuthenticatedWholeFileAndExactGeneration() throws { + let session = try fixture() + let scope = NativeConstructionScope() + defer { if scope.snapshot.isRetainedFault { _ = Unmanaged.passRetained(scope) } } + let permit = AudioLoadTestReservation(session.request) + var authenticatedBeforeFirstTensor = false + let loaded = try session.load( + reservation: permit, retaining: scope, + progress: { progress in + if progress.phase == .authenticated { + XCTAssertEqual(progress.authenticatedFileBytes, 1_872_618_384) + authenticatedBeforeFirstTensor = true + } + if progress.phase == .inputMaterialization { + XCTAssertTrue(authenticatedBeforeFirstTensor) + } + }) + try loaded.validate() + XCTAssertEqual(loaded.receipt.materializedInputTensors, 389) + XCTAssertEqual(loaded.receipt.materializedInputBytes, 634_204_160) + XCTAssertEqual(loaded.receipt.request.unusedTensorCount, 439) + XCTAssertEqual(loaded.receipt.request.unusedStoredBytes, 1_238_321_176) + XCTAssertEqual(loaded.receipt.runtimeRoots, 389) + XCTAssertEqual(loaded.receipt.codecGeneration, loaded.codec.generation) + guard case .completed(let receipt) = scope.snapshot.disposition else { + return XCTFail("No actual construction completion") + } + try scope.validate(receipt) + XCTAssertEqual(receipt.completion, .capturedStreamsCompleted) + XCTAssertThrowsError(try session.load(reservation: permit, retaining: scope)) + } + + func testInsufficientPermitFailsBeforeFullPayloadAuthenticationOrNativeSubmission() throws { + let session = try fixture() + let scope = NativeConstructionScope() + let permit = AudioLoadTestReservation(session.request, bytes: 0) + XCTAssertThrowsError( + try session.load( + reservation: permit, retaining: scope, + progress: { _ in XCTFail("Invalid permit reached load progress") }) + ) { + XCTAssertEqual($0 as? MiMoV26AudioSidecarError, .insufficientReservation) + } + guard case .completed(let receipt) = scope.snapshot.disposition else { + return XCTFail("No actual no-submission completion") + } + try scope.validate(receipt) + XCTAssertEqual(receipt.completion, .noNativeSubmission) + } + + func testPartialFailureRetainsSourceAndNativeRootsWhenFenceFails() throws { + guard ProcessInfo.processInfo.environment["MIMO_V26_AUDIO_SIDECAR_FAULT_TEST"] == "1" else { + throw XCTSkip("Retained-fault selector must run alone in its owned process") + } + let session = try fixture() + let scope = NativeConstructionScope() + defer { if scope.snapshot.isRetainedFault { _ = Unmanaged.passRetained(scope) } } + let permit = AudioLoadTestReservation(session.request) + scope.testingBoundary = { name, _ in + if name == "audioSidecar.sourceMaterialized" { throw Fault.injected } + } + scope.testingBeforeFence = { _ in throw Fault.injected } + XCTAssertThrowsError(try session.load(reservation: permit, retaining: scope)) + XCTAssertTrue(scope.snapshot.isRetainedFault) + XCTAssertGreaterThan(scope.snapshot.retainedArrayCount, 0) + XCTAssertGreaterThan(scope.snapshot.retainedOwnerCount, 0) + XCTAssertThrowsError(try session.load(reservation: permit, retaining: scope)) + } + + func testRawBF16DataInitializerPreservesStorageRatherThanConvertingUInt16Numerically() throws { + guard ProcessInfo.processInfo.environment["MIMO_V26_AUDIO_SIDECAR_NATIVE_TESTS"] == "1" + else { + throw XCTSkip("Requires owned native lane") + } + let bits: [UInt16] = [0, 0x8000, 0x3f80, 0xbf80, 0x3f81, 0x0080, 0x0040] + let data = bits.withUnsafeBytes { Data($0) } + let actual = MLXArray(data, [bits.count], dtype: .bfloat16) + eval(actual) + XCTAssertEqual(actual.view(dtype: .uint16).asArray(UInt16.self), bits) + XCTAssertNotEqual(actual.asType(.float32).asArray(Float.self), bits.map(Float.init)) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26AudioTokenizerEncoderTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26AudioTokenizerEncoderTests.swift new file mode 100644 index 0000000000..f700626fec --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26AudioTokenizerEncoderTests.swift @@ -0,0 +1,231 @@ +import Foundation +import MLX +import MLXNN +import XCTest + +@testable import MLXLLM +@testable import MLXVLM + +struct MiMoAudioOracleTensor: Decodable { + let shape: [Int] + let dtype: String + let data: [Float] + func array() -> MLXArray { + MLXArray(data).reshaped(shape).asType(dtype == "BF16" ? .bfloat16 : .float32) + } +} +struct MiMoAudioCodecOracle: Decodable { + struct Case: Decodable { + let name: String + let mels: [MiMoAudioOracleTensor] + let codes: [[Int32]] + let traces: [String: MiMoAudioOracleTensor] + } + let sourceSHA256: String + let weights: [String: MiMoAudioOracleTensor] + let cases: [Case] +} +func mimoAudioCodecOracle() throws -> MiMoAudioCodecOracle { + let root = try mimoAudioInputFixtureRoot() + let value = try JSONDecoder().decode( + MiMoAudioCodecOracle.self, + from: Data(contentsOf: root.appendingPathComponent("codec-oracle.json"))) + XCTAssertEqual( + value.sourceSHA256, "a8c3cb3aae473bcc15f023010547c919f15eba6546e6ed7efb61a8937b12f3ad") + return value +} + +final class MiMoV26AudioTokenizerEncoderTests: XCTestCase { + func testStrictCheckpointIndexedPoolLoadsRealArraysWithoutExtraParameters() throws { + try Device.withDefaultDevice(.cpu) { + let c = try MiMoV26AudioInputConfiguration.fixture() + var source = MiMoV26AudioTokenizerWeights.networkSourceShapes(configuration: c) + .mapValues { MLXArray.zeros($0, dtype: .bfloat16, stream: .cpu) } + let name = "encoder.down_sample_layer.0.weight" + let width = c.hiddenSize + let values = (0 ..< width * width * 2).map { Float($0) } + source[name] = MLXArray(values).reshaped(width, width, 2, stream: .cpu) + .asType(.bfloat16, stream: .cpu) + let encoder = MiMoV26AudioTokenizerEncoder(configuration: c) + // This is the normal strict unflatten/update path that rejected + // the old module-wrapped numeric key as incompatibleItems. + try encoder.loadNativeNetworkWeights(source) + XCTAssertNotNil(encoder.loadedGeneration) + let installed = Dictionary(uniqueKeysWithValues: encoder.parameters().flattened()) + XCTAssertEqual(Set(installed.keys), Set(source.keys)) + XCTAssertEqual(installed.count, 69) + XCTAssertEqual( + installed.keys.filter { $0.hasPrefix("encoder.down_sample_layer.") }, [name]) + let pool = try XCTUnwrap(installed[name]) + XCTAssertEqual(pool.shape, [width, 2, width]) + XCTAssertEqual(pool.dtype, .bfloat16) + // Independent source-layout oracle: [out, in, kernel] -> [out, kernel, in]. + let expected = (0 ..< width).flatMap { output in + (0 ..< 2).flatMap { kernel in + (0 ..< width).map { input in values[(output * width + input) * 2 + kernel] } + } + } + XCTAssertEqual(pool.asType(.float32, stream: .cpu).asArray(Float.self), expected) + } + } + + func testStrictCheckpointPoolRejectsMissingExtraWrongShapeAndWrongDType() throws { + try Device.withDefaultDevice(.cpu) { + let c = try MiMoV26AudioInputConfiguration.fixture() + let source = MiMoV26AudioTokenizerWeights.networkSourceShapes(configuration: c) + .mapValues { MLXArray.zeros($0, dtype: .bfloat16, stream: .cpu) } + let name = "encoder.down_sample_layer.0.weight" + let encoder = MiMoV26AudioTokenizerEncoder(configuration: c) + try encoder.loadNativeNetworkWeights(source) + var missing = source + missing.removeValue(forKey: name) + XCTAssertThrowsError(try encoder.loadNativeNetworkWeights(missing)) { + XCTAssertEqual($0 as? MiMoV26AudioInputError, .weights("network tensor closure")) + } + XCTAssertNil(encoder.loadedGeneration) + var extra = source + extra["encoder.down_sample_layer.1.weight"] = source[name] + XCTAssertThrowsError(try encoder.loadNativeNetworkWeights(extra)) { + XCTAssertEqual($0 as? MiMoV26AudioInputError, .weights("network tensor closure")) + } + var wrongShape = source + wrongShape[name] = MLXArray.zeros( + [c.hiddenSize, 2, c.hiddenSize], dtype: .bfloat16, stream: .cpu) + XCTAssertThrowsError(try encoder.loadNativeNetworkWeights(wrongShape)) { + XCTAssertEqual($0 as? MiMoV26AudioInputError, .weights(name)) + } + var wrongDType = source + wrongDType[name] = source[name]!.asType(.float32, stream: .cpu) + XCTAssertThrowsError(try encoder.loadNativeNetworkWeights(wrongDType)) { + XCTAssertEqual($0 as? MiMoV26AudioInputError, .weights(name)) + } + XCTAssertNil(encoder.loadedGeneration) + try encoder.loadNativeNetworkWeights(source) + XCTAssertNotNil(encoder.loadedGeneration) + } + } + + func testCompleteSidecarMetadataClosureAndNoInventedKeyBias() throws { + let root = try mimoAudioInputFixtureRoot() + let main = try JSONDecoder().decode( + MiMoV26Configuration.self, + from: Data(contentsOf: root.appendingPathComponent("main-config.json"))) + let c = try MiMoV26AudioInputConfiguration( + sidecarJSON: Data(contentsOf: root.appendingPathComponent("sidecar-config.json")), + mainConfiguration: main) + let descriptors = try JSONDecoder().decode( + [String: MiMoV26AudioTensorDescriptor].self, + from: Data(contentsOf: root.appendingPathComponent("sidecar-descriptors.json"))) + let plan = try MiMoV26AudioTokenizerWeights.preflight( + descriptors: descriptors, configuration: c, + sourcePayloadSHA256: MiMoV26AudioTokenizerWeights.selectedPayloadSHA256) + XCTAssertEqual(plan.requiredInputNames.count, 389) + XCTAssertEqual(plan.inputStoredBytes, 634_204_160) + XCTAssertEqual(plan.retainedUnusedStoredBytes, 1_238_321_176) + XCTAssertFalse(plan.requiredInputNames.contains { $0.hasPrefix("decoder.") }) + XCTAssertFalse( + plan.requiredInputNames.contains { + $0.hasSuffix("k_proj.bias") || $0.contains("inv_freq") + }) + var incomplete = descriptors + incomplete.removeValue(forKey: "encoder.quantizer.vq.layers.0._codebook.embed") + XCTAssertThrowsError( + try MiMoV26AudioTokenizerWeights.preflight( + descriptors: incomplete, configuration: c, + sourcePayloadSHA256: plan.sourcePayloadSHA256)) + var wrong = descriptors + wrong["encoder.conv1.weight"] = .init( + shape: [1024, 128, 3], dtype: .float32, byteCount: 1_572_864) + XCTAssertThrowsError( + try MiMoV26AudioTokenizerWeights.preflight( + descriptors: wrong, configuration: c, sourcePayloadSHA256: plan.sourcePayloadSHA256) + ) + } + + func testUnchangedHFOracleAllIntermediatesAndOriginalBatchGeometry() throws { + try mimoAudioInputRequireNative() + let oracle = try mimoAudioCodecOracle() + let c = try MiMoV26AudioInputConfiguration.fixture() + let bundle = try MiMoV26AudioTokenizerWeights.fixtureBundle( + configuration: c, weights: oracle.weights.mapValues { $0.array() }) + XCTAssertEqual(bundle.encoder.parameters().flattened().count, 69) + XCTAssertGreaterThanOrEqual(oracle.cases.count, 5) + var capturedConv2: [String: [Float]] = [:] + for item in oracle.cases { + let plan = try MiMoV26AudioInputPlan.makeMelInputs( + frameCounts: item.mels.map { $0.shape[0] }, + sourceIdentities: item.mels.indices.map { "clip-\($0)" }, configuration: c, + limits: mimoAudioInputTestLimits()) + var traces: [String: MLXArray] = [:] + let output = try bundle.encoder.encode( + item.mels.map { $0.array() }, plan: plan, isCancelled: { false } + ) { traces[$0] = $1 } + eval(Array(traces.values) + [output.features]) + XCTAssertEqual(Set(traces.keys), Set(item.traces.keys), item.name) + for (name, expected) in item.traces { + let actual = try XCTUnwrap(traces[name]) + XCTAssertEqual(actual.shape, expected.shape, item.name + ":" + name) + let values = actual.asType(.float32).asArray(Float.self) + XCTAssertEqual(values.count, expected.data.count) + for i in values.indices { + XCTAssertEqual( + values[i], expected.data[i], accuracy: 0.04, item.name + ":" + name) + } + } + let quantized = try bundle.quantizer.quantize( + features: output.features, frameCounts: plan.codeFrameCounts, tileFrames: 2) + eval(quantized.codes, quantized.allFinite) + XCTAssertTrue(quantized.allFinite.item(Bool.self)) + XCTAssertEqual( + quantized.codes.asArray(Int32.self), item.codes.flatMap { $0 }, item.name) + capturedConv2[item.name] = traces["group.0.conv2"]!.asType(.float32).asArray(Float.self) + } + // Same short input, different padded peer extent; do not turn the + // unpadded serial variant into the oracle for the selected profile. + let alone = try XCTUnwrap(capturedConv2["alone5"]) + let mixed = try XCTUnwrap(capturedConv2["mixed5_6"]) + XCTAssertNotEqual(alone, Array(mixed.prefix(alone.count))) + } + + func testRoundedRotaryAndNoLearnedConstantParameter() throws { + try mimoAudioInputRequireNative() + let c = try MiMoV26AudioInputConfiguration.fixture(hiddenSize: 64, heads: 1) + let rope = MiMoV26AudioTokenizerEncoder.rotary(configuration: c, positions: [0, 128, 2999]) + eval(rope.inverse, rope.cosine, rope.sine) + XCTAssertEqual(rope.inverse.asArray(Float.self)[1], 0.75) + XCTAssertEqual(rope.cosine.dtype, .bfloat16) + XCTAssertEqual(rope.sine.dtype, .bfloat16) + let ordinary = Float(1) / pow(Float(10000), Float(2) / 64) + XCTAssertNotEqual(ordinary * 2999, Float(0.75) * 2999) + let encoder = MiMoV26AudioTokenizerEncoder(configuration: c) + XCTAssertFalse(encoder.parameters().flattened().contains { $0.0.contains("inv_freq") }) + } + + func testMissingWeightsBadShapeCancellationAndSupportedReloadGeneration() throws { + try mimoAudioInputRequireNative() + let c = try MiMoV26AudioInputConfiguration.fixture() + let oracle = try mimoAudioCodecOracle() + let encoder = MiMoV26AudioTokenizerEncoder(configuration: c) + let p = try MiMoV26AudioInputPlan.makeMelInputs( + frameCounts: [3], sourceIdentities: ["fixture"], configuration: c, + limits: mimoAudioInputTestLimits()) + let mel = MLXArray.zeros([3, 2], dtype: .float32) + XCTAssertThrowsError(try encoder.encodeMelFeatures(mels: [mel], plan: p)) + let network = oracle.weights.filter { !$0.key.hasPrefix("encoder.quantizer.") }.mapValues { + $0.array() + } + try encoder.loadNativeNetworkWeights(network) + let first = try XCTUnwrap(encoder.loadedGeneration) + XCTAssertThrowsError( + try encoder.encodeMelFeatures(mels: [MLXArray.zeros([4, 2])], plan: p)) + XCTAssertThrowsError( + try encoder.encodeMelFeatures(mels: [mel], plan: p, isCancelled: { true })) + try encoder.loadNativeNetworkWeights(network) + XCTAssertNotEqual(encoder.loadedGeneration, first) + var missing = network + missing.removeValue(forKey: "encoder.layers.0.self_attn.k_proj.weight") + XCTAssertThrowsError(try encoder.loadNativeNetworkWeights(missing)) + XCTAssertNil(encoder.loadedGeneration) + XCTAssertThrowsError(try encoder.encodeMelFeatures(mels: [mel], plan: p)) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26BlockBatchTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26BlockBatchTests.swift new file mode 100644 index 0000000000..e442e9c3e4 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26BlockBatchTests.swift @@ -0,0 +1,425 @@ +import Foundation +import MLX +import MLXFast +import MLXHuggingFace +import Tokenizers +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon +@testable import MLXVLM + +/// Source-prepared only. Arithmetic/scope cells are not native owner proof. +/// Numerical cells require actual NAX hardware and never replace its result. +final class MiMoV26BlockBatchTests: XCTestCase { + private enum Failure: Error { case injected, fixture, nativeCompletion } + private func lane() throws { + guard ProcessInfo.processInfo.environment["MIMO_V26_BLOCKBATCH_NATIVE_TESTS"] == "1", + MiMoV26NAXGatherQMM.gpuStream(.default), MiMoV26NAXGatherQMM.naxAvailable + else { + throw XCTSkip("Explicit owned NAX native process required") + } + } + func testExactDescriptorVisibilityAndOrderedCoverage() throws { + for window: Int? in [nil, 128] { + for prefix in [0, 1, 127, 128, 129, 8193] { + for count in [256, 300, 384, 511, 512, 1024, 2048, 4095] { + guard + let plan = MiMoV26BlockBatchAttention.layout( + queries: count, keys: prefix + count, + heads: 64, kvHeads: 8, window: window, admittedMaximumQueries: 4096) + else { + // Cold SWA256 has one causal + one window variant, + // so deliberately no real aggregate; old loop remains. + XCTAssertEqual(window, 128) + XCTAssertTrue([256, 300].contains(count)) + XCTAssertEqual(prefix, 0) + continue + } + let flat = plan.groups.flatMap { $0 } + XCTAssertEqual(flat.reduce(0) { $0 + $1.queryCount }, count) + var cursor = 0 + for d in flat { + XCTAssertEqual(d.queryStart, cursor) + let end = prefix + cursor + d.queryCount + let start = window.map { max(0, prefix + cursor + 1 - $0) } ?? 0 + XCTAssertEqual(d.keyStart, start) + XCTAssertEqual(d.keyCount, end - start) + XCTAssertEqual(d.causal, window == nil || end - start <= window!) + if window != nil { XCTAssertLessThanOrEqual(d.keyCount, 255) } + cursor += d.queryCount + } + XCTAssertTrue(plan.groups.contains { $0.count > 1 }) + for group in plan.groups { + XCTAssertLessThanOrEqual(group.count, 4) + XCTAssertTrue(group.allSatisfy { $0.sameVariant(group[0]) }) + } + } + } + } + } + func testMalformedBoundsAndShortTailDeclineBeforeNativeWork() { + for q in [1, 8, 9, 127, 128, 129, 136, 257, 264] { + XCTAssertNil( + MiMoV26BlockBatchAttention.layout( + queries: q, keys: q, heads: 64, kvHeads: 4, + window: nil, admittedMaximumQueries: 2048)) + } + for tuple in [ + (Int.max, Int.max, 8192), (256, 255, 2048), (256, Int.max, 2048), (256, 256, Int.max), + ] { + XCTAssertNil( + MiMoV26BlockBatchAttention.layout( + queries: tuple.0, keys: tuple.1, heads: 64, kvHeads: 4, + window: nil, admittedMaximumQueries: tuple.2)) + } + XCTAssertNil( + MiMoV26BlockBatchAttention.layout( + queries: 512, keys: 512, heads: 64, kvHeads: 7, + window: nil, admittedMaximumQueries: 2048)) + XCTAssertNil( + MiMoV26BlockBatchAttention.layout( + queries: 512, keys: 512, heads: 64, kvHeads: 8, + window: 256, admittedMaximumQueries: 2048)) + } + func testAllocatorPartitionBoundOverflowAndUnavailability() throws { + func bound(_ n: Int) -> Int? { n + 16384 } + let small = try MiMoV26BlockBatchAttention.scratchBytes( + maximumQueries: 512, layerCount: 2, + maximumExtraBytes: 16384, upperBound: bound) + let wide = try MiMoV26BlockBatchAttention.scratchBytes( + maximumQueries: 2048, layerCount: 2, + maximumExtraBytes: 16384, upperBound: bound) + XCTAssertGreaterThan(wide, small) + XCTAssertGreaterThan(small, 0) + XCTAssertThrowsError( + try MiMoV26BlockBatchAttention.scratchBytes( + maximumQueries: 512, layerCount: 2, + maximumExtraBytes: Int.max, upperBound: bound)) + XCTAssertThrowsError( + try MiMoV26BlockBatchAttention.scratchBytes( + maximumQueries: 512, layerCount: 2, + maximumExtraBytes: 0, upperBound: { _ in nil })) + XCTAssertThrowsError( + try MiMoV26BlockBatchAttention.scratchBytes( + maximumQueries: 512, layerCount: 2, + maximumExtraBytes: 0, upperBound: { $0 - 1 })) + XCTAssertThrowsError( + try MiMoV26BlockBatchAttention.scratchBytes( + maximumQueries: Int.max, layerCount: 2, + maximumExtraBytes: 16384, upperBound: bound)) + } + func testNestedThrowingScopeRestoresAndRejectsUnarmedCrossEngineIdentity() throws { + try lane() + let policy = try XCTUnwrap(Memory.allocationFootprintPolicy()) + let owner = NSObject() + let backend = NSObject() + let bank = NSObject() + // Metadata-only scope objects; never a fabricated execution contract, + // row, loaded resource owner or successful retirement receipt. + let a = try MiMoV26BlockBatchBudget( + engineID: UUID(), model: owner, backend: backend, cacheProvider: bank, + maximumQueries: 512, layerCount: 2, policy: policy) + let b = try MiMoV26BlockBatchBudget( + engineID: UUID(), model: owner, backend: backend, cacheProvider: bank, + maximumQueries: 512, layerCount: 2, policy: policy) + XCTAssertFalse(MiMoV26BlockBatchAttention.matchesCurrentBudget(nil)) + XCTAssertFalse(MiMoV26BlockBatchAttention.matchesCurrentBudget(a)) + try MiMoV26BlockBatchAttention.withBudget(a) { + XCTAssertTrue(MiMoV26BlockBatchAttention.matchesCurrentBudget(a)) + XCTAssertFalse(MiMoV26BlockBatchAttention.matchesCurrentBudget(b)) + XCTAssertThrowsError( + try MiMoV26BlockBatchAttention.withBudget(b) { + XCTAssertTrue(MiMoV26BlockBatchAttention.matchesCurrentBudget(b)) + XCTAssertFalse(MiMoV26BlockBatchAttention.matchesCurrentBudget(a)) + throw Failure.injected + }) + XCTAssertTrue(MiMoV26BlockBatchAttention.matchesCurrentBudget(a)) + MiMoV26BlockBatchAttention.withBudget(nil) { + XCTAssertFalse(MiMoV26BlockBatchAttention.matchesCurrentBudget(a)) + } + XCTAssertTrue(MiMoV26BlockBatchAttention.matchesCurrentBudget(a)) + } + XCTAssertFalse(MiMoV26BlockBatchAttention.matchesCurrentBudget(a)) + } + private let scale: Float = Float(1 / sqrt(192.0)) + func testUnarmedAndForeignScopedComponentCallsDoNotEncode() throws { + try lane() + guard ProcessInfo.processInfo.environment["DARKBLOOM_MIMO_BLOCK_BATCH_PREFILL"] == "1", + ProcessInfo.processInfo.environment["DARKBLOOM_MIMO_V26_NAX_ATTENTION"] == "1" + else { + throw XCTSkip( + "Exact process-start route flags required for discriminating fallback test") + } + let policy = try XCTUnwrap(Memory.allocationFootprintPolicy()) + let owner = NSObject() + let backend = NSObject() + let bank = NSObject() + let a = try MiMoV26BlockBatchBudget( + engineID: UUID(), model: owner, backend: backend, cacheProvider: bank, + maximumQueries: 512, layerCount: 2, policy: policy) + let b = try MiMoV26BlockBatchBudget( + engineID: UUID(), model: owner, backend: backend, cacheProvider: bank, + maximumQueries: 512, layerCount: 2, policy: policy) + let q = MLXArray.zeros([1, 64, 256, 192], dtype: .bfloat16) + let k = MLXArray.zeros([1, 4, 256, 192], dtype: .bfloat16) + let v = MLXArray.zeros([1, 4, 256, 128], dtype: .bfloat16) + func call(_ budget: MiMoV26BlockBatchBudget?) -> MLXArray? { + MiMoV26BlockBatchAttention.tryAttention( + queries: q, keys: k, values: v, scale: scale, + sinks: nil, window: nil, queryBlockSize: 128, budget: budget) + } + let before = MiMoV26BlockBatchAttention.encodedDispatches() + XCTAssertNil(call(nil)) + XCTAssertNil(call(a)) + MiMoV26BlockBatchAttention.withBudget(a) { + XCTAssertNil(call(nil)) + XCTAssertNil(call(b)) + } + XCTAssertEqual(MiMoV26BlockBatchAttention.encodedDispatches(), before) + let result = try MiMoV26BlockBatchAttention.withBudget(a) { try XCTUnwrap(call(a)) } + try withError { error in + eval(result) + try error.check() + } + XCTAssertEqual( + MiMoV26BlockBatchAttention.encodedDispatches(), before + 1, + "positive component control proves negatives did not merely use an unavailable kernel") + } + private func values(_ shape: [Int], salt: Int, dtype: DType) -> MLXArray { + MLXArray((0 ..< shape.reduce(1, *)).map { sin(Float(($0 + salt) * 7)) * 0.12 }) + .reshaped(shape).asType(dtype) + } + private func exact(_ a: MLXArray, _ b: MLXArray, _ label: String) throws { + try withError { error in + eval(a, b) + try error.check() + } + XCTAssertEqual(a.shape, b.shape, label) + XCTAssertEqual(a.dtype, b.dtype, label) + XCTAssertEqual(a.asData(access: .copy).data, b.asData(access: .copy).data, label) + } + private func compare(q: MLXArray, k: MLXArray, v: MLXArray, window: Int?, sinks: MLXArray?) + throws -> MLXArray + { + let plan = try XCTUnwrap( + MiMoV26BlockBatchAttention.makePlan( + queries: q, keys: k, values: v, + scale: scale, sinks: sinks, window: window, maximumQueries: 4096, production: false) + ) + let candidate = MiMoV26BlockBatchAttention.launch( + queries: q, keys: k, values: v, + scale: scale, sinks: sinks, plan: plan) + var reference: [MLXArray] = [] + // Baseline descriptors recomputed independently, not replayed from plan. + let history = k.dim(2) - q.dim(2) + var offset = 0 + while offset < q.dim(2) { + let count = min(128, q.dim(2) - offset) + let end = history + offset + count + let start = window.map { max(0, history + offset + 1 - $0) } ?? 0 + let qs = q[0..., 0..., offset ..< offset + count, 0...] + let ks = k[0..., 0..., start ..< end, 0...] + let vs = v[0..., 0..., start ..< end, 0...] + let mask = CBv2AttentionV1.maskMode(L: count, kL: end - start, window: window) + let baseline = try XCTUnwrap( + MiMoV26NAXAttention.makePlan( + queries: qs, keys: ks, values: vs, + scale: scale, mask: mask, sinks: sinks, production: false)) + reference.append( + MiMoV26NAXAttention.launch( + queries: qs, keys: ks, values: vs, + scale: scale, plan: baseline)) + offset += count + } + try exact(candidate, concatenated(reference, axis: 2), "exact ordinary q128 NAX baseline") + return candidate + } + func testExactBytesDistinctKeyLengthsRaggedAndBooleanWindowMasks() throws { + try lane() + for dtype: DType in [.bfloat16, .float16] { + for (count, prefix, window) in [ + (512, 0, nil), (300, 17, nil), (511, 129, 128), (512, 127, 128), (384, 0, 128), + ] as [(Int, Int, Int?)] { + let q = values([1, 4, count, 192], salt: 7, dtype: dtype) + let k = values([1, 2, count + prefix, 192], salt: 31, dtype: dtype) + let v = values([1, 2, count + prefix, 128], salt: 97, dtype: dtype) + for useSinks in [false, true] { + let sinks = useSinks ? values([4], salt: 11, dtype: dtype) : nil + _ = try compare(q: q, k: k, v: v, window: window, sinks: sinks) + } + } + } + } + func testExactBytesWithNonunitHeadAndSequenceStrides() throws { + try lane() + let dtype: DType = .bfloat16 + let count = 384 + let prefix = 129 + let q = values([1, count, 4, 384], salt: 2, dtype: dtype) + .transposed(0, 2, 1, 3)[.ellipsis, .stride(by: 2)] + let k = values([1, 2, 2 * (count + prefix), 384], salt: 17, dtype: dtype)[ + 0..., 0..., MLXSlice.stride(by: 2), MLXSlice.stride(by: 2)] + let v = values([1, 2, 2 * (count + prefix), 256], salt: 43, dtype: dtype)[ + 0..., 0..., MLXSlice.stride(by: 2), MLXSlice.stride(by: 2)] + _ = try compare(q: q, k: k, v: v, window: 128, sinks: nil) + _ = try compare(q: q, k: k, v: v, window: nil, sinks: nil) + } + func testOverflowAndNonfiniteFutureValuesNeverExpandFirstBlock() throws { + try lane() + let dtype: DType = .float16 + let count = 256 + let q = (MLXArray.ones([1, 4, count, 192], dtype: dtype) * 2048).asType(dtype) + let k = (MLXArray.ones([1, 2, count, 192], dtype: dtype) * (-2048)).asType(dtype) + let overflow = matmul( + q[0 ..< 1, 0 ..< 1, 0 ..< 1, 0...] * MLXArray(scale).asType(dtype), + k[0 ..< 1, 0 ..< 1, 0 ..< 1, 0...].swappedAxes(-1, -2)) + try withError { error in + eval(overflow) + try error.check() + } + XCTAssertTrue(overflow.asType(.float32).item(Float.self).isInfinite) + for future: Float in [1, -2, .infinity, .nan] { + let v = concatenated( + [ + MLXArray.zeros([1, 2, 128, 128], dtype: dtype), + MLXArray.ones([1, 2, 128, 128], dtype: dtype) * future, + ], axis: 2 + ).asType(dtype) + let result = try compare(q: q, k: k, v: v, window: nil, sinks: nil) + let first = result[0..., 0..., 0 ..< 1, 0...] + XCTAssertTrue(first.asType(.float32).asArray(Float.self).allSatisfy { $0 == 0 }) + } + } + func testRawAdapterHasNoIssuedBankAndCannotInstallCallerBudget() throws { + try lane() + let (target, _) = try MiMoV26MTPChecks.fixture() + let adapter = try MiMoV26CBv2Adapter(target: target) + let budget = try MiMoV26BlockBatchBudget( + engineID: UUID(), model: adapter, + backend: NSObject(), cacheProvider: NSObject(), maximumQueries: 512, layerCount: 2, + policy: XCTUnwrap(Memory.allocationFootprintPolicy())) + XCTAssertFalse(adapter.cbv2TryInstallBlockBatchBudget(budget)) + XCTAssertFalse(MiMoV26BlockBatchAttention.matchesCurrentBudget(budget)) + } + + private final class Permit: MiMoV26SerialLoadReservation, Sendable { + let request: MiMoV26SerialLoadRequest + var reservedLoadBytes: UInt64 { request.requiredLoadBytes } + init(_ request: MiMoV26SerialLoadRequest) { self.request = request } + func validateActive(progress: MiMoV26SerialLoadProgress) throws {} + } + private struct Loader: TokenizerLoader { + func load(from directory: URL) async throws -> any MLXLMCommon.Tokenizer { + let raw = try await AutoTokenizer.from(modelFolder: directory) + return #adaptHuggingFaceTokenizer(raw) + } + } + private struct Built: Sendable { + let engine: EngineV2 + let contract: CBv2NativeExecutionContract + } + func testActualStrictIssuedEngineMtpOffChargesOnceAndKeepsOriginalBinding() async throws { + try lane() + let env = ProcessInfo.processInfo.environment + guard env["DARKBLOOM_MIMO_BLOCK_BATCH_PREFILL"] == "1", + env["DARKBLOOM_MIMO_V26_NAX_ATTENTION"] == "1", + let root = env["MIMO_V26_BLOCKBATCH_NATIVE_FIXTURE"] + else { + throw XCTSkip( + "Separate strict tiny192/128 Q64/window128 fixture and actual route flags required") + } + // Existing strict loader, real tensor payload and actual tokenizer. + // This selector never substitutes a conformance marker or fake receipt. + let directory = URL(fileURLWithPath: root) + let p = try XCTUnwrap( + JSONSerialization.jsonObject( + with: + Data(contentsOf: directory.appendingPathComponent("provenance.json"))) + as? [String: String]) + let provenance = MiMoV26ConvertedProvenance( + artifactID: try XCTUnwrap(p["artifactID"]), + sourceRepository: try XCTUnwrap(p["sourceRepository"]), + sourceRevision: try XCTUnwrap(p["sourceRevision"]), + conversionManifestSHA256: try XCTUnwrap(p["conversionManifestSHA256"])) + let plan = try MiMoV26FilesystemWeights.preflight( + root: directory, provenance: provenance, + limits: .init(maximumShardBytes: 64 << 20, maximumTotalFileBytes: 128 << 20)) + let c = plan.bundlePlan.configuration + guard c.hiddenSize <= 64, c.numHiddenLayers <= 4, c.maxPositionEmbeddings >= 520, + [c.fullAttention, c.slidingAttention].allSatisfy({ + $0.queryHeads == 64 && [4, 8].contains($0.keyValueHeads) + && $0.headDim == 192 && $0.valueHeadDim == 128 + }), c.slidingWindow == 128 + else { throw Failure.fixture } + let session = try MiMoV26SerialLoadSession(plan: plan) + let prepared = try await MiMoV26ModelFactory.prepare( + request: session.request, + configuration: .init(directory: directory), tokenizerLoader: Loader()) + let work = NativeConstructionWork() + let container = try await MiMoV26ModelFactory.loadContainer( + session: session, + reservation: Permit(session.request), prepared: prepared, retaining: work) + var retired = false + defer { + if !retired { + _ = Unmanaged.passRetained(work) + _ = Unmanaged.passRetained(container) + } + } + try await work.acknowledgeContainerAdoption(container) + let built = try await MiMoV26ModelFactory.withNativeConstruction( + container: container, retaining: work + ) { model, scope in + let binding = try model.makeCBv2Binding(enableMTP: false) + _ = try binding.adapter.probeNativeKVTypes(retaining: scope) + let resources = try binding.adapter.makeNativeExecutionResources( + bytesCapacity: 1 << 30, retaining: scope) + let base = 4096 + let engine = EngineV2( + model: binding.adapter, layerKinds: binding.adapter.layerKinds, + backend: resources.backend, cacheProvider: resources.cacheProvider, + schedulerConfig: .init( + maxConcurrentRequests: 1, maxBatchedTokensPerStep: 512, + prefillChunkSize: 512, enablePrefixCache: false), + admissionConfig: .init(fixedBytesPerRequest: base), + nativeCompletionTracking: true, nativeExecutionContract: resources.contract) + try scope.retainOwner(engine) + XCTAssertNil(engine.mtpMetricsSnapshot()) + XCTAssertNil(engine.groupedPrefillInactiveReason) + XCTAssertGreaterThan(engine.groupedPrefillScratchBytes, 0) + XCTAssertEqual( + engine.resolvedFixedBytesPerRequest, base + engine.groupedPrefillScratchBytes) + let incompatible = try MiMoV26BlockBatchBudget( + engineID: UUID(), model: binding.adapter, + backend: resources.backend, cacheProvider: resources.cacheProvider, + maximumQueries: 1024, layerCount: c.numHiddenLayers, + policy: XCTUnwrap(Memory.allocationFootprintPolicy())) + XCTAssertFalse( + binding.adapter.cbv2TryInstallBlockBatchBudget(incompatible), + "second binding never replaces the first actual engine's cache bound") + return Built(engine: engine, contract: resources.contract) + } + defer { if !retired { _ = Unmanaged.passRetained(built.engine) } } + guard case .completed(let completion) = work.snapshot.disposition else { + throw Failure.nativeCompletion + } + try await work.sealForPublication(completion) + let before = MiMoV26BlockBatchAttention.encodedDispatches() + let request = CBv2Request( + id: .init(301), promptTokens: Array(repeating: 1, count: 512), + sampling: .init(temperature: 0), maxTokens: 2, stopTokens: [], prefixCacheEnabled: false + ) + let submission = try built.engine.submitWithNativeRetirement(request) + let result = await cbv2SchedCollect(submission.events) + await submission.retirement.wait() + XCTAssertEqual(result.tokens.count, 2) + XCTAssertGreaterThan(MiMoV26BlockBatchAttention.encodedDispatches(), before) + guard case .quiescent(let receipt) = await built.engine.shutdownReportingNativeCompletion() + else { + throw Failure.nativeCompletion + } + XCTAssertEqual(receipt.executionContractID, built.contract.id) + retired = true + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26CBv2MultimodalTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26CBv2MultimodalTests.swift new file mode 100644 index 0000000000..1ae8507be7 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26CBv2MultimodalTests.swift @@ -0,0 +1,367 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon +@testable import MLXVLM + +private func withMiMoConstructionScope( + _ body: (NativeConstructionScope) throws -> Value +) rethrows -> Value { + let work = NativeConstructionScope() + defer { + // Unexpected failed completion is restart-only, including in this + // dedicated native test process. Never deallocate its sole SDK owner. + if work.snapshot.isRetainedFault { _ = Unmanaged.passRetained(work) } + } + return try body(work) +} + +// Direct untracked target/math fixtures. Scoped KV probes below do not issue a +// managed media execution profile or turn Void shutdown into F1 retirement. +final class MiMoV26CBv2MultimodalTests: XCTestCase { + private func prepare(_ f: MiMoMediaFixture.Models, _ input: MiMoV26MultimodalInput) throws + -> MiMoV26PreparedMultimodal + { + try f.processor.prepare( + f.processor.plan(input), authorize: { MiMoMediaFixture.Reservation($0) }) + } + private static func collect(_ stream: AsyncStream) async -> ( + [Int], CBv2FinishReason? + ) { + var tokens: [Int] = [] + var reason: CBv2FinishReason? + for await event in stream { + switch event { + case .delta(_, let values, _): tokens += values + case .finished(let value, _): reason = value + } + } + return (tokens, reason) + } + /// Independent host span assembly; does not call engine splice/resolve. + private func embeddings( + _ target: MiMoV26TextModel, _ prompt: [Int], + _ spans: [MiMoV26MultimodalSpan], _ arrays: [MLXArray] + ) -> MLXArray { + let text = target.model.embedTokens(MLXArray(prompt.map(Int32.init), [1, prompt.count])) + var pieces: [MLXArray] = [] + var cursor = 0 + for (span, array) in zip(spans, arrays) { + if cursor < span.tokenOffset { + pieces.append(text[0..., cursor ..< span.tokenOffset, 0...]) + } + pieces.append(array.expandedDimensions(axis: 0)) + cursor = span.tokenOffset + span.length + } + if cursor < prompt.count { pieces.append(text[0..., cursor ..< prompt.count, 0...]) } + return concatenated(pieces, axis: 1) + } + private func reference( + _ f: MiMoMediaFixture.Models, _ prepared: MiMoV26PreparedMultimodal, id: UInt64 + ) throws -> [Int] { + let request = try prepared.makeRequest( + binding: f.binding, id: .init(id), sampling: .init(temperature: 0)) + let arrays = try XCTUnwrap(request.multimodal).embeddings() + let cache = f.target.newCache() + var output = try f.target.forward( + embeddings: embeddings(f.target, request.promptTokens, prepared.plan.spans, arrays), + cache: cache + ).logits + var result: [Int] = [] + for step in 0 ..< request.maxTokens { + let last = output[0..., -1, 0...] + let next = argMax(last, axis: -1) + eval(next) + let token = Int(next.item(Int32.self)) + result.append(token) + if step + 1 < request.maxTokens { + output = try f.target.forward( + inputIDs: MLXArray([Int32(token)], [1, 1]), cache: cache + ).logits + } + } + return result + } + func testRealEngineMixedImageVideoAndTextMatchOrdinaryNativeReference() async throws { + let f = try MiMoMediaFixture.models() + _ = try withMiMoConstructionScope { constructionWork in + try f.adapter.probeNativeKVTypes(retaining: constructionWork) + } + XCTAssertTrue(f.adapter.layerKinds.allSatisfy { $0.headDim == 32 && $0.valueHeadDim == 16 }) + let image = MiMoMediaFixture.image(60) + let video = MiMoV26SilentVideo( + frames: [image, MiMoMediaFixture.image(100), image], timestamps: [0, 1, 2]) + let inputs = [ + MiMoMediaFixture.request([.text("a"), .image(image), .text("tail")]), + MiMoMediaFixture.request([.silentVideo(video), .image(image), .text("b")]), + ] + var prepared: [MiMoV26PreparedMultimodal] = [] + var references: [[Int]] = [] + for (i, input) in inputs.enumerated() { + references.append(try reference(f, prepare(f, input), id: UInt64(100 + i))) + prepared.append(try prepare(f, input)) + } + let textPrompt = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30] + let textCache = f.target.newCache() + var logits = try f.target.forward( + inputIDs: MLXArray(textPrompt.map(Int32.init), [1, textPrompt.count]), cache: textCache + ).logits + var textExpected: [Int] = [] + for i in 0 ..< 3 { + let next = argMax(logits[0..., -1, 0...], axis: -1) + eval(next) + let token = Int(next.item(Int32.self)) + textExpected.append(token) + if i < 2 { + logits = try f.target.forward( + inputIDs: MLXArray([Int32(token)], [1, 1]), cache: textCache + ).logits + } + } + let backend = try f.adapter.makeBackend(bytesCapacity: 32 << 20) + let engine = EngineV2( + model: f.adapter, layerKinds: f.adapter.layerKinds, backend: backend, + cacheProvider: try f.adapter.makeMultimodalCacheProvider(), + schedulerConfig: .init( + maxConcurrentRequests: 3, maxBatchedTokensPerStep: 5, prefillChunkSize: 3, + maxWaiting: 8), + loopConfig: .init( + requestTimeout: 30, stepTimeout: 15, shutdownTimeout: 5, + useLegacyRequestTimeout: true), + nativeCompletionTracking: false) + do { + let a = try engine.submit( + prepared[0].makeRequest( + binding: f.binding, id: .init(1), sampling: .init(temperature: 0))) + let b = try engine.submit( + prepared[1].makeRequest( + binding: f.binding, id: .init(2), sampling: .init(temperature: 0))) + let text = try engine.submit( + .init( + id: .init(3), promptTokens: textPrompt, sampling: .init(temperature: 0), + maxTokens: 3, prefixCacheEnabled: false)) + async let resultA = Self.collect(a) + async let resultB = Self.collect(b) + async let resultText = Self.collect(text) + let result = await (resultA, resultB, resultText) + XCTAssertEqual(result.0.0, references[0]) + XCTAssertEqual(result.1.0, references[1]) + XCTAssertEqual(result.2.0, textExpected) + XCTAssertEqual(result.0.1, .length) + XCTAssertEqual(result.1.1, .length) + XCTAssertEqual(result.2.1, .length) + XCTAssertFalse(engine.packedPrefillActivity().isSupported) + await engine.shutdown() + XCTAssertEqual(backend.bytesReserved, 0) + } catch { + await engine.shutdown() + throw error + } + } + func testCausalChunksAndSWAWrapMatchFP32AndBF16Logits() throws { + for dtype in ["float32", "bfloat16"] { + let f = try MiMoMediaFixture.models(dtype) + _ = try withMiMoConstructionScope { constructionWork in + try f.adapter.probeNativeKVTypes(retaining: constructionWork) + } + let value = try prepare( + f, + MiMoMediaFixture.request([.image(MiMoMediaFixture.image()), .text("0123456789")])) + let request = try value.makeRequest(binding: f.binding, id: .init(11)) + let arrays = try XCTUnwrap(request.multimodal).embeddings() + let whole = embeddings(f.target, request.promptTokens, value.plan.spans, arrays) + let ordinary = f.target.newCache() + let backend = try f.adapter.makeBackend(bytesCapacity: 16 << 20) + let rows = try backend.makeSequenceState( + layerKinds: f.adapter.layerKinds, promptLength: request.promptTokens.count, + maxLength: 128) + let caches = f.adapter.makeCaches() + for start in stride(from: 0, to: request.promptTokens.count, by: 3) { + let end = min(start + 3, request.promptTokens.count) + let ids = MLXArray( + request.promptTokens[start ..< end].map(Int32.init), [1, end - start]) + try f.adapter.bindRows([rows], caches: caches) + let actual = try f.adapter.forwardValidated( + tokens: ids, inputEmbeddings: whole[0..., start ..< end, 0...], caches: caches) + let expected = try f.target.forward( + embeddings: whole[0..., start ..< end, 0...], cache: ordinary + ).logits + eval(actual, expected) + let absolute: Float = dtype == "bfloat16" ? 0.02 : 5e-5 + let relative: Float = dtype == "bfloat16" ? 0.02 : 1e-4 + XCTAssertTrue( + all(abs(actual - expected) .<= (absolute + relative * abs(expected))).item( + Bool.self)) + } + XCTAssertEqual( + rows.compactMap { $0?.absoluteOffset }, + Array(repeating: request.promptTokens.count, count: rows.count)) + backend.release(rows) + } + } + func testActualEngineCancellationDrainsRequestReservation() async throws { + let f = try MiMoMediaFixture.models() + _ = try withMiMoConstructionScope { constructionWork in + try f.adapter.probeNativeKVTypes(retaining: constructionWork) + } + let input = MiMoV26MultimodalInput( + messages: [.init(role: .user, content: [.image(MiMoMediaFixture.image())])], + maximumOutputTokens: 100) + let plan = try f.processor.plan(input) + weak var reservation: MiMoMediaFixture.Reservation? + var prepared: MiMoV26PreparedMultimodal? = try f.processor.prepare( + plan, + authorize: { value in + let owner = MiMoMediaFixture.Reservation(value) + reservation = owner + return owner + }) + let backend = try f.adapter.makeBackend(bytesCapacity: 16 << 20) + let engine = EngineV2( + model: f.adapter, layerKinds: f.adapter.layerKinds, backend: backend, + cacheProvider: try f.adapter.makeMultimodalCacheProvider(), + schedulerConfig: .init( + maxConcurrentRequests: 1, maxBatchedTokensPerStep: 1, prefillChunkSize: 1, + maxWaiting: 2), + loopConfig: .init( + requestTimeout: 30, stepTimeout: 15, shutdownTimeout: 5, + useLegacyRequestTimeout: true), + nativeCompletionTracking: false) + do { + var request: CBv2Request? = try prepared!.makeRequest( + binding: f.binding, id: .init(90), sampling: .init(temperature: 0)) + let stream = try engine.submit(request!) + prepared = nil + request = nil + XCTAssertNotNil(reservation) + engine.cancel(.init(90)) + let result = await Self.collect(stream) + XCTAssertEqual(result.1, .cancelled) + await engine.shutdown() + XCTAssertNil(reservation) + XCTAssertEqual(backend.bytesReserved, 0) + } catch { + await engine.shutdown() + throw error + } + } + func testCausalRefinementDoesNotFakeBidirectionalOrPackedCacheCapabilities() throws { + let f = try MiMoMediaFixture.models() + XCTAssertThrowsError(try f.adapter.makeMultimodalCacheProvider()) + _ = try withMiMoConstructionScope { constructionWork in + try f.adapter.probeNativeKVTypes(retaining: constructionWork) + } + let provider = try f.adapter.makeMultimodalCacheProvider() + XCTAssertFalse(provider.supportsMultimodalSpans) + XCTAssertFalse(provider.supportsPackedPrefill) + XCTAssertFalse(provider.supportsPackedMultimodalSpans) + XCTAssertTrue( + (provider as! any CBv2MultimodalAttentionCapabilityProviding).supportsMultimodalPrefill( + attention: .causal)) + XCTAssertFalse( + (provider as! any CBv2MultimodalAttentionCapabilityProviding).supportsMultimodalPrefill( + attention: .bidirectionalSpans)) + var calls = 0 + let input = CBv2MultimodalInput( + spans: [.init(tokenOffset: 0, length: 1)], attention: .causal + ) { + calls += 1 + return [] + } + XCTAssertEqual( + try CBv2MultimodalPlan.validate( + input, promptTokenCount: 2, model: f.adapter, cacheProvider: provider, + maxBatchedTokensPerStep: 1), []) + XCTAssertThrowsError( + try CBv2MultimodalPlan.validate( + input, promptTokenCount: 2, model: f.adapter, + cacheProvider: CBv2LayerCacheBank(caches: f.adapter.makeCaches()), + maxBatchedTokensPerStep: 1)) + var bidirectional = input + bidirectional.attention = .bidirectionalSpans + XCTAssertThrowsError( + try CBv2MultimodalPlan.validate( + bidirectional, promptTokenCount: 2, model: f.adapter, cacheProvider: provider, + maxBatchedTokensPerStep: 1)) + XCTAssertEqual(calls, 0) + XCTAssertTrue(f.adapter.makeCaches().allSatisfy { !($0 is any CBv2SpanMaskBinding) }) + } + func testForeignRowsWrongEmbeddingTypeAndReleasedRowsRefuseWithoutWrites() throws { + let a = try MiMoMediaFixture.models() + let b = try MiMoMediaFixture.models() + _ = try withMiMoConstructionScope { constructionWork in + try a.adapter.probeNativeKVTypes(retaining: constructionWork) + } + _ = try withMiMoConstructionScope { constructionWork in + try b.adapter.probeNativeKVTypes(retaining: constructionWork) + } + let backend = try a.adapter.makeBackend(bytesCapacity: 16 << 20) + let rows = try backend.makeSequenceState( + layerKinds: a.adapter.layerKinds, promptLength: 4, maxLength: 128) + let before = backend.bytesReserved + let caches = a.adapter.makeCaches() + XCTAssertThrowsError(try b.adapter.bindRows([rows], caches: b.adapter.makeCaches())) + try a.adapter.bindRows([rows], caches: caches) + let tokens = MLXArray([Int32(20), 21], [1, 2]) + XCTAssertThrowsError( + try a.adapter.forwardValidated( + tokens: tokens, inputEmbeddings: MLXArray.zeros([1, 2, 64], dtype: .int32), + caches: caches)) + XCTAssertTrue(rows.allSatisfy { $0?.absoluteOffset == 0 }) + XCTAssertEqual(backend.bytesReserved, before) + backend.release(rows) + XCTAssertThrowsError(try a.adapter.bindRows([rows], caches: caches)) + XCTAssertEqual(backend.bytesReserved, 0) + } + // Preserve this original test selector. Paging stays refused; the former + // installed-assistant refusal is replaced by actual successful EngineV2 + // target-only media with the same native trained text assistant installed. + func testPagedAndInstalledAssistantRemainExplicitlyUnqualified() async throws { + let f = try MiMoMediaFixture.models() + let paged = try PagedKVBackend( + layerKinds: [.init(attention: .full, headDim: 64, kvHeads: 1, queryHeads: 1)], + config: .init( + capacityBytes: 1 << 20, maxPrefillChunk: 16, nominalMaxSequenceLength: 128, + maxBufferLength: 8 << 20)) + XCTAssertNotNil( + EngineV2.backendCapabilityViolation( + capabilities: f.adapter.cbv2Capabilities, backend: paged)) + let mtp = try MiMoV26MTP(target: f.target) + try mtp.loadConvertedWeights( + Dictionary( + uniqueKeysWithValues: mtp.parameters().flattened().map { name, array in + ( + "mtp." + name, + MiMoMediaFixture.values( + name, array.shape, + name.hasSuffix("e_score_correction_bias") + ? .float32 + : name.hasSuffix("mlp.gate.weight") ? .bfloat16 : .float32) + ) + })) + let assistant = try MiMoV26MTPAssistant(target: f.target, predictor: mtp) + let adapter = try MiMoV26CBv2Adapter(target: f.target, assistant: assistant) + XCTAssertTrue(adapter.supportsMultimodalPrefill(attention: .causal)) + XCTAssertFalse(adapter.cbv2Capabilities.supportsPagedKV) + let prepared = try MiMoMediaMTPFixture.prepared(f, adapter, output: 3) + let (engine, backend) = try MiMoMediaMTPFixture.engine(adapter) + do { + let request = try prepared.makeRequest( + binding: MiMoMediaMTPFixture.binding(f, adapter), id: .init(501), + sampling: .init(temperature: 0)) + let result = await MiMoMediaMTPFixture.collect(try engine.submit(request)) + XCTAssertEqual(result.0.count, 3) + XCTAssertEqual(result.1, .length) + let metrics = try XCTUnwrap(engine.mtpMetricsSnapshot()) + XCTAssertTrue(metrics.active) + XCTAssertEqual(metrics.draftedTokens, 0) + await engine.shutdown() + XCTAssertEqual(backend.bytesReserved, 0) + } catch { + await engine.shutdown() + throw error + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26CBv2Tests.swift b/Tests/MLXLMTests/MiMo/MiMoV26CBv2Tests.swift new file mode 100644 index 0000000000..e1c54b8819 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26CBv2Tests.swift @@ -0,0 +1,553 @@ +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +@testable import MLXLLM + +#if !MIMO_CBV2_COMPONENT_PROBE + import XCTest +#endif + +private func withMiMoConstructionScope( + _ body: (NativeConstructionScope) throws -> Value +) rethrows -> Value { + let work = NativeConstructionScope() + defer { + // Unexpected failed completion is restart-only, including in this + // dedicated native test process. Never deallocate its sole SDK owner. + if work.snapshot.isRetainedFault { _ = Unmanaged.passRetained(work) } + } + return try body(work) +} + +private final class MiMoV26ReadoutSpy: Linear { + var inputShapes: [[Int]] = [] + override func callAsFunction(_ x: MLXArray) -> MLXArray { + inputShapes.append(x.shape) + return super.callAsFunction(x) + } +} + +private enum MiMoV26CBv2Checks { + struct Failure: Error { let message: String } + static func require(_ condition: Bool, _ message: String) throws { + if !condition { throw Failure(message: message) } + } + static func rejected(_ body: () throws -> Void) throws { + do { + try body() + throw Failure(message: "invalid adapter input accepted") + } catch is MiMoV26CBv2Error {} + } + static func configuration(_ dtype: String = "float32") throws -> MiMoV26Configuration { + var fields = try JSONDecoder().decode( + [String: MiMoV26JSONValue].self, + from: Data( + """ + {"model_type":"mimo_v2","architectures":["MiMoV2ForCausalLM"], + "hidden_size":16,"intermediate_size":32,"moe_intermediate_size":8, + "vocab_size":64,"num_hidden_layers":2,"max_position_embeddings":64, + "sliding_window_size":3,"sliding_window":3,"num_nextn_predict_layers":3, + "hybrid_layer_pattern":[0,1],"moe_layer_freq":[0,1], + "partial_rotary_factor":0.5,"attention_value_scale":0.707, + "layernorm_epsilon":0.000001,"attention_projection_layout":"split", + "moe_router_dtype":"bfloat16","hidden_act":"silu","dtype":"float32", + "attention_bias":false,"tie_word_embeddings":false,"attention_dropout":0, + "scoring_func":"sigmoid","topk_method":"noaux_tc","n_routed_experts":4, + "num_experts_per_tok":2,"n_group":1,"topk_group":1,"norm_topk_prob":true, + "n_shared_experts":null,"routed_scaling_factor":null, + "num_attention_heads":4,"num_key_value_heads":1,"head_dim":8,"v_head_dim":4, + "swa_num_attention_heads":4,"swa_num_key_value_heads":2,"swa_head_dim":8, + "swa_v_head_dim":4,"rope_theta":10000000,"swa_rope_theta":10000, + "add_full_attention_sink_bias":false,"add_swa_attention_sink_bias":true, + "eos_token_id":3,"pad_token_id":0} + """.utf8)) + fields["dtype"] = .string(dtype) + return try MiMoV26Configuration(rawFields: fields) + } + static func fill(_ target: MiMoV26TextModel) throws { + let values = target.parameters().flattened().map { name, array in + let salt = name.utf8.reduce(0) { ($0 + Int($1)) % 997 } + let data = (0 ..< array.size).map { i -> Float in + if name.contains("norm.weight") { return 1 } + return sin(Float((i * 13 + salt) % 109)) * 0.15 + } + let dtype: DType = + name.hasSuffix("e_score_correction_bias") + ? .float32 + : name.hasSuffix("mlp.gate.weight") ? .bfloat16 : target.activationDType + return (name, MLXArray(data, array.shape).asType(dtype)) + } + try target.update(parameters: .unflattened(values), verify: .all) + } + static func fixture(_ type: String = "float32") throws -> ( + MiMoV26TextModel, MiMoV26CBv2Adapter, MiMoV26CBv2Backend + ) { + let target = try MiMoV26TextModel(configuration(type)) + try fill(target) + let adapter = try MiMoV26CBv2Adapter(target: target) + _ = try withMiMoConstructionScope { constructionWork in + try adapter.probeNativeKVTypes(retaining: constructionWork) + } + return (target, adapter, try adapter.makeBackend(bytesCapacity: 16 << 20)) + } + static func tokens(_ values: [Int]) -> MLXArray { + MLXArray(values.map(Int32.init), [1, values.count]) + } + static func near(_ actual: MLXArray, _ expected: MLXArray, dtype: DType, label: String) throws { + eval(actual, expected) + try require(actual.shape == expected.shape, label + " shape") + let a = actual.asType(.float32) + let b = expected.asType(.float32) + let error = abs(a - b) + let absolute: Float = dtype == .bfloat16 ? 0.02 : 5e-5 + let relative: Float = dtype == .bfloat16 ? 0.02 : 1e-4 + let maximum = error.max().item(Float.self) + try require( + maximum.isFinite && all(error .<= (absolute + relative * abs(b))).item(Bool.self), + "\(label) maxAbsoluteError=\(maximum)") + } + static func rows(_ adapter: MiMoV26CBv2Adapter, _ backend: MiMoV26CBv2Backend) throws + -> [CBv2SequenceKV?] + { + try backend.makeSequenceState( + layerKinds: adapter.layerKinds, promptLength: 8, maxLength: 64) + } + static func cases() -> [(String, () throws -> Void)] { + [ + ( + "native layer metadata and all unqualified serving capabilities fail closed", + { + let (target, adapter, _) = try fixture() + try require(adapter.target === target, "adapter duplicated target") + let full = adapter.layerKinds[0] + let sliding = adapter.layerKinds[1] + try require( + full.headDim == 8 && full.valueHeadDim == 4 && full.kvHeads == 1 + && full.attention == .full && !full.hasSinks, "full metadata") + try require( + sliding.headDim == 8 && sliding.valueHeadDim == 4 && sliding.kvHeads == 2 + && sliding.attention == .slidingWindow(3) && sliding.hasSinks, + "SWA metadata") + try require( + full.kvGeometry?.bytesPerToken(elementBytes: 4) == 48 + && sliding.kvGeometry?.bytesPerToken(elementBytes: 4) == 96, + "native byte metadata") + let c = adapter.cbv2Capabilities + try require( + !c.supportsPrefixReuse && !c.supportsPagedKV && !c.supportsCompiledDecode + && !c.supportsMTP && !c.supportsPackedPrefill + && !c.supportsRecurrentCheckpointReuse, "premature capability") + let bank = CBv2LayerCacheBank(caches: adapter.makeCaches()) + try require( + !bank.supportsMultimodalSpans && !bank.supportsPackedPrefill + && !bank.supportsMTPRectangularVerification, "cache capability widened") + } + ), + ( + "FP32 and BF16 ordinary versus CBv2 chunks wrap and independent decode rows", + { + for type in ["float32", "bfloat16"] { + let (target, adapter, backend) = try fixture(type) + let caches = adapter.makeCaches() + let a = try rows(adapter, backend) + let b = try rows(adapter, backend) + let ordinaryA = target.newCache() + let ordinaryB = target.newCache() + for (state, ordinary, chunks) in [ + (a, ordinaryA, [[1, 2], [3, 4, 5]]), + (b, ordinaryB, [[8, 9, 10, 11], [12, 13, 14, 15, 16]]), + ] { + for ids in chunks { + try adapter.bindRows([state], caches: caches) + let actual = try adapter.forwardValidated( + tokens: tokens(ids), caches: caches) + let expected = try target.forward( + inputIDs: tokens(ids), cache: ordinary + ).logits + try near( + actual, expected, dtype: target.activationDType, + label: "\(type) chunk") + } + } + try adapter.bindRows([a, b], caches: caches) + let actual = try adapter.forwardValidated( + tokens: MLXArray([Int32(6), 17], [2, 1]), caches: caches) + let expectedA = try target.forward(inputIDs: tokens([6]), cache: ordinaryA) + .logits + let expectedB = try target.forward(inputIDs: tokens([17]), cache: ordinaryB) + .logits + try near( + actual[0 ..< 1], expectedA, dtype: target.activationDType, + label: "\(type) rowA offset5") + try near( + actual[1 ..< 2], expectedB, dtype: target.activationDType, + label: "\(type) rowB offset9") + try adapter.bindRows([b, a], caches: caches) + let reordered = try adapter.forwardValidated( + tokens: MLXArray([Int32(18), 7], [2, 1]), caches: caches) + try near( + reordered[0 ..< 1], + target.forward(inputIDs: tokens([18]), cache: ordinaryB).logits, + dtype: target.activationDType, label: "\(type) reorderedB") + try near( + reordered[1 ..< 2], + target.forward(inputIDs: tokens([7]), cache: ordinaryA).logits, + dtype: target.activationDType, label: "\(type) reorderedA") + try adapter.bindRows([a], caches: caches) + try near( + adapter.forwardValidated(tokens: tokens([8]), caches: caches), + target.forward(inputIDs: tokens([8]), cache: ordinaryA).logits, + dtype: target.activationDType, label: "\(type) shrink") + backend.release(a) + backend.release(b) + } + } + ), + ( + "explicit B2 prefill rows equal isolated ordinary targets without enabling packing", + { + let (target, adapter, backend) = try fixture() + let caches = adapter.makeCaches() + let a = try rows(adapter, backend) + let b = try rows(adapter, backend) + try adapter.bindRows([a, b], caches: caches) + let idsA = [1, 2, 3, 4, 5] + let idsB = [9, 8, 7, 6, 5] + let batched = MLXArray((idsA + idsB).map(Int32.init), [2, 5]) + let output = try adapter.forwardValidated(tokens: batched, caches: caches) + try near( + output[0 ..< 1], target.forward(inputIDs: tokens(idsA)).logits, + dtype: .float32, label: "B2 prefill A") + try near( + output[1 ..< 2], target.forward(inputIDs: tokens(idsB)).logits, + dtype: .float32, label: "B2 prefill B") + backend.release(a) + backend.release(b) + } + ), + ( + "causal prepared embeddings equal text without any span capability", + { + let (target, adapter, backend) = try fixture() + let ids = tokens([1, 2, 3, 4, 5]) + let textRows = try rows(adapter, backend) + let embeddedRows = try rows(adapter, backend) + let textCaches = adapter.makeCaches() + let embeddedCaches = adapter.makeCaches() + try adapter.bindRows([textRows], caches: textCaches) + try adapter.bindRows([embeddedRows], caches: embeddedCaches) + let text = try adapter.forwardValidated(tokens: ids, caches: textCaches) + let embedded = try adapter.forwardValidated( + tokens: ids, inputEmbeddings: target.model.embedTokens(ids), + caches: embeddedCaches) + try near(text, embedded, dtype: .float32, label: "embedding seam") + try require( + embeddedCaches.allSatisfy { !($0 is any CBv2SpanMaskBinding) }, + "Gemma span overlay exposed") + backend.release(textRows) + backend.release(embeddedRows) + } + ), + ( + "prompt intermediate skips readout and frontier projects one row while preserving all KV", + { + let (target, adapter, backend) = try fixture() + let state = try rows(adapter, backend) + let caches = adapter.makeCaches() + let spy = MiMoV26ReadoutSpy(16, 64, bias: false) + try spy.update(parameters: target.lmHead!.parameters(), verify: .all) + target.update(modules: ModuleChildren.unflattened([("lm_head", spy as Module)])) + try adapter.bindRows([state], caches: caches) + let intermediate = try adapter.prefillValidated( + tokens: tokens([1, 2, 3, 4]), caches: caches, requirement: .evaluationOnly) + eval(intermediate) + try require( + spy.inputShapes.isEmpty && intermediate.shape == [1], + "intermediate constructed vocabulary logits") + let frontier = try adapter.prefillValidated( + tokens: tokens([5, 6]), caches: caches, requirement: .lastPositionLogits) + eval(frontier) + try require( + spy.inputShapes == [[1, 16]] && frontier.shape == [1, 64], + "frontier projected discarded positions") + try require( + state.allSatisfy { $0?.absoluteOffset == 6 }, + "prompt did not commit all positions") + let reference = try target.forward(inputIDs: tokens([1, 2, 3, 4, 5, 6])) + try near( + frontier, reference.logits[0..., -1, 0...], dtype: .float32, + label: "frontier logits") + backend.release(state) + } + ), + ( + "real native probe accepts empty FP16 placeholders and records FP32 BF16 storage", + { + for type in ["float32", "bfloat16"] { + let (target, adapter, _) = try fixture(type) + let result = try withMiMoConstructionScope { constructionWork in + try adapter.probeNativeKVTypes(retaining: constructionWork) + } + try require( + result.layerDTypes == [target.activationDType, target.activationDType] + && result.observations.count == 4, + "native probe did not observe both phases") + try require( + result.observations.allSatisfy { + $0.keysShape.last == 8 && $0.valuesShape.last == 4 + }, "probe widths") + } + } + ), + ( + "malformed cache owner alias layout history or embeddings reject before writes", + { + let (target, adapter, backend) = try fixture() + let state = try rows(adapter, backend) + let caches = adapter.makeCaches() + try adapter.bindRows([state], caches: caches) + let (_, other, _) = try fixture() + try rejected { + _ = try adapter.forwardValidated( + tokens: tokens([1]), caches: other.makeCaches()) + } + try rejected { + _ = try adapter.forwardValidated( + tokens: tokens([1]), caches: [caches[0], caches[0]]) + } + try rejected { try adapter.bindRows([[state[0], state[0]]], caches: caches) } + var wrong = state + wrong[1] = CBv2WindowedSequenceKV( + window: 3, kvHeads: 2, headDim: 8, valueHeadDim: 8) + try rejected { try adapter.bindRows([wrong], caches: caches) } + try rejected { + _ = try adapter.forwardValidated( + tokens: tokens([1]), inputEmbeddings: MLXArray.zeros([1, 1, 15]), + caches: caches) + } + try rejected { try adapter.validateTokenIDs([-1]) } + try rejected { + try adapter.validateTokenIDs([target.configuration.vocabularySize]) + } + try require( + state.allSatisfy { $0?.absoluteOffset == 0 && $0?.byteCount == 0 }, + "failed preflight mutated an earlier layer") + _ = try adapter.forwardValidated(tokens: tokens([1, 2]), caches: caches) + state[0]!.rollback(1) + try rejected { + _ = try adapter.forwardValidated(tokens: tokens([3]), caches: caches) + } + try require( + state[1]!.absoluteOffset == 2, + "stale-position failure advanced another layer") + backend.release(state) + } + ), + ( + "identical-geometry foreign empty and nonempty rows cannot cross target ownership", + { + let (_, a, backendA) = try fixture() + let (_, b, backendB) = try fixture() + let stateA = try rows(a, backendA) + let stateB = try rows(b, backendB) + let cachesA = a.makeCaches() + let cachesB = b.makeCaches() + try b.bindRows([stateB], caches: cachesB) + try rejected { try b.bindRows([stateA], caches: cachesB) } + try require( + cachesB[0].rows[0] === stateB[0]!, + "foreign empty bind partially replaced owner") + try a.bindRows([stateA], caches: cachesA) + let first = try a.forwardValidated(tokens: tokens([1, 2]), caches: cachesA) + eval(first) + let offsets = stateA.map { $0!.absoluteOffset } + let bytes = stateA.map { $0!.byteCount } + try rejected { try b.bindRows([stateA], caches: cachesB) } + // Simulate an incorrect internal composition caller bypassing + // external bindRows. Forward must independently reject it. + for index in cachesB.indices { cachesB[index].setRows([stateA[index]!]) } + try rejected { + _ = try b.forwardValidated(tokens: tokens([3]), caches: cachesB) + } + try require( + stateA.map { $0!.absoluteOffset } == offsets + && stateA.map { $0!.byteCount } == bytes, + "foreign populated row rejection mutated target A") + try require( + stateB.allSatisfy { $0!.absoluteOffset == 0 && $0!.byteCount == 0 }, + "foreign rejection mutated target B") + try rejected { try backendB.releaseValidated(stateA) } + backendA.release(stateA) + backendB.release(stateB) + } + ), + ( + "owner registration survives reorder join and cancellation but rejects released or spliced rows", + { + let (_, adapter, backend) = try fixture() + let caches = adapter.makeCaches() + let a = try rows(adapter, backend) + let b = try rows(adapter, backend) + try rejected { try adapter.bindRows([[a[0], b[1]]], caches: caches) } + try adapter.bindRows([a, b], caches: caches) + eval( + try adapter.forwardValidated( + tokens: MLXArray([Int32(1), 2], [2, 1]), caches: caches)) + try adapter.bindRows([b, a], caches: caches) + eval( + try adapter.forwardValidated( + tokens: MLXArray([Int32(3), 4], [2, 1]), caches: caches)) + try backend.releaseValidated(a) + try rejected { + _ = try adapter.forwardValidated( + tokens: MLXArray([Int32(5), 6], [2, 1]), caches: caches) + } + try require( + b.allSatisfy { $0!.absoluteOffset == 2 }, + "released-row failure advanced survivor") + try rejected { try adapter.bindRows([a], caches: caches) } + try adapter.bindRows([b], caches: caches) + eval(try adapter.forwardValidated(tokens: tokens([5]), caches: caches)) + let c = try rows(adapter, backend) + try adapter.bindRows([c, b], caches: caches) + eval( + try adapter.forwardValidated( + tokens: MLXArray([Int32(7), 6], [2, 1]), caches: caches)) + try require( + c.allSatisfy { $0!.absoluteOffset == 1 } + && b.allSatisfy { $0!.absoluteOffset == 4 }, + "join did not preserve independent histories") + backend.release(b) + backend.release(c) + try require( + backend.bytesReserved == 0 && backend.bytesInUse == 0, + "cancel lifecycle leaked native owner") + } + ), + ( + "registered sliding rows reject nonzero empty or inadequate retained history", + { + let (_, adapter, backend) = try fixture() + let caches = adapter.makeCaches() + for inadequate in [false, true] { + let state = try rows(adapter, backend) + let count = inadequate ? 4 : 2 + _ = state[0]!.update( + keys: MLXArray.zeros([1, 1, count, 8]), + values: MLXArray.zeros([1, 1, count, 4])) + if inadequate { + _ = state[1]!.update( + keys: MLXArray.zeros([1, 2, 5, 8]), + values: MLXArray.zeros([1, 2, 5, 4])) + state[1]!.rollback(1) + } else { + state[1]!.fastForward(to: 2) + } + let offsets = state.map { $0!.absoluteOffset } + try rejected { try adapter.bindRows([state], caches: caches) } + try require( + state.map { $0!.absoluteOffset } == offsets + && caches.allSatisfy { $0.rows.isEmpty }, + "missing history rejection partially rebound caches") + backend.release(state) + } + } + ), + ( + "weak row metadata is bounded and pruned on registration and removal", + { + let ledger = MiMoV26CBv2RowLedger() + let owner = UUID() + weak var observed: CBv2FullSequenceKV? + for _ in 0 ..< 64 { + var row: CBv2FullSequenceKV? = CBv2FullSequenceKV( + promptLength: 1, maxLength: 2, + kvHeads: 1, headDim: 8, valueHeadDim: 4) + observed = row + try ledger.register([row], backend: owner) + try require( + ledger.metadataEntryCount == 1, + "dead metadata accumulated during registration") + row = nil + try require(observed == nil, "ledger became a strong native row owner") + } + let live = CBv2FullSequenceKV( + promptLength: 1, maxLength: 2, kvHeads: 1, headDim: 8, valueHeadDim: 4) + try ledger.register([live], backend: owner) + var retiring: CBv2FullSequenceKV? = CBv2FullSequenceKV( + promptLength: 1, maxLength: 2, + kvHeads: 1, headDim: 8, valueHeadDim: 4) + try ledger.register([retiring], backend: UUID()) + try require( + ledger.metadataEntryCount == 2 && live.byteCount == 0 + && retiring!.byteCount == 0, + "metadata-only test allocated/duplicated tensor state") + retiring = nil + try ledger.remove([live], backend: owner) + try require( + ledger.metadataEntryCount == 0, + "retirement did not prune other dead weak entries") + } + ), + ( + "serving backend requires completed native probe before reserving precision", + { + for type in ["float32", "bfloat16"] { + let target = try MiMoV26TextModel(configuration(type)) + try fill(target) + let adapter = try MiMoV26CBv2Adapter(target: target) + try rejected { _ = try adapter.makeBackend(bytesCapacity: 16 << 20) } + try rejected { try adapter.bindRows([], caches: adapter.makeCaches()) } + let observed = try withMiMoConstructionScope { constructionWork in + try adapter.probeNativeKVTypes(retaining: constructionWork) + } + let backend = try adapter.makeBackend(bytesCapacity: 16 << 20) + let state = try rows(adapter, backend) + let elementBytes = + Set(observed.layerDTypes).count == 1 ? observed.layerDTypes[0].size : 4 + let expected = (64 * 1 * (8 + 4) + 3 * 2 * (8 + 4)) * elementBytes + try require( + backend.bytesReserved == expected && backend.bytesInUse == 0, + "backend reserved activation-based rather than observed native bytes") + backend.release(state) + try require( + backend.bytesReserved == 0, "probe-bound backend reservation leaked") + } + } + ), + ] + } +} + +#if MIMO_CBV2_COMPONENT_PROBE + @main + private struct MiMoV26CBv2Probe { + static func main() throws { + let cases = MiMoV26CBv2Checks.cases() + var failures = 0 + for (name, body) in cases { + do { + try body() + print("PASS \(name)") + } catch { + failures += 1 + print("FAIL \(name): \(error)") + } + } + print( + "RESULT discovered=\(cases.count) passed=\(cases.count-failures) failed=\(failures) skipped=0" + ) + if failures > 0 { throw MiMoV26CBv2Checks.Failure(message: "MiMo CBv2 probe failed") } + } + } +#else + final class MiMoV26CBv2Tests: XCTestCase { + func testNativeContiguousAdapter() throws { + for (name, body) in MiMoV26CBv2Checks.cases() { + do { try body() } catch { XCTFail("\(name): \(error)") } + } + } + } +#endif diff --git a/Tests/MLXLMTests/MiMo/MiMoV26CausalPositionContractTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26CausalPositionContractTests.swift new file mode 100644 index 0000000000..db23db4352 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26CausalPositionContractTests.swift @@ -0,0 +1,184 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon +@testable import MLXVLM + +/// Direct native numerical/submit regressions only. These deliberately use the +/// existing untracked tiny media fixture, not a fabricated managed contract. +/// Real managed media issuance/preparation/retirement remains a separate gate. +final class MiMoV26CausalPositionContractTests: XCTestCase { + private enum Failure: Error { case expectedPositionRefusal } + + private func prepared(_ fixture: MiMoMediaFixture.Models) throws -> MiMoV26PreparedMultimodal { + let input = MiMoV26MultimodalInput( + messages: [ + .init( + role: .user, + content: [ + .text("before"), .image(MiMoMediaFixture.image()), + .text("01234567890123456789"), + ]) + ], maximumOutputTokens: 18) + return try fixture.processor.prepare( + fixture.processor.plan(input), + authorize: { + MiMoMediaFixture.Reservation($0) + }) + } + + /// Independent ordinary-cache reference: assemble exact native feature + /// spans on the host and run native target prefill/decode. Does not invoke + /// the engine's splice, position planner or changed submit validator. + private func reference( + _ fixture: MiMoMediaFixture.Models, + prepared: MiMoV26PreparedMultimodal + ) throws -> [Int] { + let request = try prepared.makeRequest( + binding: fixture.binding, id: .init(6000), + sampling: .init(temperature: 0)) + let features = try XCTUnwrap(request.multimodal).embeddings() + let text = fixture.target.model.embedTokens( + MLXArray(request.promptTokens.map(Int32.init), [1, request.promptTokens.count])) + var pieces: [MLXArray] = [] + var cursor = 0 + XCTAssertEqual(features.count, prepared.plan.spans.count) + for (span, feature) in zip(prepared.plan.spans, features) { + if cursor < span.tokenOffset { + pieces.append(text[0..., cursor ..< span.tokenOffset, 0...]) + } + pieces.append(feature.expandedDimensions(axis: 0)) + cursor = span.tokenOffset + span.length + } + if cursor < request.promptTokens.count { + pieces.append(text[0..., cursor ..< request.promptTokens.count, 0...]) + } + let cache = fixture.target.newCache() + var logits = try fixture.target.forward( + embeddings: concatenated(pieces, axis: 1), cache: cache + ).logits + var tokens: [Int] = [] + for step in 0 ..< request.maxTokens { + let next = argMax(logits[0..., -1, 0...], axis: -1) + eval(next) + let token = Int(next.item(Int32.self)) + tokens.append(token) + if step + 1 < request.maxTokens { + logits = try fixture.target.forward( + inputIDs: MLXArray([Int32(token)], [1, 1]), cache: cache + ).logits + } + } + return tokens + } + + func testRealProducedImageRequestUsesScalarPositionsAcrossChunksAndSWAWrap() async throws { + for dtype in ["float32", "bfloat16"] { + let fixture = try MiMoMediaFixture.models(dtype) + let model: any CBv2MultimodalSteppableModel = fixture.adapter + // Existential dispatch must use the MiMo extension's witness, not + // accidentally inherit the protocol's required-position default. + XCTAssertEqual(model.causalPositionRequirement, .scalarCacheOffset) + let expectedPrepared = try prepared(fixture) + let expected = try reference(fixture, prepared: expectedPrepared) + let windows = fixture.adapter.layerKinds.compactMap { kind -> Int? in + if case .slidingWindow(let value) = kind.attention { return value } + return nil + } + XCTAssertGreaterThan( + expectedPrepared.plan.promptTokens.count, try XCTUnwrap(windows.max())) + XCTAssertTrue( + fixture.adapter.layerKinds.contains { + if case .full = $0.attention { return true } + return false + }) + for chunk in [1, 3] { + let value = try prepared(fixture) + XCTAssertEqual(value.plan.promptTokens, expectedPrepared.plan.promptTokens) + let request = try value.makeRequest( + binding: fixture.binding, id: .init(UInt64(6100 + chunk)), + sampling: .init(temperature: 0)) + XCTAssertEqual(request.multimodal?.attention, .causal) + XCTAssertNil(request.positionState) + XCTAssertNil(request.multimodal?.positionState) + XCTAssertFalse(request.prefixCacheEnabled) + let (actual, backend) = try MiMoMediaMTPFixture.engine( + fixture.adapter, chunk: chunk) + do { + XCTAssertNil( + actual.nativeShutdownExecutionContractID, + "direct fixture is not managed-media proof") + let result = await cbv2SchedCollect(try actual.submit(request)) + XCTAssertEqual(result.finishReason, .length) + XCTAssertEqual( + result.tokens, expected, + "native scalar positions must preserve exact greedy tokens") + let usage = try XCTUnwrap(result.usage) + XCTAssertEqual(usage.promptTokens, request.promptTokens.count) + XCTAssertEqual(usage.completionTokens, request.maxTokens) + XCTAssertGreaterThan(usage.timing.prefillChunks, 1) + await actual.shutdown() + XCTAssertEqual(backend.bytesReserved, 0) + } catch { + await actual.shutdown() + throw error + } + } + } + } + + func testSuppliedPositionsRemainRejectedWithoutConsumingTheActualMiMoProducer() async throws { + let fixture = try MiMoMediaFixture.models() + for (axisCount, badLength, onMedia) in [ + (3, true, false), (3, false, true), (1, false, false), + ] { + let value = try prepared(fixture) + var request = try value.makeRequest( + binding: fixture.binding, id: .init(6200), + sampling: .init(temperature: 0)) + let positions = CBv2PositionState( + promptPositionIds: MLXArray.zeros( + [axisCount, 1, request.promptTokens.count - (badLength ? 1 : 0)], dtype: .int32), + decodeDeltas: [0]) + if onMedia { + request.multimodal?.positionState = positions + } else { + request.positionState = positions + } + let (actual, backend) = try MiMoMediaMTPFixture.engine(fixture.adapter, chunk: 3) + do { + do { + _ = try actual.submit(request) + XCTFail("MiMo must not silently ignore supplied positions") + throw Failure.expectedPositionRefusal + } catch let error as CBv2MultimodalError { + if badLength { + guard case .invalidSpans(let detail) = error else { throw error } + XCTAssertTrue(detail.contains("position length")) + } else { + guard case .unsupportedModel(let detail) = error else { throw error } + XCTAssertTrue(detail.contains("positioned model forwarding")) + } + } + XCTAssertEqual(backend.bytesReserved, 0) + XCTAssertEqual( + actual.loopForTesting.onEngineQueueSync { actual.loopForTesting.stepCount }, 0) + request.positionState = nil + request.multimodal?.positionState = nil + // Reuse the SAME one-shot produced closure and numeric ID. + // Successful actual submit proves the negative path neither + // consumed the features nor registered a stale generation. + let result = await cbv2SchedCollect(try actual.submit(request)) + XCTAssertEqual(result.finishReason, .length) + XCTAssertEqual(result.tokens.count, request.maxTokens) + await actual.shutdown() + XCTAssertEqual(backend.bytesReserved, 0) + } catch { + await actual.shutdown() + throw error + } + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26ConfigurationTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26ConfigurationTests.swift new file mode 100644 index 0000000000..84b3384548 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26ConfigurationTests.swift @@ -0,0 +1,558 @@ +import Foundation + +#if !MIMO_CONFIG_CPU_PROBE + import MLXLLM + import XCTest +#endif + +// These same assertions run under XCTest or a Foundation-only swiftc probe. +// The probe compiles only this file and MiMoV26Configuration.swift; no MLX load. +private enum MiMoV26ConfigurationChecks { + struct Failure: Error, CustomStringConvertible { + let description: String + } + + static func expect(_ condition: Bool, _ message: String) throws { + if !condition { throw Failure(description: message) } + } + + static func tiny() throws -> MiMoV26Configuration { + try JSONDecoder().decode( + MiMoV26Configuration.self, + from: Data( + """ + { + "model_type":"mimo_v2", "architectures":["MiMoV2ForCausalLM"], + "hidden_size":16, "intermediate_size":32, "moe_intermediate_size":8, + "vocab_size":128, "num_hidden_layers":2, "max_position_embeddings":8192, + "sliding_window_size":7, "sliding_window":7, "num_nextn_predict_layers":3, + "hybrid_layer_pattern":[0,1], "moe_layer_freq":[0,1], + "partial_rotary_factor":0.5, "attention_value_scale":0.707, + "layernorm_epsilon":0.000001, "attention_projection_layout":"split", + "moe_router_dtype":"bfloat16", "hidden_act":"silu", "dtype":"bfloat16", + "attention_bias":false, "tie_word_embeddings":false, "attention_dropout":0, + "scoring_func":"sigmoid", "topk_method":"noaux_tc", "n_routed_experts":4, + "num_experts_per_tok":2, "n_group":1, "topk_group":1, + "norm_topk_prob":true, "n_shared_experts":null, "routed_scaling_factor":null, + "num_attention_heads":4, "num_key_value_heads":1, "head_dim":8, "v_head_dim":4, + "swa_num_attention_heads":4, "swa_num_key_value_heads":2, + "swa_head_dim":8, "swa_v_head_dim":4, "rope_theta":10000000, + "swa_rope_theta":10000, "add_full_attention_sink_bias":false, + "add_swa_attention_sink_bias":true, "eos_token_id":3, "pad_token_id":0, + "bos_token_id":null + } + """.utf8)) + } + + static func decode(_ raw: [String: MiMoV26JSONValue]) throws -> MiMoV26Configuration { + try JSONDecoder().decode(MiMoV26Configuration.self, from: JSONEncoder().encode(raw)) + } + + static func roundtrip(_ config: MiMoV26Configuration) throws { + let data = try JSONEncoder().encode(config) + let tree = try JSONDecoder().decode([String: MiMoV26JSONValue].self, from: data) + try expect(tree == config.rawFields, "semantic JSON was changed by encoding") + try expect( + try JSONDecoder().decode(MiMoV26Configuration.self, from: data) == config, + "typed configuration changed during roundtrip") + } + + static func rejects(_ raw: [String: MiMoV26JSONValue], field: String? = nil) throws { + do { + _ = try decode(raw) + throw Failure(description: "invalid configuration was accepted: \(field ?? "unknown")") + } catch let error as MiMoV26ConfigurationError { + if let field { + guard case .invalid(let actual, _) = error else { return } + try expect(actual.contains(field), "wrong error field \(actual), expected \(field)") + } + } + } + + static func pureCases() -> [(String, () throws -> Void)] { + [ + ( + "tiny geometry and bounds", + { + let config = try tiny() + let full = try config.attentionGeometry(at: 0) + let sliding = try config.attentionGeometry(at: 1) + try expect( + full.headDim == 8 && full.valueHeadDim == 4 && full.rotaryDimensions == 4, + "unequal K/V geometry was lost") + try expect( + full.keyValueHeads == 1 && full.slidingWindow == nil && !full.hasSinks, + "full-attention geometry is wrong") + try expect( + sliding.keyValueHeads == 2 && sliding.slidingWindow == 7 + && sliding.hasSinks, + "sliding-attention geometry is wrong") + for index in [-1, 2] { + do { + _ = try config.attentionGeometry(at: index) + throw Failure(description: "out-of-range layer accepted") + } catch is MiMoV26ConfigurationError {} + } + try roundtrip(config) + } + ), + ( + "unknown nested values preserve integer precision and null", + { + var fields = try tiny().rawFields + let extra = try JSONDecoder().decode( + MiMoV26JSONValue.self, + from: Data( + """ + {"null":null,"bool":true,"text":"keep","large":9007199254740993, + "fraction":0.1234567890123456789012345678,"array":[false,0,"x",{}], + "uint64":18446744073709551615} + """.utf8)) + fields["future_semantics"] = extra + fields["rope_parameters"] = .object([ + "rope_type": .string("default"), "type": .string("default"), + "rope_theta": .number(10_000_000), "partial_rotary_factor": .number(0.5), + "future": extra, + ]) + let config = try decode(fields) + try roundtrip(config) + guard case .object(let extraFields) = config.rawFields["future_semantics"] + else { + throw Failure(description: "missing unknown object") + } + try expect( + extraFields["large"] == .number(Decimal(string: "9007199254740993")!), + "large integer lost precision") + try expect( + extraFields["uint64"] == .number(Decimal(string: "18446744073709551615")!), + "unsigned integer lost precision") + } + ), + ( + "nondefault operational values roundtrip", + { + var fields = try tiny().rawFields + fields["attention_bias"] = .bool(true) + fields["tie_word_embeddings"] = .bool(true) + fields["attention_dropout"] = .number(0.125) + fields["attention_value_scale"] = .number(0.625) + fields["moe_router_dtype"] = .string("float32") + fields["dtype"] = .string("float32") + fields["routed_scaling_factor"] = .number(1.5) + fields["n_shared_experts"] = .number(2) + fields["max_position_embeddings"] = .number(12345) + let config = try decode(fields) + try expect( + config.attentionBias && config.tieWordEmbeddings + && config.attentionDropout == 0.125 + && config.attentionValueScale == 0.625 + && config.routedScalingFactor == 1.5 + && config.sharedExpertCount == 2 + && config.maxPositionEmbeddings == 12345, + "nondefault typed semantics were replaced") + try roundtrip(config) + } + ), + ( + "wrong model and architecture fail recoverably", + { + for type in ["mimo", "mimo_v2_flash", "qwen3", "MIMO_V2"] { + var fields = try tiny().rawFields + fields["model_type"] = .string(type) + try rejects(fields, field: "model_type") + } + var fields = try tiny().rawFields + fields["architectures"] = .array([.string("DFlashDraftModel")]) + try rejects(fields, field: "architectures") + } + ), + ( + "required semantics are not silently defaulted", + { + for key in [ + "model_type", "attention_value_scale", "moe_router_dtype", "v_head_dim", + "add_swa_attention_sink_bias", "num_nextn_predict_layers", + "hybrid_layer_pattern", + "eos_token_id", + ] { + var fields = try tiny().rawFields + fields.removeValue(forKey: key) + try rejects(fields, field: key) + } + } + ), + ( + "JSON type confusion is rejected", + { + for value in [MiMoV26JSONValue.bool(true), .string("16"), .number(16.5), .null] + { + var fields = try tiny().rawFields + fields["hidden_size"] = value + try rejects(fields, field: "hidden_size") + } + var fields = try tiny().rawFields + fields["attention_bias"] = .number(0) + try rejects(fields, field: "attention_bias") + } + ), + ( + "malformed layer and expert geometry is rejected", + { + let changes: [(String, MiMoV26JSONValue)] = [ + ("num_hidden_layers", .number(0)), + ("hybrid_layer_pattern", .array([.number(0)])), + ("moe_layer_freq", .array([.number(0), .number(2)])), + ("num_key_value_heads", .number(3)), + ("swa_num_key_value_heads", .number(3)), + ("n_group", .number(3)), ("topk_group", .number(2)), + ("num_experts_per_tok", .number(5)), ("n_routed_experts", .number(1)), + ("sliding_window", .number(8)), ("v_head_dim", .number(0)), + ("max_position_embeddings", .number(0)), ("layernorm_epsilon", .number(0)), + ("attention_dropout", .number(1)), ("attention_value_scale", .number(-1)), + ] + for (key, value) in changes { + var fields = try tiny().rawFields + fields[key] = value + try rejects(fields) + } + } + ), + ( + "RoPE truncation and conflicting nested semantics", + { + for factor: Decimal in [0, 0.125, 0.375, 1.1] { + var fields = try tiny().rawFields + fields["partial_rotary_factor"] = .number(factor) + try rejects(fields, field: "partial_rotary_factor") + } + var fields = try tiny().rawFields + fields["rope_parameters"] = .object([ + "rope_type": .string("default"), "rope_theta": .number(2), + "partial_rotary_factor": .number(0.5), + ]) + try rejects(fields, field: "rope_parameters") + } + ), + ( + "integer overflow is rejected before allocation", + { + var fields = try tiny().rawFields + fields["hidden_size"] = .number(Decimal(Int.max)) + try rejects(fields, field: "dense MLP") + fields = try tiny().rawFields + fields["head_dim"] = .number(Decimal(Int.max)) + try rejects(fields) + fields = try tiny().rawFields + fields["hidden_size"] = .number(Decimal(string: "18446744073709551615")!) + try rejects(fields, field: "hidden_size") + } + ), + ( + "native mixed quantization and skip policy", + { + var fields = try tiny().rawFields + fields["quantization"] = .object([ + "mode": .string("mxfp4"), "bits": .number(4), "group_size": .number(32), + "mtp.layers.0.eh_proj": .object([ + "mode": .string("affine"), "bits": .number(4), + "group_size": .number(64), + "future": .array([.null, .bool(true)]), + ]), + "model.layers.0.self_attn.o_proj": .bool(false), + "lm_head": .bool(false), + "future_metadata": .object(["flag": .bool(true)]), + ]) + let config = try decode(fields) + try expect( + config.quantization.policy(for: "model.layers.1.mlp.switch_mlp.up_proj")? + .mode == "mxfp4", + "native default missing") + try expect( + config.quantization.policy(for: "mtp.layers.0.eh_proj")?.groupSize == 64, + "MTP policy missing") + try expect( + config.quantization.policy(for: "model.layers.0.self_attn.o_proj") == nil, + "explicit high-precision layer was quantized") + try expect( + config.quantization.policy(for: "lm_head") == nil, + "single-component module override was ignored") + try roundtrip(config) + } + ), + ( + "MLX affine8 aliases preserve the native policy", + { + var fields = try tiny().rawFields + let policy: MiMoV26JSONValue = .object([ + "mode": .string("affine"), "bits": .number(4), "group_size": .number(64), + "language_model.model.embed_tokens": .object([ + "mode": .string("affine"), "bits": .number(8), + "group_size": .number(64), + ]), + ]) + fields["quantization"] = policy + fields["quantization_config"] = policy + let config = try decode(fields) + try expect( + config.quantization.sourceMetadata == nil, + "MLX policy was labelled source FP8") + try expect( + config.quantization.policy(for: "language_model.model.embed_tokens")?.bits + == 8, + "affine8 override was lost") + try roundtrip(config) + fields.removeValue(forKey: "quantization") + try expect( + try decode(fields).quantization == config.quantization, + "single MLX alias was lost") + fields["quantization"] = .object([ + "mode": .string("mxfp4"), "bits": .number(4), "group_size": .number(32), + ]) + try rejects(fields, field: "quantization_config") + } + ), + ( + "unsupported quantization fails rather than falling back", + { + for (mode, bits, group) in [ + ("awq", 4, 32), ("mxfp4", 8, 32), ("mxfp4", 4, 64), ("affine", 4, 32), + ] { + var fields = try tiny().rawFields + fields["quantization"] = .object([ + "mode": .string(mode), "bits": .number(Decimal(bits)), + "group_size": .number(Decimal(group)), + ]) + try rejects(fields, field: "quantization") + } + var fields = try tiny().rawFields + fields["quantization_config"] = .object(["quant_method": .string("gptq")]) + try rejects(fields, field: "quantization_config") + } + ), + ( + "embedded MTP count and path validation", + { + var fields = try tiny().rawFields + let valid: [String: MiMoV26JSONValue] = [ + "architecture": .string("mimo_v2_nextn"), "num_layers": .number(3), + "storage": .string("embedded"), "file": .string("model-mtp.safetensors"), + ] + fields["omlx_mimo_mtp"] = .object(valid) + try expect( + try decode(fields).embeddedMTP?.numLayers == 3, + "three predictors not represented") + for (key, value) in [ + ("num_layers", MiMoV26JSONValue.number(5)), + ("architecture", .string("DFlashDraftModel")), + ("file", .string("../outside.safetensors")), + ] { + var bad = valid + bad[key] = value + fields["omlx_mimo_mtp"] = .object(bad) + try rejects(fields, field: "omlx_mimo_mtp") + } + } + ), + ( + "token namespace is preserved and range checked", + { + var fields = try tiny().rawFields + fields["eos_token_id"] = .number(127) + let config = try decode(fields) + try expect( + config.tokenIDs["eos_token_id"] == 127 + && config.rawFields["bos_token_id"] == .null, + "token IDs/null were normalized") + fields["eos_token_id"] = .number(128) + try rejects(fields, field: "eos_token_id") + } + ), + ( + "all native EOS IDs survive scalar and array contracts", + { + var fields = try tiny().rawFields + fields["eos_token_id"] = .array([.number(3), .number(7), .number(0)]) + let config = try decode(fields) + try expect(config.eosTokenIDs == Set([3, 7, 0]), "EOS set was truncated") + try expect( + config.tokenIDs["eos_token_id"] == 3, "primary EOS ordering was lost") + try roundtrip(config) + for invalid: MiMoV26JSONValue in [ + .array([]), .array([.number(3), .number(3)]), + .array([.number(128)]), .array([.number(-1)]), .array([.number(0.5)]), + .null, + ] { + fields["eos_token_id"] = invalid + try rejects(fields, field: "eos_token_id") + } + } + ), + ] + } + + static func metadataCases(official: URL, native: URL, dflash: URL) -> [( + String, () throws -> Void + )] { + func read(_ url: URL) throws -> MiMoV26Configuration { + try JSONDecoder().decode(MiMoV26Configuration.self, from: Data(contentsOf: url)) + } + return [ + ( + "actual official config geometry and roundtrip", + { + let config = try read(official) + try expect( + config.numHiddenLayers == 48 && config.numNextnPredictLayers == 3, + "wrong target or nextn count") + try expect( + config.hybridLayerPattern.filter { $0 == 0 }.count == 9 + && config.moeLayerFrequency.filter { $0 == 1 }.count == 47, + "wrong trained layer pattern") + try expect( + config.maxPositionEmbeddings == 1_048_576 && config.headDim == 192 + && config.valueHeadDim == 128 + && config.fullAttention.rotaryDimensions == 64 + && config.slidingAttention.keyValueHeads == 8, + "official context/attention was narrowed") + try expect( + config.vision?.depth == 28 && config.audio?.channels == 20 + && config.audio?.zeroEmbeddingIndex == 1024 + && config.tokenIDs["audio_token_id"] == 151669, + "native modality namespace changed") + try expect( + config.quantization.nativeDefault == nil + && config.quantization.sourceMetadata != nil, + "raw source policy mistaken for converted native policy") + try roundtrip(config) + } + ), + ( + "actual native mixed policy and original metadata coexist", + { + let config = try read(native) + try expect( + config.quantization.nativeDefault?.mode == "mxfp4" + && config.quantization.nativeDefault?.groupSize == 32 + && config.quantization.sourceMetadata?["quant_method"] + == .string("fp8"), + "native and provenance policies were conflated") + for depth in 0 ..< 3 { + for prefix in ["mtp", "language_model.mtp"] { + let policy = config.quantization.policy( + for: "\(prefix).layers.\(depth).eh_proj") + try expect( + policy?.mode == "affine" && policy?.bits == 4 + && policy?.groupSize == 64, + "embedded MTP alias policy lost") + } + } + try expect( + config.attentionProjectionLayout == "fused_qkv" + && config.embeddedMTP?.numLayers == 3, + "original layout label or native component metadata mutated") + try roundtrip(config) + } + ), + ( + "actual modality conflicts fail recoverably", + { + let config = try read(official) + guard case .object(let original) = config.rawFields["processor_config"] else { + throw Failure(description: "official processor missing") + } + for key in ["audio_token_id", "audio_channels", "image_token_id"] { + var fields = config.rawFields + var processor = original + processor[key] = .number(1) + fields["processor_config"] = .object(processor) + try rejects(fields, field: "processor_config") + } + var fields = config.rawFields + fields.removeValue(forKey: "processor_config") + try rejects(fields, field: "processor_config") + } + ), + ( + "actual DFlash five layers remain distinct from nextn three", + { + let target = try read(official) + let data = try Data(contentsOf: dflash) + let draft = try JSONDecoder().decode(MiMoV26DFlashMetadata.self, from: data) + try draft.validateTarget(target) + try expect( + draft.numHiddenLayers == 5 && draft.targetLayerIDs == [0, 11, 23, 35, 47] + && draft.blockSize == 8 && draft.maskTokenID == 151675 + && target.numNextnPredictLayers == 3, + "draft and nextn metadata were conflated") + let roundtrip = try JSONDecoder().decode( + MiMoV26DFlashMetadata.self, from: JSONEncoder().encode(draft)) + try expect(roundtrip == draft, "DFlash metadata roundtrip changed") + try rejects(draft.rawFields, field: "model_type") + do { + try draft.validateTarget(tiny()) + throw Failure(description: "wrong target draft binding accepted") + } catch is MiMoV26ConfigurationError {} + } + ), + ] + } +} + +#if MIMO_CONFIG_CPU_PROBE + @main + private struct MiMoV26ConfigurationCPUProbe { + static func main() throws { + let args = CommandLine.arguments + guard args.count == 4 else { + throw MiMoV26ConfigurationChecks.Failure( + description: "expected official, native, DFlash config paths") + } + let cases = + MiMoV26ConfigurationChecks.pureCases() + + MiMoV26ConfigurationChecks.metadataCases( + official: URL(fileURLWithPath: args[1]), native: URL(fileURLWithPath: args[2]), + dflash: URL(fileURLWithPath: args[3])) + var failures = 0 + for (name, body) in cases { + do { + try body() + print("PASS \(name)") + } catch { + failures += 1 + print("FAIL \(name): \(error)") + } + } + print( + "RESULT discovered=\(cases.count) passed=\(cases.count - failures) failed=\(failures) skipped=0" + ) + if failures > 0 { + throw MiMoV26ConfigurationChecks.Failure(description: "configuration probe failed") + } + } + } +#else + final class MiMoV26ConfigurationTests: XCTestCase { + func testPureConfigurationContracts() throws { + for (name, body) in MiMoV26ConfigurationChecks.pureCases() { + do { try body() } catch { XCTFail("\(name): \(error)") } + } + } + + func testActualOfficialAndNativeMetadata() throws { + let environment = ProcessInfo.processInfo.environment + guard let official = environment["MIMO_V26_OFFICIAL_CONFIG"], + let native = environment["MIMO_V26_NATIVE_CONFIG"], + let dflash = environment["MIMO_V26_DFLASH_CONFIG"] + else { + throw XCTSkip( + "Set the three MIMO_V26_*_CONFIG paths for artifact-bound metadata tests") + } + for (name, body) in MiMoV26ConfigurationChecks.metadataCases( + official: URL(fileURLWithPath: official), native: URL(fileURLWithPath: native), + dflash: URL(fileURLWithPath: dflash)) + { + do { try body() } catch { XCTFail("\(name): \(error)") } + } + } + } +#endif diff --git a/Tests/MLXLMTests/MiMo/MiMoV26ConvertedWeightsTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26ConvertedWeightsTests.swift new file mode 100644 index 0000000000..2aaf5e3275 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26ConvertedWeightsTests.swift @@ -0,0 +1,284 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN +import MLXVLM +import XCTest + +final class MiMoV26ConvertedWeightsTests: XCTestCase { + func testActualMetadataPlanCoversCompleteBundle() throws { + let inputs = try fixture("actual") + let plan = try inputs.plan() + XCTAssertEqual(plan.descriptors.count, 1258) + XCTAssertEqual(plan.rootFiles.count, 52) + XCTAssertEqual(plan.tensorBytes, 175_362_324_736) + XCTAssertEqual(plan.components[.target]?.count, 709) + XCTAssertEqual(plan.components[.vision]?.count, 364) + XCTAssertEqual(plan.components[.audioPatch]?.count, 95) + XCTAssertEqual(plan.components[.mtp]?.count, 90) + XCTAssertEqual(plan.targetExpertModulePaths.count, 141) + XCTAssertEqual(plan.configuration.attentionProjectionLayout, "fused_qkv") + XCTAssertFalse(plan.descriptors.keys.contains { $0.contains("qkv_proj") }) + XCTAssertEqual( + plan.descriptors["model.layers.0.self_attn.q_proj.weight"]?.shape, [12288, 4096]) + XCTAssertEqual( + plan.descriptors["model.layers.0.self_attn.v_proj.weight"]?.shape, [512, 4096]) + XCTAssertEqual( + plan.descriptors["model.layers.1.mlp.switch_mlp.gate_proj.weight"]?.dtype, .uint32) + XCTAssertEqual( + plan.descriptors["model.layers.1.mlp.switch_mlp.gate_proj.scales"]?.dtype, .uint8) + XCTAssertEqual( + plan.descriptors["model.layers.1.mlp.gate.e_score_correction_bias"]?.dtype, .float32) + XCTAssertEqual( + plan.configSHA256, "6f1895d782b0b872961a9e03dfef52144c5983d1c7373194290ea854889cacc6") + XCTAssertEqual( + plan.indexSHA256, "2bcc3ba76e2c5502299858e2e8d20b4cb11ae26e7b18609a196c06317e9ac959") + XCTAssertEqual(plan.externalRequiredComponents, ["audio_tokenizer", "dflash"]) + XCTAssertNil(plan.provenance.payloadVerificationReceiptSHA256) + XCTAssertEqual( + plan.configuration.rawFields, + try JSONDecoder().decode(MiMoV26Configuration.self, from: inputs.config).rawFields) + XCTAssertEqual(plan.descriptorSHA256, try inputs.plan().descriptorSHA256) + } + + func testMetadataRejectsMissingExtraShapesPrecisionAndFiles() throws { + let inputs = try fixture("tiny") + let key = "model.layers.1.mlp.switch_mlp.gate_proj.weight" + let original = try XCTUnwrap(inputs.descriptors[key]) + var missing = inputs + missing.descriptors.removeValue(forKey: "visual.blocks.1.attn.sinks") + XCTAssertThrowsError(try missing.plan()) + var extra = inputs + extra.descriptors["audio_tokenizer.encoder.weight"] = original + XCTAssertThrowsError(try extra.plan()) + var wrongShape = inputs + wrongShape.descriptors[key] = .init(shape: [2, 64, 9], dtype: .uint32, file: original.file) + XCTAssertThrowsError(try wrongShape.plan()) + var wrongDType = inputs + wrongDType.descriptors[key] = .init( + shape: original.shape, dtype: .uint8, file: original.file) + XCTAssertThrowsError(try wrongDType.plan()) + var fused = inputs + fused.descriptors.removeValue(forKey: "model.layers.0.self_attn.q_proj.weight") + fused.descriptors["model.layers.0.self_attn.qkv_proj.weight"] = original + XCTAssertThrowsError(try fused.plan()) + var badFile = inputs + badFile.descriptors[key] = .init( + shape: original.shape, dtype: original.dtype, file: "../target.safetensors") + var badIndex = try object(badFile.index) + var badMap = try XCTUnwrap(badIndex["weight_map"] as? [String: String]) + badMap[key] = "../target.safetensors" + badIndex["weight_map"] = badMap + badFile.index = try data(badIndex) + XCTAssertThrowsError(try badFile.plan()) { + XCTAssertEqual($0 as? MiMoV26ConvertedLoadError, .invalidInventory(key)) + } + var wrongTotal = inputs + var index = try object(wrongTotal.index) + index["metadata"] = ["total_size": 1] + wrongTotal.index = try data(index) + XCTAssertThrowsError(try wrongTotal.plan()) + var indexExtra = inputs + var idx = try object(indexExtra.index) + var map = try XCTUnwrap(idx["weight_map"] as? [String: String]) + map["unexpected.weight"] = "target.safetensors" + idx["weight_map"] = map + indexExtra.index = try data(idx) + XCTAssertThrowsError(try indexExtra.plan()) + } + + func testMetadataRejectsUnmappedAndConflictingPolicies() throws { + let inputs = try fixture("tiny") + let key = "mtp.layers.0.self_attn.q_proj" + let alias = "language_model." + key + for change in ["missing", "conflict", "dense", "typo", "unknownMetadata", "headCount"] { + var test = inputs + var c = try object(test.config) + var q = try XCTUnwrap(c["quantization"] as? [String: Any]) + switch change { + case "missing": + q.removeValue(forKey: key) + q.removeValue(forKey: alias) + case "conflict": q[alias] = ["mode": "mxfp4", "bits": 4, "group_size": 32] + case "dense": + q["model.layers.0.self_attn.q_proj"] = [ + "mode": "mxfp4", "bits": 4, "group_size": 32, + ] + case "typo": + q["language_model.mtp.layers.7.self_attn.q_proj"] = [ + "mode": "affine", "bits": 4, "group_size": 64, + ] + case "unknownMetadata": q["unparsed"] = "ignore me" + default: c["num_nextn_predict_layers"] = 2 + } + c["quantization"] = q + test.config = try data(c) + XCTAssertThrowsError(try test.plan(), change) + } + // One valid alias may name the same explicit projection policy. + var single = inputs + var c = try object(single.config) + var q = try XCTUnwrap(c["quantization"] as? [String: Any]) + q.removeValue(forKey: alias) + c["quantization"] = q + single.config = try data(c) + XCTAssertNoThrow(try single.plan()) + } + + func testProvenanceRejectsMalformedIdentityWithoutClaimingPayloadVerification() throws { + var inputs = try fixture("tiny") + inputs.provenance = .init( + artifactID: "", sourceRepository: "wrong/model", sourceRevision: "main", + conversionManifestSHA256: "unknown") + XCTAssertThrowsError(try inputs.plan()) + inputs = try fixture("tiny") + inputs.provenance = .init( + artifactID: "tiny", sourceRepository: inputs.provenance.sourceRepository, + sourceRevision: inputs.provenance.sourceRevision, + conversionManifestSHA256: inputs.provenance.conversionManifestSHA256, + payloadVerificationReceiptSHA256: String(repeating: "a", count: 64)) + let plan = try inputs.plan() + XCTAssertEqual( + plan.provenance.payloadVerificationReceiptSHA256, String(repeating: "a", count: 64)) + // This is only a supplied receipt reference, never a verified-byte flag. + XCTAssertEqual(plan.tensorBytes, 370672) + } + + func testNativeTinyBundleLoadsAllComponentsAndOnlyDeclaredQuantization() throws { + try nativeLane() + let inputs = try fixture("tiny") + let plan = try inputs.plan() + let weights = arrays(plan) + let bundle = try MiMoV26ConvertedWeights.load(plan: plan, tensors: weights) + XCTAssertEqual(bundle.plan.configSHA256, plan.configSHA256) + XCTAssertTrue(bundle.mtp.isLoaded) + XCTAssertEqual(bundle.mtp.headCount, 3) + let leaves = bundle.target.leafModules().flattened() + XCTAssertEqual( + Set(leaves.compactMap { path, module in module is Quantized ? path : nil }), + plan.targetExpertModulePaths) + for (path, module) in leaves where plan.targetExpertModulePaths.contains(path) { + let packed = try XCTUnwrap(module as? QuantizedSwitchLinear) + XCTAssertEqual(packed.groupSize, 32) + XCTAssertEqual(packed.bits, 4) + XCTAssertEqual(packed.mode, .mxfp4) + } + let targetWeights = Dictionary(uniqueKeysWithValues: bundle.target.parameters().flattened()) + XCTAssertEqual(Set(targetWeights.keys), try XCTUnwrap(plan.components[.target])) + for (key, value) in targetWeights { + XCTAssertEqual(value.shape, weights[key]?.shape) + XCTAssertEqual(value.dtype, weights[key]?.dtype) + } + let result = try bundle.target.forward(inputIDs: MLXArray([Int32(1), 2, 3]).reshaped(1, 3)) + eval(result.logits) + XCTAssertEqual(result.logits.shape, [1, 3, 128]) + XCTAssertTrue(result.logits.asArray(Float.self).allSatisfy(\.isFinite)) + let audio = try bundle.audioPatch.forward( + clips: [.init(codes: [Int32](repeating: 1, count: 20), frameCount: 1)], + limits: .init( + maximumClips: 1, maximumFrames: 1, maximumPatches: 1, + maximumWorkingElements: 100_000)) + let vision = try bundle.vision.forward( + patches: MLXArray.zeros([4, 24]), grids: [.init(temporal: 1, height: 2, width: 2)], + limits: .init(maximumPatches: 4, maximumAttentionScoreElements: 1000)) + eval(audio.features, vision) + XCTAssertEqual(audio.features.shape, [1, 64]) + XCTAssertEqual(vision.shape, [1, 64]) + XCTAssertTrue(audio.features.asArray(Float.self).allSatisfy(\.isFinite)) + XCTAssertTrue(vision.asArray(Float.self).allSatisfy(\.isFinite)) + } + + func testNativeInvalidSecondBundleDoesNotModifyPublishedFirstBundle() throws { + try nativeLane() + let plan = try fixture("tiny").plan() + let weights = arrays(plan) + let first = try MiMoV26ConvertedWeights.load(plan: plan, tensors: weights) + let ids = MLXArray([Int32(1), 2]).reshaped(1, 2) + let before = try first.target.forward(inputIDs: ids).logits + eval(before) + var missing = weights + missing.removeValue(forKey: "mtp.layers.2.eh_proj.biases") + XCTAssertThrowsError(try MiMoV26ConvertedWeights.load(plan: plan, tensors: missing)) + var badType = weights + badType["model.norm.weight"] = weights["model.norm.weight"]!.asType(.int32) + XCTAssertThrowsError(try MiMoV26ConvertedWeights.load(plan: plan, tensors: badType)) + var extra = weights + extra["dflash.fc.weight"] = MLXArray.zeros([1]) + XCTAssertThrowsError(try MiMoV26ConvertedWeights.load(plan: plan, tensors: extra)) + // This metadata plan and tensor map pass complete inventory preflight, + // but target construction rejects an unsupported execution semantic. + // Exercise a late construction failure, not just missing-map failures. + var late = try fixture("tiny") + var configuration = try object(late.config) + configuration["rope_scaling"] = ["type": "linear", "factor": 2] + late.config = try data(configuration) + let latePlan = try late.plan() + XCTAssertThrowsError(try MiMoV26ConvertedWeights.load(plan: latePlan, tensors: weights)) { + XCTAssertEqual($0 as? MiMoV26ExecutionError, .unsupportedConfiguration("rope_scaling")) + } + let after = try first.target.forward(inputIDs: ids).logits + eval(after) + XCTAssertEqual(before.asArray(Float.self), after.asArray(Float.self)) + XCTAssertTrue(first.mtp.isLoaded) + } + + private struct Inputs { + var config, index: Data + var descriptors: [String: MiMoV26ConvertedTensorDescriptor] + var provenance: MiMoV26ConvertedProvenance + func plan() throws -> MiMoV26ConvertedLoadPlan { + try .make( + configurationData: config, indexData: index, descriptors: descriptors, + provenance: provenance) + } + } + private func fixture(_ prefix: String) throws -> Inputs { + guard let root = ProcessInfo.processInfo.environment["MIMO_V26_CONVERTED_LOAD_FIXTURES"] + else { + throw XCTSkip("Set MIMO_V26_CONVERTED_LOAD_FIXTURES to metadata-only fixture directory") + } + let url = URL(fileURLWithPath: root) + let config = try Data(contentsOf: url.appendingPathComponent(prefix + "-config.json")) + let index = try Data(contentsOf: url.appendingPathComponent(prefix + "-index.json")) + let descriptors = try JSONDecoder().decode( + [String: MiMoV26ConvertedTensorDescriptor].self, + from: Data(contentsOf: url.appendingPathComponent(prefix + "-descriptors.json"))) + let p = try object(Data(contentsOf: url.appendingPathComponent("provenance.json"))) + let provenance = try MiMoV26ConvertedProvenance( + artifactID: XCTUnwrap(p["artifactID"] as? String), + sourceRepository: XCTUnwrap(p["sourceRepository"] as? String), + sourceRevision: XCTUnwrap(p["sourceRevision"] as? String), + conversionManifestSHA256: XCTUnwrap(p["conversionManifestSHA256"] as? String)) + return .init(config: config, index: index, descriptors: descriptors, provenance: provenance) + } + private func nativeLane() throws { + guard ProcessInfo.processInfo.environment["MIMO_V26_CONVERTED_LOAD_NATIVE_TESTS"] == "1" + else { + throw XCTSkip( + "Requires an exclusive native execution lane and MIMO_V26_CONVERTED_LOAD_NATIVE_TESTS=1" + ) + } + } + private func arrays(_ plan: MiMoV26ConvertedLoadPlan) -> [String: MLXArray] { + plan.descriptors.mapValues { d in + let count = d.shape.reduce(1, *) + switch d.dtype { + case .uint32: + return MLXArray([UInt32](repeating: 0x2222_2222, count: count)).reshaped(d.shape) + case .uint8: return MLXArray([UInt8](repeating: 127, count: count)).reshaped(d.shape) + default: + return MLXArray((0 ..< count).map { Float(($0 % 13) + 1) / 100 }).reshaped(d.shape) + .asType( + d.dtype == .bfloat16 + ? .bfloat16 : (d.dtype == .float16 ? .float16 : .float32)) + } + } + } + private func object(_ d: Data) throws -> [String: Any] { + try XCTUnwrap(JSONSerialization.jsonObject(with: d) as? [String: Any]) + } + private func data(_ object: [String: Any]) throws -> Data { + try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26DecodeExpertsTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26DecodeExpertsTests.swift new file mode 100644 index 0000000000..b0e51e0eac --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26DecodeExpertsTests.swift @@ -0,0 +1,239 @@ +import Foundation +import MLX +import MLXNN +import XCTest + +@testable import MLXLMCommon + +final class MiMoV26DecodeExpertEligibilityTests: XCTestCase { + func testShortPackedShapeContract() { + for rows in 1 ... 7 { + XCTAssertTrue( + MiMoV26DecodeExperts.supports( + rows: rows, hidden: 4096, + intermediate: 2048, experts: 256, topK: 8, dtype: .bfloat16)) + } + for rows in [0, 8] { + XCTAssertFalse( + MiMoV26DecodeExperts.supports( + rows: rows, hidden: 4096, + intermediate: 2048, experts: 256, topK: 8, dtype: .bfloat16)) + } + for hidden in [0, 4000, 8192] { + XCTAssertFalse( + MiMoV26DecodeExperts.supports( + rows: 1, hidden: hidden, + intermediate: 2048, experts: 256, topK: 8, dtype: .bfloat16)) + } + XCTAssertFalse( + MiMoV26DecodeExperts.supports( + rows: 1, hidden: 4096, + intermediate: 2048, experts: 256, topK: 6, dtype: .bfloat16)) + XCTAssertFalse( + MiMoV26DecodeExperts.supports( + rows: 1, hidden: 4096, + intermediate: 2048, experts: 256, topK: 8, dtype: .float32)) + } +} + +final class MiMoV26DecodeExpertsTests: XCTestCase { + override func setUpWithError() throws { + guard ProcessInfo.processInfo.environment["MLX_TEST_MIMO_DECODE_KERNELS"] == "1" else { + throw XCTSkip("Requires explicitly owned native lane") + } + guard MiMoV26DecodeExperts.gpuStream(.default), MLXHardwareInfo.isCompiledDecodeSupported + else { + throw XCTSkip("Requires the actual GPU stream and existing compiled SiLU contract") + } + } + + private typealias Matrix = MiMoV26DecodeExperts.Matrix + + private func packed(_ experts: Int, _ output: Int, _ input: Int, salt: Int) -> Matrix { + let count = experts * output * input / 8 + // Direct native codes/scales, not a requantized reference. Nibbles + // exercise both signs, signed zeros and every E2M1 magnitude. + let words = (0 ..< count).map { UInt32(truncatingIfNeeded: $0 * 2_654_435_761 + salt * 97) } + let scales = (0 ..< experts * output * input / 32).map { UInt8(120 + ($0 + salt) % 7) } + return Matrix( + weight: MLXArray(words, [experts, output, input / 8]), + scales: MLXArray(scales, [experts, output, input / 32])) + } + + private func gather(_ x: MLXArray, _ matrix: Matrix, _ indices: MLXArray) -> MLXArray { + MLX.gatherQuantizedMM( + x, matrix.weight, scales: matrix.scales, + biases: nil, rhsIndices: indices, transpose: true, + groupSize: 32, bits: 4, mode: .mxfp4) + } + + private func exact(_ actual: MLXArray, _ expected: MLXArray, _ label: String) { + XCTAssertEqual(actual.shape, expected.shape, label) + XCTAssertEqual(actual.dtype, expected.dtype, label) + eval(actual, expected) + let left = actual.view(dtype: .uint16).asArray(UInt16.self) + let right = expected.view(dtype: .uint16).asArray(UInt16.self) + func ordered(_ value: UInt16) -> UInt16 { + value & 0x8000 == 0 ? value | 0x8000 : ~value + } + let maximum: UInt16 = + zip(left, right).map { a, b in + let x = ordered(a) + let y = ordered(b) + return x > y ? x - y : y - x + }.max() ?? 0 + XCTAssertEqual(maximum, 0, "\(label) maxStorageULP=\(maximum)") + XCTAssertEqual(left, right, label + " storage bits") + } + + private func indices(rows: Int, pattern: Int) -> MLXArray { + let ids: [UInt32] = (0 ..< rows * 8).map { p in + let row = p / 8 + let slot = p % 8 + switch pattern { + case 0: return UInt32((slot + row) % 12) // cross-row sharing, unique per row + case 1: return 3 // every slot shares one expert + case 2: return UInt32((slot / 3 + row % 2) % 12) // both duplicate kinds + default: return UInt32((7 - slot + 2 * row) % 12) // reversed slot order + } + } + return MLXArray(ids, [1, rows, 8]) + } + + func testEveryShortRowCountAndDuplicatePatternMatchesStockMXFP4() throws { + let gate = packed(12, 512, 1024, salt: 1) + let up = packed(12, 512, 1024, salt: 7) + let down = packed(12, 1024, 512, salt: 11) + let fused = Matrix( + weight: concatenated([gate.weight, up.weight], axis: 1), + scales: concatenated([gate.scales, up.scales], axis: 1)) + for dtype: DType in [.bfloat16, .float16] { + for rows in 1 ... 7 { + let input = (0 ..< rows * 1024).map { sin(Float(($0 * 17 + 13) % 509)) * 0.2 } + let x = MLXArray(input, [1, rows, 1024]).asType(dtype) + for pattern in 0 ... 3 { + let ids = indices(rows: rows, pattern: pattern) + let expanded = MLX.expandedDimensions(x, axes: [-2, -3]) + let referenceActivation = compiledSiluProduct( + gather(expanded, gate, ids), + gather(expanded, up, ids)) + let referenceOutput = gather(referenceActivation, down, ids).squeezed(axis: -2) + for fusion in [false, true] { + let actual = try XCTUnwrap( + MiMoV26DecodeExperts.project( + x, indices: ids, gate: fusion ? fused : gate, + up: fusion ? fused : up, down: down, upOffset: fusion ? 512 : 0)) + exact( + actual.activation, referenceActivation.squeezed(axis: -2), + "activation \(dtype) rows\(rows) pattern\(pattern) fused\(fusion)") + exact( + actual.output, referenceOutput, + "down \(dtype) rows\(rows) pattern\(pattern) fused\(fusion)") + } + } + } + } + } + + func testActualFusedNonlinearityAcrossEveryFiniteLowPrecisionGate() { + let kernel = MLXFast.metalKernel( + name: "mimo_v26_decode_swiglu_contract_test", inputNames: ["g", "u"], + outputNames: ["y"], + source: "uint i = thread_position_in_grid.x; y[i] = mimo_swiglu(g[i], u[i]);", + header: MiMoV26DecodeExpertMetal.header) + for dtype: DType in [.bfloat16, .float16] { + let mask: UInt16 = dtype == .bfloat16 ? 0x7f80 : 0x7c00 + let bits = (0 ... 65535).map(UInt16.init).filter { $0 & mask != mask } + let gates = MLXArray(bits).view(dtype: dtype) + let fractions: [Float] = [0.125, 0.75, 1.0625, -1.25, 3.140625] + let ups = MLXArray(bits.indices.map { fractions[$0 % fractions.count] }).asType(dtype) + let actual = kernel( + [gates, ups], grid: (bits.count, 1, 1), threadGroup: (128, 1, 1), + outputShapes: [[bits.count]], outputDTypes: [dtype])[0] + exact(actual, compiledSiluProduct(gates, ups), "every finite \(dtype) gate") + } + } + + func testReloadAndNoncontiguousInputDoNotUseStaleMatrices() throws { + let gate = packed(8, 512, 512, salt: 2) + let up = packed(8, 512, 512, salt: 3) + let down = packed(8, 512, 512, salt: 4) + let newGate = packed(8, 512, 512, salt: 5) + let ids = MLXArray((0 ..< 24).map { UInt32($0 % 8) }, [1, 3, 8]) + let x = MLXArray((0 ..< 1536).map { cos(Float($0)) * 0.1 }, [1, 512, 3]) + .asType(.bfloat16).transposed(0, 2, 1) + for current in [gate, newGate] { + let actual = try XCTUnwrap( + MiMoV26DecodeExperts.project( + x, indices: ids, gate: current, up: up, down: down)) + let input = MLX.expandedDimensions(x, axes: [-2, -3]) + let act = compiledSiluProduct(gather(input, current, ids), gather(input, up, ids)) + exact(actual.output, gather(act, down, ids).squeezed(axis: -2), "fresh matrix") + } + } + + func testStockOwnedQuantizedModulesEngageAndKeepOriginalParameterObjects() throws { + let glu = SwitchGLU( + inputDims: 512, hiddenDims: 512, numExperts: 8, + weightedReductionProfile: .mimoV26FP32) + quantize( + model: glu, + filter: { _, module in + module is SwitchLinear ? (groupSize: 32, bits: 4, mode: .mxfp4) : nil + }) + let gate = packed(8, 512, 512, salt: 2) + let up = packed(8, 512, 512, salt: 4) + let down = packed(8, 512, 512, salt: 6) + let leaves = ["gate_proj": gate, "up_proj": up, "down_proj": down] + let parameters = glu.parameters().flattened().map { name, original in + let parts = name.split(separator: ".") + guard parts.count == 2, let matrix = leaves[String(parts[0])] else { + return (name, original) + } + return (name, parts[1] == "weight" ? matrix.weight : matrix.scales) + } + try glu.update(parameters: .unflattened(parameters), verify: .all) + let before = Dictionary(uniqueKeysWithValues: glu.parameters().flattened()) + let x = MLXArray((0 ..< 1536).map { sin(Float($0)) * 0.15 }, [1, 3, 512]).asType(.bfloat16) + let ids = MLXArray((0 ..< 24).map { UInt32(($0 / 3) % 8) }, [1, 3, 8]) + let result = try XCTUnwrap( + MiMoV26DecodeExperts.tryProject(x, indices: ids, glu: glu, enabled: true)) + let input = MLX.expandedDimensions(x, axes: [-2, -3]) + let act = compiledSiluProduct(gather(input, gate, ids), gather(input, up, ids)) + exact(result.activation, act.squeezed(axis: -2), "stock module activation") + exact(result.output, gather(act, down, ids).squeezed(axis: -2), "stock module output") + for (name, array) in glu.parameters().flattened() { + XCTAssertTrue(before[name] === array, "parameter view/requantization change: \(name)") + } + } + + func testActualCPUStreamAndUnsupportedPackedLayoutsRefuse() throws { + let matrix = packed(8, 512, 512, salt: 1) + let x = MLXArray.ones([1, 1, 512], dtype: .bfloat16) + let ids = MLXArray((0 ..< 8).map(UInt32.init), [1, 1, 8]) + Device.withDefaultDevice(.gpu) { + Stream.withNewDefaultStream(device: .cpu) { + XCTAssertEqual(Device.defaultDevice().deviceType, .gpu) + XCTAssertFalse(MiMoV26DecodeExperts.gpuStream(.default)) + XCTAssertNil( + MiMoV26DecodeExperts.project( + x, indices: ids, gate: matrix, up: matrix, down: matrix)) + } + } + let wrongScales = Matrix(weight: matrix.weight, scales: matrix.scales.asType(.bfloat16)) + XCTAssertNil( + MiMoV26DecodeExperts.project( + x, indices: ids, gate: wrongScales, up: matrix, down: matrix)) + XCTAssertNil( + MiMoV26DecodeExperts.project( + x, indices: ids, gate: matrix, up: matrix, down: matrix, upOffset: 1)) + let ordinary = SwitchGLU( + inputDims: 512, hiddenDims: 512, numExperts: 8, + weightedReductionProfile: .mimoV26FP32) + XCTAssertNil( + MiMoV26DecodeExperts.tryProject(x, indices: ids, glu: ordinary, enabled: true), + "dense leaves cannot enter MXFP4 kernels") + XCTAssertNil( + MiMoV26DecodeExperts.tryProject(x, indices: ids, glu: ordinary, enabled: false)) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26DecodeKernelsTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26DecodeKernelsTests.swift new file mode 100644 index 0000000000..445d4e90fa --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26DecodeKernelsTests.swift @@ -0,0 +1,353 @@ +// Copyright © 2026 Eigen Labs. +// Native tests for the source-only #3990 residual/norm port. They are NOT run +// by preparing this packet and require the coordinator's exclusive native lane. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN +import XCTest + +@testable import MLXLLM + +final class MiMoV26DecodeEligibilityTests: XCTestCase { + func testNarrowShapeDTypeAndDeviceContract() { + for rows in 1 ... 7 { + for type: DType in [.bfloat16, .float16] { + XCTAssertTrue( + MiMoV26DecodeKernels.supports( + shape: [1, rows, 4096], dtype: type, device: .gpu)) + } + } + for shape in [ + [1, 0, 4096], [1, 8, 4096], [2, 1, 4096], [1, 1, 4097], + [1, 1, 8192], [4096], [1, 1, 0], [1, 1, 3], + ] { + XCTAssertFalse( + MiMoV26DecodeKernels.supports( + shape: shape, dtype: .bfloat16, device: .gpu)) + } + XCTAssertFalse( + MiMoV26DecodeKernels.supports( + shape: [1, 1, 4096], dtype: .float32, device: .gpu)) + XCTAssertFalse( + MiMoV26DecodeKernels.supports( + shape: [1, 1, 4096], dtype: .bfloat16, device: .cpu)) + } +} + +final class MiMoV26DecodeKernelsTests: XCTestCase { + override func setUpWithError() throws { + guard ProcessInfo.processInfo.environment["MLX_TEST_MIMO_DECODE_KERNELS"] == "1" else { + throw XCTSkip("Requires explicit native-lane run: MLX_TEST_MIMO_DECODE_KERNELS=1") + } + guard Device.defaultDevice().deviceType == .gpu else { + throw XCTSkip("The Metal dispatch cannot be qualified by a CPU fallback") + } + } + + private func signal(_ shape: [Int], dtype: DType, salt: Int = 0) -> MLXArray { + let size = shape.reduce(1, *) + let values = (0 ..< size).map { i in + sin(Float((i * 13 + salt * 17) % 251)) * Float(1 + i % 5) + } + return MLXArray(values, shape).asType(dtype) + } + + private func norm(_ width: Int, dtype: DType, salt: Int = 1) throws -> RMSNorm { + let result = RMSNorm(dimensions: width, eps: 1e-6) + let gamma = (0 ..< width).map { i in 1 + Float((i + salt) % 17 - 8) / 32 } + try result.update( + parameters: .unflattened([ + ("weight", MLXArray(gamma).asType(dtype)) + ]), verify: .all) + return result + } + + /// Check actual storage bits, plus an explicit maximum-ULP report. This + /// slice claims zero ULP for every row, so no tolerance is inherited from + /// the upstream verify-router or attention tests. + private func exact( + _ actual: MLXArray, _ expected: MLXArray, _ label: String, + file: StaticString = #filePath, line: UInt = #line + ) { + XCTAssertEqual(actual.shape, expected.shape, label, file: file, line: line) + XCTAssertEqual(actual.dtype, expected.dtype, label, file: file, line: line) + eval(actual, expected) + let values = actual.asType(.float32).asArray(Float.self) + let reference = expected.asType(.float32).asArray(Float.self) + XCTAssertTrue(values.allSatisfy(\.isFinite), label, file: file, line: line) + XCTAssertTrue(reference.allSatisfy(\.isFinite), label, file: file, line: line) + func ordered(_ bits: UInt32) -> UInt32 { + bits & 0x8000_0000 == 0 ? bits | 0x8000_0000 : ~bits + } + let maxULP: UInt32 = + zip(values, reference).map { a, b in + let x = ordered(a.bitPattern) + let y = ordered(b.bitPattern) + return x > y ? x - y : y - x + }.max() ?? 0 + XCTAssertEqual(maxULP, 0, "\(label) maxFloat32ULP=\(maxULP)", file: file, line: line) + if actual.dtype == .bfloat16 || actual.dtype == .float16 { + XCTAssertEqual( + actual.view(dtype: .uint16).asArray(UInt16.self), + expected.view(dtype: .uint16).asArray(UInt16.self), + label + " storage bits", file: file, line: line) + } else { + XCTAssertEqual( + values.map(\.bitPattern), reference.map(\.bitPattern), + label + " storage bits", file: file, line: line) + } + } + + func testAddRMSMatchesPinnedPrimitiveIncludingTailAndStrides() throws { + for type: DType in [.bfloat16, .float16] { + for width in [4, 128, 4000, 4096] { + let normalizer = try norm(width, dtype: type) + for rows in 1 ... 7 { + let x = signal([1, width, rows], dtype: type).transposed(0, 2, 1) + let y = signal([1, rows, width], dtype: type, salt: 2) + let actual = try XCTUnwrap(MiMoV26DecodeKernels.addRMS(x, y, norm: normalizer)) + let residual = x + y + exact(actual.residual, residual, "add \(type) rows\(rows) D\(width)") + exact( + actual.normalized, normalizer(residual), + "norm \(type) rows\(rows) D\(width)") + } + } + } + } + + func testCombineKeepsFP32ScoresProductsAndIntermediateRounding() throws { + for type: DType in [.bfloat16, .float16] { + for rows in 1 ... 7 { + let width = 4096 + let normalizer = try norm(width, dtype: type) + let hidden = signal([1, rows, width], dtype: type) + let experts = signal([1, rows, 8, width], dtype: type, salt: 3) + // Values deliberately distinguish FP32 routing from BF16. + let scoreValues: [Float] = (0 ..< (rows * 8)).map { index in + let routed: Float = Float(index % 8 + 1) / 37 + let roundingWitness: Float = 1.0 / 65536 + return routed + roundingWitness + } + let weights = MLXArray(scoreValues, [1, rows, 8]) + let actual = try XCTUnwrap( + MiMoV26DecodeKernels.combineRMS( + hidden, experts: experts, weights: weights, norm: normalizer)) + let reduced = (experts * weights[.ellipsis, .newAxis]).sum(axis: -2).asType(type) + let residual = hidden + reduced + exact(actual.residual, residual, "combine \(type) rows\(rows)") + exact(actual.normalized, normalizer(residual), "combine norm \(type) rows\(rows)") + } + } + } + + func testUnsupportedAndChangedNormWeightsUseTheReference() throws { + let x = signal([1, 1, 128], dtype: .bfloat16) + let normalizer = try norm(128, dtype: .bfloat16) + let first = try XCTUnwrap(MiMoV26DecodeKernels.addRMS(x, x, norm: normalizer)) + let changed = (0 ..< 128).map { Float(1 + $0 % 9) / 8 } + try normalizer.update( + parameters: .unflattened([ + ("weight", MLXArray(changed).asType(.bfloat16)) + ]), verify: .all) + let second = try XCTUnwrap(MiMoV26DecodeKernels.addRMS(x, x, norm: normalizer)) + exact(second.normalized, normalizer(x + x), "fresh norm weights") + eval(first.normalized, second.normalized) + XCTAssertFalse(arrayEqual(first.normalized, second.normalized).item(Bool.self)) + let fp32Norm = try norm(128, dtype: .float32) + XCTAssertNil(MiMoV26DecodeKernels.addRMS(x, x, norm: fp32Norm)) + XCTAssertNil( + MiMoV26DecodeKernels.addRMS( + signal([1, 8, 128], dtype: .bfloat16), signal([1, 8, 128], dtype: .bfloat16), + norm: normalizer)) + let experts = signal([1, 1, 8, 128], dtype: .bfloat16) + XCTAssertNil( + MiMoV26DecodeKernels.combineRMS( + x, experts: experts, weights: MLXArray(Float(1)), norm: normalizer)) + XCTAssertNil( + MiMoV26DecodeKernels.combineRMS( + x, experts: experts, weights: signal([1, 1, 8], dtype: .bfloat16), norm: normalizer) + ) + } + + private func configuration() throws -> MiMoV26Configuration { + try JSONDecoder().decode( + MiMoV26Configuration.self, + from: Data( + """ + {"model_type":"mimo_v2","architectures":["MiMoV2ForCausalLM"], + "hidden_size":128,"intermediate_size":256,"moe_intermediate_size":64, + "vocab_size":64,"num_hidden_layers":2,"max_position_embeddings":128, + "sliding_window_size":7,"sliding_window":7,"num_nextn_predict_layers":3, + "hybrid_layer_pattern":[0,1],"moe_layer_freq":[0,1], + "partial_rotary_factor":0.334,"attention_value_scale":0.707, + "layernorm_epsilon":0.000001,"attention_projection_layout":"split", + "moe_router_dtype":"bfloat16","hidden_act":"silu","dtype":"bfloat16", + "attention_bias":false,"tie_word_embeddings":false,"attention_dropout":0, + "scoring_func":"sigmoid","topk_method":"noaux_tc","n_routed_experts":16, + "num_experts_per_tok":8,"n_group":1,"topk_group":1,"norm_topk_prob":true, + "n_shared_experts":null,"routed_scaling_factor":null, + "num_attention_heads":8,"num_key_value_heads":2,"head_dim":48,"v_head_dim":32, + "swa_num_attention_heads":8,"swa_num_key_value_heads":4,"swa_head_dim":48, + "swa_v_head_dim":32,"rope_theta":10000000,"swa_rope_theta":10000, + "add_full_attention_sink_bias":false,"add_swa_attention_sink_bias":true, + "eos_token_id":3,"pad_token_id":0} + """.utf8)) + } + + private func model(fused: Bool) throws -> MiMoV26TextModel { + let result = try MiMoV26TextModel(configuration()) + let values = result.parameters().flattened().map { name, array in + let salt = name.utf8.reduce(0) { ($0 + Int($1)) % 997 } + let data = (0 ..< array.size).map { i -> Float in + if name.contains("norm.weight") { return 1 + Float((i + salt) % 11 - 5) / 32 } + return sin(Float((i * 13 + salt) % 109)) * 0.12 + } + let dtype: DType = name.hasSuffix("e_score_correction_bias") ? .float32 : .bfloat16 + return (name, MLXArray(data, array.shape).asType(dtype)) + } + try result.update(parameters: .unflattened(values), verify: .all) + result.model.useFusedDecodeNorms = fused + return result + } + + private func ids(_ start: Int, _ count: Int) -> MLXArray { + MLXArray((start ..< start + count).map { Int32($0 % 63) }, [1, count]) + } + + private func completeOrdinaryState(_ actual: [KVCache], _ expected: [KVCache]) { + XCTAssertEqual(actual.count, expected.count) + for (index, pair) in zip(actual, expected).enumerated() { + let (a, b) = pair + XCTAssertEqual(a.offset, b.offset, "layer \(index) offset") + XCTAssertEqual(a.metaState, b.metaState, "layer \(index) metadata") + XCTAssertEqual(a.state.count, b.state.count) + for (i, arrays) in zip(a.state, b.state).enumerated() { + exact(arrays.0, arrays.1, "layer \(index) complete active state \(i)") + } + } + } + + func testOrdinaryForwardExactGreedyHiddenFeaturesAndCompleteCache() throws { + let reference = try model(fused: false) + let candidate = try model(fused: true) + let refCache = reference.newCache() + let fastCache = candidate.newCache() + var position = 0 + // Initial fallback prefill; every short row count; wrap and fallback + // reentry. The baseline always uses the unmodified router/attention. + for count in [9, 1, 2, 3, 4, 5, 6, 7, 8, 1] { + let tokens = ids(position, count) + let expected = try reference.forward( + inputIDs: tokens, cache: refCache, captureLayers: [0, 1]) + let actual = try candidate.forward( + inputIDs: tokens, cache: fastCache, captureLayers: [0, 1]) + exact(actual.logits, expected.logits, "ordinary logits rows\(count)") + exact( + actual.normalizedHiddenStates, expected.normalizedHiddenStates, "target post-norm") + for layer in [0, 1] { + exact( + try XCTUnwrap(actual.layerFeatures[layer]), + try XCTUnwrap(expected.layerFeatures[layer]), "raw layer feature \(layer)") + } + XCTAssertEqual( + argMax(actual.logits, axis: -1).asArray(UInt32.self), + argMax(expected.logits, axis: -1).asArray(UInt32.self)) + completeOrdinaryState(fastCache, refCache) + position += count + } + } + + private struct ManagedFixture { + let target: MiMoV26TextModel + let adapter: MiMoV26CBv2Adapter + let backend: MiMoV26CBv2Backend + let caches: [any CBv2AttendingLayerCache] + let rows: [CBv2SequenceKV?] + } + + private func managed(fused: Bool) throws -> ManagedFixture { + let target = try model(fused: fused) + let adapter = try MiMoV26CBv2Adapter(target: target) + let work = NativeConstructionScope() + defer { if work.snapshot.isRetainedFault { _ = Unmanaged.passRetained(work) } } + _ = try adapter.probeNativeKVTypes(retaining: work) + let backend = try adapter.makeBackend(bytesCapacity: 16 << 20) + let rows = try backend.makeSequenceState( + layerKinds: adapter.layerKinds, promptLength: 9, maxLength: 128) + let caches = adapter.makeCaches() + try adapter.bindRows([rows], caches: caches) + return ManagedFixture( + target: target, adapter: adapter, backend: backend, caches: caches, rows: rows) + } + + private func completeManagedState(_ actual: ManagedFixture, _ expected: ManagedFixture) throws { + XCTAssertEqual(actual.rows.count, expected.rows.count) + for (index, pair) in zip(actual.rows, expected.rows).enumerated() { + let a = try XCTUnwrap(pair.0) + let b = try XCTUnwrap(pair.1) + XCTAssertEqual(a.absoluteOffset, b.absoluteOffset, "managed layer\(index) offset") + XCTAssertEqual(a.retainedCount, b.retainedCount, "managed layer\(index) retained count") + let left = a.snapshot() + let right = b.snapshot() + XCTAssertEqual(left.offset, right.offset) + exact(left.keys, right.keys, "managed layer\(index) all retained keys") + exact(left.values, right.values, "managed layer\(index) all retained values") + } + } + + private func step(_ fixture: ManagedFixture, _ tokens: MLXArray) throws -> MLXArray { + try fixture.adapter.bindRows([fixture.rows], caches: fixture.caches) + return try fixture.adapter.forwardValidated(tokens: tokens, caches: fixture.caches) + } + + func testManagedTrunkExactGreedyAndCompleteCacheForEveryRowCount() throws { + let reference = try managed(fused: false) + let candidate = try managed(fused: true) + defer { + reference.backend.release(reference.rows) + candidate.backend.release(candidate.rows) + } + var position = 0 + for count in [9, 1, 2, 3, 4, 5, 6, 7, 8, 1] { + let expected = try step(reference, ids(position, count)) + let actual = try step(candidate, ids(position, count)) + exact(actual, expected, "managed logits rows\(count)") + XCTAssertEqual( + argMax(actual, axis: -1).asArray(UInt32.self), + argMax(expected, axis: -1).asArray(UInt32.self)) + try completeManagedState(candidate, reference) + position += count + } + } + + func testManagedRollbackEveryPrefixPreservesFullAndWindowState() throws { + for accepted in 0 ... 7 { + let reference = try managed(fused: false) + let candidate = try managed(fused: true) + defer { + reference.backend.release(reference.rows) + candidate.backend.release(candidate.rows) + } + exact(try step(candidate, ids(0, 9)), try step(reference, ids(0, 9)), "prompt") + for fixture in [reference, candidate] { + for row in fixture.rows { try XCTUnwrap(row).beginSpeculativeWrite() } + } + exact(try step(candidate, ids(9, 7)), try step(reference, ids(9, 7)), "verify rows") + for fixture in [reference, candidate] { + for item in fixture.rows { + let row = try XCTUnwrap(item) + row.rollback(7 - accepted) + row.commitSpeculativeWrite() + } + } + try completeManagedState(candidate, reference) + exact( + try step(candidate, ids(9 + accepted, 1)), + try step(reference, ids(9 + accepted, 1)), "post-rollback decode") + try completeManagedState(candidate, reference) + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26DecodeRouterTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26DecodeRouterTests.swift new file mode 100644 index 0000000000..eb1231391c --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26DecodeRouterTests.swift @@ -0,0 +1,174 @@ +// Copyright © 2026 Eigen Labs. +// Source-only native test candidate; requires the exclusive native lane. + +import Foundation +import MLX +import MLXNN +import XCTest + +@testable import MLXLLM + +final class MiMoV26DecodeRouterEligibilityTests: XCTestCase { + func testOnlyAlignedShortGPURouterShapesAreEligible() { + func supported( + _ shape: [Int], _ weight: [Int], _ type: DType = .bfloat16, + _ operand: DType = .bfloat16, _ device: DeviceType = .gpu + ) -> Bool { + MiMoV26DecodeRouter.supports( + shape: shape, weightShape: weight, + inputDType: type, weightDType: type, operandDType: operand, device: device) + } + for rows in 1 ... 7 { XCTAssertTrue(supported([1, rows, 4096], [256, 4096])) } + XCTAssertTrue(supported([1, 2, 1024], [64, 1024], .float32, .float32)) + XCTAssertFalse(supported([2, 1, 4096], [256, 4096])) + XCTAssertFalse(supported([1, 8, 4096], [256, 4096])) + XCTAssertFalse(supported([1, 1, 4000], [256, 4000])) + XCTAssertFalse(supported([1, 1, 1024], [256, 1024])) + XCTAssertFalse(supported([1, 1, 4096], [255, 4096])) + XCTAssertFalse(supported([1, 1, 4096], [256, 2048])) + XCTAssertFalse(supported([1, 1, 4096], [256, 4096], .uint32)) + XCTAssertFalse(supported([1, 1, 4096], [256, 4096], .bfloat16, .float16)) + XCTAssertFalse(supported([1, 1, 4096], [256, 4096], .bfloat16, .bfloat16, .cpu)) + } +} + +final class MiMoV26DecodeRouterTests: XCTestCase { + override func setUpWithError() throws { + guard ProcessInfo.processInfo.environment["MLX_TEST_MIMO_DECODE_KERNELS"] == "1" else { + throw XCTSkip("Requires explicit native-lane run: MLX_TEST_MIMO_DECODE_KERNELS=1") + } + guard Device.defaultDevice().deviceType == .gpu else { + throw XCTSkip("Metal dispatch cannot be qualified by a CPU fallback") + } + } + + private func signal(_ shape: [Int], salt: Int, positive: Bool = false) -> MLXArray { + MLXArray( + (0 ..< shape.reduce(1, *)).map { i -> Float in + let value = sin(Float((i * 13 + salt * 19) % 4093)) + return positive ? 0.01 + abs(value) * 0.01 : value * 0.1 + }, shape) + } + + private func maxULP(_ a: MLXArray, _ b: MLXArray) -> UInt32 { + eval(a, b) + XCTAssertEqual(a.shape, b.shape) + XCTAssertEqual(a.dtype, .float32) + XCTAssertEqual(b.dtype, .float32) + let left = a.asArray(Float.self) + let right = b.asArray(Float.self) + XCTAssertTrue(left.allSatisfy(\.isFinite) && right.allSatisfy(\.isFinite)) + func ordered(_ bits: UInt32) -> UInt32 { + bits & 0x8000_0000 == 0 ? bits | 0x8000_0000 : ~bits + } + return zip(left, right).map { x, y in + let u = ordered(x.bitPattern) + let v = ordered(y.bitPattern) + return u > v ? u - v : v - u + }.max() ?? 0 + } + + private func perRow(_ x: MLXArray, _ w: MLXArray, operand: DType) -> MLXArray { + let matrix = w.asType(operand).asType(.float32).T + return concatenated( + (0 ..< x.dim(1)).map { row in + matmul(x[0..., row ..< row + 1, 0...].asType(operand).asType(.float32), matrix) + }, axis: 1) + } + + func testNativeRouterShapeMatchesIndependentDecodeGEMVAtEveryRowCount() throws { + let weight = signal([256, 4096], salt: 3).asType(.bfloat16) + for rows in 1 ... 7 { + let x = signal([1, 4096, rows], salt: rows).asType(.bfloat16).transposed(0, 2, 1) + let actual = try XCTUnwrap( + MiMoV26DecodeRouter.logits( + x, weight: weight, operandDType: .bfloat16, enabled: true)) + let expected = perRow(x, weight, operand: .bfloat16) + XCTAssertEqual(maxULP(actual, expected), 0, "rows \(rows), per-row FP32 GEMV") + XCTAssertEqual( + actual.view(dtype: .uint32).asArray(UInt32.self), + expected.view(dtype: .uint32).asArray(UInt32.self)) + } + } + + func testDeclaredOperandCastAndWeightReloadArePreserved() throws { + let x = signal([1, 3, 1024], salt: 11) + let initial = signal([64, 1024], salt: 7) + for operand: DType in [.bfloat16, .float32] { + for weight in [initial, initial * 1.01 + 0.001] { + let actual = try XCTUnwrap( + MiMoV26DecodeRouter.logits( + x, weight: weight, operandDType: operand, enabled: true)) + XCTAssertEqual(maxULP(actual, perRow(x, weight, operand: operand)), 0) + } + } + let rounded = perRow(x, initial, operand: .bfloat16) + let unrounded = perRow(x, initial, operand: .float32) + XCTAssertGreaterThan( + maxULP(rounded, unrounded), 0, "fixture must detect a skipped BF16 cast") + XCTAssertNil( + MiMoV26DecodeRouter.logits(x, weight: initial, operandDType: .bfloat16, enabled: false)) + } + + private func select(_ logits: MLXArray, _ bias: MLXArray) -> (MLXArray, MLXArray) { + let scores = sigmoid(logits) + let indices = argPartition(-(scores + bias), kth: 7, axis: -1)[.ellipsis, ..<8] + var weights = takeAlong(scores, indices, axis: -1) + weights = weights / (weights.sum(axis: -1, keepDims: true) + 1e-20) + return (indices, weights) + } + + func testVerifyReportsBatchedULPAndPreservesFixtureExpertSelection() throws { + // The original <=2 normalized-weight bound is contradicted by an + // independent STOCK per-row-vs-batched witness on the exact fixture. + // Require candidate bits to match the original per-row FP32 pipeline; + // retain the original batched selection and logit guard separately. + let w = signal([256, 4096], salt: 23, positive: true).asType(.bfloat16) + let bias = MLXArray((0 ..< 256).map { Float($0) / 1024 }) + for rows in 1 ... 7 { + let x = signal([1, rows, 4096], salt: 29, positive: true).asType(.bfloat16) + let actual = try XCTUnwrap( + MiMoV26DecodeRouter.logits( + x, weight: w, operandDType: .bfloat16, enabled: true)) + // Independent stock reference: no candidate helper/custom kernel. + let independent = perRow(x, w, operand: .bfloat16) + let candidatePerRowLogitsULP = maxULP(actual, independent) + XCTAssertEqual( + candidatePerRowLogitsULP, 0, "positive fixture exact stock per-row logits") + XCTAssertEqual( + actual.view(dtype: .uint32).asArray(UInt32.self), + independent.view(dtype: .uint32).asArray(UInt32.self)) + + let batched = matmul(x.asType(.float32), w.asType(.float32).T) + let logitsULP = maxULP(actual, batched) + let nativeBaselineLogitsULP = maxULP(independent, batched) + let a = select(actual, bias) + let rowOracle = select(independent, bias) + let batchOracle = select(batched, bias) + let candidatePerRowScoresULP = maxULP(a.1, rowOracle.1) + XCTAssertEqual( + candidatePerRowScoresULP, 0, "positive fixture exact stock normalized weights") + XCTAssertEqual( + a.1.view(dtype: .uint32).asArray(UInt32.self), + rowOracle.1.view(dtype: .uint32).asArray(UInt32.self)) + XCTAssertEqual( + a.0.asArray(UInt32.self), rowOracle.0.asArray(UInt32.self), + "exact stock per-row routed experts") + XCTAssertEqual( + a.0.asArray(UInt32.self), batchOracle.0.asArray(UInt32.self), + "exact original batched routed experts") + let scoresULP = maxULP(a.1, batchOracle.1) + let nativeBaselineScoresULP = maxULP(rowOracle.1, batchOracle.1) + // Context only: no new 3-ULP (or other) score tolerance. + print( + "MiMo router rows=\(rows) candidatePerRowLogitULP=\(candidatePerRowLogitsULP) candidatePerRowScoreULP=\(candidatePerRowScoresULP) candidateBatchLogitULP=\(logitsULP) nativeBatchLogitULP=\(nativeBaselineLogitsULP) candidateBatchScoreULP=\(scoresULP) nativeBatchScoreULP=\(nativeBaselineScoresULP)" + ) + if rows == 1 { + XCTAssertEqual(logitsULP, 0) + XCTAssertEqual(scoresULP, 0) + } else { + XCTAssertLessThanOrEqual(logitsULP, 64, "positive fixture only") + } + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26DecodeRowsTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26DecodeRowsTests.swift new file mode 100644 index 0000000000..7064c1a263 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26DecodeRowsTests.swift @@ -0,0 +1,80 @@ +import Foundation +import MLX +import MLXFast +import MLXRandom +import XCTest + +@testable import MLXLMCommon + +final class MiMoV26DecodeRowsTests: XCTestCase { + func testPlanUsesEveryScalarReferenceBoundary() { + XCTAssertNil(MiMoV26DecodeRows.serialBlocks(rows: 3, keys: 1024, deviceClass: "d")) + XCTAssertEqual(MiMoV26DecodeRows.serialBlocks(rows: 3, keys: 1026, deviceClass: "d"), 128) + XCTAssertNil(MiMoV26DecodeRows.serialBlocks(rows: 3, keys: 16384, deviceClass: "d")) + XCTAssertEqual(MiMoV26DecodeRows.serialBlocks(rows: 3, keys: 16386, deviceClass: "d"), 512) + XCTAssertNil(MiMoV26DecodeRows.serialBlocks(rows: 4, keys: 65536, deviceClass: "d")) + XCTAssertEqual(MiMoV26DecodeRows.serialBlocks(rows: 4, keys: 65539, deviceClass: "d"), 1024) + XCTAssertNil(MiMoV26DecodeRows.serialBlocks(rows: 3, keys: 8193, deviceClass: "s")) + XCTAssertNil(MiMoV26DecodeRows.serialBlocks(rows: 3, keys: 32769, deviceClass: "s")) + XCTAssertEqual( + MiMoV26DecodeRows.serialBlocks(rows: 3, keys: 8193, deviceClass: "s", override: 65), 96) + XCTAssertNil( + MiMoV26DecodeRows.serialBlocks(rows: 3, keys: 8193, deviceClass: "s", override: Int.max) + ) + XCTAssertNil(MiMoV26DecodeRows.serialBlocks(rows: 1, keys: 8193, deviceClass: "d")) + XCTAssertNil(MiMoV26DecodeRows.serialBlocks(rows: 5, keys: 8193, deviceClass: "d")) + XCTAssertNil( + MiMoV26DecodeRows.serialBlocks(rows: 3, keys: 8193, kvHeads: 8, deviceClass: "d")) + } + + func testFullCausalRowsMatchActualScalarFP32PartialAttention() throws { + guard ProcessInfo.processInfo.environment["DARKBLOOM_TEST_MIMO_DECODE_ROWS"] == "1", + MiMoV26NAXGatherQMM.gpuStream(.default) + else { + throw XCTSkip("Requires exclusive native GPU qualification") + } + let name = GPU.deviceInfo().architecture + guard name.hasPrefix("applegpu_"), let deviceClass = name.last else { + throw XCTSkip("Unknown native Metal block policy") + } + let override = Int(ProcessInfo.processInfo.environment["MLX_SDPA_BLOCKS"] ?? "") ?? 0 + for dtype in [DType.bfloat16, .float16] { + for rows in 2 ... 4 { + for keys in [1100, 4099, 16400, 65540] { + let blocks = try XCTUnwrap( + MiMoV26DecodeRows.serialBlocks( + rows: rows, keys: keys, deviceClass: deviceClass, override: override)) + let q = (MLXRandom.normal([1, 64, rows, 192], key: MLXRandom.key(301)) * 0.2) + .asType(dtype) + let k = (MLXRandom.normal([1, 4, keys, 192], key: MLXRandom.key(302)) * 0.2) + .asType(dtype) + let v = (MLXRandom.normal([1, 4, keys, 128], key: MLXRandom.key(303)) * 0.2) + .asType(dtype) + for hasSinks in [false, true] { + let sinks = + hasSinks + ? MLXArray(Array(repeating: Float(-1.75), count: 64)).asType(dtype) + : nil + let actual = MiMoV26DecodeRows.launch( + queries: q, keys: k, values: v, + scale: 0.07216878, sinks: sinks, blocks: blocks) + let expected = concatenated( + (0 ..< rows).map { row in + MLXFast.scaledDotProductAttention( + queries: q[0..., 0..., row ..< row + 1, 0...], + keys: k[0..., 0..., ..<(keys - rows + row + 1), 0...], + values: v[0..., 0..., ..<(keys - rows + row + 1), 0...], + scale: 0.07216878, mask: .none, sinks: sinks) + }, axis: 2) + eval(actual, expected) + XCTAssertEqual(actual.shape, expected.shape) + XCTAssertEqual( + actual.asData(access: .copy).data, expected.asData(access: .copy).data, + "scalar parity dtype=\(dtype) rows=\(rows) keys=\(keys) sinks=\(hasSinks)" + ) + } + } + } + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26DecodeStreamTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26DecodeStreamTests.swift new file mode 100644 index 0000000000..a2b90705e8 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26DecodeStreamTests.swift @@ -0,0 +1,72 @@ +import Foundation +import MLX +import MLXNN +import XCTest + +@testable import MLXLLM + +final class MiMoV26DecodeStreamTests: XCTestCase { + override func setUpWithError() throws { + guard ProcessInfo.processInfo.environment["MLX_TEST_MIMO_DECODE_KERNELS"] == "1" else { + throw XCTSkip("Requires explicitly owned native lane") + } + } + + private func normalizer() throws -> RMSNorm { + let norm = RMSNorm(dimensions: 128, eps: 1e-6) + try norm.update( + parameters: .unflattened([ + ("weight", MLXArray.ones([128], dtype: .bfloat16)) + ]), verify: .all) + return norm + } + + func testTaskLocalCPURefusesBothKernelsWhenDefaultDeviceIsGPU() throws { + try Device.withDefaultDevice(.gpu) { + try Stream.withNewDefaultStream(device: .cpu) { + XCTAssertEqual(Device.defaultDevice().deviceType, .gpu) + XCTAssertEqual(MiMoV26DecodeStream.deviceType(of: .default), .cpu) + let x = MLXArray.ones([1, 1, 128], dtype: .bfloat16) + let norm = try normalizer() + XCTAssertNil(MiMoV26DecodeKernels.addRMS(x, x, norm: norm)) + XCTAssertNil( + MiMoV26DecodeKernels.combineRMS( + x, experts: MLXArray.ones([1, 1, 8, 128], dtype: .bfloat16), + weights: MLXArray.ones([1, 1, 8], dtype: .float32), norm: norm)) + XCTAssertNil( + MiMoV26DecodeRouter.logits( + MLXArray.ones([1, 1, 1024], dtype: .bfloat16), + weight: MLXArray.ones([64, 1024], dtype: .bfloat16), + operandDType: .bfloat16, enabled: true)) + // The reference still evaluates on the selected CPU stream. + let expected = norm(x + x) + eval(expected) + XCTAssertTrue(expected.asType(.float32).asArray(Float.self).allSatisfy(\.isFinite)) + } + } + } + + func testOrdinaryGPUControlEngagesAndMatchesReference() throws { + try Device.withDefaultDevice(.gpu) { + XCTAssertEqual(MiMoV26DecodeStream.deviceType(of: .default), .gpu) + let x = MLXArray.ones([1, 1, 128], dtype: .bfloat16) + let norm = try normalizer() + let result = try XCTUnwrap(MiMoV26DecodeKernels.addRMS(x, x, norm: norm)) + let expected = norm(x + x) + eval(result.normalized, expected) + XCTAssertEqual( + result.normalized.view(dtype: .uint16).asArray(UInt16.self), + expected.view(dtype: .uint16).asArray(UInt16.self)) + let vector = MLXArray.ones([1, 1, 1024], dtype: .bfloat16) + let matrix = MLXArray.ones([64, 1024], dtype: .bfloat16) + let logits = try XCTUnwrap( + MiMoV26DecodeRouter.logits( + vector, weight: matrix, operandDType: .bfloat16, enabled: true)) + let reference = matmul(vector.asType(.float32), matrix.asType(.float32).T) + eval(logits, reference) + XCTAssertEqual( + logits.asArray(Float.self).map(\.bitPattern), + reference.asArray(Float.self).map(\.bitPattern)) + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26DecodedAudiovisualTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26DecodedAudiovisualTests.swift new file mode 100644 index 0000000000..b8e84783f2 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26DecodedAudiovisualTests.swift @@ -0,0 +1,102 @@ +import Foundation +import XCTest + +@testable import MLXVLM + +/// Independent scalar expectations only; no tokenizer, codec, pixels or MLX. +final class MiMoV26DecodedAudiovisualTests: XCTestCase { + func testInterleaveZeroUsesPatchRateAndKeepsUnusedWholeAudioBacking() throws { + let value = try MiMoV26AudiovisualLayout.make( + timestamps: [0, 0.16, 0.32], + segmentEnd: .float32(0.48), temporalPatchSize: 2, wholeAudioPatches: 4, maximumUnits: 2) + XCTAssertEqual(value.units.map(\.audioRange), [0 ..< 2, 2 ..< 3]) + XCTAssertEqual(value.units.map(\.visualGroup), [0, 1]) + XCTAssertEqual(value.units.map(\.timestamp), [0, 0.32]) + XCTAssertEqual(value.alignedFrames, 4) + XCTAssertEqual(value.duplicatedFrames, 1) + XCTAssertEqual(value.wholeAudioPatches, 4) + XCTAssertEqual(value.usedAudioPatches, 3) + XCTAssertEqual(value.unusedAudioPatches, 1) + } + func testFloat32MultiplyBeforeTruncationIsNotFloat64Promotion() throws { + let good = try MiMoV26AudiovisualLayout.make( + timestamps: [0, 0.16, 0.32], + segmentEnd: .float32(0.48), temporalPatchSize: 2, wholeAudioPatches: 4, maximumUnits: 2) + XCTAssertEqual(good.units[1].audioRange, 2 ..< 3) + // Float32(.48)*6.25 rounds to3. Promoting the stored F32 first + // yields2.9999999329...: truncation would make the final unit empty. + XCTAssertThrowsError( + try MiMoV26AudiovisualLayout.make( + timestamps: [0, 0.16, 0.32], + segmentEnd: .float64(Double(Float(0.48))), temporalPatchSize: 2, + wholeAudioPatches: 4, maximumUnits: 2)) + } + func testClippedEndIsNotSilencePaddingOrDroppingAnEmptyUnit() throws { + let clipped = try MiMoV26AudiovisualLayout.make( + timestamps: [0, 1, 2], + segmentEnd: .float32(3), temporalPatchSize: 2, wholeAudioPatches: 14, maximumUnits: 2) + XCTAssertEqual(clipped.units.map(\.audioRange), [0 ..< 12, 12 ..< 14]) + XCTAssertEqual(clipped.unusedAudioPatches, 0) + XCTAssertThrowsError( + try MiMoV26AudiovisualLayout.make( + timestamps: [0, 1, 2], + segmentEnd: .float32(3), temporalPatchSize: 2, wholeAudioPatches: 12, + maximumUnits: 2)) + } + func testWholeAudioPrefixAndTailAreNotRefundedByARepresentedSlice() throws { + let value = try MiMoV26AudiovisualLayout.make( + timestamps: [1, 1.16], + segmentEnd: .float32(1.32), temporalPatchSize: 2, wholeAudioPatches: 10, maximumUnits: 2 + ) + XCTAssertEqual(value.units[0].audioRange, 6 ..< 8) + XCTAssertEqual(value.wholeAudioPatches, 10) + XCTAssertEqual(value.usedAudioPatches, 2) + XCTAssertEqual(value.unusedAudioPatches, 8) + } + func testSingleFrameAlignsWithoutInventingAnotherAudioUnit() throws { + let value = try MiMoV26AudiovisualLayout.make( + timestamps: [0], + segmentEnd: .float32(1), temporalPatchSize: 2, wholeAudioPatches: 1, maximumUnits: 1) + XCTAssertEqual(value.alignedFrames, 2) + XCTAssertEqual(value.duplicatedFrames, 1) + XCTAssertEqual(value.units.count, 1) + XCTAssertEqual(value.units[0].audioRange, 0 ..< 1) + } + func testMalformedAndResourceBoundsRefuseBeforeUnitAllocation() throws { + for times in [[Float](), [0, 0], [1, 0], [-1, 0], [0, .nan], [0, .infinity]] { + XCTAssertThrowsError( + try MiMoV26AudiovisualLayout.make( + timestamps: times, + segmentEnd: .float32(3), temporalPatchSize: 2, wholeAudioPatches: 20, + maximumUnits: 2)) + } + for end in [ + MiMoV26DecodedAudiovisual.SegmentEnd.float32(.infinity), .float64(.nan), + .float32(0), .float32(0.01), + ] { + XCTAssertThrowsError( + try MiMoV26AudiovisualLayout.make( + timestamps: [0], + segmentEnd: end, temporalPatchSize: 2, wholeAudioPatches: 20, maximumUnits: 2)) + } + XCTAssertThrowsError( + try MiMoV26AudiovisualLayout.make( + timestamps: [0, 1, 2], + segmentEnd: .float32(3), temporalPatchSize: 2, wholeAudioPatches: 20, + maximumUnits: 1)) + XCTAssertThrowsError( + try MiMoV26AudiovisualLayout.make( + timestamps: [0], + segmentEnd: .float32(1), temporalPatchSize: 0, wholeAudioPatches: 20, + maximumUnits: 1)) + XCTAssertThrowsError( + try MiMoV26AudiovisualLayout.make( + timestamps: [0], + segmentEnd: .float32(1), temporalPatchSize: 2, wholeAudioPatches: 0, maximumUnits: 1 + )) + let largeFinite = try MiMoV26AudiovisualLayout.make( + timestamps: [0], + segmentEnd: .float64(1e20), temporalPatchSize: 2, wholeAudioPatches: 4, maximumUnits: 1) + XCTAssertEqual(largeFinite.units[0].audioRange, 0 ..< 4) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26EncodedAudioDecoderTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26EncodedAudioDecoderTests.swift new file mode 100644 index 0000000000..266764d7de --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26EncodedAudioDecoderTests.swift @@ -0,0 +1,126 @@ +import Foundation +import XCTest + +@testable import MLXVLM + +/// Pure byte/scalar tests; no model, decoder backend, resampler or native eval. +final class MiMoV26EncodedAudioDecoderTests: XCTestCase { + private func u16(_ n: UInt16) -> [UInt8] { + [UInt8(truncatingIfNeeded: n), UInt8(truncatingIfNeeded: n >> 8)] + } + private func u32(_ n: UInt32) -> [UInt8] { + [ + UInt8(truncatingIfNeeded: n), UInt8(truncatingIfNeeded: n >> 8), + UInt8(truncatingIfNeeded: n >> 16), UInt8(truncatingIfNeeded: n >> 24), + ] + } + private func chunk(_ name: String, _ body: [UInt8]) -> [UInt8] { + Array(name.utf8) + u32(UInt32(body.count)) + body + (body.count % 2 == 1 ? [0] : []) + } + private func wave( + _ bytes: [UInt8], code: UInt16 = 1, bits: UInt16 = 16, + channels: UInt16 = 1, rate: UInt32 = 24000, + leading: [UInt8] = [], trailing: [UInt8] = [] + ) -> Data { + let block = channels * (bits / 8) + let format = + u16(code) + u16(channels) + u32(rate) + u32(rate * UInt32(block)) + u16(block) + + u16(bits) + let body = + Array("WAVE".utf8) + leading + chunk("fmt ", format) + chunk("data", bytes) + trailing + return Data(Array("RIFF".utf8) + u32(UInt32(body.count)) + body) + } + private let limits = MiMoV26EncodedAudioDecoder.Limits( + maximumEncodedBytes: 65536, + maximumFrames: 8192, maximumWorkingBytes: 65536) + func testPCM16BytesProduceExactNativeScalarsAndFrameCount() throws { + let bits: [UInt16] = [0x8000, 0xffff, 0, 1, 0x7fff] + let bytes = wave(bits.flatMap(u16)) + let plan = try MiMoV26EncodedAudioDecoder.inspect(bytes, limits: limits) + let pcm = try MiMoV26EncodedAudioDecoder.decode(plan) + let expectedBits: [UInt32] = [0xbf80_0000, 0xb800_0000, 0, 0x3800_0000, 0x3f7f_fe00] + XCTAssertEqual(plan.encoding, .pcm16) + XCTAssertEqual(plan.frameCount, 5) + XCTAssertEqual(plan.encodedByteCount, bytes.count) + XCTAssertEqual(pcm.descriptor.frameCount, 5) + XCTAssertEqual(pcm.descriptor.channels, 1) + XCTAssertEqual(pcm.descriptor.sampleRate, 24000) + XCTAssertEqual(pcm.samples.map(\.bitPattern), expectedBits) + XCTAssertEqual(pcm.descriptor.sourceIdentity, plan.sourceIdentity) + XCTAssertEqual(plan.decodedByteBound, 5 * 4 + 1024) + } + func testFloat32PreservesBitsSignedZeroAndFiniteOutOfUnitRangeWithoutNormalization() throws { + let values: [Float] = [ + Float(bitPattern: 0x8000_0000), 0, 1.25, -2, Float.leastNormalMagnitude, + ] + let bytes = wave(values.flatMap { u32($0.bitPattern) }, code: 3, bits: 32) + let pcm = try MiMoV26EncodedAudioDecoder.decode( + MiMoV26EncodedAudioDecoder.inspect(bytes, limits: limits)) + XCTAssertEqual(pcm.samples.map(\.bitPattern), values.map(\.bitPattern)) + XCTAssertEqual(pcm.descriptor.frameCount, values.count) + } + func testOddMetadataPaddingDataSliceAndFactCountDoNotChangeSamples() throws { + let bytes = wave( + u16(0x1234) + u16(0x8000), + leading: chunk("JUNK", [1, 2, 3]), trailing: chunk("fact", u32(2))) + var backing = Data([9, 8, 7]) + backing.append(bytes) + let sliced = backing[backing.index(backing.startIndex, offsetBy: 3)...] + let a = try MiMoV26EncodedAudioDecoder.decode( + MiMoV26EncodedAudioDecoder.inspect(bytes, limits: limits)) + let b = try MiMoV26EncodedAudioDecoder.decode( + MiMoV26EncodedAudioDecoder.inspect(sliced, limits: limits)) + XCTAssertEqual(a.samples.map(\.bitPattern), b.samples.map(\.bitPattern)) + XCTAssertEqual(a.descriptor.sourceIdentity, b.descriptor.sourceIdentity) + XCTAssertThrowsError( + try MiMoV26EncodedAudioDecoder.inspect( + wave(u16(1), trailing: chunk("fact", u32(2))), limits: limits)) + } + func testMalformedTruncatedDuplicateAndUnalignedDataRefuseBeforePCMReturn() throws { + let good = wave(u16(1)) + var badLength = good + badLength[4] = 0xff + var badBlock = good + badBlock[32] = 0 + var malformed = [ + Data(), Data("RIFF".utf8), Data(good.dropLast()), badLength, badBlock, + wave([1]), wave([], code: 1), wave(u16(1), trailing: chunk("data", u16(2))), + ] + var wrongEndian = good + wrongEndian[3] = UInt8(ascii: "X") + malformed.append(wrongEndian) + for data in malformed { + XCTAssertThrowsError(try MiMoV26EncodedAudioDecoder.inspect(data, limits: limits)) + } + } + func testChannelsRateEncodingAndNonfiniteValuesRemainExplicitRefusals() throws { + for data in [ + wave(u16(1) + u16(2), channels: 2), wave(u16(1), rate: 48000), wave(u16(1), code: 6), + ] { + XCTAssertThrowsError(try MiMoV26EncodedAudioDecoder.inspect(data, limits: limits)) + } + for value in [Float.infinity, Float.nan] { + let plan = try MiMoV26EncodedAudioDecoder.inspect( + wave(u32(value.bitPattern), code: 3, bits: 32), limits: limits) + XCTAssertThrowsError(try MiMoV26EncodedAudioDecoder.decode(plan)) { + XCTAssertEqual($0 as? MiMoV26EncodedAudioDecoder.Failure, .nonfiniteSamples) + } + } + } + func testExactFrameWorkingByteAndChunkCeilingsRejectBeforeAllocation() throws { + let data = wave(u16(1) + u16(2)) + for cap in [ + MiMoV26EncodedAudioDecoder.Limits( + maximumEncodedBytes: data.count - 1, maximumFrames: 2, maximumWorkingBytes: 65536), + .init(maximumEncodedBytes: 65536, maximumFrames: 1, maximumWorkingBytes: 65536), + .init(maximumEncodedBytes: 65536, maximumFrames: 2, maximumWorkingBytes: 1031), + .init( + maximumEncodedBytes: 65536, maximumFrames: 2, maximumWorkingBytes: 65536, + maximumChunks: 1), + ] { + XCTAssertThrowsError(try MiMoV26EncodedAudioDecoder.inspect(data, limits: cap)) { + XCTAssertEqual($0 as? MiMoV26EncodedAudioDecoder.Failure, .limit) + } + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26EncodedAudiovisualDecoderTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26EncodedAudiovisualDecoderTests.swift new file mode 100644 index 0000000000..be4110d518 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26EncodedAudiovisualDecoderTests.swift @@ -0,0 +1,314 @@ +import Foundation +import MLXLMCommon +import XCTest + +@testable import MLXVLM + +/// Prepared/unrun CPU transport tests. No MLX/model/codec-weight work. +final class MiMoV26EncodedAudiovisualDecoderTests: XCTestCase { + private let videoLimits = MiMoV26EncodedVisualDecoder.Limits( + maximumPixels: 10000, + maximumWorkingBytes: 16 << 20, maximumSourceFrames: 10000, maximumSampledFrames: 64) + private let audioLimits = MiMoV26EncodedAudiovisualDecoder.Limits( + maximumFrames: 48000, + maximumWorkingBytes: 16 << 20) + private func inspect(_ data: Data) async throws -> MiMoV26EncodedAudiovisualDecoder.Plan { + let owner = try MemoryBackedVideoAsset(videoData: data) + let video = try await MiMoV26EncodedVisualDecoder.inspectVideo( + owner, + sampling: .init(fps: 1, minimumFrames: 8, maximumFrames: 3600), limits: videoLimits) + XCTAssertTrue(video.hasAudioTrack) + XCTAssertTrue(video.sourceOwner === owner) + XCTAssertEqual(video.sampledIndices, [0, 2]) + let audio = try await MiMoV26EncodedAudiovisualDecoder.inspect(video, limits: audioLimits) + XCTAssertTrue(audio.video.sourceOwner === owner) + return audio + } + func testActualPCM16MOVBecomesOneWholeAudioClipWithNativeFrameTimestamps() async throws { + let plan = try await inspect(MiMoAVFixture.movie()) + XCTAssertEqual(plan.frameCount, 24000) + XCTAssertGreaterThan(plan.audioWorkingByteBound, 24000 * 4) + let result = try await MiMoV26EncodedAudiovisualDecoder.decode( + plan, videoLimits: videoLimits, audioLimits: audioLimits) + XCTAssertEqual(result.frames.count, 2) + let silentOwner = try MemoryBackedVideoAsset( + videoData: + XCTUnwrap(Data(base64Encoded: MiMoAVFixture.videoBase64))) + let silentPlan = try await MiMoV26EncodedVisualDecoder.inspectVideo( + silentOwner, + sampling: .init(fps: 1, minimumFrames: 8, maximumFrames: 3600), limits: videoLimits) + let silent = try await MiMoV26EncodedVisualDecoder.silentVideo( + silentPlan, limits: videoLimits) + for (actual, original) in zip(result.frames, silent.frames) { + XCTAssertEqual(actual.width, original.width) + XCTAssertEqual(actual.height, original.height) + XCTAssertEqual(actual.planarRGB, original.planarRGB) + } + XCTAssertEqual( + result.timestamps.map(\.bitPattern), + [Float(0).bitPattern, (Float(2) / Float(3)).bitPattern]) + XCTAssertEqual(result.wholeAudio.descriptor.sampleRate, 24000) + XCTAssertEqual(result.wholeAudio.descriptor.channels, 1) + let expected = (0 ..< 24000).map { + Float(Int16(bitPattern: [UInt16(0x8000), 0xffff, 0, 1, 0x7fff][$0 % 5])) / 32768 + } + XCTAssertEqual(result.wholeAudio.samples.map(\.bitPattern), expected.map(\.bitPattern)) + let fps: Float = 1 / (Float(2) / Float(3)) + let end: Float = Float(2) / Float(3) + 1 / fps + XCTAssertEqual(result.segmentEnd, .float32(end)) + let layout = try MiMoV26AudiovisualLayout.make( + timestamps: result.timestamps, + segmentEnd: result.segmentEnd, temporalPatchSize: 2, wholeAudioPatches: 7, + maximumUnits: 1) + XCTAssertEqual(layout.units.map(\.audioRange), [0 ..< 7]) + XCTAssertEqual(layout.usedAudioPatches, 7) + // Existing silent entrypoint MUST NOT become a sound-dropping bypass. + do { + _ = try await MiMoV26EncodedVisualDecoder.silentVideo(plan.video, limits: videoLimits) + XCTFail("audio silently dropped") + } catch { + XCTAssertEqual( + error as? MiMoV26EncodedVisualDecoder.Failure, + .audioTrackRequiresAudiovisualProfile) + } + } + func testActualFloat32LPCMPreservesSignedZeroSubnormalsAndFractionalBits() async throws { + let bits: [UInt32] = [0x8000_0000, 1, 0x3f80_0001, 0xbfa0_0000, 0x3eaa_aaab] + let plan = try await inspect(MiMoAVFixture.movie(floatBits: bits)) + let value = try await MiMoV26EncodedAudiovisualDecoder.decode( + plan, videoLimits: videoLimits, audioLimits: audioLimits) + XCTAssertEqual( + value.wholeAudio.samples.map(\.bitPattern), (0 ..< 24000).map { bits[$0 % bits.count] }) + } + func testActualNonfiniteTrackFailsWithoutNormalization() async throws { + let plan = try await inspect(MiMoAVFixture.movie(floatBits: [0x7fc0_0001])) + do { + _ = try await MiMoV26EncodedAudiovisualDecoder.decode( + plan, videoLimits: videoLimits, audioLimits: audioLimits) + XCTFail("NaN accepted") + } catch { + XCTAssertEqual(error as? MiMoV26EncodedAudiovisualDecoder.Failure, .nonfiniteSamples) + } + } + func testActualRateChannelsMultipleTracksAndEditsRemainTypedRefusals() async throws { + let cases: [(Data, MiMoV26EncodedAudiovisualDecoder.Failure)] = [ + (try MiMoAVFixture.movie(rate: 22050), .unsupportedSampleRate), + (try MiMoAVFixture.movie(channels: 2), .unsupportedChannels), + (try MiMoAVFixture.movie(edited: true), .unsupportedTimeline), + (try MiMoAVFixture.movie(duplicateTrack: true), .unsupportedEncoding), + ] + for (data, expected) in cases { + do { + _ = try await inspect(data) + XCTFail("unsupported transport accepted") + } catch { XCTAssertEqual(error as? MiMoV26EncodedAudiovisualDecoder.Failure, expected) } + } + } + func testRealCompressedTrackMetadataIsNotARequestForImplicitDecode() async throws { + // The u-law sample entry is an actual unsupported audio codec declaration, + // not a mock Plan. Payload is deliberately not decoded on this route. + do { + _ = try await inspect(MiMoAVFixture.movie(codec: "ulaw")) + XCTFail("codec accepted") + } catch { + XCTAssertEqual(error as? MiMoV26EncodedAudiovisualDecoder.Failure, .unsupportedEncoding) + } + } + func testBoundAndCancellationBeforePCMExpansion() async throws { + let plan = try await inspect(MiMoAVFixture.movie()) + let small = MiMoV26EncodedAudiovisualDecoder.Limits( + maximumFrames: 23999, maximumWorkingBytes: 16 << 20) + do { + _ = try await MiMoV26EncodedAudiovisualDecoder.inspect(plan.video, limits: small) + XCTFail("frame cap") + } catch { XCTAssertEqual(error as? MiMoV26EncodedAudiovisualDecoder.Failure, .limit) } + let video = videoLimits + let audio = audioLimits + let task = Task { + withUnsafeCurrentTask { $0?.cancel() } + return try await MiMoV26EncodedAudiovisualDecoder.decode( + plan, videoLimits: video, audioLimits: audio) + } + do { + _ = try await task.value + XCTFail("cancelled transport returned content") + } catch { XCTAssertTrue(error is CancellationError) } + } + func testIndividualEndKeepsFloat32ReciprocalOrderNotContainerDuration() throws { + for gap: Float in [0.16, 0.33333334, 0.7, 1.234567] { + let t: [Float] = [0, gap, 17.3] + let fps: Float = 1 / gap + let step: Float = 1 / fps + XCTAssertEqual( + try MiMoV26EncodedAudiovisualDecoder.individualSegmentEnd(t).bitPattern, + (t[2] + step).bitPattern) + } + XCTAssertThrowsError(try MiMoV26EncodedAudiovisualDecoder.individualSegmentEnd([0, 0])) + } + + /// Separate regression for the root-owned encoded-byte pre-audio guard. + /// Uses the actual PCM MOV plan, never a fake decoder or completion flag. + func testEncodedSourceCeilingPrecedesCancellationAndAcceptsExactBytes() async throws { + let data = try MiMoAVFixture.movie() + let plan = try await inspect(data) + XCTAssertEqual(plan.video.sourceOwner.byteCount, data.count) + let audio = audioLimits + let tight = MiMoV26EncodedVisualDecoder.Limits( + maximumPixels: 10000, + maximumWorkingBytes: 16 << 20, maximumSourceFrames: 10000, maximumSampledFrames: 64, + maximumEncodedBytes: data.count - 1) + do { + _ = try await MiMoV26EncodedAudiovisualDecoder.decode( + plan, videoLimits: tight, audioLimits: audio) + XCTFail("encoded source exceeded the reused plan's current ceiling") + } catch { + XCTAssertEqual(error as? MiMoV26EncodedAudiovisualDecoder.Failure, .limit) + } + let cancelled = Task { + withUnsafeCurrentTask { $0?.cancel() } + XCTAssertTrue(Task.isCancelled) + return try await MiMoV26EncodedAudiovisualDecoder.decode( + plan, videoLimits: tight, audioLimits: audio) + } + do { + _ = try await cancelled.value + XCTFail("encoded ceiling did not refuse cancelled AV transport") + } catch { + // Removing the pre-audio byte guard exposes CancellationError here. + XCTAssertEqual(error as? MiMoV26EncodedAudiovisualDecoder.Failure, .limit) + } + let exact = MiMoV26EncodedVisualDecoder.Limits( + maximumPixels: 10000, + maximumWorkingBytes: 16 << 20, maximumSourceFrames: 10000, maximumSampledFrames: 64, + maximumEncodedBytes: data.count) + let decoded = try await MiMoV26EncodedAudiovisualDecoder.decode( + plan, videoLimits: exact, audioLimits: audio) + XCTAssertEqual(decoded.frames.count, 2) + XCTAssertEqual( + decoded.timestamps.map(\.bitPattern), + [Float(0).bitPattern, (Float(2) / Float(3)).bitPattern]) + XCTAssertEqual(decoded.wholeAudio.descriptor.sampleRate, 24000) + XCTAssertEqual(decoded.wholeAudio.descriptor.channels, 1) + let words: [UInt16] = [0x8000, 0xffff, 0, 1, 0x7fff] + let expected: [Float] = (0 ..< 24000).map { + Float(Int16(bitPattern: words[$0 % 5])) / 32768 + } + XCTAssertEqual(decoded.wholeAudio.samples.map(\.bitPattern), expected.map(\.bitPattern)) + } +} + +/// A real ISO-BMFF fixture: retain the pre-existing three-frame H.264 mdat and +/// video track byte-for-byte, append one bounded uncompressed audio mdat/track. +/// Pure Swift byte construction only; AVAssetReader remains the actual decoder. +/// The two test targets deliberately carry identical private fixture builders. +private enum MiMoAVFixture { + static let videoBase64 = + "AAAAHGZ0eXBtcDQyAAAAAWlzb21tcDQxbXA0MgAAAAFtZGF0AAAAAAAAAK4AAAA7BgUyR1ZK3FxMQz+U78URPNFDqAEAAAMAAQMAAAMAAQIAAeYACwAAAwAAAwAAAwAUDAOJJAEN/////4AAAAAxJbggH4AuSqwRNmYXSACJwyG5akafRwrPDoFqVCtjHBP+QvRWhyAAGk1PzfAEsEedgAAAABEh4QhfAoAvQrFXFN4ACQ7CtgAAABEBqIGK/1jQw/VufW+ACvdnuAAAAvFtb292AAAAbG12aGQAAAAA5lOws+ZTsLMAAAJYAAACWAABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAACfXRyYWsAAABcdGtoZAAAAAHmU7Cz5lOwswAAAAEAAAAAAAACWAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAQAAAAEAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAAlgAAADIAAEAAAAAAfVtZGlhAAAAIG1kaGQAAAAA5lOws+ZTsLMAAAJYAAACWFXEAAAAAAAxaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAENvcmUgTWVkaWEgVmlkZW8AAAABnG1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAVxzdGJsAAAAoXN0c2QAAAAAAAAAAQAAAJFhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAEAAQABIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAJ2F2Y0MBZAAL/+EADCdkAAusVlDDeBBhFAEABCjuPLD9+PgAAAAACmZpZWwBAAAAAApjaHJtAAAAAAAYc3R0cwAAAAAAAAABAAAAAwAAAMgAAAAoY3R0cwAAAAAAAAADAAAAAQAAAMgAAAABAAABkAAAAAEAAAAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAPc2R0cAAAAAAgEBgAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAMAAAABAAAAIHN0c3oAAAAAAAAAAAAAAAMAAAB0AAAAFQAAABUAAAAUc3RjbwAAAAAAAAABAAAALA==" + static func be(_ value: UInt64, _ width: Int = 4) -> Data { + Data((0 ..< width).reversed().map { UInt8(truncatingIfNeeded: value >> ($0 * 8)) }) + } + static func atom(_ name: String, _ body: Data) -> Data { + be(UInt64(body.count + 8)) + Data(name.utf8) + body + } + static let matrix = [UInt64(0x10000), 0, 0, 0, 0x10000, 0, 0, 0, 0x4000_0000] + .reduce(into: Data()) { $0.append(be($1)) } + static let frames = 24000 + static func movie( + floatBits: [UInt32]? = nil, rate: Int = 24000, channels: Int = 1, + codec: String? = nil, edited: Bool = false, duplicateTrack: Bool = false + ) throws -> Data { + let original = try XCTUnwrap(Data(base64Encoded: videoBase64)) + let step = floatBits == nil ? 2 : 4 + var pcm = Data() + for i in 0 ..< frames { + let bits = + floatBits.map { $0[i % $0.count] } + ?? UInt32([UInt16(0x8000), 0xffff, 0, 1, 0x7fff][i % 5]) + for _ in 0 ..< channels { + for byte in 0 ..< step { pcm.append(UInt8(truncatingIfNeeded: bits >> (byte * 8))) } + } + } + func track(offset: Int, id: Int = 2) -> Data { + let duration = UInt64(frames * 600 / rate) + let tkhdFields: [Data] = [ + be(7), be(0), be(0), be(UInt64(id)), be(0), be(duration), + Data(repeating: 0, count: 12), be(0x100, 2), be(0, 2), matrix, be(0), be(0), + ] + let tkhd = atom("tkhd", tkhdFields.reduce(into: Data()) { $0.append($1) }) + let mdhd = atom( + "mdhd", + Data(repeating: 0, count: 12) + be(UInt64(rate)) + be(UInt64(frames)) + + be(0x55c4, 2) + be(0, 2)) + let hdlr = atom( + "hdlr", + Data(repeating: 0, count: 8) + Data("soun".utf8) + + Data(repeating: 0, count: 12) + Data("Sound\0".utf8)) + let sample: Data + if floatBits != nil { + // QuickTime SoundDescription V2, LPCM float32 little-endian, + // packed, 1 PCM frame/packet. No platform conversion request. + let common = + Data(repeating: 0, count: 6) + be(1, 2) + be(2, 2) + be(0, 2) + be(0) + + be(3, 2) + be(16, 2) + be(0xfffe, 2) + be(0, 2) + be(0x10000) + let extended = + be(72) + be(Double(rate).bitPattern, 8) + be(UInt64(channels)) + + be(0x7f00_0000) + be(32) + be(9) + be(UInt64(step * channels)) + be(1) + sample = atom(codec ?? "lpcm", common + extended) + } else { + let body = + Data(repeating: 0, count: 6) + be(1, 2) + Data(repeating: 0, count: 8) + + be(UInt64(channels), 2) + be(16, 2) + be(0, 2) + be(0, 2) + + be(UInt64(rate) << 16) + sample = atom(codec ?? "sowt", body) + } + let stsd = atom("stsd", be(0) + be(1) + sample) + let stts = atom("stts", be(0) + be(1) + be(UInt64(frames)) + be(1)) + let stsc = atom("stsc", be(0) + be(1) + be(1) + be(UInt64(frames)) + be(1)) + let stsz = atom("stsz", be(0) + be(UInt64(step * channels)) + be(UInt64(frames))) + let stco = atom("stco", be(0) + be(1) + be(UInt64(offset))) + let stbl = atom("stbl", stsd + stts + stsc + stsz + stco) + let dinf = atom("dinf", atom("dref", be(0) + be(1) + atom("url ", be(1)))) + let minf = atom("minf", atom("smhd", Data(repeating: 0, count: 8)) + dinf + stbl) + let edit = + edited + ? atom( + "edts", + atom( + "elst", + be(0) + be(1) + be(duration) + be(1) + be(0x10000))) : Data() + return atom("trak", tkhd + edit + atom("mdia", mdhd + hdlr + minf)) + } + // This bound fixture's last atom is moov; existing stco offsets remain + // unchanged because only the tail moov grows, then a new mdat is added. + var moovStart = 0 + while moovStart < original.count { + let n = original[moovStart ..< moovStart + 4].reduce(UInt64(0)) { + ($0 << 8) | UInt64($1) + } + let type = String(data: original[moovStart + 4 ..< moovStart + 8], encoding: .ascii) + if type == "moov" { break } + let actual = + n == 1 + ? original[moovStart + 8 ..< moovStart + 16] + .reduce(UInt64(0)) { ($0 << 8) | UInt64($1) } : n + guard actual >= 8, actual <= UInt64(original.count - moovStart) else { + throw NSError(domain: "MiMoAVFixture", code: 1) + } + moovStart += Int(actual) + } + let addition = track(offset: 0).count * (duplicateTrack ? 2 : 1) + let offset = original.count + addition + 8 + var body = Data(original[(moovStart + 8)...]) + // mvhd's final next_track_ID; movie/video payload otherwise unchanged. + let mvhdSize = body.prefix(4).reduce(0) { ($0 << 8) | Int($1) } + body.replaceSubrange((mvhdSize - 4) ..< mvhdSize, with: be(duplicateTrack ? 4 : 3)) + body += track(offset: offset) + if duplicateTrack { body += track(offset: offset, id: 3) } + var prefix = Data(original.prefix(moovStart)) + // LPCM sound descriptions use the QuickTime container contract. + // Retain byte offsets/lengths; video track and video mdat are unchanged. + prefix.replaceSubrange(8 ..< 12, with: Data("qt ".utf8)) + prefix.replaceSubrange(16 ..< 28, with: Data("qt qt qt ".utf8)) + return prefix + atom("moov", body) + atom("mdat", pcm) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26EncodedVisualDecoderTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26EncodedVisualDecoderTests.swift new file mode 100644 index 0000000000..8412b9c6e4 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26EncodedVisualDecoderTests.swift @@ -0,0 +1,327 @@ +import CoreGraphics +import Foundation +import ImageIO +import MLXLLM +import MLXLMCommon +import XCTest + +@testable import MLXVLM + +/// Prepared only. Real ImageIO/CG raster APIs; no CoreImage renderer, model, +/// fake decoder or plaintext fixture file. +final class MiMoV26EncodedVisualDecoderTests: XCTestCase { + private let mp4Base64 = + "AAAAHGZ0eXBtcDQyAAAAAWlzb21tcDQxbXA0MgAAAAFtZGF0AAAAAAAAAK4AAAA7BgUyR1ZK3FxMQz+U78URPNFDqAEAAAMAAQMAAAMAAQIAAeYACwAAAwAA" + + "AwAAAwAUDAOJJAEN/////4AAAAAxJbggH4AuSqwRNmYXSACJwyG5akafRwrPDoFqVCtjHBP+QvRWhyAAGk1PzfAEsEedgAAAABEh4QhfAoAvQrFXFN4ACQ7CtgA" + + "AABEBqIGK/1jQw/VufW+ACvdnuAAAAvFtb292AAAAbG12aGQAAAAA5lOws+ZTsLMAAAJYAAACWAABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAA" + + "AAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAACfXRyYWsAAABcdGtoZAAAAAHmU7Cz5lOwswAAAAEAAAAAAAACWAAAAAAAAAAA" + + "AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAQAAAAEAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAAlgAAADIAAEAAAAAAfV" + + "tZGlhAAAAIG1kaGQAAAAA5lOws+ZTsLMAAAJYAAACWFXEAAAAAAAxaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAENvcmUgTWVkaWEgVmlkZW8AAAABnG1pbm" + + "YAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAVxzdGJsAAAAoXN0c2QAAAAAAAAAAQAAAJFhdmMxAAAAAA" + + "AAAAEAAAAAAAAAAAAAAAAAAAAAAEAAQABIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAJ2F2Y0MBZAAL/+EADCdkAA" + + "usVlDDeBBhFAEABCjuPLD9+PgAAAAACmZpZWwBAAAAAApjaHJtAAAAAAAYc3R0cwAAAAAAAAABAAAAAwAAAMgAAAAoY3R0cwAAAAAAAAADAAAAAQAAAMgAAAABAA" + + "ABkAAAAAEAAAAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAPc2R0cAAAAAAgEBgAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAMAAAABAAAAIHN0c3oAAAAAAAAAAAAAAA" + + "MAAAB0AAAAFQAAABUAAAAUc3RjbwAAAAAAAAABAAAALA==" + private let limits = MiMoV26EncodedVisualDecoder.Limits( + maximumPixels: 10000, + maximumWorkingBytes: 16 << 20, maximumSourceFrames: 10000, maximumSampledFrames: 64) + private func image() throws -> CGImage { + let bytes: [UInt8] = [ + 1, 41, 81, 0, 2, 42, 82, 127, 3, 43, 83, 255, + 4, 44, 84, 255, 5, 45, 85, 255, 6, 46, 86, 255, + ] + let provider = try XCTUnwrap(CGDataProvider(data: Data(bytes) as CFData)) + return try XCTUnwrap( + CGImage( + width: 2, height: 3, bitsPerComponent: 8, bitsPerPixel: 32, + bytesPerRow: 8, space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue).union( + .byteOrder32Big), + provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)) + } + func testNativeSmartFramesAndIndexSamplingNotNearestPresentationTime() throws { + let sampling = try MiMoV26EncodedVisualDecoder.Sampling( + fps: 1, minimumFrames: 8, maximumFrames: 3600) + XCTAssertEqual( + try sampling.indices(totalFrames: 3, averageFPS: 3, admissionLimit: 64), [0, 2]) + XCTAssertEqual( + try sampling.indices(totalFrames: 9, averageFPS: 30, admissionLimit: 64), + [0, 1, 2, 3, 4, 5, 6, 8]) + XCTAssertEqual( + try sampling.indices(totalFrames: 16, averageFPS: 4, admissionLimit: 64), + [0, 2, 4, 6, 8, 10, 12, 15]) + XCTAssertThrowsError( + try sampling.indices(totalFrames: 16, averageFPS: 4, admissionLimit: 7) + ) { + XCTAssertEqual($0 as? MiMoV26EncodedVisualDecoder.Failure, .limit) + } + XCTAssertThrowsError( + try sampling.indices(totalFrames: 1, averageFPS: 1, admissionLimit: 64)) + XCTAssertThrowsError( + try sampling.indices(totalFrames: 8, averageFPS: .nan, admissionLimit: 64)) + let odd = try MiMoV26EncodedVisualDecoder.Sampling( + fps: 1, minimumFrames: 9, maximumFrames: 100) + XCTAssertEqual( + try odd.indices(totalFrames: 11, averageFPS: 30, admissionLimit: 64), + [0, 1, 2, 3, 4, 5, 6, 7, 8, 10]) + } + func testAllEightLosslessOrientationsKeepStraightHiddenRGBAndChannelOrder() throws { + let expected: [[Float]] = [ + [1, 2, 3, 4, 5, 6], [2, 1, 4, 3, 6, 5], [6, 5, 4, 3, 2, 1], [5, 6, 3, 4, 1, 2], + [1, 3, 5, 2, 4, 6], [5, 3, 1, 6, 4, 2], [6, 4, 2, 5, 3, 1], [2, 4, 6, 1, 3, 5], + ] + for orientation in 1 ... 8 { + let rgb = try MiMoV26EncodedVisualDecoder.straightRGB( + image(), orientation: orientation, limits: limits) + XCTAssertEqual(rgb.width, orientation >= 5 ? 3 : 2) + XCTAssertEqual(rgb.height, orientation >= 5 ? 2 : 3) + XCTAssertEqual(Array(rgb.planarRGB[0 ..< 6]), expected[orientation - 1]) + XCTAssertEqual( + Array(rgb.planarRGB[6 ..< 12]), expected[orientation - 1].map { $0 + 40 }) + XCTAssertEqual( + Array(rgb.planarRGB[12 ..< 18]), expected[orientation - 1].map { $0 + 80 }) + } + } + func testSamplingRejectsInvertedRoundedBoundsFromBothInitializers() throws { + // Metadata-only configuration: no weights, native load or fixture-path prerequisite. + let raw = Data( + """ + {"model_type":"mimo_v2","architectures":["MiMoV2ForCausalLM"], + "hidden_size":16,"intermediate_size":32,"moe_intermediate_size":8, + "vocab_size":64,"num_hidden_layers":2,"max_position_embeddings":64, + "sliding_window_size":3,"sliding_window":3,"num_nextn_predict_layers":3, + "hybrid_layer_pattern":[0,1],"moe_layer_freq":[0,1], + "partial_rotary_factor":0.5,"attention_value_scale":0.707, + "layernorm_epsilon":0.000001,"attention_projection_layout":"split", + "moe_router_dtype":"bfloat16","hidden_act":"silu","dtype":"float32", + "attention_bias":false,"tie_word_embeddings":false,"attention_dropout":0, + "scoring_func":"sigmoid","topk_method":"noaux_tc","n_routed_experts":4, + "num_experts_per_tok":2,"n_group":1,"topk_group":1,"norm_topk_prob":true, + "n_shared_experts":null,"routed_scaling_factor":null, + "num_attention_heads":4,"num_key_value_heads":1,"head_dim":8,"v_head_dim":4, + "swa_num_attention_heads":4,"swa_num_key_value_heads":2,"swa_head_dim":8, + "swa_v_head_dim":4,"rope_theta":10000000,"swa_rope_theta":10000, + "add_full_attention_sink_bias":false,"add_swa_attention_sink_bias":true, + "eos_token_id":3,"pad_token_id":0} + """.utf8) + var fields = try JSONDecoder().decode([String: MiMoV26JSONValue].self, from: raw) + for (low, high) in [(10, 8), (9, 9), (1, 1)] { + XCTAssertThrowsError( + try MiMoV26EncodedVisualDecoder.Sampling( + fps: 1, minimumFrames: low, maximumFrames: high) + ) { + XCTAssertEqual($0 as? MiMoV26EncodedVisualDecoder.Failure, .invalidVideo) + } + fields["processor_config"] = .object([ + "fps": .number(1), "min_frames": .number(Decimal(low)), + "max_frames": .number(Decimal(high)), + ]) + let configuration = try MiMoV26Configuration(rawFields: fields) + XCTAssertThrowsError( + try MiMoV26EncodedVisualDecoder.Sampling(configuration: configuration) + ) { + XCTAssertEqual($0 as? MiMoV26EncodedVisualDecoder.Failure, .invalidVideo) + } + } + XCTAssertThrowsError( + try MiMoV26EncodedVisualDecoder.Sampling( + fps: 1, minimumFrames: Int.max, maximumFrames: Int.max)) + let valid = try MiMoV26EncodedVisualDecoder.Sampling( + fps: 1, minimumFrames: 9, maximumFrames: 10) + XCTAssertEqual( + try valid.indices(totalFrames: 10, averageFPS: 1, admissionLimit: 10), Array(0 ..< 10)) + } + func testEncodedImageByteCeilingPrecedesPlatformParsingAndIncludesPadding() throws { + let encoded = NSMutableData() + let destination = try XCTUnwrap( + CGImageDestinationCreateWithData(encoded, "public.png" as CFString, 1, nil)) + CGImageDestinationAddImage(destination, try image(), nil) + XCTAssertTrue(CGImageDestinationFinalize(destination)) + let data = encoded as Data + let bounded = MiMoV26EncodedVisualDecoder.Limits( + maximumPixels: 10000, + maximumWorkingBytes: 16 << 20, maximumSourceFrames: 10000, + maximumSampledFrames: 64, maximumEncodedBytes: data.count) + XCTAssertEqual(try MiMoV26EncodedVisualDecoder.image(data, limits: bounded).width, 2) + var padded = data + padded.append(Data(repeating: 0, count: 1024)) + for rejected in [padded, Data(repeating: 0, count: data.count + 1)] { + XCTAssertThrowsError(try MiMoV26EncodedVisualDecoder.image(rejected, limits: bounded)) { + XCTAssertEqual($0 as? MiMoV26EncodedVisualDecoder.Failure, .limit) + } + } + XCTAssertEqual(limits.maximumEncodedBytes, limits.maximumWorkingBytes) + } + func testEncodedVideoByteCeilingPrecedesAssetReadsAndAppliesToReusedPlan() async throws { + let data = try XCTUnwrap(Data(base64Encoded: mp4Base64)) + let owner = try MemoryBackedVideoAsset(videoData: data) + let sampling = try MiMoV26EncodedVisualDecoder.Sampling( + fps: 1, minimumFrames: 8, maximumFrames: 3600) + let small = MiMoV26EncodedVisualDecoder.Limits( + maximumPixels: 10000, + maximumWorkingBytes: 16 << 20, maximumSourceFrames: 10000, + maximumSampledFrames: 64, maximumEncodedBytes: data.count - 1) + XCTAssertEqual(owner.resourceRequestCount, 0) + do { + _ = try await MiMoV26EncodedVisualDecoder.inspectVideo( + owner, sampling: sampling, limits: small) + XCTFail("oversized encoded video reached AVFoundation") + } catch { XCTAssertEqual(error as? MiMoV26EncodedVisualDecoder.Failure, .limit) } + XCTAssertEqual(owner.resourceRequestCount, 0) + let plan = try await MiMoV26EncodedVisualDecoder.inspectVideo( + owner, sampling: sampling, limits: limits) + // The real reader emits zero-sample, zero-duration control markers. + // They must not become frames or turn valid content into a limit error. + XCTAssertEqual(plan.codedPixels, 64 * 64) + XCTAssertEqual(plan.sourceFrameCount, 3) + XCTAssertEqual(plan.averageFPS, 3) + XCTAssertEqual(plan.sampledIndices, [0, 2]) + let decoded = try await MiMoV26EncodedVisualDecoder.silentVideo(plan, limits: limits) + XCTAssertEqual(decoded.frames.count, 2) + XCTAssertEqual(decoded.frames.map(\.width), [64, 64]) + XCTAssertEqual(decoded.frames.map(\.height), [64, 64]) + XCTAssertEqual( + decoded.timestamps.map(\.bitPattern), + [Float(0).bitPattern, (Float(2) / Float(3)).bitPattern]) + // A canceled caller must receive the synchronous resource refusal, + // not enter a reader and only then notice cancellation. Do not infer + // AVFoundation quiescence from a sampled resource-request count. + let task = Task { () -> (Bool, MiMoV26EncodedVisualDecoder.Failure?) in + withUnsafeCurrentTask { $0?.cancel() } + let cancelled = Task.isCancelled + do { + _ = try await MiMoV26EncodedVisualDecoder.silentVideo(plan, limits: small) + return (cancelled, nil) + } catch { return (cancelled, error as? MiMoV26EncodedVisualDecoder.Failure) } + } + let result = await task.value + XCTAssertTrue(result.0) + XCTAssertEqual(result.1, .limit) + } + func testSourceFrameLimitCountsMediaIndependentlyOfControlMarkers() async throws { + let data = try XCTUnwrap(Data(base64Encoded: mp4Base64)) + let sampling = try MiMoV26EncodedVisualDecoder.Sampling( + fps: 1, minimumFrames: 8, maximumFrames: 3600) + let exact = MiMoV26EncodedVisualDecoder.Limits( + maximumPixels: 10000, + maximumWorkingBytes: 16 << 20, maximumSourceFrames: 3, + maximumSampledFrames: 64, maximumEncodedBytes: data.count) + XCTAssertEqual(exact.maximumSourceFrames, 3) + XCTAssertEqual(exact.maximumControlMarkers, 4096) + let plan = try await MiMoV26EncodedVisualDecoder.inspectVideo( + MemoryBackedVideoAsset(videoData: data), sampling: sampling, limits: exact) + XCTAssertEqual(plan.sourceFrameCount, 3) + XCTAssertEqual(plan.averageFPS, 3) + XCTAssertEqual(plan.sampledIndices, [0, 2]) + let decoded = try await MiMoV26EncodedVisualDecoder.silentVideo(plan, limits: exact) + XCTAssertEqual(decoded.frames.count, 2) + XCTAssertEqual(decoded.frames.map(\.width), [64, 64]) + XCTAssertEqual(decoded.frames.map(\.height), [64, 64]) + XCTAssertEqual( + decoded.timestamps.map(\.bitPattern), + [Float(0).bitPattern, (Float(2) / Float(3)).bitPattern]) + + let lower = MiMoV26EncodedVisualDecoder.Limits( + maximumPixels: exact.maximumPixels, + maximumWorkingBytes: exact.maximumWorkingBytes, maximumSourceFrames: 2, + maximumSampledFrames: exact.maximumSampledFrames, + maximumEncodedBytes: exact.maximumEncodedBytes) + do { + _ = try await MiMoV26EncodedVisualDecoder.inspectVideo( + MemoryBackedVideoAsset(videoData: data), sampling: sampling, limits: lower) + XCTFail("three media frames exceeded the unchanged two-frame ceiling") + } catch { + XCTAssertEqual(error as? MiMoV26EncodedVisualDecoder.Failure, .limit) + } + } + + func testActualRGBAImageIODecodeDoesNotWhiteCompositeOrNormalize() throws { + let data = NSMutableData() + let destination = try XCTUnwrap( + CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil)) + CGImageDestinationAddImage(destination, try image(), nil) + XCTAssertTrue(CGImageDestinationFinalize(destination)) + let rgb = try MiMoV26EncodedVisualDecoder.image(data as Data, limits: limits) + XCTAssertEqual(rgb.width, 2) + XCTAssertEqual(rgb.height, 3) + XCTAssertEqual( + rgb.planarRGB, [1, 2, 3, 4, 5, 6, 41, 42, 43, 44, 45, 46, 81, 82, 83, 84, 85, 86]) + } + func testActualJPEGEXIFOrientationMatchesApplicationPolicy() throws { + let data = NSMutableData() + let destination = try XCTUnwrap( + CGImageDestinationCreateWithData(data, "public.jpeg" as CFString, 1, nil)) + CGImageDestinationAddImage( + destination, try image(), + [ + kCGImagePropertyOrientation: 6, kCGImageDestinationLossyCompressionQuality: 1.0, + ] as CFDictionary) + XCTAssertTrue(CGImageDestinationFinalize(destination)) + let source = try XCTUnwrap(CGImageSourceCreateWithData(data, nil)) + let properties = try XCTUnwrap( + CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]) + XCTAssertEqual((properties[kCGImagePropertyOrientation] as? NSNumber)?.intValue, 6) + let raw = try XCTUnwrap(CGImageSourceCreateImageAtIndex(source, 0, nil)) + let expected = try MiMoV26EncodedVisualDecoder.straightRGB( + raw, orientation: 6, limits: limits) + let actual = try MiMoV26EncodedVisualDecoder.image(data as Data, limits: limits) + XCTAssertEqual(actual.width, expected.width) + XCTAssertEqual(actual.height, expected.height) + XCTAssertEqual(actual.planarRGB, expected.planarRGB) + // Decoder/orientation evidence only, not JPEG identity with another codec. + } + func testBoundsRejectBeforeRasterCopyAndNoHeuristicPremultipliedRecovery() throws { + let small = MiMoV26EncodedVisualDecoder.Limits( + maximumPixels: 1, + maximumWorkingBytes: 128, maximumSourceFrames: 2, maximumSampledFrames: 2) + XCTAssertThrowsError( + try MiMoV26EncodedVisualDecoder.straightRGB(image(), orientation: 1, limits: small)) + let provider = try XCTUnwrap(CGDataProvider(data: Data([UInt8(0), 0, 0, 0]) as CFData)) + let premultiplied = try XCTUnwrap( + CGImage( + width: 1, height: 1, bitsPerComponent: 8, bitsPerPixel: 32, + bytesPerRow: 4, space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) + .union(.byteOrder32Big), + provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)) + XCTAssertThrowsError( + try MiMoV26EncodedVisualDecoder.straightRGB( + premultiplied, orientation: 1, limits: limits)) + XCTAssertThrowsError( + try MiMoV26EncodedVisualDecoder.image(Data("invalid".utf8), limits: limits)) + } + func testTighterVideoPixelLimitRejectsBeforeCancelledReaderWork() async throws { + // Reuse the existing real inline MP4 fixture; no generated decoder or + // public hook. Inspection creates the actual immutable source plan. + let owner = try MemoryBackedVideoAsset(videoData: XCTUnwrap(Data(base64Encoded: mp4Base64))) + let sampling = try MiMoV26EncodedVisualDecoder.Sampling( + fps: 1, minimumFrames: 8, maximumFrames: 3600) + let plan = try await MiMoV26EncodedVisualDecoder.inspectVideo( + owner, sampling: sampling, limits: limits) + XCTAssertFalse(plan.hasAudioTrack) + XCTAssertGreaterThan(plan.codedPixels, 1) + XCTAssertLessThanOrEqual(try plan.decodeWorkingByteBound(), limits.maximumWorkingBytes) + let tighter = MiMoV26EncodedVisualDecoder.Limits( + maximumPixels: plan.codedPixels - 1, + maximumWorkingBytes: limits.maximumWorkingBytes, + maximumSourceFrames: limits.maximumSourceFrames, + maximumSampledFrames: limits.maximumSampledFrames) + // Bounds must win synchronously before withAsset/reader work. The old + // implementation only checked pixels after copyNextSampleBuffer and + // Task.checkCancellation, so it cannot return .limit in this case. + let task = Task { () -> (Bool, MiMoV26EncodedVisualDecoder.Failure?) in + withUnsafeCurrentTask { $0?.cancel() } + let cancelled = Task.isCancelled + do { + _ = try await MiMoV26EncodedVisualDecoder.silentVideo(plan, limits: tighter) + return (cancelled, nil) + } catch { + return (cancelled, error as? MiMoV26EncodedVisualDecoder.Failure) + } + } + let result = await task.value + XCTAssertTrue(result.0) + XCTAssertEqual(result.1, .limit) + } + +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26FP32WeightedReductionTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26FP32WeightedReductionTests.swift new file mode 100644 index 0000000000..037794d333 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26FP32WeightedReductionTests.swift @@ -0,0 +1,335 @@ +// Prepared source only. Run these real Metal cells serially under root's +// exclusive native test grant. No skip or scripted effective-route substitute. +import Foundation +import MLX +import MLXNN +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon + +final class MiMoV26FP32WeightedReductionTests: XCTestCase { + private func exact( + _ actual: MLXArray, _ expected: MLXArray, + file: StaticString = #filePath, line: UInt = #line + ) { + eval(actual, expected) + XCTAssertEqual(actual.shape, expected.shape, file: file, line: line) + XCTAssertEqual(actual.dtype, expected.dtype, file: file, line: line) + XCTAssertEqual( + actual.asData(access: .copy).data, expected.asData(access: .copy).data, + "Exact bytes are a separate lossless gate, not an allclose claim", file: file, + line: line) + } + + private func glu( + _ profile: SwitchGLUWeightedReductionProfile = .mimoV26FP32, + hidden: Int = 64, dtype: DType = .bfloat16 + ) throws -> SwitchGLU { + let value = SwitchGLU( + inputDims: hidden, hiddenDims: 32, numExperts: 16, + weightedReductionProfile: profile) + let weights = Dictionary( + uniqueKeysWithValues: value.parameters().flattened().map { name, array in + let salt = name.utf8.reduce(0) { ($0 + Int($1)) % 31 } + let values = (0 ..< array.size).map { sin(Float($0 * 7 + salt)) * 0.075 } + return (name, MLXArray(values, array.shape).asType(dtype)) + }) + try value.update(parameters: .unflattened(weights), verify: .all) + return value + } + + private func inputs( + batch: Int = 1, length: Int, hidden: Int = 64, + topK: Int = 8, dtype: DType = .bfloat16 + ) -> (MLXArray, MLXArray, MLXArray) { + let rows = batch * length + let x = MLXArray( + (0 ..< rows * hidden).map { cos(Float($0 * 3 + 7)) }, + [batch, length, hidden] + ).asType(dtype) + // Deliberate duplicates within a token and across tokens. This tests + // assignment/row mapping, not a claim that the real router emits ties. + let idx = MLXArray( + (0 ..< rows * topK).map { UInt32(($0 / 2 + $0 / topK * 3) % 16) }, + [batch, length, topK]) + let weights = MLXArray( + (0 ..< rows * topK).map { Float(($0 * 13) % 101 + 1) / 137.0 }, + [batch, length, topK]) + return (x, idx, weights) + } + + private func baseline( + _ value: SwitchGLU, _ x: MLXArray, _ indices: MLXArray, + _ weights: MLXArray + ) -> MLXArray { + // EXACT current MiMo unfused expression; deliberately not compiled + // weightedExpertSum and never a pre-cast of the FP32 router weights. + (value(x, indices) * weights[.ellipsis, .newAxis]).sum(axis: -2) + } + + func testOptInIsOffByDefaultAndRequiresExplicitTrue() { + XCTAssertFalse(MiMoV26FP32WeightedReduction.isEnabled(environment: [:])) + for value in ["", "0", "false", "off", "unknown"] { + XCTAssertFalse( + MiMoV26FP32WeightedReduction.isEnabled( + environment: [MiMoV26FP32WeightedReduction.envFlag: value])) + } + for value in ["1", "true", "on", " TRUE "] { + XCTAssertTrue( + MiMoV26FP32WeightedReduction.isEnabled( + environment: [MiMoV26FP32WeightedReduction.envFlag: value])) + } + } + + func testRealSortedSwitchRouteEngagesForBothTypesAndTopK() throws { + for dtype: DType in [.float16, .bfloat16] { + let value = try glu(dtype: dtype) + for topK in [6, 8] { + for (batch, length) in [(1, 12), (2, 7)] { + let (x, indices, weights) = inputs( + batch: batch, length: length, topK: topK, dtype: dtype) + let actual = value.callAndMiMoFP32WeightedReduce( + x, indices, weights: weights, enabled: true) + XCTAssertEqual( + actual.route, .fused, "This test MUST NOT silently pass fallback") + XCTAssertEqual(actual.output.dtype, .float32) + let expected = baseline(value, x, indices, weights) + exact(actual.output, expected) + exact(actual.output.asType(dtype), expected.asType(dtype)) + } + } + } + } + + func testOffUnsortedDecodeAndUnsupportedCallsKeepExactUnfusedFallback() throws { + let value = try glu() + let cases: [(Int, Int, Int, Bool, MiMoV26FP32WeightedReductionRoute)] = [ + (1, 12, 8, false, .disabled), (1, 4, 8, true, .notSorted), + (1, 1, 8, true, .notPrefill), (16, 1, 8, true, .notPrefill), + (1, 12, 2, true, .unsupportedTopK), + ] + for (batch, length, topK, enabled, route) in cases { + let (x, idx, w) = inputs(batch: batch, length: length, topK: topK) + let actual = value.callAndMiMoFP32WeightedReduce(x, idx, weights: w, enabled: enabled) + XCTAssertEqual(actual.route, route) + exact(actual.output, baseline(value, x, idx, w)) + } + let (x, idx, w) = inputs(length: 12) + let rounded = w.asType(.bfloat16) + let badWeights = value.callAndMiMoFP32WeightedReduce( + x, idx, weights: rounded, enabled: true) + XCTAssertEqual(badWeights.route, .unsupportedDType) + exact(badWeights.output, baseline(value, x, idx, rounded)) + let fp32 = try glu(dtype: .float32) + let badType = fp32.callAndMiMoFP32WeightedReduce( + x.asType(.float32), idx, weights: w, enabled: true) + XCTAssertEqual(badType.route, .unsupportedDType) + exact(badType.output, baseline(fp32, x.asType(.float32), idx, w)) + let odd = try glu(hidden: 65) + let (oddX, oddIdx, oddW) = inputs(length: 12, hidden: 65) + let badShape = odd.callAndMiMoFP32WeightedReduce(oddX, oddIdx, weights: oddW, enabled: true) + XCTAssertEqual(badShape.route, .unsupportedShape) + exact(badShape.output, baseline(odd, oddX, oddIdx, oddW)) + } + + private func reductionFixture(topK: Int, dtype: DType, cancellation: Bool) + -> (original: MLXArray, sorted: MLXArray, inverse: MLXArray, weights: MLXArray) + { + let tokens = 16 + let hidden = 64 + let count = tokens * topK + MLXRandom.seed(UInt64(700 + topK)) + var original = MLXRandom.normal([2, tokens / 2, topK, hidden]).asType(dtype) + var weights = MLXRandom.uniform(low: -1, high: 1, [2, tokens / 2, topK]) + if cancellation { + let terms: [Float] = [256, -256, 1, -1, 2, -2, 4, -4] + let scores: [Float] = [1.001, 1, 1.1, 1, 1, 1, 1, 1] + original = MLXArray( + (0 ..< count * hidden).map { terms[($0 / hidden) % topK] }, + [2, tokens / 2, topK, hidden] + ).asType(dtype) + weights = MLXArray((0 ..< count).map { scores[$0 % topK] }, [2, tokens / 2, topK]) + } + let assignments = MLXArray((0 ..< count).map { UInt32(($0 * 17 + $0 / topK) % 13) }) + let order = argSort(assignments) + let inverse = argSort(order) + return (original, original.reshaped(count, hidden)[order], inverse, weights) + } + + func testExactFP32BytesRemainHardGateForRandomAndCancellationSensitiveValues() { + for dtype: DType in [.float16, .bfloat16] { + for topK in [6, 8] { + for cancellation in [false, true] { + let f = reductionFixture(topK: topK, dtype: dtype, cancellation: cancellation) + XCTAssertNil( + mimoV26FP32WeightedUnsortRefusal( + sortedOutputs: f.sorted, inverseOrder: f.inverse, weights: f.weights)) + let actual = mimoV26FP32WeightedUnsort( + sortedOutputs: f.sorted, inverseOrder: f.inverse, weights: f.weights) + let expected = (f.original * f.weights[.ellipsis, .newAxis]).sum(axis: -2) + // If this fails under a real compiler/device, retain the + // numerical counterexample; do not replace with allclose. + exact(actual, expected) + exact(actual.asType(dtype), expected.asType(dtype)) + } + } + } + } + + func testSeparateReferenceToleranceAndDiscriminatingBF16Negative() { + for topK in [6, 8] { + let f = reductionFixture(topK: topK, dtype: .bfloat16, cancellation: true) + let actual = mimoV26FP32WeightedUnsort( + sortedOutputs: f.sorted, inverseOrder: f.inverse, weights: f.weights) + let expected = (f.original * f.weights[.ellipsis, .newAxis]).sum(axis: -2) + eval(actual, expected) + // PR17's existing numerical check, reported separately. This is + // not substituted for either exact-byte or trained-token gates. + XCTAssertTrue(allClose(actual, expected, rtol: 2e-2, atol: 2e-2).item(Bool.self)) + let wrong = weightedExpertUnsort( + sortedOutputs: f.sorted, inverseOrder: f.inverse, + weights: f.weights.reshaped(16, topK).asType(.bfloat16) + ).reshaped(2, 8, 64) + eval(wrong) + XCTAssertGreaterThan( + max(abs(expected - wrong.asType(.float32))).item(Float.self), 0.1, + "Fixture must detect the forbidden BF16 product/weight path") + XCTAssertEqual( + wrong.dtype, .bfloat16, "Old other-family reducer keeps its old contract") + } + } + + func testMetadataAndCPURefusalDoNotDispatchTheKernel() { + let f = reductionFixture(topK: 8, dtype: .bfloat16, cancellation: false) + XCTAssertEqual( + mimoV26FP32WeightedUnsortRefusal( + sortedOutputs: f.sorted, + inverseOrder: f.inverse.asType(.int32), weights: f.weights), .unsupportedDType) + XCTAssertEqual( + mimoV26FP32WeightedUnsortRefusal( + sortedOutputs: f.sorted, + inverseOrder: f.inverse, weights: f.weights.asType(.float16)), .unsupportedDType) + XCTAssertEqual( + mimoV26FP32WeightedUnsortRefusal( + sortedOutputs: f.sorted[0 ..< 1], + inverseOrder: f.inverse, weights: f.weights), .unsupportedShape) + MLX.Stream.withNewDefaultStream(device: .cpu) { + XCTAssertEqual( + mimoV26FP32WeightedUnsortRefusal( + sortedOutputs: f.sorted, inverseOrder: f.inverse, weights: f.weights), + .unsupportedStream) + } + } + + func testOtherFamilyProfilesNeverEnterMiMoRouteAndKeepExistingEntryPoint() throws { + for profile: SwitchGLUWeightedReductionProfile in [ + .generic, .gemma4ProductionGeGLU, .qwen35ProductionSwiGLU, .qwen4ProductionSwiGLU, + ] { + let value = try glu(profile) + let (x, indices, weights) = inputs(length: 12) + let candidate = value.callAndMiMoFP32WeightedReduce( + x, indices, weights: weights, enabled: true) + XCTAssertEqual(candidate.route, .unsupportedProfile) + exact(candidate.output, baseline(value, x, indices, weights)) + let legacy = value.callAndWeightedReduce( + x, indices, weights: weights.asType(.bfloat16), + fuseSortedReduction: true) + exact(legacy, weightedExpertSum(value(x, indices), weights.asType(.bfloat16))) + } + } + + func testCustomActivationCannotBorrowMiMoProfile() { + let value = SwitchGLU( + inputDims: 64, hiddenDims: 32, numExperts: 16, + activation: { $0 + 0.25 }, weightedReductionProfile: .mimoV26FP32) + let (x, indices, weights) = inputs(length: 12, dtype: .float32) + let actual = value.callAndMiMoFP32WeightedReduce( + x, indices, weights: weights, enabled: true) + XCTAssertEqual(actual.route, .unsupportedActivation) + exact(actual.output, baseline(value, x, indices, weights)) + } + + func testRealMXFP4SwitchProjectionEngagesWithoutChangingQuantizedParameters() throws { + let value = try glu() + quantize( + model: value, + filter: { _, module in + module is SwitchLinear ? (groupSize: 32, bits: 4, mode: .mxfp4) : nil + }) + let parameters = value.parameters().flattened() + XCTAssertTrue(parameters.contains { $0.0.hasSuffix("scales") }) + let (x, indices, weights) = inputs(length: 12) + let actual = value.callAndMiMoFP32WeightedReduce( + x, indices, weights: weights, enabled: true) + XCTAssertEqual(actual.route, .fused) + exact(actual.output, baseline(value, x, indices, weights)) + let after = Dictionary(uniqueKeysWithValues: value.parameters().flattened()) + XCTAssertEqual(after.count, parameters.count) + for (name, original) in parameters { XCTAssertTrue(after[name] === original, name) } + } + + private func nativeConfig() throws -> MiMoV26Configuration { + try JSONDecoder().decode( + MiMoV26Configuration.self, + from: Data( + """ + {"model_type":"mimo_v2","architectures":["MiMoV2ForCausalLM"], + "hidden_size":64,"intermediate_size":128,"moe_intermediate_size":32, + "vocab_size":32,"num_hidden_layers":2,"max_position_embeddings":128, + "sliding_window_size":4,"sliding_window":4,"num_nextn_predict_layers":3, + "hybrid_layer_pattern":[0,1],"moe_layer_freq":[0,1], + "partial_rotary_factor":1,"attention_value_scale":0.707, + "layernorm_epsilon":0.000001,"attention_projection_layout":"split", + "moe_router_dtype":"bfloat16","hidden_act":"silu","dtype":"bfloat16", + "attention_bias":false,"tie_word_embeddings":false,"attention_dropout":0, + "scoring_func":"sigmoid","topk_method":"noaux_tc","n_routed_experts":16, + "num_experts_per_tok":8,"n_group":1,"topk_group":1,"norm_topk_prob":true, + "n_shared_experts":null,"routed_scaling_factor":1.7, + "num_attention_heads":2,"num_key_value_heads":1,"head_dim":32,"v_head_dim":16, + "swa_num_attention_heads":2,"swa_num_key_value_heads":1,"swa_head_dim":32, + "swa_v_head_dim":16,"rope_theta":10000000,"swa_rope_theta":10000, + "add_full_attention_sink_bias":false,"add_swa_attention_sink_bias":true, + "eos_token_id":3,"pad_token_id":0} + """.utf8)) + } + + func testActualMiMoRouterAndMoEUseFP32WeightsAndOriginalFinalCast() throws { + let config = try nativeConfig() + let off = MiMoV26MoE(config, fp32WeightedReduction: false) + let on = MiMoV26MoE(config, fp32WeightedReduction: true) + let parameters = Dictionary( + uniqueKeysWithValues: off.parameters().flattened().map { name, value in + let dtype: DType = name.hasSuffix("e_score_correction_bias") ? .float32 : .bfloat16 + return ( + name, + MLXArray( + (0 ..< value.size).map { sin(Float($0 * 11 + 17)) * 0.05 }, + value.shape + ).asType(dtype) + ) + }) + try off.update(parameters: .unflattened(parameters), verify: .all) + try on.update(parameters: .unflattened(parameters), verify: .all) + let (x, _, _) = inputs(length: 12) + let before = off.gate(x) + let after = on.gate(x) + XCTAssertEqual(before.weights.dtype, .float32) + XCTAssertEqual(after.weights.dtype, .float32) + exact(before.weights, after.weights) + exact(before.indices, after.indices) + eval(after.weights) + XCTAssertTrue( + any(after.weights .!= after.weights.asType(.bfloat16).asType(.float32)).item(Bool.self), + "Actual router fixture must retain information beyond BF16") + let candidate = on.forwardWithWeightedReductionRoute(x) + XCTAssertEqual( + candidate.route, .fused, "Real MiMo route must engage, not just direct helper") + XCTAssertEqual(candidate.output.dtype, x.dtype) + let reference = (off.switchMLP(x, before.indices) * before.weights[.ellipsis, .newAxis]) + .sum(axis: -2).asType(x.dtype) + exact(candidate.output, reference) + exact(off(x), reference) + exact(on(x), candidate.output) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26FactoryTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26FactoryTests.swift new file mode 100644 index 0000000000..265bd1515d --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26FactoryTests.swift @@ -0,0 +1,751 @@ +import Foundation +import MLX +import MLXLLM +import MLXNN +import XCTest + +@testable import MLXLMCommon +@testable import MLXVLM + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +/// Mock-tokenizer routing tests are not real tokenizer/Jinja qualification. +/// Native tests use the existing generated BF16 payload and explicit lane gate. + +private func withMiMoConstructionScope( + _ body: (NativeConstructionScope) throws -> Value +) rethrows -> Value { + let work = NativeConstructionScope() + defer { + // Unexpected failed completion is restart-only, including in this + // dedicated native test process. Never deallocate its sole SDK owner. + if work.snapshot.isRetainedFault { _ = Unmanaged.passRetained(work) } + } + return try body(work) +} + +final class MiMoV26FactoryTests: XCTestCase { + private enum ProbeError: Error { case tokenizer, callback, revoked } + private final class Permit: MiMoV26SerialLoadReservation, @unchecked Sendable { + let request: MiMoV26SerialLoadRequest + let reservedLoadBytes: UInt64 + private let lock = NSLock() + private var revoked = false + private var count = 0 + var validations: Int { + lock.lock() + defer { lock.unlock() } + return count + } + init(_ request: MiMoV26SerialLoadRequest) { + self.request = request + reservedLoadBytes = request.requiredLoadBytes + } + func revoke() { + lock.lock() + revoked = true + lock.unlock() + } + func validateActive(progress: MiMoV26SerialLoadProgress) throws { + lock.lock() + defer { lock.unlock() } + count += 1 + if revoked { throw ProbeError.revoked } + } + } + private final class MockTokenizer: Tokenizer, @unchecked Sendable { + struct Call: Sendable { + let messages: [Message] + let template: String + let tools: [[String: any Sendable]]? + let context: [String: any Sendable]? + } + private let lock = NSLock() + private var recorded: [Call] = [] + private var directories: [URL] = [] + var calls: [Call] { + lock.lock() + defer { lock.unlock() } + return recorded + } + var loadedDirectories: [URL] { + lock.lock() + defer { lock.unlock() } + return directories + } + func loaded(from directory: URL) { + lock.lock() + directories.append(directory) + lock.unlock() + } + func encode(text: String, addSpecialTokens: Bool) -> [Int] { [6] } + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + tokenIds.map(String.init).joined(separator: " ") + } + func convertTokenToId(_ token: String) -> Int? { + ["<|im_start|>": 1, "<|im_end|>": 3, "": 4, "": 5, "<|extra_eos|>": 7][ + token] + } + func convertIdToToken(_ id: Int) -> String? { id == 3 ? "<|im_end|>" : nil } + var bosToken: String? { nil } + var eosToken: String? { "<|im_end|>" } + var unknownToken: String? { nil } + func applyChatTemplate( + messages: [Message], tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { + throw TokenizerError.missingChatTemplate + } + func applyChatTemplate(messages: [Message], chatTemplate: String) throws -> [Int] { + try applyChatTemplate( + messages: messages, chatTemplate: chatTemplate, tools: nil, additionalContext: nil) + } + func applyChatTemplate( + messages: [Message], chatTemplate: String, tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { + lock.lock() + recorded.append( + .init( + messages: messages, template: chatTemplate, + tools: tools, context: additionalContext)) + lock.unlock() + return [1, 2] + + ((additionalContext?["enable_thinking"] as? Bool) == false ? [4, 5] : []) + [6] + } + } + private struct Loader: TokenizerLoader { + let tokenizer: MockTokenizer + var fail = false + var mutateTemplate: URL? + func load(from directory: URL) async throws -> any Tokenizer { + tokenizer.loaded(from: directory) + if fail { throw ProbeError.tokenizer } + if let mutateTemplate { try Data("changed template".utf8).write(to: mutateTemplate) } + return tokenizer + } + } + private let literal = + "{{ messages }}{% if enable_thinking is false %}{% endif %}\n" + + private func fixture(allEOS: Bool = false) throws -> (URL, MiMoV26SerialLoadSession) { + guard let path = ProcessInfo.processInfo.environment["MIMO_V26_SERIAL_LOAD_FIXTURES"] else { + throw XCTSkip("Requires existing generated MIMO_V26_SERIAL_LOAD_FIXTURES") + } + let fixtures = URL(fileURLWithPath: path) + let root = fixtures.appendingPathComponent("factory-work-" + UUID().uuidString) + try FileManager.default.copyItem(at: fixtures.appendingPathComponent("tiny-bf16"), to: root) + // These are mock-tokenizer sidecars, never replacements for model payloads + // or an assertion that this placeholder is a real tokenizer asset. + try Data("{}".utf8).write(to: root.appendingPathComponent("tokenizer.json")) + try JSONSerialization.data(withJSONObject: [ + "chat_template": "embedded alternate", "eos_token": "<|im_end|>", + ]) + .write(to: root.appendingPathComponent("tokenizer_config.json")) + try Data(literal.utf8).write(to: root.appendingPathComponent("chat_template.jinja")) + let native = try JSONDecoder().decode( + MiMoV26Configuration.self, + from: Data(contentsOf: root.appendingPathComponent("config.json"))) + try JSONSerialization.data(withJSONObject: [ + "eos_token_id": allEOS ? Array(0 ..< native.vocabularySize) : [4, 5] + ]) + .write(to: root.appendingPathComponent("generation_config.json")) + let p = try XCTUnwrap( + JSONSerialization.jsonObject( + with: Data(contentsOf: fixtures.appendingPathComponent("provenance.json"))) + as? [String: String]) + let provenance = try MiMoV26ConvertedProvenance( + artifactID: XCTUnwrap(p["artifactID"]), + sourceRepository: XCTUnwrap(p["sourceRepository"]), + sourceRevision: XCTUnwrap(p["sourceRevision"]), + conversionManifestSHA256: XCTUnwrap(p["conversionManifestSHA256"])) + let plan = try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance, + limits: .init(maximumShardBytes: 1_048_576, maximumTotalFileBytes: 4_194_304)) + return (root, try MiMoV26SerialLoadSession(plan: plan)) + } + private func nativeLane() throws { + guard ProcessInfo.processInfo.environment["MIMO_V26_SERIAL_NATIVE_TESTS"] == "1" else { + throw XCTSkip("Requires coordinator-owned native lane") + } + } + private func prepared( + _ root: URL, _ session: MiMoV26SerialLoadSession, + tokenizer: MockTokenizer = .init(), toolCallFormat: ToolCallFormat? = nil + ) async throws -> MiMoV26ModelFactory.Prepared { + var configuration = ResolvedModelConfiguration(directory: root) + configuration.extraEOSTokens = ["<|extra_eos|>"] + configuration.toolCallFormat = toolCallFormat + return try await MiMoV26ModelFactory.prepare( + request: session.request, configuration: configuration, + tokenizerLoader: Loader(tokenizer: tokenizer)) + } + + func testPreparationBindsExactRequestTemplateEOSAndNativeDefaults() async throws { + let (root, session) = try fixture() + let tokenizer = MockTokenizer() + let value = try await prepared(root, session, tokenizer: tokenizer) + XCTAssertEqual(value.request, session.request) + XCTAssertEqual(value.processor.chatTemplate, literal) + XCTAssertEqual(value.stopTokenIDs, [3, 4, 5, 7]) + XCTAssertEqual( + tokenizer.loadedDirectories, [root.resolvingSymlinksInPath().standardizedFileURL]) + XCTAssertEqual(tokenizer.calls.count, 3) + XCTAssertNil(tokenizer.calls[0].context) + XCTAssertEqual(tokenizer.calls[1].context?["enable_thinking"] as? Bool, true) + XCTAssertEqual(tokenizer.calls[2].context?["enable_thinking"] as? Bool, false) + XCTAssertTrue(tokenizer.calls.allSatisfy { $0.template == literal }) + let other = try MiMoV26SerialLoadSession( + plan: MiMoV26FilesystemWeights.preflight( + root: root, + provenance: try provenance(), + limits: .init(maximumShardBytes: 1_048_576, maximumTotalFileBytes: 4_194_304))) + let wrong = Permit(other.request) + XCTAssertThrowsError( + try withMiMoConstructionScope { constructionWork in + try MiMoV26ModelFactory.load( + session: other, reservation: wrong, prepared: value, retaining: constructionWork + ) + }) + XCTAssertEqual(wrong.validations, 0) + } + + func testTokenizerFailureAndAssetDriftRejectBeforeNativeLoad() async throws { + let (root, session) = try fixture() + let tokenizer = MockTokenizer() + do { + _ = try await MiMoV26ModelFactory.prepare( + request: session.request, configuration: .init(directory: root), + tokenizerLoader: Loader(tokenizer: tokenizer, fail: true)) + XCTFail("tokenizer failure accepted") + } catch is ProbeError {} + let value = try await prepared(root, session) + let permit = Permit(session.request) + try Data("different".utf8).write(to: root.appendingPathComponent("chat_template.jinja")) + XCTAssertThrowsError( + try withMiMoConstructionScope { constructionWork in + try MiMoV26ModelFactory.load( + session: session, reservation: permit, prepared: value, + retaining: constructionWork) + }) + XCTAssertEqual(permit.validations, 0) + let (secondRoot, second) = try fixture() + do { + _ = try await MiMoV26ModelFactory.prepare( + request: second.request, configuration: .init(directory: secondRoot), + tokenizerLoader: Loader( + tokenizer: .init(), + mutateTemplate: secondRoot.appendingPathComponent("chat_template.jinja"))) + XCTFail("tokenizer await changed source without refusal") + } catch { XCTAssertTrue(error is MiMoV26FactoryError) } + } + + func testBoundedReaderDetectsGrowthReplacementAndSymlinkWithoutOversizedRead() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("mimo-factory-read-" + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let root = directory.resolvingSymlinksInPath().standardizedFileURL + let exact = root.appendingPathComponent("exact.json") + try Data(repeating: 65, count: 16).write(to: exact) + let exactReader = try MiMoV26FactoryMetadataFile(exact) + XCTAssertEqual(try exactReader.read(maximumBytes: 16).count, 16) + XCTAssertEqual(exactReader.bytesRead, 16) + XCTAssertThrowsError(try exactReader.read(maximumBytes: 16)) + let tooSmall = try MiMoV26FactoryMetadataFile(exact) + XCTAssertThrowsError(try tooSmall.read(maximumBytes: 15)) + XCTAssertEqual(tooSmall.bytesRead, 0) + + let growing = root.appendingPathComponent("growing.json") + try Data(repeating: 65, count: 8).write(to: growing) + let growingReader = try MiMoV26FactoryMetadataFile(growing) + XCTAssertThrowsError( + try growingReader.read( + maximumBytes: 16, + beforeFirstRead: { + // Deterministic mutation after the pre-read validation: no racing + // thread or sleep is required to reach the actual read-size bound. + let writer = try FileHandle(forWritingTo: growing) + defer { try? writer.close() } + try writer.seekToEnd() + try writer.write(contentsOf: Data(repeating: 66, count: 64)) + })) + XCTAssertEqual(growingReader.largestReadRequest, 17) + XCTAssertGreaterThan(growingReader.bytesRead, 0) + XCTAssertLessThanOrEqual( + growingReader.bytesRead, 17, "actual read must be limited to maximum+1 after growth") + + let replaced = root.appendingPathComponent("replaced.json") + try Data("old".utf8).write(to: replaced) + let replacementReader = try MiMoV26FactoryMetadataFile(replaced) + XCTAssertThrowsError( + try replacementReader.read( + maximumBytes: 16, + beforeFirstRead: { + let next = root.appendingPathComponent("next.json") + try Data("new".utf8).write(to: next) + try FileManager.default.moveItem( + at: replaced, to: root.appendingPathComponent("old.json")) + try FileManager.default.moveItem(at: next, to: replaced) + })) + XCTAssertLessThanOrEqual(replacementReader.bytesRead, 17) + let link = root.appendingPathComponent("link.json") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: exact) + XCTAssertThrowsError(try MiMoV26FactoryMetadataFile(link)) + } + + func testTokenizerSameSizeEditWithRestoredMTimeChangesCTimeAndRefusesLoad() async throws { + let (root, session) = try fixture() + let value = try await prepared(root, session) + let url = root.appendingPathComponent("tokenizer.json").resolvingSymlinksInPath() + .standardizedFileURL + let before = try MiMoV26FactoryMetadataFile(url).object + var raw = stat() + XCTAssertEqual(lstat(url.path, &raw), 0) + #if canImport(Darwin) + let preserved = [raw.st_atimespec, raw.st_mtimespec] + #else + let preserved = [raw.st_atim, raw.st_mtim] + #endif + let writer = try FileHandle(forWritingTo: url) + try writer.write(contentsOf: Data("[]".utf8)) // replaces "{}" without changing size or inode + XCTAssertEqual( + preserved.withUnsafeBufferPointer { futimens(writer.fileDescriptor, $0.baseAddress) }, 0 + ) + try writer.close() + let after = try MiMoV26FactoryMetadataFile(url).object + XCTAssertEqual(after.bytes, before.bytes) + XCTAssertEqual(after.inode, before.inode) + XCTAssertEqual(after.modifiedSeconds, before.modifiedSeconds) + XCTAssertEqual(after.modifiedNanoseconds, before.modifiedNanoseconds) + XCTAssertTrue( + after.changedSeconds != before.changedSeconds + || after.changedNanoseconds != before.changedNanoseconds) + let permit = Permit(session.request) + // If the metadata gate regresses, this still blocks native construction. + permit.revoke() + XCTAssertThrowsError( + try withMiMoConstructionScope { constructionWork in + try MiMoV26ModelFactory.load( + session: session, reservation: permit, prepared: value, + retaining: constructionWork) + } + ) { + XCTAssertEqual($0 as? MiMoV26FactoryError, .changedTokenizerAssets) + } + XCTAssertEqual(permit.validations, 0) + } + + func testTextInputPreservesToolsAndRejectsEveryMediaRouteBeforeTokenization() throws { + let tokenizer = MockTokenizer() + let processor = try MiMoV26TextProcessor( + tokenizer: tokenizer, chatTemplate: literal, + vocabularySize: 128, maximumSequenceLength: 128) + let historicalFunction: [String: String] = ["name": "f", "arguments": "{\"x\": 1}"] + let historicalCalls: [Message] = [["id": "call-1", "function": historicalFunction]] + let messages: [Message] = [ + [ + "role": "assistant", "content": "answer", "reasoning_content": "prior thought", + "tool_calls": historicalCalls, + ] + ] + let tools: [[String: any Sendable]] = [["type": "function", "function": ["name": "f"]]] + _ = try processor.renderTokens( + input: UserInput( + messages: messages, tools: tools, + additionalContext: ["enable_thinking": false])) + let call = try XCTUnwrap(tokenizer.calls.last) + XCTAssertEqual(call.messages[0]["reasoning_content"] as? String, "prior thought") + XCTAssertEqual(call.tools?.count, 1) + var chat = Chat.Message.user("per-message tools") + chat.templateFields["tools"] = tools + _ = try processor.renderTokens(input: UserInput(chat: [chat])) + XCTAssertNotNil(tokenizer.calls.last?.messages[0]["tools"]) + var audioChat = Chat.Message.user("audio") + audioChat.templateFields["audio"] = "unused" + let callsBefore = tokenizer.calls.count + let unusedAudio: [String: String] = ["data": "unused", "format": "wav"] + let audioContent: [Message] = [["type": "input_audio", "input_audio": unusedAudio]] + for input in [ + UserInput(prompt: "image", images: [.url(URL(fileURLWithPath: "/not-read.png"))]), + UserInput(prompt: "video", videos: [.frames([])]), + UserInput(messages: [["role": "user", "content": audioContent]]), + UserInput(messages: [ + ["role": "user", "content": [["type": "image_url", "image_url": "unused"]]] + ]), + UserInput(messages: [ + ["role": "user", "content": [["type": "video", "video": "unused"]]] + ]), + UserInput(messages: [["role": "user", "content": "text", "audio": "unused"]]), + UserInput(chat: [audioChat]), + UserInput(prompt: "audio", additionalContext: ["audio": "unused"]), + UserInput(prompt: "bad control", additionalContext: ["enable_thinking": "false"]), + UserInput(prompt: "bad control", additionalContext: ["enable_thinking": 0]), + ] { + XCTAssertThrowsError(try processor.renderTokens(input: input)) + } + XCTAssertEqual(tokenizer.calls.count, callsBefore) + } + + func testKnownRoleMissingNullEmptyBodiesPreserveNativeToolHistory() throws { + let tokenizer = MockTokenizer() + let processor = try MiMoV26TextProcessor( + tokenizer: tokenizer, chatTemplate: literal, + vocabularySize: 128, maximumSequenceLength: 128) + let bodyVariants: [Message] = [ + [:], ["content": NSNull()], + ["content": MLXLMCommon.JSONValue.null], ["content": ""], + ] + let arguments: [String: any Sendable] = [ + "text": "literal & e\u{301}", "nothing": NSNull(), + ] + let calls: [[String: any Sendable]] = [ + [ + "id": "c", "type": "function", + "function": ["name": "echo", "arguments": arguments] as [String: any Sendable], + ] + ] + let currentTools: [ToolSpec] = [ + ["type": "function", "function": ["name": "different"] as [String: any Sendable]] + ] + for role in ["system", "user", "assistant", "tool"] { + for variant in bodyVariants { + var message = variant + message["role"] = role + if role == "assistant" { + message["reasoning_content"] = "retain prior thought" + message["tool_calls"] = calls + } + for tools: [ToolSpec]? in [nil, currentTools] { + var messages = [message] + if role == "assistant" { + messages.append(["role": "tool", "tool_call_id": "c", "content": "ok"]) + } + _ = try processor.renderTokens( + input: UserInput(messages: messages, tools: tools)) + let delegated = try XCTUnwrap(tokenizer.calls.last) + XCTAssertEqual(delegated.messages[0]["role"] as? String, role) + XCTAssertEqual(delegated.messages[0]["content"] as? String, "") + if role == "assistant" { + XCTAssertEqual( + delegated.messages[0]["reasoning_content"] as? String, + "retain prior thought") + let retained = try XCTUnwrap( + delegated.messages[0]["tool_calls"] as? [[String: any Sendable]]) + XCTAssertEqual(retained[0]["id"] as? String, "c") + let function = try XCTUnwrap( + retained[0]["function"] as? [String: any Sendable]) + XCTAssertEqual(function["name"] as? String, "echo") + let values = try XCTUnwrap(function["arguments"] as? [String: any Sendable]) + XCTAssertEqual( + Data(try XCTUnwrap(values["text"] as? String).utf8), + Data("literal & e\u{301}".utf8)) + XCTAssertTrue( + values["nothing"] is NSNull, + "Only the content slot may be canonicalized") + XCTAssertEqual(delegated.messages[1]["tool_call_id"] as? String, "c") + } + } + } + } + // This spy proves admission/delegation only. Pinned Jinja byte/token + // parity is prepared in MiMoV26ConsumerParityTests, not mocked here. + } + + func testEmptyBodyCompatibilityKeepsMalformedUnknownAndMediaRefusals() throws { + let tokenizer = MockTokenizer() + let processor = try MiMoV26TextProcessor( + tokenizer: tokenizer, chatTemplate: literal, + vocabularySize: 128, maximumSequenceLength: 128) + let invalid: [Message] = [ + ["role": "unknown"], ["role": 0, "content": NSNull()], + ["role": "assistant", "content": 17], ["role": "assistant", "content": false], + ["role": "assistant", "content": ["text": "not a part array"]], + ["role": "assistant", "content": [1, 2]], + [ + "role": "assistant", + "content": [["type": "text", "text": 7] as [String: any Sendable]], + ], + ["role": "assistant", "content": [["type": "unknown", "text": "ignored"]]], + ["role": "assistant", "content": NSNull(), "image": NSNull()], + [ + "role": "assistant", + "content": [["type": "input_audio", "input_audio": "not-read"]], + ], + ] + for message in invalid { + XCTAssertThrowsError(try processor.renderTokens(input: UserInput(messages: [message]))) + } + XCTAssertTrue(tokenizer.calls.isEmpty) + } + + func testConflictingEOSAndDifferentTokenizerRootHaveNoLoaderFallback() async throws { + let (root, session) = try fixture() + let tokenizer = MockTokenizer() + var config = ResolvedModelConfiguration(directory: root) + config.eosTokenIds = [9] + do { + _ = try await MiMoV26ModelFactory.prepare( + request: session.request, configuration: config, + tokenizerLoader: Loader(tokenizer: tokenizer)) + XCTFail("conflicting EOS accepted") + } catch { XCTAssertTrue(error is MiMoV26FactoryError) } + config.eosTokenIds = [] + config.tokenizerDirectory = root.deletingLastPathComponent() + do { + _ = try await MiMoV26ModelFactory.prepare( + request: session.request, configuration: config, + tokenizerLoader: Loader(tokenizer: tokenizer)) + XCTFail("foreign tokenizer root accepted") + } catch { XCTAssertTrue(error is MiMoV26FactoryError) } + XCTAssertTrue(tokenizer.loadedDirectories.isEmpty) + } + + func testNativeContextHasOneParameterTreeAndRecoverableGenerationGate() async throws { + try nativeLane() + let (root, session) = try fixture() + let value = try await prepared(root, session) + let context = try withMiMoConstructionScope { constructionWork in + try MiMoV26ModelFactory.load( + session: session, reservation: Permit(session.request), prepared: value, + retaining: constructionWork) + } + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + XCTAssertEqual(model.loadReceipt.sessionID, session.request.sessionID) + XCTAssertEqual(model.parameters().flattened().count, model.loadReceipt.parameterCount) + XCTAssertEqual(model.nativeConfiguration.modelType, "mimo_v2") + XCTAssertEqual(context.configuration.eosTokenIds, [4, 5]) + XCTAssertEqual(context.configuration.toolCallFormat, .mimoV2) + XCTAssertEqual(model.stopTokenIDs, [3, 4, 5, 7]) + let input = try await context.processor.prepare(input: UserInput(prompt: "hello")) + XCTAssertThrowsError( + try TokenIterator(input: input, model: model, parameters: .init(maxTokens: 2)) + ) { + XCTAssertEqual($0 as? MiMoV26FactoryError, .nativeCBv2Required) + XCTAssertTrue($0.localizedDescription.contains("makeCBv2Binding")) + XCTAssertFalse($0.localizedDescription.contains("sparse")) + XCTAssertFalse($0.localizedDescription.contains("recurrent")) + } + let cache = model.newCache(parameters: nil) + XCTAssertThrowsError(try model.prepare(input, cache: cache, windowSize: nil)) + XCTAssertThrowsError( + try withMiMoConstructionScope { constructionWork in + try MiMoV26ModelFactory.load( + session: session, reservation: Permit(session.request), prepared: value, + retaining: constructionWork) + } + ) { + XCTAssertEqual($0 as? MiMoV26SerialLoadError, .alreadyConsumed) + } + } + + func testNativeBindingRetainsReservationAndAllTowersAfterWrapperRelease() async throws { + try nativeLane() + let (root, session) = try fixture() + let value = try await prepared(root, session) + var permit: Permit? = Permit(session.request) + weak var permitWitness = permit + var context: ModelContext? = try withMiMoConstructionScope { constructionWork in + try MiMoV26ModelFactory.load( + session: session, + reservation: XCTUnwrap(permit), prepared: value, retaining: constructionWork) + } + var wrapper = context?.model as? MiMoV26LoadedModel + weak var visionWitness = wrapper?.resources.loaded.bundle.vision + weak var audioWitness = wrapper?.resources.loaded.bundle.audioPatch + var binding: MiMoV26CBv2Binding? = try XCTUnwrap(wrapper).makeCBv2Binding(enableMTP: true) + var adapter = binding?.adapter + var assistant = binding?.assistant + binding = nil + wrapper = nil + context = nil + permit = nil + XCTAssertNotNil(permitWitness) + XCTAssertNotNil(visionWitness) + XCTAssertNotNil(audioWitness) + XCTAssertNotNil(adapter?.target) + adapter = nil + XCTAssertNotNil(assistant?.mtpTargetIdentity) + XCTAssertNotNil(permitWitness) + XCTAssertNotNil(visionWitness) + assistant = nil + XCTAssertNil(permitWitness) + XCTAssertNil(visionWitness) + XCTAssertNil(audioWitness) + } + + func testNativeCBv2GenerationUsesFactoryEOSAndContainerOwnership() async throws { + try nativeLane() + let (root, session) = try fixture(allEOS: true) + let value = try await prepared(root, session) + let context = try withMiMoConstructionScope { constructionWork in + try MiMoV26ModelFactory.load( + session: session, reservation: Permit(session.request), prepared: value, + retaining: constructionWork) + } + let wrapper = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + let binding = try wrapper.makeCBv2Binding() + XCTAssertNil(binding.assistant) + _ = try withMiMoConstructionScope { constructionWork in + try binding.adapter.probeNativeKVTypes(retaining: constructionWork) + } + let backend = try binding.adapter.makeBackend(bytesCapacity: 16 << 20) + let engine = EngineV2( + model: binding.adapter, layerKinds: binding.adapter.layerKinds, backend: backend, + cacheProvider: CBv2LayerCacheBank(caches: binding.adapter.makeCaches()), + schedulerConfig: .init( + maxConcurrentRequests: 1, maxBatchedTokensPerStep: 16, prefillChunkSize: 4, + maxWaiting: 2)) + let output = await cbv2SchedCollect( + try engine.submit( + .init( + id: .init(1), promptTokens: [1, 2, 6], + sampling: .init(temperature: 0), maxTokens: 4, stopTokens: binding.stopTokenIDs) + )) + await engine.shutdown() + XCTAssertEqual(output.finishReason, .stop) + XCTAssertEqual( + output.tokens.count, 1, + "all-vocabulary synthetic EOS must stop the actual first target token") + XCTAssertEqual(backend.bytesInUse, 0) + let (otherRoot, other) = try fixture() + let otherPrepared = try await prepared(otherRoot, other, toolCallFormat: .json) + let managedWork = NativeConstructionWork() + defer { + if managedWork.snapshot.isRetainedFault { _ = Unmanaged.passRetained(managedWork) } + } + let container = try await MiMoV26ModelFactory.loadContainer( + session: other, reservation: Permit(other.request), + prepared: otherPrepared, retaining: managedWork) + try await managedWork.acknowledgeContainerAdoption(container) + let identity = await container.perform { context in + ( + (context.model as! MiMoV26LoadedModel).loadReceipt.sessionID, + context.configuration.toolCallFormat + ) + } + XCTAssertEqual(identity.0, other.request.sessionID) + XCTAssertEqual( + identity.1, .json, + "explicit supported parser override must survive factory construction") + } + + func testNativeFinalCallbackFailureCancellationAndReloadDoNotPublish() async throws { + try nativeLane() + for cancel in [false, true] { + let (root, session) = try fixture() + let value = try await prepared(root, session) + var permit: Permit? = Permit(session.request) + weak var witness = permit + var reached = false + var cancelled = false + XCTAssertThrowsError( + try withMiMoConstructionScope { constructionWork in + try MiMoV26ModelFactory.load( + session: session, reservation: XCTUnwrap(permit), prepared: value, + retaining: constructionWork, + isCancelled: { cancelled }, + progress: { progress in + XCTAssertNotNil(witness) + if progress.phase == .complete { + reached = true + permit = nil + XCTAssertNotNil( + witness, + "factory/serial transaction must retain the host owner through unwind" + ) + if cancel { cancelled = true } else { throw ProbeError.callback } + } + }) + }) + XCTAssertTrue(reached) + XCTAssertNil(witness, "failed publication must not leak a hidden loaded owner") + XCTAssertThrowsError( + try withMiMoConstructionScope { constructionWork in + try MiMoV26ModelFactory.load( + session: session, reservation: Permit(session.request), prepared: value, + retaining: constructionWork) + } + ) { + XCTAssertEqual($0 as? MiMoV26SerialLoadError, .alreadyConsumed) + } + } + let (root, session) = try fixture() + let value = try await prepared(root, session) + let permit = Permit(session.request) + permit.revoke() + XCTAssertThrowsError( + try withMiMoConstructionScope { constructionWork in + try MiMoV26ModelFactory.load( + session: session, reservation: permit, prepared: value, + retaining: constructionWork) + }) + XCTAssertEqual(permit.validations, 1) + } + + func testCustomCancellationGetsAnAdditionalVetoAfterSerialLoadCompletes() async throws { + try nativeLane() + let (root, control) = try fixture() + var complete = false + var serialPostCompleteCalls = 0 + do { + // Measure the real serial session's own predicate visits, rather + // than hard-code its internal revalidation/shard loop count. + let loaded = try withMiMoConstructionScope { constructionWork in + try control.load( + reservation: Permit(control.request), retaining: constructionWork, + isCancelled: { + if complete { serialPostCompleteCalls += 1 } + return false + }, progress: { if $0.phase == .complete { complete = true } }) + } + StreamOrDevice.default.stream.synchronize() + withExtendedLifetime(loaded) {} + } + let session = try MiMoV26SerialLoadSession( + plan: MiMoV26FilesystemWeights.preflight( + root: root, + provenance: try provenance(), + limits: .init(maximumShardBytes: 1_048_576, maximumTotalFileBytes: 4_194_304))) + let value = try await prepared(root, session) + var completedAgain = false + var postCompleteCalls = 0 + XCTAssertThrowsError( + try withMiMoConstructionScope { constructionWork in + try MiMoV26ModelFactory.load( + session: session, reservation: Permit(session.request), + prepared: value, retaining: constructionWork, + isCancelled: { + guard completedAgain else { return false } + postCompleteCalls += 1 + return postCompleteCalls > serialPostCompleteCalls + }, progress: { if $0.phase == .complete { completedAgain = true } }) + } + ) { + XCTAssertEqual($0 as? MiMoV26SerialLoadError, .cancelled) + } + XCTAssertTrue(completedAgain) + XCTAssertEqual( + postCompleteCalls, serialPostCompleteCalls + 1, + "factory must query custom cancellation after its final metadata revalidation") + } + + private func provenance() throws -> MiMoV26ConvertedProvenance { + let path = try XCTUnwrap( + ProcessInfo.processInfo.environment["MIMO_V26_SERIAL_LOAD_FIXTURES"]) + let p = try XCTUnwrap( + JSONSerialization.jsonObject( + with: Data( + contentsOf: + URL(fileURLWithPath: path).appendingPathComponent("provenance.json"))) + as? [String: String]) + return try .init( + artifactID: XCTUnwrap(p["artifactID"]), + sourceRepository: XCTUnwrap(p["sourceRepository"]), + sourceRevision: XCTUnwrap(p["sourceRevision"]), + conversionManifestSHA256: XCTUnwrap(p["conversionManifestSHA256"])) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26FailedConstructionTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26FailedConstructionTests.swift new file mode 100644 index 0000000000..5e01d637c5 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26FailedConstructionTests.swift @@ -0,0 +1,600 @@ +import Foundation +import MLX +import MLXLLM +import XCTest + +@testable import MLXLMCommon +@testable import MLXVLM + +/// Ownership tests execute real tiny filesystem/model/probe work. The stateless +/// tokenizer below controls preparation only; it is NOT tokenizer/Jinja parity. +final class MiMoV26FailedConstructionTests: XCTestCase { + private enum Failure: Error { case boundary, fence, unexpectedlyExecuted } + private final class Permit: MiMoV26SerialLoadReservation, Sendable { + let request: MiMoV26SerialLoadRequest + let reservedLoadBytes: UInt64 + init(_ request: MiMoV26SerialLoadRequest) { + self.request = request + reservedLoadBytes = request.requiredLoadBytes + } + func validateActive(progress: MiMoV26SerialLoadProgress) throws {} + } + private final class ControlTokenizer: Tokenizer, Sendable { + func encode(text: String, addSpecialTokens: Bool) -> [Int] { [6] } + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + tokenIds.map(String.init).joined() + } + func convertTokenToId(_ token: String) -> Int? { token == "<|im_end|>" ? 3 : nil } + func convertIdToToken(_ id: Int) -> String? { id == 3 ? "<|im_end|>" : nil } + var bosToken: String? { nil } + var eosToken: String? { "<|im_end|>" } + var unknownToken: String? { nil } + func applyChatTemplate( + messages: [Message], tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { + throw TokenizerError.missingChatTemplate + } + func applyChatTemplate(messages: [Message], chatTemplate: String) throws -> [Int] { + try applyChatTemplate( + messages: messages, chatTemplate: chatTemplate, tools: nil, additionalContext: nil) + } + func applyChatTemplate( + messages: [Message], chatTemplate: String, tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { + [1] + ((additionalContext?["enable_thinking"] as? Bool) == false ? [4, 5] : []) + [6] + } + } + private struct Loader: TokenizerLoader { + func load(from directory: URL) async throws -> any Tokenizer { ControlTokenizer() } + } + private func nativeLane(faultCase: String? = nil) throws { + let environment = ProcessInfo.processInfo.environment + guard environment["MIMO_V26_SERIAL_NATIVE_TESTS"] == "1" else { + throw XCTSkip( + "Requires a root-authorized exclusive native failure-ownership test process") + } + // Every retained-fault selector gets its OWN process and exact selector. + // Never run another native cell after an unknown-completion outcome. + guard environment["MIMO_V26_CONSTRUCTION_FAULT_CASE"] == faultCase else { + throw XCTSkip( + "Run this retained-fault selector alone with its exact MIMO_V26_CONSTRUCTION_FAULT_CASE name" + ) + } + } + private func preserveFault(_ work: NativeConstructionScope) { + // Restart-only faults deliberately survive this dedicated test process. + // This is NOT an in-process recovery or a production global registry. + if work.snapshot.isRetainedFault { _ = Unmanaged.passRetained(work) } + } + private func preserveFault(_ work: NativeConstructionWork) { + if work.snapshot.isRetainedFault { _ = Unmanaged.passRetained(work) } + } + private func fixture() throws -> (URL, MiMoV26FilesystemLoadPlan, MiMoV26SerialLoadSession) { + let path = try XCTUnwrap( + ProcessInfo.processInfo.environment["MIMO_V26_SERIAL_LOAD_FIXTURES"]) + let fixtures = URL(fileURLWithPath: path) + let root = fixtures.appendingPathComponent("construction-work-" + UUID().uuidString) + try FileManager.default.copyItem(at: fixtures.appendingPathComponent("tiny-bf16"), to: root) + try Data("{}".utf8).write(to: root.appendingPathComponent("tokenizer.json")) + try JSONSerialization.data(withJSONObject: ["eos_token": "<|im_end|>"]) + .write(to: root.appendingPathComponent("tokenizer_config.json")) + try Data("{{ messages }}{% if enable_thinking is false %}{% endif %}".utf8) + .write(to: root.appendingPathComponent("chat_template.jinja")) + let p = try XCTUnwrap( + JSONSerialization.jsonObject( + with: + Data(contentsOf: fixtures.appendingPathComponent("provenance.json"))) + as? [String: String]) + let provenance = try MiMoV26ConvertedProvenance( + artifactID: XCTUnwrap(p["artifactID"]), + sourceRepository: XCTUnwrap(p["sourceRepository"]), + sourceRevision: XCTUnwrap(p["sourceRevision"]), + conversionManifestSHA256: XCTUnwrap(p["conversionManifestSHA256"])) + let plan = try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance, + limits: .init(maximumShardBytes: 1_048_576, maximumTotalFileBytes: 4_194_304)) + return (root, plan, try MiMoV26SerialLoadSession(plan: plan)) + } + private func prepare(_ root: URL, _ session: MiMoV26SerialLoadSession) async throws + -> MiMoV26ModelFactory.Prepared + { + try await MiMoV26ModelFactory.prepare( + request: session.request, + configuration: .init(directory: root), tokenizerLoader: Loader()) + } + private func receipt(_ snapshot: NativeConstructionSnapshot) throws -> NativeConstructionReceipt + { + guard case .completed(let receipt) = snapshot.disposition else { + XCTFail("missing completed epoch: \(snapshot)") + throw Failure.boundary + } + return receipt + } + + func testMetadataFailureHasNoSubmissionReceiptAndConsumesSession() throws { + try nativeLane() + let (_, plan, session) = try fixture() + let other = try MiMoV26SerialLoadSession(plan: plan) + let work = NativeConstructionScope() + defer { preserveFault(work) } + XCTAssertThrowsError(try session.load(reservation: Permit(other.request), retaining: work)) + { + XCTAssertEqual($0 as? MiMoV26SerialLoadError, .reservationMismatch) + } + let first = try receipt(work.snapshot) + XCTAssertEqual(first.completion, .noNativeSubmission) + XCTAssertEqual(work.snapshot.retainedArrayCount, 0) + XCTAssertEqual(work.snapshot.retainedOwnerCount, 0) + XCTAssertEqual(work.snapshot.capturedStreamCount, 0) + XCTAssertThrowsError( + try session.load(reservation: Permit(session.request), retaining: work) + ) { + XCTAssertEqual($0 as? MiMoV26SerialLoadError, .alreadyConsumed) + } + XCTAssertThrowsError(try work.validate(first)) + XCTAssertGreaterThan(try receipt(work.snapshot).epoch, first.epoch) + } + + func testCPUFailureRetainsActualSourceAndPermit() throws { + try nativeLane(faultCase: "testCPUFailureRetainsActualSourceAndPermit") + try checkSourceFailure(refuseCPU: true) + } + + func testDefaultFailureRetainsActualSourceAndPermit() throws { + try nativeLane(faultCase: "testDefaultFailureRetainsActualSourceAndPermit") + try checkSourceFailure(refuseCPU: false) + } + + private func checkSourceFailure(refuseCPU: Bool) throws { + let (_, _, session) = try fixture() + var permit: Permit? = Permit(session.request) + weak var permitWitness = permit + weak var sourceWitness: MLXArray? + let work = NativeConstructionScope() + defer { preserveFault(work) } + var attempted: [MLX.Stream] = [] + try MLX.Stream.withNewDefaultStream(device: .gpu) { + let cpu = StreamOrDevice.cpu.stream + let gpu = StreamOrDevice.default.stream + XCTAssertNotEqual(cpu, gpu) + work.testingBoundary = { name, scope in + let boundary = + refuseCPU ? "serial.sourceMaterialized" : "serial.parameterMaterialized" + if name == boundary { + sourceWitness = scope.retainedArraysForTesting.first { + (try? $0.evaluatedBufferInfo()) != nil + } + throw Failure.boundary + } + } + work.testingBeforeFence = { stream in + attempted.append(stream) + if stream == (refuseCPU ? cpu : gpu) { throw Failure.fence } + } + XCTAssertThrowsError(try session.load(reservation: XCTUnwrap(permit), retaining: work)) + XCTAssertTrue(attempted.contains(cpu)) + XCTAssertTrue(attempted.contains(gpu)) + XCTAssertEqual( + attempted.count, 2, "one failed stream must not suppress the other drain attempt") + } + permit = nil + XCTAssertTrue(work.snapshot.isRetainedFault) + XCTAssertNotNil(permitWitness) + XCTAssertNotNil(sourceWitness) + let source = try XCTUnwrap(sourceWitness) + XCTAssertTrue(work.retainedArraysForTesting.contains { $0 === source }) + XCTAssertGreaterThan(work.snapshot.retainedOwnerCount, 3) + XCTAssertEqual(work.snapshot.capturedStreamCount, 2) + let retry = try MiMoV26SerialLoadSession(plan: fixture().1) + XCTAssertThrowsError(try retry.load(reservation: Permit(retry.request), retaining: work)) { + guard let error = $0 as? NativeConstructionError, case .retainedFault = error else { + return XCTFail("fault reset: \($0)") + } + } + } + + func testFilesystemSourceIdentityAndSuccessfulFailureRetirement() throws { + try nativeLane() + let (_, plan, _) = try fixture() + let work = NativeConstructionScope() + defer { preserveFault(work) } + weak var source: MLXArray? + work.testingBoundary = { name, scope in + if name == "filesystem.returnedSourceHandles", source == nil { + source = scope.retainedArraysForTesting.first + } + } + var loaded = try MiMoV26FilesystemWeights.load(plan: plan, retaining: work) + let handles = loaded.takeMaterializationHandles() + let original = try XCTUnwrap(source) + XCTAssertTrue( + handles.contains { $0.array === original }, "no copied source tree at handoff") + XCTAssertEqual(try receipt(work.snapshot).completion, .noNativeSubmission) + XCTAssertEqual(work.snapshot.retainedArrayCount, 0) + XCTAssertEqual(work.snapshot.retainedOwnerCount, 0) + let session = try MiMoV26SerialLoadSession(plan: plan) + var permit: Permit? = Permit(session.request) + weak var permitWitness = permit + work.testingBoundary = { name, _ in + if name == "serial.sourceMaterialized" { throw Failure.boundary } + } + XCTAssertThrowsError(try session.load(reservation: XCTUnwrap(permit), retaining: work)) { + XCTAssertTrue($0 is Failure) + } + permit = nil + XCTAssertNil(permitWitness, "proved completion may drop the SDK's extra permit alias") + XCTAssertEqual(try receipt(work.snapshot).completion, .capturedStreamsCompleted) + XCTAssertEqual(work.snapshot.retainedArrayCount, 0) + XCTAssertEqual(work.snapshot.retainedOwnerCount, 0) + } + + func testFactoryLateCancellationFailedFenceRetainsCompleteBundle() async throws { + try nativeLane(faultCase: "testFactoryLateCancellationFailedFenceRetainsCompleteBundle") + let (root, _, session) = try fixture() + let prepared = try await prepare(root, session) + var permit: Permit? = Permit(session.request) + weak var permitWitness = permit + weak var vision: MiMoV26VisionTower? + let work = NativeConstructionScope() + defer { preserveFault(work) } + var cancelled = false + work.testingBoundary = { name, scope in + if name == "factory.beforePublication" { + vision = + scope.retainedOwnersForTesting.compactMap { $0 as? MiMoV26VisionTower }.first + cancelled = true + } + } + work.testingBeforeFence = { _ in throw Failure.fence } + XCTAssertThrowsError( + try MiMoV26ModelFactory.load( + session: session, reservation: XCTUnwrap(permit), + prepared: prepared, retaining: work, isCancelled: { cancelled })) + permit = nil + XCTAssertTrue(cancelled) + XCTAssertTrue(work.snapshot.isRetainedFault) + XCTAssertNotNil(vision) + XCTAssertNotNil(permitWitness) + XCTAssertGreaterThan(work.snapshot.retainedArrayCount, 0) + if case .retainedFault(let fault) = work.snapshot.disposition { + XCTAssertTrue(fault.cause.contains("cancelled")) + XCTAssertFalse(fault.completionFailures.isEmpty) + } else { + XCTFail("late cancelled factory lost its complete native owner") + } + } + + func testFactoryLateCancellationWithSuccessfulDrainDropsTemporaryOwners() async throws { + try nativeLane() + let (root, _, session) = try fixture() + let prepared = try await prepare(root, session) + var permit: Permit? = Permit(session.request) + weak var permitWitness = permit + weak var vision: MiMoV26VisionTower? + let work = NativeConstructionScope() + defer { preserveFault(work) } + var cancelled = false + work.testingBoundary = { name, scope in + if name == "factory.beforePublication" { + vision = + scope.retainedOwnersForTesting.compactMap { $0 as? MiMoV26VisionTower }.first + cancelled = true + } + } + XCTAssertThrowsError( + try MiMoV26ModelFactory.load( + session: session, reservation: XCTUnwrap(permit), + prepared: prepared, retaining: work, isCancelled: { cancelled }) + ) { + XCTAssertEqual($0 as? MiMoV26SerialLoadError, .cancelled) + } + permit = nil + XCTAssertTrue(cancelled) + XCTAssertNil(vision) + XCTAssertNil(permitWitness) + XCTAssertEqual(try receipt(work.snapshot).completion, .capturedStreamsCompleted) + XCTAssertEqual(work.snapshot.retainedArrayCount, 0) + XCTAssertEqual(work.snapshot.retainedOwnerCount, 0) + } + + func testManagedPreReturnFailureKeepsPreinstalledActualOwner() async throws { + try nativeLane(faultCase: "testManagedPreReturnFailureKeepsPreinstalledActualOwner") + let (root, _, session) = try fixture() + let prepared = try await prepare(root, session) + let work = NativeConstructionWork() // installed before invoking the factory + defer { preserveFault(work) } + var permit: Permit? = Permit(session.request) + weak var witness = permit + try await work.configureFailureForTesting { scope in + scope.testingBoundary = { name, _ in + if name == "serial.sourceMaterialized" { throw Failure.boundary } + } + scope.testingBeforeFence = { _ in throw Failure.fence } + } + do { + _ = try await MiMoV26ModelFactory.loadContainer( + session: session, + reservation: XCTUnwrap(permit), prepared: prepared, retaining: work) + XCTFail("failed construction returned a model") + } catch { + guard let error = error as? NativeConstructionError, case .retainedFault = error else { + return XCTFail("managed failure lost its completion error: \(error)") + } + } + permit = nil + XCTAssertNotNil( + witness, "the exact permit survives even though no ModelContainer was returned") + XCTAssertTrue(work.snapshot.isRetainedFault) + XCTAssertGreaterThan(work.snapshot.retainedArrayCount, 0) + XCTAssertGreaterThan(work.snapshot.retainedOwnerCount, 3) + XCTAssertGreaterThanOrEqual(work.snapshot.capturedStreamCount, 2) + } + + func testManagedAdoptionGapRetainsIdenticalContainerAndRejectsForeignOwner() async throws { + try nativeLane() + let (root, plan, session) = try fixture() + let prepared = try await prepare(root, session) + let work = NativeConstructionWork() + defer { preserveFault(work) } + var permit: Permit? = Permit(session.request) + weak var permitWitness = permit + var container: ModelContainer? = try await MiMoV26ModelFactory.loadContainer( + session: session, reservation: XCTUnwrap(permit), prepared: prepared, retaining: work) + weak var witness = container + container = nil + permit = nil + XCTAssertNotNil(witness) + XCTAssertNotNil(permitWitness, "ready-unclaimed owner must precede host await/veto") + let otherSession = try MiMoV26SerialLoadSession(plan: plan) + let otherPrepared = try await prepare(root, otherSession) + let otherWork = NativeConstructionWork() + defer { preserveFault(otherWork) } + let other = try await MiMoV26ModelFactory.loadContainer( + session: otherSession, + reservation: Permit(otherSession.request), prepared: otherPrepared, retaining: otherWork + ) + do { + try await work.acknowledgeContainerAdoption(other) + XCTFail("foreign container adopted") + } catch { XCTAssertEqual(error as? NativeConstructionError, .invalidContainerAdoption) } + XCTAssertNotNil(witness) + var adopted: ModelContainer? = try XCTUnwrap(witness) + try await work.acknowledgeContainerAdoption(XCTUnwrap(adopted)) + do { + try await work.acknowledgeContainerAdoption(XCTUnwrap(adopted)) + XCTFail("duplicate adoption") + } catch { XCTAssertEqual(error as? NativeConstructionError, .invalidContainerAdoption) } + adopted = nil + XCTAssertNil(witness) + XCTAssertNil(permitWitness, "successful handoff must not create a facade/owner cycle") + let releasedContainerReceipt = try receipt(work.snapshot) + do { + try await work.sealForPublication(releasedContainerReceipt) + XCTFail("a released adopted container cannot authorize publication") + } catch { + XCTAssertEqual(error as? NativeConstructionError, .invalidContainerAdoption) + } + try await otherWork.acknowledgeContainerAdoption(other) + } + + func testManagedSetupAdvancesEpochAndSealRejectsStaleReceipts() async throws { + try nativeLane() + let (root, _, session) = try fixture() + let prepared = try await prepare(root, session) + let work = NativeConstructionWork() + defer { preserveFault(work) } + let container = try await MiMoV26ModelFactory.loadContainer( + session: session, + reservation: Permit(session.request), prepared: prepared, retaining: work) + let loadReceipt = try receipt(work.snapshot) + do { + _ = try await MiMoV26ModelFactory.withNativeConstruction( + container: container, retaining: work + ) { _, _ -> Int in + throw Failure.unexpectedlyExecuted + } + XCTFail("unadopted setup accepted") + } catch { XCTAssertEqual(error as? NativeConstructionError, .invalidContainerAdoption) } + try await work.acknowledgeContainerAdoption(container) + let sessionID = try await MiMoV26ModelFactory.withNativeConstruction( + container: container, retaining: work + ) { model, scope in + let binding = try model.makeCBv2Binding() + _ = try binding.adapter.probeNativeKVTypes(retaining: scope) + let unowned = try MiMoV26CBv2Adapter(target: binding.adapter.target) + XCTAssertThrowsError( + try unowned.makeNativeExecutionResources(bytesCapacity: 1 << 20, retaining: scope) + ) { + XCTAssertEqual($0 as? NativeConstructionError, .unqualifiedNativeOwner) + } + let resources = try binding.adapter.makeNativeExecutionResources( + bytesCapacity: 1 << 20, retaining: scope) + XCTAssertEqual(resources.contract.constructionOwnerID, scope.snapshot.ownerID) + XCTAssertEqual(resources.contract.constructionEpoch, scope.snapshot.epoch) + XCTAssertEqual(resources.contract.constructionOwnerID, work.snapshot.ownerID) + XCTAssertTrue(scope.retainedOwnersForTesting.contains { $0 === resources.backend }) + XCTAssertTrue( + scope.retainedOwnersForTesting.contains { $0 === resources.cacheProvider }) + return model.loadReceipt.sessionID + } + XCTAssertEqual(sessionID, session.request.sessionID) + let setupReceipt = try receipt(work.snapshot) + XCTAssertGreaterThan(setupReceipt.epoch, loadReceipt.epoch) + XCTAssertThrowsError(try work.validate(loadReceipt)) + XCTAssertNoThrow(try work.validate(setupReceipt)) + try await work.sealForPublication(setupReceipt) + do { + _ = try await MiMoV26ModelFactory.withNativeConstruction( + container: container, retaining: work + ) { _, _ -> Int in + throw Failure.unexpectedlyExecuted + } + XCTFail("sealed owner reopened") + } catch { XCTAssertEqual(error as? NativeConstructionError, .invalidContainerAdoption) } + } + + func testUnstartedManagedFailureAtomicallyRefusesLaterLoad() async throws { + try nativeLane() + let (root, _, session) = try fixture() + let prepared = try await prepare(root, session) + let work = NativeConstructionWork() + let noWork = try await work.finishUnstartedConstruction() + XCTAssertEqual(noWork.completion, .noNativeSubmission) + XCTAssertNoThrow(try work.validate(noWork)) + XCTAssertEqual(work.snapshot.capturedStreamCount, 0) + do { + _ = try await MiMoV26ModelFactory.loadContainer( + session: session, + reservation: Permit(session.request), prepared: prepared, retaining: work) + XCTFail("closed metadata failure started native work") + } catch { XCTAssertEqual(error as? NativeConstructionError, .alreadyConsumed) } + do { + _ = try await work.finishUnstartedConstruction() + XCTFail("duplicate completion") + } catch { XCTAssertEqual(error as? NativeConstructionError, .alreadyConsumed) } + XCTAssertEqual(try receipt(work.snapshot), noWork) + } + + func testProbeFailedFenceRetainsRowsOutputAndPermanentlyDisablesAdapter() throws { + try nativeLane( + faultCase: "testProbeFailedFenceRetainsRowsOutputAndPermanentlyDisablesAdapter") + let (target, _) = try MiMoV26MTPChecks.fixture() + let adapter = try MiMoV26CBv2Adapter(target: target) + let work = NativeConstructionScope() + defer { preserveFault(work) } + weak var row: AnyObject? + weak var output: MLXArray? + work.testingBoundary = { name, scope in + if name == "probe.evaluated.decode" { + row = scope.retainedOwnersForTesting.first { $0 is any CBv2SequenceKV } + output = scope.retainedArraysForTesting.first { + $0.ndim == 3 && $0.shape.last == target.configuration.vocabularySize + } + throw Failure.boundary + } + } + work.testingBeforeFence = { _ in throw Failure.fence } + XCTAssertThrowsError(try adapter.probeNativeKVTypes(retaining: work)) + XCTAssertTrue(work.snapshot.isRetainedFault) + XCTAssertNotNil(row) + XCTAssertNotNil(output) + XCTAssertEqual((row as? any CBv2SequenceKV)?.absoluteOffset, 3) + XCTAssertGreaterThan(work.snapshot.retainedArrayCount, 0) + XCTAssertThrowsError(try adapter.probeNativeKVTypes(retaining: NativeConstructionScope())) + XCTAssertThrowsError(try adapter.makeBackend(bytesCapacity: 1 << 20)) + } + + func testSuccessfulProbeKeepsRowsUntilFenceThenUnbinds() throws { + try nativeLane() + let (target, _) = try MiMoV26MTPChecks.fixture() + let adapter = try MiMoV26CBv2Adapter(target: target) + let work = NativeConstructionScope() + defer { preserveFault(work) } + weak var row: AnyObject? + var fenced = 0 + work.testingBoundary = { name, scope in + if name == "probe.evaluated.decode" { + row = scope.retainedOwnersForTesting.first { $0 is any CBv2SequenceKV } + } + } + work.testingBeforeFence = { _ in + XCTAssertNotNil(row) + XCTAssertEqual((row as? any CBv2SequenceKV)?.absoluteOffset, 3) + fenced += 1 + } + let result = try adapter.probeNativeKVTypes(retaining: work) + XCTAssertFalse(result.observations.isEmpty) + XCTAssertGreaterThan(fenced, 0) + XCTAssertTrue(adapter.target === target) + XCTAssertNil(row) + XCTAssertEqual(work.snapshot.retainedArrayCount, 0) + XCTAssertEqual(work.snapshot.retainedOwnerCount, 0) + XCTAssertEqual(try receipt(work.snapshot).completion, .capturedStreamsCompleted) + } + + func testMoreThanEightActualStreamsAreAttemptedAndRetainedOnPartialFailure() throws { + try nativeLane( + faultCase: "testMoreThanEightActualStreamsAreAttemptedAndRetainedOnPartialFailure") + let work = NativeConstructionScope() + defer { preserveFault(work) } + var captured: [MLX.Stream] = [] + var attempted: [MLX.Stream] = [] + work.testingBeforeFence = { stream in + attempted.append(stream) + if stream == captured[4] { throw Failure.fence } + } + XCTAssertThrowsError( + try work.withPhase(.nativeSetup) { + for index in 0 ..< 9 { + try MLX.Stream.withNewDefaultStream(device: .gpu) { + let stream = StreamOrDevice.default.stream + captured.append(stream) + try work.capture(stream) + let output = MLXArray([Int32(index)]) + Int32(1) + try work.retain(output) + try work.willSubmit() + eval(output) + } + } + }) + XCTAssertEqual(captured.count, 9) + XCTAssertEqual(attempted.count, 9) + XCTAssertTrue(captured.allSatisfy { attempted.contains($0) }) + XCTAssertEqual(work.snapshot.capturedStreamCount, 9) + XCTAssertEqual(work.snapshot.retainedArrayCount, 9) + XCTAssertTrue(work.snapshot.isRetainedFault) + } + + func testExecutionResourceOwnersSurviveLateVetoAndRequireActiveScope() async throws { + try nativeLane(faultCase: "testExecutionResourceOwnersSurviveLateVetoAndRequireActiveScope") + let (root, _, session) = try fixture() + let prepared = try await prepare(root, session) + let loading = NativeConstructionScope() + defer { preserveFault(loading) } + let context = try MiMoV26ModelFactory.load( + session: session, reservation: Permit(session.request), + prepared: prepared, retaining: loading) + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + let binding = try model.makeCBv2Binding() + let adapter = binding.adapter + let work = NativeConstructionScope() + defer { preserveFault(work) } + XCTAssertThrowsError( + try adapter.makeNativeExecutionResources(bytesCapacity: 1 << 20, retaining: work) + ) { + XCTAssertEqual($0 as? NativeConstructionError, .inactiveScope) + } + weak var backend: MiMoV26CBv2Backend? + weak var bank: CBv2LayerCacheBank? + var created = false + work.testingBoundary = { name, scope in + if name == "adapter.nativeExecutionResources" { + backend = + scope.retainedOwnersForTesting.compactMap { $0 as? MiMoV26CBv2Backend }.first + bank = scope.retainedOwnersForTesting.compactMap { $0 as? CBv2LayerCacheBank }.first + created = true + throw Failure.boundary + } + } + work.testingBeforeFence = { _ in if created { throw Failure.fence } } + XCTAssertThrowsError( + try work.withPhase(.nativeSetup) { + // The same package-only authorization used by the managed factory; + // the owner here came from the actual strict filesystem/serial load. + try work.authorizeImmutableLoadedOwner(model.resources) + _ = try adapter.probeNativeKVTypes(retaining: work) + _ = try adapter.makeNativeExecutionResources( + bytesCapacity: 1 << 20, retaining: work) + }) + XCTAssertTrue(created) + XCTAssertTrue(work.snapshot.isRetainedFault) + XCTAssertNotNil(backend) + XCTAssertNotNil(bank) + XCTAssertTrue(work.retainedOwnersForTesting.contains { $0 === adapter }) + XCTAssertThrowsError( + try adapter.probeNativeKVTypes(retaining: NativeConstructionScope()), + "an outer setup fence must invalidate the already-completed nested probe") + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26FilesystemWeightsTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26FilesystemWeightsTests.swift new file mode 100644 index 0000000000..fef6174d12 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26FilesystemWeightsTests.swift @@ -0,0 +1,362 @@ +import Foundation +import MLX +import MLXLMCommon +import MLXVLM +import XCTest + +/// Header cases do not invoke MLX readers. Native-reader cases require root's +/// explicit opt-in and use only the complete193-tensor synthetic checkpoint. + +private func withMiMoConstructionScope( + _ body: (NativeConstructionScope) throws -> Value +) rethrows -> Value { + let work = NativeConstructionScope() + defer { + // Unexpected failed completion is restart-only, including in this + // dedicated native test process. Never deallocate its sole SDK owner. + if work.snapshot.isRetainedFault { _ = Unmanaged.passRetained(work) } + } + return try body(work) +} + +final class MiMoV26FilesystemWeightsTests: XCTestCase { + private let limits = MiMoV26FilesystemLimits( + maximumShardBytes: 1_048_576, maximumTotalFileBytes: 4_194_304) + + func testBoundedPreflightCloses193TensorsAndPreservesMetadata() throws { + let root = try fixture(copy: false) + let plan = try preflight(root, expectations: expectations(includeObjects: true)) + XCTAssertEqual(plan.bundlePlan.descriptors.count, 193) + XCTAssertEqual(plan.bundlePlan.tensorBytes, 370672) + XCTAssertEqual(plan.totalFileBytes, 390016) + XCTAssertEqual(plan.metadataBytesRead, 45684) + XCTAssertEqual(plan.shards.count, 4) + XCTAssertTrue( + plan.shards.allSatisfy { + Set($0.tensorKeysInFileOrder) == $0.tensorKeys + && $0.tensorKeysInFileOrder.count == $0.tensorKeys.count + }) + XCTAssertEqual(plan.shards.reduce(0) { $0 + $1.tensorBytes }, 370672) + XCTAssertEqual(plan.bundlePlan.configuration.attentionProjectionLayout, "fused_qkv") + XCTAssertEqual(plan.configurationURL.lastPathComponent, "config.json") + XCTAssertEqual(plan.indexURL.lastPathComponent, "model.safetensors.index.json") + XCTAssertEqual(plan.tokenizerURL.lastPathComponent, "tokenizer.json") + XCTAssertEqual(plan.tokenizerConfigurationURL.lastPathComponent, "tokenizer_config.json") + try MiMoV26FilesystemWeights.validateCurrentObjects(plan: plan) + XCTAssertTrue(plan.shards.allSatisfy { $0.suppliedPayloadSHA256?.count == 64 }) + } + + func testCPUHeaderRejectsWrongShapeDTypeOffsetsAndUnmappedKeys() throws { + for variant in [ + "shape", "dtype", "offset", "negativeOffset", "positiveGap", "missing", "extra", + ] { + let root = try fixture() + let file = root.appendingPathComponent("target.safetensors") + try mutateHeader(file) { header in + let key = + variant == "positiveGap" + ? "model.layers.0.self_attn.q_proj.weight" : "model.norm.weight" + let original = header[key] as! [String: Any] + switch variant { + case "missing": header.removeValue(forKey: key) + case "extra": header["unexpected.weight"] = original + default: + var entry = original + if variant == "shape" { entry["shape"] = [1] } + if variant == "dtype" { entry["dtype"] = "U32" } + if variant == "offset" { entry["data_offsets"] = [0, 256] } + if variant == "negativeOffset" { entry["data_offsets"] = [-1, 255] } + if variant == "positiveGap" { + let offsets = original["data_offsets"] as! [Int] + entry["data_offsets"] = [offsets[0] + 4, offsets[1] + 4] + } + header[key] = entry + } + } + XCTAssertThrowsError(try preflight(root), variant) { error in + if variant == "positiveGap" { + XCTAssertEqual( + error as? MiMoV26FilesystemError, + .invalidHeader("overlap/gap: target.safetensors")) + } + } + } + } + + func testCPUMissingExtraPathSymlinkAndTruncationFail() throws { + let missing = try fixture() + try FileManager.default.removeItem(at: missing.appendingPathComponent("vision.safetensors")) + XCTAssertThrowsError(try preflight(missing)) + let extra = try fixture() + try Data([0]).write(to: extra.appendingPathComponent("unindexed.bin")) + XCTAssertThrowsError(try preflight(extra)) + let unsafe = try fixture() + let indexURL = unsafe.appendingPathComponent("model.safetensors.index.json") + var index = try object(Data(contentsOf: indexURL)) + var map = index["weight_map"] as! [String: String] + map["model.norm.weight"] = "../outside.safetensors" + index["weight_map"] = map + try JSONSerialization.data(withJSONObject: index).write(to: indexURL) + XCTAssertThrowsError(try preflight(unsafe)) + let symlink = try fixture() + let file = symlink.appendingPathComponent("target.safetensors") + let outside = symlink.appendingPathComponent("retained.target") + try FileManager.default.moveItem(at: file, to: outside) + try FileManager.default.createSymbolicLink(at: file, withDestinationURL: outside) + XCTAssertThrowsError(try preflight(symlink)) + let truncated = try fixture() + let h = try FileHandle(forWritingTo: truncated.appendingPathComponent("target.safetensors")) + try h.truncate(atOffset: 16) + try h.close() + XCTAssertThrowsError(try preflight(truncated)) + } + + func testCPUHeaderLengthDuplicateJSONAndBudgetsFail() throws { + let badLength = try fixture() + let h = try FileHandle(forWritingTo: badLength.appendingPathComponent("target.safetensors")) + try h.write(contentsOf: Data(repeating: 255, count: 8)) + try h.close() + XCTAssertThrowsError(try preflight(badLength)) + let duplicate = try fixture() + let c = duplicate.appendingPathComponent("config.json") + let original = try Data(contentsOf: c) + var data = Data("{\"model_type\":\"mimo_v2\",".utf8) + data.append(original.dropFirst()) + try data.write(to: c) + XCTAssertThrowsError(try preflight(duplicate)) + let root = try fixture(copy: false) + XCTAssertThrowsError( + try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance(), + limits: .init(maximumShardBytes: 10, maximumTotalFileBytes: 4_194_304))) + XCTAssertThrowsError( + try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance(), + limits: .init(maximumShardBytes: 1_048_576, maximumTotalFileBytes: 10))) + XCTAssertThrowsError( + try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance(), + limits: .init( + maximumShardBytes: 1_048_576, maximumTotalFileBytes: 4_194_304, + maximumConfigurationBytes: 8))) + XCTAssertThrowsError( + try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance(), + limits: .init( + maximumShardBytes: 1_048_576, maximumTotalFileBytes: 4_194_304, + maximumHeaderBytes: 8))) + XCTAssertThrowsError( + try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance(), + limits: .init( + maximumShardBytes: 1_048_576, maximumTotalFileBytes: 4_194_304, + maximumMetadataBytes: 32))) + XCTAssertThrowsError( + try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance(), + limits: .init( + maximumShardBytes: 1_048_576, maximumTotalFileBytes: 4_194_304, maximumShards: 1 + ))) + } + + func testCPUEvidenceAndMutationChecks() throws { + let root = try fixture(copy: false) + XCTAssertThrowsError( + try preflight( + root, expectations: .init(configurationSHA256: String(repeating: "0", count: 64)))) + XCTAssertThrowsError( + try preflight(root, expectations: .init(files: ["missing.safetensors": .init()]))) + XCTAssertThrowsError( + try preflight( + root, + expectations: .init(files: [ + "target.safetensors": .init(headerSHA256: String(repeating: "0", count: 64)) + ]))) + // A supplied payload digest is intentionally descriptive; preflight + // must not pretend to compare it without reading the tensor payload. + let descriptive = try preflight( + root, + expectations: .init(files: [ + "target.safetensors": .init(payloadSHA256: String(repeating: "0", count: 64)) + ])) + XCTAssertEqual( + descriptive.shards.first { $0.name == "target.safetensors" }?.suppliedPayloadSHA256, + String(repeating: "0", count: 64)) + let changed = try fixture() + let plan = try preflight(changed) + try appendByte(changed.appendingPathComponent("target.safetensors")) + XCTAssertThrowsError(try MiMoV26FilesystemWeights.validateCurrentObjects(plan: plan)) + let laterExtra = try fixture() + let extraPlan = try preflight(laterExtra) + try Data([1]).write(to: laterExtra.appendingPathComponent("extra.safetensors")) + XCTAssertThrowsError(try MiMoV26FilesystemWeights.validateCurrentObjects(plan: extraPlan)) + // A retained external component is outside root-index traversal. + let external = try fixture() + try FileManager.default.createDirectory( + at: external.appendingPathComponent("dflash"), withIntermediateDirectories: false) + try Data([1]).write(to: external.appendingPathComponent("dflash/model.safetensors")) + XCTAssertNoThrow(try preflight(external)) + } + + func testCPUCancellationBetweenMetadataStages() throws { + let root = try fixture(copy: false) + XCTAssertThrowsError( + try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance(), limits: limits, isCancelled: { true }) + ) { + XCTAssertEqual($0 as? MiMoV26FilesystemError, .cancelled) + } + var cancel = false + var headers = 0 + XCTAssertThrowsError( + try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance(), limits: limits, + isCancelled: { cancel }, + progress: { p in + if p.phase == .headerRead { + headers += 1 + cancel = true + } + }) + ) { + XCTAssertEqual($0 as? MiMoV26FilesystemError, .cancelled) + } + XCTAssertEqual(headers, 1) + } + + func testNativeReaderReturnsCompleteLazyBundle() throws { + try nativeLane() + let root = try fixture(copy: false) + let plan = try preflight(root, expectations: expectations(includeObjects: true)) + var events: [MiMoV26FilesystemProgress] = [] + var result = try withMiMoConstructionScope { constructionWork in + try MiMoV26FilesystemWeights.load( + plan: plan, retaining: constructionWork, progress: { events.append($0) }) + } + XCTAssertEqual(events.filter { $0.phase == .shardHandlesCreated }.count, 4) + XCTAssertEqual(result.receipt.returnedHandleTensorBytes, 370672) + XCTAssertEqual(result.receipt.returnedHandleFileBytes, 390016) + XCTAssertTrue(result.receipt.payloadDisposition.contains("lazy")) + XCTAssertTrue(result.bundle.mtp.isLoaded) + // Explicit tiny-fixture materialization is a separate test action, + // not implicit evaluation by the loader itself. + XCTAssertEqual(result.materializationHandleCount, 193) + let handles = result.takeMaterializationHandles() + XCTAssertEqual(result.materializationHandleCount, 0) + XCTAssertEqual(handles.map(\.name), plan.shards.flatMap(\.tensorKeysInFileOrder)) + XCTAssertEqual(handles.reduce(0) { $0 + $1.byteCount }, 370672) + for handle in handles { eval(handle.array) } + XCTAssertEqual(result.takeMaterializationHandles().count, 0) + try MiMoV26FilesystemWeights.validateCurrentObjects(plan: plan) + let target = Dictionary(uniqueKeysWithValues: result.bundle.target.parameters().flattened()) + let expert = try XCTUnwrap(target["model.layers.1.mlp.switch_mlp.gate_proj.weight"]) + XCTAssertEqual(expert.dtype, .uint32) + XCTAssertEqual(expert.asArray(UInt32.self).first, 0x2222_2222) + let scales = try XCTUnwrap(target["model.layers.1.mlp.switch_mlp.gate_proj.scales"]) + XCTAssertEqual(scales.dtype, .uint8) + XCTAssertEqual(scales.asArray(UInt8.self).first, 127) + XCTAssertNoThrow(try JSONEncoder().encode(result.receipt)) + } + + func testNativeCancellationAndMutationDoNotPublishPartialBundle() throws { + try nativeLane() + let root = try fixture() + let plan = try preflight(root) + var cancel = false + var constructed = false + XCTAssertThrowsError( + try withMiMoConstructionScope { constructionWork in + try MiMoV26FilesystemWeights.load( + plan: plan, retaining: constructionWork, isCancelled: { cancel }, + progress: { p in + if p.phase == .shardHandlesCreated { cancel = true } + if p.phase == .bundleConstructed { constructed = true } + }) + } + ) { XCTAssertEqual($0 as? MiMoV26FilesystemError, .cancelled) } + XCTAssertFalse(constructed) + let changed = try fixture() + let changedPlan = try preflight(changed) + XCTAssertThrowsError( + try withMiMoConstructionScope { constructionWork in + try MiMoV26FilesystemWeights.load( + plan: changedPlan, retaining: constructionWork, + progress: { p in + if p.phase == .willCreateShardHandles, let name = p.currentFile { + try self.appendByte(changed.appendingPathComponent(name)) + } + }) + }) + } + + private func directory() throws -> URL { + guard let value = ProcessInfo.processInfo.environment["MIMO_V26_FILESYSTEM_FIXTURES"] else { + throw XCTSkip("Set MIMO_V26_FILESYSTEM_FIXTURES to owned synthetic fixture directory") + } + return URL(fileURLWithPath: value) + } + private func fixture(copy: Bool = true) throws -> URL { + let directory = try directory() + let original = directory.appendingPathComponent("tiny-bundle") + if !copy { return original } + let target = directory.appendingPathComponent("test-work-" + UUID().uuidString) + try FileManager.default.copyItem(at: original, to: target) + // Retain bounded unique test roots for failure inspection. + return target + } + private func provenance() throws -> MiMoV26ConvertedProvenance { + let p = try object(Data(contentsOf: directory().appendingPathComponent("provenance.json"))) + return try .init( + artifactID: XCTUnwrap(p["artifactID"] as? String), + sourceRepository: XCTUnwrap(p["sourceRepository"] as? String), + sourceRevision: XCTUnwrap(p["sourceRevision"] as? String), + conversionManifestSHA256: XCTUnwrap(p["conversionManifestSHA256"] as? String)) + } + private func expectations(includeObjects: Bool) throws -> MiMoV26FilesystemExpectations { + let data = try Data(contentsOf: directory().appendingPathComponent("expectations.json")) + let value = try JSONDecoder().decode(MiMoV26FilesystemExpectations.self, from: data) + if includeObjects { return value } + return .init( + configurationSHA256: value.configurationSHA256, indexSHA256: value.indexSHA256, + files: value.files.mapValues { + .init(headerSHA256: $0.headerSHA256, payloadSHA256: $0.payloadSHA256) + }) + } + private func preflight(_ root: URL, expectations: MiMoV26FilesystemExpectations = .init()) + throws -> MiMoV26FilesystemLoadPlan + { + try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance(), limits: limits, expectations: expectations) + } + private func object(_ data: Data) throws -> [String: Any] { + try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + private func appendByte(_ url: URL) throws { + let h = try FileHandle(forWritingTo: url) + defer { try? h.close() } + try h.seekToEnd() + try h.write(contentsOf: Data([0])) + } + private func mutateHeader(_ url: URL, _ mutation: (inout [String: Any]) throws -> Void) throws { + let data = try Data(contentsOf: url) + let rawLength = Array(data.prefix(8)).enumerated().reduce(UInt64(0)) { + $0 | (UInt64($1.element) << ($1.offset * 8)) + } + let length = Int(rawLength) + var header = try object(data.subdata(in: 8 ..< (8 + length))) + try mutation(&header) + var raw = try JSONSerialization.data(withJSONObject: header, options: [.sortedKeys]) + raw.append(Data(repeating: 32, count: (8 - raw.count % 8) % 8)) + let n = UInt64(raw.count) + var result = Data((0 ..< 8).map { UInt8((n >> ($0 * 8)) & 255) }) + result.append(raw) + result.append(data.dropFirst(8 + length)) + try result.write(to: url) + } + private func nativeLane() throws { + guard ProcessInfo.processInfo.environment["MIMO_V26_FILESYSTEM_NATIVE_TESTS"] == "1" else { + throw XCTSkip( + "Requires coordinator-owned native lane and MIMO_V26_FILESYSTEM_NATIVE_TESTS=1") + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26HistoricalCaptureIntegrationTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26HistoricalCaptureIntegrationTests.swift new file mode 100644 index 0000000000..f6d5cd8368 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26HistoricalCaptureIntegrationTests.swift @@ -0,0 +1,204 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon + +/// Genuine tiny MiMo target/three-head module and real Common capture buffers. +/// These component tests do NOT mint a native-engine contract or a load receipt. +/// Provider's separate strict-load interior-publication selector covers that seam. +final class MiMoV26HistoricalCaptureIntegrationTests: XCTestCase { + private enum Failure: Error { case injected } + private struct Fixture { + let target: MiMoV26TextModel + let assistant: MiMoV26MTPAssistant + let adapter: MiMoV26CBv2Adapter + let backend: MiMoV26CBv2Backend + let caches: [any CBv2AttendingLayerCache] + let rows: [CBv2SequenceKV?] + let driver: CBv2MTPRoundDriver + let state: MiMoV26MTPState + let codec: CBv2CompleteCheckpointCodec + let capture: CBv2ContiguousHistoricalCheckpoint + let tokens: [Int] + } + private func fixture() throws -> Fixture { + var object = + try JSONSerialization.jsonObject( + with: JSONEncoder().encode(MiMoV26MTPChecks.config())) as! [String: Any] + object["dtype"] = "bfloat16" + object["moe_router_dtype"] = "bfloat16" + // Actual native asymmetric layout accepted by Common, not a different + // row geometry attached to a tiny4/2 target. Hidden/vocab remain4/32. + for key in ["head_dim", "swa_head_dim"] { object[key] = 64 } + for key in ["v_head_dim", "swa_v_head_dim"] { object[key] = 32 } + let config = try JSONDecoder().decode( + MiMoV26Configuration.self, + from: JSONSerialization.data(withJSONObject: object)) + let target = try MiMoV26TextModel(config) + try target.update( + parameters: .unflattened( + MiMoV26MTPChecks.fixtureWeights(target).mapValues { $0.asType(.bfloat16) }), + verify: .all) + let predictor = try MiMoV26MTP(target: target) + try predictor.loadConvertedWeights( + MiMoV26MTPChecks.fixtureWeights(predictor, prefix: "mtp.").mapValues { + $0.asType(.bfloat16) + }) + let assistant = try MiMoV26MTPAssistant(target: target, predictor: predictor) + let adapter = try MiMoV26CBv2Adapter(target: target, assistant: assistant) + let construction = NativeConstructionScope() + defer { + if construction.snapshot.isRetainedFault { _ = Unmanaged.passRetained(construction) } + } + _ = try adapter.probeNativeKVTypes(retaining: construction) + let backend = try adapter.makeBackend(bytesCapacity: 16 << 20) + let rows = try backend.makeSequenceState( + layerKinds: adapter.layerKinds, promptLength: 17, maxLength: 64) + let caches = adapter.makeCaches() + try adapter.bindRows([rows], caches: caches) + let driver = try XCTUnwrap( + CBv2MTPRoundDriver.build( + model: adapter, drafter: assistant, + config: .init( + enabled: true, maxDraftTokens: 3, maxSpeculativeBatch: 1, + fixedDraftTokens: 3, verificationMode: .serialTarget))) + let tokens = (0 ..< 17).map { 1 + ($0 * 7) % 31 } + let state = try XCTUnwrap( + driver.takeOrMakeAssistantState( + for: .init(91), + maximumSequenceLength: 64, historicalPrefixPromptTokens: tokens) as? MiMoV26MTPState + ) + let prefix = MLXArray(tokens.prefix(8).map(Int32.init), [1, 8]) + let output = adapter.forwardWithHidden(tokens: prefix, caches: caches) + try withError { fault in + eval( + [output.logits, output.lastHidden] + + caches.flatMap { ($0 as? KVCache)?.innerState() ?? [] }) + try fault.check() + } + assistant.observeCommittedTarget( + .init(tokens: prefix, hidden: output.lastHidden), requestState: state) + let codec = CBv2CompleteCheckpointCodec( + identity: .init( + modelAggregateHash: "synthetic-tiny-mimo", promptContractID: "test-prompt", + buildID: "source-regression", numericsFingerprint: "native-bf16"), + layerKinds: adapter.layerKinds, recurrentSpec: nil, + kvDTypes: Array(repeating: .bfloat16, count: adapter.layerKinds.count), + assistant: assistant, + admission: .init( + layerKinds: adapter.layerKinds, bytesCapacity: 8 << 20, + config: .init(watermarkFraction: 0, elementBytes: 2))) + let capture = try CBv2ContiguousHistoricalCheckpoint( + codec: codec, position: 8, chunkSize: 8, state: rows) + return .init( + target: target, assistant: assistant, adapter: adapter, backend: backend, + caches: caches, rows: rows, driver: driver, state: state, + codec: codec, capture: capture, tokens: tokens) + } + private func finishAssistant(_ value: Fixture) throws { + try withError { fault in + eval(value.assistant.evaluationTargets(for: value.state)) + try fault.check() + } + try value.assistant.requestStateDidFinishEvaluation(value.state) + } + private func release(_ value: Fixture) { + value.assistant.releaseRequestState(value.state) + // Release the ACTUAL bound rows only after all test evaluation/drains. + XCTAssertNoThrow(try value.backend.releaseValidated(value.rows)) + // The local Fixture still has known passive cache/row aliases. This + // component assertion is never a physical-free/native-engine receipt. + withExtendedLifetime(value.target) {} + } + + func testFreshDriverContextReusedWithoutLateReinstallationAndActualCaptureSettles() throws { + let value = try fixture() + defer { release(value) } + try finishAssistant(value) + XCTAssertEqual(value.state.observedCount, 8) + XCTAssertNotNil( + value.state.prefixCaptureContext, "driver must install before the first observation") + value.driver.restoreAssistantState(value.state, for: .init(91)) + let again = try XCTUnwrap( + value.driver.takeOrMakeAssistantState( + for: .init(91), + maximumSequenceLength: 64, historicalPrefixPromptTokens: value.tokens) + as? MiMoV26MTPState) + XCTAssertTrue( + again === value.state, + "existing observed state must not be replaced or reconfigured as fresh") + try value.capture.captureSettledAssistant(requestState: again) + let targetWindowCopies = + value.adapter.layerKinds.filter { + if case .slidingWindow = $0.attention { return true } + return false + }.count * 2 + XCTAssertEqual(value.capture.evaluationRoots.count, targetWindowCopies + 9) + try value.capture.finishEvaluation() + XCTAssertNotNil(value.capture.compactAllocationEvidence) + XCTAssertFalse(value.capture.completionFailed) + value.capture.close() + XCTAssertEqual(value.codec.admission.bytesReserved, 0) + } + + func testDiscardSubmittedTargetCopiesBeforeAssistantAttachmentReallyDrains() throws { + let value = try fixture() + defer { release(value) } + value.capture.markSubmitted() + try withError { fault in + asyncEval(value.capture.evaluationRoots) + try fault.check() + } + XCTAssertTrue(value.capture.requiresAssistant) + XCTAssertThrowsError( + try value.capture.finishEvaluation(), "publication requires the missing assistant") + XCTAssertGreaterThan(value.codec.admission.bytesReserved, 0) + var drains = 0 + value.capture.beforeRequiredDrainForTesting = { drains += 1 } // observes the REAL following drain + try value.capture.finishEvaluationForRetirement() + XCTAssertEqual(drains, 1) + XCTAssertNil(value.capture.compactAllocationEvidence, "discard is not publication") + value.capture.close() + XCTAssertEqual(value.codec.admission.bytesReserved, 0) + XCTAssertFalse(value.capture.completionFailed) + // Assistant observation is still owned independently; complete it + // truthfully before releasing its real cache/state. + try finishAssistant(value) + } + + func testRequiredCopyFenceFailureKeepsRealAssistantRootsAndPromiseAfterLaterDrain() throws { + guard + ProcessInfo.processInfo.environment["MIMO_PREFIX_CAPTURE_FAULT"] + == "required_copy_fence" + else { + throw XCTSkip( + "Run alone in a fresh native process; real roots intentionally remain quarantined") + } + let value = try fixture() + defer { release(value) } + try finishAssistant(value) + try value.capture.captureSettledAssistant(requestState: value.state) + weak var actualAssistantRoot = value.capture.evaluationRoots.last + let charge = value.codec.admission.bytesReserved + XCTAssertGreaterThan(charge, 0) + XCTAssertNotNil(actualAssistantRoot) + value.capture.beforeRequiredDrainForTesting = { throw Failure.injected } + XCTAssertThrowsError(try value.capture.finishEvaluation()) + XCTAssertTrue(value.capture.completionFailed) + value.capture.beforeRequiredDrainForTesting = nil + try withError { fault in + StreamOrDevice.default.stream.synchronize() + try fault.check() + } + XCTAssertThrowsError( + try value.capture.finishEvaluation(), "later general drain cannot erase first failure") + value.capture.close() + XCTAssertNotNil( + actualAssistantRoot, "retain actual nine-tensor assistant copy owner, not just C") + XCTAssertEqual(value.codec.admission.bytesReserved, charge) + XCTAssertNil(value.capture.compactAllocationEvidence) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26LoadFootprintTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26LoadFootprintTests.swift new file mode 100644 index 0000000000..e91906580f --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26LoadFootprintTests.swift @@ -0,0 +1,140 @@ +import Foundation +import XCTest + +@testable import MLXVLM + +/// Actual estimate implementation over authenticated metadata only. These +/// assertions allocate no model arrays and do not measure a full-model peak. +final class MiMoV26LoadFootprintTests: XCTestCase { + private struct Inventory: Decodable { + struct File: Decodable { + let name: String + let bytes: Int + } + let files: [File] + } + + func testSelectedBundlePricesEveryComponentAndCopyFamily() throws { + let (plan, files) = try inputs() + let estimate = try MiMoV26LoadFootprint.estimateValidatedLayout( + plan, files: files, allocationPageBytes: 16_384) + // Independently calculated from the frozen1258-tensor header inventory. + XCTAssertEqual(estimate.residentBytes, 175_362_473_140) + XCTAssertEqual(estimate.largestShardBytes, 4_230_398_519) + XCTAssertEqual(estimate.largestTensorBytes, 1_249_902_592) + XCTAssertEqual(estimate.largestExpertBlockBytes, 3_422_552_064) + XCTAssertEqual(estimate.auxiliaryCopyBytes, 2_535_180_672) + XCTAssertEqual(estimate.pageRoundingBytes, 41_222_144) + XCTAssertEqual(estimate.metadataAllowanceBytes, 1_073_741_824) + XCTAssertEqual(estimate.transientBytes, 12_552_997_815) + XCTAssertEqual(estimate.totalBytes, 187_915_470_955) + XCTAssertEqual(estimate.tensorCount, 1258) + XCTAssertEqual(estimate.configSHA256, plan.configSHA256) + XCTAssertEqual(estimate.indexSHA256, plan.indexSHA256) + XCTAssertEqual(estimate.descriptorSHA256, plan.descriptorSHA256) + XCTAssertEqual(estimate.contract, MiMoV26LoadFootprint.contract) + } + + func testFileOrderCannotChangeEstimateOrDropInventory() throws { + let (plan, files) = try inputs() + let original = try MiMoV26LoadFootprint.estimateValidatedLayout( + plan, files: files, allocationPageBytes: 16_384) + XCTAssertEqual( + original, + try MiMoV26LoadFootprint.estimateValidatedLayout( + plan, files: Array(files.reversed()), allocationPageBytes: 16_384)) + XCTAssertThrowsError( + try MiMoV26LoadFootprint.estimateValidatedLayout( + plan, files: Array(files.dropLast()), allocationPageBytes: 16_384)) + var duplicate = files + duplicate[1] = duplicate[0] + XCTAssertThrowsError( + try MiMoV26LoadFootprint.estimateValidatedLayout( + plan, files: duplicate, allocationPageBytes: 16_384)) + XCTAssertThrowsError( + try MiMoV26LoadFootprint.estimateValidatedLayout( + plan, files: files + [("unaccounted.safetensors", 1024)], + allocationPageBytes: 16_384)) + } + + func testTruncatedOrOversizedFileMetadataCannotObtainAllowance() throws { + let (plan, files) = try inputs() + for size in [-1, 0, 8, 1024] { + var changed = files + changed[0].bytes = size + XCTAssertThrowsError( + try MiMoV26LoadFootprint.estimateValidatedLayout( + plan, files: changed, allocationPageBytes: 16_384)) + } + var excessive = files + excessive[0].bytes += 32 * 1_048_576 + XCTAssertThrowsError( + try MiMoV26LoadFootprint.estimateValidatedLayout( + plan, files: excessive, allocationPageBytes: 16_384)) + let overflowing = files.map { (name: $0.name, bytes: Int.max) } + XCTAssertThrowsError( + try MiMoV26LoadFootprint.estimateValidatedLayout( + plan, files: overflowing, allocationPageBytes: 16_384) + ) { + XCTAssertEqual($0 as? MiMoV26LoadFootprintError, .overflow) + } + } + + func testOtherPageSizeAndUnqualifiedPrecisionRemainIneligible() throws { + let (plan, files) = try inputs() + for page in [0, 4096, 8192, 32768] { + XCTAssertThrowsError( + try MiMoV26LoadFootprint.estimateValidatedLayout( + plan, files: files, allocationPageBytes: page) + ) { + XCTAssertEqual($0 as? MiMoV26LoadFootprintError, .unsupportedProfile) + } + } + let tiny = try convertedPlan("tiny") // Existing validFP32 component fixture. + let tinyFiles = tiny.rootFiles.sorted().map { (name: $0, bytes: 1_048_576) } + XCTAssertThrowsError( + try MiMoV26LoadFootprint.estimateValidatedLayout( + tiny, files: tinyFiles, allocationPageBytes: 16_384) + ) { + XCTAssertEqual($0 as? MiMoV26LoadFootprintError, .unsupportedProfile) + } + } + + private func inputs() throws -> (MiMoV26ConvertedLoadPlan, [(name: String, bytes: Int)]) { + guard let file = ProcessInfo.processInfo.environment["MIMO_V26_FOOTPRINT_FILE_INVENTORY"] + else { + throw XCTSkip("Set MIMO_V26_FOOTPRINT_FILE_INVENTORY to frozen header file inventory") + } + let inventory = try JSONDecoder().decode( + Inventory.self, from: Data(contentsOf: URL(fileURLWithPath: file))) + return ( + try convertedPlan("actual"), inventory.files.map { (name: $0.name, bytes: $0.bytes) } + ) + } + private func convertedPlan(_ prefix: String) throws -> MiMoV26ConvertedLoadPlan { + guard let root = ProcessInfo.processInfo.environment["MIMO_V26_CONVERTED_LOAD_FIXTURES"] + else { + throw XCTSkip( + "Set MIMO_V26_CONVERTED_LOAD_FIXTURES to owned metadata fixture directory") + } + let directory = URL(fileURLWithPath: root) + func data(_ name: String) throws -> Data { + try Data(contentsOf: directory.appendingPathComponent(name)) + } + let provenanceObject = + try JSONSerialization.jsonObject(with: data("provenance.json")) as? [String: Any] + let provenance = try XCTUnwrap(provenanceObject) + return try MiMoV26ConvertedLoadPlan.make( + configurationData: data(prefix + "-config.json"), + indexData: data(prefix + "-index.json"), + descriptors: JSONDecoder().decode( + [String: MiMoV26ConvertedTensorDescriptor].self, + from: data(prefix + "-descriptors.json")), + provenance: .init( + artifactID: XCTUnwrap(provenance["artifactID"] as? String), + sourceRepository: XCTUnwrap(provenance["sourceRepository"] as? String), + sourceRevision: XCTUnwrap(provenance["sourceRevision"] as? String), + conversionManifestSHA256: XCTUnwrap( + provenance["conversionManifestSHA256"] as? String))) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26MLXVLMWeightsTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26MLXVLMWeightsTests.swift new file mode 100644 index 0000000000..f010ab37ab --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26MLXVLMWeightsTests.swift @@ -0,0 +1,329 @@ +import Foundation +import MLX +import MLXLMCommon +import MLXNN +import XCTest + +@testable import MLXLLM +@testable import MLXVLM + +final class MiMoV26MLXVLMWeightsTests: XCTestCase { + func testSelectedPublishedMetadataInventory() throws { + guard let location = ProcessInfo.processInfo.environment["MIMO_V26_MLXVLM_METADATA"] else { + throw XCTSkip( + "Set the approved metadata/header receipt directory; no payload or credential access" + ) + } + let root = URL(fileURLWithPath: location) + let data = try Data(contentsOf: root.appendingPathComponent("all-root-headers.json")) + let receipt = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + let headers = try XCTUnwrap(receipt["headers"] as? [[String: Any]]) + var descriptors: [String: MiMoV26ConvertedTensorDescriptor] = [:] + for header in headers { + let file = try XCTUnwrap(header["file"] as? String) + for (key, raw) in try XCTUnwrap(header["tensors"] as? [String: Any]) + where key != "__metadata__" { + let tensor = try XCTUnwrap(raw as? [String: Any]) + let shape = try XCTUnwrap(tensor["shape"] as? [Int]) + let dtype = try XCTUnwrap( + MiMoV26ConvertedScalarType(rawValue: XCTUnwrap(tensor["dtype"] as? String))) + XCTAssertNil( + descriptors.updateValue( + .init(shape: shape, dtype: dtype, file: file), forKey: key)) + } + } + let provenanceData = try Data( + contentsOf: root.appendingPathComponent("metadata/artifact-provenance.json")) + let provenance = try XCTUnwrap( + JSONSerialization.jsonObject(with: provenanceData) as? [String: Any]) + let plan = try MiMoV26ConvertedLoadPlan.make( + configurationData: Data( + contentsOf: root.appendingPathComponent("metadata/config.json")), + indexData: Data( + contentsOf: root.appendingPathComponent("metadata/model.safetensors.index.json")), + descriptors: descriptors, + provenance: .init( + artifactID: "selected-published-header-check", + sourceRepository: XCTUnwrap(provenance["original_model"] as? String), + sourceRevision: XCTUnwrap(provenance["original_revision"] as? String), + conversionManifestSHA256: convertedHash(provenanceData), layout: .mlxVLM)) + XCTAssertEqual(plan.descriptors.count, 1732) + XCTAssertEqual(plan.rootFiles.count, 37) + XCTAssertEqual(plan.tensorBytes, 170_974_427_392) + XCTAssertEqual(plan.components[.target]?.count, 1103) + XCTAssertEqual(plan.components[.vision]?.count, 364) + XCTAssertEqual(plan.components[.audioPatch]?.count, 223) + XCTAssertEqual(plan.components[.mtp]?.count, 42) + XCTAssertGreaterThan(plan.tensorBytes(for: .mtp), 0) + XCTAssertEqual( + MiMoV26ConvertedComponent.allCases.reduce(0) { $0 + plan.tensorBytes(for: $1) }, + plan.tensorBytes) + XCTAssertEqual(plan.targetExpertModulePaths.count, 141) + XCTAssertEqual( + plan.targetQuantizationPolicies.count + plan.audioQuantizationPolicies.count, 402) + XCTAssertTrue(plan.floatingMTP) + XCTAssertEqual(plan.configuration.eosTokenIDs, Set([151643, 151645, 151672])) + XCTAssertNil(plan.provenance.payloadVerificationReceiptSHA256) + } + + private struct Fixture { + var config: Data + var index: Data + var descriptors: [String: MiMoV26ConvertedTensorDescriptor] + let tensors: [String: MLXArray] + let provenance = MiMoV26ConvertedProvenance( + artifactID: "synthetic-mlx-vlm-fixture", + sourceRepository: "XiaomiMiMo/MiMo-V2.6-Flash-MOPD", + sourceRevision: String(repeating: "1", count: 40), + conversionManifestSHA256: String(repeating: "2", count: 64), layout: .mlxVLM) + func plan() throws -> MiMoV26ConvertedLoadPlan { + try .make( + configurationData: config, indexData: index, descriptors: descriptors, + provenance: provenance) + } + } + + private func fixtureValues(key: String, count: Int) -> [Float] { + // Full-key FNV seed + xorshift stream: repeated shapes do not produce + // identical gate/up/layer/head bytes and hide an incorrect name mapping. + var state = key.utf8.reduce(UInt64(14_695_981_039_346_656_037)) { + ($0 ^ UInt64($1)) &* 1_099_511_628_211 + } + if state == 0 { state = 1 } + return (0 ..< count).map { _ in + state ^= state << 13 + state ^= state >> 7 + state ^= state << 17 + return Float(Int(state & 0xffff) - 32768) / 262144 + } + } + + private func fixture() throws -> Fixture { + let env = ProcessInfo.processInfo.environment + guard env["MIMO_V26_MLXVLM_NATIVE_TESTS"] == "1", + let root = env["MIMO_V26_SERIAL_LOAD_FIXTURES"] + else { + throw XCTSkip("Requires exclusive native lane and the existing synthetic fixture root") + } + let original = try Data( + contentsOf: URL(fileURLWithPath: root).appendingPathComponent("tiny-bf16/config.json")) + var raw = try XCTUnwrap(JSONSerialization.jsonObject(with: original) as? [String: Any]) + raw.removeValue(forKey: "quantization") + raw.removeValue(forKey: "quantization_config") + raw.removeValue(forKey: "omlx_mimo_mtp") + var audio = try XCTUnwrap(raw["audio_config"] as? [String: Any]) + audio["input_local_dim"] = 64 + audio["input_local_head_dim"] = 32 + audio["input_local_intermediate_size"] = 128 + raw["audio_config"] = audio + let config = try JSONDecoder().decode( + MiMoV26Configuration.self, from: JSONSerialization.data(withJSONObject: raw)) + // Build the independent float modules, then quantize SMALL deterministic + // arrays with MLX's stock quantizer. Never convert the published weights. + let target = try MiMoV26TextModel(config) + let patch = try MiMoV26AudioPatchEncoder(configuration: XCTUnwrap(config.audio)) + let mtp = try MiMoV26MTP(target: target) + var q: [String: Any] = ["bits": 4, "group_size": 64, "mode": "affine"] + var tensors: [String: MLXArray] = [:] + var descriptors: [String: MiMoV26ConvertedTensorDescriptor] = [:] + var index: [String: String] = [:] + var bytes = 0 + func record(_ name: String, _ array: MLXArray, _ component: String) { + let file = component + ".safetensors" + let dtype: MiMoV26ConvertedScalarType = + array.dtype == .uint32 + ? .uint32 + : (array.dtype == .uint8 + ? .uint8 : (array.dtype == .float32 ? .float32 : .bfloat16)) + tensors[name] = array + descriptors[name] = .init(shape: array.shape, dtype: dtype, file: file) + index[name] = file + bytes += array.size * dtype.bytes + } + for (component, module) in [("target", target as Module), ("audio", patch), ("mtp", mtp)] { + let leaves = Dictionary(uniqueKeysWithValues: module.leafModules().flattened()) + for (path, param) in module.parameters().flattened() { + let name: String + switch component { + case "target": name = "language_model." + path + case "mtp": name = "language_model.model.mtp." + path + default: name = path + } + let float = MLXArray(fixtureValues(key: name, count: param.size)).reshaped( + param.shape + ) + .asType( + path.hasSuffix("e_score_correction_bias") || path.hasSuffix("mlp.gate.weight") + ? .float32 : .bfloat16) + let modulePath = String(path.dropLast(".weight".count)) + let leaf = path.hasSuffix(".weight") ? leaves[modulePath] : nil + let packed = + ["target", "audio"].contains(component) + && (leaf is Linear || leaf is Embedding || leaf is SwitchLinear) + if packed { + let expert = leaf is SwitchLinear + let group = expert ? 32 : 64 + let bits = expert ? 4 : 8 + let prefix = String(name.dropLast(".weight".count)) + q[prefix] = [ + "mode": expert ? "mxfp4" : "affine", "bits": bits, "group_size": group, + ] + let (weight, scales, biases) = MLX.quantized( + float, groupSize: group, bits: bits, mode: expert ? .mxfp4 : .affine) + record(name, weight, component) + record(prefix + ".scales", scales, component) + if let biases { record(prefix + ".biases", biases, component) } + } else { + record(name, float, component) + } + } + } + for (key, shape) in try MiMoV26VisionTower.expectedTensorShapes( + configuration: XCTUnwrap(config.vision)) + { + let stored = + key == "visual.patch_embed.proj.weight" + ? [shape[0], shape.dropFirst().reduce(1, *)] : shape + let name = "vision_tower." + key.dropFirst("visual.".count) + let array = MLXArray(fixtureValues(key: name, count: shape.reduce(1, *))).reshaped( + stored + ).asType(.bfloat16) + record(name, array, "vision") + } + eval(Array(tensors.values)) + for (a, b) in [ + ( + "language_model.model.layers.0.mlp.gate_proj.weight", + "language_model.model.layers.0.mlp.up_proj.weight" + ), + ( + "language_model.model.layers.1.mlp.switch_mlp.gate_proj.weight", + "language_model.model.layers.1.mlp.switch_mlp.up_proj.weight" + ), + ( + "language_model.model.mtp.layers.0.mlp.gate_proj.weight", + "language_model.model.mtp.layers.0.mlp.up_proj.weight" + ), + ( + "language_model.model.mtp.layers.1.enorm.weight", + "language_model.model.mtp.layers.2.enorm.weight" + ), + ( + "audio_encoder.input_local_transformer.layers.0.self_attn.q_proj.weight", + "audio_encoder.input_local_transformer.layers.0.self_attn.k_proj.weight" + ), + ("vision_tower.blocks.0.norm1.weight", "vision_tower.blocks.0.norm2.weight"), + ] { + let first = try XCTUnwrap(tensors[a]) + let second = try XCTUnwrap(tensors[b]) + XCTAssertEqual(first.shape, second.shape) + XCTAssertNotEqual( + first.asData(access: .copy).data, second.asData(access: .copy).data, a + " / " + b) + } + raw["quantization"] = q + raw["quantization_config"] = q + return .init( + config: try JSONSerialization.data(withJSONObject: raw, options: [.sortedKeys]), + index: try JSONSerialization.data( + withJSONObject: ["metadata": ["total_size": bytes], "weight_map": index], + options: [.sortedKeys]), + descriptors: descriptors, tensors: tensors) + } + + func testPackedTargetAudioAndFloatingHeadsLoadAndExecute() throws { + let f = try fixture() + let plan = try f.plan() + XCTAssertEqual(plan.components[.mtp]?.count, 42) + XCTAssertEqual(plan.externalRequiredComponents, ["audio_tokenizer"]) + XCTAssertEqual(Set(plan.parameterNames.values).count, plan.descriptors.count) + // Freeze independent copies BEFORE loading: a mutation of a borrowed + // source handle must not change both sides of the equality oracle. + let sourceBytes = f.tensors.mapValues { $0.asData(access: .copy).data } + let loaded = try MiMoV26ConvertedWeights.load(plan: plan, tensors: f.tensors) + XCTAssertTrue(loaded.target.hasLoadedEmbeddingPrecision) + XCTAssertTrue(loaded.target.hasLoadedReadoutPrecision) + XCTAssertTrue(loaded.mtp.isLoaded) + XCTAssertEqual(loaded.mtp.headCount, 3) + XCTAssertFalse(loaded.mtp.leafModules().flattened().contains { $0.1 is Quantized }) + let output = try loaded.target.forward(inputIDs: MLXArray([Int32(1), 2, 3]).reshaped(1, 3)) + let audio = try loaded.audioPatch.forward( + clips: [.init(codes: [Int32](repeating: 1, count: 20), frameCount: 1)], + limits: .init( + maximumClips: 1, maximumFrames: 1, maximumPatches: 1, + maximumWorkingElements: 100_000)) + let image = try loaded.vision.forward( + patches: MLXArray.zeros([4, 24]), + grids: [.init(temporal: 1, height: 2, width: 2)], + limits: .init(maximumPatches: 4, maximumAttentionScoreElements: 1000)) + eval(output.logits, audio.features, image) + XCTAssertEqual(output.logits.shape, [1, 3, 128]) + XCTAssertEqual(audio.features.shape, [1, 64]) + XCTAssertTrue(output.logits.asArray(Float.self).allSatisfy(\.isFinite)) + XCTAssertTrue(audio.features.asArray(Float.self).allSatisfy(\.isFinite)) + XCTAssertEqual(image.shape, [1, 64]) + XCTAssertTrue(image.asArray(Float.self).allSatisfy(\.isFinite)) + _ = try MiMoV26CBv2Adapter(target: loaded.target) + let features = try MiMoV26MTPFeatures(targetOutput: output, target: loaded.target) + let cache = try loaded.mtp.newCache() + for depth in 0 ..< 3 { + let result = try loaded.mtp.forward( + depth: depth, features: features, + inputIDs: MLXArray([Int32(2), 3, 4]).reshaped(1, 3), target: loaded.target, + cache: cache) + eval(result.logits) + XCTAssertEqual(result.logits.shape, [1, 3, 128]) + XCTAssertTrue(result.logits.asArray(Float.self).allSatisfy(\.isFinite)) + } + for (component, module) in [ + (MiMoV26ConvertedComponent.target, loaded.target as Module), + (.vision, loaded.vision), (.audioPatch, loaded.audioPatch), (.mtp, loaded.mtp), + ] { + let parameters = Dictionary(uniqueKeysWithValues: module.parameters().flattened()) + for source in plan.components[component]! { + let canonical = plan.parameterNames[source]! + let path = + component == .vision + ? String(canonical.dropFirst("visual.".count)) + : (component == .mtp ? String(canonical.dropFirst("mtp.".count)) : canonical) + let actual = try XCTUnwrap(parameters[path]) + let expected = f.tensors[source]! + XCTAssertEqual(actual.shape, expected.shape, source) + XCTAssertEqual(actual.dtype, expected.dtype, source) + XCTAssertEqual(actual.asData(access: .copy).data, sourceBytes[source], source) + } + } + } + + func testMissingHeadWrongStorageAndConflictingPolicyRefuse() throws { + let f = try fixture() + for change in [ + "missingHead", "wrongDtype", "duplicateNamespace", "implicitDense", "quantizedHead", + ] { + var bad = f + let key = "language_model.model.mtp.layers.2.eh_proj.weight" + if change == "missingHead" { + bad.descriptors.removeValue(forKey: key) + } else if change == "wrongDtype" { + let d = try XCTUnwrap(bad.descriptors[key]) + bad.descriptors[key] = .init(shape: d.shape, dtype: .float16, file: d.file) + } else if change == "duplicateNamespace" { + bad.descriptors["mtp.layers.2.eh_proj.weight"] = bad.descriptors[key] + } else { + var raw = try XCTUnwrap( + JSONSerialization.jsonObject(with: bad.config) as? [String: Any]) + var q = try XCTUnwrap(raw["quantization"] as? [String: Any]) + if change == "implicitDense" { + q.removeValue(forKey: "language_model.model.embed_tokens") + } else { + q["language_model.model.mtp.layers.2.eh_proj"] = [ + "mode": "affine", "bits": 8, "group_size": 64, + ] + } + raw["quantization"] = q + raw["quantization_config"] = q + bad.config = try JSONSerialization.data(withJSONObject: raw) + } + XCTAssertThrowsError(try bad.plan(), change) + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26MTPEngineTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26MTPEngineTests.swift new file mode 100644 index 0000000000..e03090c62e --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26MTPEngineTests.swift @@ -0,0 +1,817 @@ +import Foundation +import MLX +import MLXNN +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon + +/// A one-shot visit gate, not a semaphore permit left borrowed at destruction. + +private func withMiMoConstructionScope( + _ body: (NativeConstructionScope) throws -> Value +) rethrows -> Value { + let work = NativeConstructionScope() + defer { + // Unexpected failed completion is restart-only, including in this + // dedicated native test process. Never deallocate its sole SDK owner. + if work.snapshot.isRetainedFault { _ = Unmanaged.passRetained(work) } + } + return try body(work) +} + +private final class MiMoV26SecondFenceVisit: @unchecked Sendable { + private let lock = NSLock() + private var visits = 0 + func shouldBlock() -> Bool { + lock.withLock { + guard visits < 2 else { return false } + visits += 1 + return visits == 2 + } + } +} + +private final class MiMoV26MTPReadoutSpy: Linear { + var shapes: [[Int]] = [] + override func callAsFunction(_ x: MLXArray) -> MLXArray { + shapes.append(x.shape) + return super.callAsFunction(x) + } +} + +/// Test-only proposal override. Every native head still executes and advances +/// its own request state. A target continuation controls exactly where the +/// generic verifier accepts/rejects, independently of random tiny-head quality. +private final class MiMoV26ScriptedAssistant: CBv2MTPRequestStatefulDrafter { + let native: MiMoV26MTPAssistant + let script: [Int]? + let promptLength: Int + let rejectPosition: Int + var states: [MiMoV26MTPState] = [] + var observations = 0 + var observationFenceReads = 0 + var fenceHook: ((MiMoV26MTPState) throws -> Void)? + init( + _ native: MiMoV26MTPAssistant, script: [Int]? = nil, + promptLength: Int = 0, rejectPosition: Int = 3 + ) { + self.native = native + self.script = script + self.promptLength = promptLength + self.rejectPosition = rejectPosition + } + var mtpTargetIdentity: ObjectIdentifier? { native.mtpTargetIdentity } + var requiredVerificationMode: CBv2MTPVerificationMode? { .serialTarget } + var maximumDraftTokens: Int? { 3 } + var maximumSpeculativeBatch: Int? { 1 } + var requiresCommittedObservationFence: Bool { true } + var requestStateBytesPerToken: Int { native.requestStateBytesPerToken } + var requestStateTokenGranularity: Int { native.requestStateTokenGranularity } + var requestStateTokenAllocationPadding: Int { native.requestStateTokenAllocationPadding } + func makeRequestState() -> any CBv2MTPRequestState { + let state = native.makeRequestState() as! MiMoV26MTPState + states.append(state) + return state + } + func configureRequestState(_ state: any CBv2MTPRequestState, maximumSequenceLength: Int) throws + { + try native.configureRequestState(state, maximumSequenceLength: maximumSequenceLength) + } + func observeCommittedTarget( + _ observation: CBv2MTPCommittedTargetObservation, + requestState: any CBv2MTPRequestState + ) { + observations += 1 + native.observeCommittedTarget(observation, requestState: requestState) + } + func prepare(rows: [CBv2MTPRowCapture]) -> CBv2MTPPreparedCapture { native.prepare(rows: rows) } + func draftStep(tokens: MLXArray, hidden: MLXArray, prepared: CBv2MTPPreparedCapture) + -> (tokens: MLXArray, hidden: MLXArray) + { + native.draftStep(tokens: tokens, hidden: hidden, prepared: prepared) + } + func draftStep( + tokens: MLXArray, hidden: MLXArray, shortlist: MLXArray?, + requestState: any CBv2MTPRequestState + ) -> (tokens: MLXArray, hidden: MLXArray) { + let result = native.draftStep( + tokens: tokens, hidden: hidden, shortlist: shortlist, + requestState: requestState) + guard let script else { return result } + let state = requestState as! MiMoV26MTPState + let depth = state.stagedInputCount - 1 + let index = state.observedCount - promptLength + depth + 1 + precondition(script.indices.contains(index)) + let token = (script[index] + (depth == rejectPosition ? 1 : 0)) % 32 + return (MLXArray([Int32(token)]), result.hidden) + } + func evaluationTargets(for state: any CBv2MTPRequestState) -> [MLXArray] { + if state.stagedInputCount == 0 { observationFenceReads += 1 } + return native.evaluationTargets(for: state) + } + func requestStateDidFinishEvaluation(_ state: any CBv2MTPRequestState) throws { + if let state = state as? MiMoV26MTPState { try fenceHook?(state) } + try native.requestStateDidFinishEvaluation(state) + } + func finalizeRound( + requestState: any CBv2MTPRequestState, confirmedInputTokens: Int, + committedDraftTokens: MLXArray, committedTargetHidden: MLXArray + ) { + native.finalizeRound( + requestState: requestState, confirmedInputTokens: confirmedInputTokens, + committedDraftTokens: committedDraftTokens, committedTargetHidden: committedTargetHidden + ) + } + func discardRound(requestState: any CBv2MTPRequestState) { + native.discardRound(requestState: requestState) + } + func releaseRequestState(_ state: any CBv2MTPRequestState) { native.releaseRequestState(state) } +} + +final class MiMoV26MTPEngineTests: XCTestCase { + private func ids(_ values: [Int]) -> MLXArray { + MLXArray(values.map(Int32.init), [1, values.count]) + } + private func prompt(_ length: Int) -> [Int] { (0 ..< length).map { 1 + ($0 * 7) % 31 } } + private func state(_ assistant: MiMoV26MTPAssistant) throws -> MiMoV26MTPState { + let state = assistant.makeRequestState() as! MiMoV26MTPState + try assistant.configureRequestState(state, maximumSequenceLength: 64) + return state + } + private func observe( + _ assistant: MiMoV26MTPAssistant, _ state: MiMoV26MTPState, + _ tokens: MLXArray, _ hidden: MLXArray + ) { + assistant.observeCommittedTarget(.init(tokens: tokens, hidden: hidden), requestState: state) + eval(assistant.evaluationTargets(for: state)) + XCTAssertNoThrow(try assistant.requestStateDidFinishEvaluation(state)) + } + private func propose( + _ assistant: MiMoV26MTPAssistant, _ state: MiMoV26MTPState, + seed: Int, hidden: MLXArray, depth: Int = 3 + ) -> [Int] { + var token = ids([seed]) + var feature = hidden + var result: [Int] = [] + for _ in 0 ..< depth { + let output = assistant.draftStep( + tokens: token, hidden: feature, shortlist: nil, requestState: state) + eval([output.tokens, output.hidden] + assistant.evaluationTargets(for: state)) + XCTAssertNoThrow(try assistant.requestStateDidFinishEvaluation(state)) + result.append(Int(output.tokens.item(Int32.self))) + token = output.tokens.reshaped([1, 1]) + feature = output.hidden + } + return result + } + + func testChunkedPrimingAndEveryDepthMatchScalarNonChainingReference() throws { + let (target, mtp) = try MiMoV26MTPChecks.fixture() + let assistant = try MiMoV26MTPAssistant(target: target, predictor: mtp) + for length in [1, 2, 3, 11, 31] { + let tokens = prompt(length) + let output = try target.forward(inputIDs: ids(tokens)) + let allHidden = output.normalizedHiddenStates.asArray(Float.self) + let scalarHidden = (0 ..< length).map { Array(allHidden[$0 * 4 ..< ($0 + 1) * 4]) } + for chunk in [1, 2, 7, 64] { + let state = try state(assistant) + for start in stride(from: 0, to: length, by: chunk) { + let end = min(length, start + chunk) + observe( + assistant, state, ids(Array(tokens[start ..< end])), + output.normalizedHiddenStates[0..., start ..< end, 0...]) + XCTAssertLessThanOrEqual(state.retainedFeatureRows, 3) + for shapes in state.retainedHistoryShapes { + for shape in shapes { XCTAssertLessThanOrEqual(shape[2], 3) } + } + } + XCTAssertEqual(state.headInputCounts, (0 ..< 3).map { max(0, length - $0 - 1) }) + var chain = tokens + [7] + var hidden = output.normalizedHiddenStates[0..., (-1)..., 0...] + for depth in 0 ..< 3 { + let proposal = assistant.draftStep( + tokens: ids([chain.last!]), hidden: hidden, + shortlist: nil, requestState: state) + eval( + [proposal.tokens, proposal.hidden] + assistant.evaluationTargets(for: state) + ) + try assistant.requestStateDidFinishEvaluation(state) + let expected = MiMoV26MTPChecks.reference( + mtp.layers[depth], hidden: scalarHidden, + tokens: Array(chain[(depth + 1)...]), target: target, + firstTokenPosition: depth + 1) + let lastLogits = Array(expected.logits.suffix(32)) + let expectedToken = lastLogits.indices.max { lastLogits[$0] < lastLogits[$1] }! + XCTAssertEqual( + Int(proposal.tokens.item(Int32.self)), expectedToken, + "length=\(length) chunk=\(chunk) depth=\(depth)") + try MiMoV26MTPChecks.near( + proposal.hidden, + output.normalizedHiddenStates[0..., (-1)..., 0...], "target feature reuse") + chain.append(Int(proposal.tokens.item(Int32.self))) + hidden = proposal.hidden + } + XCTAssertEqual(state.headProposalCounts, [1, 1, 1]) + assistant.discardRound(requestState: state) + XCTAssertEqual(state.headInputCounts, (0 ..< 3).map { max(0, length - $0 - 1) }) + assistant.releaseRequestState(state) + XCTAssertEqual(state.materializedBytes, 0) + } + } + } + + func testAcceptedPrefixesRollbackWrapAndCarryFallbackMatchTrustedReplay() throws { + let (target, mtp) = try MiMoV26MTPChecks.fixture() + let assistant = try MiMoV26MTPAssistant(target: target, predictor: mtp) + for accepted in 0 ... 3 { + let tokens = prompt(11) + let targetCache = target.newCache() + let initial = try target.forward(inputIDs: ids(tokens), cache: targetCache) + let native = try state(assistant) + let oracle = try state(assistant) + observe(assistant, native, ids(tokens), initial.normalizedHiddenStates) + observe(assistant, oracle, ids(tokens), initial.normalizedHiddenStates) + let seed = Int(argMax(initial.logits[0, -1], axis: -1).item(Int32.self)) + let drafts = propose( + assistant, native, seed: seed, + hidden: initial.normalizedHiddenStates[0..., (-1)..., 0...]) + var outputs: [MiMoV26TextOutput] = [] + for token in [seed] + drafts.prefix(accepted) { + let output = try target.forward(inputIDs: ids([token]), cache: targetCache) + eval(output.normalizedHiddenStates, output.logits) + outputs.append(output) + } + let acceptedHidden = + accepted == 0 + ? MLXArray.zeros([1, 0, 4]) + : concatenated(outputs.prefix(accepted).map(\.normalizedHiddenStates), axis: 1) + assistant.finalizeRound( + requestState: native, confirmedInputTokens: accepted + 1, + committedDraftTokens: ids(Array(drafts.prefix(accepted))), + committedTargetHidden: acceptedHidden) + let canonical = [seed] + drafts.prefix(accepted) + observe( + assistant, oracle, ids(Array(canonical)), + concatenated(outputs.map(\.normalizedHiddenStates), axis: 1)) + XCTAssertEqual(native.committedInputCount, oracle.committedInputCount) + let last = outputs.last! + let next = Int(argMax(last.logits[0, -1], axis: -1).item(Int32.self)) + // A separate admitted request exercises fallback from the same + // canonical prefix. No unpriced public snapshot owner is exported. + let fallback = try state(assistant) + observe(assistant, fallback, ids(tokens), initial.normalizedHiddenStates) + XCTAssertEqual( + propose( + assistant, fallback, seed: seed, + hidden: initial.normalizedHiddenStates[0..., (-1)..., 0...]), drafts) + assistant.finalizeRound( + requestState: fallback, confirmedInputTokens: accepted + 1, + committedDraftTokens: ids(Array(drafts.prefix(accepted))), + committedTargetHidden: acceptedHidden) + let actual = propose(assistant, native, seed: next, hidden: last.normalizedHiddenStates) + let expected = propose( + assistant, oracle, seed: next, hidden: last.normalizedHiddenStates) + XCTAssertEqual(actual, expected, "accepted prefix \(accepted)") + XCTAssertEqual(native.headInputCounts, oracle.headInputCounts) + assistant.discardRound(requestState: native) + assistant.discardRound(requestState: oracle) + // Verification-to-plain fallback emits a historyCarry callback, + // followed by the ordinary target input observation. + observe(assistant, fallback, ids([next]), last.normalizedHiddenStates) + let nextOutput = try target.forward(inputIDs: ids([next]), cache: targetCache) + observe(assistant, fallback, ids([next]), nextOutput.normalizedHiddenStates) + observe(assistant, oracle, ids([next]), nextOutput.normalizedHiddenStates) + let nextSeed = Int(argMax(nextOutput.logits[0, -1], axis: -1).item(Int32.self)) + XCTAssertEqual( + propose( + assistant, fallback, seed: nextSeed, hidden: nextOutput.normalizedHiddenStates), + propose( + assistant, oracle, seed: nextSeed, hidden: nextOutput.normalizedHiddenStates)) + for state in [native, oracle, fallback] { assistant.releaseRequestState(state) } + } + } + + private func measuredBacking(_ assistant: MiMoV26MTPAssistant, _ state: MiMoV26MTPState) throws + -> Int + { + try assistant.evaluationTargets(for: state).reduce(0) { total, array in + let info = try XCTUnwrap(array.evaluatedBufferInfo()) + return total + info.allocatedBytes + } + } + + func testRequestIsolationMeasuredOwnershipAndRelease() throws { + let (target, mtp) = try MiMoV26MTPChecks.fixture() + let assistant = try MiMoV26MTPAssistant(target: target, predictor: mtp) + let first = try state(assistant) + let second = try state(assistant) + let output = try target.forward(inputIDs: ids(prompt(20))) + observe(assistant, first, ids(prompt(20)), output.normalizedHiddenStates) + observe(assistant, second, ids(prompt(20)), output.normalizedHiddenStates) + XCTAssertFalse(first.hasUnmeasuredResidency) + XCTAssertEqual(first.materializedBytes, try measuredBacking(assistant, first)) + let before = second.materializedBytes + let counters = second.headInputCounts + let knownBeforeDraft = first.materializedBytes + let one = assistant.draftStep( + tokens: ids([7]), hidden: output.normalizedHiddenStates[0..., (-1)..., 0...], + shortlist: nil, requestState: first) + XCTAssertTrue(first.hasUnmeasuredResidency) + XCTAssertEqual( + first.materializedBytes, knownBeforeDraft, + "prior frozen owners retire only at successor fence") + eval([one.tokens, one.hidden] + assistant.evaluationTargets(for: first)) + try assistant.requestStateDidFinishEvaluation(first) + XCTAssertFalse(first.hasUnmeasuredResidency) + XCTAssertEqual(first.materializedBytes, try measuredBacking(assistant, first)) + XCTAssertEqual(second.materializedBytes, before) + XCTAssertEqual(second.headInputCounts, counters) + let beforeDiscard = first.materializedBytes + assistant.discardRound(requestState: first) + XCTAssertTrue(first.hasUnmeasuredResidency) + XCTAssertEqual( + first.materializedBytes, beforeDiscard, + "discard cannot refund retained measured contexts") + eval(assistant.evaluationTargets(for: first)) + try assistant.requestStateDidFinishEvaluation(first) + let expected = propose( + assistant, first, seed: 7, hidden: output.normalizedHiddenStates[0..., (-1)..., 0...]) + assistant.discardRound(requestState: first) + XCTAssertEqual( + propose( + assistant, first, seed: 7, + hidden: output.normalizedHiddenStates[0..., (-1)..., 0...]), expected) + XCTAssertFalse(assistant is any CBv2MTPPrefixCheckpointDrafter) + assistant.releaseRequestState(first) + assistant.releaseRequestState(first) + XCTAssertTrue(first.isReleased) + XCTAssertEqual(first.materializedBytes, 0) + XCTAssertEqual(first.measuredRootCount, 0) + XCTAssertFalse(first.hasUnmeasuredResidency) + XCTAssertTrue(assistant.evaluationTargets(for: first).isEmpty) + XCTAssertThrowsError(try assistant.requestStateDidFinishEvaluation(first)) + assistant.releaseRequestState(second) + } + + func testFenceRejectsDuplicateAndAliasedBackingWithoutInventedIdentity() throws { + let (target, mtp) = try MiMoV26MTPChecks.fixture() + let assistant = try MiMoV26MTPAssistant(target: target, predictor: mtp) + let tokens = prompt(11) + let output = try target.forward(inputIDs: ids(tokens)) + for duplicateDescriptor in [true, false] { + let candidate = try state(assistant) + observe(assistant, candidate, ids(tokens), output.normalizedHiddenStates) + candidate.willMutate() + if duplicateDescriptor { + candidate.pendingHidden = candidate.tail + } else { + // Different MLX descriptors, same backing. Shape/extents alone + // cannot justify counting both allocations. + candidate.tail = candidate.cache!.innerState()[0].reshaped([1, 3, 4]) + } + eval(assistant.evaluationTargets(for: candidate)) + XCTAssertThrowsError(try assistant.requestStateDidFinishEvaluation(candidate)) + XCTAssertTrue(candidate.hasUnmeasuredResidency) + assistant.releaseRequestState(candidate) + XCTAssertEqual(candidate.materializedBytes, 0) + XCTAssertEqual(candidate.measuredRootCount, 0) + } + } + + func testNamedReloadAndExplicitSessionInvalidationFailClosed() throws { + let (target, mtp) = try MiMoV26MTPChecks.fixture() + let assistant = try MiMoV26MTPAssistant(target: target, predictor: mtp) + let adapter = try MiMoV26CBv2Adapter(target: target, assistant: assistant) + let existing = try state(assistant) + XCTAssertTrue(adapter.cbv2Capabilities.supportsMTP) + try mtp.loadConvertedWeights(MiMoV26MTPChecks.fixtureWeights(mtp, prefix: "mtp.")) + XCTAssertNil(assistant.mtpTargetIdentity) + XCTAssertFalse(adapter.cbv2Capabilities.supportsMTP) + XCTAssertThrowsError( + try assistant.configureRequestState(existing, maximumSequenceLength: 64)) + assistant.releaseRequestState(existing) + + let newAssistant = try MiMoV26MTPAssistant(target: target, predictor: mtp) + let valid = try state(newAssistant) + XCTAssertEqual(newAssistant.mtpTargetIdentity, ObjectIdentifier(target)) + let (replacement, replacementMTP) = try MiMoV26MTPChecks.fixture() + XCTAssertThrowsError(try MiMoV26MTPAssistant(target: replacement, predictor: mtp)) + XCTAssertThrowsError(try MiMoV26CBv2Adapter(target: replacement, assistant: newAssistant)) + newAssistant.releaseRequestState(valid) + newAssistant.invalidateLoadedSession() + // Generic parent/child/target Module mutation is unsupported while a + // session is active. A host that performs it must invalidate first; the + // old assistant never becomes valid again after such updates. + try mtp.update(parameters: mtp.parameters(), verify: .all) + try mtp.layers[0].update(parameters: mtp.layers[0].parameters(), verify: .all) + try target.update(parameters: target.parameters(), verify: .all) + XCTAssertNil(newAssistant.mtpTargetIdentity) + XCTAssertThrowsError(try MiMoV26CBv2Adapter(target: target, assistant: newAssistant)) + let fresh = try MiMoV26MTPAssistant(target: replacement, predictor: replacementMTP) + XCTAssertEqual(fresh.mtpTargetIdentity, ObjectIdentifier(replacement)) + } + + func testAffine4Group64BF16AssistantUsesAllThreeNativeHeads() throws { + let target = try MiMoV26TextModel(MiMoV26MTPChecks.affineConfiguration()) + try target.update( + parameters: .unflattened( + MiMoV26MTPChecks.fixtureWeights(target) + .mapValues { $0.asType(.bfloat16) }), verify: .all) + let mtp = try MiMoV26MTP(target: target) + try mtp.loadConvertedWeights(MiMoV26MTPChecks.packedFixture(mtp).stored) + let assistant = try MiMoV26MTPAssistant(target: target, predictor: mtp) + let state = try state(assistant) + let tokens = prompt(9) + let output = try target.forward(inputIDs: ids(tokens)) + observe(assistant, state, ids(tokens), output.normalizedHiddenStates) + _ = propose( + assistant, state, seed: 7, hidden: output.normalizedHiddenStates[0..., (-1)..., 0...]) + XCTAssertEqual(state.headProposalCounts, [1, 1, 1]) + XCTAssertEqual(state.retainedFeatureRows, 3) + for depth in state.retainedHistoryShapes { + for shape in depth { XCTAssertLessThanOrEqual(shape[2], 3) } + } + assistant.releaseRequestState(state) + XCTAssertEqual(state.materializedBytes, 0) + } + + func testCopyPreservesFloatingBitsAndDetachesLargeParent() throws { + for dtype: DType in [.float32, .bfloat16] { + let data: Data + if dtype == .float32 { + let bits: [UInt32] = [ + 0, 0x8000_0000, 1, 0x007f_ffff, 0x7fc0_1234, 0x7f80_0000, 0xff80_0000, + ] + data = (0 ..< 36).map { bits[$0 % bits.count] }.withUnsafeBufferPointer { + Data(buffer: $0) + } + } else { + let bits: [UInt16] = [0, 0x8000, 1, 0x007f, 0x7fc1, 0x7f80, 0xff80] + data = (0 ..< 36).map { bits[$0 % bits.count] }.withUnsafeBufferPointer { + Data(buffer: $0) + } + } + let parent = MLXArray(data, [1, 9, 4], dtype: dtype) + let selected = parent[0..., 6 ..< 9, 0...] + let copy = mimoV26MTPCopy(selected) + eval(copy) + StreamOrDevice.default.stream.synchronize() + let info = try XCTUnwrap(copy.evaluatedBufferInfo()) + XCTAssertTrue(info.isUnique) + XCTAssertTrue(info.isRowContiguous) + XCTAssertEqual(info.dataOffset, 0) + XCTAssertEqual(info.dataElements, 12) + XCTAssertLessThanOrEqual( + info.allocatedBytes, + try Memory.allocationFootprintUpperBound(byteCount: 12 * dtype.size)) + XCTAssertEqual(copy.asData(access: .copy).data, Data(data.suffix(12 * dtype.size))) + } + } + + func testOfficialKVWidthsResidencyAtWindowAndChunkBoundaries() throws { + for dtype: DType in [.float32, .bfloat16] { + var fields = + try JSONSerialization.jsonObject( + with: JSONEncoder().encode(MiMoV26MTPChecks.config())) as! [String: Any] + fields["max_position_embeddings"] = 256 + fields["sliding_window"] = 128 + fields["sliding_window_size"] = 128 + fields["head_dim"] = 192 + fields["swa_head_dim"] = 192 + fields["v_head_dim"] = 128 + fields["swa_v_head_dim"] = 128 + fields["dtype"] = dtype == .float32 ? "float32" : "bfloat16" + fields["moe_router_dtype"] = fields["dtype"] + let config = try JSONDecoder().decode( + MiMoV26Configuration.self, + from: JSONSerialization.data(withJSONObject: fields)) + let target = try MiMoV26TextModel(config) + try target.update( + parameters: .unflattened( + MiMoV26MTPChecks.fixtureWeights(target) + .mapValues { $0.asType(dtype) }), verify: .all) + let mtp = try MiMoV26MTP(target: target) + try mtp.loadConvertedWeights( + MiMoV26MTPChecks.fixtureWeights(mtp, prefix: "mtp.") + .mapValues { $0.asType(dtype) }) + let assistant = try MiMoV26MTPAssistant(target: target, predictor: mtp) + eval(target, mtp) + for length in [1, 2, 3, 127, 128, 129] { + let tokens = prompt(length) + let targetOutput = try target.forward(inputIDs: ids(tokens)) + eval(targetOutput.normalizedHiddenStates) + for chunk in [1, 64, 129] { + let state = assistant.makeRequestState() as! MiMoV26MTPState + try assistant.configureRequestState(state, maximumSequenceLength: 256) + for start in stride(from: 0, to: length, by: chunk) { + let end = min(length, start + chunk) + let previous = state.materializedBytes + assistant.observeCommittedTarget( + .init( + tokens: ids(Array(tokens[start ..< end])), + hidden: targetOutput.normalizedHiddenStates[ + 0..., start ..< end, 0...]), requestState: state) + XCTAssertTrue(state.hasUnmeasuredResidency) + XCTAssertEqual(state.materializedBytes, previous) + eval(assistant.evaluationTargets(for: state)) + try assistant.requestStateDidFinishEvaluation(state) + XCTAssertFalse(state.hasUnmeasuredResidency) + XCTAssertEqual( + state.materializedBytes, try measuredBacking(assistant, state)) + XCTAssertEqual( + state.measuredRootCount, assistant.evaluationTargets(for: state).count) + } + print( + "MTP_RESIDENCY dtype=\(dtype) prompt=\(length) chunk=\(chunk) measured=\(state.materializedBytes) logical=\(state.logicalRootBytes) active=\(Memory.activeMemory) cache=\(Memory.cacheMemory)" + ) + assistant.releaseRequestState(state) + XCTAssertEqual(state.materializedBytes, 0) + XCTAssertEqual(state.measuredRootCount, 0) + XCTAssertTrue(assistant.evaluationTargets(for: state).isEmpty) + } + } + } + } + + func testAdapterExplicitLoadedOwnerAndHiddenPrefillReadoutContract() throws { + let (target, mtp) = try MiMoV26MTPChecks.fixture() + let unloaded = try MiMoV26MTP(target: target) + XCTAssertThrowsError(try MiMoV26MTPAssistant(target: target, predictor: unloaded)) + let native = try MiMoV26MTPAssistant(target: target, predictor: mtp) + let otherTarget = try MiMoV26TextModel(MiMoV26MTPChecks.config()) + XCTAssertThrowsError(try MiMoV26CBv2Adapter(target: otherTarget, assistant: native)) + XCTAssertFalse(try MiMoV26CBv2Adapter(target: target).cbv2Capabilities.supportsMTP) + let adapter = try MiMoV26CBv2Adapter(target: target, assistant: native) + XCTAssertTrue(adapter.cbv2Capabilities.supportsMTP) + XCTAssertTrue(adapter.supportsRequestStatefulMTP) + XCTAssertNil(adapter.mtpCaptureLayers) + _ = try withMiMoConstructionScope { constructionWork in + try adapter.probeNativeKVTypes(retaining: constructionWork) + } + let backend = try adapter.makeBackend(bytesCapacity: 1 << 20) + let rows = try backend.makeSequenceState( + layerKinds: adapter.layerKinds, promptLength: 9, maxLength: 32) + let caches = adapter.makeCaches() + try adapter.bindRows([rows], caches: caches) + let spy = MiMoV26MTPReadoutSpy(4, 32, bias: false) + try spy.update(parameters: target.lmHead!.parameters(), verify: .all) + target.update(modules: ModuleChildren.unflattened([("lm_head", spy as Module)])) + let requestState = try state(native) + let first = adapter.forwardWithHiddenForPrefill( + tokens: ids(prompt(6)), caches: caches, + requirement: .evaluationOnly) + observe(native, requestState, ids(prompt(6)), first.lastHidden) + eval(first.logits) + XCTAssertEqual(first.logits.shape, [1, 1]) + XCTAssertTrue( + spy.shapes.isEmpty, "prompt priming constructed target or predictor vocabulary logits") + XCTAssertEqual(first.lastHidden.shape, [1, 6, 4]) + let final = adapter.forwardWithHiddenForPrefill( + tokens: ids([2, 3, 4]), caches: caches, + requirement: .lastPositionLogits) + observe(native, requestState, ids([2, 3, 4]), final.lastHidden) + eval(final.logits) + XCTAssertEqual(final.logits.shape, [1, 32]) + XCTAssertEqual(spy.shapes, [[1, 4]]) + let reference = try target.forward(inputIDs: ids(prompt(6) + [2, 3, 4])) + try MiMoV26MTPChecks.near( + final.lastHidden, reference.normalizedHiddenStates[0..., 6..., 0...], + "CBv2 post-norm features") + try MiMoV26MTPChecks.near( + final.logits, reference.logits[0..., -1, 0...], "CBv2 prefill logits") + native.releaseRequestState(requestState) + backend.release(rows) + XCTAssertEqual(backend.bytesInUse, 0) + } + + private func engine( + target: MiMoV26TextModel, assistant: MiMoV26MTPAssistant?, + drafter: (any CBv2MTPDrafter)? = nil, chunk: Int = 3, depth: Int = 3 + ) + throws -> (EngineV2, MiMoV26CBv2Backend) + { + let adapter = try MiMoV26CBv2Adapter(target: target, assistant: assistant) + _ = try withMiMoConstructionScope { constructionWork in + try adapter.probeNativeKVTypes(retaining: constructionWork) + } + let backend = try adapter.makeBackend(bytesCapacity: 32 << 20) + let engine = EngineV2( + model: adapter, layerKinds: adapter.layerKinds, backend: backend, + cacheProvider: CBv2LayerCacheBank(caches: adapter.makeCaches()), + schedulerConfig: .init( + maxConcurrentRequests: 2, maxBatchedTokensPerStep: 32, + prefillChunkSize: chunk, maxWaiting: 8), + mtpDrafter: drafter ?? assistant, + mtpConfig: .init( + enabled: assistant != nil, maxDraftTokens: depth, + maxSpeculativeBatch: 1, fixedDraftTokens: depth, verificationMode: .serialTarget)) + return (engine, backend) + } + private func request(_ id: UInt64, _ tokens: [Int], _ budget: Int) -> CBv2Request { + .init( + id: .init(id), promptTokens: tokens, sampling: .init(temperature: 0), maxTokens: budget) + } + private func baseline( + _ target: MiMoV26TextModel, _ request: CBv2Request, + chunk: Int = 3 + ) async throws -> CBv2SchedCollected { + let (engine, backend) = try engine(target: target, assistant: nil, chunk: chunk) + let result = await cbv2SchedCollect(try engine.submit(request)) + await engine.shutdown() + XCTAssertEqual(backend.bytesInUse, 0) + return result + } + + func testRealEngineNativeOFFONAgreementAcrossChunksDepthAndBudget() async throws { + let (target, mtp) = try MiMoV26MTPChecks.fixture() + let native = try MiMoV26MTPAssistant(target: target, predictor: mtp) + for (length, chunk, depth, budget) in [ + (1, 1, 1, 1), (2, 1, 2, 2), (11, 3, 3, 16), (17, 7, 2, 13), + ] { + let req = request(1, prompt(length), budget) + let off = try await baseline(target, req, chunk: chunk) + let tracking = MiMoV26ScriptedAssistant(native) + let (engine, backend) = try engine( + target: target, assistant: native, drafter: tracking, chunk: chunk, depth: depth) + let on = await cbv2SchedCollect(try engine.submit(req)) + let metrics = try XCTUnwrap(engine.mtpMetricsSnapshot()) + await engine.shutdown() + XCTAssertEqual(on.tokens, off.tokens) + XCTAssertEqual(on.finishReason, off.finishReason) + XCTAssertEqual(on.tokens.count, budget) + if budget > 2 { + XCTAssertGreaterThan(metrics.rounds, 0) + XCTAssertGreaterThan(tracking.observations, 1) + XCTAssertGreaterThan(tracking.observationFenceReads, 0) + XCTAssertTrue(tracking.states.contains { $0.headProposalCounts[depth - 1] > 0 }) + } + XCTAssertTrue(tracking.states.allSatisfy { $0.isReleased && $0.materializedBytes == 0 }) + XCTAssertEqual(backend.bytesInUse, 0) + XCTAssertEqual(metrics.rectangularVerificationRounds, 0) + } + } + + func testRealEngineAcceptRejectPositionsZeroThroughThreeAndEOS() async throws { + let (target, mtp) = try MiMoV26MTPChecks.fixture() + let native = try MiMoV26MTPAssistant(target: target, predictor: mtp) + let tokens = prompt(11) + let req = request(1, tokens, 24) + let off = try await baseline(target, req) + for rejection in 0 ... 3 { + let tracking = MiMoV26ScriptedAssistant( + native, script: off.tokens, + promptLength: tokens.count, rejectPosition: rejection) + let (engine, backend) = try engine(target: target, assistant: native, drafter: tracking) + let on = await cbv2SchedCollect(try engine.submit(req)) + let metrics = try XCTUnwrap(engine.mtpMetricsSnapshot()) + await engine.shutdown() + XCTAssertEqual(on.tokens, off.tokens, "first rejected position \(rejection)") + XCTAssertGreaterThan(metrics.rounds, 0) + if rejection == 0 { + XCTAssertEqual(metrics.acceptedTokens, 0) + } else { + XCTAssertGreaterThan(metrics.perPositionAccepted[rejection - 1], 0) + } + if rejection < 3 { XCTAssertEqual(metrics.perPositionAccepted[rejection], 0) } + XCTAssertEqual(backend.bytesInUse, 0) + } + var eos = req + eos.stopTokens = [off.tokens[2]] + let eosOff = try await baseline(target, eos) + let tracking = MiMoV26ScriptedAssistant( + native, script: off.tokens, promptLength: tokens.count) + let (engine, backend) = try engine(target: target, assistant: native, drafter: tracking) + let eosOn = await cbv2SchedCollect(try engine.submit(eos)) + await engine.shutdown() + XCTAssertEqual(eosOn.tokens, eosOff.tokens) + XCTAssertEqual(eosOn.finishReason, .stop) + XCTAssertEqual(backend.bytesInUse, 0) + } + + func testRealEngineRequestJoinIsolationAndCancellationDrain() async throws { + let (target, mtp) = try MiMoV26MTPChecks.fixture() + let native = try MiMoV26MTPAssistant(target: target, predictor: mtp) + let first = request(1, prompt(11), 13) + let second = request(2, prompt(19), 11) + let expectedFirst = try await baseline(target, first) + let expectedSecond = try await baseline(target, second) + let tracking = MiMoV26ScriptedAssistant(native) + let (engine, backend) = try engine(target: target, assistant: native, drafter: tracking) + let firstStream = try engine.submit(first) + let secondStream = try engine.submit(second) + let firstTask = Task { await cbv2SchedCollect(firstStream) } + let secondTask = Task { await cbv2SchedCollect(secondStream) } + let resultFirst = await firstTask.value + let resultSecond = await secondTask.value + XCTAssertEqual(resultFirst.tokens, expectedFirst.tokens) + XCTAssertEqual(resultSecond.tokens, expectedSecond.tokens) + let cancellation = request(3, prompt(13), 40) + let stream = try engine.submit(cancellation) + var cancelled = false + var emitted = 0 + var finish: CBv2FinishReason? + for await event in stream { + switch event { + case .delta(_, let tokens, _): + emitted += tokens.count + if emitted >= 6 && !cancelled { + cancelled = true + engine.cancel(cancellation.id) + } + case .finished(let reason, _): finish = reason + } + } + await engine.shutdown() + XCTAssertTrue(cancelled) + XCTAssertEqual(finish, .cancelled) + XCTAssertEqual(backend.bytesInUse, 0) + XCTAssertTrue(tracking.states.allSatisfy { $0.isReleased && $0.materializedBytes == 0 }) + XCTAssertEqual(Set(tracking.states.map(ObjectIdentifier.init)).count, tracking.states.count) + } + + func testRealEngineSamplingSafetyFallbacksDoNotDraft() async throws { + let (target, mtp) = try MiMoV26MTPChecks.fixture() + let native = try MiMoV26MTPAssistant(target: target, predictor: mtp) + for sampling in [ + CBv2SamplingParams(temperature: 0.7, seed: 7), + CBv2SamplingParams(temperature: 0, repetitionPenalty: 1.1), + CBv2SamplingParams(temperature: 0, logitBias: [3: 1]), + ] { + let tracking = MiMoV26ScriptedAssistant(native) + let (engine, backend) = try engine(target: target, assistant: native, drafter: tracking) + var req = request(1, prompt(7), 8) + req.sampling = sampling + let result = await cbv2SchedCollect(try engine.submit(req)) + let metrics = try XCTUnwrap(engine.mtpMetricsSnapshot()) + await engine.shutdown() + XCTAssertEqual(result.tokens.count, 8) + XCTAssertEqual(metrics.rounds, 0) + XCTAssertEqual(metrics.draftedTokens, 0) + XCTAssertTrue(tracking.states.isEmpty) + XCTAssertEqual(backend.bytesInUse, 0) + } + } + + func testEngineCompletionFenceRetainsKnownOwnersThroughCancelDrainAndFailure() async throws { + let (target, mtp) = try MiMoV26MTPChecks.fixture() + let native = try MiMoV26MTPAssistant(target: target, predictor: mtp) + for shutdown in [false, true] { + let tracking = MiMoV26ScriptedAssistant(native) + let visit = MiMoV26SecondFenceVisit() + let entered = DispatchSemaphore(value: 0) + let resume = DispatchSemaphore(value: 0) + tracking.fenceHook = { state in + if visit.shouldBlock() { + XCTAssertTrue(state.hasUnmeasuredResidency) + XCTAssertGreaterThan(state.materializedBytes, 0) + entered.signal() + _ = resume.wait(timeout: .now() + 10) + } + } + let (engine, backend) = try engine(target: target, assistant: native, drafter: tracking) + let stream = try engine.submit(request(1, prompt(11), 16)) + let collected = Task { await cbv2SchedCollect(stream) } + let blocked = await withCheckedContinuation { continuation in + DispatchQueue.global().async { + continuation.resume(returning: entered.wait(timeout: .now() + 5) == .success) + } + } + XCTAssertTrue(blocked) + let owner = try XCTUnwrap(tracking.states.first) + let held = owner.materializedBytes + XCTAssertGreaterThan(held, 0) + XCTAssertTrue(owner.hasUnmeasuredResidency) + let drain = shutdown ? Task { await engine.shutdown() } : nil + if !shutdown { engine.cancel(.init(1)) } + XCTAssertEqual( + owner.materializedBytes, held, + "queued cancel/drain cannot retire the measured owner") + resume.signal() + let result = await collected.value + if let drain { + await drain.value + } else { + XCTAssertEqual(result.finishReason, .cancelled) + await engine.shutdown() + } + XCTAssertEqual(backend.bytesInUse, 0) + XCTAssertTrue( + tracking.states.allSatisfy { + $0.isReleased && $0.materializedBytes == 0 && $0.measuredRootCount == 0 + }) + } + let failing = MiMoV26ScriptedAssistant(native) + failing.fenceHook = { _ in throw MLXError.caught("intentional MTP completion-owner refusal") + } + let (engine, backend) = try engine(target: target, assistant: native, drafter: failing) + let result = await cbv2SchedCollect(try engine.submit(request(2, prompt(11), 16))) + if case .error? = result.finishReason { + } else { + XCTFail("owner proof failure did not fail closed") + } + await engine.shutdown() + XCTAssertEqual(backend.bytesInUse, 0) + XCTAssertTrue(failing.states.allSatisfy { $0.isReleased && $0.materializedBytes == 0 }) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26MTPParkResumeTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26MTPParkResumeTests.swift new file mode 100644 index 0000000000..e1d8555030 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26MTPParkResumeTests.swift @@ -0,0 +1,98 @@ +import Foundation +import MLX +import MLXLMCommon +import XCTest + +@testable import MLXLLM + +/// Regression equivalent of oMLX #3978's abandoned-cycle history fold. +/// Tests the native request-state seam, not a full scheduler/HTTP park event. +final class MiMoV26MTPParkResumeTests: XCTestCase { + private func ids(_ values: [Int]) -> MLXArray { + MLXArray(values.map(Int32.init), [1, values.count]) + } + private func fence(_ assistant: MiMoV26MTPAssistant, _ state: MiMoV26MTPState) throws { + eval(assistant.evaluationTargets(for: state)) + try assistant.requestStateDidFinishEvaluation(state) + } + private func drafts( + _ assistant: MiMoV26MTPAssistant, _ state: MiMoV26MTPState, + seed: Int, hidden: MLXArray, depth: Int + ) throws -> [Int32] { + var token = ids([seed]) + var feature = hidden + var outputs: [Int32] = [] + for _ in 0 ..< depth { + let result = assistant.draftStep( + tokens: token, hidden: feature, + shortlist: nil, requestState: state) + eval([result.tokens, result.hidden] + assistant.evaluationTargets(for: state)) + try assistant.requestStateDidFinishEvaluation(state) + outputs.append(result.tokens.item(Int32.self)) + token = result.tokens.reshaped([1, 1]) + feature = result.hidden + } + return outputs + } + func testAbandonedRoundsDoNotTurnParkedHistoryIntoDrafts() throws { + let (target, predictor) = try MiMoV26MTPChecks.fixture() + let assistant = try MiMoV26MTPAssistant(target: target, predictor: predictor) + let tokens = (0 ..< 40).map { 1 + ($0 * 7) % 31 } + let hidden = try target.forward(inputIDs: ids(tokens)).normalizedHiddenStates + eval(hidden) + for depth in 1 ... 3 { + let candidate = assistant.makeRequestState() as! MiMoV26MTPState + let control = assistant.makeRequestState() as! MiMoV26MTPState + try assistant.configureRequestState(candidate, maximumSequenceLength: 64) + try assistant.configureRequestState(control, maximumSequenceLength: 64) + defer { + assistant.releaseRequestState(candidate) + assistant.releaseRequestState(control) + } + var offset = 0 + // Two abandoned rounds, each followed by a multi-token parked + // history and a separate one-token re-entry seam, then continue. + for length in [4, 6, 1, 1, 9, 1, 1] { + if offset == 4 || offset == 12 { + let before = candidate.headInputCounts + _ = try drafts( + assistant, candidate, seed: 7, + hidden: hidden[0..., (offset - 1) ..< offset, 0...], depth: depth) + XCTAssertGreaterThan(candidate.stagedInputCount, 0) + assistant.discardRound(requestState: candidate) + try fence(assistant, candidate) + XCTAssertNil(candidate.round) + XCTAssertEqual(candidate.stagedInputCount, 0) + XCTAssertEqual(candidate.headInputCounts, before) + } + let end = offset + length + for state in [candidate, control] { + assistant.observeCommittedTarget( + .init( + tokens: ids(Array(tokens[offset ..< end])), + hidden: hidden[0..., offset ..< end, 0...]), requestState: state) + try fence(assistant, state) + XCTAssertEqual(state.headInputCounts, (0 ..< 3).map { max(0, end - $0 - 1) }) + } + XCTAssertEqual(candidate.observedCount, control.observedCount) + XCTAssertEqual(candidate.ownedArrays.count, control.ownedArrays.count) + for (actual, expected) in zip(candidate.ownedArrays, control.ownedArrays) { + XCTAssertEqual(actual.shape, expected.shape) + XCTAssertEqual(actual.dtype, expected.dtype) + XCTAssertEqual( + actual.asData(access: .copy).data, + expected.asData(access: .copy).data) + } + offset = end + } + let feature = hidden[0..., (offset - 1) ..< offset, 0...] + XCTAssertEqual( + try drafts(assistant, candidate, seed: 9, hidden: feature, depth: depth), + try drafts(assistant, control, seed: 9, hidden: feature, depth: depth)) + assistant.discardRound(requestState: candidate) + assistant.discardRound(requestState: control) + try fence(assistant, candidate) + try fence(assistant, control) + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26MTPPrefixCheckpointTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26MTPPrefixCheckpointTests.swift new file mode 100644 index 0000000000..947a122213 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26MTPPrefixCheckpointTests.swift @@ -0,0 +1,784 @@ +// Copyright © 2026 Eigen Labs. +import Foundation +import MLX +import MLXNN +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon + +/// Prepared native component regressions, UNRUN. Reuses the real tiny target +/// and all three trained-head module fixtures, never a scripted/fake drafter. +/// Common's complete-store/target-adoption tests are a separate integration gate. +final class MiMoV26MTPPrefixCheckpointTests: XCTestCase { + private func fixture() throws -> (MiMoV26TextModel, MiMoV26MTP, MiMoV26MTPAssistant) { + var object = + try JSONSerialization.jsonObject( + with: JSONEncoder().encode(MiMoV26MTPChecks.config())) as! [String: Any] + object["dtype"] = "bfloat16" + object["moe_router_dtype"] = "bfloat16" + let config = try JSONDecoder().decode( + MiMoV26Configuration.self, + from: JSONSerialization.data(withJSONObject: object)) + let target = try MiMoV26TextModel(config) + try target.update( + parameters: .unflattened( + MiMoV26MTPChecks.fixtureWeights(target).mapValues { $0.asType(.bfloat16) }), + verify: .all) + let predictor = try MiMoV26MTP(target: target) + try predictor.loadConvertedWeights( + MiMoV26MTPChecks.fixtureWeights(predictor, prefix: "mtp.").mapValues { + $0.asType(.bfloat16) + }) + return (target, predictor, try MiMoV26MTPAssistant(target: target, predictor: predictor)) + } + private func prompt(_ count: Int = 17) -> [Int] { (0 ..< count).map { 1 + ($0 * 7) % 31 } } + private func ids(_ values: [Int]) -> MLXArray { + MLXArray(values.map(Int32.init), [1, values.count]) + } + private func state(_ assistant: MiMoV26MTPAssistant, prompt: [Int]? = nil) throws + -> MiMoV26MTPState + { + let result = assistant.makeRequestState() as! MiMoV26MTPState + try assistant.configureRequestState(result, maximumSequenceLength: 64) + if let prompt { + try assistant.installPrefixCaptureContext(requestState: result, promptTokens: prompt) + } + return result + } + private func finish(_ assistant: MiMoV26MTPAssistant, _ state: MiMoV26MTPState) throws { + try withError { eval(assistant.evaluationTargets(for: state)) } + try assistant.requestStateDidFinishEvaluation(state) + } + private func observe( + _ assistant: MiMoV26MTPAssistant, _ state: MiMoV26MTPState, + tokens: [Int], hidden: MLXArray, range: Range, chunk: Int = 1 + ) throws { + for start in stride(from: range.lowerBound, to: range.upperBound, by: chunk) { + let end = min(range.upperBound, start + chunk) + assistant.observeCommittedTarget( + .init( + tokens: ids(Array(tokens[start ..< end])), + hidden: hidden[0..., start ..< end, 0...]), requestState: state) + try finish(assistant, state) + } + } + private func capture( + _ assistant: MiMoV26MTPAssistant, _ state: MiMoV26MTPState, + at position: Int = 11 + ) throws -> any CBv2MTPPrefixCheckpoint { + let value = try XCTUnwrap( + assistant.capturePrefixCheckpoint(requestState: state, targetInputCount: position)) + try withError { eval(value.evaluationTargets) } + return value + } + private func bytes(_ arrays: [MLXArray]) -> [Data] { + arrays.map { $0.asData(access: .copy).data } + } + private func proposals( + _ assistant: MiMoV26MTPAssistant, _ state: MiMoV26MTPState, + seed: Int, hidden: MLXArray, depth: Int + ) throws -> [Int] { + var token = ids([seed]) + var feature = hidden + var result: [Int] = [] + for _ in 0 ..< depth { + let output = assistant.draftStep( + tokens: token, hidden: feature, shortlist: nil, requestState: state) + try withError { + eval([output.tokens, output.hidden] + assistant.evaluationTargets(for: state)) + } + try assistant.requestStateDidFinishEvaluation(state) + result.append(Int(output.tokens.item(Int32.self))) + token = output.tokens.reshaped([1, 1]) + feature = output.hidden + } + return result + } + + func testDescriptorsAreAllThreeNativeHeadsTailTokensAndExactMetadata() throws { + let (target, _, assistant) = try fixture() + defer { withExtendedLifetime(target) {} } + XCTAssertEqual(assistant.mtpTargetIdentity, ObjectIdentifier(target)) + let descriptors = try XCTUnwrap( + assistant.prefixCheckpointTensorDescriptors(targetInputCount: 4)) + XCTAssertEqual(descriptors.count, 9) + for depth in 0 ..< 3 { + XCTAssertEqual(descriptors[2 * depth].role, .assistantKeys) + XCTAssertEqual(descriptors[2 * depth + 1].role, .assistantValues) + XCTAssertEqual(descriptors[2 * depth].layer, depth) + XCTAssertEqual(descriptors[2 * depth].shape, [1, 1, 3 - depth, 4]) + XCTAssertEqual(descriptors[2 * depth + 1].shape, [1, 1, 3 - depth, 2]) + XCTAssertEqual(descriptors[2 * depth].dtype, .bfloat16) + XCTAssertEqual(descriptors[2 * depth + 1].dtype, .bfloat16) + } + XCTAssertEqual(descriptors[6].shape, [1, 3, 4]) + XCTAssertEqual(descriptors[7].shape, [1, 4]) + XCTAssertEqual(descriptors[8].shape, [3, 7]) + XCTAssertEqual(descriptors[8].dtype, .int64) + XCTAssertNil(assistant.prefixCheckpointTensorDescriptors(targetInputCount: 3)) + XCTAssertNil(assistant.prefixCheckpointTensorDescriptors(targetInputCount: 64)) + XCTAssertNil(assistant.prefixCheckpointTensorDescriptors(targetInputCount: Int.max)) + } + + func testContextIsOneTimeOwnerBoundAndBeforeObservationWithoutCallerCOW() throws { + let (target, _, assistant) = try fixture() + defer { withExtendedLifetime(target) {} } + var actual = prompt() + let original = actual + let output = try target.forward(inputIDs: ids(actual)) + let bound = try state(assistant, prompt: actual) + actual[0] = 30 + XCTAssertThrowsError( + try assistant.installPrefixCaptureContext(requestState: bound, promptTokens: original)) + try observe( + assistant, bound, tokens: original, hidden: output.normalizedHiddenStates, + range: 0 ..< 11) + XCTAssertNotNil( + assistant.capturePrefixCheckpoint(requestState: bound, targetInputCount: 11)) + let late = try state(assistant) + try observe( + assistant, late, tokens: original, hidden: output.normalizedHiddenStates, range: 0 ..< 1 + ) + XCTAssertThrowsError( + try assistant.installPrefixCaptureContext(requestState: late, promptTokens: original)) + let (foreignTarget, _, foreign) = try fixture() + defer { withExtendedLifetime(foreignTarget) {} } + XCTAssertEqual(assistant.mtpTargetIdentity, ObjectIdentifier(target)) + XCTAssertEqual(foreign.mtpTargetIdentity, ObjectIdentifier(foreignTarget)) + XCTAssertNotEqual(assistant.mtpTargetIdentity, foreign.mtpTargetIdentity) + XCTAssertThrowsError( + try foreign.installPrefixCaptureContext(requestState: bound, promptTokens: original)) + let invalid = try state(assistant) + XCTAssertThrowsError( + try assistant.installPrefixCaptureContext( + requestState: invalid, promptTokens: [0, 1, -1, 2, 3])) + XCTAssertThrowsError( + try assistant.installPrefixCaptureContext( + requestState: invalid, promptTokens: [0, 1, 32, 2, 3])) + XCTAssertThrowsError( + try assistant.installPrefixCaptureContext(requestState: invalid, promptTokens: [])) + // A valid short request is not refused merely because no interior + // boundary can contain all three trained heads yet. + XCTAssertNoThrow( + try assistant.installPrefixCaptureContext( + requestState: invalid, promptTokens: [0, 1, 2, 3])) + XCTAssertNil(assistant.capturePrefixCheckpoint(requestState: invalid, targetInputCount: 4)) + assistant.releaseRequestState(bound) + assistant.releaseRequestState(late) + assistant.releaseRequestState(invalid) + } + + func testCaptureRequiresActualSettledInteriorBoundaryAndMatchingObservedTokens() throws { + let (target, _, assistant) = try fixture() + let tokens = prompt() + let output = try target.forward(inputIDs: ids(tokens)) + let request = try state(assistant, prompt: tokens) + assistant.observeCommittedTarget( + .init( + tokens: ids(Array(tokens[0 ..< 11])), + hidden: output.normalizedHiddenStates[0..., 0 ..< 11, 0...]), requestState: request) + XCTAssertNil(assistant.capturePrefixCheckpoint(requestState: request, targetInputCount: 11)) + try finish(assistant, request) + XCTAssertNotNil( + assistant.capturePrefixCheckpoint(requestState: request, targetInputCount: 11)) + XCTAssertNil(assistant.capturePrefixCheckpoint(requestState: request, targetInputCount: 10)) + try observe( + assistant, request, tokens: tokens, hidden: output.normalizedHiddenStates, + range: 11 ..< 17) + XCTAssertNil(assistant.capturePrefixCheckpoint(requestState: request, targetInputCount: 17)) + let wrong = try state(assistant, prompt: tokens) + var different = tokens + different[3] = different[3] == 1 ? 2 : 1 + let otherOutput = try target.forward(inputIDs: ids(different)) + try observe( + assistant, wrong, tokens: different, hidden: otherOutput.normalizedHiddenStates, + range: 0 ..< 11) + XCTAssertNil(assistant.capturePrefixCheckpoint(requestState: wrong, targetInputCount: 11)) + assistant.releaseRequestState(request) + assistant.releaseRequestState(wrong) + } + + func testNoDraftRoundCarryOrPendingStateCanBecomeHistoricalPrompt() throws { + let (target, _, assistant) = try fixture() + let tokens = prompt() + let output = try target.forward(inputIDs: ids(tokens)) + let request = try state(assistant, prompt: tokens) + try observe( + assistant, request, tokens: tokens, hidden: output.normalizedHiddenStates, + range: 0 ..< 11) + _ = try proposals( + assistant, request, seed: 7, + hidden: output.normalizedHiddenStates[0..., 10 ..< 11, 0...], depth: 1) + XCTAssertNil(assistant.capturePrefixCheckpoint(requestState: request, targetInputCount: 11)) + assistant.finalizeRound( + requestState: request, confirmedInputTokens: 1, + committedDraftTokens: ids([]), + committedTargetHidden: MLXArray.zeros([1, 0, 4], dtype: .bfloat16)) + try finish(assistant, request) + XCTAssertNotNil(request.pendingLastToken) + XCTAssertNil(assistant.capturePrefixCheckpoint(requestState: request, targetInputCount: 11)) + assistant.discardRound(requestState: request) + try finish(assistant, request) + XCTAssertNil(assistant.capturePrefixCheckpoint(requestState: request, targetInputCount: 11)) + XCTAssertThrowsError( + try assistant.installPrefixCaptureContext(requestState: request, promptTokens: tokens)) + assistant.releaseRequestState(request) + } + + func testWrappedPhysicalRingAndAllTensorBytesSurviveEncodeDecodeRestore() throws { + let (target, _, assistant) = try fixture() + let tokens = prompt() + let output = try target.forward(inputIDs: ids(tokens)) + for chunk in [1, 2, 7] { + let donor = try state(assistant, prompt: tokens) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, + range: 0 ..< 11, chunk: chunk) + let checkpoint = try capture(assistant, donor) + let arrays = try XCTUnwrap(assistant.encodePrefixCheckpoint(checkpoint)) + let expected = bytes(arrays) // independent host byte copies, before adoption + let imported = try XCTUnwrap( + assistant.decodePrefixCheckpoint( + tensors: arrays, prefixTokens: Array(tokens.prefix(11)))) + let restored = try XCTUnwrap( + assistant.restorePrefixCheckpoint(imported) as? MiMoV26MTPState) + try assistant.configureRequestState(restored, maximumSequenceLength: 64) + try assistant.installPrefixCaptureContext(requestState: restored, promptTokens: tokens) + try finish(assistant, restored) + let recaptured = try capture(assistant, restored) + XCTAssertEqual(bytes(recaptured.evaluationTargets), expected, "chunk \(chunk)") + XCTAssertEqual(restored.headInputCounts, [10, 9, 8]) + XCTAssertEqual(restored.cache?.nextTokenPositions, [11, 11, 11]) + XCTAssertEqual(restored.retainedFeatureRows, 3) + XCTAssertEqual(restored.committedInputCount, 11) + XCTAssertEqual(restored.stagedInputCount, 0) + XCTAssertFalse(restored.hasRequiredRestoredSuffix) + XCTAssertNil(restored.pendingTokens) + XCTAssertNil(restored.pendingHidden) + XCTAssertNil(restored.pendingLastToken) + assistant.releaseRequestState(restored) + assistant.releaseRequestState(donor) + } + } + + func testImportRejectsWrongTokensDtypesShapesHeadCountAndRingMetadata() throws { + let (target, _, assistant) = try fixture() + let tokens = prompt() + let output = try target.forward(inputIDs: ids(tokens)) + let donor = try state(assistant, prompt: tokens) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, range: 0 ..< 11 + ) + let checkpoint = try capture(assistant, donor) + let arrays = checkpoint.evaluationTargets + let prefix = Array(tokens.prefix(11)) + var wrongTokens = prefix + wrongTokens[0] = 0 + XCTAssertNil(assistant.decodePrefixCheckpoint(tensors: arrays, prefixTokens: wrongTokens)) + XCTAssertNil( + assistant.decodePrefixCheckpoint( + tensors: Array(arrays.dropLast()), prefixTokens: prefix)) + for index in 0 ..< 8 { + var changed = arrays + changed[index] = arrays[index].asType(index == 7 ? .int64 : .float32) + XCTAssertNil(assistant.decodePrefixCheckpoint(tensors: changed, prefixTokens: prefix)) + changed = arrays + changed[index] = arrays[index].reshaped([-1]) + XCTAssertNil(assistant.decodePrefixCheckpoint(tensors: changed, prefixTokens: prefix)) + } + let metadata = arrays[8].asArray(Int64.self) + let invalidFields: [(Int, Int64)] = [ + (0, 0), (1, 1), (2, 4), (3, 128), (4, 1), (5, 0), (6, 1), + ] + for depth in 0 ..< 3 { + for (column, invalid) in invalidFields { + var values = metadata + values[depth * 7 + column] = invalid + var changed = arrays + changed[8] = MLXArray(values, [3, 7]) + XCTAssertNil( + assistant.decodePrefixCheckpoint(tensors: changed, prefixTokens: prefix), + "depth \(depth), field \(column)") + } + } + assistant.releaseRequestState(donor) + } + + func testTokenAndMetadataValidationNeverEvaluatesLazyImportedWitnesses() throws { + let (target, _, assistant) = try fixture() + let tokens = prompt() + let output = try target.forward(inputIDs: ids(tokens)) + let donor = try state(assistant, prompt: tokens) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, range: 0 ..< 11 + ) + let checkpoint = try capture(assistant, donor) + let arrays = checkpoint.evaluationTargets + let prefix = Array(tokens.prefix(11)) + var lazy = arrays + lazy[7] = mimoV26MTPCopy(arrays[7]) + XCTAssertNil(try lazy[7].evaluatedBufferInfo()) + XCTAssertNil(assistant.decodePrefixCheckpoint(tensors: lazy, prefixTokens: prefix)) + XCTAssertNil(try lazy[7].evaluatedBufferInfo()) + try withError { eval(lazy) } + XCTAssertNotNil(assistant.decodePrefixCheckpoint(tensors: lazy, prefixTokens: prefix)) + lazy = arrays + lazy[8] = mimoV26MTPCopy(arrays[8]) + XCTAssertNil(try lazy[8].evaluatedBufferInfo()) + XCTAssertNil(assistant.decodePrefixCheckpoint(tensors: lazy, prefixTokens: prefix)) + XCTAssertNil(try lazy[8].evaluatedBufferInfo()) + try withError { eval(lazy) } + assistant.releaseRequestState(donor) + } + + func testRestoreIsCurrentOwnerBoundAndReloadInvalidatesOldCheckpoint() throws { + let (target, predictor, assistant) = try fixture() + let tokens = prompt() + let output = try target.forward(inputIDs: ids(tokens)) + let donor = try state(assistant, prompt: tokens) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, range: 0 ..< 11 + ) + let checkpoint = try capture(assistant, donor) + let foreign = try MiMoV26MTPAssistant(target: target, predictor: predictor) + XCTAssertNil(foreign.encodePrefixCheckpoint(checkpoint)) + XCTAssertNil(foreign.restorePrefixCheckpoint(checkpoint)) + // Authentic import is separately rebound to the current owner; it is + // not permission to restore another owner's in-memory checkpoint. + let imported = try XCTUnwrap( + foreign.decodePrefixCheckpoint( + tensors: checkpoint.evaluationTargets, prefixTokens: Array(tokens.prefix(11)))) + let candidate = try XCTUnwrap(foreign.restorePrefixCheckpoint(imported) as? MiMoV26MTPState) + try finish(foreign, candidate) + foreign.releaseRequestState(candidate) + assistant.releaseRequestState(donor) + try predictor.loadConvertedWeights( + MiMoV26MTPChecks.fixtureWeights(predictor, prefix: "mtp.").mapValues { + $0.asType(.bfloat16) + }) + XCTAssertNil(assistant.encodePrefixCheckpoint(checkpoint)) + XCTAssertNil(assistant.restorePrefixCheckpoint(checkpoint)) + } + + func testPristineRestoreContextRejectsChangedPrefixAndLateInstall() throws { + let (target, _, assistant) = try fixture() + let tokens = prompt() + let output = try target.forward(inputIDs: ids(tokens)) + let donor = try state(assistant, prompt: tokens) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, range: 0 ..< 11 + ) + let checkpoint = try capture(assistant, donor) + let restored = try XCTUnwrap( + assistant.restorePrefixCheckpoint(checkpoint) as? MiMoV26MTPState) + try assistant.configureRequestState(restored, maximumSequenceLength: 64) + try finish(assistant, restored) // installer also works after actual copy completion + var changed = tokens + changed[0] = 0 + XCTAssertThrowsError( + try assistant.installPrefixCaptureContext(requestState: restored, promptTokens: changed) + ) + XCTAssertThrowsError( + try assistant.installPrefixCaptureContext( + requestState: restored, promptTokens: Array(tokens.prefix(11)))) + try assistant.installPrefixCaptureContext(requestState: restored, promptTokens: tokens) + XCTAssertThrowsError( + try assistant.installPrefixCaptureContext(requestState: restored, promptTokens: tokens)) + let late = try XCTUnwrap(assistant.restorePrefixCheckpoint(checkpoint) as? MiMoV26MTPState) + try assistant.configureRequestState(late, maximumSequenceLength: 64) + try finish(assistant, late) + try observe( + assistant, late, tokens: tokens, hidden: output.normalizedHiddenStates, range: 11 ..< 12 + ) + XCTAssertThrowsError( + try assistant.installPrefixCaptureContext(requestState: late, promptTokens: tokens)) + assistant.releaseRequestState(late) + assistant.releaseRequestState(restored) + assistant.releaseRequestState(donor) + } + + func testActualSuffixAndDepthOneThroughThreeMatchUncachedNativeContinuation() throws { + let (target, _, assistant) = try fixture() + let tokens = prompt() + let output = try target.forward(inputIDs: ids(tokens)) + let donor = try state(assistant, prompt: tokens) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, range: 0 ..< 11 + ) + let checkpoint = try capture(assistant, donor) + for depth in 1 ... 3 { + let cold = try state(assistant) + try observe( + assistant, cold, tokens: tokens, hidden: output.normalizedHiddenStates, + range: 0 ..< 11) + let restored = try XCTUnwrap( + assistant.restorePrefixCheckpoint(checkpoint) as? MiMoV26MTPState) + try assistant.configureRequestState(restored, maximumSequenceLength: 64) + try assistant.installPrefixCaptureContext(requestState: restored, promptTokens: tokens) + try finish(assistant, restored) + for request in [cold, restored] { + try observe( + assistant, request, tokens: tokens, hidden: output.normalizedHiddenStates, + range: 11 ..< 17) + } + XCTAssertTrue(restored.hasRequiredRestoredSuffix) + XCTAssertEqual(bytes(restored.cache!.innerState()), bytes(cold.cache!.innerState())) + let seed = Int(argMax(output.logits[0, -1], axis: -1).item(Int32.self)) + let hidden = output.normalizedHiddenStates[0..., (-1)..., 0...] + XCTAssertEqual( + try proposals(assistant, restored, seed: seed, hidden: hidden, depth: depth), + try proposals(assistant, cold, seed: seed, hidden: hidden, depth: depth)) + XCTAssertEqual(restored.headProposalCounts, cold.headProposalCounts) + XCTAssertEqual( + bytes(restored.round!.cache.innerState()), bytes(cold.round!.cache.innerState())) + assistant.discardRound(requestState: restored) + assistant.discardRound(requestState: cold) + try finish(assistant, restored) + try finish(assistant, cold) + assistant.releaseRequestState(restored) + assistant.releaseRequestState(cold) + } + assistant.releaseRequestState(donor) + } + + func testFirstSuffixAndEveryDraftDepthPreservePartialAndWrappedPrefixState() throws { + let (target, _, assistant) = try fixture() + defer { withExtendedLifetime(target) {} } + XCTAssertEqual(assistant.mtpTargetIdentity, ObjectIdentifier(target)) + let tokens = prompt() + let output = try target.forward(inputIDs: ids(tokens)) + XCTAssertEqual(target.configuration.slidingWindow, 3) + // P=4 has live head lengths [3,2,1]; P=11 has three wrapped rings. + for boundary in [4, 11] { + let donor = try state(assistant, prompt: tokens) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, + range: 0 ..< boundary) + let checkpoint = try capture(assistant, donor, at: boundary) + let published = bytes(try XCTUnwrap(assistant.encodePrefixCheckpoint(checkpoint))) + XCTAssertEqual(published.count, 9) + for depth in 1 ... 3 { + // No state/proposal from a preceding depth is reused. + let cold = try state(assistant, prompt: tokens) + try observe( + assistant, cold, tokens: tokens, hidden: output.normalizedHiddenStates, + range: 0 ..< boundary) + let restored = try XCTUnwrap( + assistant.restorePrefixCheckpoint(checkpoint) as? MiMoV26MTPState) + try assistant.configureRequestState(restored, maximumSequenceLength: 64) + try assistant.installPrefixCaptureContext( + requestState: restored, promptTokens: tokens) + try finish(assistant, restored) + + let coldBefore = bytes(try capture(assistant, cold, at: boundary).evaluationTargets) + let restoredBefore = bytes( + try capture(assistant, restored, at: boundary).evaluationTargets) + XCTAssertEqual(coldBefore.count, 9) + XCTAssertEqual(restoredBefore.count, 9) + // Data(access: .copy) snapshots were taken independently, not + // by comparing two aliases of the same checkpoint array. + XCTAssertEqual(coldBefore, published, "cold boundary P=\(boundary), depth=\(depth)") + XCTAssertEqual( + restoredBefore, coldBefore, "restored boundary P=\(boundary), depth=\(depth)") + for request in [cold, restored] { + XCTAssertEqual(request.headInputCounts, (0 ..< 3).map { boundary - $0 - 1 }) + XCTAssertEqual( + request.cache?.nextTokenPositions, [boundary, boundary, boundary]) + XCTAssertEqual(request.committedInputCount, boundary) + XCTAssertEqual(request.retainedFeatureRows, 3) + XCTAssertEqual(request.stagedInputCount, 0) + XCTAssertNil(request.round) + XCTAssertNil(request.pendingTokens) + XCTAssertNil(request.pendingHidden) + XCTAssertNil(request.pendingLastToken) + } + XCTAssertFalse(restored.hasRequiredRestoredSuffix) + + // Exactly one real target suffix input; at W=3 this cannot + // overwrite all restored history or the complete target tail. + for request in [cold, restored] { + try observe( + assistant, request, tokens: tokens, hidden: output.normalizedHiddenStates, + range: boundary ..< boundary + 1) + } + let coldAfter = bytes( + try capture(assistant, cold, at: boundary + 1).evaluationTargets) + let restoredAfter = bytes( + try capture(assistant, restored, at: boundary + 1).evaluationTargets) + XCTAssertEqual(coldAfter.count, 9) + XCTAssertEqual(restoredAfter.count, 9) + XCTAssertEqual( + restoredAfter, coldAfter, "first suffix P=\(boundary), depth=\(depth)") + XCTAssertTrue(restored.hasRequiredRestoredSuffix) + for request in [cold, restored] { + XCTAssertEqual(request.headInputCounts, (0 ..< 3).map { boundary - $0 }) + XCTAssertEqual( + request.cache?.nextTokenPositions, + [boundary + 1, boundary + 1, boundary + 1]) + XCTAssertEqual(request.committedInputCount, boundary + 1) + XCTAssertNil(request.pendingTokens) + XCTAssertNil(request.pendingHidden) + XCTAssertNil(request.pendingLastToken) + } + + let seedArray = argMax(output.logits[0, boundary], axis: -1).asType(.int32) + try withError { eval(seedArray) } + let seed = Int(seedArray.item(Int32.self)) + let feature = output.normalizedHiddenStates[0..., boundary ..< boundary + 1, 0...] + let restoredProposals = try proposals( + assistant, restored, seed: seed, hidden: feature, depth: depth) + let coldProposals = try proposals( + assistant, cold, seed: seed, hidden: feature, depth: depth) + XCTAssertEqual( + restoredProposals, coldProposals, "first drafts P=\(boundary), depth=\(depth)") + XCTAssertEqual(restored.headProposalCounts, (0 ..< 3).map { $0 < depth ? 1 : 0 }) + XCTAssertEqual(restored.headProposalCounts, cold.headProposalCounts) + let restoredRound = try XCTUnwrap(restored.round) + let coldRound = try XCTUnwrap(cold.round) + XCTAssertEqual(restoredRound.baseCount, boundary + 1) + XCTAssertEqual(restoredRound.baseCount, coldRound.baseCount) + XCTAssertEqual( + restoredRound.cache.consumedTokenCounts, coldRound.cache.consumedTokenCounts) + XCTAssertEqual( + restoredRound.cache.nextTokenPositions, coldRound.cache.nextTokenPositions) + XCTAssertEqual( + bytes(restoredRound.cache.innerState()), bytes(coldRound.cache.innerState())) + XCTAssertEqual(bytes(restoredRound.inputs), bytes(coldRound.inputs)) + XCTAssertEqual(restored.stagedInputCount, depth) + XCTAssertEqual(cold.stagedInputCount, depth) + assistant.discardRound(requestState: restored) + assistant.discardRound(requestState: cold) + try finish(assistant, restored) + try finish(assistant, cold) + assistant.releaseRequestState(restored) + assistant.releaseRequestState(cold) + } + assistant.releaseRequestState(donor) + } + } + + func testRetainedPhysicalRowBitCorruptionSurvivesFirstSuffixAndDraft() throws { + let (target, _, assistant) = try fixture() + defer { withExtendedLifetime(target) {} } + let tokens = prompt() + let boundary = 11 + let output = try target.forward(inputIDs: ids(tokens)) + let donor = try state(assistant, prompt: tokens) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, + range: 0 ..< boundary) + let checkpoint = try capture(assistant, donor, at: boundary) + let arrays = try XCTUnwrap(assistant.encodePrefixCheckpoint(checkpoint)) + let original = bytes(arrays) + XCTAssertEqual(arrays.count, 9) + XCTAssertEqual(arrays[0].dtype, .bfloat16) + XCTAssertEqual(arrays[0].shape, [1, 1, 3, 4]) + let metadata = arrays[8].asArray(Int64.self) + let window = arrays[0].dim(2) + let index = Int(metadata[5]) + XCTAssertTrue((1 ... window).contains(index)) + let retainedRow = (index - 1) % window + XCTAssertNotEqual(retainedRow, index % window) // next suffix write + XCTAssertNotEqual(retainedRow, (index + 1) % window) // first depth-0 draft write + let byteOffset = retainedRow * arrays[0].dim(3) * MemoryLayout.size + var changedKeyBytes = original[0] + let changedByte = try XCTUnwrap( + changedKeyBytes.indices.contains(byteOffset) ? byteOffset : nil) + changedKeyBytes[changedByte] ^= 1 + var changedArrays = arrays + // A transport-oracle negative only, not a model-generated value or a + // bypass of Common's authentication. Raw bytes avoid any BF16 cast. + changedArrays[0] = try withError { + MLXArray(changedKeyBytes, arrays[0].shape, dtype: .bfloat16) + } + try withError { eval(changedArrays) } + let corruptedCheckpoint = try XCTUnwrap( + assistant.decodePrefixCheckpoint( + tensors: changedArrays, prefixTokens: Array(tokens.prefix(boundary)))) + let clean = try XCTUnwrap(assistant.restorePrefixCheckpoint(checkpoint) as? MiMoV26MTPState) + let corrupted = try XCTUnwrap( + assistant.restorePrefixCheckpoint(corruptedCheckpoint) as? MiMoV26MTPState) + for request in [clean, corrupted] { + try assistant.configureRequestState(request, maximumSequenceLength: 64) + try assistant.installPrefixCaptureContext(requestState: request, promptTokens: tokens) + try finish(assistant, request) + } + var changedBefore = original + changedBefore[0] = changedKeyBytes + XCTAssertEqual( + bytes(try capture(assistant, clean, at: boundary).evaluationTargets), original) + XCTAssertEqual( + bytes(try capture(assistant, corrupted, at: boundary).evaluationTargets), changedBefore) + XCTAssertNotEqual(changedBefore, original) + + for request in [clean, corrupted] { + try observe( + assistant, request, tokens: tokens, hidden: output.normalizedHiddenStates, + range: boundary ..< boundary + 1) + } + let cleanAfter = bytes(try capture(assistant, clean, at: boundary + 1).evaluationTargets) + let corruptedAfter = bytes( + try capture(assistant, corrupted, at: boundary + 1).evaluationTargets) + var expectedAfter = cleanAfter + expectedAfter[0][changedByte] ^= 1 + XCTAssertEqual(corruptedAfter, expectedAfter) // exactly the retained bit, all nine tensors + XCTAssertNotEqual(corruptedAfter, cleanAfter) + + let seedArray = argMax(output.logits[0, boundary], axis: -1).asType(.int32) + try withError { eval(seedArray) } + let seed = Int(seedArray.item(Int32.self)) + let feature = output.normalizedHiddenStates[0..., boundary ..< boundary + 1, 0...] + _ = try proposals(assistant, clean, seed: seed, hidden: feature, depth: 1) + _ = try proposals(assistant, corrupted, seed: seed, hidden: feature, depth: 1) + let cleanRound = try XCTUnwrap(clean.round) + let corruptedRound = try XCTUnwrap(corrupted.round) + let cleanDraftBytes = bytes(cleanRound.cache.innerState()) + let corruptedDraftBytes = bytes(corruptedRound.cache.innerState()) + var expectedDraftBytes = cleanDraftBytes + expectedDraftBytes[0][changedByte] ^= 1 + XCTAssertEqual(corruptedDraftBytes, expectedDraftBytes) + XCTAssertNotEqual(corruptedDraftBytes, cleanDraftBytes) + // No assertion that argmax must change: exact state is the discriminator. + XCTAssertEqual(bytes(checkpoint.evaluationTargets), original) + assistant.discardRound(requestState: clean) + assistant.discardRound(requestState: corrupted) + try finish(assistant, clean) + try finish(assistant, corrupted) + assistant.releaseRequestState(clean) + assistant.releaseRequestState(corrupted) + assistant.releaseRequestState(donor) + } + + func testDonorAdvanceDoesNotMutatePartialOrWrappedPublishedPrefix() throws { + let (target, _, assistant) = try fixture() + defer { withExtendedLifetime(target) {} } + let tokens = prompt() + let output = try target.forward(inputIDs: ids(tokens)) + for boundary in [4, 11] { + let donor = try state(assistant, prompt: tokens) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, + range: 0 ..< boundary) + let checkpoint = try capture(assistant, donor, at: boundary) + let published = bytes(try XCTUnwrap(assistant.encodePrefixCheckpoint(checkpoint))) + XCTAssertEqual(published.count, 9) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, + range: boundary ..< boundary + 1) + XCTAssertEqual(bytes(checkpoint.evaluationTargets), published) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, + range: boundary + 1 ..< tokens.count) + XCTAssertEqual(donor.committedInputCount, tokens.count) + XCTAssertEqual(checkpoint.targetInputCount, boundary) + XCTAssertEqual(bytes(checkpoint.evaluationTargets), published) + + let restored = try XCTUnwrap( + assistant.restorePrefixCheckpoint(checkpoint) as? MiMoV26MTPState) + try assistant.configureRequestState(restored, maximumSequenceLength: 64) + try assistant.installPrefixCaptureContext(requestState: restored, promptTokens: tokens) + try finish(assistant, restored) + XCTAssertEqual( + bytes(try capture(assistant, restored, at: boundary).evaluationTargets), published) + XCTAssertEqual(restored.headInputCounts, (0 ..< 3).map { boundary - $0 - 1 }) + XCTAssertEqual(restored.cache?.nextTokenPositions, [boundary, boundary, boundary]) + XCTAssertFalse(restored.hasRequiredRestoredSuffix) + assistant.releaseRequestState(restored) + assistant.releaseRequestState(donor) + } + } + + func testCancelledOffToSideAdoptionLeavesDonorAndCheckpointUnchanged() throws { + let (target, _, assistant) = try fixture() + let tokens = prompt() + let output = try target.forward(inputIDs: ids(tokens)) + let donor = try state(assistant, prompt: tokens) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, range: 0 ..< 11 + ) + let checkpoint = try capture(assistant, donor) + let originalCache = bytes(donor.cache!.innerState()) + let originalCheckpoint = bytes(checkpoint.evaluationTargets) + let candidate = try XCTUnwrap( + assistant.restorePrefixCheckpoint(checkpoint) as? MiMoV26MTPState) + XCTAssertTrue(candidate.hasUnmeasuredResidency) + XCTAssertFalse(candidate === donor) + // Component-side cancellation/target-veto rollback: no candidate is + // published, and it is disposed ONLY after its actual native completion. + try finish(assistant, candidate) + assistant.releaseRequestState(candidate) + XCTAssertTrue(candidate.isReleased) + XCTAssertEqual(candidate.materializedBytes, 0) // owner bookkeeping, not physical-free proof + XCTAssertEqual(bytes(donor.cache!.innerState()), originalCache) + XCTAssertEqual(bytes(checkpoint.evaluationTargets), originalCheckpoint) + XCTAssertEqual(donor.observedCount, 11) + let retry = try XCTUnwrap(assistant.restorePrefixCheckpoint(checkpoint) as? MiMoV26MTPState) + try finish(assistant, retry) + XCTAssertEqual(retry.headInputCounts, [10, 9, 8]) + assistant.releaseRequestState(retry) + assistant.releaseRequestState(donor) + } + + func testCodecTransportPreservesBF16NonfiniteAndSubnormalPayloadBits() throws { + let (target, _, assistant) = try fixture() + let tokens = prompt() + let output = try target.forward(inputIDs: ids(tokens)) + let donor = try state(assistant, prompt: tokens) + try observe( + assistant, donor, tokens: tokens, hidden: output.normalizedHiddenStates, range: 0 ..< 11 + ) + let checkpoint = try capture(assistant, donor) + var arrays = checkpoint.evaluationTargets + let patterns: [UInt16] = [0x0001, 0x8000, 0x7fc3, 0xff80, 0x3f80, 0x8001] + // Codec transport test, not a claim these artificial values were + // generated by the model. The real model cases above remain separate. + for index in 0 ... 6 { + arrays[index] = MLXArray( + (0 ..< arrays[index].size).map { patterns[$0 % patterns.count] }, + arrays[index].shape + ).view(dtype: .bfloat16) + } + try withError { eval(arrays) } + let expected = bytes(arrays) + let imported = try XCTUnwrap( + assistant.decodePrefixCheckpoint( + tensors: arrays, prefixTokens: Array(tokens.prefix(11)))) + let restored = try XCTUnwrap( + assistant.restorePrefixCheckpoint(imported) as? MiMoV26MTPState) + try assistant.configureRequestState(restored, maximumSequenceLength: 64) + try assistant.installPrefixCaptureContext(requestState: restored, promptTokens: tokens) + try finish(assistant, restored) + let recaptured = try capture(assistant, restored) + XCTAssertEqual(bytes(recaptured.evaluationTargets), expected) + assistant.releaseRequestState(restored) + assistant.releaseRequestState(donor) + } + + func testBoundedPlanPricesContextWitnessCopiesAndOverflowRefuses() throws { + let config = try MiMoV26MTPChecks.config() + let spec = try XCTUnwrap( + MiMoV26MTPAssistant.boundedRequestAllocation( + configuration: config, + limits: .init(maximumPrefillTokens: 16, maximumDraftTokens: 3))) + XCTAssertGreaterThanOrEqual(spec.hostBytes, (64 << 10) + 32 * config.maxPositionEmbeddings) + XCTAssertTrue( + spec.resident.contains( + .init(logicalBytes: 4 * config.maxPositionEmbeddings, allocationCount: 3))) + XCTAssertTrue( + spec.working.contains( + .init(logicalBytes: 4 * config.maxPositionEmbeddings, allocationCount: 4))) + XCTAssertNil( + MiMoV26MTPAssistant.boundedRequestAllocation( + configuration: config, + limits: .init(maximumPrefillTokens: Int.max, maximumDraftTokens: 3))) + let (target, predictor) = try MiMoV26MTPChecks.fixture() // FP32 remains valid MTP, not this BF16 codec + let floatAssistant = try MiMoV26MTPAssistant(target: target, predictor: predictor) + XCTAssertNil(floatAssistant.prefixCheckpointTensorDescriptors(targetInputCount: 11)) + let request = try state(floatAssistant) + XCTAssertThrowsError( + try floatAssistant.installPrefixCaptureContext( + requestState: request, promptTokens: prompt())) + floatAssistant.releaseRequestState(request) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26MTPTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26MTPTests.swift new file mode 100644 index 0000000000..45daf5aa1d --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26MTPTests.swift @@ -0,0 +1,806 @@ +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +@testable import MLXLLM + +#if !MIMO_MTP_COMPONENT_PROBE + import XCTest +#endif + +// Prepared for the coordinator's exclusive native lane. This worker did not +// build or run these numerical cases; syntax and metadata checks are separate. +// Shared tiny fixture/oracle for the request-lifecycle tests. Existing 17 +// component cases below remain unchanged. +enum MiMoV26MTPChecks { + struct Failure: Error { let message: String } + static func require(_ condition: Bool, _ message: String) throws { + if !condition { throw Failure(message: message) } + } + static func config() throws -> MiMoV26Configuration { + try JSONDecoder().decode( + MiMoV26Configuration.self, + from: Data( + """ + {"model_type":"mimo_v2","architectures":["MiMoV2ForCausalLM"], + "hidden_size":4,"intermediate_size":8,"moe_intermediate_size":4, + "vocab_size":32,"num_hidden_layers":2,"max_position_embeddings":64, + "sliding_window_size":3,"sliding_window":3,"num_nextn_predict_layers":3, + "hybrid_layer_pattern":[0,1],"moe_layer_freq":[0,1], + "partial_rotary_factor":1,"attention_value_scale":0.707, + "layernorm_epsilon":0.000001,"attention_projection_layout":"split", + "moe_router_dtype":"float32","hidden_act":"silu","dtype":"float32", + "attention_bias":false,"tie_word_embeddings":false,"attention_dropout":0, + "scoring_func":"sigmoid","topk_method":"noaux_tc","n_routed_experts":2, + "num_experts_per_tok":1,"n_group":1,"topk_group":1,"norm_topk_prob":true, + "n_shared_experts":null,"routed_scaling_factor":null, + "num_attention_heads":2,"num_key_value_heads":1,"head_dim":4,"v_head_dim":2, + "swa_num_attention_heads":2,"swa_num_key_value_heads":1,"swa_head_dim":4, + "swa_v_head_dim":2,"rope_theta":10000000,"swa_rope_theta":10000, + "add_full_attention_sink_bias":false,"add_swa_attention_sink_bias":true, + "eos_token_id":3,"pad_token_id":0} + """.utf8)) + } + static func fixtureWeights(_ model: Module, prefix: String = "") -> [String: MLXArray] { + Dictionary( + uniqueKeysWithValues: model.parameters().flattened().map { key, value in + let salt = key.utf8.reduce(0) { ($0 * 31 + Int($1)) % 997 } + let values = (0 ..< value.size).map { i -> Float in + if key.contains("norm.weight") { return 0.8 + Float((salt + i) % 9) * 0.03 } + return sin(Float(i * 7 + salt)) * 0.2 + } + return (prefix + key, MLXArray(values, value.shape)) + }) + } + static func fixture() throws -> (MiMoV26TextModel, MiMoV26MTP) { + let target = try MiMoV26TextModel(config()) + try target.update(parameters: .unflattened(fixtureWeights(target)), verify: .all) + let mtp = try MiMoV26MTP(target: target) + try mtp.loadConvertedWeights(fixtureWeights(mtp, prefix: "mtp.")) + return (target, mtp) + } + + // Small actual-storage-profile fixture: BF16 activations/norms and all24 + // trained predictor projections affine4/group64, not the trunk MXFP4. + // Synthetic packed nibbles are constructed directly; expected dense + // weights never use MLX quantize/dequantize as their oracle. + static func affineConfiguration(omit: String? = nil, conflict: Bool = false) throws + -> MiMoV26Configuration + { + var object = + try JSONSerialization.jsonObject(with: JSONEncoder().encode(config())) as! [String: Any] + object["hidden_size"] = 64 + object["intermediate_size"] = 128 + object["moe_intermediate_size"] = 64 + object["dtype"] = "bfloat16" + object["moe_router_dtype"] = "bfloat16" + for key in ["head_dim", "swa_head_dim"] { object[key] = 64 } + for key in ["v_head_dim", "swa_v_head_dim"] { object[key] = 32 } + var policies: [String: Any] = ["mode": "mxfp4", "bits": 4, "group_size": 32] + for depth in 0 ..< 3 { + for suffix in [ + "eh_proj", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", + "self_attn.o_proj", "mlp.gate_proj", "mlp.up_proj", "mlp.down_proj", + ] { + let key = "mtp.layers.\(depth).\(suffix)" + if key != omit { policies[key] = ["mode": "affine", "bits": 4, "group_size": 64] } + } + } + if conflict { + policies["language_model.mtp.layers.0.eh_proj"] = [ + "mode": "mxfp4", "bits": 4, "group_size": 32, + ] + } + object["quantization"] = policies + return try JSONDecoder().decode( + MiMoV26Configuration.self, + from: JSONSerialization.data(withJSONObject: object)) + } + + static func packedFixture(_ mtp: MiMoV26MTP, expectedProjections: Int = 24) throws + -> (stored: [String: MLXArray], expanded: [String: MLXArray]) + { + var stored = fixtureWeights(mtp, prefix: "mtp.").mapValues { $0.asType(.bfloat16) } + var expanded: [String: MLXArray] = [:] + let projections = mtp.leafModules().flattened().compactMap { + name, module -> (String, QuantizedLinear)? in + guard let linear = module as? QuantizedLinear else { return nil } + return (name, linear) + } + try require( + projections.count == expectedProjections, "declared affine projection count mismatch") + for (name, linear) in projections { + try require( + linear.mode == .affine && linear.bits == 4 && linear.groupSize == 64, + "trunk quantization leaked into predictor") + let (rows, columns) = linear.shape + let groups = columns / 64 + var packed = [UInt32](repeating: 0, count: rows * columns / 8) + var dense = [Float](repeating: 0, count: rows * columns) + var scales = [Float](repeating: 0, count: rows * groups) + let offsets = [Float](repeating: -0.25, count: rows * groups) + for row in 0 ..< rows { + for column in 0 ..< columns { + let code = UInt32((row * 3 + column * 5) % 16) + let group = row * groups + column / 64 + scales[group] = Float(group % 3 + 1) / 64 + packed[row * (columns / 8) + column / 8] |= code << UInt32((column % 8) * 4) + dense[row * columns + column] = Float(code) * scales[group] + offsets[group] + } + } + let prefix = "mtp." + name + stored[prefix + ".weight"] = MLXArray(packed, [rows, columns / 8]) + stored[prefix + ".scales"] = MLXArray(scales, [rows, groups]).asType(.bfloat16) + stored[prefix + ".biases"] = MLXArray(offsets, [rows, groups]).asType(.bfloat16) + expanded[name] = MLXArray(dense, [rows, columns]).asType(.bfloat16) + } + return (stored, expanded) + } + static func targetOutput(_ target: MiMoV26TextModel, length: Int = 9) throws + -> MiMoV26TextOutput + { + try target.forward(inputIDs: MLXArray((1 ... length).map(Int32.init), [1, length])) + } + static func targetFeatures(_ target: MiMoV26TextModel, length: Int = 9) throws + -> MiMoV26MTPFeatures + { + try MiMoV26MTPFeatures(targetOutput: targetOutput(target, length: length), target: target) + } + static func near( + _ actual: MLXArray, _ expected: MLXArray, _ name: String, + tolerance: Float = 8e-5 + ) throws { + eval(actual, expected) + try require(actual.shape == expected.shape, "\(name): shape mismatch") + let error = abs(actual - expected).max().item(Float.self) + try require(error.isFinite && error <= tolerance, "\(name): error=\(error)") + } + static func rejected(_ operation: () throws -> Void) throws { + do { + try operation() + throw Failure(message: "invalid MTP operation accepted") + } catch is MiMoV26MTPError {} + } + + // Independent scalar CPU math: no MLX norm, attention, RoPE, softmax, + // activation, cache or concatenation operation forms expected outputs. + static func linear(_ x: [Float], _ layer: Linear) -> [Float] { + let weight = layer.weight.asArray(Float.self) + var y = [Float](repeating: 0, count: layer.weight.dim(0)) + for row in y.indices { + for column in x.indices { y[row] += weight[row * x.count + column] * x[column] } + } + return y + } + static func norm(_ x: [Float], _ layer: RMSNorm, eps: Float) -> [Float] { + let weights = layer.weight.asArray(Float.self) + let scale = 1 / sqrt(x.reduce(0) { $0 + $1 * $1 } / Float(x.count) + eps) + return x.indices.map { x[$0] * scale * weights[$0] } + } + static func reference( + _ head: MiMoV26MTPHead, hidden: [[Float]], tokens: [Int], + target: MiMoV26TextModel, firstTokenPosition: Int, + reverseConcatenation: Bool = false + ) -> (hidden: [[Float]], logits: [Float]) { + let config = target.configuration + let width = config.hiddenSize + let eps = Float(config.layernormEpsilon) + let geometry = config.slidingAttention + let table = target.model.embedTokens.weight.asArray(Float.self) + var projected: [[Float]] = [] + var queries: [[Float]] = [] + var keys: [[Float]] = [] + var values: [[Float]] = [] + func rotate(_ vector: inout [Float], heads: Int, position: Int) { + let half = geometry.rotaryDimensions / 2 + for head in 0 ..< heads { + for dimension in 0 ..< half { + let phase = + Float(position) + / pow( + Float(geometry.ropeTheta), + Float(dimension * 2) / Float(geometry.rotaryDimensions)) + let a = head * geometry.headDim + dimension + let b = a + half + let first = vector[a] + let second = vector[b] + vector[a] = first * cos(phase) - second * sin(phase) + vector[b] = first * sin(phase) + second * cos(phase) + } + } + } + for row in hidden.indices { + let embedding = Array(table[tokens[row] * width ..< (tokens[row] + 1) * width]) + let e = norm(embedding, head.enorm, eps: eps) + let h = norm(hidden[row], head.hnorm, eps: eps) + let projection = linear(reverseConcatenation ? h + e : e + h, head.ehProjection) + projected.append(projection) + let normalized = norm(projection, head.inputNorm, eps: eps) + var q = linear(normalized, head.attention.qProj) + var k = linear(normalized, head.attention.kProj) + rotate(&q, heads: geometry.queryHeads, position: firstTokenPosition + row) + rotate(&k, heads: geometry.keyValueHeads, position: firstTokenPosition + row) + queries.append(q) + keys.append(k) + values.append( + linear(normalized, head.attention.vProj).map { + $0 * Float(config.attentionValueScale) + }) + } + let sinks = head.attention.attentionSinkBias!.asArray(Float.self) + var result: [[Float]] = [] + var logits: [Float] = [] + for row in hidden.indices { + var attended = [Float](repeating: 0, count: geometry.queryHeads * geometry.valueHeadDim) + let start = max(0, row - config.slidingWindow + 1) + for queryHead in 0 ..< geometry.queryHeads { + let kv = queryHead / (geometry.queryHeads / geometry.keyValueHeads) + var scores: [Float] = [] + for keyRow in start ... row { + var dot: Float = 0 + for d in 0 ..< geometry.headDim { + dot += + queries[row][queryHead * geometry.headDim + d] + * keys[keyRow][kv * geometry.headDim + d] + } + scores.append(dot / sqrt(Float(geometry.headDim))) + } + let maximum = max(scores.max()!, sinks[queryHead]) + let probabilities = scores.map { exp($0 - maximum) } + let denominator = probabilities.reduce(0, +) + exp(sinks[queryHead] - maximum) + for (index, keyRow) in (start ... row).enumerated() { + for d in 0 ..< geometry.valueHeadDim { + attended[queryHead * geometry.valueHeadDim + d] += + probabilities[index] / denominator + * values[keyRow][kv * geometry.valueHeadDim + d] + } + } + } + let attentionOutput = linear(attended, head.attention.oProj) + let residual = zip(projected[row], attentionOutput).map(+) + let normalized = norm(residual, head.preMLPNorm, eps: eps) + let gate = linear(normalized, head.mlp.gateProj) + let up = linear(normalized, head.mlp.upProj) + let activated = gate.indices.map { gate[$0] / (1 + exp(-gate[$0])) * up[$0] } + let down = linear(activated, head.mlp.downProj) + let output = norm(zip(residual, down).map(+), head.finalNorm, eps: eps) + result.append(output) + if let readout = target.lmHead { + logits += linear(output, readout) + } else { + for token in 0 ..< config.vocabularySize { + logits.append( + output.indices.reduce(0) { $0 + output[$1] * table[token * width + $1] }) + } + } + } + return (result, logits) + } + + static func cases() -> [(String, () throws -> Void)] { + [ + ( + "actual affine4 group64 BF16 predictor format loads all90 tensors and executes all3 heads", + { + let target = try MiMoV26TextModel(affineConfiguration()) + let parameters = fixtureWeights(target).mapValues { $0.asType(.bfloat16) } + try target.update(parameters: .unflattened(parameters), verify: .all) + let mtp = try MiMoV26MTP(target: target) + let fixture = try packedFixture(mtp) + try require(fixture.stored.count == 90, "native predictor tensor count changed") + var bad = fixture.stored + bad["mtp.layers.0.eh_proj.scales"] = bad["mtp.layers.0.eh_proj.scales"]!.asType( + .float32) + try rejected { try mtp.loadConvertedWeights(bad) } + try require(!mtp.isLoaded, "wrong-precision scales loaded") + try mtp.loadConvertedWeights(fixture.stored) + for (name, module) in mtp.leafModules().flattened() { + guard let linear = module as? QuantizedLinear else { continue } + let expected = fixture.expanded[name]! + let columns = linear.shape.1 + let input = MLXArray( + (0 ..< (2 * columns)).map { Float(($0 * 7) % 17 - 8) / 32 }, + [2, columns] + ).asType(.bfloat16) + try require( + linear.weight.asArray(UInt32.self) + == fixture.stored["mtp." + name + ".weight"]!.asArray(UInt32.self), + "packed predictor codes changed on load") + try near( + linear(input).asType(.float32), + matmul(input, expected.T).asType(.float32), + "native affine projection \(name)", tolerance: 0.00390625) + } + let features = try targetFeatures(target, length: 3) + let firstCache = try mtp.newCache() + let repeatCache = try mtp.newCache() + for depth in 0 ..< 3 { + let ids = MLXArray( + [Int32(2 + depth), Int32(3 + depth), Int32(4 + depth)], [1, 3]) + let result = try mtp.forward( + depth: depth, features: features, inputIDs: ids, target: target, + cache: firstCache) + let repeated = try mtp.forward( + depth: depth, features: features, inputIDs: ids, target: target, + cache: repeatCache) + try require( + result.logits.dtype == .bfloat16 && result.logits.shape == [1, 3, 32], + "native output contract") + try near( + result.logits.asType(.float32), repeated.logits.asType(.float32), + "affine deterministic repeat", tolerance: 0) + } + try require( + firstCache.nextTokenPositions == [4, 5, 6], "affine head history mismatch") + } + ), + ( + "MTP never inherits MXFP4 for a missing or conflicting affine projection policy", + { + for candidate in [ + try affineConfiguration(omit: "mtp.layers.2.mlp.down_proj"), + try affineConfiguration(conflict: true), + ] { + let target = try MiMoV26TextModel(candidate) + try rejected { _ = try MiMoV26MTP(target: target) } + } + } + ), + ( + "an explicitly unquantized first head does not break later affine head replacement", + { + var object = + try JSONSerialization.jsonObject( + with: JSONEncoder().encode(affineConfiguration())) as! [String: Any] + var policies = object["quantization"] as! [String: Any] + for key in Array(policies.keys) where key.hasPrefix("mtp.layers.0.") { + policies[key] = false + } + object["quantization"] = policies + let configuration = try JSONDecoder().decode( + MiMoV26Configuration.self, + from: JSONSerialization.data(withJSONObject: object)) + let target = try MiMoV26TextModel(configuration) + try target.update( + parameters: .unflattened( + fixtureWeights(target).mapValues { $0.asType(.bfloat16) }), verify: .all + ) + let mtp = try MiMoV26MTP(target: target) + let stored = try packedFixture(mtp, expectedProjections: 16).stored + try require(stored.count == 74, "preserved first-head tensor closure") + try require( + mtp.layers[0].leafModules().flattened().allSatisfy { !($0.1 is Quantized) }, + "first head was silently quantized") + try mtp.loadConvertedWeights(stored) + let features = try targetFeatures(target, length: 1) + let cache = try mtp.newCache() + for depth in 0 ..< 3 { + let output = try mtp.forward( + depth: depth, features: features, + inputIDs: MLXArray([Int32(depth + 2)], [1, 1]), target: target, + cache: cache) + eval(output.logits) + try require( + output.logits.asType(.float32).asArray(Float.self).allSatisfy( + \.isFinite), + "mixed head profile failed") + } + } + ), + ( + "fresh positioned-cache copies preserve empty history without invoking state setter", + { + let original = MiMoV26MTPPositionedCache(window: 3, firstPosition: 2) + let copy = original.copy() + try require( + copy.state.isEmpty && copy.innerState().isEmpty, + "fresh copy allocated or fabricated cache state") + try require( + original.offset == 2 && copy.offset == 2 && copy.maxSize == 3, + "fresh copy changed absolute position or window") + try require(copy.metaState == original.metaState, "fresh ring metadata changed") + } + ), + ( + "all three distinct heads match independent complete scalar oracle", + { + let (target, mtp) = try fixture() + let length = 9 + let features = try targetFeatures(target, length: length) + let flat = features.normalizedHiddenStates.asArray(Float.self) + let expectedHidden = (0 ..< length).map { Array(flat[$0 * 4 ..< ($0 + 1) * 4]) } + let cache = try mtp.newCache() + var firstValues: [Float] = [] + for depth in 0 ..< 3 { + let tokens = (0 ..< length).map { $0 + depth + 2 } + let expected = reference( + mtp.layers[depth], hidden: expectedHidden, tokens: tokens, + target: target, firstTokenPosition: depth + 1) + let actual = try mtp.forward( + depth: depth, features: features, + inputIDs: MLXArray(tokens.map(Int32.init), [1, length]), target: target, + cache: cache) + try near( + actual.normalizedHiddenStates, + MLXArray(expected.hidden.flatMap { $0 }, [1, length, 4]), + "head\(depth) hidden") + try near( + actual.logits, MLXArray(expected.logits, [1, length, 32]), + "head\(depth) logits") + try require( + actual.features.provenance == .predictorPostNorm(depth: depth), + "missing output provenance") + firstValues.append(actual.logits[0, 0, 0].item(Float.self)) + } + try require( + Set(firstValues).count == 3, "fixture failed to distinguish predictor heads" + ) + try require( + cache.nextTokenPositions == [10, 11, 12], "depth-shifted offsets are wrong") + } + ), + ( + "embedding-first concatenation has a discriminating negative oracle", + { + let (target, mtp) = try fixture() + let features = try targetFeatures(target, length: 1) + let hidden = [features.normalizedHiddenStates.asArray(Float.self)] + let correct = reference( + mtp.layers[0], hidden: hidden, tokens: [2], target: target, + firstTokenPosition: 1) + let reversed = reference( + mtp.layers[0], hidden: hidden, tokens: [2], target: target, + firstTokenPosition: 1, reverseConcatenation: true) + let difference = zip(correct.logits, reversed.logits).map { abs($0 - $1) } + .max()! + try require(difference > 1e-3, "oracle cannot distinguish concatenation order") + } + ), + ( + "chunked append agrees across sliding-window wrap", + { + let (target, mtp) = try fixture() + let output = try targetOutput(target) + let features = try MiMoV26MTPFeatures(targetOutput: output, target: target) + let allIDs = MLXArray((2 ... 10).map(Int32.init), [1, 9]) + let expected = try mtp.forward( + depth: 0, features: features, inputIDs: allIDs, + target: target, cache: mtp.newCache()) + let cache = try mtp.newCache() + var pieces: [MLXArray] = [] + for range in [0 ..< 2, 2 ..< 5, 5 ..< 8, 8 ..< 9] { + let segment = try MiMoV26MTPFeatures( + targetOutput: output, target: target, range: range) + pieces.append( + try mtp.forward( + depth: 0, features: segment, inputIDs: allIDs[0..., range], + target: target, cache: cache + ).logits) + } + try near(concatenated(pieces, axis: 1), expected.logits, "window wrap") + eval(cache) + try require( + cache.consumedTokenCounts == [9, 0, 0], "head caches are not independent") + try require( + cache.stateShapesByDepth[0].map { $0.last! } == [4, 2], + "unequal cache widths were changed") + } + ), + ( + "strict loading rejects absent head norm sink and extra keys before mutation", + { + let target = try MiMoV26TextModel(config()) + let mtp = try MiMoV26MTP(target: target) + let complete = fixtureWeights(mtp, prefix: "mtp.") + for key in [ + "mtp.layers.2.eh_proj.weight", "mtp.layers.1.pre_mlp_layernorm.weight", + "mtp.layers.0.self_attn.attention_sink_bias", + ] { + var bad = complete + bad.removeValue(forKey: key) + try rejected { try mtp.loadConvertedWeights(bad) } + try require(!mtp.isLoaded, "incomplete predictor set became executable") + } + var extra = complete + extra["mtp.lm_head.weight"] = MLXArray.zeros([1]) + try rejected { try mtp.loadConvertedWeights(extra) } + var wrongShape = complete + wrongShape["mtp.layers.2.eh_proj.weight"] = MLXArray.zeros([1]) + try rejected { try mtp.loadConvertedWeights(wrongShape) } + try mtp.loadConvertedWeights(complete) + try require(mtp.isLoaded, "complete trained fixture did not load") + } + ), + ( + "borrowed target parameters never appear in predictor tree", + { + let (target, mtp) = try fixture() + let names = mtp.parameters().flattened().map(\.0) + try require( + names.allSatisfy { $0.hasPrefix("layers.") }, + "target registered as predictor child") + try require( + names.filter { $0.hasSuffix("pre_mlp_layernorm.weight") }.count == 3, + "trained norm spelling changed") + try require( + !names.contains { $0.contains("embed_tokens") || $0.contains("lm_head") }, + "readout was duplicated") + try require(target.model.embedTokens.weight.shape == [32, 4], "target mutated") + } + ), + ( + "feature provenance depth ownership and history fail before cache writes", + { + let (target, mtp) = try fixture() + let features = try targetFeatures(target, length: 1) + let ids = MLXArray([Int32(2)], [1, 1]) + let cache = try mtp.newCache() + for depth in [-1, 3] { + try rejected { + _ = try mtp.forward( + depth: depth, features: features, inputIDs: ids, target: target, + cache: cache) + } + } + let (otherTarget, other) = try fixture() + try withExtendedLifetime(otherTarget) { + let otherCache = try other.newCache() + try rejected { + _ = try mtp.forward( + depth: 0, features: features, inputIDs: ids, target: target, + cache: otherCache) + } + } + let targetCache = target.newCache() + _ = try target.forward( + inputIDs: MLXArray([Int32(1)], [1, 1]), cache: targetCache) + let displacedOutput = try target.forward(inputIDs: ids, cache: targetCache) + let displaced = try MiMoV26MTPFeatures( + targetOutput: displacedOutput, target: target) + try rejected { + _ = try mtp.forward( + depth: 0, features: displaced, inputIDs: ids, target: target, + cache: cache) + } + try require( + cache.consumedTokenCounts == [0, 0, 0], "failed preflight mutated a cache") + } + ), + ( + "invalid IDs dimensions dtype and positions fail before cache writes", + { + let (target, mtp) = try fixture() + let features = try targetFeatures(target, length: 1) + let cache = try mtp.newCache() + for ids in [ + MLXArray([Int32(-1)], [1, 1]), MLXArray([Int32(32)], [1, 1]), + MLXArray([Float(2)], [1, 1]), MLXArray([Int32(2), Int32(3)], [1, 2]), + ] { + try rejected { + _ = try mtp.forward( + depth: 0, features: features, inputIDs: ids, target: target, + cache: cache) + } + } + for hidden in [ + MLXArray.zeros([1, 1, 3]), MLXArray.zeros([1, 1, 4], dtype: .float16), + ] { + // Internal synthetic metadata intentionally violates the + // target-output invariant; public callers cannot mint it. + let invalidOutput = MiMoV26TextOutput( + logits: MLXArray.zeros([1]), + normalizedHiddenStates: hidden, layerFeatures: [:], firstPosition: 0, + ownerIdentity: target.identity) + try rejected { + let bad = try MiMoV26MTPFeatures( + targetOutput: invalidOutput, target: target) + _ = try mtp.forward( + depth: 0, features: bad, inputIDs: MLXArray([Int32(2)], [1, 1]), + target: target, cache: cache) + } + } + for position in [-1, 63, Int.max] { + // Explicit internal negative fixture, never a public + // promise that callers may choose actual output positions. + let invalidOutput = MiMoV26TextOutput( + logits: MLXArray.zeros([1]), + normalizedHiddenStates: features.normalizedHiddenStates, + layerFeatures: [:], + firstPosition: position, ownerIdentity: target.identity) + try rejected { + let bad = try MiMoV26MTPFeatures( + targetOutput: invalidOutput, target: target) + _ = try mtp.forward( + depth: 0, features: bad, inputIDs: MLXArray([Int32(2)], [1, 1]), + target: target, cache: cache) + } + } + try require( + cache.consumedTokenCounts == [0, 0, 0], "invalid input appended history") + } + ), + ( + "an actual target output cannot be relabeled to a different target", + { + let (targetA, mtp) = try fixture() + let outputA = try targetOutput(targetA, length: 2) + let targetB = try MiMoV26TextModel(config()) + let cache = try mtp.newCache() + try rejected { + _ = try MiMoV26MTPFeatures(targetOutput: outputA, target: targetB) + } + try require( + cache.consumedTokenCounts == [0, 0, 0], "owner mismatch mutated cache") + } + ), + ( + "target feature ranges reject empty negative oversized and overflow bounds", + { + let (target, mtp) = try fixture() + let output = try targetOutput(target, length: 4) + let cache = try mtp.newCache() + for range in [0 ..< 0, -1 ..< 1, 0 ..< 5, 4 ..< 5, (Int.max - 1) ..< Int.max] { + try rejected { + _ = try MiMoV26MTPFeatures( + targetOutput: output, target: target, range: range) + } + } + try require( + cache.consumedTokenCounts == [0, 0, 0], + "invalid feature range mutated cache") + } + ), + ( + "feature positions derive from real cached target outputs and selected rows", + { + let (target, mtp) = try fixture() + let targetCache = target.newCache() + _ = try target.forward( + inputIDs: MLXArray([Int32(1), 2, 3], [1, 3]), cache: targetCache) + let output = try target.forward( + inputIDs: MLXArray([Int32(4), 5, 6, 7], [1, 4]), cache: targetCache) + let full = try MiMoV26MTPFeatures(targetOutput: output, target: target) + let selected = try MiMoV26MTPFeatures( + targetOutput: output, target: target, range: 1 ..< 3) + try require( + output.firstPosition == 3 && full.firstPosition == 3 + && selected.firstPosition == 4, + "cached target output position was not retained") + try near( + selected.normalizedHiddenStates, + output.normalizedHiddenStates[0..., 1 ..< 3, 0...], + "selected target rows") + let emptyHistory = try mtp.newCache() + try rejected { + _ = try mtp.forward( + depth: 0, features: selected, + inputIDs: MLXArray([Int32(6), 7], [1, 2]), target: target, + cache: emptyHistory) + } + try require( + emptyHistory.consumedTokenCounts == [0, 0, 0], + "invented predictor history was accepted") + } + ), + ( + "reload invalidates old predictor cache and uninitialized heads refuse forward", + { + let target = try MiMoV26TextModel(config()) + try target.update( + parameters: .unflattened(fixtureWeights(target)), verify: .all) + let mtp = try MiMoV26MTP(target: target) + let features = try targetFeatures(target, length: 1) + let ids = MLXArray([Int32(2)], [1, 1]) + try rejected { + _ = try mtp.forward( + depth: 0, features: features, inputIDs: ids, target: target, + cache: mtp.newCache()) + } + let weights = fixtureWeights(mtp, prefix: "mtp.") + try mtp.loadConvertedWeights(weights) + let stale = try mtp.newCache() + try mtp.loadConvertedWeights(weights) + try rejected { + _ = try mtp.forward( + depth: 0, features: features, inputIDs: ids, target: target, + cache: stale) + } + try require(stale.consumedTokenCounts == [0, 0, 0], "stale cache mutated") + } + ), + ( + "target lifetime and different live target are enforced", + { + var target: MiMoV26TextModel? = try MiMoV26TextModel(config()) + weak var weakTarget = target + let mtp = try MiMoV26MTP(target: target!) + target = nil + try require( + weakTarget == nil, "predictor retains target or duplicated its ownership") + try rejected { _ = try mtp.newCache() } + let (live, loaded) = try fixture() + let features = try targetFeatures(live, length: 1) + let other = try MiMoV26TextModel(config()) + try rejected { + _ = try loaded.forward( + depth: 0, features: features, + inputIDs: MLXArray([Int32(2)], [1, 1]), target: other, + cache: loaded.newCache()) + } + } + ), + ( + "MiMo reuses target features instead of chaining predictor readouts", + { + let (target, mtp) = try fixture() + let features = try targetFeatures(target, length: 1) + let cache = try mtp.newCache() + let first = try mtp.forward( + depth: 0, features: features, + inputIDs: MLXArray([Int32(2)], [1, 1]), target: target, cache: cache) + try rejected { + _ = try mtp.forward( + depth: 1, features: first.features, + inputIDs: MLXArray([Int32(3)], [1, 1]), target: target, cache: cache) + } + try require( + cache.consumedTokenCounts == [1, 0, 0], + "rejected predictor chain mutated head1") + let targetHidden = [features.normalizedHiddenStates.asArray(Float.self)] + let wrongHidden = [first.normalizedHiddenStates.asArray(Float.self)] + let expected = reference( + mtp.layers[1], hidden: targetHidden, tokens: [3], + target: target, firstTokenPosition: 2) + let chained = reference( + mtp.layers[1], hidden: wrongHidden, tokens: [3], + target: target, firstTokenPosition: 2) + try require( + zip(expected.logits, chained.logits).map { abs($0 - $1) }.max()! > 1e-3, + "fixture cannot distinguish target-reuse from incorrect chaining") + let actual = try mtp.forward( + depth: 1, features: features, + inputIDs: MLXArray([Int32(3)], [1, 1]), target: target, cache: cache) + try near( + actual.logits, MLXArray(expected.logits, [1, 1, 32]), "target-feature reuse" + ) + try require( + cache.nextTokenPositions == [2, 3, 3], "independent head positions changed") + } + ), + ] + } +} + +#if MIMO_MTP_COMPONENT_PROBE + @main + private struct MiMoV26MTPComponentProbe { + static func main() throws { + let cases = MiMoV26MTPChecks.cases() + var failures = 0 + for (name, body) in cases { + do { + try body() + print("PASS \(name)") + } catch { + failures += 1 + print("FAIL \(name): \(error)") + } + } + print( + "RESULT discovered=\(cases.count) passed=\(cases.count - failures) failed=\(failures) skipped=0" + ) + if failures != 0 { + throw MiMoV26MTPChecks.Failure(message: "native MTP component probe failed") + } + } + } +#else + final class MiMoV26MTPTests: XCTestCase { + func testNativeNextNHeadContracts() throws { + for (name, body) in MiMoV26MTPChecks.cases() { + do { try body() } catch { XCTFail("\(name): \(error)") } + } + } + } +#endif diff --git a/Tests/MLXLMTests/MiMo/MiMoV26ManagedAudioCommitmentTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26ManagedAudioCommitmentTests.swift new file mode 100644 index 0000000000..ec180bbb11 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26ManagedAudioCommitmentTests.swift @@ -0,0 +1,88 @@ +import Foundation +import MLXLLM +import MLXVLM +import XCTest + +/// Metadata-only plan/accounting tests; no waveform buffers or native arrays. +final class MiMoV26ManagedAudioCommitmentTests: XCTestCase { + private func metadata() throws -> (MiMoV26AudioInputConfiguration, MiMoV26AudioConfiguration) { + guard let root = ProcessInfo.processInfo.environment["MIMO_V26_AUDIO_SIDECAR_FIXTURE_ROOT"] + else { + throw XCTSkip("Requires selected main/sidecar configuration metadata only") + } + func read(_ relative: String) throws -> Data { + let file = try FileHandle( + forReadingFrom: URL(fileURLWithPath: root).appendingPathComponent(relative)) + defer { try? file.close() } + let data = try XCTUnwrap(file.read(upToCount: (1 << 20) + 1)) + guard data.count <= 1 << 20 else { throw MiMoV26AudioSidecarError.invalidConfiguration } + return data + } + let main = try JSONDecoder().decode(MiMoV26Configuration.self, from: read("config.json")) + return ( + try .init(sidecarJSON: read("audio_tokenizer/config.json"), mainConfiguration: main), + try XCTUnwrap(main.audio) + ) + } + + private func limits(tile: Int) -> MiMoV26AudioInputLimits { + .init( + maximumClips: 4, maximumChannels: 2, maximumSampleRate: 48_000, + maximumInputSamples: 1_000_000, maximumResampledSamples: 1_000_000, + maximumResampleCoefficients: 1_000_000, maximumMelFrames: 20_000, + maximumSegments: 8, maximumPaddedMelFrames: 40_000, + maximumWorkingElements: 1_000_000_000_000, frontendFrameBlockSize: 64, + rvqTileFrames: tile) + } + private var patchLimits: MiMoV26AudioPatchLimits { + .init( + maximumClips: 4, maximumFrames: 100_000, maximumPatches: 25_000, + maximumWorkingElements: 1_000_000_000_000) + } + + func testAdditionalCommitmentPricesMixedOriginalGroupsAndEveryRVQTile() throws { + let (codec, patch) = try metadata() + let first = MiMoV26AudioPCMDescriptor( + sourceIdentity: "first", channels: 1, frameCount: 24_000, sampleRate: 24_000) + let second = MiMoV26AudioPCMDescriptor( + sourceIdentity: "second", channels: 1, frameCount: 12_001, sampleRate: 24_000) + let one = try MiMoV26AudioInputPlan.make( + clips: [first], configuration: codec, limits: limits(tile: 64)) + let mixed = try MiMoV26AudioInputPlan.make( + clips: [first, second], configuration: codec, limits: limits(tile: 64)) + let tiled = try MiMoV26AudioInputPlan.make( + clips: [first], configuration: codec, limits: limits(tile: 1)) + let originalGroups = mixed.groups + let singleBytes = try MiMoV26ManagedAudioCommitment.additionalBytes( + input: one, patchConfiguration: patch, limits: patchLimits) + let mixedBytes = try MiMoV26ManagedAudioCommitment.additionalBytes( + input: mixed, patchConfiguration: patch, limits: patchLimits) + let tiledBytes = try MiMoV26ManagedAudioCommitment.additionalBytes( + input: tiled, patchConfiguration: patch, limits: patchLimits) + XCTAssertGreaterThan(singleBytes, one.workingElementUpperBound * 4) + XCTAssertGreaterThan(mixedBytes, singleBytes) + XCTAssertGreaterThan(tiledBytes, singleBytes) + XCTAssertEqual(mixed.groups, originalGroups, "admission must not regroup audio to fit") + } + + func testMelOnlyNamespaceAndInsufficientPatchLimitsRefuse() throws { + let (codec, patch) = try metadata() + let mel = try MiMoV26AudioInputPlan.makeMelInputs( + frameCounts: [101], sourceIdentities: ["mel"], + configuration: codec, limits: limits(tile: 64)) + XCTAssertThrowsError( + try MiMoV26ManagedAudioCommitment.additionalBytes( + input: mel, patchConfiguration: patch, limits: patchLimits)) + let pcm = try MiMoV26AudioInputPlan.make( + clips: [ + .init(sourceIdentity: "pcm", channels: 1, frameCount: 24_000, sampleRate: 24_000) + ], configuration: codec, limits: limits(tile: 64)) + XCTAssertThrowsError( + try MiMoV26ManagedAudioCommitment.additionalBytes( + input: pcm, + patchConfiguration: patch, + limits: .init( + maximumClips: 1, maximumFrames: 1, + maximumPatches: 1, maximumWorkingElements: 1))) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26ManagedAudiovisualTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26ManagedAudiovisualTests.swift new file mode 100644 index 0000000000..7cee8f51fd --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26ManagedAudiovisualTests.swift @@ -0,0 +1,534 @@ +import CryptoKit +import Foundation +import MLX +import MLXHuggingFace +import MLXLLM +import Tokenizers +import XCTest + +@testable import MLXLMCommon +@testable import MLXVLM + +/// Real decoded AV through the same strict target, selected codec and managed engine. +/// New feature oracle compares actual whole-clip/audio and video reference features; +/// it never substitutes a fake encoder, tokenizer, target or retirement receipt. +/// Requires an explicitly supplied small audio-compatible target fixture; this +/// class never weakens the selected sidecar hash/geometry or invents a loaded +/// owner. Reservation counters are SDK lifetime witnesses, NOT host ledger or +/// measured-peak qualification. Each fault selector needs its own process. +final class MiMoV26ManagedAudiovisualTests: XCTestCase { + private enum Failure: Error { case inputRequired, nativeLaneRequired, noProof, injected } + private enum Profile: Sendable, Equatable { case audio, visual, text } + private final class RootPermit: MiMoV26SerialLoadReservation, Sendable { + let request: MiMoV26SerialLoadRequest + let reservedLoadBytes: UInt64 + init(_ request: MiMoV26SerialLoadRequest) { + self.request = request + reservedLoadBytes = request.requiredLoadBytes + } + func validateActive(progress: MiMoV26SerialLoadProgress) throws {} + } + private final class AudioPermit: MiMoV26AudioSidecarLoadReservation, @unchecked Sendable { + let request: MiMoV26AudioSidecarLoadRequest + let reservedLoadBytes: UInt64 + private let lock = NSLock() + private var invalid = false + init(_ request: MiMoV26AudioSidecarLoadRequest) { + self.request = request + reservedLoadBytes = request.requiredLoadBytes + } + func revoke() { lock.withLock { invalid = true } } + func validateActive() throws { + if lock.withLock({ invalid }) { throw MiMoV26AudioSidecarError.invalidatedOwner } + } + } + private final class WorkPermit: MiMoV26MediaWorkReservation, @unchecked Sendable { + private let lock = NSLock() + private var digest: String? + private var admittedPlan: MiMoV26MultimodalPlan? + var plan: MiMoV26MultimodalPlan? { lock.withLock { admittedPlan } } + private var charge = 0 + private var releaseCount = 0 + private var failures: [MiMoV26FailedMediaWork] = [] + private var validations = 0 + private var kinds: [String] = [] + private var frames: [Int] = [] + var onValidation: (@Sendable (Int) -> Void)? + var bytes: Int { lock.withLock { charge } } + var retired: Int { lock.withLock { releaseCount } } + var retainedFailures: Int { lock.withLock { failures.count } } + var failedAudioRootCounts: [Int] { + lock.withLock { failures.flatMap(\.retainedAudioFailureRootCountsForTesting) } + } + var orderedKinds: [String] { lock.withLock { kinds } } + var pcmFrames: [Int] { lock.withLock { frames } } + func admit(_ plan: MiMoV26MultimodalPlan, bytes: Int) throws { + try lock.withLock { + guard digest == nil, bytes > 0 else { + throw MiMoV26MultimodalError.reservationRejected + } + digest = plan.preparationSHA256 + charge = bytes + admittedPlan = plan + kinds = plan.spans.map { $0.kind.rawValue } + frames = plan.audioPlan?.pcmDescriptors?.map(\.frameCount) ?? [] + } + } + func validate(plan: MiMoV26MultimodalPlan) throws { + let count: Int = try lock.withLock { + guard digest == plan.preparationSHA256, charge > 0, releaseCount == 0 else { + throw MiMoV26MultimodalError.reservationRejected + } + validations += 1 + return validations + } + onValidation?(count) + } + func retainAfterFailedDrain(_ work: MiMoV26FailedMediaWork) { + lock.withLock { + if !failures.contains(where: { $0 === work }) { failures.append(work) } + } + } + func retire() throws { + try lock.withLock { + guard failures.isEmpty, releaseCount == 0 else { throw Failure.noProof } + charge = 0 + releaseCount = 1 + } + } + } + private final class Cancel: @unchecked Sendable { + private let lock = NSLock() + private var value = false + private var beforeRoots: Int? + var rootsBeforeAudio: Int? { lock.withLock { beforeRoots } } + func recordRootsBeforeAudio(_ value: Int) { lock.withLock { beforeRoots = value } } + var cancelled: Bool { lock.withLock { value } } + func set() { lock.withLock { value = true } } + } + private struct Loader: TokenizerLoader { + func load(from directory: URL) async throws -> any MLXLMCommon.Tokenizer { + let raw = try await AutoTokenizer.from(modelFolder: directory) + return #adaptHuggingFaceTokenizer(raw) + } + } + private struct Fixture: Sendable { + let container: ModelContainer + let engine: EngineV2 + let construction: NativeConstructionWork + let audioPermit: AudioPermit? + let contract: CBv2NativeExecutionContract + } + private struct Built: Sendable { + let engine: EngineV2 + let contract: CBv2NativeExecutionContract + } + private static let limits = MiMoV26MultimodalLimits( + maximumMedia: 4, maximumVideoFrames: 4, maximumPromptTokens: 2048, + maximumMetadataBytes: 1 << 20, maximumMetadataNodes: 10000, maximumMetadataDepth: 32, + pixels: .init( + maximumInputElements: 100000, maximumOutputElements: 100000, + maximumWorkingBytes: 1 << 20), + vision: .init(maximumPatches: 256, maximumAttentionScoreElements: 131072), + audio: .init( + maximumClips: 2, maximumChannels: 1, maximumSampleRate: 24000, + maximumInputSamples: 48000, maximumResampledSamples: 48000, + maximumResampleCoefficients: 100000, maximumMelFrames: 256, maximumSegments: 4, + maximumPaddedMelFrames: 256, maximumWorkingElements: 64_000_000, + frontendFrameBlockSize: 8, rvqTileFrames: 8), + audioPatch: .init( + maximumClips: 2, maximumFrames: 256, maximumPatches: 64, + maximumWorkingElements: 16_000_000)) + + private func fixture( + profile: Profile = .audio, installAudio: Bool = true, + enableMTP: Bool = false + ) async throws -> Fixture { + let env = ProcessInfo.processInfo.environment + guard env["MIMO_V26_SERIAL_NATIVE_TESTS"] == "1", + env["MIMO_V26_MANAGED_AUDIO_NATIVE_TESTS"] == "1", + env["MIMO_V26_DECODED_AV_NATIVE_TESTS"] == "1" + else { throw Failure.nativeLaneRequired } + guard let path = env["MIMO_V26_MANAGED_AUDIO_FIXTURE_ROOT"] else { + throw Failure.inputRequired + } + let root = URL(fileURLWithPath: path) + // Deliberately excludes a full target: the real selected SIDE-CAR is + // separate and authenticated by its existing loader below. + let provenanceFile = try FileHandle( + forReadingFrom: root.appendingPathComponent("provenance.json")) + defer { try? provenanceFile.close() } + let provenanceData = try XCTUnwrap(provenanceFile.read(upToCount: 65537)) + guard provenanceData.count <= 65536 else { throw Failure.inputRequired } + let p = try XCTUnwrap( + JSONSerialization.jsonObject(with: provenanceData) as? [String: String]) + let provenance = try MiMoV26ConvertedProvenance( + artifactID: XCTUnwrap(p["artifactID"]), + sourceRepository: XCTUnwrap(p["sourceRepository"]), + sourceRevision: XCTUnwrap(p["sourceRevision"]), + conversionManifestSHA256: XCTUnwrap(p["conversionManifestSHA256"])) + let plan = try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance, + limits: .init(maximumShardBytes: 64 << 20, maximumTotalFileBytes: 128 << 20)) + let session = try MiMoV26SerialLoadSession(plan: plan) + let config = plan.bundlePlan.configuration + guard config.vocabularySize > 151674, config.hiddenSize <= 64, + config.numHiddenLayers <= 4 + else { throw Failure.inputRequired } + let prepared = try await MiMoV26ModelFactory.prepare( + request: session.request, + configuration: .init(directory: root), tokenizerLoader: Loader()) + let construction = NativeConstructionWork() + defer { + if construction.snapshot.isRetainedFault { _ = Unmanaged.passRetained(construction) } + } + let container = try await MiMoV26ModelFactory.loadContainer( + session: session, + reservation: RootPermit(session.request), prepared: prepared, retaining: construction) + try await construction.acknowledgeContainerAdoption(container) + let sidecar: SendableBox? + let permit: AudioPermit? + if installAudio { + let value = try MiMoV26AudioSidecarLoadSession( + root: root, mainConfiguration: config, + mainConfigurationSHA256: plan.bundlePlan.configSHA256) + sidecar = SendableBox(value) + permit = AudioPermit(value.request) + } else { + sidecar = nil + permit = nil + } + let built = try await MiMoV26ModelFactory.withNativeConstruction( + container: container, retaining: construction + ) { model, scope in + if let sidecar, let permit { + _ = try model.installAudioSidecar( + session: sidecar.consume(), reservation: permit, + retaining: scope, isCancelled: { false }) + } + let binding = try model.makeCBv2Binding(enableMTP: enableMTP) + _ = try binding.adapter.probeNativeKVTypes(retaining: scope) + let resources: MiMoV26ManagedMediaExecutionResources + switch profile { + case .audio: + resources = try model.makeManagedAudioExecutionResources( + binding: binding, + bytesCapacity: 32 << 20, limits: Self.limits, retaining: scope) + case .visual: + resources = try model.makeManagedMediaExecutionResources( + binding: binding, + bytesCapacity: 32 << 20, limits: Self.limits, retaining: scope) + case .text: + let text = try binding.adapter.makeNativeExecutionResources( + bytesCapacity: 32 << 20, retaining: scope) + resources = .init( + backend: text.backend, cacheProvider: text.cacheProvider, + contract: text.contract) + } + let engine = EngineV2( + model: binding.adapter, layerKinds: binding.adapter.layerKinds, + backend: resources.backend, cacheProvider: resources.cacheProvider, + schedulerConfig: .init( + maxConcurrentRequests: 1, maxBatchedTokensPerStep: 4, + prefillChunkSize: 3, maxConcurrentPartialPrefills: 1, enablePrefixCache: false), + loopConfig: .init(stepTimeout: 60, watchdogInterval: 0.01, shutdownTimeout: 10), + mtpDrafter: binding.assistant, + mtpConfig: .init( + enabled: enableMTP, maxDraftTokens: 2, + maxSpeculativeBatch: 1, fixedDraftTokens: 2, verificationMode: .serialTarget), + nativeCompletionTracking: true, nativeExecutionContract: resources.contract) + try scope.retainOwner(engine) + return Built(engine: engine, contract: resources.contract) + } + guard case .completed(let completion) = construction.snapshot.disposition else { + throw Failure.noProof + } + try await construction.sealForPublication(completion) + return .init( + container: container, engine: built.engine, construction: construction, + audioPermit: permit, contract: built.contract) + } + private func prepared( + _ fixture: Fixture, input: MiMoV26MultimodalInput, + reservation: WorkPermit = WorkPermit(), cancel: Cancel = Cancel() + ) async throws -> (CBv2Request, WorkPermit) { + let request = try await fixture.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + return try model.prepareManagedDecodedAudioMedia( + input, engine: fixture.engine, + authorize: { plan, bytes in + try reservation.admit(plan, bytes: bytes) + return reservation + }, + retire: { _ in try reservation.retire() }, isCancelled: { cancel.cancelled }) + } + return (request, reservation) + } + private func shutdown(_ fixture: Fixture) async throws { + guard + case .quiescent(let receipt) = await fixture.engine.shutdownReportingNativeCompletion() + else { + _ = Unmanaged.passRetained(fixture.engine) + _ = Unmanaged.passRetained(fixture.container) + _ = Unmanaged.passRetained(fixture.construction) + throw Failure.noProof + } + XCTAssertEqual(receipt.executionContractID, fixture.contract.id) + if fixture.contract.supportsDecodedAudioMedia { + try await fixture.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + try model.releaseManagedAudioAfterNativeRetirement(receipt) + XCTAssertNil(model.resources.audioSidecar) + } + } + } + + private final class Count: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + func increment() { lock.withLock { count += 1 } } + var value: Int { lock.withLock { count } } + } + private func retainUnverified(_ f: Fixture) { + // Test failure is not permission to drop an unknown native owner. + _ = Unmanaged.passRetained(f.engine) + _ = Unmanaged.passRetained(f.container) + _ = Unmanaged.passRetained(f.construction) + } + private func clip(end: MiMoV26DecodedAudiovisual.SegmentEnd = .float32(0.48)) throws + -> MiMoV26DecodedAudiovisual + { + let pcm = try MiMoV26DecodedPCM( + samples: (0 ..< 11520).map { sin(Float($0) * 0.02) * 0.05 }, + descriptor: .init( + sourceIdentity: "decoded-av-whole-sine-048", channels: 1, + frameCount: 11520, sampleRate: 24000)) + let frames = [70, 90, 110].map { value in + MiMoV26Pixels.DecodedRGB( + height: 4, width: 4, + planarRGB: (0 ..< 48).map { Float((value + $0 * 7) % 256) }) + } + return .init(frames: frames, timestamps: [0, 0.16, 0.32], wholeAudio: pcm, segmentEnd: end) + } + private func message(_ content: MiMoV26MultimodalContent) -> MiMoV26MultimodalInput { + .init( + messages: [.init(role: .user, content: [.text("Describe."), content])], + maximumOutputTokens: 2) + } + + func testWholeEncodeOnceExactFeatureSlicesInterleaveFullBackingPriceAndRealRetirement() + async throws + { + #if DEBUG + let f = try await fixture() + var closed = false + defer { if !closed { retainUnverified(f) } } + let av = try clip() + let (whole, wholePermit) = try await prepared(f, input: message(.audio(av.wholeAudio))) + let (video, videoPermit) = try await prepared( + f, + input: message( + .silentVideo( + .init(frames: av.frames, timestamps: av.timestamps)))) + let count = Count() + try await f.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + try XCTUnwrap(model.resources.audioSidecar).codec.input + .beforeManagedRequiredCompletionForTesting = { + if case .codesReadback = $0 { count.increment() } + } + } + var (request, permit) = try await prepared(f, input: message(.audiovisual(av))) + try await f.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + try XCTUnwrap(model.resources.audioSidecar).codec.input + .beforeManagedRequiredCompletionForTesting = nil + } + XCTAssertEqual( + count.value, 1, "one actual whole clip encode, never one encode per AV unit") + let plan = try XCTUnwrap(permit.plan) + let a = try XCTUnwrap(wholePermit.plan) + let v = try XCTUnwrap(videoPermit.plan) + XCTAssertEqual(plan.spans.map(\.kind.rawValue), ["video", "audio", "video", "audio"]) + XCTAssertEqual(plan.spans.filter { $0.kind == .audio }.map(\.featureOffset), [0, 2]) + XCTAssertEqual(plan.spans.filter { $0.kind == .audio }.map(\.length), [2, 1]) + XCTAssertEqual(plan.audioPlan?.pcmDescriptors?.map(\.frameCount), [11520]) + XCTAssertEqual(plan.audioPlan?.codeFrameCounts, [13]) + XCTAssertEqual(plan.audioPlan?.patchCounts, [4]) + XCTAssertEqual( + plan.featureElements, a.featureElements + v.featureElements, + "last whole-audio feature row remains charged even though prompt spans use only three" + ) + XCTAssertEqual(plan.logicalFeatureBytes, a.logicalFeatureBytes + v.logicalFeatureBytes) + let geometry = try XCTUnwrap(plan.visionGeometryByMediaIndex[0]) + XCTAssertEqual(geometry.alignedFrames, 4) + XCTAssertEqual(geometry.timestampCount, 2) + XCTAssertEqual( + permit.bytes, + wholePermit.bytes + videoPermit.bytes + - Self.limits.pixels.maximumWorkingBytes + 32768 * geometry.timestampCount) + let wholeAudio = try XCTUnwrap(a.spans.first) + for span in plan.spans where span.kind == .audio { + XCTAssertEqual( + plan.promptTokens[span.tokenOffset - 1], + a.promptTokens[wholeAudio.tokenOffset - 1]) + XCTAssertEqual( + plan.promptTokens[span.tokenOffset + span.length], + a.promptTokens[wholeAudio.tokenOffset + wholeAudio.length]) + XCTAssertEqual( + Array(plan.promptTokens[span.tokenOffset ..< (span.tokenOffset + span.length)]), + Array(repeating: a.promptTokens[wholeAudio.tokenOffset], count: span.length)) + } + // Independent prompt oracle: unchanged silent-video timestamps/outer + // framing, with each native whole-audio marker inserted after that + // grid's vision_end. This catches grouped/late timestamp alternatives. + var expectedPrompt: [Int] = [] + var cursor = 0 + for (index, span) in v.spans.enumerated() { + let end = span.tokenOffset + span.length + 1 + expectedPrompt += v.promptTokens[cursor ..< end] + expectedPrompt.append(a.promptTokens[wholeAudio.tokenOffset - 1]) + expectedPrompt += Array( + repeating: a.promptTokens[wholeAudio.tokenOffset], count: [2, 1][index]) + expectedPrompt.append(a.promptTokens[wholeAudio.tokenOffset + wholeAudio.length]) + cursor = end + } + expectedPrompt += v.promptTokens[cursor...] + XCTAssertEqual(plan.promptTokens, expectedPrompt) + // Features stay inside the exact owning queue. Diagnostic comparison + // expressions are retained on the existing AV loan BEFORE evaluation. + try f.engine.loopForTesting.onEngineQueueSync { + let target = try XCTUnwrap(request.multimodal?.nativeMediaToken) + let wholeToken = try XCTUnwrap(whole.multimodal?.nativeMediaToken) + let videoToken = try XCTUnwrap(video.multimodal?.nativeMediaToken) + let actual = try XCTUnwrap(target.work.resolved).embeddings + let audio = try XCTUnwrap(wholeToken.work.resolved).embeddings + let visual = try XCTUnwrap(videoToken.work.resolved).embeddings + XCTAssertEqual(actual.count, 4) + XCTAssertEqual(audio.count, 1) + XCTAssertEqual(visual.count, 2) + let expected = [ + visual[0], audio[0][0..., 0 ..< 2, 0...], visual[1], + audio[0][0..., 2 ..< 3, 0...], + ] + let equalities = zip(actual, expected).map { pair in all(pair.0 .== pair.1) } + try target.work.beforeNativeWork(actual + expected + equalities) + do { + try withError { eval(equalities) } + for equality in equalities { + XCTAssertTrue(try withError { equality.item(Bool.self) }) + } + } catch { + target.work.requiredCompletionFailed() + throw error + } + } + // Comparison graphs retained on the AV loan still reference these + // independently prepared arrays. Keep BOTH real reference reservations + // live until AV retirement removes those diagnostic aliases. + XCTAssertEqual(wholePermit.retired, 0) + XCTAssertEqual(videoPermit.retired, 0) + XCTAssertGreaterThan(wholePermit.bytes, 0) + XCTAssertGreaterThan(videoPermit.bytes, 0) + XCTAssertEqual(permit.retired, 0) + XCTAssertGreaterThan(permit.bytes, 0) + XCTAssertThrowsError( + try request.multimodal!.embeddings(), "no public native feature alias") + request.id = .init(701) + request.sampling = .init(temperature: 0) + let submission = try f.engine.submitWithNativeRetirement(request) + let result = await cbv2SchedCollect(submission.events) + await submission.retirement.wait() + XCTAssertFalse(result.tokens.isEmpty) + XCTAssertEqual(permit.retired, 1) + XCTAssertEqual(permit.bytes, 0) + f.engine.discardUnsubmittedNativeMedia(try XCTUnwrap(whole.multimodal)) + f.engine.discardUnsubmittedNativeMedia(try XCTUnwrap(video.multimodal)) + XCTAssertEqual(wholePermit.retired, 1) + XCTAssertEqual(videoPermit.retired, 1) + XCTAssertThrowsError( + try f.engine.submitWithNativeRetirement(request), "same native seal is one-shot") + XCTAssertNil(f.engine.nativeCompletionFault) + try await shutdown(f) + closed = true + #else + throw Failure.inputRequired // exact whole-encode observer is DEBUG-only; never silently skip + #endif + } + + func testVisualProfileAndEmptyNativeUnitRefuseBeforeAdmissionThenHealthyAVWorks() async throws { + let visual = try await fixture(profile: .visual, installAudio: false) + var visualClosed = false + defer { if !visualClosed { retainUnverified(visual) } } + let valid = message(.audiovisual(try clip())) + do { + _ = try await visual.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + return try model.prepareManagedDecodedMedia( + valid, engine: visual.engine, + authorize: { _, _ in + XCTFail("visual profile admitted linked audio") + return WorkPermit() + }, + retire: { _ in XCTFail("visual profile issued audio retirement") }, + isCancelled: { false }) + } + XCTFail("visual profile accepted AV") + } catch { XCTAssertEqual(error as? MiMoV26MultimodalError, .missingAudioCodec) } + XCTAssertNil(visual.engine.nativeCompletionFault) + try await shutdown(visual) + visualClosed = true + + let f = try await fixture() + var closed = false + defer { if !closed { retainUnverified(f) } } + let rejected = WorkPermit() + do { + _ = try await prepared( + f, + input: message( + .audiovisual( + try clip(end: .float64(Double(Float(0.48)))))), reservation: rejected) + XCTFail("native empty last audio unit was padded or silently dropped") + } catch { + guard let failure = error as? MiMoV26MultimodalError, + case .invalidInput = failure + else { throw error } + } + XCTAssertNil(rejected.plan) + XCTAssertEqual(rejected.bytes, 0) + XCTAssertEqual(rejected.retired, 0) + XCTAssertNil(f.engine.nativeCompletionFault) + let (request, permit) = try await prepared(f, input: valid) + XCTAssertEqual(permit.orderedKinds, ["video", "audio", "video", "audio"]) + f.engine.discardUnsubmittedNativeMedia(try XCTUnwrap(request.multimodal)) + XCTAssertEqual(permit.retired, 1) + try await shutdown(f) + closed = true + } + + func testDecodedAVTargetOnlyThenActualTextMTPOnSameIssuedEngine() async throws { + let f = try await fixture(enableMTP: true) + var closed = false + defer { if !closed { retainUnverified(f) } } + XCTAssertTrue(CBv2MTPConfig.envEnabled, "ON selector requires actual kill switch enabled") + let (request, permit) = try await prepared(f, input: message(.audiovisual(try clip()))) + let media = try f.engine.submitWithNativeRetirement(request) + let mediaOutput = await cbv2SchedCollect(media.events) + await media.retirement.wait() + XCTAssertFalse(mediaOutput.tokens.isEmpty) + XCTAssertEqual(permit.retired, 1) + XCTAssertEqual(try XCTUnwrap(f.engine.mtpMetricsSnapshot()).draftedTokens, 0) + let text = CBv2Request( + id: .init(719), promptTokens: Array(repeating: 20, count: 13), + sampling: .init(temperature: 0), maxTokens: 8, stopTokens: [], prefixCacheEnabled: false + ) + let result = try f.engine.submitWithNativeRetirement(text) + let output = await cbv2SchedCollect(result.events) + await result.retirement.wait() + XCTAssertEqual(output.tokens.count, 8) + XCTAssertGreaterThan(try XCTUnwrap(f.engine.mtpMetricsSnapshot()).draftedTokens, 0) + try await shutdown(f) + closed = true + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26ManagedCompletePrefixTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26ManagedCompletePrefixTests.swift new file mode 100644 index 0000000000..9c0207c925 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26ManagedCompletePrefixTests.swift @@ -0,0 +1,509 @@ +import Foundation +import MLX +import MLXHuggingFace +import MLXLLM +import Tokenizers +import XCTest + +@testable import MLXLMCommon +@testable import MLXVLM + +/// Prepared native component tests, UNRUN. Strict small target and (audio case) +/// the actual authenticated selected sidecar. Test-only bounded ledger/encoded +/// transport are not provider global-memory or encrypted-store qualification. +final class MiMoV26ManagedCompletePrefixTests: XCTestCase { + private enum Failure: Error { case inputRequired, nativeLaneRequired, noProof, injected } + private enum Profile: Sendable, Equatable { case audio, visual } + private final class RootPermit: MiMoV26SerialLoadReservation, Sendable { + let request: MiMoV26SerialLoadRequest + let reservedLoadBytes: UInt64 + init(_ request: MiMoV26SerialLoadRequest) { + self.request = request + reservedLoadBytes = request.requiredLoadBytes + } + func validateActive(progress: MiMoV26SerialLoadProgress) throws {} + } + private final class AudioPermit: MiMoV26AudioSidecarLoadReservation, @unchecked Sendable { + let request: MiMoV26AudioSidecarLoadRequest + let reservedLoadBytes: UInt64 + private let lock = NSLock() + private var invalid = false + init(_ request: MiMoV26AudioSidecarLoadRequest) { + self.request = request + reservedLoadBytes = request.requiredLoadBytes + } + func revoke() { lock.withLock { invalid = true } } + func validateActive() throws { + if lock.withLock({ invalid }) { throw MiMoV26AudioSidecarError.invalidatedOwner } + } + } + private final class WorkPermit: MiMoV26MediaWorkReservation, @unchecked Sendable { + private let lock = NSLock() + private var digest: String? + private var charge = 0, releaseCount = 0 + private var failures: [MiMoV26FailedMediaWork] = [] + var bytes: Int { lock.withLock { charge } } + var retired: Int { lock.withLock { releaseCount } } + func admit(_ plan: MiMoV26MultimodalPlan, bytes: Int) throws { + try lock.withLock { + guard digest == nil, bytes > 0 else { + throw MiMoV26MultimodalError.reservationRejected + } + digest = plan.preparationSHA256 + charge = bytes + } + } + func validate(plan: MiMoV26MultimodalPlan) throws { + try lock.withLock { + guard digest == plan.preparationSHA256, charge > 0, releaseCount == 0 else { + throw MiMoV26MultimodalError.reservationRejected + } + } + } + func retainAfterFailedDrain(_ work: MiMoV26FailedMediaWork) { + lock.withLock { + if !failures.contains(where: { $0 === work }) { failures.append(work) } + } + } + func retire() throws { + try lock.withLock { + guard failures.isEmpty, releaseCount == 0 else { throw Failure.noProof } + charge = 0 + releaseCount = 1 + } + } + } + private struct Loader: TokenizerLoader { + func load(from directory: URL) async throws -> any MLXLMCommon.Tokenizer { + let raw = try await AutoTokenizer.from(modelFolder: directory) + return #adaptHuggingFaceTokenizer(raw) + } + } + + /// Existing encoded checkpoint fixture transport with real async export + /// jobs and close joins. Provider tests below use the actual encrypted store. + private final class Store: CBv2NativeCompletePrefixCache, @unchecked Sendable { + let base = CompleteCheckpointFixtureStore(segmentBytes: 1 << 20) + private let jobs = DispatchGroup() + var identity: CBv2CompleteCheckpointIdentity { base.identity } + func acceptsCheckpoint(position: Int, packedBytes: Int) -> Bool { + base.acceptsCheckpoint(position: position, packedBytes: packedBytes) + } + func takeStaged( + requestID: CBv2RequestID, tokens: [Int], cacheSalt: String?, + maximumSequenceLength: Int + ) -> CBv2StagedCompleteCheckpoint? { + base.takeStaged( + requestID: requestID, tokens: tokens, cacheSalt: cacheSalt, + maximumSequenceLength: maximumSequenceLength) + } + func donate( + _ source: CBv2CompleteCheckpointExport, requestID: CBv2RequestID?, tokens: [Int], + cacheSalt: String?, completion: @escaping @Sendable ([Int]) -> Void + ) { + jobs.enter() + base.donate(source, requestID: requestID, tokens: tokens, cacheSalt: cacheSalt) { + [self] positions in + completion(positions) + jobs.leave() + } + } + func close() { base.close() } + func closeAndWait() async { + close() + await withCheckedContinuation { continuation in + jobs.notify(queue: .global()) { continuation.resume() } + } + } + } + private final class ProcessOwner: CBv2ProcessMemoryOwner, @unchecked Sendable { + private let lock = NSLock() + private var c: UInt64 = 0, m: UInt64 = 0 + private var closed = false + var bytes: UInt64 { lock.withLock { c } } + func replaceCharge(_ bytes: UInt64) throws { + try lock.withLock { + guard !closed, bytes >= m, bytes <= 256 << 20 else { throw Failure.noProof } + c = bytes + } + } + func recordMaterialization(_ bytes: UInt64) throws { + try lock.withLock { + guard !closed, bytes >= m, bytes <= c else { throw Failure.noProof } + m = bytes + } + } + func withdrawCoverage(_ bytes: UInt64) throws { + try lock.withLock { + guard bytes <= m else { throw Failure.noProof } + m -= bytes + } + } + func retire() { + lock.withLock { + XCTAssertEqual(c, 0) + closed = true + } + } + } + private struct Fixture: Sendable { + let container: ModelContainer + let engine: EngineV2 + let construction: NativeConstructionWork + let audioPermit: AudioPermit? + let contract: CBv2NativeExecutionContract + let store: Store + let process: ProcessOwner + } + private struct Built: Sendable { + let engine: EngineV2 + let contract: CBv2NativeExecutionContract + } + private static let limits = MiMoV26MultimodalLimits( + maximumMedia: 4, maximumVideoFrames: 4, maximumPromptTokens: 2048, + maximumMetadataBytes: 1 << 20, maximumMetadataNodes: 10000, maximumMetadataDepth: 32, + pixels: .init( + maximumInputElements: 100000, maximumOutputElements: 100000, + maximumWorkingBytes: 1 << 20), + vision: .init(maximumPatches: 256, maximumAttentionScoreElements: 131072), + audio: .init( + maximumClips: 2, maximumChannels: 1, maximumSampleRate: 24000, + maximumInputSamples: 48000, maximumResampledSamples: 48000, + maximumResampleCoefficients: 100000, maximumMelFrames: 256, maximumSegments: 4, + maximumPaddedMelFrames: 256, maximumWorkingElements: 64_000_000, + frontendFrameBlockSize: 8, rvqTileFrames: 8), + audioPatch: .init( + maximumClips: 2, maximumFrames: 256, maximumPatches: 64, + maximumWorkingElements: 16_000_000)) + + private func fixture( + profile: Profile = .audio, installAudio: Bool = true, + enableMTP: Bool = false + ) async throws -> Fixture { + let env = ProcessInfo.processInfo.environment + guard env["MIMO_V26_SERIAL_NATIVE_TESTS"] == "1", + env["MIMO_V26_MANAGED_AUDIO_NATIVE_TESTS"] == "1" + else { throw Failure.nativeLaneRequired } + guard let path = env["MIMO_V26_MANAGED_AUDIO_FIXTURE_ROOT"] else { + throw Failure.inputRequired + } + let root = URL(fileURLWithPath: path) + // Deliberately excludes a full target: the real selected SIDE-CAR is + // separate and authenticated by its existing loader below. + let provenanceFile = try FileHandle( + forReadingFrom: root.appendingPathComponent("provenance.json")) + defer { try? provenanceFile.close() } + let provenanceData = try XCTUnwrap(provenanceFile.read(upToCount: 65537)) + guard provenanceData.count <= 65536 else { throw Failure.inputRequired } + let p = try XCTUnwrap( + JSONSerialization.jsonObject(with: provenanceData) as? [String: String]) + let provenance = try MiMoV26ConvertedProvenance( + artifactID: XCTUnwrap(p["artifactID"]), + sourceRepository: XCTUnwrap(p["sourceRepository"]), + sourceRevision: XCTUnwrap(p["sourceRevision"]), + conversionManifestSHA256: XCTUnwrap(p["conversionManifestSHA256"])) + let plan = try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance, + limits: .init(maximumShardBytes: 64 << 20, maximumTotalFileBytes: 128 << 20)) + let session = try MiMoV26SerialLoadSession(plan: plan) + let config = plan.bundlePlan.configuration + guard config.vocabularySize > 151674, config.hiddenSize <= 64, + config.numHiddenLayers <= 4, config.maxPositionEmbeddings >= 1024 + else { throw Failure.inputRequired } + let prepared = try await MiMoV26ModelFactory.prepare( + request: session.request, + configuration: .init(directory: root), tokenizerLoader: Loader()) + let construction = NativeConstructionWork() + defer { + if construction.snapshot.isRetainedFault { _ = Unmanaged.passRetained(construction) } + } + let container = try await MiMoV26ModelFactory.loadContainer( + session: session, + reservation: RootPermit(session.request), prepared: prepared, retaining: construction) + try await construction.acknowledgeContainerAdoption(container) + let sidecar: SendableBox? + let permit: AudioPermit? + if installAudio { + let value = try MiMoV26AudioSidecarLoadSession( + root: root, mainConfiguration: config, + mainConfigurationSHA256: plan.bundlePlan.configSHA256) + sidecar = SendableBox(value) + permit = AudioPermit(value.request) + } else { + sidecar = nil + permit = nil + } + let store = Store() + let process = ProcessOwner() + let built = try await MiMoV26ModelFactory.withNativeConstruction( + container: container, retaining: construction + ) { model, scope in + if let sidecar, let permit { + _ = try model.installAudioSidecar( + session: sidecar.consume(), reservation: permit, + retaining: scope, isCancelled: { false }) + } + let binding = try model.makeCBv2Binding(enableMTP: enableMTP) + _ = try binding.adapter.probeNativeKVTypes(retaining: scope) + let metadata = try model.nativeCompletePrefixMetadata( + binding: binding, retaining: scope) + let resources: MiMoV26ManagedMediaExecutionResources + switch profile { + case .audio: + resources = try model.makeManagedAudioCompletePrefixExecutionResources( + binding: binding, + bytesCapacity: 32 << 20, expectedMetadata: metadata, completePrefixCache: store, + processMemoryOwner: process, limits: Self.limits, retaining: scope) + case .visual: + resources = try model.makeManagedMediaCompletePrefixExecutionResources( + binding: binding, + bytesCapacity: 32 << 20, expectedMetadata: metadata, completePrefixCache: store, + processMemoryOwner: process, limits: Self.limits, retaining: scope) + } + XCTAssertFalse( + resources.contract.consume( + model: binding.adapter, backend: resources.backend, + cacheProvider: resources.cacheProvider, assistant: binding.assistant, + completePrefixCache: Store(), processMemoryOwner: process)) + XCTAssertFalse( + resources.contract.consume( + model: binding.adapter, backend: resources.backend, + cacheProvider: resources.cacheProvider, assistant: binding.assistant, + completePrefixCache: store, processMemoryOwner: ProcessOwner())) + let engine = EngineV2( + model: binding.adapter, layerKinds: binding.adapter.layerKinds, + backend: resources.backend, cacheProvider: resources.cacheProvider, + schedulerConfig: .init( + maxConcurrentRequests: 1, maxBatchedTokensPerStep: 128, + prefillChunkSize: 128, maxConcurrentPartialPrefills: 1, enablePrefixCache: true), + loopConfig: .init(stepTimeout: 60, watchdogInterval: 0.01, shutdownTimeout: 10), + completePrefixCache: store, + mtpDrafter: binding.assistant, + mtpConfig: .init( + enabled: enableMTP, maxDraftTokens: 3, + maxSpeculativeBatch: 1, fixedDraftTokens: 3, verificationMode: .serialTarget), + processMemoryOwner: process, + nativeCompletionTracking: true, nativeExecutionContract: resources.contract) + try scope.retainOwner(engine) + XCTAssertNil(engine.nativeCompletionFault) + guard engine.nativeCompletionFault == nil else { throw Failure.noProof } + return Built(engine: engine, contract: resources.contract) + } + guard case .completed(let completion) = construction.snapshot.disposition else { + throw Failure.noProof + } + try await construction.sealForPublication(completion) + return .init( + container: container, engine: built.engine, construction: construction, + audioPermit: permit, contract: built.contract, store: store, process: process) + } + private func input(mixed: Bool = false) throws -> MiMoV26MultimodalInput { + let pcm = try MiMoV26DecodedPCM( + samples: (0 ..< 2400).map { sin(Float($0) * 0.02) * 0.05 }, + descriptor: .init( + sourceIdentity: "synthetic-sine-owned-pcm", channels: 1, + frameCount: 2400, sampleRate: 24000)) + var parts: [MiMoV26MultimodalContent] = [] + if mixed { + parts.append( + .image( + .init( + height: 4, width: 4, + planarRGB: (0 ..< 48).map { Float(($0 * 17) % 256) }))) + } + parts += [.text("listen"), .audio(pcm), .text("describe")] + return .init(messages: [.init(role: .user, content: parts)], maximumOutputTokens: 2) + } + + private func collect( + _ request: CBv2Request, fixture f: Fixture, + expectDrafting: Bool = false, requireFirstDepthThree: Bool = false + ) async throws -> CBv2SchedCollected { + let before = f.engine.mtpMetricsSnapshot() + if requireFirstDepthThree { + XCTAssertTrue( + try XCTUnwrap(before).perPositionAccepted.isEmpty, + "the fixed-depth witness must start before this engine's first round") + } + let submission = try f.engine.submitWithNativeRetirement(request) + let result = await cbv2SchedCollect(submission.events) + guard result.finishReason == .length || result.finishReason == .stop else { + throw Failure.noProof + } + await submission.retirement.wait() + let after = f.engine.mtpMetricsSnapshot() + let timing = try XCTUnwrap(result.usage).timing + if expectDrafting { + let a = try XCTUnwrap(before) + let b = try XCTUnwrap(after) + XCTAssertTrue(a.active) + XCTAssertTrue(b.active) + XCTAssertEqual(b.verificationMode, .serialTarget) + XCTAssertGreaterThan(timing.mtpRounds, 0, "this request must actually verify drafts") + XCTAssertGreaterThan(timing.mtpProposed, 0, "active MTP is not execution") + XCTAssertEqual(b.rounds - a.rounds, Int(timing.mtpRounds)) + XCTAssertEqual(b.draftedTokens - a.draftedTokens, Int(timing.mtpProposed)) + XCTAssertEqual( + b.serialVerificationRounds - a.serialVerificationRounds, Int(timing.mtpRounds)) + XCTAssertEqual(b.rectangularVerificationRounds - a.rectangularVerificationRounds, 0) + if requireFirstDepthThree { + // recordRound grows this vector by DRAFTED depth even if every + // proposal is rejected. No acceptance requirement for tiny weights. + XCTAssertEqual(b.perPositionAccepted.count, 3) + } + } else { + XCTAssertEqual(timing.mtpRounds, 0) + XCTAssertEqual(timing.mtpProposed, 0) + if let a = before, let b = after { + XCTAssertEqual(b.rounds, a.rounds) + XCTAssertEqual(b.draftedTokens, a.draftedTokens) + XCTAssertEqual(b.serialVerificationRounds, a.serialVerificationRounds) + XCTAssertEqual(b.rectangularVerificationRounds, a.rectangularVerificationRounds) + } else { + XCTAssertNil(before) + XCTAssertNil(after) + } + } + return result + } + private func shutdown(_ f: Fixture) async throws { + guard case .quiescent(let receipt) = await f.engine.shutdownReportingNativeCompletion() + else { + _ = Unmanaged.passRetained(f.engine) + _ = Unmanaged.passRetained(f.container) + _ = Unmanaged.passRetained(f.construction) + throw Failure.noProof + } + XCTAssertEqual(receipt.engineID, f.engine.nativeShutdownEngineID) + XCTAssertEqual(receipt.executionContractID, f.contract.id) + try await f.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + try model.releaseNativeCompletePrefixAfterNativeRetirement(receipt) + if f.contract.supportsDecodedAudioMedia { + try model.releaseManagedAudioAfterNativeRetirement(receipt) + } + } + XCTAssertEqual(f.process.bytes, 0) + } + private func exercise(audio: Bool, mtp: Bool) async throws { + let f = try await fixture( + profile: audio ? .audio : .visual, installAudio: audio, enableMTP: mtp) + do { + XCTAssertTrue(f.contract.supportsNativeCompletePrefix) + XCTAssertTrue(f.contract.supportsManagedDecodedMedia) + XCTAssertEqual(f.contract.supportsDecodedAudioMedia, audio) + XCTAssertEqual(f.engine.mtpMetricsSnapshot()?.active == true, mtp) + let engineID = f.engine.nativeShutdownEngineID + let tokens = (0 ..< 513).map { 20 + ($0 % 9) } + let first = CBv2Request( + id: .init(41), promptTokens: tokens, + sampling: .init(temperature: 0), maxTokens: 16, cacheSalt: "fixture-tenant", + prefixCacheEnabled: true, prefixCacheReceiptID: .init(1041)) + let cold = try await collect( + first, fixture: f, expectDrafting: mtp, requireFirstDepthThree: mtp) + XCTAssertFalse(f.store.base.saved.isEmpty) + var hit = first + hit.id = .init(42) + hit.prefixCacheReceiptID = .init(1042) + XCTAssertTrue(try f.store.base.stage(engine: f.engine, request: hit)) + let warm = try await collect(hit, fixture: f, expectDrafting: mtp) + XCTAssertEqual(warm.tokens, cold.tokens) + XCTAssertGreaterThan(warm.usage?.prefixCachePrefillTokensSaved ?? 0, 0) + let beforeMedia = f.store.base.saved.count + let permit = WorkPermit() + let mediaInput: MiMoV26MultimodalInput = + audio + ? try input(mixed: true) + : .init( + messages: [ + .init( + role: .user, + content: [ + .image( + .init( + height: 4, width: 4, planarRGB: (0 ..< 48).map { Float($0) } + )), + .text("describe"), + ]) + ], additionalContext: ["enable_thinking": false], maximumOutputTokens: 2) + var request = try await f.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + let authorize: + (MiMoV26MultimodalPlan, Int) throws -> any MiMoV26MediaWorkReservation = { + plan, bytes in + try permit.admit(plan, bytes: bytes) + return permit + } + if audio { + return try model.prepareManagedDecodedAudioMedia( + mediaInput, engine: f.engine, + authorize: authorize, retire: { _ in try permit.retire() }, + isCancelled: { false }) + } + return try model.prepareManagedDecodedMedia( + mediaInput, engine: f.engine, + authorize: authorize, retire: { _ in try permit.retire() }, + isCancelled: { false }) + } + request.id = .init(43) + request.sampling = .init(temperature: 0) + XCTAssertFalse(request.prefixCacheEnabled) + XCTAssertNotNil(request.multimodal?.nativeMediaToken) + let mediaResult = try await collect(request, fixture: f) + XCTAssertEqual(mediaResult.usage?.prefixCachePrefillTokensSaved ?? 0, 0) + XCTAssertEqual(f.store.base.saved.count, beforeMedia) + XCTAssertEqual(permit.retired, 1) + XCTAssertEqual(permit.bytes, 0) + XCTAssertThrowsError(try f.engine.submitWithNativeRetirement(request)) + hit.id = .init(44) + hit.prefixCacheReceiptID = .init(1044) + XCTAssertTrue(try f.store.base.stage(engine: f.engine, request: hit)) + let afterMedia = try await collect(hit, fixture: f, expectDrafting: mtp) + XCTAssertEqual(afterMedia.tokens, cold.tokens) + XCTAssertGreaterThan(afterMedia.usage?.prefixCachePrefillTokensSaved ?? 0, 0) + XCTAssertEqual(f.engine.nativeShutdownEngineID, engineID) + try await shutdown(f) + } catch { + _ = Unmanaged.passRetained(f.engine) + _ = Unmanaged.passRetained(f.container) + _ = Unmanaged.passRetained(f.construction) + throw error + } + } + func testJointVisualKeepsActualTextReuseAndNoncacheableImageOnSameEngine() async throws { + try await exercise(audio: false, mtp: false) + } + func testJointAudioAndThreeHeadMTPKeepTextReuseAfterRealMixedPCM() async throws { + try await exercise(audio: true, mtp: true) + } + func testAlreadyIssuedJointProfileRejectsMetadataAndSeparateProfileUpgrade() async throws { + let f = try await fixture(profile: .visual, installAudio: false) + do { + try await f.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + let scope = NativeConstructionScope() + try scope.withPhase(.nativeSetup) { + try scope.authorizeImmutableLoadedOwner(model.resources) + let binding = try model.makeCBv2Binding() + XCTAssertThrowsError( + try model.nativeCompletePrefixMetadata(binding: binding, retaining: scope)) + XCTAssertThrowsError( + try model.makeManagedMediaExecutionResources( + binding: binding, + bytesCapacity: 32 << 20, limits: Self.limits, retaining: scope)) + } + } + let request = CBv2Request( + id: .init(51), promptTokens: [20, 21, 22, 23], + sampling: .init(temperature: 0), maxTokens: 2, prefixCacheEnabled: false) + let continued = try await collect(request, fixture: f) + XCTAssertFalse(continued.tokens.isEmpty) + try await shutdown(f) + } catch { + _ = Unmanaged.passRetained(f.engine) + _ = Unmanaged.passRetained(f.container) + _ = Unmanaged.passRetained(f.construction) + throw error + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26ManagedDecodedAudioTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26ManagedDecodedAudioTests.swift new file mode 100644 index 0000000000..7df4c2e263 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26ManagedDecodedAudioTests.swift @@ -0,0 +1,593 @@ +import CryptoKit +import Foundation +import MLX +import MLXHuggingFace +import MLXLLM +import Tokenizers +import XCTest + +@testable import MLXLMCommon +@testable import MLXVLM + +/// Real strict target + authenticated selected codec + actual PCM/engine work. +/// Requires an explicitly supplied small audio-compatible target fixture; this +/// class never weakens the selected sidecar hash/geometry or invents a loaded +/// owner. Reservation counters are SDK lifetime witnesses, NOT host ledger or +/// measured-peak qualification. Each fault selector needs its own process. +final class MiMoV26ManagedDecodedAudioTests: XCTestCase { + private enum Failure: Error { case inputRequired, nativeLaneRequired, noProof, injected } + private enum Profile: Sendable, Equatable { case audio, visual, text } + private final class RootPermit: MiMoV26SerialLoadReservation, Sendable { + let request: MiMoV26SerialLoadRequest + let reservedLoadBytes: UInt64 + init(_ request: MiMoV26SerialLoadRequest) { + self.request = request + reservedLoadBytes = request.requiredLoadBytes + } + func validateActive(progress: MiMoV26SerialLoadProgress) throws {} + } + private final class AudioPermit: MiMoV26AudioSidecarLoadReservation, @unchecked Sendable { + let request: MiMoV26AudioSidecarLoadRequest + let reservedLoadBytes: UInt64 + private let lock = NSLock() + private var invalid = false + init(_ request: MiMoV26AudioSidecarLoadRequest) { + self.request = request + reservedLoadBytes = request.requiredLoadBytes + } + func revoke() { lock.withLock { invalid = true } } + func validateActive() throws { + if lock.withLock({ invalid }) { throw MiMoV26AudioSidecarError.invalidatedOwner } + } + } + private final class WorkPermit: MiMoV26MediaWorkReservation, @unchecked Sendable { + private let lock = NSLock() + private var digest: String? + private var charge = 0 + private var releaseCount = 0 + private var failures: [MiMoV26FailedMediaWork] = [] + private var validations = 0 + private var kinds: [String] = [] + private var frames: [Int] = [] + var onValidation: (@Sendable (Int) -> Void)? + var bytes: Int { lock.withLock { charge } } + var retired: Int { lock.withLock { releaseCount } } + var retainedFailures: Int { lock.withLock { failures.count } } + var failedAudioRootCounts: [Int] { + lock.withLock { failures.flatMap(\.retainedAudioFailureRootCountsForTesting) } + } + var orderedKinds: [String] { lock.withLock { kinds } } + var pcmFrames: [Int] { lock.withLock { frames } } + func admit(_ plan: MiMoV26MultimodalPlan, bytes: Int) throws { + try lock.withLock { + guard digest == nil, bytes > 0 else { + throw MiMoV26MultimodalError.reservationRejected + } + digest = plan.preparationSHA256 + charge = bytes + kinds = plan.spans.map { $0.kind.rawValue } + frames = plan.audioPlan?.pcmDescriptors?.map(\.frameCount) ?? [] + } + } + func validate(plan: MiMoV26MultimodalPlan) throws { + let count: Int = try lock.withLock { + guard digest == plan.preparationSHA256, charge > 0, releaseCount == 0 else { + throw MiMoV26MultimodalError.reservationRejected + } + validations += 1 + return validations + } + onValidation?(count) + } + func retainAfterFailedDrain(_ work: MiMoV26FailedMediaWork) { + lock.withLock { + if !failures.contains(where: { $0 === work }) { failures.append(work) } + } + } + func retire() throws { + try lock.withLock { + guard failures.isEmpty, releaseCount == 0 else { throw Failure.noProof } + charge = 0 + releaseCount = 1 + } + } + } + private final class Cancel: @unchecked Sendable { + private let lock = NSLock() + private var value = false + private var beforeRoots: Int? + var rootsBeforeAudio: Int? { lock.withLock { beforeRoots } } + func recordRootsBeforeAudio(_ value: Int) { lock.withLock { beforeRoots = value } } + var cancelled: Bool { lock.withLock { value } } + func set() { lock.withLock { value = true } } + } + private struct Loader: TokenizerLoader { + func load(from directory: URL) async throws -> any MLXLMCommon.Tokenizer { + let raw = try await AutoTokenizer.from(modelFolder: directory) + return #adaptHuggingFaceTokenizer(raw) + } + } + private struct Fixture: Sendable { + let container: ModelContainer + let engine: EngineV2 + let construction: NativeConstructionWork + let audioPermit: AudioPermit? + let contract: CBv2NativeExecutionContract + } + private struct Built: Sendable { + let engine: EngineV2 + let contract: CBv2NativeExecutionContract + } + private static let limits = MiMoV26MultimodalLimits( + maximumMedia: 4, maximumVideoFrames: 4, maximumPromptTokens: 2048, + maximumMetadataBytes: 1 << 20, maximumMetadataNodes: 10000, maximumMetadataDepth: 32, + pixels: .init( + maximumInputElements: 100000, maximumOutputElements: 100000, + maximumWorkingBytes: 1 << 20), + vision: .init(maximumPatches: 256, maximumAttentionScoreElements: 131072), + audio: .init( + maximumClips: 2, maximumChannels: 1, maximumSampleRate: 24000, + maximumInputSamples: 48000, maximumResampledSamples: 48000, + maximumResampleCoefficients: 100000, maximumMelFrames: 256, maximumSegments: 4, + maximumPaddedMelFrames: 256, maximumWorkingElements: 64_000_000, + frontendFrameBlockSize: 8, rvqTileFrames: 8), + audioPatch: .init( + maximumClips: 2, maximumFrames: 256, maximumPatches: 64, + maximumWorkingElements: 16_000_000)) + + private func fixture( + profile: Profile = .audio, installAudio: Bool = true, + enableMTP: Bool = false + ) async throws -> Fixture { + let env = ProcessInfo.processInfo.environment + guard env["MIMO_V26_SERIAL_NATIVE_TESTS"] == "1", + env["MIMO_V26_MANAGED_AUDIO_NATIVE_TESTS"] == "1" + else { throw Failure.nativeLaneRequired } + guard let path = env["MIMO_V26_MANAGED_AUDIO_FIXTURE_ROOT"] else { + throw Failure.inputRequired + } + let root = URL(fileURLWithPath: path) + // Deliberately excludes a full target: the real selected SIDE-CAR is + // separate and authenticated by its existing loader below. + let provenanceFile = try FileHandle( + forReadingFrom: root.appendingPathComponent("provenance.json")) + defer { try? provenanceFile.close() } + let provenanceData = try XCTUnwrap(provenanceFile.read(upToCount: 65537)) + guard provenanceData.count <= 65536 else { throw Failure.inputRequired } + let p = try XCTUnwrap( + JSONSerialization.jsonObject(with: provenanceData) as? [String: String]) + let provenance = try MiMoV26ConvertedProvenance( + artifactID: XCTUnwrap(p["artifactID"]), + sourceRepository: XCTUnwrap(p["sourceRepository"]), + sourceRevision: XCTUnwrap(p["sourceRevision"]), + conversionManifestSHA256: XCTUnwrap(p["conversionManifestSHA256"])) + let plan = try MiMoV26FilesystemWeights.preflight( + root: root, provenance: provenance, + limits: .init(maximumShardBytes: 64 << 20, maximumTotalFileBytes: 128 << 20)) + let session = try MiMoV26SerialLoadSession(plan: plan) + let config = plan.bundlePlan.configuration + guard config.vocabularySize > 151674, config.hiddenSize <= 64, + config.numHiddenLayers <= 4 + else { throw Failure.inputRequired } + let prepared = try await MiMoV26ModelFactory.prepare( + request: session.request, + configuration: .init(directory: root), tokenizerLoader: Loader()) + let construction = NativeConstructionWork() + defer { + if construction.snapshot.isRetainedFault { _ = Unmanaged.passRetained(construction) } + } + let container = try await MiMoV26ModelFactory.loadContainer( + session: session, + reservation: RootPermit(session.request), prepared: prepared, retaining: construction) + try await construction.acknowledgeContainerAdoption(container) + let sidecar: SendableBox? + let permit: AudioPermit? + if installAudio { + let value = try MiMoV26AudioSidecarLoadSession( + root: root, mainConfiguration: config, + mainConfigurationSHA256: plan.bundlePlan.configSHA256) + sidecar = SendableBox(value) + permit = AudioPermit(value.request) + } else { + sidecar = nil + permit = nil + } + let built = try await MiMoV26ModelFactory.withNativeConstruction( + container: container, retaining: construction + ) { model, scope in + if let sidecar, let permit { + _ = try model.installAudioSidecar( + session: sidecar.consume(), reservation: permit, + retaining: scope, isCancelled: { false }) + } + let binding = try model.makeCBv2Binding(enableMTP: enableMTP) + _ = try binding.adapter.probeNativeKVTypes(retaining: scope) + let resources: MiMoV26ManagedMediaExecutionResources + switch profile { + case .audio: + resources = try model.makeManagedAudioExecutionResources( + binding: binding, + bytesCapacity: 32 << 20, limits: Self.limits, retaining: scope) + case .visual: + resources = try model.makeManagedMediaExecutionResources( + binding: binding, + bytesCapacity: 32 << 20, limits: Self.limits, retaining: scope) + case .text: + let text = try binding.adapter.makeNativeExecutionResources( + bytesCapacity: 32 << 20, retaining: scope) + resources = .init( + backend: text.backend, cacheProvider: text.cacheProvider, + contract: text.contract) + } + let engine = EngineV2( + model: binding.adapter, layerKinds: binding.adapter.layerKinds, + backend: resources.backend, cacheProvider: resources.cacheProvider, + schedulerConfig: .init( + maxConcurrentRequests: 1, maxBatchedTokensPerStep: 4, + prefillChunkSize: 3, maxConcurrentPartialPrefills: 1, enablePrefixCache: false), + loopConfig: .init(stepTimeout: 60, watchdogInterval: 0.01, shutdownTimeout: 10), + mtpDrafter: binding.assistant, + mtpConfig: .init( + enabled: enableMTP, maxDraftTokens: 2, + maxSpeculativeBatch: 1, fixedDraftTokens: 2, verificationMode: .serialTarget), + nativeCompletionTracking: true, nativeExecutionContract: resources.contract) + try scope.retainOwner(engine) + return Built(engine: engine, contract: resources.contract) + } + guard case .completed(let completion) = construction.snapshot.disposition else { + throw Failure.noProof + } + try await construction.sealForPublication(completion) + return .init( + container: container, engine: built.engine, construction: construction, + audioPermit: permit, contract: built.contract) + } + private func input(mixed: Bool = false) throws -> MiMoV26MultimodalInput { + let pcm = try MiMoV26DecodedPCM( + samples: (0 ..< 2400).map { sin(Float($0) * 0.02) * 0.05 }, + descriptor: .init( + sourceIdentity: "synthetic-sine-owned-pcm", channels: 1, + frameCount: 2400, sampleRate: 24000)) + var parts: [MiMoV26MultimodalContent] = [] + if mixed { + parts.append( + .image( + .init( + height: 4, width: 4, + planarRGB: (0 ..< 48).map { Float(($0 * 17) % 256) }))) + } + parts += [.text("listen"), .audio(pcm), .text("describe")] + return .init(messages: [.init(role: .user, content: parts)], maximumOutputTokens: 2) + } + private func prepared( + _ fixture: Fixture, input: MiMoV26MultimodalInput, + reservation: WorkPermit = WorkPermit(), cancel: Cancel = Cancel() + ) async throws -> (CBv2Request, WorkPermit) { + let request = try await fixture.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + return try model.prepareManagedDecodedAudioMedia( + input, engine: fixture.engine, + authorize: { plan, bytes in + try reservation.admit(plan, bytes: bytes) + return reservation + }, + retire: { _ in try reservation.retire() }, isCancelled: { cancel.cancelled }) + } + return (request, reservation) + } + private func shutdown(_ fixture: Fixture) async throws { + guard + case .quiescent(let receipt) = await fixture.engine.shutdownReportingNativeCompletion() + else { + _ = Unmanaged.passRetained(fixture.engine) + _ = Unmanaged.passRetained(fixture.container) + _ = Unmanaged.passRetained(fixture.construction) + throw Failure.noProof + } + XCTAssertEqual(receipt.executionContractID, fixture.contract.id) + if fixture.contract.supportsDecodedAudioMedia { + try await fixture.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + try model.releaseManagedAudioAfterNativeRetirement(receipt) + XCTAssertNil(model.resources.audioSidecar) + } + } + } + + func testRealPCMAndOrderedMixedPreparationSubmitRetireThenTextOnSameEngine() async throws { + let f = try await fixture() + XCTAssertTrue(f.contract.supportsDecodedAudioMedia) + XCTAssertFalse(f.contract.supportsDecodedVisualMedia) + XCTAssertEqual(f.contract.audioSidecarSessionID, f.audioPermit?.request.sessionID) + let epoch = f.construction.snapshot.epoch + for mixed in [false, true] { + var (request, permit) = try await prepared(f, input: input(mixed: mixed)) + request.id = .init(mixed ? 2 : 1) + request.sampling = .init(temperature: 0) + XCTAssertNotNil(request.multimodal?.nativeMediaToken) + XCTAssertGreaterThan(permit.bytes, 0) + XCTAssertEqual(permit.orderedKinds, mixed ? ["image", "audio"] : ["audio"]) + XCTAssertEqual(permit.pcmFrames, [2400]) + let submission = try f.engine.submitWithNativeRetirement(request) + let result = await cbv2SchedCollect(submission.events) + await submission.retirement.wait() + XCTAssertFalse(result.tokens.isEmpty) + XCTAssertEqual(permit.retired, 1) + XCTAssertEqual(permit.bytes, 0) + XCTAssertEqual(f.audioPermit?.reservedLoadBytes, 3_879_023_504) + XCTAssertThrowsError(try f.engine.submitWithNativeRetirement(request)) + } + let text = CBv2Request( + id: .init(3), promptTokens: [20, 21, 22, 23], + sampling: .init(temperature: 0), maxTokens: 2, prefixCacheEnabled: false) + let submission = try f.engine.submitWithNativeRetirement(text) + let textResult = await cbv2SchedCollect(submission.events) + XCTAssertFalse(textResult.tokens.isEmpty) + await submission.retirement.wait() + XCTAssertEqual(f.construction.snapshot.epoch, epoch) + try await shutdown(f) + } + + func testTextAndVisualProfilesDoNotGainAudioFromInstalledSidecar() async throws { + for profile in [Profile.text, .visual] { + let f = try await fixture(profile: profile) + XCTAssertFalse(f.contract.supportsDecodedAudioMedia) + do { + _ = try await prepared(f, input: input()) + XCTFail("audio profile bypass") + } catch { XCTAssertEqual(error as? MiMoV26MultimodalError, .incompatibleOwner) } + XCTAssertNil(f.engine.nativeCompletionFault) + if profile == .visual { + let pcm = try input() + do { + _ = try await f.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + return try model.prepareManagedDecodedMedia( + pcm, engine: f.engine, + authorize: { _, _ in + XCTFail("visual profile admitted PCM") + return WorkPermit() + }, + retire: { _ in XCTFail("visual profile issued audio retirement") }, + isCancelled: { false }) + } + XCTFail("visual PCM accepted") + } catch { XCTAssertEqual(error as? MiMoV26MultimodalError, .missingAudioCodec) } + } + try await shutdown(f) + } + } + + func testActualInstalledTextMTPRemainsActiveAfterTargetOnlyAudio() async throws { + let f = try await fixture(enableMTP: true) + XCTAssertTrue(CBv2MTPConfig.envEnabled, "run ON selector with the real kill switch enabled") + let (request, permit) = try await prepared(f, input: input()) + let media = try f.engine.submitWithNativeRetirement(request) + _ = await cbv2SchedCollect(media.events) + await media.retirement.wait() + XCTAssertEqual(permit.retired, 1) + XCTAssertEqual( + try XCTUnwrap(f.engine.mtpMetricsSnapshot()).draftedTokens, 0, + "audio row must use the real target-only media fallback") + let text = CBv2Request( + id: .init(19), promptTokens: Array(repeating: 20, count: 13), + sampling: .init(temperature: 0), maxTokens: 8, stopTokens: [], prefixCacheEnabled: false + ) + let submission = try f.engine.submitWithNativeRetirement(text) + let output = await cbv2SchedCollect(submission.events) + await submission.retirement.wait() + XCTAssertEqual(output.tokens.count, 8) + XCTAssertGreaterThan(try XCTUnwrap(f.engine.mtpMetricsSnapshot()).draftedTokens, 0) + try await shutdown(f) + } + + func testActualSidecarInvalidationAtBindingRefusesWhenBareCodecStillValid() async throws { + let f = try await fixture() + let (request, permit) = try await prepared(f, input: input()) + try await f.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + let sidecar = try XCTUnwrap(model.resources.audioSidecar) + try sidecar.codec.validate() + sidecar.invalidate() + XCTAssertNoThrow( + try sidecar.codec.validate(), "discriminator: bare codec is insufficient") + } + XCTAssertThrowsError(try f.engine.submitWithNativeRetirement(request)) + XCTAssertEqual(permit.retired, 0) + f.engine.discardUnsubmittedNativeMedia(try XCTUnwrap(request.multimodal)) + XCTAssertEqual(permit.retired, 1) + try await shutdown(f) + } + + func testForeignActualEngineCannotBorrowTheLoadedAudioProfile() async throws { + let audio = try await fixture() + let foreign = try await fixture(profile: .text, installAudio: false) + let pcm = try input() + do { + _ = try await audio.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + return try model.prepareManagedDecodedAudioMedia( + pcm, engine: foreign.engine, + authorize: { _, _ in + XCTFail("foreign engine reached audio admission") + return WorkPermit() + }, + retire: { _ in XCTFail("foreign engine issued retirement") }, + isCancelled: { false }) + } + XCTFail("foreign engine accepted") + } catch { XCTAssertEqual(error as? MiMoV26MultimodalError, .incompatibleOwner) } + XCTAssertNil(audio.engine.nativeCompletionFault) + XCTAssertNil(foreign.engine.nativeCompletionFault) + try await shutdown(foreign) + try await shutdown(audio) + } + + func testSupportedLoadedGenerationInvalidationRejectsAlreadyPreparedAudio() async throws { + let f = try await fixture() + let (request, permit) = try await prepared(f, input: input()) + try await f.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + model.invalidateMultimodalPreparation() + } + XCTAssertThrowsError(try f.engine.submitWithNativeRetirement(request)) + XCTAssertEqual(permit.retired, 0) + f.engine.discardUnsubmittedNativeMedia(try XCTUnwrap(request.multimodal)) + XCTAssertEqual(permit.retired, 1) + try await shutdown(f) + } + + func testSeparateSidecarReservationRevocationRefusesBeforeWarmWorkAndAtActualBind() async throws + { + let f = try await fixture() + let (request, permit) = try await prepared(f, input: input()) + try XCTUnwrap(f.audioPermit).revoke() + do { + _ = try await prepared(f, input: input()) + XCTFail("revoked load owner prepared audio") + } catch { XCTAssertEqual(error as? MiMoV26AudioSidecarError, .invalidatedOwner) } + XCTAssertThrowsError(try f.engine.submitWithNativeRetirement(request)) + XCTAssertNil(f.engine.nativeCompletionFault) + f.engine.discardUnsubmittedNativeMedia(try XCTUnwrap(request.multimodal)) + XCTAssertEqual(permit.retired, 1) + try await shutdown(f) + } + + func testAudioLoanPrecedesCodecAndSuccessfullyDrainedCancellationKeepsEngineHealthy() + async throws + { + let f = try await fixture() + let permit = WorkPermit() + let cancel = Cancel() + // Actual audio-only source sequence: outer authorize/check(1/2), part + // check(3), audio phase check(4), inner codec pre-front-end check(5), + // post-front-end/pre-eval check(6). No elapsed-time approximation. + permit.onValidation = { count in + if count == 4 { + cancel.recordRootsBeforeAudio( + f.engine.loopForTesting.nativeShutdownState?.debugRetainedRootCount ?? 0) + } + if count == 5 { + guard let before = cancel.rootsBeforeAudio else { + return XCTFail("missing actual pre-audio phase") + } + XCTAssertEqual( + f.engine.loopForTesting.nativeShutdownState?.debugRetainedRootCount, before + 1, + "exact new registration must precede codec work; the pre-existing owner root is not proof" + ) + } + if count == 6 { cancel.set() } // real mel eval/readback then typed cancellation/drain + } + do { + _ = try await prepared(f, input: input(), reservation: permit, cancel: cancel) + XCTFail("cancelled PCM prepared") + } catch { XCTAssertEqual(error as? MiMoV26MultimodalError, .cancelled) } + XCTAssertTrue(cancel.cancelled, "must enter actual codec, not a pre-work cancellation") + XCTAssertEqual(permit.retired, 1) + XCTAssertEqual(permit.bytes, 0) + XCTAssertNil(f.engine.nativeCompletionFault) + let (request, healthy) = try await prepared(f, input: input()) + let submission = try f.engine.submitWithNativeRetirement(request) + _ = await cbv2SchedCollect(submission.events) + await submission.retirement.wait() + XCTAssertEqual(healthy.retired, 1) + try await shutdown(f) + } + + func testInnerRequiredCodesReadbackFailureRetainsOriginalInnerRootsBeforeCleanup() async throws + { + #if DEBUG + guard ProcessInfo.processInfo.environment["MIMO_V26_MANAGED_AUDIO_FAULT_TEST"] == "1" + else { + throw Failure.nativeLaneRequired + } + let f = try await fixture() + let permit = WorkPermit() + let reached = Cancel() + try await f.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + let input = try XCTUnwrap(model.resources.audioSidecar).codec.input + input.beforeManagedRequiredCompletionForTesting = { phase in + if case .codesReadback = phase { + reached.set() + throw Failure.injected + } + } + } + do { + _ = try await prepared(f, input: input(), reservation: permit) + XCTFail("required inner readback succeeded") + } catch { XCTAssertEqual(error as? MiMoV26MultimodalError, .drainFailed) } + XCTAssertTrue( + reached.cancelled, + "real frontend/encoder/RVQ evaluation must reach the required readback") + XCTAssertFalse( + permit.failedAudioRootCounts.isEmpty, + "the ORIGINAL inner owner must transfer before cleanup") + XCTAssertTrue(permit.failedAudioRootCounts.allSatisfy { $0 > 0 }) + XCTAssertEqual(permit.retired, 0) + XCTAssertGreaterThan(permit.bytes, 0) + XCTAssertEqual(f.audioPermit?.reservedLoadBytes, 3_879_023_504) + let roots = permit.failedAudioRootCounts + try await f.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + try XCTUnwrap(model.resources.audioSidecar).codec.input + .beforeManagedRequiredCompletionForTesting = nil + } + guard case .incomplete = await f.engine.shutdownReportingNativeCompletion() else { + XCTFail("required inner failure was rehabilitated") + _ = Unmanaged.passRetained(f.engine) + return + } + XCTAssertEqual(permit.failedAudioRootCounts, roots) + XCTAssertEqual(permit.retired, 0) + _ = Unmanaged.passRetained(f.engine) + _ = Unmanaged.passRetained(f.container) + _ = Unmanaged.passRetained(permit) + _ = Unmanaged.passRetained(try XCTUnwrap(f.audioPermit)) + // Refusal injected at a required readback after REAL native evaluation, + // not evidence of a physical backend readback failure. + #else + throw Failure.nativeLaneRequired + #endif + } + + func testRequiredPreparationFenceFailureRetainsAudioOwnerAndBothObligations() async throws { + guard ProcessInfo.processInfo.environment["MIMO_V26_MANAGED_AUDIO_FAULT_TEST"] == "1" else { + throw Failure.nativeLaneRequired + } + let f = try await fixture() + let permit = WorkPermit() + f.engine.loopForTesting.onEngineQueueSync { + f.engine.loopForTesting.nativeShutdownState?.beforeFenceForTesting = { _ in + throw Failure.injected + } + } + do { + _ = try await prepared(f, input: input(), reservation: permit) + XCTFail("failed fence prepared audio") + } catch { XCTAssertEqual(error as? MiMoV26MultimodalError, .drainFailed) } + XCTAssertEqual(permit.retired, 0) + XCTAssertGreaterThan(permit.bytes, 0) + XCTAssertGreaterThan(permit.retainedFailures, 0) + XCTAssertEqual(f.audioPermit?.reservedLoadBytes, 3_879_023_504) + try await f.container.perform { context in + let model = try XCTUnwrap(context.model as? MiMoV26LoadedModel) + XCTAssertNotNil(model.resources.audioSidecar) + } + f.engine.loopForTesting.onEngineQueueSync { + f.engine.loopForTesting.nativeShutdownState?.beforeFenceForTesting = nil + } + guard case .incomplete = await f.engine.shutdownReportingNativeCompletion() else { + XCTFail("late successful fence rehabilitated the original required failure") + _ = Unmanaged.passRetained(f.engine) + return + } + XCTAssertEqual(permit.retired, 0) + _ = Unmanaged.passRetained(f.engine) + _ = Unmanaged.passRetained(f.container) + _ = Unmanaged.passRetained(permit) + _ = Unmanaged.passRetained(try XCTUnwrap(f.audioPermit)) + // Injected BEFORE-fence fault, not evidence of a physical backend failure. + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26MediaGeometryTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26MediaGeometryTests.swift new file mode 100644 index 0000000000..519b59e058 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26MediaGeometryTests.swift @@ -0,0 +1,308 @@ +import Foundation + +#if !MIMO_MEDIA_CPU_PROBE + import MLXVLM + import XCTest +#endif + +private enum MiMoV26MediaChecks { + typealias Geometry = MiMoV26MediaGeometry + struct Failure: Error, CustomStringConvertible { let description: String } + static func expect(_ value: Bool, _ message: String) throws { + if !value { throw Failure(description: message) } + } + static func native() throws -> Geometry.Settings { + try .init( + patchSize: 16, mergeSize: 2, temporalPatchSize: 2, temporalCompressionRatio: 1, + imageMinPixels: 8192, imageMaxPixels: 8_388_608, + videoMinPixels: 8192, videoMaxPixels: 8_388_608, videoTotalMaxPixels: 268_435_456) + } + static func rejects(_ body: () throws -> Void) throws { + do { + try body() + throw Failure(description: "invalid geometry accepted") + } catch is Geometry.Failure {} + } + static func pureCases() -> [(String, () throws -> Void)] { + [ + ( + "native still-image repetition and patch accounting", + { + let p = try Geometry.image(height: 64, width: 128, settings: native()) + try expect( + p.height == 64 && p.width == 128 && p.gridT == 1 && p.gridH == 4 + && p.gridW == 8, + "native image grid changed") + try expect( + p.alignedFrames == 2 && p.duplicatedFrames == 1 && p.patchCount == 32 + && p.patchVectorSize == 1536 && p.patchElementCount == 49152 + && p.mediaTokens == 8 && p.promptTokensExcludingTimestamps == 10, + "image patch/token accounting changed") + } + ), + ( + "native ties round to even rather than away from zero", + { + let s = try Geometry.Settings( + patchSize: 16, mergeSize: 2, temporalPatchSize: 2, + temporalCompressionRatio: 1, imageMinPixels: 1, imageMaxPixels: 1_000_000, + videoMinPixels: 1, videoMaxPixels: 1_000_000, videoTotalMaxPixels: 1_000_000 + ) + let p = try Geometry.image(height: 48, width: 80, settings: s) + try expect( + p.height == 64 && p.width == 64, "Python round(1.5)/round(2.5) parity") + } + ), + ( + "native tiny-axis branch precedes aspect refusal", + { + let p = try Geometry.image(height: 1, width: 201, settings: native()) + try expect( + p.height == 32 && p.width == 6432, + "tiny aspect branch incorrectly rejected or clamped") + try rejects { + _ = try Geometry.image(height: 32, width: 6432, settings: native()) + } + } + ), + ( + "video duplicates last odd frame and separates timestamp tokens", + { + let p = try Geometry.video( + height: 64, width: 128, sampledFrames: 3, settings: native()) + try expect( + p.alignedFrames == 4 && p.duplicatedFrames == 1 && p.gridT == 2 + && p.mediaTokens == 16 && p.timestampCount == 2 + && p.fixedWrapperTokens == 6 && p.promptTokensExcludingTimestamps == 22, + "video padding/token accounting") + } + ), + ( + "full sampled clip determines segment pixel cap", + { + let p = try Geometry.video( + height: 64, width: 128, sampledFrames: 1000, + segmentFrames: 3, settings: native()) + try expect( + p.effectiveMaxPixelsPerFrame == 536870 && p.alignedFrames == 4, + "segment count replaced full clip divisor") + } + ), + ( + "sampling maximum is not silently a geometry limit", + { + _ = try Geometry.video( + height: 64, width: 128, sampledFrames: 3601, settings: native()) + try rejects { + _ = try Geometry.video( + height: 64, width: 128, sampledFrames: 3601, + sampledFrameLimit: 3600, settings: native()) + } + } + ), + ( + "native minimum floor reports soft aggregate overrun", + { + let s = try Geometry.Settings( + patchSize: 16, mergeSize: 2, temporalPatchSize: 2, + temporalCompressionRatio: 1, imageMinPixels: 8192, + imageMaxPixels: 8_388_608, + videoMinPixels: 8192, videoMaxPixels: 8_388_608, videoTotalMaxPixels: 1) + let p = try Geometry.video( + height: 64, width: 128, sampledFrames: 1, settings: s) + try expect( + p.effectiveMaxPixelsPerFrame == 8192 && p.aggregateBudgetPixels == 8192 + && p.exceedsAggregateBudget, "minimum floor was clamped or hidden") + } + ), + ( + "temporal duplication alone can exceed aggregate budget", + { + let s = try Geometry.Settings( + patchSize: 1, mergeSize: 1, temporalPatchSize: 2, + temporalCompressionRatio: 1, imageMinPixels: 1, imageMaxPixels: 100, + videoMinPixels: 1, videoMaxPixels: 100, videoTotalMaxPixels: 10) + let p = try Geometry.video(height: 2, width: 3, sampledFrames: 3, settings: s) + try expect( + p.effectiveMaxPixelsPerFrame == 6 && p.aggregateBudgetPixels == 12 + && p.exceedsAggregateBudget && !p.exceedsPerFrameMaximum, + "odd padding aggregate cost omitted") + } + ), + ( + "native and generic HF sidecar bounds remain distinct", + { + let generic = try Geometry.Settings( + patchSize: 16, mergeSize: 2, temporalPatchSize: 2, + temporalCompressionRatio: 1, imageMinPixels: 3136, + imageMaxPixels: 12_845_056, + videoMinPixels: 8192, videoMaxPixels: 8_388_608, + videoTotalMaxPixels: 268_435_456) + let n = try Geometry.image(height: 64, width: 64, settings: native()) + let g = try Geometry.image(height: 64, width: 64, settings: generic) + try expect( + n.height == 96 && n.width == 96 && g.height == 64 && g.width == 64, + "generic metadata replaced native bounds") + } + ), + ( + "invalid and unrepresentable inputs reject recoverably", + { + for (h, w) in [ + (0, 64), (-1, 64), (64, 0), (Int.max, 64), (Int(Int32.max), Int(Int32.max)), + ] { + try rejects { + _ = try Geometry.image(height: h, width: w, settings: native()) + } + } + for frames in [0, -1, Int.max] { + try rejects { + _ = try Geometry.video( + height: 64, width: 64, sampledFrames: frames, settings: native()) + } + } + try rejects { + _ = try Geometry.video( + height: 64, width: 64, sampledFrames: 4, segmentFrames: 5, + settings: native()) + } + try rejects { + _ = try Geometry.video( + height: 64, width: 64, sampledFrames: 4, sampledFrameLimit: 0, + settings: native()) + } + } + ), + ( + "decoded settings cannot bypass operational validation", + { + var raw = + try JSONSerialization.jsonObject(with: JSONEncoder().encode(native())) + as! [String: Any] + raw["patchSize"] = 0 + let decoded = try JSONDecoder().decode( + Geometry.Settings.self, from: JSONSerialization.data(withJSONObject: raw)) + try rejects { _ = try Geometry.image(height: 64, width: 64, settings: decoded) } + raw["patchSize"] = Int.max + let large = try JSONDecoder().decode( + Geometry.Settings.self, from: JSONSerialization.data(withJSONObject: raw)) + try rejects { _ = try Geometry.image(height: 64, width: 64, settings: large) } + } + ), + ( + "patch count overflow and native soft spatial bounds", + { + try rejects { + _ = try Geometry.video( + height: 64, width: 128, sampledFrames: Int(Int32.max) - 1, + settings: native()) + } + let s = try Geometry.Settings( + patchSize: 16, mergeSize: 2, temporalPatchSize: 2, + temporalCompressionRatio: 1, imageMinPixels: 5000, imageMaxPixels: 5000, + videoMinPixels: 8192, videoMaxPixels: 8_388_608, + videoTotalMaxPixels: 268_435_456) + let up = try Geometry.image(height: 32, width: 32, settings: s) + let down = try Geometry.image(height: 100, width: 100, settings: s) + try expect( + up.height == 96 && up.width == 96 && up.exceedsPerFrameMaximum, + "native ceil overshoot was silently clamped") + try expect( + down.height == 64 && down.width == 64 && down.belowPerFrameMinimum, + "native floor undershoot was silently clamped") + } + ), + ] + } + + struct Vector: Decodable { + let id, kind: String + let height, width: Int + let sampledFrames, segmentFrames, sampledFrameLimit: Int? + let settings: Geometry.Settings + let expected: Geometry.Plan? + let expectsFailure: Bool + } + struct Corpus: Decodable { + let schemaVersion: Int + let vectors: [Vector] + } + static func referenceCases(_ path: String) throws -> [(String, () throws -> Void)] { + let corpus = try JSONDecoder().decode( + Corpus.self, from: Data(contentsOf: URL(fileURLWithPath: path))) + try expect(corpus.schemaVersion == 1 && !corpus.vectors.isEmpty, "empty reference corpus") + try expect( + Set(corpus.vectors.map(\.id)).count == corpus.vectors.count, "duplicate reference IDs") + return corpus.vectors.map { v in + ( + v.id, + { + func run() throws -> Geometry.Plan { + if v.kind == "image" { + return try Geometry.image( + height: v.height, width: v.width, settings: v.settings) + } + try expect( + v.kind == "video" && v.sampledFrames != nil, "invalid fixture kind") + return try Geometry.video( + height: v.height, width: v.width, sampledFrames: v.sampledFrames!, + segmentFrames: v.segmentFrames, sampledFrameLimit: v.sampledFrameLimit, + settings: v.settings) + } + if v.expectsFailure { + try rejects { _ = try run() } + } else { + try expect(try run() == v.expected, "scalar reference divergence: \(v.id)") + } + } + ) + } + } +} + +#if MIMO_MEDIA_CPU_PROBE + @main private struct MiMoV26MediaCPUProbe { + static func main() throws { + guard CommandLine.arguments.count == 2 else { + throw MiMoV26MediaChecks.Failure(description: "expected scalar vector path") + } + let tests = + MiMoV26MediaChecks.pureCases() + + (try MiMoV26MediaChecks.referenceCases(CommandLine.arguments[1])) + var failures = 0 + for (name, test) in tests { + do { + try test() + print("PASS \(name)") + } catch { + failures += 1 + print("FAIL \(name): \(error)") + } + } + print( + "RESULT discovered=\(tests.count) passed=\(tests.count - failures) failed=\(failures) skipped=0" + ) + if failures > 0 { + throw MiMoV26MediaChecks.Failure(description: "geometry probe failed") + } + } + } +#else + final class MiMoV26MediaGeometryTests: XCTestCase { + func testNativeGeometryContracts() throws { + for (name, test) in MiMoV26MediaChecks.pureCases() { + do { try test() } catch { XCTFail("\(name): \(error)") } + } + } + func testIndependentScalarVectors() throws { + guard let path = ProcessInfo.processInfo.environment["MIMO_MEDIA_REFERENCE_VECTORS"] + else { + throw XCTSkip( + "Set MIMO_MEDIA_REFERENCE_VECTORS for the independent scalar reference corpus") + } + for (name, test) in try MiMoV26MediaChecks.referenceCases(path) { + do { try test() } catch { XCTFail("\(name): \(error)") } + } + } + } +#endif diff --git a/Tests/MLXLMTests/MiMo/MiMoV26MediaMTPFallbackTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26MediaMTPFallbackTests.swift new file mode 100644 index 0000000000..cfe829147f --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26MediaMTPFallbackTests.swift @@ -0,0 +1,1144 @@ +import Foundation +import MLX +import MLXNN +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon +@testable import MLXVLM + +// DIRECT / UNTRACKED numerical and scheduler fixtures, including AUTO mode. +// A retained probe scope proves only its own real construction completion; it +// does not mint the SDK's strict-loaded execution contract or qualify managed +// media retirement. Observer wrappers and retained numeric carry views remain +// outside that tracked profile. Do not weaken the F1 request/issuer guards. +private func withMiMoMediaMTPConstructionScope( + _ body: (NativeConstructionScope) throws -> Value +) rethrows -> Value { + let work = NativeConstructionScope() + defer { + // Same real failed-probe ownership pattern as the current multimodal + // tests: a genuine retained completion fault lives to test-process exit. + if work.snapshot.isRetainedFault { _ = Unmanaged.passRetained(work) } + } + return try body(work) +} + +/// Ordinary coexistence records metadata only. A separately enabled NUMERIC +/// cell retains one genuine seed carry/reference pair until engine drain; that +/// cell is not lifecycle/memory/performance evidence. No hot-path readback, +/// fabricated hidden row, scripted proposal or replacement logits are used. +private final class MiMoMediaMTPTrace { + struct Row { + let id: CBv2RequestID + let arrival: UInt64 + let media: Bool + } + struct State { + let step: Int + let earlyDrafts: Int + let rounds: Int + let drafted: Int + let liveMedia: [Row] + let roundDepths: [CBv2RequestID: Int] + let seedIDs: Set + let marginal: Bool + } + struct Forward { + let kind: String + let rows: [Row] + let shape: [Int] + let state: State? + } + struct Sample { + let step: Int + let ids: [CBv2RequestID] + } + struct Witness { + let step: Int + let media: Row + let text: Row + let depth: Int + let completedStep: Int + } + struct NumericSeed { + let id: CBv2RequestID + let step: Int + let expectedHidden: MLXArray + var sampleIDs: [CBv2RequestID] = [] + var policyValues: MLXArray? + var stored: CBv2MTPCarryObservationForTesting? + var actualHidden: MLXArray? + } + var identify: (([CBv2AttendingLayerCache]) -> [Row])? + var inspect: (([CBv2RequestID]) -> Bool)? + var state: (() -> State?)? + let numeric: Bool + private let lock = NSLock() + private var forwards: [Forward] = [], samples: [Sample] = [] + private var cleanMediaHistory = true + private var witnesses: [Witness] = [] + private var scalarCarries: [CBv2MTPCarryObservationForTesting] = [] + private var numericSeed: NumericSeed? + private var compactPolicyCalls = 0 + init(numeric: Bool = false) { self.numeric = numeric } + private func completedBoundary(_ current: State) { + // Called on the engine queue. A round is not qualified by a mark or + // launch: require the immediately following step's completed counters + // and the SAME still-live, unpaused media generation. + for verify in forwards where verify.kind == "hidden" && verify.rows.count == 1 { + guard let before = verify.state, current.step == before.step + 1, + let text = verify.rows.first, !text.media, + let depth = before.roundDepths[text.id], depth > 0, + current.rounds == before.rounds + 1, current.drafted == before.drafted + depth, + !witnesses.contains(where: { $0.step == before.step }) + else { continue } + for media in before.liveMedia { + guard + current.liveMedia.contains(where: { + $0.id == media.id && $0.arrival == media.arrival + }), + let ordinary = forwards.first(where: { + $0.kind == "ordinary" && $0.state?.step == before.step + && $0.rows.contains(where: { + $0.id == media.id && $0.arrival == media.arrival + }) + }), let ordinaryState = ordinary.state, + before.earlyDrafts == ordinaryState.earlyDrafts + 1, + samples.contains(where: { $0.step == before.step && $0.ids.contains(media.id) }) + else { continue } + witnesses.append( + .init( + step: before.step, media: media, text: text, depth: depth, + completedStep: current.step)) + } + } + } + @discardableResult + func forward(_ kind: String, _ tokens: MLXArray, _ caches: [CBv2AttendingLayerCache]) + -> Forward? + { + guard let identify else { return nil } + let rows = identify(caches) + let current = state?() + let value = Forward(kind: kind, rows: rows, shape: tokens.shape, state: current) + lock.lock() + if let current { completedBoundary(current) } + forwards.append(value) + lock.unlock() + return value + } + func sample(_ ids: [CBv2RequestID], step: Int) { + let clean = inspect?(ids) ?? true + let current = state?() + lock.lock() + if let current { completedBoundary(current) } + samples.append(.init(step: step, ids: ids)) + cleanMediaHistory = cleanMediaHistory && clean + lock.unlock() + } + func hidden(_ hidden: MLXArray, frame: Forward?) { + guard numeric, let frame, let current = frame.state, current.marginal, + frame.kind == "hidden", frame.rows.count == 1, + let row = frame.rows.first, current.seedIDs.contains(row.id), + !current.liveMedia.isEmpty + else { return } + lock.lock() + defer { lock.unlock() } + if let pending = numericSeed, pending.policyValues == nil, pending.step < current.step { + numericSeed = nil + } + guard numericSeed == nil else { return } + // Reference is the actual singleton text target output, not a zero or + // media placeholder. No additional graph operation is built here. + numericSeed = .init(id: row.id, step: current.step, expectedHidden: hidden) + } + func policy(_ values: MLXArray) { + guard let current = state?(), current.marginal else { return } + lock.lock() + defer { lock.unlock() } + guard let sample = samples.last, sample.step == current.step, sample.ids.count == 2, + current.liveMedia.contains(where: { sample.ids.contains($0.id) }) + else { return } + compactPolicyCalls += 1 + guard numeric, numericSeed?.step == current.step, numericSeed?.policyValues == nil else { + return + } + numericSeed?.sampleIDs = sample.ids + numericSeed?.policyValues = values + } + func carry(_ value: CBv2MTPCarryObservationForTesting) { + let current = state?() + lock.lock() + defer { lock.unlock() } + scalarCarries.append(value) + if numeric, numericSeed?.id == value.id, numericSeed?.stored == nil, + numericSeed?.policyValues != nil, + numericSeed?.step == (current?.step ?? -1) - 1, value.previousTopTwoMargin != nil + { + numericSeed?.stored = value + } + } + func carryHidden(_ id: CBv2RequestID, _ hidden: MLXArray) { + guard numeric else { return } + lock.lock() + defer { lock.unlock() } + guard numericSeed?.id == id, numericSeed?.stored != nil, numericSeed?.actualHidden == nil + else { return } + numericSeed?.actualHidden = hidden + } + func snapshot() -> ([Forward], [Sample], Bool) { + lock.lock() + defer { lock.unlock() } + return (forwards, samples, cleanMediaHistory) + } + func proof() -> ([Witness], [CBv2MTPCarryObservationForTesting], Int) { + lock.lock() + defer { lock.unlock() } + return (witnesses, scalarCarries, compactPolicyCalls) + } + func takeNumericSeedAfterDrain() -> NumericSeed? { + lock.lock() + defer { lock.unlock() } + let value = numericSeed + numericSeed = nil + return value + } + func clearAfterDrain() { + lock.lock() + numericSeed = nil + lock.unlock() + identify = nil + inspect = nil + state = nil + } +} + +/// A transparent test interposer, not another Module/parameter tree. The +/// actual MiMo adapter, loaded target identity and trained heads are unchanged. +private final class MiMoMediaMTPObservedTarget: CBv2MTPRequestScopedMediaFallback, + CBv2MTPPrefillSteppableModel, CBv2PrefillSteppableModel, + CBv2ModelCapabilityProviding, CBv2MTPPolicyTopTwoProviding +{ + let native: MiMoV26CBv2Adapter + let trace: MiMoMediaMTPTrace + init(_ native: MiMoV26CBv2Adapter, _ trace: MiMoMediaMTPTrace) { + self.native = native + self.trace = trace + } + var cbv2Capabilities: CBv2ModelCapabilities { native.cbv2Capabilities } + var mtpCaptureLayers: CBv2MTPCaptureLayers? { native.mtpCaptureLayers } + var mtpTargetIdentity: ObjectIdentifier? { native.mtpTargetIdentity } + var supportsRequestStatefulMTP: Bool { native.supportsRequestStatefulMTP } + var supportsMultimodalPrefill: Bool { native.supportsMultimodalPrefill } + var causalPositionRequirement: CBv2CausalPositionRequirement { + native.causalPositionRequirement + } + func supportsMultimodalPrefill(attention: CBv2MultimodalAttention) -> Bool { + native.supportsMultimodalPrefill(attention: attention) + } + func embedPromptTokens(_ tokens: MLXArray) -> MLXArray { native.embedPromptTokens(tokens) } + func forward(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> MLXArray { + trace.forward("ordinary", tokens, caches) + return native.forward(tokens: tokens, caches: caches) + } + func forward(tokens: MLXArray, inputEmbeddings: MLXArray, caches: [CBv2AttendingLayerCache]) + -> MLXArray + { + trace.forward("embedding", tokens, caches) + return native.forward(tokens: tokens, inputEmbeddings: inputEmbeddings, caches: caches) + } + func prefill( + tokens: MLXArray, inputEmbeddings: MLXArray?, caches: [CBv2AttendingLayerCache], + requirement: CBv2PrefillRequirement + ) -> MLXArray { + trace.forward(inputEmbeddings == nil ? "prefill" : "media-prefill", tokens, caches) + return native.prefill( + tokens: tokens, inputEmbeddings: inputEmbeddings, caches: caches, + requirement: requirement) + } + func forwardWithHidden(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> ( + logits: MLXArray, lastHidden: MLXArray + ) { + let frame = trace.forward("hidden", tokens, caches) + let output = native.forwardWithHidden(tokens: tokens, caches: caches) + trace.hidden(output.lastHidden, frame: frame) + return output + } + func forwardWithHiddenForPrefill( + tokens: MLXArray, caches: [CBv2AttendingLayerCache], + requirement: CBv2PrefillRequirement + ) -> (logits: MLXArray, lastHidden: MLXArray) { + trace.forward("hidden-prefill", tokens, caches) + return native.forwardWithHiddenForPrefill( + tokens: tokens, caches: caches, requirement: requirement) + } + func cbv2MTPTopTwo(_ logits: MLXArray) -> (ids: MLXArray, values: MLXArray) { + let output = native.cbv2MTPTopTwo(logits) + trace.policy(output.values) + return output + } +} + +enum MiMoMediaMTPFixture { + static func installed(_ f: MiMoMediaFixture.Models) throws -> ( + MiMoV26MTP, MiMoV26MTPAssistant, MiMoV26CBv2Adapter + ) { + let predictor = try MiMoV26MTP(target: f.target) + try predictor.loadConvertedWeights( + Dictionary( + uniqueKeysWithValues: predictor.parameters().flattened().map { name, array in + let dtype: DType = + name.hasSuffix("e_score_correction_bias") + ? .float32 + : name.hasSuffix("mlp.gate.weight") ? .bfloat16 : f.target.activationDType + return ("mtp." + name, MiMoMediaFixture.values(name, array.shape, dtype)) + })) + let assistant = try MiMoV26MTPAssistant( + target: f.target, predictor: predictor, retaining: f.owner) + return ( + predictor, assistant, + try MiMoV26CBv2Adapter(target: f.target, assistant: assistant, retaining: f.owner) + ) + } + static func binding( + _ f: MiMoMediaFixture.Models, _ adapter: MiMoV26CBv2Adapter, stops: Set = [] + ) -> MiMoV26CBv2Binding { + .init( + adapter: adapter, assistant: adapter.assistant, stopTokenIDs: stops, + mediaGeneration: f.generation) + } + static func processor( + _ f: MiMoMediaFixture.Models, _ adapter: MiMoV26CBv2Adapter, + stops: Set = [] + ) throws -> MiMoV26MultimodalProcessor { + try .init( + configuration: f.target.configuration, tokenizer: f.tokenizer, + chatTemplate: f.processor.chatTemplate, templateSHA256: f.processor.templateSHA256, + limits: MiMoMediaFixture.limits, vision: f.vision, audioPatch: f.patch, + adapter: adapter, + stopTokens: stops, generation: f.generation, retaining: f.owner, audioCodec: nil) + } + static func prepared( + _ f: MiMoMediaFixture.Models, _ adapter: MiMoV26CBv2Adapter, + video: Bool = false, output: Int = 18 + ) throws -> MiMoV26PreparedMultimodal { + let image = MiMoMediaFixture.image(70) + let content: [MiMoV26MultimodalContent] = + video + ? [ + .silentVideo( + .init( + frames: [image, MiMoMediaFixture.image(110), image], timestamps: [0, 1, 2])), + .text("tail"), + ] + : [.image(image)] + let input = MiMoV26MultimodalInput( + messages: [.init(role: .user, content: content)], maximumOutputTokens: output) + let processor = try processor(f, adapter) + return try processor.prepare( + processor.plan(input), authorize: { MiMoMediaFixture.Reservation($0) }) + } + static func engine( + _ adapter: MiMoV26CBv2Adapter, model: (any CBv2SteppableModel)? = nil, + sampler: (any CBv2StepSampler)? = nil, chunk: Int = 3, events: Int = 256, + fixedDraftTokens: Int? = 2 + ) throws -> (EngineV2, MiMoV26CBv2Backend) { + _ = try withMiMoMediaMTPConstructionScope { work in + try adapter.probeNativeKVTypes(retaining: work) + } + let backend = try adapter.makeBackend(bytesCapacity: 32 << 20) + let engine = EngineV2( + model: model ?? adapter, layerKinds: adapter.layerKinds, backend: backend, + cacheProvider: try adapter.makeMultimodalCacheProvider(), + sampler: sampler ?? CBv2DefaultSampler(), + schedulerConfig: .init( + maxConcurrentRequests: 3, maxBatchedTokensPerStep: 8, prefillChunkSize: chunk, + maxWaiting: 8), + loopConfig: .init( + requestTimeout: 40, stepTimeout: 20, eventBufferCapacity: events, + shutdownTimeout: 5, useLegacyRequestTimeout: true), + mtpDrafter: adapter.assistant, + mtpConfig: .init( + enabled: adapter.assistant != nil, maxDraftTokens: 2, + maxSpeculativeBatch: 1, fixedDraftTokens: fixedDraftTokens, + verificationMode: fixedDraftTokens == nil ? .automatic : .serialTarget), + nativeCompletionTracking: false) + return (engine, backend) + } + static func collect(_ stream: AsyncStream) async -> ([Int], CBv2FinishReason?) { + var tokens: [Int] = [] + var reason: CBv2FinishReason? + for await event in stream { + switch event { + case .delta(_, let ids, _): tokens += ids + case .finished(let value, _): reason = value + } + } + return (tokens, reason) + } + static func text(_ id: UInt64, length: Int = 13, output: Int = 18) -> CBv2Request { + var prompt = (0 ..< length).map { 20 + $0 % 32 } + prompt[prompt.count - 1] = 53 + return .init( + id: .init(id), promptTokens: prompt, sampling: .init(temperature: 0), maxTokens: output, + prefixCacheEnabled: false) + } +} + +final class MiMoV26MediaMTPFallbackTests: XCTestCase { + func testHistoricalMultimodalEligibilityTruthTableRemainsUnchanged() { + XCTAssertFalse( + EngineLoopV2.mtpMultimodalHistoryEligible(hasSpans: true, tracksPersistentHistory: true) + ) + XCTAssertTrue( + EngineLoopV2.mtpMultimodalHistoryEligible( + hasSpans: true, tracksPersistentHistory: false)) + XCTAssertTrue( + EngineLoopV2.mtpMultimodalHistoryEligible( + hasSpans: false, tracksPersistentHistory: true)) + XCTAssertTrue( + EngineLoopV2.mtpMultimodalHistoryEligible( + hasSpans: false, tracksPersistentHistory: false)) + } + private func attach(_ trace: MiMoMediaMTPTrace, to engine: EngineV2) { + // These closures execute ON the engine queue; do not sync-dispatch it. + trace.identify = { [weak engine] caches in + guard let loop = engine?.loopForTesting, let cache = caches.first else { return [] } + return cache.rows.compactMap { row in + for (id, states) in loop.kvStates where states.first.flatMap({ $0 }) === row { + guard let rec = loop.scheduler.record(for: id) else { continue } + return .init( + id: id, arrival: rec.arrivalSeq, + media: rec.request.multimodal?.spans.isEmpty == false) + } + return nil + } + } + trace.inspect = { [weak engine] ids in + guard let loop = engine?.loopForTesting, let driver = loop.mtp else { return false } + for id in ids { + guard let rec = loop.scheduler.record(for: id), + rec.request.multimodal?.spans.isEmpty == false + else { continue } + if !driver.isTargetOnlyMediaForTesting(id) + || driver.assistantStateCountsForTesting(id) != nil + || driver.hasValidCarry(for: rec) || driver.isSeedMarked(id) + || driver.roundMark(for: id) != nil + { + return false + } + } + return true + } + trace.state = { [weak engine] in + guard let loop = engine?.loopForTesting, let driver = loop.mtp else { return nil } + let rows = loop.scheduler.running + let liveMedia = rows.filter { + !$0.isPaused && !$0.cancelRequested && $0.request.multimodal?.spans.isEmpty == false + }.map { MiMoMediaMTPTrace.Row(id: $0.id, arrival: $0.arrivalSeq, media: true) } + let metrics = driver.metricsSnapshot() + return .init( + step: loop.stepCount, earlyDrafts: metrics.earlyDraftSubmissions, + rounds: metrics.rounds, drafted: metrics.draftedTokens, liveMedia: liveMedia, + roundDepths: Dictionary( + uniqueKeysWithValues: rows.compactMap { rec in + driver.roundMark(for: rec.id).map { (rec.id, $0) } + }), seedIDs: Set(rows.filter { driver.isSeedMarked($0.id) }.map(\.id)), + marginal: driver.usesMarginalPolicy) + } + engine.loopForTesting.onEngineQueueSync { + let driver = engine.loopForTesting.mtp + XCTAssertNotNil(driver, "the real accepted sampler must leave native MTP active") + driver?.carryStoredObserverForTesting = { [weak trace] in trace?.carry($0) } + if trace.numeric { + driver?.carryHiddenObserverForTesting = { [weak trace] in trace?.carryHidden($0, $1) + } + } + } + } + private func detachAfterDrain( + _ trace: MiMoMediaMTPTrace, engine: EngineV2, sampler: CBv2DefaultSampler + ) { + engine.loopForTesting.onEngineQueueSync { + engine.loopForTesting.mtp?.carryStoredObserverForTesting = nil + engine.loopForTesting.mtp?.carryHiddenObserverForTesting = nil + sampler.sampleObserverForTesting = nil + } + trace.clearAfterDrain() + } + /// Separate call boundary releases the single retained numerical pair + /// before the caller makes any subsequent lifecycle assertions. + private func assertNumericMappingAfterDrain( + _ trace: MiMoMediaMTPTrace, dtype: String, + mediaFirst: Bool, mediaID: CBv2RequestID, textID: CBv2RequestID, hiddenSize: Int + ) throws { + let seed = try XCTUnwrap(trace.takeNumericSeedAfterDrain()) + let stored = try XCTUnwrap(seed.stored) + let actualHidden = try XCTUnwrap(seed.actualHidden) + let values = try XCTUnwrap(seed.policyValues) + XCTAssertEqual(seed.sampleIDs, mediaFirst ? [mediaID, textID] : [textID, mediaID]) + XCTAssertEqual(values.shape, [1, 2, 2]) + XCTAssertEqual(stored.hiddenShape, [1, 1, hiddenSize]) + XCTAssertEqual(actualHidden.shape, seed.expectedHidden.shape) + eval(values, actualHidden, seed.expectedHidden) + let table = values.asArray(Float.self) + let textIndex = mediaFirst ? 1 : 0 + let mediaIndex = 1 - textIndex + let textMargin = Double(table[textIndex * 2] - table[textIndex * 2 + 1]) + let mediaMargin = Double(table[mediaIndex * 2] - table[mediaIndex * 2 + 1]) + XCTAssertEqual(stored.previousTopTwoMargin, textMargin) + XCTAssertNotEqual( + textMargin, mediaMargin, "native scores must discriminate a wrong policy gather") + let actualValues = actualHidden.asArray(Float.self) + let expectedValues = seed.expectedHidden.asArray(Float.self) + XCTAssertEqual( + actualValues, expectedValues, + "stored carry must use the genuine text hidden, not a same-shaped media placeholder") + print( + "MIMO_MEDIA_ADAPTIVE_MAPPING dtype=\(dtype) media_first=\(mediaFirst) step=\(seed.step) text_margin=\(textMargin) media_margin=\(mediaMargin) hidden_exact=\(actualValues == expectedValues)" + ) + } + func testRealMediaOFFONParityWithTextDraftingAndOneOrderedSamplerInvocation() async throws { + for dtype in ["float32", "bfloat16"] { + for mediaFirst in [true, false] { + try await mixedWitness( + dtype: dtype, mediaFirst: mediaFirst, fixedDraftTokens: 2, numeric: false) + } + } + } + func testAdaptiveCompactPolicyAndHiddenMappingUseRealSerialMiMoInBothRowOrders() async throws { + // Raw references are enabled ONLY in this numerical mapping cell. + // It is not lifecycle/residency/peak/timing/performance evidence. + for dtype in ["float32", "bfloat16"] { + for mediaFirst in [true, false] { + try await mixedWitness( + dtype: dtype, mediaFirst: mediaFirst, fixedDraftTokens: nil, numeric: true) + } + } + } + func testTwoGenuinelyEligibleTextRowsBesideLiveMediaKeepNativeHeadBatchOneGate() async throws { + for mediaFirst in [true, false] { + let f = try MiMoMediaFixture.models() + let (_, _, on) = try MiMoMediaMTPFixture.installed(f) + let offPrepared = try MiMoMediaMTPFixture.prepared(f, f.adapter) + let onPrepared = try MiMoMediaMTPFixture.prepared(f, on) + let mediaID = CBv2RequestID(81) + let aID = CBv2RequestID(82) + let bID = CBv2RequestID(83) + let a = MiMoMediaMTPFixture.text(82, length: offPrepared.plan.promptTokens.count) + let b = MiMoMediaMTPFixture.text(83, length: offPrepared.plan.promptTokens.count) + let trace = MiMoMediaMTPTrace() + let observed = MiMoMediaMTPObservedTarget(on, trace) + let sampler = CBv2DefaultSampler() + sampler.sampleObserverForTesting = { [weak trace] in trace?.sample($0, step: $1) } + let (off, offBackend) = try MiMoMediaMTPFixture.engine(f.adapter, chunk: 1) + var startedEngine: EngineV2? + func run( + _ value: EngineV2, _ prepared: MiMoV26PreparedMultimodal, + _ binding: MiMoV26CBv2Binding + ) async throws -> [[Int]] { + value.loopForTesting.onEngineQueueSync { + value.loopForTesting.suspendStepExecutionAtCountForTesting = 0 + } + let media = try prepared.makeRequest( + binding: binding, id: mediaID, sampling: .init(temperature: 0)) + let requests = mediaFirst ? [media, a, b] : [a, media, b] + let streams = try requests.map { try value.submit($0) } + value.loopForTesting.onEngineQueueSync { + XCTAssertEqual(value.loopForTesting.stepCount, 0) + for id in [mediaID, aID, bID] { + XCTAssertNotNil(value.loopForTesting.scheduler.record(for: id)) + } + value.loopForTesting.suspendStepExecutionAtCountForTesting = nil + } + async let one = MiMoMediaMTPFixture.collect(streams[0]) + async let two = MiMoMediaMTPFixture.collect(streams[1]) + async let three = MiMoMediaMTPFixture.collect(streams[2]) + let results = await (one, two, three) + let all = [results.0, results.1, results.2] + for result in all { XCTAssertEqual(result.1, .length) } + return all.map { $0.0 } + } + do { + let (engine, backend) = try MiMoMediaMTPFixture.engine( + on, model: observed, sampler: sampler, chunk: 1) + startedEngine = engine + attach(trace, to: engine) + let expected = try await run(off, offPrepared, f.binding) + await off.shutdown() + XCTAssertEqual(offBackend.bytesReserved, 0) + let actual = try await run(engine, onPrepared, MiMoMediaMTPFixture.binding(f, on)) + XCTAssertEqual(actual, expected) + let metrics = try XCTUnwrap(engine.mtpMetricsSnapshot()) + XCTAssertTrue(metrics.active) + XCTAssertEqual(metrics.draftedTokens, 0) + let (forwards, samples, clean) = trace.snapshot() + XCTAssertTrue(clean) + XCTAssertTrue( + forwards.contains { + $0.kind == "hidden" && $0.rows.count == 2 + && Set($0.rows.map(\.id)) == Set([aID, bID]) + }, "both real eligible text rows must share target work beside media") + let shared = samples.filter { Set($0.ids) == Set([mediaID, aID, bID]) } + XCTAssertFalse(shared.isEmpty) + for sample in shared { + XCTAssertEqual( + sample.ids, mediaFirst ? [mediaID, aID, bID] : [aID, mediaID, bID]) + } + for calls in Dictionary( + grouping: samples.filter { $0.ids.contains(mediaID) }, by: \.step + ).values { XCTAssertEqual(calls.count, 1) } + XCTAssertTrue(trace.proof().1.allSatisfy { $0.id != mediaID }) + await engine.shutdown() + detachAfterDrain(trace, engine: engine, sampler: sampler) + XCTAssertEqual(backend.bytesReserved, 0) + XCTAssertTrue( + engine.loopForTesting.onEngineQueueSync { + let loop = engine.loopForTesting + return loop.mtp?.carryHiddenObserverForTesting == nil + && [mediaID, aID, bID].allSatisfy { + loop.mtp?.assistantStateCountsForTesting($0) == nil + } + }) + } catch { + off.loopForTesting.onEngineQueueSync { + off.loopForTesting.suspendStepExecutionAtCountForTesting = nil + } + await off.shutdown() + if let engine = startedEngine { + engine.loopForTesting.onEngineQueueSync { + engine.loopForTesting.suspendStepExecutionAtCountForTesting = nil + } + await engine.shutdown() + detachAfterDrain(trace, engine: engine, sampler: sampler) + } else { + sampler.sampleObserverForTesting = nil + trace.clearAfterDrain() + } + throw error + } + } + } + private func mixedWitness( + dtype: String, mediaFirst: Bool, fixedDraftTokens: Int?, numeric: Bool + ) async throws { + let f = try MiMoMediaFixture.models(dtype) + let (_, assistant, on) = try MiMoMediaMTPFixture.installed(f) + XCTAssertTrue(on.target === f.adapter.target) + XCTAssertEqual(assistant.mtpTargetIdentity, ObjectIdentifier(f.target)) + let output = fixedDraftTokens == nil ? 48 : 18 + let offPrepared = try MiMoMediaMTPFixture.prepared(f, f.adapter, output: output) + let onPrepared = try MiMoMediaMTPFixture.prepared(f, on, output: output) + let mediaID = CBv2RequestID(1) + let textID = CBv2RequestID(2) + let text = MiMoMediaMTPFixture.text( + 2, length: offPrepared.plan.promptTokens.count, output: output) + let windows = on.layerKinds.compactMap { kind -> Int? in + if case .slidingWindow(let window) = kind.attention { return window } + return nil + } + XCTAssertGreaterThan(offPrepared.plan.promptTokens.count, try XCTUnwrap(windows.max())) + XCTAssertTrue( + on.layerKinds.contains { + if case .full = $0.attention { return true } + return false + }) + let (off, offBackend) = try MiMoMediaMTPFixture.engine(f.adapter) + off.loopForTesting.onEngineQueueSync { + off.loopForTesting.suspendStepExecutionAtCountForTesting = 0 + } + do { + let media = try off.submit( + offPrepared.makeRequest( + binding: f.binding, id: mediaID, sampling: .init(temperature: 0))) + let ordinary = try off.submit(text) + off.loopForTesting.onEngineQueueSync { + XCTAssertEqual(off.loopForTesting.stepCount, 0) + XCTAssertNotNil(off.loopForTesting.scheduler.record(for: mediaID)) + XCTAssertNotNil(off.loopForTesting.scheduler.record(for: textID)) + off.loopForTesting.suspendStepExecutionAtCountForTesting = nil + } + async let mediaValue = MiMoMediaMTPFixture.collect(media) + async let textValue = MiMoMediaMTPFixture.collect(ordinary) + let expected = await (mediaValue, textValue) + await off.shutdown() + XCTAssertEqual(offBackend.bytesReserved, 0) + XCTAssertEqual(expected.0.1, .length) + XCTAssertEqual(expected.1.1, .length) + XCTAssertNotEqual( + expected.0.0, expected.1.0, "fixture must discriminate a swapped sampler row") + let trace = MiMoMediaMTPTrace(numeric: numeric) + let observed = MiMoMediaMTPObservedTarget(on, trace) + let sampler = CBv2DefaultSampler() + sampler.sampleObserverForTesting = { [weak trace] in trace?.sample($0, step: $1) } + let (engine, backend) = try MiMoMediaMTPFixture.engine( + on, model: observed, sampler: sampler, + fixedDraftTokens: fixedDraftTokens) + attach(trace, to: engine) + engine.loopForTesting.onEngineQueueSync { + let loop = engine.loopForTesting + loop.suspendStepExecutionAtCountForTesting = 0 + XCTAssertEqual(loop.mtp?.config.fixedDraftTokens, fixedDraftTokens) + XCTAssertEqual(loop.mtp?.config.verificationMode, .serialTarget) + XCTAssertEqual(loop.mtp?.usesMarginalPolicy, fixedDraftTokens == nil) + XCTAssertEqual(loop.mtp?.config.maxSpeculativeBatch, 1) + if !numeric { XCTAssertNil(loop.mtp?.carryHiddenObserverForTesting) } + } + do { + let mediaRequest = try onPrepared.makeRequest( + binding: MiMoMediaMTPFixture.binding(f, on), id: mediaID, + sampling: .init(temperature: 0)) + let first = try engine.submit(mediaFirst ? mediaRequest : text) + let second = try engine.submit(mediaFirst ? text : mediaRequest) + engine.loopForTesting.onEngineQueueSync { + let loop = engine.loopForTesting + XCTAssertEqual(loop.stepCount, 0) + let media = loop.scheduler.record(for: mediaID) + let text = loop.scheduler.record(for: textID) + XCTAssertNotNil(media) + XCTAssertNotNil(text) + if let media, let text { + XCTAssertEqual(media.arrivalSeq < text.arrivalSeq, mediaFirst) + } + loop.suspendStepExecutionAtCountForTesting = nil + } + async let firstValue = MiMoMediaMTPFixture.collect(first) + async let secondValue = MiMoMediaMTPFixture.collect(second) + let actual = await (firstValue, secondValue) + XCTAssertEqual(actual.0.0, mediaFirst ? expected.0.0 : expected.1.0) + XCTAssertEqual(actual.1.0, mediaFirst ? expected.1.0 : expected.0.0) + XCTAssertEqual(actual.0.1, .length) + XCTAssertEqual(actual.1.1, .length) + let metrics = try XCTUnwrap(engine.mtpMetricsSnapshot()) + XCTAssertGreaterThan(metrics.draftedTokens, 0) + XCTAssertGreaterThan(metrics.serialVerificationRounds, 0) + XCTAssertEqual(metrics.rectangularVerificationRounds, 0) + await engine.shutdown() + let (forwards, samples, clean) = trace.snapshot() + XCTAssertTrue(clean) + XCTAssertFalse(forwards.isEmpty) + XCTAssertTrue( + forwards.allSatisfy { $0.rows.count == $0.shape[0] }, + "trace must identify every actual target row") + XCTAssertTrue( + forwards.filter { $0.kind.hasPrefix("hidden") }.allSatisfy { + !$0.rows.contains(where: \.media) + }) + XCTAssertTrue( + forwards.contains { $0.kind == "ordinary" && $0.rows.contains(where: \.media) }) + let shared = samples.filter { $0.ids.contains(mediaID) && $0.ids.contains(textID) } + XCTAssertFalse(shared.isEmpty, "must exercise the mixed decode/seed cohort") + for sample in shared { + XCTAssertEqual(sample.ids, mediaFirst ? [mediaID, textID] : [textID, mediaID]) + } + for calls in Dictionary( + grouping: samples.filter { $0.ids.contains(mediaID) }, by: \.step + ).values { + XCTAssertEqual(calls.count, 1, "media row sampled twice in one engine step") + } + let (witnesses, carries, policyCalls) = trace.proof() + XCTAssertTrue( + witnesses.contains { + $0.media.id == mediaID && $0.text.id == textID && $0.depth > 0 + && $0.completedStep == $0.step + 1 + }, + "require a COMPLETED real text draft/serial verification in the SAME step as live, unpaused media forward+sample" + ) + XCTAssertFalse(carries.isEmpty) + XCTAssertTrue( + carries.allSatisfy { $0.id == textID }, "media must never acquire any carry") + XCTAssertTrue( + forwards.contains { + $0.kind == "media-prefill" && $0.rows.contains(where: \.media) + }, + "the media history must contain actual embedding-spliced prefill") + if fixedDraftTokens == nil { + XCTAssertGreaterThan( + metrics.controllerFallbacks["marginal_offer", default: 0], 0) + XCTAssertGreaterThan( + policyCalls, 0, "the actual mixed compact top-two branch must run") + } + if numeric { + // The engine is drained BEFORE any numeric observer + // readback. Do not treat this retained-view run as a + // memory, ownership, liveness or performance result. + try assertNumericMappingAfterDrain( + trace, dtype: dtype, mediaFirst: mediaFirst, + mediaID: mediaID, textID: textID, + hiddenSize: f.target.configuration.hiddenSize) + } else { + XCTAssertNil(trace.takeNumericSeedAfterDrain()) + } + detachAfterDrain(trace, engine: engine, sampler: sampler) + XCTAssertEqual(backend.bytesReserved, 0) + XCTAssertTrue( + engine.loopForTesting.onEngineQueueSync { + let driver = engine.loopForTesting.mtp! + return !driver.isTargetOnlyMediaForTesting(mediaID) + && driver.assistantStateCountsForTesting(mediaID) == nil + && driver.assistantStateCountsForTesting(textID) == nil + }) + } catch { + engine.loopForTesting.onEngineQueueSync { + engine.loopForTesting.suspendStepExecutionAtCountForTesting = nil + } + await engine.shutdown() + detachAfterDrain(trace, engine: engine, sampler: sampler) + throw error + } + } catch { + off.loopForTesting.onEngineQueueSync { + off.loopForTesting.suspendStepExecutionAtCountForTesting = nil + } + await off.shutdown() + throw error + } + } + func testVideoChunksAndTextBeforeAfterStillUseRealHeadsOnSameTarget() async throws { + let f = try MiMoMediaFixture.models() + let (_, _, on) = try MiMoMediaMTPFixture.installed(f) + let offPrepared = try MiMoMediaMTPFixture.prepared(f, f.adapter, video: true) + let onPrepared = try MiMoMediaMTPFixture.prepared(f, on, video: true) + let (off, _) = try MiMoMediaMTPFixture.engine(f.adapter, chunk: 2) + let expected: ([Int], CBv2FinishReason?) + do { + expected = await MiMoMediaMTPFixture.collect( + try off.submit( + offPrepared.makeRequest( + binding: f.binding, id: .init(10), sampling: .init(temperature: 0)))) + await off.shutdown() + } catch { + await off.shutdown() + throw error + } + let (engine, backend) = try MiMoMediaMTPFixture.engine(on, chunk: 2) + do { + let before = await MiMoMediaMTPFixture.collect( + try engine.submit(MiMoMediaMTPFixture.text(20))) + XCTAssertEqual(before.1, .length) + let draftsBefore = try XCTUnwrap(engine.mtpMetricsSnapshot()).draftedTokens + XCTAssertGreaterThan(draftsBefore, 0) + let actual = await MiMoMediaMTPFixture.collect( + try engine.submit( + onPrepared.makeRequest( + binding: MiMoMediaMTPFixture.binding(f, on), id: .init(10), + sampling: .init(temperature: 0)))) + XCTAssertEqual(actual.0, expected.0) + XCTAssertEqual(actual.1, .length) + XCTAssertEqual( + engine.mtpMetricsSnapshot()?.draftedTokens, draftsBefore, + "media itself must never draft") + let after = await MiMoMediaMTPFixture.collect( + try engine.submit(MiMoMediaMTPFixture.text(21))) + XCTAssertEqual(after.0, before.0) + XCTAssertEqual(after.1, .length) + XCTAssertGreaterThan( + try XCTUnwrap(engine.mtpMetricsSnapshot()).draftedTokens, draftsBefore) + await engine.shutdown() + XCTAssertEqual(backend.bytesReserved, 0) + } catch { + await engine.shutdown() + throw error + } + } + func testActualAudioPatchSpansUseTargetOnlyRouteWithTextHeadsInstalled() async throws { + let f = try MiMoMediaFixture.models() + let (_, _, on) = try MiMoMediaMTPFixture.installed(f) + let codes = MiMoV26AudioCodeClip( + codes: (0 ..< (9 * f.patch.configuration.channels)).map { Int32($0 % 6) }, frameCount: 9 + ) + let output = try f.patch.forward(clips: [codes], limits: MiMoMediaFixture.limits.audioPatch) + eval(output.features) + XCTAssertEqual(output.clipPatchRanges.map(\.count), [3]) + let prompt = [20, 7, 6, 6, 6, 8, 21, 22] + func request(_ id: UInt64) -> CBv2Request { + .init( + id: .init(id), promptTokens: prompt, sampling: .init(temperature: 0), maxTokens: 18, + prefixCacheEnabled: false, + multimodal: .init(spans: [.init(tokenOffset: 2, length: 3)], attention: .causal) { + [features = output.features] in [features] + }) + } + let (off, offBackend) = try MiMoMediaMTPFixture.engine(f.adapter, chunk: 2) + let expected: ([Int], CBv2FinishReason?) + do { + expected = await MiMoMediaMTPFixture.collect(try off.submit(request(70))) + await off.shutdown() + } catch { + await off.shutdown() + throw error + } + XCTAssertEqual(offBackend.bytesReserved, 0) + let (engine, backend) = try MiMoMediaMTPFixture.engine(on, chunk: 2) + do { + let actual = await MiMoMediaMTPFixture.collect(try engine.submit(request(70))) + XCTAssertEqual(actual.0, expected.0) + XCTAssertEqual(actual.1, .length) + XCTAssertEqual(engine.mtpMetricsSnapshot()?.draftedTokens, 0) + let text = await MiMoMediaMTPFixture.collect( + try engine.submit(MiMoMediaMTPFixture.text(71))) + XCTAssertEqual(text.1, .length) + XCTAssertGreaterThan(try XCTUnwrap(engine.mtpMetricsSnapshot()).draftedTokens, 0) + await engine.shutdown() + XCTAssertEqual(backend.bytesReserved, 0) + } catch { + await engine.shutdown() + throw error + } + // This is the real discrete-code AudioPatch seam, not a PCM codec or + // encoded-audio qualification. Those remain separate root gates. + } + func testCancellationAndNumericIDReuseDoNotSeedMediaOrPoisonLaterText() async throws { + let f = try MiMoMediaFixture.models() + let (_, _, on) = try MiMoMediaMTPFixture.installed(f) + let media = try MiMoMediaMTPFixture.prepared(f, on, output: 80) + let (engine, backend) = try MiMoMediaMTPFixture.engine(on, chunk: 1, events: 1) + let id = CBv2RequestID(50) + do { + let initial = await MiMoMediaMTPFixture.collect( + try engine.submit(MiMoMediaMTPFixture.text(50))) + XCTAssertEqual(initial.1, .length) + let before = try XCTUnwrap(engine.mtpMetricsSnapshot()).draftedTokens + let stream = try engine.submit( + media.makeRequest( + binding: MiMoMediaMTPFixture.binding(f, on), id: id, + sampling: .init(temperature: 0))) + var cancelled = false + var finish: CBv2FinishReason? + for await event in stream { + switch event { + case .delta: + if !cancelled { + engine.cancel(id) + cancelled = true + } + case .finished(let reason, _): finish = reason + } + } + XCTAssertTrue(cancelled) + XCTAssertEqual(finish, .cancelled) + XCTAssertEqual(engine.mtpMetricsSnapshot()?.draftedTokens, before) + XCTAssertTrue( + engine.loopForTesting.onEngineQueueSync { + let loop = engine.loopForTesting + return loop.kvStates[id] == nil + && loop.mtp?.assistantStateCountsForTesting(id) == nil + && loop.mtp?.isTargetOnlyMediaForTesting(id) == false + }) + let later = await MiMoMediaMTPFixture.collect( + try engine.submit(MiMoMediaMTPFixture.text(50))) + XCTAssertEqual(later.0, initial.0) + XCTAssertEqual(later.1, .length) + XCTAssertGreaterThan(try XCTUnwrap(engine.mtpMetricsSnapshot()).draftedTokens, before) + await engine.shutdown() + XCTAssertEqual(backend.bytesReserved, 0) + } catch { + await engine.shutdown() + throw error + } + } + func testSplitTargetLogitsRecordDifferencesAgainstRectangularNativeForward() throws { + for dtype in ["float32", "bfloat16"] { + let f = try MiMoMediaFixture.models(dtype) + let (_, _, on) = try MiMoMediaMTPFixture.installed(f) + _ = try withMiMoMediaMTPConstructionScope { work in + try f.adapter.probeNativeKVTypes(retaining: work) + } + _ = try withMiMoMediaMTPConstructionScope { work in + try on.probeNativeKVTypes(retaining: work) + } + let referenceBackend = try f.adapter.makeBackend(bytesCapacity: 16 << 20) + let splitBackend = try on.makeBackend(bytesCapacity: 16 << 20) + let referenceRows = try (0 ..< 2).map { _ in + try referenceBackend.makeSequenceState( + layerKinds: f.adapter.layerKinds, promptLength: 16, maxLength: 64) + } + let splitRows = try (0 ..< 2).map { _ in + try splitBackend.makeSequenceState( + layerKinds: on.layerKinds, promptLength: 16, maxLength: 64) + } + let referenceCaches = f.adapter.makeCaches() + let splitCaches = on.makeCaches() + for step in 0 ..< 20 { + let tokens = [Int32(20 + step % 12), Int32(53 - step % 12)] + try f.adapter.bindRows(referenceRows, caches: referenceCaches) + let expected = try f.adapter.forwardValidated( + tokens: MLXArray(tokens, [2, 1]), caches: referenceCaches) + try on.bindRows([splitRows[0]], caches: splitCaches) + let media = on.forward(tokens: MLXArray([tokens[0]], [1, 1]), caches: splitCaches) + try on.bindRows([splitRows[1]], caches: splitCaches) + let text = on.forwardWithHidden( + tokens: MLXArray([tokens[1]], [1, 1]), caches: splitCaches + ).logits + let actual = concatenated([media, text], axis: 0) + eval(actual, expected) + let difference = abs(actual - expected) + let maximum = difference.max().item(Float.self) + print("MIMO_MEDIA_MTP_SPLIT dtype=\(dtype) step=\(step) max_abs=\(maximum)") + let absolute: Float = dtype == "bfloat16" ? 0.02 : 5e-5 + let relative: Float = dtype == "bfloat16" ? 0.02 : 1e-4 + XCTAssertTrue( + all(difference .<= (absolute + relative * abs(expected))).item(Bool.self)) + XCTAssertEqual( + argMax(actual, axis: -1).asArray(Int32.self), + argMax(expected, axis: -1).asArray(Int32.self)) + } + for rows in referenceRows { referenceBackend.release(rows) } + for rows in splitRows { splitBackend.release(rows) } + } + } + func testLoadedAssistantInvalidationAndEOSUnionStillFailClosedOrPreserve() throws { + let f = try MiMoMediaFixture.models() + let (_, assistant, on) = try MiMoMediaMTPFixture.installed(f) + let stops: Set = [1, 57, 63] + let processor = try MiMoMediaMTPFixture.processor(f, on, stops: stops) + let plan = try processor.plan(MiMoMediaFixture.request([.image(MiMoMediaFixture.image())])) + let first = try processor.prepare(plan, authorize: { MiMoMediaFixture.Reservation($0) }) + let request = try first.makeRequest( + binding: MiMoMediaMTPFixture.binding(f, on, stops: stops), id: .init(77)) + XCTAssertEqual(request.stopTokens, stops) + XCTAssertFalse(request.prefixCacheEnabled) + assistant.invalidateLoadedSession() + XCTAssertFalse(on.supportsMultimodalPrefill) + XCTAssertThrowsError(try request.multimodal!.embeddings()) + var admitted = 0 + XCTAssertThrowsError( + try processor.prepare( + plan, + authorize: { + admitted += 1 + return MiMoMediaFixture.Reservation($0) + })) + XCTAssertEqual(admitted, 0) + } + + /// Keep the original token-only split oracle above intact. This additional + /// cell starts from genuine media-conditioned history in BOTH branches, + /// then compares rectangular ordinary decode with the media/text split. + func testMediaConditionedSplitLogitsPreserveFP32BF16OraclesAfterSWAWrap() throws { + for dtype in ["float32", "bfloat16"] { + let f = try MiMoMediaFixture.models(dtype) + let (_, _, on) = try MiMoMediaMTPFixture.installed(f) + _ = try withMiMoMediaMTPConstructionScope { work in + try f.adapter.probeNativeKVTypes(retaining: work) + } + _ = try withMiMoMediaMTPConstructionScope { work in + try on.probeNativeKVTypes(retaining: work) + } + let prepared = try MiMoMediaMTPFixture.prepared(f, f.adapter) + let request = try prepared.makeRequest( + binding: f.binding, id: .init(601), sampling: .init(temperature: 0)) + let spans = try XCTUnwrap(request.multimodal).spans + let features = try request.multimodal!.embeddings() + XCTAssertFalse(spans.isEmpty) + XCTAssertEqual(features.count, spans.count) + XCTAssertTrue(features.allSatisfy { $0.dtype == f.target.activationDType }) + // Independent host assembly, not the engine's splice/resolve path. + let base = f.target.model.embedTokens( + MLXArray(request.promptTokens.map(Int32.init), [1, request.promptTokens.count])) + var pieces: [MLXArray] = [] + var cursor = 0 + for (span, feature) in zip(spans, features) { + if cursor < span.tokenOffset { + pieces.append(base[0..., cursor ..< span.tokenOffset, 0...]) + } + pieces.append(feature.expandedDimensions(axis: 0)) + cursor = span.tokenOffset + span.length + } + if cursor < request.promptTokens.count { + pieces.append(base[0..., cursor ..< request.promptTokens.count, 0...]) + } + let mediaEmbeddings = concatenated(pieces, axis: 1) + let textPrompt = MiMoMediaMTPFixture.text(602, length: request.promptTokens.count) + .promptTokens + let referenceBackend = try f.adapter.makeBackend(bytesCapacity: 16 << 20) + let splitBackend = try on.makeBackend(bytesCapacity: 16 << 20) + let referenceRows = try (0 ..< 2).map { _ in + try referenceBackend.makeSequenceState( + layerKinds: f.adapter.layerKinds, promptLength: request.promptTokens.count, + maxLength: 128) + } + let splitRows = try (0 ..< 2).map { _ in + try splitBackend.makeSequenceState( + layerKinds: on.layerKinds, promptLength: request.promptTokens.count, + maxLength: 128) + } + defer { + for rows in referenceRows { referenceBackend.release(rows) } + for rows in splitRows { splitBackend.release(rows) } + } + let referenceCaches = f.adapter.makeCaches() + let splitCaches = on.makeCaches() + func compare(_ actual: MLXArray, _ expected: MLXArray, phase: String, step: Int) { + eval(actual, expected) + let difference = abs(actual - expected) + let maximum = difference.max().item(Float.self) + print( + "MIMO_MEDIA_CONDITIONED_SPLIT dtype=\(dtype) phase=\(phase) step=\(step) max_abs=\(maximum)" + ) + let absolute: Float = dtype == "bfloat16" ? 0.02 : 5e-5 + let relative: Float = dtype == "bfloat16" ? 0.02 : 1e-4 + XCTAssertTrue( + all(difference .<= (absolute + relative * abs(expected))).item(Bool.self)) + XCTAssertEqual( + argMax(actual, axis: -1).asArray(Int32.self), + argMax(expected, axis: -1).asArray(Int32.self)) + } + for start in stride(from: 0, to: request.promptTokens.count, by: 3) { + let end = min(start + 3, request.promptTokens.count) + let mediaIDs = MLXArray( + request.promptTokens[start ..< end].map(Int32.init), [1, end - start]) + let textIDs = MLXArray(textPrompt[start ..< end].map(Int32.init), [1, end - start]) + let chunk = mediaEmbeddings[0..., start ..< end, 0...] + try f.adapter.bindRows([referenceRows[0]], caches: referenceCaches) + let expectedMedia = try f.adapter.forwardValidated( + tokens: mediaIDs, inputEmbeddings: chunk, caches: referenceCaches) + try on.bindRows([splitRows[0]], caches: splitCaches) + let actualMedia = try on.forwardValidated( + tokens: mediaIDs, inputEmbeddings: chunk, caches: splitCaches) + compare(actualMedia, expectedMedia, phase: "media-prefill", step: start) + try f.adapter.bindRows([referenceRows[1]], caches: referenceCaches) + let expectedText = try f.adapter.forwardValidated( + tokens: textIDs, caches: referenceCaches) + try on.bindRows([splitRows[1]], caches: splitCaches) + let actualText = on.forwardWithHidden(tokens: textIDs, caches: splitCaches) + compare(actualText.logits, expectedText, phase: "text-prefill", step: start) + eval(actualText.lastHidden) + } + let windows = f.adapter.layerKinds.compactMap { kind -> Int? in + if case .slidingWindow(let window) = kind.attention { return window } + return nil + } + XCTAssertFalse(windows.isEmpty) + XCTAssertTrue( + f.adapter.layerKinds.contains { + if case .full = $0.attention { return true } + return false + }) + XCTAssertGreaterThan( + request.promptTokens.count, try XCTUnwrap(windows.max()), + "media history must wrap SWA before mixed decode") + for step in 0 ..< 20 { + let tokens = [Int32(20 + step % 12), Int32(53 - step % 12)] + try f.adapter.bindRows(referenceRows, caches: referenceCaches) + let expected = try f.adapter.forwardValidated( + tokens: MLXArray(tokens, [2, 1]), caches: referenceCaches) + try on.bindRows([splitRows[0]], caches: splitCaches) + let media = on.forward(tokens: MLXArray([tokens[0]], [1, 1]), caches: splitCaches) + try on.bindRows([splitRows[1]], caches: splitCaches) + let text = on.forwardWithHidden( + tokens: MLXArray([tokens[1]], [1, 1]), caches: splitCaches) + compare( + concatenated([media, text.logits], axis: 0), expected, phase: "mixed-decode", + step: step) + eval(text.lastHidden) + for rows in referenceRows + splitRows { + XCTAssertEqual( + rows.compactMap { $0?.absoluteOffset }, + Array(repeating: request.promptTokens.count + step + 1, count: rows.count)) + } + } + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26MediaReaderMarkerTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26MediaReaderMarkerTests.swift new file mode 100644 index 0000000000..2e88123f6a --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26MediaReaderMarkerTests.swift @@ -0,0 +1,92 @@ +import CoreMedia +import Foundation +import XCTest + +@testable import MLXVLM + +/// Real Core Media buffers exercise marker admission; no decoder is mocked. +final class MiMoV26MediaReaderMarkerTests: XCTestCase { + private func marker(ready: Bool = true, payloadBytes: Int = 0) throws -> CMSampleBuffer { + var block: CMBlockBuffer? + if payloadBytes > 0 { + XCTAssertEqual( + CMBlockBufferCreateWithMemoryBlock( + allocator: kCFAllocatorDefault, + memoryBlock: nil, blockLength: payloadBytes, + blockAllocator: kCFAllocatorDefault, + customBlockSource: nil, offsetToData: 0, dataLength: payloadBytes, + flags: 0, blockBufferOut: &block), kCMBlockBufferNoErr) + } + var sample: CMSampleBuffer? + XCTAssertEqual( + CMSampleBufferCreate( + allocator: kCFAllocatorDefault, dataBuffer: block, + dataReady: ready, makeDataReadyCallback: nil, refcon: nil, formatDescription: nil, + sampleCount: 0, sampleTimingEntryCount: 0, sampleTimingArray: nil, + sampleSizeEntryCount: 0, sampleSizeArray: nil, sampleBufferOut: &sample), noErr) + return try XCTUnwrap(sample) + } + + func testActualEmptyMarkersStayBoundedForVideoAndAudio() throws { + let sample = try marker() + XCTAssertTrue(CMSampleBufferIsValid(sample)) + XCTAssertTrue(CMSampleBufferDataIsReady(sample)) + XCTAssertEqual(CMSampleBufferGetNumSamples(sample), 0) + XCTAssertEqual(CMSampleBufferGetDuration(sample), .zero) + var videoMarkers = 0 + XCTAssertTrue( + try MiMoV26EncodedVisualDecoder.consumeEmptyMarker( + sample, count: &videoMarkers, limit: 1)) + XCTAssertEqual(videoMarkers, 1) + XCTAssertThrowsError( + try MiMoV26EncodedVisualDecoder.consumeEmptyMarker( + sample, count: &videoMarkers, limit: 1) + ) { + XCTAssertEqual($0 as? MiMoV26EncodedVisualDecoder.Failure, .limit) + } + XCTAssertEqual(videoMarkers, 1) + var audioMarkers = 0 + XCTAssertTrue( + try MiMoV26EncodedAudiovisualDecoder.consumeEmptyMarker( + sample, count: &audioMarkers, limit: 1)) + XCTAssertThrowsError( + try MiMoV26EncodedAudiovisualDecoder.consumeEmptyMarker( + sample, count: &audioMarkers, limit: 1) + ) { + XCTAssertEqual($0 as? MiMoV26EncodedAudiovisualDecoder.Failure, .limit) + } + } + + func testInvalidUnreadyPayloadAndRetimedMarkersRemainTypedRefusals() throws { + let invalid = try marker() + XCTAssertEqual(CMSampleBufferInvalidate(invalid), noErr) + let unready = try marker(ready: false) + XCTAssertFalse(CMSampleBufferDataIsReady(unready)) + let payload = try marker(payloadBytes: 1) + XCTAssertEqual( + CMBlockBufferGetDataLength(try XCTUnwrap(CMSampleBufferGetDataBuffer(payload))), 1) + let retimed = try marker() + CMSetAttachment( + retimed, key: kCMSampleBufferAttachmentKey_SpeedMultiplier, + value: NSNumber(value: 2), attachmentMode: kCMAttachmentMode_ShouldPropagate) + for sample in [invalid, unready, payload, retimed] { + var videoMarkers = 0 + XCTAssertThrowsError( + try MiMoV26EncodedVisualDecoder.consumeEmptyMarker( + sample, count: &videoMarkers, limit: 10) + ) { + XCTAssertEqual($0 as? MiMoV26EncodedVisualDecoder.Failure, .invalidVideo) + } + XCTAssertEqual(videoMarkers, 0) + var audioMarkers = 0 + XCTAssertThrowsError( + try MiMoV26EncodedAudiovisualDecoder.consumeEmptyMarker( + sample, count: &audioMarkers, limit: 10) + ) { + XCTAssertEqual( + $0 as? MiMoV26EncodedAudiovisualDecoder.Failure, .unsupportedTimeline) + } + XCTAssertEqual(audioMarkers, 0) + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26MultimodalInputTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26MultimodalInputTests.swift new file mode 100644 index 0000000000..14f749bc10 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26MultimodalInputTests.swift @@ -0,0 +1,296 @@ +import CryptoKit +import Foundation +import MLX +import MLXNN +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon +@testable import MLXVLM + +/// Routing tokenizer only; NOT a Jinja/BPE numerical oracle. Native feature +/// and engine tests below use real MiMo modules, caches and actual EngineV2. +final class MiMoMediaTestTokenizer: Tokenizer, @unchecked Sendable { + let ids = [ + "<|vision_start|>": 4, "<|vision_end|>": 5, "<|image_pad|>": 2, "<|video_pad|>": 3, + "<|mimo_video_start|>": 9, "<|mimo_video_end|>": 10, "<|mimo_audio_start|>": 7, + "<|mimo_audio_end|>": 8, "<|audio_pad|>": 6, + ] + var override: [Int]? + var messages: [Message] = [] + var bosToken: String? { nil } + var eosToken: String? { nil } + var unknownToken: String? { nil } + func encode(text: String, addSpecialTokens: Bool) -> [Int] { + text.utf8.map { 20 + Int($0) % 32 } + } + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { "routing-fixture" } + func convertTokenToId(_ token: String) -> Int? { ids[token] } + func convertIdToToken(_ id: Int) -> String? { ids.first { $0.value == id }?.key } + func applyChatTemplate( + messages: [Message], tools: [ToolSpec]?, additionalContext: [String: any Sendable]? + ) throws -> [Int] { + try applyChatTemplate( + messages: messages, chatTemplate: "fixture", tools: tools, + additionalContext: additionalContext) + } + func applyChatTemplate(messages: [Message], chatTemplate: String) throws -> [Int] { + try applyChatTemplate( + messages: messages, chatTemplate: chatTemplate, tools: nil, additionalContext: nil) + } + func applyChatTemplate( + messages: [Message], chatTemplate: String, tools: [ToolSpec]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { + self.messages = messages + if let override { return override } + var result = [11] + for message in messages { + for part in message["content"] as! [[String: any Sendable]] { + switch part["type"] as! String { + case "image": result += [4, 2, 5] + case "video": result += [4, 3, 5] + case "audio": result += [7, 6, 8] + default: result += encode(text: part["text"] as! String, addSpecialTokens: true) + } + } + } + return result + [12] + } +} + +enum MiMoMediaFixture { + final class Owner {} + final class Reservation: MiMoV26MediaWorkReservation { + let digest: String + var calls = 0, revoked = false + var quarantine: ((MiMoV26FailedMediaWork) -> Void)? + init(_ plan: MiMoV26MultimodalPlan) { digest = plan.preparationSHA256 } + func validate(plan: MiMoV26MultimodalPlan) throws { + calls += 1 + guard !revoked, plan.preparationSHA256 == digest else { + throw MiMoV26MultimodalError.reservationRejected + } + } + func retainAfterFailedDrain(_ work: MiMoV26FailedMediaWork) { + guard let quarantine else { + preconditionFailure("test must install a real failed-work holder") + } + quarantine(work) + } + } + static func native() throws { + guard ProcessInfo.processInfo.environment["MIMO_V26_MULTIMODAL_NATIVE_TESTS"] == "1" else { + throw XCTSkip("Requires root's exclusive native lane; no component pass inferred") + } + } + static let limits = MiMoV26MultimodalLimits( + maximumMedia: 16, maximumVideoFrames: 16, maximumPromptTokens: 120, + maximumMetadataBytes: 65536, maximumMetadataNodes: 10000, maximumMetadataDepth: 32, + pixels: .init( + maximumInputElements: 1_000_000, maximumOutputElements: 1_000_000, + maximumWorkingBytes: 16 << 20), + vision: .init(maximumPatches: 1024, maximumAttentionScoreElements: 1_000_000), + audio: .init( + maximumClips: 8, maximumChannels: 2, maximumSampleRate: 48000, + maximumInputSamples: 100000, + maximumResampledSamples: 100000, maximumResampleCoefficients: 100000, + maximumMelFrames: 10000, + maximumSegments: 16, maximumPaddedMelFrames: 100000, maximumWorkingElements: 1_000_000, + frontendFrameBlockSize: 8, rvqTileFrames: 8), + audioPatch: .init( + maximumClips: 8, maximumFrames: 10000, maximumPatches: 4096, + maximumWorkingElements: 1_000_000)) + static func configuration(_ dtype: String = "float32") throws -> MiMoV26Configuration { + guard let path = ProcessInfo.processInfo.environment["MIMO_V26_MULTIMODAL_TINY_CONFIG"] + else { + throw XCTSkip( + "Requires existing identity/filesystem-load-fixtures/tiny-bundle/config.json (metadata only)" + ) + } + var fields = try JSONDecoder().decode( + [String: MiMoV26JSONValue].self, from: Data(contentsOf: URL(fileURLWithPath: path))) + fields["attention_projection_layout"] = .string("split") + fields["moe_router_dtype"] = .string("bfloat16") + fields["dtype"] = .string(dtype) + fields["quantization"] = nil + fields["quantization_config"] = nil + fields["v_head_dim"] = .number(16) + fields["swa_v_head_dim"] = .number(16) + fields["omlx_mimo_mtp"] = nil + guard case .object(var processor) = fields["processor_config"] else { + throw MiMoV26MultimodalError.incompatiblePlan + } + processor["video_start_token_id"] = .number(9) + processor["video_end_token_id"] = .number(10) + fields["processor_config"] = .object(processor) + return try .init(rawFields: fields) + } + static func values(_ name: String, _ shape: [Int], _ dtype: DType) -> MLXArray { + let count = shape.reduce(1, *) + let salt = name.utf8.reduce(0) { ($0 + Int($1)) % 997 } + return MLXArray( + (0 ..< count).map { i -> Float in + name.contains("norm") && name.hasSuffix("weight") + ? 1 : sin(Float((i * 7 + salt) % 73)) * 0.035 + }, shape + ).asType(dtype) + } + struct Models { + let target: MiMoV26TextModel, vision: MiMoV26VisionTower, patch: MiMoV26AudioPatchEncoder + let adapter: MiMoV26CBv2Adapter, processor: MiMoV26MultimodalProcessor + let tokenizer: MiMoMediaTestTokenizer, generation: MiMoV26MediaGeneration, owner: Owner + var binding: MiMoV26CBv2Binding { + .init(adapter: adapter, assistant: nil, stopTokenIDs: [], mediaGeneration: generation) + } + } + static func models(_ dtype: String = "float32") throws -> Models { + try native() + let c = try configuration(dtype) + let d: DType = dtype == "float32" ? .float32 : .bfloat16 + let target = try MiMoV26TextModel(c) + try target.update( + parameters: .unflattened( + target.parameters().flattened().map { name, value in + ( + name, + values( + name, value.shape, + name.hasSuffix("e_score_correction_bias") + ? .float32 : name.hasSuffix("mlp.gate.weight") ? .bfloat16 : d) + ) + }), verify: .all) + let vision = try MiMoV26VisionTower(configuration: XCTUnwrap(c.vision)) + try vision.loadNativeWeights( + try MiMoV26VisionTower.expectedTensorShapes(configuration: XCTUnwrap(c.vision)) + .mapValues { values("vision", $0, d) }, expectedDType: d) + let patch = try MiMoV26AudioPatchEncoder(configuration: XCTUnwrap(c.audio)) + try patch.loadNativeWeights( + try MiMoV26AudioPatchEncoder.expectedTensorShapes(configuration: XCTUnwrap(c.audio)) + .mapValues { values("audio", $0, d) }, expectedDType: d) + let adapter = try MiMoV26CBv2Adapter(target: target) + let tokenizer = MiMoMediaTestTokenizer() + let generation = MiMoV26MediaGeneration() + let owner = Owner() + let template = "routing fixture, not Jinja" + let processor = try MiMoV26MultimodalProcessor( + configuration: c, tokenizer: tokenizer, chatTemplate: template, + templateSHA256: MiMoV26MultimodalProcessor.hash(Data(template.utf8)), limits: limits, + vision: vision, + audioPatch: patch, adapter: adapter, stopTokens: [], generation: generation, + retaining: owner, audioCodec: nil) + return .init( + target: target, vision: vision, patch: patch, adapter: adapter, processor: processor, + tokenizer: tokenizer, generation: generation, owner: owner) + } + static func image(_ value: Float = 80) -> MiMoV26Pixels.DecodedRGB { + .init( + height: 64, width: 64, planarRGB: (0 ..< (3 * 64 * 64)).map { value + Float($0 % 31) }) + } + static func request(_ content: [MiMoV26MultimodalContent]) -> MiMoV26MultimodalInput { + .init(messages: [.init(role: .user, content: content)], maximumOutputTokens: 3) + } +} + +final class MiMoV26MultimodalInputTests: XCTestCase { + func testNativeTimestampFormattingIsFloorAndUnboundedMinutes() throws { + let cases: [(Float, String)] = [ + (0, "00:00"), (59.999, "00:59"), (60, "01:00"), (3600, "60:00"), + ] + for (value, expected) in cases { + XCTAssertEqual(try MiMoV26MultimodalProfile.timestamp(value), expected) + } + let invalid: [Float] = [-1, .nan, .infinity] + for value in invalid { XCTAssertThrowsError(try MiMoV26MultimodalProfile.timestamp(value)) } + } + func testOrderedImageVideoAndAllHistoryRolesSurvive() throws { + let f = try MiMoMediaFixture.models() + let image = MiMoMediaFixture.image() + let video = MiMoV26SilentVideo(frames: [image, image, image], timestamps: [0, 1, 2]) + let input = MiMoV26MultimodalInput( + messages: [ + .init(role: .system, content: [.text("s")]), + .init( + role: .assistant, content: [.image(image)], + templateFields: ["reasoning_content": "kept"]), + .init( + role: .tool, content: [.silentVideo(video)], + templateFields: ["tool_call_id": "tool-1"]), + .init(role: .user, content: [.text("u"), .image(image)]), + ], maximumOutputTokens: 3) + let plan = try f.processor.plan(input) + XCTAssertEqual(plan.spans.map(\.kind), [.image, .video, .video, .image]) + XCTAssertEqual(plan.spans.map(\.length), [9, 9, 9, 9]) + XCTAssertEqual(plan.spans.map(\.mediaIndex), [0, 1, 1, 2]) + XCTAssertEqual(plan.spans.map(\.featureOffset), [0, 0, 9, 0]) + XCTAssertEqual( + f.tokenizer.messages.map { $0["role"] as! String }, + ["system", "assistant", "tool", "user"]) + XCTAssertEqual(f.tokenizer.messages[1]["reasoning_content"] as? String, "kept") + XCTAssertEqual(f.tokenizer.messages[2]["tool_call_id"] as? String, "tool-1") + XCTAssertEqual(plan.promptTokens.filter { $0 == 3 }.count, 18) + } + func testAmbiguousMissingExtraAndWrongKindMarkersRefuse() throws { + let f = try MiMoMediaFixture.models() + let input = MiMoMediaFixture.request([.image(MiMoMediaFixture.image())]) + for ids in [[11, 12], [11, 4, 3, 5, 12], [11, 4, 2, 5, 4, 2, 5, 12], [11, 2, 12]] { + f.tokenizer.override = ids + XCTAssertThrowsError(try f.processor.plan(input)) + } + f.tokenizer.override = nil + XCTAssertThrowsError( + try f.processor.plan( + MiMoMediaFixture.request([ + .text("literal <|image_pad|>"), .image(MiMoMediaFixture.image()), + ]))) + } + func testMissingCodecAndMalformedVideoRefuseWithoutAuthorization() throws { + let f = try MiMoMediaFixture.models() + let image = MiMoMediaFixture.image() + let pcm = try MiMoV26DecodedPCM( + samples: Array(repeating: 0, count: 960), + descriptor: .init( + sourceIdentity: "test", channels: 1, frameCount: 960, sampleRate: 24000)) + XCTAssertThrowsError(try f.processor.plan(MiMoMediaFixture.request([.audio(pcm)]))) { + XCTAssertEqual($0 as? MiMoV26MultimodalError, .missingAudioCodec) + } + let invalidStamps: [[Float]] = [[], [0], [1, 0], [0, .nan], [0, 0]] + for stamps in invalidStamps { + XCTAssertThrowsError( + try f.processor.plan( + MiMoMediaFixture.request([ + .silentVideo(.init(frames: [image, image], timestamps: stamps)) + ]))) + } + } + func testMetadataBoundsControlsAndActualPixelsBindPlan() throws { + let f = try MiMoMediaFixture.models() + let a = try f.processor.plan(MiMoMediaFixture.request([.image(MiMoMediaFixture.image(50))])) + let b = try f.processor.plan(MiMoMediaFixture.request([.image(MiMoMediaFixture.image(51))])) + XCTAssertEqual(a.promptTokens, b.promptTokens) + XCTAssertNotEqual(a.preparationSHA256, b.preparationSHA256) + XCTAssertThrowsError( + try f.processor.plan( + .init( + messages: [.init(role: .user, content: [.image(MiMoMediaFixture.image())])], + additionalContext: ["input_audio": "forbidden"], maximumOutputTokens: 3))) + XCTAssertThrowsError( + try f.processor.plan( + .init( + messages: [.init(role: .user, content: [.image(MiMoMediaFixture.image())])], + additionalContext: ["enable_thinking": "false"], maximumOutputTokens: 3))) + XCTAssertThrowsError( + try f.processor.plan( + .init( + messages: [ + .init( + role: .user, content: [.image(MiMoMediaFixture.image())], + templateFields: ["audio_url": "unbound"]) + ], maximumOutputTokens: 3))) + XCTAssertThrowsError( + try f.processor.plan( + .init( + messages: [.init(role: .user, content: [.image(MiMoMediaFixture.image())])], + maximumOutputTokens: Int.max))) + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26MultimodalProcessorTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26MultimodalProcessorTests.swift new file mode 100644 index 0000000000..06b8548f09 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26MultimodalProcessorTests.swift @@ -0,0 +1,212 @@ +import Foundation +import MLX +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon +@testable import MLXVLM + +final class MiMoV26MultimodalProcessorTests: XCTestCase { + private func prepared(_ f: MiMoMediaFixture.Models, _ content: [MiMoV26MultimodalContent]) + throws -> MiMoV26PreparedMultimodal + { + let plan = try f.processor.plan(MiMoMediaFixture.request(content)) + return try f.processor.prepare(plan, authorize: { MiMoMediaFixture.Reservation($0) }) + } + func testActualVisionFeaturesArePairedInPromptOrderIncludingOddVideo() throws { + let f = try MiMoMediaFixture.models() + let a = MiMoMediaFixture.image(40) + let b = MiMoMediaFixture.image(90) + let video = MiMoV26SilentVideo(frames: [a, b, a], timestamps: [0, 1, 2]) + let value = try prepared(f, [.image(b), .text("between"), .silentVideo(video), .image(a)]) + let request = try value.makeRequest(binding: f.binding, id: .init(1)) + XCTAssertFalse(request.prefixCacheEnabled) + XCTAssertNil(request.positionState) + XCTAssertNil(request.hybridPrefixIdentity) + XCTAssertEqual(request.multimodal?.attention, .causal) + let arrays = try XCTUnwrap(request.multimodal).embeddings() + XCTAssertEqual(arrays.count, 4) + var expected: [MLXArray] = [] + for content in [MiMoV26MultimodalContent.image(b), .silentVideo(video), .image(a)] { + let pixels: MiMoV26Pixels.Prepared + switch content { + case .image(let frame): + pixels = try MiMoV26Pixels.image( + frame, settings: f.processor.profile.settings, + limits: MiMoMediaFixture.limits.pixels) + case .silentVideo(let clip): + pixels = try MiMoV26Pixels.video( + frames: clip.frames, sampledFrameCount: clip.frames.count, + settings: f.processor.profile.settings, limits: MiMoMediaFixture.limits.pixels) + default: throw MiMoV26MultimodalError.incompatiblePlan + } + let g = pixels.geometry + let feature = try f.vision.forward( + patches: MLXArray(pixels.patchValues, [g.patchCount, g.patchVectorSize]), + grids: [.init(temporal: g.gridT, height: g.gridH, width: g.gridW)], + limits: MiMoMediaFixture.limits.vision) + let per = g.gridH * g.gridW / 4 + for t in 0 ..< g.gridT { expected.append(feature[(t * per) ..< ((t + 1) * per), 0...]) } + } + for (a, b) in zip(arrays, expected) { + eval(a, b) + XCTAssertEqual(a.shape, b.shape) + XCTAssertLessThanOrEqual(abs(a - b).max().item(Float.self), 1e-6) + } + XCTAssertThrowsError(try XCTUnwrap(request.multimodal).embeddings()) + } + func testForeignPlanAndBindingRefuseBeforeAuthorizationOrConsumption() throws { + let a = try MiMoMediaFixture.models() + let b = try MiMoMediaFixture.models() + let plan = try a.processor.plan( + MiMoMediaFixture.request([.image(MiMoMediaFixture.image())])) + var authorizations = 0 + XCTAssertThrowsError( + try b.processor.prepare( + plan, + authorize: { + authorizations += 1 + return MiMoMediaFixture.Reservation($0) + })) + XCTAssertEqual(authorizations, 0) + let value = try a.processor.prepare(plan, authorize: { MiMoMediaFixture.Reservation($0) }) + XCTAssertThrowsError(try value.makeRequest(binding: b.binding, id: .init(2))) + let request = try value.makeRequest(binding: a.binding, id: .init(3)) + XCTAssertNotNil(request.multimodal) + XCTAssertThrowsError(try value.makeRequest(binding: a.binding, id: .init(4))) + } + func testGenerationInvalidationRejectsPlanPreparedAndQueuedHandoffs() throws { + let f = try MiMoMediaFixture.models() + let plan = try f.processor.plan( + MiMoMediaFixture.request([.image(MiMoMediaFixture.image())])) + let first = try f.processor.prepare(plan, authorize: { MiMoMediaFixture.Reservation($0) }) + let second = try f.processor.prepare(plan, authorize: { MiMoMediaFixture.Reservation($0) }) + let queued = try second.makeRequest(binding: f.binding, id: .init(5)) + f.generation.invalidate() + var calls = 0 + XCTAssertThrowsError( + try f.processor.prepare( + plan, + authorize: { + calls += 1 + return MiMoMediaFixture.Reservation($0) + })) + XCTAssertEqual(calls, 0) + XCTAssertThrowsError(try first.makeRequest(binding: f.binding, id: .init(6))) + XCTAssertThrowsError(try XCTUnwrap(queued.multimodal).embeddings()) + } + func testMandatoryReservationRejectionAndCancellationRetainThenReleaseOwner() throws { + let f = try MiMoMediaFixture.models() + let plan = try f.processor.plan( + MiMoMediaFixture.request([.image(MiMoMediaFixture.image())])) + var calls = 0 + XCTAssertThrowsError( + try f.processor.prepare( + plan, + authorize: { + calls += 1 + return MiMoMediaFixture.Reservation($0) + }, isCancelled: { true })) + XCTAssertEqual(calls, 0) + weak var observed: MiMoMediaFixture.Reservation? + var cancelled = false + XCTAssertThrowsError( + try f.processor.prepare( + plan, + authorize: { value in + let reservation = MiMoMediaFixture.Reservation(value) + observed = reservation + cancelled = true + return reservation + }, isCancelled: { cancelled })) + XCTAssertNil(observed, "preparation failure drained and released the only work owner") + XCTAssertThrowsError( + try f.processor.prepare( + plan, + authorize: { value in + let reservation = MiMoMediaFixture.Reservation(value) + reservation.revoked = true + return reservation + })) + } + func testPreparedAndRequestKeepWorkOwnerWithoutArraySnapshots() throws { + let f = try MiMoMediaFixture.models() + let plan = try f.processor.plan( + MiMoMediaFixture.request([.image(MiMoMediaFixture.image())])) + weak var observed: MiMoMediaFixture.Reservation? + var prepared: MiMoV26PreparedMultimodal? = try f.processor.prepare( + plan, + authorize: { value in + let reservation = MiMoMediaFixture.Reservation(value) + observed = reservation + return reservation + }) + var request: CBv2Request? = try prepared!.makeRequest(binding: f.binding, id: .init(7)) + prepared = nil + XCTAssertNotNil(observed) + _ = try request!.multimodal!.embeddings() + XCTAssertNotNil(observed) + request = nil + XCTAssertNil(observed) + } + func testUnloadedOrWrongPrecisionTowerIsNotSilentlyAccepted() throws { + let f = try MiMoMediaFixture.models("bfloat16") + try f.vision.update(parameters: f.vision.parameters(), verify: .all) + let plan = try f.processor.plan( + MiMoMediaFixture.request([.image(MiMoMediaFixture.image())])) + XCTAssertThrowsError( + try f.processor.prepare(plan, authorize: { MiMoMediaFixture.Reservation($0) })) + let source = try MiMoV26VisionTower.expectedTensorShapes( + configuration: f.vision.configuration + ) + .mapValues { MiMoMediaFixture.values("wrong-type", $0, .float32) } + try f.vision.loadNativeWeights(source, expectedDType: .float32) + XCTAssertThrowsError( + try f.processor.prepare(plan, authorize: { MiMoMediaFixture.Reservation($0) }) + ) { + XCTAssertEqual($0 as? MiMoV26MultimodalError, .invalidFeatures) + } + } + func testFailedMediaDrainKeepsActualRootSourceAndLeaseUntilRecovery() throws { + let f = try MiMoMediaFixture.models() + let plan = try f.processor.plan( + MiMoMediaFixture.request([.image(MiMoMediaFixture.image())])) + enum Failure: Error { case injected } + var quarantined: MiMoV26FailedMediaWork? + var lease: MiMoMediaFixture.Reservation? = .init(plan) + weak var weakLease = lease + lease!.quarantine = { quarantined = $0 } + var source: NSObject? = NSObject() + weak var weakSource = source + var array: MLXArray? = MLXArray([Float(1), 2]) + weak var weakArray = array + var work: MiMoV26FailedMediaWork? = .init( + plan: plan, owner: source!, codec: nil, reservation: lease!) + work!.track([array!]) + array = nil + source = nil + lease = nil + XCTAssertThrowsError( + try work!.drain(generation: f.generation, synchronize: { throw Failure.injected }) + ) { + XCTAssertEqual($0 as? MiMoV26MultimodalError, .drainFailed) + } + work = nil + XCTAssertNotNil(weakArray) + XCTAssertNotNil(weakSource) + XCTAssertNotNil(weakLease) + XCTAssertEqual(quarantined?.retainedRootCount, 1) + XCTAssertThrowsError(try f.generation.validate()) + XCTAssertThrowsError( + try quarantined!.verifyRecoveryDrain(synchronize: { throw Failure.injected })) + XCTAssertNotNil(weakArray) + XCTAssertNotNil(weakSource) + XCTAssertNotNil(weakLease) + try quarantined!.recoverAndReleaseAfterDrain() + XCTAssertNil(weakArray) + XCTAssertNil(weakSource) + XCTAssertNil(weakLease) + XCTAssertThrowsError(try quarantined!.recoverAndReleaseAfterDrain()) + quarantined = nil + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26NAXAttentionKeyRangeTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26NAXAttentionKeyRangeTests.swift new file mode 100644 index 0000000000..fe277ba259 --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26NAXAttentionKeyRangeTests.swift @@ -0,0 +1,295 @@ +// Copyright © 2026 Eigen Labs. +// SPDX-License-Identifier: Apache-2.0 +// Source-prepared component gates; no measured performance/peak or model claim. + +import Foundation +import MLX +import MLXFast +import MLXRandom +import XCTest + +@testable import MLXLMCommon + +final class MiMoV26NAXAttentionKeyRangeTests: XCTestCase { + private let payloadLimit = 64 << 20 + + private func requireGPU() throws { + guard ProcessInfo.processInfo.environment["DARKBLOOM_TEST_MIMO_NAX_KEY_RANGES"] == "1" + else { + throw XCTSkip("Requires exclusive native lane and explicit key-range component opt-in") + } + guard MiMoV26NAXGatherQMM.gpuStream(.default), MiMoV26NAXGatherQMM.naxAvailable + else { throw XCTSkip("M5 NAX required; M3 control is not kernel qualification") } + } + + private func schedule(_ q: MLXArray, _ k: MLXArray, _ edges: [Int]) throws + -> MiMoV26NAXAttentionKeyRanges.Schedule + { + try XCTUnwrap( + MiMoV26NAXAttentionKeyRanges.makeSchedule( + batch: q.dim(0), heads: q.dim(1), queries: q.dim(2), keys: k.dim(2), + edges: edges, maximumPayloadBytes: payloadLimit)) + } + + private func fixture(_ length: Int, _ keyCount: Int, _ dtype: DType, batch: Int = 1) + -> (q: MLXArray, k: MLXArray, v: MLXArray) + { + ( + (MLXRandom.normal([batch, 4, length, 192], key: MLXRandom.key(40320)) * 0.5).asType( + dtype), + (MLXRandom.normal([batch, 2, keyCount, 192], key: MLXRandom.key(40321)) * 0.5).asType( + dtype), + (MLXRandom.normal([batch, 2, keyCount, 128], key: MLXRandom.key(40322)) * 0.5).asType( + dtype) + ) + } + + private final class FaultRoots { + var arrays: [MLXArray] = [] + } + + /// Keep every array until actual synchronous evaluation and readback. + /// Failed completion retains real roots until this isolated test process + /// exits; it is not a refund/retirement proof and normal cells must stop. + @discardableResult + private func compare( + _ q: MLXArray, _ k: MLXArray, _ v: MLXArray, edges: [Int], + mask: MLXFast.ScaledDotProductAttentionMaskMode, + sinks: MLXArray? = nil, nativeExact: Bool = false, + firstNativeRowExact: Bool = false + ) throws -> Data { + let roots = FaultRoots() + roots.arrays = [q, k, v] + (sinks.map { [$0] } ?? []) + var completed = false + defer { if !completed { _ = Unmanaged.passRetained(roots) } } + var bytes = Data() + try withError { errors in + let scale = 1 / Float(192).squareRoot() + let plan = try XCTUnwrap( + MiMoV26NAXAttention.makePlan( + queries: q, keys: k, values: v, scale: scale, + mask: mask, sinks: sinks, production: false)) + let old = MiMoV26NAXAttention.launch( + queries: q, keys: k, values: v, scale: scale, plan: plan) + roots.arrays.append(old) + let bounds = try schedule(q, k, edges) + let split = try XCTUnwrap( + MiMoV26NAXAttentionKeyRanges.launch( + queries: q, keys: k, values: v, scale: scale, mask: mask, sinks: sinks, + schedule: bounds, maximumPayloadBytes: payloadLimit, + retain: { roots.arrays.append(contentsOf: $0) })) + roots.arrays.append(split.output) + // Every non-final phase/range output is full FP32 state. No + // ping-pong/reclamation assumption: all actual objects stay held. + XCTAssertEqual(split.retainedArrays.count, 4 + 3 * bounds.dispatches) + XCTAssertEqual( + split.retainedArrays.filter { + $0.dtype == .float32 && $0.size == bounds.stateElements + }.count, bounds.fullStateBuffers) + let native = MLXFast.scaledDotProductAttention( + queries: q, keys: k, values: v, scale: scale, mask: mask, sinks: sinks) + roots.arrays.append(native) + try errors.check() + eval(roots.arrays) + try errors.check() + XCTAssertEqual(split.output.shape, old.shape) + XCTAssertEqual(split.output.dtype, old.dtype) + bytes = split.output.asData().data + XCTAssertEqual( + bytes, old.asData().data, + "range handoff must preserve stored bytes, including signed zero/NaN payloads") + if nativeExact { XCTAssertEqual(bytes, native.asData().data) } + if firstNativeRowExact { + // Overflow cells deliberately have unrelated all-infinite + // rows; never require finiteness or equal NaN payloads there. + let a = split.output[0..., 0..., 0 ..< 1, 0...] + let b = native[0..., 0..., 0 ..< 1, 0...] + XCTAssertEqual(a.asData().data, b.asData().data) + } + let a = split.output.view(dtype: .uint16).asArray(UInt16.self) + let b = native.view(dtype: .uint16).asArray(UInt16.self) + let exponent: UInt16 = q.dtype == .bfloat16 ? 0x7f80 : 0x7c00 + func ordered(_ x: UInt16) -> UInt32 { + x & 0x8000 == 0 ? UInt32(x) + 0x8000 : UInt32(~x) + } + var maxULP: UInt32 = 0 + var nonfinitePairs = 0 + for (x, y) in zip(a, b) { + if x & exponent == exponent || y & exponent == exponent { + nonfinitePairs += 1 + } else { + let xx = ordered(x) + let yy = ordered(y) + maxULP = max(maxULP, xx > yy ? xx - yy : yy - xx) + } + } + print( + "MiMoKeyRanges shape=\(q.shape)/\(k.shape) dtype=\(q.dtype)" + + " edges=\(edges) oldBytesExact=\(bytes == old.asData().data)" + + " nativeMaxFiniteULP=\(maxULP) nativeNonfinitePairs=\(nonfinitePairs)" + + " heldStateBuffers=\(bounds.fullStateBuffers) arrayPayloadBytes=\(bounds.arrayPayloadBytes)" + ) + try errors.check() + } + completed = true + return bytes + } + + func testBalancedRangesAndAllPendingStatePayloadAreBounded() throws { + typealias R = MiMoV26NAXAttentionKeyRanges + XCTAssertEqual(R.balancedEdges(batch: 1, heads: 64, queries: 448, keys: 65536), [0, 2048]) + XCTAssertEqual( + R.balancedEdges(batch: 1, heads: 64, queries: 512, keys: 65536), + Array(stride(from: 0, through: 2048, by: 256))) + XCTAssertEqual( + R.balancedEdges(batch: 1, heads: 64, queries: 512, keys: 12288), [0, 192, 384]) + // Python ties-to-even: 2.5 ranges -> 2, not 3. + XCTAssertEqual( + R.balancedEdges(batch: 1, heads: 64, queries: 512, keys: 20480), [0, 320, 640]) + XCTAssertEqual( + R.balancedEdges(batch: 1, heads: 64, queries: 512, keys: 21001), [0, 219, 438, 657]) + XCTAssertNil( + R.balancedEdges( + batch: 1, heads: 64, queries: 512, keys: 8192, + preferredKeys: 1, minimumThreadgroups: 0)) + let edges = [0, 1, 3, 9] // 257 keys, deliberately uneven and padded. + let value = try XCTUnwrap( + R.makeSchedule( + batch: 2, heads: 4, queries: 65, keys: 257, + edges: edges, maximumPayloadBytes: Int.max)) + XCTAssertEqual(value.stateElements, 2 * 4 * 128 * 130) + XCTAssertEqual(value.fullStateBuffers, 8) + XCTAssertEqual(value.dispatches, 9) + XCTAssertGreaterThan(value.arrayPayloadBytes, 2 * value.stateBufferBytes) + XCTAssertNotNil( + R.makeSchedule( + batch: 2, heads: 4, queries: 65, keys: 257, + edges: edges, maximumPayloadBytes: value.arrayPayloadBytes)) + XCTAssertNil( + R.makeSchedule( + batch: 2, heads: 4, queries: 65, keys: 257, + edges: edges, maximumPayloadBytes: value.arrayPayloadBytes - 1)) + for bad in [[0, 0, 9], [0, 5, 4, 9], [1, 9], [0, 8], [0, 10], []] { + XCTAssertNil( + R.makeSchedule( + batch: 2, heads: 4, queries: 65, keys: 257, + edges: bad, maximumPayloadBytes: Int.max)) + } + XCTAssertNil( + R.makeSchedule( + batch: Int.max, heads: 64, queries: 65, keys: 257, + edges: edges, maximumPayloadBytes: Int.max)) + XCTAssertNil( + R.makeSchedule( + batch: 64, heads: 64, queries: 1_048_576, keys: 1_048_576, + edges: [0, 32768], maximumPayloadBytes: Int.max)) + XCTAssertNil( + R.makeSchedule( + batch: 1, heads: 1, queries: 8, keys: 257, + edges: edges, maximumPayloadBytes: Int.max)) + } + + func testCPUStreamRefusesBeforeCustomEncoding() throws { + let f = fixture(64, 128, .bfloat16) + let bounds = try schedule(f.q, f.k, [0, 2, 4]) + XCTAssertNil( + MiMoV26NAXAttentionKeyRanges.launch( + queries: f.q, keys: f.k, values: f.v, scale: 0.07, mask: .causal, + sinks: nil, schedule: bounds, maximumPayloadBytes: payloadLimit, stream: .cpu, + retain: { _ in XCTFail("CPU refusal must precede range graph allocation") })) + } + + func testOneManyUnevenRangesPreserveStoredBytesAcrossMasksAndSinks() throws { + try requireGPU() + for dtype in [DType.bfloat16, .float16] { + for (length, keyCount, edges) in [ + (64, 128, [0, 4]), (65, 257, [0, 1, 3, 9]), + (100, 300, [0, 3, 6, 10]), (16, 8193, [0, 128, 257]), + ] { + let f = fixture(length, keyCount, dtype, batch: length == 65 ? 2 : 1) + let sink = MLXArray([Float(-0.75), 0, 0.5, 1.25]).asType(dtype) + for mode in 0 ..< 4 { + let mask: MLXFast.ScaledDotProductAttentionMaskMode + switch mode { + case 0: mask = .none + case 1: mask = .causal + case 2: + mask = .array( + createCausalMask(n: length, offset: keyCount - length, windowSize: 47)) + default: mask = .array(MLXArray.zeros([length, keyCount], dtype: .bool)) + } + try compare( + f.q, f.k, f.v, edges: edges, mask: mask, + sinks: mode % 2 == 0 ? nil : sink) + } + } + } + } + + func testLazyStridedKVMaskAndSinksPreserveExactRangeState() throws { + try requireGPU() + for dtype in [DType.bfloat16, .float16] { + let qWide = MLXRandom.normal([2, 65, 4, 384], key: MLXRandom.key(410)).asType(dtype) + let kWide = MLXRandom.normal([2, 2, 514, 384], key: MLXRandom.key(411)).asType(dtype) + let vWide = MLXRandom.normal([2, 2, 514, 256], key: MLXRandom.key(412)).asType(dtype) + let q = qWide.transposed(0, 2, 1, 3)[.ellipsis, .stride(by: 2)] + let k = kWide[0..., 0..., .stride(by: 2), .stride(by: 2)] + let v = vWide[0..., 0..., .stride(by: 2), .stride(by: 2)] + let maskWide = createCausalMask(n: 130, offset: 514 - 130, windowSize: 94) + let mask = maskWide[.stride(by: 2), .stride(by: 2)] + let sinks = MLXArray([Float(0), 99, 0.5, 99, -0.25, 99, 0.75, 99]) + .asType(dtype)[.stride(by: 2)] + // No eval before handing lazy inner-head and sequence views in. + let a = try compare(q, k, v, edges: [0, 1, 3, 9], mask: .array(mask), sinks: sinks) + let b = try compare( + contiguous(q), contiguous(k), contiguous(v), + edges: [0, 1, 3, 9], mask: .array(contiguous(mask)), + sinks: contiguous(sinks)) + XCTAssertEqual(a, b) + } + } + + func testNativeUniformRoundingAndFullyMaskedRowsRemainExact() throws { + try requireGPU() + for dtype in [DType.bfloat16, .float16] { + let q = MLXArray.zeros([1, 4, 65, 192], dtype: dtype) + for (count, sink, masked) in [ + (128, false, false), (127, true, false), (127, false, true), + ] { + let k = MLXArray.zeros([1, 2, count, 192], dtype: dtype) + let v = MLXArray.ones([1, 2, count, 128], dtype: dtype) + let mask: MLXFast.ScaledDotProductAttentionMaskMode = + masked + ? .array(MLXArray.zeros([65, count], dtype: .bool)) : .none + try compare( + q, k, v, edges: [0, 1, 4], mask: mask, + sinks: sink ? MLXArray.zeros([4], dtype: dtype) : nil, nativeExact: true) + } + } + } + + func testOverflowAndNonfiniteRowsDoNotTruncateRealMaskedKeys() throws { + try requireGPU() + let q = MLXArray.full([1, 4, 256, 192], values: MLXArray(Float(2048)), dtype: .float16) + let k = MLXArray.full([1, 2, 256, 192], values: MLXArray(Float(-2048)), dtype: .float16) + let v = concatenated( + [ + MLXArray.zeros([1, 2, 128, 128], dtype: .float16), + MLXArray.ones([1, 2, 128, 128], dtype: .float16), + ], axis: 2) + // Native QK overflows to -inf. The first row's real masked keys use + // finite minimum and contribute the out-of-prefix nonzero V values. + // A causal-range truncation would incorrectly produce 0 or NaN. + try compare(q, k, v, edges: [0, 1, 4, 8], mask: .causal, firstNativeRowExact: true) + for dtype in [DType.bfloat16, .float16] { + let normal = fixture(65, 127, dtype) + let nanQ = MLXArray.full(normal.q.shape, values: MLXArray(Float.nan), dtype: dtype) + try compare(nanQ, normal.k, normal.v, edges: [0, 1, 4], mask: .none) + let infiniteV = MLXArray.full( + normal.v.shape, values: MLXArray(Float.infinity), dtype: dtype) + try compare( + normal.q, normal.k, infiniteV, edges: [0, 1, 4], + mask: .array(MLXArray.zeros([65, 127], dtype: .bool))) + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26NAXAttentionTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26NAXAttentionTests.swift new file mode 100644 index 0000000000..521a5c8e6c --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26NAXAttentionTests.swift @@ -0,0 +1,212 @@ +// Copyright © 2026 Eigen Labs. +// SPDX-License-Identifier: Apache-2.0 +// Source-only candidate tests. Numerical diagnostics alone are not qualification. + +import Foundation +import MLX +import MLXRandom +import XCTest + +@testable import MLXLMCommon + +final class MiMoV26NAXAttentionTests: XCTestCase { + private func requireGPU() throws { + guard ProcessInfo.processInfo.environment["DARKBLOOM_TEST_MIMO_NAX_ATTENTION"] == "1" + else { throw XCTSkip("Requires explicitly owned NAX GPU lane") } + guard MiMoV26NAXGatherQMM.gpuStream(.default), MiMoV26NAXGatherQMM.naxAvailable + else { throw XCTSkip("Current stream/build/device cannot execute NAX") } + } + + private func fixture(_ length: Int, _ keys: Int, dtype: DType, heads: Int = 8, kvHeads: Int = 2) + -> (q: MLXArray, k: MLXArray, v: MLXArray) + { + ( + q: (MLXRandom.normal([1, heads, length, 192], key: MLXRandom.key(192)) * 0.5).asType( + dtype), + k: (MLXRandom.normal([1, kvHeads, keys, 192], key: MLXRandom.key(193)) * 0.5).asType( + dtype), + v: (MLXRandom.normal([1, kvHeads, keys, 128], key: MLXRandom.key(194)) * 0.5).asType( + dtype) + ) + } + + private func run( + _ q: MLXArray, _ k: MLXArray, _ v: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, sinks: MLXArray? = nil + ) + throws -> MLXArray + { + let scale = 1 / Float(192).squareRoot() + let plan = try XCTUnwrap( + MiMoV26NAXAttention.makePlan( + queries: q, keys: k, values: v, scale: scale, mask: mask, + sinks: sinks, production: false)) + return MiMoV26NAXAttention.launch( + queries: q, keys: k, values: v, scale: scale, plan: plan) + } + + private func report(_ a: MLXArray, _ b: MLXArray, label: String) { + eval(a, b) + XCTAssertEqual(a.dtype, b.dtype) + XCTAssertEqual(a.shape, b.shape) + let aa = a.asType(.float32).asArray(Float.self) + let bb = b.asType(.float32).asArray(Float.self) + var maxULP: UInt32 = 0 + var maxAbsolute: Float = 0 + for (x, y) in zip(aa, bb) { + XCTAssertTrue(x.isFinite && y.isFinite) + let xb = + a.dtype == .bfloat16 + ? UInt16(truncatingIfNeeded: x.bitPattern >> 16) : Float16(x).bitPattern + let yb = + b.dtype == .bfloat16 + ? UInt16(truncatingIfNeeded: y.bitPattern >> 16) : Float16(y).bitPattern + let xi = (xb & 0x8000) == 0 ? UInt32(xb) + 0x8000 : UInt32(~xb) + let yi = (yb & 0x8000) == 0 ? UInt32(yb) + 0x8000 : UInt32(~yb) + maxULP = max(maxULP, xi > yi ? xi - yi : yi - xi) + maxAbsolute = max(maxAbsolute, abs(x - y)) + } + print("MiMoNAXAttention \(label) dtype=\(a.dtype) maxULP=\(maxULP) maxAbs=\(maxAbsolute)") + // Full-model greedy/state and arithmetic attribution gates are separate. + // A finite or tolerance-close result is deliberately not called lossless. + } + + func testShapeDtypeMaskAndOwnerGates() { + let f = fixture(64, 128, dtype: .bfloat16) + func plan( + _ q: MLXArray, _ k: MLXArray, _ v: MLXArray, + _ mask: MLXFast.ScaledDotProductAttentionMaskMode = .causal, + _ sinks: MLXArray? = nil, production: Bool = false + ) -> MiMoV26NAXAttention.Plan? { + MiMoV26NAXAttention.makePlan( + queries: q, keys: k, values: v, + scale: 0.07, mask: mask, sinks: sinks, production: production) + } + XCTAssertNotNil(plan(f.q, f.k, f.v)) + XCTAssertNil(plan(f.q, f.k, f.v, production: true)) + XCTAssertNil(plan(f.q.asType(.float32), f.k.asType(.float32), f.v.asType(.float32))) + XCTAssertNil(plan(f.q[.ellipsis, ..<8, 0...], f.k, f.v)) + XCTAssertNil(plan(f.q, f.k, f.v, .array(MLXArray.zeros([64, 128])))) + XCTAssertNil(plan(f.q, f.k, f.v, .array(MLXArray.zeros([3, 64, 128], dtype: .bool)))) + XCTAssertNil(plan(f.q, f.k, f.v, .causal, MLXArray.zeros([8], dtype: .float32))) + } + + func testUniformProbabilityRoundingAndMaskedTailExactly() throws { + try requireGPU() + for dtype in [DType.bfloat16, .float16] { + let q = MLXArray.zeros([1, 8, 64, 192], dtype: dtype) + for (keyCount, hasSink, fullyMasked) in [ + (128, false, false), (127, true, false), + (127, false, true), + ] { + let k = MLXArray.zeros([1, 2, keyCount, 192], dtype: dtype) + let v = MLXArray.ones([1, 2, keyCount, 128], dtype: dtype) + let sinks = hasSink ? MLXArray.zeros([8], dtype: dtype) : nil + let mask: MLXFast.ScaledDotProductAttentionMaskMode = + fullyMasked + ? .array(MLXArray.zeros([64, keyCount], dtype: .bool)) : .none + let actual = try run(q, k, v, mask: mask, sinks: sinks) + let expected = + MLXArray.ones(actual.shape, dtype: dtype) + * (hasSink ? Float(127.0 / 128.0) : Float(1)) + report( + actual, expected, + label: "uniform k=\(keyCount) sink=\(hasSink) masked=\(fullyMasked)") + XCTAssertEqual(actual.asData().data, expected.asData().data) + } + } + } + + func testLazyInnerHeadStrideAndSequenceStrideAreBitExact() throws { + try requireGPU() + for dtype in [DType.bfloat16, .float16] { + // No eval occurs before the kernel receives these lazy views. + let qWide = MLXRandom.normal([1, 200, 8, 384], key: MLXRandom.key(200)).asType(dtype) + let kWide = MLXRandom.normal([1, 2, 900, 384], key: MLXRandom.key(201)).asType(dtype) + let vWide = MLXRandom.normal([1, 2, 900, 256], key: MLXRandom.key(202)).asType(dtype) + let q = qWide.transposed(0, 2, 1, 3)[.ellipsis, .stride(by: 2)] + let k = kWide[0..., 0..., .stride(by: 2), .stride(by: 2)] + let v = vWide[0..., 0..., .stride(by: 2), .stride(by: 2)] + let actual = try run(q, k, v, mask: .causal) + let expected = try run(contiguous(q), contiguous(k), contiguous(v), mask: .causal) + report(actual, expected, label: "lazy head/sequence strides") + XCTAssertEqual(actual.asData().data, expected.asData().data) + let rows = actual.transposed(0, 2, 1, 3).reshaped([1, 200, 8 * 128]) + let referenceRows = expected.transposed(0, 2, 1, 3).reshaped(rows.shape) + XCTAssertEqual(rows.asData().data, referenceRows.asData().data) + } + } + + func testBaselineNumericalDiagnosticsForTailsSinksAndWindow() throws { + try requireGPU() + for dtype in [DType.bfloat16, .float16] { + for (length, keys) in [(16, 512), (63, 127), (64, 128), (255, 4095), (300, 700)] { + let f = fixture(length, keys, dtype: dtype) + let sink = MLXRandom.normal([8], key: MLXRandom.key(301)).asType(dtype) + for window in [false, true] { + let mask: MLXFast.ScaledDotProductAttentionMaskMode = + window + ? .array( + createCausalMask(n: length, offset: keys - length, windowSize: 128)) + : .causal + let actual = try run(f.q, f.k, f.v, mask: mask, sinks: sink) + let baseline = MLXFast.scaledDotProductAttention( + queries: f.q, keys: f.k, values: f.v, + scale: 1 / Float(192).squareRoot(), mask: mask, sinks: sink) + report( + actual, baseline, label: "baseline q=\(length) k=\(keys) window=\(window)") + } + } + } + } + + func testManagedFullAndWindowKeepExactKVStateAndExcludeSerialMTP() throws { + try requireGPU() + guard MiMoV26NAXAttention.requested else { + throw XCTSkip( + "Start process with DARKBLOOM_MIMO_V26_NAX_ATTENTION=1 for managed dispatch") + } + for window in [false, true] { + let kind = CBv2LayerKind( + attention: window ? .slidingWindow(128) : .full, hasSinks: window, + headDim: 192, valueHeadDim: 128, kvHeads: 4, queryHeads: 64) + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 128 << 20, kvDType: .bfloat16)) + let baselineState = try backend.makeSequenceState( + layerKinds: [kind], promptLength: 0, maxLength: 1024) + let candidateState = try backend.makeSequenceState( + layerKinds: [kind], promptLength: 0, maxLength: 1024) + defer { + backend.release(baselineState) + backend.release(candidateState) + } + let baseline = CBv2LayerCache(layerIndex: 0, kind: kind) + let candidate = CBv2LayerCache(layerIndex: 0, kind: kind, mimoV26NAXAttention: true) + baseline.setRows([try XCTUnwrap(baselineState[0])]) + candidate.setRows([try XCTUnwrap(candidateState[0])]) + let f = fixture(300, 300, dtype: .bfloat16, heads: 64, kvHeads: 4) + let sinks = window ? MLXArray.zeros([64], dtype: .bfloat16) : nil + let before = MiMoV26NAXAttention.encodedCalls() + let a = baseline.updateAndAttend( + queries: f.q, keys: f.k, values: f.v, scale: 0.07, sinks: sinks) + XCTAssertEqual(MiMoV26NAXAttention.encodedCalls(), before) + let b = candidate.updateAndAttend( + queries: f.q, keys: f.k, values: f.v, scale: 0.07, sinks: sinks) + XCTAssertGreaterThan(MiMoV26NAXAttention.encodedCalls(), before) + report(b, a, label: "managed window=\(window)") + let sa = baselineState[0]!.snapshot() + let sb = candidateState[0]!.snapshot() + eval(sa.keys, sa.values, sb.keys, sb.values) + XCTAssertEqual(sa.offset, sb.offset) + XCTAssertEqual(sa.keys.asData().data, sb.keys.asData().data) + XCTAssertEqual(sa.values.asData().data, sb.values.asData().data) + candidate.mtpSerializesRectangularAttention = true + let verify = fixture(16, 16, dtype: .bfloat16, heads: 64, kvHeads: 4) + let serialBefore = MiMoV26NAXAttention.encodedCalls() + let serial = candidate.updateAndAttend( + queries: verify.q, keys: verify.k, values: verify.v, scale: 0.07, sinks: sinks) + eval(serial) + XCTAssertEqual(MiMoV26NAXAttention.encodedCalls(), serialBefore) + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26NAXAttentionVisibilityTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26NAXAttentionVisibilityTests.swift new file mode 100644 index 0000000000..1421c1ab0f --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26NAXAttentionVisibilityTests.swift @@ -0,0 +1,187 @@ +// Copyright © 2026 Eigen Labs. +// Source-only regression: preserve managed q128 / K-prefix visibility. +// Run only under an explicitly owned M5/NAX lane. No execution is claimed. + +import Foundation +import MLX +import XCTest + +@testable import MLXLMCommon + +final class MiMoV26NAXAttentionVisibilityTests: XCTestCase { + override func setUpWithError() throws { + guard ProcessInfo.processInfo.environment["DARKBLOOM_TEST_MIMO_NAX_ATTENTION"] == "1", + MiMoV26NAXAttention.requested + else { + throw XCTSkip("Requires owned lane and process-start NAX attention/test opt-ins") + } + guard MiMoV26NAXGatherQMM.gpuStream(.default), MiMoV26NAXGatherQMM.naxAvailable else { + throw XCTSkip("Requires actual NAX-capable GPU stream/build") + } + guard CBv2AttentionV1.queryBlockSize == 128 else { + throw XCTSkip("This visibility witness requires the unchanged q128 baseline") + } + } + + private let scale: Float = 1 / Float(192).squareRoot() + + private func withCaches( + dtype: DType, length: Int, + _ body: (CBv2LayerCache, CBv2LayerCache, any CBv2SequenceKV, any CBv2SequenceKV) throws -> + Void + ) throws { + let kind = CBv2LayerKind( + attention: .full, headDim: 192, valueHeadDim: 128, + kvHeads: 4, queryHeads: 64) + let backend = CBv2ContiguousKVBackend( + config: .init(bytesCapacity: 128 << 20, kvDType: dtype)) + let baselineState = try backend.makeSequenceState( + layerKinds: [kind], promptLength: 0, maxLength: length) + let candidateState = try backend.makeSequenceState( + layerKinds: [kind], promptLength: 0, maxLength: length) + defer { + backend.release(baselineState) + backend.release(candidateState) + } + let baselineRow = try XCTUnwrap(baselineState[0]) + let candidateRow = try XCTUnwrap(candidateState[0]) + let baseline = CBv2LayerCache(layerIndex: 0, kind: kind) + let candidate = CBv2LayerCache(layerIndex: 0, kind: kind, mimoV26NAXAttention: true) + baseline.setRows([baselineRow]) + candidate.setRows([candidateRow]) + try body(baseline, candidate, baselineRow, candidateRow) + } + + /// Independent expression of the pre-port full-cache q128/K-prefix path. + /// This helper never asks the new NAX dispatcher to select its oracle. + private func slicedReference(q: MLXArray, k: MLXArray, v: MLXArray) -> MLXArray { + let length = q.dim(2) + let history = k.dim(2) - length + var outputs: [MLXArray] = [] + for start in stride(from: 0, to: length, by: 128) { + let count = min(128, length - start) + let end = history + start + count + outputs.append( + MLXFast.scaledDotProductAttention( + queries: q[0..., 0..., start ..< (start + count), 0...], + keys: k[0..., 0..., .. yi ? xi - yi : yi - xi) + } + print("MiMoNAX visibility \(label) maxStorageULP=\(maxULP)") + XCTAssertEqual(maxULP, 0, label) + XCTAssertEqual(a, b, label) + } + + private func exactState(_ a: any CBv2SequenceKV, _ b: any CBv2SequenceKV, length: Int) { + XCTAssertEqual(a.absoluteOffset, length) + XCTAssertEqual(b.absoluteOffset, length) + XCTAssertEqual(a.retainedCount, length) + XCTAssertEqual(b.retainedCount, length) + let sa = a.snapshot() + let sb = b.snapshot() + XCTAssertEqual(sa.offset, sb.offset) + exact(sa.keys, sb.keys, label: "unchanged K and one update") + exact(sa.values, sb.values, label: "unchanged V and one update") + } + + func testFiniteFP16OverflowCannotReadValuesBeyondFirstBlockPrefix() throws { + let length = 256 + let q = (MLXArray.ones([1, 64, length, 192], dtype: .float16) * 2048).asType(.float16) + let k = (MLXArray.ones([1, 4, length, 192], dtype: .float16) * -2048).asType(.float16) + // Finite native inputs deliberately overflow the materialized native QK. + let score = matmul( + q[0 ..< 1, 0 ..< 1, 0 ..< 1, 0...] * MLXArray(scale).asType(.float16), + k[0 ..< 1, 0 ..< 1, 0 ..< 1, 0...].swappedAxes(-1, -2)) + let nativeScore = score.asType(.float32).item(Float.self) + XCTAssertTrue(nativeScore.isInfinite && nativeScore < 0) + for futureValue: Float in [1, -2] { + let v = concatenated( + [ + MLXArray.zeros([1, 4, 128, 128], dtype: .float16), + MLXArray.ones([1, 4, 128, 128], dtype: .float16) * futureValue, + ], axis: 2 + ).asType(.float16) + try withCaches(dtype: .float16, length: length) { baseline, candidate, a, b in + let before = MiMoV26NAXAttention.encodedCalls() + let reference = baseline.updateAndAttend( + queries: q, keys: k, values: v, + scale: scale, sinks: nil) + XCTAssertEqual(MiMoV26NAXAttention.encodedCalls(), before) + let actual = candidate.updateAndAttend( + queries: q, keys: k, values: v, + scale: scale, sinks: nil) + XCTAssertEqual( + MiMoV26NAXAttention.encodedCalls() - before, 2, + "Both original q128 blocks must engage, not one full call") + let sliced = slicedReference(q: q, k: k, v: v) + let first = actual[0..., 0..., 0 ..< 1, 0...] + let baselineFirst = reference[0..., 0..., 0 ..< 1, 0...] + let slicedFirst = sliced[0..., 0..., 0 ..< 1, 0...] + exact(first, baselineFirst, label: "overflow actual cache first query") + exact(first, slicedFirst, label: "overflow independent sliced oracle") + XCTAssertTrue(first.asType(.float32).asArray(Float.self).allSatisfy { $0 == 0 }) + + // Negative control: the ordinary unblocked contract legitimately + // includes those finite-min-masked future columns. It differs. + let full = try XCTUnwrap( + MiMoV26NAXAttention.tryAttention( + queries: q, keys: k, values: v, scale: scale, mask: .causal, sinks: nil)) + let fullFirst = full[0..., 0..., 0 ..< 1, 0...] + let magnitude = abs(fullFirst.asType(.float32)).max().item(Float.self) + XCTAssertGreaterThan( + magnitude, 0.25, "Fixture must discriminate the removed shortcut") + // Last fully-visible rows can legitimately be all -inf/NaN. + // Deliberately inspect only the discriminating first row. + exactState(a, b, length: length) + } + } + } + + func testHealthyUniformScoresKeepOriginalPrefixSlicesAndShortCalls() throws { + for dtype in [DType.bfloat16, .float16] { + for length in [64, 128, 129, 256, 300] { + let q = MLXArray.zeros([1, 64, length, 192], dtype: dtype) + let k = MLXArray.zeros([1, 4, length, 192], dtype: dtype) + let values = MLXArray((0 ..< length).map { Float($0 % 2) }, [1, 1, length, 1]) + .asType(dtype) + let v = broadcast(values, to: [1, 4, length, 128]) + let expectedEncodings = (0 ..< length).filter { $0 % 128 == 0 } + .filter { min(128, length - $0) > 8 }.count + try withCaches(dtype: dtype, length: length) { baseline, candidate, a, b in + let before = MiMoV26NAXAttention.encodedCalls() + let reference = baseline.updateAndAttend( + queries: q, keys: k, values: v, + scale: scale, sinks: nil) + XCTAssertEqual(MiMoV26NAXAttention.encodedCalls(), before) + let actual = candidate.updateAndAttend( + queries: q, keys: k, values: v, + scale: scale, sinks: nil) + XCTAssertEqual(MiMoV26NAXAttention.encodedCalls() - before, expectedEncodings) + exact(actual, reference, label: "healthy cache \(dtype) L\(length)") + exact( + actual, slicedReference(q: q, k: k, v: v), + label: "healthy sliced oracle \(dtype) L\(length)") + XCTAssertTrue( + actual.asType(.float32).asArray(Float.self).allSatisfy(\.isFinite)) + exactState(a, b, length: length) + } + } + } + } +} diff --git a/Tests/MLXLMTests/MiMo/MiMoV26NAXGateUpTests.swift b/Tests/MLXLMTests/MiMo/MiMoV26NAXGateUpTests.swift new file mode 100644 index 0000000000..7bedfc116a --- /dev/null +++ b/Tests/MLXLMTests/MiMo/MiMoV26NAXGateUpTests.swift @@ -0,0 +1,281 @@ +// Copyright © 2026 Eigen Labs. +// SPDX-License-Identifier: Apache-2.0 +// Joint MXFP4 gather source candidate: tests prepared, not executed. + +import Foundation +import MLX +import MLXNN +import MLXRandom +import XCTest + +@testable import MLXLMCommon + +final class MiMoV26NAXGateUpTests: XCTestCase { + private func requireGPU() throws { + guard ProcessInfo.processInfo.environment["DARKBLOOM_TEST_MIMO_NAX_GATE_UP"] == "1" + else { throw XCTSkip("Requires explicitly owned NAX GPU lane") } + guard MiMoV26NAXGatherQMM.gpuStream(.default), MiMoV26NAXGatherQMM.naxAvailable + else { throw XCTSkip("Current stream/build/device cannot execute NAX") } + } + + private func weights( + _ experts: Int, _ output: Int, _ input: Int, + dtype: DType, seed: UInt64 + ) -> (MLXArray, MLXArray) { + let w = (MLXRandom.normal([experts, output, input], key: MLXRandom.key(seed)) * 0.05) + .asType(dtype) + let (packed, scales, biases) = MLX.quantized(w, groupSize: 32, bits: 4, mode: .mxfp4) + XCTAssertNil(biases) + return (packed, scales) + } + + private func stock( + _ x: MLXArray, _ indices: MLXArray, + _ weights: (MLXArray, MLXArray) + ) -> MLXArray { + MLX.gatherQuantizedMM( + x, weights.0, scales: weights.1, biases: nil, + rhsIndices: indices, transpose: true, groupSize: 32, bits: 4, + mode: .mxfp4, sortedIndices: true) + } + + private func exact(_ actual: MLXArray, _ reference: MLXArray, _ label: String) { + eval(actual, reference) + XCTAssertEqual(actual.dtype, reference.dtype) + XCTAssertEqual(actual.shape, reference.shape) + let a = actual.asType(.float32).asArray(Float.self) + let b = reference.asType(.float32).asArray(Float.self) + var maxULP: UInt32 = 0 + for (x, y) in zip(a, b) { + XCTAssertTrue(x.isFinite && y.isFinite) + let xb = + actual.dtype == .bfloat16 + ? UInt16(truncatingIfNeeded: x.bitPattern >> 16) : Float16(x).bitPattern + let yb = + reference.dtype == .bfloat16 + ? UInt16(truncatingIfNeeded: y.bitPattern >> 16) : Float16(y).bitPattern + let xi = xb & 0x8000 == 0 ? UInt32(xb) + 0x8000 : UInt32(~xb) + let yi = yb & 0x8000 == 0 ? UInt32(yb) + 0x8000 : UInt32(~yb) + maxULP = max(maxULP, xi > yi ? xi - yi : yi - xi) + } + print("MiMoNAXGateUp \(label) dtype=\(actual.dtype) maxULP=\(maxULP)") + XCTAssertEqual(maxULP, 0) + XCTAssertEqual(actual.asData().data, reference.asData().data) + } + + func testJointOutputsMatchBothIndependentOracles() throws { + try requireGPU() + let routes = [ + [70, 0, 5, 33, 64, 17, 1, 130], + [300, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 300], + ] + for dtype in [DType.bfloat16, .float16] { + let gate = weights(8, 128, 256, dtype: dtype, seed: 100) + let up = weights(8, 128, 256, dtype: dtype, seed: 101) + for counts in routes { + let ids = counts.enumerated().flatMap { + Array(repeating: UInt32($0.offset), count: $0.element) + } + let indices = MLXArray(ids) + let x = MLXRandom.normal([ids.count, 1, 256], key: MLXRandom.key(102)).asType(dtype) + let plan = MiMoV26NAXGatherQMM.Plan( + rows: ids.count, experts: 8, input: 256, output: 128) + for bm in [64, 128] { + let joint = MiMoV26NAXGateUp.launch( + x: x, indices: indices, + gateWeight: gate.0, gateScales: gate.1, + upWeight: up.0, upScales: up.1, plan: plan, tileRows: bm) + exact(joint.gate, stock(x, indices, gate), "stock gate bm=\(bm)") + exact(joint.up, stock(x, indices, up), "stock up bm=\(bm)") + let separateGate = MiMoV26NAXGatherQMM.launch( + x: x, indices: indices, + weight: gate.0, scales: gate.1, plan: plan, tileRows: bm, + doubleBuffer: false) + let separateUp = MiMoV26NAXGatherQMM.launch( + x: x, indices: indices, + weight: up.0, scales: up.1, plan: plan, tileRows: bm, doubleBuffer: false) + exact(joint.gate, separateGate, "single NAX gate bm=\(bm)") + exact(joint.up, separateUp, "single NAX up bm=\(bm)") + } + } + } + } + + func testOversizedSortedRowsAgainstSafeStockSlices() throws { + try requireGPU() + let counts = Array(repeating: 2304, count: 15) + [4000] + let ids = counts.enumerated().flatMap { + Array(repeating: UInt32($0.offset), count: $0.element) + } + let indices = MLXArray(ids) + let x = MLXRandom.normal([ids.count, 1, 128], key: MLXRandom.key(103)).asType(.bfloat16) + let gate = weights(16, 64, 128, dtype: .bfloat16, seed: 104) + let up = weights(16, 64, 128, dtype: .bfloat16, seed: 105) + let half = ids.count / 2 + func reference(_ w: (MLXArray, MLXArray)) -> MLXArray { + concatenated([ + stock(x[..