Skip to content

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

[GGUF] Add LFM3 packed vision layout and simplify mmproj GenAI adaptation (#39392)

Maxim Vafin02068fd3eeaf
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/projector.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/projector.hpp
index 45d61cb8177..8acb25dc9f7 100644
--- a/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/projector.hpp
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/projector.hpp
@@ -13,8 +13,16 @@
namespace ov::frontend::gguf {
-// Recipes use resolved vision.patch_size/window_size/merge and clip.* dimensions in config.
-enum class ProjectorLayout { Unsupported, Image, PaddedPatches, WindowedPatches, SplitMerger, PackedPatches };
+// Recipes use resolved vision.patch_size/temporal_patch_size/window_size/merge and clip.* dimensions in config.
+enum class ProjectorLayout {
+ Unsupported,
+ Image,
+ PaddedPatches,
+ WindowedPatches,
+ SplitMerger,
+ PackedPatches,
+ TemporalPackedPatches
+};
struct GGUF_FRONTEND_API ProjectorResult {
GgufValue output;
diff --git a/src/frontends/gguf/docs/extensions.md b/src/frontends/gguf/docs/extensions.md
index e7b1f736e7f..719cb6fe0e5 100644
--- a/src/frontends/gguf/docs/extensions.md
+++ b/src/frontends/gguf/docs/extensions.md
@@ -144,9 +144,12 @@ component list comes from `ArchRegistry::projectors().supported_projectors()`. A
than `clip` would also need its own whole-model coordinator.
The builder selects GenAI layout explicitly with `genai_layout`. Recipes describe input
-semantics (`Image`, `PaddedPatches`, `WindowedPatches`, `SplitMerger`) and are serialized with the
-model; 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.
+semantics (`Image`, `PaddedPatches`, `WindowedPatches`, `SplitMerger`, `PackedPatches`,
+`TemporalPackedPatches`) and are serialized with the model. `build_builtin_projector()` returns
+the recipe matching its graph. A result's explicit recipe overrides the definition. A new or
+replacement projector declaring neither gets `Unsupported`; it does not inherit a recipe from
+its projector name. Only legacy models without `vision.genai_layout` use a built-in recipe
+selected by `vision.projector`.
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
diff --git a/src/frontends/gguf/docs/mmproj.md b/src/frontends/gguf/docs/mmproj.md
index fd1d9faece4..5d604e48217 100644
--- a/src/frontends/gguf/docs/mmproj.md
+++ b/src/frontends/gguf/docs/mmproj.md
@@ -1,270 +1,118 @@
# Native GGUF multimodal conversion
A llama.cpp multimodal projector file (`general.architecture = clip`, usually named
-`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.
+`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
-Projector support is separate from the architecture list: `clip` selects the mmproj coordinator,
-and the per-frontend projector registry selects each vision/audio branch. Built-in entries come
-from `projector_catalog` in
-[`mmproj_builder.cpp`](../src/builder/arch/mmproj_builder.cpp). Every entry has a small
-numerical fixture checked against the llama.cpp CPU encoder (see
-[the fixture README](../tests/test_data/mmproj_accuracy/README.md)).
-
-| Modality | Projector | Graph features |
-|---|---|---|
-| Vision | `gemma3`, `idefics3`, `janus_pro` | SigLIP; fused QKV and legacy FFN names |
-| Vision | `mlp` | CLIP feature layers; normalized variant detected from tensors |
-| Vision | `internvl` | InternViT, class token, pixel-shuffle merge |
-| Vision | `resampler` | MiniCPM-V resampler, `clip.minicpmv_version` 2-6 and 100045 |
-| Vision | `minicpmv4_6` | window attention, two-stage merging |
-| Vision | `minicpmv4_7` | window-attention and direct 2x2 merging; packed-patch GenAI layout |
-| 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 |
-
-The built-in `qwen3vl_merger` projector supports BF16 and Q8_0 weights.
-
-InternViT-6B (width 3200, 45 layers) uses RMS norms like the reference, but has no fixture.
+`clip` selects the mmproj coordinator, and a separate projector registry selects each vision or
+audio branch. Built-in entries come from `projector_catalog` in
+[`mmproj_builder.cpp`](../src/builder/arch/mmproj_builder.cpp) and from the LFM3 builder.
+
+| Modality | Projectors |
+|---|---|
+| Vision | `gemma3`, `idefics3`, `janus_pro`, `mlp`, `internvl`, `resampler`, `minicpmv4_6`, `minicpmv4_7`, `qwen2vl_merger`, `qwen2.5vl_merger`, `qwen3vl_merger`, `pixtral`, `phi4`, `lfm2`, `lfm3vl`, `gemma4v`, `gemma4uv`, `muse-glimmer`, `deepseekocr`, `deepseekocr2` |
+| Audio | `gemma4a`, `gemma4ua`, `lfm2a`, `lfm3a`, `qwen2a`, `ultravox`, `voxtral`, `musicflamingo`, `meralion`, `glma` |
+| Speech generation | `lfm3a_gen`; the LFM2.5 vocoder is a separate `lfm2.audio_vocoder` architecture |
Not implemented: `ldp`, `ldpv2`, `adapter`, `step3vl`, `gemma3nv`, `llama4`, `qwen3a`,
`kimivl`, `paddleocr`, `lightonocr`, `cogvlm`, `dots_ocr`, `glm4v`, `youtuvl`, `yasa2`,
`kimik25`, `nemotron_v2_vl`, `exaone4_5`, `hunyuanvl`, `granite_speech`, `mimovl`,
-`granite4_vision`. `gemma3na` has no graph builder in the reference.
+`granite4_vision`. An unsupported projector fails conversion of the whole file.
## Validation coverage
-| Evidence | Scope and limits |
-|---|---|
-| Offline numerical fixtures | Every catalog projector has a small CPU encoder reference; tests compare raw and GenAI-adapted features |
-| Dynamic fixtures | Multiple sizes reuse one compiled model; variants are listed in the [fixture README](../tests/test_data/mmproj_accuracy/README.md) |
-| Real-checkpoint lists | [Precommit](../../../../tests/model_hub_tests/gguf/gguf_mmproj_precommit) and [nightly](../../../../tests/model_hub_tests/gguf/gguf_mmproj_nightly) select checkpoints, including combined Gemma4 and Qwen2.5-Omni files |
-| Qwen2-VL real checkpoint | CPU NMSE limit is explicitly relaxed to `2e-4`; the list records reference patch-embedding arithmetic as the reason |
-| DeepSeek-OCR real checkpoint | Skipped: model-hub input preparation does not yet implement SAM tiles/views; offline OCR fixtures remain covered |
-| Full media application | Encoder fixtures and generated-input checkpoint tests do not validate host preprocessing, media insertion, or complete VLM/audio generation |
-
-See [testing](testing.md) for commands and acceptance. A catalog entry is not a claim of coverage
-for every checkpoint, resolution, quantization, or device.
-
-## Files with multiple components
-
-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 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 the
- per-modality keys; only the legacy `qwen2.5o` resolves to a different projector per modality
- (Qwen2.5 VL vision, Qwen2 audio). An unsupported projector fails conversion of the whole file,
- so no declared modality is dropped silently.
-3. The encoders become disconnected branches of the same graph. Vision reads `v.*` tensors and
- `vision.*` inputs and produces `vision.embeddings`; audio reads `a.*` tensors and `audio.*`
- inputs and produces `audio.embeddings`.
-4. `gguf_mmproj` rt_info records each encoder's `<modality>.projector` and `<modality>.merge`.
-
-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.
+- Every catalog projector has a small numerical fixture checked against the pinned llama.cpp CPU
+ encoder, for both raw and GenAI-adapted features. Dynamic fixtures reuse one compiled model
+ across several input sizes; see the [fixture README](../tests/test_data/mmproj_accuracy/README.md).
+- [Precommit](../../../../tests/model_hub_tests/gguf/gguf_mmproj_precommit) and
+ [nightly](../../../../tests/model_hub_tests/gguf/gguf_mmproj_nightly) lists run real
+ checkpoints with generated inputs. Per-checkpoint relaxations and skips are recorded in those
+ lists.
+- Encoder tests do not validate media preprocessing, media insertion or complete VLM/audio
+ generation. A catalog entry is not a claim of coverage for every checkpoint, resolution,
+ quantization or device.
+
+See [testing](testing.md) for commands and acceptance criteria.
+
+## Files with vision and audio encoders
+
+One file may carry at most one vision and one audio encoder (for example Gemma4 and Qwen2.5-Omni).
+`clip.has_vision_encoder` / `clip.has_audio_encoder` select the encoders, and each takes its
+projector from `clip.projector_type` or the per-modality `clip.<modality>.projector_type`. The
+encoders become disconnected branches of one model: vision reads `v.*` tensors and `vision.*`
+inputs and produces `vision.embeddings`; audio uses `a.*`, `audio.*` and `audio.embeddings`.
+Declared speech-generation components are built into the same model.
## Graph boundary
-Preprocessing belongs to the caller. Activations are F32 and indices I32, except the
-explicit F32 positional inputs below. Dynamic encoders accept different spatial sizes;
-fixed-resolution encoders retain the size recorded in metadata.
+The converted graph mirrors the llama.cpp encoder graph:
-| Family | Inputs |
-|---|---|
-| Fixed-resolution vision | `vision.pixel_values [1,3,S,S]`, normalized NCHW |
-| MiniCPM resampler | `vision.pixel_values [1,3,H,W]`, learned `vision.position_ids [1,1,1,T]`, F32 `vision.position_h` / `vision.position_w [1,1,T,1]` |
-| Qwen vision | `vision.pixel_values [2,3,H,W]` (a temporal pair; repeat a still image), `vision.patch_indices [1,1,1,T]`, `vision.position_ids [1,1,1,4*T]` |
-| Qwen2.5 vision | also `vision.attention_mask [1,1,T,T]` (additive window mask) and `vision.output_indices [1,1,1,T/4]` |
-| Pixtral / Phi4 / Gemma4 vision | `vision.pixel_values [1,3,H,W]`; Pixtral and Gemma4 also `vision.position_x`, `vision.position_y [1,1,1,T]` |
-| 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)]` |
-
-Index inputs reorder patches the way the reference does: spatial grouping and windows before
-the encoder, the inverse order after it. Qwen sizes must be divisible by patch size times merge
-size. Gemma4 vision takes pixels in [0,1] and applies the reference's `2*x-1` inside the graph;
-unified vision uses patch size times projector scale factor. Gemma4 audio builds its
-12-position causal horizon and relative positions in the graph as `[T,T]` tensors, so memory
-grows quadratically with the number of frames. Missing/zero `clip.minicpmv_version` selects 2; missing/zero `clip.minicpmv_query_num`
-selects 96 queries for version 2 and 64 otherwise, and an explicit count must match the query
-tensor.
-
-Outputs are `vision.embeddings` and/or `audio.embeddings`, `[1,1,T,D]`. `qwen3vl_merger` packs
-the DeepStack features after the primary ones along `D`.
+- Preprocessing belongs to the caller: resize/crop, normalization, mel extraction and frame
+ padding follow the reference processor of each model.
+- Inputs are named `<modality>.<name>`. Besides pixels or audio features, many encoders take
+ index inputs that reorder patches the way the reference does (spatial grouping and windows
+ before the encoder, the inverse order after it), positions and additive attention masks.
+- Activations are F32 and indices I32. Dynamic encoders accept different spatial sizes;
+ fixed-resolution encoders keep the size recorded in metadata.
+- Outputs are `vision.embeddings` and/or `audio.embeddings` with shape `[1,1,T,D]`. Projectors
+ with auxiliary features (for example DeepStack) pack them after the primary features along `D`.
+- Streaming encoders and speech components expose their recurrent state as explicit inputs and
+ outputs.
+
+The exact inputs of each projector are defined by its builder.
+[`checkpoint_inputs`](../tests/mmproj_fixtures.py) shows how tests construct them; it creates
+random pixels/features and is not a media preprocessor.
## Runtime metadata
-Model rt_info `gguf_mmproj` keeps every source `clip.*` key and adds `<modality>.projector`,
-`<modality>.merge`, `vision.auxiliary_count`, the effective `vision.patch_size`,
-`vision.window_size` (Muse Glimmer) and
-`vision.minicpmv_version` / `vision.query_count` (resampler). Values are strings: numeric
-arrays are comma-separated, and string arrays are `length:value` entries flagged by a
-`<key>.encoding` companion. The metadata survives IR serialization and adaptation; supplied
-cgraph decoders return an empty map.
-
-## Preprocessing real media
-
-`GGUFMMProjAccuracy` and `GGUFMMProjDynamicAccuracy` run every projector offline from committed
-inputs and llama.cpp outputs; see [testing.md](testing.md).
-
-For real files, [model-hub commands](testing.md#real-checkpoints) reproduce encoder comparisons
-with generated inputs. [`checkpoint_inputs`](../tests/mmproj_fixtures.py) illustrates supported
-index construction; it creates random pixels/features and is not a media preprocessor.
-For real Gemma3 images, reproduce the reference resize/crop and RGB channel normalization from
-`clip.vision.image_mean` / `clip.vision.image_std` before supplying NCHW pixels. Whisper-derived
-audio needs the reference mel extraction and frame padding before `audio.features`; Gemma4 unified
-audio 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.
+Model rt_info `gguf_mmproj` keeps every source `clip.*` key and adds derived values such as
+`<modality>.projector`, `<modality>.merge`, `vision.patch_size` and `vision.genai_layout`. Values
+are strings: numeric arrays are comma-separated, and string arrays use `length:value` entries
+flagged by a `<key>.encoding` companion. The metadata survives IR serialization and adaptation.
## Using the encoders and a language model
[`AdaptMmprojToGenAI`](../include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp) keeps one
-modality and drops the other branch's inputs and prefixes. Its default `Layout::EMBEDDINGS`
-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 model
- takes `inputs_embeds [B,T,D]`; token-embedding scaling is applied once;
-- Gemma4 E2B/E4B use a separate `get_per_layer_embedding_model()` whose output feeds
- `per_layer_inputs [B,T,layers,width]`; it is not a second output of `get_embedding_model()`;
-- Gemma3 and Gemma4 outside the E2B/E4B embedding widths take `token_type_ids [B,T]`: image tokens attend
- bidirectionally within their image, in every Gemma3 layer and in Gemma4 sliding-window layers;
-- interleaved M-RoPE models take `position_ids [4,B,T]`: GenAI's sequence, time, height and width
- sections;
-- the per-layer lookup reads image, video and audio placeholders as the padding token, as HF and
- llama.cpp do;
-- Gemma4 image attention remains causal at the E2B/E4B embedding widths (1536/2560), matching
- llama.cpp; other variants allow bidirectional attention within an image in sliding-window layers.
-
-For vision, `AdaptMmprojToGenAI(Modality::VISION, Layout::VISION_ENCODERS)` rewrites the
-model to the optimum-intel export layout, allowing OpenVINO GenAI to reuse its existing
-encoders. `get_vision_models()` returns the adapted model under `vision_embeddings`, or
-the three Qwen components below; the supplied model becomes the Qwen merger. Vision layout
-construction runs on a clone and replaces the supplied graph only on success, preserving it for
-native-embedding fallback if metadata, weights or graph requirements are invalid. GGUF
-preprocessing uses llama.cpp geometry and token limits:
-
-| Projector | Models | Inputs |
-|---|---|---|
-| `gemma3` | `vision_embeddings` | `pixel_values [1,3,S,S]` |
-| `gemma4v`, `gemma4uv` | `vision_embeddings` | `pixel_values [1,P,patch*patch*3]` with patches in raster order, then padding; `image_position_ids [1,P,2]` as (x, y), -1 for padding |
-| `muse-glimmer` | `vision_embeddings` | `pixel_values [rows*cols,3*patch*patch]`, `image_grid_thw [1,3]`; window, merge and position indices are derived in the graph |
-| `minicpmv4_7` | `vision_embeddings` | packed `pixel_values [1,3,patch,N*patch]`, `position_ids [N]`, `patch_grid [2]`, `merge_index`; the two-stage merger also uses `window_index` |
-| `qwen3vl_merger` | `vision_embeddings`, `vision_embeddings_pos`, `vision_embeddings_merger` | flattened patches `hidden_states`; position-table indices `input [4,N]`; `hidden_states`, `attention_mask [1,N,N]`, `rotary_pos_emb [N,head/2]` |
-
-The adapted vision graphs preserve llama.cpp computation: Gemma4 retains GELU_QUICK unless the
-GGUF specifies GELU. Muse Glimmer GGUF files collapse HF's two-frame patch kernel,
-so the layout takes one frame per patch.
-
-GenAI selects these settings from the GGUF metadata while keeping the existing exported-model
-processor defaults. GGUF video inputs keep all supplied frames unless the caller provides
-sampled frame indices. Numerical acceptance uses the pinned llama.cpp CPU reference; an
-optimum-intel comparison checks compatibility and does not replace that reference.
-
-GenAI uses an F16 KV cache for GGUF multimodal models to match llama.cpp's default cache
-precision; explicit cache precision properties take precedence.
+modality of a converted mmproj model and rewrites it in place, so run it on a separate clone for
+each modality:
-### Gemma4 image-window parity gap
+| Mode | Result |
+|---|---|
+| `Layout::EMBEDDINGS` (default) | Native inputs without the modality prefix; `[1,T,D]` outputs `image_features` (plus `deepstack_features.N`) or `audio_features` |
+| `Modality::VISION`, `Layout::VISION_ENCODERS` | optimum-intel export layout, so OpenVINO GenAI can reuse its existing vision encoders; `get_vision_models()` returns the models |
+| `Modality::AUDIO_GENERATION` | Independent speech components from `get_audio_generation_models()` |
-GenAI-adapted GGUF masks follow Optimum-intel's sliding-window behavior in both SDPA and
-PagedAttention: tokens within the same image attend bidirectionally to the entire image
-group, even when its beginning lies outside the sliding window. Text queries still use
-the normal window. This allows reuse of existing PA implementations without a behavioral
-switch in `rt_info`; serialization or transformations can discard that metadata.
-
-The pinned llama.cpp CPU reference (`03fa73cb27f5c251b9528489b18d303b1366aca4`) clips older
-image patches at the window boundary. For example, an image spanning positions 10–150,
-query position 100 and window 64 permits keys 10–150 here, versus 37–150 in llama.cpp.
-Gemma4 and Unified multimodal logits, generated tokens and subsequent text can therefore
-diverge when image groups cross that boundary. This is an accepted integration gap, not
-quantization loss; numerical parity is not established for affected requests. Text-only
-requests and same-image keys already inside the window are unaffected by this difference.
-Native GGUF graphs before GenAI adaptation retain their supplied-mask semantics.
-
-To close the gap while supporting both reference behaviors, add an explicit serializable
-image-window policy to the PA operation contract and implement it in the target plugins,
-then emit the corresponding SDPA mask in the frontend. Do not use runtime metadata as a
-semantic switch. Retain llama.cpp comparisons and failed artifacts for affected scenarios;
-report API compatibility and SDPA/PA agreement separately from llama.cpp parity.
+`VISION_ENCODERS` follows the projector's `vision.genai_layout`:
-### Bidirectional image prefix-cache gap
+| Layout | Interface |
+|---|---|
+| `image` | Native pixel inputs are kept |
+| `padded_patches` | Raster patches followed by padding, with per-patch (x, y) positions |
+| `windowed_patches` | Flattened patches and `image_grid_thw`; window, merge and position indices are derived in the graph |
+| `split_merger` | Separate patch-embedding, position-table and merger models |
+| `packed_patches` | One packed pixel strip with positions, a patch grid and merge/window indices |
+| `temporal_packed_patches` | `[groups,rows,cols,patch features]` pixels; raster positions are derived in the graph and groups are encoded independently |
+
+Layout construction runs on a clone and replaces the model only on success, so an invalid
+layout leaves the native model available for the `EMBEDDINGS` fallback. A
+[ProjectorExtension](extensions.md#extend-mmproj-with-a-projector-component) can declare a
+built-in layout or provide its own adapter callback.
+
+`temporal_packed_patches` requires `vision.temporal_patch_size` to match the number of frame
+inputs (one or two). The LFM3 builder declares two only when `v.patch_embd.weight.1` exists;
+otherwise it declares one. The graph encodes groups sequentially using `TensorIterator`, so
+the target device must support that operation (CPU/GPU; NPU is not supported by this layout).
+It does not rely on GenAI looping over groups externally.
-The Unified fixture also exposes a separate GenAI PA prefix-cache issue: after a
-single-image request, a two-image request can differ from SDPA, and restarting image
-chat can change the generated tokens. With the same model, media and F16 KV precision,
-disabling `SchedulerConfig.enable_prefix_caching` restores backend token agreement and
-chat/reset checks. Full-prompt prefill logits agree closely before cache reuse. This
-diagnostic does not restore llama.cpp parity or waive the failing default-cache checks.
-
-Until GenAI prefix reuse handles bidirectional image groups correctly, disable prefix
-caching for affected requests. A reusable prefix must include complete image groups and
-their media identity; cached attention states cannot be reused across changed image
-context. Validate this independently of the serializable PA image-window policy above.
-
-Use language checkpoints containing Q4_0 weights for quantized generation accuracy tests;
-inspect their tensor types because files named Q4_0 can also contain Q5_K/Q6_K weights.
-Q4_0 can still diverge on close greedy choices because the CPU engines use different
-quantized arithmetic. Keep the original llama.cpp comparison and its accuracy thresholds;
-an exact F16 expansion can help distinguish arithmetic differences from integration errors.
-Q4_K_M conversion currently has an expected accuracy loss relative to llama.cpp; it retains the existing
-conversion until the plugin-side issue is resolved. Q4_K_M differences therefore do not
-establish an mmproj integration regression.
+[`AdaptToGenAI`](../include/openvino/frontend/gguf/adapt_to_genai.hpp) in `EMBEDS_TO_LOGITS`
+mode prepares the language model for media injection. The token lookup moves to
+`get_embedding_model()` and the language model takes `inputs_embeds [B,T,D]`. Depending on the
+model, it also takes `token_type_ids` for bidirectional attention within an image, `position_ids
+[4,B,T]` for interleaved M-RoPE, or per-layer inputs computed by
+`get_per_layer_embedding_model()`.
Register `GenAIExtension` before converting the language model, as described in
[runtime.md](runtime.md#stateful-and-genai-conversion). In C++, with a `FrontEndManager manager`
@@ -291,75 +139,55 @@ auto token_lookup = genai->get_embedding_model();
auto per_layer_lookup = genai->get_per_layer_embedding_model();
```
-`per_layer_lookup` is null for models without that branch. Compile the selected encoders and
-lookup models; the consumer inserts their raw features into `inputs_embeds` at the model's media
-token positions and supplies masks, positions, and any per-layer inputs. Keep model-specific
-placeholder handling and DeepStack delivery in the consumer. These passes expose graph contracts;
-they do not construct tokenizers, media preprocessing, or a complete GenAI pipeline.
+`per_layer_lookup` is null for models without that branch. The consumer inserts the encoder
+features into `inputs_embeds` at the media token positions and supplies masks, positions and any
+per-layer inputs. These passes expose graph contracts; they do not construct tokenizers, media
+preprocessing or a complete GenAI pipeline. GenAI uses an F16 KV cache for GGUF multimodal models
+to match llama.cpp, unless cache precision is set explicitly.
+
+## Speech generation components
+
+Builders declare speech components in `ModelContract::component_groups["audio_generation"]`,
+naming the primary model and each component's outputs and recurrent-state prefix. Vision and
+audio groups describe their encoders the same way, so adaptation also works after loading an
+unadapted IR. The adapter keeps only the selected component's state and prunes other branches.
+For LFM3, `lfm3a_gen` provides `depthformer`, `feedback` and `codec` models; sampling and
+waveform reconstruction belong to the caller.
+
+### LFM2 audio components
+
+LFM2.5 Audio uses the `lfm2a` encoder for audio input and the standalone `lfm2.audio_vocoder`
+GGUF (depthformer, feedback and codec) for speech output; the publisher's architecture string is
+normalized on load. The vocoder is checked against pinned publisher PyTorch fixtures. GenAI
+supplies waveform preprocessing and speech reconstruction in the `gguf-frontend-mmproj`
+integration. Older Mimi-based LFM2 speech output is not supported.
+
+## Known limitations
+
+### Gemma4 image-window parity gap
+
+GenAI-adapted Gemma4 masks follow optimum-intel: tokens of one image attend to the whole image
+even beyond the sliding window, while llama.cpp clips older image patches at the window boundary.
+Outputs can diverge when an image crosses that boundary; text-only requests are unaffected.
+Closing the gap needs an explicit serializable image-window policy in the PagedAttention
+operation, not a runtime-metadata switch.
+
+### Bidirectional image prefix-cache gap
+
+GenAI PagedAttention prefix caching can reuse attention states across changed image context, so
+multi-image and restarted image chats can differ from SDPA. Disable
+`SchedulerConfig.enable_prefix_caching` for affected requests until prefix reuse respects
+complete image groups.
+
+### Quantized language models
+
+Close greedy choices can diverge between engines because of different quantized arithmetic.
+Q4_K_M conversion has a known accuracy loss relative to llama.cpp, so Q4_K_M differences alone
+do not indicate an mmproj integration regression.
## Projector extensions
-Use [ProjectorExtension](extensions.md#extend-mmproj-with-a-projector-component) to add or replace one
-vision/audio branch under the `clip` coordinator; the [examples](../examples/architecture_extension/README.md)
-build and run one. A different whole-model format needs an `ArchitectureExtension`.
-
-## LFM2 vision projectors
-
-The `lfm2` projector supports LFM2-VL and LFM2.5-VL SigLIP encoders, resized square
-position embeddings, spatial pixel unshuffle, optional input LayerNorm and a GELU MLP.
-Native IO is `vision.pixel_values` (NCHW) plus `vision.merge_indices` (row-major indices
-grouped by each spatial merge window). The embedding adapter preserves these inputs and
-exposes `image_features`. The `VISION_ENCODERS` adapter exposes the same native pixels
-and merge-index layout for a GenAI LFM2 vision encoder.
-
-Two nonzero F32 fixtures compare raw and adapted embeddings at multiple rectangular sizes
-on one compiled model, with and without projector input normalization. LFM2-VL-450M's
-Q8_0 projector from `LiquidAI/LFM2-VL-450M-GGUF` revision
-`7cf9679aa137039135e342aa77014f7b5f2bef73` matches a represented-F32 llama.cpp CPU
-reference at 256x128 and 128x192 pixels with NMSE `1.79e-6` and `7.38e-7`. This validates
-the encoder graph, not image preprocessing, chat assembly or full multimodal generation.
-
-## LFM2 audio components
-
-The `lfm2a` audio projector supports the LFM2/LFM2.5 conformer encoder: depthwise
-subsampling, relative-position attention, half-step feed-forward branches, temporal
-convolution and the GELU language projection. Native inputs are `audio.features`
-`[1,1,mel_bins,frames]` and `audio.pos_emb`
-`[1,1,2*ceil(frames/8)-1,encoder_width]`, with interleaved sine/cosine positions.
-The audio adapter exposes `features`, `pos_emb` and `audio_features` `[1,tokens,hidden]`.
-GenAI supplies mono 16 kHz waveform preprocessing; the frontend accepts features.
-
-A pinned llama.cpp fixture checks 49/101/49 frames on one compiled model. The
-LFM2.5-Audio-1.5B Q4_0 encoder from LiquidAI revision
-`7d525f883a077e20afb782f2ff618edcae0e39e4` matches exact F32 expansions of the same
-weights with NMSE `3.81e-10` and `2.35e-9`. This is represented-F32 reference parity.
-
-LFM2.5 Audio's separate vocoder GGUF is a standalone speech-component architecture,
-`lfm2.audio_vocoder`, with `depthformer_n_layer`/`depthformer_n_embd` metadata. The
-publisher's `general.architecture` string, `this model cannot be used as LLM, use it
-via --model-vocoder in TTS examples`, is normalized to `lfm2.audio_vocoder` during
-loading for compatibility. Only the canonical name appears in the architecture catalog.
-It exposes
-`audio.depth_logits`, summed `audio.feedback`, averaged `audio.codec_features`, and
-`audio.istft_window`. Its `lfm2` detokenizer uses a 1282-channel `dense_2` spectral
-head and preserves all frames, including after GenAI adaptation. Pinned publisher
-PyTorch fixtures check depthformer outputs and detokenizer sliding-window boundaries.
-Actual Q4_0 depthformer and detokenizer represented-F32 comparisons have NMSE
-`2.62e-12` and `1.32e-9`; feedback and codec lookups match exactly.
-
-The GenAI `gguf-frontend-mmproj` integration supplies audio input through
-`VLMPipeline` and LFM2.5 speech output through `OmniPipeline`, including audio
-feedback and 24 kHz ISTFT reconstruction. Older Mimi-based LFM2 speech output
-requires a different codec and is not covered by the LFM2.5 vocoder builder.
-
-Final GenAI acceptance used the same pinned LFM2.5 audio bundle and the
-LFM2-VL-450M language/projector pair. Audio SDPA and PagedAttention each matched
-109/109 greedy reference choices over text, spoken input, multiple/reversed clips,
-audio chat and reset. Vision SDPA/PagedAttention passed seven scenarios each for
-square, JPEG and tiled inputs, including reversed images and both chat APIs.
-These are teacher-forced greedy-choice checks on the generated history, not
-strict full-logit parity or identical free-running speech reference generation.
-Speech API tests check deterministic repeated output, waveform chunk reconstruction,
-text-only output, retained audio inputs, cancellation recovery and sequential TTS.
-Speech chunks are delivered after decoding the complete waveform; low-latency
-streaming and replay of assistant codec tokens in chat history are not implemented.
+Use [ProjectorExtension](extensions.md#extend-mmproj-with-a-projector-component) to add or
+replace one vision/audio branch under the `clip` coordinator; the
+[examples](../examples/architecture_extension/README.md) build and run one. A different
+whole-model format needs an `ArchitectureExtension`.
diff --git a/src/frontends/gguf/src/builder/arch/lfm3_projector_builder.cpp b/src/frontends/gguf/src/builder/arch/lfm3_projector_builder.cpp
index f1a7e939172..5b8f8866c56 100644
--- a/src/frontends/gguf/src/builder/arch/lfm3_projector_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/lfm3_projector_builder.cpp
@@ -31,7 +31,8 @@ public:
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")) {
+ const auto temporal = g.tensors().has("v.patch_embd.weight.1") ? 2 : 1;
+ if (temporal == 2) {
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",
@@ -74,8 +75,11 @@ public:
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"}};
+ result.genai_layout = ProjectorLayout::TemporalPackedPatches;
+ result.config = {{"vision.merge", "2"},
+ {"vision.patch_size", std::to_string(patch)},
+ {"vision.temporal_patch_size", std::to_string(temporal)},
+ {"vision.streaming", "false"}};
return result;
}
diff --git a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
index e7e80334923..75369530e62 100644
--- a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
@@ -65,6 +65,7 @@ struct ProjectorTopology {
const char* name;
EncoderTopology topology;
unsigned traits = 0;
+ ProjectorLayout genai_layout = ProjectorLayout::Unsupported;
};
// Entries describe implemented graph topologies, independently of language DecoderConfig.
@@ -73,16 +74,16 @@ constexpr ProjectorTopology projector_catalog[] = {
{"vision", "deepseekocr2", EncoderTopology::OCR2, RMS_NORM},
{"vision", "pixtral", EncoderTopology::PIXTRAL, RMS_NORM},
{"vision", "phi4", EncoderTopology::PHI4},
- {"vision", "lfm2", EncoderTopology::LFM2},
- {"vision", "muse-glimmer", EncoderTopology::MUSE_GLIMMER},
- {"vision", "gemma4v", EncoderTopology::GEMMA4, RMS_NORM},
- {"vision", "gemma4uv", EncoderTopology::UNIFIED_VISION},
+ {"vision", "lfm2", EncoderTopology::LFM2, 0, ProjectorLayout::Image},
+ {"vision", "muse-glimmer", EncoderTopology::MUSE_GLIMMER, 0, ProjectorLayout::WindowedPatches},
+ {"vision", "gemma4v", EncoderTopology::GEMMA4, RMS_NORM, ProjectorLayout::PaddedPatches},
+ {"vision", "gemma4uv", EncoderTopology::UNIFIED_VISION, 0, ProjectorLayout::PaddedPatches},
{"audio", "gemma4a", EncoderTopology::GEMMA4_AUDIO},
{"audio", "lfm2a", EncoderTopology::LFM2_AUDIO},
{"audio", "gemma4ua", EncoderTopology::UNIFIED_AUDIO},
{"vision", "minicpmv4_6", EncoderTopology::MINICPM46},
- {"vision", "minicpmv4_7", EncoderTopology::MINICPM46},
- {"vision", "gemma3", EncoderTopology::SIGLIP, SWAPPED_FFN},
+ {"vision", "minicpmv4_7", EncoderTopology::MINICPM46, 0, ProjectorLayout::PackedPatches},
+ {"vision", "gemma3", EncoderTopology::SIGLIP, SWAPPED_FFN, ProjectorLayout::Image},
{"vision", "idefics3", EncoderTopology::SIGLIP, SWAPPED_FFN},
{"vision", "janus_pro", EncoderTopology::SIGLIP},
{"vision", "mlp", EncoderTopology::CLIP, SWAPPED_FFN},
@@ -90,7 +91,7 @@ constexpr ProjectorTopology projector_catalog[] = {
{"vision", "resampler", EncoderTopology::RESAMPLER},
{"vision", "qwen2vl_merger", EncoderTopology::QWEN, SWAPPED_FFN},
{"vision", "qwen2.5vl_merger", EncoderTopology::QWEN, RMS_NORM | SWAPPED_FFN},
- {"vision", "qwen3vl_merger", EncoderTopology::QWEN},
+ {"vision", "qwen3vl_merger", EncoderTopology::QWEN, 0, ProjectorLayout::SplitMerger},
{"audio", "qwen2a", EncoderTopology::WHISPER, POOL_2},
{"audio", "ultravox", EncoderTopology::WHISPER},
{"audio", "voxtral", EncoderTopology::WHISPER, POOL_2},
@@ -1331,6 +1332,14 @@ private:
} // namespace
+ProjectorLayout builtin_projector_layout(const std::string& projector_type) {
+ for (const auto& entry : projector_catalog) {
+ if (std::string(entry.modality) == "vision" && projector_type == entry.name)
+ return entry.genai_layout;
+ }
+ return ProjectorLayout::Unsupported;
+}
+
ProjectorResult build_builtin_projector(GgufGraphContext& graph,
const std::string& modality,
const std::string& projector_type) {
diff --git a/src/frontends/gguf/src/builder/arch/projector_adapter.cpp b/src/frontends/gguf/src/builder/arch/projector_adapter.cpp
index f66b8d60158..447574472b8 100644
--- a/src/frontends/gguf/src/builder/arch/projector_adapter.cpp
+++ b/src/frontends/gguf/src/builder/arch/projector_adapter.cpp
@@ -4,12 +4,14 @@
#include "projector_adapter.hpp"
+#include <algorithm>
#include <limits>
-#include <stdexcept>
+#include <unordered_set>
#include <utility>
#include "openvino/core/graph_util.hpp"
#include "openvino/op/add.hpp"
+#include "openvino/op/broadcast.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
@@ -36,23 +38,44 @@
#include "openvino/op/shape_of.hpp"
#include "openvino/op/slice.hpp"
#include "openvino/op/squeeze.hpp"
+#include "openvino/op/tensor_iterator.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
+#include "pass/prune_orphaned_parameters.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf {
namespace {
using namespace ov::op;
using Value = ov::Output<ov::Node>;
-using Models = ProjectorModels;
+
+std::shared_ptr<v0::Constant> ints(const std::vector<int64_t>& values) {
+ return v0::Constant::create(ov::element::i64, {values.size()}, values);
+}
+
+std::shared_ptr<v0::Constant> scalar(int64_t value) {
+ return v0::Constant::create(ov::element::i64, {}, {value});
+}
+
+Value add(const Value& a, const Value& b) {
+ return std::make_shared<v1::Add>(a, b);
+}
+
+Value multiply(const Value& a, const Value& b) {
+ return std::make_shared<v1::Multiply>(a, b);
+}
+
+Value divide(const Value& a, const Value& b) {
+ return std::make_shared<v1::Divide>(a, b);
+}
+
+Value modulo(const Value& a, const Value& b) {
+ return std::make_shared<v1::FloorMod>(a, b);
+}
Value range(const Value& count) {
- auto axis = v0::Constant::create(ov::element::i64, {1}, {0});
- auto start = v0::Constant::create(ov::element::i64, {}, {0});
- auto step = v0::Constant::create(ov::element::i64, {}, {1});
- auto stop = std::make_shared<v0::Squeeze>(count, axis);
- auto indices = std::make_shared<v4::Range>(start, stop, step, ov::element::i64);
- return indices;
+ auto stop = std::make_shared<v0::Squeeze>(count, ints({0}));
+ return std::make_shared<v4::Range>(scalar(0), stop, scalar(1), ov::element::i64);
}
std::shared_ptr<v0::Parameter> parameter(const std::shared_ptr<ov::Model>& model, const std::string& name) {
@@ -62,27 +85,41 @@ std::shared_ptr<v0::Parameter> parameter(const std::shared_ptr<ov::Model>& model
}
Value flat_index(const Value& value) {
- auto index_shape = v0::Constant::create(ov::element::i64, {4}, {1, 1, 1, -1});
- return std::make_shared<v1::Reshape>(value, index_shape, false);
+ return std::make_shared<v1::Reshape>(value, ints({1, 1, 1, -1}), false);
+}
+
+Value additive_mask(const Value& visible) {
+ auto unmasked = v0::Constant::create(ov::element::f32, {}, {0.f});
+ auto masked = v0::Constant::create(ov::element::f32, {}, {-std::numeric_limits<float>::infinity()});
+ return std::make_shared<v1::Select>(visible, unmasked, masked);
}
void require_square_fits(int64_t value, int64_t factor, const char* key) {
- OPENVINO_ASSERT(value <= std::numeric_limits<int64_t>::max() / factor / value,
+ OPENVINO_ASSERT(value > 0 && value <= std::numeric_limits<int64_t>::max() / factor / value,
"[GGUF] out-of-range mmproj metadata ",
key);
}
void replace_input(const std::shared_ptr<ov::Model>& model, const std::string& name, Value value) {
auto source = parameter(model, name);
- if (value.get_element_type() != source->get_element_type()) {
- auto converted = std::make_shared<v0::Convert>(value, source->get_element_type());
- value = converted;
- }
+ if (value.get_element_type() != source->get_element_type())
+ value = std::make_shared<v0::Convert>(value, source->get_element_type());
source->output(0).replace(value);
value.get_tensor().set_names({});
model->remove_parameter(source);
}
+// Replaces "<prefix>0".."<prefix>3" with the four interleaved quarters of `source`.
+void replace_strided_inputs(const std::shared_ptr<ov::Model>& model,
+ const Value& source,
+ const Value& count,
+ const std::string& prefix) {
+ for (int64_t i = 0; i < 4; ++i) {
+ auto quarter = std::make_shared<v8::Slice>(source, ints({i}), count, ints({4}), ints({0}));
+ replace_input(model, prefix + std::to_string(i), flat_index(quarter));
+ }
+}
+
void add_inputs(const std::shared_ptr<ov::Model>& model,
const std::vector<std::pair<std::string, std::shared_ptr<v0::Parameter>>>& inputs) {
for (const auto& [name, input] : inputs) {
@@ -95,7 +132,7 @@ void add_inputs(const std::shared_ptr<ov::Model>& model,
// The translator names a GGUF tensor "<tensor>_<tensor>".
Value weight(const std::shared_ptr<ov::Model>& model, const std::string& tensor) {
const auto name = tensor + "_" + tensor;
- for (const auto& node : model->get_ordered_ops()) {
+ for (const auto& node : model->get_ops()) {
if (node->get_friendly_name() == name)
return node->output(0);
}
@@ -108,34 +145,31 @@ Value require_weight(const std::shared_ptr<ov::Model>& model, const std::string&
return value;
}
+Value image_shape(const Value& rows, const Value& cols, int64_t patch) {
+ auto patch_size = scalar(patch);
+ return std::make_shared<v0::Concat>(
+ ov::OutputVector{ints({1, 3}), multiply(rows, patch_size), multiply(cols, patch_size)},
+ 0);
+}
+
Value image_from_patches(const Value& patches,
const Value& rows,
const Value& cols,
int64_t patch,
bool channels_last) {
- auto p = v0::Constant::create(ov::element::i64, {1}, {patch});
- auto c = v0::Constant::create(ov::element::i64, {1}, {3});
+ auto p = ints({patch});
+ auto c = ints({3});
auto grid = channels_last ? ov::OutputVector{rows, cols, p, p, c} : ov::OutputVector{rows, cols, c, p, p};
auto grid_shape = std::make_shared<v0::Concat>(grid, 0);
auto patch_grid = std::make_shared<v1::Reshape>(patches, grid_shape, false);
- auto order =
- v0::Constant::create(ov::element::i64,
- {5},
- channels_last ? std::vector<int64_t>{4, 0, 2, 1, 3} : std::vector<int64_t>{2, 0, 3, 1, 4});
+ auto order = channels_last ? ints({4, 0, 2, 1, 3}) : ints({2, 0, 3, 1, 4});
auto image_grid = std::make_shared<v1::Transpose>(patch_grid, order);
- auto batch_channels = v0::Constant::create(ov::element::i64, {2}, {1, 3});
- auto patch_size = v0::Constant::create(ov::element::i64, {}, {patch});
- auto height = std::make_shared<v1::Multiply>(rows, patch_size);
- auto width = std::make_shared<v1::Multiply>(cols, patch_size);
- auto image_shape = std::make_shared<v0::Concat>(ov::OutputVector{batch_channels, height, width}, 0);
- auto image = std::make_shared<v1::Reshape>(image_grid, image_shape, false);
- return image;
+ return std::make_shared<v1::Reshape>(image_grid, image_shape(rows, cols, patch), false);
}
void squeeze_output(const std::shared_ptr<ov::Model>& model) {
auto result = model->get_results().front();
- auto axis = v0::Constant::create(ov::element::i64, {1}, {0});
- auto features = std::make_shared<v0::Squeeze>(result->input_value(0), axis);
+ auto features = std::make_shared<v0::Squeeze>(result->input_value(0), ints({0}));
features->output(0).get_tensor().set_names({"last_hidden_state"});
result->input(0).replace_source_output(features);
}
@@ -145,29 +179,24 @@ void padded_patch_layout(const std::shared_ptr<ov::Model>& model, int64_t patch)
require_square_fits(patch, 3, "vision.patch_size");
auto pixels = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, -1, 3 * patch * patch});
auto positions = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{1, -1, 2});
- auto zero_axis = v0::Constant::create(ov::element::i64, {1}, {0});
- auto one_step = v0::Constant::create(ov::element::i64, {1}, {1});
- auto zero = v0::Constant::create(ov::element::i64, {}, {0});
- auto one = v0::Constant::create(ov::element::i64, {}, {1});
+ auto zero_axis = ints({0});
+ auto zero = scalar(0);
+ auto one = scalar(1);
auto flat = std::make_shared<v0::Squeeze>(positions, zero_axis);
auto x = std::make_shared<v8::Gather>(flat, zero, one);
auto y = std::make_shared<v8::Gather>(flat, one, one);
auto nonnegative = std::make_shared<v1::GreaterEqual>(x, zero);
auto valid_rows = std::make_shared<v0::Convert>(nonnegative, ov::element::i64);
auto count = std::make_shared<v1::ReduceSum>(valid_rows, zero_axis, true);
- auto maximum_x = std::make_shared<v1::ReduceMax>(x, zero_axis, true);
- auto cols = std::make_shared<v1::Add>(maximum_x, one);
- auto rows = std::make_shared<v1::Divide>(count, cols);
+ auto cols = add(std::make_shared<v1::ReduceMax>(x, zero_axis, true), one);
+ auto rows = divide(count, cols);
+ auto leading = [&](const Value& value) -> Value {
+ return std::make_shared<v8::Slice>(value, zero_axis, count, ints({1}), zero_axis);
+ };
auto flat_pixels = std::make_shared<v0::Squeeze>(pixels, zero_axis);
- auto valid_pixels = std::make_shared<v8::Slice>(flat_pixels, zero_axis, count, one_step, zero_axis);
- auto valid_x = std::make_shared<v8::Slice>(x, zero_axis, count, one_step, zero_axis);
- auto valid_y = std::make_shared<v8::Slice>(y, zero_axis, count, one_step, zero_axis);
- auto image = image_from_patches(valid_pixels, rows, cols, patch, true);
- auto position_x = flat_index(valid_x);
- auto position_y = flat_index(valid_y);
- replace_input(model, "pixel_values", image);
- replace_input(model, "position_x", position_x);
- replace_input(model, "position_y", position_y);
+ replace_input(model, "pixel_values", image_from_patches(leading(flat_pixels), rows, cols, patch, true));
+ replace_input(model, "position_x", flat_index(leading(x)));
+ replace_input(model, "position_y", flat_index(leading(y)));
add_inputs(model, {{"pixel_values", pixels}, {"image_position_ids", positions}});
}
@@ -177,97 +206,50 @@ void windowed_patch_layout(const std::shared_ptr<ov::Model>& model, int64_t patc
require_square_fits(merge, 1, "vision.merge");
auto pixels = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 3 * patch * patch});
auto grid = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{1, 3});
- auto zero_axis = v0::Constant::create(ov::element::i64, {1}, {0});
- auto row_index = v0::Constant::create(ov::element::i64, {1}, {1});
- auto col_index = v0::Constant::create(ov::element::i64, {1}, {2});
- auto zero = v0::Constant::create(ov::element::i64, {}, {0});
- auto one = v0::Constant::create(ov::element::i64, {}, {1});
- auto thw = std::make_shared<v0::Squeeze>(grid, zero_axis);
- auto rows = std::make_shared<v8::Gather>(thw, row_index, zero);
- auto cols = std::make_shared<v8::Gather>(thw, col_index, zero);
- auto image = image_from_patches(pixels, rows, cols, patch, false);
- replace_input(model, "pixel_values", image);
+ auto thw = std::make_shared<v0::Squeeze>(grid, ints({0}));
+ auto rows = gather_dims(thw, {1});
+ auto cols = gather_dims(thw, {2});
+ replace_input(model, "pixel_values", image_from_patches(pixels, rows, cols, patch, false));
// Slots outside the image repeat the window's first patch and are masked out as keys.
const int64_t slots = window * window;
- auto window_size = v0::Constant::create(ov::element::i64, {}, {window});
- auto window_padding = v0::Constant::create(ov::element::i64, {}, {window - 1});
- auto window_slots = v0::Constant::create(ov::element::i64, {}, {slots});
- auto padded_cols = std::make_shared<v1::Add>(cols, window_padding);
- auto window_cols = std::make_shared<v1::Divide>(padded_cols, window_size);
- auto padded_rows = std::make_shared<v1::Add>(rows, window_padding);
- auto window_rows = std::make_shared<v1::Divide>(padded_rows, window_size);
- auto window_count = std::make_shared<v1::Multiply>(window_rows, window_cols);
- auto slot_count = std::make_shared<v1::Multiply>(window_count, window_slots);
- auto slot = range(slot_count);
- auto index_in_window = std::make_shared<v1::FloorMod>(slot, window_slots);
- auto window_index = std::make_shared<v1::Divide>(slot, window_slots);
- auto window_row = std::make_shared<v1::Divide>(window_index, window_cols);
- auto window_col = std::make_shared<v1::FloorMod>(window_index, window_cols);
- auto top = std::make_shared<v1::Multiply>(window_row, window_size);
- auto left = std::make_shared<v1::Multiply>(window_col, window_size);
- auto row_in_window = std::make_shared<v1::Divide>(index_in_window, window_size);
- auto col_in_window = std::make_shared<v1::FloorMod>(index_in_window, window_size);
- auto y = std::make_shared<v1::Add>(top, row_in_window);
- auto x = std::make_shared<v1::Add>(left, col_in_window);
- auto inside_rows = std::make_shared<v1::Less>(y, rows);
- auto inside_cols = std::make_shared<v1::Less>(x, cols);
- auto inside = std::make_shared<v1::LogicalAnd>(inside_rows, inside_cols);
- auto row_offset = std::make_shared<v1::Multiply>(y, cols);
- auto patch_index = std::make_shared<v1::Add>(row_offset, x);
- auto top_offset = std::make_shared<v1::Multiply>(top, cols);
- auto first_patch = std::make_shared<v1::Add>(top_offset, left);
- auto index = std::make_shared<v1::Select>(inside, patch_index, first_patch);
- auto patch_indices = flat_index(index);
- auto patch_x = std::make_shared<v1::FloorMod>(index, cols);
- auto patch_y = std::make_shared<v1::Divide>(index, cols);
- auto offset_x = std::make_shared<v1::Add>(patch_x, one);
- auto offset_y = std::make_shared<v1::Add>(patch_y, one);
- auto position_x = flat_index(offset_x);
- auto position_y = flat_index(offset_y);
- replace_input(model, "patch_indices", patch_indices);
- replace_input(model, "position_x", position_x);
- replace_input(model, "position_y", position_y);
- auto unmasked = v0::Constant::create(ov::element::f32, {}, {0.f});
- auto masked = v0::Constant::create(ov::element::f32, {}, {-std::numeric_limits<float>::infinity()});
- auto key_mask = std::make_shared<v1::Select>(inside, unmasked, masked);
- auto mask_shape = v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{-1, 1, 1, slots});
- auto window_mask = std::make_shared<v1::Reshape>(key_mask, mask_shape, false);
+ auto window_size = scalar(window);
+ auto window_padding = scalar(window - 1);
+ auto window_slots = scalar(slots);
+ auto window_cols = divide(add(cols, window_padding), window_size);
+ auto window_rows = divide(add(rows, window_padding), window_size);
+ auto slot = range(multiply(multiply(window_rows, window_cols), window_slots));
+ auto index_in_window = modulo(slot, window_slots);
+ auto window_index = divide(slot, window_slots);
+ auto top = multiply(divide(window_index, window_cols), window_size);
+ auto left = multiply(modulo(window_index, window_cols), window_size);
+ auto y = add(top, divide(index_in_window, window_size));
+ auto x = add(left, modulo(index_in_window, window_size));
+ auto inside =
+ std::make_shared<v1::LogicalAnd>(std::make_shared<v1::Less>(y, rows), std::make_shared<v1::Less>(x, cols));
+ auto index = std::make_shared<v1::Select>(inside, add(multiply(y, cols), x), add(multiply(top, cols), left));
+ auto one = scalar(1);
+ replace_input(model, "patch_indices", flat_index(index));
+ replace_input(model, "position_x", flat_index(add(modulo(index, cols), one)));
+ replace_input(model, "position_y", flat_index(add(divide(index, cols), one)));
+ auto window_mask = std::make_shared<v1::Reshape>(additive_mask(inside), ints({-1, 1, 1, slots}), false);
replace_input(model, "window_mask", window_mask);
- auto patch_count = std::make_shared<v1::Multiply>(rows, cols);
- auto raster = range(patch_count);
- auto r = std::make_shared<v1::Divide>(raster, cols);
- auto c = std::make_shared<v1::FloorMod>(raster, cols);
- auto raster_window_row = std::make_shared<v1::Divide>(r, window_size);
- auto raster_window_col = std::make_shared<v1::Divide>(c, window_size);
- auto raster_window_offset = std::make_shared<v1::Multiply>(raster_window_row, window_cols);
- auto raster_window_index = std::make_shared<v1::Add>(raster_window_offset, raster_window_col);
- auto raster_slot_offset = std::make_shared<v1::Multiply>(raster_window_index, window_slots);
- auto raster_row_in_window = std::make_shared<v1::FloorMod>(r, window_size);
- auto raster_col_in_window = std::make_shared<v1::FloorMod>(c, window_size);
- auto raster_row_offset = std::make_shared<v1::Multiply>(raster_row_in_window, window_size);
- auto raster_index_in_window = std::make_shared<v1::Add>(raster_row_offset, raster_col_in_window);
- auto slot_of = std::make_shared<v1::Add>(raster_slot_offset, raster_index_in_window);
- auto output_indices = flat_index(slot_of);
- replace_input(model, "output_indices", output_indices);
- auto merge_size = v0::Constant::create(ov::element::i64, {}, {merge});
- auto merge_slots = v0::Constant::create(ov::element::i64, {}, {merge * merge});
- auto block = std::make_shared<v1::Divide>(raster, merge_slots);
- auto within = std::make_shared<v1::FloorMod>(raster, merge_slots);
- auto block_cols = std::make_shared<v1::Divide>(cols, merge_size);
- auto block_row = std::make_shared<v1::Divide>(block, block_cols);
- auto block_col = std::make_shared<v1::FloorMod>(block, block_cols);
- auto block_top = std::make_shared<v1::Multiply>(block_row, merge_size);
- auto block_left = std::make_shared<v1::Multiply>(block_col, merge_size);
- auto row_in_block = std::make_shared<v1::Divide>(within, merge_size);
- auto col_in_block = std::make_shared<v1::FloorMod>(within, merge_size);
- auto merged_row = std::make_shared<v1::Add>(block_top, row_in_block);
- auto merged_col = std::make_shared<v1::Add>(block_left, col_in_block);
- auto merged_row_offset = std::make_shared<v1::Multiply>(merged_row, cols);
- auto merged = std::make_shared<v1::Add>(merged_row_offset, merged_col);
- auto merge_indices = flat_index(merged);
- replace_input(model, "merge_indices", merge_indices);
+ auto raster = range(multiply(rows, cols));
+ auto r = divide(raster, cols);
+ auto c = modulo(raster, cols);
+ auto raster_window = add(multiply(divide(r, window_size), window_cols), divide(c, window_size));
+ auto raster_in_window = add(multiply(modulo(r, window_size), window_size), modulo(c, window_size));
+ replace_input(model, "output_indices", flat_index(add(multiply(raster_window, window_slots), raster_in_window)));
+
+ auto merge_size = scalar(merge);
+ auto merge_slots = scalar(merge * merge);
+ auto block = divide(raster, merge_slots);
+ auto within = modulo(raster, merge_slots);
+ auto block_cols = divide(cols, merge_size);
+ auto merged_row = add(multiply(divide(block, block_cols), merge_size), divide(within, merge_size));
+ auto merged_col = add(multiply(modulo(block, block_cols), merge_size), modulo(within, merge_size));
+ replace_input(model, "merge_indices", flat_index(add(multiply(merged_row, cols), merged_col)));
add_inputs(model, {{"pixel_values", pixels}, {"image_grid_thw", grid}});
squeeze_output(model);
}
@@ -281,34 +263,32 @@ std::shared_ptr<ov::Model> single_output_model(const Value& output,
return model->clone();
}
-Models split_merger_layout(const std::shared_ptr<ov::Model>& model) {
- Models models;
+ProjectorModels split_merger_layout(const std::shared_ptr<ov::Model>& model) {
+ ProjectorModels models;
+ auto live_before = std::make_shared<std::unordered_set<const ov::Node*>>();
+ pass::SnapshotLiveParameters(live_before).run_on_model(model);
// HF flattens patches as (channel, frame, y, x).
- auto first_weight = require_weight(model, "v.patch_embd.weight");
- auto second_weight = require_weight(model, "v.patch_embd.weight.1");
- auto frame_axis = v0::Constant::create(ov::element::i64, {1}, {2});
- auto first_frame = std::make_shared<v0::Unsqueeze>(first_weight, frame_axis);
- auto second_frame = std::make_shared<v0::Unsqueeze>(second_weight, frame_axis);
+ auto frame = [](const Value& kernel) {
+ return std::make_shared<v0::Unsqueeze>(kernel, ints({2}));
+ };
+ auto first_frame = frame(require_weight(model, "v.patch_embd.weight"));
+ auto second_frame = frame(require_weight(model, "v.patch_embd.weight.1"));
auto kernel = std::make_shared<v0::Concat>(ov::OutputVector{first_frame, second_frame}, 2);
const auto& kernel_shape = kernel->get_output_partial_shape(0);
const auto width = kernel_shape[0].get_length();
- const auto patch_dim = ov::shape_size(kernel_shape.get_shape()) / width;
- auto patches = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, int64_t(patch_dim)});
+ const auto patch_dim = static_cast<int64_t>(ov::shape_size(kernel_shape.get_shape()) / width);
+ auto patches = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, patch_dim});
name_output(patches, "hidden_states");
- auto kernel_shape_2d = v0::Constant::create(ov::element::i64, {2}, {width, int64_t(patch_dim)});
- auto kernel_2d = std::make_shared<v1::Reshape>(kernel, kernel_shape_2d, false);
- auto projection = std::make_shared<v0::MatMul>(patches, kernel_2d, false, true);
- Value embeddings = projection;
- if (auto bias = weight(model, "v.patch_embd.bias"); bias.get_node()) {
- auto biased = std::make_shared<v1::Add>(embeddings, bias);
- embeddings = biased;
- }
+ auto kernel_2d = std::make_shared<v1::Reshape>(kernel, ints({width, patch_dim}), false);
+ Value embeddings = std::make_shared<v0::MatMul>(patches, kernel_2d, false, true);
+ if (auto bias = weight(model, "v.patch_embd.bias"); bias.get_node())
+ embeddings = add(embeddings, bias);
models["vision_embeddings"] = single_output_model(embeddings, "last_hidden_state", {patches});
auto table_indices = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{4, -1});
name_output(table_indices, "input");
auto position_weight = require_weight(model, "v.position_embd.weight");
- auto zero = v0::Constant::create(ov::element::i64, {}, {0});
+ auto zero = scalar(0);
auto table = std::make_shared<v8::Gather>(position_weight, table_indices, zero);
models["vision_embeddings_pos"] = single_output_model(table, "last_hidden_state", {table_indices});
@@ -321,12 +301,10 @@ Models split_merger_layout(const std::shared_ptr<ov::Model>& model) {
(scale->input_value(0) == norm_weight ? scale->input_value(1) : scale->input_value(0)).get_node_shared_ptr());
OPENVINO_ASSERT(normalized, "[GGUF] expected LayerNorm before v.blk.0.ln1.weight");
auto hidden_states = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, width});
- auto batch_axes = v0::Constant::create(ov::element::i64, {2}, {0, 1});
- auto hidden_states_4d = std::make_shared<v0::Unsqueeze>(hidden_states, batch_axes);
+ auto hidden_states_4d = std::make_shared<v0::Unsqueeze>(hidden_states, ints({0, 1}));
// Replace the activation shared by LayerNorm and its residual path.
normalized->input_value(0).replace(hidden_states_4d);
- model->remove_parameter(parameter(model, "pixel_values"));
- model->remove_parameter(parameter(model, "patch_indices"));
+ pass::PruneParametersOrphanedSince(live_before).run_on_model(model);
// The first column of each rotary half has frequency 1, so it holds the row or column.
const auto width_metadata = mmproj_int_metadata(model, "clip.vision.embedding_length");
@@ -336,18 +314,15 @@ Models split_merger_layout(const std::shared_ptr<ov::Model>& model) {
"clip.vision.attention.head_count");
const auto head = width_metadata / heads;
auto rotary = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, head / 2});
- auto col_index = v0::Constant::create(ov::element::i64, {}, {head / 4});
- auto one = v0::Constant::create(ov::element::i64, {}, {1});
+ auto one = scalar(1);
auto row = std::make_shared<v8::Gather>(rotary, zero, one);
- auto col = std::make_shared<v8::Gather>(rotary, col_index, one);
+ auto col = std::make_shared<v8::Gather>(rotary, scalar(head / 4), one);
auto coordinates = std::make_shared<v0::Concat>(ov::OutputVector{row, col, row, col}, 0);
auto positions = std::make_shared<v5::Round>(coordinates, v5::Round::RoundMode::HALF_TO_EVEN);
- auto position_ids = flat_index(positions);
- replace_input(model, "position_ids", position_ids);
+ replace_input(model, "position_ids", flat_index(positions));
auto mask = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, -1, -1});
- auto zero_axis = v0::Constant::create(ov::element::i64, {1}, {0});
- auto mask4 = std::make_shared<v0::Unsqueeze>(mask, zero_axis);
+ auto mask4 = std::make_shared<v0::Unsqueeze>(mask, ints({0}));
for (const auto& node : model->get_ordered_ops()) {
if (auto sdpa = ov::as_type_ptr<v13::ScaledDotProductAttention>(node)) {
OPENVINO_ASSERT(sdpa->get_input_size() == 3, "[GGUF] split-merger vision attention already has a mask");
@@ -376,13 +351,13 @@ Models split_merger_layout(const std::shared_ptr<ov::Model>& model) {
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);
- model->add_results({deepstack_result});
+ model->add_results({std::make_shared<v0::Result>(deepstack)});
}
add_inputs(model, {{"hidden_states", hidden_states}, {"attention_mask", mask}, {"rotary_pos_emb", rotary}});
models["vision_embeddings_merger"] = model;
return models;
}
+
void packed_patch_layout(const std::shared_ptr<ov::Model>& model, int64_t patch, int64_t merge) {
require_square_fits(patch, 3, "vision.patch_size");
OPENVINO_ASSERT(merge == 2 || merge == 4, "[GGUF] invalid packed-patch merge size");
@@ -391,55 +366,28 @@ void packed_patch_layout(const std::shared_ptr<ov::Model>& model, int64_t patch,
auto window_index = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1});
auto merge_index = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1});
auto grid = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{2});
- auto zero = v0::Constant::create(ov::element::i64, {}, {0});
- auto row_index = v0::Constant::create(ov::element::i64, {1}, {0});
- auto col_index = v0::Constant::create(ov::element::i64, {1}, {1});
- auto rows = std::make_shared<v8::Gather>(grid, row_index, zero);
- auto cols = std::make_shared<v8::Gather>(grid, col_index, zero);
- auto strip_shape = v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{1, 3, patch, -1, patch});
- auto strip = std::make_shared<v1::Reshape>(pixels, strip_shape, false);
- auto strip_order = v0::Constant::create(ov::element::i64, {5}, {0, 3, 1, 2, 4});
- auto reordered = std::make_shared<v1::Transpose>(strip, strip_order);
- auto packed_shape = v0::Constant::create(ov::element::i64, {2}, std::vector<int64_t>{-1, 3 * patch * patch});
- auto packed = std::make_shared<v1::Reshape>(reordered, packed_shape, false);
- auto image = image_from_patches(packed, rows, cols, patch, false);
- replace_input(model, "pixel_values", image);
- auto flat_positions = flat_index(positions);
- replace_input(model, "position_ids", flat_positions);
- auto merge_count = std::make_shared<v3::ShapeOf>(merge_index);
- auto four_steps = v0::Constant::create(ov::element::i64, {1}, {4});
- for (int64_t i = 0; i < 4; ++i) {
- auto start = v0::Constant::create(ov::element::i64, {1}, {i});
- auto index = std::make_shared<v8::Slice>(merge_index, start, merge_count, four_steps, row_index);
- auto flat = flat_index(index);
- replace_input(model, "merger.indices." + std::to_string(i), flat);
- }
+ auto rows = gather_dims(grid, {0});
+ auto cols = gather_dims(grid, {1});
+ auto strip = std::make_shared<v1::Reshape>(pixels, ints({1, 3, patch, -1, patch}), false);
+ auto reordered = std::make_shared<v1::Transpose>(strip, ints({0, 3, 1, 2, 4}));
+ auto packed = std::make_shared<v1::Reshape>(reordered, ints({-1, 3 * patch * patch}), false);
+ replace_input(model, "pixel_values", image_from_patches(packed, rows, cols, patch, false));
+ replace_input(model, "position_ids", flat_index(positions));
+ replace_strided_inputs(model, merge_index, std::make_shared<v3::ShapeOf>(merge_index), "merger.indices.");
if (merge == 4) {
- auto flat_window = flat_index(window_index);
- replace_input(model, "window_indices", flat_window);
+ replace_input(model, "window_indices", flat_index(window_index));
auto count = std::make_shared<v3::ShapeOf>(window_index);
auto ordered = range(count);
- auto inverse = std::make_shared<v3::ScatterUpdate>(ordered, window_index, ordered, zero);
- auto flat_inverse = flat_index(inverse);
- replace_input(model, "inverse_window_indices", flat_inverse);
- auto four = v0::Constant::create(ov::element::i64, {}, {4});
- auto group = std::make_shared<v1::Divide>(ordered, four);
- auto query_group = std::make_shared<v0::Unsqueeze>(group, col_index);
- auto key_group = std::make_shared<v0::Unsqueeze>(group, row_index);
+ auto inverse = std::make_shared<v3::ScatterUpdate>(ordered, window_index, ordered, scalar(0));
+ replace_input(model, "inverse_window_indices", flat_index(inverse));
+ auto group = divide(ordered, scalar(4));
+ auto query_group = std::make_shared<v0::Unsqueeze>(group, ints({1}));
+ auto key_group = std::make_shared<v0::Unsqueeze>(group, ints({0}));
auto same_group = std::make_shared<v1::Equal>(query_group, key_group);
- auto visible = v0::Constant::create(ov::element::f32, {}, {0.0f});
- auto hidden = v0::Constant::create(ov::element::f32, {}, {-std::numeric_limits<float>::infinity()});
- auto mask = std::make_shared<v1::Select>(same_group, visible, hidden);
- auto batch_heads = v0::Constant::create(ov::element::i64, {2}, {1, 1});
- auto mask_shape = std::make_shared<v0::Concat>(ov::OutputVector{batch_heads, count, count}, 0);
- auto attention_mask = std::make_shared<v1::Reshape>(mask, mask_shape, false);
+ auto mask_shape = std::make_shared<v0::Concat>(ov::OutputVector{ints({1, 1}), count, count}, 0);
+ auto attention_mask = std::make_shared<v1::Reshape>(additive_mask(same_group), mask_shape, false);
replace_input(model, "attention_mask", attention_mask);
- for (int64_t i = 0; i < 4; ++i) {
- auto start = v0::Constant::create(ov::element::i64, {1}, {i});
- auto index = std::make_shared<v8::Slice>(window_index, start, count, four_steps, row_index);
- auto flat = flat_index(index);
- replace_input(model, "vit_merger.indices." + std::to_string(i), flat);
- }
+ replace_strided_inputs(model, window_index, count, "vit_merger.indices.");
}
add_inputs(model,
{{"pixel_values", pixels},
@@ -450,6 +398,74 @@ void packed_patch_layout(const std::shared_ptr<ov::Model>& model, int64_t patch,
squeeze_output(model);
}
+void temporal_packed_patch_layout(const std::shared_ptr<ov::Model>& model, int64_t patch, int64_t temporal) {
+ OPENVINO_ASSERT(temporal == 1 || temporal == 2,
+ "[GGUF] temporal packed vision requires one or two temporal patches");
+ require_square_fits(patch, 3 * temporal, "vision.patch_size");
+ // The body is a clone so the supplied model stays untouched until the iterator is complete.
+ auto body = model->clone();
+ auto first_pixels = find_parameter(body, "pixel_values");
+ auto second_pixels = find_parameter(body, "pixel_values_1");
+ auto spatial_positions = find_parameter(body, "positions");
+ OPENVINO_ASSERT(bool(second_pixels) == (temporal == 2),
+ "[GGUF] temporal packed vision input count must match vision.temporal_patch_size");
+ OPENVINO_ASSERT(first_pixels && spatial_positions && body->get_parameters().size() == (second_pixels ? 3u : 2u) &&
+ body->get_results().size() == 1 && body->get_sinks().empty() && body->get_variables().empty(),
+ "[GGUF] temporal packed vision requires pixel inputs, positions and one embedding output");
+ OPENVINO_ASSERT(spatial_positions->get_element_type() == ov::element::i32,
+ "[GGUF] temporal packed vision requires i32 spatial positions");
+
+ const auto pixel_dim = 3 * temporal * patch * patch;
+ auto pixels = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, -1, -1, pixel_dim});
+ auto shape = std::make_shared<v3::ShapeOf>(pixels);
+ auto rows = gather_dims(shape, {1});
+ auto cols = gather_dims(shape, {2});
+ auto packed_shape =
+ std::make_shared<v0::Concat>(ov::OutputVector{ints({1}), rows, cols, ints({3, temporal, patch, patch})}, 0);
+ auto packed = std::make_shared<v1::Reshape>(pixels, packed_shape, false);
+ auto frame_shape = image_shape(rows, cols, patch);
+ auto replace_frame = [&](const std::shared_ptr<v0::Parameter>& input, int64_t index) {
+ const auto& input_shape = input->get_partial_shape();
+ OPENVINO_ASSERT(input->get_element_type() == ov::element::f32 && input_shape.rank() == 4 &&
+ input_shape[0] == 1 && input_shape[1] == 3,
+ "[GGUF] temporal packed vision requires singleton RGB NCHW pixel inputs");
+ auto frame = std::make_shared<v8::Gather>(packed, scalar(index), scalar(4));
+ auto image = std::make_shared<v1::Transpose>(frame, ints({0, 3, 1, 4, 2, 5}));
+ replace_input(body, input->get_friendly_name(), std::make_shared<v1::Reshape>(image, frame_shape, false));
+ };
+ replace_frame(first_pixels, 0);
+ if (second_pixels)
+ replace_frame(second_pixels, 1);
+
+ auto count = multiply(rows, cols);
+ auto indices = range(count);
+ auto zeros = std::make_shared<v3::Broadcast>(ints({0}), count);
+ auto raster =
+ std::make_shared<v0::Concat>(ov::OutputVector{divide(indices, cols), modulo(indices, cols), zeros, zeros}, 0);
+ replace_input(body, "positions", flat_index(std::make_shared<v0::Convert>(raster, ov::element::i32)));
+ add_inputs(body, {{"pixel_values", pixels}});
+ const auto features = body->get_results().front()->input_value(0);
+ const auto output_shape = features.get_partial_shape();
+ OPENVINO_ASSERT(features.get_element_type() == ov::element::f32 && output_shape.rank() == 3 && output_shape[0] == 1,
+ "[GGUF] temporal packed vision requires f32 [1, tokens, width] embeddings");
+
+ auto input = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, -1, -1, pixel_dim});
+ name_output(input, "pixel_values");
+ auto iterator = std::make_shared<v0::TensorIterator>();
+ iterator->set_body(body);
+ iterator->set_sliced_input(pixels, input, 0, 1, 1, -1, 0);
+ auto output = iterator->get_concatenated_slices(features, 0, 1, 1, -1, 0);
+ output.set_names({"last_hidden_state"});
+ iterator->validate_and_infer_types();
+ for (const auto& result : ov::ResultVector(model->get_results()))
+ model->remove_result(result);
+ for (const auto& parameter : ov::ParameterVector(model->get_parameters()))
+ model->remove_parameter(parameter);
+ model->add_parameters({input});
+ model->add_results({std::make_shared<v0::Result>(output)});
+ model->validate_nodes_and_infer_types();
+}
+
constexpr std::pair<ProjectorLayout, const char*> layout_names[] = {
{ProjectorLayout::Unsupported, "unsupported"},
{ProjectorLayout::Image, "image"},
@@ -457,7 +473,9 @@ constexpr std::pair<ProjectorLayout, const char*> layout_names[] = {
{ProjectorLayout::WindowedPatches, "windowed_patches"},
{ProjectorLayout::SplitMerger, "split_merger"},
{ProjectorLayout::PackedPatches, "packed_patches"},
+ {ProjectorLayout::TemporalPackedPatches, "temporal_packed_patches"},
};
+} // namespace
ProjectorLayout read_projector_layout(const std::shared_ptr<ov::Model>& model) {
if (!model->has_rt_info({"gguf_mmproj", "vision.genai_layout"})) {
@@ -478,7 +496,6 @@ ProjectorLayout read_projector_layout(const std::shared_ptr<ov::Model>& model) {
}
OPENVINO_THROW("[GGUF] no GenAI vision layout for mmproj contract '", name, "'");
}
-} // namespace
std::string projector_layout_name(ProjectorLayout layout) {
for (const auto& [candidate, name] : layout_names) {
@@ -488,24 +505,6 @@ std::string projector_layout_name(ProjectorLayout layout) {
OPENVINO_THROW("[GGUF] invalid GenAI projector layout contract");
}
-ProjectorLayout builtin_projector_layout(const std::string& projector_type) {
- if (projector_type == "gemma3" || projector_type == "lfm2")
- return ProjectorLayout::Image;
- if (projector_type == "gemma4v" || projector_type == "gemma4uv")
- return ProjectorLayout::PaddedPatches;
- if (projector_type == "muse-glimmer")
- return ProjectorLayout::WindowedPatches;
- if (projector_type == "qwen3vl_merger")
- return ProjectorLayout::SplitMerger;
- if (projector_type == "minicpmv4_7")
- return ProjectorLayout::PackedPatches;
- return ProjectorLayout::Unsupported;
-}
-
-void require_projector_layout(const std::shared_ptr<ov::Model>& model) {
- read_projector_layout(model);
-}
-
ProjectorModels adapt_projector_layout(const std::shared_ptr<ov::Model>& model) {
switch (read_projector_layout(model)) {
case ProjectorLayout::Image:
@@ -526,6 +525,11 @@ ProjectorModels adapt_projector_layout(const std::shared_ptr<ov::Model>& model)
mmproj_int_metadata(model, "vision.patch_size"),
mmproj_int_metadata(model, "vision.merge"));
break;
+ case ProjectorLayout::TemporalPackedPatches:
+ temporal_packed_patch_layout(model,
+ mmproj_int_metadata(model, "vision.patch_size"),
+ mmproj_int_metadata(model, "vision.temporal_patch_size"));
+ break;
case ProjectorLayout::Unsupported:
OPENVINO_THROW("[GGUF] no GenAI vision layout contract");
}
diff --git a/src/frontends/gguf/src/builder/arch/projector_adapter.hpp b/src/frontends/gguf/src/builder/arch/projector_adapter.hpp
index 50e39cb59d9..f3dc7a420ec 100644
--- a/src/frontends/gguf/src/builder/arch/projector_adapter.hpp
+++ b/src/frontends/gguf/src/builder/arch/projector_adapter.hpp
@@ -18,7 +18,8 @@ using ProjectorModels = std::map<std::string, std::shared_ptr<ov::Model>>;
std::string projector_layout_name(ProjectorLayout layout);
// Vision GenAI layout of a built-in projector type; Unsupported for other types.
ProjectorLayout builtin_projector_layout(const std::string& projector_type);
-void require_projector_layout(const std::shared_ptr<ov::Model>& model);
+// Throws when the model declares no adaptable GenAI vision layout.
+ProjectorLayout read_projector_layout(const std::shared_ptr<ov::Model>& model);
ProjectorModels adapt_projector_layout(const std::shared_ptr<ov::Model>& model);
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
index d4d9fe8ae13..eca6e05813e 100644
--- a/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
@@ -155,7 +155,7 @@ ModelAdapterResult adapt_mmproj(const std::shared_ptr<ov::Model>& model,
const auto selected = embedding_result(model, modality);
const auto adapter = get_model_adapter(selected);
if (layout == Layout::VISION_ENCODERS && !adapter)
- require_projector_layout(model);
+ read_projector_layout(model);
auto live_before = std::make_shared<std::unordered_set<const ov::Node*>>();
SnapshotLiveParameters(live_before).run_on_model(model);
ComponentStateSelection states;
diff --git a/src/frontends/gguf/tests/test_lfm3_media.cpp b/src/frontends/gguf/tests/test_lfm3_media.cpp
index 650c5dcb3c5..a5e64e32d80 100644
--- a/src/frontends/gguf/tests/test_lfm3_media.cpp
+++ b/src/frontends/gguf/tests/test_lfm3_media.cpp
@@ -16,6 +16,7 @@
#include "openvino/frontend/gguf/make_stateful.hpp"
#include "openvino/op/add.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/multiply.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/openvino.hpp"
#include "openvino/pass/serialize.hpp"
@@ -38,6 +39,31 @@ ov::Tensor tensor(const cnpy::NpyArray& value, ov::element::Type type = ov::elem
return result;
}
+using Frames = std::pair<ov::Tensor, ov::Tensor>;
+
+ov::Tensor packed_pixels(const std::vector<Frames>& groups, size_t patch = 16, size_t temporal = 2) {
+ OPENVINO_ASSERT(!groups.empty(), "packed_pixels requires at least one group");
+ const auto shape = groups.front().first.get_shape();
+ OPENVINO_ASSERT(shape.size() == 4 && shape[0] == 1 && shape[1] == 3, "packed_pixels requires [1,3,H,W] frames");
+ const auto height = shape[2], width = shape[3];
+ OPENVINO_ASSERT(height % patch == 0 && width % patch == 0, "packed_pixels requires patch-aligned frames");
+ ov::Tensor packed(ov::element::f32, {groups.size(), height / patch, width / patch, 3 * temporal * patch * patch});
+ auto* destination = packed.data<float>();
+ for (const auto& frames : groups) {
+ OPENVINO_ASSERT(frames.first.get_shape() == shape && frames.second.get_shape() == shape);
+ for (size_t row = 0; row < height / patch; ++row)
+ for (size_t col = 0; col < width / patch; ++col)
+ for (size_t channel = 0; channel < 3; ++channel)
+ for (size_t frame_index = 0; frame_index < temporal; ++frame_index)
+ for (size_t y = 0; y < patch; ++y)
+ for (size_t x = 0; x < patch; ++x)
+ *destination++ = (frame_index == 0 ? frames.first : frames.second)
+ .data<const float>()[(channel * height + row * patch + y) * width +
+ col * patch + x];
+ }
+ return packed;
+}
+
class GGUFTestLfm3Media : public ::testing::TestWithParam<std::string> {};
TEST_P(GGUFTestLfm3Media, IndependentCpuEncoderAndStates) {
@@ -128,6 +154,130 @@ INSTANTIATE_TEST_SUITE_P(Components,
return info.param;
});
+TEST(GGUFLfm3MediaAdapter, TemporalPackedLayoutMatchesCpuOracleAcrossGroupsAndIR) {
+ const auto path = std::filesystem::path(ov_gguf_test::test_data_dir()) / "lfm3_media_vision.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));
+ EXPECT_EQ(native->get_rt_info<std::string>({"gguf_mmproj", "vision.genai_layout"}), "temporal_packed_patches");
+ EXPECT_EQ(native->get_rt_info<std::string>({"gguf_mmproj", "vision.patch_size"}), "16");
+ EXPECT_EQ(native->get_rt_info<std::string>({"gguf_mmproj", "vision.temporal_patch_size"}), "2");
+ ov::Core core;
+ const ov::AnyMap properties{{"INFERENCE_PRECISION_HINT", "f32"}, {"DYNAMIC_QUANTIZATION_GROUP_SIZE", 0}};
+ auto native_request = core.compile_model(native, "CPU", properties).create_infer_request();
+ const auto xml = fixture.path + ".xml";
+ ov::serialize(native, xml);
+ enum class Reload { None, Native, Adapted };
+ for (const auto reload : {Reload::None, Reload::Native, Reload::Adapted}) {
+ auto model = reload == Reload::Native ? core.read_model(xml) : native->clone();
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ ASSERT_TRUE(adapter.run_on_model(model));
+ ASSERT_EQ(adapter.get_vision_models().size(), 1);
+ EXPECT_EQ(adapter.get_vision_models().at("vision_embeddings"), model);
+ if (reload == Reload::Adapted) {
+ ov::serialize(model, xml);
+ model = core.read_model(xml);
+ }
+ ASSERT_EQ(model->inputs().size(), 1);
+ EXPECT_EQ(model->input().get_any_name(), "pixel_values");
+ EXPECT_EQ(model->input().get_element_type(), ov::element::f32);
+ EXPECT_EQ(model->input().get_partial_shape(), (ov::PartialShape{-1, -1, -1, 1536}));
+ EXPECT_EQ(model->output().get_any_name(), "last_hidden_state");
+ EXPECT_EQ(model->output().get_element_type(), ov::element::f32);
+ EXPECT_EQ(model->output().get_partial_shape(), (ov::PartialShape{-1, -1, 12}));
+ auto request = core.compile_model(model, "CPU", properties).create_infer_request();
+ for (const size_t step : {0, 1, 0}) {
+ const auto key = std::to_string(step) + ".";
+ const auto first = tensor(data.at(key + "pixel_values"));
+ const auto second = tensor(data.at(key + "pixel_values_1"));
+ for (const size_t group_count : {1, 3, 1}) {
+ std::vector<Frames> groups{{first, second}, {second, first}, {first, first}};
+ groups.resize(group_count);
+ request.set_tensor("pixel_values", packed_pixels(groups));
+ request.infer();
+ const auto actual = request.get_tensor("last_hidden_state");
+ const auto& expected = data.at(key + "embeddings");
+ EXPECT_EQ(actual.get_shape(), (ov::Shape{group_count, expected.shape[1], expected.shape[2]}));
+ ov_gguf_test::expect_nmse_below(
+ ov_gguf_test::nmse(actual.data<const float>(), expected.data<float>(), expected.num_vals),
+ 1e-5);
+ for (size_t group = 1; group < groups.size(); ++group) {
+ native_request.set_tensor("vision.pixel_values", groups[group].first);
+ native_request.set_tensor("vision.pixel_values_1", groups[group].second);
+ native_request.set_tensor("vision.positions", tensor(data.at(key + "positions"), ov::element::i32));
+ native_request.infer();
+ const auto native_features = native_request.get_tensor("vision.embeddings");
+ ov_gguf_test::expect_nmse_below(
+ ov_gguf_test::nmse(actual.data<const float>() + group * expected.num_vals,
+ native_features.data<const float>(),
+ expected.num_vals),
+ 1e-5);
+ }
+ }
+ }
+ }
+ std::filesystem::remove(xml);
+ std::filesystem::remove(fixture.path + ".bin");
+}
+
+TEST(GGUFLfm3MediaAdapter, TemporalPackedLayoutRequiresMatchingFrameCount) {
+ const auto path = std::filesystem::path(ov_gguf_test::test_data_dir()) / "lfm3_media_vision.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));
+ const auto second =
+ ov::as_type_ptr<ov::op::v0::Parameter>(native->input("vision.pixel_values_1").get_node_shared_ptr());
+ auto zero = std::make_shared<ov::op::v1::Multiply>(native->input("vision.pixel_values"),
+ ov::op::v0::Constant::create(ov::element::f32, {}, {0.f}));
+ second->output(0).replace(zero);
+ native->remove_parameter(second);
+ native->validate_nodes_and_infer_types();
+ ov::Core core;
+ const ov::AnyMap properties{{"INFERENCE_PRECISION_HINT", "f32"}, {"DYNAMIC_QUANTIZATION_GROUP_SIZE", 0}};
+ auto native_request = core.compile_model(native, "CPU", properties).create_infer_request();
+ for (const int64_t temporal : {1, 2}) {
+ auto model = native->clone();
+ model->set_rt_info(std::to_string(temporal), {"gguf_mmproj", "vision.temporal_patch_size"});
+ if (temporal == 2) {
+ const auto parameters = model->get_parameters();
+ const auto results = model->get_results();
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ EXPECT_THROW(adapter.run_on_model(model), ov::Exception);
+ EXPECT_TRUE(adapter.get_vision_models().empty());
+ EXPECT_EQ(model->get_parameters(), parameters);
+ EXPECT_EQ(model->get_results(), results);
+ continue;
+ }
+ ASSERT_TRUE(Adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS).run_on_model(model));
+ ASSERT_EQ(model->inputs().size(), 1);
+ EXPECT_EQ(model->input().get_partial_shape(), (ov::PartialShape{-1, -1, -1, 768 * temporal}));
+ auto request = core.compile_model(model, "CPU", properties).create_infer_request();
+ for (const size_t step : {0, 1}) {
+ const auto key = std::to_string(step) + ".";
+ const auto first = tensor(data.at(key + "pixel_values"));
+ native_request.set_tensor("vision.pixel_values", first);
+ native_request.set_tensor("vision.positions", tensor(data.at(key + "positions"), ov::element::i32));
+ native_request.infer();
+ for (const auto& second_frame : {tensor(data.at(key + "pixel_values_1")), first}) {
+ request.set_tensor("pixel_values", packed_pixels({{first, second_frame}}, 16, temporal));
+ request.infer();
+ const auto actual = request.get_tensor("last_hidden_state");
+ const auto expected = native_request.get_tensor("vision.embeddings");
+ ASSERT_EQ(actual.get_size(), expected.get_size());
+ ov_gguf_test::expect_nmse_below(
+ ov_gguf_test::nmse(actual.data<const float>(), expected.data<const float>(), expected.get_size()),
+ 1e-5);
+ }
+ }
+ }
+}
+
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));
@@ -153,7 +303,11 @@ TEST(GGUFLfm3MediaAdapter, CombinedOmniPreservesIndependentComponentsAndStates)
: 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.set_tensor(name,
+ name == "pixel_values" && outputs.count("last_hidden_state")
+ ? packed_pixels({{tensor(data.at("vision.pixel_values")),
+ tensor(data.at("vision.pixel_values_1"))}})
+ : tensor(data.at(source), input.get_element_type()));
}
request.infer();
for (const auto& [output, reference] : outputs) {
@@ -193,7 +347,7 @@ TEST(GGUFLfm3MediaAdapter, CombinedOmniPreservesIndependentComponentsAndStates)
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);
+ compare(vision, {{"last_hidden_state", "vision.embeddings"}}, 0);
auto audio = native->clone();
ASSERT_TRUE(Adapter(Adapter::Modality::AUDIO).run_on_model(audio));
compare(audio, {{"audio_features", "audio.embeddings"}}, 7);
@@ -243,6 +397,70 @@ TEST(GGUFLfm3MediaAdapter, BuiltinProjectorHelperBuildsLfm3Types) {
}
}
+TEST(GGUFLfm3MediaAdapter, ProjectorCanOverrideTemporalPackedLayoutWithRecipeOrCallback) {
+ using namespace ov::frontend::gguf;
+ const auto path = std::filesystem::path(ov_gguf_test::test_data_dir()) / "lfm3_media_vision.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"));
+ for (const bool callback : {false, true}) {
+ auto definition = lfm3_replacement("vision", [callback](GgufGraphContext& graph) {
+ auto result = build_builtin_projector(graph, "vision", "lfm3vl");
+ if (!callback)
+ result.genai_layout = ProjectorLayout::Image;
+ return result;
+ });
+ definition.genai_layout = ProjectorLayout::Image;
+ if (callback) {
+ definition.genai_adapter = [](const std::shared_ptr<ov::Model>& model) {
+ return ModelAdapterResult{model, {{"vision_embeddings", model}}};
+ };
+ }
+ FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ProjectorExtension>(definition, RegistrationMode::Replace));
+ auto model = frontend.convert(frontend.load(fixture.path));
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.genai_layout"}),
+ callback ? "temporal_packed_patches" : "image");
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ ASSERT_TRUE(adapter.run_on_model(model));
+ ASSERT_EQ(model->inputs().size(), 3);
+ EXPECT_EQ(model->input("pixel_values").get_partial_shape(), (ov::PartialShape{1, 3, -1, -1}));
+ EXPECT_NO_THROW(model->input("pixel_values_1"));
+ EXPECT_NO_THROW(model->input("positions"));
+ EXPECT_EQ(model->output().get_any_name(), "image_features");
+ EXPECT_EQ(adapter.get_vision_models().at("vision_embeddings"), model);
+ }
+}
+
+TEST(GGUFLfm3MediaAdapter, TemporalPackedLayoutRejectsInvalidMetadataWithoutChangingModel) {
+ const auto path = std::filesystem::path(ov_gguf_test::test_data_dir()) / "lfm3_media_vision.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));
+ for (const auto& [key, value] :
+ std::vector<std::pair<std::string, std::string>>{{"vision.temporal_patch_size", "0"},
+ {"vision.temporal_patch_size", "1"},
+ {"vision.temporal_patch_size", "3"},
+ {"vision.patch_size", "0"},
+ {"vision.patch_size", "9223372036854775807"}}) {
+ auto model = native->clone();
+ model->set_rt_info(value, {"gguf_mmproj", key});
+ const auto inputs = model->get_parameters();
+ const auto outputs = model->get_results();
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ EXPECT_THROW(adapter.run_on_model(model), ov::Exception);
+ EXPECT_TRUE(adapter.get_vision_models().empty());
+ EXPECT_EQ(model->get_parameters(), inputs);
+ EXPECT_EQ(model->get_results(), outputs);
+ EXPECT_NO_THROW(Adapter(Adapter::Modality::VISION).run_on_model(model));
+ EXPECT_EQ(model->output().get_any_name(), "image_features");
+ }
+}
+
TEST(GGUFLfm3MediaAdapter, ProjectorSuppliedContractIsPreserved) {
using namespace ov::frontend::gguf;
const auto path = std::filesystem::path(ov_gguf_test::test_data_dir()) / "lfm3_media_audio.npz";
diff --git a/src/frontends/gguf/tests/test_mmproj.cpp b/src/frontends/gguf/tests/test_mmproj.cpp
index 03c34d61cac..284de52b252 100644
--- a/src/frontends/gguf/tests/test_mmproj.cpp
+++ b/src/frontends/gguf/tests/test_mmproj.cpp
@@ -182,6 +182,67 @@ TEST_F(GGUFMMProj, ExtensionReusesBuiltinProjectorAndReplacementIsExplicit) {
ov::Exception);
}
+TEST_F(GGUFMMProj, ReplacementProjectorKeepsExplicitUnsupportedGenAILayout) {
+ using namespace ov::frontend::gguf;
+ using Adapter = pass::AdaptMmprojToGenAI;
+ encoder("vision", "gemma3");
+ ASSERT_TRUE(writer.write(path));
+ ProjectorDefinition definition{"clip.vision.gemma3",
+ "clip",
+ "vision",
+ "gemma3",
+ [](GgufGraphContext& graph) {
+ auto result = build_builtin_projector(graph, "vision", "gemma3");
+ result.genai_layout = ProjectorLayout::Unsupported;
+ return result;
+ },
+ {}};
+ FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ProjectorExtension>(definition, RegistrationMode::Replace));
+ auto model = frontend.convert(frontend.load(path));
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.genai_layout"}), "unsupported");
+ ov::serialize(model, path + ".xml", path + ".bin");
+ auto restored = ov::Core{}.read_model(path + ".xml");
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ OV_EXPECT_THROW(adapter.run_on_model(restored), ov::Exception, testing::HasSubstr("no GenAI vision layout"));
+ EXPECT_TRUE(adapter.get_vision_models().empty());
+}
+
+TEST_F(GGUFMMProj, ReplacementProjectorWithoutGenAILayoutDoesNotInheritBuiltinRecipe) {
+ using namespace ov::frontend::gguf;
+ using Adapter = pass::AdaptMmprojToGenAI;
+ encoder("vision", "gemma3");
+ ASSERT_TRUE(writer.write(path));
+ ProjectorDefinition definition{
+ "clip.vision.gemma3",
+ "clip",
+ "vision",
+ "gemma3",
+ [](GgufGraphContext& graph) {
+ return ProjectorResult{graph.add_input("vision.custom", ov::element::f32, {1, 1, 2, 3}), {}};
+ },
+ {}};
+ FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ProjectorExtension>(definition, RegistrationMode::Replace));
+ auto model = frontend.convert(frontend.load(path));
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.genai_layout"}), "unsupported");
+ ov::serialize(model, path + ".xml", path + ".bin");
+ auto restored = ov::Core{}.read_model(path + ".xml");
+ for (const auto& source : {model, restored}) {
+ const auto parameters = source->get_parameters();
+ const auto results = source->get_results();
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ OV_EXPECT_THROW(adapter.run_on_model(source),
+ ov::Exception,
+ testing::HasSubstr("no GenAI vision layout for mmproj contract 'unsupported'"));
+ EXPECT_TRUE(adapter.get_vision_models().empty());
+ EXPECT_EQ(source->get_parameters(), parameters);
+ EXPECT_EQ(source->get_results(), results);
+ EXPECT_NO_THROW(Adapter(Adapter::Modality::VISION).run_on_model(source));
+ EXPECT_EQ(source->input().get_any_name(), "custom");
+ }
+}
+
TEST_F(GGUFMMProj, CustomProjectorOverridesSerializableGenAILayout) {
using namespace ov::frontend::gguf;
using Adapter = pass::AdaptMmprojToGenAI;
@@ -232,6 +293,41 @@ TEST_F(GGUFMMProj, CustomProjectorOverridesSerializableGenAILayout) {
EXPECT_EQ(replacement->input().get_any_name(), "replacement");
}
+TEST_F(GGUFMMProj, Lfm3BuilderDeclaresSingleFrameWithoutSecondPatchWeight) {
+ writer.kv_bool("clip.has_vision_encoder", true);
+ writer.kv_str("clip.vision.projector_type", "lfm3vl");
+ for (const auto& [key, value] : std::map<std::string, uint32_t>{{"embedding_length", 8},
+ {"block_count", 1},
+ {"attention.head_count", 2},
+ {"attention.head_count_kv", 1},
+ {"patch_size", 16}})
+ writer.kv_u32("clip.vision." + key, value);
+ writer.kv_f32("clip.vision.attention.layer_norm_epsilon", 1e-5f);
+ weight("v.patch_embd.weight", {16, 16, 3, 8});
+ for (const auto* name : {"v.embedding_norm", "v.blk.0.ln1", "v.blk.0.ln2", "mm.input_norm"})
+ weight(std::string(name) + ".weight", {8}, true);
+ weight("mm.input_norm.bias", {8});
+ for (const auto* name : {"attn_q", "attn_out"})
+ weight(std::string("v.blk.0.") + name + ".weight", {8, 8});
+ for (const auto* name : {"attn_k", "attn_v"})
+ weight(std::string("v.blk.0.") + name + ".weight", {8, 4});
+ for (const auto* name : {"attn_q_norm", "attn_k_norm"})
+ weight(std::string("v.blk.0.") + name + ".weight", {4}, true);
+ for (const auto* name : {"ffn_gate", "ffn_up"})
+ weight(std::string("v.blk.0.") + name + ".weight", {8, 12});
+ weight("v.blk.0.ffn_down.weight", {12, 8});
+ weight("mm.0.weight", {32, 12});
+ weight("mm.0.bias", {12});
+ weight("mm.2.weight", {12, 6});
+ weight("mm.2.bias", {6});
+ auto model = convert();
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.temporal_patch_size"}), "1");
+ EXPECT_EQ(model->get_parameters().size(), 2);
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ ASSERT_TRUE(Adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS).run_on_model(model));
+ EXPECT_EQ(model->input().get_partial_shape(), (ov::PartialShape{-1, -1, -1, 768}));
+}
+
TEST_F(GGUFMMProj, ArbitraryProjectorCallbacksOverrideRecipesAndDefinitions) {
using namespace ov::frontend::gguf;
using Adapter = pass::AdaptMmprojToGenAI;