OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GGUF] Add LFM3 decoder, multimodal and speech support (#39293)
Maxim Vafin5c93944ea92a
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hppindex 6ef6b54ca30..6eba420b9b2 100644--- a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp@@ -34,6 +34,8 @@ public:// Options are validated before deriving execution plans and graph metadata.DecoderDimensions configure_decoder(const DecoderParameters& parameters);void configure_model_contract(const ModelContract& contract);+ // Contract declared so far, including declarations installed by projector callbacks.+ ModelContract model_contract() const;DecoderDimensions configure_decoder(RopeMode rope, const DecoderOptions& options = {});DecoderLayerParameters decoder_layer_parameters(int layer) const;GgufValue decoder_attention(int layer, const GgufValue& normalized_input);diff --git a/src/frontends/gguf/docs/architectures.md b/src/frontends/gguf/docs/architectures.mdindex b8aab743f08..a9d383f7da0 100644--- a/src/frontends/gguf/docs/architectures.md+++ b/src/frontends/gguf/docs/architectures.md@@ -91,10 +91,17 @@ Complete parameters and overrides are validated before dependent plans are deriv`ModelContract` declares recurrent batching and image-attention semantics consumed by genericGenAI adaptation. Decoder configuration exports it automatically; other builders may call-`configure_model_contract(contract)`. The common `GgufDecoder::get_model_contract()` accessor+`configure_model_contract(contract)`; `model_contract()` returns the declarations made so far. The common `GgufDecoder::get_model_contract()` accessoralso lets the llama.cpp adapter supply resolved facts. Architecture names are diagnostic data.An explicit `batchable_recurrent` value overrides structural inference; leave it unset to inferbatching from generic operation capabilities. All three states survive IR serialization.+`sequence_outputs` names auxiliary decoder outputs that `AdaptToGenAI` reshapes to+`[B,T,D]`. `component_groups` declares named groups of independently selectable models,+the primary model of each group, its output names and its recurrent-state prefix.+The contracts survive IR serialization; adaptation consumes them without family-name checks.+`supports_genai_adaptation` lets a builder reject the standard decoder interface+when its graph requires a different inference protocol. An unset value defers to+legacy input compatibility, which is resolved before serializing the contract.### Auto-detected features@@ -119,6 +126,13 @@ helpers remain internal migration adapters under builder. The topology never rer| Sliding-window attention | `attention.sliding_window(_pattern)`, or sinks || Per-layer KV heads | `attention.head_count_kv` as an array |+Attention output gates may provide one sigmoid value per channel or per head.+The shared attention block reshapes per-head gates to `[B,T,H,1]` and broadcasts+across head dimensions, preserving the existing full-width and interleaved gate+paths. When GGUF frequency factors encode partial RoPE, retain those factors+instead of reducing the rotary dimension; sliding layers can select a different+RoPE configuration through the per-layer decoder parameters.+MiniCPM's `logit_scale` is a divisor. When the key is absent, the builder uses`embedding_length / 256`, giving the model's `256 / embedding_length` output multiplier.This deliberately corrects the inverted fallback in unpatched llama.cpp, which defaults the@@ -174,6 +188,17 @@ for a custom attention fragment. The Qwen3 builder in[`test_architecture_extension.cpp`](../tests/test_architecture_extension.cpp) owns its layer orderthis way; `VisionEncoderBuilder` in the same file is a larger non-decoder family.+The [LFM builder](../src/builder/arch/lfm_builder.cpp) handles `lfm2`, `lfm2moe` and+`lfm3` in one decoder loop. Family-specific metadata and tensor validation select+normalization and output behavior; residual connections, short convolution,+attention and FFN construction are shared.+For `lfm3`, zero per-layer KV+heads select short convolution; other layers use sliding or full attention. Its+dense SwiGLU layers require both post-attention and post-FFN norms or neither.+Sliding layers rotate the full head, while full-attention layers retain the+partial rotation encoded by `rope_freqs.weight`. Final normalization requires+`output_norm.weight`; an absent output projection uses tied token embeddings.+### Declare model contractsGraph nodes alone do not tell consumers how to maintain state or form masks:diff --git a/src/frontends/gguf/docs/extensions.md b/src/frontends/gguf/docs/extensions.mdindex 448c0911fa6..e7b1f736e7f 100644--- a/src/frontends/gguf/docs/extensions.md+++ b/src/frontends/gguf/docs/extensions.md@@ -148,6 +148,12 @@ semantics (`Image`, `PaddedPatches`, `WindowedPatches`, `SplitMerger`) and are smodel; generic adaptation never selects them by projector name. `build_builtin_projector()`returns the recipe matching its graph. A result's explicit recipe overrides the definition.+A projector may declare its components with `configure_model_contract()`. For `lfm3vl`, `lfm3a`+and `lfm3a_gen` models the coordinator reads that declaration through `model_contract()` and+adds built-in component groups only where the projector declared none; declared recurrent+batching, outputs and state prefixes are preserved. `build_builtin_projector()` also builds+`lfm3vl` (vision) and `lfm3a` (audio).+A custom `genai_adapter` runs for both `EMBEDDINGS` and `VISION_ENCODERS` after generic extractionof the selected modality. It receives an independent model clone and returns `ModelAdapterResult`:the primary graph in `model` and optional named graphs in `models`. It can replace the entirediff --git a/src/frontends/gguf/docs/mmproj.md b/src/frontends/gguf/docs/mmproj.mdindex 0499c25746e..fd1d9faece4 100644--- a/src/frontends/gguf/docs/mmproj.md+++ b/src/frontends/gguf/docs/mmproj.md@@ -1,8 +1,9 @@# Native GGUF multimodal conversionA llama.cpp multimodal projector file (`general.architecture = clip`, usually named-`mmproj-*.gguf`) converts to an `ov::Model` that runs its vision and/or audio encoder and-projector. The language model is a separate `.gguf` converted by the regular decoder path.+`mmproj-*.gguf`) converts to an `ov::Model` with vision/audio encoders and+projectors, and optional speech-generation components. The language model is a+separate `.gguf` converted by the regular decoder path.## Supported projectors@@ -24,10 +25,13 @@ 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 | `lfm3vl` | dynamic raster patches, temporal frame pairs, hybrid convolution/attention, 2x2 merger || 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 |+| Audio | `lfm3a` | streaming mel encoder, causal convolution, KV/position state, learned normalization |+| Speech | `lfm3a_gen` | MaskGIT depthformer, feedback lookup, FSQ and streaming spectral decoder || Audio | `gemma4a` | causal convolution, 12-position relative attention with softcap || Audio | `gemma4ua` | raw 640-sample waveform frames || Audio | `qwen2a`, `ultravox`, `voxtral`, `musicflamingo`, `meralion`, `glma` | Whisper-derived encoders |@@ -55,13 +59,13 @@ Not implemented: `ldp`, `ldpv2`, `adapter`, `step3vl`, `gemma3nv`, `llama4`, `qwSee [testing](testing.md) for commands and acceptance. A catalog entry is not a claim of coveragefor every checkpoint, resolution, quantization, or device.-## Files with vision and audio encoders+## Files with multiple components-A projector file holds at most one vision and one audio encoder; Gemma4 E2B/E4B/12B files carry-both. Conversion builds every encoder the file declares into one model:+The generic `clip` coordinator handles files with at most one vision and one audio encoder;+Gemma4 E2B/E4B/12B files carry both. It builds every declared encoder into one model:1. `clip.has_vision_encoder` and `clip.has_audio_encoder` select the encoders. A file with- neither fails conversion.+ neither is rejected by the generic encoder coordinator.2. Each encoder takes its projector from the global `clip.projector_type`, or else from`clip.vision.projector_type` / `clip.audio.projector_type`. A combined file therefore uses theper-modality keys; only the legacy `qwen2.5o` resolves to a different projector per modality@@ -75,6 +79,10 @@ both. Conversion builds every encoder the file declares into one model:Running the combined model requires the inputs of both branches. `AdaptMmprojToGenAI` (below)turns it into one encoder; apply it to a clone per modality to obtain both.+All `clip` mmproj files use the same builder. It assembles registered vision/audio+encoders and declared LFM3 speech-generation components, recording the component+contracts used for GenAI selection and IR serialization.+## Graph boundaryPreprocessing belongs to the caller. Activations are F32 and indices I32, except the@@ -91,6 +99,8 @@ fixed-resolution encoders retain the size recorded in metadata.| Muse Glimmer | pixels; `patch_indices` in window order with each window padded to `window_size²` slots; one-based `position_x` / `position_y` per slot; `output_indices`; pixel-shuffle `merge_indices`; additive key mask `window_mask [W,1,1,window_size²]` that hides the padding || MiniCPM-V 4.6 | pixels, position IDs, `window_indices`, `inverse_window_indices`, `attention_mask`, `vit_merger.indices.N`, `merger.indices.N` || DeepSeek-OCR / OCR2 | `vision.pixel_values [B,3,H,W]` (independent square tiles), local/global relative-position indices, `vision.output_indices`; OCR1 `position_indices`, OCR2 `query_indices`, `query_output_indices`, `position_ids`, `attention_mask` |+| LFM3 vision | `vision.pixel_values [1,3,H,W]`, `vision.positions`; `vision.pixel_values_1 [1,3,H,W]` when the projector has a second-frame patch kernel |+| LFM3 audio | `audio.features [1,1,mel,frames]`; streaming convolution, K/V and position state inputs || Gemma4 audio | `audio.features [1,1,mel,frames]` || Gemma4 unified audio | `audio.waveform_frames [1,1,T,640]`, 16 kHz waveform in 640-sample frames || Whisper-derived audio | `audio.features [1,mel,1,frames]`, `audio.position_ids [1,1,1,ceil(frames/2)]` |@@ -130,6 +140,14 @@ For real Gemma3 images, reproduce the reference resize/crop and RGB channel normaudio needs the reference mel extraction and frame padding before `audio.features`; Gemma4 unifiedaudio instead takes consecutive 640-sample frames from a 16 kHz waveform, without mel extraction.+The `lfm3vl` encoder uses raster patches and spatial merging at dynamic image+resolutions. Paired-frame projectors take consecutive video frames; repeat a still+image for the second frame. The `lfm3a` encoder takes mel features from mono 16 kHz+audio. Streaming sessions retain position, downsampling, convolution and K/V state.+Non-final chunks contain a multiple of eight mel frames; the final chunk is right+padded. Seven frames of lookahead preserve the centered-convolution boundary.+Flush ends the stream, and reset starts a new utterance.+## Using the encoders and a language model[`AdaptMmprojToGenAI`](../include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp) keeps one@@ -138,9 +156,29 @@ exposes `[1,T,D]` outputs named`image_features` and `deepstack_features.N`, or `audio_features`. It rewrites the model in place,so run it on a separate clone for each modality of a combined file.+For speech generation, select `Modality::AUDIO_GENERATION` on another clone.+`get_audio_generation_models()` returns independent `depthformer`, `feedback` and+`codec` models. Their named inputs, outputs, state declarations and `gguf_mmproj`+configuration survive IR serialization.++Builders declare these components in `ModelContract::component_groups["audio_generation"]`.+The group names its primary model and each component's outputs and recurrent-state prefix.+Vision/audio groups describe their encoder in the same way. The adapter retains only the+selected component's state, preserves state input names and prunes other branches.+An empty state prefix selects a stateless component. These declarations also allow+adaptation after loading an unadapted IR.++The `lfm3a_gen` depthformer uses twelve codebooks with 2017 entries (2016 FSQ codes+and a mask token). Feedback maps sampled codes to decoder embeddings. The codec+uses FSQ levels `[8,7,6,6]`, retains attention/convolution state and produces 1282+polar spectral channels. Sampling and waveform reconstruction belong to the+caller: use MaskGIT sampling and streaming overlap-add with a periodic 1280-point+Hann window to reconstruct audio at 24 kHz.+[`AdaptToGenAI`](../include/openvino/frontend/gguf/adapt_to_genai.hpp) in `EMBEDS_TO_LOGITS`mode prepares the language model for media injection:+- `lfm3` retains normalized `audio_hidden_states` for the speech depthformer alongside primary `logits`;- the token lookup moves to `get_embedding_model()`, sharing its weights, and the language modeltakes `inputs_embeds [B,T,D]`; token-embedding scaling is applied once;- Gemma4 E2B/E4B use a separate `get_per_layer_embedding_model()` whose output feedsdiff --git a/src/frontends/gguf/docs/supported_models.md b/src/frontends/gguf/docs/supported_models.mdindex fae37b46f84..d8b7bf301f3 100644--- a/src/frontends/gguf/docs/supported_models.md+++ b/src/frontends/gguf/docs/supported_models.md@@ -41,6 +41,7 @@ with the [strict accuracy settings](quantization.md#accuracy-controls) (`OV_GGUF| `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 |+| `lfm3` | Dense hybrid convolution/GQA, per-head output gates, paired optional post norms, tied output, mixed full/sliding RoPE | LFM3-1.7B / LFM3-VL-2B / LFM3-Audio-2B / LFM3-Omni-2B | || `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 |@@ -90,6 +91,7 @@ Bailing grouped routing; see the [fixture README](../tests/test_data/arch_accura`nemotron_h_moe` are not supported. See [runtime.md](runtime.md#stateful-and-genai-conversion).- **Multimodal:** a tested language backbone does not cover its vision or audio encoders,preprocessing or application pipeline.+- **Model variants:** the `lfm3` builder supports causal autoregressive backbones; Decision/D1 variants are unsupported.- **Quantization and memory:** see [quantization.md](quantization.md).## llama.cpp cgraph pathdiff --git a/src/frontends/gguf/include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/adapt_mmproj_to_genai.hppindex 3fd7ff37ee0..2b23902c7b9 100644--- a/src/frontends/gguf/include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp+++ b/src/frontends/gguf/include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp@@ -16,7 +16,7 @@ namespace ov::frontend::gguf::pass {class GGUF_FRONTEND_API AdaptMmprojToGenAI : public ov::pass::ModelPass {public:OPENVINO_MODEL_PASS_RTTI("ov::frontend::gguf::pass::AdaptMmprojToGenAI");- enum class Modality { VISION, AUDIO };+ enum class Modality { VISION, AUDIO, AUDIO_GENERATION };/// EMBEDDINGS retains native encoder inputs and exposes [B,T,D] features./// VISION_ENCODERS exposes the family-specific inputs used by GenAI vision encoders./// Invalid layout requirements throw without changing the supplied model.@@ -33,9 +33,15 @@ public:return m_vision_models;}+ /// AUDIO_GENERATION returns independent depthformer, feedback and codec models.+ const std::map<std::string, std::shared_ptr<ov::Model>>& get_audio_generation_models() const {+ return m_audio_generation_models;+ }+private:Modality m_modality;Layout m_layout;std::map<std::string, std::shared_ptr<ov::Model>> m_vision_models;+ std::map<std::string, std::shared_ptr<ov::Model>> m_audio_generation_models;};} // namespace ov::frontend::gguf::passdiff --git a/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hppindex b68b26b7050..5d6f5f11560 100644--- a/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp+++ b/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp@@ -21,11 +21,24 @@namespace ov::frontend::gguf {+struct ModelComponentContract {+ std::vector<std::string> outputs;+ std::string state_prefix;+};++struct ModelComponentGroup {+ std::string primary;+ std::map<std::string, ModelComponentContract> models;+};+struct ModelContract {enum class ImageAttentionMode { CAUSAL, GLOBAL_AND_SLIDING, SLIDING_ONLY };std::optional<bool> batchable_recurrent;ImageAttentionMode image_attention = ImageAttentionMode::CAUSAL;+ std::vector<std::string> sequence_outputs;+ std::map<std::string, ModelComponentGroup> component_groups;+ std::optional<bool> supports_genai_adaptation;};// Typed RoPE configuration, replacing the raw gguf `op_params`/`rope_params` int32 arraydiff --git a/src/frontends/gguf/src/builder/api/graph_context.cpp b/src/frontends/gguf/src/builder/api/graph_context.cppindex a98e44164ed..650fc60360d 100644--- a/src/frontends/gguf/src/builder/api/graph_context.cpp+++ b/src/frontends/gguf/src/builder/api/graph_context.cpp@@ -58,6 +58,10 @@ void GgufGraphContext::configure_model_contract(const ModelContract& contract) {m_impl->emitter.graph()->model_contract = contract;}+ModelContract GgufGraphContext::model_contract() const {+ return m_impl->emitter.graph()->model_contract;+}+DecoderLayerParameters GgufGraphContext::decoder_layer_parameters(int layer) const {m_impl->check_layer(layer);const auto& cfg = *m_impl->decoder;diff --git a/src/frontends/gguf/src/builder/arch/dspark_builder.cpp b/src/frontends/gguf/src/builder/arch/dspark_builder.cppindex ac33d91a5ff..d63b14be17a 100644--- a/src/frontends/gguf/src/builder/arch/dspark_builder.cpp+++ b/src/frontends/gguf/src/builder/arch/dspark_builder.cpp@@ -41,6 +41,7 @@ public:OPENVINO_ASSERT(!captures.empty(), "[GGUF] missing DSpark target_layers");OPENVINO_ASSERT(!m_metadata.get_bool("dspark.dspark.hidden_correction").value_or(false),"[GGUF] DSpark hidden correction is not supported");+ m_config.model_contract.supports_genai_adaptation = false;auto& e = m_emitter;m_config.configure_graph(e, m_metadata);const auto kv = blocks::KvCachePlan::build(m_config);diff --git a/src/frontends/gguf/src/builder/arch/lfm2_builder.hpp b/src/frontends/gguf/src/builder/arch/lfm2_builder.hppdeleted file mode 100644index d6c48f53eba..00000000000--- a/src/frontends/gguf/src/builder/arch/lfm2_builder.hpp+++ /dev/null@@ -1,11 +0,0 @@-// 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::ggufdiff --git a/src/frontends/gguf/src/builder/arch/lfm2_builder.cpp b/src/frontends/gguf/src/builder/arch/lfm2_vocoder_builder.cppsimilarity index 61%rename from src/frontends/gguf/src/builder/arch/lfm2_builder.cpprename to src/frontends/gguf/src/builder/arch/lfm2_vocoder_builder.cppindex d23944319e2..f57403f19ac 100644--- a/src/frontends/gguf/src/builder/arch/lfm2_builder.cpp+++ b/src/frontends/gguf/src/builder/arch/lfm2_vocoder_builder.cpp@@ -2,97 +2,13 @@// SPDX-License-Identifier: Apache-2.0//-#include "lfm2_builder.hpp"-#include <cmath>#include <limits>-#include "builder/decoder_metadata.hpp"-#include "openvino/frontend/gguf/builder/graph_context.hpp"+#include "lfm_builder.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 parameters = resolve_decoder_parameters(g.metadata(), RopeMode::Neox, options);- const auto dims = g.configure_decoder(parameters);- 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) {}@@ -220,10 +136,6 @@ private:};} // 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);}diff --git a/src/frontends/gguf/src/builder/arch/lfm3_audio_generator.cpp b/src/frontends/gguf/src/builder/arch/lfm3_audio_generator.cppnew file mode 100644index 00000000000..657f019cc12--- /dev/null+++ b/src/frontends/gguf/src/builder/arch/lfm3_audio_generator.cpp@@ -0,0 +1,249 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "lfm3_audio_generator.hpp"++#include <cmath>++#include "lfm_builder.hpp"+#include "openvino/frontend/gguf/builder/graph_context.hpp"++namespace ov::frontend::gguf {+namespace {+class AudioGeneration {+public:+ explicit AudioGeneration(GgufGraphContext& context) : g(context) {}++ void build() {+ const auto embedding = g.tensors().require("a.gen.code.embd.weight");+ width = embedding.ne(0);+ vocabulary = embedding.ne(1);+ books = embedding.ne(2);+ OPENVINO_ASSERT(width > 0 && books == 12 && vocabulary == 2017,+ "[GGUF] LFM3 audio generation requires twelve 2017-entry codebooks");+ depth();+ feedback();+ codec();+ ov::Tensor window(ov::element::f32, {1280});+ for (size_t i = 0; i < window.get_size(); ++i)+ window.data<float>()[i] = .5f * (1.f - std::cos(2.f * std::acos(-1.f) * float(i) / 1280.f));+ g.set_output(g.add_constant("audio.codec.istft_window", window), "audio.istft_window");+ }++private:+ GgufValue reshape(const GgufValue& x, const std::vector<int64_t>& shape) {+ return g.node("GGML_OP_RESHAPE", {x}, 0, {{"reshape_target", shape}});+ }+ GgufValue slice(const GgufValue& x, int axis, int64_t start, int64_t length) {+ return g.node("GGML_OP_VIEW", {x}, 3, {{"view_slice", std::vector<int64_t>{axis, start, length}}});+ }+ GgufValue concat(const GgufValue& x, const GgufValue& y, int axis) {+ return g.node("GGML_OP_CONCAT", {x, y}, 0, {{"concat_axis", axis}});+ }+ GgufValue add(const GgufValue& x, const GgufValue& y) {+ return g.node("GGML_OP_ADD", {x, y});+ }+ GgufValue mul(const GgufValue& x, const GgufValue& y) {+ return g.node("GGML_OP_MUL", {x, y});+ }+ GgufValue linear(const GgufValue& x, const std::string& name) {+ auto y = g.node("GGML_OP_MUL_MAT", {g.tensors().require(name + ".weight"), x});+ if (auto b = g.tensors()(name + ".bias"))+ y = add(y, b);+ return y;+ }+ GgufValue norm(const GgufValue& x, const std::string& name, float epsilon) {+ return g.build_norm(x, g.tensors().require(name + ".weight"), epsilon);+ }+ GgufValue book_ids(const GgufValue& codes, int64_t book, const std::string& prefix, bool offset) {+ auto index = reshape(slice(codes, 3, book, 1), {1, 1, 1, -1});+ if (offset) {+ ov::Tensor value(ov::element::i32, {1, 1, 1, 1});+ value.data<int32_t>()[0] = int32_t(book * vocabulary);+ index = add(index, g.add_constant(prefix + ".offset." + std::to_string(book), value));+ }+ return index;+ }+ GgufValue attention(const GgufValue& x,+ const std::string& prefix,+ float epsilon,+ const GgufValue& positions,+ const GgufValue& mask = {},+ int layer = -1) {+ const auto head = g.tensors().require(prefix + "attn_q_norm.weight").ne(0);+ const auto qwidth = g.tensors().require(prefix + "attn_q.weight").ne(1);+ const auto kvwidth = g.tensors().require(prefix + "attn_k.weight").ne(1);+ OPENVINO_ASSERT(head > 0 && head % 2 == 0 && qwidth % head == 0 && kvwidth > 0 && kvwidth % head == 0 &&+ qwidth % kvwidth == 0 && g.tensors().require(prefix + "attn_v.weight").ne(1) == kvwidth,+ "[GGUF] invalid LFM3 audio attention dimensions at ",+ prefix);+ const bool streaming = layer >= 0;+ const auto heads = [&](const GgufValue& value, int64_t count, int64_t size) {+ return streaming ? reshape(value, {1, -1, count, size}) : reshape(value, {-1, books, count, size});+ };+ auto q = norm(heads(linear(x, prefix + "attn_q"), qwidth / head, head), prefix + "attn_q_norm", epsilon);+ auto k = norm(heads(linear(x, prefix + "attn_k"), kvwidth / head, head), prefix + "attn_k_norm", epsilon);+ auto v = heads(linear(x, prefix + "attn_v"), kvwidth / head, head);+ RopeConfig rope;+ rope.n_dims = int(head);+ rope.freq_base = 1000000.f;+ rope.freq_scale = 1.f;+ rope.attn_factor = 1.f;+ rope.per_op = true;+ q = g.node("GGML_OP_ROPE", {q, positions}, 1 << 16, {{"rope_config", rope}});+ k = g.node("GGML_OP_ROPE", {k, positions}, 1 << 16, {{"rope_config", rope}});+ if (streaming) {+ const auto state = [&](const std::string& kind, const GgufValue& current) {+ auto input = g.add_input("audio.codec.state." + kind + "." + std::to_string(layer),+ ov::element::f32,+ {1, 1, 29, kvwidth});+ auto all = concat(input, reshape(current, {1, 1, -1, kvwidth}), 1);+ g.add_recurrent_state(input, slice(all, 2, -29, 29));+ return heads(all, kvwidth / head, head);+ };+ k = state("k", k);+ v = state("v", v);+ }+ std::vector<GgufValue> inputs{q, k, v};+ if (mask)+ inputs.push_back(mask);+ auto output = g.node("GGML_OP_FLASH_ATTN_EXT",+ inputs,+ 100,+ {{"f32_attention", true}, {"scale", 1.f / std::sqrt(float(head))}});+ if (auto gate_weight = g.tensors()(prefix + "attn_gate.weight")) {+ OPENVINO_ASSERT(gate_weight.ne(1) == qwidth / head,+ "[GGUF] LFM3 audio requires one sigmoid gate per query head");+ auto gate = g.node("GGML_UNARY_OP_SIGMOID", {linear(x, prefix + "attn_gate")});+ output = mul(output, heads(gate, qwidth / head, 1));+ }+ output = streaming ? reshape(output, {1, 1, -1, qwidth}) : reshape(output, {-1, 1, books, qwidth});+ return linear(output, prefix + "attn_out");+ }+ GgufValue convolution(const GgufValue& x, const std::string& prefix, int layer) {+ const auto channels = x.ne(0);+ const auto kernel = g.tensors().require(prefix + "conv_dw.weight").ne(0);+ OPENVINO_ASSERT(kernel > 1 && g.tensors().require(prefix + "conv_pw1.weight").ne(1) == 3 * channels,+ "[GGUF] invalid LFM3 codec short convolution");+ const auto gated = build_lfm_short_conv(g,+ linear(x, prefix + "conv_pw1"),+ g.tensors().require(prefix + "conv_dw.weight"),+ channels,+ "audio.codec.state.conv." + std::to_string(layer));+ return linear(gated, prefix + "conv_pw2");+ }+ GgufValue block(const GgufValue& x,+ const std::string& prefix,+ float epsilon,+ const GgufValue& positions,+ const GgufValue& mask = {},+ int layer = -1) {+ const bool conv = g.tensors().has(prefix + "conv_dw.weight");+ OPENVINO_ASSERT(conv != g.tensors().has(prefix + "attn_q.weight") && (!conv || layer >= 0),+ "[GGUF] LFM3 audio blocks require exactly one supported operator");+ OPENVINO_ASSERT(+ g.tensors().has(prefix + "attn_post_norm.weight") == g.tensors().has(prefix + "ffn_post_norm.weight"),+ "[GGUF] LFM3 audio sandwich norms must appear as a pair");+ auto y = norm(x, prefix + "ln1", epsilon);+ y = conv ? convolution(y, prefix, layer) : attention(y, prefix, epsilon, positions, mask, layer);+ if (g.tensors().has(prefix + "attn_post_norm.weight"))+ y = norm(y, prefix + "attn_post_norm", epsilon);+ auto residual = add(x, y);+ y = norm(residual, prefix + "ln2", epsilon);+ y = mul(g.node("GGML_UNARY_OP_SILU", {linear(y, prefix + "ffn_gate")}), linear(y, prefix + "ffn_up"));+ y = linear(y, prefix + "ffn_down");+ if (g.tensors().has(prefix + "ffn_post_norm.weight"))+ y = norm(y, prefix + "ffn_post_norm", epsilon);+ return add(residual, y);+ }+ void depth() {+ const auto projection = g.tensors().require("a.gen.code.proj_in.weight");+ OPENVINO_ASSERT(projection.ne(1) == books * width, "[GGUF] invalid LFM3 depth projection");+ const auto hidden = g.add_input("audio.depth.hidden_states", ov::element::f32, {1, 1, -1, projection.ne(0)});+ const auto codes = g.add_input("audio.depth.codes", ov::element::i32, {1, 1, -1, books});+ const auto mask = g.add_input("audio.depth.mask", ov::element::f32, {1, 1, -1, books});+ const auto tables = reshape(g.tensors().require("a.gen.code.embd.weight"), {1, books, vocabulary, width});+ GgufValue embedded;+ for (int64_t book = 0; book < books; ++book) {+ auto token =+ g.node("GGML_OP_GET_ROWS", {slice(tables, 1, book, 1), book_ids(codes, book, "audio.depth", false)});+ auto revealed = slice(mask, 3, book, 1);+ token = add(mul(token, revealed),+ mul(g.tensors().require("a.gen.code.mask_embd"),+ g.node("GGML_OP_SCALE", {revealed}, 0, {{"scale", -1.f}, {"bias", 1.f}})));+ token = reshape(token, {-1, 1, 1, width});+ embedded = embedded ? concat(embedded, token, 1) : token;+ }+ auto current = add(reshape(linear(hidden, "a.gen.code.proj_in"), {-1, 1, books, width}), embedded);+ ov::Tensor positions(ov::element::i32, {1, 1, 1, size_t(books)});+ for (int64_t i = 0; i < books; ++i)+ positions.data<int32_t>()[i] = int32_t(i);+ const auto pos = g.add_constant("audio.depth.positions", positions);+ const auto layers = g.metadata().get_int("clip.gen.audio.block_count").value_or(0);+ const auto epsilon =+ float(g.metadata().get_float("clip.gen.audio.attention.layer_norm_epsilon").value_or(1e-5));+ OPENVINO_ASSERT(layers == 3, "[GGUF] LFM3 depthformer requires three bidirectional attention layers");+ for (int layer = 0; layer < layers; ++layer)+ current = block(current, "a.gen.code.blk." + std::to_string(layer) + ".", epsilon, pos);+ current = norm(current, "a.gen.code.output_norm", epsilon);+ const auto head_norms = reshape(g.tensors().require("a.gen.code.head_norm.weight"), {1, 1, books, width});+ GgufValue logits;+ for (int64_t book = 0; book < books; ++book) {+ const auto value = g.build_norm(slice(current, 2, book, 1), slice(head_norms, 2, book, 1), epsilon);+ auto output = g.node("GGML_OP_MUL_MAT", {slice(tables, 1, book, 1), value});+ logits = logits ? concat(logits, output, 1) : output;+ }+ g.set_output(reshape(logits, {1, -1, books, vocabulary}), "audio.depth_logits");+ }+ void feedback() {+ const auto codes = g.add_input("audio.feedback.codes", ov::element::i32, {1, 1, -1, books});+ const auto table = g.tensors().require("a.gen.code.out_embd.weight");+ OPENVINO_ASSERT(table.ne(1) == books * vocabulary, "[GGUF] invalid LFM3 feedback embedding table");+ GgufValue sum;+ for (int64_t book = 0; book < books; ++book) {+ auto value = g.node("GGML_OP_GET_ROWS", {table, book_ids(codes, book, "audio.feedback", true)});+ sum = sum ? add(sum, value) : value;+ }+ g.set_output(sum, "audio.feedback");+ }+ void codec() {+ const auto table = g.tensors().require("a.gen.wav.quant.first.codebook.weight");+ OPENVINO_ASSERT(table.ne(0) == 4 && table.ne(1) == vocabulary - 1,+ "[GGUF] LFM3 codec requires the [8,7,6,6] finite scalar codebook");+ const auto codes = g.add_input("audio.codec.codes", ov::element::i32, {1, 1, -1, books});+ GgufValue quantized;+ for (int64_t book = 0; book < books; ++book) {+ auto value = g.node("GGML_OP_GET_ROWS", {table, book_ids(codes, book, "audio.codec", false)});+ quantized = quantized ? concat(quantized, value, 0) : value;+ }+ auto current = linear(linear(quantized, "a.gen.wav.quant.first.out_proj"), "a.gen.wav.tfm.in_proj");+ const auto channels = current.ne(0);+ current = g.node("GGML_OP_REPEAT",+ {reshape(current, {1, -1, 1, channels})},+ 0,+ {{"repeats", std::vector<int64_t>{1, 1, 6, 1}}});+ current = reshape(current, {1, 1, -1, channels});+ const auto positions = g.add_input("audio.codec.positions", ov::element::i32, {1, 1, 1, -1});+ const auto mask = g.add_input("audio.codec.attention_mask", ov::element::f32, {1, 1, -1, -1});+ const auto position = g.add_input("audio.codec.state.pos", ov::element::f32, {1, 1, 1, 1});+ auto count = g.node("GGML_OP_TRANSPOSE", {slice(current, 3, 0, 1)});+ count = g.node("GGML_OP_SUM_ROWS", {g.node("GGML_OP_FILL", {count}, 0, {{"fill_value", 1.f}})});+ g.add_recurrent_state(position, add(position, count));+ int layer = 0;+ for (; g.tensors().has("a.gen.wav.tfm.blk." + std::to_string(layer) + ".ln1.weight"); ++layer)+ current = block(current, "a.gen.wav.tfm.blk." + std::to_string(layer) + ".", 1e-5f, positions, mask, layer);+ OPENVINO_ASSERT(layer == 8, "[GGUF] LFM3 codec requires eight streaming decoder layers");+ current = linear(norm(current, "a.gen.wav.tfm.output_norm", 1e-5f), "a.gen.wav.tfm.out_proj");+ OPENVINO_ASSERT(current.ne(0) == 1282, "[GGUF] LFM3 codec requires a 1282-channel polar spectral output");+ g.set_output(current, "audio.spectrogram");+ }+ GgufGraphContext& g;+ int64_t width = 0, vocabulary = 0, books = 0;+};+} // namespace++void build_lfm3_audio_generation(GgufGraphContext& g) {+ AudioGeneration(g).build();+}+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/builder/arch/lfm3_audio_generator.hpp b/src/frontends/gguf/src/builder/arch/lfm3_audio_generator.hppnew file mode 100644index 00000000000..9c5c53832ea--- /dev/null+++ b/src/frontends/gguf/src/builder/arch/lfm3_audio_generator.hpp@@ -0,0 +1,10 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++namespace ov::frontend::gguf {+class GgufGraphContext;+void build_lfm3_audio_generation(GgufGraphContext& g);+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/builder/arch/lfm3_projector_builder.cpp b/src/frontends/gguf/src/builder/arch/lfm3_projector_builder.cppnew file mode 100644index 00000000000..f1a7e939172--- /dev/null+++ b/src/frontends/gguf/src/builder/arch/lfm3_projector_builder.cpp@@ -0,0 +1,298 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "lfm3_projector_builder.hpp"++#include <cmath>++#include "builder/metadata_checks.hpp"+#include "lfm_builder.hpp"++namespace ov::frontend::gguf {+namespace {+class Lfm3Projector {+public:+ explicit Lfm3Projector(GgufGraphContext& graph, const std::string& modality) : g(graph) {+ const auto key = "clip." + modality + ".";+ width = require_positive_int(g.metadata(), key + "embedding_length", "LFM3 mmproj");+ heads = require_positive_int(g.metadata(), key + "attention.head_count", "LFM3 mmproj");+ kv_heads = require_positive_int(g.metadata(), key + "attention.head_count_kv", "LFM3 mmproj");+ layers = require_positive_int(g.metadata(), key + "block_count", "LFM3 mmproj");+ eps = require_positive_float(g.metadata(), key + "attention.layer_norm_epsilon", "LFM3 mmproj");+ OPENVINO_ASSERT(width % heads == 0 && heads % kv_heads == 0, "[GGUF] invalid LFM3 encoder head geometry");+ head = width / heads;+ g.configure_rope(rope_config(head));+ }++ ProjectorResult vision() {+ const auto patch = require_positive_int(g.metadata(), "clip.vision.patch_size", "LFM3-VL");+ const auto merge = g.metadata().get_int("clip.vision.spatial_merge_size").value_or(2);+ OPENVINO_ASSERT(patch == 16 && merge == 2 && head % 4 == 0, "[GGUF] unsupported LFM3-VL patch/merge geometry");+ auto pixels = g.add_input("vision.pixel_values", ov::element::f32, {1, 3, -1, -1});+ auto spatial = conv(pixels, "v.patch_embd", patch, patch, 0, 0);+ if (g.tensors().has("v.patch_embd.weight.1")) {+ auto second = g.add_input("vision.pixel_values_1", ov::element::f32, {1, 3, -1, -1});+ spatial = add(spatial,+ g.node("GGML_OP_CONV_2D",+ {g.tensors().require("v.patch_embd.weight.1"), second},+ 0,+ {{"conv_params", std::vector<int64_t>{patch, patch, 0, 0, 1, 1}}}));+ }+ auto x = transpose(reshape(spatial, {1, 1, width, -1}));+ x = rms(x, "v.embedding_norm");+ auto positions = g.add_input("vision.positions", ov::element::i32, {1, 1, 1, -1});+ for (int64_t layer = 0; layer < layers; ++layer) {+ const auto p = "v.blk." + std::to_string(layer) + ".";+ auto z = rms(x, p + "ln1");+ if (g.tensors().has(p + "conv2d_in_proj.weight")) {+ auto projection = linear(z, p + "conv2d_in_proj");+ auto gated = mul(slice(projection, 3, 0, width), slice(projection, 3, 2 * width, width));+ if (g.tensors().has(p + "conv2d_spatial.weight")) {+ gated = transpose(reshape(conv(to_grid(gated, spatial), p + "conv2d_spatial", 1, 1, 1, 1, true),+ {1, 1, width, -1}));+ }+ z = linear(mul(slice(projection, 3, width, width), gated), p + "conv2d_out_proj");+ } else {+ z = attention(z, p, positions, true);+ }+ x = add(x, z);+ x = add(x, ffn(rms(x, p + "ln2"), p, "GGML_UNARY_OP_SILU"));+ }+ x = g.build_norm_ln(x,+ g.tensors().require("mm.input_norm.weight"),+ g.tensors().require("mm.input_norm.bias"),+ 1e-6f);+ // Unfold is channel-major; restore raster 2x2 patches with features innermost.+ x = g.node("GGML_OP_IM2COL",+ {to_grid(x, spatial)},+ 0,+ {{"kernel_shape", ov::Shape{size_t(4 * width), size_t(width), 2, 2}},+ {"im2col_params", std::vector<int32_t>{2, 2, 0, 0, 1, 1, 1}},+ {"dst_type", ov::element::f32}});+ x = reshape(transpose(reshape(x, {1, -1, width, 4}), {0, 1, 3, 2}), {1, 1, -1, 4 * width});+ x = linear(g.node("GGML_UNARY_OP_GELU_ERF", {linear(x, "mm.0")}), "mm.2");+ ProjectorResult result;+ result.output = x;+ result.genai_layout = ProjectorLayout::Image;+ result.config = {{"vision.merge", "2"}, {"vision.temporal_patch_size", "2"}, {"vision.streaming", "false"}};+ return result;+ }++ ProjectorResult audio() {+ const auto mel = require_positive_int(g.metadata(), "clip.audio.num_mel_bins", "LFM3-Audio");+ const auto window = require_positive_int(g.metadata(), "clip.audio.window_size", "LFM3-Audio");+ OPENVINO_ASSERT(mel == 128 && window > 1, "[GGUF] invalid LFM3-Audio mel/window geometry");+ prefix = window - 1;+ auto base_position = state("pos", {1, 1, 1, 1});+ auto x = g.add_input("audio.features", ov::element::f32, {1, 1, mel, -1});+ x = downsample(x, "ds0", "a.conv1d.0", false);+ x = g.node("GGML_UNARY_OP_SILU", {x});+ x = downsample(x, "ds1", "a.conv1d.2", true);+ x = pointwise_silu(x, "a.conv1d.3");+ x = downsample(x, "ds2", "a.conv1d.5", true);+ x = pointwise_silu(x, "a.conv1d.6");+ const auto flat = g.tensors().require("a.pre_encode.out.weight").ne(0);+ x = linear(reshape(transpose(x, {0, 3, 1, 2}), {1, 1, -1, flat}), "a.pre_encode.out");+ auto index = scale(g.node("GGML_OP_CUMSUM", {transpose(scale(slice(x, 3, 0, 1), 0.f, 1.f))}), 1.f, -1.f);+ auto positions = g.node("GGML_OP_CPY", {add(index, base_position)}, 0, {{"dst_type", ov::element::i32}});+ update(base_position, add(base_position, scale(slice(index, 3, -1, 1), 1.f, 1.f)));+ for (int64_t layer = 0; layer < layers; ++layer) {+ const auto p = "a.blk." + std::to_string(layer) + ".";+ auto z = rms(x, p + "ln1");+ if (g.tensors().has(p + "conv_dw.weight")) {+ z = build_lfm_short_conv(g,+ linear(z, p + "conv_pw1"),+ g.tensors().require(p + "conv_dw.weight"),+ width,+ "audio.state.conv_" + std::to_string(layer),+ false);+ z = linear(z, p + "conv_pw2");+ } else {+ z = attention(z, p, positions, false, layer, index, base_position);+ }+ x = add(x, z);+ x = add(x, ffn(rms(x, p + "ln2"), p, "GGML_UNARY_OP_SILU"));+ }+ x = rms(x, "a.post_ln");+ x = g.build_norm_ln(x, g.tensors().require("mm.a.mlp.0.weight"), g.tensors().require("mm.a.mlp.0.bias"), 1e-5f);+ x = linear(g.node("GGML_UNARY_OP_GELU_ERF", {linear(x, "mm.a.mlp.1")}), "mm.a.mlp.3");+ ProjectorResult result;+ result.output = x;+ result.config = {{"audio.merge", "1"}, {"audio.streaming", "true"}, {"audio.encoder_stride", "8"}};+ return result;+ }++private:+ GgufGraphContext& g;+ int64_t width, heads, kv_heads, layers, head, prefix = 0;+ float eps;+ GgufValue audio_mask;++ static RopeConfig rope_config(int64_t dims) {+ RopeConfig config;+ config.per_op = true;+ config.n_dims = int(dims);+ config.freq_base = 1e6f;+ config.freq_scale = config.attn_factor = 1.f;+ return config;+ }++ GgufValue reshape(const GgufValue& x, std::vector<int64_t> shape) {+ return g.node("GGML_OP_RESHAPE", {x}, 6, {{"reshape_target", std::move(shape)}});+ }+ GgufValue transpose(const GgufValue& x, std::vector<int64_t> perm = {0, 1, 3, 2}) {+ return g.node("GGML_OP_TRANSPOSE", {x}, 0, {{"perm", std::move(perm)}});+ }+ GgufValue slice(const GgufValue& x, int64_t axis, int64_t begin, int64_t count) {+ return g.node("GGML_OP_VIEW", {x}, 3, {{"view_slice", std::vector<int64_t>{axis, begin, count}}});+ }+ GgufValue add(const GgufValue& x, const GgufValue& y) {+ return g.node("GGML_OP_ADD", {x, y});+ }+ GgufValue mul(const GgufValue& x, const GgufValue& y) {+ return g.node("GGML_OP_MUL", {x, y});+ }+ GgufValue concat(const GgufValue& x, const GgufValue& y, int64_t axis) {+ return g.node("GGML_OP_CONCAT", {x, y}, 0, {{"concat_axis", int(3 - axis)}});+ }+ GgufValue scale(const GgufValue& x, float value, float bias = 0.f) {+ return g.node("GGML_OP_SCALE", {x}, 0, {{"scale", value}, {"bias", bias}});+ }+ GgufValue linear(const GgufValue& x, const std::string& name) {+ auto y = g.node("GGML_OP_MUL_MAT", {g.tensors().require(name + ".weight"), x});+ if (auto bias = g.tensors()(name + ".bias"))+ y = add(y, bias);+ return y;+ }+ GgufValue rms(const GgufValue& x, const std::string& name) {+ auto y = g.build_norm(x, g.tensors().require(name + ".weight"), eps);+ if (auto bias = g.tensors()(name + ".bias"))+ y = add(y, bias);+ return y;+ }+ GgufValue ffn(const GgufValue& x, const std::string& p, const std::string& activation) {+ return linear(mul(g.node(activation, {linear(x, p + "ffn_gate")}), linear(x, p + "ffn_up")), p + "ffn_down");+ }+ GgufValue+ conv(const GgufValue& x, const std::string& name, int64_t sx, int64_t sy, int64_t px, int64_t py, bool dw = false) {+ return g.node("GGML_OP_CONV_2D",+ {g.tensors().require(name + ".weight"), x},+ 0,+ {{"conv_params", std::vector<int64_t>{sx, sy, px, py, 1, 1}}, {"depthwise", dw}});+ }+ GgufValue to_grid(const GgufValue& tokens, const GgufValue& spatial) {+ return g.node("GGML_OP_RESHAPE",+ {transpose(tokens), spatial},+ 0,+ {{"reshape_target", std::vector<int64_t>{1, width, 0, 0}},+ {"shape_axes", std::vector<int64_t>{-1, -1, 2, 3}}});+ }+ GgufValue pointwise_silu(const GgufValue& x, const std::string& name) {+ return g.node("GGML_UNARY_OP_SILU", {add(conv(x, name, 1, 1, 0, 0), g.tensors().require(name + ".bias"))});+ }+ GgufValue state(const std::string& name, const ov::PartialShape& shape) {+ return g.add_input("audio.state." + name, ov::element::f32, shape);+ }+ void update(const GgufValue& previous, const GgufValue& next) {+ OPENVINO_ASSERT(previous.shape().compatible(next.shape()),+ "[GGUF] LFM3 state shape mismatch ",+ previous.name(),+ " ",+ previous.shape(),+ " -> ",+ next.shape());+ g.add_recurrent_state(previous, next);+ }+ GgufValue downsample(GgufValue x, const std::string& slot, const std::string& name, bool dw) {+ const auto shape = x.shape();+ auto previous = state(slot, {1, shape[1], shape[2], 1});+ x = concat(previous, x, 3);+ update(previous, slice(x, 3, -1, 1));+ x = g.node("GGML_OP_PAD", {x}, 0, {{"pad_params", std::vector<int32_t>{0, 1, 0, 0, 0, 0, 0, 0}}});+ return add(conv(x, name, 2, 2, 0, 1, dw), g.tensors().require(name + ".bias"));+ }+ GgufValue attention(const GgufValue& x,+ const std::string& p,+ const GgufValue& positions,+ bool vision,+ int64_t layer = 0,+ const GgufValue& index = {},+ const GgufValue& base_position = {}) {+ auto q = reshape(linear(x, p + "attn_q"), {1, -1, heads, head});+ auto k = reshape(linear(x, p + "attn_k"), {1, -1, kv_heads, head});+ auto v = reshape(linear(x, p + "attn_v"), {1, -1, kv_heads, head});+ OPENVINO_ASSERT(+ vision || (g.tensors().has(p + "attn_q_norm.weight") && g.tensors().has(p + "attn_k_norm.weight")),+ "[GGUF] LFM3-Audio requires per-head Q/K RMS normalization");+ if (g.tensors().has(p + "attn_q_norm.weight"))+ q = rms(q, p + "attn_q_norm");+ if (g.tensors().has(p + "attn_k_norm.weight"))+ k = rms(k, p + "attn_k_norm");+ auto rope = rope_config(vision ? head / 2 : head);+ if (vision) {+ rope.n_ctx_orig = 32768;+ rope.beta_fast = 32.f;+ rope.beta_slow = 1.f;+ rope.sections = {int32_t(head / 4), int32_t(head / 4), 0, 0};+ }+ q = g.node("GGML_OP_ROPE", {q, positions}, (vision ? 3 : 1) << 16, {{"rope_config", rope}});+ k = g.node("GGML_OP_ROPE", {k, positions}, (vision ? 3 : 1) << 16, {{"rope_config", rope}});+ std::vector<GgufValue> inputs{q, k, v};+ if (!vision) {+ auto previous_k = state("k_" + std::to_string(layer), {1, 1, prefix, kv_heads * head});+ auto previous_v = state("v_" + std::to_string(layer), {1, 1, prefix, kv_heads * head});+ auto flat_k = concat(previous_k, reshape(k, {1, 1, -1, kv_heads * head}), 2);+ auto flat_v = concat(previous_v, reshape(v, {1, 1, -1, kv_heads * head}), 2);+ update(previous_k, slice(flat_k, 2, -prefix, prefix));+ update(previous_v, slice(flat_v, 2, -prefix, prefix));+ k = reshape(flat_k, {1, -1, kv_heads, head});+ v = reshape(flat_v, {1, -1, kv_heads, head});+ // Every streaming layer sees the same [prefix + T] keys, so the window mask is built once.+ if (!audio_mask) {+ auto key_index = scale(g.node("GGML_OP_CUMSUM", {transpose(scale(slice(flat_k, 3, 0, 1), 0.f, 1.f))}),+ 1.f,+ -1.f - float(prefix));+ auto distance = g.node("GGML_OP_SUB", {transpose(index), key_index});+ auto clamp = [&](const GgufValue& value) {+ return g.node("GGML_OP_CLAMP", {value}, 0, {{"clamp_min", 0.f}, {"clamp_max", 1.f}});+ };+ auto inside = mul(clamp(scale(distance, 1.f, 1.f)), clamp(scale(distance, -1.f, float(prefix + 1))));+ inside = mul(inside, clamp(scale(add(key_index, base_position), 1.f, 1.f)));+ audio_mask = scale(inside, 1e9f, -1e9f);+ }+ inputs = {q, k, v, audio_mask};+ }+ return linear(reshape(g.node("GGML_OP_FLASH_ATTN_EXT",+ inputs,+ 100,+ {{"f32_attention", true}, {"scale", 1.f / std::sqrt(float(head))}}),+ {1, 1, -1, width}),+ p + "attn_out");+ }+};++} // namespace++ProjectorResult build_lfm3_projector(GgufGraphContext& graph, const std::string& modality) {+ OPENVINO_ASSERT(modality == "vision" || modality == "audio", "[GGUF] invalid LFM3 projector modality");+ Lfm3Projector builder(graph, modality);+ return modality == "vision" ? builder.vision() : builder.audio();+}++std::vector<ProjectorDefinition> lfm3_projector_definitions() {+ std::vector<ProjectorDefinition> result;+ for (const auto* modality : {"vision", "audio"}) {+ const std::string type = std::string(modality) == "vision" ? "lfm3vl" : "lfm3a";+ result.push_back({"clip." + std::string(modality) + "." + type,+ "clip",+ modality,+ type,+ [modality](GgufGraphContext& graph) {+ return build_lfm3_projector(graph, modality);+ },+ {}});+ }+ return result;+}+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/builder/arch/lfm3_projector_builder.hpp b/src/frontends/gguf/src/builder/arch/lfm3_projector_builder.hppnew file mode 100644index 00000000000..d7020aa8564--- /dev/null+++ b/src/frontends/gguf/src/builder/arch/lfm3_projector_builder.hpp@@ -0,0 +1,12 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/frontend/gguf/extension/projector.hpp"++namespace ov::frontend::gguf {+ProjectorResult build_lfm3_projector(GgufGraphContext& graph, const std::string& modality);+std::vector<ProjectorDefinition> lfm3_projector_definitions();+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/builder/arch/lfm_builder.cpp b/src/frontends/gguf/src/builder/arch/lfm_builder.cppnew file mode 100644index 00000000000..56d244d3c85--- /dev/null+++ b/src/frontends/gguf/src/builder/arch/lfm_builder.cpp@@ -0,0 +1,179 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "lfm_builder.hpp"++#include <algorithm>+#include <limits>++#include "builder/decoder_metadata.hpp"++namespace ov::frontend::gguf {+namespace {+DecoderParameters lfm_decoder_parameters(const GgufMetadata& metadata, bool lfm3) {+ if (!lfm3) {+ DecoderOptions options;+ options.normalize_expert_weights = true;+ return resolve_decoder_parameters(metadata, RopeMode::Neox, options);+ }+ OPENVINO_ASSERT(metadata.has("lfm3.attention.sliding_window_pattern") &&+ metadata.has("lfm3.attention.sliding_window") && metadata.has("lfm3.rope.freq_base_swa"),+ "[GGUF] LFM3 requires sliding-window metadata and its RoPE frequency base");+ DecoderParameters defaults;+ defaults.attention.rope_mode = RopeMode::Neox;+ defaults.attention.output_gate = true;+ defaults.normalization.qk_norm = true;+ defaults.normalization.qk_full_width = false;+ defaults.model_contract.batchable_recurrent = true;+ defaults.model_contract.sequence_outputs = {"audio_hidden_states"};+ auto parameters = read_decoder_parameters(metadata, defaults);+ parameters.experts.enabled = false;+ const auto layers = static_cast<size_t>(parameters.dimensions.layers);+ const auto& kv_heads = parameters.dimensions.kv_heads_per_layer;+ const auto& sliding = parameters.attention.sliding_layers;+ OPENVINO_ASSERT(kv_heads.size() == layers && sliding.size() == layers && parameters.attention.window_size > 0 &&+ std::any_of(sliding.begin(),+ sliding.end(),+ [](int value) {+ return value == 1;+ }),+ "[GGUF] LFM3 requires per-layer KV heads and sliding-window flags");+ const auto value_size = metadata.get_int("lfm3.attention.value_length");+ OPENVINO_ASSERT(!value_size || *value_size == parameters.dimensions.head_size,+ "[GGUF] LFM3 requires equal key and value head sizes");+ parameters.layers.resize(layers);+ for (size_t layer = 0; layer < layers; ++layer) {+ OPENVINO_ASSERT((sliding[layer] == 0 || sliding[layer] == 1) && (!sliding[layer] || kv_heads[layer] > 0),+ "[GGUF] LFM3 sliding-window flags must select attention layers");+ parameters.layers[layer].recurrent = kv_heads[layer] == 0;+ }+ return parameters;+}++class LfmBuilder : public ModelBuilder {+public:+ explicit LfmBuilder(const BuildContext& context) : g(context) {}++ std::shared_ptr<GgufGraph> build() override {+ const bool lfm3 = g.arch() == "lfm3";+ const auto kernel = g.metadata().get_int(g.arch() + ".shortconv.l_cache");+ OPENVINO_ASSERT(kernel && *kernel > 1 && *kernel <= std::numeric_limits<int>::max(),+ "[GGUF] ",+ lfm3 ? "LFM3" : "LFM2",+ " requires shortconv.l_cache > 1");+ OPENVINO_ASSERT(g.metadata().get_bool(g.arch() + ".attention.causal").value_or(true),+ lfm3 ? "[GGUF] LFM3 decision models are not supported"+ : "[GGUF] noncausal LFM2 embedding models require a centered convolution builder");+ const auto parameters = lfm_decoder_parameters(g.metadata(), lfm3);+ const auto dims = g.configure_decoder(parameters);+ OPENVINO_ASSERT(dims.layers > 0 && dims.embedding > 0,+ "[GGUF] LFM decoder requires positive layer and embedding counts");+ auto weights = g.tensors();+ const bool detokenizer = !lfm3 && weights.has("dense_2.weight");+ const auto output_weight = weights.require(detokenizer ? "dense_2.weight"+ : weights.has("output.weight") ? "output.weight"+ : "token_embd.weight");+ if (detokenizer)+ OPENVINO_ASSERT(output_weight.ne(0) == dims.embedding && output_weight.ne(1) == 1282,+ "[GGUF] LFM2 audio detokenizer requires a 1282-channel spectral head");+ g.build_inp_pos();+ g.build_attn_inp_kv();+ auto cur = g.build_inp_embd(weights.require("token_embd.weight"));+ 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 weight = [&](const std::string& name) {+ return weights.require(prefix + name);+ };+ const bool post_norm = lfm3 && weights.has(prefix + "post_attention_norm.weight");+ if (lfm3)+ OPENVINO_ASSERT(post_norm == weights.has(prefix + "post_ffw_norm.weight"),+ "[GGUF] LFM3 requires both post norms or neither in layer ",+ layer);+ const bool recurrent = lfm3 ? parameters.dimensions.kv_heads_per_layer[layer] == 0+ : weights.has(prefix + "shortconv.in_proj.weight");+ auto residual = cur;+ cur = g.build_norm(cur, weight("attn_norm.weight"), dims.norm_epsilon);+ if (recurrent) {+ const auto in = weight("shortconv.in_proj.weight");+ const auto conv = weight("shortconv.conv.weight");+ const auto out = weight("shortconv.out_proj.weight");+ if (lfm3)+ OPENVINO_ASSERT(in.ne(0) == dims.embedding && in.ne(1) == int64_t{3} * dims.embedding &&+ conv.ne(0) == *kernel && conv.ne(1) == dims.embedding &&+ out.ne(0) == dims.embedding && out.ne(1) == dims.embedding,+ "[GGUF] invalid LFM3 short-convolution weights in layer ",+ layer);+ const auto gated = build_lfm_short_conv(g,+ g.node("GGML_OP_MUL_MAT", {in, cur}),+ conv,+ dims.embedding,+ "conv_state_l" + std::to_string(layer));+ cur = g.node("GGML_OP_MUL_MAT", {out, gated});+ } else {+ if (lfm3) {+ OPENVINO_ASSERT(!weights.has(prefix + "shortconv.in_proj.weight"),+ "[GGUF] LFM3 convolution tensor conflicts with attention-layer metadata");+ OPENVINO_ASSERT(weight("attn_gate.weight").ne(1) == g.decoder_layer_parameters(layer).query_heads,+ "[GGUF] LFM3 requires a sigmoid gate per attention head");+ if (!parameters.attention.sliding_layers[layer])+ weights.require("rope_freqs.weight");+ }+ cur = g.decoder_attention(layer, cur);+ }+ if (post_norm)+ cur = g.build_norm(cur, weight("post_attention_norm.weight"), dims.norm_epsilon);+ 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", {residual, cur});+ residual = cur;+ cur = g.decoder_ffn(layer, g.build_norm(cur, weight("ffn_norm.weight"), dims.norm_epsilon));+ if (post_norm)+ cur = g.build_norm(cur, weight("post_ffw_norm.weight"), dims.norm_epsilon);+ cur = g.node("GGML_OP_ADD", {residual, cur});+ }+ cur = g.build_norm(cur,+ weights.require(lfm3 ? "output_norm.weight" : "token_embd_norm.weight"),+ dims.norm_epsilon);+ if (lfm3)+ g.set_output(cur, "audio_hidden_states");+ auto output = g.node("GGML_OP_MUL_MAT", {output_weight, cur});+ if (detokenizer) {+ if (auto bias = weights("dense_2.bias"))+ output = g.node("GGML_OP_ADD", {output, bias});+ }+ g.set_primary_output(output);+ return g.finish();+ }++private:+ GgufGraphContext g;+};+} // namespace++GgufValue build_lfm_short_conv(GgufGraphContext& g,+ const GgufValue& projected,+ const GgufValue& conv_weight,+ int64_t channels,+ const std::string& state_name,+ bool batch_major) {+ const auto 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}}});+ };+ const auto taps = conv_weight.ne(0) - 1;+ const auto bx =+ g.node("GGML_OP_TRANSPOSE",+ {g.node("GGML_OP_MUL", {slice(projected, 0, channels), slice(projected, 2 * channels, channels)})});+ const auto state = g.add_input(state_name, ov::element::f32, {1, 1, channels, taps});+ const auto window = g.node("GGML_OP_CONCAT", {state, bx}, 0, {{"concat_axis", 0}});+ g.add_recurrent_state(state, slice(window, -taps, taps));+ const auto conv = g.node("GGML_OP_SSM_CONV", {window, conv_weight}, 0, {{"batch_major", batch_major}});+ return g.node("GGML_OP_MUL", {slice(projected, channels, channels), conv});+}+std::shared_ptr<ModelBuilder> make_lfm_builder(const BuildContext& context) {+ return std::make_shared<LfmBuilder>(context);+}+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/builder/arch/lfm_builder.hpp b/src/frontends/gguf/src/builder/arch/lfm_builder.hppnew file mode 100644index 00000000000..f2c530b95bd--- /dev/null+++ b/src/frontends/gguf/src/builder/arch/lfm_builder.hpp@@ -0,0 +1,23 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>++#include "openvino/frontend/gguf/builder/graph_context.hpp"+#include "openvino/frontend/gguf/builder/model_builder.hpp"++namespace ov::frontend::gguf {+std::shared_ptr<ModelBuilder> make_lfm_builder(const BuildContext& context);+std::shared_ptr<ModelBuilder> make_lfm2_vocoder_builder(const BuildContext& context);++// Returns C * conv(B * x), retaining trailing taps from the [B, C, x] input projection.+GgufValue build_lfm_short_conv(GgufGraphContext& g,+ const GgufValue& projected,+ const GgufValue& conv_weight,+ int64_t channels,+ const std::string& state_name,+ bool batch_major = true);+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp b/src/frontends/gguf/src/builder/arch/mmproj_builder.cppindex 484fe770999..e7e80334923 100644--- a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp+++ b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp@@ -8,13 +8,17 @@#include <array>#include <cmath>#include <limits>+#include <map>#include <optional>#include <sstream>+#include <vector>#include "builder/api/metadata_store.hpp"#include "builder/gguf_graph.hpp"#include "builder/metadata_checks.hpp"#include "builder/projector_registry.hpp"+#include "lfm3_audio_generator.hpp"+#include "lfm3_projector_builder.hpp"#include "openvino/frontend/gguf/builder/graph_context.hpp"#include "projector_adapter.hpp"@@ -1194,85 +1198,129 @@ private:}};+std::vector<std::string> build_mmproj_encoders(GgufGraphContext& g,+ const BuildContext& ctx,+ ModelAdapters& adapters,+ std::map<std::string, std::string>& config) {+ std::optional<ProjectorRegistry> defaults;+ const auto& registry = ctx.projectors ? *ctx.projectors : defaults.emplace();+ std::vector<std::shared_ptr<const ProjectorDefinition>> encoders;+ for (const auto* modality : {"vision", "audio"}) {+ if (!ctx.metadata.get_bool(std::string("clip.has_") + modality + "_encoder").value_or(false))+ continue;+ const auto type = resolve_projector_type(ctx.metadata, modality);+ const auto definition = registry.find(ctx.metadata, modality, type);+ OPENVINO_ASSERT(definition, "[GGUF] unsupported ", modality, " mmproj projector '", type, "'");+ encoders.push_back(definition);+ }+ std::vector<std::string> modalities;+ config.emplace("vision.auxiliary_count", "0");+ for (const auto& definition : encoders) {+ auto result = definition->build(g);+ OPENVINO_ASSERT(result.output, "[GGUF] projector handler '", definition->id, "' returned no output");+ g.set_output(result.output, definition->modality + ".embeddings");+ for (const auto& entry : result.config) {+ OPENVINO_ASSERT(entry.first.rfind(definition->modality + ".", 0) == 0,+ "[GGUF] projector metadata must use its modality prefix");+ config[entry.first] = entry.second;+ }+ config[definition->modality + ".projector"] = definition->projector_type;+ const auto layout =+ result.genai_layout.value_or(definition->genai_layout.value_or(ProjectorLayout::Unsupported));+ config[definition->modality + ".genai_layout"] = projector_layout_name(layout);+ auto callback = result.genai_adapter.value_or(definition->genai_adapter);+ if (callback) {+ auto adapter = std::make_shared<ModelAdapter>();+ adapter->transform = std::move(callback);+ adapters[definition->modality + ".embeddings"] = std::move(adapter);+ }+ modalities.push_back(definition->modality);+ }+ return modalities;+}++void write_mmproj_config(GgufGraph& graph,+ const GgufMetadata& metadata,+ const std::map<std::string, std::string>& config) {+ const auto number = [](auto value) {+ std::ostringstream stream;+ stream.precision(std::numeric_limits<double>::max_digits10);+ stream << value;+ return stream.str();+ };+ const auto join = [&](const auto& values) {+ std::string text;+ for (size_t i = 0; i < values.size(); ++i)+ text += (i ? "," : "") + number(values[i]);+ return text;+ };+ // Preserve full metadata names. Strings serialize through the standard IR rt_info path.+ for (const auto& [key, value] : detail::MetadataAccess::get(metadata).map) {+ if (key.rfind("clip.", 0) != 0)+ continue;+ if (const auto s = metadata.get_str(key)) {+ graph.mmproj_config[key] = *s;+ } else if (const auto n = metadata.get_int(key)) {+ graph.mmproj_config[key] = std::to_string(*n);+ } else if (const auto f = metadata.get_float(key)) {+ graph.mmproj_config[key] = number(*f);+ } else if (std::holds_alternative<std::vector<std::string>>(value)) {+ // Length-prefixed strings preserve commas, quotes and empty entries.+ std::ostringstream stream;+ for (const auto& item : metadata.get_str_array(key))+ stream << item.size() << ':' << item;+ graph.mmproj_config[key] = stream.str();+ graph.mmproj_config[key + ".encoding"] = std::string("length-prefixed-strings");+ } else if (const auto integers = metadata.get_int_array(key); !integers.empty()) {+ graph.mmproj_config[key] = join(integers);+ } else {+ graph.mmproj_config[key] = join(metadata.get_float_array(key));+ }+ }+ for (const auto& entry : config)+ graph.mmproj_config[entry.first] = entry.second;+}+class MmprojBuilder : public ModelBuilder {public:explicit MmprojBuilder(const BuildContext& context) : ctx(context), g(context) {}std::shared_ptr<GgufGraph> build() override {- std::optional<ProjectorRegistry> defaults;- const auto& registry = ctx.projectors ? *ctx.projectors : defaults.emplace();- std::vector<std::shared_ptr<const ProjectorDefinition>> encoders;- for (const auto* modality : {"vision", "audio"}) {- if (!ctx.metadata.get_bool(std::string("clip.has_") + modality + "_encoder").value_or(false))- continue;- const auto type = resolve_projector_type(ctx.metadata, modality);- const auto definition = registry.find(ctx.metadata, modality, type);- OPENVINO_ASSERT(definition, "[GGUF] unsupported ", modality, " mmproj projector '", type, "'");- encoders.push_back(definition);- }- OPENVINO_ASSERT(!encoders.empty(), "[GGUF] mmproj has no encoder");ModelAdapters adapters;- std::map<std::string, std::string> branch_config;- branch_config["vision.auxiliary_count"] = "0";- for (const auto& definition : encoders) {- auto result = definition->build(g);- OPENVINO_ASSERT(result.output, "[GGUF] projector handler '", definition->id, "' returned no output");- g.set_output(result.output, definition->modality + ".embeddings");- for (const auto& entry : result.config) {- OPENVINO_ASSERT(entry.first.rfind(definition->modality + ".", 0) == 0,- "[GGUF] projector metadata must use its modality prefix");- branch_config[entry.first] = entry.second;- }- branch_config[definition->modality + ".projector"] = definition->projector_type;- const auto layout =- result.genai_layout.value_or(definition->genai_layout.value_or(ProjectorLayout::Unsupported));- branch_config[definition->modality + ".genai_layout"] = projector_layout_name(layout);- auto callback = result.genai_adapter.value_or(definition->genai_adapter);- if (callback) {- auto adapter = std::make_shared<ModelAdapter>();- adapter->transform = std::move(callback);- adapters[definition->modality + ".embeddings"] = std::move(adapter);+ std::map<std::string, std::string> config;+ const auto modalities = build_mmproj_encoders(g, ctx, adapters, config);+ const auto generation_type = resolve_projector_type(ctx.metadata, "gen.audio");+ const bool lfm3 = resolve_projector_type(ctx.metadata, "vision") == "lfm3vl" ||+ resolve_projector_type(ctx.metadata, "audio") == "lfm3a" || generation_type == "lfm3a_gen";+ const bool generation = lfm3 && ctx.metadata.get_bool("clip.has_gen_audio_encoder").value_or(false);+ OPENVINO_ASSERT(!modalities.empty() || generation, "[GGUF] mmproj has no encoder");+ if (lfm3) {+ auto contract = g.model_contract();+ if (!contract.batchable_recurrent)+ contract.batchable_recurrent = false;+ for (const auto& modality : modalities)+ contract.component_groups.try_emplace(+ modality,+ ModelComponentGroup{+ "encoder",+ {{"encoder", {{modality + ".embeddings"}, modality == "audio" ? "audio.state." : ""}}}});+ if (generation) {+ OPENVINO_ASSERT(generation_type == "lfm3a_gen", "[GGUF] unsupported LFM3 audio generation projector");+ build_lfm3_audio_generation(g);+ contract.component_groups.try_emplace(+ "audio_generation",+ ModelComponentGroup{+ "depthformer",+ {{"depthformer", {{"audio.depth_logits"}, ""}},+ {"feedback", {{"audio.feedback"}, ""}},+ {"codec", {{"audio.spectrogram", "audio.istft_window"}, "audio.codec.state."}}}});+ config["audio_generation.projector"] = "lfm3a_gen";}+ g.configure_model_contract(contract);}auto graph = g.finish();graph->model_adapters = std::move(adapters);- const auto number = [](auto value) {- std::ostringstream stream;- stream.precision(std::numeric_limits<double>::max_digits10);- stream << value;- return stream.str();- };- const auto join = [&](const auto& values) {- std::string text;- for (size_t i = 0; i < values.size(); ++i)- text += (i ? "," : "") + number(values[i]);- return text;- };- // Preserve full metadata names. Strings serialize through the standard IR rt_info path.- for (const auto& [key, value] : detail::MetadataAccess::get(ctx.metadata).map) {- if (key.rfind("clip.", 0) != 0)- continue;- if (const auto s = ctx.metadata.get_str(key)) {- graph->mmproj_config[key] = *s;- } else if (const auto n = ctx.metadata.get_int(key)) {- graph->mmproj_config[key] = std::to_string(*n);- } else if (const auto f = ctx.metadata.get_float(key)) {- graph->mmproj_config[key] = number(*f);- } else if (std::holds_alternative<std::vector<std::string>>(value)) {- // Length-prefixed strings preserve commas, quotes and empty entries.- std::ostringstream stream;- for (const auto& item : ctx.metadata.get_str_array(key))- stream << item.size() << ':' << item;- graph->mmproj_config[key] = stream.str();- graph->mmproj_config[key + ".encoding"] = std::string("length-prefixed-strings");- } else if (const auto integers = ctx.metadata.get_int_array(key); !integers.empty()) {- graph->mmproj_config[key] = join(integers);- } else {- graph->mmproj_config[key] = join(ctx.metadata.get_float_array(key));- }- }- for (const auto& entry : branch_config)- graph->mmproj_config[entry.first] = entry.second;+ write_mmproj_config(*graph, ctx.metadata, config);return graph;}@@ -1286,6 +1334,8 @@ private:ProjectorResult build_builtin_projector(GgufGraphContext& graph,const std::string& modality,const std::string& projector_type) {+ if ((modality == "vision" && projector_type == "lfm3vl") || (modality == "audio" && projector_type == "lfm3a"))+ return build_lfm3_projector(graph, modality);auto result = BuiltinProjectorBuilder(graph).build(modality, projector_type);if (modality == "vision") {const auto layout = builtin_projector_layout(projector_type);@@ -1296,7 +1346,7 @@ ProjectorResult build_builtin_projector(GgufGraphContext& graph,}std::vector<ProjectorDefinition> builtin_projectors() {- std::vector<ProjectorDefinition> definitions;+ auto definitions = lfm3_projector_definitions();for (const auto& entry : projector_catalog) {const std::string modality = entry.modality;const std::string type = entry.name;diff --git a/src/frontends/gguf/src/builder/arch/mmproj_builder.hpp b/src/frontends/gguf/src/builder/arch/mmproj_builder.hppindex ed5fbe9e1b1..0c2e5e23309 100644--- a/src/frontends/gguf/src/builder/arch/mmproj_builder.hpp+++ b/src/frontends/gguf/src/builder/arch/mmproj_builder.hpp@@ -8,4 +8,5 @@namespace ov::frontend::gguf {std::shared_ptr<ModelBuilder> make_mmproj_builder(const BuildContext& context);+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/builder/arch/projector_adapter.cpp b/src/frontends/gguf/src/builder/arch/projector_adapter.cppindex b1a269de1b9..f66b8d60158 100644--- a/src/frontends/gguf/src/builder/arch/projector_adapter.cpp+++ b/src/frontends/gguf/src/builder/arch/projector_adapter.cpp@@ -363,12 +363,17 @@ Models split_merger_layout(const std::shared_ptr<ov::Model>& model) {const auto results = model->get_results();squeeze_output(model);- if (results.size() > 1) {- ov::OutputVector levels;- for (size_t i = 1; i < results.size(); ++i) {+ ov::OutputVector levels;+ for (size_t i = 1; i < results.size(); ++i) {+ const auto& names = results[i]->output(0).get_names();+ if (std::any_of(names.begin(), names.end(), [](const std::string& name) {+ return name.rfind("deepstack_features.", 0) == 0;+ })) {levels.push_back(results[i]->input_value(0));model->remove_result(results[i]);}+ }+ if (!levels.empty()) {auto deepstack = std::make_shared<v0::Concat>(levels, 0);deepstack->output(0).get_tensor().set_names({"deepstack_feature_lists"});auto deepstack_result = std::make_shared<v0::Result>(deepstack);diff --git a/src/frontends/gguf/src/builder/arch_registry.cpp b/src/frontends/gguf/src/builder/arch_registry.cppindex 616306f78bf..706ab0a4b73 100644--- a/src/frontends/gguf/src/builder/arch_registry.cpp+++ b/src/frontends/gguf/src/builder/arch_registry.cpp@@ -8,7 +8,7 @@#include <utility>#include "builder/arch/dspark_builder.hpp"-#include "builder/arch/lfm2_builder.hpp"+#include "builder/arch/lfm_builder.hpp"#include "builder/arch/mamba_builder.hpp"#include "builder/arch/mmproj_builder.hpp"#include "openvino/core/except.hpp"@@ -41,7 +41,8 @@ const ArchitectureEntry architectures[] = {make_mmproj_builder,[](const GgufMetadata& meta) {return meta.has("clip.projector_type") || meta.has("clip.vision.projector_type") ||- meta.has("clip.audio.projector_type");+ meta.has("clip.audio.projector_type") || meta.has("clip.gen.audio.projector_type") ||+ meta.get_bool("clip.has_gen_audio_encoder").value_or(false);},"clip.mmproj"},{"deepseek2-ocr", RopeMode::Neox},@@ -58,13 +59,14 @@ const ArchitectureEntry architectures[] = {{"hunyuan-dense", RopeMode::Neox},{"hunyuan-moe", RopeMode::Neox},{"jais2", RopeMode::Neox},- {"lfm2", make_lfm2_builder},+ {"lfm2", make_lfm_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},+ {"lfm2moe", make_lfm_builder},+ {"lfm3", make_lfm_builder},{"llama", RopeMode::Normal},{"llama-embed", RopeMode::Normal},{"maincoder", RopeMode::Normal},diff --git a/src/frontends/gguf/src/builder/blocks/attention.cpp b/src/frontends/gguf/src/builder/blocks/attention.cppindex e1fdf03db9c..32f859cfd6c 100644--- a/src/frontends/gguf/src/builder/blocks/attention.cpp+++ b/src/frontends/gguf/src/builder/blocks/attention.cpp@@ -312,21 +312,51 @@ std::string attention(GraphEmitter& e,{{"activation_rank", rank3_gate ? 3 : 4}});}gate = e.add_op("GGML_UNARY_OP_SIGMOID", p + "attn_gate_sig", {gate});- const auto gate_attention =- rank3_gate ? e.add_op("GGML_OP_RESHAPE",- p + "kqv_gate_input",- {attn_2d},- 6,- {{"reshape_target", std::vector<int64_t>{0, -1, q_width}}, {"special_zero", true}})- : attn_2d;- const auto gated = e.add_op("GGML_OP_MUL", p + "kqv_gated", {gate_attention, gate});- attn_2d = rank3_gate- ? e.add_op("GGML_OP_RESHAPE",- p + "kqv_gated_4d",- {gated},- 6,- {{"reshape_target", std::vector<int64_t>{0, 1, -1, q_width}}, {"special_zero", true}})- : gated;+ auto gate_width = static_cast<size_t>(q_width);+ if (!cfg.interleaved_q_gate) {+ const auto& gate_shape = e.weight_tensor(p + "attn_gate.weight").get_shape();+ OPENVINO_ASSERT(gate_shape.size() == 2 && (gate_shape[0] == static_cast<size_t>(n_head_l) ||+ gate_shape[0] == static_cast<size_t>(q_width)),+ "[GGUF] attention gate must have one value per head or per channel");+ gate_width = gate_shape[0];+ }+ if (gate_width == static_cast<size_t>(n_head_l) && head_size_l > 1) {+ auto heads = e.add_op(+ "GGML_OP_RESHAPE",+ p + "kqv_heads",+ {attn_2d},+ 6,+ {{"reshape_target", std::vector<int64_t>{0, -1, n_head_l, head_size_l}}, {"special_zero", true}});+ gate = e.add_op("GGML_OP_RESHAPE",+ p + "attn_gate_heads",+ {gate},+ 6,+ {{"reshape_target", std::vector<int64_t>{0, -1, n_head_l, 1}}, {"special_zero", true}});+ heads = e.add_op("GGML_OP_MUL", p + "kqv_gated_heads", {heads, gate});+ attn_2d = e.add_op("GGML_OP_RESHAPE",+ p + "kqv_gated",+ {heads},+ 6,+ {{"reshape_target", std::vector<int64_t>{0, 1, -1, q_width}}, {"special_zero", true}});+ } else {+ const auto gate_attention =+ rank3_gate+ ? e.add_op("GGML_OP_RESHAPE",+ p + "kqv_gate_input",+ {attn_2d},+ 6,+ {{"reshape_target", std::vector<int64_t>{0, -1, q_width}}, {"special_zero", true}})+ : attn_2d;+ const auto gated = e.add_op("GGML_OP_MUL", p + "kqv_gated", {gate_attention, gate});+ attn_2d =+ rank3_gate+ ? e.add_op("GGML_OP_RESHAPE",+ p + "kqv_gated_4d",+ {gated},+ 6,+ {{"reshape_target", std::vector<int64_t>{0, 1, -1, q_width}}, {"special_zero", true}})+ : gated;+ }}// output projection (+ optional bias)diff --git a/src/frontends/gguf/src/builder/legacy_model_contract.hpp b/src/frontends/gguf/src/builder/legacy_model_contract.hppindex 31add2be2a0..9af71ba5bbd 100644--- a/src/frontends/gguf/src/builder/legacy_model_contract.hpp+++ b/src/frontends/gguf/src/builder/legacy_model_contract.hpp@@ -210,9 +210,19 @@ inline LegacyEmbeddingBoundaries resolve_legacy_embedding_boundaries(const std::return boundaries;}+inline bool resolve_legacy_genai_adaptation(const std::shared_ptr<ov::Model>& model) {+ for (const auto& parameter : model->get_parameters()) {+ if (parameter->get_friendly_name() == "dspark_ctx_feat" ||+ parameter->output(0).get_names().count("dspark_ctx_feat"))+ return false;+ }+ return true;+}+inline ModelContract resolve_legacy_model_contract(const std::shared_ptr<ov::Model>& model,std::optional<int64_t> embedding_width) {ModelContract contract;+ contract.supports_genai_adaptation = resolve_legacy_genai_adaptation(model);if (!model->has_rt_info({"gguf_architecture"}))return contract;const auto architecture = model->get_rt_info<std::string>({"gguf_architecture"});diff --git a/src/frontends/gguf/src/model_contract.hpp b/src/frontends/gguf/src/model_contract.hppindex 6e33b220d51..9cc78f05126 100644--- a/src/frontends/gguf/src/model_contract.hpp+++ b/src/frontends/gguf/src/model_contract.hpp@@ -4,6 +4,9 @@#pragma once+#include <unordered_set>+#include <utility>+#include "builder/legacy_model_contract.hpp"#include "openvino/core/except.hpp"#include "openvino/core/model.hpp"@@ -11,7 +14,28 @@namespace ov::frontend::gguf {+inline void validate_model_contract(const ModelContract& contract) {+ const auto validate_outputs = [](const std::vector<std::string>& outputs) {+ std::unordered_set<std::string> names;+ for (const auto& name : outputs)+ OPENVINO_ASSERT(!name.empty() && names.insert(name).second,+ "[GGUF] model contract output names must be nonempty and unique");+ };+ validate_outputs(contract.sequence_outputs);+ for (const auto& [name, group] : contract.component_groups) {+ OPENVINO_ASSERT(!name.empty(), "[GGUF] model contract component group name must be nonempty");+ OPENVINO_ASSERT(group.models.count(group.primary),+ "[GGUF] model contract component group primary must name a component");+ for (const auto& [component_name, component] : group.models) {+ OPENVINO_ASSERT(!component_name.empty(), "[GGUF] model contract component name must be nonempty");+ OPENVINO_ASSERT(!component.outputs.empty(), "[GGUF] model contract component outputs must be nonempty");+ validate_outputs(component.outputs);+ }+ }+}+inline void write_model_contract(const std::shared_ptr<ov::Model>& model, const ModelContract& contract) {+ validate_model_contract(contract);std::string image_attention;switch (contract.image_attention) {case ModelContract::ImageAttentionMode::CAUSAL:@@ -29,15 +53,39 @@ inline void write_model_contract(const std::shared_ptr<ov::Model>& model, constconst std::string recurrent = !contract.batchable_recurrent ? "auto": *contract.batchable_recurrent ? "true": "false";+ ov::AnyMap component_groups;+ for (const auto& [name, group] : contract.component_groups) {+ ov::AnyMap models;+ for (const auto& [component_name, component] : group.models)+ models.emplace(component_name,+ ov::AnyMap{{"outputs", component.outputs}, {"state_prefix", component.state_prefix}});+ component_groups.emplace(name, ov::AnyMap{{"primary", group.primary}, {"models", models}});+ }+ const bool supports_genai = contract.supports_genai_adaptation ? *contract.supports_genai_adaptation+ : resolve_legacy_genai_adaptation(model);model->get_rt_info()["gguf_model_contract"] =- ov::AnyMap{{"batchable_recurrent", recurrent}, {"image_attention", image_attention}};+ ov::AnyMap{{"batchable_recurrent", recurrent},+ {"image_attention", image_attention},+ {"sequence_outputs", contract.sequence_outputs},+ {"component_groups", component_groups},+ {"supports_genai_adaptation", std::string(supports_genai ? "true" : "false")}};}inline ModelContract read_model_contract(const std::shared_ptr<ov::Model>& model,std::optional<int64_t> embedding_width = std::nullopt) {- if (!model->has_rt_info({"gguf_model_contract"}))- return resolve_legacy_model_contract(model, embedding_width);+ if (!model->has_rt_info({"gguf_model_contract"})) {+ auto contract = resolve_legacy_model_contract(model, embedding_width);+ validate_model_contract(contract);+ return contract;+ }ModelContract contract;+ if (model->has_rt_info({"gguf_model_contract", "supports_genai_adaptation"})) {+ const auto value = model->get_rt_info<std::string>({"gguf_model_contract", "supports_genai_adaptation"});+ OPENVINO_ASSERT(value == "true" || value == "false", "[GGUF] invalid GenAI adaptation contract");+ contract.supports_genai_adaptation = value == "true";+ } else {+ contract.supports_genai_adaptation = resolve_legacy_genai_adaptation(model);+ }if (model->has_rt_info({"gguf_model_contract", "batchable_recurrent"})) {const auto value = model->get_rt_info<std::string>({"gguf_model_contract", "batchable_recurrent"});OPENVINO_ASSERT(value == "true" || value == "false" || value == "auto",@@ -55,6 +103,29 @@ inline ModelContract read_model_contract(const std::shared_ptr<ov::Model>& modelOPENVINO_ASSERT(value == "causal", "[GGUF] invalid image attention contract");}}+ if (model->has_rt_info({"gguf_model_contract", "sequence_outputs"}))+ contract.sequence_outputs =+ model->get_rt_info<std::vector<std::string>>({"gguf_model_contract", "sequence_outputs"});+ if (model->has_rt_info({"gguf_model_contract", "component_groups"})) {+ const auto groups = model->get_rt_info<ov::AnyMap>({"gguf_model_contract", "component_groups"});+ for (const auto& [name, value] : groups) {+ const auto& group = value.as<ov::AnyMap>();+ OPENVINO_ASSERT(group.count("primary") && group.count("models"),+ "[GGUF] model contract component group requires primary and models");+ ModelComponentGroup components;+ components.primary = group.at("primary").as<std::string>();+ for (const auto& [component_name, component_value] : group.at("models").as<ov::AnyMap>()) {+ const auto& component = component_value.as<ov::AnyMap>();+ OPENVINO_ASSERT(component.count("outputs") && component.count("state_prefix"),+ "[GGUF] model contract component requires outputs and state_prefix");+ components.models.emplace(component_name,+ ModelComponentContract{component.at("outputs").as<std::vector<std::string>>(),+ component.at("state_prefix").as<std::string>()});+ }+ contract.component_groups.emplace(name, std::move(components));+ }+ }+ validate_model_contract(contract);return contract;}diff --git a/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cppindex 971eaa9890e..d4d9fe8ae13 100644--- a/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp+++ b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp@@ -4,12 +4,18 @@#include "openvino/frontend/gguf/adapt_mmproj_to_genai.hpp"+#include <algorithm>#include <stdexcept>#include <unordered_set>+#include <vector>#include "builder/arch/projector_adapter.hpp"#include "model_adapter_attribute.hpp"+#include "model_contract.hpp"+#include "openvino/frontend/gguf/make_stateful.hpp"+#include "openvino/op/assign.hpp"#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"#include "openvino/op/result.hpp"#include "openvino/op/split.hpp"#include "openvino/op/squeeze.hpp"@@ -20,6 +26,111 @@ namespace ov::frontend::gguf::pass {namespace {using Models = std::map<std::string, std::shared_ptr<ov::Model>>;+struct ComponentStateSelection {+ ov::ResultVector results;+ std::unordered_set<std::string> parameters;+};++ComponentStateSelection retain_component_states(const std::shared_ptr<ov::Model>& model, const std::string& prefix) {+ ComponentStateSelection retained;+ auto& info = model->get_rt_info();+ const auto key = gguf_recurrent_states_key();+ if (const auto it = info.find(key); it != info.end()) {+ const auto pairs = it->second.as<std::vector<std::string>>();+ OPENVINO_ASSERT(pairs.size() % 2 == 0, "[GGUF] invalid component state declarations");+ std::vector<std::string> selected;+ for (size_t i = 0; i < pairs.size(); i += 2) {+ if (prefix.empty() || pairs[i].rfind(prefix, 0) != 0)+ continue;+ selected.insert(selected.end(), {pairs[i], pairs[i + 1]});+ retained.parameters.insert(pairs[i]);+ bool found = false;+ for (const auto& result : model->get_results()) {+ if (result->get_friendly_name() == pairs[i + 1] ||+ result->input_value(0).get_names().count(pairs[i + 1])) {+ retained.results.push_back(result);+ found = true;+ }+ }+ OPENVINO_ASSERT(found || !find_parameter(model, pairs[i]),+ "[GGUF] missing component state output ",+ pairs[i + 1]);+ }+ info[key] = std::move(selected);+ }+ const auto sinks = model->get_sinks();+ for (const auto& sink : sinks) {+ const auto assign = ov::as_type_ptr<ov::op::util::AssignBase>(sink);+ if (assign && (prefix.empty() || assign->get_variable_id().rfind(prefix, 0) != 0))+ model->remove_sink(sink);+ }+ const auto variables = model->get_variables();+ for (const auto& variable : variables) {+ if (prefix.empty() || variable->get_info().variable_id.rfind(prefix, 0) != 0)+ model->remove_variable(variable);+ }+ return retained;+}++ComponentStateSelection select_component(const std::shared_ptr<ov::Model>& model,+ const ModelComponentContract& contract) {+ auto live = std::make_shared<std::unordered_set<const ov::Node*>>();+ SnapshotLiveParameters(live).run_on_model(model);+ auto retained = retain_component_states(model, contract.state_prefix);+ std::unordered_set<std::string> found;+ const auto results = model->get_results();+ for (const auto& result : results) {+ bool selected = false;+ for (const auto& name : contract.outputs) {+ if (result->input_value(0).get_names().count(name) || result->get_friendly_name() == name) {+ selected = true;+ found.insert(name);+ if (!result->output(0).get_names().count(name))+ result->output(0).add_names({name});+ }+ }+ if (!selected && std::find(retained.results.begin(), retained.results.end(), result) == retained.results.end())+ model->remove_result(result);+ }+ for (const auto& name : contract.outputs)+ OPENVINO_ASSERT(found.count(name), "[GGUF] missing declared component output ", name);+ PruneParametersOrphanedSince(live).run_on_model(model);+ model->validate_nodes_and_infer_types();+ return retained;+}++Models split_components(const std::shared_ptr<ov::Model>& model, const ModelComponentGroup& group) {+ Models models;+ for (const auto& [name, contract] : group.models) {+ auto branch = model->clone();+ select_component(branch, contract);+ branch->set_friendly_name(name);+ remove_model_adapters(branch);+ models.emplace(name, std::move(branch));+ }+ return models;+}++void replace_model(const std::shared_ptr<ov::Model>& model, const std::shared_ptr<ov::Model>& adapted) {+ const auto results = model->get_results();+ const auto parameters = model->get_parameters();+ const auto sinks = model->get_sinks();+ const auto variables = model->get_variables();+ for (const auto& result : results)+ model->remove_result(result);+ for (const auto& parameter : parameters)+ model->remove_parameter(parameter);+ for (const auto& sink : sinks)+ model->remove_sink(sink);+ for (const auto& variable : variables)+ model->remove_variable(variable);+ model->add_parameters(adapted->get_parameters());+ model->add_results(adapted->get_results());+ model->add_variables(adapted->get_variables());+ model->add_sinks(adapted->get_sinks());+ model->get_rt_info() = adapted->get_rt_info();+}+std::shared_ptr<ov::op::v0::Result> embedding_result(const std::shared_ptr<ov::Model>& model,AdaptMmprojToGenAI::Modality modality) {const std::string prefix = modality == AdaptMmprojToGenAI::Modality::VISION ? "vision." : "audio.";@@ -47,6 +158,27 @@ ModelAdapterResult adapt_mmproj(const std::shared_ptr<ov::Model>& model,require_projector_layout(model);auto live_before = std::make_shared<std::unordered_set<const ov::Node*>>();SnapshotLiveParameters(live_before).run_on_model(model);+ ComponentStateSelection states;+ ov::ResultVector retained_results;+ const auto contract = read_model_contract(model);+ if (const auto group = contract.component_groups.find(modality == Modality::VISION ? "vision" : "audio");+ group != contract.component_groups.end()) {+ states = select_component(model, group->second.models.at(group->second.primary));+ embedding_result(model, modality);+ for (const auto& result : model->get_results()) {+ if (result != selected) {+ const auto value = result->input_value(0);+ if (ov::as_type_ptr<ov::op::v0::Parameter>(value.get_node_shared_ptr())) {+ // Separate passthrough output names from renamed input names during cloning.+ auto passthrough = std::make_shared<ov::op::v0::Convert>(value, value.get_element_type());+ passthrough->output(0).set_names(result->output(0).get_names());+ result->set_argument(0, passthrough);+ result->validate_and_infer_types();+ }+ retained_results.push_back(result);+ }+ }+ }const auto results = model->get_results();for (const auto& result : results)model->remove_result(result);@@ -68,10 +200,11 @@ ModelAdapterResult adapt_mmproj(const std::shared_ptr<ov::Model>& model,embeddings->output(0).set_names({modality == Modality::VISION ? "image_features" : "audio_features"});model->add_results({std::make_shared<ov::op::v0::Result>(embeddings)});}+ model->add_results(retained_results);PruneParametersOrphanedSince(live_before).run_on_model(model);for (const auto& p : model->get_parameters()) {const auto& name = p->get_friendly_name();- if (name.rfind(prefix, 0) == 0)+ if (name.rfind(prefix, 0) == 0 && !states.parameters.count(name))name_output(p, name.substr(prefix.size()));}model->validate_nodes_and_infer_types();@@ -87,9 +220,18 @@ ModelAdapterResult adapt_mmproj(const std::shared_ptr<ov::Model>& model,bool AdaptMmprojToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {m_vision_models.clear();- if (m_layout == Layout::EMBEDDINGS && !get_model_adapter(embedding_result(model, m_modality))) {- adapt_mmproj(model, m_modality, m_layout);- remove_model_adapters(model);+ m_audio_generation_models.clear();+ if (m_modality == Modality::AUDIO_GENERATION) {+ OPENVINO_ASSERT(m_layout == Layout::EMBEDDINGS, "[GGUF] AUDIO_GENERATION requires EMBEDDINGS layout");+ const auto contract = read_model_contract(model);+ const auto group = contract.component_groups.find("audio_generation");+ OPENVINO_ASSERT(group != contract.component_groups.end(),+ "[GGUF] model declares no audio-generation component group");+ auto models = split_components(model, group->second);+ const auto primary = models.at(group->second.primary);+ replace_model(model, primary);+ models[group->second.primary] = model;+ m_audio_generation_models = std::move(models);return true;}// Callbacks and layout construction may fail after rewiring the independent clone.@@ -109,23 +251,7 @@ bool AdaptMmprojToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {remove_model_adapters(adapted);for (const auto& [name, encoder] : vision_models)remove_model_adapters(encoder);- const auto results = model->get_results();- const auto parameters = model->get_parameters();- const auto sinks = model->get_sinks();- const auto variables = model->get_variables();- for (const auto& result : results)- model->remove_result(result);- for (const auto& parameter : parameters)- model->remove_parameter(parameter);- for (const auto& sink : sinks)- model->remove_sink(sink);- for (const auto& variable : variables)- model->remove_variable(variable);- model->add_parameters(adapted->get_parameters());- model->add_results(adapted->get_results());- model->add_sinks(adapted->get_sinks());- model->add_variables(adapted->get_variables());- model->get_rt_info() = adapted->get_rt_info();+ replace_model(model, adapted);for (auto& [name, encoder] : vision_models) {if (encoder == adapted)encoder = model;diff --git a/src/frontends/gguf/src/pass/adapt_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_to_genai.cppindex 9f41500827e..f183d0c3e97 100644--- a/src/frontends/gguf/src/pass/adapt_to_genai.cpp+++ b/src/frontends/gguf/src/pass/adapt_to_genai.cpp@@ -6,6 +6,7 @@#include <algorithm>#include <memory>+#include <unordered_set>#include <vector>#include "model_contract.hpp"@@ -64,6 +65,11 @@ using std::make_shared;// f16 lowest, matches genai's causal-mask "-inf" fill.constexpr float NEG_INF = -65504.0f;+bool has_output_name(const std::shared_ptr<ov::op::v0::Result>& result, const std::string& name) {+ return result->get_friendly_name() == name || result->input_value(0).get_names().count(name) ||+ result->output(0).get_names().count(name);+}+// translate_get_rows's embedding-table lookup restores ggml's rank-4 form with a fixed// Unsqueeze(axis=0), pinning the residual stream's leading axis to a literal 1 regardless of// backend -- correct for SDPA, but wrong once SDPAToPagedAttention rewrites input_ids to rank-1@@ -213,9 +219,6 @@ ov::Output<ov::Node> pad_media_placeholders(const ov::Model& model, const ov::Oubool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {using namespace ov::op;- if (find_parameter(model, "dspark_ctx_feat"))- return false;-for (const auto& output : model->outputs()) {if (output.get_names().count("embeddings"))return false;@@ -230,6 +233,19 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {const bool has_recurrent_states = model->get_rt_info().count(gguf_recurrent_states_key()) != 0;const auto operations = model->get_ops();auto contract = read_model_contract(model);+ if (!contract.supports_genai_adaptation.value_or(true))+ return false;+ for (const auto& name : contract.sequence_outputs) {+ const auto result =+ std::find_if(model->get_results().begin(), model->get_results().end(), [&](const auto& output) {+ return has_output_name(output, name);+ });+ OPENVINO_ASSERT(result != model->get_results().end(), "[GGUF] missing declared sequence output ", name);+ const auto rank = (*result)->input_value(0).get_partial_shape().rank();+ OPENVINO_ASSERT(rank.is_static() && (rank.get_length() == 3 || rank.get_length() == 4),+ "[GGUF] sequence output requires rank 3 or 4: ",+ name);+ }const auto has_gated_delta_net = [&] {return std::any_of(operations.begin(), operations.end(), [](const auto& node) {return ov::is_type<internal::GatedDeltaNet>(node);@@ -739,8 +755,51 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {auto new_result = make_shared<v0::Result>(logits);new_result->set_friendly_name("logits");- model->add_results({new_result});- model->remove_result(old_result);+ ov::ResultVector outputs{new_result};+ const auto old_results = model->get_results();+ for (const auto& result : old_results) {+ model->remove_result(result);+ if (result != old_result)+ outputs.push_back(result);+ }+ model->add_results(outputs);++ std::unordered_set<std::string> normalized;+ for (const auto& result : model->get_results()) {+ const auto source = result->input_value(0);+ const auto selected =+ std::find_if(contract.sequence_outputs.begin(), contract.sequence_outputs.end(), [&](const auto& name) {+ return has_output_name(result, name);+ });+ if (selected == contract.sequence_outputs.end())+ continue;+ auto names = source.get_names();+ const auto& result_names = result->output(0).get_names();+ names.insert(result_names.begin(), result_names.end());+ for (const auto& name : contract.sequence_outputs) {+ if (has_output_name(result, name))+ names.insert(name);+ }+ const auto shape = source.get_partial_shape();+ OPENVINO_ASSERT(shape.rank().is_static() && (shape.size() == 3 || shape.size() == 4),+ "[GGUF] sequence output requires rank 3 or 4: ",+ *selected);+ auto width = get_dimensions(source, {-1});+ auto reshaped = make_shared<v1::Reshape>(+ source,+ make_shared<v0::Concat>(+ ov::OutputVector{batch_len, v0::Constant::create(ov::element::i64, {1}, {-1}), width},+ 0),+ false);+ name_output(reshaped, *selected);+ reshaped->output(0).set_names(names);+ result->input(0).replace_source_output(reshaped);+ result->validate_and_infer_types();+ result->output(0).add_names(names);+ normalized.insert(names.begin(), names.end());+ }+ for (const auto& name : contract.sequence_outputs)+ OPENVINO_ASSERT(normalized.count(name), "[GGUF] missing declared sequence output ", name);// Swap the input list to the genai contract. beam_idx is kept as-is; every other old// gguf Parameter has had its output rewired (consumers now read the derived subgraph),diff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txtindex cc13ef77ad2..eae75509793 100644--- a/src/frontends/gguf/tests/CMakeLists.txt+++ b/src/frontends/gguf/tests/CMakeLists.txt@@ -51,7 +51,10 @@ 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/lfm_builder.cpp"+ "${FE_SRC_DIR}/builder/arch/lfm2_vocoder_builder.cpp"+ "${FE_SRC_DIR}/builder/arch/lfm3_projector_builder.cpp"+ "${FE_SRC_DIR}/builder/arch/lfm3_audio_generator.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"@@ -110,6 +113,8 @@ set(FRONTEND_SRCS)set(TEST_SRCS+ "${CMAKE_CURRENT_SOURCE_DIR}/test_lfm3_media.cpp"+ "${CMAKE_CURRENT_SOURCE_DIR}/test_lfm3_speech.cpp""${CMAKE_CURRENT_SOURCE_DIR}/test_mmproj.cpp""${CMAKE_CURRENT_SOURCE_DIR}/test_adapt_to_genai.cpp""${CMAKE_CURRENT_SOURCE_DIR}/test_arch_conversion.cpp"diff --git a/src/frontends/gguf/tests/gen_arch_accuracy.py b/src/frontends/gguf/tests/gen_arch_accuracy.pyindex cb1b9518359..163e9aff442 100644--- a/src/frontends/gguf/tests/gen_arch_accuracy.py+++ b/src/frontends/gguf/tests/gen_arch_accuracy.py@@ -27,6 +27,10 @@ CASES = {"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},+ "lfm3": {"tied": True, "post": True},+ "lfm3-plain": {"architecture": "lfm3"},+ "lfm3-attention-first": {"architecture": "lfm3", "attention_first": True, "fused": True, "post": True},+ "lfm3-wide-query": {"architecture": "lfm3", "heads": 6, "post": True},"qwen35": {}, "qwen35moe": {},"qwen35-zero-scales": {"architecture": "qwen35", "zero_scales": True},"qwen35moe-fused": {"architecture": "qwen35moe", "fused_experts": True},@@ -303,9 +307,11 @@ def write_gemma4_model(path, opts):finish(w)-def write_lfm2_model(path, arch, opts):+def write_lfm_model(path, arch, opts):w = gguf.GGUFWriter(path, arch)d, heads, kv, head, ff, vocab = 32, 4, 2, 8, 48, 32+ heads = opts.get("heads", heads)+ q_width = heads * headkernel = 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)@@ -322,6 +328,10 @@ def write_lfm2_model(path, arch, opts):w.add_uint32(arch + ".shortconv.l_cache", kernel)w.add_vocab_size(vocab)w.add_tokenizer_model("none")+ if arch == "lfm3":+ w.add_sliding_window(2)+ w.add_sliding_window_pattern([i == kv_layers.index(kv) for i in range(len(kv_layers))])+ w.add_float32(arch + ".rope.freq_base_swa", 10000.)if opts.get("swa"):w.add_sliding_window(2)if opts.get("moe"):@@ -334,22 +344,29 @@ def write_lfm2_model(path, arch, opts):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)+ tensor("output_norm.weight" if arch == "lfm3" else "token_embd_norm.weight", (d,), True)+ if arch == "lfm3":+ w.add_tensor("rope_freqs.weight", np.array([1.] * (head // 4) + [1e30] * (head // 4), dtype=np.float32))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 arch == "lfm3" and opts.get("post"):+ tensor(p + "post_attention_norm.weight", (d,), True)+ tensor(p + "post_ffw_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)):+ for name, width in (("q", q_width), ("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))+ tensor(p + "attn_output.weight", (d, q_width))+ if arch == "lfm3":+ tensor(p + "attn_gate.weight", (heads, d))else:tensor(p + "shortconv.in_proj.weight", (3 * d, d))tensor(p + "shortconv.conv.weight", (d, kernel))@@ -367,8 +384,8 @@ def write_lfm2_model(path, arch, opts):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 in ("lfm2", "lfm2moe", "lfm3"):+ return write_lfm_model(path, arch, opts)if arch == "gemma4":return write_gemma4_model(path, opts)if arch in ("qwen35", "qwen35moe"):@@ -516,6 +533,7 @@ def main():parser.add_argument("--embedding-oracle")parser.add_argument("--out-dir", type=Path, default=Path(__file__).parent / "test_data/arch_accuracy")parser.add_argument("--architectures", nargs="+", default=list(CASES))+ parser.add_argument("--header-dir", type=Path, help="also write header-only conversion fixtures")args = parser.parse_args()if not args.embedding_oracle and any(CASES[arch].get("embedding_output") for arch in args.architectures):parser.error("--embedding-oracle is required to generate embedding fixtures")@@ -541,6 +559,16 @@ def main():logits = np.fromfile(reference, dtype="<f4", offset=4).reshape(3, vocab)assert np.isfinite(logits).all() and np.linalg.norm(logits) > 0save_npz(args.out_dir / f"{arch}.npz", {"model": np.fromfile(model, dtype=np.uint8), "logits": logits})+ if args.header_dir:+ from gen_arch_fixtures import strip_to_header+ args.header_dir.mkdir(parents=True, exist_ok=True)+ filename = f"{arch}.gguf.hdr"+ _, data_bytes, _ = strip_to_header(model, args.header_dir / filename)+ manifest = args.header_dir / "manifest.txt"+ lines = manifest.read_text().splitlines() if manifest.exists() else []+ lines = [line for line in lines if not line.startswith(filename + " ")]+ lines.append(f"{filename} {data_bytes} convert")+ manifest.write_text("\n".join(lines) + "\n")print(f"{arch}: {model.stat().st_size} bytes, reference logits {logits.shape}", flush=True)diff --git a/src/frontends/gguf/tests/gen_arch_fixtures.py b/src/frontends/gguf/tests/gen_arch_fixtures.pyindex 0150810b759..1512c9b2c28 100644--- a/src/frontends/gguf/tests/gen_arch_fixtures.py+++ b/src/frontends/gguf/tests/gen_arch_fixtures.py@@ -190,6 +190,13 @@ def main():models = os.path.join(work, "models")os.makedirs(models, exist_ok=True)files = run_generator(exe, models)+ import numpy as np++ lfm3_fixture = os.path.join(os.path.dirname(__file__), "test_data", "arch_accuracy", "lfm3.npz")+ with np.load(lfm3_fixture) as fixture:+ lfm3_model = os.path.join(models, "lfm3.gguf")+ fixture["model"].tofile(lfm3_model)+ files.append(lfm3_model)print(f"generated {len(files)} models in {models}")out_dir = os.path.abspath(args.out_dir)diff --git a/src/frontends/gguf/tests/gen_lfm2_speech_accuracy.py b/src/frontends/gguf/tests/gen_lfm2_speech_accuracy.pyindex d7032a7542c..d30507a94e4 100644--- a/src/frontends/gguf/tests/gen_lfm2_speech_accuracy.py+++ b/src/frontends/gguf/tests/gen_lfm2_speech_accuracy.py@@ -13,7 +13,7 @@ import ggufimport numpy as npimport torchfrom transformers import Lfm2Config, Lfm2Model-from gen_arch_accuracy import write_lfm2_model+from gen_arch_accuracy import write_lfm_modelfrom mmproj_fixtures import finish, save_npz@@ -87,7 +87,7 @@ def main():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})+ write_lfm_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) * .08diff --git a/src/frontends/gguf/tests/gen_lfm3_media_fixtures.py b/src/frontends/gguf/tests/gen_lfm3_media_fixtures.pynew file mode 100644index 00000000000..7c1708e53d5--- /dev/null+++ b/src/frontends/gguf/tests/gen_lfm3_media_fixtures.py@@ -0,0 +1,229 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++"""Generate LFM3 media expectations with pinned libmtmd CPU, without OpenVINO."""+import argparse+import hashlib+import json+import subprocess+import tempfile+from pathlib import Path++import gguf+import numpy as np++from mmproj_fixtures import TensorWriter, finish, save_npz++REVISION = "604cc430239c76ff636c443e3400bf552b750421"+++def write_model(path, modality, projection_width=12):+ writer = gguf.GGUFWriter(path, "clip")+ writer.add_bool(f"clip.has_{modality}_encoder", True)+ writer.add_string(f"clip.{modality}.projector_type", "lfm3vl" if modality == "vision" else "lfm3a")+ writer.add_bool("clip.use_silu", True)+ key = f"clip.{modality}."+ for name, value in {"embedding_length": 16, "feed_forward_length": 24, "block_count": 2,+ "projection_dim": projection_width, "attention.head_count": 4, "attention.head_count_kv": 2}.items():+ writer.add_uint32(key + name, value)+ writer.add_float32(key + "attention.layer_norm_epsilon", 1e-5)+ tensor = TensorWriter(writer, np.random.default_rng(20261028))+ prefix = "v." if modality == "vision" else "a."+ for layer in range(2):+ p = f"{prefix}blk.{layer}."+ tensor.norm(p + "ln1", 16, False)+ tensor.norm(p + "ln2", 16, False)+ if layer == 0:+ if modality == "vision":+ tensor.linear(p + "conv2d_in_proj", 16, 48, False)+ tensor.tensor(p + "conv2d_spatial.weight", (16, 1, 3, 3))+ tensor.linear(p + "conv2d_out_proj", 16, 16, False)+ else:+ tensor.linear(p + "conv_pw1", 16, 48, False)+ tensor.tensor(p + "conv_dw.weight", (16, 3))+ tensor.linear(p + "conv_pw2", 16, 16, False)+ else:+ tensor.linear(p + "attn_q", 16, 16, False)+ tensor.linear(p + "attn_k", 16, 8, False)+ tensor.linear(p + "attn_v", 16, 8, False)+ tensor.linear(p + "attn_out", 16, 16, False)+ tensor.norm(p + "attn_q_norm", 4, False)+ tensor.norm(p + "attn_k_norm", 4, False)+ tensor.linear(p + "ffn_gate", 16, 24, False)+ tensor.linear(p + "ffn_up", 16, 24, False)+ tensor.linear(p + "ffn_down", 24, 16, False)+ if modality == "vision":+ writer.add_uint32(key + "image_size", 32)+ writer.add_uint32(key + "patch_size", 16)+ writer.add_uint32(key + "spatial_merge_size", 2)+ writer.add_uint32(key + "image_min_pixels", 1024)+ writer.add_uint32(key + "image_max_pixels", 65536)+ writer.add_string(key + "image_resize_algo", "bicubic")+ writer.add_array(key + "image_mean", [0.5, 0.5, 0.5])+ writer.add_array(key + "image_std", [0.5, 0.5, 0.5])+ tensor.tensor("v.patch_embd.weight", (16, 3, 16, 16))+ tensor.tensor("v.patch_embd.weight.1", (16, 3, 16, 16))+ tensor.norm("v.embedding_norm", 16, False)+ tensor.norm("mm.input_norm", 16)+ tensor.linear("mm.0", 64, 24)+ tensor.linear("mm.2", 24, projection_width)+ else:+ writer.add_uint32(key + "num_mel_bins", 128)+ writer.add_uint32(key + "window_size", 4)+ for layer, shape in {0: (2, 1, 3, 3), 2: (2, 1, 3, 3), 3: (2, 2, 1, 1),+ 5: (2, 1, 3, 3), 6: (2, 2, 1, 1)}.items():+ tensor.tensor(f"a.conv1d.{layer}.weight", shape)+ tensor.tensor(f"a.conv1d.{layer}.bias", (2, 1, 1))+ tensor.linear("a.pre_encode.out", 32, 16)+ tensor.norm("a.post_ln", 16, False)+ tensor.norm("mm.a.mlp.0", 16)+ tensor.linear("mm.a.mlp.1", 16, 24)+ tensor.linear("mm.a.mlp.3", 24, projection_width)+ finish(writer)+++def generate(oracle, directory, modality, streaming, projection_width=12):+ arrays = {}+ rng = np.random.default_rng(1731)+ with tempfile.TemporaryDirectory() as scratch:+ scratch = Path(scratch)+ model = scratch / "model.gguf"+ write_model(model, modality, projection_width)+ arrays["model"] = np.frombuffer(model.read_bytes(), np.uint8)+ cases = [(64, 32), (96, 64)] if modality == "vision" else [(24, 128), (17, 128)]+ arguments = [str(oracle), str(model), modality, str(scratch / "oracle")]+ for i, (width, height) in enumerate(cases):+ first = rng.normal(0, 0.4, (height, width, 3) if modality == "vision" else (height, width)).astype(np.float32)+ first.tofile(scratch / f"{i}.f32")+ second_name = "-"+ if modality == "vision":+ second = rng.normal(0, 0.4, first.shape).astype(np.float32)+ second.tofile(scratch / f"{i}.second.f32")+ second_name = str(scratch / f"{i}.second.f32")+ arrays[f"{i}.pixel_values"] = first.transpose(2, 0, 1)[None].copy()+ arrays[f"{i}.pixel_values_1"] = second.transpose(2, 0, 1)[None].copy()+ y, x = np.meshgrid(np.arange(height // 16), np.arange(width // 16), indexing="ij")+ arrays[f"{i}.positions"] = np.stack((y, x, np.zeros_like(y), np.zeros_like(y))).astype(np.int32).reshape(1, 1, 1, -1)+ else:+ arrays[f"{i}.features"] = first.reshape(1, 1, height, width)+ arguments.extend((str(width), str(height), str(scratch / f"{i}.f32"), second_name))+ if modality == "vision" or streaming:+ subprocess.run(arguments, check=True)+ else:+ for i in range(2):+ call = arguments[:4] + arguments[4 + 4 * i:8 + 4 * i]+ call[3] = str(scratch / f"cold.{i}")+ subprocess.run(call, check=True)+ (scratch / "oracle" / str(i)).mkdir(parents=True)+ for file in (scratch / f"cold.{i}" / "0").glob("*.f32"):+ (scratch / "oracle" / str(i) / file.name).write_bytes(file.read_bytes())+ for i in range(2):+ output = scratch / "oracle" / str(i)+ arrays[f"{i}.embeddings"] = np.fromfile(output / "embeddings.f32", np.float32).reshape(1, -1, projection_width)+ for file in output.glob("state_out_*.f32"):+ arrays[f"{i}.state.{file.stem.removeprefix('state_out_')}"] = np.fromfile(file, np.float32)+ label = modality + ("_stream" if streaming else "")+ target = directory / f"lfm3_media_{label}.npz"+ save_npz(target, arrays)+ return {"file": target.name, "sha256": hashlib.sha256(target.read_bytes()).hexdigest(), "cases": len(cases)}++++def combine_omni(oracle, output, speech_fixture):+ with tempfile.TemporaryDirectory() as scratch:+ scratch = Path(scratch)+ vision_info = generate(oracle, scratch, "vision", False, 6)+ audio_info = generate(oracle, scratch, "audio", False, 6)+ vision = np.load(scratch / vision_info["file"])+ audio = np.load(scratch / audio_info["file"])+ speech = np.load(speech_fixture)+ writer = gguf.GGUFWriter(scratch / "omni.gguf", "clip")+ metadata = {}+ names = set()+ for i, arrays in enumerate((vision, audio, speech)):+ path = scratch / f"component.{i}.gguf"+ path.write_bytes(arrays["model"].tobytes())+ reader = gguf.GGUFReader(path)+ for name, field in reader.fields.items():+ if name.startswith("GGUF.") or name == "general.architecture":+ continue+ value = field.contents()+ if name in metadata:+ if metadata[name] != value:+ raise ValueError(f"Conflicting component metadata: {name}")+ continue+ metadata[name] = value+ writer.add_key_value(name, value, field.types[0],+ field.types[-1] if field.types[0] == gguf.GGUFValueType.ARRAY else None)+ for tensor in reader.tensors:+ if tensor.name in names:+ raise ValueError(f"Conflicting component tensor: {tensor.name}")+ names.add(tensor.name)+ writer.add_tensor(tensor.name, tensor.data.copy(), raw_dtype=tensor.tensor_type)+ finish(writer)+ arrays = {"model": np.frombuffer((scratch / "omni.gguf").read_bytes(), np.uint8)}+ for name in ("pixel_values", "pixel_values_1", "positions"):+ arrays["vision." + name] = vision["0." + name]+ arrays["audio.features"] = audio["0.features"]+ arrays["audio.depth.hidden_states"] = speech["hidden"].reshape(1, 1, 9, 6)+ arrays["audio.depth.codes"] = np.zeros((1, 1, 9, 12), np.int32)+ arrays["audio.depth.mask"] = np.zeros((1, 1, 9, 12), np.float32)+ arrays["audio.feedback.codes"] = speech["depth_codes"].reshape(1, 1, 9, 12)+ arrays["audio.codec.codes"] = speech["codes"][:1].reshape(1, 1, 1, 12)+ arrays["audio.codec.positions"] = np.arange(6, dtype=np.int32).reshape(1, 1, 1, 6)+ mask = np.full((6, 35), -np.inf, np.float32)+ for query in range(6):+ for key in range(query, query + 30):+ if key >= 29:+ mask[query, key] = 0+ arrays["audio.codec.attention_mask"] = mask.reshape(1, 1, 6, 35)+ arrays["expected.vision.embeddings"] = vision["0.embeddings"]+ arrays["expected.audio.embeddings"] = audio["0.embeddings"]+ arrays["expected.audio.depth_logits"] = np.concatenate([speech[f"depth_0_{i}"] for i in range(9)])+ arrays["expected.audio.feedback"] = np.concatenate([speech[f"feedback_{i}"] for i in range(9)])+ arrays["expected.audio.spectrogram"] = speech["spectra_0"]+ for name in audio.files:+ if name.startswith("0.state."):+ arrays["state.audio.state." + name.removeprefix("0.state.")] = audio[name]+ for name in speech.files:+ if name.startswith("state_0_gen_state_"):+ arrays["state.audio.codec.state." + name.removeprefix("state_0_gen_state_").replace("_", ".")] = speech[name]+ target = output / "lfm3_media_omni.npz"+ save_npz(target, arrays)+ return {"file": target.name, "sha256": hashlib.sha256(target.read_bytes()).hexdigest(),+ "independent_components": [vision_info, audio_info,+ {"file": speech_fixture.name, "sha256": hashlib.sha256(speech_fixture.read_bytes()).hexdigest()}],+ "language_width": 6}+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("--llama-src", type=Path, required=True)+ parser.add_argument("--oracle", type=Path, required=True)+ parser.add_argument("--llama-build", type=Path, required=True)+ parser.add_argument("--omni-speech", type=Path)+ parser.add_argument("--output", type=Path, default=Path(__file__).parent / "test_data")+ args = parser.parse_args()+ actual = subprocess.check_output(["git", "-C", str(args.llama_src), "rev-parse", "HEAD"], text=True).strip()+ if actual != REVISION:+ raise ValueError(f"LFM3 CPU oracle must use {REVISION}, got {actual}")+ cache = (args.llama_build / "CMakeCache.txt").read_text()+ if "GGML_OPENVINO:BOOL=OFF" not in cache:+ raise ValueError("CPU reference must be built with GGML_OPENVINO=OFF")+ libraries = {path.name: hashlib.sha256(path.read_bytes()).hexdigest()+ for path in sorted((args.llama_build / "bin").glob("lib*.so"))}+ args.output.mkdir(parents=True, exist_ok=True)+ fixtures = [generate(args.oracle.resolve(), args.output, "vision", False),+ generate(args.oracle.resolve(), args.output, "audio", False),+ generate(args.oracle.resolve(), args.output, "audio", True)]+ if args.omni_speech:+ fixtures.append(combine_omni(args.oracle.resolve(), args.output, args.omni_speech))+ manifest = {"llama_cpp": REVISION, "backend": "CPU", "flash_attention": False,+ "oracle_sha256": hashlib.sha256(args.oracle.read_bytes()).hexdigest(),+ "oracle_source_sha256": hashlib.sha256((Path(__file__).parent / "lfm3_media_oracle.cpp").read_bytes()).hexdigest(),+ "libraries": libraries, "fixtures": fixtures}+ (args.output / "lfm3_media_provenance.json").write_text(json.dumps(manifest, indent=2) + "\n")+++if __name__ == "__main__":+ main()diff --git a/src/frontends/gguf/tests/gen_lfm3_speech_fixtures.py b/src/frontends/gguf/tests/gen_lfm3_speech_fixtures.pynew file mode 100644index 00000000000..088c6574dfb--- /dev/null+++ b/src/frontends/gguf/tests/gen_lfm3_speech_fixtures.py@@ -0,0 +1,100 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++"""Nonzero LFM3 speech fixtures from llama.cpp CPU at 604cc430239c76ff636c443e3400bf552b750421."""+import argparse+from pathlib import Path+import subprocess++import gguf+import numpy as np++from mmproj_fixtures import TensorWriter, finish, save_npz+++class SpeechTensorWriter(TensorWriter):+ def tensor(self, name, shape, norm=False):+ count = int(np.prod(shape))+ if name.startswith("a.gen.wav.") and count > 8192:+ pattern = self.rng.normal(0, self.std, 4093).astype(np.float32)+ self.writer.add_tensor(name, np.resize(pattern, count).reshape(shape))+ else:+ super().tensor(name, shape, norm)+++def make_model(path):+ writer = gguf.GGUFWriter(path, "clip")+ writer.add_bool("clip.has_gen_audio_encoder", True)+ writer.add_string("clip.gen.audio.projector_type", "lfm3a_gen")+ for name, value in [("embedding_length", 8), ("feed_forward_length", 12), ("block_count", 3),+ ("projection_dim", 6), ("attention.head_count", 4), ("attention.head_count_kv", 2)]:+ writer.add_uint32("clip.gen.audio." + name, value)+ writer.add_float32("clip.gen.audio.attention.layer_norm_epsilon", 1e-5)+ tensors = SpeechTensorWriter(writer, np.random.default_rng(7103))+ tensors.tensor("a.gen.code.embd.weight", (12, 2017, 8))+ tensors.tensor("a.gen.code.head_norm.weight", (12, 8), True)+ tensors.tensor("a.gen.code.out_embd.weight", (12 * 2017, 6))+ tensors.tensor("a.gen.code.mask_embd", (8,))+ tensors.norm("a.gen.code.output_norm", 8, False)+ tensors.linear("a.gen.code.proj_in", 6, 12 * 8)+ levels = np.array([8, 7, 6, 6])+ basis = np.array([1, 8, 56, 336])+ codebook = ((np.arange(2016)[:, None] // basis) % levels - levels // 2) / (levels // 2)+ writer.add_tensor("a.gen.wav.quant.first.codebook.weight", codebook.astype(np.float32))+ tensors.linear("a.gen.wav.quant.first.out_proj", 48, 6)+ tensors.linear("a.gen.wav.tfm.in_proj", 6, 512)+ tensors.linear("a.gen.wav.tfm.out_proj", 512, 1282)+ tensors.norm("a.gen.wav.tfm.output_norm", 512, False)+ for base, count in [("a.gen.code", 3), ("a.gen.wav.tfm", 8)]:+ for layer in range(count):+ prefix = f"{base}.blk.{layer}."+ channels = 512 if base.endswith("tfm") else 8+ for name in ["ln1", "ln2"]:+ tensors.norm(prefix + name, channels, False)+ if base.endswith("tfm"):+ for name in ["attn_post_norm", "ffn_post_norm"]:+ tensors.norm(prefix + name, channels, False)+ if base.endswith("tfm") and layer % 2 == 0:+ tensors.linear(prefix + "conv_pw1", channels, 3 * channels, False)+ tensors.tensor(prefix + "conv_dw.weight", (channels, 4))+ tensors.linear(prefix + "conv_pw2", channels, channels, False)+ else:+ for name, inp, out in [("attn_q", channels, 8), ("attn_k", channels, 4),+ ("attn_v", channels, 4), ("attn_out", 8, channels),+ ("attn_gate", channels, 4)]:+ tensors.linear(prefix + name, inp, out, False)+ for name in ["attn_q_norm", "attn_k_norm"]:+ tensors.norm(prefix + name, 2, False)+ for name, inp, out in [("ffn_gate", channels, 12), ("ffn_up", channels, 12), ("ffn_down", 12, channels)]:+ tensors.linear(prefix + name, inp, out, False)+ finish(writer)+++def generate(oracle, output):+ directory = Path(oracle).resolve().parent / "speech-fixture-work"+ directory.mkdir(exist_ok=True)+ model = directory / "model.gguf"+ make_model(model)+ hidden = np.random.default_rng(43).normal(size=(9, 6)).astype(np.float32)+ codes = np.random.default_rng(44).integers(0, 2016, size=(9, 12), dtype=np.int32)+ codes[0, 0], codes[0, 1] = 0, 2015+ depth_codes = codes.copy()+ depth_codes[0, 2], depth_codes[8, 11] = 2016, 2016+ hidden.tofile(directory / "hidden.f32")+ codes.tofile(directory / "codes.i32")+ depth_codes.tofile(directory / "depth_codes.i32")+ reference = directory / "reference"+ subprocess.run([str(Path(oracle).resolve()), str(model), str(directory), str(reference)], check=True)+ arrays = {"model": np.frombuffer(model.read_bytes(), np.uint8), "hidden": hidden, "codes": codes,+ "depth_codes": depth_codes}+ for path in sorted(reference.glob("*.f32")):+ arrays[path.stem] = np.fromfile(path, np.float32)+ save_npz(output, arrays)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument("--oracle", required=True)+ parser.add_argument("--output", type=Path, default=Path(__file__).parent / "test_data/mmproj_accuracy/lfm3_speech.npz")+ args = parser.parse_args()+ generate(args.oracle, args.output)diff --git a/src/frontends/gguf/tests/lfm3_media_oracle.cpp b/src/frontends/gguf/tests/lfm3_media_oracle.cppnew file mode 100644index 00000000000..25672f6df59--- /dev/null+++ b/src/frontends/gguf/tests/lfm3_media_oracle.cpp@@ -0,0 +1,86 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <algorithm>+#include <filesystem>+#include <fstream>+#include <string>+#include <vector>++#include "clip-impl.h"+#include "clip.h"+#include "ggml-backend.h"++// model modality output-directory [width height input.f32 second.f32|-]...+int main(int argc, char** argv) {+ if (argc < 8 || (argc - 4) % 4)+ return 2;+ ggml_backend_load_all();+ std::filesystem::path dump;+ clip_context_params params{};+ params.use_gpu = false;+ params.flash_attn_type = CLIP_FLASH_ATTN_TYPE_DISABLED;+ params.cb_eval_user_data = &dump;+ params.cb_eval = [](ggml_tensor* tensor, bool ask, void* data) {+ if (ask)+ return tensor->type == GGML_TYPE_F32 && std::string(tensor->name).rfind("state_out_", 0) == 0;+ std::vector<char> bytes(ggml_nbytes(tensor));+ ggml_backend_tensor_get(tensor, bytes.data(), 0, bytes.size());+ auto path = *static_cast<std::filesystem::path*>(data) / (std::string(tensor->name) + ".f32");+ std::ofstream file(path, std::ios::binary);+ file.write(bytes.data(), bytes.size());+ return bool(file);+ };+ const auto contexts = clip_init(argv[1], params);+ const bool audio = std::string(argv[2]) == "audio";+ auto* context = audio ? contexts.ctx_a : contexts.ctx_v;+ if (!context)+ return 3;+ auto* state = audio ? clip_enc_state_init(context, 128) : nullptr;+ if (audio && !state)+ return 4;+ for (int i = 4; i < argc; i += 4) {+ dump = std::filesystem::path(argv[3]) / std::to_string((i - 4) / 4);+ std::filesystem::create_directories(dump);+ const int width = std::stoi(argv[i]), height = std::stoi(argv[i + 1]);+ std::vector<float> values(size_t(width) * height * (audio ? 1 : 3));+ auto read = [&](const char* name) {+ std::ifstream file(name, std::ios::binary);+ file.read(reinterpret_cast<char*>(values.data()), values.size() * sizeof(float));+ return bool(file);+ };+ if (!read(argv[i + 2]))+ return 5;+ clip_image_f32 image;+ image.set_size({width, height}, false, audio);+ image.cpy_buf(values);+ clip_image_f32_batch batch;+ batch.is_audio = audio;+ batch.entries.push_back(image);+ if (std::string(argv[i + 3]) != "-") {+ if (!read(argv[i + 3]))+ return 5;+ image.cpy_buf(values);+ batch.entries.push_back(image);+ }+ std::vector<float> output(size_t(clip_n_output_tokens(context, &image)) * clip_n_mmproj_embd(context));+ clip_encode_params encode;+ encode.n_threads = 2;+ encode.imgs = &batch;+ encode.out_embd = &output;+ encode.enc_state = state;+ if (!clip_encode(context, &encode))+ return 6;+ std::ofstream file(dump / "embeddings.f32", std::ios::binary);+ file.write(reinterpret_cast<const char*>(output.data()), output.size() * sizeof(float));+ }+ if (state)+ clip_enc_state_free(state);+ if (contexts.ctx_v)+ clip_free(contexts.ctx_v);+ if (contexts.ctx_a)+ clip_free(contexts.ctx_a);+ if (contexts.ctx_gen_a)+ clip_free(contexts.ctx_gen_a);+}diff --git a/src/frontends/gguf/tests/lfm3_speech_README.md b/src/frontends/gguf/tests/lfm3_speech_README.mdnew file mode 100644index 00000000000..e9cae8d7f62--- /dev/null+++ b/src/frontends/gguf/tests/lfm3_speech_README.md@@ -0,0 +1,95 @@+# LFM3 speech reference fixture++`lfm3_speech.npz` contains a nonzero synthetic GGUF plus outputs from the real+llama.cpp CPU implementation at `604cc430239c76ff636c443e3400bf552b750421`.+The oracle invokes `clip_encode()` on the LFM3 depthformer and streaming codec;+expected features are never calculated by NumPy.++The depthformer has three bidirectional layers, twelve tied 2017-entry tables,+four query heads and two KV heads with head size two. Nine independent frames+exercise all masked slots, partially revealed slots, feedback, and IDs 0, 2015,+and 2016. The codec uses the reference's required 512-channel state, eight+alternating convolution/attention layers, nonuniform sandwich norms, sigmoid+head gates, and the `[8,7,6,6]` FSQ table. Query and KV widths differ. Large+codec matrices repeat a random 4093-element pattern to compress the fixture;+this prime period keeps channels and the convolution's three projections+distinct. Norms and attention/gate weights remain independent random values.++Codec calls contain one, two, and six frames (six STFT positions per frame).+The final chunk crosses the 30-position attention window. Additional calls+reset state and decode two frames, then reset and decode all nine frames.+The archive keeps the thirteen nonzero state outputs for every call.++Spectral assertions use the established mmproj component gate in+[`docs/testing.md`](../docs/testing.md): NMSE below `1e-5`, with exact shape and+finite-value checks. Depth logits, feedback, and logical recurrent states keep+the existing elementwise helper. The initial spectral elementwise diagnostic+failed twelve values on the reset two-frame clip: maximum absolute difference+`1.3113e-4`, NMSE `1.6276e-10`. Stateless and plain stateful execution had identical+outputs. Intermediate CPU-reference bisection showed accumulated F32 differences+amplified by layer four's FFN post norm; the same reference norm input agrees at+`7.15e-7` maximum absolute error. The diagnostic failure and metrics remain in+`speech-summary.json` under the task's validation artifact directory. No existing+acceptance gate was changed.++Real Q8 checkpoint validation uses the same pinned CPU oracle, F32 inference,+disabled OpenVINO dynamic quantization, and F32 KV states. Each report contains+68 comparisons: two depth outputs, feedback, five spectra, and sixty state+arrays including the five position states. The required NMSE gate remains+`1e-5`.++| Checkpoint | Masked depth NMSE | Partly revealed depth NMSE | Result |+| --- | ---: | ---: | --- |+| LFM3-Audio-2B-Q8_0 | `2.26475e-4` | `2.33621e-4` | Both depth checks fail |+| LFM3-Omni-2B-Q8_0 | `2.41716e-4` | `2.60034e-4` | Both depth checks fail |+| Audio Q8 weights expanded to represented F32 | `1.26399e-12` | `1.48760e-12` | All 68 checks pass |++Original Q8 feedback is exact. Both checkpoints' spectra have maximum NMSE+`8.38669e-8`; recurrent states have maximum NMSE `2.67943e-7`. The represented+F32 diagnostic expands Q8 generation weights exactly, retains original F16+weights, and omits encoder branches. It checks graph math and layout; the+original Q8 depth failures remain unresolved, and no represented F32 Omni+check was run.++An artifact-only activation Q8 prototype patches 37 constant-weight depth+MatMuls and explicitly emulates the stored FP16 per-block scale. Its projection+agrees with the CPU oracle at NMSE `6.66357e-13`, but full depth still fails at+`1.64416e-4` and `1.82022e-4`. Feeding the identical reference layer-zero norm+output to its query projection gives NMSE `1.81619e-13`, maximum absolute error+`3.33786e-6`. This supports activation rounding threshold changes from small+upstream F32 differences as an explanation for error growth. It does not+establish full Q8 equivalence, and no production quantization patch was made.+The real reports and diagnostic records are retained beside+`speech-summary.json` in the task's validation artifact directory.++Build the oracle against the pinned CPU-only `mtmd`, `ggml`, and `ggml-base`+libraries, with include directories `tools/mtmd`, `include`, and `ggml/include`:++```sh+c++ -std=c++17 -O2 lfm3_speech_oracle.cpp \+ -I"$LFM3_REFERENCE_SRC/tools/mtmd" -I"$LFM3_REFERENCE_SRC/include" \+ -I"$LFM3_REFERENCE_SRC/ggml/include" -L"$LFM3_REFERENCE_BUILD/bin" \+ -Wl,-rpath,"$LFM3_REFERENCE_BUILD/bin" -lmtmd -lggml -lggml-base \+ -o lfm3_speech_oracle+PYTHONPATH="$LFM3_REFERENCE_SRC/gguf-py" python3 gen_lfm3_speech_fixtures.py \+ --oracle ./lfm3_speech_oracle+ov_gguf_frontend_tests --gtest_filter='GGUFLfm3Speech.*'+```++The generator retains its work in `speech-fixture-work` beside the oracle.+Run from the frontend test source directory or supply an absolute `--output`.++Native inputs use `[1,1,F,D]` hidden states and `[1,1,F,12]` local code IDs.+`audio.depth.mask` is one for revealed slots, zero for masked slots, whose+lookup ID must be valid (use zero). Codec codes must be below 2016.+`audio.codec.positions` contains the continued positions `[1,1,1,6F]`.+Its additive mask is `[1,1,6F,29+6F]`; entry `(q,k)` is zero precisely when+`q <= k <= q+29` and `base-29+k >= 0`, and negative infinity otherwise.+This hides nonexistent cached keys after reset.++Outputs are `audio.depth_logits [1,F,12,2017]`,+`audio.feedback [1,1,F,Dtext]`, and `audio.spectrogram [1,1,6F,1282]`.+Spectral channels contain 641 log-magnitudes followed by 641 phases.+`audio.istft_window` is a 1280-sample periodic Hann window for host inverse STFT+at 24 kHz with hop 320. Recurrent input/output pairs are recorded for+`GGUFMakeStateful`; positions and masks remain caller inputs.diff --git a/src/frontends/gguf/tests/lfm3_speech_oracle.cpp b/src/frontends/gguf/tests/lfm3_speech_oracle.cppnew file mode 100644index 00000000000..b7a14f1337b--- /dev/null+++ b/src/frontends/gguf/tests/lfm3_speech_oracle.cpp@@ -0,0 +1,140 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <cstdint>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <limits>++#include "clip-impl.h"+#include "clip.h"+#include "ggml-backend.h"++namespace {+template <class T>+std::vector<T> read(const std::filesystem::path& path) {+ std::ifstream file(path, std::ios::binary | std::ios::ate);+ if (!file)+ throw std::runtime_error("cannot read " + path.string());+ const std::streamoff size = file.tellg();+ if (size < 0)+ throw std::runtime_error("invalid input size " + path.string());+ const auto bytes = static_cast<uintmax_t>(size);+ if (bytes % sizeof(T) != 0 || bytes > std::numeric_limits<size_t>::max() ||+ bytes > static_cast<uintmax_t>(std::numeric_limits<std::streamsize>::max()))+ throw std::runtime_error("invalid input size " + path.string());+ std::vector<T> values(static_cast<size_t>(bytes) / sizeof(T));+ file.seekg(0);+ file.read(reinterpret_cast<char*>(values.data()), static_cast<std::streamsize>(bytes));+ if (!file)+ throw std::runtime_error("short input " + path.string());+ return values;+}+constexpr size_t codebooks = 12;+constexpr size_t codec_frames = 9;++size_t validate_input_shapes(int width, size_t hidden_elements, size_t code_elements, size_t depth_code_elements) {+ if (width <= 0 || hidden_elements % static_cast<size_t>(width) != 0)+ throw std::runtime_error("invalid hidden state dimensions");+ const auto frames = hidden_elements / static_cast<size_t>(width);+ if (depth_code_elements % codebooks != 0 || depth_code_elements / codebooks < frames)+ throw std::runtime_error("invalid depth code dimensions");+ if (code_elements % codebooks != 0 || code_elements / codebooks < codec_frames)+ throw std::runtime_error("invalid codec code dimensions");+ return frames;+}++void write(const std::filesystem::path& path, const std::vector<float>& values) {+ std::ofstream file(path, std::ios::binary);+ file.write(reinterpret_cast<const char*>(values.data()), values.size() * sizeof(float));+ if (!file)+ throw std::runtime_error("cannot write " + path.string());+}+} // namespace++int main(int argc, char** argv) {+ if (argc != 4)+ return 2;+ ggml_backend_load_all();+ clip_context_params options{};+ options.use_gpu = false;+ options.flash_attn_type = CLIP_FLASH_ATTN_TYPE_DISABLED;+ const auto contexts = clip_init(argv[1], options);+ if (!contexts.ctx_gen_a)+ return 3;+ const auto input = std::filesystem::path(argv[2]);+ const auto output = std::filesystem::path(argv[3]);+ std::filesystem::create_directories(output);+ const auto hidden = read<float>(input / "hidden.f32");+ const auto codes = read<int32_t>(input / "codes.i32");+ const auto depth_codes = read<int32_t>(input / "depth_codes.i32");+ const int width = clip_n_mmproj_embd(contexts.ctx_gen_a);+ const auto frames = validate_input_shapes(width, hidden.size(), codes.size(), depth_codes.size());+ clip_image_f32 image;+ image.set_size({1, width}, false, false);+ clip_image_f32_batch batch;+ batch.is_audio = true;+ batch.entries.push_back(image);+ auto* state = clip_gen_state_init(contexts.ctx_gen_a, 42);+ if (!state)+ return 4;+ clip_encode_params params;+ params.n_threads = 2;+ params.imgs = &batch;+ params.gen_state = state;+ std::vector<float> feedback(width), features;+ params.out_embd = &feedback;+ params.out_feats = &features;+ params.gen_process = CLIP_GEN_PROCESS_GEN_CODE;+ for (int phase = 0; phase < 3; ++phase) {+ for (size_t frame = 0; frame < frames; ++frame) {+ batch.entries[0].cpy_buf(+ std::vector<float>(hidden.begin() + frame * width, hidden.begin() + (frame + 1) * width));+ std::vector<int32_t> current(depth_codes.begin() + frame * codebooks,+ depth_codes.begin() + (frame + 1) * codebooks);+ for (size_t book = 0; book < current.size(); ++book)+ if (phase == 0 || (phase == 1 && book % 3 != 0))+ current[book] = -1;+ params.codes = ¤t;+ features.clear();+ if (!clip_encode(contexts.ctx_gen_a, ¶ms))+ return 5;+ const auto stem = "depth_" + std::to_string(phase) + "_" + std::to_string(frame);+ if (phase < 2)+ write(output / (stem + ".f32"), features);+ else+ write(output / ("feedback_" + std::to_string(frame) + ".f32"), feedback);+ }+ }+ params.gen_process = CLIP_GEN_PROCESS_GEN_WAV;+ params.out_embd = nullptr;+ const int counts[] = {1, 2, 6, 2, 9};+ size_t offset = 0;+ for (int step = 0; step < 5; ++step) {+ if (step >= 3) {+ clip_gen_state_reset(state);+ offset = step == 3 ? 1 : 0;+ }+ std::vector<int32_t> current(codes.begin() + offset * codebooks,+ codes.begin() + (offset + counts[step]) * codebooks);+ params.codes = ¤t;+ if (!clip_encode(contexts.ctx_gen_a, ¶ms))+ return 6;+ write(output / ("spectra_" + std::to_string(step) + ".f32"), features);+ for (const auto* slot : state->slots) {+ std::vector<float> values(ggml_nelements(slot));+ ggml_backend_tensor_get(slot, values.data(), 0, ggml_nbytes(slot));+ write(output / ("state_" + std::to_string(step) + "_" + slot->name + ".f32"), values);+ }+ offset += counts[step];+ }+ clip_gen_state_free(state);+ clip_free(contexts.ctx_gen_a);+ if (contexts.ctx_a)+ clip_free(contexts.ctx_a);+ if (contexts.ctx_v)+ clip_free(contexts.ctx_v);+ return 0;+}diff --git a/src/frontends/gguf/tests/op_test_utils.hpp b/src/frontends/gguf/tests/op_test_utils.hppindex df30d5f2f3e..321f5633a51 100644--- a/src/frontends/gguf/tests/op_test_utils.hpp+++ b/src/frontends/gguf/tests/op_test_utils.hpp@@ -24,6 +24,7 @@#include <map>#include <memory>#include <set>+#include <sstream>#include <string>#include <vector>@@ -38,6 +39,7 @@#include "openvino/core/visibility.hpp"#include "openvino/frontend/gguf/frontend.hpp"#include "openvino/op/parameter.hpp"+#include "openvino/pass/serialize.hpp"#include "openvino/runtime/core.hpp"#include "openvino/runtime/properties.hpp"#include "openvino/runtime/tensor.hpp"@@ -373,6 +375,28 @@ inline void expect_nmse_below(const Nmse& metric, double limit, const std::strinEXPECT_LT(metric.value(), limit) << context;}+// Round-trips a model through in-memory IR serialization.+inline std::shared_ptr<ov::Model> reload_ir_model(const std::shared_ptr<ov::Model>& model) {+ std::stringstream xml, weights;+ ov::pass::Serialize(xml, weights).run_on_model(model);+ const auto bytes = weights.str();+ ov::Tensor constants(ov::element::u8, {bytes.size()});+ if (!bytes.empty())+ std::memcpy(constants.data(), bytes.data(), bytes.size());+ return ov::Core{}.read_model(xml.str(), constants);+}++// GGUFMakeStateful keeps extra leading convolution taps; returns the trailing `taps` per channel.+inline ov::Tensor trailing_conv_taps(const ov::Tensor& state, size_t channels, size_t taps) {+ const auto stride = state.get_size() / channels;+ ov::Tensor logical(ov::element::f32, {channels, taps});+ for (size_t channel = 0; channel < channels; ++channel)+ std::copy_n(state.data<const float>() + channel * stride + stride - taps,+ taps,+ logical.data<float>() + channel * taps);+ return logical;+}+// The GGUF bytes a reference npz stores as "model", written to a temporary file for its lifetime.struct TemporaryGguf {std::string path =diff --git a/src/frontends/gguf/tests/test_adapt_to_genai.cpp b/src/frontends/gguf/tests/test_adapt_to_genai.cppindex 02f7511ba4f..7ffcbf1f38a 100644--- a/src/frontends/gguf/tests/test_adapt_to_genai.cpp+++ b/src/frontends/gguf/tests/test_adapt_to_genai.cpp@@ -24,6 +24,8 @@#include "openvino/core/validation_util.hpp"#include "openvino/core/visibility.hpp"#include "openvino/frontend/gguf/adapt_to_genai.hpp"+#include "openvino/frontend/gguf/extension/genai.hpp"+#include "openvino/frontend/gguf/frontend.hpp"#include "openvino/frontend/gguf/make_stateful.hpp"#include "openvino/frontend/gguf/tokenizer_metadata.hpp"#include "openvino/op/add.hpp"@@ -33,6 +35,7 @@#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"#include "openvino/op/divide.hpp"+#include "openvino/op/equal.hpp"#include "openvino/op/gated_delta_net.hpp"#include "openvino/op/gather.hpp"#include "openvino/op/matmul.hpp"@@ -87,6 +90,22 @@ struct MinimalGgufModel {std::shared_ptr<ov::Node> pe_tok;};+void add_probe_result(const std::shared_ptr<ov::Model>& model,+ const ov::Output<ov::Node>& value,+ const std::string& name) {+ auto result = std::make_shared<v0::Result>(value);+ result->set_friendly_name(name);+ model->add_results({result});+}++void name_probe_outputs(const std::shared_ptr<ov::Model>& model) {+ for (const auto& result : model->get_results()) {+ const auto& name = result->get_friendly_name();+ if (name.rfind("test_probe_", 0) == 0)+ result->input_value(0).set_names({name});+ }+}+std::map<std::string, ov::Tensor> make_genai_inputs(size_t length, size_t past = 0) {ov::Tensor ids(ov::element::i64, {1, length}), mask(ov::element::i64, {1, past + length});ov::Tensor positions(ov::element::i64, {1, length}), beam(ov::element::i32, {1});@@ -402,12 +421,13 @@ TEST(GGUFAdaptToGenAI, EmbeddingModeRetainsScalingOnce) {TEST(GGUFAdaptToGenAI, BatchedMaskKeepsSequencesSeparateAndExcludesPadding) {auto m = build_minimal_gguf_model();auto mask = find_parameter(m.model, "self_kq_mask");- m.model->add_results({std::make_shared<v0::Result>(mask)});+ add_probe_result(m.model, mask, "test_probe_global_mask");auto swa = ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, -1, -1}, "self_kq_mask_swa");m.model->add_parameters({swa});- m.model->add_results({std::make_shared<v0::Result>(swa)});+ add_probe_result(m.model, swa, "test_probe_sliding_mask");m.model->get_rt_info()[ov::frontend::gguf::pass::gguf_swa_window_key()] = int64_t{2};ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));+ name_probe_outputs(m.model);ov::Core core;auto request = core.compile_model(m.model, "CPU").create_infer_request();// The second sequence has two left-padding columns and one current token.@@ -429,7 +449,7 @@ TEST(GGUFAdaptToGenAI, BatchedMaskKeepsSequencesSeparateAndExcludesPadding) {request.set_tensor("beam_idx", beams);request.infer();for (size_t layer = 0; layer < 2; ++layer) {- const auto actual = request.get_output_tensor(layer);+ const auto actual = request.get_tensor(layer == 0 ? "test_probe_global_mask" : "test_probe_sliding_mask");ASSERT_EQ(actual.get_shape(), (ov::Shape{2, 1, 3, past + 3}));for (size_t b = 0; b < 2; ++b) {// Padded query rows are ignored by generation.@@ -456,16 +476,6 @@ static void image_attention_contract(const std::shared_ptr<ov::Model>& model, Imov::frontend::gguf::write_model_contract(model, contract);}-static std::shared_ptr<ov::Model> reload_ir_model(const std::shared_ptr<ov::Model>& model) {- std::stringstream xml, weights;- ov::pass::Serialize(xml, weights).run_on_model(model);- const auto bytes = weights.str();- ov::Tensor constants(ov::element::u8, {bytes.size()});- if (!bytes.empty())- std::memcpy(constants.data(), bytes.data(), bytes.size());- return ov::Core{}.read_model(xml.str(), constants);-}-class GGUFAdaptToGenAIImageMask : public testing::TestWithParam<ImageAttentionMode> {};TEST_P(GGUFAdaptToGenAIImageMask, RespectsLayerTypeImageGroupsAndCachedPrefix) {@@ -476,9 +486,10 @@ TEST_P(GGUFAdaptToGenAIImageMask, RespectsLayerTypeImageGroupsAndCachedPrefix) {auto mask = find_parameter(m.model, "self_kq_mask");auto swa_mask = ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, -1, -1}, "self_kq_mask_swa");m.model->add_parameters({swa_mask});- m.model->add_results({std::make_shared<v0::Result>(mask), std::make_shared<v0::Result>(swa_mask)});+ add_probe_result(m.model, mask, "test_probe_global_mask");+ add_probe_result(m.model, swa_mask, "test_probe_sliding_mask");AdaptToGenAI(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS).run_on_model(m.model);- // Adaptation replaces the original first result with logits; the retained mask is now first.+ name_probe_outputs(m.model);ov::Core core;for (const auto& node : m.model->get_ops())node->get_rt_info().clear();@@ -503,7 +514,7 @@ TEST_P(GGUFAdaptToGenAIImageMask, RespectsLayerTypeImageGroupsAndCachedPrefix) {request.set_tensor(entry.first, entry.second);request.infer();for (size_t layer = 0; layer < 2; ++layer) {- auto actual = request.get_output_tensor(layer);+ auto actual = request.get_tensor(layer == 0 ? "test_probe_global_mask" : "test_probe_sliding_mask");ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 1, types.size(), past + types.size()}));const bool bidirectional = layer == 1 || GetParam() == ImageAttentionMode::GLOBAL_AND_SLIDING;SCOPED_TRACE("layer=" + std::to_string(layer) + " past=" + std::to_string(past));@@ -529,8 +540,9 @@ TEST(GGUFAdaptToGenAI, EmbeddingModeMapsGenAIMultimodalPositionsToGGML) {auto m = build_minimal_gguf_model();m.model->get_rt_info()[ov::frontend::gguf::pass::gguf_imrope_key()] = true;auto positions = find_parameter(m.model, "inp_pos");- m.model->add_results({std::make_shared<v0::Result>(positions)});+ add_probe_result(m.model, positions, "test_probe_rope_positions");AdaptToGenAI(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS).run_on_model(m.model);+ name_probe_outputs(m.model);auto inputs = make_genai_inputs(2, 7);inputs.erase("input_ids");inputs.emplace("inputs_embeds", make_f32_tensor({1, 2, 2}, {1, 2, 3, 4}));@@ -538,7 +550,11 @@ TEST(GGUFAdaptToGenAI, EmbeddingModeMapsGenAIMultimodalPositionsToGGML) {const std::vector<int64_t> data{3, 7, 11, 2, 5, 13, 17, 19};std::copy(data.begin(), data.end(), coordinates.data<int64_t>());inputs["position_ids"] = coordinates;- auto actual = run_on_cpu(m.model, inputs);+ auto request = ov::Core{}.compile_model(m.model, "CPU").create_infer_request();+ for (const auto& [name, tensor] : inputs)+ request.set_tensor(name, tensor);+ request.infer();+ auto actual = request.get_tensor("test_probe_rope_positions");ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 1, 1, 8}));for (size_t i = 0; i < data.size(); ++i)EXPECT_EQ(actual.data<int32_t>()[i], data[(i + 2) % data.size()]);@@ -1283,6 +1299,263 @@ INSTANTIATE_TEST_SUITE_P(EmbeddingWidth,ImageAttentionMode::GLOBAL_AND_SLIDING,ImageAttentionMode::SLIDING_ONLY)));+TEST(GGUFAdaptToGenAI, SequenceOutputsUseDeclaredContractBeforeAndAfterReload) {+ auto native = build_minimal_gguf_model();+ native.embd->get_input_node_shared_ptr(0)->get_input_node_shared_ptr(0)->set_friendly_name("token_embd.weight");+ auto features = std::make_shared<v1::Multiply>(native.embd, v0::Constant::create(ov::element::f32, {}, {2.f}));+ ov::frontend::gguf::name_output(features, "decoder_features");+ features->output(0).set_names({"decoder_features", "features_alias", "extra_alias"});+ auto summary = std::make_shared<v1::Multiply>(native.embd, v0::Constant::create(ov::element::f32, {}, {3.f}));+ ov::frontend::gguf::name_output(summary, "decoder_summary");+ native.model->add_results({std::make_shared<v0::Result>(features), std::make_shared<v0::Result>(summary)});+ native.model->get_rt_info()["gguf_architecture"] = std::string("custom-sequence-decoder");+ ov::frontend::gguf::ModelContract contract;+ contract.sequence_outputs = {"decoder_features", "features_alias", "decoder_summary"};+ ov::frontend::gguf::write_model_contract(native.model, contract);+ for (const bool reload : {false, true}) {+ for (const auto mode : {AdaptToGenAI::InputMode::IDS_TO_LOGITS, AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS}) {+ auto model = reload ? ov_gguf_test::reload_ir_model(native.model) : native.model->clone();+ EXPECT_EQ(ov::frontend::gguf::read_model_contract(model).sequence_outputs, contract.sequence_outputs);+ AdaptToGenAI adapter(mode);+ ASSERT_TRUE(adapter.run_on_model(model));+ EXPECT_EQ(model->output("decoder_features").get_partial_shape().rank(), 3);+ EXPECT_EQ(model->output(0).get_any_name(), "logits");+ EXPECT_EQ(model->output("features_alias"), model->output("decoder_features"));+ EXPECT_EQ(model->output("extra_alias"), model->output("decoder_features"));+ auto request = ov::Core{}.compile_model(model, "CPU").create_infer_request();+ for (const size_t batch : {1, 2}) {+ for (const size_t length : {3, 1}) {+ ov::Tensor ids(ov::element::i64, {batch, length});+ ov::Tensor embeddings(ov::element::f32, {batch, length, 2});+ ov::Tensor positions(ov::element::i64, {batch, length});+ ov::Tensor mask(ov::element::i64, {batch, length});+ ov::Tensor beams(ov::element::i32, {batch});+ for (size_t i = 0; i < batch * length; ++i) {+ ids.data<int64_t>()[i] = int64_t(i % 4);+ positions.data<int64_t>()[i] = int64_t(i % length);+ mask.data<int64_t>()[i] = 1;+ for (size_t d = 0; d < 2; ++d)+ embeddings.data<float>()[i * 2 + d] = float((i % 4) * 2 + d);+ }+ std::fill_n(beams.data<int32_t>(), batch, 0);+ request.set_tensor(mode == AdaptToGenAI::InputMode::IDS_TO_LOGITS ? "input_ids" : "inputs_embeds",+ mode == AdaptToGenAI::InputMode::IDS_TO_LOGITS ? ids : embeddings);+ request.set_tensor("position_ids", positions);+ request.set_tensor("attention_mask", mask);+ request.set_tensor("beam_idx", beams);+ request.infer();+ auto output = request.get_tensor("decoder_features");+ ASSERT_EQ(output.get_shape(), (ov::Shape{batch, length, 2}));+ for (size_t i = 0; i < output.get_size(); ++i)+ EXPECT_EQ(output.data<float>()[i], 2.f * embeddings.data<float>()[i]);+ auto secondary = request.get_tensor("decoder_summary");+ ASSERT_EQ(secondary.get_shape(), output.get_shape());+ for (size_t i = 0; i < secondary.get_size(); ++i)+ EXPECT_EQ(secondary.data<float>()[i], 3.f * embeddings.data<float>()[i]);+ }+ }+ }+ }+}++TEST(GGUFAdaptToGenAI, InvalidSequenceContractsRejectBeforeRewiring) {+ for (const bool missing : {false, true}) {+ auto model = build_minimal_gguf_model().model;+ auto features = v0::Constant::create(ov::element::f32, {2, 2}, {1.f});+ ov::frontend::gguf::name_output(features, "decoder_features");+ model->add_results({std::make_shared<v0::Result>(features)});+ ov::frontend::gguf::ModelContract contract;+ contract.sequence_outputs = {missing ? "missing_features" : "decoder_features"};+ ov::frontend::gguf::write_model_contract(model, contract);+ const auto parameters = model->get_parameters();+ const auto results = model->get_results();+ EXPECT_THROW(AdaptToGenAI().run_on_model(model), ov::Exception);+ EXPECT_EQ(model->get_parameters(), parameters);+ EXPECT_EQ(model->get_results(), results);+ }+ auto model = build_minimal_gguf_model().model;+ model->get_rt_info()["gguf_architecture"] = std::string("lfm3");+ ov::frontend::gguf::write_model_contract(model, {});+ EXPECT_TRUE(ov::frontend::gguf::read_model_contract(ov_gguf_test::reload_ir_model(model)).sequence_outputs.empty());+ model->get_rt_info()["gguf_model_contract"].as<ov::AnyMap>()["sequence_outputs"] =+ std::vector<std::string>{"duplicate", "duplicate"};+ EXPECT_THROW(AdaptToGenAI().run_on_model(model), ov::Exception);+}++class DefaultContractModelDecoder : public SingleOpDecoder {+public:+ explicit DefaultContractModelDecoder(bool with_context)+ : SingleOpDecoder("GGML_OP_NONE", {}, {}, {"supplied_logits", ov::element::f32, {1, 1, -1, 1}}, {}) {+ auto native = build_minimal_gguf_model();+ auto axes = v0::Constant::create(ov::element::i64, {4}, {0, 1, 2, 3});+ auto positions = std::make_shared<v0::Convert>(find_parameter(native.model, "inp_pos"), ov::element::f32);+ auto position_sum = std::make_shared<v1::ReduceSum>(positions, axes, true);+ auto allowed = std::make_shared<v1::Equal>(find_parameter(native.model, "self_kq_mask"),+ v0::Constant::create(ov::element::f32, {}, {0.f}));+ auto mask_sum =+ std::make_shared<v1::ReduceSum>(std::make_shared<v0::Convert>(allowed, ov::element::f32), axes, true);+ auto dependency = std::make_shared<v1::Multiply>(std::make_shared<v1::Add>(position_sum, mask_sum),+ v0::Constant::create(ov::element::f32, {}, {0.f}));+ auto beams = std::make_shared<v1::ReduceSum>(find_parameter(native.model, "beam_idx"),+ v0::Constant::create(ov::element::i64, {1}, {0}),+ false);+ auto beam_value = std::make_shared<v0::Convert>(beams, ov::element::f32);+ std::shared_ptr<ov::Node> output = std::make_shared<v1::Add>(+ std::make_shared<v1::Add>(native.model->get_results().front()->input_value(0), dependency),+ beam_value);+ if (with_context) {+ auto context = ov::test::utils::make_param(ov::element::f32, {1, 1, 1, 1}, "dspark_ctx_feat");+ native.model->add_parameters({context});+ output = std::make_shared<v1::Add>(output, context);+ }+ for (const auto& parameter : native.model->get_parameters())+ m_scope_inputs.emplace(parameter->get_friendly_name(), parameter);+ m_scope_inputs.emplace("supplied_logits", output);+ }+ const std::map<std::string, std::shared_ptr<ov::Node>>& get_model_inputs() const override {+ return m_scope_inputs;+ }+ void visit_subgraph(std::function<void(std::shared_ptr<ov::frontend::gguf::GgufDecoder>)>) const override {}++protected:+ void add_sequence_output(bool rank_three) {+ std::shared_ptr<ov::Node> features =+ std::make_shared<v1::Multiply>(m_scope_inputs.at("supplied_logits"),+ v0::Constant::create(ov::element::f32, {}, {2.f}));+ if (rank_three)+ features = std::make_shared<v0::Squeeze>(features, v0::Constant::create(ov::element::i64, {1}, {0}));+ m_scope_inputs.emplace("decoder_features", features);+ }++private:+ std::map<std::string, std::shared_ptr<ov::Node>> m_scope_inputs;+};++class SequenceOutputModelDecoder : public DefaultContractModelDecoder {+public:+ explicit SequenceOutputModelDecoder(bool rank_three) : DefaultContractModelDecoder(false) {+ add_sequence_output(rank_three);+ }+ std::vector<std::string> get_model_output_names() const override {+ return {"supplied_logits", "decoder_features"};+ }+ ov::frontend::gguf::ModelContract get_model_contract() const override {+ ov::frontend::gguf::ModelContract contract;+ contract.sequence_outputs = {"decoder_features"};+ return contract;+ }+};++TEST(GGUFAdaptToGenAI, SuppliedDecoderSequenceOutputsSupportResultNamesAndIR) {+ using namespace ov::frontend::gguf;+ for (const bool rank_three : {false, true}) {+ auto decoder = std::make_shared<SequenceOutputModelDecoder>(rank_three);+ FrontEnd frontend;+ auto converted = frontend.convert(frontend.load(std::shared_ptr<GgufDecoder>(decoder)));+ ASSERT_EQ(converted->get_results().back()->get_friendly_name(), "decoder_features");+ ASSERT_TRUE(converted->get_results().back()->input_value(0).get_names().empty());+ const auto shape = converted->get_results().back()->input_value(0).get_partial_shape();+ const auto width = static_cast<size_t>(shape[shape.rank().get_length() - 1].get_length());+ for (const bool reload : {false, true}) {+ for (const bool alias : {false, true}) {+ SCOPED_TRACE("rank=" + std::to_string(rank_three ? 3 : 4) + " reload=" + std::to_string(reload) ++ " alias=" + std::to_string(alias));+ auto model = reload ? ov_gguf_test::reload_ir_model(converted) : converted->clone();+ if (alias)+ model->get_results().back()->output(0).set_names({"existing_alias"});+ bool adapted = false;+ ASSERT_NO_THROW(adapted = AdaptToGenAI().run_on_model(model));+ ASSERT_TRUE(adapted);+ EXPECT_EQ(model->output(0).get_any_name(), "logits");+ EXPECT_EQ(model->output("decoder_features").get_partial_shape().rank(), 3);+ if (alias) {+ EXPECT_EQ(model->output("existing_alias"), model->output("decoder_features"));+ }+ auto restored = ov_gguf_test::reload_ir_model(model);+ auto request = ov::Core{}.compile_model(restored, "CPU").create_infer_request();+ for (const size_t length : {3, 1}) {+ for (const auto& [name, tensor] : make_genai_inputs(length))+ request.set_tensor(name, tensor);+ request.infer();+ auto features = request.get_tensor("decoder_features");+ auto logits = request.get_tensor("logits");+ ASSERT_EQ(features.get_shape(), (ov::Shape{1, length, width}));+ ASSERT_EQ(features.get_shape(), logits.get_shape());+ for (size_t i = 0; i < features.get_size(); ++i) {+ ASSERT_TRUE(std::isfinite(logits.data<float>()[i]));+ EXPECT_EQ(features.data<float>()[i], 2.f * logits.data<float>()[i]);+ }+ }+ }+ }+ FrontEnd genai;+ genai.add_extension(std::make_shared<GenAIExtension>());+ auto adapted = genai.convert(genai.load(std::shared_ptr<GgufDecoder>(decoder)));+ EXPECT_EQ(adapted->output("decoder_features").get_partial_shape().rank(), 3);+ }+}++TEST(GGUFAdaptToGenAI, SuppliedDecoderDefaultCapabilityResolvesBeforeSerialization) {+ for (const bool with_context : {false, true}) {+ SCOPED_TRACE(with_context);+ const std::shared_ptr<ov::frontend::gguf::GgufDecoder> decoder =+ std::make_shared<DefaultContractModelDecoder>(with_context);+ EXPECT_FALSE(decoder->get_model_contract().supports_genai_adaptation.has_value());+ ov::frontend::gguf::FrontEnd frontend;+ auto converted = frontend.convert(frontend.load(decoder));+ EXPECT_EQ(converted->get_rt_info<std::string>({"gguf_model_contract", "supports_genai_adaptation"}),+ with_context ? "false" : "true");+ if (with_context) {+ ov::frontend::gguf::FrontEnd genai;+ genai.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());+ EXPECT_THROW(genai.convert(genai.load(decoder)), ov::Exception);+ }+ for (const auto& source : {converted, ov_gguf_test::reload_ir_model(converted)}) {+ EXPECT_EQ(ov::frontend::gguf::read_model_contract(source).supports_genai_adaptation,+ std::optional<bool>{!with_context});+ const auto parameters = source->get_parameters();+ const auto results = source->get_results();+ EXPECT_EQ(AdaptToGenAI().run_on_model(source), !with_context);+ if (with_context) {+ EXPECT_EQ(source->get_parameters(), parameters);+ EXPECT_EQ(source->get_results(), results);+ EXPECT_NE(find_parameter(source, "dspark_ctx_feat"), nullptr);+ }+ }+ auto explicit_contract = ov::frontend::gguf::read_model_contract(converted);+ explicit_contract.supports_genai_adaptation = true;+ ov::frontend::gguf::write_model_contract(converted, explicit_contract);+ EXPECT_EQ(+ ov::frontend::gguf::read_model_contract(ov_gguf_test::reload_ir_model(converted)).supports_genai_adaptation,+ std::optional<bool>{true});+ }+}++TEST(GGUFAdaptToGenAI, UnsupportedAdaptationUsesDeclaredCapabilityBeforeAndAfterReload) {+ auto model = build_minimal_gguf_model().model;+ ov::frontend::gguf::ModelContract contract;+ contract.supports_genai_adaptation = false;+ model->get_rt_info()["gguf_architecture"] = std::string("custom-unsupported-decoder");+ ov::frontend::gguf::write_model_contract(model, contract);+ for (const auto& source : {model, ov_gguf_test::reload_ir_model(model)}) {+ const auto parameters = source->get_parameters();+ const auto results = source->get_results();+ EXPECT_FALSE(AdaptToGenAI().run_on_model(source));+ EXPECT_EQ(source->get_parameters(), parameters);+ EXPECT_EQ(source->get_results(), results);+ }+ auto legacy = build_minimal_gguf_model().model;+ legacy->add_parameters({ov::test::utils::make_param(ov::element::f32, {1}, "dspark_ctx_feat")});+ EXPECT_FALSE(AdaptToGenAI().run_on_model(ov_gguf_test::reload_ir_model(legacy)));++ auto aliased = build_minimal_gguf_model().model;+ auto context = ov::test::utils::make_param(ov::element::f32, {1}, "renamed_context");+ context->output(0).set_names({"dspark_ctx_feat"});+ aliased->add_parameters({context});+ EXPECT_FALSE(ov::frontend::gguf::read_model_contract(aliased).supports_genai_adaptation.value());+ EXPECT_FALSE(AdaptToGenAI().run_on_model(ov_gguf_test::reload_ir_model(aliased)));+}+TEST(GGUFAdaptToGenAI, ModelContractSurvivesIRReloadBeforeAdaptation) {for (const auto batchable : std::vector<std::optional<bool>>{std::nullopt, false, true}) {auto model = build_attention_gguf_model(8, 4);@@ -1313,7 +1586,7 @@ TEST(GGUFAdaptToGenAI, LegacyRecurrentContractSurvivesIRReloadBeforeAdaptation)auto model = build_minimal_gguf_model().model;model->get_rt_info()["gguf_architecture"] = architecture;model->get_rt_info()[ov::frontend::gguf::pass::gguf_recurrent_states_key()] = std::vector<std::string>{};- auto restored = reload_ir_model(model);+ auto restored = ov_gguf_test::reload_ir_model(model);ASSERT_FALSE(restored->has_rt_info({"gguf_model_contract"}));ASSERT_EQ(restored->get_rt_info<std::string>({"gguf_architecture"}), architecture);const bool batchable = architecture == "lfm2" || architecture == "lfm2moe";@@ -1339,11 +1612,10 @@ TEST_P(GGUFAdaptToGenAILegacyImageContract, ReloadsOldSchemaAndKeepsGlobalAndSliauto global_mask = find_parameter(m.model, "self_kq_mask");auto sliding_mask =ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, -1, -1}, "self_kq_mask_swa");- auto global_result = std::make_shared<v0::Result>(global_mask);- auto sliding_result = std::make_shared<v0::Result>(sliding_mask);m.model->add_parameters({sliding_mask});- m.model->add_results({global_result, sliding_result});- auto restored = reload_ir_model(m.model);+ add_probe_result(m.model, global_mask, "test_probe_global_mask");+ add_probe_result(m.model, sliding_mask, "test_probe_sliding_mask");+ auto restored = ov_gguf_test::reload_ir_model(m.model);ASSERT_FALSE(restored->has_rt_info({"gguf_model_contract"}));ASSERT_EQ(restored->get_rt_info<std::string>({"gguf_architecture"}), architecture);for (const auto& node : restored->get_ops())@@ -1351,6 +1623,7 @@ TEST_P(GGUFAdaptToGenAILegacyImageContract, ReloadsOldSchemaAndKeepsGlobalAndSliEXPECT_EQ(ov::frontend::gguf::read_model_contract(restored, hidden).image_attention, mode);AdaptToGenAI adapter(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);ASSERT_TRUE(adapter.run_on_model(restored));+ name_probe_outputs(restored);ASSERT_NE(adapter.get_embedding_model(), nullptr);ASSERT_EQ(find_parameter(restored, "input_ids"), nullptr);EXPECT_EQ(restored->input("inputs_embeds").get_partial_shape(), (ov::PartialShape{-1, -1, hidden}));@@ -1372,7 +1645,7 @@ TEST_P(GGUFAdaptToGenAILegacyImageContract, ReloadsOldSchemaAndKeepsGlobalAndSlirequest.set_tensor(name, tensor);request.infer();for (size_t layer = 0; layer < 2; ++layer) {- const auto mask = request.get_output_tensor(layer);+ const auto mask = request.get_tensor(layer == 0 ? "test_probe_global_mask" : "test_probe_sliding_mask");ASSERT_EQ(mask.get_shape(), (ov::Shape{1, 1, 3, 3}));expect_mask(mask.data<const float>(), 3, 3, [&, mode = mode](size_t q, size_t k) {const bool image_attention = mode == ImageAttentionMode::GLOBAL_AND_SLIDING ||@@ -1405,7 +1678,7 @@ TEST(GGUFAdaptToGenAI, ExplicitPartialContractPreventsLegacyRecurrentFallbackAftmodel->get_rt_info()["gguf_architecture"] = architecture;model->get_rt_info()["gguf_model_contract"] = contract;model->get_rt_info()[ov::frontend::gguf::pass::gguf_recurrent_states_key()] = std::vector<std::string>{};- auto restored = reload_ir_model(model);+ auto restored = ov_gguf_test::reload_ir_model(model);ASSERT_TRUE(restored->has_rt_info({"gguf_model_contract"}));EXPECT_NE(ov::frontend::gguf::read_model_contract(restored).batchable_recurrent, std::optional<bool>{true});ASSERT_TRUE(AdaptToGenAI().run_on_model(restored));@@ -1427,7 +1700,7 @@ TEST(GGUFAdaptToGenAI, ExplicitPartialContractPreventsLegacyImageFallbackAfterIRtable->set_friendly_name("token_embd.weight");m.model->get_rt_info()["gguf_architecture"] = architecture;m.model->get_rt_info()["gguf_model_contract"] = contract;- auto restored = reload_ir_model(m.model);+ auto restored = ov_gguf_test::reload_ir_model(m.model);ASSERT_TRUE(restored->has_rt_info({"gguf_model_contract"}));EXPECT_EQ(ov::frontend::gguf::read_model_contract(restored, 32).image_attention,ImageAttentionMode::CAUSAL);@@ -1496,7 +1769,7 @@ class GGUFAdaptToGenAILegacyScaledEmbedding : public testing::TestWithParam<std:TEST_P(GGUFAdaptToGenAILegacyScaledEmbedding, ReloadPreservesTokenScalingAndInjectedMediaValues) {const auto& [architecture, per_layer] = GetParam();auto m = build_scaled_legacy_gguf_model(architecture, per_layer);- auto restored = reload_ir_model(m.model);+ auto restored = ov_gguf_test::reload_ir_model(m.model);ASSERT_FALSE(restored->has_rt_info({"gguf_model_contract"}));for (const auto& node : restored->get_ops()) {ASSERT_EQ(node->get_rt_info().count("gguf.token_embedding"), 0);@@ -1619,7 +1892,7 @@ TEST_P(GGUFAdaptToGenAILegacyHadamardEmbedding, ReloadExtractsCompleteInverseGetlogits->input(0).replace_source_output(endpoint);m.model->get_rt_info()["gguf_architecture"] = std::string{"qwen35"};m.model->validate_nodes_and_infer_types();- const auto restored = reload_ir_model(m.model);+ const auto restored = ov_gguf_test::reload_ir_model(m.model);for (const auto& node : restored->get_ops())ASSERT_EQ(node->get_rt_info().count("gguf.token_embedding"), 0);AdaptToGenAI direct_adapter(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);@@ -1675,7 +1948,7 @@ TEST(GGUFAdaptToGenAI, LegacyCompleteEmbeddingEndpointRejectsSeparateBranches) {const auto left_result = std::make_shared<v0::Result>(left);const auto right_result = std::make_shared<v0::Result>(right);m.model->add_results({left_result, right_result});- const auto restored = reload_ir_model(m.model);+ const auto restored = ov_gguf_test::reload_ir_model(m.model);AdaptToGenAI adapter(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);EXPECT_THROW(adapter.run_on_model(restored), ov::Exception);}@@ -1689,7 +1962,7 @@ TEST(GGUFAdaptToGenAI, LegacyCompleteEmbeddingEndpointIgnoresPerLayerSuffix) {per_layer->set_friendly_name("Convert_native_per_layer_embd");const auto result = std::make_shared<v0::Result>(per_layer);m.model->add_results({result});- const auto restored = reload_ir_model(m.model);+ const auto restored = ov_gguf_test::reload_ir_model(m.model);const auto legacy = ov::frontend::gguf::resolve_legacy_embedding_boundaries(restored, true, false);ASSERT_NE(legacy.token, nullptr);EXPECT_EQ(legacy.token->get_friendly_name(), m.embd->get_friendly_name());diff --git a/src/frontends/gguf/tests/test_arch_accuracy.cpp b/src/frontends/gguf/tests/test_arch_accuracy.cppindex 69fde00a951..56ed1ca2faf 100644--- a/src/frontends/gguf/tests/test_arch_accuracy.cpp+++ b/src/frontends/gguf/tests/test_arch_accuracy.cpp@@ -837,6 +837,19 @@ TEST(GGUFMultimodalBackboneAdaptation, Rank3HeadRemainsVisibleToGenAI) {}}+TEST(GGUFMultimodalBackboneAdaptation, Lfm3SupportsBatchesAndBeamReordering) {+ for (const auto* family : {"lfm3", "lfm3-attention-first", "lfm3-wide-query"}) {+ SCOPED_TRACE(family);+ const 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));+ EXPECT_EQ(model->output("audio_hidden_states").get_partial_shape().rank().get_length(), 3);+ check_batched_decode(model);+ }+}+TEST(GGUFMultimodalBackboneAdaptation, QwenAndGemmaSupportBatchesAndPagedAttention) {for (const auto* family :{"qwen35", "bonsai2-hadamard", "qwen35moe", "qwen35moe-fused", "gemma4-mqa", "gemma4-moe", "gemma4-ple"}) {@@ -1098,6 +1111,30 @@ TEST(GGUFMultimodalBackboneAdaptation, Lfm2RejectsMissingOrInvalidConvolutionCac}}+TEST(GGUFMultimodalBackboneAdaptation, Lfm3RejectsMissingRequiredMetadataAndWeights) {+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/lfm3.npz");+ const auto& model = ov_gguf_test::npz_array(arrays, "model");+ for (const auto& [key, diagnostic] : std::vector<std::pair<std::string, std::string>>{+ {"lfm3.shortconv.l_cache", "shortconv.l_cache"},+ {"lfm3.attention.sliding_window_pattern", "sliding-window metadata"},+ {"lfm3.rope.freq_base_swa", "sliding-window metadata"},+ {"blk.0.post_ffw_norm.weight", "both post norms"},+ {"blk.1.attn_gate.weight", "attn_gate.weight"},+ {"output_norm.weight", "output_norm.weight"},+ {"rope_freqs.weight", "rope_freqs.weight"}}) {+ SCOPED_TRACE(key);+ 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());+ at[key.size() - 1] = 'X';+ 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(diagnostic));+ }+}+TEST(GGUFEmbeddingAccuracy, TokenEmbeddingsAndPoolingMatchLlamaCPU) {for (const auto* family :{"llama-embed", "llama-embed-noncausal", "llama-embed-mean", "llama-embed-cls", "llama-embed-last"}) {@@ -1217,8 +1254,8 @@ 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" ||- std::string(GetParam()).find("lfm2") == 0;- const bool lfm2 = std::string(GetParam()).find("lfm2") == 0;+ std::string(GetParam()).find("lfm2") == 0 || std::string(GetParam()).find("lfm3") == 0;+ const bool lfm2 = std::string(GetParam()).find("lfm2") == 0 || std::string(GetParam()).find("lfm3") == 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;@@ -1302,7 +1339,7 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {}))request.set_tensor("beam_idx", beam);request.infer();- return request.get_output_tensor();+ return request.get_tensor("logits");};size_t past = 0;size_t step = 0;@@ -1365,6 +1402,10 @@ INSTANTIATE_TEST_SUITE_P(Architectures,"lfm2-attention-first","lfm2moe","lfm2moe-all-experts",+ "lfm3",+ "lfm3-plain",+ "lfm3-attention-first",+ "lfm3-wide-query","bonsai2-hadamard","qwen35-mixed","qwen35moe",diff --git a/src/frontends/gguf/tests/test_arch_conversion.cpp b/src/frontends/gguf/tests/test_arch_conversion.cppindex 9eca7a31c43..549e18bc4bb 100644--- a/src/frontends/gguf/tests/test_arch_conversion.cpp+++ b/src/frontends/gguf/tests/test_arch_conversion.cpp@@ -181,21 +181,37 @@ struct Fingerprint {const std::map<std::string, Fingerprint>& fingerprints() {static const std::map<std::string, Fingerprint> fp{- {"mamba2-dense.gguf.hdr", {241, 6}}, {"nemotron_h-dense.gguf.hdr", {254, 8}},- {"bailingmoe2-moe.gguf.hdr", {496, 10}}, {"ernie4_5-moe-moe.gguf.hdr", {471, 10}},- {"exaone4-dense.gguf.hdr", {422, 11}}, {"gemma-dense.gguf.hdr", {372, 10}},- {"gemma2-dense.gguf.hdr", {422, 11}}, {"glm4moe-moe.gguf.hdr", {508, 10}},- {"gpt-oss-moe.gguf.hdr", {598, 11}}, {"hunyuan-dense-dense.gguf.hdr", {421, 10}},- {"hunyuan-moe-moe.gguf.hdr", {607, 10}}, {"llama-dense.gguf.hdr", {405, 10}},- {"lfm2-dense.gguf.hdr", {307, 9}}, {"lfm2moe-moe.gguf.hdr", {382, 8}},- {"llama-moe.gguf.hdr", {532, 10}}, {"maincoder-dense.gguf.hdr", {437, 10}},- {"minicpm-dense.gguf.hdr", {413, 10}}, {"minicpm-moe.gguf.hdr", {540, 10}},- {"minimax-m2-moe.gguf.hdr", {572, 10}}, {"mistral3-dense.gguf.hdr", {405, 10}},- {"mistral3-moe.gguf.hdr", {532, 10}}, {"olmoe-moe.gguf.hdr", {560, 10}},- {"phi3-dense.gguf.hdr", {358, 10}}, {"qwen2-dense.gguf.hdr", {373, 10}},- {"qwen3-dense.gguf.hdr", {421, 10}}, {"qwen3moe-moe.gguf.hdr", {572, 10}},- {"qwen35-dense.gguf.hdr", {399, 10}}, {"qwen35moe-moe.gguf.hdr", {571, 10}},- {"smollm3-dense.gguf.hdr", {389, 10}}, {"jais2-dense.gguf.hdr", {334, 10}},+ {"mamba2-dense.gguf.hdr", {241, 6}},+ {"nemotron_h-dense.gguf.hdr", {254, 8}},+ {"bailingmoe2-moe.gguf.hdr", {496, 10}},+ {"ernie4_5-moe-moe.gguf.hdr", {471, 10}},+ {"exaone4-dense.gguf.hdr", {422, 11}},+ {"gemma-dense.gguf.hdr", {372, 10}},+ {"gemma2-dense.gguf.hdr", {422, 11}},+ {"glm4moe-moe.gguf.hdr", {508, 10}},+ {"gpt-oss-moe.gguf.hdr", {598, 11}},+ {"hunyuan-dense-dense.gguf.hdr", {421, 10}},+ {"hunyuan-moe-moe.gguf.hdr", {607, 10}},+ {"llama-dense.gguf.hdr", {405, 10}},+ {"lfm2-dense.gguf.hdr", {307, 9}},+ {"lfm2moe-moe.gguf.hdr", {382, 8}},+ {"llama-moe.gguf.hdr", {532, 10}},+ {"maincoder-dense.gguf.hdr", {437, 10}},+ {"minicpm-dense.gguf.hdr", {413, 10}},+ {"minicpm-moe.gguf.hdr", {540, 10}},+ {"minimax-m2-moe.gguf.hdr", {572, 10}},+ {"mistral3-dense.gguf.hdr", {405, 10}},+ {"mistral3-moe.gguf.hdr", {532, 10}},+ {"olmoe-moe.gguf.hdr", {560, 10}},+ {"phi3-dense.gguf.hdr", {358, 10}},+ {"qwen2-dense.gguf.hdr", {373, 10}},+ {"qwen3-dense.gguf.hdr", {421, 10}},+ {"qwen3moe-moe.gguf.hdr", {572, 10}},+ {"qwen35-dense.gguf.hdr", {399, 10}},+ {"qwen35moe-moe.gguf.hdr", {571, 10}},+ {"smollm3-dense.gguf.hdr", {389, 10}},+ {"jais2-dense.gguf.hdr", {334, 10}},+ {"lfm3.gguf.hdr", {702, 12}},};return fp;}diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/lfm3-attention-first.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm3-attention-first.npznew file mode 100644index 00000000000..c129ebafc50Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm3-attention-first.npz differdiff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/lfm3-plain.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm3-plain.npznew file mode 100644index 00000000000..15c36827aceBinary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm3-plain.npz differdiff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/lfm3-wide-query.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm3-wide-query.npznew file mode 100644index 00000000000..28b2d2de139Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm3-wide-query.npz differdiff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/lfm3.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm3.npznew file mode 100644index 00000000000..67aefb56136Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/lfm3.npz differdiff --git a/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt b/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txtindex e6c2545c0f0..c04222c2eeb 100644--- a/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt+++ b/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt@@ -114,3 +114,4 @@ starcoder-dense.gguf.hdr 4087296 rejectstarcoder2-dense.gguf.hdr 3956480 rejecttalkie-dense.gguf.hdr 4725760 rejectxverse-dense.gguf.hdr 4730752 reject+lfm3.gguf.hdr 139296 convertdiff --git a/src/frontends/gguf/tests/test_data/lfm3_media_audio.npz b/src/frontends/gguf/tests/test_data/lfm3_media_audio.npznew file mode 100644index 00000000000..d99d3c568a5Binary files /dev/null and b/src/frontends/gguf/tests/test_data/lfm3_media_audio.npz differdiff --git a/src/frontends/gguf/tests/test_data/lfm3_media_audio_stream.npz b/src/frontends/gguf/tests/test_data/lfm3_media_audio_stream.npznew file mode 100644index 00000000000..7034016ba1dBinary files /dev/null and b/src/frontends/gguf/tests/test_data/lfm3_media_audio_stream.npz differdiff --git a/src/frontends/gguf/tests/test_data/lfm3_media_omni.npz b/src/frontends/gguf/tests/test_data/lfm3_media_omni.npznew file mode 100644index 00000000000..881a6832aa0Binary files /dev/null and b/src/frontends/gguf/tests/test_data/lfm3_media_omni.npz differdiff --git a/src/frontends/gguf/tests/test_data/lfm3_media_provenance.json b/src/frontends/gguf/tests/test_data/lfm3_media_provenance.jsonnew file mode 100644index 00000000000..0fa228db685--- /dev/null+++ b/src/frontends/gguf/tests/test_data/lfm3_media_provenance.json@@ -0,0 +1,54 @@+{+ "llama_cpp": "604cc430239c76ff636c443e3400bf552b750421",+ "backend": "CPU",+ "flash_attention": false,+ "oracle_sha256": "7e2cd8f93d1c8b537f233752b3455aa003e4e966bb372fe25baa9bc1a97e8900",+ "oracle_source_sha256": "d56eb57a6a25dc1e55d9d67e79f3120dcb5313f631a5f1ab13dded2c47793110",+ "libraries": {+ "libggml-base.so": "a51c5f6feae91e2156aec23e6f2e379d4fc4792b7f523528ee01d418bfd6af66",+ "libggml-cpu.so": "9c6a8cc6ba1ec143eb124b3cd93d926d4d2f78461835f5e1963cf5b20b522343",+ "libggml.so": "96df0da39879685cb55fbf6d81504b0c099fb297106d9e10e9fc7c9bdb7ccb77",+ "libllama-common.so": "e7c66e9c347e6427856e7eb766213c5dd1cdcedd23d900cfa83411e74ae5ab01",+ "libllama-quantize-impl.so": "71dd69628a67d9872dda0d3a68b6fa5c4cd2d2632c2d9ab5633146f5ce3f5586",+ "libllama.so": "93ab5a8d2b74e9208676592b9733d23a3be2f7bee6ff343653b8bfd26eed2cc2",+ "libmtmd.so": "115ffdc7cd7c62b5603bd7bda005a467944b517951e08995e7c7806ad6fc2db2"+ },+ "fixtures": [+ {+ "file": "lfm3_media_vision.npz",+ "sha256": "e2a9439d11b3cfdb65eb14f09d12a32f5d5f354525d4bdad92206943e408c29e",+ "cases": 2+ },+ {+ "file": "lfm3_media_audio.npz",+ "sha256": "4f837208839c1e8e5d24f957514c8b5ae02e5d2a52d8187dc7c1617adbaa144a",+ "cases": 2+ },+ {+ "file": "lfm3_media_audio_stream.npz",+ "sha256": "5734ce114b37915a7699c75d790bce1c357a0521f3223d4f32cad756b533e314",+ "cases": 2+ },+ {+ "file": "lfm3_media_omni.npz",+ "sha256": "3560658127a9e12b2b3f7c3a48eaeab75a06ea1637de90d7a446d80268f346f6",+ "independent_components": [+ {+ "file": "lfm3_media_vision.npz",+ "sha256": "afa6dd8702b1bf62fd941e357c7bfde868595cff5ee3333152f66f8de26831a5",+ "cases": 2+ },+ {+ "file": "lfm3_media_audio.npz",+ "sha256": "aad1cd4038be13caf5972bfdcd09b6094a5fb40691158a8141ec4f0bea4b50a6",+ "cases": 2+ },+ {+ "file": "lfm3_speech.npz",+ "sha256": "6693f663050f5853d0e1abdefbe52164b3552e1f51ca8c9ddbc8820678a2bb61"+ }+ ],+ "language_width": 6+ }+ ]+}diff --git a/src/frontends/gguf/tests/test_data/lfm3_media_vision.npz b/src/frontends/gguf/tests/test_data/lfm3_media_vision.npznew file mode 100644index 00000000000..214eb4eac5bBinary files /dev/null and b/src/frontends/gguf/tests/test_data/lfm3_media_vision.npz differdiff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/lfm3_speech.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/lfm3_speech.npznew file mode 100644index 00000000000..8ee28703752Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/lfm3_speech.npz differdiff --git a/src/frontends/gguf/tests/test_lfm3_media.cpp b/src/frontends/gguf/tests/test_lfm3_media.cppnew file mode 100644index 00000000000..650c5dcb3c5--- /dev/null+++ b/src/frontends/gguf/tests/test_lfm3_media.cpp@@ -0,0 +1,321 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <cstring>+#include <filesystem>++#include "cnpy.h"+#include "common_test_utils/common_utils.hpp"+#include "gtest/gtest.h"+#include "model_contract.hpp"+#include "op_test_utils.hpp"+#include "openvino/frontend/gguf/adapt_mmproj_to_genai.hpp"+#include "openvino/frontend/gguf/extension/projector.hpp"+#include "openvino/frontend/gguf/frontend.hpp"+#include "openvino/frontend/gguf/make_stateful.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/openvino.hpp"+#include "openvino/pass/serialize.hpp"++namespace {+using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;+using ov::frontend::gguf::pass::gguf_recurrent_states_key;+using ov::frontend::gguf::pass::GGUFMakeStateful;++void expect_nmse(const ov::Tensor& actual, const cnpy::NpyArray& expected) {+ ASSERT_EQ(actual.get_size(), expected.num_vals);+ ov_gguf_test::expect_nmse_below(+ ov_gguf_test::nmse(actual.data<const float>(), expected.data<float>(), expected.num_vals),+ 1e-5);+}++ov::Tensor tensor(const cnpy::NpyArray& value, ov::element::Type type = ov::element::f32) {+ ov::Tensor result(type, ov::Shape(value.shape.begin(), value.shape.end()));+ std::memcpy(result.data(), value.data<char>(), result.get_byte_size());+ return result;+}++class GGUFTestLfm3Media : public ::testing::TestWithParam<std::string> {};++TEST_P(GGUFTestLfm3Media, IndependentCpuEncoderAndStates) {+ const auto family = GetParam();+ const auto path = std::filesystem::path(ov_gguf_test::test_data_dir()) / ("lfm3_media_" + family + ".npz");+ ASSERT_TRUE(std::filesystem::is_regular_file(path)) << "Generate with gen_lfm3_media_fixtures.py";+ const auto arrays = cnpy::npz_load(path.string());+ const std::map<std::string, cnpy::NpyArray> data(arrays.begin(), arrays.end());+ ov_gguf_test::TemporaryGguf fixture(data.at("model"));+ const auto model_path = std::filesystem::path(fixture.path);+ const bool vision = family == "vision";+ const bool streaming = family == "audio_stream";+ ov::frontend::gguf::FrontEnd frontend;+ auto native = frontend.convert(frontend.load(model_path.string()));+ ov::Core core;+ for (const bool adapted : {false, true}) {+ auto model = native->clone();+ if (adapted) {+ ASSERT_TRUE(Adapter(vision ? Adapter::Modality::VISION : Adapter::Modality::AUDIO).run_on_model(model));+ }+ const auto pairs = model->has_rt_info(gguf_recurrent_states_key())+ ? model->get_rt_info<std::vector<std::string>>(gguf_recurrent_states_key())+ : std::vector<std::string>{};+ auto compiled = core.compile_model(+ model,+ "CPU",+ {{ov::hint::inference_precision.name(), ov::element::f32}, {"DYNAMIC_QUANTIZATION_GROUP_SIZE", 0}});+ auto request = compiled.create_infer_request();+ std::map<std::string, ov::Tensor> states;+ for (size_t i = 0; i < pairs.size(); i += 2) {+ auto zero = ov::Tensor(ov::element::f32, model->input(pairs[i]).get_shape());+ std::memset(zero.data(), 0, zero.get_byte_size());+ states.emplace(pairs[i], zero);+ }+ for (size_t step = 0; step < 2; ++step) {+ const auto key = std::to_string(step) + ".";+ for (const auto& input : compiled.inputs()) {+ const auto name = input.get_any_name();+ const auto state = states.find(name);+ if (state != states.end()) {+ if (!streaming)+ std::memset(state->second.data(), 0, state->second.get_byte_size());+ request.set_tensor(name, state->second);+ continue;+ }+ const auto short_name = name.substr(name.find('.') == std::string::npos ? 0 : name.find('.') + 1);+ request.set_tensor(+ name,+ tensor(data.at(key + short_name), short_name == "positions" ? ov::element::i32 : ov::element::f32));+ }+ request.infer();+ const auto output_name = adapted ? (vision ? "image_features" : "audio_features")+ : (vision ? "vision.embeddings" : "audio.embeddings");+ expect_nmse(request.get_tensor(output_name), data.at(key + "embeddings"));+ for (size_t i = 0; i < pairs.size(); i += 2) {+ size_t output_index = 0;+ for (; output_index < model->get_results().size(); ++output_index)+ if (model->get_results()[output_index]->get_friendly_name() == pairs[i + 1])+ break;+ ASSERT_LT(output_index, model->get_results().size());+ const auto actual = request.get_output_tensor(output_index);+ const auto slot = pairs[i].substr(std::string("audio.state.").size());+ expect_nmse(actual, data.at(key + "state." + slot));+ actual.copy_to(states.at(pairs[i]));+ }+ }+ }+ if (!vision) {+ auto model = native->clone();+ ASSERT_TRUE(Adapter(Adapter::Modality::AUDIO).run_on_model(model));+ ASSERT_TRUE(GGUFMakeStateful().run_on_model(model));+ EXPECT_EQ(model->get_variables().size(), 7);+ EXPECT_EQ(model->get_results().size(), 1);+ const auto xml = model_path.string() + ".xml";+ ov::serialize(model, xml);+ auto restored = core.read_model(xml);+ EXPECT_EQ(restored->get_variables().size(), model->get_variables().size());+ EXPECT_EQ(restored->get_rt_info<std::string>({"gguf_mmproj", "audio.streaming"}), "true");+ std::filesystem::remove(xml);+ std::filesystem::remove(model_path.string() + ".bin");+ }+}++INSTANTIATE_TEST_SUITE_P(Components,+ GGUFTestLfm3Media,+ ::testing::Values("vision", "audio", "audio_stream"),+ [](const ::testing::TestParamInfo<std::string>& info) {+ return info.param;+ });++TEST(GGUFLfm3MediaAdapter, CombinedOmniPreservesIndependentComponentsAndStates) {+ const auto path = std::filesystem::path(ov_gguf_test::test_data_dir()) / "lfm3_media_omni.npz";+ ASSERT_TRUE(std::filesystem::is_regular_file(path));+ const auto arrays = cnpy::npz_load(path.string());+ const std::map<std::string, cnpy::NpyArray> data(arrays.begin(), arrays.end());+ ov_gguf_test::TemporaryGguf fixture(data.at("model"));+ ov::frontend::gguf::FrontEnd frontend;+ const auto native = frontend.convert(frontend.load(fixture.path));+ ov::Core core;+ const auto compare = [&](const std::shared_ptr<ov::Model>& model,+ const std::map<std::string, std::string>& outputs,+ size_t state_count) {+ GGUFMakeStateful().run_on_model(model);+ auto compiled = core.compile_model(model,+ "CPU",+ {{"INFERENCE_PRECISION_HINT", "f32"},+ {"DYNAMIC_QUANTIZATION_GROUP_SIZE", 0},+ {"KV_CACHE_PRECISION", "f32"}});+ auto request = compiled.create_infer_request();+ for (const auto& input : compiled.inputs()) {+ const auto name = input.get_any_name();+ const auto source = data.count(name) ? name+ : data.count("vision." + name) ? "vision." + name+ : "audio." + name;+ ASSERT_TRUE(data.count(source)) << source;+ request.set_tensor(name, tensor(data.at(source), input.get_element_type()));+ }+ request.infer();+ for (const auto& [output, reference] : outputs) {+ const auto& expected = data.at("expected." + reference);+ if (reference == "vision.embeddings" || reference == "audio.embeddings") {+ expect_nmse(request.get_tensor(output), expected);+ } else {+ ov_gguf_test::expect_near(request.get_tensor(output),+ {expected.data<float>(), expected.data<float>() + expected.num_vals});+ }+ }+ const auto states = request.query_state();+ ASSERT_EQ(states.size(), state_count);+ for (const auto& state : states) {+ const auto& expected = data.at("state." + state.get_name());+ auto actual = state.get_state();+ if (state.get_name().find("conv") != std::string::npos && actual.get_size() != expected.num_vals) {+ const auto shape = actual.get_shape();+ const auto channels = shape[shape.size() - 2];+ actual = ov_gguf_test::trailing_conv_taps(actual, channels, expected.num_vals / channels);+ }+ if (state.get_name().rfind("audio.state.", 0) == 0) {+ expect_nmse(actual, expected);+ } else {+ ov_gguf_test::expect_near(actual, {expected.data<float>(), expected.data<float>() + expected.num_vals});+ }+ }+ };+ compare(native->clone(),+ {{"vision.embeddings", "vision.embeddings"},+ {"audio.embeddings", "audio.embeddings"},+ {"audio.depth_logits", "audio.depth_logits"},+ {"audio.feedback", "audio.feedback"},+ {"audio.spectrogram", "audio.spectrogram"}},+ 20);+ auto vision = native->clone();+ Adapter vision_adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);+ ASSERT_TRUE(vision_adapter.run_on_model(vision));+ ASSERT_EQ(vision_adapter.get_vision_models().size(), 1);+ compare(vision, {{"image_features", "vision.embeddings"}}, 0);+ auto audio = native->clone();+ ASSERT_TRUE(Adapter(Adapter::Modality::AUDIO).run_on_model(audio));+ compare(audio, {{"audio_features", "audio.embeddings"}}, 7);+ auto generation = native->clone();+ Adapter generation_adapter(Adapter::Modality::AUDIO_GENERATION);+ ASSERT_TRUE(generation_adapter.run_on_model(generation));+ const auto& models = generation_adapter.get_audio_generation_models();+ compare(models.at("depthformer"), {{"audio.depth_logits", "audio.depth_logits"}}, 0);+ compare(models.at("feedback"), {{"audio.feedback", "audio.feedback"}}, 0);+ compare(models.at("codec"), {{"audio.spectrogram", "audio.spectrogram"}}, 13);+ const auto xml = fixture.path + ".xml";+ ov::serialize(models.at("codec"), xml);+ compare(core.read_model(xml), {{"audio.spectrogram", "audio.spectrogram"}}, 13);+ std::filesystem::remove(xml);+ std::filesystem::remove(fixture.path + ".bin");+}++ov::frontend::gguf::ProjectorDefinition lfm3_replacement(const std::string& modality,+ ov::frontend::gguf::ProjectorDefinition::BuildFn build) {+ const auto type = modality == "vision" ? "lfm3vl" : "lfm3a";+ return {"clip." + modality + "." + type, "clip", modality, type, std::move(build), {}};+}++TEST(GGUFLfm3MediaAdapter, BuiltinProjectorHelperBuildsLfm3Types) {+ using namespace ov::frontend::gguf;+ for (const std::string modality : {"vision", "audio"}) {+ SCOPED_TRACE(modality);+ const auto path = std::filesystem::path(ov_gguf_test::test_data_dir()) / ("lfm3_media_" + modality + ".npz");+ ASSERT_TRUE(std::filesystem::is_regular_file(path)) << "Generate with gen_lfm3_media_fixtures.py";+ const auto arrays = cnpy::npz_load(path.string());+ const std::map<std::string, cnpy::NpyArray> data(arrays.begin(), arrays.end());+ ov_gguf_test::TemporaryGguf fixture(data.at("model"));+ FrontEnd reference_frontend;+ auto reference = reference_frontend.convert(reference_frontend.load(fixture.path));+ FrontEnd frontend;+ frontend.add_extension(std::make_shared<ProjectorExtension>(+ lfm3_replacement(+ modality,+ [modality](GgufGraphContext& graph) {+ return build_builtin_projector(graph, modality, modality == "vision" ? "lfm3vl" : "lfm3a");+ }),+ RegistrationMode::Replace));+ auto model = frontend.convert(frontend.load(fixture.path));+ EXPECT_EQ(model->get_ordered_ops().size(), reference->get_ordered_ops().size());+ EXPECT_EQ(model->inputs().size(), reference->inputs().size());+ EXPECT_NO_THROW(model->output(modality + ".embeddings"));+ }+}++TEST(GGUFLfm3MediaAdapter, ProjectorSuppliedContractIsPreserved) {+ using namespace ov::frontend::gguf;+ const auto path = std::filesystem::path(ov_gguf_test::test_data_dir()) / "lfm3_media_audio.npz";+ ASSERT_TRUE(std::filesystem::is_regular_file(path)) << "Generate with gen_lfm3_media_fixtures.py";+ const auto arrays = cnpy::npz_load(path.string());+ const std::map<std::string, cnpy::NpyArray> data(arrays.begin(), arrays.end());+ ov_gguf_test::TemporaryGguf fixture(data.at("model"));+ FrontEnd frontend;+ frontend.add_extension(std::make_shared<ProjectorExtension>(+ lfm3_replacement(+ "audio",+ [](GgufGraphContext& graph) {+ ModelContract contract;+ contract.batchable_recurrent = true;+ contract.component_groups["audio"] = {"custom",+ {{"custom", {{"audio.embeddings"}, "audio.custom_state."}}}};+ graph.configure_model_contract(contract);+ auto input = graph.add_input("audio.custom", ov::element::f32, {1, 1, 2, 2});+ return ProjectorResult{graph.node("GGML_OP_SCALE", {input}, 0, {{"scale", 2.f}, {"bias", 0.f}}), {}};+ }),+ RegistrationMode::Replace));+ auto model = frontend.convert(frontend.load(fixture.path));+ const auto contract = read_model_contract(model);+ EXPECT_EQ(contract.batchable_recurrent, std::optional<bool>(true));+ const auto& group = contract.component_groups.at("audio");+ EXPECT_EQ(group.primary, "custom");+ EXPECT_EQ(group.models.size(), 1);+ EXPECT_EQ(group.models.at("custom").state_prefix, "audio.custom_state.");+ EXPECT_EQ(group.models.at("custom").outputs, std::vector<std::string>{"audio.embeddings"});+}++TEST(GGUFLfm3MediaAdapter, IndependentGenerationMapsPreserveCodecState) {+ auto depth = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, -1, 12, 2017});+ depth->set_friendly_name("audio.depth.hidden_states");+ auto feedback = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, 16});+ feedback->set_friendly_name("audio.feedback.codes");+ auto spectrum = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, 1282});+ spectrum->set_friendly_name("audio.codec.codes");+ auto state = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, 1, 1});+ state->set_friendly_name("audio.codec.state.pos");+ state->output(0).set_names({"audio.codec.state.pos"});+ auto update = std::make_shared<ov::op::v1::Add>(state, ov::op::v0::Constant::create(ov::element::f32, {}, {1.f}));+ update->output(0).set_names({"codec_position_update"});+ depth->output(0).set_names({"audio.depth_logits"});+ feedback->output(0).set_names({"audio.feedback"});+ spectrum->output(0).set_names({"audio.spectrogram"});+ auto model = std::make_shared<ov::Model>(ov::OutputVector{depth, feedback, spectrum, update},+ ov::ParameterVector{depth, feedback, spectrum, state});+ model->get_results().back()->set_friendly_name("codec_position_update");+ ov::frontend::gguf::ModelContract contract;+ contract.component_groups["audio_generation"] = {"depthformer",+ {{"depthformer", {{"audio.depth_logits"}, ""}},+ {"feedback", {{"audio.feedback"}, ""}},+ {"codec", {{"audio.spectrogram"}, "audio.codec.state."}}}};+ ov::frontend::gguf::write_model_contract(model, contract);+ model->get_rt_info()[gguf_recurrent_states_key()] =+ std::vector<std::string>{"audio.codec.state.pos", "codec_position_update"};+ for (const bool stateful : {false, true}) {+ auto source = model->clone();+ if (stateful) {+ ASSERT_TRUE(GGUFMakeStateful().run_on_model(source));+ }+ Adapter adapter(Adapter::Modality::AUDIO_GENERATION);+ ASSERT_TRUE(adapter.run_on_model(source));+ const auto& models = adapter.get_audio_generation_models();+ ASSERT_EQ(models.size(), 3);+ EXPECT_EQ(models.at("depthformer"), source);+ EXPECT_EQ(models.at("depthformer")->get_parameters().size(), 1);+ EXPECT_EQ(models.at("feedback")->get_parameters().size(), 1);+ EXPECT_EQ(models.at("codec")->get_parameters().size(), stateful ? 1 : 2);+ EXPECT_EQ(models.at("codec")->get_sinks().size(), stateful ? 1 : 0);+ EXPECT_EQ(models.at("depthformer")->get_sinks().size(), 0);+ EXPECT_EQ(models.at("feedback")->get_sinks().size(), 0);+ }+}+} // namespacediff --git a/src/frontends/gguf/tests/test_lfm3_speech.cpp b/src/frontends/gguf/tests/test_lfm3_speech.cppnew file mode 100644index 00000000000..92957275275--- /dev/null+++ b/src/frontends/gguf/tests/test_lfm3_speech.cpp@@ -0,0 +1,163 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <algorithm>+#include <cmath>+#include <filesystem>+#include <limits>++#include "cnpy.h"+#include "gtest/gtest.h"+#include "op_test_utils.hpp"+#include "openvino/frontend/extension/decoder_transformation.hpp"+#include "openvino/frontend/gguf/make_stateful.hpp"+#include "openvino/openvino.hpp"++namespace {+class GGUFLfm3Speech : public ::testing::Test {+protected:+ void SetUp() override {+ const auto path = std::filesystem::path(ov_gguf_test::test_data_dir()) / "mmproj_accuracy/lfm3_speech.npz";+ ASSERT_TRUE(std::filesystem::exists(path)) << "Regenerate with gen_lfm3_speech_fixtures.py";+ arrays = cnpy::npz_load(path.string());+ fixture = std::make_unique<ov_gguf_test::TemporaryGguf>(ov_gguf_test::npz_array(arrays, "model"));+ ov::frontend::gguf::FrontEnd frontend;+ frontend.add_extension(std::make_shared<ov::frontend::DecoderTransformationExtension>(+ ov::frontend::gguf::pass::GGUFMakeStateful()));+ auto model = frontend.convert(frontend.load(fixture->path));+ ov::Core core;+ compiled = core.compile_model(model,+ "CPU",+ {{"INFERENCE_PRECISION_HINT", "f32"},+ {"DYNAMIC_QUANTIZATION_GROUP_SIZE", 0},+ {"KV_CACHE_PRECISION", "f32"}});+ request = compiled.create_infer_request();+ }+ std::vector<float> floats(const std::string& name) const {+ const auto& values = ov_gguf_test::npz_array(arrays, name);+ return {values.data<float>(), values.data<float>() + values.num_vals};+ }+ void input(const std::string& name, const ov::Shape& shape, const std::vector<float>& values) {+ ov::Tensor tensor(ov::element::f32, shape);+ std::copy(values.begin(), values.end(), tensor.data<float>());+ request.set_tensor(name, tensor);+ }+ void codes(const std::string& name, size_t offset, size_t frames, bool masked = false) {+ ov::Tensor tensor(ov::element::i32, {1, 1, frames, 12});+ const auto* source =+ ov_gguf_test::npz_array(arrays, name == "audio.codec.codes" ? "codes" : "depth_codes").data<int32_t>();+ std::copy_n(source + offset * 12, frames * 12, tensor.data<int32_t>());+ if (masked)+ std::fill_n(tensor.data<int32_t>(), tensor.get_size(), 0);+ request.set_tensor(name, tensor);+ }+ void prepare(size_t offset, size_t frames, size_t base, int phase) {+ input("audio.depth.hidden_states", {1, 1, 9, 6}, floats("hidden"));+ codes("audio.depth.codes", 0, 9, phase == 0);+ codes("audio.feedback.codes", 0, 9);+ codes("audio.codec.codes", offset, frames);+ std::vector<float> mask(9 * 12);+ for (size_t frame = 0; frame < 9; ++frame)+ for (size_t book = 0; book < 12; ++book)+ mask[frame * 12 + book] = phase == 0 ? 0.f : float(book % 3 == 0);+ input("audio.depth.mask", {1, 1, 9, 12}, mask);+ const auto count = 6 * frames;+ ov::Tensor positions(ov::element::i32, {1, 1, 1, count});+ for (size_t i = 0; i < count; ++i)+ positions.data<int32_t>()[i] = int32_t(base + i);+ request.set_tensor("audio.codec.positions", positions);+ std::vector<float> attention(count * (29 + count), -std::numeric_limits<float>::infinity());+ for (size_t q = 0; q < count; ++q)+ for (size_t k = q; k <= q + 29; ++k)+ if (int64_t(base) - 29 + int64_t(k) >= 0)+ attention[q * (29 + count) + k] = 0.f;+ input("audio.codec.attention_mask", {1, 1, count, 29 + count}, attention);+ }+ void check_depth(int phase) {+ std::vector<float> expected, feedback;+ for (size_t frame = 0; frame < 9; ++frame) {+ const auto value = floats("depth_" + std::to_string(phase) + "_" + std::to_string(frame));+ expected.insert(expected.end(), value.begin(), value.end());+ const auto embedding = floats("feedback_" + std::to_string(frame));+ feedback.insert(feedback.end(), embedding.begin(), embedding.end());+ }+ ov_gguf_test::expect_near(request.get_tensor("audio.depth_logits"), expected);+ ov_gguf_test::expect_near(request.get_tensor("audio.feedback"), feedback);+ }+ void check_state(int step) {+ const auto states = request.query_state();+ ASSERT_EQ(states.size(), 13);+ for (const auto& state : states) {+ const auto name = state.get_name();+ const auto prefix = std::string("audio.codec.state.");+ ASSERT_EQ(name.find(prefix), 0);+ auto slot = name.substr(prefix.size());+ std::replace(slot.begin(), slot.end(), '.', '_');+ const auto expected = floats("state_" + std::to_string(step) + "_gen_state_" + slot);+ auto actual = state.get_state();+ SCOPED_TRACE(name + " " + ov::PartialShape(actual.get_shape()).to_string());+ if (slot.find("conv_") == 0) {+ // GGUFMakeStateful retains one extra sample for causal-convolution fusion.+ ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 512, 4}));+ actual = ov_gguf_test::trailing_conv_taps(actual, 512, 3);+ }+ ov_gguf_test::expect_near(actual, expected);+ }+ }+ void check_spectrum(int step, size_t frames) {+ const auto actual = request.get_tensor("audio.spectrogram");+ const auto expected = floats("spectra_" + std::to_string(step));+ ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 1, 6 * frames, 1282}));+ ASSERT_EQ(actual.get_size(), expected.size());+ for (size_t i = 0; i < actual.get_size(); ++i)+ ASSERT_TRUE(std::isfinite(actual.data<const float>()[i])) << i;+ ov_gguf_test::expect_nmse_below(+ ov_gguf_test::nmse(actual.data<const float>(), expected.data(), actual.get_size()),+ 1e-5);+ }+ cnpy::npz_t arrays;+ std::unique_ptr<ov_gguf_test::TemporaryGguf> fixture;+ ov::CompiledModel compiled;+ ov::InferRequest request;+};++TEST_F(GGUFLfm3Speech, MaskedAndRevealedBidirectionalDepthAndFeedback) {+ for (int phase = 0; phase < 2; ++phase) {+ for (auto state : request.query_state())+ state.reset();+ prepare(0, 1, 0, phase);+ request.infer();+ check_depth(phase);+ }+}++TEST_F(GGUFLfm3Speech, StreamingSpectraStateResetAndWindowBoundary) {+ const size_t counts[] = {1, 2, 6, 2, 9};+ size_t offset = 0, base = 0;+ for (int step = 0; step < 5; ++step) {+ SCOPED_TRACE("codec step " + std::to_string(step));+ if (step >= 3) {+ for (auto state : request.query_state())+ state.reset();+ offset = step == 3 ? 1 : 0;+ base = 0;+ }+ prepare(offset, counts[step], base, 1);+ request.infer();+ check_spectrum(step, counts[step]);+ check_state(step);+ offset += counts[step];+ base += counts[step] * 6;+ }+}++TEST_F(GGUFLfm3Speech, FiniteScalarCodebookBoundaries) {+ prepare(0, 1, 0, 0);+ const auto source = request.get_tensor("audio.codec.codes");+ ASSERT_EQ(source.data<int32_t>()[0], 0);+ ASSERT_EQ(source.data<int32_t>()[1], 2015);+ request.infer();+ check_spectrum(0, 1);+}+} // namespacediff --git a/src/frontends/gguf/tests/test_mmproj.cpp b/src/frontends/gguf/tests/test_mmproj.cppindex 77b5c0ce22c..03c34d61cac 100644--- a/src/frontends/gguf/tests/test_mmproj.cpp+++ b/src/frontends/gguf/tests/test_mmproj.cpp@@ -4,7 +4,9 @@#include <algorithm>#include <cmath>+#include <cstring>#include <filesystem>+#include <sstream>#include "builder/api/metadata_store.hpp"#include "builder/arch_registry.hpp"@@ -15,10 +17,12 @@#include "gguf_writer.hpp"#include "gtest/gtest.h"#include "model_adapter_attribute.hpp"+#include "model_contract.hpp"#include "op_test_utils.hpp"#include "openvino/frontend/gguf/adapt_mmproj_to_genai.hpp"#include "openvino/frontend/gguf/extension/projector.hpp"#include "openvino/frontend/gguf/frontend.hpp"+#include "openvino/frontend/gguf/make_stateful.hpp"#include "openvino/op/add.hpp"#include "openvino/op/gather.hpp"#include "openvino/op/gelu.hpp"@@ -900,6 +904,33 @@ INSTANTIATE_TEST_SUITE_P(VisionEncoders,std::make_pair("qwen3vl_merger", "clip.vision.embedding_length"),std::make_pair("qwen3vl_merger", "clip.vision.attention.head_count")));+TEST(GGUFMMProjLayout, DeclaredAuxiliaryOutputsSurviveSplitMergerAndIR) {+ using namespace ov::frontend::gguf;+ using Adapter = pass::AdaptMmprojToGenAI;+ for (const bool deepstack : {false, true}) {+ SCOPED_TRACE(deepstack);+ auto model = vision_fixture("qwen3vl_merger");+ auto lengths = ov::op::v0::Constant::create(ov::element::i32, {1}, {2});+ lengths->output(0).set_names({"vision.lengths"});+ model->add_results({std::make_shared<ov::op::v0::Result>(lengths)});+ auto contract = read_model_contract(model);+ contract.component_groups["vision"] = {"encoder", {{"encoder", {{"vision.embeddings", "vision.lengths"}, ""}}}};+ write_model_contract(model, contract);+ model->set_rt_info(std::string(deepstack ? "1" : "0"), {"gguf_mmproj", "vision.auxiliary_count"});+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);+ ASSERT_TRUE(adapter.run_on_model(model));+ ASSERT_EQ(model->get_results().size(), deepstack ? 3 : 2);+ EXPECT_NO_THROW(model->output("vision.lengths"));+ if (deepstack) {+ EXPECT_NO_THROW(model->output("deepstack_feature_lists"));+ }+ auto restored = ov_gguf_test::reload_ir_model(model);+ EXPECT_NO_THROW(restored->output("vision.lengths"));+ auto compiled = ov::Core{}.compile_model(restored, "CPU");+ EXPECT_NO_THROW(compiled.output("vision.lengths"));+ }+}+TEST(GGUFMMProjLayout, RejectsMissingQwenWeightsWithoutChangingModel) {auto source = vision_fixture("qwen3vl_merger");for (const std::string tensor :@@ -997,6 +1028,16 @@ TEST_F(GGUFMMProj, LegacyGlobalProjectorTakesPrecedence) {EXPECT_NO_THROW(convert());}+TEST_F(GGUFMMProj, LegacyEncoderIgnoresUnrelatedGenerationMetadata) {+ encoder("vision", "gemma3");+ writer.kv_bool("clip.has_gen_audio_encoder", true);+ writer.kv_str("clip.gen.audio.projector_type", "lfm2a_gen");+ const auto model = convert();+ ASSERT_EQ(model->outputs().size(), 1);+ EXPECT_EQ(model->output().get_any_name(), "vision.embeddings");+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"}), "gemma3");+}+// Legacy Qwen2.5 Omni files name one global projector for both encoders.TEST_F(GGUFMMProj, Qwen25OmniResolvesProjectorPerModality) {encoder("vision", "unused_modality_key");@@ -1479,4 +1520,266 @@ INSTANTIATE_TEST_SUITE_P(Reference,"qwen3vl_merger","lfm2","lfm2_no_norm"));++std::pair<std::shared_ptr<ov::Model>, ov::frontend::gguf::ModelContract> component_contract_model() {+ const auto parameter = [](const std::string& name, const ov::Shape& shape) {+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);+ input->set_friendly_name(name);+ input->output(0).set_names({name});+ return input;+ };+ auto samples = parameter("audio.samples", {1, 1, 2, 2});+ auto score = parameter("score_input", {1, 1, 2, 2});+ auto lookup = parameter("lookup_input", {1, 1, 2, 2});+ auto render = parameter("render_input", {1, 1, 2, 2});+ auto encoder_state = parameter("audio.cache.counter", {1, 1, 1, 1});+ auto speech_state = parameter("speech.cache.counter", {1, 1, 1, 1});+ auto one = ov::op::v0::Constant::create(ov::element::f32, {}, {1.f});+ auto audio = std::make_shared<ov::op::v1::Add>(samples, encoder_state);+ auto rendered = std::make_shared<ov::op::v1::Add>(render, speech_state);+ auto encoder_update = std::make_shared<ov::op::v1::Add>(encoder_state, one);+ auto speech_update = std::make_shared<ov::op::v1::Add>(speech_state, one);+ auto window = ov::op::v0::Constant::create(ov::element::f32, {1}, {2.f});+ audio->output(0).set_names({"audio.embeddings"});+ score->output(0).set_names({"scores"});+ lookup->output(0).set_names({"lookup"});+ rendered->output(0).set_names({"rendered"});+ window->output(0).set_names({"window"});+ encoder_update->output(0).set_names({"encoder_update"});+ speech_update->output(0).set_names({"speech_update"});+ auto model = std::make_shared<ov::Model>(+ ov::OutputVector{audio, score, lookup, rendered, window, encoder_update, speech_update},+ ov::ParameterVector{samples, score, lookup, render, encoder_state, speech_state});+ model->get_results()[5]->set_friendly_name("encoder_update");+ model->get_results()[6]->set_friendly_name("speech_update");+ model->get_rt_info()["gguf_architecture"] = std::string("custom-mmproj");+ model->get_rt_info()["gguf_mmproj"] = ov::AnyMap{{"audio.projector", std::string("custom-audio")}};+ model->get_rt_info()[ov::frontend::gguf::pass::gguf_recurrent_states_key()] =+ std::vector<std::string>{"audio.cache.counter", "encoder_update", "speech.cache.counter", "speech_update"};+ ov::frontend::gguf::ModelContract contract;+ contract.component_groups = {{"audio", {"encoder", {{"encoder", {{"audio.embeddings"}, "audio.cache."}}}}},+ {"audio_generation",+ {"lookup",+ {{"score", {{"scores"}, ""}},+ {"lookup", {{"lookup"}, ""}},+ {"renderer", {{"rendered", "window"}, "speech.cache."}}}}}};+ ov::frontend::gguf::write_model_contract(model, contract);+ return {model, contract};+}++TEST(GGUFMMProjContract, DeclaredComponentsPreservePrimaryNamesStateAndIR) {+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;+ using ov::frontend::gguf::pass::GGUFMakeStateful;+ const auto native = component_contract_model().first;+ ov::Core core;+ for (const bool stateful : {false, true}) {+ for (const bool reload : {false, true}) {+ auto source = native->clone();+ if (stateful) {+ ASSERT_TRUE(GGUFMakeStateful().run_on_model(source));+ }+ if (reload)+ source = ov_gguf_test::reload_ir_model(source);+ const auto run_stream = [&](const std::shared_ptr<ov::Model>& model,+ const std::string& input,+ const std::string& output,+ const std::string& state_name,+ const ov::Shape& expected_shape) {+ GGUFMakeStateful().run_on_model(model);+ ASSERT_EQ(model->get_variables().size(), 1);+ auto request = core.compile_model(model, "CPU").create_infer_request();+ const auto states = request.query_state();+ ASSERT_EQ(states.size(), 1);+ EXPECT_EQ(states[0].get_name(), state_name);+ ov::Tensor data(ov::element::f32, {1, 1, 2, 2});+ std::fill_n(data.data<float>(), 4, 4.f);+ request.set_tensor(input, data);+ for (const float expected : {4.f, 5.f}) {+ request.infer();+ auto actual = request.get_tensor(output);+ ASSERT_EQ(actual.get_shape(), expected_shape);+ for (size_t i = 0; i < actual.get_size(); ++i)+ EXPECT_EQ(actual.data<float>()[i], expected);+ }+ request.reset_state();+ request.infer();+ EXPECT_EQ(request.get_tensor(output).data<float>()[0], 4.f);+ };+ auto audio = source->clone();+ ASSERT_TRUE(Adapter(Adapter::Modality::AUDIO).run_on_model(audio));+ if (!stateful) {+ EXPECT_EQ(audio->input("audio.cache.counter").get_any_name(), "audio.cache.counter");+ }+ run_stream(audio, "samples", "audio_features", "audio.cache.counter", {1, 2, 2});+ Adapter adapter(Adapter::Modality::AUDIO_GENERATION);+ ASSERT_TRUE(adapter.run_on_model(source));+ const auto& models = adapter.get_audio_generation_models();+ ASSERT_EQ(models.size(), 3);+ EXPECT_EQ(models.at("lookup"), source);+ EXPECT_EQ(models.at("score")->get_parameters().size(), 1);+ EXPECT_EQ(models.at("lookup")->get_parameters().size(), 1);+ EXPECT_TRUE(models.at("score")->get_sinks().empty());+ EXPECT_TRUE(models.at("lookup")->get_sinks().empty());+ auto renderer = ov_gguf_test::reload_ir_model(models.at("renderer"));+ EXPECT_EQ(renderer->output("window").get_shape(), (ov::Shape{1}));+ run_stream(renderer, "render_input", "rendered", "speech.cache.counter", {1, 1, 2, 2});+ }+ }+}++TEST(GGUFMMProjContract, StatefulPrimaryDoesNotDuplicateVariableRegistration) {+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;+ auto [model, contract] = component_contract_model();+ contract.component_groups.at("audio_generation").primary = "renderer";+ ov::frontend::gguf::write_model_contract(model, contract);+ ASSERT_TRUE(ov::frontend::gguf::pass::GGUFMakeStateful().run_on_model(model));+ ASSERT_EQ(model->get_variables().size(), 2);+ Adapter adapter(Adapter::Modality::AUDIO_GENERATION);+ ASSERT_TRUE(adapter.run_on_model(model));+ EXPECT_EQ(adapter.get_audio_generation_models().at("renderer"), model);+ ASSERT_EQ(model->get_variables().size(), 1);+ EXPECT_EQ(model->get_variables().front()->get_info().variable_id, "speech.cache.counter");+ auto restored = ov_gguf_test::reload_ir_model(model);+ EXPECT_EQ(restored->get_variables().size(), 1);+}++TEST(GGUFMMProjContract, FriendlyNameOnlyComponentOutputIsExposedByTensorName) {+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 2});+ input->output(0).set_names({"render_input"});+ auto output = std::make_shared<ov::op::v1::Add>(input, ov::op::v0::Constant::create(ov::element::f32, {}, {1.f}));+ auto model = std::make_shared<ov::Model>(ov::OutputVector{output}, ov::ParameterVector{input});+ model->get_results().front()->set_friendly_name("friendly_only");+ ASSERT_TRUE(model->get_results().front()->output(0).get_names().empty());+ model->get_rt_info()["gguf_architecture"] = std::string("custom-mmproj");+ ov::frontend::gguf::ModelContract contract;+ contract.component_groups["audio_generation"] = {"renderer", {{"renderer", {{"friendly_only"}, ""}}}};+ ov::frontend::gguf::write_model_contract(model, contract);+ for (const bool reload : {false, true}) {+ auto source = model->clone();+ if (reload)+ source = ov_gguf_test::reload_ir_model(source);+ Adapter adapter(Adapter::Modality::AUDIO_GENERATION);+ ASSERT_TRUE(adapter.run_on_model(source));+ auto component = adapter.get_audio_generation_models().at("renderer");+ EXPECT_NO_THROW(component->output("friendly_only"));+ auto restored = ov_gguf_test::reload_ir_model(component);+ EXPECT_NO_THROW(restored->output("friendly_only"));+ auto request = ov::Core{}.compile_model(restored, "CPU").create_infer_request();+ ov::Tensor data(ov::element::f32, {1, 2});+ std::fill_n(data.data<float>(), 2, 1.f);+ request.set_tensor("render_input", data);+ request.infer();+ EXPECT_EQ(request.get_tensor("friendly_only").data<float>()[0], 2.f);+ }+}++TEST(GGUFMMProjContract, DeclaredAuxiliaryOutputsSurviveExtractionCallbacksAndIR) {+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;+ using namespace ov::frontend::gguf;+ for (const std::string modality : {"vision", "audio"}) {+ for (const int mode : {0, 1, 2, 3, 4, 5}) {+ SCOPED_TRACE(modality + " mode=" + std::to_string(mode));+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, 2, 2});+ input->set_friendly_name(modality + ".samples");+ input->output(0).set_names({modality + ".samples"});+ auto embeddings =+ std::make_shared<ov::op::v1::Add>(input, ov::op::v0::Constant::create(ov::element::f32, {}, {1.f}));+ embeddings->output(0).set_names({modality + ".embeddings"});+ const bool passthrough = mode >= 3;+ auto length_input = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});+ length_input->set_friendly_name(modality + ".lengths");+ std::shared_ptr<ov::Node> lengths = passthrough ? std::static_pointer_cast<ov::Node>(length_input)+ : ov::op::v0::Constant::create(ov::element::i32, {1}, {2});+ lengths->output(0).set_names({modality + ".lengths"});+ auto discarded = ov::op::v0::Constant::create(ov::element::f32, {1}, {9.f});+ discarded->output(0).set_names({"discarded_output"});+ ov::ParameterVector inputs{input};+ if (passthrough)+ inputs.push_back(length_input);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{embeddings, lengths, discarded}, inputs);+ ModelContract contract;+ contract.component_groups[modality] = {+ "encoder",+ {{"encoder", {{modality + ".embeddings", modality + ".lengths"}, ""}}}};+ write_model_contract(model, contract);+ bool called = false;+ const std::string features = modality == "vision" ? "image_features" : "audio_features";+ if (mode % 3 == 2) {+ auto adapter = std::make_shared<ModelAdapter>();+ adapter->transform = [&](const std::shared_ptr<ov::Model>& selected) {+ called = true;+ EXPECT_EQ(selected->get_results().size(), 2);+ EXPECT_EQ(selected->output(0).get_any_name(), features);+ EXPECT_NO_THROW(selected->output(modality + ".lengths"));+ return ModelAdapterResult{selected, {}};+ };+ model->get_results().front()->get_rt_info()[ModelAdapterAttribute::get_type_info_static()] =+ ModelAdapterAttribute(adapter);+ } else if (mode % 3 == 1) {+ model = ov_gguf_test::reload_ir_model(model);+ }+ ASSERT_TRUE(Adapter(modality == "vision" ? Adapter::Modality::VISION : Adapter::Modality::AUDIO)+ .run_on_model(model));+ EXPECT_EQ(called, mode % 3 == 2);+ ASSERT_EQ(model->get_results().size(), 2);+ EXPECT_EQ(model->output(0).get_any_name(), features);+ if (passthrough) {+ ASSERT_NO_THROW(model->input("lengths"));+ }+ auto restored = ov_gguf_test::reload_ir_model(model);+ if (passthrough) {+ ASSERT_NO_THROW(restored->input("lengths"));+ }+ if (passthrough) {+ auto cloned = restored->clone();+ ASSERT_NO_THROW(cloned->input("lengths"));+ }+ auto compiled = ov::Core{}.compile_model(restored, "CPU");+ if (passthrough) {+ ASSERT_NO_THROW(compiled.input("lengths"));+ }+ auto request = compiled.create_infer_request();+ ov::Tensor data(ov::element::f32, {1, 1, 2, 2});+ std::fill_n(data.data<float>(), data.get_size(), 4.f);+ request.set_tensor("samples", data);+ if (passthrough) {+ ov::Tensor length(ov::element::i32, {1});+ length.data<int32_t>()[0] = 2;+ request.set_tensor("lengths", length);+ }+ request.infer();+ EXPECT_EQ(request.get_tensor(modality + ".lengths").data<int32_t>()[0], 2);+ auto actual = request.get_tensor(features);+ ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 2, 2}));+ for (size_t i = 0; i < actual.get_size(); ++i)+ EXPECT_EQ(actual.data<float>()[i], 5.f);+ }+ }+}++TEST(GGUFMMProjContract, InvalidComponentsLeaveSourceUnchanged) {+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;+ auto [model, contract] = component_contract_model();+ contract.component_groups.at("audio_generation").models.at("renderer").outputs.push_back("missing_output");+ ov::frontend::gguf::write_model_contract(model, contract);+ const auto parameters = model->get_parameters();+ const auto results = model->get_results();+ const auto states = model->get_rt_info()[ov::frontend::gguf::pass::gguf_recurrent_states_key()];+ Adapter adapter(Adapter::Modality::AUDIO_GENERATION);+ EXPECT_THROW(adapter.run_on_model(model), ov::Exception);+ EXPECT_EQ(model->get_parameters(), parameters);+ EXPECT_EQ(model->get_results(), results);+ EXPECT_EQ(+ model->get_rt_info()[ov::frontend::gguf::pass::gguf_recurrent_states_key()].as<std::vector<std::string>>(),+ states.as<std::vector<std::string>>());+ EXPECT_TRUE(adapter.get_audio_generation_models().empty());+ contract.component_groups.at("audio_generation").primary = "missing_component";+ EXPECT_THROW(ov::frontend::gguf::write_model_contract(model, contract), ov::Exception);+ auto& groups = model->get_rt_info()["gguf_model_contract"].as<ov::AnyMap>().at("component_groups").as<ov::AnyMap>();+ groups.at("audio_generation").as<ov::AnyMap>().at("primary") = std::string("missing_component");+ EXPECT_THROW(adapter.run_on_model(model), ov::Exception);+ EXPECT_EQ(model->get_parameters(), parameters);+ EXPECT_EQ(model->get_results(), results);+}} // namespace