Skip to content

Add LiquidAI LFM3 model support - #750

Merged
davidkoski merged 4 commits into
ml-explore:mainfrom
pHequals7:lfm3-text
Nov 6, 2026
Merged

davidkoski merged 4 commits into
ml-explore:mainfrom
pHequals7:lfm3-text

Conversation

@pHequals7

@pHequals7 pHequals7 commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

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 text
model 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 lfm3 support 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:

  • a third layer type, sliding-window attention (window 256), next to conv and full attention;
  • a sigmoid gate per attention head, applied before o_proj;
  • partial RoPE on full-attention layers (partial_rotary_factor 0.5, theta 1e6) and plain RoPE on sliding layers (theta 1e4);
  • an optional RMSNorm on each block output (use_sandwich_norm).

Implementation notes:

  • Partial RoPE uses the existing 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.
  • Caches: MambaCache for conv layers, makeHybridAttentionKVCache for attention layers (sliding layers get a
    RotatingKVCache(sliding_window)), the same pattern as GPT-OSS and Olmo3. Masks are built once per attention type.
  • Loading strips the language_model. prefix used by the released MLX bundles, keeps model.* / lm_head.*, drops lm_head when
    embeddings are tied, and transposes conv weights from the transformers layout.
  • Registers "lfm3" and adds LLMRegistry.lfm3_1_7b_4bit.
  • Declares reasoningConfig = .alwaysOnThinking (LFM3's template always opens <think>), so chat sessions put the thinking in .reasoning.
  • Overrides nextTokenLogits to project only the last position onto the 128k vocabulary (quantizedVocabularyProjectionInput, as in Qwen3 and Mellum).
  • Reads the LFM2 key tie_embedding ahead of tie_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):

  • The LFM3 configuration, blocks and backbone live in MLXLMCommon, following the Gemma 4 shared encoder layout, so an MLXVLM
    wrapper can use them without depending on MLXLLM. LFM3Model, checkpoint handling, the registry entry and LoRA stay in MLXLLM.
  • LFM3ModelInner accepts token ids or embeddings (callAsFunction(embeddings:cache:masks:)); the token path embeds and runs the
    same code. Lengths and positions come from the embedding sequence and the cache offsets.
  • embed(_:) and projectLogits(_:lmHead:) on the backbone, and LFM3Model conforms to HiddenStateLanguageModel, so one pass
    gives hidden states and text logits, for tied and untied embeddings.
  • The backbone keeps no state: caches are caller-owned, and LFM3AttentionMasks lets the caller override the full or sliding mask.
  • These entry points are package, not public: a wrapper in MLXVLM lives in this package, as with Gemma 4's shared encoders.
  • Fix: the language_model. prefix filter dropped a bare lm_head per-layer quantization entry, so an untied, differently quantized
    head 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 (including tie_embedding), invalid configs, registry
    entries, .alwaysOnThinking, forward shapes, tied and untied heads (untied compared against lm_head directly), per-layer cache
    types and maxKVSize caps, 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_head bug
    above), nextTokenLogits last row bitwise equal to the full forward (quantized tied and untied), and logits on hashed weights against
    float32 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):

    Prompt Tokens Top-1 match (one-shot / chunked+decode) Max abs logit diff (top-5)
    short 18 100% / 100% 1.0e-4
    medium 54 100% / 100% 1.5e-4
    over window 500 100% / 100% 4.6e-3
    long chat prompt 623 100% / 100% 8.1e-4

    (MLX_ENABLE_TF32=0, weights cast to float32.) The LFM3-1.7B-MLX-bf16 bundle matches HF fp32 at 94-100% top-1, the same as
    HF'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 main merge (same numbers as the table).

  • pre-commit run --all-files with swift-format 603.0.0 (the CI pin): no changes.

Tokenizer note

LFM3's tokenizer.json sets BPE "ignore_merges": true: a pre-token that is already in the vocabulary is emitted as one token
without applying merges. swift-transformers 1.3.5 and earlier ignore this flag, so some words split differently from HF. For example,
.reduce becomes .re + du + ce instead of the single .reduce token. This is not a model bug: with identical token ids the
port matches HF (table above). It is fixed in swift-transformers by huggingface/swift-transformers#397 (with #398, code-point
regex splits), merged on main but not yet in a release. With swift-transformers main (ee21658e), 1,995 of 1,995 test
prompts (201-1,083 tokens, chat format) tokenize identically to HF tokenizers; with 1.3.2, one 623-token prompt came out 2 tokens
longer. Until a release includes #397, LFM3 users on swift-transformers should expect occasional tokenization differences.

Checklist

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it accurately describes the code changes.
  • AI usage disclosure: The implementation, tests and this description were drafted with Claude (Anthropic) via Claude Code, working
    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.

@reneleonhardt

Copy link
Copy Markdown

Thank you for making this great model family work! 🚀

Small suggestions for future Omni support

  • Let LFM3ModelInner accept embeddings directly, with the token-ID path calling the same method. Omni can then insert projected image/audio features and reuse the backbone. Use the embedding sequence and cache offsets for lengths and positions.
  • Expose methods to embed tokens and convert hidden states to next-token scores, with support for tied and untied weights. Speech generation can then get hidden states and text scores from one backbone pass, and feed audio-codebook embeddings into the next step.
  • Add tests that compare token and embedding input, cover chunked embedding prefill, and load a mixed 4/6-bit checkpoint. ModelCheckpoint.mapNames already maps prefixes and quantization settings together. The checkpoint test can protect that behavior.

Follow-up work

  • Move the shared configuration, backbone and blocks to MLXLMCommon when adding Omni. MLXVLM currently does not depend on MLXLLM. Expose only what other modules need, such as read-only hiddenSize.
  • Add the Omni wrapper, media processors, vision/audio encoders and speech codec/depth decoder separately. Keep all modality weights in the wrapper. Pass only the text portion of its checkpoint to the text checkpoint filter.
  • Keep streaming state, cancellation and scheduling outside the backbone. Let inference tasks take turns, with caller-owned caches and configurable block masks.

@pHequals7

Copy link
Copy Markdown
Contributor Author

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:

  • LFM3ModelInner now takes embeddings directly, and the token path just embeds and calls the same code. Lengths and positions come from the embeddings and the cache offsets
  • added embed(:) and projectLogits(:lmHead:), and LFM3Model now conforms to HiddenStateLanguageModel, so you get hidden states and text logits from one pass (tied and untied)
  • moved the config, blocks and backbone into MLXLMCommon (same idea as the Gemma 4 shared encoders) so an MLXVLM Omni wrapper can use them without pulling in MLXLLM. LFM3Model, checkpoint handling and the registry stay in MLXLLM
  • the backbone keeps no state: caches are caller owned, and LFM3AttentionMasks lets you override the full or sliding masks
  • tests for token vs embedding input, chunked embedding prefill and a mixed 4/6/8 bit checkpoint. That last one actually caught a bug where an untied lm_head with its own quantization wouldn't load (the 1.7B ties its embeddings so released checkpoints were fine)

@reneleonhardt

Copy link
Copy Markdown

Glad my hands-on guidance was helpful, Omni is running beautifully, I hope your contribution will be reviewed soon, thank you for your work! ❤️

@pHequals7 pHequals7 changed the title Add LiquidAI LFM3 text model support Add LiquidAI LFM3 model support Nov 2, 2026
public var loraLayers: [Module] {
model.layers
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
}
}
// 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])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)")
        }
    }

Comment on lines +34 to +36
public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray {
projectLogits(model(inputs, cache: cache))
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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)))
}

Comment thread Libraries/MLXLLM/Models/LFM3.swift Outdated
Comment on lines +74 to +79
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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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 {

Comment thread Libraries/MLXLMCommon/Models/LFM3.swift Outdated
Comment on lines +114 to +115
self.tieWordEmbeddings =
try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread Libraries/MLXLMCommon/Models/LFM3.swift Outdated
///
/// 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread Tests/MLXLMTests/LFM3Tests.swift Outdated
Comment on lines +184 to +186
XCTAssertNotNil(model.lmHead)
XCTAssertEqual(
model(MLXArray([Int32(1), 2, 3]).reshaped(1, 3), cache: nil).shape, [1, 3, 64])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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)

Comment thread Tests/MLXLMTests/LFM3Tests.swift Outdated
Comment on lines +370 to +379
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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)

Comment on lines +343 to +346
/// 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
/// 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:)`.

@pHequals7

Copy link
Copy Markdown
Contributor Author

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..

  1. LFM3Model declares .alwaysOnThinking now, plus your test
  2. added hashedWeights and testLogitsMatchReference as is. Passes without touching your numbers, and I also re-ran your setup against Lfm3ForCausalLM in float32 on CPU and got the same values within about 1e-6
  3. nextTokenLogits now goes through quantizedVocabularyProjectionInput, embedTokens is package. Added a test that the last row is bitwise equal to the full forward on quantized tied and untied models
  4. hiddenStates and projectLogits are package like Qwen3 and Mellum
  5. tie_embedding is read first through an AltCodingKeys enum, with a test for both keys and the conflicting combos
  6. switched all the lines you listed to package and fixed the DocC link
  7. untied head test compares against lmHead directly
  8. mask test checks full and sliding on their own, with .none spelled out
  9. added your doc comment on LFM3AttentionMasks
    18 LFM3 tests pass, DocC passes for MLXLMCommon and MLXLLM, and parity against HF on the real 1.7B weights hasn't moved.

Comment thread Libraries/MLXLLM/Models/LFM3.swift Outdated
// MARK: - Chat conventions

extension LFM3Model {
public var reasoningConfig: ReasoningConfig? { .alwaysOnThinking }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My experiences

  • LFM3-1.7B supports thinking and enables it by default. Setting enable_thinking=false adds 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 using alwaysOnThinking, and testing output parsing with both prefixes.

  • LFM3-Omni-2B is a separate, non-reasoning checkpoint. Its model card says enable_thinking=true is 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 {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! Look at the two comments on LFM3 configuration and see if those make sense.

Thank you!

@davidkoski

Copy link
Copy Markdown
Member

Also needs a rebase to fix the conflict in LLMModelFactory.swift

pHequals7 and others added 4 commits November 7, 2026 01:43
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>

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great, thank you!

@davidkoski
davidkoski merged commit c48e55e into ml-explore:main Nov 6, 2026
4 checks passed
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Nov 14, 2026
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>
smdesai added a commit to smdesai/mlx-swift-lm that referenced this pull request Nov 28, 2026
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.
@alvarogarciapiz alvarogarciapiz mentioned this pull request Nov 30, 2026
9 of 19 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants