Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[GGUF] Add LFM2/LFM2.5 dense, MoE, vision and audio support (#38857)

Maxim Vafin6bfaf9d2da5e
diff --git a/.claude/skills/ov-gguf/SKILL.md b/.claude/skills/ov-gguf/SKILL.md
index 7ac5cbcc83e..d45de1907ca 100644
--- a/.claude/skills/ov-gguf/SKILL.md
+++ b/.claude/skills/ov-gguf/SKILL.md
@@ -22,11 +22,11 @@ converters; builders and validation differ. Registration or conversion alone nev
|---|---|
| Is a model supported? | [supported_models.md](../../../src/frontends/gguf/docs/supported_models.md) or [mmproj.md](../../../src/frontends/gguf/docs/mmproj.md#supported-projectors); quote the checkpoint result and limitations, not just the catalog entry |
| Load a model, make it stateful/GenAI/PA-ready, tokenizer, IR export | [runtime.md](../../../src/frontends/gguf/docs/runtime.md) |
-| Add or port an architecture | [architectures.md](../../../src/frontends/gguf/docs/architectures.md); [extensions.md](../../../src/frontends/gguf/docs/extensions.md) when shipping it as a plugin |
-| Add or replace an mmproj branch | [extensions.md](../../../src/frontends/gguf/docs/extensions.md#extend-mmproj-with-a-projector-component), then the graph contracts in [mmproj.md](../../../src/frontends/gguf/docs/mmproj.md) |
+| Add or port an architecture | [architectures.md](../../../src/frontends/gguf/docs/architectures.md) and the [family contract](references/validation.md#family-contract); [extensions.md](../../../src/frontends/gguf/docs/extensions.md) when shipping it as a plugin |
+| Add or replace an mmproj branch | [extensions.md](../../../src/frontends/gguf/docs/extensions.md#extend-mmproj-with-a-projector-component), then the graph contracts in [mmproj.md](../../../src/frontends/gguf/docs/mmproj.md) and [multimodal contracts](references/validation.md#multimodal-contracts) |
| Missing ggml operation or `op_case` | [how_to_add_op.md](../../../src/frontends/gguf/docs/how_to_add_op.md) |
| Wrong numbers | [debugging_accuracy.md](../../../src/frontends/gguf/docs/debugging_accuracy.md) |
-| GenAI/mmproj token, media or PA mismatch | [multimodal integration bisection](../../../src/frontends/gguf/docs/debugging_accuracy.md#multimodal-integration-bisection) |
+| GenAI/mmproj token, media or PA mismatch | [multimodal integration bisection](../../../src/frontends/gguf/docs/debugging_accuracy.md#multimodal-integration-bisection) and [multimodal contracts](references/validation.md#multimodal-contracts) |
| Unsupported weight type | [quantization.md](../../../src/frontends/gguf/docs/quantization.md); the fix belongs in `src/quant/`, not a builder |
| Build, run tests, regenerate fixtures | [testing.md](../../../src/frontends/gguf/docs/testing.md) |
| Run or resume GGUF validation across OpenVINO, GenAI and llama.cpp | [validation.md](references/validation.md); use existing GHA workflows and focused local tests, preserving revisions, coverage and failures |
@@ -50,9 +50,11 @@ converters; builders and validation differ. Registration or conversion alone nev
share the bug. Do not tighten `expect_near` tolerances from an x86-only run.
- **Comparisons.** Use full logits or features on identical inputs and token histories, with
`INFERENCE_PRECISION_HINT=f32`, `DYNAMIC_QUANTIZATION_GROUP_SIZE=0` and the reference's KV precision.
- Set `OV_GGUF_Q4_K_ZP_F16=1` before the process starts. Report quantized-CPU and represented-F32
- comparisons separately and keep failed results. `GGML_OPENVINO_*` variables configure only the
- llama.cpp backend.
+ For strict checkpoint comparisons, set `OV_GGUF_Q4_K_ZP_F16=1` before starting the process.
+ Run the unfiltered frontend unit suite with this variable unset: integer-zero-point tests require
+ the default mode. Keep [scenario environments](references/validation.md#scenario-environments)
+ explicit. Report quantized-CPU and represented-F32 comparisons separately and keep failed results.
+ `GGML_OPENVINO_*` variables configure only the llama.cpp backend.
Inspect tensor-type inventory rather than checkpoint names. Identical quantized weights do
not rule out CPU arithmetic differences; exact expansions isolate them but do not waive the
original parity gate. Shared exported-model layout does not imply identical media geometry.
diff --git a/.claude/skills/ov-gguf/references/build-runtime.md b/.claude/skills/ov-gguf/references/build-runtime.md
index b47ac53d6bf..506d944b310 100644
--- a/.claude/skills/ov-gguf/references/build-runtime.md
+++ b/.claude/skills/ov-gguf/references/build-runtime.md
@@ -21,11 +21,52 @@ overlay is necessary, check the actual compile and link commands:
headers in the overlay. State which unchanged base objects are reused. Do not call an
overlay a full clean build or treat an old embedded version string as the new commit.
-After an actual inference, record resolved module paths and loaded core/frontend/plugin
-libraries. On Linux, `/proc/self/maps` from that process shows plugins loaded lazily;
-`ldd` on the executable alone does not. Hash the actual files and put those paths in the
-validation record, along with the build wrapper and explicit untracked source dependencies.
-Separate the OpenVINO runtime from the independent reference runtime.
+## Runtime preflight
+
+Before a broad test or checkpoint batch, preflight the runtime and prerequisites selected
+by its actual commands. Check frontend discovery, each requested device (including a default
+device wrapper when used), tokenizer extensions, fixture registration and required media/model
+files. Missing optional data must produce explicit skips; missing required data blocks that
+scenario. Do not require unused devices or export/download unrelated models.
+
+Run a small conversion/inference through the same harness and launch
+environment. Record intended core/frontend/plugin paths and hashes, then check the libraries
+actually loaded after inference. On Linux, `/proc/self/maps` shows plugins loaded lazily; `ldd`
+and pre-run hashes alone do not establish execution identity. Fix stale frontend or missing plugin
+discovery before launching the batch. Reuse the preflight result only while its inputs and launch
+environment remain unchanged; retain runtime identity from the actual validation process too.
+
+Use [runtime_identity.py](../scripts/runtime_identity.py) in the inference process, or with
+`--pid` while that process is alive after inference. Supply expected core/frontend/plugin paths
+and SHA-256 values captured before launch:
+
+```json
+{
+ "core": {"path": "/task/runtime/<resolved-core-library>", "sha256": "<expected SHA-256>"},
+ "frontend": {"path": "/task/runtime/libopenvino_gguf_frontend.so", "sha256": "<expected SHA-256>"},
+ "cpu": {"path": "/task/runtime/libopenvino_intel_cpu_plugin.so", "sha256": "<expected SHA-256>"}
+}
+```
+
+```python
+from runtime_identity import record_identity
+
+# Call after inference, while the frontend, core and compiled model remain alive.
+record_identity(expected, report_path)
+```
+
+The helper writes actual mapped paths/hashes and fails when an expected library is absent or
+mismatched. Add its directory to the harness's Python path, or invoke it from another process:
+
+```bash
+python runtime_identity.py --pid <inference-pid> --expected expected-runtime.json --output runtime.json
+```
+
+For overlays, check frontend discovery as well as `LD_LIBRARY_PATH`: a core loaded from the base
+directory can cause the frontend manager to scan that directory. Prefer a verified task-local
+runtime directory. Record any Linux `LD_PRELOAD` workaround explicitly; it is not a general default.
+Keep the report alongside build commands and untracked source dependencies. Separate the OpenVINO
+runtime from the independent reference runtime.
## When a pass or plugin fix seems ineffective
diff --git a/.claude/skills/ov-gguf/references/validation.md b/.claude/skills/ov-gguf/references/validation.md
index 36aff3da3e9..89dc313f44e 100644
--- a/.claude/skills/ov-gguf/references/validation.md
+++ b/.claude/skills/ov-gguf/references/validation.md
@@ -5,6 +5,35 @@ llama.cpp OpenVINO backend and GenAI. Use [testing.md](../../../../src/frontends
for build targets, fixture generation and individual tests. Registration or
conversion alone does not establish accuracy or end-to-end integration.
+## Family contract
+
+Before implementing a family, inspect the pinned reference loader and graph. Record consumed
+metadata and defaults, optional tensors, layer ordering, normalization/RoPE/routing order,
+tensor layouts and recurrent state shapes. Metadata present in a file may be ignored by the
+reference loader. Identify decoder, projector, embedding and audio contracts separately while
+preserving the user's requested scope. Distinguish implemented behavior from validated checkpoints;
+an unimplemented contract remains outstanding work, not an implicit scope reduction.
+
+Test layout-sensitive recurrent paths with batching early, alongside single-sequence numerics.
+Include multiple heads/tokens and unequal Q/KV dimensions where applicable.
+
+## Multimodal contracts
+
+Before connecting generation, record the pinned reference contract for each requested
+modality. Read only the applicable rows; derive values from source and checkpoint metadata.
+
+| Boundary | Facts to establish |
+|---|---|
+| Media preprocessing | Sample rate/channel layout; window, hop, padding and feature extraction; resize/tiling; normalization units and order |
+| Token and embedding assembly | Actual special-token IDs/spellings; per-media lengths; ordered spans and positions, including adjacent and reversed inputs |
+| Native and adapted graph | Input/output axes and dtypes; dynamic lengths; cache/state sizes, updates and reset; exact normalization and rotary-pair layout |
+| Speech generation, when requested | Codebook layout; modality cadence, EOS and feedback; sampling defaults; spectral/output head, preserved frames and waveform reconstruction |
+| API behavior | Supported configuration, media history, cancellation/reset and ownership/timing of streamed outputs |
+
+Check one small real media input through the application early. Use independent component
+references and boundary cases (unequal/dynamic dimensions, adjacent media, padding/window
+edges) before a broad sweep. Record unsupported contracts as remaining work.
+
## Define the matrix and reference
Record repository revisions, model/projector paths and revisions, tensor-type
@@ -14,8 +43,13 @@ and build wrapper files used. Verify the libraries actually loaded after
inference; read [build and runtime identity](build-runtime.md) for overlays,
incremental builds, multiple worktrees or dispatched CPU kernels.
-Specify selected scenarios, expected test counts and allowed skips, numerical
-metrics/tolerances, per-case timeouts and artifact paths. Distinguish conversion,
+Use one reusable runner and task manifest, extending the existing harness where available.
+Update the manifest at milestones and input/environment changes; retain commands, completed
+checks, failure signatures and the next diagnostic so handoffs can resume without full logs.
+Specify selected scenarios, per-case environments, expected test counts and allowed skips,
+existing numerical metrics/tolerances, timeouts and artifact paths. Keep runtime identity,
+completed cases and failed attempts in its reports; preserve the tests' acceptance gates
+rather than duplicating numerical assertions in a report parser. Distinguish conversion,
decoder numerics, text quality, vision/audio, PA/SDPA and Optimum compatibility.
Passing one scenario does not establish support for the others. Keep exclusions
and missing coverage explicit. A quantized reference checks backend parity, not
@@ -45,6 +79,17 @@ thresholds, expected failures or coverage to obtain a pass. For performance,
preserve hardware, load, warmup and repetition settings; noisy measurements do
not establish a regression or improvement.
+## Scenario environments
+
+Set the environment before each process starts; do not inherit checkpoint settings into the
+unfiltered unit suite. Record precision, KV precision and activation quantization independently.
+
+| Scenario | Zero-point setting | Acceptance |
+|---|---|---|
+| Unfiltered frontend unit suite | Unset `OV_GGUF_Q4_K_ZP_F16` | Default test expectations, required fixtures and op coverage |
+| Strict quantized checkpoint comparison | `OV_GGUF_Q4_K_ZP_F16=1` | Original full-logit or feature parity gate |
+| Represented-F32 diagnostic | Explicit environment and tensor-type inventory | Arithmetic isolation; does not replace quantized parity |
+
## Multimodal and API coverage
Choose a small discriminating matrix: synthetic square and real JPEG inputs,
@@ -111,7 +156,9 @@ an overlay. A successful local run does not prove GHA packaging or job selection
Retain failed attempts. Use `gh run rerun <run-id> --failed` for a deliberate retry
of transient failures; fixes require a new run at the new revision. Changed inputs
invalidate reuse. Expand or repeat only for changed inputs, a new failure or
-missing required coverage. Stop on a user pause and retain the run IDs and logs.
+missing required coverage. Before repeating an unchanged failing reproducer, record the
+new hypothesis or diagnostic; verify the actual graph/runtime inputs before another sweep.
+Stop on a user pause and retain the run IDs and logs.
## Delegate and report
@@ -128,9 +175,22 @@ needed. Wait for execution and the provenance check to finish before committing,
merging or rebuilding those inputs. Report useful checkpoints from the workflow
artifacts without per-test polling.
-Return tested revisions and runtime identity, completed/remaining cases, exact
-selected counts/skips, failures with excerpts, reproduction commands and artifact
-paths. Distinguish selected skips from filtered or unregistered suites and disclose
+Keep full XML, logs and inventories on disk. Return tested revisions and runtime identity,
+completed/remaining cases, exact selected counts/skips, grouped failure signatures, reproduction
+commands and artifact paths. Aim for at most 1,500 tokens of aggregate output per routine tool call
+(including batched results) or worker report; read larger excerpts only for a concrete
+investigation. Use [summarize_tests.py](../scripts/summarize_tests.py) for GTest/pytest XML:
+
+```bash
+python summarize_tests.py tests.xml --output test-summary.json --process-exit <test-exit-code>
+```
+
+The helper retains full failure/skip details in JSON and prints bounded counts/signatures.
+Its exit status reports parsing success; test acceptance still requires the test process
+status, required coverage and original numerical gates.
+
+Send checkpoints for completion, failure, missing prerequisites
+or a material state change. Distinguish selected skips from filtered or unregistered suites and disclose
standalone fixture adapters. Group equivalent errors without asserting a common
cause. Preserve original failures and numerical differences for diagnosis; known
arithmetic differences remain failed parity checks unless the user changes the
diff --git a/.claude/skills/ov-gguf/scripts/runtime_identity.py b/.claude/skills/ov-gguf/scripts/runtime_identity.py
new file mode 100644
index 00000000000..2c4dc852cf2
--- /dev/null
+++ b/.claude/skills/ov-gguf/scripts/runtime_identity.py
@@ -0,0 +1,69 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""Verify expected libraries in a live Linux inference process."""
+
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+
+
+def record_identity(expected, output, pid=None):
+ pid = os.getpid() if pid is None else int(pid)
+ report = {"pid": pid, "expected": expected, "mapped_libraries": [], "errors": []}
+ try:
+ libraries = {}
+ for label, entry in expected.items():
+ path = Path(entry["path"])
+ digest = entry["sha256"]
+ if not path.is_absolute() or not re.fullmatch(r"[0-9a-fA-F]{64}", digest):
+ raise ValueError(f"{label}: expected an absolute path and SHA-256")
+ libraries[label] = (path.resolve(strict=True), digest.lower())
+ if not libraries:
+ raise ValueError("expected library manifest is empty")
+ expected_names = {path.name for path, _ in libraries.values()}
+ mapped = {}
+ for line in Path(f"/proc/{pid}/maps").read_text().splitlines():
+ fields = line.split(maxsplit=5)
+ if len(fields) != 6 or not fields[5].startswith("/"):
+ continue
+ name = re.sub(r"\\([0-7]{3})", lambda match: chr(int(match[1], 8)), fields[5])
+ deleted = name.endswith(" (deleted)")
+ path = Path(name.removesuffix(" (deleted)"))
+ if path.name.startswith("libopenvino") or path.name in expected_names:
+ mapped[path.resolve()] = deleted
+ hashes = {}
+ for path, deleted in sorted(mapped.items()):
+ digest = None if deleted else hashlib.sha256(path.read_bytes()).hexdigest()
+ hashes[path] = digest
+ report["mapped_libraries"].append(
+ {"path": str(path), "sha256": digest, "deleted": deleted}
+ )
+ for label, (path, digest) in libraries.items():
+ if path not in hashes:
+ report["errors"].append(f"{label}: expected library is not mapped: {path}")
+ elif hashes[path] != digest:
+ report["errors"].append(f"{label}: mapped library hash differs: {path}")
+ except (OSError, KeyError, TypeError, ValueError) as error:
+ report["errors"].append(str(error))
+ report["passed"] = not report["errors"]
+ Path(output).write_text(json.dumps(report, indent=2) + "\n")
+ if not report["passed"]:
+ raise RuntimeError("; ".join(report["errors"]))
+ return report
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--expected", required=True, type=Path)
+ parser.add_argument("--output", required=True, type=Path)
+ parser.add_argument("--pid", type=int, default=os.getpid())
+ args = parser.parse_args()
+ record_identity(json.loads(args.expected.read_text()), args.output, args.pid)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.claude/skills/ov-gguf/scripts/summarize_tests.py b/.claude/skills/ov-gguf/scripts/summarize_tests.py
new file mode 100644
index 00000000000..b4230f8df9d
--- /dev/null
+++ b/.claude/skills/ov-gguf/scripts/summarize_tests.py
@@ -0,0 +1,90 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""Retain GTest/JUnit XML details and print a bounded summary; exit codes indicate parsing only."""
+
+import argparse
+from collections import Counter
+import json
+from pathlib import Path
+import re
+import xml.etree.ElementTree as ET
+
+
+def signature(message):
+ lines = [line.strip() for line in message.splitlines() if line.strip()]
+ useful = [line for line in lines if line != "unknown file" and "Exception from " not in line and not re.fullmatch(r".*:\d+(?::\d+)?", line)]
+ return " ".join((useful or lines)[:2])[:320] or "No message provided"
+
+
+def summarize(path):
+ root = ET.parse(path).getroot()
+ for node in root.iter():
+ node.tag = node.tag.rsplit("}", 1)[-1]
+ cases = list(root.iter("testcase"))
+ counts = Counter(selected=0, passed=0, failed=0, errors=0, skipped=0, not_run=0)
+ failures, skips = [], []
+ for case in cases:
+ if case.get("status") == "notrun" or case.get("result") == "suppressed":
+ counts["not_run"] += 1
+ continue
+ counts["selected"] += 1
+ name = ".".join(filter(None, (case.get("classname"), case.get("name"))))
+ errors = case.findall("error")
+ failed = case.findall("failure")
+ skipped = case.findall("skipped")
+ counts["errors" if errors else "failed" if failed else "skipped" if skipped else "passed"] += 1
+ for node in errors + failed:
+ message = node.text or node.get("message", "")
+ failures.append({"id": name, "kind": node.tag, "message": message, "signature": signature(message)})
+ for node in skipped:
+ skips.append({"id": name, "message": node.text or node.get("message", "")})
+ suite_errors = [
+ {"kind": node.tag, "message": node.text or node.get("message", "")}
+ for suite in root.iter("testsuite")
+ for node in list(suite)
+ if node.tag in ("failure", "error")
+ ]
+ return {"path": str(path.resolve()), "counts": dict(counts), "failures": failures,
+ "skips": skips, "suite_errors": suite_errors}
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("reports", nargs="+", type=Path)
+ parser.add_argument("--output", required=True, type=Path, help="Full JSON details; must differ from input reports")
+ parser.add_argument("--process-exit", type=int, help="Recorded exit code of the test process")
+ args = parser.parse_args()
+ if args.output.resolve() in {path.resolve() for path in args.reports}:
+ parser.error("output must not overwrite an input report")
+ reports, errors = [], []
+ for path in args.reports:
+ try:
+ reports.append(summarize(path))
+ except (OSError, ET.ParseError) as error:
+ errors.append({"path": str(path), "error": str(error)})
+ counts = Counter()
+ groups = Counter()
+ for report in reports:
+ counts.update(report["counts"])
+ groups.update(item["signature"] for item in report["failures"])
+ full = {"process_exit": args.process_exit, "counts": dict(counts), "reports": reports,
+ "parse_errors": errors}
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(json.dumps(full, indent=2) + "\n")
+ compact = {
+ "process_exit": args.process_exit,
+ "reports": len(reports),
+ "counts": dict(counts),
+ "suite_errors": sum(len(report["suite_errors"]) for report in reports),
+ "failure_signatures": [{"count": count, "signature": text} for text, count in groups.most_common(5)],
+ "omitted_signature_groups": max(0, len(groups) - 5),
+ "parse_errors": len(errors),
+ "details": str(args.output.resolve()),
+ }
+ print(json.dumps(compact, indent=2))
+ return 2 if errors else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/frontends/gguf/docs/mmproj.md b/src/frontends/gguf/docs/mmproj.md
index 8fb51d6cb4d..474f0359aff 100644
--- a/src/frontends/gguf/docs/mmproj.md
+++ b/src/frontends/gguf/docs/mmproj.md
@@ -23,6 +23,7 @@ numerical fixture checked against the llama.cpp CPU encoder (see
| Vision | `qwen2vl_merger`, `qwen2.5vl_merger`, `qwen3vl_merger` | temporal pairs, M-RoPE, windows (2.5), DeepStack (3) |
| Vision | `pixtral` | 2D RoPE, patch merger, row separators |
| Vision | `phi4` | dynamic resolution, resized positions |
+| Vision | `lfm2` | SigLIP, resized positions, pixel unshuffle, optional projector LayerNorm |
| Vision | `gemma4v`, `gemma4uv` | two-axis positions, per-tensor clipping, pooling; unified patch normalization |
| Vision | `muse-glimmer` | sparse/global windows, two-axis RoPE, pixel shuffle |
| Vision | `deepseekocr`, `deepseekocr2` | SAM local/global attention, tiles, queries, view separators |
@@ -37,8 +38,8 @@ frontend.
InternViT-6B (width 3200, 45 layers) uses RMS norms like the reference, but has no fixture.
-Not implemented: `ldp`, `ldpv2`, `adapter`, `step3vl`, `gemma3nv`, `llama4`, `qwen3a`, `lfm2`,
-`kimivl`, `paddleocr`, `lightonocr`, `cogvlm`, `dots_ocr`, `lfm2a`, `glm4v`, `youtuvl`, `yasa2`,
+Not implemented: `ldp`, `ldpv2`, `adapter`, `step3vl`, `gemma3nv`, `llama4`, `qwen3a`,
+`kimivl`, `paddleocr`, `lightonocr`, `cogvlm`, `dots_ocr`, `glm4v`, `youtuvl`, `yasa2`,
`kimik25`, `nemotron_v2_vl`, `exaone4_5`, `hunyuanvl`, `granite_speech`, `mimovl`,
`granite4_vision`. `gemma3na` has no graph builder in the reference.
@@ -264,3 +265,64 @@ they do not construct tokenizers, media preprocessing, or a complete GenAI pipel
Use [ProjectorExtension](extensions.md#extend-mmproj-with-a-projector-component) to add or replace one
vision/audio branch under the `clip` coordinator; the [examples](../examples/architecture_extension/README.md)
build and run one. A different whole-model format needs an `ArchitectureExtension`.
+
+## LFM2 vision projectors
+
+The `lfm2` projector supports LFM2-VL and LFM2.5-VL SigLIP encoders, resized square
+position embeddings, spatial pixel unshuffle, optional input LayerNorm and a GELU MLP.
+Native IO is `vision.pixel_values` (NCHW) plus `vision.merge_indices` (row-major indices
+grouped by each spatial merge window). The embedding adapter preserves these inputs and
+exposes `image_features`. The `VISION_ENCODERS` adapter exposes the same native pixels
+and merge-index layout for a GenAI LFM2 vision encoder.
+
+Two nonzero F32 fixtures compare raw and adapted embeddings at multiple rectangular sizes
+on one compiled model, with and without projector input normalization. LFM2-VL-450M's
+Q8_0 projector from `LiquidAI/LFM2-VL-450M-GGUF` revision
+`7cf9679aa137039135e342aa77014f7b5f2bef73` matches a represented-F32 llama.cpp CPU
+reference at 256x128 and 128x192 pixels with NMSE `1.79e-6` and `7.38e-7`. This validates
+the encoder graph, not image preprocessing, chat assembly or full multimodal generation.
+
+## LFM2 audio components
+
+The `lfm2a` audio projector supports the LFM2/LFM2.5 conformer encoder: depthwise
+subsampling, relative-position attention, half-step feed-forward branches, temporal
+convolution and the GELU language projection. Native inputs are `audio.features`
+`[1,1,mel_bins,frames]` and `audio.pos_emb`
+`[1,1,2*ceil(frames/8)-1,encoder_width]`, with interleaved sine/cosine positions.
+The audio adapter exposes `features`, `pos_emb` and `audio_features` `[1,tokens,hidden]`.
+GenAI supplies mono 16 kHz waveform preprocessing; the frontend accepts features.
+
+A pinned llama.cpp fixture checks 49/101/49 frames on one compiled model. The
+LFM2.5-Audio-1.5B Q4_0 encoder from LiquidAI revision
+`7d525f883a077e20afb782f2ff618edcae0e39e4` matches exact F32 expansions of the same
+weights with NMSE `3.81e-10` and `2.35e-9`. This is represented-F32 reference parity.
+
+LFM2.5 Audio's separate vocoder GGUF is a standalone speech-component architecture,
+`lfm2.audio_vocoder`, with `depthformer_n_layer`/`depthformer_n_embd` metadata. The
+publisher's `general.architecture` string, `this model cannot be used as LLM, use it
+via --model-vocoder in TTS examples`, is normalized to `lfm2.audio_vocoder` during
+loading for compatibility. Only the canonical name appears in the architecture catalog.
+It exposes
+`audio.depth_logits`, summed `audio.feedback`, averaged `audio.codec_features`, and
+`audio.istft_window`. Its `lfm2` detokenizer uses a 1282-channel `dense_2` spectral
+head and preserves all frames, including after GenAI adaptation. Pinned publisher
+PyTorch fixtures check depthformer outputs and detokenizer sliding-window boundaries.
+Actual Q4_0 depthformer and detokenizer represented-F32 comparisons have NMSE
+`2.62e-12` and `1.32e-9`; feedback and codec lookups match exactly.
+
+The GenAI `gguf-frontend-mmproj` integration supplies audio input through
+`VLMPipeline` and LFM2.5 speech output through `OmniPipeline`, including audio
+feedback and 24 kHz ISTFT reconstruction. Older Mimi-based LFM2 speech output
+requires a different codec and is not covered by the LFM2.5 vocoder builder.
+
+Final GenAI acceptance used the same pinned LFM2.5 audio bundle and the
+LFM2-VL-450M language/projector pair. Audio SDPA and PagedAttention each matched
+109/109 greedy reference choices over text, spoken input, multiple/reversed clips,
+audio chat and reset. Vision SDPA/PagedAttention passed seven scenarios each for
+square, JPEG and tiled inputs, including reversed images and both chat APIs.
+These are teacher-forced greedy-choice checks on the generated history, not
+strict full-logit parity or identical free-running speech reference generation.
+Speech API tests check deterministic repeated output, waveform chunk reconstruction,
+text-only output, retained audio inputs, cancellation recovery and sequential TTS.
+Speech chunks are delivered after decoding the complete waveform; low-latency
+streaming and replay of assistant codec tokens in chat history are not implemented.
diff --git a/src/frontends/gguf/docs/runtime.md b/src/frontends/gguf/docs/runtime.md
index e7b215be371..081671ecc0a 100644
--- a/src/frontends/gguf/docs/runtime.md
+++ b/src/frontends/gguf/docs/runtime.md
@@ -56,7 +56,8 @@ exposes GenAI's interface. Select the mode in the `GenAIExtension` constructor:
- The LM head is connected directly to the logits Result with a rank-3 input, so GenAI's
slice-before-matmul optimization projects only the sampled rows during prefill.
- Sliding-window masks use the `gguf_swa_window_size` rt_info value when the file records a window length.
-- Gated-DeltaNet states (`qwen35`, `qwen35moe`) get a dynamic batch, follow `beam_idx` and mask
+- Gated-DeltaNet states (`qwen35`, `qwen35moe`) and LFM2 short-convolution states
+ (`lfm2`, `lfm2moe`) get a dynamic batch, follow `beam_idx` and mask
left padding. Mamba 2 and `nemotron_h` states stay at one sequence: greedy, batch-1 decoding only.
A consumer must reset, not trim, the states listed in `gguf_recurrent_states`.
- The pass does not create a tokenizer, sampler or pipeline, and it does not adapt encoder models.
diff --git a/src/frontends/gguf/docs/supported_models.md b/src/frontends/gguf/docs/supported_models.md
index 03cdb113ec5..434f3f4bd24 100644
--- a/src/frontends/gguf/docs/supported_models.md
+++ b/src/frontends/gguf/docs/supported_models.md
@@ -37,6 +37,9 @@ with the [strict accuracy settings](quantization.md#accuracy-controls) (`OV_GGUF
| `hunyuan-dense` | Learned QK-norm after RoPE | Hunyuan-0.5B-Instruct Q8_0 | 13/13 |
| `hunyuan-moe` | QK-norm after RoPE, routed and shared experts | Hunyuan-A13B-Instruct Q2_K | 13/13 |
| `jais2` | Biased LayerNorm, ungated ReLU² FFN | Jais-2-8B-Chat Q4_K_M | 13/13 ² |
+| `lfm2` | LFM2 / LFM2.5 dense hybrid short convolution and GQA, QK-norm, tied head | LFM2-350M / LFM2.5-1.2B-Instruct Q4_0 | 13/13 each |
+| `lfm2.audio_vocoder` | Standalone speech component; accepts the existing publisher architecture string | LFM2.5-Audio-1.5B Q4_0 | [Component parity](mmproj.md#lfm2-audio-components) |
+| `lfm2moe` | LFM2 / LFM2.5 MoE hybrid, dense lead, biased normalized expert routing | LFM2.5-8B-A1B Q4_0 | 12/13 |
| `llama` | llama-2 / llama-3, YaRN | Devstral Small 2507 24B Q4_K_M | 13/13 |
| `llama-embed` | Per-token embeddings; mean/first/last pooling; causal or bidirectional | Llama-Nemotron-Embed-1B-v2 Q4_K_M | NMSE 3e-6 ² |
| `maincoder` | NORMAL RoPE, QK-norm after RoPE | Maincoder-1B Q4_K_M | 13/13 |
@@ -115,6 +118,46 @@ GGML_OPENVINO_DEVICE=CPU GGML_OPENVINO_STATEFUL_EXECUTION=1 \
Checkpoints used `Q2_K`, `Q4_0`, `Q4_K_M`, `Q6_K` and `Q8_0`; other formats are covered by unit tests only.
+## LFM2 and LFM2.5 coverage
+
+Dense and MoE language models use the `lfm2` and `lfm2moe` GGUF architecture names,
+respectively. The builder detects each convolution or attention layer from its weights;
+it supports arbitrary layer ordering, separate or fused QKV, per-head QK normalization,
+dense leading layers, softmax/sigmoid expert routing with selection bias, tied output
+weights, and attention sliding windows. No model-size-specific layer schedule is hardcoded.
+LFM2.5 8B-A1B and LFM2 24B-A2B use the same MoE builder; the 24B checkpoint has not been
+replayed. LFM2-VL and LFM2.5-VL language backbones use `lfm2`; their separate SigLIP vision
+projector is covered in [mmproj.md](mmproj.md).
+
+Six nonzero F32 llama.cpp fixtures cover mixed layer order, tied heads, a sliding-window
+boundary, fused QKV, dense-leading MoE, and all-routed sigmoid MoE. They compare full logits
+through prefill, cached one/multiple-token decode, and state reset with NMSE below `1e-5`.
+Batching, left padding, beam reordering, injected embeddings and structural conversion to
+PagedAttention/PagedCausalConv1D are covered separately. This does not establish a GenAI
+multimodal application or audio generation pipeline.
+
+Real CPU reference-token replay uses llama.cpp `03fa73cb27f5c251b9528489b18d303b1366aca4`,
+F32 inference, F16 KV, and disabled activation quantization. The prompt is
+`The capital of France is`. Quantized-CPU logit NMSE ranges are `2.32e-4..6.20e-3` for
+LFM2-350M, `3.99e-4..1.45e-3` for LFM2.5-1.2B-Instruct, and `2.98e-4..8.17e-2` for
+LFM2.5-8B-A1B. These pass the real-checkpoint greedy-choice gate above, not the F32
+fixture NMSE gate. Checkpoint revisions are `8fdc9d526b7ed346b19257551b05816c7912ecc2`,
+`8ed288026e23958ad9dfa92d53ed773a8eee7125`, and
+`49c14831707011e64d70b2ebd8462ba08d608434`, respectively, from LiquidAI's GGUF repositories.
+
+The standalone `lfm2.audio_vocoder` architecture loads LFM2.5 Audio depthformer and
+codec components; the existing publisher architecture string is also accepted.
+It consumes hidden states and codec codes rather than text tokens; see
+[audio component inputs and outputs](mmproj.md#lfm2-audio-components).
+
+Noncausal LFM2 embedding/encoder/ColBERT variants need centered convolution and their
+embedding/pooling output contracts and are rejected explicitly. LFM2.5-Audio's `lfm2a`
+conformer projector and LFM2.5 speech components are supported as described in
+[mmproj.md](mmproj.md#lfm2-audio-components). GenAI waveform preprocessing and generation
+require the `gguf-frontend-mmproj` integration. Older Mimi-based LFM2 speech output
+requires a separate codec. Other sizes, quantizations, long contexts,
+and downstream fine-tunes require their own checkpoint validation.
+
## Bonsai and Bonsai-2
The native GGUF frontend supports the following model families and weight formats:
diff --git a/src/frontends/gguf/src/builder/api/graph_context.cpp b/src/frontends/gguf/src/builder/api/graph_context.cpp
index 91d6fad2dda..7b3315f469e 100644
--- a/src/frontends/gguf/src/builder/api/graph_context.cpp
+++ b/src/frontends/gguf/src/builder/api/graph_context.cpp
@@ -133,7 +133,9 @@ GgufValue GgufGraphContext::add_constant(const std::string& name, const ov::Tens
GgufValue GgufGraphContext::build_inp_embd(const GgufValue& tok_embd) {
OPENVINO_ASSERT(tok_embd, "[GGUF] build_inp_embd: the token embedding weight is missing");
auto tokens = add_input("inp_tokens", i32, ov::PartialShape({1, 1, 1, D}));
- return node("GGML_OP_GET_ROWS", {tok_embd, tokens});
+ auto embeddings = node("GGML_OP_GET_ROWS", {tok_embd, tokens});
+ embeddings.m_value.get_node_shared_ptr()->get_rt_info()["gguf.token_embedding"] = true;
+ return embeddings;
}
GgufValue GgufGraphContext::build_inp_pos() {
diff --git a/src/frontends/gguf/src/builder/arch/lfm2_builder.cpp b/src/frontends/gguf/src/builder/arch/lfm2_builder.cpp
new file mode 100644
index 00000000000..ea09a1dcf37
--- /dev/null
+++ b/src/frontends/gguf/src/builder/arch/lfm2_builder.cpp
@@ -0,0 +1,228 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "lfm2_builder.hpp"
+
+#include <cmath>
+#include <limits>
+
+#include "openvino/frontend/gguf/builder/graph_context.hpp"
+
+namespace ov::frontend::gguf {
+namespace {
+class Lfm2Builder : public ModelBuilder {
+public:
+ explicit Lfm2Builder(const BuildContext& context) : g(context) {}
+
+ std::shared_ptr<GgufGraph> build() override {
+ const auto kernel = g.metadata().get_int(g.arch() + ".shortconv.l_cache");
+ OPENVINO_ASSERT(kernel && *kernel > 1 && *kernel <= std::numeric_limits<int>::max(),
+ "[GGUF] LFM2 requires shortconv.l_cache > 1");
+ OPENVINO_ASSERT(g.metadata().get_bool(g.arch() + ".attention.causal").value_or(true),
+ "[GGUF] noncausal LFM2 embedding models require a centered convolution builder");
+ DecoderOptions options;
+ options.normalize_expert_weights = true;
+ const auto dims = g.configure_decoder(RopeMode::Neox, options);
+ OPENVINO_ASSERT(dims.layers > 0 && dims.embedding > 0,
+ "[GGUF] LFM2 requires positive layer and embedding counts");
+ g.build_inp_pos();
+ g.build_attn_inp_kv();
+ auto weights = g.tensors();
+ auto cur = g.build_inp_embd(weights.require("token_embd.weight"));
+ const bool detokenizer = weights.has("dense_2.weight");
+ if (detokenizer)
+ OPENVINO_ASSERT(weights.require("dense_2.weight").ne(0) == dims.embedding &&
+ weights.require("dense_2.weight").ne(1) == 1282,
+ "[GGUF] LFM2 audio detokenizer requires a 1282-channel spectral head");
+ const auto out_ids = detokenizer ? GgufValue{} : g.build_inp_out_ids();
+ for (int layer = 0; layer < dims.layers; ++layer) {
+ const auto prefix = "blk." + std::to_string(layer) + ".";
+ const auto w = [&](const std::string& name) {
+ return weights.require(prefix + name);
+ };
+ auto residual = cur;
+ cur = g.build_norm(cur, w("attn_norm.weight"), dims.norm_epsilon);
+ if (weights.has(prefix + "shortconv.in_proj.weight")) {
+ const auto projected = g.node("GGML_OP_MUL_MAT", {w("shortconv.in_proj.weight"), cur});
+ const auto b = slice(projected, 0, dims.embedding);
+ const auto c = slice(projected, dims.embedding, dims.embedding);
+ const auto x = slice(projected, 2 * int64_t{dims.embedding}, dims.embedding);
+ const auto bx = g.node("GGML_OP_TRANSPOSE", {g.node("GGML_OP_MUL", {b, x})});
+ const auto state = g.add_input("conv_state_l" + std::to_string(layer),
+ ov::element::f32,
+ {1, 1, dims.embedding, *kernel - 1});
+ const auto window = g.node("GGML_OP_CONCAT", {state, bx}, 0, {{"concat_axis", 0}});
+ g.add_recurrent_state(state, slice(window, -(*kernel - 1), *kernel - 1));
+ const auto convolution =
+ g.node("GGML_OP_SSM_CONV", {window, w("shortconv.conv.weight")}, 0, {{"batch_major", true}});
+ cur = g.node("GGML_OP_MUL_MAT",
+ {w("shortconv.out_proj.weight"), g.node("GGML_OP_MUL", {c, convolution})});
+ } else {
+ cur = g.decoder_attention(layer, cur);
+ }
+ if (layer == dims.layers - 1 && out_ids) {
+ cur = g.node("GGML_OP_GET_ROWS", {cur, out_ids});
+ residual = g.node("GGML_OP_GET_ROWS", {residual, out_ids});
+ }
+ cur = g.node("GGML_OP_ADD", {cur, residual});
+ residual = cur;
+ cur = g.build_norm(cur, w("ffn_norm.weight"), dims.norm_epsilon);
+ cur = g.node("GGML_OP_ADD", {residual, g.decoder_ffn(layer, cur)});
+ }
+ cur = g.build_norm(cur, weights.require("token_embd_norm.weight"), dims.norm_epsilon);
+ if (detokenizer) {
+ auto output = g.node("GGML_OP_MUL_MAT", {weights.require("dense_2.weight"), cur});
+ if (auto bias = weights("dense_2.bias"))
+ output = g.node("GGML_OP_ADD", {output, bias});
+ g.set_primary_output(output);
+ } else {
+ const auto output =
+ weights.has("output.weight") ? weights.require("output.weight") : weights.require("token_embd.weight");
+ g.set_primary_output(g.node("GGML_OP_MUL_MAT", {output, cur}));
+ }
+ return g.finish();
+ }
+
+private:
+ GgufValue slice(const GgufValue& value, int64_t start, int64_t length) {
+ return g.node("GGML_OP_VIEW", {value}, 3, {{"view_slice", std::vector<int64_t>{3, start, length}}});
+ }
+
+ GgufGraphContext g;
+};
+class Lfm2VocoderBuilder : public ModelBuilder {
+public:
+ explicit Lfm2VocoderBuilder(const BuildContext& context) : g(context) {}
+
+ std::shared_ptr<GgufGraph> build() override {
+ auto weights = g.tensors();
+ const auto width = g.metadata().get_int("depthformer_n_embd").value_or(0);
+ const auto layers = g.metadata().get_int("depthformer_n_layer").value_or(0);
+ OPENVINO_ASSERT(width > 0 && layers > 0, "[GGUF] invalid LFM2 depthformer dimensions");
+ const auto projection = weights.require("depth_linear.weight");
+ constexpr int64_t books = 8;
+ const auto vocabulary = weights.require("depth_embeddings.0.to_logits.weight").ne(1);
+ const auto head = weights.require("depthformer.layers.0.operator.attention.q_layernorm.weight").ne(0);
+ const auto qkv_width = weights.require("depthformer.layers.0.operator.qkv_proj.weight").ne(1);
+ const auto kv_width = (qkv_width - width) / 2;
+ OPENVINO_ASSERT(projection.ne(1) == books * width && vocabulary == 2049 && head > 0 && width % head == 0 &&
+ kv_width > 0 && kv_width % head == 0 && width % kv_width == 0,
+ "[GGUF] invalid LFM2 audio depthformer tensor dimensions");
+ RopeConfig rope;
+ rope.n_dims = int(head);
+ rope.n_ctx_orig = 128000;
+ rope.freq_base = 1000000.f;
+ rope.freq_scale = 1.f;
+ rope.attn_factor = 1.f;
+ rope.per_op = true;
+ g.configure_rope(rope);
+ auto hidden = g.add_input("audio.hidden_states", ov::element::f32, {1, 1, 1, projection.ne(0)});
+ auto previous = g.add_input("audio.depth_codes", ov::element::i32, {1, 1, 1, books});
+ auto x = reshape(linear(hidden, "depth_linear"), {1, 1, books, width});
+ ov::Tensor zeros(ov::element::f32, {1, 1, 1, size_t(width)});
+ std::fill_n(zeros.data<float>(), zeros.get_size(), 0.f);
+ auto shifted = g.add_constant("audio.depth_zero", zeros);
+ for (int64_t book = 1; book < books; ++book) {
+ auto embedding =
+ g.node("GGML_OP_GET_ROWS",
+ {weights.require("depth_embeddings." + std::to_string(book - 1) + ".embedding.weight"),
+ slice(previous, 3, book - 1, 1)});
+ shifted = concat(shifted, embedding, 1);
+ }
+ x = add(x, shifted);
+ ov::Tensor positions(ov::element::i32, {1, 1, 1, size_t(books)});
+ ov::Tensor mask(ov::element::f32, {1, 1, size_t(books), size_t(books)});
+ for (int64_t i = 0; i < books; ++i) {
+ positions.data<int32_t>()[i] = int32_t(i);
+ for (int64_t j = 0; j < books; ++j)
+ mask.data<float>()[i * books + j] = j <= i ? 0.f : -std::numeric_limits<float>::infinity();
+ }
+ auto pos = g.add_constant("audio.depth_positions", positions);
+ auto causal = g.add_constant("audio.depth_mask", mask);
+ for (int64_t i = 0; i < layers; ++i) {
+ const auto p = "depthformer.layers." + std::to_string(i) + ".";
+ auto normalized = g.build_norm(x, weights.require(p + "operator_norm.weight"), 1e-5f);
+ auto qkv = linear(normalized, p + "operator.qkv_proj");
+ const auto heads = [&](int64_t begin, int64_t channels, const std::string& norm) {
+ auto value = reshape(slice(qkv, 3, begin, channels), {1, books, channels / head, head});
+ if (!norm.empty())
+ value = g.build_norm(value, weights.require(p + norm), 1e-5f);
+ return value;
+ };
+ auto q = heads(0, width, "operator.attention.q_layernorm.weight");
+ auto k = heads(width, kv_width, "operator.attention.k_layernorm.weight");
+ auto v = heads(width + kv_width, kv_width, "");
+ q = g.node("GGML_OP_ROPE", {q, pos}, 0, {{"rope_config", rope}});
+ k = g.node("GGML_OP_ROPE", {k, pos}, 0, {{"rope_config", rope}});
+ auto attention = g.node("GGML_OP_FLASH_ATTN_EXT",
+ {q, k, v, causal},
+ 100,
+ {{"f32_attention", true}, {"scale", 1.f / std::sqrt(float(head))}});
+ x = add(x, linear(reshape(attention, {1, 1, books, width}), p + "operator.out_proj"));
+ normalized = g.build_norm(x, weights.require(p + "ffn_norm.weight"), 1e-5f);
+ auto gated = g.node("GGML_OP_MUL",
+ {g.node("GGML_UNARY_OP_SILU", {linear(normalized, p + "feed_forward.w1")}),
+ linear(normalized, p + "feed_forward.w3")});
+ x = add(x, linear(gated, p + "feed_forward.w2"));
+ }
+ GgufValue logits;
+ for (int64_t book = 0; book < books; ++book) {
+ const auto p = "depth_embeddings." + std::to_string(book);
+ auto normalized = g.build_norm(slice(x, 2, book, 1), weights.require(p + ".embedding_norm.weight"), 1e-5f);
+ auto current = linear(normalized, p + ".to_logits");
+ logits = logits ? concat(logits, current, 1) : current;
+ }
+ g.set_output(logits, "audio.depth_logits");
+ auto codes = g.add_input("audio.codes", ov::element::i32, {1, 1, -1, books});
+ GgufValue feedback, codec;
+ for (int64_t book = 0; book < books; ++book) {
+ auto index = reshape(slice(codes, 3, book, 1), {1, 1, 1, -1});
+ const auto lookup = [&](const std::string& name, int64_t stride) {
+ ov::Tensor offset(ov::element::i32, {1, 1, 1, 1});
+ offset.data<int32_t>()[0] = int32_t(book * stride);
+ auto ids = add(index, g.add_constant(name + ".offset." + std::to_string(book), offset));
+ return g.node("GGML_OP_GET_ROWS", {weights.require(name), ids});
+ };
+ auto audio = lookup("audio_embedding.embedding.weight", vocabulary);
+ auto frame = lookup("emb.emb.weight", vocabulary - 1);
+ feedback = feedback ? add(feedback, audio) : audio;
+ codec = codec ? add(codec, frame) : frame;
+ }
+ g.set_output(feedback, "audio.feedback");
+ g.set_output(g.node("GGML_OP_SCALE", {codec}, 0, {{"scale", 1.f / float(books)}}), "audio.codec_features");
+ g.set_output(weights.require("istft.window"), "audio.istft_window");
+ return g.finish();
+ }
+
+private:
+ GgufValue reshape(const GgufValue& value, const std::vector<int64_t>& shape) {
+ return g.node("GGML_OP_RESHAPE", {value}, 0, {{"reshape_target", shape}});
+ }
+ GgufValue slice(const GgufValue& value, int64_t axis, int64_t start, int64_t length) {
+ return g.node("GGML_OP_VIEW", {value}, 3, {{"view_slice", std::vector<int64_t>{axis, start, length}}});
+ }
+ GgufValue add(const GgufValue& a, const GgufValue& b) {
+ return g.node("GGML_OP_ADD", {a, b});
+ }
+ GgufValue concat(const GgufValue& a, const GgufValue& b, int axis) {
+ return g.node("GGML_OP_CONCAT", {a, b}, 0, {{"concat_axis", axis}});
+ }
+ GgufValue linear(const GgufValue& value, const std::string& name) {
+ auto result = g.node("GGML_OP_MUL_MAT", {g.tensors().require(name + ".weight"), value});
+ if (auto bias = g.tensors()(name + ".bias"))
+ result = add(result, bias);
+ return result;
+ }
+ GgufGraphContext g;
+};
+} // namespace
+
+std::shared_ptr<ModelBuilder> make_lfm2_builder(const BuildContext& context) {
+ return std::make_shared<Lfm2Builder>(context);
+}
+
+std::shared_ptr<ModelBuilder> make_lfm2_vocoder_builder(const BuildContext& context) {
+ return std::make_shared<Lfm2VocoderBuilder>(context);
+}
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/arch/lfm2_builder.hpp b/src/frontends/gguf/src/builder/arch/lfm2_builder.hpp
new file mode 100644
index 00000000000..d6c48f53eba
--- /dev/null
+++ b/src/frontends/gguf/src/builder/arch/lfm2_builder.hpp
@@ -0,0 +1,11 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+#include "openvino/frontend/gguf/builder/model_builder.hpp"
+
+namespace ov::frontend::gguf {
+std::shared_ptr<ModelBuilder> make_lfm2_builder(const BuildContext& context);
+std::shared_ptr<ModelBuilder> make_lfm2_vocoder_builder(const BuildContext& context);
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
index e22a2305cb8..eb0c06855c4 100644
--- a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
@@ -36,7 +36,9 @@ enum class EncoderTopology {
MINICPM46,
MUSE_GLIMMER,
PHI4,
+ LFM2,
GEMMA4_AUDIO,
+ LFM2_AUDIO,
OCR,
OCR2
};
@@ -65,10 +67,12 @@ constexpr ProjectorTopology projector_catalog[] = {
{"vision", "deepseekocr2", EncoderTopology::OCR2, RMS_NORM},
{"vision", "pixtral", EncoderTopology::PIXTRAL, RMS_NORM},
{"vision", "phi4", EncoderTopology::PHI4},
+ {"vision", "lfm2", EncoderTopology::LFM2},
{"vision", "muse-glimmer", EncoderTopology::MUSE_GLIMMER},
{"vision", "gemma4v", EncoderTopology::GEMMA4, RMS_NORM},
{"vision", "gemma4uv", EncoderTopology::UNIFIED_VISION},
{"audio", "gemma4a", EncoderTopology::GEMMA4_AUDIO},
+ {"audio", "lfm2a", EncoderTopology::LFM2_AUDIO},
{"audio", "gemma4ua", EncoderTopology::UNIFIED_AUDIO},
{"vision", "minicpmv4_6", EncoderTopology::MINICPM46},
{"vision", "gemma3", EncoderTopology::SIGLIP, SWAPPED_FFN},
@@ -178,12 +182,14 @@ EncoderConfig config(const GgufMetadata& meta, const std::string& modality, cons
}
if (c.topology == EncoderTopology::PIXTRAL || c.topology == EncoderTopology::GEMMA4 ||
c.topology == EncoderTopology::UNIFIED_VISION || c.topology == EncoderTopology::MINICPM46 ||
- c.topology == EncoderTopology::PHI4) {
+ c.topology == EncoderTopology::PHI4 || c.topology == EncoderTopology::LFM2) {
if (c.topology == EncoderTopology::PIXTRAL)
c.merge = meta.get_int(key + "spatial_merge_size").value_or(1);
else if (c.topology != EncoderTopology::PHI4)
c.merge = meta.get_int(key + "projector.scale_factor")
- .value_or(c.topology == EncoderTopology::MINICPM46 ? 4 : 3);
+ .value_or(c.topology == EncoderTopology::MINICPM46 ? 4
+ : c.topology == EncoderTopology::LFM2 ? 2
+ : 3);
OPENVINO_ASSERT(c.merge > 0, "[GGUF] invalid vision merge size");
if (c.topology == EncoderTopology::UNIFIED_VISION) {
c.patch *= c.merge;
@@ -533,7 +539,8 @@ private:
if (c.topology == EncoderTopology::OCR || c.topology == EncoderTopology::OCR2)
return ocr_vision(c);
if (c.topology == EncoderTopology::PIXTRAL || c.topology == EncoderTopology::GEMMA4 ||
- c.topology == EncoderTopology::UNIFIED_VISION || c.topology == EncoderTopology::PHI4)
+ c.topology == EncoderTopology::UNIFIED_VISION || c.topology == EncoderTopology::PHI4 ||
+ c.topology == EncoderTopology::LFM2)
return dynamic_vision(c);
if (c.topology == EncoderTopology::MINICPM46)
return minicpm46(c);
@@ -636,7 +643,7 @@ private:
x = patch_embeddings(spatial, c.width, c.topology != EncoderTopology::GEMMA4);
}
GgufValue pos_a, pos_b, learned;
- if (c.topology == EncoderTopology::PHI4) {
+ if (c.topology == EncoderTopology::PHI4 || c.topology == EncoderTopology::LFM2) {
auto table =
resize_square_table(g.tensors().require("v.position_embd.weight"), spatial, c.width, 0x201, "phi4");
learned = reshape(transpose(table, {0, 2, 3, 1}), {1, 1, -1, c.width});
@@ -663,6 +670,15 @@ private:
c.topology == EncoderTopology::PIXTRAL ? pos_b : pos_a,
{},
c.topology == EncoderTopology::PIXTRAL ? pos_a : pos_b);
+ if (c.topology == EncoderTopology::LFM2) {
+ x = gather_rows(x, "merge_indices");
+ x = reshape(x, {1, 1, -1, c.width * c.merge * c.merge});
+ if (g.tensors().has("mm.input_norm.weight"))
+ x = norm(x, "mm.input_norm", 1e-5f);
+ else if (auto bias = g.tensors()("mm.input_norm.bias"))
+ x = add(x, bias);
+ return ffn(x, "mm.1", "mm.2", "GGML_UNARY_OP_GELU");
+ }
if (c.topology == EncoderTopology::PHI4) {
g.tensors().require("mm.0.bias");
g.tensors().require("mm.2.bias");
@@ -935,6 +951,74 @@ private:
x = concat(x, reshape(g.tensors().require("v.view_seperator"), {1, 1, 1, width}), 1);
return gather_rows(x, "output_indices");
}
+ GgufValue lfm2_audio(const EncoderConfig& c) {
+ const auto mel = positive(g.metadata(), "clip.audio.num_mel_bins");
+ auto x = transpose(g.add_input("audio.features", ov::element::f32, {1, 1, mel, -1}));
+ for (int i : {0, 2, 3, 5, 6}) {
+ const auto p = "a.conv1d." + std::to_string(i);
+ const bool depthwise = i == 2 || i == 5;
+ const int64_t stride = i == 0 || depthwise ? 2 : 1;
+ x = g.node("GGML_OP_CONV_2D",
+ {g.tensors().require(p + ".weight"), x},
+ 0,
+ {{"conv_params", std::vector<int64_t>{stride, stride, stride - 1, stride - 1, 1, 1}},
+ {"depthwise", depthwise}});
+ x = add(x, g.tensors().require(p + ".bias"));
+ if (i == 0 || i == 3 || i == 6)
+ x = g.node("GGML_UNARY_OP_RELU", {x});
+ }
+ const auto flattened = g.tensors().require("a.pre_encode.out.weight").ne(0);
+ x = linear(reshape(transpose(x, {0, 2, 1, 3}), {1, 1, -1, flattened}), "a.pre_encode.out");
+ const auto pos_width = g.tensors().require("a.blk.0.linear_pos.weight").ne(0);
+ auto positions = g.add_input("audio.pos_emb", ov::element::f32, {1, 1, -1, pos_width});
+ const auto head = c.width / c.heads;
+ const auto half_ffn = [&](const GgufValue& value, const std::string& p, const std::string& suffix) {
+ return add(value,
+ scale(ffn(norm(value, p + "ffn_norm" + suffix, c.eps),
+ p + "ffn_up" + suffix,
+ p + "ffn_down" + suffix,
+ "GGML_UNARY_OP_SILU"),
+ .5f));
+ };
+ for (int64_t i = 0; i < c.layers; ++i) {
+ const auto p = "a.blk." + std::to_string(i) + ".";
+ x = half_ffn(x, p, "");
+ auto z = norm(x, p + "ln1", c.eps);
+ auto q = reshape(linear(z, p + "attn_q"), {1, -1, c.heads, head});
+ const auto biased_query = [&](const char* name) {
+ return transpose(add(q, reshape(g.tensors().require(p + name), {1, 1, c.heads, head})), {0, 2, 1, 3});
+ };
+ auto k = transpose(reshape(linear(z, p + "attn_k"), {1, -1, c.heads, head}), {0, 2, 1, 3});
+ auto v = transpose(reshape(linear(z, p + "attn_v"), {1, -1, c.heads, head}), {0, 2, 3, 1});
+ auto pos =
+ transpose(reshape(linear(positions, p + "linear_pos", false), {1, -1, c.heads, head}), {0, 2, 1, 3});
+ auto content = g.node("GGML_OP_MUL_MAT", {k, biased_query("pos_bias_u")});
+ auto relative = g.node("GGML_OP_MUL_MAT", {pos, biased_query("pos_bias_v")});
+ relative = g.node("GGML_OP_GET_ROWS", {relative}, 0, {{"relative_shift", true}});
+ auto probability = g.node("GGML_OP_SOFT_MAX",
+ {scale(add(content, relative), 1.f / std::sqrt(float(head)))},
+ 0,
+ {{"scale", 1.f}});
+ z = g.node("GGML_OP_MUL_MAT", {v, probability});
+ x = add(x, linear(reshape(transpose(z, {0, 2, 1, 3}), {1, 1, -1, c.width}), p + "attn_out"));
+ z = linear(norm(x, p + "norm_conv", c.eps), p + "conv_pw1");
+ z = transpose(
+ mul(slice(z, 3, 0, c.width), g.node("GGML_UNARY_OP_SIGMOID", {slice(z, 3, c.width, c.width)})));
+ const auto kernel = g.tensors().require(p + "conv_dw.weight").ne(0);
+ OPENVINO_ASSERT(kernel % 2 == 1, "[GGUF] LFM2 audio requires an odd convolution kernel");
+ z = g.node(
+ "GGML_OP_PAD",
+ {z},
+ 0,
+ {{"pad_params", std::vector<int32_t>{int32_t(kernel / 2), int32_t(kernel / 2), 0, 0, 0, 0, 0, 0}}});
+ z = add(g.node("GGML_OP_SSM_CONV", {z, g.tensors().require(p + "conv_dw.weight")}),
+ g.tensors().require(p + "conv_dw.bias"));
+ z = add(mul(z, g.tensors().require(p + "conv_norm.weight")), g.tensors().require(p + "conv_norm.bias"));
+ x = add(x, linear(g.node("GGML_UNARY_OP_SILU", {z}), p + "conv_pw2"));
+ x = norm(half_ffn(x, p, "_1"), p + "ln2", c.eps);
+ }
+ return ffn(norm(x, "mm.a.mlp.0", c.eps), "mm.a.mlp.1", "mm.a.mlp.3", "GGML_UNARY_OP_GELU_ERF");
+ }
GgufValue gemma4_audio(const EncoderConfig& c) {
const auto mel = positive(g.metadata(), "clip.audio.num_mel_bins");
auto x = g.add_input("audio.features", ov::element::f32, {1, 1, mel, -1});
@@ -1040,6 +1124,8 @@ private:
return linear(x, "mm.a.input_projection", false);
}
GgufValue audio(const EncoderConfig& c) {
+ if (c.topology == EncoderTopology::LFM2_AUDIO)
+ return lfm2_audio(c);
if (c.topology == EncoderTopology::GEMMA4_AUDIO)
return gemma4_audio(c);
if (c.topology == EncoderTopology::UNIFIED_AUDIO) {
diff --git a/src/frontends/gguf/src/builder/arch_registry.cpp b/src/frontends/gguf/src/builder/arch_registry.cpp
index 73f8f2c5d8c..750410dbfc9 100644
--- a/src/frontends/gguf/src/builder/arch_registry.cpp
+++ b/src/frontends/gguf/src/builder/arch_registry.cpp
@@ -8,6 +8,7 @@
#include <utility>
#include "builder/arch/dspark_builder.hpp"
+#include "builder/arch/lfm2_builder.hpp"
#include "builder/arch/mamba_builder.hpp"
#include "builder/arch/mmproj_builder.hpp"
#include "openvino/core/except.hpp"
@@ -56,6 +57,13 @@ const ArchitectureEntry architectures[] = {
{"hunyuan-dense", RopeMode::Neox},
{"hunyuan-moe", RopeMode::Neox},
{"jais2", RopeMode::Neox},
+ {"lfm2", make_lfm2_builder},
+ {"lfm2.audio_vocoder",
+ make_lfm2_vocoder_builder,
+ [](const GgufMetadata& meta) {
+ return meta.has("depthformer_n_layer") && meta.has("depthformer_n_embd");
+ }},
+ {"lfm2moe", make_lfm2_builder},
{"llama", RopeMode::Normal},
{"llama-embed", RopeMode::Normal},
{"maincoder", RopeMode::Normal},
diff --git a/src/frontends/gguf/src/builder/decoder_config.cpp b/src/frontends/gguf/src/builder/decoder_config.cpp
index 5ae387f5270..4c5aa53109a 100644
--- a/src/frontends/gguf/src/builder/decoder_config.cpp
+++ b/src/frontends/gguf/src/builder/decoder_config.cpp
@@ -78,14 +78,22 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
relu_squared_ffn = arch == "jais2";
// Per-architecture structure, auto-detected from the GGUF tensor table (layer 0).
- has_qk_norm = has("blk.0.attn_q_norm.weight");
+ std::string attention_probe = "blk.0.";
+ for (int layer = 0; layer < n_layer; ++layer) {
+ const auto prefix = "blk." + std::to_string(layer) + ".";
+ if (has(prefix + "attn_q_norm.weight")) {
+ attention_probe = prefix;
+ break;
+ }
+ }
+ has_qk_norm = has(attention_probe + "attn_q_norm.weight");
// q/k norm width: per-head (head_size, applied after reshape -> qwen3/hunyuan/gemma4)
// vs full projection width (n_head*head_size, applied before reshape -> OLMoE).
// For gemma4, norm width equals per-layer head_size (may differ by SWA/global); always
// per-head. For OLMoE, norm width equals n_head*head_size. Detect by checking against
// the global head_size; but for gemma4 override to per-head since it has mixed head sizes.
if (has_qk_norm) {
- const size_t qn = weights.at("blk.0.attn_q_norm.weight").get_shape()[0];
+ const size_t qn = weights.at(attention_probe + "attn_q_norm.weight").get_shape()[0];
qk_norm_full = (arch != "gemma4") && (qn != static_cast<size_t>(head_size));
}
n_dense_lead = cfg_i("n_layer_dense_lead");
@@ -208,6 +216,9 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
logit_scale = cfg_f("logit_scale");
attention_scale = cfg_f("attention_scale"); // 0 -> 1/sqrt(head_size)
expert_weights_scale = cfg_f("expert_weights_scale"); // 0 -> 1.0 no-op
+ // llama.cpp's LFM2 MoE loader leaves the routing scale unset.
+ if (arch == "lfm2moe")
+ expert_weights_scale = 0.0f;
// These llama.cpp builders require normalization independently of optional GGUF metadata.
expert_weights_norm = options.normalize_expert_weights.value_or(
arch == "hunyuan-moe" || arch == "minimax-m2" || arch == "qwen3moe" || arch == "qwen35moe" ||
@@ -318,6 +329,8 @@ bool DecoderConfig::layer_is_moe(int il) const {
}
bool DecoderConfig::layer_is_swa(int il) const {
+ if (arch == "lfm2" || arch == "lfm2moe")
+ return has_swa && layer_n_head_kv(il) > 0;
if (!swa_layer_flags.empty()) {
return il < static_cast<int>(swa_layer_flags.size()) && swa_layer_flags[il] != 0;
}
diff --git a/src/frontends/gguf/src/builder/gguf_builder.cpp b/src/frontends/gguf/src/builder/gguf_builder.cpp
index 49a9f8db9b1..ef28f9a888f 100644
--- a/src/frontends/gguf/src/builder/gguf_builder.cpp
+++ b/src/frontends/gguf/src/builder/gguf_builder.cpp
@@ -56,6 +56,9 @@ GraphBuilder load_gguf_builder(const std::string& file, const ArchRegistry& regi
const detail::MetadataStore meta_store{metadata};
const GgufMetadata meta_view(meta_store);
+ if (meta_view.architecture() == "this model cannot be used as LLM, use it via --model-vocoder in TTS examples") {
+ metadata["general.architecture"] = std::string("lfm2.audio_vocoder");
+ }
// Built-in and external definitions share selection, construction and postprocessing.
// Family detection is only a diagnostic fallback; it must not reject a registered family.
diff --git a/src/frontends/gguf/src/op/get_rows.cpp b/src/frontends/gguf/src/op/get_rows.cpp
index 081d80a8493..be72d1a0f1f 100644
--- a/src/frontends/gguf/src/op/get_rows.cpp
+++ b/src/frontends/gguf/src/op/get_rows.cpp
@@ -6,27 +6,33 @@
#include "op_table.hpp"
#include "openvino/core/node.hpp"
#include "openvino/core/node_output.hpp"
+#include "openvino/op/add.hpp"
#include "openvino/op/broadcast.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
#include "openvino/op/gather.hpp"
#include "openvino/op/gather_elements.hpp"
+#include "openvino/op/range.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/squeeze.hpp"
+#include "openvino/op/subtract.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf::op {
OutputVector translate_get_rows(const NodeContext& context) {
- num_inputs_check(context, 2, 2);
+ const bool relative_shift = context.get_attribute<bool>("relative_shift", false);
+ num_inputs_check(context, relative_shift ? 1 : 2, relative_shift ? 1 : 2);
int op_case = context.get_op_case();
Output<Node> res;
auto data = context.get_input(0);
- auto indices = context.get_input(1);
+ ov::Output<ov::Node> indices;
+ if (!relative_shift)
+ indices = context.get_input(1);
// GGML gathers integer rows as I32 and all floating/quantized rows as F32.
const auto type = data.get_element_type() == ov::element::i32 ? ov::element::i32 : ov::element::f32;
const auto convert_rows = [&](ov::Output<Node> rows) {
@@ -36,7 +42,23 @@ OutputVector translate_get_rows(const NodeContext& context) {
return rows;
};
- if (context.get_attribute<bool>("gather_elements", false)) {
+ if (relative_shift) {
+ const auto scalar = [](int64_t value) {
+ return ov::op::v0::Constant::create(ov::element::i64, {}, {value});
+ };
+ auto length = std::make_shared<ov::op::v0::Squeeze>(get_dimensions(data, {2}));
+ auto range = std::make_shared<ov::op::v4::Range>(scalar(0), length, scalar(1), ov::element::i64);
+ auto row =
+ std::make_shared<ov::op::v0::Unsqueeze>(range,
+ ov::op::v0::Constant::create(ov::element::i64, {3}, {0, 1, 3}));
+ auto column =
+ std::make_shared<ov::op::v0::Unsqueeze>(range,
+ ov::op::v0::Constant::create(ov::element::i64, {3}, {0, 1, 2}));
+ indices = std::make_shared<ov::op::v1::Add>(
+ std::make_shared<ov::op::v1::Subtract>(std::make_shared<ov::op::v1::Subtract>(length, scalar(1)), row),
+ column);
+ }
+ if (context.get_attribute<bool>("gather_elements", false) || relative_shift) {
// Select a column independently in each row; singleton index batches broadcast.
auto shape = std::make_shared<ov::op::v0::Concat>(
ov::OutputVector{get_dimensions(data, {0, 1, 2}), get_dimensions(indices, {3})},
diff --git a/src/frontends/gguf/src/op/multimodal.cpp b/src/frontends/gguf/src/op/multimodal.cpp
index 8f8a220ac0d..1beb81f113e 100644
--- a/src/frontends/gguf/src/op/multimodal.cpp
+++ b/src/frontends/gguf/src/op/multimodal.cpp
@@ -12,6 +12,7 @@
#include "openvino/op/floor_mod.hpp"
#include "openvino/op/gather.hpp"
#include "openvino/op/greater.hpp"
+#include "openvino/op/group_conv.hpp"
#include "openvino/op/interpolate.hpp"
#include "openvino/op/less.hpp"
#include "openvino/op/logical_and.hpp"
@@ -137,6 +138,17 @@ OutputVector translate_conv_2d(const NodeContext& context) {
w = std::make_shared<ov::op::v0::Convert>(w, ov::element::f32);
if (x.get_element_type() != ov::element::f32)
x = std::make_shared<ov::op::v0::Convert>(x, ov::element::f32);
+ if (context.get_attribute<bool>("depthwise", false)) {
+ w = std::make_shared<ov::op::v0::Unsqueeze>(w, i64_const({1}));
+ return rename_outputs_with_suffix({std::make_shared<ov::op::v1::GroupConvolution>(
+ x,
+ w,
+ ov::Strides{size_t(p[1]), size_t(p[0])},
+ ov::CoordinateDiff{std::ptrdiff_t(p[3]), std::ptrdiff_t(p[2])},
+ ov::CoordinateDiff{std::ptrdiff_t(p[3]), std::ptrdiff_t(p[2])},
+ ov::Strides{size_t(p[5]), size_t(p[4])})},
+ context.get_name());
+ }
return rename_outputs_with_suffix(
{std::make_shared<ov::op::v1::Convolution>(x,
w,
diff --git a/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
index dc60e399be3..6a19ed7e3e9 100644
--- a/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
@@ -366,7 +366,7 @@ Models adapt_mmproj(const std::shared_ptr<ov::Model>& model,
if (layout == Layout::VISION_ENCODERS) {
projector = model->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"});
OPENVINO_ASSERT(projector == "gemma3" || projector == "gemma4v" || projector == "gemma4uv" ||
- projector == "muse-glimmer" || projector == "qwen3vl_merger",
+ projector == "muse-glimmer" || projector == "qwen3vl_merger" || projector == "lfm2",
"[GGUF] no GenAI vision layout for mmproj projector '",
projector,
"'");
diff --git a/src/frontends/gguf/src/pass/adapt_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
index 601ddb97966..4ea9cf16739 100644
--- a/src/frontends/gguf/src/pass/adapt_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
@@ -248,10 +248,14 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
auto token_len_per_seq = find_parameter(model, "token_len_per_seq");
const bool has_recurrent_states = model->get_rt_info().count(gguf_recurrent_states_key()) != 0;
const auto operations = model->get_ops();
+ const auto architecture = model->get_rt_info().find("gguf_architecture");
+ const bool lfm2 =
+ architecture != model->get_rt_info().end() &&
+ (architecture->second.as<std::string>() == "lfm2" || architecture->second.as<std::string>() == "lfm2moe");
const bool batchable_recurrent =
- has_recurrent_states && std::any_of(operations.begin(), operations.end(), [](const auto& node) {
- return ov::is_type<internal::GatedDeltaNet>(node);
- });
+ has_recurrent_states && (lfm2 || std::any_of(operations.begin(), operations.end(), [](const auto& node) {
+ return ov::is_type<internal::GatedDeltaNet>(node);
+ }));
const bool recurrent_only = !inp_pos && !self_kq_mask && has_recurrent_states;
if (!inp_tokens || (!recurrent_only && !self_kq_mask)) {
return false;
diff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txt
index ada968c59cb..44e0dc117c5 100644
--- a/src/frontends/gguf/tests/CMakeLists.txt
+++ b/src/frontends/gguf/tests/CMakeLists.txt
@@ -45,6 +45,7 @@ set(FRONTEND_SRCS
"${FE_SRC_DIR}/builder/api/metadata.cpp"
"${FE_SRC_DIR}/builder/api/tensor_table.cpp"
"${FE_SRC_DIR}/builder/arch/decoder_builder.cpp"
+ "${FE_SRC_DIR}/builder/arch/lfm2_builder.cpp"
"${FE_SRC_DIR}/builder/arch/dspark_builder.cpp"
"${FE_SRC_DIR}/builder/arch/mamba_builder.cpp"
"${FE_SRC_DIR}/builder/arch/mmproj_builder.cpp"
diff --git a/src/frontends/gguf/tests/gen_arch_accuracy.py b/src/frontends/gguf/tests/gen_arch_accuracy.py
index 7de00be3444..189e18d6295 100644
--- a/src/frontends/gguf/tests/gen_arch_accuracy.py
+++ b/src/frontends/gguf/tests/gen_arch_accuracy.py
@@ -19,6 +19,12 @@ import numpy as np
from mmproj_fixtures import finish, save_npz
CASES = {
+ "lfm2": {},
+ "lfm2-tied": {"architecture": "lfm2", "tied": True},
+ "lfm2-swa": {"architecture": "lfm2", "swa": True, "kernel": 4},
+ "lfm2-attention-first": {"architecture": "lfm2", "attention_first": True, "fused": True},
+ "lfm2moe": {"moe": True, "lead": 1},
+ "lfm2moe-all-experts": {"architecture": "lfm2moe", "moe": True, "sigmoid": True, "expert_scale": 2.5},
"qwen35": {}, "qwen35moe": {},
"qwen35moe-fused": {"architecture": "qwen35moe", "fused_experts": True},
# Real checkpoints quantize attn_gate apart from ssm_beta/ssm_alpha: F16 here selects the
@@ -289,8 +295,72 @@ def write_gemma4_model(path, opts):
finish(w)
+def write_lfm2_model(path, arch, opts):
+ w = gguf.GGUFWriter(path, arch)
+ d, heads, kv, head, ff, vocab = 32, 4, 2, 8, 48, 32
+ kernel = opts.get("kernel", 3)
+ kv_layers = [kv, 0, kv, 0] if opts.get("attention_first") else [0, kv, 0, kv]
+ w.add_context_length(128)
+ w.add_embedding_length(d)
+ w.add_block_count(len(kv_layers))
+ w.add_feed_forward_length(ff)
+ w.add_head_count(heads)
+ w.add_head_count_kv(kv_layers)
+ w.add_key_length(head)
+ w.add_value_length(head)
+ w.add_rope_dimension_count(head)
+ w.add_rope_freq_base(1000000.)
+ w.add_layer_norm_rms_eps(1e-5)
+ w.add_uint32(arch + ".shortconv.l_cache", kernel)
+ w.add_vocab_size(vocab)
+ w.add_tokenizer_model("none")
+ if opts.get("swa"):
+ w.add_sliding_window(2)
+ if opts.get("moe"):
+ w.add_expert_count(4)
+ w.add_expert_used_count(2)
+ w.add_expert_feed_forward_length(ff)
+ w.add_leading_dense_block_count(opts.get("lead", 0))
+ w.add_uint32(arch + ".expert_gating_func", 2 if opts.get("sigmoid") else 1)
+ if opts.get("expert_scale"):
+ w.add_expert_weights_scale(opts["expert_scale"])
+ tensor = tensor_writer(w, np.random.default_rng(20261014))
+ tensor("token_embd.weight", (vocab, d))
+ tensor("token_embd_norm.weight", (d,), True)
+ if not opts.get("tied"):
+ tensor("output.weight", (vocab, d))
+ for layer, layer_kv in enumerate(kv_layers):
+ p = f"blk.{layer}."
+ tensor(p + "attn_norm.weight", (d,), True)
+ tensor(p + "ffn_norm.weight", (d,), True)
+ if layer_kv:
+ if opts.get("fused"):
+ tensor(p + "attn_qkv.weight", ((heads + 2 * kv) * head, d))
+ else:
+ for name, width in (("q", d), ("k", kv * head), ("v", kv * head)):
+ tensor(p + f"attn_{name}.weight", (width, d))
+ for name in ("q", "k"):
+ tensor(p + f"attn_{name}_norm.weight", (head,), True)
+ tensor(p + "attn_output.weight", (d, d))
+ else:
+ tensor(p + "shortconv.in_proj.weight", (3 * d, d))
+ tensor(p + "shortconv.conv.weight", (d, kernel))
+ tensor(p + "shortconv.out_proj.weight", (d, d))
+ if opts.get("moe") and layer >= opts.get("lead", 0):
+ tensor(p + "ffn_gate_inp.weight", (4, d))
+ tensor(p + "exp_probs_b.bias", (4,))
+ for name, shape in (("gate", (4, ff, d)), ("up", (4, ff, d)), ("down", (4, d, ff))):
+ tensor(p + f"ffn_{name}_exps.weight", shape)
+ else:
+ for name, shape in (("gate", (ff, d)), ("up", (ff, d)), ("down", (d, ff))):
+ tensor(p + f"ffn_{name}.weight", shape)
+ finish(w)
+
+
def write_model(path, arch, opts):
arch = opts.get("architecture", arch)
+ if arch in ("lfm2", "lfm2moe"):
+ return write_lfm2_model(path, arch, opts)
if arch == "gemma4":
return write_gemma4_model(path, opts)
if arch in ("qwen35", "qwen35moe"):
diff --git a/src/frontends/gguf/tests/gen_lfm2_speech_accuracy.py b/src/frontends/gguf/tests/gen_lfm2_speech_accuracy.py
new file mode 100644
index 00000000000..d7032a7542c
--- /dev/null
+++ b/src/frontends/gguf/tests/gen_lfm2_speech_accuracy.py
@@ -0,0 +1,142 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""Generate a compact depthformer fixture using the pinned LiquidAI PyTorch reference."""
+import argparse
+import hashlib
+import tempfile
+from pathlib import Path
+import subprocess
+import types
+
+import gguf
+import numpy as np
+import torch
+from transformers import Lfm2Config, Lfm2Model
+from gen_arch_accuracy import write_lfm2_model
+
+from mmproj_fixtures import finish, save_npz
+
+REVISION = "19e65845923a7f136442c95137884ec61eb386aa"
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--liquid-audio", required=True, type=Path)
+ args = parser.parse_args()
+ revision = subprocess.check_output(["git", "-C", str(args.liquid_audio), "rev-parse", "HEAD"], text=True).strip()
+ if revision != REVISION:
+ raise ValueError(f"Expected {REVISION}, got {revision}")
+ source = args.liquid_audio / "src/liquid_audio/model/transformer.py"
+ code = source.read_text().replace("type CacheType =", "CacheType =").replace(
+ "def wrap_activation_checkpoint[T: nn.Module]", "def wrap_activation_checkpoint")
+ module = types.ModuleType("liquid_reference")
+ exec(compile("from __future__ import annotations\n" + code, str(source), "exec"), module.__dict__)
+ torch.manual_seed(612)
+ width, books, vocabulary, language, codec = 16, 8, 2049, 12, 6
+ model = module.RawLMBackbone([
+ module.StandardBlock(module.MHA(width, num_heads=4, gqa_dim=2), ff_dim=24, multiple_of=8)
+ for _ in range(2)], has_embedding=False).eval()
+ projection = torch.nn.Linear(language, width * books)
+ embeddings = [module.SharedEmbedding(width, vocabulary, tie_embedding=False) for _ in range(books)]
+ audio_embedding = torch.nn.Embedding(books * vocabulary, language)
+ codec_embedding = torch.nn.Embedding(books * (vocabulary - 1), codec)
+ for value in list(model.parameters()) + list(projection.parameters()) + [p for e in embeddings for p in e.parameters()] + list(audio_embedding.parameters()) + list(codec_embedding.parameters()):
+ with torch.no_grad():
+ if value.ndim == 1 and value.numel() != width * books:
+ value.copy_(1 + .08 * torch.randn_like(value))
+ else:
+ value.copy_(.08 * torch.randn_like(value))
+ hidden = torch.randn(1, 1, language) * .3
+ depth_codes = torch.randint(0, vocabulary - 1, (1, books), dtype=torch.int32)
+ codes = torch.randint(0, vocabulary - 1, (1, 3, books), dtype=torch.int32)
+ with torch.no_grad():
+ x = projection(hidden).reshape(1, books, width)
+ for i in range(1, books):
+ x[:, i] += embeddings[i - 1](depth_codes[:, i - 1].long())
+ y = model(x)
+ logits = torch.stack([embeddings[i].get_logits(y[:, i]) for i in range(books)], 1)
+ feedback = audio_embedding(codes.long() + torch.arange(books) * vocabulary).sum(2)
+ features = codec_embedding(codes.long() + torch.arange(books) * (vocabulary - 1)).mean(2)
+ temporary = tempfile.TemporaryDirectory()
+ path = Path(temporary.name) / "vocoder.gguf"
+ weights = {"depthformer." + key.replace("operator.bounded_attention.", "operator.attention."): value
+ for key, value in model.state_dict().items()}
+ weights.update({"depth_linear." + key: value for key, value in projection.state_dict().items()})
+ for i, embedding in enumerate(embeddings):
+ weights.update({f"depth_embeddings.{i}." + key: value for key, value in embedding.state_dict().items()})
+ weights["audio_embedding.embedding.weight"] = audio_embedding.weight
+ weights["emb.emb.weight"] = codec_embedding.weight
+ weights["istft.window"] = torch.hann_window(1280)
+ arrays = {"hidden": hidden.numpy().reshape(1, 1, 1, language),
+ "depth_codes": depth_codes.numpy().reshape(1, 1, 1, books),
+ "codes": codes.numpy().reshape(1, 1, 3, books),
+ "logits": logits.numpy(), "feedback": feedback.numpy(), "codec": features.numpy(),
+ "reference_revision": np.frombuffer(REVISION.encode(), np.uint8),
+ "reference_sha256": np.frombuffer(hashlib.sha256(source.read_bytes()).hexdigest().encode(), np.uint8)}
+ for key, architecture in [
+ ("model", "lfm2.audio_vocoder"),
+ ("publisher_model", "this model cannot be used as LLM, use it via --model-vocoder in TTS examples"),
+ ]:
+ writer = gguf.GGUFWriter(path, architecture)
+ writer.add_uint32("depthformer_n_layer", 2)
+ writer.add_uint32("depthformer_n_embd", width)
+ for name, value in weights.items():
+ writer.add_tensor(name, value.detach().numpy())
+ finish(writer)
+ arrays[key] = np.frombuffer(path.read_bytes(), np.uint8)
+ save_npz(Path(__file__).parent / "test_data/lfm2_speech.npz", arrays)
+ detok_path = Path(temporary.name) / "detokenizer.gguf"
+ write_lfm2_model(detok_path, "lfm2", {"tied": True})
+ reader = gguf.GGUFReader(detok_path)
+ weights = {t.name: torch.from_numpy(t.data.copy().reshape(tuple(reversed(t.shape)))) for t in reader.tensors}
+ weights["dense_2.weight"] = torch.randn(1282, 32) * .08
+ weights["dense_2.bias"] = torch.randn(1282) * .08
+ writer = gguf.GGUFWriter(detok_path, "lfm2")
+ for field in reader.fields.values():
+ if field.name.startswith("GGUF.") or field.name == "general.architecture":
+ continue
+ value = field.contents()
+ if isinstance(value, np.ndarray):
+ value = value.tolist()
+ writer.add_key_value(field.name, value, field.types[0], field.types[1] if len(field.types) > 1 else None)
+ writer.add_sliding_window(30)
+ for name, value in weights.items():
+ writer.add_tensor(name, value.numpy())
+ finish(writer)
+ config = Lfm2Config(hidden_size=32, intermediate_size=48, num_hidden_layers=4,
+ num_attention_heads=4, num_key_value_heads=2, vocab_size=32,
+ layer_types=["conv", "full_attention", "conv", "full_attention"],
+ conv_L_cache=3, norm_eps=1e-5, rope_theta=1000000.,
+ block_auto_adjust_ff_dim=False)
+ detok = Lfm2Model(config).eval()
+ state = {"embed_tokens.weight": weights["token_embd.weight"],
+ "embedding_norm.weight": weights["token_embd_norm.weight"]}
+ for i in range(4):
+ p, target = f"blk.{i}.", f"layers.{i}."
+ for a, b in [("attn_norm.weight", "operator_norm.weight"), ("ffn_norm.weight", "ffn_norm.weight"),
+ ("ffn_gate.weight", "feed_forward.w1.weight"), ("ffn_down.weight", "feed_forward.w2.weight"),
+ ("ffn_up.weight", "feed_forward.w3.weight")]:
+ state[target + b] = weights[p + a]
+ if p + "shortconv.conv.weight" in weights:
+ for name in ["in_proj", "out_proj", "conv"]:
+ value = weights[p + "shortconv." + name + ".weight"]
+ state[target + "conv." + name + ".weight"] = value.unsqueeze(1) if name == "conv" else value
+ else:
+ for a, b in [("attn_q", "q_proj"), ("attn_k", "k_proj"), ("attn_v", "v_proj"),
+ ("attn_output", "out_proj"), ("attn_q_norm", "q_layernorm"), ("attn_k_norm", "k_layernorm")]:
+ state[target + "self_attn." + b + ".weight"] = weights[p + a + ".weight"]
+ detok.load_state_dict(state)
+ embeds = torch.randn(1, 37, 32) * .3
+ positions = torch.arange(37)
+ mask = ((positions - positions[:, None]) <= 0) & ((positions - positions[:, None]) > -30)
+ with torch.no_grad():
+ hidden = detok(inputs_embeds=embeds, attention_mask=mask[None, None], use_cache=False).last_hidden_state
+ spectral = torch.nn.functional.linear(hidden, weights["dense_2.weight"], weights["dense_2.bias"])
+ save_npz(Path(__file__).parent / "test_data/lfm2_detokenizer.npz",
+ {"model": np.frombuffer(detok_path.read_bytes(), np.uint8),
+ "embeds": embeds.numpy(), "spectral": spectral.numpy()})
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/frontends/gguf/tests/gen_mmproj_accuracy.py b/src/frontends/gguf/tests/gen_mmproj_accuracy.py
index e18610f54ff..46e8dcbb60f 100644
--- a/src/frontends/gguf/tests/gen_mmproj_accuracy.py
+++ b/src/frontends/gguf/tests/gen_mmproj_accuracy.py
@@ -18,7 +18,7 @@ from pathlib import Path
import gguf
import numpy as np
-from mmproj_fixtures import TensorWriter, finish, merge_window_order, muse_glimmer_indices, save_npz, split_variants
+from mmproj_fixtures import TensorWriter, finish, merge_window_order, muse_glimmer_indices, save_npz, split_variants, lfm2_audio_positions
SINGLE_GRID = ("gemma3", "gemma3_fused", "gemma3_legacy", "idefics3", "janus_pro", "mlp", "mlp_norm", "mlp_feature",
"qwen2a", "ultravox", "voxtral", "musicflamingo", "meralion", "glma", "qwen2vl_merger",
@@ -26,7 +26,7 @@ SINGLE_GRID = ("gemma3", "gemma3_fused", "gemma3_legacy", "idefics3", "janus_pro
"voxtral_odd", "resampler", "resampler_v2", "resampler_v4")
# Single-grid models rerun here on two grids with different token counts.
REGRIDDED = ("qwen2.5vl_merger_grids", "resampler_grids")
-TWO_GRID = ("muse-glimmer", "pixtral", "pixtral_merge", "phi4", "gemma4v", "gemma4uv", "gemma4uv_low_contrast",
+TWO_GRID = ("muse-glimmer", "pixtral", "pixtral_merge", "phi4", "lfm2", "lfm2_no_norm", "lfm2a", "gemma4v", "gemma4uv", "gemma4uv_low_contrast",
"gemma4ua", "gemma4v_one_sided", "minicpmv4_6", "gemma4a", "deepseekocr", "deepseekocr2",
"deepseekocr_resize", "deepseekocr_overview", "deepseekocr2_overview", *REGRIDDED)
@@ -330,6 +330,47 @@ def write_muse_model(path):
def write_grid_model(path, family):
+ if family == "lfm2a":
+ w = gguf.GGUFWriter(path, "clip")
+ t = TensorWriter(w, np.random.default_rng(2718))
+ width, hidden, output, channels = 16, 24, 12, 4
+ w.add_bool("clip.has_audio_encoder", True)
+ w.add_string("clip.projector_type", family)
+ for name, value in {"embedding_length": width, "feed_forward_length": hidden,
+ "block_count": 2, "projection_dim": output, "attention.head_count": 2,
+ "num_mel_bins": 8}.items():
+ w.add_uint32("clip.audio." + name, value)
+ w.add_float32("clip.audio.attention.layer_norm_epsilon", 1e-5)
+ t.tensor("a.position_embd.weight", (256, output))
+ for i in (0, 2, 3, 5, 6):
+ t.tensor(f"a.conv1d.{i}.weight", (channels, 1 if i in (0, 2, 5) else channels,
+ 3 if i in (0, 2, 5) else 1,
+ 3 if i in (0, 2, 5) else 1))
+ t.tensor(f"a.conv1d.{i}.bias", (channels, 1, 1))
+ t.linear("a.pre_encode.out", channels, width)
+ for i in range(2):
+ p = f"a.blk.{i}."
+ for name in ("ffn_norm", "ffn_norm_1", "ln1", "ln2", "norm_conv", "conv_norm"):
+ t.norm(p + name, width)
+ for name in ("attn_q", "attn_k", "attn_v", "attn_out", "conv_pw2"):
+ t.linear(p + name, width, width)
+ t.linear(p + "linear_pos", 512, width, False)
+ for name in ("pos_bias_u", "pos_bias_v"):
+ t.tensor(p + name, (2, width // 2))
+ for suffix in ("", "_1"):
+ t.linear(p + "ffn_up" + suffix, width, hidden)
+ t.linear(p + "ffn_down" + suffix, hidden, width)
+ t.linear(p + "conv_pw1", width, width * 2)
+ t.tensor(p + "conv_dw.weight", (width, 9))
+ t.tensor(p + "conv_dw.bias", (width,))
+ t.norm("mm.a.mlp.0", width)
+ t.linear("mm.a.mlp.1", width, hidden)
+ t.linear("mm.a.mlp.3", hidden, output)
+ finish(w)
+ return output
+ lfm2_norm = family != "lfm2_no_norm"
+ if family == "lfm2_no_norm":
+ family = "lfm2"
if family == "muse-glimmer":
return write_muse_model(path)
family, variants = split_variants(family, *VARIANTS)
@@ -449,9 +490,11 @@ def write_grid_model(path, family):
if family == "gemma4v":
tensor("v.std_bias", (width,))
tensor("v.std_scale", (width,), True)
- elif family == "phi4":
+ elif family in {"phi4", "lfm2"}:
tensor("v.position_embd.weight", (16, width))
- linear("mm.0", width, hidden)
+ if family == "lfm2" and lfm2_norm:
+ norm("mm.input_norm", width * 4)
+ linear("mm.1" if family == "lfm2" else "mm.0", width * 4 if family == "lfm2" else width, hidden)
linear("mm.2", hidden, output)
elif family.startswith("pixtral"):
tensor("v.token_embd.img_break", (output,))
@@ -503,6 +546,14 @@ def write_grid_model(path, family):
def grid_inputs(family, width, height):
+ if family == "lfm2a":
+ raw = np.random.default_rng(42).normal(.1, .4, (height, width)).astype(np.float32)
+ return raw, {"features": raw.reshape(1, 1, height, width),
+ "pos_emb": lfm2_audio_positions(width, 512)}
+ if family in {"lfm2", "lfm2_no_norm"}:
+ raw = np.random.default_rng(42).normal(.1, .4, (height, width, 3)).astype(np.float32)
+ return raw, {"pixel_values": raw.transpose(2, 0, 1)[None],
+ "merge_indices": np.array(merge_window_order(height // 2, width // 2), np.int32).reshape(1, 1, 1, -1)}
if family == "muse-glimmer":
raw = np.random.default_rng(42).uniform(-1, 1, (height, width, 3)).astype(np.float32)
return raw, {"pixel_values": raw.transpose(2, 0, 1)[None], **muse_glimmer_indices(height // 2, width // 2, 3)}
@@ -597,6 +648,7 @@ def two_grid_fixture(oracle, family):
"deepseekocr_overview": [(256, 256), (256, 256)],
"deepseekocr": [(256, 256), (256, 512)],
"gemma4a": [(49, 8), (101, 8)],
+ "lfm2a": [(49, 8), (101, 8)],
"gemma4ua": [(3, 640), (5, 640)],
"gemma4uv_low_contrast": [(96, 48), (48, 144)],
"muse-glimmer": [(12, 8), (4, 4)],
diff --git a/src/frontends/gguf/tests/mmproj_fixtures.py b/src/frontends/gguf/tests/mmproj_fixtures.py
index 1eb6fe91276..c87a2ead941 100644
--- a/src/frontends/gguf/tests/mmproj_fixtures.py
+++ b/src/frontends/gguf/tests/mmproj_fixtures.py
@@ -102,10 +102,20 @@ def muse_glimmer_indices(height, width, window, merge=2):
WHISPER_AUDIO = {"qwen2a", "ultravox", "voxtral", "musicflamingo", "meralion", "glma"}
FIXED_VISION = {"gemma3", "idefics3", "internvl", "janus_pro", "mlp"}
-DYNAMIC_VISION = {"gemma4v", "gemma4uv", "pixtral", "qwen2vl_merger", "qwen2.5vl_merger", "qwen3vl_merger",
+DYNAMIC_VISION = {"lfm2", "gemma4v", "gemma4uv", "pixtral", "qwen2vl_merger", "qwen2.5vl_merger", "qwen3vl_merger",
"muse-glimmer"}
+def lfm2_audio_positions(frames, width):
+ tokens = (frames + 7) // 8
+ positions = tokens - 1 - np.arange(2 * tokens - 1)
+ frequency = np.exp(-np.log(10000.) * np.arange(0, width, 2) / width)
+ angle = (positions[:, None] * frequency).astype(np.float32)
+ result = np.empty((2 * tokens - 1, width), np.float32)
+ result[:, 0::2], result[:, 1::2] = np.sin(angle), np.cos(angle)
+ return result.reshape(1, 1, -1, width)
+
+
def vision_patch(metadata):
"""Pixels per encoder patch; unified Gemma4 patches span scale_factor reference patches."""
patch = int(metadata["clip.vision.patch_size"])
@@ -117,7 +127,7 @@ def vision_patch(metadata):
def grid_unit(metadata, modality):
"""Image side granularity (pixels) or audio frame granularity a checkpoint accepts."""
if modality == "audio":
- return 1 if metadata["audio.projector"] in {"gemma4a", "gemma4ua"} else 32
+ return 1 if metadata["audio.projector"] in {"gemma4a", "gemma4ua", "lfm2a"} else 32
return vision_patch(metadata) * int(metadata.get("vision.merge", 1))
@@ -135,6 +145,9 @@ def checkpoint_inputs(metadata, modality, width, height=None, seed=42):
return {"audio.waveform_frames": raw.T.reshape(1, 1, width, 640)}, raw, width, 640
mel = int(metadata["clip.audio.num_mel_bins"])
raw = rng.normal(0, .4, (mel, width)).astype(np.float32)
+ if projector == "lfm2a":
+ return {"audio.features": raw.reshape(1, 1, mel, width),
+ "audio.pos_emb": lfm2_audio_positions(width, 512)}, raw, width, mel
if projector == "gemma4a":
return {"audio.features": raw.reshape(1, 1, mel, width)}, raw, width, mel
if projector not in WHISPER_AUDIO:
@@ -153,7 +166,9 @@ def checkpoint_inputs(metadata, modality, width, height=None, seed=42):
patch = vision_patch(metadata)
gh, gw = height // patch, width // patch
index = lambda values: np.asarray(values, np.int32).reshape(1, 1, 1, -1)
- if projector in {"gemma4v", "gemma4uv", "pixtral"}:
+ if projector == "lfm2":
+ feeds["vision.merge_indices"] = index(merge_window_order(gh, gw, int(metadata["vision.merge"])))
+ elif projector in {"gemma4v", "gemma4uv", "pixtral"}:
rows, cols = np.indices((gh, gw))
feeds.update({"vision.position_x": index(cols), "vision.position_y": index(rows)})
elif projector == "muse-glimmer":
diff --git a/src/frontends/gguf/tests/test_arch_accuracy.cpp b/src/frontends/gguf/tests/test_arch_accuracy.cpp
index 208b0831df8..dd547f73d9e 100644
--- a/src/frontends/gguf/tests/test_arch_accuracy.cpp
+++ b/src/frontends/gguf/tests/test_arch_accuracy.cpp
@@ -33,6 +33,7 @@
#include "openvino/op/constant.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/paged_attention.hpp"
+#include "openvino/op/paged_causal_conv1d.hpp"
#include "openvino/op/paged_gated_delta_net.hpp"
#include "openvino/op/read_value.hpp"
#include "openvino/op/unsqueeze.hpp"
@@ -532,6 +533,30 @@ void check_batched_decode(const std::shared_ptr<ov::Model>& model) {
compare(infer(batch, 2, {5, 4}, {0, 1, 1, 1, 1, 1, 1, 1}, {2, 3}, {1, 0}), b, a);
}
+TEST(GGUFMultimodalBackboneAdaptation, Lfm2SupportsBatchesAndBeamReordering) {
+ for (const auto* family : {"lfm2", "lfm2-attention-first", "lfm2moe"}) {
+ SCOPED_TRACE(family);
+ auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/" + family + ".npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ ov::frontend::gguf::FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());
+ auto model = frontend.convert(frontend.load(temporary.path));
+ check_batched_decode(model);
+ ov::pass::Manager manager;
+ manager.register_pass<ov::pass::SDPAToPagedAttention>();
+ ASSERT_NO_THROW(manager.run_passes(model));
+ model->reshape({{"input_ids", {5}}, {"position_ids", {5}}});
+ size_t attention = 0, convolution = 0;
+ for (const auto& node : model->get_ops()) {
+ attention += ov::is_type<ov::op::PagedAttentionExtension>(node);
+ convolution += ov::is_type<ov::op::internal::PagedCausalConv1D>(node);
+ }
+ EXPECT_EQ(attention, 2);
+ EXPECT_EQ(convolution, 2);
+ EXPECT_TRUE(model->get_sinks().empty());
+ }
+}
+
TEST(GGUFMultimodalBackboneAdaptation, QwenAndGemmaSupportBatchesAndPagedAttention) {
for (const auto* family :
{"qwen35", "bonsai2-hadamard", "qwen35moe", "qwen35moe-fused", "gemma4-mqa", "gemma4-moe", "gemma4-ple"}) {
@@ -581,8 +606,8 @@ TEST(GGUFMultimodalBackboneAdaptation, QwenAndGemmaSupportBatchesAndPagedAttenti
// Gemma3/Gemma4 scale token lookups only, as in llama.cpp, so the scale belongs to the embedding
// model and injected media embeddings reach the decoder unscaled.
-TEST(GGUFMultimodalBackboneAdaptation, GemmaEmbeddingModelOwnsTokenScaling) {
- for (const auto* family : {"gemma3", "gemma4-mqa", "gemma4-ple"}) {
+TEST(GGUFMultimodalBackboneAdaptation, EmbeddingModelPreservesTokenScaling) {
+ for (const auto* family : {"gemma3", "gemma4-mqa", "gemma4-ple", "lfm2", "lfm2moe"}) {
SCOPED_TRACE(family);
auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/" + family + ".npz");
const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
@@ -614,7 +639,7 @@ TEST(GGUFMultimodalBackboneAdaptation, GemmaEmbeddingModelOwnsTokenScaling) {
return constant && ov::shape_size(constant->get_shape()) == 1 &&
std::abs(constant->cast_vector<float>()[0] - std::sqrt(float(width))) < 1e-4f;
});
- EXPECT_TRUE(scaled) << "embedding model does not apply sqrt(n_embd)";
+ EXPECT_EQ(scaled, std::string(family).find("lfm2") != 0);
ov::Core core;
const auto compile = [&](const std::shared_ptr<ov::Model>& model) {
@@ -763,6 +788,32 @@ TEST(GGUFMultimodalBackboneAdaptation, MakeStatefulFindsCachesBehindReversedGrou
}
}
+TEST(GGUFMultimodalBackboneAdaptation, Lfm2RejectsMissingOrInvalidConvolutionCache) {
+ auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/lfm2.npz");
+ const auto& model = ov_gguf_test::npz_array(arrays, "model");
+ const std::string key = "lfm2.shortconv.l_cache";
+ for (const int cache : {-1, 0, 1}) {
+ SCOPED_TRACE(cache);
+ std::vector<uint8_t> bytes(model.data<uint8_t>(), model.data<uint8_t>() + model.num_vals);
+ const auto at = std::search(bytes.begin(), bytes.end(), key.begin(), key.end());
+ ASSERT_NE(at, bytes.end());
+ if (cache < 0) {
+ at[key.size() - 1] = 'X';
+ } else {
+ const auto value = at + key.size() + sizeof(uint32_t);
+ std::fill(value, value + sizeof(uint32_t), 0);
+ *value = static_cast<uint8_t>(cache);
+ }
+ cnpy::NpyArray patched({bytes.size()}, sizeof(uint8_t), false);
+ std::copy(bytes.begin(), bytes.end(), patched.data<uint8_t>());
+ const ov_gguf_test::TemporaryGguf temporary(patched);
+ ov::frontend::gguf::FrontEnd frontend;
+ OV_EXPECT_THROW(frontend.convert(frontend.load(temporary.path)),
+ ov::Exception,
+ testing::HasSubstr("shortconv.l_cache"));
+ }
+}
+
TEST(GGUFEmbeddingAccuracy, TokenEmbeddingsAndPoolingMatchLlamaCPU) {
for (const auto* family :
{"llama-embed", "llama-embed-noncausal", "llama-embed-mean", "llama-embed-cls", "llama-embed-last"}) {
@@ -881,7 +932,9 @@ TEST(GGUFEmbeddingAccuracy, RealCheckpointTokenEmbeddingsMatchLlamaCPU) {
TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
const char* override_dir = std::getenv("OV_GGUF_ACCURACY_DATA");
- const bool mamba = std::string(GetParam()).find("mamba2") == 0 || std::string(GetParam()) == "nemotron_h";
+ const bool mamba = std::string(GetParam()).find("mamba2") == 0 || std::string(GetParam()) == "nemotron_h" ||
+ std::string(GetParam()).find("lfm2") == 0;
+ const bool lfm2 = std::string(GetParam()).find("lfm2") == 0;
const auto directory = override_dir ? std::filesystem::path(override_dir)
: std::filesystem::path(ov_gguf_test::test_data_dir()) / "arch_accuracy";
ASSERT_TRUE(std::filesystem::exists(directory)) << "Missing architecture reference data: " << directory;
@@ -933,7 +986,7 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
fe.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());
auto model = fe.convert(fe.load(model_path));
if (mamba) {
- EXPECT_EQ(model->input("input_ids").get_partial_shape(), (ov::PartialShape{1, -1}));
+ EXPECT_EQ(model->input("input_ids").get_partial_shape(), (ov::PartialShape{lfm2 ? -1 : 1, -1}));
EXPECT_NO_THROW(model->input("beam_idx"));
}
ov::Core core;
@@ -1020,6 +1073,12 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
INSTANTIATE_TEST_SUITE_P(Architectures,
GGUFArchitectureAccuracy,
::testing::Values("qwen35",
+ "lfm2",
+ "lfm2-tied",
+ "lfm2-swa",
+ "lfm2-attention-first",
+ "lfm2moe",
+ "lfm2moe-all-experts",
"bonsai2-hadamard",
"qwen35-mixed",
"qwen35moe",
@@ -1066,3 +1125,81 @@ INSTANTIATE_TEST_SUITE_P(Architectures,
return name;
});
} // namespace
+
+class GGUFLFM2VocoderAccuracy : public ::testing::TestWithParam<const char*> {};
+
+TEST_P(GGUFLFM2VocoderAccuracy, DepthformerFeedbackAndCodecMatchLiquidReference) {
+ auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/lfm2_speech.npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, GetParam()));
+ ov::frontend::gguf::FrontEnd frontend;
+ auto model = frontend.convert(frontend.load(temporary.path));
+ EXPECT_EQ(model->get_rt_info().at("gguf_architecture").as<std::string>(), "lfm2.audio_vocoder");
+ auto request = ov::Core{}
+ .compile_model(model,
+ "CPU",
+ ov::hint::inference_precision(ov::element::f32),
+ ov::hint::dynamic_quantization_group_size(0))
+ .create_infer_request();
+ for (const auto& [input, reference] :
+ std::vector<std::pair<std::string, std::string>>{{"audio.hidden_states", "hidden"},
+ {"audio.depth_codes", "depth_codes"},
+ {"audio.codes", "codes"}}) {
+ const auto& array = ov_gguf_test::npz_array(arrays, reference);
+ ov::Tensor tensor(reference == "hidden" ? ov::element::f32 : ov::element::i32, array.shape);
+ std::memcpy(tensor.data(), array.data<char>(), tensor.get_byte_size());
+ request.set_tensor(input, tensor);
+ }
+ request.infer();
+ for (const auto& [output, reference] :
+ std::vector<std::pair<std::string, std::string>>{{"audio.depth_logits", "logits"},
+ {"audio.feedback", "feedback"},
+ {"audio.codec_features", "codec"}}) {
+ const auto actual = request.get_tensor(output);
+ const auto& expected = ov_gguf_test::npz_array(arrays, reference);
+ ASSERT_EQ(actual.get_size(), expected.num_vals) << output;
+ ov_gguf_test::expect_nmse_below(
+ ov_gguf_test::nmse(actual.data<const float>(), expected.data<float>(), actual.get_size()),
+ 1e-5);
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(ArchitectureNames, GGUFLFM2VocoderAccuracy, ::testing::Values("model", "publisher_model"));
+
+TEST(GGUFLFM2SpeechAccuracy, DetokenizerPreservesAllFramesAcrossSlidingWindow) {
+ auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/lfm2_detokenizer.npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ ov::frontend::gguf::FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>(
+ ov::frontend::gguf::GenAIExtension::InputMode::EMBEDS_TO_LOGITS));
+ auto model = frontend.convert(frontend.load(temporary.path));
+ auto request = ov::Core{}
+ .compile_model(model,
+ "CPU",
+ ov::hint::inference_precision(ov::element::f32),
+ ov::hint::dynamic_quantization_group_size(0),
+ ov::hint::kv_cache_precision(ov::element::f32))
+ .create_infer_request();
+ const auto& source = ov_gguf_test::npz_array(arrays, "embeds");
+ for (size_t frames : {18, 37, 18}) {
+ SCOPED_TRACE(frames);
+ request.reset_state();
+ ov::Tensor embeds(ov::element::f32, {1, frames, 32}), mask(ov::element::i64, {1, frames}),
+ positions(ov::element::i64, {1, frames}), beam(ov::element::i32, {1});
+ std::memcpy(embeds.data(), source.data<char>(), embeds.get_byte_size());
+ std::fill_n(mask.data<int64_t>(), frames, 1);
+ for (size_t i = 0; i < frames; ++i)
+ positions.data<int64_t>()[i] = i;
+ beam.data<int32_t>()[0] = 0;
+ request.set_tensor("inputs_embeds", embeds);
+ request.set_tensor("attention_mask", mask);
+ request.set_tensor("position_ids", positions);
+ request.set_tensor("beam_idx", beam);
+ request.infer();
+ const auto actual = request.get_tensor("logits");
+ ASSERT_EQ(actual.get_shape(), (ov::Shape{1, frames, 1282}));
+ ov_gguf_test::expect_nmse_below(ov_gguf_test::nmse(actual.data<const float>(),
+ ov_gguf_test::npz_array(arrays, "spectral").data<float>(),
+ actual.get_size()),
+ 1e-5);
+ }
+}
diff --git a/src/frontends/gguf/tests/test_arch_conversion.cpp b/src/frontends/gguf/tests/test_arch_conversion.cpp
index f03452ef9ed..8f4a4afc7ec 100644
--- a/src/frontends/gguf/tests/test_arch_conversion.cpp
+++ b/src/frontends/gguf/tests/test_arch_conversion.cpp
@@ -187,6 +187,7 @@ const std::map<std::string, Fingerprint>& fingerprints() {
{"gemma2-dense.gguf.hdr", {415, 11}}, {"glm4moe-moe.gguf.hdr", {501, 10}},
{"gpt-oss-moe.gguf.hdr", {608, 11}}, {"hunyuan-dense-dense.gguf.hdr", {414, 10}},
{"hunyuan-moe-moe.gguf.hdr", {600, 10}}, {"llama-dense.gguf.hdr", {398, 10}},
+ {"lfm2-dense.gguf.hdr", {290, 9}}, {"lfm2moe-moe.gguf.hdr", {373, 8}},
{"llama-moe.gguf.hdr", {542, 10}}, {"maincoder-dense.gguf.hdr", {430, 10}},
{"minicpm-dense.gguf.hdr", {396, 10}}, {"minicpm-moe.gguf.hdr", {540, 10}},
{"minimax-m2-moe.gguf.hdr", {582, 10}}, {"mistral3-dense.gguf.hdr", {398, 10}},
diff --git a/src/frontends/gguf/tests/test_builder_api.cpp b/src/frontends/gguf/tests/test_builder_api.cpp
index f99cc5999c4..1b6943c8573 100644
--- a/src/frontends/gguf/tests/test_builder_api.cpp
+++ b/src/frontends/gguf/tests/test_builder_api.cpp
@@ -362,6 +362,30 @@ TEST(GGUFArchitectureRegistry, SupportedNamesTrackReplacementAndDeduplicateHandl
EXPECT_EQ(registry.describe_supported(), "other");
}
+TEST(GGUFArchitectureRegistry, Lfm2AudioVocoderListsOnlyCanonicalName) {
+ ArchRegistry registry;
+ EXPECT_EQ(registry.supported_archs().count("lfm2.audio_vocoder"), 1);
+ Environment env;
+ const std::string publisher_name = "this model cannot be used as LLM, use it via --model-vocoder in TTS examples";
+ EXPECT_EQ(registry.supported_archs().count(publisher_name), 0);
+ EXPECT_EQ(registry.describe_supported().find(publisher_name), std::string::npos);
+ env.metadata["general.architecture"] = std::string("lfm2.audio_vocoder");
+ EXPECT_FALSE(registry.find(env.context.metadata));
+ env.integer("depthformer_n_layer", 2);
+ EXPECT_FALSE(registry.find(env.context.metadata));
+ env.integer("depthformer_n_embd", 16);
+ const auto definition = registry.find(env.context.metadata);
+ ASSERT_TRUE(definition);
+ EXPECT_EQ(definition->architecture, "lfm2.audio_vocoder");
+ EXPECT_TRUE(definition->factory);
+
+ auto replacement = *registry.find(env.context.metadata);
+ EXPECT_EQ(replacement.id, "lfm2.audio_vocoder");
+ registry.add_extension(std::make_shared<ArchitectureExtension>(replacement, RegistrationMode::Replace));
+ EXPECT_NO_THROW(registry.find(env.context.metadata));
+ ASSERT_TRUE(registry.find(env.context.metadata));
+}
+
TEST(GGUFArchitectureRegistry, DisjointHandlersForTheSameArchitectureCoexist) {
Environment env;
env.integer("modality", 1);
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/README.md b/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
index 6932bded50a..03d5f9a97af 100644
--- a/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
+++ b/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
@@ -101,3 +101,10 @@ Use `OV_GGUF_Q4_K_ZP_F16=1` for Q4_K accuracy comparisons.
For the embedding checkpoint, put `llama-embed.gguf` and the output of
`embedding_oracle llama-embed.gguf llama-embed.bin "<prompt>"` in a directory and set
`OV_GGUF_EMBEDDING_DATA` to it; `GGUFEmbeddingAccuracy` then compares per-token embeddings.
+
+LFM2 fixtures (`lfm2`, `lfm2-tied`, `lfm2-swa`, `lfm2-attention-first`, `lfm2moe`,
+`lfm2moe-all-experts`) use the decoder oracle revision `03fa73cb27f5c251b9528489b18d303b1366aca4`
+and random seed 20261014. They cover four hybrid layers, four query/two KV heads,
+three/four-tap convolution caches, a two-token attention window, dense leading layers,
+selection bias and normalized softmax/sigmoid expert weights. The sigmoid case includes
+expert-scale metadata that llama.cpp's LFM2 MoE loader ignores.
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2-attention-first.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2-attention-first.npz
new file mode 100644
index 00000000000..b002e2cc3f1
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2-attention-first.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2-swa.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2-swa.npz
new file mode 100644
index 00000000000..70d3b180668
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2-swa.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2-tied.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2-tied.npz
new file mode 100644
index 00000000000..6329b2febc3
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2-tied.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2.npz
new file mode 100644
index 00000000000..074070670af
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2moe-all-experts.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2moe-all-experts.npz
new file mode 100644
index 00000000000..fb93ed7e2cd
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2moe-all-experts.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2moe.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2moe.npz
new file mode 100644
index 00000000000..bc8d5377129
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm2moe.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt b/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt
index 4763d912452..e6c2545c0f0 100644
--- a/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt
+++ b/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt
@@ -60,8 +60,8 @@ jais-dense.gguf.hdr 4745856 reject
jais2-dense.gguf.hdr 3956480 convert
jamba-dense.gguf.hdr 6061856 reject
kimi-linear-moe.gguf.hdr 2833984 reject
-lfm2-dense.gguf.hdr 4731520 reject
-lfm2moe-moe.gguf.hdr 5913248 reject
+lfm2-dense.gguf.hdr 4731520 convert
+lfm2moe-moe.gguf.hdr 5913248 convert
llada-dense.gguf.hdr 4735104 reject
llada-moe-moe.gguf.hdr 7096192 reject
llama-dense.gguf.hdr 4741248 convert
diff --git a/src/frontends/gguf/tests/test_data/lfm2_detokenizer.npz b/src/frontends/gguf/tests/test_data/lfm2_detokenizer.npz
new file mode 100644
index 00000000000..fe7dd5e571a
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/lfm2_detokenizer.npz differ
diff --git a/src/frontends/gguf/tests/test_data/lfm2_speech.md b/src/frontends/gguf/tests/test_data/lfm2_speech.md
new file mode 100644
index 00000000000..5aa948646a9
--- /dev/null
+++ b/src/frontends/gguf/tests/test_data/lfm2_speech.md
@@ -0,0 +1,14 @@
+# LFM2.5 speech references
+
+`lfm2_speech.npz` contains a two-layer random F32 depthformer with unequal Q/KV
+heads, eight codebooks, full per-book logits, summed language feedback and averaged
+codec features. `lfm2_detokenizer.npz` contains a mixed convolution/attention LFM2
+detokenizer with a 1282-channel spectral head and a 30-token sliding window.
+The test executes its GenAI-adapted input-embeddings path at 18/37/18 frames.
+
+Regenerate using `gen_lfm2_speech_accuracy.py --liquid-audio <checkout>`, with
+`PYTHONPATH=<llama.cpp>/gguf-py`, NumPy, PyTorch and Transformers installed. The
+LiquidAI checkout must be revision `19e65845923a7f136442c95137884ec61eb386aa`.
+The generator runs the publisher transformer and Transformers Lfm2Model; OpenVINO
+does not generate expected outputs. Python 3.12 type syntax is adapted for Python 3.10.
+These are represented F32 fixtures, separate from quantized checkpoint comparisons.
diff --git a/src/frontends/gguf/tests/test_data/lfm2_speech.npz b/src/frontends/gguf/tests/test_data/lfm2_speech.npz
new file mode 100644
index 00000000000..38d30f8cf6c
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/lfm2_speech.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md b/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md
index df485fb5993..034a55564ea 100644
--- a/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md
+++ b/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md
@@ -58,3 +58,11 @@ shared by the generator and the model hub tests.
See [testing](../../../docs/testing.md#real-checkpoints) for pytest commands, dependencies,
oracle caches, and local-file lists, and [coverage limits](../../../docs/mmproj.md#validation-coverage)
for checkpoint tolerance overrides and skipped cases.
+
+`lfm2` and `lfm2_no_norm` use the same pinned oracle revision above and the two-grid
+generator seed 2718. They cover SigLIP, resized positions, spatial unshuffle and the
+optional input LayerNorm at 16x8 and 8x24 pixels, through both native and embedding-adapted IO.
+
+`lfm2a` uses the same pinned llama.cpp CPU oracle, with 49 and 101 feature frames.
+It exercises depthwise subsampling, relative attention shift and temporal convolution.
+The dynamic test returns to the first shape to check request reuse.
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/lfm2.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/lfm2.npz
new file mode 100644
index 00000000000..28624774a9b
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/lfm2.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/lfm2_no_norm.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/lfm2_no_norm.npz
new file mode 100644
index 00000000000..fea7d193185
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/lfm2_no_norm.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/lfm2a.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/lfm2a.npz
new file mode 100644
index 00000000000..3de2bd9ddb5
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/lfm2a.npz differ
diff --git a/src/frontends/gguf/tests/test_mmproj.cpp b/src/frontends/gguf/tests/test_mmproj.cpp
index d15b0c1f28d..5421885b414 100644
--- a/src/frontends/gguf/tests/test_mmproj.cpp
+++ b/src/frontends/gguf/tests/test_mmproj.cpp
@@ -723,6 +723,9 @@ INSTANTIATE_TEST_SUITE_P(Reference,
"pixtral",
"pixtral_merge",
"phi4",
+ "lfm2",
+ "lfm2_no_norm",
+ "lfm2a",
"gemma4v",
"gemma4v_one_sided",
"gemma4uv",
@@ -817,7 +820,11 @@ TEST_P(GGUFMMProjGenAIVisionLayout, MatchesSourceGraph) {
return image.data<const float>()[((frame * 3 + channel) * height + row) * width + col];
};
std::vector<ov::Tensor> actual;
- if (projector == "gemma3") {
+ if (projector == "lfm2") {
+ actual =
+ infer(models.at("vision_embeddings"),
+ {{"pixel_values", image}, {"merge_indices", tensor(step + "merge_indices", ov::element::i32)}});
+ } else if (projector == "gemma3") {
actual = infer(models.at("vision_embeddings"), {{"pixel_values", image}});
} else if (projector == "gemma4v" || projector == "gemma4uv") {
const size_t padded = count + 3, dim = patch * patch * 3;
@@ -939,8 +946,14 @@ TEST_P(GGUFMMProjGenAIVisionLayout, MatchesSourceGraph) {
}
}
-INSTANTIATE_TEST_SUITE_P(
- Reference,
- GGUFMMProjGenAIVisionLayout,
- ::testing::Values("gemma3", "gemma4v", "gemma4v_one_sided", "gemma4uv", "muse-glimmer", "qwen3vl_merger"));
+INSTANTIATE_TEST_SUITE_P(Reference,
+ GGUFMMProjGenAIVisionLayout,
+ ::testing::Values("gemma3",
+ "gemma4v",
+ "gemma4v_one_sided",
+ "gemma4uv",
+ "muse-glimmer",
+ "qwen3vl_merger",
+ "lfm2",
+ "lfm2_no_norm"));
} // namespace
diff --git a/tests/model_hub_tests/gguf/gguf_mmproj_nightly b/tests/model_hub_tests/gguf/gguf_mmproj_nightly
index 7af30978a28..86be1d93139 100644
--- a/tests/model_hub_tests/gguf/gguf_mmproj_nightly
+++ b/tests/model_hub_tests/gguf/gguf_mmproj_nightly
@@ -7,6 +7,8 @@ gemma4v+gemma4a,unsloth/gemma-4-E2B-it-GGUF,mmproj-F16.gguf
ultravox,ggml-org/ultravox-v0_5-llama-3_2-1b-GGUF,mmproj-ultravox-v0_5-llama-3_2-1b-f16.gguf
qwen2.5vl_merger+qwen2a,ggml-org/Qwen2.5-Omni-3B-GGUF,mmproj-Qwen2.5-Omni-3B-Q8_0.gguf
deepseekocr,ggml-org/deepseek-ocr-GGUF,mmproj-DeepSeek-OCR-Q8_0.gguf,skip,the test has no input contract for SAM tiles and views yet
+
+lfm2,LiquidAI/LFM2-VL-450M-GGUF,mmproj-LFM2-VL-450M-Q8_0.gguf
qwen3vl_merger,prism-ml/Bonsai-27B-gguf,Bonsai-27B-mmproj-BF16.gguf
qwen3vl_merger,prism-ml/Bonsai-27B-gguf,Bonsai-27B-mmproj-Q8_0.gguf
qwen3vl_merger,prism-ml/Ternary-Bonsai-27B-gguf,Ternary-Bonsai-27B-mmproj-BF16.gguf
diff --git a/tests/model_hub_tests/gguf/gguf_models_nightly b/tests/model_hub_tests/gguf/gguf_models_nightly
index 159a0692227..b1391525211 100644
--- a/tests/model_hub_tests/gguf/gguf_models_nightly
+++ b/tests/model_hub_tests/gguf/gguf_models_nightly
@@ -34,6 +34,9 @@ minimax-m2,mradermacher/MiniMax-M2.1-REAP-50-i1-GGUF,MiniMax-M2.1-REAP-50.i1-Q2_
jais2,mradermacher/JAIS2-IT-0.3-GGUF,JAIS2-IT-0.3.Q4_K_M.gguf
nemotron_h,bartowski/nvidia_Nemotron-H-8B-Reasoning-128K-GGUF,nvidia_Nemotron-H-8B-Reasoning-128K-Q4_K_M.gguf
mamba2-2.7b,Nicholas55555/mamba2-2.7b-Q8_0-GGUF,mamba2-2.7b-q8_0.gguf
+
+lfm2,LiquidAI/LFM2.5-1.2B-Instruct-GGUF,LFM2.5-1.2B-Instruct-Q4_0.gguf
+lfm2moe,LiquidAI/LFM2.5-8B-A1B-GGUF,LFM2.5-8B-A1B-Q4_0.gguf
qwen35-bonsai-pq2_0,prism-ml/Ternary-Bonsai-27B-gguf,Ternary-Bonsai-27B-PQ2_0.gguf
qwen35-bonsai2-pq2_0,prism-ml/Ternary-Bonsai-2-27B-gguf,Ternary-Bonsai-2-27B-PQ2_0.gguf
qwen35-bonsai2-ptq1_0,prism-ml/Ternary-Bonsai-2-27B-gguf,Ternary-Bonsai-2-27B-PTQ1_0.gguf
diff --git a/tests/model_hub_tests/gguf/gguf_models_precommit b/tests/model_hub_tests/gguf/gguf_models_precommit
index af1d323af1e..8b787987a96 100644
--- a/tests/model_hub_tests/gguf/gguf_models_precommit
+++ b/tests/model_hub_tests/gguf/gguf_models_precommit
@@ -35,3 +35,5 @@ maincoder,mradermacher/Maincoder-1B-GGUF,Maincoder-1B.Q4_K_M.gguf
mistral3,mradermacher/Ministral-3b-instruct-GGUF,Ministral-3b-instruct.Q4_K_M.gguf
qwen35,ggml-org/Qwen3.5-0.8B-GGUF,Qwen3.5-0.8B-Q4_0.gguf
mamba2,rpatel622/mamba2-130m-hf-Q8_0-GGUF,mamba2-130m-q8_0.gguf
+
+lfm2,LiquidAI/LFM2-350M-GGUF,LFM2-350M-Q4_0.gguf