Repository navigation
Add LiquidAI LFM3 model support - #750
Conversation
|
Thank you for making this great model family work! 🚀 Small suggestions for future Omni support
Follow-up work
|
|
Thanks @reneleonhardt, these were really helpful! Agreed it makes more sense to get the backbone ready for Omni here than to move things around later. Pushed e292400 with all of it:
|
|
Glad my hands-on guidance was helpful, Omni is running beautifully, I hope your contribution will be reviewed soon, thank you for your work! ❤️ |
| public var loraLayers: [Module] { | ||
| model.layers | ||
| } | ||
| } |
There was a problem hiding this comment.
The chat template ends the prompt with <think>, but LFM3Model has no reasoningConfig. In 24 greedy runs on the 4, 5, 6 and 8-bit checkpoints, .reasoning stayed empty and every answer began with the thinking. On 4-bit, ChatSession.respond returned 301 characters of thinking, then </think>391. LFM3 always thinks, so declare the always-on preset:
| } | |
| } | |
| // MARK: - Chat conventions | |
| extension LFM3Model { | |
| public var reasoningConfig: ReasoningConfig? { .alwaysOnThinking } | |
| } |
With it, all 24 fill .reasoning, none show </think>, and respond returns 391. On 4-bit, the turn that sends a get_weather result prefills 27 tokens instead of 196, because 170 now come from the cache. As with DeepSeek-R1, an MLXFoundationModels app then has to declare .reasoning when it creates MLXLanguageModel, or requests throw unsupportedCapability. A test:
func testDeclaresAlwaysOnThinking() throws {
XCTAssertEqual(LFM3Model(try tinyConfiguration()).reasoningConfig, .alwaysOnThinking)
}|
|
||
| let logits = model(inputs, cache: nil) | ||
|
|
||
| XCTAssertEqual(logits.shape, [2, 7, 64]) |
There was a problem hiding this comment.
This checks only the shape. The other forward-pass tests compare this code with itself, and the RoPE test checks only RoPE. I made 12 small changes to MLXLMCommon/Models/LFM3.swift, such as no gate sigmoid, w1 and w3 swapped, or theta 1e6 on sliding layers, and all 14 tests passed with each one. The test below, with float32 logits from Lfm3ForCausalLM (revision 40ebe0aa) on the CPU, fails for all 12. Unchanged code is within 3.9e-6 on an M3 Ultra, and the change with the smallest effect, sliding theta, is off by 0.134. The weights use one running index across all tensors, so w1 and w3 get different values and a swap shows up.
/// Distinct values for every tensor, from a hash of one running index over the parameters
/// in name order: `1 + u` for norms and `u / 2` otherwise, with `u` in [-0.5, 0.5).
private func hashedWeights(_ model: Module) -> [String: MLXArray] {
var start = 0
var weights = [String: MLXArray]()
for (key, value) in model.parameters().flattened().sorted(by: { $0.0 < $1.0 }) {
let values = (start ..< start + value.size).map { i in
let u = Double(UInt64(i) * 2_654_435_761 % (1 << 32)) / 4_294_967_296 - 0.5
return Float(value.ndim == 1 ? 1 + u : u / 2)
}
weights[key] = MLXArray(values, value.shape)
start += value.size
}
return weights
}
/// Expected logits come from modeling_lfm3.py in float32 on the CPU with the same weights
/// and tokens: the first 8 at positions 3, 10 and 18, with a sliding window of 4.
func testLogitsMatchReference() throws {
let model = try tinyModel()
try model.update(
parameters: ModuleParameters.unflattened(hashedWeights(model)), verify: [.all])
let tokens = MLXArray((0 ..< 19).map { Int32(($0 * 7 + 3) % 64) }).reshaped(1, 19)
let expected: [Int: [Float]] = [
3: [
0.124086142, -0.628987074, 0.808857799, -0.596109271, 0.524976909, -1.24413228,
0.590065658, -0.482998401,
],
10: [
0.897291958, -1.01679277, -0.422243804, -0.528702438, -0.0963748991, 2.48546743,
-0.584653139, 0.0170748997,
],
18: [
0.402512223, -0.151311055, -0.361906171, -0.781367064, 0.596630931, 0.113322325,
0.043631494, -0.346791685,
],
]
let logits = model(tokens, cache: nil)
for (position, values) in expected {
assertClose(
logits[0, position, 0 ..< 8], MLXArray(values), atol: 1e-4, reducedAtol: 2e-2,
"position \(position)")
}
}| public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { | ||
| projectLogits(model(inputs, cache: cache)) | ||
| } |
There was a problem hiding this comment.
With the default prefill step of 512, a prompt of up to 512 tokens goes whole to the first nextTokenLogits call. The default implementation runs callAsFunction, which projects every position onto the 128,000-token vocabulary, but only the last row is used. Qwen3 and Mellum override nextTokenLogits with quantizedVocabularyProjectionInput for this. On an M3 Ultra, the same override cuts generate prompt time for 511 tokens from 91.0 to 82.7 ms (4-bit) and 93.8 to 83.9 ms (8-bit), median of 20 runs, and peak MLX memory by 115 and 86 MB. Last-row logits stay bitwise equal. It also needs embedTokens at line 371 of MLXLMCommon/Models/LFM3.swift to be package.
| public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { | |
| projectLogits(model(inputs, cache: cache)) | |
| } | |
| public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { | |
| 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 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 { |
There was a problem hiding this comment.
HiddenStateLanguageModel is a package protocol, and the two other models that conform, Qwen3Model and MellumModel, declare these methods package. As public, they add hiddenStates(_:cache:) and projectLogits(_:) to the public API of LFM3Model, and DocC lists both. No other model makes them plain public. With this change the package builds, the 14 LFM3Tests pass, and DocC passes for MLXLLM.
| 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 { | |
| package func hiddenStates(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { | |
| model(inputs, cache: cache) | |
| } | |
| /// Vocabulary logits for final hidden states, tied or untied. | |
| package func projectLogits(_ hiddenStates: MLXArray) -> MLXArray { |
| self.tieWordEmbeddings = | ||
| try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true |
There was a problem hiding this comment.
The reference lets the LFM2 key tie_embedding override tie_word_embeddings (configuration_lfm3.py: self.tie_word_embeddings = kwargs.pop("tie_embedding", self.tie_word_embeddings)), and so does LFM2VL.swift. This decoder ignores it. Released LFM3 configs use tie_word_embeddings, but LiquidAI's LFM2.5-1.2B configs use only tie_embedding, so an LFM3 checkpoint saved with the LFM2 key loads wrong. A 6-layer test checkpoint with "tie_embedding": false and its own lm_head.weight loads as tied: logits differ from torch by up to 2.32, and the top token differs at 24 of 24 positions. With "tie_embedding": true, "tie_word_embeddings": false, loading fails with Key lm_head.weight not found in LFM3Model.Linear.
A new CodingKeys case breaks the synthesized Encodable, so add an enum after CodingKeys, like AltCodingKeys in Hunyuan.swift:
/// The reference reads the LFM2 spelling `tie_embedding` before `tie_word_embeddings`.
private enum AltCodingKeys: String, CodingKey {
case tieEmbedding = "tie_embedding"
}and replace these lines with:
let alt = try decoder.container(keyedBy: AltCodingKeys.self)
self.tieWordEmbeddings =
try alt.decodeIfPresent(Bool.self, forKey: .tieEmbedding)
?? container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true| /// | ||
| /// 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 { |
There was a problem hiding this comment.
LFM3AttentionMasks, RopeParameters (whose fields are already package) and seven LFM3ModelInner members are public, but their only callers are LFM3Model and the tests, and the MLXVLM wrapper the header plans would live in this package too. package covers that, as it does for Gemma4VisionModel (Gemma4Encoders.swift:610), which MLXVLM builds at Gemma4.swift:1398. Falcon-H1 and Gemma put entry points for outside callers behind @_spi.
public can become package on lines 26, 43, 347, 348, 349, 351, 374, 376, 392, 397, 404, 434 and 440. Line 362 then has to write newCache(parameters:) as plain code, because DocC fails on a link to a package method. With that, the package builds, the 14 LFM3Tests pass, and DocC passes for MLXLMCommon and MLXLLM.
| XCTAssertNotNil(model.lmHead) | ||
| XCTAssertEqual( | ||
| model(MLXArray([Int32(1), 2, 3]).reshaped(1, 3), cache: nil).shape, [1, 3, 64]) |
There was a problem hiding this comment.
This checks that lmHead exists and the logits shape, but logits from the tied embedding have the same shape. LFM3ModelInner.projectLogits defaults lmHead to nil, so a call that leaves it out still compiles. With lmHead dropped from LFM3Model.projectLogits (line 80 of MLXLLM/Models/LFM3.swift), untied checkpoints get logits from the embedding and all 14 tests still pass. Comparing with lmHead directly catches it: the logits differ by 2.78.
| XCTAssertNotNil(model.lmHead) | |
| XCTAssertEqual( | |
| model(MLXArray([Int32(1), 2, 3]).reshaped(1, 3), cache: nil).shape, [1, 3, 64]) | |
| let lmHead = 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 - lmHead(model.model(tokens))).max().item(Float.self), 0) |
| 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) |
There was a problem hiding this comment.
No check here gives full-attention layers a mask that differs from their default, so masks.fullAttention is never tested. With masks.fullAttention ?? removed from LFM3ModelInner (line 411 of MLXLMCommon/Models/LFM3.swift), all 14 tests pass. They also pass when the sliding override reaches full layers, or the full override reaches sliding layers. This version checks each type on its own and fails for all three. .none must be spelled out: .init(fullAttention: .none) means Optional.none, which keeps the default, and Swift only warns.
| 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) | |
| } | |
| // An override equal to its type's default changes nothing, so each one reaches only | |
| // its own layers. | |
| 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) | |
| // Any other mask changes the output: no mask on full layers, no window on sliding ones. | |
| let unmasked = MLXFast.ScaledDotProductAttentionMaskMode.none | |
| XCTAssertGreaterThan(difference(.init(fullAttention: unmasked)), 1e-3) | |
| XCTAssertGreaterThan(difference(.init(slidingAttention: .causal)), 1e-3) |
| /// 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. |
There was a problem hiding this comment.
Two traps in these overrides are worth a line in the docs. The fields are optional, so .init(fullAttention: .none) means nil and keeps the causal default; Swift only warns. With the 4-bit model and 9 tokens it gives exactly the default output, while MLXFast.ScaledDotProductAttentionMaskMode.none changes the hidden states by up to 9.06. An .array mask must also match the keys the cache returns. After 300 cached tokens, a sliding mask from createCausalMask(n: 8, offset: 300, windowSize: 256) crashes with [broadcast_shapes] Shapes (8,308) and (1,16,8,263) cannot be broadcast, while one from makeAttentionMask(n:cache:windowSize:returnArray:) on the first sliding cache matches the default.
| /// 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. | |
| /// 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. | |
| /// For no mask, write `MLXFast.ScaledDotProductAttentionMaskMode.none`: a bare `.none` is `nil`. | |
| /// An `.array` mask must match the keys the cache returns. A sliding cache drops keys outside | |
| /// the window, so build that mask with `makeAttentionMask(n:cache:windowSize:returnArray:)`. |
|
Thanks @ykhrustalev, this is a really thorough review, appreciate you actually breaking the code to check what the tests catch. Took all nine in the recent comit..
|
| // MARK: - Chat conventions | ||
|
|
||
| extension LFM3Model { | ||
| public var reasoningConfig: ReasoningConfig? { .alwaysOnThinking } |
There was a problem hiding this comment.
Per the template, the model does support turning off thinking (it adds an empty think tag):
{%- set thinking = message.thinking if message.thinking is defined else message.reasoning if message.reasoning is defined else message.reasoning_content -%}
{%- set keep_thinking = preserve_thinking or loop.index0 > ns.last_user_index -%}
{%- if thinking is defined and keep_thinking -%}
{{- "<think>" + (thinking or "") + "</think>" -}}
{%- elif keep_thinking and "</think>" not in (message.get("content") if message.get("content") is string else "") -%}
{{- "<think></think>" -}}
{%- endif -%}
{%- set _cfm_tag = "CONTINUE_FINAL_MESSAGE_TAG " -%}
{%- set _has_cfm = false -%}
{%- set content = "" -%}
{%- if message.get("content") -%}
{%- set content = parse_content(message.content) -%}
{%- endif -%}
{%- if not keep_thinking -%}
{%- if "</think>" in content -%}
{%- set content = content.split("</think>")[-1] | trim -%}
{%- endif -%}
{%- set content = "<think></think>" + content -%}
{%- endif -%}I think this should probably be .thinkTagsWithEnableThinking or potentially the qwen config:
public static let tagged = ReasoningConfig(
startDelimiter: "<think>", endDelimiter: "</think>",
promptStrategy: .templateFlag(key: "enable_thinking", defaultOn: true),
isSpecialToken: true,
implicitEndDelimiters: ["<tool_call>"])which adds the implicit stop on a tool_call.
There was a problem hiding this comment.
My experiences
-
LFM3-1.7B supports thinking and enables it by default. Setting
enable_thinking=falseadds an empty<think></think>prefix. My Swift/MLX text prototype generated answers with that setting, though I did not measure how reliably it suppresses thinking on harder prompts. For this PR, I suggest making thinking configurable rather than usingalwaysOnThinking, and testing output parsing with both prefixes. -
LFM3-Omni-2B is a separate, non-reasoning checkpoint. Its model card says
enable_thinking=trueis unsupported. I kept it disabled throughout my Omni work. The template still contains thinking tags, so those tags alone do not establish reasoning support.
For future Omni support, keep the reasoning configuration separate from the shared LFM3 backbone: configurable for LFM3-1.7B, disabled for LFM3-Omni-2B.
|
|
||
| // MARK: - Chat conventions | ||
|
|
||
| extension LFM3Model { |
There was a problem hiding this comment.
Might also want to declare the tool call format:
public var toolCallFormat: ToolCallFormat? { .xmlFunction }I think this is inferred from the template (if the model has one), but might be best to declare.
davidkoski
left a comment
There was a problem hiding this comment.
Looks good! Look at the two comments on LFM3 configuration and see if those make sense.
Thank you!
|
Also needs a rebase to fix the conflict in LLMModelFactory.swift |
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 <noreply@anthropic.com>
- Declare always-on thinking for LFM3Model. - Project only the trailing rows in nextTokenLogits for quantized heads. - Read the LFM2 key tie_embedding before tie_word_embeddings. - Make the backbone helpers, masks and RoPE parameters package. - Compare logits with modeling_lfm3.py on hashed weights; tighten the untied lm_head and per-type mask override tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Apply the upstream commits 22bdf2c..6352907 (the 15 after c8dabc6) as cherry-picks. CLAUDE.md is untouched. Where a conflict was only a fork refactor, upstream's code is taken; the fork's MTP speed and prompt-cache behavior is kept. - 22bdf2c Decode surrogate pairs and the remaining Python escapes (ml-explore#769) - 0877a36 Fix model weight loading progress (ml-explore#551) - 0dabaf7 Add production-ready LFM2.5 model support (ml-explore#528) - 173c163 Add mid-turn steering to ChatSession (ml-explore#608) - 37424a5 Stop image prompts from running VLM language models in float32 (ml-explore#766) - c48e55e Add LiquidAI LFM3 model support (ml-explore#750) - 4ab2679 MLXVLM Qwen35: apply YaRN from rope_parameters on the VLM rotary (ml-explore#761) - 6e3fe5d Report token log probabilities during speculative decoding (ml-explore#774) - ec4c966 Batch greedy MTP verification into one GPU readback per round (ml-explore#724) - c9a9a3d Skip the checkpoint components a model does not have (ml-explore#711) - a8429d0 Measure the memory of an EmbeddingGemma 2 embedding (ml-explore#787) - 7b0e790 Parse triple-quoted strings in PythonLiteralParser (ml-explore#786) - 4c91662 Fix the flaky usage test on the tool-calling path (ml-explore#784) - d7b94ee Add ModelTypeRegistry.contains(_:configuration:) for shared model types (ml-explore#778) - 6352907 Use MLXLogger for the model component warning (ml-explore#790) Conflict resolutions: - ml-explore#551 load progress: `LoadProgressHandlers` and `progress:` are threaded through the fork's async `loadWeights`/`installWeights`. The progress-aware `MLXLanguageModel.init(...progress:load:)` and the `#huggingFaceLanguageModel` macro also take the fork's `speculativeDecoding:`. The fork's tests and benchmark helpers move off the now-deprecated download-only loader. - ml-explore#528 LFM2.5: `RewindableConvolutionCache` lives in ArraysCache.swift without upstream's extra `offset +=`, because the fork's `advance` moves `offset`. Speculative rewind and verify checks trim it like attention, and do not select a Mamba snapshot slot for it. It is also `PromptCacheRestorable`, so a saved LFM2 prompt cache restores into the model's template. `mtpTargetLayerIdsKey` is added to the fork's MTP exchange. `shouldSortExpertRoutes` drives the fork's shared switch projection. The fork's in-place verify (`verifiesInPlace`) and its greedy-only passthrough string are kept. The upstream tests that expect a wrapped sliding window to refuse rewind now expect the fork's behavior: the window rewinds the verify write and keeps speculating. - ml-explore#608 steering: the steering boundary goes into the fork's `GenerationLoop.runTokenLoop`, and `Generation.steering` and `GenerateStopReason.steered` go into GenerationResults.swift. The fork's generation worker keeps its own stream synchronization. - ml-explore#750 LFM3 is added to HybridRecurrentCacheOffsetTests. - ml-explore#711: the new test awaits the fork's async `loadWeights`. Dropped: - ml-explore#774 (speculative log probabilities): the fork's MTP iterator already reports log probabilities by decoding plainly when they are requested. Upstream's batched recording in the draft-model iterator does not fit the fork's `sampleToken` path, so `ChatSession.ObservationError` stays for draft-model speculation. - ml-explore#724 (batched greedy MTP verification): the fork already batches its greedy verify (`verifyDrafts`, MTPGreedyVerificationTests). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Upstream's 27 commits since 7dde329, among them per-row rotary positions in the LLM and VLM models (ml-explore#773), LFM3 text validation (ml-explore#756), Gemma 4's warm-cache image attention (ml-explore#813), Gemma 2's per-row mask (ml-explore#772), the segsum batch mask (ml-explore#829), Hadamard-rotated Qwen3.5 packs (ml-explore#630, ml-explore#835) and the caller's sampler in guided generation (ml-explore#733). Conflicts: - GuidedGenerationLoop.swift: both. The fork's prompt reuse, then upstream's logit processor, which sees the whole prompt. maskedArgMax becomes maskedSample, taking upstream's processor and sampler, so the batched row (BatchedGuidedGeneration, still greedy) and the single loop share it. - QwenVL.swift: both, one mechanism. textBatchPositionIds is now upstream's decodePositionIds with no rope delta (each row's cache.ropeOffset), as Qwen3VL, Qwen3VLMoE, Qwen3.5 and GlmOcr call it. - Gemma4.swift (MLXVLM): the same per-row cache.ropeOffset change on both sides; the fork's comment kept. - LFM3.swift (MLXLLM): upstream's tokenizer error, and the marker (now in BatchPositionedModels.swift). One LFM3Model and one "lfm3" entry, as before: both sides extend upstream's ml-explore#750 model. - MLXVLM README: both model lists. Merged without conflict, but reconciled: - prism_hadamard_qwen35 was registered twice in VLMTypeRegistry (a duplicate dictionary key traps at launch). Upstream's loader (ml-explore#630, both registries, its tests) replaces the fork's 8de2623 one (Qwen35+PrismHadamard.swift, PackedModuleInstalling, Qwen35Configuration.hadamardConfig); the same pack carries both upstream's manifest and the hadamard.json the fork read. - prism mlx-swift's MLXNN also defines HadamardQuantizedLinear, HadamardQuantizedEmbedding and SignedBlockHadamard: the tests that use upstream's name them MLXLMCommon.*. - SSM.swift segsum: upstream now expands the mask once; the fork's second expansion of the same fix is dropped. BatchPositionedModel: upstream positions rows by cache.ropeOffset across most models, but not all (PaliGemma, LFM2-DSpark, hybrids without an attention cache), so the gate stays. MLXLLM's and MLXVLM's BatchPositionedModels.swift list the models, 38 MLXLLM types and 10 MLXVLM, the fork's six moved there. Each is checked by BatchedPrefillTests.markedModelsWriteWhatTheyWriteAlone: a tiny model from the type registry, whose rows, read together or read alone and joined, choose the tokens and logits they do alone. PaliGemma, which rotates by the batch cache's one offset, fails it (logits off by 1.6 to 2.8). Package.swift keeps smdesai/mlx-swift prism-ml.
Proposed changes
Adds the LiquidAI LFM3 text model (
model_type: "lfm3", e.g.LiquidAI/LFM3-1.7B-MLX-4bit) to MLXLLM. Addresses #741 for the textmodel only; LFM3-VL is not included.
Why
We build Muesli, a macOS dictation app. After speech recognition, a small on-device model cleans up the raw transcript: fillers,
self-corrections ("no wait, Tuesday"), punctuation for the app being typed into, and lists or paragraphs when the speaker asks for
them. We are moving that model from llama.cpp to MLX Swift. We fine-tuned LFM3-1.7B for this task. In our tests it handled formatting
(lists, line breaks, spoken punctuation) best of the models we tried: a 1.49% word error rate on our formatting test set, against
2.93% for a fine-tuned Qwen3.5-2B and 3.04% for a fine-tuned Gemma 4 E2B. It needs
lfm3support in mlx-swift-lm to ship.With this change it runs in the app at 8-bit at about 0.5 s per dictation on an M5 Mac (prefill ~1,580 tok/s, decode ~48 tok/s).
What changed
LFM3 is LFM2 plus:
o_proj;partial_rotary_factor0.5, theta 1e6) and plain RoPE on sliding layers (theta 1e4);use_sandwich_norm).Implementation notes:
ProportionalRoPE(as in Gemma 4). HF rotates pairs (j, j+64) for j < 32 with full-head frequencies,which is not what
RoPE(dimensions: 64)does.MambaCachefor conv layers,makeHybridAttentionKVCachefor attention layers (sliding layers get aRotatingKVCache(sliding_window)), the same pattern as GPT-OSS and Olmo3. Masks are built once per attention type.language_model.prefix used by the released MLX bundles, keepsmodel.*/lm_head.*, dropslm_headwhenembeddings are tied, and transposes conv weights from the transformers layout.
"lfm3"and addsLLMRegistry.lfm3_1_7b_4bit.reasoningConfig = .alwaysOnThinking(LFM3's template always opens<think>), so chat sessions put the thinking in.reasoning.nextTokenLogitsto project only the last position onto the 128k vocabulary (quantizedVocabularyProjectionInput, as in Qwen3 and Mellum).tie_embeddingahead oftie_word_embeddings, as the reference config does.Omni-ready backbone (added after review feedback, so LFM3-Omni can reuse the text model without reworking it):
MLXLMCommon, following the Gemma 4 shared encoder layout, so an MLXVLMwrapper can use them without depending on MLXLLM.
LFM3Model, checkpoint handling, the registry entry and LoRA stay in MLXLLM.LFM3ModelInneraccepts token ids or embeddings (callAsFunction(embeddings:cache:masks:)); the token path embeds and runs thesame code. Lengths and positions come from the embedding sequence and the cache offsets.
embed(_:)andprojectLogits(_:lmHead:)on the backbone, andLFM3Modelconforms toHiddenStateLanguageModel, so one passgives hidden states and text logits, for tied and untied embeddings.
LFM3AttentionMaskslets the caller override the full or sliding mask.package, notpublic: a wrapper in MLXVLM lives in this package, as with Gemma 4's shared encoders.language_model.prefix filter dropped a barelm_headper-layer quantization entry, so an untied, differently quantizedhead would fail to load. LFM3-1.7B ties its embeddings, so released checkpoints were not affected.
Not ported: packed sequences (
seq_idx), padding masks inside the conv, scaled RoPE types (rejected at config decode).The osaurus-ai vMLX port (MIT) was a useful reference for the partial-RoPE layout and the MLX bundle weight names; no code was copied,
and every behaviour was checked against
modeling_lfm3.py.Tests
Tests/MLXLMTests/LFM3Tests.swift(18 tests): config decoding and defaults (includingtie_embedding), invalid configs, registryentries,
.alwaysOnThinking, forward shapes, tied and untied heads (untied compared againstlm_headdirectly), per-layer cachetypes and
maxKVSizecaps, partial RoPE against the HF formula, sanitize for MLX and transformers layouts with strict verification,one-shot vs chunked prefill plus decode steps past the sliding window, token vs embedding input (identical logits), chunked embedding
prefill, per-type mask overrides, a mixed 4/6/8-bit checkpoint loaded with strict verification (this test caught the
lm_headbugabove),
nextTokenLogitslast row bitwise equal to the full forward (quantized tied and untied), and logits on hashed weights againstfloat32 values from
modeling_lfm3.py(re-derived independently, agreeing within 1.3e-6).xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS' -skipPackagePluginValidation -only-testing:MLXLMTests/LFM3Tests-> 18 passed. DocC (
--warnings-as-errors) passes for MLXLMCommon and MLXLLM.Numeric parity on the real LFM3-1.7B weights against HF transformers (fp32, CPU), same token ids, 4 prompts of 18, 54, 500 and
623 tokens (the last two exceed the 256-token window):
(
MLX_ENABLE_TF32=0, weights cast to float32.) TheLFM3-1.7B-MLX-bf16bundle matches HF fp32 at 94-100% top-1, the same asHF's own bf16 model (95-100%), so the gap is bf16 rounding, not the port.
Our fine-tuned LFM3-1.7B (converted to MLX 8-bit) loads through this path and was evaluated on about 2,000 held-out cleanup prompts.
Parity is unchanged after the backbone refactor, the review changes and the
mainmerge (same numbers as the table).pre-commit run --all-fileswith swift-format 603.0.0 (the CI pin): no changes.Tokenizer note
LFM3's
tokenizer.jsonsets BPE"ignore_merges": true: a pre-token that is already in the vocabulary is emitted as one tokenwithout applying merges. swift-transformers 1.3.5 and earlier ignore this flag, so some words split differently from HF. For example,
.reducebecomes.re+du+ceinstead of the single.reducetoken. This is not a model bug: with identical token ids theport matches HF (table above). It is fixed in swift-transformers by huggingface/swift-transformers#397 (with #398, code-point
regex splits), merged on
mainbut not yet in a release. With swift-transformersmain(ee21658e), 1,995 of 1,995 testprompts (201-1,083 tokens, chat format) tokenize identically to HF
tokenizers; with 1.3.2, one 623-token prompt came out 2 tokenslonger. Until a release includes #397, LFM3 users on swift-transformers should expect occasional tokenization differences.
Checklist
pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesAI usage
from the HF reference implementation. The follow-up commits (Omni-ready backbone, review changes) were drafted the same way. I reviewed the code, ran the tests and the numeric parity check, and can explain each part.