From 38c922fc7590b4f8abc8316470a1deea071188f5 Mon Sep 17 00:00:00 2001 From: pHequals7 Date: Thu, 29 Oct 2026 12:04:11 +0530 Subject: [PATCH 1/7] Add LiquidAI LFM3 text model support --- Libraries/MLXLLM/LLMModelFactory.swift | 7 + Libraries/MLXLLM/Models/LFM3.swift | 465 ++++++++++++++++++ Tests/MLXLMTests/LFM3Tests.swift | 306 ++++++++++++ .../references/supported-models.md | 1 + 4 files changed, 779 insertions(+) create mode 100644 Libraries/MLXLLM/Models/LFM3.swift create mode 100644 Tests/MLXLMTests/LFM3Tests.swift diff --git a/Libraries/MLXLLM/LLMModelFactory.swift b/Libraries/MLXLLM/LLMModelFactory.swift index f33a8d9c87..3ee66f6145 100644 --- a/Libraries/MLXLLM/LLMModelFactory.swift +++ b/Libraries/MLXLLM/LLMModelFactory.swift @@ -97,6 +97,7 @@ public enum LLMTypeRegistry { "smollm3": create(SmolLM3Configuration.self, SmolLM3Model.init), "ernie4_5": create(Ernie45Configuration.self, Ernie45Model.init), "lfm2": create(LFM2Configuration.self, LFM2Model.init), + "lfm3": create(LFM3Configuration.self, LFM3Model.init), "baichuan_m1": create(BaichuanM1Configuration.self, BaichuanM1Model.init), "exaone4": create(Exaone4Configuration.self, Exaone4Model.init), "gpt_oss": create(GPTOSSConfiguration.self, GPTOSSModel.init), @@ -474,6 +475,11 @@ public class LLMRegistry: AbstractModelRegistry, @unchecked Sendable { toolCallFormat: .lfm2 ) + static public let lfm3_1_7b_4bit = ModelConfiguration( + id: "LiquidAI/LFM3-1.7B-MLX-4bit", + defaultPrompt: "Why is the sky blue?" + ) + static public let exaone_4_0_1_2b_4bit = ModelConfiguration( id: "mlx-community/exaone-4.0-1.2b-4bit", defaultPrompt: "Why is the sky blue?" @@ -591,6 +597,7 @@ public class LLMRegistry: AbstractModelRegistry, @unchecked Sendable { smollm3_3b_4bit, ernie_45_0_3BPT_bf16_ft, lfm2_1_2b_4bit, + lfm3_1_7b_4bit, baichuan_m1_14b_instruct_4bit, exaone_4_0_1_2b_4bit, lille_130m_bf16, diff --git a/Libraries/MLXLLM/Models/LFM3.swift b/Libraries/MLXLLM/Models/LFM3.swift new file mode 100644 index 0000000000..da1351b73b --- /dev/null +++ b/Libraries/MLXLLM/Models/LFM3.swift @@ -0,0 +1,465 @@ +// +// LFM3.swift +// mlx-swift-lm +// + +// Port of https://huggingface.co/LiquidAI/LFM3-1.7B/blob/main/modeling_lfm3.py +// +// LFM3 is LFM2 with sliding-window attention as a third layer type, a sigmoid +// gate per attention head, partial RoPE on full-attention layers, and an +// optional RMSNorm on each block output ("sandwich norm"). + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +public struct LFM3Configuration: Codable, Sendable { + public enum LayerType: String, Codable, Sendable { + case conv + case fullAttention = "full_attention" + case slidingAttention = "sliding_attention" + } + + public struct RopeParameters: Codable, Sendable { + let ropeType: String + let ropeTheta: Float + let partialRotaryFactor: Float + + enum CodingKeys: String, CodingKey { + case ropeType = "rope_type" + case ropeTheta = "rope_theta" + case partialRotaryFactor = "partial_rotary_factor" + } + + init(ropeTheta: Float, partialRotaryFactor: Float = 1.0) { + self.ropeType = "default" + self.ropeTheta = ropeTheta + self.partialRotaryFactor = partialRotaryFactor + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.ropeType = + try container.decodeIfPresent(String.self, forKey: .ropeType) ?? "default" + self.ropeTheta = try container.decode(Float.self, forKey: .ropeTheta) + self.partialRotaryFactor = + try container.decodeIfPresent(Float.self, forKey: .partialRotaryFactor) ?? 1.0 + } + } + + let modelType: String + let vocabularySize: Int + let hiddenSize: Int + let hiddenLayers: Int + let attentionHeads: Int + let kvHeads: Int + let headDim: Int + let intermediateSize: Int + let maxPositionEmbeddings: Int? + let normEps: Float + let convBias: Bool + let convLCache: Int + let layerTypes: [LayerType] + let slidingWindow: Int + let useSandwichNorm: Bool + let tieWordEmbeddings: Bool + let ropeParameters: [String: RopeParameters] + + enum CodingKeys: String, CodingKey { + case modelType = "model_type" + case vocabularySize = "vocab_size" + case hiddenSize = "hidden_size" + case hiddenLayers = "num_hidden_layers" + case attentionHeads = "num_attention_heads" + case kvHeads = "num_key_value_heads" + case headDim = "head_dim" + case intermediateSize = "intermediate_size" + case maxPositionEmbeddings = "max_position_embeddings" + case normEps = "norm_eps" + case convBias = "conv_bias" + case convLCache = "conv_L_cache" + case layerTypes = "layer_types" + case slidingWindow = "sliding_window" + case useSandwichNorm = "use_sandwich_norm" + case tieWordEmbeddings = "tie_word_embeddings" + case ropeParameters = "rope_parameters" + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.modelType = try container.decodeIfPresent(String.self, forKey: .modelType) ?? "lfm3" + self.vocabularySize = + try container.decodeIfPresent(Int.self, forKey: .vocabularySize) ?? 128_000 + self.hiddenSize = try container.decode(Int.self, forKey: .hiddenSize) + self.hiddenLayers = try container.decode(Int.self, forKey: .hiddenLayers) + self.attentionHeads = try container.decode(Int.self, forKey: .attentionHeads) + self.kvHeads = try container.decode(Int.self, forKey: .kvHeads) + self.headDim = + try container.decodeIfPresent(Int.self, forKey: .headDim) + ?? hiddenSize / attentionHeads + self.intermediateSize = try container.decode(Int.self, forKey: .intermediateSize) + self.maxPositionEmbeddings = try container.decodeIfPresent( + Int.self, forKey: .maxPositionEmbeddings) + self.normEps = try container.decodeIfPresent(Float.self, forKey: .normEps) ?? 1e-5 + self.convBias = try container.decodeIfPresent(Bool.self, forKey: .convBias) ?? false + self.convLCache = try container.decodeIfPresent(Int.self, forKey: .convLCache) ?? 7 + self.slidingWindow = + try container.decodeIfPresent(Int.self, forKey: .slidingWindow) ?? 256 + self.useSandwichNorm = + try container.decodeIfPresent(Bool.self, forKey: .useSandwichNorm) ?? true + self.tieWordEmbeddings = + try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true + + // Same default pattern as the reference: full attention every fourth layer from + // the third, sliding attention in between, short convolutions elsewhere. + let hiddenLayers = self.hiddenLayers + self.layerTypes = + try container.decodeIfPresent([LayerType].self, forKey: .layerTypes) + ?? (0 ..< hiddenLayers).map { i in + i % 4 == 2 ? .fullAttention : (i % 4 == 0 && i > 0 ? .slidingAttention : .conv) + } + guard layerTypes.count == hiddenLayers else { + throw DecodingError.dataCorruptedError( + forKey: .layerTypes, in: container, + debugDescription: + "layer_types has \(layerTypes.count) entries but num_hidden_layers is \(hiddenLayers)" + ) + } + + self.ropeParameters = + try container.decodeIfPresent([String: RopeParameters].self, forKey: .ropeParameters) + ?? [ + LayerType.fullAttention.rawValue: .init( + ropeTheta: 1_000_000, partialRotaryFactor: 0.5), + LayerType.slidingAttention.rawValue: .init(ropeTheta: 10_000), + ] + for layerType in Set(layerTypes) where layerType != .conv { + guard let rope = ropeParameters[layerType.rawValue] else { + throw DecodingError.dataCorruptedError( + forKey: .ropeParameters, in: container, + debugDescription: "rope_parameters has no entry for \(layerType.rawValue)") + } + // Scaled RoPE types are not ported; running them as default would be wrong. + guard rope.ropeType == "default" else { + throw DecodingError.dataCorruptedError( + forKey: .ropeParameters, in: container, + debugDescription: "Unsupported LFM3 rope_type '\(rope.ropeType)'") + } + } + } +} + +class LFM3Attention: Module { + let attentionHeads: Int + let kvHeads: Int + let headDim: Int + let scale: Float + + @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 + @ModuleInfo(key: "gate_proj") var gateProj: Linear + + @ModuleInfo(key: "q_norm") var qNorm: RMSNorm + @ModuleInfo(key: "k_norm") var kNorm: RMSNorm + + let rope: RoPELayer + + init(_ args: LFM3Configuration, layerType: LFM3Configuration.LayerType) { + self.attentionHeads = args.attentionHeads + self.kvHeads = args.kvHeads + self.headDim = args.headDim + self.scale = pow(Float(headDim), -0.5) + + let dim = args.hiddenSize + _qProj.wrappedValue = Linear(dim, attentionHeads * headDim, bias: false) + _kProj.wrappedValue = Linear(dim, kvHeads * headDim, bias: false) + _vProj.wrappedValue = Linear(dim, kvHeads * headDim, bias: false) + _oProj.wrappedValue = Linear(attentionHeads * headDim, dim, bias: false) + _gateProj.wrappedValue = Linear(dim, attentionHeads, bias: false) + + _qNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: args.normEps) + _kNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: args.normEps) + + // Partial RoPE rotates the first dimensions of each half of the head with the + // full-head frequencies, which is what ProportionalRoPE does. RoPE(dimensions:) + // would rotate a contiguous prefix with different frequencies instead. + let rope = args.ropeParameters[layerType.rawValue]! + if rope.partialRotaryFactor < 1 { + self.rope = initializeRope( + dims: headDim, base: rope.ropeTheta, traditional: false, + scalingConfig: [ + "type": .string("proportional"), + "partial_rotary_factor": .float(rope.partialRotaryFactor), + ], + maxPositionEmbeddings: nil) + } else { + self.rope = RoPE(dimensions: headDim, traditional: false, base: rope.ropeTheta) + } + } + + func callAsFunction( + _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache? + ) -> MLXArray { + let (B, L) = (x.dim(0), x.dim(1)) + + var queries = qNorm(qProj(x).reshaped(B, L, attentionHeads, -1)).transposed(0, 2, 1, 3) + var keys = kNorm(kProj(x).reshaped(B, L, kvHeads, -1)).transposed(0, 2, 1, 3) + let values = vProj(x).reshaped(B, L, kvHeads, -1).transposed(0, 2, 1, 3) + + let offset = cache?.ropeOffset + queries = applyRotaryPosition(rope, to: queries, offset: offset) + keys = applyRotaryPosition(rope, to: keys, offset: offset) + + let output = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: cache, + scale: scale, + mask: mask + ) + .transposed(0, 2, 1, 3) + + // One sigmoid gate per head, computed from the block input. + let gate = sigmoid(gateProj(x)).expandedDimensions(axis: -1) + return oProj((output * gate).reshaped(B, L, -1)) + } +} + +class LFM3ShortConv: Module { + let hiddenSize: Int + let lCache: Int + + @ModuleInfo(key: "conv") var conv: Conv1d + @ModuleInfo(key: "in_proj") var inProj: Linear + @ModuleInfo(key: "out_proj") var outProj: Linear + + init(_ args: LFM3Configuration) { + self.hiddenSize = args.hiddenSize + self.lCache = args.convLCache + + _conv.wrappedValue = Conv1d( + inputChannels: hiddenSize, + outputChannels: hiddenSize, + kernelSize: lCache, + groups: hiddenSize, + bias: args.convBias + ) + _inProj.wrappedValue = Linear(hiddenSize, 3 * hiddenSize, bias: args.convBias) + _outProj.wrappedValue = Linear(hiddenSize, hiddenSize, bias: args.convBias) + } + + func callAsFunction(_ x: MLXArray, cache: MambaCache?) -> MLXArray { + let BCx = inProj(x).split(parts: 3, axis: -1) + let (B, C) = (BCx[0], BCx[1]) + var Bx = B * BCx[2] + + // The cache holds the last `lCache - 1` inputs, so the conv needs no padding. + let state = + cache?[0] ?? MLXArray.zeros([Bx.dim(0), lCache - 1, hiddenSize], dtype: Bx.dtype) + Bx = concatenated([state, Bx], axis: -2) + if let cache { + cache[0] = contiguous(Bx[0..., (Bx.dim(1) - (lCache - 1))..., 0...]) + cache.advance(x.dim(1)) + } + + return outProj(C * conv(Bx)) + } +} + +class LFM3MLP: Module, UnaryLayer { + @ModuleInfo(key: "w1") var w1: Linear + @ModuleInfo(key: "w2") var w2: Linear + @ModuleInfo(key: "w3") var w3: Linear + + init(dim: Int, hiddenDim: Int) { + _w1.wrappedValue = Linear(dim, hiddenDim, bias: false) + _w2.wrappedValue = Linear(hiddenDim, dim, bias: false) + _w3.wrappedValue = Linear(dim, hiddenDim, bias: false) + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + w2(silu(w1(x)) * w3(x)) + } +} + +class LFM3DecoderLayer: Module { + let layerType: LFM3Configuration.LayerType + + @ModuleInfo(key: "self_attn") var attention: LFM3Attention? + @ModuleInfo(key: "conv") var conv: LFM3ShortConv? + @ModuleInfo(key: "feed_forward") var feedForward: LFM3MLP + @ModuleInfo(key: "operator_norm") var operatorNorm: RMSNorm + @ModuleInfo(key: "ffn_norm") var ffnNorm: RMSNorm + @ModuleInfo(key: "post_operator_norm") var postOperatorNorm: RMSNorm? + @ModuleInfo(key: "post_ffn_norm") var postFFNNorm: RMSNorm? + + init(_ args: LFM3Configuration, layerIdx: Int) { + self.layerType = args.layerTypes[layerIdx] + + if layerType == .conv { + _conv.wrappedValue = LFM3ShortConv(args) + } else { + _attention.wrappedValue = LFM3Attention(args, layerType: layerType) + } + + _feedForward.wrappedValue = LFM3MLP(dim: args.hiddenSize, hiddenDim: args.intermediateSize) + _operatorNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) + _ffnNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) + if args.useSandwichNorm { + _postOperatorNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) + _postFFNNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) + } + } + + func callAsFunction( + _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache? + ) -> MLXArray { + var r: MLXArray + if let attention { + r = attention(operatorNorm(x), mask: mask, cache: cache) + } else { + r = conv!(operatorNorm(x), cache: cache as? MambaCache) + } + if let postOperatorNorm { + r = postOperatorNorm(r) + } + let h = x + r + + var f = feedForward(ffnNorm(h)) + if let postFFNNorm { + f = postFFNNorm(f) + } + return h + f + } +} + +public class LFM3ModelInner: Module { + let args: LFM3Configuration + let firstFullAttentionIdx: Int? + let firstSlidingAttentionIdx: Int? + + let layers: [LFM3DecoderLayer] + + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + @ModuleInfo(key: "embedding_norm") var embeddingNorm: RMSNorm + + public init(_ args: LFM3Configuration) { + self.args = args + self.firstFullAttentionIdx = args.layerTypes.firstIndex(of: .fullAttention) + self.firstSlidingAttentionIdx = args.layerTypes.firstIndex(of: .slidingAttention) + + _embedTokens.wrappedValue = Embedding( + embeddingCount: args.vocabularySize, dimensions: args.hiddenSize) + + self.layers = (0 ..< args.hiddenLayers).map { i in + LFM3DecoderLayer(args, layerIdx: i) + } + + _embeddingNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) + } + + public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]? = nil) -> MLXArray { + var h = embedTokens(inputs) + let n = h.dim(1) + + // One mask per attention type, sized by the first cache of that type. + let fullMask = firstFullAttentionIdx.map { + makeAttentionMask(n: n, cache: cache?[$0]) + } + let slidingMask = firstSlidingAttentionIdx.map { + makeAttentionMask(n: n, cache: cache?[$0], windowSize: args.slidingWindow) + } + + for (i, layer) in layers.enumerated() { + let mask: MLXFast.ScaledDotProductAttentionMaskMode = + switch layer.layerType { + case .fullAttention: fullMask! + case .slidingAttention: slidingMask! + case .conv: .none + } + h = layer(h, mask: mask, cache: cache?[i]) + } + + return embeddingNorm(h) + } +} + +public class LFM3Model: Module, LLMModel, KVCacheDimensionProvider { + public let vocabularySize: Int + public let kvHeads: [Int] + + public let model: LFM3ModelInner + let configuration: LFM3Configuration + + @ModuleInfo(key: "lm_head") var lmHead: Linear? + + public init(_ args: LFM3Configuration) { + self.configuration = args + self.vocabularySize = args.vocabularySize + self.kvHeads = args.layerTypes.map { $0 == .conv ? 0 : args.kvHeads } + self.model = LFM3ModelInner(args) + if !args.tieWordEmbeddings { + _lmHead.wrappedValue = Linear(args.hiddenSize, args.vocabularySize, bias: false) + } + } + + public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + let out = model(inputs, cache: cache) + if let lmHead { + return lmHead(out) + } + return model.embedTokens.asLinear(out) + } + + public func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint { + // MLX conversions nest the text model under `language_model`. Keep only the text + // model, which drops any vision or audio tensors. + var checkpoint = try checkpoint.mapNames { name in + var name = name + if name.hasPrefix("language_model.") { + name.removeFirst("language_model.".count) + } + return name.hasPrefix("model.") || name.hasPrefix("lm_head.") ? name : nil + } + var weights = filterLMHeadWeights( + from: checkpoint.weights, tiedWordEmbeddings: configuration.tieWordEmbeddings) + + // PyTorch stores the depthwise conv as [C, 1, K]; MLX expects [C, K, 1]. + for (name, value) in weights where name.hasSuffix("conv.conv.weight") { + if value.dim(-1) > value.dim(1) { + weights[name] = value.transposed(0, 2, 1) + } + } + checkpoint.weights = weights + return checkpoint + } + + public func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] { + try prepareCheckpoint(.init(weights: weights)).weights + } + + public func newCache(parameters: GenerateParameters?) throws -> [KVCache] { + try configuration.layerTypes.map { layerType in + switch layerType { + case .conv: + MambaCache() + case .fullAttention, .slidingAttention: + try makeHybridAttentionKVCache( + parameters: parameters, + slidingWindow: configuration.slidingWindow, + usesSlidingWindow: layerType == .slidingAttention) + } + } + } +} + +extension LFM3Model: LoRAModel { + public var loraLayers: [Module] { + model.layers + } +} diff --git a/Tests/MLXLMTests/LFM3Tests.swift b/Tests/MLXLMTests/LFM3Tests.swift new file mode 100644 index 0000000000..cca086b3a9 --- /dev/null +++ b/Tests/MLXLMTests/LFM3Tests.swift @@ -0,0 +1,306 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN +import XCTest + +@testable import MLXLLM + +final class LFM3Tests: XCTestCase { + + /// `config.json` of LiquidAI/LFM3-1.7B. + private let realConfigJSON = """ + { + "architectures": ["Lfm3ForCausalLM"], + "bos_token_id": 124894, + "conv_L_cache": 7, + "conv_bias": false, + "dtype": "bfloat16", + "eos_token_id": 124900, + "head_dim": 128, + "hidden_size": 2048, + "intermediate_size": 7680, + "layer_types": [ + "conv", "conv", "full_attention", "conv", "sliding_attention", "conv", + "full_attention", "conv", "sliding_attention", "conv", "full_attention", "conv", + "sliding_attention", "conv", "full_attention", "conv", "sliding_attention", "conv", + "full_attention", "conv", "sliding_attention", "conv", "full_attention", "conv" + ], + "max_position_embeddings": 262144, + "model_type": "lfm3", + "norm_eps": 1e-05, + "num_attention_heads": 16, + "num_hidden_layers": 24, + "num_key_value_heads": 4, + "pad_token_id": 124893, + "rope_parameters": { + "full_attention": { + "partial_rotary_factor": 0.5, "rope_theta": 1000000.0, "rope_type": "default" + }, + "sliding_attention": {"rope_theta": 10000, "rope_type": "default"} + }, + "sliding_window": 256, + "tie_word_embeddings": true, + "transformers_version": "5.12.1", + "use_cache": true, + "use_sandwich_norm": true, + "vocab_size": 128000 + } + """ + + private static let tinyLayerTypes = [ + "conv", "sliding_attention", "full_attention", "conv", "sliding_attention", + "full_attention", + ] + + private func decode(_ json: String) throws -> LFM3Configuration { + try JSONDecoder().decode(LFM3Configuration.self, from: Data(json.utf8)) + } + + /// A tiny config with the real layer kinds and a sliding window shorter than the + /// test prompts. + private func tinyConfiguration( + layerTypes: [String] = tinyLayerTypes, tieWordEmbeddings: Bool = true, + fullRope: String = + #"{"rope_type": "default", "rope_theta": 1000000.0, "partial_rotary_factor": 0.5}"# + ) throws -> LFM3Configuration { + let layerTypesJSON = layerTypes.map { "\"\($0)\"" }.joined(separator: ", ") + return try decode( + """ + { + "model_type": "lfm3", "vocab_size": 64, "hidden_size": 32, + "intermediate_size": 48, "num_hidden_layers": \(layerTypes.count), + "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 16, + "norm_eps": 1e-5, "conv_L_cache": 3, "conv_bias": false, + "sliding_window": 4, "use_sandwich_norm": true, + "tie_word_embeddings": \(tieWordEmbeddings), + "layer_types": [\(layerTypesJSON)], + "rope_parameters": { + "full_attention": \(fullRope), + "sliding_attention": {"rope_type": "default", "rope_theta": 10000.0} + } + } + """) + } + + private func tinyModel(_ configuration: LFM3Configuration? = nil) throws -> LFM3Model { + let configuration = try configuration ?? tinyConfiguration() + return withRandomState(MLXRandom.RandomState(seed: 7)) { + let model = LFM3Model(configuration) + eval(model) + return model + } + } + + // MARK: - Configuration + + func testRealConfigDecodes() throws { + let c = try decode(realConfigJSON) + + XCTAssertEqual(c.hiddenLayers, 24) + XCTAssertEqual(c.headDim, 128) + XCTAssertEqual(c.kvHeads, 4) + XCTAssertEqual(c.intermediateSize, 7680) + XCTAssertEqual(c.convLCache, 7) + XCTAssertFalse(c.convBias) + XCTAssertEqual(c.slidingWindow, 256) + XCTAssertTrue(c.useSandwichNorm) + XCTAssertTrue(c.tieWordEmbeddings) + + let indices = { (type: LFM3Configuration.LayerType) in + c.layerTypes.indices.filter { c.layerTypes[$0] == type } + } + XCTAssertEqual(indices(.fullAttention), [2, 6, 10, 14, 18, 22]) + XCTAssertEqual(indices(.slidingAttention), [4, 8, 12, 16, 20]) + XCTAssertEqual(indices(.conv).count, 13) + + let full = try XCTUnwrap(c.ropeParameters["full_attention"]) + XCTAssertEqual(full.ropeTheta, 1_000_000) + XCTAssertEqual(full.partialRotaryFactor, 0.5) + let sliding = try XCTUnwrap(c.ropeParameters["sliding_attention"]) + XCTAssertEqual(sliding.ropeTheta, 10_000) + XCTAssertEqual(sliding.partialRotaryFactor, 1.0) + } + + func testMissingFieldsTakeReferenceDefaults() throws { + let c = try decode( + """ + { + "hidden_size": 32, "intermediate_size": 48, "num_hidden_layers": 9, + "num_attention_heads": 4, "num_key_value_heads": 2 + } + """) + + XCTAssertEqual(c.headDim, 8) + XCTAssertEqual(c.slidingWindow, 256) + XCTAssertEqual(c.convLCache, 7) + XCTAssertEqual( + c.layerTypes, + [ + .conv, .conv, .fullAttention, .conv, .slidingAttention, .conv, .fullAttention, + .conv, .slidingAttention, + ]) + XCTAssertEqual(c.ropeParameters["full_attention"]?.partialRotaryFactor, 0.5) + XCTAssertEqual(c.ropeParameters["sliding_attention"]?.ropeTheta, 10_000) + } + + func testInvalidConfigsThrow() throws { + XCTAssertThrowsError( + try tinyConfiguration(layerTypes: ["conv", "linear_attention"])) + XCTAssertThrowsError( + try tinyConfiguration( + fullRope: #"{"rope_type": "yarn", "rope_theta": 1000000.0, "factor": 4.0}"#)) + // layer_types must cover every layer. + let json = realConfigJSON.replacingOccurrences( + of: "\"num_hidden_layers\": 24", with: "\"num_hidden_layers\": 23") + XCTAssertThrowsError(try decode(json)) + } + + func testRegisteredModelType() async throws { + XCTAssertTrue(LLMRegistry.shared.contains(id: "LiquidAI/LFM3-1.7B-MLX-4bit")) + let model = try await LLMTypeRegistry.shared.createModel( + configuration: Data(realConfigJSON.utf8), modelType: "lfm3") + XCTAssertTrue(model is LFM3Model) + } + + // MARK: - Model + + func testForwardShape() throws { + let model = try tinyModel() + let inputs = MLXArray((0 ..< 14).map { Int32($0 * 5 % 64) }).reshaped(2, 7) + + let logits = model(inputs, cache: nil) + + XCTAssertEqual(logits.shape, [2, 7, 64]) + XCTAssertNil(model.lmHead) + } + + func testUntiedEmbeddingsUseLMHead() throws { + let model = try tinyModel(tinyConfiguration(tieWordEmbeddings: false)) + XCTAssertNotNil(model.lmHead) + XCTAssertEqual( + model(MLXArray([Int32(1), 2, 3]).reshaped(1, 3), cache: nil).shape, [1, 3, 64]) + } + + func testCacheTypesPerLayer() throws { + let model = try tinyModel() + + let cache = try model.newCache(parameters: nil) + XCTAssertEqual(cache.count, 6) + for (i, layerType) in model.configuration.layerTypes.enumerated() { + switch layerType { + case .conv: + XCTAssertTrue(cache[i] is MambaCache, "layer \(i)") + case .slidingAttention: + let rotating = try XCTUnwrap(cache[i] as? RotatingKVCache, "layer \(i)") + XCTAssertEqual(rotating.maxSize, 4) + case .fullAttention: + XCTAssertTrue(cache[i] is KVCacheSimple, "layer \(i)") + } + } + + // maxKVSize bounds full attention and never widens the sliding window. + let bounded = try model.newCache(parameters: GenerateParameters(maxKVSize: 16)) + XCTAssertEqual((bounded[1] as? RotatingKVCache)?.maxSize, 4) + XCTAssertEqual((bounded[2] as? RotatingKVCache)?.maxSize, 16) + XCTAssertTrue(bounded[0] is MambaCache) + } + + func testPartialRoPEMatchesReference() throws { + let attention = try XCTUnwrap(try tinyModel().model.layers[2].attention) + let (headDim, base, offset) = (16, Float(1_000_000), 3) + let x = withRandomState(MLXRandom.RandomState(seed: 1)) { + MLXRandom.normal([1, 2, 5, headDim]) + } + + // The reference keeps the full-head frequencies for the first + // `partial_rotary_factor * headDim / 2` angles and zeroes the rest. + let angles = 4 + let invFreq = MLXArray( + (0 ..< headDim / 2).map { j in + j < angles ? pow(base, -Float(2 * j) / Float(headDim)) : 0 + }) + let positions = MLXArray((offset ..< offset + 5).map(Float.init)) + let freqs = positions.expandedDimensions(axis: -1) * invFreq + let emb = concatenated([freqs, freqs], axis: -1) + let halves = split(x, parts: 2, axis: -1) + let rotated = concatenated([-halves[1], halves[0]], axis: -1) + let expected = x * cos(emb) + rotated * sin(emb) + + let actual = applyRotaryPosition(attention.rope, to: x, offset: .scalar(offset)) + + XCTAssertLessThan(abs(actual - expected).max().item(Float.self), 1e-4) + } + + func testSanitizeLoadsMLXAndTransformersLayouts() throws { + let model = try tinyModel() + let parameters = Dictionary(uniqueKeysWithValues: model.parameters().flattened()) + let convKeys = parameters.keys.filter { $0.hasSuffix("conv.conv.weight") } + XCTAssertEqual(convKeys.count, 2) + + // MLX bundles: wrapped under `language_model`, plus tensors the text model drops. + var mlx = Dictionary( + uniqueKeysWithValues: parameters.map { ("language_model." + $0.key, $0.value) }) + mlx["language_model.lm_head.weight"] = MLXArray.zeros([64, 32]) + mlx["vision_tower.encoder.weight"] = MLXArray.zeros([4]) + + // Transformers checkpoints store the depthwise conv as [C, 1, K]. + var transformers = parameters + for key in convKeys { + transformers[key] = parameters[key]!.transposed(0, 2, 1) + } + + for weights in [mlx, transformers] { + let sanitized = try model.sanitize(weights: weights) + XCTAssertEqual(Set(sanitized.keys), Set(parameters.keys)) + for (key, value) in sanitized { + XCTAssertEqual(value.shape, parameters[key]!.shape, key) + } + try model.update(parameters: ModuleParameters.unflattened(sanitized), verify: [.all]) + } + } + + /// Prefill in one call, in chunks, and one token at a time must give the same logits, + /// including past the sliding window where the rotating caches wrap. + func testChunkedPrefillAndDecodeMatchOneShot() throws { + let model = try tinyModel() + let tokenCount = 19 + let tokens = MLXArray((0 ..< tokenCount).map { Int32(($0 * 7 + 3) % 64) }) + .reshaped(1, tokenCount) + + let cacheless = model(tokens, cache: nil) + let oneShotCache = try model.newCache(parameters: nil) + let oneShot = model(tokens, cache: oneShotCache) + eval(cacheless, oneShot) + XCTAssertLessThan( + abs(oneShot - cacheless).max().item(Float.self), MatmulPrecision.splitTolerance) + + let decodeCount = 6 + for chunkSize in [1, 3, 4, 5, 13] { + let cache = try model.newCache(parameters: nil) + var logits = [MLXArray]() + var start = 0 + while start < tokenCount { + let prefillEnd = tokenCount - decodeCount + let end = start < prefillEnd ? min(start + chunkSize, prefillEnd) : start + 1 + logits.append(model(tokens[0..., start ..< end], cache: cache)) + eval(logits.last!) + start = end + } + + let drift = abs(concatenated(logits, axis: 1) - oneShot).max().item(Float.self) + XCTAssertLessThan(drift, MatmulPrecision.splitTolerance, "chunk size \(chunkSize)") + XCTAssertEqual(cache.map(\.offset), oneShotCache.map(\.offset)) + // Like LFM2, conv caches hold a state window and do not track an offset. + for layerCache in cache { + if layerCache is MambaCache { + XCTAssertFalse(layerCache.innerState().isEmpty) + } else { + XCTAssertEqual(layerCache.offset, tokenCount) + } + } + } + } +} diff --git a/skills/mlx-swift-lm/references/supported-models.md b/skills/mlx-swift-lm/references/supported-models.md index d061cd4c93..1665a3cc68 100644 --- a/skills/mlx-swift-lm/references/supported-models.md +++ b/skills/mlx-swift-lm/references/supported-models.md @@ -100,6 +100,7 @@ LLMRegistry.mellum2_1_12b_a2_5b_thinking_6bit // mlx-community/Mellum2.1-12B-A2 | `smollm3` | SmolLM 3 | | `ernie4_5` | ERNIE 4.5 | | `lfm2`, `lfm2_moe` | LFM 2 | +| `lfm3` | LFM 3 | | `exaone4` | EXAONE 4 | | `olmo2`, `olmo3`, `olmoe` | OLMo | | `falcon_h1` | Falcon H1 | From 499c2e57aa35eb0147c6460624149a3b8eb3e91a Mon Sep 17 00:00:00 2001 From: pHequals7 Date: Sun, 1 Nov 2026 14:03:20 +0530 Subject: [PATCH 2/7] Share the LFM3 text backbone for multimodal wrappers Move the LFM3 configuration, decoder blocks, and backbone to MLXLMCommon so an MLXVLM wrapper can reuse them; LFM3Model, its registry entry, and LoRA stay in MLXLLM. The backbone takes token ids or embeddings through the same code path, uses caller-owned caches for positions, and accepts an optional mask per attention type. It exposes embed(_:), projectLogits(_:lmHead:) for tied and untied heads, and newCache(parameters:). LFM3Model conforms to HiddenStateLanguageModel. Keep the bare lm_head module path when stripping the language_model prefix, so an untied lm_head keeps its per-layer quantization. Co-Authored-By: Claude Opus 5.5 --- Libraries/MLXLLM/Models/LFM3.swift | 415 +--------------------- Libraries/MLXLMCommon/Models/LFM3.swift | 453 ++++++++++++++++++++++++ Tests/MLXLMTests/LFM3Tests.swift | 158 ++++++++- 3 files changed, 628 insertions(+), 398 deletions(-) create mode 100644 Libraries/MLXLMCommon/Models/LFM3.swift diff --git a/Libraries/MLXLLM/Models/LFM3.swift b/Libraries/MLXLLM/Models/LFM3.swift index da1351b73b..4e05a3a865 100644 --- a/Libraries/MLXLLM/Models/LFM3.swift +++ b/Libraries/MLXLLM/Models/LFM3.swift @@ -5,390 +5,13 @@ // Port of https://huggingface.co/LiquidAI/LFM3-1.7B/blob/main/modeling_lfm3.py // -// LFM3 is LFM2 with sliding-window attention as a third layer type, a sigmoid -// gate per attention head, partial RoPE on full-attention layers, and an -// optional RMSNorm on each block output ("sandwich norm"). +// The configuration and backbone are in MLXLMCommon (`Models/LFM3.swift`). import Foundation import MLX import MLXLMCommon import MLXNN -public struct LFM3Configuration: Codable, Sendable { - public enum LayerType: String, Codable, Sendable { - case conv - case fullAttention = "full_attention" - case slidingAttention = "sliding_attention" - } - - public struct RopeParameters: Codable, Sendable { - let ropeType: String - let ropeTheta: Float - let partialRotaryFactor: Float - - enum CodingKeys: String, CodingKey { - case ropeType = "rope_type" - case ropeTheta = "rope_theta" - case partialRotaryFactor = "partial_rotary_factor" - } - - init(ropeTheta: Float, partialRotaryFactor: Float = 1.0) { - self.ropeType = "default" - self.ropeTheta = ropeTheta - self.partialRotaryFactor = partialRotaryFactor - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.ropeType = - try container.decodeIfPresent(String.self, forKey: .ropeType) ?? "default" - self.ropeTheta = try container.decode(Float.self, forKey: .ropeTheta) - self.partialRotaryFactor = - try container.decodeIfPresent(Float.self, forKey: .partialRotaryFactor) ?? 1.0 - } - } - - let modelType: String - let vocabularySize: Int - let hiddenSize: Int - let hiddenLayers: Int - let attentionHeads: Int - let kvHeads: Int - let headDim: Int - let intermediateSize: Int - let maxPositionEmbeddings: Int? - let normEps: Float - let convBias: Bool - let convLCache: Int - let layerTypes: [LayerType] - let slidingWindow: Int - let useSandwichNorm: Bool - let tieWordEmbeddings: Bool - let ropeParameters: [String: RopeParameters] - - enum CodingKeys: String, CodingKey { - case modelType = "model_type" - case vocabularySize = "vocab_size" - case hiddenSize = "hidden_size" - case hiddenLayers = "num_hidden_layers" - case attentionHeads = "num_attention_heads" - case kvHeads = "num_key_value_heads" - case headDim = "head_dim" - case intermediateSize = "intermediate_size" - case maxPositionEmbeddings = "max_position_embeddings" - case normEps = "norm_eps" - case convBias = "conv_bias" - case convLCache = "conv_L_cache" - case layerTypes = "layer_types" - case slidingWindow = "sliding_window" - case useSandwichNorm = "use_sandwich_norm" - case tieWordEmbeddings = "tie_word_embeddings" - case ropeParameters = "rope_parameters" - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - self.modelType = try container.decodeIfPresent(String.self, forKey: .modelType) ?? "lfm3" - self.vocabularySize = - try container.decodeIfPresent(Int.self, forKey: .vocabularySize) ?? 128_000 - self.hiddenSize = try container.decode(Int.self, forKey: .hiddenSize) - self.hiddenLayers = try container.decode(Int.self, forKey: .hiddenLayers) - self.attentionHeads = try container.decode(Int.self, forKey: .attentionHeads) - self.kvHeads = try container.decode(Int.self, forKey: .kvHeads) - self.headDim = - try container.decodeIfPresent(Int.self, forKey: .headDim) - ?? hiddenSize / attentionHeads - self.intermediateSize = try container.decode(Int.self, forKey: .intermediateSize) - self.maxPositionEmbeddings = try container.decodeIfPresent( - Int.self, forKey: .maxPositionEmbeddings) - self.normEps = try container.decodeIfPresent(Float.self, forKey: .normEps) ?? 1e-5 - self.convBias = try container.decodeIfPresent(Bool.self, forKey: .convBias) ?? false - self.convLCache = try container.decodeIfPresent(Int.self, forKey: .convLCache) ?? 7 - self.slidingWindow = - try container.decodeIfPresent(Int.self, forKey: .slidingWindow) ?? 256 - self.useSandwichNorm = - try container.decodeIfPresent(Bool.self, forKey: .useSandwichNorm) ?? true - self.tieWordEmbeddings = - try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true - - // Same default pattern as the reference: full attention every fourth layer from - // the third, sliding attention in between, short convolutions elsewhere. - let hiddenLayers = self.hiddenLayers - self.layerTypes = - try container.decodeIfPresent([LayerType].self, forKey: .layerTypes) - ?? (0 ..< hiddenLayers).map { i in - i % 4 == 2 ? .fullAttention : (i % 4 == 0 && i > 0 ? .slidingAttention : .conv) - } - guard layerTypes.count == hiddenLayers else { - throw DecodingError.dataCorruptedError( - forKey: .layerTypes, in: container, - debugDescription: - "layer_types has \(layerTypes.count) entries but num_hidden_layers is \(hiddenLayers)" - ) - } - - self.ropeParameters = - try container.decodeIfPresent([String: RopeParameters].self, forKey: .ropeParameters) - ?? [ - LayerType.fullAttention.rawValue: .init( - ropeTheta: 1_000_000, partialRotaryFactor: 0.5), - LayerType.slidingAttention.rawValue: .init(ropeTheta: 10_000), - ] - for layerType in Set(layerTypes) where layerType != .conv { - guard let rope = ropeParameters[layerType.rawValue] else { - throw DecodingError.dataCorruptedError( - forKey: .ropeParameters, in: container, - debugDescription: "rope_parameters has no entry for \(layerType.rawValue)") - } - // Scaled RoPE types are not ported; running them as default would be wrong. - guard rope.ropeType == "default" else { - throw DecodingError.dataCorruptedError( - forKey: .ropeParameters, in: container, - debugDescription: "Unsupported LFM3 rope_type '\(rope.ropeType)'") - } - } - } -} - -class LFM3Attention: Module { - let attentionHeads: Int - let kvHeads: Int - let headDim: Int - let scale: Float - - @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 - @ModuleInfo(key: "gate_proj") var gateProj: Linear - - @ModuleInfo(key: "q_norm") var qNorm: RMSNorm - @ModuleInfo(key: "k_norm") var kNorm: RMSNorm - - let rope: RoPELayer - - init(_ args: LFM3Configuration, layerType: LFM3Configuration.LayerType) { - self.attentionHeads = args.attentionHeads - self.kvHeads = args.kvHeads - self.headDim = args.headDim - self.scale = pow(Float(headDim), -0.5) - - let dim = args.hiddenSize - _qProj.wrappedValue = Linear(dim, attentionHeads * headDim, bias: false) - _kProj.wrappedValue = Linear(dim, kvHeads * headDim, bias: false) - _vProj.wrappedValue = Linear(dim, kvHeads * headDim, bias: false) - _oProj.wrappedValue = Linear(attentionHeads * headDim, dim, bias: false) - _gateProj.wrappedValue = Linear(dim, attentionHeads, bias: false) - - _qNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: args.normEps) - _kNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: args.normEps) - - // Partial RoPE rotates the first dimensions of each half of the head with the - // full-head frequencies, which is what ProportionalRoPE does. RoPE(dimensions:) - // would rotate a contiguous prefix with different frequencies instead. - let rope = args.ropeParameters[layerType.rawValue]! - if rope.partialRotaryFactor < 1 { - self.rope = initializeRope( - dims: headDim, base: rope.ropeTheta, traditional: false, - scalingConfig: [ - "type": .string("proportional"), - "partial_rotary_factor": .float(rope.partialRotaryFactor), - ], - maxPositionEmbeddings: nil) - } else { - self.rope = RoPE(dimensions: headDim, traditional: false, base: rope.ropeTheta) - } - } - - func callAsFunction( - _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache? - ) -> MLXArray { - let (B, L) = (x.dim(0), x.dim(1)) - - var queries = qNorm(qProj(x).reshaped(B, L, attentionHeads, -1)).transposed(0, 2, 1, 3) - var keys = kNorm(kProj(x).reshaped(B, L, kvHeads, -1)).transposed(0, 2, 1, 3) - let values = vProj(x).reshaped(B, L, kvHeads, -1).transposed(0, 2, 1, 3) - - let offset = cache?.ropeOffset - queries = applyRotaryPosition(rope, to: queries, offset: offset) - keys = applyRotaryPosition(rope, to: keys, offset: offset) - - let output = attentionWithCacheUpdate( - queries: queries, - keys: keys, - values: values, - cache: cache, - scale: scale, - mask: mask - ) - .transposed(0, 2, 1, 3) - - // One sigmoid gate per head, computed from the block input. - let gate = sigmoid(gateProj(x)).expandedDimensions(axis: -1) - return oProj((output * gate).reshaped(B, L, -1)) - } -} - -class LFM3ShortConv: Module { - let hiddenSize: Int - let lCache: Int - - @ModuleInfo(key: "conv") var conv: Conv1d - @ModuleInfo(key: "in_proj") var inProj: Linear - @ModuleInfo(key: "out_proj") var outProj: Linear - - init(_ args: LFM3Configuration) { - self.hiddenSize = args.hiddenSize - self.lCache = args.convLCache - - _conv.wrappedValue = Conv1d( - inputChannels: hiddenSize, - outputChannels: hiddenSize, - kernelSize: lCache, - groups: hiddenSize, - bias: args.convBias - ) - _inProj.wrappedValue = Linear(hiddenSize, 3 * hiddenSize, bias: args.convBias) - _outProj.wrappedValue = Linear(hiddenSize, hiddenSize, bias: args.convBias) - } - - func callAsFunction(_ x: MLXArray, cache: MambaCache?) -> MLXArray { - let BCx = inProj(x).split(parts: 3, axis: -1) - let (B, C) = (BCx[0], BCx[1]) - var Bx = B * BCx[2] - - // The cache holds the last `lCache - 1` inputs, so the conv needs no padding. - let state = - cache?[0] ?? MLXArray.zeros([Bx.dim(0), lCache - 1, hiddenSize], dtype: Bx.dtype) - Bx = concatenated([state, Bx], axis: -2) - if let cache { - cache[0] = contiguous(Bx[0..., (Bx.dim(1) - (lCache - 1))..., 0...]) - cache.advance(x.dim(1)) - } - - return outProj(C * conv(Bx)) - } -} - -class LFM3MLP: Module, UnaryLayer { - @ModuleInfo(key: "w1") var w1: Linear - @ModuleInfo(key: "w2") var w2: Linear - @ModuleInfo(key: "w3") var w3: Linear - - init(dim: Int, hiddenDim: Int) { - _w1.wrappedValue = Linear(dim, hiddenDim, bias: false) - _w2.wrappedValue = Linear(hiddenDim, dim, bias: false) - _w3.wrappedValue = Linear(dim, hiddenDim, bias: false) - } - - func callAsFunction(_ x: MLXArray) -> MLXArray { - w2(silu(w1(x)) * w3(x)) - } -} - -class LFM3DecoderLayer: Module { - let layerType: LFM3Configuration.LayerType - - @ModuleInfo(key: "self_attn") var attention: LFM3Attention? - @ModuleInfo(key: "conv") var conv: LFM3ShortConv? - @ModuleInfo(key: "feed_forward") var feedForward: LFM3MLP - @ModuleInfo(key: "operator_norm") var operatorNorm: RMSNorm - @ModuleInfo(key: "ffn_norm") var ffnNorm: RMSNorm - @ModuleInfo(key: "post_operator_norm") var postOperatorNorm: RMSNorm? - @ModuleInfo(key: "post_ffn_norm") var postFFNNorm: RMSNorm? - - init(_ args: LFM3Configuration, layerIdx: Int) { - self.layerType = args.layerTypes[layerIdx] - - if layerType == .conv { - _conv.wrappedValue = LFM3ShortConv(args) - } else { - _attention.wrappedValue = LFM3Attention(args, layerType: layerType) - } - - _feedForward.wrappedValue = LFM3MLP(dim: args.hiddenSize, hiddenDim: args.intermediateSize) - _operatorNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) - _ffnNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) - if args.useSandwichNorm { - _postOperatorNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) - _postFFNNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) - } - } - - func callAsFunction( - _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache? - ) -> MLXArray { - var r: MLXArray - if let attention { - r = attention(operatorNorm(x), mask: mask, cache: cache) - } else { - r = conv!(operatorNorm(x), cache: cache as? MambaCache) - } - if let postOperatorNorm { - r = postOperatorNorm(r) - } - let h = x + r - - var f = feedForward(ffnNorm(h)) - if let postFFNNorm { - f = postFFNNorm(f) - } - return h + f - } -} - -public class LFM3ModelInner: Module { - let args: LFM3Configuration - let firstFullAttentionIdx: Int? - let firstSlidingAttentionIdx: Int? - - let layers: [LFM3DecoderLayer] - - @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding - @ModuleInfo(key: "embedding_norm") var embeddingNorm: RMSNorm - - public init(_ args: LFM3Configuration) { - self.args = args - self.firstFullAttentionIdx = args.layerTypes.firstIndex(of: .fullAttention) - self.firstSlidingAttentionIdx = args.layerTypes.firstIndex(of: .slidingAttention) - - _embedTokens.wrappedValue = Embedding( - embeddingCount: args.vocabularySize, dimensions: args.hiddenSize) - - self.layers = (0 ..< args.hiddenLayers).map { i in - LFM3DecoderLayer(args, layerIdx: i) - } - - _embeddingNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) - } - - public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]? = nil) -> MLXArray { - var h = embedTokens(inputs) - let n = h.dim(1) - - // One mask per attention type, sized by the first cache of that type. - let fullMask = firstFullAttentionIdx.map { - makeAttentionMask(n: n, cache: cache?[$0]) - } - let slidingMask = firstSlidingAttentionIdx.map { - makeAttentionMask(n: n, cache: cache?[$0], windowSize: args.slidingWindow) - } - - for (i, layer) in layers.enumerated() { - let mask: MLXFast.ScaledDotProductAttentionMaskMode = - switch layer.layerType { - case .fullAttention: fullMask! - case .slidingAttention: slidingMask! - case .conv: .none - } - h = layer(h, mask: mask, cache: cache?[i]) - } - - return embeddingNorm(h) - } -} - public class LFM3Model: Module, LLMModel, KVCacheDimensionProvider { public let vocabularySize: Int public let kvHeads: [Int] @@ -409,22 +32,20 @@ public class LFM3Model: Module, LLMModel, KVCacheDimensionProvider { } public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { - let out = model(inputs, cache: cache) - if let lmHead { - return lmHead(out) - } - return model.embedTokens.asLinear(out) + projectLogits(model(inputs, cache: cache)) } public func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint { // MLX conversions nest the text model under `language_model`. Keep only the text - // model, which drops any vision or audio tensors. + // model, which drops any vision or audio tensors. The same mapping renames the + // per-layer quantization settings, including the bare `lm_head` module path. var checkpoint = try checkpoint.mapNames { name in var name = name if name.hasPrefix("language_model.") { name.removeFirst("language_model.".count) } - return name.hasPrefix("model.") || name.hasPrefix("lm_head.") ? name : nil + let root = name.prefix { $0 != "." } + return root == "model" || root == "lm_head" ? name : nil } var weights = filterLMHeadWeights( from: checkpoint.weights, tiedWordEmbeddings: configuration.tieWordEmbeddings) @@ -444,17 +65,19 @@ public class LFM3Model: Module, LLMModel, KVCacheDimensionProvider { } public func newCache(parameters: GenerateParameters?) throws -> [KVCache] { - try configuration.layerTypes.map { layerType in - switch layerType { - case .conv: - MambaCache() - case .fullAttention, .slidingAttention: - try makeHybridAttentionKVCache( - parameters: parameters, - slidingWindow: configuration.slidingWindow, - usesSlidingWindow: layerType == .slidingAttention) - } - } + try model.newCache(parameters: parameters) + } +} + +extension LFM3Model: HiddenStateLanguageModel { + /// Final normed hidden states `[B, L, hidden]` for token ids `[B, L]`. + public func hiddenStates(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + model(inputs, cache: cache) + } + + /// Vocabulary logits for final hidden states, tied or untied. + public func projectLogits(_ hiddenStates: MLXArray) -> MLXArray { + model.projectLogits(hiddenStates, lmHead: lmHead) } } diff --git a/Libraries/MLXLMCommon/Models/LFM3.swift b/Libraries/MLXLMCommon/Models/LFM3.swift new file mode 100644 index 0000000000..9f99dbfc82 --- /dev/null +++ b/Libraries/MLXLMCommon/Models/LFM3.swift @@ -0,0 +1,453 @@ +// +// LFM3.swift +// mlx-swift-lm +// + +// Port of https://huggingface.co/LiquidAI/LFM3-1.7B/blob/main/modeling_lfm3.py +// +// LFM3 is LFM2 with sliding-window attention as a third layer type, a sigmoid +// gate per attention head, partial RoPE on full-attention layers, and an +// optional RMSNorm on each block output ("sandwich norm"). +// +// The configuration and backbone live here so that MLXLLM's `LFM3Model` and a future +// MLXVLM wrapper share one implementation. + +import Foundation +import MLX +import MLXNN + +public struct LFM3Configuration: Codable, Sendable { + public enum LayerType: String, Codable, Sendable { + case conv + case fullAttention = "full_attention" + case slidingAttention = "sliding_attention" + } + + public struct RopeParameters: Codable, Sendable { + package let ropeType: String + package let ropeTheta: Float + package let partialRotaryFactor: Float + + enum CodingKeys: String, CodingKey { + case ropeType = "rope_type" + case ropeTheta = "rope_theta" + case partialRotaryFactor = "partial_rotary_factor" + } + + init(ropeTheta: Float, partialRotaryFactor: Float = 1.0) { + self.ropeType = "default" + self.ropeTheta = ropeTheta + self.partialRotaryFactor = partialRotaryFactor + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.ropeType = + try container.decodeIfPresent(String.self, forKey: .ropeType) ?? "default" + self.ropeTheta = try container.decode(Float.self, forKey: .ropeTheta) + self.partialRotaryFactor = + try container.decodeIfPresent(Float.self, forKey: .partialRotaryFactor) ?? 1.0 + } + } + + package let modelType: String + public let vocabularySize: Int + public let hiddenSize: Int + public let hiddenLayers: Int + public let attentionHeads: Int + public let kvHeads: Int + public let headDim: Int + public let intermediateSize: Int + package let maxPositionEmbeddings: Int? + package let normEps: Float + package let convBias: Bool + package let convLCache: Int + public let layerTypes: [LayerType] + public let slidingWindow: Int + package let useSandwichNorm: Bool + public let tieWordEmbeddings: Bool + package let ropeParameters: [String: RopeParameters] + + enum CodingKeys: String, CodingKey { + case modelType = "model_type" + case vocabularySize = "vocab_size" + case hiddenSize = "hidden_size" + case hiddenLayers = "num_hidden_layers" + case attentionHeads = "num_attention_heads" + case kvHeads = "num_key_value_heads" + case headDim = "head_dim" + case intermediateSize = "intermediate_size" + case maxPositionEmbeddings = "max_position_embeddings" + case normEps = "norm_eps" + case convBias = "conv_bias" + case convLCache = "conv_L_cache" + case layerTypes = "layer_types" + case slidingWindow = "sliding_window" + case useSandwichNorm = "use_sandwich_norm" + case tieWordEmbeddings = "tie_word_embeddings" + case ropeParameters = "rope_parameters" + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.modelType = try container.decodeIfPresent(String.self, forKey: .modelType) ?? "lfm3" + self.vocabularySize = + try container.decodeIfPresent(Int.self, forKey: .vocabularySize) ?? 128_000 + self.hiddenSize = try container.decode(Int.self, forKey: .hiddenSize) + self.hiddenLayers = try container.decode(Int.self, forKey: .hiddenLayers) + self.attentionHeads = try container.decode(Int.self, forKey: .attentionHeads) + self.kvHeads = try container.decode(Int.self, forKey: .kvHeads) + self.headDim = + try container.decodeIfPresent(Int.self, forKey: .headDim) + ?? hiddenSize / attentionHeads + self.intermediateSize = try container.decode(Int.self, forKey: .intermediateSize) + self.maxPositionEmbeddings = try container.decodeIfPresent( + Int.self, forKey: .maxPositionEmbeddings) + self.normEps = try container.decodeIfPresent(Float.self, forKey: .normEps) ?? 1e-5 + self.convBias = try container.decodeIfPresent(Bool.self, forKey: .convBias) ?? false + self.convLCache = try container.decodeIfPresent(Int.self, forKey: .convLCache) ?? 7 + self.slidingWindow = + try container.decodeIfPresent(Int.self, forKey: .slidingWindow) ?? 256 + self.useSandwichNorm = + try container.decodeIfPresent(Bool.self, forKey: .useSandwichNorm) ?? true + self.tieWordEmbeddings = + try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true + + // Same default pattern as the reference: full attention every fourth layer from + // the third, sliding attention in between, short convolutions elsewhere. + let hiddenLayers = self.hiddenLayers + self.layerTypes = + try container.decodeIfPresent([LayerType].self, forKey: .layerTypes) + ?? (0 ..< hiddenLayers).map { i in + i % 4 == 2 ? .fullAttention : (i % 4 == 0 && i > 0 ? .slidingAttention : .conv) + } + guard layerTypes.count == hiddenLayers else { + throw DecodingError.dataCorruptedError( + forKey: .layerTypes, in: container, + debugDescription: + "layer_types has \(layerTypes.count) entries but num_hidden_layers is \(hiddenLayers)" + ) + } + + self.ropeParameters = + try container.decodeIfPresent([String: RopeParameters].self, forKey: .ropeParameters) + ?? [ + LayerType.fullAttention.rawValue: .init( + ropeTheta: 1_000_000, partialRotaryFactor: 0.5), + LayerType.slidingAttention.rawValue: .init(ropeTheta: 10_000), + ] + for layerType in Set(layerTypes) where layerType != .conv { + guard let rope = ropeParameters[layerType.rawValue] else { + throw DecodingError.dataCorruptedError( + forKey: .ropeParameters, in: container, + debugDescription: "rope_parameters has no entry for \(layerType.rawValue)") + } + // Scaled RoPE types are not ported; running them as default would be wrong. + guard rope.ropeType == "default" else { + throw DecodingError.dataCorruptedError( + forKey: .ropeParameters, in: container, + debugDescription: "Unsupported LFM3 rope_type '\(rope.ropeType)'") + } + } + } +} + +class LFM3Attention: Module { + let attentionHeads: Int + let kvHeads: Int + let headDim: Int + let scale: Float + + @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 + @ModuleInfo(key: "gate_proj") var gateProj: Linear + + @ModuleInfo(key: "q_norm") var qNorm: RMSNorm + @ModuleInfo(key: "k_norm") var kNorm: RMSNorm + + let rope: RoPELayer + + init(_ args: LFM3Configuration, layerType: LFM3Configuration.LayerType) { + self.attentionHeads = args.attentionHeads + self.kvHeads = args.kvHeads + self.headDim = args.headDim + self.scale = pow(Float(headDim), -0.5) + + let dim = args.hiddenSize + _qProj.wrappedValue = Linear(dim, attentionHeads * headDim, bias: false) + _kProj.wrappedValue = Linear(dim, kvHeads * headDim, bias: false) + _vProj.wrappedValue = Linear(dim, kvHeads * headDim, bias: false) + _oProj.wrappedValue = Linear(attentionHeads * headDim, dim, bias: false) + _gateProj.wrappedValue = Linear(dim, attentionHeads, bias: false) + + _qNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: args.normEps) + _kNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: args.normEps) + + // Partial RoPE rotates the first dimensions of each half of the head with the + // full-head frequencies, which is what ProportionalRoPE does. RoPE(dimensions:) + // would rotate a contiguous prefix with different frequencies instead. + let rope = args.ropeParameters[layerType.rawValue]! + if rope.partialRotaryFactor < 1 { + self.rope = initializeRope( + dims: headDim, base: rope.ropeTheta, traditional: false, + scalingConfig: [ + "type": .string("proportional"), + "partial_rotary_factor": .float(rope.partialRotaryFactor), + ], + maxPositionEmbeddings: nil) + } else { + self.rope = RoPE(dimensions: headDim, traditional: false, base: rope.ropeTheta) + } + } + + func callAsFunction( + _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache? + ) -> MLXArray { + let (B, L) = (x.dim(0), x.dim(1)) + + var queries = qNorm(qProj(x).reshaped(B, L, attentionHeads, -1)).transposed(0, 2, 1, 3) + var keys = kNorm(kProj(x).reshaped(B, L, kvHeads, -1)).transposed(0, 2, 1, 3) + let values = vProj(x).reshaped(B, L, kvHeads, -1).transposed(0, 2, 1, 3) + + let offset = cache?.ropeOffset + queries = applyRotaryPosition(rope, to: queries, offset: offset) + keys = applyRotaryPosition(rope, to: keys, offset: offset) + + let output = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: cache, + scale: scale, + mask: mask + ) + .transposed(0, 2, 1, 3) + + // One sigmoid gate per head, computed from the block input. + let gate = sigmoid(gateProj(x)).expandedDimensions(axis: -1) + return oProj((output * gate).reshaped(B, L, -1)) + } +} + +class LFM3ShortConv: Module { + let hiddenSize: Int + let lCache: Int + + @ModuleInfo(key: "conv") var conv: Conv1d + @ModuleInfo(key: "in_proj") var inProj: Linear + @ModuleInfo(key: "out_proj") var outProj: Linear + + init(_ args: LFM3Configuration) { + self.hiddenSize = args.hiddenSize + self.lCache = args.convLCache + + _conv.wrappedValue = Conv1d( + inputChannels: hiddenSize, + outputChannels: hiddenSize, + kernelSize: lCache, + groups: hiddenSize, + bias: args.convBias + ) + _inProj.wrappedValue = Linear(hiddenSize, 3 * hiddenSize, bias: args.convBias) + _outProj.wrappedValue = Linear(hiddenSize, hiddenSize, bias: args.convBias) + } + + func callAsFunction(_ x: MLXArray, cache: MambaCache?) -> MLXArray { + let BCx = inProj(x).split(parts: 3, axis: -1) + let (B, C) = (BCx[0], BCx[1]) + var Bx = B * BCx[2] + + // The cache holds the last `lCache - 1` inputs, so the conv needs no padding. + let state = + cache?[0] ?? MLXArray.zeros([Bx.dim(0), lCache - 1, hiddenSize], dtype: Bx.dtype) + Bx = concatenated([state, Bx], axis: -2) + if let cache { + cache[0] = contiguous(Bx[0..., (Bx.dim(1) - (lCache - 1))..., 0...]) + cache.advance(x.dim(1)) + } + + return outProj(C * conv(Bx)) + } +} + +class LFM3MLP: Module, UnaryLayer { + @ModuleInfo(key: "w1") var w1: Linear + @ModuleInfo(key: "w2") var w2: Linear + @ModuleInfo(key: "w3") var w3: Linear + + init(dim: Int, hiddenDim: Int) { + _w1.wrappedValue = Linear(dim, hiddenDim, bias: false) + _w2.wrappedValue = Linear(hiddenDim, dim, bias: false) + _w3.wrappedValue = Linear(dim, hiddenDim, bias: false) + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + w2(silu(w1(x)) * w3(x)) + } +} + +package class LFM3DecoderLayer: Module { + let layerType: LFM3Configuration.LayerType + + @ModuleInfo(key: "self_attn") var attention: LFM3Attention? + @ModuleInfo(key: "conv") var conv: LFM3ShortConv? + @ModuleInfo(key: "feed_forward") var feedForward: LFM3MLP + @ModuleInfo(key: "operator_norm") var operatorNorm: RMSNorm + @ModuleInfo(key: "ffn_norm") var ffnNorm: RMSNorm + @ModuleInfo(key: "post_operator_norm") var postOperatorNorm: RMSNorm? + @ModuleInfo(key: "post_ffn_norm") var postFFNNorm: RMSNorm? + + init(_ args: LFM3Configuration, layerIdx: Int) { + self.layerType = args.layerTypes[layerIdx] + + if layerType == .conv { + _conv.wrappedValue = LFM3ShortConv(args) + } else { + _attention.wrappedValue = LFM3Attention(args, layerType: layerType) + } + + _feedForward.wrappedValue = LFM3MLP(dim: args.hiddenSize, hiddenDim: args.intermediateSize) + _operatorNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) + _ffnNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) + if args.useSandwichNorm { + _postOperatorNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) + _postFFNNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) + } + } + + func callAsFunction( + _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache? + ) -> MLXArray { + var r: MLXArray + if let attention { + r = attention(operatorNorm(x), mask: mask, cache: cache) + } else { + r = conv!(operatorNorm(x), cache: cache as? MambaCache) + } + if let postOperatorNorm { + r = postOperatorNorm(r) + } + let h = x + r + + var f = feedForward(ffnNorm(h)) + if let postFFNNorm { + f = postFFNNorm(f) + } + return h + f + } +} + +/// Attention masks for one backbone pass, one per attention layer type. +/// +/// A `nil` entry uses the default: causal for full attention, and causal within the +/// sliding window for sliding attention, both sized by the first cache of that type. +public struct LFM3AttentionMasks { + public var fullAttention: MLXFast.ScaledDotProductAttentionMaskMode? + public var slidingAttention: MLXFast.ScaledDotProductAttentionMaskMode? + + public init( + fullAttention: MLXFast.ScaledDotProductAttentionMaskMode? = nil, + slidingAttention: MLXFast.ScaledDotProductAttentionMaskMode? = nil + ) { + self.fullAttention = fullAttention + self.slidingAttention = slidingAttention + } +} + +/// The LFM3 text backbone: token embedding, decoder layers, and the final norm. +/// +/// The caller owns the caches, one per layer from ``newCache(parameters:)``. Positions come +/// from the caches, so a sequence can be fed in chunks of token ids or embeddings. +public class LFM3ModelInner: Module { + let args: LFM3Configuration + let firstFullAttentionIdx: Int? + let firstSlidingAttentionIdx: Int? + + package let layers: [LFM3DecoderLayer] + + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + @ModuleInfo(key: "embedding_norm") var embeddingNorm: RMSNorm + + public var hiddenSize: Int { args.hiddenSize } + + public init(_ args: LFM3Configuration) { + self.args = args + self.firstFullAttentionIdx = args.layerTypes.firstIndex(of: .fullAttention) + self.firstSlidingAttentionIdx = args.layerTypes.firstIndex(of: .slidingAttention) + + _embedTokens.wrappedValue = Embedding( + embeddingCount: args.vocabularySize, dimensions: args.hiddenSize) + + self.layers = (0 ..< args.hiddenLayers).map { i in + LFM3DecoderLayer(args, layerIdx: i) + } + + _embeddingNorm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.normEps) + } + + /// Token embeddings `[B, L, hidden]` for token ids `[B, L]`. + public func embed(_ inputs: MLXArray) -> MLXArray { + embedTokens(inputs) + } + + /// Final normed hidden states `[B, L, hidden]` for token ids `[B, L]`. + public func callAsFunction( + _ inputs: MLXArray, cache: [KVCache]? = nil, masks: LFM3AttentionMasks = .init() + ) -> MLXArray { + callAsFunction(embeddings: embed(inputs), cache: cache, masks: masks) + } + + /// Final normed hidden states `[B, L, hidden]` for input embeddings `[B, L, hidden]`. + public func callAsFunction( + embeddings: MLXArray, cache: [KVCache]? = nil, masks: LFM3AttentionMasks = .init() + ) -> MLXArray { + var h = embeddings + let n = h.dim(1) + + let fullMask = + masks.fullAttention + ?? firstFullAttentionIdx.map { makeAttentionMask(n: n, cache: cache?[$0]) } + let slidingMask = + masks.slidingAttention + ?? firstSlidingAttentionIdx.map { + makeAttentionMask(n: n, cache: cache?[$0], windowSize: args.slidingWindow) + } + + for (i, layer) in layers.enumerated() { + let mask: MLXFast.ScaledDotProductAttentionMaskMode = + switch layer.layerType { + case .fullAttention: fullMask! + case .slidingAttention: slidingMask! + case .conv: .none + } + h = layer(h, mask: mask, cache: cache?[i]) + } + + return embeddingNorm(h) + } + + /// Vocabulary logits for final hidden states, through `lmHead` when the checkpoint has + /// one and the tied token embedding otherwise. + public func projectLogits(_ hiddenStates: MLXArray, lmHead: Linear? = nil) -> MLXArray { + lmHead?(hiddenStates) ?? embedTokens.asLinear(hiddenStates) + } + + /// One cache per layer: a conv state for conv layers, a rotating cache bounded by the + /// sliding window for sliding attention, and a full or `maxKVSize` cache otherwise. + public func newCache(parameters: GenerateParameters?) throws -> [KVCache] { + try args.layerTypes.map { layerType in + switch layerType { + case .conv: + MambaCache() + case .fullAttention, .slidingAttention: + try makeHybridAttentionKVCache( + parameters: parameters, + slidingWindow: args.slidingWindow, + usesSlidingWindow: layerType == .slidingAttention) + } + } + } +} diff --git a/Tests/MLXLMTests/LFM3Tests.swift b/Tests/MLXLMTests/LFM3Tests.swift index cca086b3a9..4c997c6497 100644 --- a/Tests/MLXLMTests/LFM3Tests.swift +++ b/Tests/MLXLMTests/LFM3Tests.swift @@ -2,11 +2,11 @@ import Foundation import MLX -import MLXLMCommon import MLXNN import XCTest @testable import MLXLLM +@testable import MLXLMCommon final class LFM3Tests: XCTestCase { @@ -63,6 +63,7 @@ final class LFM3Tests: XCTestCase { /// test prompts. private func tinyConfiguration( layerTypes: [String] = tinyLayerTypes, tieWordEmbeddings: Bool = true, + intermediateSize: Int = 48, fullRope: String = #"{"rope_type": "default", "rope_theta": 1000000.0, "partial_rotary_factor": 0.5}"# ) throws -> LFM3Configuration { @@ -71,7 +72,8 @@ final class LFM3Tests: XCTestCase { """ { "model_type": "lfm3", "vocab_size": 64, "hidden_size": 32, - "intermediate_size": 48, "num_hidden_layers": \(layerTypes.count), + "intermediate_size": \(intermediateSize), + "num_hidden_layers": \(layerTypes.count), "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 16, "norm_eps": 1e-5, "conv_L_cache": 3, "conv_bias": false, "sliding_window": 4, "use_sandwich_norm": true, @@ -303,4 +305,156 @@ final class LFM3Tests: XCTestCase { } } } + + // MARK: - Backbone entry points + + /// Token ids and their embeddings take the same path, so logits match exactly. + func testEmbeddingInputMatchesTokenInput() throws { + for tied in [true, false] { + let model = try tinyModel(tinyConfiguration(tieWordEmbeddings: tied)) + let tokens = MLXArray((0 ..< 14).map { Int32($0 * 5 % 64) }).reshaped(2, 7) + + let fromTokens = model(tokens, cache: nil) + let hidden = model.model(embeddings: model.model.embed(tokens)) + let fromEmbeddings = model.projectLogits(hidden) + + XCTAssertEqual(hidden.shape, [2, 7, model.model.hiddenSize]) + XCTAssertEqual( + abs(fromEmbeddings - fromTokens).max().item(Float.self), 0, "tied \(tied)") + XCTAssertEqual( + abs(model.hiddenStates(tokens, cache: nil) - hidden).max().item(Float.self), 0) + } + } + + /// Embedding prefill in chunks and then one step at a time must match one shot, past + /// the sliding window where the rotating caches wrap. + func testChunkedEmbeddingPrefillMatchesOneShot() throws { + let model = try tinyModel() + let tokenCount = 19 + let tokens = MLXArray((0 ..< tokenCount).map { Int32(($0 * 5 + 1) % 64) }) + .reshaped(1, tokenCount) + let embeddings = model.model.embed(tokens) + + let oneShot = model(tokens, cache: nil) + eval(oneShot) + + let decodeCount = 5 + for chunkSize in [2, 4, 7, 14] { + let cache = try model.newCache(parameters: nil) + var logits = [MLXArray]() + var start = 0 + while start < tokenCount { + let prefillEnd = tokenCount - decodeCount + let end = start < prefillEnd ? min(start + chunkSize, prefillEnd) : start + 1 + let hidden = model.model(embeddings: embeddings[0..., start ..< end], cache: cache) + logits.append(model.projectLogits(hidden)) + eval(logits.last!) + start = end + } + + let drift = abs(concatenated(logits, axis: 1) - oneShot).max().item(Float.self) + XCTAssertLessThan(drift, MatmulPrecision.splitTolerance, "chunk size \(chunkSize)") + for (i, layerCache) in cache.enumerated() where !(layerCache is MambaCache) { + XCTAssertEqual(layerCache.offset, tokenCount, "layer \(i)") + } + } + } + + /// Masks passed per attention type replace the defaults for that type only. + func testAttentionMaskOverrides() throws { + let model = try tinyModel() + let tokens = MLXArray((0 ..< 9).map { Int32($0 * 3 % 64) }).reshaped(1, 9) + let window = model.configuration.slidingWindow + let defaults = model.model(tokens) + + let explicit = model.model( + tokens, + masks: .init( + fullAttention: .causal, + slidingAttention: .array(createCausalMask(n: 9, offset: 0, windowSize: window)))) + XCTAssertLessThan(abs(explicit - defaults).max().item(Float.self), 1e-5) + + // A plain causal mask lets sliding layers see past the window. + let unwindowed = model.model(tokens, masks: .init(slidingAttention: .causal)) + XCTAssertGreaterThan(abs(unwindowed - defaults).max().item(Float.self), 1e-3) + } + + // MARK: - Mixed-precision checkpoint + + /// An MLX conversion wrapped in `language_model` with 4-bit attention and conv, 6-bit + /// MLP, and an 8-bit untied `lm_head`, declared per layer in `config.json`. The prefix + /// mapping must rename tensors and settings together or strict loading fails. + func testLoadsMixedPrecisionWrappedCheckpoint() throws { + let groupSize = 32 + let configuration = try tinyConfiguration(tieWordEmbeddings: false, intermediateSize: 64) + let reference = try tinyModel(configuration) + + let bits = { (path: String) in + path == "lm_head" ? 8 : path.contains(".feed_forward.") ? 6 : 4 + } + var arrays = [String: MLXArray]() + var quantizedPaths = [String]() + for (path, module) in reference.leafModules().flattened() { + let weight: MLXArray + switch module { + case let linear as Linear: weight = linear.weight + case let embedding as Embedding: weight = embedding.weight + default: continue + } + let (wq, scales, biases) = quantized(weight, groupSize: groupSize, bits: bits(path)) + arrays["language_model.\(path).weight"] = wq + arrays["language_model.\(path).scales"] = scales + arrays["language_model.\(path).biases"] = biases + quantizedPaths.append(path) + } + for (key, value) in reference.parameters().flattened() { + let module = key.split(separator: ".").dropLast().joined(separator: ".") + if !quantizedPaths.contains(module) { + arrays["language_model.\(key)"] = value + } + } + arrays["vision_tower.proj.weight"] = MLXArray.zeros([4, 4]) + XCTAssertTrue(quantizedPaths.contains("lm_head")) + XCTAssertTrue(quantizedPaths.contains { $0.hasSuffix("conv.in_proj") }) + + // Per-layer entries use the checkpoint's own (wrapped) names. + let overrides = + quantizedPaths.filter { bits($0) != 4 }.map { path in + #""language_model.\#(path)": {"group_size": \#(groupSize), "bits": \#(bits(path))}"# + } + [#""vision_tower.proj": {"group_size": \#(groupSize), "bits": 8}"#] + let baseConfiguration = try JSONDecoder().decode( + BaseConfiguration.self, + from: Data( + """ + { + "model_type": "lfm3", + "quantization": { + "group_size": \(groupSize), "bits": 4, + \(overrides.joined(separator: ",\n")) + } + } + """.utf8)) + + let directory = FileManager.default.temporaryDirectory + .appending(component: "lfm3-mixed-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + try save(arrays: arrays, url: directory.appending(component: "model.safetensors")) + + let model = LFM3Model(configuration) + try loadWeights( + modelDirectory: directory, model: model, + perLayerQuantization: baseConfiguration.perLayerQuantization) + + let modules = Dictionary(uniqueKeysWithValues: model.leafModules().flattened()) + for path in quantizedPaths { + let module = try XCTUnwrap(modules[path] as? Quantized, path) + XCTAssertEqual(module.bits, bits(path), path) + XCTAssertEqual(module.groupSize, groupSize, path) + } + + let logits = model(MLXArray([Int32(1), 2, 3, 4, 5]).reshaped(1, 5), cache: nil) + XCTAssertEqual(logits.shape, [1, 5, 64]) + XCTAssertFalse(any(isNaN(logits)).item(Bool.self)) + } } From 65fd3ae77552f2acdc75273350ab9d9b8b0b0056 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Garc=C3=ADa=20Pizarro?= <81751965+alvarogarciapiz@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:54:25 +0100 Subject: [PATCH 3/7] fix(lfm3): harden implementation and expand regression coverage --- .../LFM3TokenizerIntegrationTests.swift | 91 ++++++ Libraries/MLXLLM/LLMModelFactory.swift | 4 + Libraries/MLXLLM/Models/LFM3.swift | 36 +++ Libraries/MLXLMCommon/Models/LFM3.swift | 65 +++- Package.swift | 7 +- Tests/MLXLMTests/LFM3CheckpointTests.swift | 95 ++++++ Tests/MLXLMTests/LFM3ReferenceTests.swift | 119 +++++++ Tests/MLXLMTests/LFM3Tests.swift | 291 ++++++++++++++++++ .../Resources/lfm3-reference-config.json | 57 ++++ .../lfm3-reference-outputs.safetensors | Bin 0 -> 15752 bytes .../lfm3-reference-weights.safetensors | Bin 0 -> 14968 bytes scripts/lfm3-checkpoint-reference.py | 98 ++++++ scripts/lfm3-reference.py | 91 ++++++ .../references/supported-models.md | 27 +- 14 files changed, 978 insertions(+), 3 deletions(-) create mode 100644 IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift create mode 100644 Tests/MLXLMTests/LFM3CheckpointTests.swift create mode 100644 Tests/MLXLMTests/LFM3ReferenceTests.swift create mode 100644 Tests/MLXLMTests/Resources/lfm3-reference-config.json create mode 100644 Tests/MLXLMTests/Resources/lfm3-reference-outputs.safetensors create mode 100644 Tests/MLXLMTests/Resources/lfm3-reference-weights.safetensors create mode 100644 scripts/lfm3-checkpoint-reference.py create mode 100644 scripts/lfm3-reference.py diff --git a/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift b/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift new file mode 100644 index 0000000000..8d923a1436 --- /dev/null +++ b/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift @@ -0,0 +1,91 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import Testing +import Tokenizers + +// Opt in after selecting a tokenizer with swift-transformers #397 and #398. +@Suite( + .serialized, .enabled(if: ProcessInfo.processInfo.environment["MLX_RUN_LFM3_TOKENIZER"] == "1")) +struct LFM3TokenizerIntegrationTests { + private func tokenizer() async throws -> any Tokenizers.Tokenizer { + if let path = ProcessInfo.processInfo.environment["MLX_LFM3_TOKENIZER_DIRECTORY"] { + return try await AutoTokenizer.from(modelFolder: URL(filePath: path)) + } + return try await AutoTokenizer.from( + pretrained: "LiquidAI/LFM3-1.7B", revision: "ac2586a34f1a1c03329dbdcdefabd8b6478ddaa7") + } + + // Goldens from tokenizers 0.23.3 and the pinned LiquidAI tokenizer. + @Test func tokenIDsMatchHuggingFace() async throws { + let tokenizer = try await tokenizer() + let cases: [(String, [Int])] = [ + (".reduce", [96744]), + ("line.\r\nThis", [1421, 64122, 1942]), + ("Hello, world!", [35808, 20, 1530, 9]), + ("Reading\nCongratulations", [49973, 207, 44069, 2867, 4461]), + ("0\u{fe0f}\u{20e3}", [24, 47353, 167, 234, 105]), + ("¡Hola! 日本語 中文 العربية", [32245, 48, 4105, 9, 37054, 12673, 50525, 4966, 54206]), + ( + "let sum = values.reduce(0, +)", + [1161, 9632, 550, 3895, 96744, 16, 24, 20, 1510, 17] + ), + ] + for (text, expected) in cases { + #expect(tokenizer.encode(text: text, addSpecialTokens: false) == expected) + } + #expect(tokenizer.convertTokenToId("<|im_end|>") == 124900) + #expect(tokenizer.convertTokenToId("") == 125019) + #expect(tokenizer.convertTokenToId("") == 125020) + } + + @Test func chatAndToolTemplatesMatchHuggingFace() async throws { + let tokenizer = try await tokenizer() + let plain = try tokenizer.applyChatTemplate(messages: [ + ["role": "user", "content": "Hello"] + ]) + #expect( + plain == [124894, 124899, 5922, 207, 35808, 124900, 207, 124899, 63514, 207, 124901]) + let messages: [[String: any Sendable]] = [ + ["role": "system", "content": "Be precise."], + ["role": "user", "content": "Weather?"], + [ + "role": "assistant", + "tool_calls": [ + [ + "type": "function", + "function": [ + "name": "get_weather", "arguments": ["location": "Paris"], + ] as [String: any Sendable], + ] as [String: any Sendable] + ], + ], + ["role": "tool", "content": "Sunny"], + ["role": "user", "content": "Thanks"], + ] + let tools: [[String: any Sendable]] = [ + [ + "type": "function", + "function": [ + "name": "get_weather", + "parameters": [ + "type": "object", "properties": ["location": ["type": "string"]], + ] as [String: any Sendable], + ] as [String: any Sendable], + ] + ] + let actual = try tokenizer.applyChatTemplate(messages: messages, tools: tools) + // Nested schema keys use the same sorted order as Swift Jinja tojson. + #expect( + actual == [ + 124894, 124899, 23630, 207, 4184, 16845, 63908, 125017, 207, 38184, 2554, 6380, 496, + 1265, 71, 51492, 1377, 496, 29701, 6380, 36579, 38805, 6380, 36579, 22061, 6380, + 36579, 5882, 6380, 496, 3987, 87961, 496, 5882, 6380, 496, 7022, 115440, 125018, + 124900, 207, 124899, 5922, 207, 97056, 39, 124900, 207, 124899, 63514, 207, 124901, + 124902, 125019, 207, 125021, 1265, 71, 51492, 703, 125023, 22061, 703, 41176, 207, + 125024, 207, 125022, 207, 125020, 124900, 207, 124899, 46765, 207, 125025, 207, + 35243, 3905, 207, 125026, 124900, 207, 124899, 5922, 207, 29163, 124900, 207, + 124899, 63514, 207, 124901, + ]) + } +} diff --git a/Libraries/MLXLLM/LLMModelFactory.swift b/Libraries/MLXLLM/LLMModelFactory.swift index 3ee66f6145..897fbe39bd 100644 --- a/Libraries/MLXLLM/LLMModelFactory.swift +++ b/Libraries/MLXLLM/LLMModelFactory.swift @@ -783,6 +783,10 @@ public final class LLMModelFactory: GenericModelFactory { let tokenizer = try await tokenizerTask + if model is LFM3Model { + try LFM3Model.validateTokenizer(tokenizer) + } + let messageGenerator: any MessageGenerator if let configuredMessageGenerator = mutableConfiguration.messageGenerator { messageGenerator = configuredMessageGenerator diff --git a/Libraries/MLXLLM/Models/LFM3.swift b/Libraries/MLXLLM/Models/LFM3.swift index 4e05a3a865..47e111f771 100644 --- a/Libraries/MLXLLM/Models/LFM3.swift +++ b/Libraries/MLXLLM/Models/LFM3.swift @@ -52,6 +52,10 @@ public class LFM3Model: Module, LLMModel, KVCacheDimensionProvider { // PyTorch stores the depthwise conv as [C, 1, K]; MLX expects [C, K, 1]. for (name, value) in weights where name.hasSuffix("conv.conv.weight") { + guard value.ndim == 3 else { + throw ModelFactoryError.invalidConfiguration( + "LFM3 convolution tensor \(name) must have rank 3, got \(value.shape)") + } if value.dim(-1) > value.dim(1) { weights[name] = value.transposed(0, 2, 1) } @@ -67,6 +71,38 @@ public class LFM3Model: Module, LLMModel, KVCacheDimensionProvider { public func newCache(parameters: GenerateParameters?) throws -> [KVCache] { try model.newCache(parameters: parameters) } + + package static func validateTokenizer(_ tokenizer: any Tokenizer) throws { + guard tokenizer.convertTokenToId("<|startoftext|>") == 124894, + tokenizer.convertTokenToId(".reduce") == 96744 + else { return } + // Probe vocabulary entries affected by ignore_merges and code-point splitting. + for (text, pieces) in [ + (".reduce", [".reduce"]), ("line.\r\nThis", ["line", ".čĊ", "This"]), + ] { + let expected = pieces.compactMap { tokenizer.convertTokenToId($0) } + guard expected.count == pieces.count, + !expected.contains(where: { $0 == tokenizer.unknownTokenId }) + else { continue } + guard tokenizer.encode(text: text, addSpecialTokens: false) == expected else { + throw LFM3TokenizerError.incompatible + } + } + } +} + +private enum LFM3TokenizerError: LocalizedError { + case incompatible + + var errorDescription: String? { + "LFM3 requires a tokenizer that honors BPE ignore_merges and splits regexes by code point. " + + "Use a tokenizer containing swift-transformers fixes #397 and #398, or a compatible TokenizerLoader." + } +} + +extension LFM3Model { + public var toolCallFormat: ToolCallFormat? { .xmlFunction } + public var reasoningConfig: ReasoningConfig? { .thinkTagsWithEnableThinking } } extension LFM3Model: HiddenStateLanguageModel { diff --git a/Libraries/MLXLMCommon/Models/LFM3.swift b/Libraries/MLXLMCommon/Models/LFM3.swift index 9f99dbfc82..b786200a2a 100644 --- a/Libraries/MLXLMCommon/Models/LFM3.swift +++ b/Libraries/MLXLMCommon/Models/LFM3.swift @@ -98,6 +98,18 @@ public struct LFM3Configuration: Codable, Sendable { self.hiddenLayers = try container.decode(Int.self, forKey: .hiddenLayers) self.attentionHeads = try container.decode(Int.self, forKey: .attentionHeads) self.kvHeads = try container.decode(Int.self, forKey: .kvHeads) + for (key, value) in [ + (CodingKeys.hiddenSize, hiddenSize), (.attentionHeads, attentionHeads), + (.kvHeads, kvHeads), + ] where value <= 0 { + throw DecodingError.dataCorruptedError( + forKey: key, in: container, debugDescription: "\(key.rawValue) must be positive") + } + guard attentionHeads % kvHeads == 0 else { + throw DecodingError.dataCorruptedError( + forKey: .kvHeads, in: container, + debugDescription: "num_attention_heads must be divisible by num_key_value_heads") + } self.headDim = try container.decodeIfPresent(Int.self, forKey: .headDim) ?? hiddenSize / attentionHeads @@ -114,6 +126,30 @@ public struct LFM3Configuration: Codable, Sendable { self.tieWordEmbeddings = try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true + for (key, value) in [ + (CodingKeys.vocabularySize, vocabularySize), (.hiddenLayers, hiddenLayers), + (.intermediateSize, intermediateSize), (.convLCache, convLCache), + (.slidingWindow, slidingWindow), + ] where value <= 0 { + throw DecodingError.dataCorruptedError( + forKey: key, in: container, debugDescription: "\(key.rawValue) must be positive") + } + guard headDim > 0, headDim % 2 == 0 else { + throw DecodingError.dataCorruptedError( + forKey: .headDim, in: container, + debugDescription: "LFM3 head_dim must be positive and even") + } + guard normEps.isFinite, normEps > 0 else { + throw DecodingError.dataCorruptedError( + forKey: .normEps, in: container, + debugDescription: "norm_eps must be finite and positive") + } + if let maxPositionEmbeddings, maxPositionEmbeddings <= 0 { + throw DecodingError.dataCorruptedError( + forKey: .maxPositionEmbeddings, in: container, + debugDescription: "max_position_embeddings must be positive") + } + // Same default pattern as the reference: full attention every fourth layer from // the third, sliding attention in between, short convolutions elsewhere. let hiddenLayers = self.hiddenLayers @@ -149,6 +185,15 @@ public struct LFM3Configuration: Codable, Sendable { forKey: .ropeParameters, in: container, debugDescription: "Unsupported LFM3 rope_type '\(rope.ropeType)'") } + guard rope.ropeTheta.isFinite, rope.ropeTheta > 0, + rope.partialRotaryFactor.isFinite, (0 ... 1).contains(rope.partialRotaryFactor) + else { + throw DecodingError.dataCorruptedError( + forKey: .ropeParameters, in: container, + debugDescription: + "LFM3 requires finite positive rope_theta and partial_rotary_factor in [0, 1]" + ) + } } } } @@ -259,13 +304,23 @@ class LFM3ShortConv: Module { let BCx = inProj(x).split(parts: 3, axis: -1) let (B, C) = (BCx[0], BCx[1]) var Bx = B * BCx[2] + if let mask = cache?.makeMask(N: x.dim(1)) { + Bx = which(mask[.ellipsis, .newAxis], Bx, 0) + } // The cache holds the last `lCache - 1` inputs, so the conv needs no padding. let state = cache?[0] ?? MLXArray.zeros([Bx.dim(0), lCache - 1, hiddenSize], dtype: Bx.dtype) Bx = concatenated([state, Bx], axis: -2) if let cache { - cache[0] = contiguous(Bx[0..., (Bx.dim(1) - (lCache - 1))..., 0...]) + if let lengths = cache.currentLengths { + let ends = clip(lengths, min: 0, max: x.dim(1)) + let positions = (ends[0..., .newAxis] + MLXArray(0 ..< lCache - 1))[ + .ellipsis, .newAxis] + cache[0] = contiguous(takeAlong(Bx, positions, axis: 1)) + } else { + cache[0] = contiguous(Bx[0..., (Bx.dim(1) - (lCache - 1))..., 0...]) + } cache.advance(x.dim(1)) } @@ -323,8 +378,11 @@ package class LFM3DecoderLayer: Module { ) -> MLXArray { var r: MLXArray if let attention { + precondition(!(cache is ArraysCache), "LFM3 attention requires an attention cache") r = attention(operatorNorm(x), mask: mask, cache: cache) } else { + precondition( + cache == nil || cache is MambaCache, "LFM3 convolution requires MambaCache") r = conv!(operatorNorm(x), cache: cache as? MambaCache) } if let postOperatorNorm { @@ -404,6 +462,11 @@ public class LFM3ModelInner: Module { public func callAsFunction( embeddings: MLXArray, cache: [KVCache]? = nil, masks: LFM3AttentionMasks = .init() ) -> MLXArray { + precondition( + cache == nil || cache?.count == layers.count, "LFM3 requires one cache per layer") + precondition( + embeddings.ndim == 3 && embeddings.dim(-1) == hiddenSize && embeddings.dim(1) > 0, + "LFM3 expects nonempty embeddings shaped [batch, sequence, hidden_size]") var h = embeddings let n = h.dim(1) diff --git a/Package.swift b/Package.swift index 5a1a4b8914..f0f9236f27 100644 --- a/Package.swift +++ b/Package.swift @@ -183,7 +183,12 @@ let package = Package( exclude: [ "README.md" ], - resources: [.process("Resources/1080p_30.mov"), .process("Resources/audio_only.mov")] + resources: [ + .process("Resources/1080p_30.mov"), .process("Resources/audio_only.mov"), + .process("Resources/lfm3-reference-config.json"), + .process("Resources/lfm3-reference-weights.safetensors"), + .process("Resources/lfm3-reference-outputs.safetensors"), + ] ), .macro( name: "MLXHuggingFaceMacros", diff --git a/Tests/MLXLMTests/LFM3CheckpointTests.swift b/Tests/MLXLMTests/LFM3CheckpointTests.swift new file mode 100644 index 0000000000..4aab8aa15d --- /dev/null +++ b/Tests/MLXLMTests/LFM3CheckpointTests.swift @@ -0,0 +1,95 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXNN +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon + +final class LFM3CheckpointTests: XCTestCase { + private func loadModel() throws -> LFM3Model { + guard let path = ProcessInfo.processInfo.environment["MLX_LFM3_CHECKPOINT"] else { + throw XCTSkip("Set MLX_LFM3_CHECKPOINT to a local published LFM3 checkpoint") + } + let directory = URL(filePath: path) + let data = try Data(contentsOf: directory.appending(component: "config.json")) + let config = try JSONDecoder().decode(LFM3Configuration.self, from: data) + let baseConfig = try JSONDecoder().decode(BaseConfiguration.self, from: data) + let start = Date.timeIntervalSinceReferenceDate + let model = LFM3Model(config) + try loadWeights( + modelDirectory: directory, model: model, + perLayerQuantization: baseConfig.perLayerQuantization) + eval(model) + print("LFM3 checkpoint load_seconds=\(Date.timeIntervalSinceReferenceDate - start)") + return model + } + + func testPublishedCheckpointPrefillAndDecode() throws { + let model = try loadModel() + Memory.peakMemory = 0 + let count = 1024 + let tokens = MLXArray((0 ..< count).map { Int32(($0 * 7 + 3) % model.vocabularySize) }) + .reshaped(1, count) + let cache = try model.newCache(parameters: nil) + let start = Date.timeIntervalSinceReferenceDate + var hidden: MLXArray? + for offset in stride(from: 0, to: count, by: 256) { + hidden = model.hiddenStates(tokens[0..., offset ..< offset + 256], cache: cache) + eval(hidden!) + eval(cache) + } + var logits = model.projectLogits(try XCTUnwrap(hidden)[0..., (-1)...]) + eval(logits) + let prefillSeconds = Date.timeIntervalSinceReferenceDate - start + let decodeStart = Date.timeIntervalSinceReferenceDate + for _ in 0 ..< 16 { + let next = argMax(logits[0, -1]).reshaped(1, 1) + logits = model(next, cache: cache) + eval(logits) + } + let decodeSeconds = Date.timeIntervalSinceReferenceDate - decodeStart + XCTAssertTrue(all(isFinite(logits)).item(Bool.self)) + print( + "LFM3 checkpoint prefill_tok_s=\(Double(count) / prefillSeconds), decode_tok_s=\(16 / decodeSeconds), peak_bytes=\(Memory.peakMemory)" + ) + } + + func testPublishedCheckpointReferenceParity() throws { + guard let path = ProcessInfo.processInfo.environment["MLX_LFM3_REFERENCE_FILE"] else { + throw XCTSkip("Set MLX_LFM3_REFERENCE_FILE to the matching FP32 reference outputs") + } + guard !MatmulPrecision.isReducedFloat32 else { + throw XCTSkip("Set MLX_ENABLE_TF32=0 to compare the published model in IEEE FP32") + } + let reference = try loadArrays(url: URL(filePath: path)) + let model = try loadModel() + model.apply { $0.dtype.isFloatingPoint ? $0.asType(.float32) : $0 } + for length in [19, 257, 1024] { + let tokens = try XCTUnwrap(reference["tokens_\(length)"]) + let cache = try model.newCache(parameters: nil) + var hidden: MLXArray? + for start in stride(from: 0, to: length, by: 127) { + hidden = model.hiddenStates( + tokens[0..., start ..< min(start + 127, length)], cache: cache) + eval(hidden!) + eval(cache) + } + let final = try XCTUnwrap(hidden)[0..., (-1)...] + let logits = model.projectLogits(final) + let expected = try XCTUnwrap(reference["logits_\(length)"]) + let error = abs(logits - expected).max().item(Float.self) + let hiddenError = abs(final - (try XCTUnwrap(reference["hidden_\(length)"]))).max() + .item(Float.self) + print( + "LFM3 published FP32 \(length): logits_max_abs=\(error), hidden_max_abs=\(hiddenError)" + ) + XCTAssertLessThan(error, 2e-4) + XCTAssertLessThan(hiddenError, 2e-4) + XCTAssertEqual( + argMax(logits, axis: -1).item(Int.self), argMax(expected, axis: -1).item(Int.self)) + } + } +} diff --git a/Tests/MLXLMTests/LFM3ReferenceTests.swift b/Tests/MLXLMTests/LFM3ReferenceTests.swift new file mode 100644 index 0000000000..006daf6e67 --- /dev/null +++ b/Tests/MLXLMTests/LFM3ReferenceTests.swift @@ -0,0 +1,119 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXNN +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon + +final class LFM3ReferenceTests: XCTestCase { + private func resource(_ name: String, _ extensionName: String) throws -> URL { + try XCTUnwrap(Bundle.module.url(forResource: name, withExtension: extensionName)) + } + + func testLongContextChunking() throws { + guard ProcessInfo.processInfo.environment["MLX_LFM3_LONG_CONTEXT"] == "1" else { + throw XCTSkip("Set MLX_LFM3_LONG_CONTEXT=1 for 4K, 16K and 32K cache checks") + } + let config = try JSONDecoder().decode( + LFM3Configuration.self, + from: Data(contentsOf: resource("lfm3-reference-config", "json"))) + let model = LFM3Model(config) + let weights = try loadArrays(url: resource("lfm3-reference-weights", "safetensors")) + try model.update( + parameters: ModuleParameters.unflattened(model.sanitize(weights: weights)), + verify: [.all]) + for length in [4096, 16384, 32768] { + let tokens = MLXArray((0 ..< length).map { Int32(($0 * 7 + 3) % 16) }).reshaped( + 1, length) + var results = [MLXArray]() + for chunkSize in [257, 512] { + let cache = try model.newCache(parameters: nil) + for start in stride(from: 0, to: length, by: chunkSize) { + let hidden = model.hiddenStates( + tokens[0..., start ..< min(start + chunkSize, length)], cache: cache) + eval(hidden) + } + let output = model(MLXArray([Int32(1)]).reshaped(1, 1), cache: cache) + eval(output) + results.append(output) + for (i, layerCache) in cache.enumerated() { + if config.layerTypes[i] == .conv { + XCTAssertEqual( + (layerCache as? MambaCache)?[0]?.dim(1), config.convLCache - 1) + } else { + XCTAssertEqual(layerCache.offset, length + 1) + if config.layerTypes[i] == .slidingAttention { + XCTAssertLessThanOrEqual( + layerCache.state[0].dim(2), config.slidingWindow) + } + } + } + } + let error = abs(results[0] - results[1]).max().item(Float.self) + print("LFM3 context \(length): final-logit max_abs=\(error)") + XCTAssertLessThan(error, MatmulPrecision.splitTolerance) + XCTAssertTrue(all(isFinite(results[0])).item(Bool.self)) + } + } + + func testOriginalHuggingFaceFloat32Parity() throws { + // CPU pins IEEE FP32, including on devices that use TF32 for GPU matmuls. + try Device.withDefaultDevice(.cpu) { + let config = try JSONDecoder().decode( + LFM3Configuration.self, + from: Data(contentsOf: resource("lfm3-reference-config", "json"))) + let model = LFM3Model(config) + let weights = try loadArrays(url: resource("lfm3-reference-weights", "safetensors")) + try model.update( + parameters: ModuleParameters.unflattened(model.sanitize(weights: weights)), + verify: [.all]) + let reference = try loadArrays(url: resource("lfm3-reference-outputs", "safetensors")) + let tokens = try XCTUnwrap(reference["tokens"]) + + func compare(_ actual: MLXArray, _ key: String) throws { + let expected = try XCTUnwrap(reference[key], key) + XCTAssertEqual(actual.shape, expected.shape, key) + let maximum = abs(actual - expected).max().item(Float.self) + let relative = maximum / max(abs(expected).max().item(Float.self), 1e-8) + print("LFM3 FP32 \(key): max_abs=\(maximum), normalized_max=\(relative)") + XCTAssertLessThan(maximum, 2e-5, key) + } + + var h = model.model.embed(tokens) + try compare(h, "model.embed_tokens") + for (i, layer) in model.model.layers.enumerated() { + let mask = makeAttentionMask( + n: tokens.dim(1), cache: nil, + windowSize: layer.layerType == .slidingAttention ? config.slidingWindow : nil) + let normalized = layer.operatorNorm(h) + if let conv = layer.conv { + try compare(conv(normalized, cache: nil), "model.layers.\(i).conv") + } else if let attention = layer.attention { + try compare( + attention(normalized, mask: mask, cache: nil), "model.layers.\(i).self_attn" + ) + } + h = layer(h, mask: mask, cache: nil) + try compare(h, "model.layers.\(i)") + } + let hidden = model.hiddenStates(tokens, cache: nil) + try compare(hidden, "model.embedding_norm") + let logits = model.projectLogits(hidden) + try compare(logits, "logits") + XCTAssertEqual( + argMax(logits, axis: -1).asArray(Int.self), + argMax(try XCTUnwrap(reference["logits"]), axis: -1).asArray(Int.self)) + + let cache = try model.newCache(parameters: nil) + var outputs = [MLXArray]() + for (start, end) in [(0, 2), (2, 7), (7, 18), (18, 19)] { + outputs.append(model(tokens[0..., start ..< end], cache: cache)) + eval(outputs.last!) + } + try compare(concatenated(outputs, axis: 1), "cached_logits") + } + } +} diff --git a/Tests/MLXLMTests/LFM3Tests.swift b/Tests/MLXLMTests/LFM3Tests.swift index 4c997c6497..a2c1227521 100644 --- a/Tests/MLXLMTests/LFM3Tests.swift +++ b/Tests/MLXLMTests/LFM3Tests.swift @@ -160,6 +160,138 @@ final class LFM3Tests: XCTestCase { XCTAssertThrowsError(try decode(json)) } + func testInvalidDimensionsFailDuringDecoding() throws { + let invalid: [(String, Any)] = [ + ("hidden_size", 0), ("hidden_size", -1), + ("num_attention_heads", 0), ("num_attention_heads", -1), + ("num_key_value_heads", 0), ("num_key_value_heads", 3), + ("head_dim", 0), ("head_dim", -2), ("head_dim", 127), + ("num_hidden_layers", 0), ("num_hidden_layers", -1), + ("vocab_size", 0), ("intermediate_size", -1), + ("sliding_window", 0), ("sliding_window", -1), + ("conv_L_cache", 0), ("conv_L_cache", -1), + ("norm_eps", 0), ("norm_eps", -1), ("max_position_embeddings", 0), + ] + for (key, value) in invalid { + var json = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(realConfigJSON.utf8)) as? [String: Any]) + json[key] = value + // Exercise the inferred head dimension too: this used to divide by zero. + if key == "num_attention_heads" { json.removeValue(forKey: "head_dim") } + let data = try JSONSerialization.data(withJSONObject: json) + XCTAssertThrowsError(try JSONDecoder().decode(LFM3Configuration.self, from: data), key) + { + XCTAssertTrue($0 is DecodingError, "\(key): \($0)") + } + } + } + + func testInvalidRotaryParametersThrow() throws { + for rope in [ + #"{"rope_theta": 0}"#, #"{"rope_theta": -10000}"#, + #"{"rope_theta": 10000, "partial_rotary_factor": -0.1}"#, + #"{"rope_theta": 10000, "partial_rotary_factor": 1.1}"#, + ] { + XCTAssertThrowsError(try tinyConfiguration(fullRope: rope)) + } + var json = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(realConfigJSON.utf8)) as? [String: Any]) + json["rope_parameters"] = ["sliding_attention": ["rope_theta": 10000]] + XCTAssertThrowsError( + try JSONDecoder().decode( + LFM3Configuration.self, from: JSONSerialization.data(withJSONObject: json))) + json.removeValue(forKey: "hidden_size") + XCTAssertThrowsError( + try JSONDecoder().decode( + LFM3Configuration.self, from: JSONSerialization.data(withJSONObject: json))) + } + + func testTokenizerCompatibilityProbes() throws { + XCTAssertNoThrow(try LFM3Model.validateTokenizer(ProbeTokenizer())) + for broken in [".reduce", "line.\r\nThis"] { + XCTAssertThrowsError(try LFM3Model.validateTokenizer(ProbeTokenizer(broken: broken))) { + XCTAssertTrue($0.localizedDescription.contains("ignore_merges")) + } + } + // A custom vocabulary without these byte-level entries is not the affected tokenizer. + XCTAssertNoThrow(try LFM3Model.validateTokenizer(ProbeTokenizer(hasProbeVocabulary: false))) + } + + func testFactoryRejectsIncompatibleTokenizer() async throws { + let directory = FileManager.default.temporaryDirectory.appending( + component: UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let config = try tinyConfiguration() + try JSONEncoder().encode(config).write(to: directory.appending(component: "config.json")) + let model = try tinyModel(config) + try save( + arrays: Dictionary(uniqueKeysWithValues: model.parameters().flattened()), + url: directory.appending(component: "model.safetensors")) + do { + _ = try await LLMModelFactory.shared.load( + from: directory, using: ProbeTokenizerLoader()) + XCTFail("The factory accepted a tokenizer that ignores ignore_merges") + } catch { + XCTAssertTrue(error.localizedDescription.contains("ignore_merges"), "\(error)") + } + } + + private struct ProbeTokenizerLoader: TokenizerLoader { + func load(from directory: URL) async throws -> any Tokenizer { + ProbeTokenizer(broken: ".reduce") + } + } + + private struct ProbeTokenizer: Tokenizer { + var broken: String? = nil + var hasProbeVocabulary = true + let bosToken: String? = nil + let eosToken: String? = nil + let unknownToken: String? = nil + private let vocabulary = [ + "<|startoftext|>": 124894, ".reduce": 96744, "line": 1421, ".čĊ": 64122, "This": 1942, + ] + + func encode(text: String, addSpecialTokens: Bool) -> [Int] { + if text == broken { return [1, 2] } + return text == ".reduce" ? [96744] : [1421, 64122, 1942] + } + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { "" } + func convertTokenToId(_ token: String) -> Int? { + hasProbeVocabulary ? vocabulary[token] : nil + } + func convertIdToToken(_ id: Int) -> String? { nil } + func applyChatTemplate( + messages: [[String: any Sendable]], tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { [] } + } + + func testOfficialXMLToolCallFormat() throws { + let model = try tinyModel() + XCTAssertEqual(model.toolCallFormat, .xmlFunction) + XCTAssertEqual(model.reasoningConfig?.startDelimiter, "") + XCTAssertEqual(model.reasoningConfig?.endDelimiter, "") + // Rendered by LiquidAI's chat_template.jinja, not LFM2's Python-style format. + let payload = """ + + + + Paris + + + + """ + let parser = XMLFunctionParser(startTag: "", endTag: "") + let call = try XCTUnwrap(parser.parse(content: payload, tools: nil)) + XCTAssertEqual(call.function.name, "get_weather") + XCTAssertEqual(call.function.arguments["location"], .string("Paris")) + XCTAssertNil( + parser.parse( + content: payload.replacingOccurrences(of: "", with: ""), tools: nil)) + } + func testRegisteredModelType() async throws { XCTAssertTrue(LLMRegistry.shared.contains(id: "LiquidAI/LFM3-1.7B-MLX-4bit")) let model = try await LLMTypeRegistry.shared.createModel( @@ -236,6 +368,155 @@ final class LFM3Tests: XCTestCase { XCTAssertLessThan(abs(actual - expected).max().item(Float.self), 1e-4) } + func testRotaryFactorsAndLongOffsets() throws { + let headDim = 16 + let x = MLXArray((0 ..< 3 * headDim).map { Float($0 % 17 - 8) / 8 }) + .reshaped(1, 1, 3, headDim) + for factor: Float in [0, 0.25, 0.6, 0.75, 1] { + let config = try tinyConfiguration( + fullRope: "{\"rope_theta\": 1000000, \"partial_rotary_factor\": \(factor)}") + let attention = try XCTUnwrap(try tinyModel(config).model.layers[2].attention) + for offset in [0, 257, 4096, 16384, 32768] { + let angles = Int(factor * Float(headDim)) / 2 + let invFreq = MLXArray( + (0 ..< headDim / 2).map { j in + j < angles ? pow(Float(1_000_000), -Float(2 * j) / Float(headDim)) : 0 + }) + let positions = MLXArray((offset ..< offset + 3).map(Float.init)) + let freqs = positions.expandedDimensions(axis: -1) * invFreq + let emb = concatenated([freqs, freqs], axis: -1) + let halves = split(x, parts: 2, axis: -1) + let rotated = concatenated([-halves[1], halves[0]], axis: -1) + let expected = x * cos(emb) + rotated * sin(emb) + let actual = applyRotaryPosition(attention.rope, to: x, offset: .scalar(offset)) + XCTAssertLessThan( + abs(actual - expected).max().item(Float.self), 1e-3, + "factor \(factor), offset \(offset)") + } + } + } + + func testConvolutionStateMatchesExplicitCausalSum() throws { + for width in [1, 3, 7] { + var json = try XCTUnwrap( + JSONSerialization.jsonObject(with: JSONEncoder().encode(tinyConfiguration())) + as? [String: Any]) + json["conv_L_cache"] = width + json["conv_bias"] = true + json["use_sandwich_norm"] = false + let config = try JSONDecoder().decode( + LFM3Configuration.self, from: JSONSerialization.data(withJSONObject: json)) + let conv = try XCTUnwrap(try tinyModel(config).model.layers[0].conv) + let values: [Float] = (0 ..< 704).map { Float($0 % 19 - 9) / 10 } + let x = MLXArray(values).reshaped(2, 11, 32) + let parts = conv.inProj(x).split(parts: 3, axis: -1) + let bx = parts[0] * parts[2] + let padded = concatenated([MLXArray.zeros([2, width - 1, 32]), bx], axis: 1) + var sum = MLXArray.zeros([2, 11, 32]) + for k in 0 ..< width { + sum = sum + padded[0..., k ..< k + 11, 0...] * conv.conv.weight[0..., k, 0] + } + if let bias = conv.conv.bias { sum = sum + bias } + let expected = conv.outProj(parts[1] * sum) + assertClose(conv(x, cache: nil), expected, atol: 1e-5, reducedAtol: 5e-4) + for chunkSize in [1, 2, 5, 11] { + let cache = MambaCache() + var outputs = [MLXArray]() + for start in stride(from: 0, to: 11, by: chunkSize) { + outputs.append( + conv(x[0..., start ..< min(start + chunkSize, 11)], cache: cache)) + eval(outputs.last!) + } + assertClose(concatenated(outputs, axis: 1), expected, atol: 1e-5, reducedAtol: 5e-4) + let state = try XCTUnwrap(cache[0]) + XCTAssertEqual(state.shape, [2, width - 1, 32]) + if width > 1 { + XCTAssertEqual( + abs(state - bx[0..., (11 - (width - 1))..., 0...]).max().item(Float.self), 0 + ) + } + } + } + } + + func testSlidingWindowBoundariesAndCacheCopy() throws { + var json = try XCTUnwrap( + JSONSerialization.jsonObject(with: JSONEncoder().encode(tinyConfiguration())) + as? [String: Any]) + json["sliding_window"] = 256 + json["conv_L_cache"] = 7 + let config = try JSONDecoder().decode( + LFM3Configuration.self, from: JSONSerialization.data(withJSONObject: json)) + let model = try tinyModel(config) + for length in [256, 257, 512, 1024] { + let tokens = MLXArray((0 ..< 2 * length).map { Int32(($0 * 7 + 3) % 64) }).reshaped( + 2, length) + let expected = model(tokens, cache: nil) + eval(expected) + for chunkSize in [127, 257] { + var cache = try model.newCache(parameters: nil) + var outputs = [MLXArray]() + for start in stride(from: 0, to: length, by: chunkSize) { + outputs.append( + model(tokens[0..., start ..< min(start + chunkSize, length)], cache: cache)) + eval(outputs.last!) + eval(cache) + // Copies model prompt-cache reuse, including convolution state. + cache = cache.map { $0.copy() } + } + XCTAssertLessThan( + abs(concatenated(outputs, axis: 1) - expected).max().item(Float.self), + MatmulPrecision.splitTolerance) + let decode = MLXArray([Int32(1), 2]).reshaped(2, 1) + let actual = model(decode, cache: cache) + let fresh = try model.newCache(parameters: nil) + let oneShot = model(concatenated([tokens, decode], axis: 1), cache: fresh)[ + 0..., length...] + XCTAssertLessThan( + abs(actual - oneShot).max().item(Float.self), MatmulPrecision.splitTolerance) + XCTAssertTrue(all(isFinite(actual)).item(Bool.self)) + } + } + } + + func testConvolutionPreparedLengthsPreserveLastValidState() throws { + var json = try XCTUnwrap( + JSONSerialization.jsonObject(with: JSONEncoder().encode(tinyConfiguration())) + as? [String: Any]) + json["conv_L_cache"] = 7 + json["conv_bias"] = true + let config = try JSONDecoder().decode( + LFM3Configuration.self, from: JSONSerialization.data(withJSONObject: json)) + let conv = try XCTUnwrap(try tinyModel(config).model.layers[0].conv) + let values: [Float] = (0 ..< 768).map { Float($0 % 19 - 9) / 10 } + let x = MLXArray(values).reshaped(3, 8, 32) + let lengths = [0, 3, 8] + for leftPadded in [false, true] { + let independent = lengths.enumerated().map { batch, length in + let cache = MambaCache() + if length > 0 { + let start = leftPadded ? 8 - length : 0 + eval(conv(x[batch ..< batch + 1, start ..< start + length], cache: cache)) + } + return cache + } + for chunkSize in [2, 5, 8] { + let cache = MambaCache(leftPadding: leftPadded ? lengths.map { 8 - $0 } : nil) + withPreparedCache([cache], lengths: leftPadded ? nil : lengths) { + for start in stride(from: 0, to: 8, by: chunkSize) { + eval(conv(x[0..., start ..< min(start + chunkSize, 8)], cache: cache)) + } + } + let next = x[0..., 0 ..< 1] + let expected = concatenated( + independent.enumerated().map { batch, reference in + conv(next[batch ..< batch + 1], cache: reference.copy() as? MambaCache) + }, axis: 0) + assertClose(conv(next, cache: cache), expected, atol: 1e-5, reducedAtol: 1e-4) + } + } + } + func testSanitizeLoadsMLXAndTransformersLayouts() throws { let model = try tinyModel() let parameters = Dictionary(uniqueKeysWithValues: model.parameters().flattened()) @@ -264,6 +545,16 @@ final class LFM3Tests: XCTestCase { } } + func testMalformedConvolutionWeightsThrow() throws { + let model = try tinyModel() + for shape in [[], [32], [32, 3]] { + XCTAssertThrowsError( + try model.sanitize(weights: [ + "model.layers.0.conv.conv.weight": MLXArray.zeros(shape) + ])) + } + } + /// Prefill in one call, in chunks, and one token at a time must give the same logits, /// including past the sliding window where the rotating caches wrap. func testChunkedPrefillAndDecodeMatchOneShot() throws { diff --git a/Tests/MLXLMTests/Resources/lfm3-reference-config.json b/Tests/MLXLMTests/Resources/lfm3-reference-config.json new file mode 100644 index 0000000000..624fa1005a --- /dev/null +++ b/Tests/MLXLMTests/Resources/lfm3-reference-config.json @@ -0,0 +1,57 @@ +{ + "transformers_version": "5.22.1", + "architectures": [ + "Lfm3ForCausalLM" + ], + "output_hidden_states": false, + "return_dict": true, + "dtype": "bfloat16", + "chunk_size_feed_forward": 0, + "is_encoder_decoder": false, + "id2label": { + "0": "LABEL_0", + "1": "LABEL_1" + }, + "label2id": { + "LABEL_0": 0, + "LABEL_1": 1 + }, + "problem_type": null, + "vocab_size": 16, + "hidden_size": 8, + "intermediate_size": 16, + "num_hidden_layers": 3, + "num_attention_heads": 2, + "num_key_value_heads": 1, + "max_position_embeddings": 262144, + "initializer_range": 0.02, + "norm_eps": 1e-05, + "use_cache": true, + "pad_token_id": 0, + "bos_token_id": 1, + "eos_token_id": 2, + "tie_word_embeddings": true, + "rope_parameters": { + "full_attention": { + "partial_rotary_factor": 0.5, + "rope_theta": 1000000.0, + "rope_type": "default" + }, + "sliding_attention": { + "rope_theta": 10000, + "rope_type": "default" + } + }, + "conv_bias": true, + "conv_L_cache": 7, + "layer_types": [ + "conv", + "full_attention", + "sliding_attention" + ], + "head_dim": 8, + "sliding_window": 4, + "use_sandwich_norm": true, + "model_type": "lfm3", + "output_attentions": false +} diff --git a/Tests/MLXLMTests/Resources/lfm3-reference-outputs.safetensors b/Tests/MLXLMTests/Resources/lfm3-reference-outputs.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..2abe1ebf5466556ee05c65514139463400486af9 GIT binary patch literal 15752 zcmeI(d036x-#_psQ8cJ%qDeGJnl$cveQrr*N~lapvnfR~Pe~|}qCzDkb4Z4!eXq46 zq)3P|MCMM&Os4!kop0xQ&UL=$InVVx&-MH7+1K^Hx_7P5XRW>NUHjGUu31*<_uF!# z>C@+i#RP>0#RN^CZsfe&XhGD%=#a4K(P4{bEtnM*Y2<7a6k;>P(LTu5F5EiEI>gG> z*2XC`I5Z?QEIcSU)G^rJ&cQJ>G$_cy$iiq|bXdqAW#JJ~K{2*A_}Q4~pvVQ`QPFe5 zq8DJlA(l2amexiqEsR2fLS}}APLGJ1F)IeYvfL;%X6d{z9OC|a-GZ4x9rvc%SXet* zSldstF#3I&QQ_eW!aBxJwX(3Wv$dIqo&LuyIvQBmIojKGbeS6!8Wv$0Ha8d-6%#cl zEb_lvl;gjzsiT*Ly_KWYUmAwaikvY$5;x($c$|OJvZI@YgN>8@f3%DUT8f)#Y4zW4 z*3rkpaftQr+xD*q{6{m(kf_K-|NV{~%`BW8Y#je>dDj2^W*vPjtgW2v{&Ye**Jo|H zAS@z$dQeOZJ}dw6x$-xA_%~|S?qnD0e5$Xnh;+8DhM(>GLnc9U7;9W1FZfmB( z@GikDbcqS%4~u2p9zG`}){EHI%$4NEi|^F){t#|YwT3V^--w=A98W&aD4~nGmXX2> zA4%CzZD`s2np9*(Q)9p9cBA$ z&Jj)T_3Y5KX)q`L1I=G!02Pr|EM&$-viWW`y_ca$h@%?Sb1f5=4c$XlMjWQ*DN5ih zr^W^*D1+VjvFrkG46k;+=8R5+K#96Dc{Obow_?glaeHFwuN%aCyBn*U(MUWOU!~92c|mg*UG8k733T~s z$Kr=b!+;A0Y`@MKvTt$>Tc0+T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xqeLFZ5aHOHQqd5TGvd(! zn_T1#G6X5jVnOQB*|OrF8f1cto$%wXG*>KhQ*8OgROD)#C-AF}3aj7hhjQ3&6uL&N;pWVoBkXx{LnOPe3%%jG zOL#uQUQjTfLDGui#afBET&_nSA!5QsQQLkwnx1-9=y`3OAm`PctekBv%zL@H%za); z*%6ZramLj?g2AwQ!FW-s$Z^64E_{uPFfvX-2=sLqU47pluPfCTt2)cj7hZCl`Ltu) zlxL%aVT0ERg&|U$>=tjKt;K}PlQarx#v8b8Hman+##s;@J1eeTblatO`e*TgC0XJ{ zVXuTe)l)<|dKH{|@IoP~XM%93XSHb2wBdrWQ?uyI;wQosn9unt$&<}5h;VINv$%HO z3zz2kU4=ykC&k`BKM6Z@^+hR>`dn#ckocW!ityPkm&-V7D;&SRlWSYsBIxj2x$uit z#IEIXnWB*`CrR7s99&{6>iu+=p!oitFj7o}j(>Mn#7JYhVN@{k7$uAxraMLkqk!qS Qb;T%Sx?p->{(sf~KLb?2&Hw-a literal 0 HcmV?d00001 diff --git a/Tests/MLXLMTests/Resources/lfm3-reference-weights.safetensors b/Tests/MLXLMTests/Resources/lfm3-reference-weights.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..a549f1f66d731fceb42376b34fe2ed76bde45209 GIT binary patch literal 14968 zcmeI0zi!%46vq7seFWtB$g(fS*pZqtRUI={sv>ZUNoWWr;3kctNDLh^bjZ-5Lx;Xd z5s%jIkU|VT;K-&!a*gy=N@e}-z32bEN3V><@5UUQw@;(6Yh6YClhedJxG}rQ^(ZnA z%(r!Ak~ujI`L7R-NB%LH-7pE;aj!Rtk_rCTriP=AZ^=B5yV1ak&Ob)ob`qaO!%0CR zc;wj1-GFxc!;|(f9-rr8gcw*Vsr+9ez@XyD7h$C$~zld#k!2149 zY@T6#a;TZLEOW`Jr>(ob=l-xg8pofl-P?vCGfrbFIj+5R-%E7f)?ro2EFhC|np>?M ze@ULQbpg#(Qfm9oSLnR0`_j&tOv?3A!MCz`FG6JZ;_+2DMzT1$VJPPd!$}3AZPr&% zxho(%ysUE>PIXrd%JmiMxhu$LU^uz9Z3|)F>kSKMDI>wHr|QYd`tc|lheJ2D+H2PC()qS4wGbP zorFpBQ1kN&vyuuk^Qqwr4cxIF7db0j9T*M1P&C*1i-wzb0FQm)`Ty$;eLdsmgh2U4# zehMkWDR7kJ)yEoFvXC+#i}=|xr1nxs8BKx0V7j^!t{nV$h_ez2%y0_aX13p?Pf)6m zGM$1T$4JEsDWh?3v~#Rfs**17eCHMBinO81)Y1hVYc$zXw>AD5#&l*F9jFD>AOo8J z!T&=Bi+`{2H#CQgLwpCdpbj);%__!owMXSUy<_?78{{wa4Z4HAL-)`R=qEISc75~W zYX<6D4f6+8w`GPgmbH*@m?m1$i z$`L*1)2bHgQwyaTLzg}voxO$H_u}WvoSEl0`e6&&)+d*9`Y(JVeY@FDH|P9ay_df= z(0gl8#R6=gnLT#B{qXycbZ1NVn7saU2gc@`Q@WRx zeGf?ACDZ%5$GW_?Io=x#__PMKAl>|1<+YxEU*0RWy}K-Pg~!vfIao2C?;DPeHF236 z9QU;uq8FN1Z*Y3v0}umKNcTA*ofA6QV~V`j_3YJs&oI(=5$O$Xd5_?`ko0Zd{YYY_ t?<{5K^KJWD&V4QPwwlI0u9{8to^5u$J#cPL539GY8f>8JJwWfd|1S(yJum 1: + value = value.transpose(0, 2, 1) + state[name] = torch.from_numpy(np.array(value.astype(mx.float32))) + model.load_state_dict(state, strict=True, assign=True) + model.eval() + del arrays, state + gc.collect() + mx.clear_cache() + outputs = {} + for length in [19, 257, 1024]: + tokens = torch.tensor([(i * 7 + 3) % config.vocab_size for i in range(length)]).reshape(1, length) + start = time.monotonic() + with torch.no_grad(): + hidden = model.model(tokens, use_cache=False).last_hidden_state + logits = model.lm_head(hidden[:, -1:]) + outputs[f"tokens_{length}"] = tokens.to(torch.int32) + outputs[f"hidden_{length}"] = hidden[:, -1:].contiguous() + outputs[f"logits_{length}"] = logits.contiguous() + print(f"{length} tokens: {time.monotonic() - start:.3f}s, top1={logits.argmax(-1).item()}") + save_file(outputs, str(args.output), metadata={ + "source_revision": REVISION, "precision": "float32 dequantized", + "checkpoint_revision": "d0ca73dcfa70ce18733754a492cdc1fb0123262d", + }) + + +if __name__ == "__main__": + main() diff --git a/scripts/lfm3-reference.py b/scripts/lfm3-reference.py new file mode 100644 index 0000000000..6162e33017 --- /dev/null +++ b/scripts/lfm3-reference.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Regenerate the small FP32 LFM3 oracle using LiquidAI's original implementation. + +Requires torch, transformers==5.22.1, huggingface_hub and safetensors. +Run from the repository root: python scripts/lfm3-reference.py +The downloaded Python code is pinned and runs on the CPU without model weights. +""" + +import json +from pathlib import Path +from tempfile import TemporaryDirectory + +import torch +from huggingface_hub import snapshot_download +from safetensors.torch import save_file +from transformers import AutoConfig, AutoModelForCausalLM + +REVISION = "ac2586a34f1a1c03329dbdcdefabd8b6478ddaa7" +OUTPUT = Path("Tests/MLXLMTests/Resources") + + +def main(): + torch.set_num_threads(4) + torch.manual_seed(7) + with TemporaryDirectory(prefix="lfm3-reference-") as source: + snapshot_download( + "LiquidAI/LFM3-1.7B", revision=REVISION, + allow_patterns=["config.json", "*.py"], local_dir=source, + ) + config = AutoConfig.from_pretrained(source, trust_remote_code=True) + config.hidden_size = 8 + config.intermediate_size = 16 + config.num_hidden_layers = 3 + config.num_attention_heads = 2 + config.num_key_value_heads = 1 + config.head_dim = 8 + config.vocab_size = 16 + config.layer_types = ["conv", "full_attention", "sliding_attention"] + config.sliding_window = 4 + config.conv_bias = True + config.pad_token_id = 0 + config.bos_token_id = 1 + config.eos_token_id = 2 + config._attn_implementation = "eager" + model = AutoModelForCausalLM.from_config(config, trust_remote_code=True).float().eval() + with torch.no_grad(): + for i, parameter in enumerate(model.parameters()): + values = (torch.arange(parameter.numel()).reshape(parameter.shape) + i * 3) % 17 + parameter.copy_((values.float() - 8) / 32) + if parameter.ndim == 1 and parameter.numel() == 8: + parameter.add_(1) + weights = {k: v.detach().contiguous().clone() for k, v in model.state_dict().items()} + outputs = {} + handles = [] + for name, module in model.named_modules(): + if name in ["model.embed_tokens", "model.embedding_norm"] or ( + name.startswith("model.layers.") and name.count(".") == 2 + ) or name.endswith((".conv", ".self_attn")) and name.count(".") == 3: + def hook(_module, _args, result, name=name): + tensor = result[0] if isinstance(result, tuple) else result + outputs[name] = tensor.detach().contiguous().clone() + handles.append(module.register_forward_hook(hook)) + tokens = torch.tensor([(i * 7 + 3) % 16 for i in range(38)]).reshape(2, 19) + with torch.no_grad(): + outputs["logits"] = model(tokens, use_cache=False).logits + for handle in handles: + handle.remove() + outputs["tokens"] = tokens.to(torch.int32) + with torch.no_grad(): + cache = None + logits = [] + for start, end in [(0, 2), (2, 7), (7, 18), (18, 19)]: + out = model(tokens[:, start:end], past_key_values=cache, use_cache=True) + logits.append(out.logits) + cache = out.past_key_values + outputs["cached_logits"] = torch.cat(logits, dim=1) + OUTPUT.mkdir(exist_ok=True) + save_file(weights, OUTPUT / "lfm3-reference-weights.safetensors") + save_file({k: v.contiguous() for k, v in outputs.items()}, OUTPUT / "lfm3-reference-outputs.safetensors", + metadata={"source_revision": REVISION, "precision": "float32", "transformers": "5.22.1"}) + config_dict = config.to_dict() + for key in ["_name_or_path", "auto_map"]: + config_dict.pop(key, None) + (OUTPUT / "lfm3-reference-config.json").write_text(json.dumps(config_dict, indent=2) + "\n") + error = (outputs["cached_logits"] - outputs["logits"]).abs().max().item() + print(f"Reference cached/uncached maximum absolute error: {error:.9g}") + print("Outputs:", ", ".join(outputs)) + + +if __name__ == "__main__": + main() diff --git a/skills/mlx-swift-lm/references/supported-models.md b/skills/mlx-swift-lm/references/supported-models.md index 1665a3cc68..f854984d01 100644 --- a/skills/mlx-swift-lm/references/supported-models.md +++ b/skills/mlx-swift-lm/references/supported-models.md @@ -100,7 +100,7 @@ LLMRegistry.mellum2_1_12b_a2_5b_thinking_6bit // mlx-community/Mellum2.1-12B-A2 | `smollm3` | SmolLM 3 | | `ernie4_5` | ERNIE 4.5 | | `lfm2`, `lfm2_moe` | LFM 2 | -| `lfm3` | LFM 3 | +| `lfm3` | LFM 3 text backbone (no vision, audio, or Omni wrapper) | | `exaone4` | EXAONE 4 | | `olmo2`, `olmo3`, `olmoe` | OLMo | | `falcon_h1` | Falcon H1 | @@ -113,6 +113,31 @@ LLMRegistry.mellum2_1_12b_a2_5b_thinking_6bit // mlx-community/Mellum2.1-12B-A2 | `gpt_oss` | GPT OSS | | `minicpm` | MiniCPM | +### LFM3 tokenizer requirements + +LFM3 needs BPE `ignore_merges: true` and regex splitting by Unicode code point. +Swift Transformers 1.3.5 does not include fixes +[#397](https://github.com/huggingface/swift-transformers/pull/397) and +[#398](https://github.com/huggingface/swift-transformers/pull/398). Supply a +`TokenizerLoader` containing both fixes or another compatible implementation; +the model factory rejects known incompatible tokenization at load time. The core +package does not depend on Swift Transformers. + +The official text checkpoint uses XML function calls (`.xmlFunction`), with +`` and `` framing. It does not use the LFM2 format. + +Small FP32 reference fixtures run in the unit suite without downloads. Regenerate +them with `python scripts/lfm3-reference.py`, which pins LiquidAI's source revision. +For a downloaded official 4-bit checkpoint, `scripts/lfm3-checkpoint-reference.py` +exports matching FP32 logits from the original Hugging Face implementation. +`LFM3CheckpointTests` reads `MLX_LFM3_CHECKPOINT` and `MLX_LFM3_REFERENCE_FILE`; +set `MLX_ENABLE_TF32=0` in the test process for that parity check. +`MLX_LFM3_LONG_CONTEXT=1` enables the synthetic 4K/16K/32K cache tests. +The integration project's tokenizer goldens are opt-in with +`MLX_RUN_LFM3_TOKENIZER=1`; `MLX_LFM3_TOKENIZER_DIRECTORY` selects local tokenizer +files instead of downloading them. Set these variables in the test process +(for example, when invoking `xcrun xctest` directly or in Xcode's test scheme). + ## VLM Families ### Qwen VL From ac7e54a770e01e60d18c65d381fba91ef541e638 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Garc=C3=ADa=20Pizarro?= <81751965+alvarogarciapiz@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:04:24 +0100 Subject: [PATCH 4/7] chore(lfm3): remove incorrect Apple attribution from new tests --- .../IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift | 2 -- Tests/MLXLMTests/LFM3CheckpointTests.swift | 2 -- Tests/MLXLMTests/LFM3ReferenceTests.swift | 2 -- 3 files changed, 6 deletions(-) diff --git a/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift b/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift index 8d923a1436..306b3385df 100644 --- a/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift @@ -1,5 +1,3 @@ -// Copyright © 2026 Apple Inc. - import Foundation import Testing import Tokenizers diff --git a/Tests/MLXLMTests/LFM3CheckpointTests.swift b/Tests/MLXLMTests/LFM3CheckpointTests.swift index 4aab8aa15d..80d2afd748 100644 --- a/Tests/MLXLMTests/LFM3CheckpointTests.swift +++ b/Tests/MLXLMTests/LFM3CheckpointTests.swift @@ -1,5 +1,3 @@ -// Copyright © 2026 Apple Inc. - import Foundation import MLX import MLXNN diff --git a/Tests/MLXLMTests/LFM3ReferenceTests.swift b/Tests/MLXLMTests/LFM3ReferenceTests.swift index 006daf6e67..4bd688b80f 100644 --- a/Tests/MLXLMTests/LFM3ReferenceTests.swift +++ b/Tests/MLXLMTests/LFM3ReferenceTests.swift @@ -1,5 +1,3 @@ -// Copyright © 2026 Apple Inc. - import Foundation import MLX import MLXNN From 02a21abbfdd94a155b0978a5bd89979e6b5c1c52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Garc=C3=ADa=20Pizarro?= <81751965+alvarogarciapiz@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:55:19 +0100 Subject: [PATCH 5/7] fix(lfm3): align validation and tests with review feedback --- .../LFM3CheckpointTests.swift | 254 +++++++ .../LFM3TokenizerIntegrationTests.swift | 2 +- Libraries/MLXLLM/LLMModel.swift | 6 + Libraries/MLXLLM/LLMModelFactory.swift | 4 +- Libraries/MLXLLM/Models/LFM3.swift | 2 +- Package.swift | 3 - Tests/MLXLMTests/LFM3CheckpointTests.swift | 93 --- Tests/MLXLMTests/LFM3ReferenceTests.swift | 55 +- Tests/MLXLMTests/LFM3ReferenceValues.swift | 703 ++++++++++++++++++ Tests/MLXLMTests/LFM3Tests.swift | 111 +-- .../Resources/lfm3-reference-config.json | 57 -- .../lfm3-reference-outputs.safetensors | Bin 15752 -> 0 bytes .../lfm3-reference-weights.safetensors | Bin 14968 -> 0 bytes scripts/lfm3-reference.py | 91 --- .../references/supported-models.md | 27 +- .../lfm3-checkpoint-reference.py | 2 +- tools/lfm3-reference.py | 100 +++ 17 files changed, 1118 insertions(+), 392 deletions(-) create mode 100644 IntegrationTesting/IntegrationTestingTests/LFM3CheckpointTests.swift delete mode 100644 Tests/MLXLMTests/LFM3CheckpointTests.swift create mode 100644 Tests/MLXLMTests/LFM3ReferenceValues.swift delete mode 100644 Tests/MLXLMTests/Resources/lfm3-reference-config.json delete mode 100644 Tests/MLXLMTests/Resources/lfm3-reference-outputs.safetensors delete mode 100644 Tests/MLXLMTests/Resources/lfm3-reference-weights.safetensors delete mode 100644 scripts/lfm3-reference.py rename {scripts => tools}/lfm3-checkpoint-reference.py (97%) create mode 100644 tools/lfm3-reference.py diff --git a/IntegrationTesting/IntegrationTestingTests/LFM3CheckpointTests.swift b/IntegrationTesting/IntegrationTestingTests/LFM3CheckpointTests.swift new file mode 100644 index 0000000000..22c588d8c3 --- /dev/null +++ b/IntegrationTesting/IntegrationTestingTests/LFM3CheckpointTests.swift @@ -0,0 +1,254 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN +import XCTest + +final class LFM3CheckpointTests: XCTestCase { + private var usesReducedFloat32: Bool { + let a = withRandomState(MLXRandom.RandomState(seed: 0)) { MLXRandom.normal([64, 512]) } + let b = withRandomState(MLXRandom.RandomState(seed: 1)) { MLXRandom.normal([512, 64]) } + let cpu = matmul(a, b, stream: .cpu) + let gpu = matmul(a, b, stream: .gpu) + return abs(gpu - cpu).max().item(Float.self) / abs(cpu).max().item(Float.self) > 1e-5 + } + + private func loadModel() throws -> LFM3Model { + guard let path = ProcessInfo.processInfo.environment["MLX_LFM3_CHECKPOINT"] else { + throw XCTSkip("Set MLX_LFM3_CHECKPOINT to a local published LFM3 checkpoint") + } + let directory = URL(filePath: path) + let data = try Data(contentsOf: directory.appending(component: "config.json")) + let config = try JSONDecoder().decode(LFM3Configuration.self, from: data) + let baseConfig = try JSONDecoder().decode(BaseConfiguration.self, from: data) + let start = Date.timeIntervalSinceReferenceDate + let model = LFM3Model(config) + try loadWeights( + modelDirectory: directory, model: model, + perLayerQuantization: baseConfig.perLayerQuantization) + eval(model) + print("LFM3 checkpoint load_seconds=\(Date.timeIntervalSinceReferenceDate - start)") + return model + } + + func testPublishedCheckpointPrefillAndDecode() throws { + let model = try loadModel() + Memory.peakMemory = 0 + let count = 1024 + let tokens = MLXArray((0 ..< count).map { Int32(($0 * 7 + 3) % model.vocabularySize) }) + .reshaped(1, count) + let cache = try model.newCache(parameters: nil) + let start = Date.timeIntervalSinceReferenceDate + var hidden: MLXArray? + for offset in stride(from: 0, to: count, by: 256) { + hidden = model.hiddenStates(tokens[0..., offset ..< offset + 256], cache: cache) + eval(hidden!) + eval(cache) + } + var logits = model.projectLogits(try XCTUnwrap(hidden)[0..., (-1)...]) + eval(logits) + let prefillSeconds = Date.timeIntervalSinceReferenceDate - start + let decodeStart = Date.timeIntervalSinceReferenceDate + for _ in 0 ..< 16 { + let next = argMax(logits[0, -1]).reshaped(1, 1) + logits = model(next, cache: cache) + eval(logits) + } + let decodeSeconds = Date.timeIntervalSinceReferenceDate - decodeStart + XCTAssertTrue(all(isFinite(logits)).item(Bool.self)) + print( + "LFM3 checkpoint prefill_tok_s=\(Double(count) / prefillSeconds), decode_tok_s=\(16 / decodeSeconds), peak_bytes=\(Memory.peakMemory)" + ) + } + + func testPublishedCheckpointReferenceParity() throws { + guard let path = ProcessInfo.processInfo.environment["MLX_LFM3_REFERENCE_FILE"] else { + throw XCTSkip("Set MLX_LFM3_REFERENCE_FILE to the matching FP32 reference outputs") + } + guard !usesReducedFloat32 else { + throw XCTSkip("Set MLX_ENABLE_TF32=0 to compare the published model in IEEE FP32") + } + let reference = try loadArrays(url: URL(filePath: path)) + let model = try loadModel() + model.apply { $0.dtype.isFloatingPoint ? $0.asType(.float32) : $0 } + for length in [19, 257, 1024] { + let tokens = try XCTUnwrap(reference["tokens_\(length)"]) + let cache = try model.newCache(parameters: nil) + var hidden: MLXArray? + for start in stride(from: 0, to: length, by: 127) { + hidden = model.hiddenStates( + tokens[0..., start ..< min(start + 127, length)], cache: cache) + eval(hidden!) + eval(cache) + } + let final = try XCTUnwrap(hidden)[0..., (-1)...] + let logits = model.projectLogits(final) + let expected = try XCTUnwrap(reference["logits_\(length)"]) + let error = abs(logits - expected).max().item(Float.self) + let hiddenError = abs(final - (try XCTUnwrap(reference["hidden_\(length)"]))).max() + .item(Float.self) + print( + "LFM3 published FP32 \(length): logits_max_abs=\(error), hidden_max_abs=\(hiddenError)" + ) + XCTAssertLessThan(error, 2e-4) + XCTAssertLessThan(hiddenError, 2e-4) + XCTAssertEqual( + argMax(logits, axis: -1).item(Int.self), argMax(expected, axis: -1).item(Int.self)) + } + } + + private func tinyConfiguration( + tieWordEmbeddings: Bool = true, intermediateSize: Int = 48 + ) throws -> LFM3Configuration { + try JSONDecoder().decode( + LFM3Configuration.self, + from: Data( + """ + { + "model_type": "lfm3", "vocab_size": 64, "hidden_size": 32, + "intermediate_size": \(intermediateSize), "num_hidden_layers": 6, + "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 16, + "norm_eps": 1e-5, "conv_L_cache": 3, "conv_bias": false, + "sliding_window": 4, "use_sandwich_norm": true, + "tie_word_embeddings": \(tieWordEmbeddings), + "layer_types": ["conv", "sliding_attention", "full_attention", + "conv", "sliding_attention", "full_attention"] + } + """.utf8)) + } + + private func tinyModel(_ configuration: LFM3Configuration) -> LFM3Model { + withRandomState(MLXRandom.RandomState(seed: 7)) { LFM3Model(configuration) } + } + + func testFactoryRejectsIncompatibleTokenizer() async throws { + let directory = FileManager.default.temporaryDirectory.appending( + component: UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let config = try tinyConfiguration() + try JSONEncoder().encode(config).write(to: directory.appending(component: "config.json")) + let model = tinyModel(config) + try save( + arrays: Dictionary(uniqueKeysWithValues: model.parameters().flattened()), + url: directory.appending(component: "model.safetensors")) + do { + _ = try await LLMModelFactory.shared.load( + from: directory, using: ProbeTokenizerLoader()) + XCTFail("The factory accepted a tokenizer that ignores ignore_merges") + } catch { + XCTAssertTrue(error.localizedDescription.contains("ignore_merges"), "\(error)") + } + } + + private struct ProbeTokenizerLoader: TokenizerLoader { + func load(from directory: URL) async throws -> any Tokenizer { + ProbeTokenizer(broken: ".reduce") + } + } + + private struct ProbeTokenizer: Tokenizer { + var broken: String? = nil + var hasProbeVocabulary = true + let bosToken: String? = nil + let eosToken: String? = nil + let unknownToken: String? = nil + private let vocabulary = [ + "<|startoftext|>": 124894, ".reduce": 96744, "line": 1421, ".čĊ": 64122, "This": 1942, + ] + + func encode(text: String, addSpecialTokens: Bool) -> [Int] { + if text == broken { return [1, 2] } + return text == ".reduce" ? [96744] : [1421, 64122, 1942] + } + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { "" } + func convertTokenToId(_ token: String) -> Int? { + hasProbeVocabulary ? vocabulary[token] : nil + } + func convertIdToToken(_ id: Int) -> String? { nil } + func applyChatTemplate( + messages: [[String: any Sendable]], tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { [] } + } + + // MARK: - Mixed-precision checkpoint + + /// An MLX conversion wrapped in `language_model` with 4-bit attention and conv, 6-bit + /// MLP, and an 8-bit untied `lm_head`, declared per layer in `config.json`. The prefix + /// mapping must rename tensors and settings together or strict loading fails. + func testLoadsMixedPrecisionWrappedCheckpoint() throws { + let groupSize = 32 + let configuration = try tinyConfiguration(tieWordEmbeddings: false, intermediateSize: 64) + let reference = tinyModel(configuration) + + let bits = { (path: String) in + path == "lm_head" ? 8 : path.contains(".feed_forward.") ? 6 : 4 + } + var arrays = [String: MLXArray]() + var quantizedPaths = [String]() + for (path, module) in reference.leafModules().flattened() { + let weight: MLXArray + switch module { + case let linear as Linear: weight = linear.weight + case let embedding as Embedding: weight = embedding.weight + default: continue + } + let (wq, scales, biases) = quantized(weight, groupSize: groupSize, bits: bits(path)) + arrays["language_model.\(path).weight"] = wq + arrays["language_model.\(path).scales"] = scales + arrays["language_model.\(path).biases"] = biases + quantizedPaths.append(path) + } + for (key, value) in reference.parameters().flattened() { + let module = key.split(separator: ".").dropLast().joined(separator: ".") + if !quantizedPaths.contains(module) { + arrays["language_model.\(key)"] = value + } + } + arrays["vision_tower.proj.weight"] = MLXArray.zeros([4, 4]) + XCTAssertTrue(quantizedPaths.contains("lm_head")) + XCTAssertTrue(quantizedPaths.contains { $0.hasSuffix("conv.in_proj") }) + + // Per-layer entries use the checkpoint's own (wrapped) names. + let overrides = + quantizedPaths.filter { bits($0) != 4 }.map { path in + #""language_model.\#(path)": {"group_size": \#(groupSize), "bits": \#(bits(path))}"# + } + [#""vision_tower.proj": {"group_size": \#(groupSize), "bits": 8}"#] + let baseConfiguration = try JSONDecoder().decode( + BaseConfiguration.self, + from: Data( + """ + { + "model_type": "lfm3", + "quantization": { + "group_size": \(groupSize), "bits": 4, + \(overrides.joined(separator: ",\n")) + } + } + """.utf8)) + + let directory = FileManager.default.temporaryDirectory + .appending(component: "lfm3-mixed-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + try save(arrays: arrays, url: directory.appending(component: "model.safetensors")) + + let model = LFM3Model(configuration) + try loadWeights( + modelDirectory: directory, model: model, + perLayerQuantization: baseConfiguration.perLayerQuantization) + + let modules = Dictionary(uniqueKeysWithValues: model.leafModules().flattened()) + for path in quantizedPaths { + let module = try XCTUnwrap(modules[path] as? Quantized, path) + XCTAssertEqual(module.bits, bits(path), path) + XCTAssertEqual(module.groupSize, groupSize, path) + } + + let logits = model(MLXArray([Int32(1), 2, 3, 4, 5]).reshaped(1, 5), cache: nil) + XCTAssertEqual(logits.shape, [1, 5, 64]) + XCTAssertFalse(any(isNaN(logits)).item(Bool.self)) + } +} diff --git a/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift b/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift index 306b3385df..486a57e028 100644 --- a/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift @@ -2,7 +2,7 @@ import Foundation import Testing import Tokenizers -// Opt in after selecting a tokenizer with swift-transformers #397 and #398. +// Opt in with swift-transformers 1.4.0 or another tokenizer with #397 and #398. @Suite( .serialized, .enabled(if: ProcessInfo.processInfo.environment["MLX_RUN_LFM3_TOKENIZER"] == "1")) struct LFM3TokenizerIntegrationTests { diff --git a/Libraries/MLXLLM/LLMModel.swift b/Libraries/MLXLLM/LLMModel.swift index b9ab78bcc8..b571509d3f 100644 --- a/Libraries/MLXLLM/LLMModel.swift +++ b/Libraries/MLXLLM/LLMModel.swift @@ -11,6 +11,10 @@ public protocol LLMModel: LanguageModel, LoRAModel { /// /// The default implementation returns `DefaultMessageGenerator`. func messageGenerator(tokenizer: Tokenizer) -> MessageGenerator + + /// Check tokenizer requirements before the factory returns a model context. + /// The default implementation accepts any tokenizer. + func validate(tokenizer: Tokenizer) throws } extension LLMModel { @@ -64,4 +68,6 @@ extension LLMModel { public func messageGenerator(tokenizer: Tokenizer) -> MessageGenerator { DefaultMessageGenerator() } + + public func validate(tokenizer: Tokenizer) throws {} } diff --git a/Libraries/MLXLLM/LLMModelFactory.swift b/Libraries/MLXLLM/LLMModelFactory.swift index 897fbe39bd..657058d9c1 100644 --- a/Libraries/MLXLLM/LLMModelFactory.swift +++ b/Libraries/MLXLLM/LLMModelFactory.swift @@ -783,8 +783,8 @@ public final class LLMModelFactory: GenericModelFactory { let tokenizer = try await tokenizerTask - if model is LFM3Model { - try LFM3Model.validateTokenizer(tokenizer) + if let model = model as? LLMModel { + try model.validate(tokenizer: tokenizer) } let messageGenerator: any MessageGenerator diff --git a/Libraries/MLXLLM/Models/LFM3.swift b/Libraries/MLXLLM/Models/LFM3.swift index 47e111f771..ace115f888 100644 --- a/Libraries/MLXLLM/Models/LFM3.swift +++ b/Libraries/MLXLLM/Models/LFM3.swift @@ -72,7 +72,7 @@ public class LFM3Model: Module, LLMModel, KVCacheDimensionProvider { try model.newCache(parameters: parameters) } - package static func validateTokenizer(_ tokenizer: any Tokenizer) throws { + public func validate(tokenizer: any Tokenizer) throws { guard tokenizer.convertTokenToId("<|startoftext|>") == 124894, tokenizer.convertTokenToId(".reduce") == 96744 else { return } diff --git a/Package.swift b/Package.swift index f0f9236f27..ee50b82c0e 100644 --- a/Package.swift +++ b/Package.swift @@ -185,9 +185,6 @@ let package = Package( ], resources: [ .process("Resources/1080p_30.mov"), .process("Resources/audio_only.mov"), - .process("Resources/lfm3-reference-config.json"), - .process("Resources/lfm3-reference-weights.safetensors"), - .process("Resources/lfm3-reference-outputs.safetensors"), ] ), .macro( diff --git a/Tests/MLXLMTests/LFM3CheckpointTests.swift b/Tests/MLXLMTests/LFM3CheckpointTests.swift deleted file mode 100644 index 80d2afd748..0000000000 --- a/Tests/MLXLMTests/LFM3CheckpointTests.swift +++ /dev/null @@ -1,93 +0,0 @@ -import Foundation -import MLX -import MLXNN -import XCTest - -@testable import MLXLLM -@testable import MLXLMCommon - -final class LFM3CheckpointTests: XCTestCase { - private func loadModel() throws -> LFM3Model { - guard let path = ProcessInfo.processInfo.environment["MLX_LFM3_CHECKPOINT"] else { - throw XCTSkip("Set MLX_LFM3_CHECKPOINT to a local published LFM3 checkpoint") - } - let directory = URL(filePath: path) - let data = try Data(contentsOf: directory.appending(component: "config.json")) - let config = try JSONDecoder().decode(LFM3Configuration.self, from: data) - let baseConfig = try JSONDecoder().decode(BaseConfiguration.self, from: data) - let start = Date.timeIntervalSinceReferenceDate - let model = LFM3Model(config) - try loadWeights( - modelDirectory: directory, model: model, - perLayerQuantization: baseConfig.perLayerQuantization) - eval(model) - print("LFM3 checkpoint load_seconds=\(Date.timeIntervalSinceReferenceDate - start)") - return model - } - - func testPublishedCheckpointPrefillAndDecode() throws { - let model = try loadModel() - Memory.peakMemory = 0 - let count = 1024 - let tokens = MLXArray((0 ..< count).map { Int32(($0 * 7 + 3) % model.vocabularySize) }) - .reshaped(1, count) - let cache = try model.newCache(parameters: nil) - let start = Date.timeIntervalSinceReferenceDate - var hidden: MLXArray? - for offset in stride(from: 0, to: count, by: 256) { - hidden = model.hiddenStates(tokens[0..., offset ..< offset + 256], cache: cache) - eval(hidden!) - eval(cache) - } - var logits = model.projectLogits(try XCTUnwrap(hidden)[0..., (-1)...]) - eval(logits) - let prefillSeconds = Date.timeIntervalSinceReferenceDate - start - let decodeStart = Date.timeIntervalSinceReferenceDate - for _ in 0 ..< 16 { - let next = argMax(logits[0, -1]).reshaped(1, 1) - logits = model(next, cache: cache) - eval(logits) - } - let decodeSeconds = Date.timeIntervalSinceReferenceDate - decodeStart - XCTAssertTrue(all(isFinite(logits)).item(Bool.self)) - print( - "LFM3 checkpoint prefill_tok_s=\(Double(count) / prefillSeconds), decode_tok_s=\(16 / decodeSeconds), peak_bytes=\(Memory.peakMemory)" - ) - } - - func testPublishedCheckpointReferenceParity() throws { - guard let path = ProcessInfo.processInfo.environment["MLX_LFM3_REFERENCE_FILE"] else { - throw XCTSkip("Set MLX_LFM3_REFERENCE_FILE to the matching FP32 reference outputs") - } - guard !MatmulPrecision.isReducedFloat32 else { - throw XCTSkip("Set MLX_ENABLE_TF32=0 to compare the published model in IEEE FP32") - } - let reference = try loadArrays(url: URL(filePath: path)) - let model = try loadModel() - model.apply { $0.dtype.isFloatingPoint ? $0.asType(.float32) : $0 } - for length in [19, 257, 1024] { - let tokens = try XCTUnwrap(reference["tokens_\(length)"]) - let cache = try model.newCache(parameters: nil) - var hidden: MLXArray? - for start in stride(from: 0, to: length, by: 127) { - hidden = model.hiddenStates( - tokens[0..., start ..< min(start + 127, length)], cache: cache) - eval(hidden!) - eval(cache) - } - let final = try XCTUnwrap(hidden)[0..., (-1)...] - let logits = model.projectLogits(final) - let expected = try XCTUnwrap(reference["logits_\(length)"]) - let error = abs(logits - expected).max().item(Float.self) - let hiddenError = abs(final - (try XCTUnwrap(reference["hidden_\(length)"]))).max() - .item(Float.self) - print( - "LFM3 published FP32 \(length): logits_max_abs=\(error), hidden_max_abs=\(hiddenError)" - ) - XCTAssertLessThan(error, 2e-4) - XCTAssertLessThan(hiddenError, 2e-4) - XCTAssertEqual( - argMax(logits, axis: -1).item(Int.self), argMax(expected, axis: -1).item(Int.self)) - } - } -} diff --git a/Tests/MLXLMTests/LFM3ReferenceTests.swift b/Tests/MLXLMTests/LFM3ReferenceTests.swift index 4bd688b80f..1e72a03de5 100644 --- a/Tests/MLXLMTests/LFM3ReferenceTests.swift +++ b/Tests/MLXLMTests/LFM3ReferenceTests.swift @@ -7,22 +7,29 @@ import XCTest @testable import MLXLMCommon final class LFM3ReferenceTests: XCTestCase { - private func resource(_ name: String, _ extensionName: String) throws -> URL { - try XCTUnwrap(Bundle.module.url(forResource: name, withExtension: extensionName)) + private func makeModel() throws -> LFM3Model { + let config = try JSONDecoder().decode( + LFM3Configuration.self, from: Data(LFM3ReferenceValues.configuration.utf8)) + let model = LFM3Model(config) + var weights = [String: MLXArray]() + // Match the Python oracle independently of module traversal order. + for (i, entry) in model.parameters().flattened().sorted(by: { $0.0 < $1.0 }).enumerated() { + let (name, parameter) = entry + let shift: Float = parameter.ndim == 1 && parameter.size == config.hiddenSize ? 1 : 0 + let values = (0 ..< parameter.size).map { Float(($0 + i * 3) % 17 - 8) / 32 + shift } + weights[name] = MLXArray(values, parameter.shape) + } + try model.update(parameters: ModuleParameters.unflattened(weights), verify: [.all]) + eval(model) + return model } func testLongContextChunking() throws { guard ProcessInfo.processInfo.environment["MLX_LFM3_LONG_CONTEXT"] == "1" else { throw XCTSkip("Set MLX_LFM3_LONG_CONTEXT=1 for 4K, 16K and 32K cache checks") } - let config = try JSONDecoder().decode( - LFM3Configuration.self, - from: Data(contentsOf: resource("lfm3-reference-config", "json"))) - let model = LFM3Model(config) - let weights = try loadArrays(url: resource("lfm3-reference-weights", "safetensors")) - try model.update( - parameters: ModuleParameters.unflattened(model.sanitize(weights: weights)), - verify: [.all]) + let model = try makeModel() + let config = model.configuration for length in [4096, 16384, 32768] { let tokens = MLXArray((0 ..< length).map { Int32(($0 * 7 + 3) % 16) }).reshaped( 1, length) @@ -60,23 +67,16 @@ final class LFM3ReferenceTests: XCTestCase { func testOriginalHuggingFaceFloat32Parity() throws { // CPU pins IEEE FP32, including on devices that use TF32 for GPU matmuls. try Device.withDefaultDevice(.cpu) { - let config = try JSONDecoder().decode( - LFM3Configuration.self, - from: Data(contentsOf: resource("lfm3-reference-config", "json"))) - let model = LFM3Model(config) - let weights = try loadArrays(url: resource("lfm3-reference-weights", "safetensors")) - try model.update( - parameters: ModuleParameters.unflattened(model.sanitize(weights: weights)), - verify: [.all]) - let reference = try loadArrays(url: resource("lfm3-reference-outputs", "safetensors")) - let tokens = try XCTUnwrap(reference["tokens"]) + let model = try makeModel() + let config = model.configuration + let tokens = MLXArray((0 ..< 38).map { Int32(($0 * 7 + 3) % 16) }).reshaped(2, 19) func compare(_ actual: MLXArray, _ key: String) throws { - let expected = try XCTUnwrap(reference[key], key) - XCTAssertEqual(actual.shape, expected.shape, key) + let values = try XCTUnwrap(LFM3ReferenceValues.outputs[key], key) + XCTAssertEqual(actual.size, values.count, key) + let expected = MLXArray(values, actual.shape) let maximum = abs(actual - expected).max().item(Float.self) - let relative = maximum / max(abs(expected).max().item(Float.self), 1e-8) - print("LFM3 FP32 \(key): max_abs=\(maximum), normalized_max=\(relative)") + print("LFM3 FP32 \(key): max_abs=\(maximum)") XCTAssertLessThan(maximum, 2e-5, key) } @@ -103,7 +103,10 @@ final class LFM3ReferenceTests: XCTestCase { try compare(logits, "logits") XCTAssertEqual( argMax(logits, axis: -1).asArray(Int.self), - argMax(try XCTUnwrap(reference["logits"]), axis: -1).asArray(Int.self)) + argMax( + MLXArray(try XCTUnwrap(LFM3ReferenceValues.outputs["logits"]), logits.shape), + axis: -1 + ).asArray(Int.self)) let cache = try model.newCache(parameters: nil) var outputs = [MLXArray]() @@ -111,7 +114,7 @@ final class LFM3ReferenceTests: XCTestCase { outputs.append(model(tokens[0..., start ..< end], cache: cache)) eval(outputs.last!) } - try compare(concatenated(outputs, axis: 1), "cached_logits") + try compare(concatenated(outputs, axis: 1), "logits") } } } diff --git a/Tests/MLXLMTests/LFM3ReferenceValues.swift b/Tests/MLXLMTests/LFM3ReferenceValues.swift new file mode 100644 index 0000000000..6782c4a948 --- /dev/null +++ b/Tests/MLXLMTests/LFM3ReferenceValues.swift @@ -0,0 +1,703 @@ +// Generated by tools/lfm3-reference.py; do not edit values by hand. +// LiquidAI/LFM3-1.7B ac2586a34f1a1c03329dbdcdefabd8b6478ddaa7; PyTorch CPU FP32, transformers 5.22.1. + +enum LFM3ReferenceValues { + static let configuration = """ + { + "model_type": "lfm3", + "hidden_size": 8, + "intermediate_size": 16, + "num_hidden_layers": 3, + "num_attention_heads": 2, + "num_key_value_heads": 1, + "head_dim": 8, + "vocab_size": 16, + "layer_types": [ + "conv", + "full_attention", + "sliding_attention" + ], + "sliding_window": 4, + "conv_L_cache": 7, + "conv_bias": true, + "norm_eps": 1e-05, + "use_sandwich_norm": true, + "tie_word_embeddings": true, + "pad_token_id": 0, + "bos_token_id": 1, + "eos_token_id": 2, + "rope_parameters": { + "full_attention": { + "rope_type": "default", + "rope_theta": 1000000.0, + "partial_rotary_factor": 0.5 + }, + "sliding_attention": { + "rope_type": "default", + "rope_theta": 10000.0 + } + } + } + """ + + static let outputs: [String: [Float]] = [ + "logits": [ + -2.560890317e-01, -4.518305659e-01, 5.563533306e-01, -4.273628891e-01, 4.670754075e-01, + -4.028952122e-01, 1.169006348e+00, -3.784275055e-01, 6.791160703e-01, -3.539597988e-01, + 6.964339018e-01, -3.294920623e-01, 2.811487913e-01, -3.050244451e-01, -1.871974170e-01, + -2.805567086e-01, 1.778570265e-01, -6.071811318e-01, 7.731676698e-01, -5.090513825e-01, + 5.145912766e-01, -4.109215736e-01, 1.042554379e+00, -3.127918243e-01, 5.180730820e-01, + -2.146620452e-01, 5.653204918e-01, -1.165322959e-01, -2.869856954e-01, -1.840251125e-02, + -4.894518256e-01, 7.972723991e-02, -3.322068751e-01, -4.890422225e-01, 5.414526463e-01, + -4.694378376e-01, 5.633859038e-01, -4.498333931e-01, 1.210364342e+00, -4.302289486e-01, + 8.391785026e-01, -4.106245637e-01, 7.662834525e-01, -3.910201192e-01, 4.033501446e-01, + -3.714157045e-01, -1.197473705e-01, -3.518112898e-01, 2.908770144e-01, -5.680198669e-01, + 8.773109913e-01, -4.606577456e-01, 4.558041692e-01, -3.532956243e-01, 9.029447436e-01, + -2.459335327e-01, 3.578447998e-01, -1.385714263e-01, 3.395329118e-01, -3.120931052e-02, + -4.736886024e-01, 7.615278661e-02, -5.372242332e-01, 1.835148782e-01, -4.707183838e-01, + -4.171750546e-01, 4.705618322e-01, -4.238679409e-01, 4.799448252e-01, -4.305608869e-01, + 1.082267404e+00, -4.372537732e-01, 9.498797059e-01, -4.439467192e-01, 9.001639485e-01, + -4.506396353e-01, 4.626751840e-01, -4.573325515e-01, 6.050959229e-02, -4.640254676e-01, + 2.380317152e-01, -5.630897880e-01, 8.926221132e-01, -4.629496038e-01, 5.038233399e-01, + -3.628093898e-01, 9.445665479e-01, -2.626692057e-01, 3.051265180e-01, -1.625290215e-01, + 3.422501385e-01, -6.238884106e-02, -3.475004733e-01, 3.775135428e-02, -5.148971081e-01, + 1.378915310e-01, -5.219186544e-01, -4.047608078e-01, 3.972659111e-01, -4.194055498e-01, + 4.354168773e-01, -4.340502620e-01, 1.049364567e+00, -4.486950040e-01, 9.450095892e-01, + -4.633397460e-01, 9.465757608e-01, -4.779844582e-01, 6.213839650e-01, -4.926291704e-01, + 1.651570499e-01, -5.072739124e-01, 2.197086364e-01, -5.851027369e-01, 1.036245942e+00, + -4.845013320e-01, 6.700240970e-01, -3.838998675e-01, 8.814580441e-01, -2.832984626e-01, + 2.940095067e-01, -1.826970428e-01, 2.879789472e-01, -8.209563047e-02, -3.585049212e-01, + 1.850580424e-02, -4.812342227e-01, 1.191072017e-01, -5.330874324e-01, -3.906089067e-01, + 4.125663340e-01, -4.084187150e-01, 4.357793033e-01, -4.262285233e-01, 1.027106166e+00, + -4.440383315e-01, 9.331373572e-01, -4.618481398e-01, 8.674497604e-01, -4.796579778e-01, + 6.573249102e-01, -4.974677265e-01, 1.960684955e-01, -5.152775049e-01, -2.061509192e-01, + -4.856692255e-01, 8.033385277e-01, -4.507294595e-01, 6.288790703e-01, -4.157896638e-01, + 1.011965752e+00, -3.808498979e-01, 6.241431236e-01, -3.459101021e-01, 6.081334352e-01, + -3.109703064e-01, 1.077284217e-01, -2.760305405e-01, -1.503884196e-01, -2.410907149e-01, + -4.444030225e-01, -4.128978252e-01, 5.221280456e-01, -4.168359935e-01, 5.002732277e-01, + -4.207741320e-01, 1.073708892e+00, -4.247122705e-01, 7.985158563e-01, -4.286504388e-01, + 7.484546900e-01, -4.325885475e-01, 5.314136744e-01, -4.365267158e-01, 9.231917560e-02, + -4.404648840e-01, -4.637224078e-01, -2.727808058e-01, 4.809819460e-01, -2.966485023e-01, + 3.972158432e-01, -3.205161989e-01, 1.010242820e+00, -3.443838954e-01, 6.542574167e-01, + -3.682516217e-01, 7.443408966e-01, -3.921193480e-01, 2.761844993e-01, -4.159870148e-01, + -4.583597183e-05, -4.398547411e-01, -2.692250311e-01, -4.529233575e-01, 6.640498042e-01, + -4.299611151e-01, 5.951160192e-01, -4.069988132e-01, 1.144489884e+00, -3.840365410e-01, + 6.419465542e-01, -3.610742092e-01, 5.934562087e-01, -3.381118774e-01, 2.771555185e-01, + -3.151496649e-01, -1.906603873e-01, -2.921873629e-01, 3.728267848e-01, -5.680493116e-01, + 9.226587415e-01, -4.504398406e-01, 5.451917052e-01, -3.328303099e-01, 9.128211141e-01, + -2.152207792e-01, 5.610261485e-02, -9.761127830e-02, 1.127975956e-01, 1.999823935e-02, + -3.659531772e-01, 1.376077682e-01, -6.194583178e-01, 2.552172840e-01, -1.297008842e-01, + -5.422888398e-01, 7.448235750e-01, -4.907153249e-01, 6.381319761e-01, -4.391418397e-01, + 1.164523005e+00, -3.875683546e-01, 6.098871827e-01, -3.359948397e-01, 5.459832549e-01, + -2.844213843e-01, 2.301939428e-01, -2.328478843e-01, -3.157269359e-01, -1.812744290e-01, + 7.002423704e-02, -5.620005727e-01, 6.810399294e-01, -4.829974473e-01, 4.318973124e-01, + -4.039943516e-01, 1.099095941e+00, -3.249912560e-01, 4.649390876e-01, -2.459881455e-01, + 5.601989031e-01, -1.669850498e-01, 5.582428724e-02, -8.798196167e-02, -4.380982518e-01, + -8.978858590e-03, -3.079440296e-01, -5.255146027e-01, 5.561183691e-01, -4.983182847e-01, + 5.255094171e-01, -4.711219370e-01, 1.148341417e+00, -4.439256489e-01, 8.254325986e-01, + -4.167293012e-01, 7.377447486e-01, -3.895330131e-01, 5.705642700e-01, -3.623366654e-01, + -6.043614447e-02, -3.351403475e-01, 4.566543922e-02, -5.320295691e-01, 6.810529232e-01, + -4.598177075e-01, 3.830276132e-01, -3.876058459e-01, 1.027110815e+00, -3.153939247e-01, + 5.046721101e-01, -2.431820631e-01, 6.436660290e-01, -1.709702015e-01, -6.341724843e-02, + -9.875833243e-02, -3.832322955e-01, -2.654644474e-02, -3.860856593e-01, + -4.989446998e-01, + 4.731692374e-01, -4.848373234e-01, 5.136559010e-01, -4.707299471e-01, 1.158368111e+00, + -4.566225410e-01, 9.444459677e-01, -4.425151348e-01, 8.031157851e-01, -4.284077585e-01, + 6.333557367e-01, -4.143003523e-01, -3.042258322e-02, -4.001929462e-01, -3.245635331e-02, + -7.490312457e-01, 7.725462317e-01, -6.594593525e-01, 1.252158403e+00, -5.698875189e-01, + 9.770199060e-01, -4.803156555e-01, 7.803775668e-01, -3.907437921e-01, 4.282981455e-01, + -3.011719584e-01, 3.435379565e-01, -2.116000950e-01, -1.986410618e-01, -1.220282465e-01, + -3.018703759e-01, -5.606005788e-01, 7.274416089e-01, -5.282593369e-01, 8.449555635e-01, + -4.959180355e-01, 1.070420980e+00, -4.635767937e-01, 7.503243089e-01, -4.312354922e-01, + 6.424427032e-01, -3.988941908e-01, 5.008597970e-01, -3.665529490e-01, -6.238368154e-02, + -3.342116773e-01, 1.142154634e-01, -6.946703792e-01, 1.010651112e+00, -5.935596824e-01, + 8.105139136e-01, -4.924489260e-01, 1.066862822e+00, -3.913382292e-01, 5.358910561e-01, + -2.902274728e-01, 3.995020688e-01, -1.891167462e-01, -1.430895180e-03, -8.800601214e-02, + -4.141617715e-01, 1.310472935e-02, -4.751736224e-01, -5.034452677e-01, 4.934528172e-01, + -4.999113083e-01, 7.706332207e-01, -4.963773489e-01, 1.009069562e+00, -4.928433895e-01, + 9.362261295e-01, -4.893094003e-01, 7.795796394e-01, -4.857754707e-01, 7.685017586e-01, + -4.822414517e-01, 1.533006281e-01, -4.787075222e-01, 2.295766920e-01, -6.327622533e-01, + 1.071992278e+00, -5.249698758e-01, 6.991869807e-01, -4.171774983e-01, 8.855822086e-01, + -3.093851507e-01, 3.200193644e-01, -2.015927583e-01, 2.846959233e-01, -9.380039573e-02, + -2.628459036e-01, 1.399196126e-02, -4.437413216e-01, 1.217843145e-01, -5.151152015e-01, + -4.360478818e-01, 4.376162887e-01, -4.459312856e-01, 5.098723173e-01, -4.558147192e-01, + 1.022501469e+00, -4.656981230e-01, 9.638120532e-01, -4.755815566e-01, 8.520069718e-01, + -4.854649901e-01, 7.281135917e-01, -4.953483641e-01, 1.924758106e-01, -5.052318573e-01, + -1.857551783e-01, -5.063362122e-01, 8.267185688e-01, -4.662635922e-01, 6.413547993e-01, + -4.261909723e-01, 1.003188014e+00, -3.861182928e-01, 6.074396372e-01, -3.460457027e-01, + 5.925151706e-01, -3.059730530e-01, 1.327161789e-01, -2.659004629e-01, -1.431123316e-01, + -2.258278131e-01, -3.814263642e-01, -4.469805062e-01, 5.879709125e-01, -4.387862384e-01, + 5.226033926e-01, -4.305919707e-01, 1.072464108e+00, -4.223977327e-01, 7.590687275e-01, + -4.142034650e-01, 7.039648890e-01, -4.060091972e-01, 4.959065914e-01, -3.978148997e-01, + 4.102706909e-02, -3.896206617e-01, -3.049106896e-01, -3.806938231e-01, 6.363743544e-01, + -3.712209165e-01, 4.582994282e-01, -3.617480397e-01, 1.025666952e+00, -3.522751331e-01, + 6.027799249e-01, -3.428022563e-01, 6.635748148e-01, -3.333294094e-01, 1.886056066e-01, + -3.238565326e-01, -9.991391003e-02, -3.143835664e-01, -1.863801181e-01, + -4.885761440e-01, + 7.366188169e-01, -4.508016407e-01, 5.870874524e-01, -4.130271375e-01, 1.117054343e+00, + -3.752526045e-01, 5.880238414e-01, -3.374781013e-01, 5.283271074e-01, -2.997035682e-01, + 2.262978405e-01, -2.619291246e-01, -2.197556496e-01, -2.241545916e-01, 3.375028074e-01, + -5.737078190e-01, 9.043588042e-01, -4.598065019e-01, 5.092918277e-01, -3.459052145e-01, + 9.342823029e-01, -2.320038676e-01, 1.168977618e-01, -1.181025282e-01, 1.631666422e-01, + -4.201201722e-03, -3.028127551e-01, 1.097001284e-01, -5.746525526e-01, 2.236014605e-01, + -1.228756756e-01, -5.460719466e-01, 7.484204769e-01, -4.931724072e-01, 5.978053808e-01, + -4.402728975e-01, 1.143178463e+00, -3.873733580e-01, 6.077592373e-01, -3.344738185e-01, + 5.396886468e-01, -2.815743089e-01, 2.498490214e-01, -2.286747694e-01, -2.774651647e-01, + -1.757752150e-01, 2.381131798e-02, -5.367071033e-01, 6.472002268e-01, -4.666422904e-01, + 3.939077854e-01, -3.965774775e-01, 1.097698212e+00, -3.265126944e-01, 4.883338213e-01, + -2.564478517e-01, 5.828876495e-01, -1.863830984e-01, 9.966574609e-02, -1.163182780e-01, + -3.948905468e-01, -4.625345767e-02, -2.774085104e-01, -5.335249305e-01, 5.834445953e-01, + -5.015103817e-01, 5.213868618e-01, -4.694958329e-01, 1.145076632e+00, -4.374813139e-01, + 8.066841960e-01, -4.054667056e-01, 7.115700245e-01, -3.734521568e-01, 5.389528871e-01, + -3.414376676e-01, -9.237487614e-02, -3.094230890e-01, 2.165694349e-02, -5.107921362e-01, + 6.596863866e-01, -4.442360401e-01, 3.556260169e-01, -3.776799142e-01, 1.022437453e+00, + -3.111237586e-01, 5.055391192e-01, -2.445676178e-01, 6.471369267e-01, -1.780114621e-01, + -4.876712710e-02, -1.114553288e-01, -3.632019758e-01, -4.489921033e-02, + -3.492651284e-01, + -5.116364956e-01, 5.110988021e-01, -4.913400710e-01, 5.142094493e-01, -4.710436463e-01, + 1.158452868e+00, -4.507472217e-01, 9.229266644e-01, -4.304508269e-01, 7.707965970e-01, + -4.101543725e-01, 5.960780382e-01, -3.898579776e-01, -6.757213175e-02, -3.695615828e-01, + 1.852326244e-01, -5.496766567e-01, 8.209580779e-01, -4.578130245e-01, 3.955731690e-01, + -3.659493625e-01, 9.526905417e-01, -2.740856707e-01, 4.365626872e-01, -1.822220087e-01, + 4.378339648e-01, -9.035835415e-02, -2.871814370e-01, 1.505305059e-03, -4.748983979e-01, + 9.336896986e-02, -4.286465049e-01, -4.330022931e-01, 4.717731774e-01, -4.324578047e-01, + 3.861968219e-01, -4.319133461e-01, 1.051078439e+00, -4.313688576e-01, 9.726445079e-01, + -4.308243990e-01, 9.024693966e-01, -4.302798808e-01, 4.937752187e-01, -4.297354817e-01, + 3.302887082e-02, -4.291910231e-01, 1.858590841e-01, -5.187903047e-01, 8.319330215e-01, + -4.307090938e-01, 4.237950146e-01, -3.426279426e-01, 9.485986829e-01, -2.545467615e-01, + 3.199582994e-01, -1.664656103e-01, 3.652305901e-01, -7.838442922e-02, -3.041316867e-01, + 9.696742520e-03, -4.803219736e-01, 9.777791798e-02, + ], + "model.embed_tokens": [ + -3.125000000e-02, 0.000000000e+00, 3.125000000e-02, 6.250000000e-02, 9.375000000e-02, + 1.250000000e-01, 1.562500000e-01, 1.875000000e-01, 1.250000000e-01, 1.562500000e-01, + 1.875000000e-01, 2.187500000e-01, 2.500000000e-01, -2.500000000e-01, -2.187500000e-01, + -1.875000000e-01, 0.000000000e+00, 3.125000000e-02, 6.250000000e-02, 9.375000000e-02, + 1.250000000e-01, 1.562500000e-01, 1.875000000e-01, 2.187500000e-01, 1.562500000e-01, + 1.875000000e-01, 2.187500000e-01, 2.500000000e-01, -2.500000000e-01, -2.187500000e-01, + -1.875000000e-01, -1.562500000e-01, -2.187500000e-01, -1.875000000e-01, + -1.562500000e-01, + -1.250000000e-01, -9.375000000e-02, -6.250000000e-02, -3.125000000e-02, 0.000000000e+00, + 1.875000000e-01, 2.187500000e-01, 2.500000000e-01, -2.500000000e-01, -2.187500000e-01, + -1.875000000e-01, -1.562500000e-01, -1.250000000e-01, -1.875000000e-01, + -1.562500000e-01, + -1.250000000e-01, -9.375000000e-02, -6.250000000e-02, -3.125000000e-02, 0.000000000e+00, + 3.125000000e-02, 2.187500000e-01, 2.500000000e-01, -2.500000000e-01, -2.187500000e-01, + -1.875000000e-01, -1.562500000e-01, -1.250000000e-01, -9.375000000e-02, + -1.562500000e-01, + -1.250000000e-01, -9.375000000e-02, -6.250000000e-02, -3.125000000e-02, 0.000000000e+00, + 3.125000000e-02, 6.250000000e-02, 2.500000000e-01, -2.500000000e-01, -2.187500000e-01, + -1.875000000e-01, -1.562500000e-01, -1.250000000e-01, -9.375000000e-02, + -6.250000000e-02, + -1.250000000e-01, -9.375000000e-02, -6.250000000e-02, -3.125000000e-02, 0.000000000e+00, + 3.125000000e-02, 6.250000000e-02, 9.375000000e-02, -2.500000000e-01, -2.187500000e-01, + -1.875000000e-01, -1.562500000e-01, -1.250000000e-01, -9.375000000e-02, + -6.250000000e-02, + -3.125000000e-02, -9.375000000e-02, -6.250000000e-02, -3.125000000e-02, 0.000000000e+00, + 3.125000000e-02, 6.250000000e-02, 9.375000000e-02, 1.250000000e-01, 6.250000000e-02, + 9.375000000e-02, 1.250000000e-01, 1.562500000e-01, 1.875000000e-01, 2.187500000e-01, + 2.500000000e-01, -2.500000000e-01, -6.250000000e-02, -3.125000000e-02, 0.000000000e+00, + 3.125000000e-02, 6.250000000e-02, 9.375000000e-02, 1.250000000e-01, 1.562500000e-01, + 9.375000000e-02, 1.250000000e-01, 1.562500000e-01, 1.875000000e-01, 2.187500000e-01, + 2.500000000e-01, -2.500000000e-01, -2.187500000e-01, -3.125000000e-02, 0.000000000e+00, + 3.125000000e-02, 6.250000000e-02, 9.375000000e-02, 1.250000000e-01, 1.562500000e-01, + 1.875000000e-01, 1.250000000e-01, 1.562500000e-01, 1.875000000e-01, 2.187500000e-01, + 2.500000000e-01, -2.500000000e-01, -2.187500000e-01, -1.875000000e-01, 0.000000000e+00, + 3.125000000e-02, 6.250000000e-02, 9.375000000e-02, 1.250000000e-01, 1.562500000e-01, + 1.875000000e-01, 2.187500000e-01, 1.562500000e-01, 1.875000000e-01, 2.187500000e-01, + 2.500000000e-01, -2.500000000e-01, -2.187500000e-01, -1.875000000e-01, -1.562500000e-01, + -2.187500000e-01, -1.875000000e-01, -1.562500000e-01, -1.250000000e-01, + -9.375000000e-02, + -6.250000000e-02, -3.125000000e-02, 0.000000000e+00, 1.875000000e-01, 2.187500000e-01, + 2.500000000e-01, -2.500000000e-01, -2.187500000e-01, -1.875000000e-01, -1.562500000e-01, + -1.250000000e-01, -1.875000000e-01, -1.562500000e-01, -1.250000000e-01, + -9.375000000e-02, + -6.250000000e-02, -3.125000000e-02, 0.000000000e+00, 3.125000000e-02, 2.187500000e-01, + 2.500000000e-01, -2.500000000e-01, -2.187500000e-01, -1.875000000e-01, -1.562500000e-01, + -1.250000000e-01, -9.375000000e-02, -1.562500000e-01, -1.250000000e-01, + -9.375000000e-02, + -6.250000000e-02, -3.125000000e-02, 0.000000000e+00, 3.125000000e-02, 6.250000000e-02, + 2.500000000e-01, -2.500000000e-01, -2.187500000e-01, -1.875000000e-01, -1.562500000e-01, + -1.250000000e-01, -9.375000000e-02, -6.250000000e-02, -1.250000000e-01, + -9.375000000e-02, + -6.250000000e-02, -3.125000000e-02, 0.000000000e+00, 3.125000000e-02, 6.250000000e-02, + 9.375000000e-02, -2.500000000e-01, -2.187500000e-01, -1.875000000e-01, -1.562500000e-01, + -1.250000000e-01, -9.375000000e-02, -6.250000000e-02, -3.125000000e-02, + -9.375000000e-02, + -6.250000000e-02, -3.125000000e-02, 0.000000000e+00, 3.125000000e-02, 6.250000000e-02, + 9.375000000e-02, 1.250000000e-01, 6.250000000e-02, 9.375000000e-02, 1.250000000e-01, + 1.562500000e-01, 1.875000000e-01, 2.187500000e-01, 2.500000000e-01, -2.500000000e-01, + -6.250000000e-02, -3.125000000e-02, 0.000000000e+00, 3.125000000e-02, 6.250000000e-02, + 9.375000000e-02, 1.250000000e-01, 1.562500000e-01, 9.375000000e-02, 1.250000000e-01, + 1.562500000e-01, 1.875000000e-01, 2.187500000e-01, 2.500000000e-01, -2.500000000e-01, + -2.187500000e-01, -3.125000000e-02, 0.000000000e+00, 3.125000000e-02, 6.250000000e-02, + 9.375000000e-02, 1.250000000e-01, 1.562500000e-01, 1.875000000e-01, 1.250000000e-01, + 1.562500000e-01, 1.875000000e-01, 2.187500000e-01, 2.500000000e-01, -2.500000000e-01, + -2.187500000e-01, -1.875000000e-01, 0.000000000e+00, 3.125000000e-02, 6.250000000e-02, + 9.375000000e-02, 1.250000000e-01, 1.562500000e-01, 1.875000000e-01, 2.187500000e-01, + 1.562500000e-01, 1.875000000e-01, 2.187500000e-01, 2.500000000e-01, -2.500000000e-01, + -2.187500000e-01, -1.875000000e-01, -1.562500000e-01, -2.187500000e-01, + -1.875000000e-01, + -1.562500000e-01, -1.250000000e-01, -9.375000000e-02, -6.250000000e-02, + -3.125000000e-02, + 0.000000000e+00, 1.875000000e-01, 2.187500000e-01, 2.500000000e-01, -2.500000000e-01, + -2.187500000e-01, -1.875000000e-01, -1.562500000e-01, -1.250000000e-01, + ], + "model.embedding_norm": [ + 1.483246446e+00, -2.141094655e-01, 1.275225163e+00, -9.682033658e-01, -1.345875021e-02, + -8.277698755e-01, -9.276496768e-01, -5.902466774e-01, 9.358698726e-01, -6.714468598e-01, + 8.090981245e-01, -1.171973825e+00, -9.577861428e-02, -1.789055824e+00, -5.658276677e-01, + -5.910378098e-01, 1.607632995e+00, 4.383723252e-03, 1.180939317e+00, -7.356052399e-01, + -1.741166562e-01, -7.200709581e-01, -1.021556616e+00, -7.689481974e-01, 9.017822742e-01, + -9.955178499e-01, 6.395829916e-01, -1.228163838e+00, -2.365628332e-01, -1.732863188e+00, + -3.216899335e-01, -4.621549547e-01, 1.784420013e+00, 3.026060015e-02, 1.146381974e+00, + -2.366018444e-01, -8.098415285e-02, -8.109098673e-01, -7.444191575e-01, + -8.739742041e-01, + 1.043671012e+00, -9.203556776e-01, 6.411350369e-01, -1.392150998e+00, -1.186194047e-01, + -1.486853242e+00, -5.035987496e-01, -4.677139521e-01, 1.757796288e+00, 9.938016534e-02, + 1.183232784e+00, -1.688665003e-01, 3.051475249e-02, -5.845591426e-01, -8.312135339e-01, + -1.017653465e+00, 1.347644210e+00, -8.787263036e-01, 2.086259723e-01, -1.295152903e+00, + -2.007190436e-01, -1.406278133e+00, -4.203871787e-01, -5.742520094e-01, 1.813578367e+00, + 7.721938193e-02, 1.146610260e+00, -1.433583051e-01, -9.012271464e-02, -3.620048463e-01, + -8.347230554e-01, -1.037285209e+00, 1.834446311e+00, -3.941631615e-01, 6.553353071e-01, + -7.957880497e-01, -9.590498358e-02, -1.007707834e+00, -5.516359806e-01, + -7.626549006e-01, + 1.826765537e+00, -3.372545913e-02, 1.086821318e+00, -5.105974078e-01, -8.681988716e-02, + -4.011347592e-01, -8.191178441e-01, -9.361707568e-01, 1.823194504e+00, -1.127499565e-01, + 1.198860645e+00, -6.251627803e-01, 2.144962847e-01, -8.363081217e-01, -4.750354886e-01, + -4.235286117e-01, 1.713529468e+00, -1.729806662e-01, 9.908923507e-01, -9.891870618e-01, + -1.344990879e-01, -6.386126876e-01, -9.238177538e-01, -5.801178217e-01, 8.135951757e-01, + -9.319088459e-01, 4.706256986e-01, -1.834029198e+00, -1.146626323e-01, -1.122560501e+00, + -6.985688210e-01, -3.459953964e-01, 1.549084187e+00, -2.979106605e-01, 8.937742114e-01, + -1.141099930e+00, -2.173692286e-01, -6.915065050e-01, -1.124695301e+00, + -6.206284165e-01, + 1.001435399e+00, -6.176860332e-01, 1.107191563e+00, -1.342418671e+00, 3.060079552e-02, + -1.098122716e+00, -1.078448296e+00, -5.306512713e-01, 1.575277328e+00, -1.088099927e-01, + 1.121196628e+00, -6.590214372e-01, -2.162526250e-01, -3.658856452e-01, -1.238958597e+00, + -9.778279662e-01, 1.060095310e+00, -6.969170570e-01, 1.076463819e+00, -1.119342327e+00, + 1.257073134e-01, -1.466908574e+00, -7.379330397e-01, -5.519454479e-01, 1.590865731e+00, + 4.965508357e-02, 1.187021017e+00, -4.292322099e-01, -2.925883830e-01, -3.461034596e-01, + -1.276020169e+00, -9.350342155e-01, 1.346693158e+00, 7.341935635e-01, -6.865136027e-01, + -5.387561321e-01, -8.313435912e-01, -3.281544447e-01, -1.189178109e+00, + -1.373240232e+00, + 1.876650810e+00, 1.603250206e-01, 3.635276854e-01, -6.634124517e-01, -2.639489770e-01, + -3.273867667e-01, -1.121100664e+00, -1.059575438e+00, 1.497082353e+00, -5.670551062e-01, + 2.922131121e-01, -1.189802408e+00, -4.470582306e-01, -9.450234175e-01, -9.672312737e-01, + -9.086683989e-01, 1.816644549e+00, 5.150991678e-01, 4.421693981e-01, -1.437694877e-01, + -3.015159667e-01, -2.750471234e-02, -1.164677858e+00, -1.249531865e+00, 1.382820249e+00, + -9.046545029e-01, 1.479583383e-01, -1.267492175e+00, -2.693944573e-01, -1.233570218e+00, + -5.434123278e-01, -7.616105676e-01, 1.811981082e+00, 1.546154618e-01, 9.835529923e-01, + -9.187004715e-02, -1.918525845e-01, -2.146070153e-01, -9.896551967e-01, + -1.145895243e+00, + 1.830402017e+00, -4.243506193e-01, 6.056669950e-01, -8.203691244e-01, -1.035238951e-01, + -9.409348369e-01, -5.946373940e-01, -8.345772028e-01, 1.809323311e+00, -1.384692341e-01, + 1.019607544e+00, -6.053451896e-01, -1.191494763e-01, -4.070636630e-01, -8.716683388e-01, + -9.494515061e-01, 1.753999352e+00, -3.530311286e-01, 1.050154567e+00, -8.138539195e-01, + 9.660606831e-02, -9.118909240e-01, -5.609269142e-01, -5.641894937e-01, 1.666304827e+00, + -3.525759578e-01, 9.264799953e-01, -1.066927195e+00, -1.834753007e-01, -6.396306157e-01, + -9.107350111e-01, -6.482249498e-01, 8.526206017e-01, -9.580579400e-01, 5.855793953e-01, + -1.753008604e+00, -1.273080856e-01, -1.091540217e+00, -7.261009812e-01, + -4.270266891e-01, + 1.540511370e+00, -3.830865026e-01, 9.270088673e-01, -1.107423306e+00, -2.277084440e-01, + -6.451560855e-01, -1.092167020e+00, -7.047639489e-01, 1.041551352e+00, -6.086724997e-01, + 1.192895055e+00, -1.278925300e+00, 4.609687254e-02, -1.041480780e+00, -1.062816143e+00, + -5.307221413e-01, 1.560166597e+00, -1.770771593e-01, 1.113741279e+00, -6.972364187e-01, + -2.393010706e-01, -3.851891458e-01, -1.248644352e+00, -9.509255290e-01, 1.075714588e+00, + -6.976311803e-01, 1.129892349e+00, -1.098267317e+00, 1.412549466e-01, -1.435219169e+00, + -7.171595097e-01, -5.283811688e-01, 1.581303477e+00, -3.234961256e-02, 1.174488306e+00, + -4.815483391e-01, -3.245675266e-01, -3.670870364e-01, -1.287428856e+00, + -9.122958779e-01, + 1.023739815e+00, -9.736443758e-01, 8.757716417e-01, -1.144454598e+00, -1.705268323e-01, + -1.537654757e+00, -5.262694359e-01, -4.865987003e-01, 1.693882823e+00, -1.621098369e-01, + 1.250517011e+00, -1.486653537e-01, -1.331191510e-01, -7.703314424e-01, -8.683122396e-01, + -8.792849183e-01, 1.050339222e+00, -9.340595603e-01, 8.220658898e-01, -1.349122882e+00, + -8.058144897e-02, -1.425775886e+00, -4.974521697e-01, -4.040106535e-01, + ], + "model.layers.0": [ + 1.667012811e+00, 2.387410641e+00, 2.273866415e+00, 2.055034399e+00, 2.047709942e+00, + 2.188353062e+00, 1.450815678e+00, 5.670793653e-01, 2.371724606e+00, 2.300396919e+00, + 2.288952351e+00, 1.562845826e+00, 1.808727026e+00, -1.422226429e-02, 5.324167013e-01, + -8.149694204e-01, 1.709804058e+00, 2.401426315e+00, 2.317487478e+00, 2.026555777e+00, + 2.095670938e+00, 2.223070860e+00, 1.501770496e+00, 5.998874307e-01, 2.439841270e+00, + 2.046147346e+00, 2.301568031e+00, 1.579159856e+00, 1.417099714e+00, -1.898247600e-01, + 6.705253124e-01, -9.426226616e-01, 1.536416054e+00, 1.518670559e+00, 2.084631920e+00, + 2.282132387e+00, 2.238708019e+00, 1.692402482e+00, 1.932704210e+00, 6.339520812e-01, + 2.517916679e+00, 1.937870741e+00, 2.305603027e+00, 1.140208006e+00, 1.511725426e+00, + -2.303019166e-01, 7.629956007e-01, -8.899884224e-01, 1.581506729e+00, 1.534169793e+00, + 2.144944906e+00, 2.227003574e+00, 2.290168524e+00, 1.748752356e+00, 1.974782825e+00, + 6.361899972e-01, 2.636434317e+00, 1.964299321e+00, 1.861216784e+00, 1.428914666e+00, + 1.703559518e+00, 4.127325118e-02, 1.003404856e+00, -4.598860741e-01, 1.565847158e+00, + 1.635602474e+00, 2.156379223e+00, 2.241621971e+00, 2.220364094e+00, 1.991723299e+00, + 1.893302679e+00, 7.657704353e-01, 2.389874458e+00, 1.250161886e+00, 1.960324883e+00, + 1.795460224e+00, 2.102133512e+00, 1.013387442e+00, 1.866458774e+00, 2.950383425e-01, + 1.538869381e+00, 1.832724571e+00, 2.149276018e+00, 2.247411728e+00, 2.097110987e+00, + 2.230749846e+00, 1.722755909e+00, 8.545615077e-01, 1.480376959e+00, 1.283376932e+00, + 2.049382210e+00, 2.259159565e+00, 2.287710667e+00, 1.680924177e+00, 2.059410572e+00, + 6.365273595e-01, 1.546980619e+00, 2.042796135e+00, 2.171475887e+00, 2.175883532e+00, + 2.029856205e+00, 2.345506668e+00, 1.586347938e+00, 8.342842460e-01, 1.886024237e+00, + 2.773323536e+00, 2.291981697e+00, 2.004436255e+00, 1.790915608e+00, 1.439521551e+00, + 8.919111490e-01, -2.862927914e-01, 1.582734585e+00, 2.224070549e+00, 2.210582733e+00, + 2.097623110e+00, 2.009777784e+00, 2.356836319e+00, 1.496542573e+00, 7.583110929e-01, + 2.108268261e+00, 2.675643921e+00, 2.338322163e+00, 1.713167191e+00, 1.656818986e+00, + 9.183706045e-01, 3.586764336e-01, -5.439436436e-01, 1.625893831e+00, 2.342742920e+00, + 2.248255968e+00, 2.053145885e+00, 2.012304783e+00, 2.346009731e+00, 1.454495907e+00, + 7.137711048e-01, 2.388000965e+00, 2.252923489e+00, 2.300971985e+00, 1.572249293e+00, + 1.833337665e+00, -2.255994081e-02, 5.655136704e-01, -8.334512711e-01, 1.671282768e+00, + 2.393374205e+00, 2.286320210e+00, 2.041717291e+00, 2.038836956e+00, 2.350221872e+00, + 1.466526747e+00, 7.172854543e-01, 2.428810596e+00, 2.093056679e+00, 2.297038794e+00, + 1.576087236e+00, 1.395770907e+00, -1.680784225e-01, 6.423871517e-01, -9.088283777e-01, + 1.527027845e+00, 1.388355255e+00, 2.093892574e+00, 2.246807814e+00, 2.283925533e+00, + 1.739825845e+00, 2.022411823e+00, 6.661166549e-01, 2.511260271e+00, 1.963679075e+00, + 2.326486826e+00, 1.150024414e+00, 1.521337390e+00, -1.541444659e-01, 7.768989205e-01, + -8.361940384e-01, 1.562026024e+00, 1.545197725e+00, 2.129195690e+00, 2.255976677e+00, + 2.251318932e+00, 1.816562891e+00, 1.941796899e+00, 6.893571615e-01, 2.610969782e+00, + 1.986112237e+00, 1.898723364e+00, 1.448355436e+00, 1.729568005e+00, 1.658836454e-01, + 1.046955585e+00, -3.806146383e-01, 1.558808804e+00, 1.668811083e+00, 2.145965815e+00, + 2.259795189e+00, 2.192706108e+00, 2.005565405e+00, 1.858484745e+00, 7.804096937e-01, + 2.389874458e+00, 1.250161886e+00, 1.960324883e+00, 1.795460224e+00, 2.102133512e+00, + 1.013387442e+00, 1.866458774e+00, 2.950383425e-01, 1.538869381e+00, 1.832724571e+00, + 2.149276018e+00, 2.247411728e+00, 2.097110987e+00, 2.230749846e+00, 1.722755909e+00, + 8.545615077e-01, 1.480376959e+00, 1.283376932e+00, 2.049382210e+00, 2.259159565e+00, + 2.287710667e+00, 1.680924177e+00, 2.059410572e+00, 6.365273595e-01, 1.546980619e+00, + 2.042796135e+00, 2.171475887e+00, 2.175883532e+00, 2.029856205e+00, 2.345506668e+00, + 1.586347938e+00, 8.342842460e-01, 1.886024237e+00, 2.773323536e+00, 2.291981697e+00, + 2.004436255e+00, 1.790915608e+00, 1.439521551e+00, 8.919111490e-01, -2.862927914e-01, + 1.582734585e+00, 2.224070549e+00, 2.210582733e+00, 2.097623110e+00, 2.009777784e+00, + 2.356836319e+00, 1.496542573e+00, 7.583110929e-01, 2.108268261e+00, 2.675643921e+00, + 2.338322163e+00, 1.713167191e+00, 1.656818986e+00, 9.183706045e-01, 3.586764336e-01, + -5.439436436e-01, 1.625893831e+00, 2.342742920e+00, 2.248255968e+00, 2.053145885e+00, + 2.012304783e+00, 2.346009731e+00, 1.454495907e+00, 7.137711048e-01, 2.388000965e+00, + 2.252923489e+00, 2.300971985e+00, 1.572249293e+00, 1.833337665e+00, -2.255994081e-02, + 5.655136704e-01, -8.334512711e-01, 1.671282768e+00, 2.393374205e+00, 2.286320210e+00, + 2.041717291e+00, 2.038836956e+00, 2.350221872e+00, 1.466526747e+00, 7.172854543e-01, + 2.444100142e+00, 2.026103258e+00, 2.294885874e+00, 1.580023766e+00, 1.417909384e+00, + -2.224726677e-01, 6.719112992e-01, -9.683926702e-01, 1.561171532e+00, 1.480701923e+00, + 2.105252743e+00, 2.245001078e+00, 2.291590691e+00, 1.614448309e+00, 1.983524799e+00, + 5.656208992e-01, 2.519832134e+00, 1.934314489e+00, 2.290132523e+00, 1.138520718e+00, + 1.497435331e+00, -2.731286287e-01, 7.446147203e-01, -9.104239941e-01, + ], + "model.layers.0.conv": [ + 8.105565310e-01, 1.040720701e+00, 8.528981805e-01, 8.338034749e-01, 8.952398896e-01, + 1.507895947e+00, 9.375815392e-01, 1.130098104e+00, 7.244580388e-01, 8.220815063e-01, + 8.430810571e-01, 7.004589438e-01, 9.617040753e-01, 6.569852829e-01, 1.080327034e+00, + 6.625930071e-01, 8.137855530e-01, 1.011203051e+00, 8.584251404e-01, 7.674973607e-01, + 9.030647278e-01, 1.494761944e+00, 9.477043748e-01, 1.121837497e+00, 8.043977022e-01, + 6.424605846e-01, 9.383563995e-01, 6.547436714e-01, 1.072315097e+00, 5.012774467e-01, + 1.206273794e+00, 6.658542156e-01, 8.736258149e-01, 5.106903911e-01, 9.247385263e-01, + 9.692496061e-01, 9.758512974e-01, 7.735186219e-01, 1.026964068e+00, 1.149311900e+00, + 8.573008776e-01, 5.229391456e-01, 9.924410582e-01, 6.150619388e-01, 1.127581239e+00, + 3.690779805e-01, 1.262721419e+00, 7.128499150e-01, 8.975634575e-01, 4.919127226e-01, + 9.540126324e-01, 9.125785232e-01, 1.010461807e+00, 8.219454288e-01, 1.066910982e+00, + 1.146567583e+00, 9.043854475e-01, 4.188366532e-01, 1.022648454e+00, 5.886836052e-01, + 1.140911460e+00, 2.699580789e-01, 1.259174466e+00, 8.443204165e-01, 9.011051655e-01, + 5.509673357e-01, 9.395184517e-01, 9.546901584e-01, 9.779317379e-01, 1.035096526e+00, + 1.016345024e+00, 1.240288734e+00, 9.691440463e-01, 2.681975961e-01, 1.046409011e+00, + 5.718727112e-01, 1.123674035e+00, 2.692351937e-01, 1.200939059e+00, 1.114069104e+00, + 8.802790642e-01, 6.944176555e-01, 8.970303535e-01, 1.008256674e+00, 9.137817025e-01, + 1.306829095e+00, 9.305329919e-01, 1.327772498e+00, 8.994040489e-01, 3.784057796e-01, + 9.570420980e-01, 9.632196426e-01, 1.014680147e+00, 7.195856571e-01, 1.072318077e+00, + 1.142463923e+00, 8.594123721e-01, 8.468682766e-01, 8.709255457e-01, 9.688718319e-01, + 8.824387193e-01, 1.502846956e+00, 8.939518929e-01, 1.333096504e+00, 6.724965572e-01, + 1.185123682e+00, 7.256630063e-01, 8.987633586e-01, 7.788295150e-01, 1.219211578e+00, + 8.319960237e-01, 9.379140139e-01, 8.365870714e-01, 9.643580317e-01, 8.544887304e-01, + 8.948893547e-01, 8.723903894e-01, 1.589308262e+00, 8.902920485e-01, 1.278328776e+00, + 6.577978134e-01, 1.028092980e+00, 7.433751822e-01, 8.203868866e-01, 8.289524913e-01, + 9.098418951e-01, 9.145298600e-01, 7.611610889e-01, 8.246574402e-01, 1.030290961e+00, + 8.479590416e-01, 8.408166170e-01, 8.712606430e-01, 1.617256880e+00, 8.945622444e-01, + 1.239399433e+00, 7.479776740e-01, 8.015141487e-01, 8.703083396e-01, 7.155977488e-01, + 9.926389456e-01, 6.545251608e-01, 1.114969611e+00, 6.675745845e-01, 8.218755126e-01, + 1.034955263e+00, 8.479232788e-01, 8.020207882e-01, 8.739709854e-01, 1.607526779e+00, + 9.000187516e-01, 1.222886801e+00, 7.906203866e-01, 6.672403812e-01, 9.197984934e-01, + 6.477116346e-01, 1.048976541e+00, 5.144910812e-01, 1.178154588e+00, 6.759800315e-01, + 9.195117354e-01, 4.280621409e-01, 9.732491970e-01, 9.589306116e-01, 1.026986599e+00, + 7.916362882e-01, 1.080724120e+00, 1.182074428e+00, 8.571742177e-01, 5.218711495e-01, + 9.871234894e-01, 6.018028259e-01, 1.117072701e+00, 3.964901567e-01, 1.247022033e+00, + 7.386778593e-01, 9.052293301e-01, 5.099664927e-01, 9.529758096e-01, 9.618282318e-01, + 1.000722289e+00, 8.822501302e-01, 1.048468828e+00, 1.197746992e+00, 9.093937874e-01, + 4.109351933e-01, 1.022361755e+00, 5.791219473e-01, 1.135329843e+00, 3.171604276e-01, + 1.248297811e+00, 8.758037090e-01, 8.930807114e-01, 5.780802369e-01, 9.270619750e-01, + 9.769684076e-01, 9.610432982e-01, 1.053094149e+00, 9.950246215e-01, 1.254424214e+00, + 9.691440463e-01, 2.681975961e-01, 1.046409011e+00, 5.718727112e-01, 1.123674035e+00, + 2.692351937e-01, 1.200939059e+00, 1.114069104e+00, 8.802790642e-01, 6.944176555e-01, + 8.970303535e-01, 1.008256674e+00, 9.137817025e-01, 1.306829095e+00, 9.305329919e-01, + 1.327772498e+00, 8.994040489e-01, 3.784057796e-01, 9.570420980e-01, 9.632196426e-01, + 1.014680147e+00, 7.195856571e-01, 1.072318077e+00, 1.142463923e+00, 8.594123721e-01, + 8.468682766e-01, 8.709255457e-01, 9.688718319e-01, 8.824387193e-01, 1.502846956e+00, + 8.939518929e-01, 1.333096504e+00, 6.724965572e-01, 1.185123682e+00, 7.256630063e-01, + 8.987633586e-01, 7.788295150e-01, 1.219211578e+00, 8.319960237e-01, 9.379140139e-01, + 8.365870714e-01, 9.643580317e-01, 8.544887304e-01, 8.948893547e-01, 8.723903894e-01, + 1.589308262e+00, 8.902920485e-01, 1.278328776e+00, 6.577978134e-01, 1.028092980e+00, + 7.433751822e-01, 8.203868866e-01, 8.289524913e-01, 9.098418951e-01, 9.145298600e-01, + 7.611610889e-01, 8.246574402e-01, 1.030290961e+00, 8.479590416e-01, 8.408166170e-01, + 8.712606430e-01, 1.617256880e+00, 8.945622444e-01, 1.239399433e+00, 7.479776740e-01, + 8.015141487e-01, 8.703083396e-01, 7.155977488e-01, 9.926389456e-01, 6.545251608e-01, + 1.114969611e+00, 6.675745845e-01, 8.218755126e-01, 1.034955263e+00, 8.479232788e-01, + 8.020207882e-01, 8.739709854e-01, 1.607526779e+00, 9.000187516e-01, 1.222886801e+00, + 8.084859252e-01, 6.380392313e-01, 9.453512430e-01, 6.647846699e-01, 1.082216620e+00, + 4.882575870e-01, 1.219081879e+00, 6.554092169e-01, 8.812755942e-01, 4.780524075e-01, + 9.432938099e-01, 9.229655266e-01, 1.005312085e+00, 7.150660753e-01, 1.067330241e+00, + 1.102434516e+00, 8.546511531e-01, 5.320209265e-01, 9.912089109e-01, 6.272823215e-01, + 1.127766609e+00, 3.554278612e-01, 1.264324307e+00, 7.031126022e-01, + ], + "model.layers.1": [ + 2.637523651e+00, 3.248355389e-01, 1.027509212e+00, 3.004598618e-02, 3.518416882e-01, + 1.566761255e+00, 2.175596952e-01, 9.710347652e-02, 1.530460715e+00, -2.997266650e-01, + 1.068613529e-01, -8.470952511e-02, 2.917687893e-01, 1.466804743e-01, 4.872288704e-01, + -2.514037490e-02, 2.383367777e+00, 5.630420446e-01, 7.533411384e-01, 4.414250255e-01, + 1.519010067e-01, 1.863706231e+00, 2.372162342e-01, 6.791472435e-03, 1.694530010e+00, + -5.681700110e-01, 1.407450438e-01, -1.351999044e-01, -3.608214855e-02, -1.474153996e-02, + 7.427087426e-01, -4.063665867e-03, 2.460473299e+00, 1.777396202e-01, 6.106069684e-01, + 1.069748878e+00, 1.176952124e-01, 1.469117045e+00, 5.721563101e-01, -1.797314882e-01, + 2.024655581e+00, -7.402617335e-01, 1.541380882e-01, -7.423181534e-01, 6.561219692e-02, + -2.160990238e-02, 7.861711979e-01, 3.800973296e-02, 2.440344572e+00, 2.453154325e-01, + 5.812001824e-01, 1.085369349e+00, 1.255656481e-01, 1.563316464e+00, 6.161295176e-01, + -1.918636560e-01, 2.743060112e+00, -3.619515896e-01, -8.019638062e-02, -4.154875278e-01, + -1.324626207e-01, -8.011257648e-02, 4.401054382e-01, -1.785195470e-01, 2.584602356e+00, + 2.618686557e-01, 6.556959152e-01, 9.759669900e-01, 5.806672573e-02, 1.764404655e+00, + 5.031970739e-01, -7.013940811e-02, 3.598707914e+00, -1.939212680e-01, 5.992768407e-01, + 4.221479893e-01, 9.753167629e-02, 8.236050606e-01, 5.834159851e-01, -3.702767491e-01, + 2.648078918e+00, 3.132135272e-01, 7.354087234e-01, 8.218182325e-01, -1.377677917e-02, + 1.941090703e+00, 3.210961819e-01, 4.992949963e-02, 2.751159668e+00, -1.005569696e-01, + 7.661143541e-01, 9.009644985e-01, 2.099128962e-01, 1.423645735e+00, 6.434162855e-01, + -2.125636339e-01, 2.761273384e+00, 3.508895040e-01, 8.131094575e-01, 4.823157787e-01, + -4.239678383e-02, 1.943957090e+00, 1.893633604e-01, 8.923089504e-02, 2.078271151e+00, + 1.623070240e-02, 4.628953934e-01, -2.952415943e-01, -1.903057098e-02, 1.112260103e+00, + 2.613066435e-01, -5.328625441e-02, 2.816339493e+00, 3.628144264e-01, 8.407778740e-01, + 1.662703156e-01, -4.040658474e-02, 1.854110003e+00, 1.174468994e-01, 7.630968094e-02, + 1.901932120e+00, -3.811132908e-01, 4.875258207e-01, -6.143975854e-01, 2.247081995e-01, + 8.625044823e-01, 2.633123398e-01, 3.070439100e-01, 2.653695583e+00, 4.734014869e-01, + 7.879050374e-01, 2.240881920e-01, -3.460013866e-02, 1.908393741e+00, 1.140141487e-01, + 6.402194500e-02, 1.991702080e+00, -7.367265224e-01, 3.895326853e-01, -5.855885148e-01, + 5.090589523e-01, 8.776849508e-02, 6.682385802e-01, 2.484451085e-01, 2.515686750e+00, + 5.994527936e-01, 7.435763478e-01, 3.849327564e-01, -1.294028759e-02, 1.997799635e+00, + 1.640025377e-01, 8.382272720e-02, 6.622738838e-01, 2.571189404e-02, -4.855788946e-01, + 6.392011642e-01, -4.708102345e-01, 3.415334225e-01, 7.859859467e-01, -2.052042186e-01, + 3.000880957e+00, -3.524601460e-03, 7.053163648e-01, 6.270767450e-01, -4.279887676e-02, + 1.381164432e+00, 5.352714062e-01, -2.641758919e-01, 2.057797909e+00, -8.391644359e-01, + -1.085054874e-02, -7.558228970e-01, -1.092946529e-01, 2.080081701e-01, 8.572080731e-01, + 1.233563647e-01, 2.454001427e+00, 3.554256558e-01, 4.843288660e-01, 1.152547836e+00, + -4.332029819e-02, 1.659156442e+00, 5.786179304e-01, -1.699136496e-01, 2.808181524e+00, + -3.254242241e-01, -1.145236492e-01, -4.169635773e-01, -2.570031881e-01, 6.110310555e-02, + 4.153802395e-01, -1.914980412e-01, 2.647520781e+00, 2.753519416e-01, 6.285797954e-01, + 9.448266625e-01, -1.837074757e-02, 1.758791804e+00, 4.538017511e-01, -6.927704811e-02, + 3.723602295e+00, -2.450159788e-01, 6.091662645e-01, 3.182751536e-01, 6.218838692e-02, + 7.906650305e-01, 5.590993166e-01, -3.827596903e-01, 2.847504616e+00, 2.129820585e-01, + 8.038608432e-01, 6.187762618e-01, -2.615475655e-02, 1.854842901e+00, 2.857031822e-01, + 3.957629204e-02, 3.043556213e+00, -2.273519039e-01, 8.798868060e-01, 6.009154916e-01, + 1.966943741e-01, 1.285059094e+00, 5.881450176e-01, -2.332797050e-01, 2.954111576e+00, + 2.460159063e-01, 8.790000677e-01, 2.414403558e-01, -5.807828903e-02, 1.837087631e+00, + 1.583213806e-01, 8.625364304e-02, 2.147912025e+00, -6.694322824e-02, 4.968500137e-01, + -4.164019823e-01, -1.033067703e-03, 1.095277429e+00, 2.966934443e-01, 3.199994564e-03, + 2.893786430e+00, 3.180745244e-01, 8.685723543e-01, 6.035459042e-02, -3.842747211e-02, + 1.802929282e+00, 1.099985838e-01, 8.301830292e-02, 1.945215225e+00, -4.317899346e-01, + 5.254815817e-01, -6.849192977e-01, 2.604402304e-01, 8.548555374e-01, 2.999501228e-01, + 3.606078625e-01, 2.753734589e+00, 4.102433324e-01, 8.407252431e-01, 8.738738298e-02, + -1.431167126e-02, 1.844045043e+00, 1.083531380e-01, 7.916426659e-02, 2.036192417e+00, + -7.810619473e-01, 4.326283932e-01, -6.552403569e-01, 5.488433838e-01, 7.989615202e-02, + 7.050190568e-01, 3.048605323e-01, 2.616690159e+00, 5.331308246e-01, 7.864535451e-01, + 2.612600327e-01, -1.135289669e-02, 1.951250196e+00, 1.509815454e-01, 8.682489395e-02, + 2.049867630e+00, -9.368787408e-01, 3.770835400e-01, -5.684503317e-01, 1.806195974e-01, + -3.816002607e-02, 9.516580701e-01, 3.195087910e-01, 2.773928404e+00, -6.439626217e-03, + 7.561464310e-01, 7.519729733e-01, 1.993795633e-01, 1.287180066e+00, 5.955326557e-01, + -2.301445007e-01, 2.256884098e+00, -9.930841923e-01, 3.628700972e-01, -1.088963270e+00, + 3.070310354e-01, -7.269072533e-02, 9.793566465e-01, 3.490094543e-01, + ], + "model.layers.1.self_attn": [ + 2.271034941e-02, -1.320974380e-01, -1.280027628e-02, -5.059826002e-02, -6.518827751e-03, + 5.962241441e-02, 2.848412283e-02, 5.817219615e-02, -2.619380131e-03, -9.346050769e-02, + -3.004643321e-02, -8.113376796e-03, -2.275783569e-03, 1.056850851e-01, 5.394617468e-02, + 7.509279251e-02, 5.399182439e-03, -1.235229820e-01, -3.445814177e-02, -3.543818742e-02, + -1.742552221e-02, 8.260743320e-02, 2.956793830e-02, 5.316107348e-02, 1.612622291e-03, + -9.204657376e-02, -2.621069923e-02, -8.801078424e-03, -1.156404614e-04, 1.022124588e-01, + 5.374746770e-02, 7.476712763e-02, -3.926493227e-04, -1.247725040e-01, -5.012091249e-02, + -3.720739484e-02, -3.258732706e-02, 8.999618888e-02, 2.458472736e-02, 4.514201358e-02, + 1.066949964e-02, -9.058186412e-02, -2.262751386e-02, -1.275819354e-02, -1.987263560e-03, + 9.505518526e-02, 4.864268750e-02, 6.948138773e-02, -2.843201160e-03, -1.232281178e-01, + -5.565942451e-02, -3.401289880e-02, -3.505002707e-02, 9.576803446e-02, 2.612506598e-02, + 4.539991543e-02, 1.340891793e-02, -9.564994276e-02, -2.505981550e-02, -1.879992522e-02, + -8.015816100e-03, 9.263680130e-02, 4.361489043e-02, 6.470896304e-02, 5.796480924e-03, + -1.223485768e-01, -4.922487587e-02, -3.751061484e-02, -3.369765356e-02, 8.805789053e-02, + 2.256014198e-02, 4.253407195e-02, 1.362066343e-02, -1.130502000e-01, -3.567107767e-02, + -3.307066485e-02, -2.292959951e-02, 8.365172148e-02, 2.655472048e-02, 4.762496799e-02, + 1.259985939e-02, -1.206279844e-01, -3.904541954e-02, -3.946497291e-02, -2.872764319e-02, + 8.032902330e-02, 2.022112533e-02, 4.145123065e-02, 1.374144107e-02, -1.222342923e-01, + -3.887666017e-02, -4.269127920e-02, -3.061603010e-02, 7.724244893e-02, 1.803532429e-02, + 3.965534642e-02, 2.182093263e-02, -1.218719333e-01, -3.028750047e-02, -4.538538307e-02, + -2.550053596e-02, 7.162531465e-02, 1.981057599e-02, 4.311490059e-02, 2.780207992e-02, + -1.083006933e-01, -1.525246538e-02, -3.770791739e-02, -1.029933803e-02, 7.093469799e-02, + 3.270362318e-02, 5.780234188e-02, 2.836905420e-02, -1.233031228e-01, -2.475392632e-02, + -5.000422150e-02, -2.333613113e-02, 6.503320485e-02, 1.982017793e-02, 4.461895674e-02, + 2.900473773e-02, -1.026528627e-01, -8.932190016e-03, -3.380349278e-02, -2.797427587e-03, + 7.124704123e-02, 3.953850269e-02, 6.557486951e-02, 2.059767395e-02, -1.220520139e-01, + -2.840017155e-02, -4.494497925e-02, -2.252645232e-02, 7.169654220e-02, 2.288172767e-02, + 4.692908376e-02, 2.279583365e-02, -9.668626636e-02, -1.028501429e-02, -2.590578422e-02, + 2.592802048e-04, 7.816393673e-02, 4.409280047e-02, 6.884827465e-02, 1.222157478e-02, + -1.206590682e-01, -3.402604535e-02, -3.894487023e-02, -2.274216712e-02, 8.103843033e-02, + 2.681083046e-02, 4.984967783e-02, -4.977105558e-02, -7.190001011e-02, -9.206201136e-02, + 3.068432212e-02, -3.411756828e-02, 1.780861169e-01, 6.864435971e-02, 7.228840888e-02, + 2.595799044e-02, -1.236675829e-01, -4.320792109e-02, -5.349849537e-02, -4.269322008e-02, + 7.219868153e-02, 1.334954984e-02, 3.377979249e-02, 1.789557189e-02, -8.527156711e-02, + -2.976243570e-02, -1.346748881e-02, -1.282196678e-02, 9.468824416e-02, 4.047014564e-02, + 5.745768547e-02, -9.440630674e-04, -1.207182556e-01, -6.278453767e-02, -3.380705416e-02, + -4.235681891e-02, 1.016945839e-01, 2.666135505e-02, 4.401670024e-02, 1.648434997e-02, + -9.402222186e-02, -2.913576737e-02, -2.002536505e-02, -1.423752122e-02, 9.314818680e-02, + 3.983740881e-02, 5.930737406e-02, 1.006412879e-02, -1.211929917e-01, -4.894187674e-02, + -3.868459165e-02, -3.521756828e-02, 8.631920069e-02, 2.100212499e-02, 4.055032134e-02, + 1.958938316e-02, -1.120691299e-01, -3.330964595e-02, -3.540636972e-02, -2.378179878e-02, + 7.926842570e-02, 2.375808544e-02, 4.474497214e-02, 2.307498455e-02, -1.199356169e-01, + -3.202389926e-02, -4.452981055e-02, -2.810421027e-02, 7.132679969e-02, 1.626629196e-02, + 3.812378272e-02, 2.868281677e-02, -1.212544441e-01, -2.818156779e-02, -5.008926988e-02, + -2.943424881e-02, 6.418459862e-02, 1.242175139e-02, 3.503376991e-02, 3.301618993e-02, + -1.210745871e-01, -2.276358940e-02, -5.110050738e-02, -2.520858869e-02, 6.223034486e-02, + 1.570317149e-02, 3.965436667e-02, 3.350374475e-02, -1.080788076e-01, -1.188396849e-02, + -4.101214930e-02, -1.069732662e-02, 6.623126566e-02, 3.066607937e-02, 5.616614968e-02, + 3.323251009e-02, -1.235368252e-01, -2.163501643e-02, -5.282337964e-02, -2.308009565e-02, + 6.080564484e-02, 1.839038916e-02, 4.371835664e-02, 3.250670061e-02, -1.032862365e-01, + -6.569705904e-03, -3.636939451e-02, -2.608150709e-03, 6.787621975e-02, 3.868217021e-02, + 6.534323096e-02, 2.643406764e-02, -1.230213866e-01, -2.381496876e-02, -4.891374707e-02, + -2.157630585e-02, 6.592868268e-02, 2.139716968e-02, 4.641050100e-02, 2.586759627e-02, + -9.758384526e-02, -7.788119838e-03, -2.853233553e-02, 6.959149614e-04, 7.503298670e-02, + 4.369376227e-02, 6.921818107e-02, 1.785539463e-02, -1.208168492e-01, -2.983795106e-02, + -4.234777391e-02, -2.237755060e-02, 7.570708543e-02, 2.466863580e-02, 4.816734791e-02, + 2.337678522e-02, -9.403048456e-02, -9.030273184e-03, -2.403287962e-02, 1.894930378e-03, + 7.898107171e-02, 4.583649337e-02, 7.030108571e-02, 1.502775773e-02, -1.242914945e-01, + -3.811265156e-02, -4.490544647e-02, -2.965560742e-02, 7.623831928e-02, 2.055917494e-02, + 4.298502952e-02, 2.547157928e-02, -9.411096573e-02, -8.153336123e-03, -2.452245727e-02, + 2.491161227e-03, 7.835865021e-02, 4.642827064e-02, 7.132798433e-02, + ], + "model.layers.2": [ + 2.953855038e+00, -4.111662507e-01, 2.364441156e+00, -1.735341549e+00, -2.334439754e-02, + -1.390910745e+00, -1.511505365e+00, -9.334568977e-01, 1.726594329e+00, -1.194516659e+00, + 1.389766335e+00, -1.945966005e+00, -1.539024115e-01, -2.784918547e+00, -8.541002274e-01, + -8.659143448e-01, 3.024693966e+00, 7.953226566e-03, 2.068654060e+00, -1.245609403e+00, + -2.853230834e-01, -1.143098354e+00, -1.572558403e+00, -1.148884773e+00, 1.670256376e+00, + -1.778018236e+00, 1.102920294e+00, -2.047294140e+00, -3.816190362e-01, -2.708067656e+00, + -4.874933660e-01, -6.797573566e-01, 3.577818394e+00, 5.850654840e-02, 2.140012503e+00, + -4.269547462e-01, -1.414240599e-01, -1.371852994e+00, -1.221204996e+00, + -1.391568661e+00, + 2.017317533e+00, -1.715426445e+00, 1.153787732e+00, -2.421806812e+00, -1.996955872e-01, + -2.424892902e+00, -7.964254618e-01, -7.179196477e-01, 3.528868437e+00, 1.923855245e-01, + 2.211581230e+00, -3.051075339e-01, 5.335545540e-02, -9.901686907e-01, -1.365303993e+00, + -1.622376680e+00, 2.649697304e+00, -1.666020751e+00, 3.819048405e-01, -2.291841507e+00, + -3.437254429e-01, -2.332953215e+00, -6.762703061e-01, -8.966199756e-01, 3.852423429e+00, + 1.581720561e-01, 2.267666817e+00, -2.740709782e-01, -1.667377949e-01, -6.488224268e-01, + -1.450741053e+00, -1.749769092e+00, 4.327544689e+00, -8.966404200e-01, 1.439348221e+00, + -1.689571142e+00, -1.970515251e-01, -2.005787611e+00, -1.064728737e+00, + -1.428727746e+00, + 3.740732670e+00, -6.659436226e-02, 2.072038412e+00, -9.410116076e-01, -1.548442841e-01, + -6.930713654e-01, -1.372366428e+00, -1.522347450e+00, 3.599264622e+00, -2.146361470e-01, + 2.203511238e+00, -1.110750198e+00, 3.688099384e-01, -1.393031359e+00, -7.672848701e-01, + -6.639698744e-01, 3.279362440e+00, -3.192281127e-01, 1.765590787e+00, -1.703800678e+00, + -2.241915464e-01, -1.031214833e+00, -1.446551800e+00, -8.816554546e-01, 1.328257561e+00, + -1.467077732e+00, 7.153447270e-01, -2.694776058e+00, -1.630414128e-01, -1.546313286e+00, + -9.331102371e-01, -4.485688508e-01, 2.967166185e+00, -5.502482057e-01, 1.593897581e+00, + -1.967129707e+00, -3.626326919e-01, -1.117575526e+00, -1.762590885e+00, + -9.440246820e-01, + 1.874611855e+00, -1.114966750e+00, 1.929642797e+00, -2.261616230e+00, 4.989111423e-02, + -1.734415174e+00, -1.651724339e+00, -7.888282537e-01, 3.135226965e+00, -2.088269293e-01, + 2.077588558e+00, -1.180467486e+00, -3.748654723e-01, -6.144281626e-01, -2.017523289e+00, + -1.545465350e+00, 2.127885580e+00, -1.348932385e+00, 2.011724710e+00, -2.022128820e+00, + 2.197687626e-01, -2.484392405e+00, -1.211909294e+00, -8.798007965e-01, 3.117049456e+00, + 9.381657839e-02, 2.165381193e+00, -7.569112778e-01, -4.993088841e-01, -5.721763372e-01, + -2.045584917e+00, -1.454864383e+00, 2.044624805e+00, 1.074883223e+00, -9.704203010e-01, + -7.361726761e-01, -1.099328756e+00, -4.203751683e-01, -1.477208138e+00, + -1.655679703e+00, + 4.118448257e+00, 3.392791450e-01, 7.427682877e-01, -1.310316563e+00, -5.045127869e-01, + -6.062126756e-01, -2.013003588e+00, -1.846574664e+00, 2.623790979e+00, -9.583287835e-01, + 4.768140316e-01, -1.876726151e+00, -6.824167967e-01, -1.397461653e+00, -1.386959195e+00, + -1.264660120e+00, 3.953471899e+00, 1.080949306e+00, 8.959074616e-01, -2.815904617e-01, + -5.715063810e-01, -5.050444603e-02, -2.073788166e+00, -2.159438848e+00, 2.655874729e+00, + -1.675445557e+00, 2.645739317e-01, -2.190935612e+00, -4.506429434e-01, -1.999030828e+00, + -8.539277315e-01, -1.161608100e+00, 3.978410721e+00, 3.273517191e-01, 2.010571241e+00, + -1.815400124e-01, -3.668813705e-01, -3.975700140e-01, -1.777827740e+00, + -1.997955084e+00, + 4.393372059e+00, -9.821596146e-01, 1.353477955e+00, -1.772161484e+00, -2.164183855e-01, + -1.905569673e+00, -1.167759895e+00, -1.590753436e+00, 3.825979948e+00, -2.823485434e-01, + 2.007360220e+00, -1.152052045e+00, -2.194424868e-01, -7.262775898e-01, -1.508091211e+00, + -1.594351768e+00, 3.687875986e+00, -7.157570124e-01, 2.055728912e+00, -1.540053606e+00, + 1.769104004e-01, -1.617720842e+00, -9.649459124e-01, -9.420126677e-01, 3.312177658e+00, + -6.757990718e-01, 1.714592695e+00, -1.908694744e+00, -3.176426888e-01, -1.072759032e+00, + -1.481156826e+00, -1.023221731e+00, 1.451410055e+00, -1.572649002e+00, 9.280809164e-01, + -2.685720921e+00, -1.887523532e-01, -1.567789793e+00, -1.011302710e+00, + -5.772635937e-01, + 3.005146265e+00, -7.206150293e-01, 1.683644414e+00, -1.944271445e+00, -3.868850470e-01, + -1.061889410e+00, -1.743169546e+00, -1.091765165e+00, 1.967306495e+00, -1.108615041e+00, + 2.097777128e+00, -2.174097538e+00, 7.583415508e-02, -1.659802437e+00, -1.642477036e+00, + -7.960555553e-01, 3.144825935e+00, -3.441865444e-01, 2.090141535e+00, -1.264876723e+00, + -4.201189876e-01, -6.551088095e-01, -2.059274197e+00, -1.522148252e+00, 2.178811073e+00, + -1.362555385e+00, 2.130715132e+00, -2.002041817e+00, 2.491886616e-01, -2.452757120e+00, + -1.188469768e+00, -8.498743773e-01, 3.119920015e+00, -6.154645234e-02, 2.157459736e+00, + -8.550876379e-01, -5.577445626e-01, -6.110982895e-01, -2.078266621e+00, + -1.429383636e+00, + 2.032448769e+00, -1.863958001e+00, 1.618775606e+00, -2.044895172e+00, -2.948660851e-01, + -2.575743675e+00, -8.548461795e-01, -7.671597004e-01, 3.505305290e+00, -3.234875798e-01, + 2.409338713e+00, -2.768820524e-01, -2.399303317e-01, -1.345036030e+00, -1.470172405e+00, + -1.444963813e+00, 2.152756929e+00, -1.846059799e+00, 1.568692446e+00, -2.488624811e+00, + -1.438475847e-01, -2.465644598e+00, -8.341930509e-01, -6.575716734e-01, + ], + "model.layers.2.self_attn": [ + -4.461497068e-03, -4.645131528e-02, 6.634586304e-02, -2.255107835e-02, 4.604065046e-02, + -8.976338804e-02, -3.512387723e-02, -1.875532791e-02, 7.998764515e-03, -2.618857846e-02, + 6.357833743e-02, -9.760051966e-03, 3.538877517e-02, -7.710067183e-02, -2.899436653e-02, + -2.104065195e-02, 6.964405999e-03, -2.937046811e-02, 6.198379397e-02, -1.701294631e-02, + 3.765193373e-02, -8.400664479e-02, -3.655922040e-02, -1.896228269e-02, 1.068732888e-02, + -2.279973403e-02, 6.116871163e-02, -9.958717972e-03, 3.467707708e-02, -7.409070432e-02, + -3.755651787e-02, -2.440267056e-02, 1.827025227e-02, -1.055546105e-02, 5.659277365e-02, + -8.756000549e-03, 3.645907342e-02, -6.541278213e-02, -3.076048568e-02, -1.720052585e-02, + 1.638240740e-02, -1.236714423e-02, 5.993459374e-02, -1.308731735e-03, 3.584163636e-02, + -5.789547786e-02, -4.672389850e-02, -2.757036686e-02, 1.301552914e-02, -1.174678281e-02, + 5.085360259e-02, -5.739189684e-03, 3.802072629e-02, -5.040255189e-02, -3.418635949e-02, + -2.023626119e-02, 2.422318608e-02, -1.322535239e-02, 5.105735362e-02, -1.563576981e-02, + 2.968759090e-02, -6.625011563e-02, -4.588982463e-02, -4.132758826e-02, 2.561303228e-02, + -1.269047335e-02, 6.734448671e-02, -6.045065820e-04, 4.148148373e-02, -5.611302704e-02, + -4.049664736e-02, -3.455144912e-02, 3.001913242e-02, -1.823448017e-02, 5.309482664e-02, + -2.874221653e-02, 4.355478659e-02, -7.186570019e-02, -3.231408447e-02, -3.186289966e-02, + 2.775838785e-02, -2.713431977e-02, 6.425093114e-02, -2.428580076e-02, 5.235427245e-02, + -6.982646137e-02, -3.021417931e-02, -3.849471360e-02, 9.353779256e-03, -2.723456174e-02, + 4.224546626e-02, -3.723604605e-02, 5.403360724e-02, -6.834104657e-02, -1.303251740e-02, + 4.197156057e-03, 1.061227918e-02, -3.389765695e-02, 4.605862126e-02, -3.987113386e-02, + 4.961792752e-02, -7.773164660e-02, -2.383343130e-02, -1.729112491e-02, -1.836262643e-03, + -3.239594027e-02, 3.611219674e-02, -3.754999861e-02, 3.880498931e-02, -7.795970142e-02, + -4.052660987e-02, -2.258003317e-02, 1.919411123e-03, -3.300013393e-02, 4.533754662e-02, + -3.228609264e-02, 4.300910607e-02, -7.731860876e-02, -3.855267167e-02, -2.299860120e-02, + -3.696240485e-03, -3.744592145e-02, 6.729612499e-02, -8.029721677e-03, 5.217359215e-02, + -6.472844630e-02, -4.449085146e-02, -2.834771387e-02, 1.178830862e-03, -3.606164828e-02, + 7.328617573e-02, -3.271117806e-03, 4.687737674e-02, -6.899672747e-02, -5.573900044e-02, + -4.291112721e-02, -1.347400248e-03, -3.013500199e-02, 7.143912464e-02, 3.530114889e-03, + 4.478195310e-02, -6.224843115e-02, -4.397661984e-02, -2.870511264e-02, -6.534308195e-04, + -2.458010241e-02, 6.888041645e-02, 7.325928658e-03, 3.377281502e-02, -6.540948898e-02, + -5.439072102e-02, -3.092735633e-02, 7.108028233e-02, 8.819280565e-02, 2.710681409e-03, + 1.800112426e-03, 3.385867178e-02, 1.492501236e-02, -7.505089045e-02, -4.543547332e-02, + 4.506141320e-02, 3.151253983e-02, 1.920360141e-02, -2.164467983e-02, 3.344263509e-02, + -3.470505774e-02, -6.369784474e-02, -4.467796534e-02, 4.306885228e-02, 2.904912829e-02, + 5.643933639e-02, 1.957577094e-02, 3.053915873e-02, -2.916823141e-02, -7.572883368e-02, + -6.206411868e-02, 4.849855602e-02, 4.039987922e-02, 2.842467837e-02, -5.033276975e-03, + 3.178856522e-02, -2.702867426e-02, -7.123319805e-02, -5.016776174e-02, 2.350981534e-02, + -1.805691235e-02, 5.574427545e-02, -1.407264918e-02, 3.409930319e-02, -6.396780908e-02, + -5.480723083e-02, -5.851079524e-02, 3.510488570e-02, 5.560815334e-04, 7.031364739e-02, + 7.297493517e-03, 4.131592065e-02, -5.016756803e-02, -5.770603567e-02, -4.967873171e-02, + 3.198132664e-02, -1.778864302e-02, 5.424560606e-02, -2.860884368e-02, 4.591653496e-02, + -7.002239674e-02, -3.868982196e-02, -4.226545990e-02, 2.953825891e-02, -2.804741263e-02, + 6.708187610e-02, -2.324872836e-02, 5.371619388e-02, -6.935936213e-02, -3.624260798e-02, + -4.723981023e-02, 1.131227054e-02, -3.113342263e-02, 4.669903591e-02, -3.659896553e-02, + 5.310977623e-02, -7.104052603e-02, -1.929515786e-02, -9.686701931e-03, 1.073856279e-02, + -3.993432224e-02, 5.233204737e-02, -3.773830086e-02, 4.965767637e-02, -7.981009781e-02, + -2.803888358e-02, -2.999530174e-02, -4.495171830e-03, -4.154253379e-02, 4.525865614e-02, + -3.342786804e-02, 4.265570268e-02, -7.766999304e-02, -3.974499181e-02, -2.893552743e-02, + 5.765445530e-05, -4.122973233e-02, 5.368173122e-02, -2.843000740e-02, 4.480513930e-02, + -7.813094556e-02, -4.029833153e-02, -3.276417404e-02, -5.711987615e-03, + -4.104515165e-02, + 7.307394594e-02, -2.900093794e-03, 5.350678414e-02, -6.310813874e-02, -4.506566003e-02, + -3.117108718e-02, -1.228261739e-03, -3.745876998e-02, 7.499467582e-02, 3.500990570e-04, + 4.459029436e-02, -6.846837699e-02, -5.846046656e-02, -4.507486522e-02, -3.132503480e-03, + -3.225398064e-02, 7.438702136e-02, 6.408605725e-03, 4.513166845e-02, -6.170369685e-02, + -4.418782145e-02, -2.974047326e-02, -3.178853542e-03, -2.666177973e-02, 7.005792111e-02, + 9.545929730e-03, 3.209725022e-02, -6.544381380e-02, -5.581519753e-02, -3.226391971e-02, + 1.758284867e-03, -2.325286530e-02, 6.817771494e-02, 6.908655167e-03, 3.432184830e-02, + -6.320511550e-02, -4.997279122e-02, -3.336627036e-02, 8.193030953e-04, -1.668153144e-02, + 6.059464067e-02, 9.625896811e-03, 2.859356627e-02, -5.584308878e-02, -3.952347487e-02, + -1.723079942e-02, 7.384879515e-03, -1.484216750e-02, 6.643884629e-02, 1.045838743e-02, + 3.293523192e-02, -5.679863319e-02, -5.196435750e-02, -3.286971152e-02, + ], + ] +} diff --git a/Tests/MLXLMTests/LFM3Tests.swift b/Tests/MLXLMTests/LFM3Tests.swift index a2c1227521..a68dfc2ff3 100644 --- a/Tests/MLXLMTests/LFM3Tests.swift +++ b/Tests/MLXLMTests/LFM3Tests.swift @@ -207,40 +207,15 @@ final class LFM3Tests: XCTestCase { } func testTokenizerCompatibilityProbes() throws { - XCTAssertNoThrow(try LFM3Model.validateTokenizer(ProbeTokenizer())) + let model: any LLMModel = try tinyModel() + XCTAssertNoThrow(try model.validate(tokenizer: ProbeTokenizer())) for broken in [".reduce", "line.\r\nThis"] { - XCTAssertThrowsError(try LFM3Model.validateTokenizer(ProbeTokenizer(broken: broken))) { + XCTAssertThrowsError(try model.validate(tokenizer: ProbeTokenizer(broken: broken))) { XCTAssertTrue($0.localizedDescription.contains("ignore_merges")) } } // A custom vocabulary without these byte-level entries is not the affected tokenizer. - XCTAssertNoThrow(try LFM3Model.validateTokenizer(ProbeTokenizer(hasProbeVocabulary: false))) - } - - func testFactoryRejectsIncompatibleTokenizer() async throws { - let directory = FileManager.default.temporaryDirectory.appending( - component: UUID().uuidString) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - let config = try tinyConfiguration() - try JSONEncoder().encode(config).write(to: directory.appending(component: "config.json")) - let model = try tinyModel(config) - try save( - arrays: Dictionary(uniqueKeysWithValues: model.parameters().flattened()), - url: directory.appending(component: "model.safetensors")) - do { - _ = try await LLMModelFactory.shared.load( - from: directory, using: ProbeTokenizerLoader()) - XCTFail("The factory accepted a tokenizer that ignores ignore_merges") - } catch { - XCTAssertTrue(error.localizedDescription.contains("ignore_merges"), "\(error)") - } - } - - private struct ProbeTokenizerLoader: TokenizerLoader { - func load(from directory: URL) async throws -> any Tokenizer { - ProbeTokenizer(broken: ".reduce") - } + XCTAssertNoThrow(try model.validate(tokenizer: ProbeTokenizer(hasProbeVocabulary: false))) } private struct ProbeTokenizer: Tokenizer { @@ -670,82 +645,4 @@ final class LFM3Tests: XCTestCase { XCTAssertGreaterThan(abs(unwindowed - defaults).max().item(Float.self), 1e-3) } - // MARK: - Mixed-precision checkpoint - - /// An MLX conversion wrapped in `language_model` with 4-bit attention and conv, 6-bit - /// MLP, and an 8-bit untied `lm_head`, declared per layer in `config.json`. The prefix - /// mapping must rename tensors and settings together or strict loading fails. - func testLoadsMixedPrecisionWrappedCheckpoint() throws { - let groupSize = 32 - let configuration = try tinyConfiguration(tieWordEmbeddings: false, intermediateSize: 64) - let reference = try tinyModel(configuration) - - let bits = { (path: String) in - path == "lm_head" ? 8 : path.contains(".feed_forward.") ? 6 : 4 - } - var arrays = [String: MLXArray]() - var quantizedPaths = [String]() - for (path, module) in reference.leafModules().flattened() { - let weight: MLXArray - switch module { - case let linear as Linear: weight = linear.weight - case let embedding as Embedding: weight = embedding.weight - default: continue - } - let (wq, scales, biases) = quantized(weight, groupSize: groupSize, bits: bits(path)) - arrays["language_model.\(path).weight"] = wq - arrays["language_model.\(path).scales"] = scales - arrays["language_model.\(path).biases"] = biases - quantizedPaths.append(path) - } - for (key, value) in reference.parameters().flattened() { - let module = key.split(separator: ".").dropLast().joined(separator: ".") - if !quantizedPaths.contains(module) { - arrays["language_model.\(key)"] = value - } - } - arrays["vision_tower.proj.weight"] = MLXArray.zeros([4, 4]) - XCTAssertTrue(quantizedPaths.contains("lm_head")) - XCTAssertTrue(quantizedPaths.contains { $0.hasSuffix("conv.in_proj") }) - - // Per-layer entries use the checkpoint's own (wrapped) names. - let overrides = - quantizedPaths.filter { bits($0) != 4 }.map { path in - #""language_model.\#(path)": {"group_size": \#(groupSize), "bits": \#(bits(path))}"# - } + [#""vision_tower.proj": {"group_size": \#(groupSize), "bits": 8}"#] - let baseConfiguration = try JSONDecoder().decode( - BaseConfiguration.self, - from: Data( - """ - { - "model_type": "lfm3", - "quantization": { - "group_size": \(groupSize), "bits": 4, - \(overrides.joined(separator: ",\n")) - } - } - """.utf8)) - - let directory = FileManager.default.temporaryDirectory - .appending(component: "lfm3-mixed-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - try save(arrays: arrays, url: directory.appending(component: "model.safetensors")) - - let model = LFM3Model(configuration) - try loadWeights( - modelDirectory: directory, model: model, - perLayerQuantization: baseConfiguration.perLayerQuantization) - - let modules = Dictionary(uniqueKeysWithValues: model.leafModules().flattened()) - for path in quantizedPaths { - let module = try XCTUnwrap(modules[path] as? Quantized, path) - XCTAssertEqual(module.bits, bits(path), path) - XCTAssertEqual(module.groupSize, groupSize, path) - } - - let logits = model(MLXArray([Int32(1), 2, 3, 4, 5]).reshaped(1, 5), cache: nil) - XCTAssertEqual(logits.shape, [1, 5, 64]) - XCTAssertFalse(any(isNaN(logits)).item(Bool.self)) - } } diff --git a/Tests/MLXLMTests/Resources/lfm3-reference-config.json b/Tests/MLXLMTests/Resources/lfm3-reference-config.json deleted file mode 100644 index 624fa1005a..0000000000 --- a/Tests/MLXLMTests/Resources/lfm3-reference-config.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "transformers_version": "5.22.1", - "architectures": [ - "Lfm3ForCausalLM" - ], - "output_hidden_states": false, - "return_dict": true, - "dtype": "bfloat16", - "chunk_size_feed_forward": 0, - "is_encoder_decoder": false, - "id2label": { - "0": "LABEL_0", - "1": "LABEL_1" - }, - "label2id": { - "LABEL_0": 0, - "LABEL_1": 1 - }, - "problem_type": null, - "vocab_size": 16, - "hidden_size": 8, - "intermediate_size": 16, - "num_hidden_layers": 3, - "num_attention_heads": 2, - "num_key_value_heads": 1, - "max_position_embeddings": 262144, - "initializer_range": 0.02, - "norm_eps": 1e-05, - "use_cache": true, - "pad_token_id": 0, - "bos_token_id": 1, - "eos_token_id": 2, - "tie_word_embeddings": true, - "rope_parameters": { - "full_attention": { - "partial_rotary_factor": 0.5, - "rope_theta": 1000000.0, - "rope_type": "default" - }, - "sliding_attention": { - "rope_theta": 10000, - "rope_type": "default" - } - }, - "conv_bias": true, - "conv_L_cache": 7, - "layer_types": [ - "conv", - "full_attention", - "sliding_attention" - ], - "head_dim": 8, - "sliding_window": 4, - "use_sandwich_norm": true, - "model_type": "lfm3", - "output_attentions": false -} diff --git a/Tests/MLXLMTests/Resources/lfm3-reference-outputs.safetensors b/Tests/MLXLMTests/Resources/lfm3-reference-outputs.safetensors deleted file mode 100644 index 2abe1ebf5466556ee05c65514139463400486af9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 15752 zcmeI(d036x-#_psQ8cJ%qDeGJnl$cveQrr*N~lapvnfR~Pe~|}qCzDkb4Z4!eXq46 zq)3P|MCMM&Os4!kop0xQ&UL=$InVVx&-MH7+1K^Hx_7P5XRW>NUHjGUu31*<_uF!# z>C@+i#RP>0#RN^CZsfe&XhGD%=#a4K(P4{bEtnM*Y2<7a6k;>P(LTu5F5EiEI>gG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z2kU4=ykC&k`BKM6Z@^+hR>`dn#ckocW!ityPkm&-V7D;&SRlWSYsBIxj2x$uit z#IEIXnWB*`CrR7s99&{6>iu+=p!oitFj7o}j(>Mn#7JYhVN@{k7$uAxraMLkqk!qS Qb;T%Sx?p->{(sf~KLb?2&Hw-a diff --git a/Tests/MLXLMTests/Resources/lfm3-reference-weights.safetensors b/Tests/MLXLMTests/Resources/lfm3-reference-weights.safetensors deleted file mode 100644 index a549f1f66d731fceb42376b34fe2ed76bde45209..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 14968 zcmeI0zi!%46vq7seFWtB$g(fS*pZqtRUI={sv>ZUNoWWr;3kctNDLh^bjZ-5Lx;Xd z5s%jIkU|VT;K-&!a*gy=N@e}-z32bEN3V><@5UUQw@;(6Yh6YClhedJxG}rQ^(ZnA z%(r!Ak~ujI`L7R-NB%LH-7pE;aj!Rtk_rCTriP=AZ^=B5yV1ak&Ob)ob`qaO!%0CR zc;wj1-GFxc!;|(f9-rr8gcw*Vsr+9ez@XyD7h$C$~zld#k!2149 zY@T6#a;TZLEOW`Jr>(ob=l-xg8pofl-P?vCGfrbFIj+5R-%E7f)?ro2EFhC|np>?M ze@ULQbpg#(Qfm9oSLnR0`_j&tOv?3A!MCz`FG6JZ;_+2DMzT1$VJPPd!$}3AZPr&% zxho(%ysUE>PIXrd%JmiMxhu$LU^uz9Z3|)F>kSKMDI>wHr|QYd`tc|lheJ2D+H2PC()qS4wGbP zorFpBQ1kN&vyuuk^Qqwr4cxIF7db0j9T*M1P&C*1i-wzb0FQm)`Ty$;eLdsmgh2U4# zehMkWDR7kJ)yEoFvXC+#i}=|xr1nxs8BKx0V7j^!t{nV$h_ez2%y0_aX13p?Pf)6m zGM$1T$4JEsDWh?3v~#Rfs**17eCHMBinO81)Y1hVYc$zXw>AD5#&l*F9jFD>AOo8J z!T&=Bi+`{2H#CQgLwpCdpbj);%__!owMXSUy<_?78{{wa4Z4HAL-)`R=qEISc75~W zYX<6D4f6+8w`GPgmbH*@m?m1$i z$`L*1)2bHgQwyaTLzg}voxO$H_u}WvoSEl0`e6&&)+d*9`Y(JVeY@FDH|P9ay_df= z(0gl8#R6=gnLT#B{qXycbZ1NVn7saU2gc@`Q@WRx zeGf?ACDZ%5$GW_?Io=x#__PMKAl>|1<+YxEU*0RWy}K-Pg~!vfIao2C?;DPeHF236 z9QU;uq8FN1Z*Y3v0}umKNcTA*ofA6QV~V`j_3YJs&oI(=5$O$Xd5_?`ko0Zd{YYY_ t?<{5K^KJWD&V4QPwwlI0u9{8to^5u$J#cPL539GY8f>8JJwWfd|1S(yJum` and `` framing. It does not use the LFM2 format. -Small FP32 reference fixtures run in the unit suite without downloads. Regenerate -them with `python scripts/lfm3-reference.py`, which pins LiquidAI's source revision. -For a downloaded official 4-bit checkpoint, `scripts/lfm3-checkpoint-reference.py` +Unit tests generate deterministic weights in memory and compare every operator, +layer, and logit against FP32 reference values embedded in Swift. Regenerate those +values with `python tools/lfm3-reference.py`, which pins LiquidAI's source revision. +No model files or downloads are needed to run the unit tests. +For a downloaded official 4-bit checkpoint, `tools/lfm3-checkpoint-reference.py` exports matching FP32 logits from the original Hugging Face implementation. -`LFM3CheckpointTests` reads `MLX_LFM3_CHECKPOINT` and `MLX_LFM3_REFERENCE_FILE`; -set `MLX_ENABLE_TF32=0` in the test process for that parity check. +`IntegrationTesting/IntegrationTestingTests/LFM3CheckpointTests.swift` reads +`MLX_LFM3_CHECKPOINT` and `MLX_LFM3_REFERENCE_FILE`; set `MLX_ENABLE_TF32=0` in the +test process for that parity check. The same integration class covers temporary +mixed-precision checkpoints and factory rejection of incompatible tokenizers. `MLX_LFM3_LONG_CONTEXT=1` enables the synthetic 4K/16K/32K cache tests. The integration project's tokenizer goldens are opt-in with `MLX_RUN_LFM3_TOKENIZER=1`; `MLX_LFM3_TOKENIZER_DIRECTORY` selects local tokenizer diff --git a/scripts/lfm3-checkpoint-reference.py b/tools/lfm3-checkpoint-reference.py similarity index 97% rename from scripts/lfm3-checkpoint-reference.py rename to tools/lfm3-checkpoint-reference.py index 1c441d4e91..14b98ac46a 100644 --- a/scripts/lfm3-checkpoint-reference.py +++ b/tools/lfm3-checkpoint-reference.py @@ -6,7 +6,7 @@ separately. This script runs LiquidAI's pinned Python code on the CPU and uses about 8 GB of memory to dequantize the same weights used by the Swift test. -python scripts/lfm3-checkpoint-reference.py /path/to/checkpoint /tmp/lfm3-reference.safetensors +python tools/lfm3-checkpoint-reference.py /path/to/checkpoint /tmp/lfm3-reference.safetensors Then run LFM3CheckpointTests with MLX_LFM3_CHECKPOINT, MLX_LFM3_REFERENCE_FILE and MLX_ENABLE_TF32=0 set in the test process environment. """ diff --git a/tools/lfm3-reference.py b/tools/lfm3-reference.py new file mode 100644 index 0000000000..cec4ec036e --- /dev/null +++ b/tools/lfm3-reference.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Generate Swift FP32 reference values from LiquidAI's original implementation. + +Requires torch, transformers==5.22.1 and huggingface_hub. +Run from the repository root: python tools/lfm3-reference.py +The downloaded Python code is pinned and runs on the CPU without model weights. +Weights are generated in sorted parameter-name order, as in LFM3ReferenceTests. +""" + +import json +from pathlib import Path +from tempfile import TemporaryDirectory + +import torch +from huggingface_hub import snapshot_download +from transformers import AutoConfig, AutoModelForCausalLM + +REVISION = "ac2586a34f1a1c03329dbdcdefabd8b6478ddaa7" +OUTPUT = Path(__file__).resolve().parents[1] / "Tests/MLXLMTests/LFM3ReferenceValues.swift" +CONFIG = { + "model_type": "lfm3", "hidden_size": 8, "intermediate_size": 16, + "num_hidden_layers": 3, "num_attention_heads": 2, "num_key_value_heads": 1, + "head_dim": 8, "vocab_size": 16, + "layer_types": ["conv", "full_attention", "sliding_attention"], + "sliding_window": 4, "conv_L_cache": 7, "conv_bias": True, + "norm_eps": 1e-5, "use_sandwich_norm": True, "tie_word_embeddings": True, + "pad_token_id": 0, "bos_token_id": 1, "eos_token_id": 2, + "rope_parameters": { + "full_attention": { + "rope_type": "default", "rope_theta": 1000000.0, "partial_rotary_factor": 0.5, + }, + "sliding_attention": {"rope_type": "default", "rope_theta": 10000.0}, + }, +} + + +def main(): + torch.set_num_threads(4) + torch.manual_seed(7) + with TemporaryDirectory(prefix="lfm3-reference-") as source: + snapshot_download( + "LiquidAI/LFM3-1.7B", revision=REVISION, + allow_patterns=["config.json", "*.py"], local_dir=source, + ) + config = AutoConfig.from_pretrained(source, trust_remote_code=True) + for key, value in CONFIG.items(): + setattr(config, key, value) + config._attn_implementation = "eager" + model = AutoModelForCausalLM.from_config(config, trust_remote_code=True).float().eval() + with torch.no_grad(): + for i, (_name, parameter) in enumerate(sorted(model.named_parameters())): + values = (torch.arange(parameter.numel()).reshape(parameter.shape) + i * 3) % 17 + parameter.copy_((values.float() - 8) / 32) + if parameter.ndim == 1 and parameter.numel() == CONFIG["hidden_size"]: + parameter.add_(1) + outputs = {} + handles = [] + for name, module in model.named_modules(): + if name in ["model.embed_tokens", "model.embedding_norm"] or ( + name.startswith("model.layers.") and name.count(".") == 2 + ) or name.endswith((".conv", ".self_attn")) and name.count(".") == 3: + def hook(_module, _args, result, name=name): + tensor = result[0] if isinstance(result, tuple) else result + outputs[name] = tensor.detach().contiguous().clone() + handles.append(module.register_forward_hook(hook)) + tokens = torch.tensor([(i * 7 + 3) % 16 for i in range(38)]).reshape(2, 19) + with torch.no_grad(): + outputs["logits"] = model(tokens, use_cache=False).logits + for handle in handles: + handle.remove() + with torch.no_grad(): + cache = None + logits = [] + for start, end in [(0, 2), (2, 7), (7, 18), (18, 19)]: + out = model(tokens[:, start:end], past_key_values=cache, use_cache=True) + logits.append(out.logits) + cache = out.past_key_values + error = (torch.cat(logits, dim=1) - outputs["logits"]).abs().max().item() + assert error < 2e-5, f"Reference cached/uncached mismatch: {error}" + lines = [ + "// Generated by tools/lfm3-reference.py; do not edit values by hand.", + f"// LiquidAI/LFM3-1.7B {REVISION}; PyTorch CPU FP32, transformers 5.22.1.", + "", "enum LFM3ReferenceValues {", ' static let configuration = """', + *[" " + line for line in json.dumps(CONFIG, indent=2).splitlines()], + ' """', "", " static let outputs: [String: [Float]] = [", + ] + for name, tensor in sorted(outputs.items()): + lines.append(f' "{name}": [') + values = tensor.flatten().tolist() + for offset in range(0, len(values), 5): + lines.append(" " + ", ".join(f"{value:.9e}" for value in values[offset:offset+5]) + ",") + lines.append(" ],") + lines.extend([" ]", "}", ""]) + OUTPUT.write_text("\n".join(lines)) + print(f"Reference cached/uncached maximum absolute error: {error:.9g}") + print(f"Wrote {OUTPUT} ({sum(t.numel() for t in outputs.values())} reference values)") + + +if __name__ == "__main__": + main() From 0074d858fdfa2c8a00ba81933f499e1689f94c5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Garc=C3=ADa=20Pizarro?= <81751965+alvarogarciapiz@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:03:16 +0100 Subject: [PATCH 6/7] fix(lfm3): address backbone and generation review feedback --- .../LFM3CheckpointTests.swift | 30 ++--- .../LFM3TokenizerIntegrationTests.swift | 6 + Libraries/MLXLLM/Models/LFM3.swift | 16 ++- Libraries/MLXLMCommon/Models/LFM3.swift | 46 +++++--- Tests/MLXLMTests/LFM3ReferenceValues.swift | 15 +++ Tests/MLXLMTests/LFM3Tests.swift | 106 +++++++++++++++--- .../references/supported-models.md | 10 ++ tools/lfm3-reference.py | 27 +++++ 8 files changed, 206 insertions(+), 50 deletions(-) diff --git a/IntegrationTesting/IntegrationTestingTests/LFM3CheckpointTests.swift b/IntegrationTesting/IntegrationTestingTests/LFM3CheckpointTests.swift index 22c588d8c3..75e1fed6ae 100644 --- a/IntegrationTesting/IntegrationTestingTests/LFM3CheckpointTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/LFM3CheckpointTests.swift @@ -40,13 +40,16 @@ final class LFM3CheckpointTests: XCTestCase { .reshaped(1, count) let cache = try model.newCache(parameters: nil) let start = Date.timeIntervalSinceReferenceDate - var hidden: MLXArray? + var output: MLXArray? for offset in stride(from: 0, to: count, by: 256) { - hidden = model.hiddenStates(tokens[0..., offset ..< offset + 256], cache: cache) - eval(hidden!) + output = + model.nextTokenLogits( + .init(tokens: tokens[0..., offset ..< offset + 256]), cache: cache, state: nil + ).logits + eval(output!) eval(cache) } - var logits = model.projectLogits(try XCTUnwrap(hidden)[0..., (-1)...]) + var logits = try XCTUnwrap(output)[0..., (-1)...] eval(logits) let prefillSeconds = Date.timeIntervalSinceReferenceDate - start let decodeStart = Date.timeIntervalSinceReferenceDate @@ -75,24 +78,23 @@ final class LFM3CheckpointTests: XCTestCase { for length in [19, 257, 1024] { let tokens = try XCTUnwrap(reference["tokens_\(length)"]) let cache = try model.newCache(parameters: nil) - var hidden: MLXArray? + var output: MLXArray? for start in stride(from: 0, to: length, by: 127) { - hidden = model.hiddenStates( - tokens[0..., start ..< min(start + 127, length)], cache: cache) - eval(hidden!) + output = + model.nextTokenLogits( + .init(tokens: tokens[0..., start ..< min(start + 127, length)]), + cache: cache, state: nil + ).logits + eval(output!) eval(cache) } - let final = try XCTUnwrap(hidden)[0..., (-1)...] - let logits = model.projectLogits(final) + let logits = try XCTUnwrap(output)[0..., (-1)...] let expected = try XCTUnwrap(reference["logits_\(length)"]) let error = abs(logits - expected).max().item(Float.self) - let hiddenError = abs(final - (try XCTUnwrap(reference["hidden_\(length)"]))).max() - .item(Float.self) print( - "LFM3 published FP32 \(length): logits_max_abs=\(error), hidden_max_abs=\(hiddenError)" + "LFM3 published FP32 \(length): logits_max_abs=\(error)" ) XCTAssertLessThan(error, 2e-4) - XCTAssertLessThan(hiddenError, 2e-4) XCTAssertEqual( argMax(logits, axis: -1).item(Int.self), argMax(expected, axis: -1).item(Int.self)) } diff --git a/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift b/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift index 486a57e028..194b54a9c9 100644 --- a/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/LFM3TokenizerIntegrationTests.swift @@ -44,6 +44,12 @@ struct LFM3TokenizerIntegrationTests { ]) #expect( plain == [124894, 124899, 5922, 207, 35808, 124900, 207, 124899, 63514, 207, 124901]) + let disabled = try tokenizer.applyChatTemplate( + messages: [["role": "user", "content": "Hello"]], + tools: nil, additionalContext: ["enable_thinking": false]) + #expect( + tokenizer.decode(tokens: disabled, skipSpecialTokens: false).hasSuffix( + "")) let messages: [[String: any Sendable]] = [ ["role": "system", "content": "Be precise."], ["role": "user", "content": "Weather?"], diff --git a/Libraries/MLXLLM/Models/LFM3.swift b/Libraries/MLXLLM/Models/LFM3.swift index ace115f888..a82d9bcfe3 100644 --- a/Libraries/MLXLLM/Models/LFM3.swift +++ b/Libraries/MLXLLM/Models/LFM3.swift @@ -16,7 +16,7 @@ public class LFM3Model: Module, LLMModel, KVCacheDimensionProvider { public let vocabularySize: Int public let kvHeads: [Int] - public let model: LFM3ModelInner + package let model: LFM3ModelInner let configuration: LFM3Configuration @ModuleInfo(key: "lm_head") var lmHead: Linear? @@ -35,6 +35,16 @@ public class LFM3Model: Module, LLMModel, KVCacheDimensionProvider { projectLogits(model(inputs, cache: cache)) } + public func nextTokenLogits( + _ input: LMInput.Text, cache: [KVCache]?, state: LMOutput.State? + ) -> LMOutput { + let hidden = hiddenStates(input.tokens, cache: cache) + let projection: Module = lmHead ?? model.embedTokens + return .init( + logits: projectLogits( + quantizedVocabularyProjectionInput(hidden, projection: projection))) + } + public func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint { // MLX conversions nest the text model under `language_model`. Keep only the text // model, which drops any vision or audio tensors. The same mapping renames the @@ -107,12 +117,12 @@ extension LFM3Model { extension LFM3Model: HiddenStateLanguageModel { /// Final normed hidden states `[B, L, hidden]` for token ids `[B, L]`. - public func hiddenStates(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + package func hiddenStates(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { model(inputs, cache: cache) } /// Vocabulary logits for final hidden states, tied or untied. - public func projectLogits(_ hiddenStates: MLXArray) -> MLXArray { + package func projectLogits(_ hiddenStates: MLXArray) -> MLXArray { model.projectLogits(hiddenStates, lmHead: lmHead) } } diff --git a/Libraries/MLXLMCommon/Models/LFM3.swift b/Libraries/MLXLMCommon/Models/LFM3.swift index b786200a2a..a4033ccbbe 100644 --- a/Libraries/MLXLMCommon/Models/LFM3.swift +++ b/Libraries/MLXLMCommon/Models/LFM3.swift @@ -23,7 +23,7 @@ public struct LFM3Configuration: Codable, Sendable { case slidingAttention = "sliding_attention" } - public struct RopeParameters: Codable, Sendable { + package struct RopeParameters: Codable, Sendable { package let ropeType: String package let ropeTheta: Float package let partialRotaryFactor: Float @@ -40,7 +40,7 @@ public struct LFM3Configuration: Codable, Sendable { self.partialRotaryFactor = partialRotaryFactor } - public init(from decoder: Decoder) throws { + package init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.ropeType = try container.decodeIfPresent(String.self, forKey: .ropeType) ?? "default" @@ -88,6 +88,10 @@ public struct LFM3Configuration: Codable, Sendable { case ropeParameters = "rope_parameters" } + private enum AltCodingKeys: String, CodingKey { + case tieEmbedding = "tie_embedding" + } + public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) @@ -123,8 +127,10 @@ public struct LFM3Configuration: Codable, Sendable { try container.decodeIfPresent(Int.self, forKey: .slidingWindow) ?? 256 self.useSandwichNorm = try container.decodeIfPresent(Bool.self, forKey: .useSandwichNorm) ?? true + let alt = try decoder.container(keyedBy: AltCodingKeys.self) self.tieWordEmbeddings = - try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true + try alt.decodeIfPresent(Bool.self, forKey: .tieEmbedding) + ?? container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true for (key, value) in [ (CodingKeys.vocabularySize, vocabularySize), (.hiddenLayers, hiddenLayers), @@ -402,11 +408,15 @@ package class LFM3DecoderLayer: Module { /// /// A `nil` entry uses the default: causal for full attention, and causal within the /// sliding window for sliding attention, both sized by the first cache of that type. -public struct LFM3AttentionMasks { - public var fullAttention: MLXFast.ScaledDotProductAttentionMaskMode? - public var slidingAttention: MLXFast.ScaledDotProductAttentionMaskMode? - - public init( +/// To disable masking, spell out `MLXFast.ScaledDotProductAttentionMaskMode.none`; +/// a bare `.none` means `nil` and keeps the default. +/// Build cached sliding array masks with `makeAttentionMask(n:cache:windowSize:returnArray:)` +/// so their key dimension matches the truncated cache. +package struct LFM3AttentionMasks { + package var fullAttention: MLXFast.ScaledDotProductAttentionMaskMode? + package var slidingAttention: MLXFast.ScaledDotProductAttentionMaskMode? + + package init( fullAttention: MLXFast.ScaledDotProductAttentionMaskMode? = nil, slidingAttention: MLXFast.ScaledDotProductAttentionMaskMode? = nil ) { @@ -417,21 +427,21 @@ public struct LFM3AttentionMasks { /// The LFM3 text backbone: token embedding, decoder layers, and the final norm. /// -/// The caller owns the caches, one per layer from ``newCache(parameters:)``. Positions come +/// The caller owns the caches, one per layer from `newCache(parameters:)`. Positions come /// from the caches, so a sequence can be fed in chunks of token ids or embeddings. -public class LFM3ModelInner: Module { +package class LFM3ModelInner: Module { let args: LFM3Configuration let firstFullAttentionIdx: Int? let firstSlidingAttentionIdx: Int? package let layers: [LFM3DecoderLayer] - @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + @ModuleInfo(key: "embed_tokens") package var embedTokens: Embedding @ModuleInfo(key: "embedding_norm") var embeddingNorm: RMSNorm - public var hiddenSize: Int { args.hiddenSize } + package var hiddenSize: Int { args.hiddenSize } - public init(_ args: LFM3Configuration) { + package init(_ args: LFM3Configuration) { self.args = args self.firstFullAttentionIdx = args.layerTypes.firstIndex(of: .fullAttention) self.firstSlidingAttentionIdx = args.layerTypes.firstIndex(of: .slidingAttention) @@ -447,19 +457,19 @@ public class LFM3ModelInner: Module { } /// Token embeddings `[B, L, hidden]` for token ids `[B, L]`. - public func embed(_ inputs: MLXArray) -> MLXArray { + package func embed(_ inputs: MLXArray) -> MLXArray { embedTokens(inputs) } /// Final normed hidden states `[B, L, hidden]` for token ids `[B, L]`. - public func callAsFunction( + package func callAsFunction( _ inputs: MLXArray, cache: [KVCache]? = nil, masks: LFM3AttentionMasks = .init() ) -> MLXArray { callAsFunction(embeddings: embed(inputs), cache: cache, masks: masks) } /// Final normed hidden states `[B, L, hidden]` for input embeddings `[B, L, hidden]`. - public func callAsFunction( + package func callAsFunction( embeddings: MLXArray, cache: [KVCache]? = nil, masks: LFM3AttentionMasks = .init() ) -> MLXArray { precondition( @@ -494,13 +504,13 @@ public class LFM3ModelInner: Module { /// Vocabulary logits for final hidden states, through `lmHead` when the checkpoint has /// one and the tied token embedding otherwise. - public func projectLogits(_ hiddenStates: MLXArray, lmHead: Linear? = nil) -> MLXArray { + package func projectLogits(_ hiddenStates: MLXArray, lmHead: Linear? = nil) -> MLXArray { lmHead?(hiddenStates) ?? embedTokens.asLinear(hiddenStates) } /// One cache per layer: a conv state for conv layers, a rotating cache bounded by the /// sliding window for sliding attention, and a full or `maxKVSize` cache otherwise. - public func newCache(parameters: GenerateParameters?) throws -> [KVCache] { + package func newCache(parameters: GenerateParameters?) throws -> [KVCache] { try args.layerTypes.map { layerType in switch layerType { case .conv: diff --git a/Tests/MLXLMTests/LFM3ReferenceValues.swift b/Tests/MLXLMTests/LFM3ReferenceValues.swift index 6782c4a948..89606dbf43 100644 --- a/Tests/MLXLMTests/LFM3ReferenceValues.swift +++ b/Tests/MLXLMTests/LFM3ReferenceValues.swift @@ -700,4 +700,19 @@ enum LFM3ReferenceValues { 3.293523192e-02, -5.679863319e-02, -5.196435750e-02, -3.286971152e-02, ], ] + + static let hashedLogits: [Int: [Float]] = [ + 3: [ + 1.240939051e-01, -6.289821267e-01, 8.088644743e-01, -5.961106420e-01, 5.249673128e-01, + -1.244127870e+00, 5.900724530e-01, -4.829960763e-01, + ], + 10: [ + 8.972907662e-01, -1.016793609e+00, -4.222442210e-01, -5.287020802e-01, -9.637345374e-02, + 2.485466719e+00, -5.846538544e-01, 1.707480289e-02, + ], + 18: [ + 4.025134742e-01, -1.513104886e-01, -3.619070649e-01, -7.813684344e-01, 5.966317058e-01, + 1.133238152e-01, 4.363057762e-02, -3.467928767e-01, + ], + ] } diff --git a/Tests/MLXLMTests/LFM3Tests.swift b/Tests/MLXLMTests/LFM3Tests.swift index a68dfc2ff3..408cc97f91 100644 --- a/Tests/MLXLMTests/LFM3Tests.swift +++ b/Tests/MLXLMTests/LFM3Tests.swift @@ -148,6 +148,23 @@ final class LFM3Tests: XCTestCase { XCTAssertEqual(c.ropeParameters["sliding_attention"]?.ropeTheta, 10_000) } + func testLegacyEmbeddingAliasTakesPrecedence() throws { + for (alias, canonical) in [(false, true), (true, false)] { + var json = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(realConfigJSON.utf8)) as? [String: Any]) + json["tie_embedding"] = alias + for canonicalValue in [canonical, nil] { + json["tie_word_embeddings"] = canonicalValue + let data = try JSONSerialization.data(withJSONObject: json) + let config = try JSONDecoder().decode(LFM3Configuration.self, from: data) + XCTAssertEqual(config.tieWordEmbeddings, alias) + let roundTrip = try JSONDecoder().decode( + LFM3Configuration.self, from: JSONEncoder().encode(config)) + XCTAssertEqual(roundTrip.tieWordEmbeddings, alias) + } + } + } + func testInvalidConfigsThrow() throws { XCTAssertThrowsError( try tinyConfiguration(layerTypes: ["conv", "linear_attention"])) @@ -246,8 +263,7 @@ final class LFM3Tests: XCTestCase { func testOfficialXMLToolCallFormat() throws { let model = try tinyModel() XCTAssertEqual(model.toolCallFormat, .xmlFunction) - XCTAssertEqual(model.reasoningConfig?.startDelimiter, "") - XCTAssertEqual(model.reasoningConfig?.endDelimiter, "") + XCTAssertEqual(model.reasoningConfig, .thinkTagsWithEnableThinking) // Rendered by LiquidAI's chat_template.jinja, not LFM2's Python-style format. let payload = """ @@ -286,11 +302,71 @@ final class LFM3Tests: XCTestCase { XCTAssertNil(model.lmHead) } + func testLogitsMatchHashedReference() throws { + try Device.withDefaultDevice(.cpu) { + let model = try tinyModel() + var start = 0 + var weights = [String: MLXArray]() + for (name, parameter) in model.parameters().flattened().sorted(by: { $0.0 < $1.0 }) { + let values = (start ..< start + parameter.size).map { i in + let u = Double(UInt64(i) * 2_654_435_761 % (1 << 32)) / 4_294_967_296 - 0.5 + return Float(parameter.ndim == 1 ? 1 + u : u / 2) + } + weights[name] = MLXArray(values, parameter.shape) + start += parameter.size + } + try model.update(parameters: ModuleParameters.unflattened(weights), verify: [.all]) + let tokens = MLXArray((0 ..< 19).map { Int32(($0 * 7 + 3) % 64) }).reshaped(1, 19) + let logits = model(tokens, cache: nil) + for (position, values) in LFM3ReferenceValues.hashedLogits { + XCTAssertLessThan( + abs(logits[0, position, 0 ..< 8] - MLXArray(values)).max().item(Float.self), + 1e-4) + } + } + } + func testUntiedEmbeddingsUseLMHead() throws { let model = try tinyModel(tinyConfiguration(tieWordEmbeddings: false)) - XCTAssertNotNil(model.lmHead) - XCTAssertEqual( - model(MLXArray([Int32(1), 2, 3]).reshaped(1, 3), cache: nil).shape, [1, 3, 64]) + let head = try XCTUnwrap(model.lmHead) + let tokens = MLXArray([Int32(1), 2, 3]).reshaped(1, 3) + let logits = model(tokens, cache: nil) + XCTAssertEqual(logits.shape, [1, 3, 64]) + XCTAssertEqual(abs(logits - head(model.model(tokens))).max().item(Float.self), 0) + } + + func testNextTokenProjectionPreservesLastLogitsAndCache() throws { + for tied in [true, false] { + for bits: Int? in [nil, 4, 6, 8] { + let model = try tinyModel( + tinyConfiguration(tieWordEmbeddings: tied, intermediateSize: 64)) + if let bits { quantize(model: model, groupSize: 32, bits: bits) } + for length in [1, 33, 97, 129, 257, 511, 512, 513] { + let tokens = MLXArray((0 ..< length).map { Int32(($0 * 7 + 3) % 64) }).reshaped( + 1, length) + let expectedCache = try model.newCache(parameters: nil) + let actualCache = try model.newCache(parameters: nil) + let expected = model(tokens, cache: expectedCache) + let output = model.nextTokenLogits( + .init(tokens: tokens), cache: actualCache, state: nil) + XCTAssertEqual(expected.shape, [1, length, 64]) + if bits == nil { XCTAssertEqual(output.logits.shape, expected.shape) } + if bits != nil && length >= 97 { + XCTAssertLessThanOrEqual(output.logits.dim(1), 96) + } + XCTAssertEqual( + abs(output.logits[0..., -1, 0...] - expected[0..., -1, 0...]).max().item( + Float.self), 0) + for (a, b) in zip(actualCache, expectedCache) { + XCTAssertEqual(a.offset, b.offset) + XCTAssertEqual(a.state.count, b.state.count) + for (x, y) in zip(a.state, b.state) { + XCTAssertEqual(abs(x - y).max().item(Float.self), 0) + } + } + } + } + } } func testCacheTypesPerLayer() throws { @@ -633,16 +709,16 @@ final class LFM3Tests: XCTestCase { let window = model.configuration.slidingWindow let defaults = model.model(tokens) - let explicit = model.model( - tokens, - masks: .init( - fullAttention: .causal, - slidingAttention: .array(createCausalMask(n: 9, offset: 0, windowSize: window)))) - XCTAssertLessThan(abs(explicit - defaults).max().item(Float.self), 1e-5) - - // A plain causal mask lets sliding layers see past the window. - let unwindowed = model.model(tokens, masks: .init(slidingAttention: .causal)) - XCTAssertGreaterThan(abs(unwindowed - defaults).max().item(Float.self), 1e-3) + let difference = { (masks: LFM3AttentionMasks) in + abs(model.model(tokens, masks: masks) - defaults).max().item(Float.self) + } + let windowed = MLXFast.ScaledDotProductAttentionMaskMode.array( + createCausalMask(n: 9, offset: 0, windowSize: window)) + XCTAssertLessThan(difference(.init(fullAttention: .causal)), 1e-5) + XCTAssertLessThan(difference(.init(slidingAttention: windowed)), 1e-5) + let unmasked = MLXFast.ScaledDotProductAttentionMaskMode.none + XCTAssertGreaterThan(difference(.init(fullAttention: unmasked)), 1e-3) + XCTAssertGreaterThan(difference(.init(slidingAttention: .causal)), 1e-3) } } diff --git a/skills/mlx-swift-lm/references/supported-models.md b/skills/mlx-swift-lm/references/supported-models.md index 05f17c55d7..016ed26682 100644 --- a/skills/mlx-swift-lm/references/supported-models.md +++ b/skills/mlx-swift-lm/references/supported-models.md @@ -128,6 +128,16 @@ at load time. The core package does not depend on Swift Transformers. The official text checkpoint uses XML function calls (`.xmlFunction`), with `` and `` framing. It does not use the LFM2 format. +Reasoning uses `.thinkTagsWithEnableThinking`, matching the official template's +`enable_thinking` flag and default-on behavior. LiquidAI documents that disabling +thinking traces can be inconsistent, especially on reasoning-heavy tasks; see the +[model card](https://huggingface.co/LiquidAI/LFM3-1.7B#inference). + +The decoder also honors the reference's `tie_embedding` alias, which takes +precedence over `tie_word_embeddings`. Backbone and hidden-state helpers stay +inside the package. Ordinary generation uses `nextTokenLogits` to avoid projecting +unused prompt rows when the quantized projection supports it; full forwards retain +all positions. Unit tests generate deterministic weights in memory and compare every operator, layer, and logit against FP32 reference values embedded in Swift. Regenerate those diff --git a/tools/lfm3-reference.py b/tools/lfm3-reference.py index cec4ec036e..d92ad45e2c 100644 --- a/tools/lfm3-reference.py +++ b/tools/lfm3-reference.py @@ -77,6 +77,26 @@ def hook(_module, _args, result, name=name): cache = out.past_key_values error = (torch.cat(logits, dim=1) - outputs["logits"]).abs().max().item() assert error < 2e-5, f"Reference cached/uncached mismatch: {error}" + # Hashed parameters and sample positions follow @ykhrustalev's review of PR #750. + hashed_config = CONFIG | { + "hidden_size": 32, "intermediate_size": 48, "num_hidden_layers": 6, + "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 16, + "vocab_size": 64, "conv_L_cache": 3, "conv_bias": False, + "layer_types": ["conv", "sliding_attention", "full_attention"] * 2, + } + hashed_config = type(config)(**hashed_config) + hashed_config._attn_implementation = "eager" + hashed_model = type(model)(hashed_config).float().eval() + start = 0 + with torch.no_grad(): + for _name, parameter in sorted(hashed_model.named_parameters()): + indices = torch.arange(start, start + parameter.numel(), dtype=torch.int64) + u = (indices * 2654435761 % (1 << 32)).double() / 4294967296 - 0.5 + values = 1 + u if parameter.ndim == 1 else u / 2 + parameter.copy_(values.float().reshape(parameter.shape)) + start += parameter.numel() + hashed_tokens = torch.tensor([(i * 7 + 3) % 64 for i in range(19)]).reshape(1, 19) + hashed_logits = hashed_model(hashed_tokens, use_cache=False).logits lines = [ "// Generated by tools/lfm3-reference.py; do not edit values by hand.", f"// LiquidAI/LFM3-1.7B {REVISION}; PyTorch CPU FP32, transformers 5.22.1.", @@ -90,6 +110,13 @@ def hook(_module, _args, result, name=name): for offset in range(0, len(values), 5): lines.append(" " + ", ".join(f"{value:.9e}" for value in values[offset:offset+5]) + ",") lines.append(" ],") + lines.extend([" ]", "", " static let hashedLogits: [Int: [Float]] = ["]) + for position in [3, 10, 18]: + values = hashed_logits[0, position, :8].tolist() + lines.append(f" {position}: [") + for offset in range(0, len(values), 5): + lines.append(" " + ", ".join(f"{value:.9e}" for value in values[offset:offset+5]) + ",") + lines.append(" ],") lines.extend([" ]", "}", ""]) OUTPUT.write_text("\n".join(lines)) print(f"Reference cached/uncached maximum absolute error: {error:.9g}") From 66bc93d4291c464bbe4db788fc6c2a45bcff7056 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Garc=C3=ADa=20Pizarro?= <81751965+alvarogarciapiz@users.noreply.github.com> Date: Sat, 7 Nov 2026 08:42:23 +0100 Subject: [PATCH 7/7] Move tokenizer validation to BaseLanguageModel --- Libraries/MLXEmbedders/ModelFactory.swift | 1 + Libraries/MLXLLM/LLMModel.swift | 6 ----- Libraries/MLXLLM/LLMModelFactory.swift | 4 +--- Libraries/MLXLMCommon/LanguageModel.swift | 6 +++++ Libraries/MLXLMCommon/ModelFactory.swift | 2 ++ .../ParoQuant/ParoQuantLoader.swift | 1 + Libraries/MLXVLM/EmbeddingGemma2.swift | 4 +++- Libraries/MLXVLM/VLMModelFactory.swift | 1 + Tests/MLXLMTests/LFM3Tests.swift | 2 +- .../MLXLMTests/ParoQuantCheckpointTests.swift | 24 ++++++++++++++++++- .../references/supported-models.md | 2 +- 11 files changed, 40 insertions(+), 13 deletions(-) diff --git a/Libraries/MLXEmbedders/ModelFactory.swift b/Libraries/MLXEmbedders/ModelFactory.swift index 5909ca4453..b0d5d09990 100644 --- a/Libraries/MLXEmbedders/ModelFactory.swift +++ b/Libraries/MLXEmbedders/ModelFactory.swift @@ -245,6 +245,7 @@ public final class EmbedderModelFactory: GenericModelFactory { excludedComponents: configuration.excludedComponents) let tokenizer = try await tokenizerTask + try model.validate(tokenizer: tokenizer) // Build a ModelConfiguration for the ModelContext let tokenizerSource: TokenizerSource? = diff --git a/Libraries/MLXLLM/LLMModel.swift b/Libraries/MLXLLM/LLMModel.swift index b571509d3f..b9ab78bcc8 100644 --- a/Libraries/MLXLLM/LLMModel.swift +++ b/Libraries/MLXLLM/LLMModel.swift @@ -11,10 +11,6 @@ public protocol LLMModel: LanguageModel, LoRAModel { /// /// The default implementation returns `DefaultMessageGenerator`. func messageGenerator(tokenizer: Tokenizer) -> MessageGenerator - - /// Check tokenizer requirements before the factory returns a model context. - /// The default implementation accepts any tokenizer. - func validate(tokenizer: Tokenizer) throws } extension LLMModel { @@ -68,6 +64,4 @@ extension LLMModel { public func messageGenerator(tokenizer: Tokenizer) -> MessageGenerator { DefaultMessageGenerator() } - - public func validate(tokenizer: Tokenizer) throws {} } diff --git a/Libraries/MLXLLM/LLMModelFactory.swift b/Libraries/MLXLLM/LLMModelFactory.swift index f039efda49..c3d335d229 100644 --- a/Libraries/MLXLLM/LLMModelFactory.swift +++ b/Libraries/MLXLLM/LLMModelFactory.swift @@ -831,9 +831,7 @@ public final class LLMModelFactory: GenericModelFactory { let tokenizer = try await tokenizerTask - if let model = model as? LLMModel { - try model.validate(tokenizer: tokenizer) - } + try model.validate(tokenizer: tokenizer) let messageGenerator: any MessageGenerator if let configuredMessageGenerator = mutableConfiguration.messageGenerator { diff --git a/Libraries/MLXLMCommon/LanguageModel.swift b/Libraries/MLXLMCommon/LanguageModel.swift index 5127cadead..d60a29d11c 100644 --- a/Libraries/MLXLMCommon/LanguageModel.swift +++ b/Libraries/MLXLMCommon/LanguageModel.swift @@ -6,6 +6,10 @@ import MLXNN /// Abstract form of a model that processes language. public protocol BaseLanguageModel: Module { + /// Check whether the loaded tokenizer meets this model's requirements. + /// The default implementation accepts any tokenizer. + func validate(tokenizer: any Tokenizer) throws + /// Serialized namespaces whose tensors this model never loads, such as the target model in /// a checkpoint that a drafter shares with it. The loader does not read them. /// @@ -59,6 +63,8 @@ public protocol ModelConversionMetadataProvider { } extension BaseLanguageModel { + public func validate(tokenizer: any Tokenizer) throws {} + public var excludedCheckpointNamespaces: [String] { [] } public func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint { diff --git a/Libraries/MLXLMCommon/ModelFactory.swift b/Libraries/MLXLMCommon/ModelFactory.swift index a53064ac3c..c184fdb942 100644 --- a/Libraries/MLXLMCommon/ModelFactory.swift +++ b/Libraries/MLXLMCommon/ModelFactory.swift @@ -118,6 +118,8 @@ public protocol GenericModelFactory: Sendable { /// load level load of a ``ResolvedModelConfiguration`` (urls) into a /// ``ContextType``. This is typically `struct` that holds the values /// needed to run inference in the model and is _not_ `Sendable`. + /// If the factory loads a tokenizer, call the model's + /// `validate(tokenizer:)` before returning the context. func _load( configuration: ResolvedModelConfiguration, tokenizerLoader: any TokenizerLoader diff --git a/Libraries/MLXLMCommon/ParoQuant/ParoQuantLoader.swift b/Libraries/MLXLMCommon/ParoQuant/ParoQuantLoader.swift index ee8170fcbe..132d399903 100644 --- a/Libraries/MLXLMCommon/ParoQuant/ParoQuantLoader.swift +++ b/Libraries/MLXLMCommon/ParoQuant/ParoQuantLoader.swift @@ -813,6 +813,7 @@ public func loadParoQuantModel( // 13. Load tokenizer let tokenizer = try await tokenizerLoader.load(from: directory) + try model.validate(tokenizer: tokenizer) // 14. Create processor with messageGenerator // Use DefaultMessageGenerator — LLMModel.messageGenerator(tokenizer:) is in MLXLLM diff --git a/Libraries/MLXVLM/EmbeddingGemma2.swift b/Libraries/MLXVLM/EmbeddingGemma2.swift index ecc1605960..935c330bc0 100644 --- a/Libraries/MLXVLM/EmbeddingGemma2.swift +++ b/Libraries/MLXVLM/EmbeddingGemma2.swift @@ -653,9 +653,11 @@ public actor EmbeddingGemma2Embedding: MultimodalEmbedding { excludedComponents: configuration.excludedComponents, componentLoading: componentLoading ) try Swift.Task.checkCancellation() + let tokenizer = try await tokenizerLoader.load(from: configuration.tokenizerDirectory) + try model.validate(tokenizer: tokenizer) self.model = model self.modelDirectory = modelDirectory - self.tokenizer = try await tokenizerLoader.load(from: configuration.tokenizerDirectory) + self.tokenizer = tokenizer var modalities: Set = [.text] if model.supportedComponents.contains(.vision) { modalities.insert(.image) diff --git a/Libraries/MLXVLM/VLMModelFactory.swift b/Libraries/MLXVLM/VLMModelFactory.swift index 430e137329..a65309a09c 100644 --- a/Libraries/MLXVLM/VLMModelFactory.swift +++ b/Libraries/MLXVLM/VLMModelFactory.swift @@ -490,6 +490,7 @@ public final class VLMModelFactory: GenericModelFactory { excludedComponents: configuration.excludedComponents) let tokenizer = try await tokenizerTask + try model.validate(tokenizer: tokenizer) let processorConfiguration: VLMProcessorConfiguration do { processorConfiguration = try await processorConfigTask diff --git a/Tests/MLXLMTests/LFM3Tests.swift b/Tests/MLXLMTests/LFM3Tests.swift index 7b494cc037..dd61cffee9 100644 --- a/Tests/MLXLMTests/LFM3Tests.swift +++ b/Tests/MLXLMTests/LFM3Tests.swift @@ -631,7 +631,7 @@ final class LFM3Tests: XCTestCase { } func testTokenizerCompatibilityProbes() throws { - let model: any LLMModel = try tinyModel() + let model: any BaseLanguageModel = try tinyModel() XCTAssertNoThrow(try model.validate(tokenizer: ProbeTokenizer())) for broken in [".reduce", "line.\r\nThis"] { XCTAssertThrowsError(try model.validate(tokenizer: ProbeTokenizer(broken: broken))) { diff --git a/Tests/MLXLMTests/ParoQuantCheckpointTests.swift b/Tests/MLXLMTests/ParoQuantCheckpointTests.swift index 0125c6210a..03aa51f253 100644 --- a/Tests/MLXLMTests/ParoQuantCheckpointTests.swift +++ b/Tests/MLXLMTests/ParoQuantCheckpointTests.swift @@ -41,6 +41,20 @@ struct ParoQuantCheckpointTests { } } + @Test + func tokenizerValidationErrorPreventsLoading() async throws { + let directory = try makeCheckpoint(prepared: true) + defer { try? FileManager.default.removeItem(at: directory) } + await #expect(throws: TestError.incompatibleTokenizer) { + try await loadParoQuantModel( + from: directory, + typeRegistry: ModelTypeRegistry(creators: [ + "qwen3_5": { _ in CheckpointModel(rejectTokenizer: true) } + ]), + tokenizerLoader: TestTokenizerLoader()) + } + } + private func makeCheckpoint(prepared: Bool, collision: Bool = false) throws -> URL { let directory = FileManager.default.temporaryDirectory.appendingPathComponent( UUID().uuidString) @@ -81,6 +95,7 @@ struct ParoQuantCheckpointTests { private enum TestError: Error { case legacySanitizerCalled + case incompatibleTokenizer } private struct TestTokenizerLoader: TokenizerLoader { @@ -93,11 +108,18 @@ struct ParoQuantCheckpointTests { @ModuleInfo var layer: Linear let kvHeads: [Int] = [] - override init() { + private let rejectTokenizer: Bool + + init(rejectTokenizer: Bool = false) { + self.rejectTokenizer = rejectTokenizer _layer.wrappedValue = Linear(32, 32, bias: false) super.init() } + func validate(tokenizer: any Tokenizer) throws { + if rejectTokenizer { throw TestError.incompatibleTokenizer } + } + func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint { var checkpoint = checkpoint checkpoint.perLayerQuantization?.perLayerQuantization["source.layer"] = diff --git a/skills/mlx-swift-lm/references/supported-models.md b/skills/mlx-swift-lm/references/supported-models.md index 88da1a1477..182a7cdc2d 100644 --- a/skills/mlx-swift-lm/references/supported-models.md +++ b/skills/mlx-swift-lm/references/supported-models.md @@ -123,7 +123,7 @@ includes both required fixes: [#398](https://github.com/huggingface/swift-transformers/pull/398). The token-ID and chat/tool-template integration tests pass with 1.4.0. Supply a `TokenizerLoader` using that release or another compatible implementation. The model rejects known -incompatible tokenization through the generic `LLMModel.validate(tokenizer:)` hook +incompatible tokenization through the generic `BaseLanguageModel.validate(tokenizer:)` hook at load time. The core package does not depend on Swift Transformers. Unit tests generate deterministic weights in memory and compare every operator,