Skip to content

Add LiquidAI LFM3 text support with extended validation and regression tests - #756

Merged
davidkoski merged 23 commits into
ml-explore:mainfrom
alvarogarciapiz:lfm3-review
Nov 16, 2026
Merged

davidkoski merged 23 commits into
ml-explore:mainfrom
alvarogarciapiz:lfm3-review

Conversation

@alvarogarciapiz

@alvarogarciapiz alvarogarciapiz commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

Original contribution and attribution

This branch builds directly on @pHequals7's implementation in PR #750. Credit for the original LFM3 text implementation, shared backbone, model registration, and original tests belongs to @pHequals7.

The original implementation and commit history are preserved unchanged, including e29240042f5544edaa6ba37d900a1e830585d391. The additional hardening is in 65fd3ae77552f2acdc75273350ab9d9b8b0b0056, followed by an attribution-only cleanup. This is a separate upstream PR from alvarogarciapiz:lfm3-review and overlaps #750; it is not a replacement attribution for that work.

The cleanup removes incorrect Copyright © 2026 Apple Inc. headers from the three test files independently added by this contribution. Existing headers in files inherited from the repository or the original contributor are retained. The root MIT license is unchanged.

Additional improvements

  • Preserve convolution cache state for the last valid tokens in batches with left/right padding and prepared sequence lengths, including rows with no valid tokens. The regression failed before the fix for multiple chunk sizes.
  • Validate configuration dimensions, attention/KV head compatibility, convolution lengths, sliding windows, epsilon, and supported RoPE parameters before constructing model modules.
  • Check cache types, cache-array length, embedding input shape, and convolution checkpoint tensor rank explicitly.
  • Detect known incompatible tokenization for the official LFM3 vocabulary at model load time.
  • Declare XML function-call metadata and the generic <think> protocol used by the official text checkpoint.
  • Add reproducible FP32 parity fixtures from LiquidAI's original implementation, operator/layer comparisons, full-vocabulary logit comparisons, and cache/window regression tests.
  • Add opt-in synthetic 4K/16K/32K cache checks and published 4-bit checkpoint validation, with reproducible reference-export scripts.
  • Document tokenizer requirements and the text-only scope. No vision, audio, or Omni wrapper is included.

Validation

Validation was run by Codex in the contributor's local checkout on an Apple M5 with 16 GB, macOS 27.0, and Xcode 27.2:

  • 28 LFM3 tests pass, including the official 4-bit checkpoint checks and synthetic long-context tests through 32K.
  • Official checkpoint parity uses identical dequantized weights, controlled FP32 execution, and matching token IDs. The maximum observed real-checkpoint logit difference is 9.33e-5, comparing all 128000 vocabulary logits at the final position of 19-, 257-, and 1024-token contexts; top-1 predictions match in all three cases. The small fixture also compares intermediate operators/layers and all token-position logits.
  • pre-commit run --all-files passes with the CI-pinned swift-format 603.0.0.
  • macOS build-for-testing passes.
  • scripts/verify-docs.sh passes for all library targets using SwiftPM's native build backend.
  • Compilation for a generic iOS device passes, with signing disabled. This is compilation verification, not iOS runtime testing.
  • The complete suite is not green: the broader run has 894 XCTest tests, seven skipped, and one failure in the unchanged GatedDeltaTests.testGatedDeltaFastPathKeepsDecayNearOneInFloat32 (0.0014360338 versus 0.001). It reproduces in isolation without instantiating LFM3. All 1334 Swift Testing tests pass. The previously reported 32K peak-memory smoke test passes both in the suite and in isolation.

Environment caveat: the Xcode 27.2 Metal component was unavailable, so macOS/iOS compilation selected the installed Metal 27.1 toolchain while retaining Xcode 27.2's Swift/Clang. DocC used the native SwiftPM backend. The standard Xcode test runner also encountered an internal cleanup error in the first broader run; the final broader run used xcrun xctest directly and completed without that runner error.

References are pinned to LiquidAI/LFM3-1.7B ac2586a34f1a1c03329dbdcdefabd8b6478ddaa7 and LiquidAI/LFM3-1.7B-MLX-4bit d0ca73dcfa70ce18733754a492cdc1fb0123262d. Real-checkpoint parity is tested through 1024 tokens; 32K coverage is synthetic. Published 6/8-bit and full original BF16 checkpoints were not validated; the existing synthetic mixed 4/6/8-bit test passes.

Known tokenizer dependency blocker

The default integration with the currently published swift-transformers 1.3.5 is incompatible with LFM3. LFM3 requires BPE ignore_merges: true and regex splitting by Unicode code point.

Both required fixes are merged, but no compatible stable release was found when checked on 2026-11-02:

The latest stable 1.3.5 release predates both merges. A compatible tokenizer implementation or dependency release containing both fixes is required for correct default integration. The core package remains tokenizer-agnostic; this PR neither duplicates the tokenizer nor pins an unstable dependency branch.

The implementation detects the known incompatible behavior instead of silently producing incorrect token IDs. For example, 1.3.5 encodes .reduce as [14425, 574, 353] instead of [96744]. The opt-in tokenizer tests, including the complete tool-call conversation, pass against corrected revision 93e4db644f7fda4460c61211c4b10fb67c1d0bdb; that validation does not establish compatibility of the published default dependency.

Checklist

Agent-run validation is documented above. First-person contributor attestations remain unchecked pending contributor confirmation.

  • 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: Codex assisted with code review, bug fixes, test implementation, numerical validation, documentation, attribution cleanup, and drafting this PR description. Personal contributor review, understanding of every line, and approval of the complete description have not been attested by the agent. The required personal approval checkbox is intentionally left unchecked pending contributor confirmation.

pHequals7 and others added 6 commits October 29, 2026 12:04
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>
@alvarogarciapiz

Copy link
Copy Markdown
Contributor Author

FYI @Liquid4All @ykhrustalev

Comment thread tools/lfm3-checkpoint-reference.py Resolved

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

The model addition looks good, but the tests shouldn't have safetensors. See my comment in the .py file.

Thanks!

Comment thread Libraries/MLXLLM/LLMModelFactory.swift Resolved
@ykhrustalev

Copy link
Copy Markdown
Contributor

@alvarogarciapiz I posted review comments in the base PR, would you mind having a look?

@github-actions github-actions Bot removed the needs-ci label Nov 2, 2026
@alvarogarciapiz

Copy link
Copy Markdown
Contributor Author

Thanks for the review @davidkoski. The follow-up commits remove the LFM3 safetensors resources from unit tests. Weights are now generated in memory in sorted parameter-name order, and Swift literals generated from LiquidAI's pinned implementation provide the numerical reference. The checkpoint-loading tests now live in IntegrationTesting/, and both generators are in tools/.

The factory no longer checks for LFM3Model. It calls the generic LLMModel.validate(tokenizer:) hook, whose default is a no-op; LFM3 owns its compatibility probes.

I also reviewed @ykhrustalev's comments on #750. The follow-up adds the tie_embedding alias with the reference's precedence, restricts backbone and hidden-state helpers to package access, adds the quantized nextTokenLogits path, and strengthens the independent-logit, untied-head, and separate attention-mask tests. The hashed-weight case follows @ykhrustalev's suggestion and is regenerated from the pinned original implementation.

For reasoning, this branch already declares .thinkTagsWithEnableThinking. I retained it because the official template implements enable_thinking=false and the current model card documents that option, with a warning that suppression can be inconsistent. The tokenizer integration test now verifies the disabled prompt ends in <think></think>. Source: https://huggingface.co/LiquidAI/LFM3-1.7B#inference . This differs from the proposed always-on preset; feedback on that distinction is welcome.

Swift Transformers 1.4.0 was published on November 2 and contains both #397 and #398. Both LFM3 tokenizer integration tests pass against this stable release, including the complete tool-call conversation. Version 1.3.5 remains incompatible and is still rejected by the known-behavior probes. No unstable dependency pin was introduced.

Local validation: 27 LFM3 unit tests, four checkpoint integration tests and two tokenizer integration tests pass. The unit tests cover synthetic contexts through 32K. The latest official 4-bit checkpoint logit comparison has maximum error 9.263e-5 (historical maximum across the earlier validations: 9.33e-5). Formatting, DocC, macOS test compilation and iOS device compilation pass.

The broader MLXLMTests run is not entirely green: its 890 XCTest cases have five skips and no failures, while its 1343 Swift Testing cases report the unchanged Gemma left-padding test as a failure and two known MiniCPM5 CDATA issues. The Gemma failure also reproduces in isolation, without running LFM3 tests.

Codex assisted with the review, implementation, tests, numerical checks, documentation and this draft. The original contribution and attribution to @pHequals7 are preserved.

@pierreromand96

Copy link
Copy Markdown

This would be really useful for us in a production environment. I’ve had a look at the code, and looks very promising.

Thanks for the contribution and for putting the work into this. Do you have a rough ETA for when this might get merged?

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

Changes look good, thank you!

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.

6 participants