Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
38c922f
Add LiquidAI LFM3 text model support
pHequals7 Oct 29, 2026
f29b4d5
Merge branch 'main' into lfm3-text
pHequals7 Oct 31, 2026
499c2e5
Share the LFM3 text backbone for multimodal wrappers
pHequals7 Nov 1, 2026
e292400
Merge remote-tracking branch 'fork/lfm3-text' into lfm3-text
pHequals7 Nov 2, 2026
65fd3ae
fix(lfm3): harden implementation and expand regression coverage
alvarogarciapiz Nov 2, 2026
ac7e54a
chore(lfm3): remove incorrect Apple attribution from new tests
alvarogarciapiz Nov 2, 2026
97eb0d8
Merge branch 'main' into lfm3-review
alvarogarciapiz Nov 2, 2026
02a21ab
fix(lfm3): align validation and tests with review feedback
alvarogarciapiz Nov 2, 2026
0074d85
fix(lfm3): address backbone and generation review feedback
alvarogarciapiz Nov 2, 2026
76c3b47
Merge branch 'main' into lfm3-review
alvarogarciapiz Nov 2, 2026
9762537
Merge branch 'main' into lfm3-review
alvarogarciapiz Nov 3, 2026
73a8c10
Merge branch 'main' into lfm3-review
alvarogarciapiz Nov 4, 2026
3d52a59
Merge branch 'main' into lfm3-review
alvarogarciapiz Nov 5, 2026
e24bf97
Merge branch 'main' into lfm3-review
alvarogarciapiz Nov 6, 2026
39da4e5
Merge upstream main and preserve LFM2.5 and LFM3 registry entries
alvarogarciapiz Nov 6, 2026
fb58b94
Merge LFM3 support from main and retain incremental hardening
alvarogarciapiz Nov 6, 2026
868818d
Merge branch 'main' into lfm3-review
alvarogarciapiz Nov 6, 2026
66bc93d
Move tokenizer validation to BaseLanguageModel
alvarogarciapiz Nov 7, 2026
09a3f7d
Merge branch 'main' into lfm3-review
alvarogarciapiz Nov 10, 2026
428329c
Merge branch 'main' into lfm3-review
alvarogarciapiz Nov 10, 2026
6953960
Merge branch 'main' into lfm3-review
alvarogarciapiz Nov 11, 2026
4736396
Merge branch 'main' into lfm3-review
alvarogarciapiz Nov 16, 2026
b1ada5b
Merge branch 'main' into lfm3-review
alvarogarciapiz Nov 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 178 additions & 0 deletions IntegrationTesting/IntegrationTestingTests/LFM3CheckpointTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
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 output: MLXArray?
for offset in stride(from: 0, to: count, by: 256) {
output =
model.nextTokenLogits(
.init(tokens: tokens[0..., offset ..< offset + 256]), cache: cache, state: nil
).logits
eval(output!)
eval(cache)
}
var logits = try XCTUnwrap(output)[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 output: MLXArray?
for start in stride(from: 0, to: length, by: 127) {
output =
model.nextTokenLogits(
.init(tokens: tokens[0..., start ..< min(start + 127, length)]),
cache: cache, state: nil
).logits
eval(output!)
eval(cache)
}
let logits = try XCTUnwrap(output)[0..., (-1)...]
let expected = try XCTUnwrap(reference["logits_\(length)"])
let error = abs(logits - expected).max().item(Float.self)
print(
"LFM3 published FP32 \(length): logits_max_abs=\(error)"
)
XCTAssertLessThan(error, 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] { [] }
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import Foundation
import Testing
import Tokenizers

// 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 {
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("<tool_call>") == 125019)
#expect(tokenizer.convertTokenToId("</tool_call>") == 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 disabled = try tokenizer.applyChatTemplate(
messages: [["role": "user", "content": "Hello"]],
tools: nil, additionalContext: ["enable_thinking": false])
#expect(
tokenizer.decode(tokens: disabled, skipSpecialTokens: false).hasSuffix(
"<think></think>"))
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,
])
}
}
1 change: 1 addition & 0 deletions Libraries/MLXEmbedders/ModelFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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? =
Expand Down
2 changes: 2 additions & 0 deletions Libraries/MLXLLM/LLMModelFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,8 @@ public final class LLMModelFactory: GenericModelFactory {

let tokenizer = try await tokenizerTask

try model.validate(tokenizer: tokenizer)

let messageGenerator: any MessageGenerator
if let configuredMessageGenerator = mutableConfiguration.messageGenerator {
messageGenerator = configuredMessageGenerator
Expand Down
31 changes: 31 additions & 0 deletions Libraries/MLXLLM/Models/LFM3.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,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)
}
Expand All @@ -77,6 +81,24 @@ public class LFM3Model: Module, LLMModel, KVCacheDimensionProvider {
public func newCache(parameters: GenerateParameters?) throws -> [KVCache] {
try model.newCache(parameters: parameters)
}

public func validate(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
}
}
}
}

extension LFM3Model: HiddenStateLanguageModel {
Expand Down Expand Up @@ -108,3 +130,12 @@ extension LFM3Model {
/// the thinking block.
public var reasoningConfig: ReasoningConfig? { QwenReasoningProtocol.tagged }
}

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."
}
}
6 changes: 6 additions & 0 deletions Libraries/MLXLMCommon/LanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions Libraries/MLXLMCommon/ModelFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ public protocol GenericModelFactory<ContextType, ContainerType>: 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
Expand Down
Loading
Loading