Skip to content

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

[GGUF] Add adapt_to_genai entry point returning GenAI models (#39783)

Maxim Vafin0a3e3fb5e92b
diff --git a/.github/workflows/job_gguf_llamacpp_validation.yml b/.github/workflows/job_gguf_llamacpp_validation.yml
index d1a54488e9e..0e871c5050f 100644
--- a/.github/workflows/job_gguf_llamacpp_validation.yml
+++ b/.github/workflows/job_gguf_llamacpp_validation.yml
@@ -84,6 +84,7 @@ jobs:
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_C_COMPILER_LAUNCHER=sccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=sccache \
+ -DLLAMA_USE_PREBUILT_UI=OFF \
-DGGML_OPENVINO=ON
- name: Build llama.cpp
diff --git a/.github/workflows/ubuntu_22.yml b/.github/workflows/ubuntu_22.yml
index d1f273d456a..ffc214a6236 100644
--- a/.github/workflows/ubuntu_22.yml
+++ b/.github/workflows/ubuntu_22.yml
@@ -579,7 +579,7 @@ jobs:
runner: 'aks-linux-4-cores-16gb'
image: ${{ fromJSON(needs.docker.outputs.images).ov_build.ubuntu_22_04_x64 }}
run-real-models: ${{ github.event_name == 'schedule' }}
- genai-ref: ccb13a1c79c067234e9af56167b360037a9dc07f
+ genai-ref: 76b60924ca6436ab05b37d6e7e3658bf1d386a15
GGUF_LlamaCpp_Validation:
name: GGUF Frontend x llama.cpp validation
diff --git a/src/frontends/gguf/README.md b/src/frontends/gguf/README.md
index 470def01747..c1380a38533 100644
--- a/src/frontends/gguf/README.md
+++ b/src/frontends/gguf/README.md
@@ -28,8 +28,8 @@ the same directory, or supply a complete list of paths. No merged GGUF copy is c
See [split-file loading](docs/runtime.md#split-gguf-files) for Python and C++ usage and validation.
The result is a stateless graph with llama.cpp-style inputs and explicit cache inputs/outputs.
-In C++, register [`GenAIExtension`](include/openvino/frontend/gguf/extension/genai.hpp) to obtain a stateful model with the
-OpenVINO GenAI interface; this extension is not available from Python. Tokenizer metadata is attached
+In C++, pass the converted model to [`adapt_to_genai()`](include/openvino/frontend/gguf/adapt_to_genai.hpp) to obtain
+stateful models with the OpenVINO GenAI interface; this function is not available from Python. Tokenizer metadata is attached
to the converted model's rt_info. See [running converted models](docs/runtime.md) for both contracts.
Projector files convert to encoder models; see [multimodal conversion](docs/mmproj.md).
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 8acb25dc9f7..05eb40b5d5c 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
@@ -21,9 +21,12 @@ enum class ProjectorLayout {
WindowedPatches,
SplitMerger,
PackedPatches,
- TemporalPackedPatches
+ TemporalPackedPatches,
+ BatchedImage
};
+enum class AudioLayout { Unsupported, Gemma4, UnifiedGemma4 };
+
struct GGUF_FRONTEND_API ProjectorResult {
GgufValue output;
std::map<std::string, std::string> config;
@@ -31,6 +34,7 @@ struct GGUF_FRONTEND_API ProjectorResult {
std::optional<ProjectorLayout> genai_layout;
// Overrides the definition; an explicit empty callback selects the serializable recipe.
std::optional<ModelAdapterFn> genai_adapter;
+ std::optional<AudioLayout> audio_layout;
};
struct GGUF_FRONTEND_API ProjectorDefinition {
@@ -44,6 +48,7 @@ struct GGUF_FRONTEND_API ProjectorDefinition {
ArchitectureDefinition::MatchFn match;
std::optional<ProjectorLayout> genai_layout;
ModelAdapterFn genai_adapter;
+ std::optional<AudioLayout> audio_layout;
};
class GGUF_FRONTEND_API ProjectorExtension : public ArchitectureExtension {
diff --git a/src/frontends/gguf/docs/extensions.md b/src/frontends/gguf/docs/extensions.md
index 719cb6fe0e5..a6d2ca80afb 100644
--- a/src/frontends/gguf/docs/extensions.md
+++ b/src/frontends/gguf/docs/extensions.md
@@ -14,7 +14,7 @@ guarantee across releases: build against the release that will load the extensio
| Different topology or model family | `ArchitectureExtension` with a `ModelBuilder` factory | `load()` |
| Add or override one mmproj encoder/projector branch | `ov::frontend::gguf::ProjectorExtension` | `load()` |
| Add or override an operation converter | `ov::frontend::ConversionExtension` | `convert()` |
-| Prepare a stateful decoder with GenAI IO | `ov::frontend::gguf::GenAIExtension` | `convert()` |
+| Prepare a stateful decoder with GenAI IO | `ov::frontend::gguf::adapt_to_genai()` | After `convert()` |
| Change state handling or the model interface | `ov::frontend::DecoderTransformationExtension` | `convert()` |
Architecture and projector extensions apply only to native `.gguf` files; converters and passes
@@ -151,6 +151,12 @@ replacement projector declaring neither gets `Unsupported`; it does not inherit
its projector name. Only legacy models without `vision.genai_layout` use a built-in recipe
selected by `vision.projector`.
+Audio builders declare `audio_layout` separately. The Gemma 4 audio layouts select the matching
+GenAI input preprocessing and are serialized as `audio.genai_layout`; custom aliases can return
+the layout from `build_builtin_projector()`. A replacement that declares no audio layout remains
+unchanged, even if it reuses a built-in projector id. Only legacy models without
+`audio.genai_layout` use the built-in audio projector name.
+
A projector may declare its components with `configure_model_contract()`. For `lfm3vl`, `lfm3a`
and `lfm3a_gen` models the coordinator reads that declaration through `model_contract()` and
adds built-in component groups only where the projector declared none; declared recurrent
@@ -199,11 +205,10 @@ operation's semantics, types and layout. For a built-in converter see [how_to_ad
## Register normalization passes
`DecoderTransformationExtension` wraps a pass or a `std::shared_ptr<ov::Model>` function and runs
-during normalization, before built-in lowerings. For a GenAI-ready decoder, register
-`GenAIExtension` instead: it owns stateful conversion and adaptation after normalization.
-Do not also register `GGUFMakeStateful` or `AdaptToGenAI` on that frontend. Register one
-`GenAIExtension` per frontend instance; it applies to every conversion on that instance.
-Its embedding lookup getters describe the latest successful conversion.
+during normalization, before built-in lowerings. For a GenAI-ready decoder, call
+`adapt_to_genai()` on the converted model instead: it owns stateful conversion and adaptation.
+Do not also register `GGUFMakeStateful` or `AdaptToGenAI` on that frontend. The deprecated
+`GenAIExtension` performs the same call during `convert()`.
See [runtime.md](runtime.md#stateful-and-genai-conversion).
## Build and load a shared library
@@ -237,7 +242,7 @@ Load the actual library, convert a matching file and compare with the reference
| Two handlers claim a file | Make predicates disjoint or replace the existing handler |
| Unsupported mmproj projector | Register a `ProjectorExtension` before `load()`; check modality and resolved type |
| Missing operation converter | Register the exact string on the same frontend before `convert()` |
-| Cache remains stateless | Register `GenAIExtension` for GenAI IO, or `GGUFMakeStateful` for GGUF IO, before `convert()` |
+| Cache remains stateless | Call `adapt_to_genai()` for GenAI IO, or register `GGUFMakeStateful` for GGUF IO before `convert()` |
| Outputs differ from the reference | Follow [debugging_accuracy.md](debugging_accuracy.md) |
GenAI C++ callers can forward extension objects or shared-library paths using
diff --git a/src/frontends/gguf/docs/mmproj.md b/src/frontends/gguf/docs/mmproj.md
index 5d604e48217..7ef20fd27db 100644
--- a/src/frontends/gguf/docs/mmproj.md
+++ b/src/frontends/gguf/docs/mmproj.md
@@ -75,9 +75,20 @@ flagged by a `<key>.encoding` companion. The metadata survives IR serialization
## Using the encoders and a language model
-[`AdaptMmprojToGenAI`](../include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp) keeps one
-modality of a converted mmproj model and rewrites it in place, so run it on a separate clone for
-each modality:
+[`adapt_to_genai()`](../include/openvino/frontend/gguf/adapt_to_genai.hpp) returns every GenAI
+encoder of a converted mmproj model by name:
+
+| Name | Model |
+|---|---|
+| `vision_embeddings` | Vision encoder in the projector's GenAI layout (below), or native pixel inputs when the projector has none |
+| `vision_embeddings_pos`, `vision_embeddings_merger` | Additional models of the `split_merger` layout |
+| `audio_embeddings` | Audio encoder; Gemma4 encoders take `input_features [1,frames,width]` (plus `input_features_mask [1,frames]` for `gemma4a`, which also returns an all-true `attention_mask`) |
+| `audio_generation_<component>` | Independent speech-generation components |
+
+It uses
+[`AdaptMmprojToGenAI`](../include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp), which keeps one
+modality of a converted mmproj model and rewrites it in place. To use it directly, run it on a
+separate clone for each modality:
| Mode | Result |
|---|---|
@@ -95,6 +106,7 @@ each modality:
| `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 |
+| `batched_image` | `pixel_values [B,3,H,W]`; each image is encoded independently into `last_hidden_state [B,T,D]` (`mlp`, `internvl`) |
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
@@ -114,32 +126,22 @@ model, it also takes `token_type_ids` for bidirectional attention within an imag
[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`
-and an already converted combined `mmproj` model:
+Adapt the language model in that mode, as described in
+[runtime.md](runtime.md#stateful-and-genai-conversion). In C++, with a `FrontEndManager manager`:
```cpp
-#include <openvino/frontend/gguf/adapt_mmproj_to_genai.hpp>
-#include <openvino/frontend/gguf/extension/genai.hpp>
-
-using namespace ov::frontend::gguf::pass;
-auto vision = mmproj->clone();
-auto audio = mmproj->clone();
-AdaptMmprojToGenAI vision_adapter(AdaptMmprojToGenAI::Modality::VISION,
- AdaptMmprojToGenAI::Layout::VISION_ENCODERS);
-vision_adapter.run_on_model(vision);
-auto vision_models = vision_adapter.get_vision_models();
-AdaptMmprojToGenAI(AdaptMmprojToGenAI::Modality::AUDIO).run_on_model(audio);
+#include <openvino/frontend/gguf/adapt_to_genai.hpp>
+
+using namespace ov::frontend::gguf;
auto frontend = manager.load_by_framework("gguf");
-auto genai = std::make_shared<ov::frontend::gguf::GenAIExtension>(
- ov::frontend::gguf::GenAIExtension::InputMode::EMBEDS_TO_LOGITS);
-frontend->add_extension(genai);
-auto language = frontend->convert(frontend->load("language.gguf"));
-auto token_lookup = genai->get_embedding_model();
-auto per_layer_lookup = genai->get_per_layer_embedding_model();
+auto encoders = adapt_to_genai(frontend->convert(frontend->load("mmproj.gguf")));
+auto decoder = adapt_to_genai(frontend->convert(frontend->load("language.gguf")),
+ {pass::AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS});
+auto language = decoder.at("language");
+auto token_lookup = decoder.at("text_embeddings");
```
-`per_layer_lookup` is null for models without that branch. The consumer inserts the encoder
+`text_embeddings_per_layer` is present only for models with 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
diff --git a/src/frontends/gguf/docs/runtime.md b/src/frontends/gguf/docs/runtime.md
index 2a43a17610e..2faea1b5580 100644
--- a/src/frontends/gguf/docs/runtime.md
+++ b/src/frontends/gguf/docs/runtime.md
@@ -1,7 +1,7 @@
# Running converted GGUF models
-`convert()` returns a stateless graph with llama.cpp-style inputs. A caller-registered `GenAIExtension`
-turns a language model into a stateful model with the OpenVINO GenAI interface. Multimodal projector
+`convert()` returns a stateless graph with llama.cpp-style inputs. `adapt_to_genai()` turns a
+converted model into the stateful models with the OpenVINO GenAI interface. Multimodal projector
files use their own [encoder contract](mmproj.md#graph-boundary).
## Split GGUF files
@@ -64,34 +64,43 @@ below have no Python bindings, and `DecoderTransformationExtension` cannot be co
## Stateful and GenAI conversion
-Register `GenAIExtension` before `convert()`. The frontend creates stateful caches before
-stateless cache lowering, completes normalization (including recurrent-operation fusion), then
-adapts the normalized graph to GenAI. Callers do not register or order individual passes.
+Convert without GenAI-specific extensions, then pass the result to
+[`adapt_to_genai()`](../include/openvino/frontend/gguf/adapt_to_genai.hpp). It returns the named
+models GenAI uses; callers do not register or order individual passes. The same call adapts a
+[projector file](mmproj.md#using-the-encoders-and-a-language-model).
```cpp
-#include <openvino/frontend/gguf/extension/genai.hpp>
+#include <openvino/frontend/gguf/adapt_to_genai.hpp>
#include <openvino/frontend/manager.hpp>
using namespace ov::frontend::gguf;
ov::frontend::FrontEndManager manager;
auto frontend = manager.load_by_framework("gguf");
-frontend->add_extension(std::make_shared<GenAIExtension>());
-auto model = frontend->convert(frontend->load("model.gguf"));
+auto models = adapt_to_genai(frontend->convert(frontend->load("model.gguf")));
+auto language = models.at("language");
```
+`adapt_to_genai()` modifies and returns the converted decoder as `language`, and throws for a
+model that is already adapted. `GenAIExtension` is deprecated: it calls `adapt_to_genai()` at
+the end of `convert()` and returns `language`.
+
Internally, [`GGUFMakeStateful`](../include/openvino/frontend/gguf/make_stateful.hpp) replaces each KV cache
-Parameter/Result pair with a Variable, adds `beam_idx` and reorders caches by it. Sliding-window
+Parameter/Result pair with a Variable, adds `beam_idx` and reorders caches by it. It accepts both
+the frontend's cache-write operation and its lowered stateless form, so it runs on a converted model. Sliding-window
caches can be left stateless with `skip_caches`. Recurrent states are declared through the
`gguf_recurrent_states` rt_info key.
-[`AdaptToGenAI`](../include/openvino/frontend/gguf/adapt_to_genai.hpp) requires a stateful model and
-exposes GenAI's interface. Select the mode in the `GenAIExtension` constructor:
+[`AdaptToGenAI`](../include/openvino/frontend/gguf/adapt_to_genai.hpp) then exposes GenAI's
+interface. Select the mode with `GenAIAdaptOptions::input`:
| Mode | Inputs | Output |
|---|---|---|
| `IDS_TO_LOGITS` (default) | `input_ids [B,T]`, `attention_mask [B,KV]`, `position_ids [B,T]`, `beam_idx [B]` | `logits [B,T,vocab]` |
| `EMBEDS_TO_LOGITS` | `inputs_embeds [B,T,D]` instead of `input_ids`; see [multimodal language models](mmproj.md#using-the-encoders-and-a-language-model) | `logits [B,T,vocab]` |
+`EMBEDS_TO_LOGITS` also returns the token lookup as `text_embeddings` and, for architectures with
+per-layer token embeddings, `text_embeddings_per_layer`.
+
- The leading dimensions are derived from the live inputs, so one graph serves both SDPA and
`ov::pass::SDPAToPagedAttention`.
- The LM head is connected directly to the logits Result with a rank-3 input, so GenAI's
diff --git a/src/frontends/gguf/examples/architecture_extension/README.md b/src/frontends/gguf/examples/architecture_extension/README.md
index 38521e1a72a..5f4749a99d2 100644
--- a/src/frontends/gguf/examples/architecture_extension/README.md
+++ b/src/frontends/gguf/examples/architecture_extension/README.md
@@ -46,7 +46,7 @@ python3 src/frontends/gguf/examples/architecture_extension/generate_fixtures.py
Both projection examples return `[1,1,3,3]` embeddings; with the runner's all-one
inputs, each token's values are `[3,7,11]`. The decoder example returns `[1,1,16]` last-token logits and
-exercises `GenAIExtension`, which creates stateful caches and adapts IO after frontend normalization.
+exercises `adapt_to_genai()`, which creates stateful caches and adapts IO of the converted model.
The runner registers the library before loading the file, converts it, compiles on
CPU, fills supported inputs, checks that F32 outputs are finite, and prints output names, shapes, types and first values.
diff --git a/src/frontends/gguf/examples/architecture_extension/runner.cpp b/src/frontends/gguf/examples/architecture_extension/runner.cpp
index 24a2f63a70b..9c15640acc0 100644
--- a/src/frontends/gguf/examples/architecture_extension/runner.cpp
+++ b/src/frontends/gguf/examples/architecture_extension/runner.cpp
@@ -7,7 +7,7 @@
#include <iostream>
#include <stdexcept>
-#include "openvino/frontend/gguf/extension/genai.hpp"
+#include "openvino/frontend/gguf/adapt_to_genai.hpp"
#include "openvino/frontend/gguf/frontend.hpp"
#include "openvino/openvino.hpp"
@@ -26,10 +26,9 @@ int main(int argc, char** argv) {
throw std::invalid_argument("TOKENS must be positive");
std::shared_ptr<ov::frontend::FrontEnd> frontend = std::make_shared<ov::frontend::gguf::FrontEnd>();
frontend->add_extension(std::string(argv[1]));
- if (stateful) {
- frontend->add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());
- }
auto model = frontend->convert(frontend->load(std::string(argv[2])));
+ if (stateful)
+ model = ov::frontend::gguf::adapt_to_genai(model).at("language");
auto compiled = ov::Core{}.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32));
auto request = compiled.create_infer_request();
for (const auto& input : compiled.inputs()) {
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/adapt_to_genai.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/adapt_to_genai.hpp
index 918bc0fb0b3..a5f90460a2d 100644
--- a/src/frontends/gguf/include/openvino/frontend/gguf/adapt_to_genai.hpp
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/adapt_to_genai.hpp
@@ -4,6 +4,7 @@
#pragma once
+#include "openvino/frontend/gguf/model_adapter.hpp"
#include "openvino/frontend/gguf/visibility.hpp"
#include "openvino/pass/pass.hpp"
@@ -80,3 +81,37 @@ private:
};
} // namespace ov::frontend::gguf::pass
+
+namespace ov::frontend::gguf {
+
+struct GenAIAdaptOptions {
+ /// Input contract of a decoder's language model; ignored for an mmproj.
+ pass::AdaptToGenAI::InputMode input = pass::AdaptToGenAI::InputMode::IDS_TO_LOGITS;
+};
+
+/// \brief Adapt a model returned by FrontEnd::convert to the models used by OpenVINO GenAI.
+///
+/// Convert without GenAI-specific extensions, then call this once per converted file:
+///
+/// ov::frontend::gguf::FrontEnd fe;
+/// auto models = ov::frontend::gguf::adapt_to_genai(fe.convert(fe.load(gguf_path)));
+/// auto language = models.at("language");
+///
+/// A decoder is made stateful (GGUFMakeStateful) and adapted (AdaptToGenAI). It returns
+/// "language" and, for EMBEDS_TO_LOGITS, "text_embeddings" plus "text_embeddings_per_layer" when the
+/// architecture has per-layer token embeddings.
+///
+/// An mmproj returns one entry per encoder:
+/// - "vision_embeddings" with the GenAI vision encoder inputs, plus "vision_embeddings_pos" and
+/// "vision_embeddings_merger" for split-merger projectors; projector callbacks name their own
+/// models. A vision projector without a GenAI layout keeps the native encoder inputs.
+/// - "audio_embeddings"; Gemma4 encoders take GenAI input_features, other encoders keep their
+/// native inputs.
+/// - "audio_generation_<component>" for each declared audio-generation component.
+///
+/// The supplied model is consumed: the returned models may reuse or modify it, and share its
+/// weights. Throws if the model is neither a converted GGUF decoder nor an mmproj.
+GGUF_FRONTEND_API ModelMap adapt_to_genai(const std::shared_ptr<ov::Model>& model,
+ const GenAIAdaptOptions& options = {});
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/extension/genai.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/extension/genai.hpp
index 3fefe3d8a79..3fc619ea3ff 100644
--- a/src/frontends/gguf/include/openvino/frontend/gguf/extension/genai.hpp
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/extension/genai.hpp
@@ -11,6 +11,7 @@ namespace ov::frontend::gguf {
/// Prepare a decoder for GenAI during convert(): stateful caches, then normalized GenAI IO.
/// Register before convert(), without separate GGUFMakeStateful or AdaptToGenAI passes.
+/// \deprecated Call ov::frontend::gguf::adapt_to_genai on the converted model instead.
class GGUF_FRONTEND_API GenAIExtension : public ov::Extension {
public:
OPENVINO_RTTI("gguf::GenAIExtension", "", ov::Extension);
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp
index 2387a66f8b4..2635b58c7c8 100644
--- a/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp
@@ -41,8 +41,8 @@ public:
/// - `ov::frontend::gguf::ArchitectureExtension` — registers decoder or custom-family builders
/// before load(), without rebuilding the frontend. See docs/extensions.md.
/// - `ov::frontend::gguf::ProjectorExtension` — registers one mmproj branch before load().
- /// - `ov::frontend::gguf::GenAIExtension` — creates stateful decoder caches during normalization
- /// and adapts the normalized model to GenAI IO before convert() returns.
+ /// - `ov::frontend::gguf::GenAIExtension` — deprecated; calls ov::frontend::gguf::adapt_to_genai
+ /// before convert() returns.
/// - `ov::frontend::TelemetryExtension` — stored; callbacks are not currently invoked.
/// - `ov::detail::SOExtension` — shared-library extension; its inner extension is recursively registered.
/// - `ov::BaseOpExtension` — recursively registers attached op-level extensions.
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/make_stateful.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/make_stateful.hpp
index c76e08ff806..34a9b4556e5 100644
--- a/src/frontends/gguf/include/openvino/frontend/gguf/make_stateful.hpp
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/make_stateful.hpp
@@ -26,9 +26,11 @@ namespace ov::frontend::gguf::pass {
///
/// Extensions run ahead of the built-in LowerSetRowsStateless, so this pass claims the KV-cache
/// SetRows ops and the default stateless lowering only sees the rest (e.g. MoE routing writes).
+/// The pass can also run on a converted stateless model, where it rewrites the KV-cache writes
+/// already lowered to ScatterUpdate; ov::frontend::gguf::adapt_to_genai does this.
///
/// Per KV cache it replaces the Parameter/Result pair with a Variable + ReadValue(empty init) +
-/// Gather(beam_idx) + Concat(past, this step's rows) + Assign. Only a SetRows writing to a model
+/// Gather(beam_idx) + Concat(past, this step's rows) + Assign. Only a write to a model
/// Parameter is converted.
///
/// Two details that are load-bearing rather than cosmetic:
diff --git a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
index 75369530e62..e9bfffdf990 100644
--- a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
@@ -66,6 +66,7 @@ struct ProjectorTopology {
EncoderTopology topology;
unsigned traits = 0;
ProjectorLayout genai_layout = ProjectorLayout::Unsupported;
+ AudioLayout audio_layout = AudioLayout::Unsupported;
};
// Entries describe implemented graph topologies, independently of language DecoderConfig.
@@ -78,16 +79,16 @@ constexpr ProjectorTopology projector_catalog[] = {
{"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", "gemma4a", EncoderTopology::GEMMA4_AUDIO, 0, ProjectorLayout::Unsupported, AudioLayout::Gemma4},
{"audio", "lfm2a", EncoderTopology::LFM2_AUDIO},
- {"audio", "gemma4ua", EncoderTopology::UNIFIED_AUDIO},
+ {"audio", "gemma4ua", EncoderTopology::UNIFIED_AUDIO, 0, ProjectorLayout::Unsupported, AudioLayout::UnifiedGemma4},
{"vision", "minicpmv4_6", EncoderTopology::MINICPM46},
{"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},
- {"vision", "internvl", EncoderTopology::INTERNVL},
+ {"vision", "mlp", EncoderTopology::CLIP, SWAPPED_FFN, ProjectorLayout::BatchedImage},
+ {"vision", "internvl", EncoderTopology::INTERNVL, 0, ProjectorLayout::BatchedImage},
{"vision", "resampler", EncoderTopology::RESAMPLER},
{"vision", "qwen2vl_merger", EncoderTopology::QWEN, SWAPPED_FFN},
{"vision", "qwen2.5vl_merger", EncoderTopology::QWEN, RMS_NORM | SWAPPED_FFN},
@@ -1228,7 +1229,10 @@ std::vector<std::string> build_mmproj_encoders(GgufGraphContext& g,
config[definition->modality + ".projector"] = definition->projector_type;
const auto layout =
result.genai_layout.value_or(definition->genai_layout.value_or(ProjectorLayout::Unsupported));
- config[definition->modality + ".genai_layout"] = projector_layout_name(layout);
+ config[definition->modality + ".genai_layout"] =
+ definition->modality == "audio" ? audio_layout_name(result.audio_layout.value_or(
+ definition->audio_layout.value_or(AudioLayout::Unsupported)))
+ : projector_layout_name(layout);
auto callback = result.genai_adapter.value_or(definition->genai_adapter);
if (callback) {
auto adapter = std::make_shared<ModelAdapter>();
@@ -1340,6 +1344,16 @@ ProjectorLayout builtin_projector_layout(const std::string& projector_type) {
return ProjectorLayout::Unsupported;
}
+namespace {
+AudioLayout builtin_audio_layout(const std::string& projector_type) {
+ for (const auto& entry : projector_catalog) {
+ if (std::string(entry.modality) == "audio" && projector_type == entry.name)
+ return entry.audio_layout;
+ }
+ return AudioLayout::Unsupported;
+}
+} // namespace
+
ProjectorResult build_builtin_projector(GgufGraphContext& graph,
const std::string& modality,
const std::string& projector_type) {
@@ -1350,6 +1364,8 @@ ProjectorResult build_builtin_projector(GgufGraphContext& graph,
const auto layout = builtin_projector_layout(projector_type);
if (layout != ProjectorLayout::Unsupported)
result.genai_layout = layout;
+ } else if (modality == "audio") {
+ result.audio_layout = builtin_audio_layout(projector_type);
}
return result;
}
@@ -1359,14 +1375,16 @@ std::vector<ProjectorDefinition> builtin_projectors() {
for (const auto& entry : projector_catalog) {
const std::string modality = entry.modality;
const std::string type = entry.name;
- definitions.push_back({"clip." + modality + "." + type,
- "clip",
- modality,
- type,
- [modality, type](GgufGraphContext& graph) {
- return build_builtin_projector(graph, modality, type);
- },
- {}});
+ auto definition = ProjectorDefinition{"clip." + modality + "." + type,
+ "clip",
+ modality,
+ type,
+ [modality, type](GgufGraphContext& graph) {
+ return build_builtin_projector(graph, modality, type);
+ },
+ {}};
+ definition.audio_layout = entry.audio_layout;
+ definitions.push_back(std::move(definition));
}
return definitions;
}
diff --git a/src/frontends/gguf/src/builder/arch/projector_adapter.cpp b/src/frontends/gguf/src/builder/arch/projector_adapter.cpp
index 447574472b8..501a0b00742 100644
--- a/src/frontends/gguf/src/builder/arch/projector_adapter.cpp
+++ b/src/frontends/gguf/src/builder/arch/projector_adapter.cpp
@@ -10,6 +10,7 @@
#include <utility>
#include "openvino/core/graph_util.hpp"
+#include "openvino/core/rt_info.hpp"
#include "openvino/op/add.hpp"
#include "openvino/op/broadcast.hpp"
#include "openvino/op/concat.hpp"
@@ -466,6 +467,44 @@ void temporal_packed_patch_layout(const std::shared_ptr<ov::Model>& model, int64
model->validate_nodes_and_infer_types();
}
+// Encode each image of a [B, 3, H, W] batch independently into [B, tokens, width] features.
+void batched_image_layout(const std::shared_ptr<ov::Model>& model) {
+ OPENVINO_ASSERT(model->get_parameters().size() == 1 && model->get_results().size() == 1,
+ "[GGUF] batched image vision requires one pixel input and one output");
+ const auto result = model->get_results().front();
+ auto body = model->clone();
+ const auto pixels = body->get_parameters().front();
+ auto shape = pixels->get_partial_shape();
+ OPENVINO_ASSERT(shape.rank().is_static() && shape.size() == 4 && shape[0] == 1 && shape[1] == 3,
+ "[GGUF] batched image vision requires RGB NCHW pixels with a singleton batch");
+ const auto features = body->get_results().front()->input_value(0);
+ const auto output_shape = features.get_partial_shape();
+ OPENVINO_ASSERT(output_shape.rank().is_static() && output_shape.size() == 3 && output_shape[0] == 1,
+ "[GGUF] batched image vision requires [1, tokens, width] embeddings");
+ shape[0] = ov::Dimension::dynamic();
+ auto input = std::make_shared<v0::Parameter>(pixels->get_element_type(), shape);
+ name_output(input, "pixel_values");
+ ov::copy_runtime_info(pixels, input);
+ 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();
+ ov::copy_runtime_info({features.get_node_shared_ptr(), result}, iterator);
+ if (!result->get_friendly_name().empty())
+ iterator->set_friendly_name(result->get_friendly_name());
+ model->remove_result(model->get_results().front());
+ model->remove_parameter(model->get_parameters().front());
+ model->add_parameters({input});
+ auto adapted_result = std::make_shared<v0::Result>(output);
+ ov::copy_runtime_info(result, adapted_result);
+ if (!result->get_friendly_name().empty())
+ adapted_result->set_friendly_name(result->get_friendly_name());
+ model->add_results({adapted_result});
+ model->validate_nodes_and_infer_types();
+}
+
constexpr std::pair<ProjectorLayout, const char*> layout_names[] = {
{ProjectorLayout::Unsupported, "unsupported"},
{ProjectorLayout::Image, "image"},
@@ -474,7 +513,33 @@ constexpr std::pair<ProjectorLayout, const char*> layout_names[] = {
{ProjectorLayout::SplitMerger, "split_merger"},
{ProjectorLayout::PackedPatches, "packed_patches"},
{ProjectorLayout::TemporalPackedPatches, "temporal_packed_patches"},
+ {ProjectorLayout::BatchedImage, "batched_image"},
+};
+
+constexpr std::pair<AudioLayout, const char*> audio_layout_names[] = {
+ {AudioLayout::Unsupported, "unsupported"},
+ {AudioLayout::Gemma4, "gemma4"},
+ {AudioLayout::UnifiedGemma4, "unified_gemma4"},
};
+
+AudioLayout read_audio_layout(const std::shared_ptr<ov::Model>& model) {
+ if (!model->has_rt_info({"gguf_mmproj", "audio.genai_layout"})) {
+ if (!model->has_rt_info({"gguf_mmproj", "audio.projector"}))
+ return AudioLayout::Unsupported;
+ const auto projector = model->get_rt_info<std::string>({"gguf_mmproj", "audio.projector"});
+ if (projector == "gemma4a")
+ return AudioLayout::Gemma4;
+ if (projector == "gemma4ua")
+ return AudioLayout::UnifiedGemma4;
+ return AudioLayout::Unsupported;
+ }
+ const auto name = model->get_rt_info<std::string>({"gguf_mmproj", "audio.genai_layout"});
+ for (const auto& [layout, layout_name] : audio_layout_names) {
+ if (name == layout_name)
+ return layout;
+ }
+ OPENVINO_THROW("[GGUF] no GenAI audio layout for mmproj contract '", name, "'");
+}
} // namespace
ProjectorLayout read_projector_layout(const std::shared_ptr<ov::Model>& model) {
@@ -505,6 +570,14 @@ std::string projector_layout_name(ProjectorLayout layout) {
OPENVINO_THROW("[GGUF] invalid GenAI projector layout contract");
}
+std::string audio_layout_name(AudioLayout layout) {
+ for (const auto& [candidate, name] : audio_layout_names) {
+ if (candidate == layout)
+ return name;
+ }
+ OPENVINO_THROW("[GGUF] invalid GenAI audio layout contract");
+}
+
ProjectorModels adapt_projector_layout(const std::shared_ptr<ov::Model>& model) {
switch (read_projector_layout(model)) {
case ProjectorLayout::Image:
@@ -530,10 +603,67 @@ ProjectorModels adapt_projector_layout(const std::shared_ptr<ov::Model>& model)
mmproj_int_metadata(model, "vision.patch_size"),
mmproj_int_metadata(model, "vision.temporal_patch_size"));
break;
+ case ProjectorLayout::BatchedImage:
+ batched_image_layout(model);
+ break;
case ProjectorLayout::Unsupported:
OPENVINO_THROW("[GGUF] no GenAI vision layout contract");
}
return {{"vision_embeddings", model}};
}
+void adapt_audio_layout(const std::shared_ptr<ov::Model>& model) {
+ const auto layout = read_audio_layout(model);
+ if (layout == AudioLayout::Unsupported)
+ return;
+ const bool unified = layout == AudioLayout::UnifiedGemma4;
+ OPENVINO_ASSERT(model->get_parameters().size() == 1 && model->get_results().size() == 1,
+ "[GGUF] Gemma4 audio requires one feature input and one output");
+ const auto original = model->get_parameters().front();
+ // The encoder reads [1, 1, mel, frames] spectrograms or [1, 1, frames, samples] waveform frames.
+ const auto& source = original->get_partial_shape();
+ const auto width_axis = unified ? 3 : 2;
+ OPENVINO_ASSERT(source.rank().is_static() && source.size() == 4 && source[width_axis].is_static(),
+ "[GGUF] Gemma4 audio requires a static feature width");
+ const auto features =
+ std::make_shared<v0::Parameter>(original->get_element_type(), ov::PartialShape{1, -1, source[width_axis]});
+ name_output(features, "input_features");
+ ov::NodeVector preprocessing{features};
+ Value input = features;
+ if (!unified) {
+ // Valid frames form a prefix; the encoder sees them as [1, mel, frames].
+ const auto mask = std::make_shared<v0::Parameter>(ov::element::boolean, ov::PartialShape{1, -1});
+ name_output(mask, "input_features_mask");
+ auto converted_mask = std::make_shared<v0::Convert>(mask, ov::element::i64);
+ auto length = std::make_shared<v1::ReduceSum>(converted_mask, ints({1}), false);
+ auto sliced = std::make_shared<v8::Slice>(input, ints({0}), length, ints({1}), ints({1}));
+ auto transposed = std::make_shared<v1::Transpose>(sliced, ints({0, 2, 1}));
+ preprocessing.insert(preprocessing.end(), {converted_mask, length, sliced, transposed});
+ input = transposed;
+ model->add_parameters({mask});
+ }
+ auto expanded = std::make_shared<v0::Unsqueeze>(input, ints({1}));
+ preprocessing.push_back(expanded);
+ ov::copy_runtime_info(original, preprocessing);
+ ov::replace_node(original, expanded);
+ model->remove_parameter(original);
+ model->add_parameters({features});
+ const auto result = model->get_results().front();
+ auto output = result->input_value(0);
+ output.set_names({"last_hidden_state"});
+ if (!unified) {
+ auto axes = ints({0, 1});
+ auto batch_axis = ints({0});
+ auto shape = std::make_shared<v3::ShapeOf>(output);
+ auto dimensions = std::make_shared<v8::Gather>(shape, axes, batch_axis);
+ auto ones = v0::Constant::create(ov::element::boolean, {}, {true});
+ auto mask = std::make_shared<v3::Broadcast>(ones, dimensions);
+ mask->output(0).set_names({"attention_mask"});
+ auto attention_mask = std::make_shared<v0::Result>(mask);
+ ov::copy_runtime_info(result, ov::NodeVector{axes, batch_axis, shape, dimensions, ones, mask, attention_mask});
+ model->add_results({attention_mask});
+ }
+ model->validate_nodes_and_infer_types();
+}
+
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/arch/projector_adapter.hpp b/src/frontends/gguf/src/builder/arch/projector_adapter.hpp
index f3dc7a420ec..ad034a0c5c1 100644
--- a/src/frontends/gguf/src/builder/arch/projector_adapter.hpp
+++ b/src/frontends/gguf/src/builder/arch/projector_adapter.hpp
@@ -16,10 +16,13 @@ namespace ov::frontend::gguf {
using ProjectorModels = std::map<std::string, std::shared_ptr<ov::Model>>;
std::string projector_layout_name(ProjectorLayout layout);
+std::string audio_layout_name(AudioLayout layout);
// Vision GenAI layout of a built-in projector type; Unsupported for other types.
ProjectorLayout builtin_projector_layout(const std::string& projector_type);
// 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);
+// GenAI audio encoder inputs for an audio model adapted to EMBEDDINGS; other projectors are unchanged.
+void adapt_audio_layout(const std::shared_ptr<ov::Model>& model);
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/frontend.cpp b/src/frontends/gguf/src/frontend.cpp
index 4e2a6391e0c..e508d72a8d0 100644
--- a/src/frontends/gguf/src/frontend.cpp
+++ b/src/frontends/gguf/src/frontend.cpp
@@ -118,19 +118,21 @@ std::shared_ptr<Model> FrontEnd::convert(const InputModel::Ptr& model) const {
}
conversion_input = std::make_shared<gguf::InputModel>(std::make_shared<GgufBuilderDecoder>(graph));
}
- auto transformations = m_impl->transformation_extensions;
- if (m_impl->genai_extension) {
- transformations.push_back(std::make_shared<DecoderTransformationExtension>(pass::GGUFMakeStateful()));
- }
- TranslateSession translate_session(conversion_input, ops, transformations);
+ TranslateSession translate_session(conversion_input, ops, m_impl->transformation_extensions);
converted_model = translate_session.get_converted_model();
}
- if (m_impl->genai_extension) {
- pass::AdaptToGenAI adapter(m_impl->genai_extension->m_mode);
- FRONT_END_GENERAL_CHECK(adapter.run_on_model(converted_model),
+ // TODO: Remove this compatibility path once GenAI no longer uses GenAIExtension.
+ if (const auto& genai = m_impl->genai_extension) {
+ FRONT_END_GENERAL_CHECK(!converted_model->has_rt_info("gguf_mmproj"),
"GenAIExtension requires a GGUF decoder with adaptable inputs");
- m_impl->genai_extension->m_embedding_model = adapter.get_embedding_model();
- m_impl->genai_extension->m_per_layer_embedding_model = adapter.get_per_layer_embedding_model();
+ auto models = adapt_to_genai(converted_model, {genai->m_mode});
+ const auto model = [&](const std::string& name) {
+ const auto found = models.find(name);
+ return found == models.end() ? nullptr : found->second;
+ };
+ converted_model = model("language");
+ genai->m_embedding_model = model("text_embeddings");
+ genai->m_per_layer_embedding_model = model("text_embeddings_per_layer");
}
return converted_model;
}
diff --git a/src/frontends/gguf/src/genai_adaptation.cpp b/src/frontends/gguf/src/genai_adaptation.cpp
new file mode 100644
index 00000000000..a68b29c0de6
--- /dev/null
+++ b/src/frontends/gguf/src/genai_adaptation.cpp
@@ -0,0 +1,110 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <unordered_set>
+
+#include "builder/arch/projector_adapter.hpp"
+#include "model_adapter_attribute.hpp"
+#include "model_contract.hpp"
+#include "openvino/frontend/gguf/adapt_mmproj_to_genai.hpp"
+#include "openvino/frontend/gguf/adapt_to_genai.hpp"
+#include "openvino/frontend/gguf/make_stateful.hpp"
+#include "pass/prune_orphaned_parameters.hpp"
+#include "utils.hpp"
+
+namespace ov::frontend::gguf {
+namespace {
+
+using pass::AdaptMmprojToGenAI;
+
+ModelMap adapt_decoder(const std::shared_ptr<ov::Model>& model, const GenAIAdaptOptions& options) {
+ if (!find_parameter(model, "beam_idx")) {
+ auto live = std::make_shared<std::unordered_set<const ov::Node*>>();
+ pass::SnapshotLiveParameters(live).run_on_model(model);
+ pass::GGUFMakeStateful().run_on_model(model);
+ // The stateful caches no longer read the lowered write indices.
+ pass::PruneParametersOrphanedSince(live).run_on_model(model);
+ }
+ pass::AdaptToGenAI adapter(options.input);
+ OPENVINO_ASSERT(adapter.run_on_model(model),
+ "[GGUF] adapt_to_genai requires a model converted by the GGUF frontend; the model is already "
+ "adapted or has no GGUF decoder inputs");
+ ModelMap models{{"language", model}};
+ if (const auto& embeddings = adapter.get_embedding_model())
+ models.emplace("text_embeddings", embeddings);
+ if (const auto& per_layer = adapter.get_per_layer_embedding_model())
+ models.emplace("text_embeddings_per_layer", per_layer);
+ return models;
+}
+
+bool has_genai_vision_layout(const std::shared_ptr<ov::Model>& model) {
+ for (const auto& result : model->get_results()) {
+ if (result->input_value(0).get_names().count("vision.embeddings") && get_model_adapter(result))
+ return true;
+ }
+ if (model->has_rt_info({"gguf_mmproj", "vision.genai_layout"}))
+ return model->get_rt_info<std::string>({"gguf_mmproj", "vision.genai_layout"}) !=
+ projector_layout_name(ProjectorLayout::Unsupported);
+ const auto projector = model->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"});
+ return builtin_projector_layout(projector) != ProjectorLayout::Unsupported;
+}
+
+bool has_genai_adapter(const std::shared_ptr<ov::Model>& model, const std::string& modality) {
+ const auto embedding_name = modality + ".embeddings";
+ for (const auto& result : model->get_results()) {
+ if (result->input_value(0).get_names().count(embedding_name) && get_model_adapter(result))
+ return true;
+ }
+ return false;
+}
+
+ModelMap adapt_mmproj(const std::shared_ptr<ov::Model>& model) {
+ ModelMap models;
+ const auto add = [&](const std::string& name, const std::shared_ptr<ov::Model>& adapted) {
+ OPENVINO_ASSERT(models.emplace(name, adapted).second, "[GGUF] mmproj declares model '", name, "' twice");
+ };
+ if (model->has_rt_info({"gguf_mmproj", "vision.projector"})) {
+ auto vision = model->clone();
+ if (has_genai_vision_layout(model)) {
+ AdaptMmprojToGenAI adapter(AdaptMmprojToGenAI::Modality::VISION,
+ AdaptMmprojToGenAI::Layout::VISION_ENCODERS);
+ adapter.run_on_model(vision);
+ for (const auto& [name, encoder] : adapter.get_vision_models())
+ add(name, encoder);
+ } else {
+ AdaptMmprojToGenAI(AdaptMmprojToGenAI::Modality::VISION).run_on_model(vision);
+ add("vision_embeddings", vision);
+ }
+ }
+ if (model->has_rt_info({"gguf_mmproj", "audio.projector"})) {
+ auto audio = model->clone();
+ const bool has_adapter = has_genai_adapter(audio, "audio");
+ AdaptMmprojToGenAI adapter(AdaptMmprojToGenAI::Modality::AUDIO);
+ adapter.run_on_model(audio);
+ if (!has_adapter)
+ adapt_audio_layout(audio);
+ const auto& audio_models = adapter.get_vision_models();
+ for (const auto& [name, component] : audio_models)
+ add(name, component);
+ if (audio_models.empty())
+ add("audio_embeddings", audio);
+ }
+ if (read_model_contract(model).component_groups.count("audio_generation")) {
+ AdaptMmprojToGenAI adapter(AdaptMmprojToGenAI::Modality::AUDIO_GENERATION);
+ adapter.run_on_model(model->clone());
+ for (const auto& [name, component] : adapter.get_audio_generation_models())
+ add("audio_generation_" + name, component);
+ }
+ OPENVINO_ASSERT(!models.empty(), "[GGUF] mmproj has no encoder for GenAI");
+ return models;
+}
+
+} // namespace
+
+ModelMap adapt_to_genai(const std::shared_ptr<ov::Model>& model, const GenAIAdaptOptions& options) {
+ OPENVINO_ASSERT(model, "[GGUF] adapt_to_genai requires a model");
+ return model->has_rt_info("gguf_mmproj") ? adapt_mmproj(model) : adapt_decoder(model, options);
+}
+
+} // 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 eca6e05813e..440cc8ab21f 100644
--- a/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
@@ -12,6 +12,7 @@
#include "builder/arch/projector_adapter.hpp"
#include "model_adapter_attribute.hpp"
#include "model_contract.hpp"
+#include "openvino/core/rt_info.hpp"
#include "openvino/frontend/gguf/make_stateful.hpp"
#include "openvino/op/assign.hpp"
#include "openvino/op/constant.hpp"
@@ -184,6 +185,7 @@ ModelAdapterResult adapt_mmproj(const std::shared_ptr<ov::Model>& model,
model->remove_result(result);
auto embeddings = std::make_shared<ov::op::v0::Squeeze>(selected->input_value(0),
ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
+ ov::copy_runtime_info({selected, selected->input_value(0).get_node_shared_ptr()}, embeddings);
size_t auxiliary_count = 0;
if (modality == Modality::VISION && model->has_rt_info({"gguf_mmproj", "vision.auxiliary_count"}))
auxiliary_count = size_t(mmproj_int_metadata(model, "vision.auxiliary_count", 0));
@@ -193,12 +195,16 @@ ModelAdapterResult adapt_mmproj(const std::shared_ptr<ov::Model>& model,
auxiliary_count + 1);
for (size_t i = 0; i <= auxiliary_count; ++i) {
split->output(i).set_names({i == 0 ? "image_features" : "deepstack_features." + std::to_string(i - 1)});
- model->add_results({std::make_shared<ov::op::v0::Result>(split->output(i))});
+ auto result = std::make_shared<ov::op::v0::Result>(split->output(i));
+ ov::copy_runtime_info(selected, result);
+ model->add_results({result});
}
} else {
// Only the tensor that becomes a Result is named; the Split path names output 0 instead.
embeddings->output(0).set_names({modality == Modality::VISION ? "image_features" : "audio_features"});
- model->add_results({std::make_shared<ov::op::v0::Result>(embeddings)});
+ auto result = std::make_shared<ov::op::v0::Result>(embeddings);
+ ov::copy_runtime_info(selected, result);
+ model->add_results({result});
}
model->add_results(retained_results);
PruneParametersOrphanedSince(live_before).run_on_model(model);
diff --git a/src/frontends/gguf/src/pass/lower_set_rows_stateless.cpp b/src/frontends/gguf/src/pass/lower_set_rows_stateless.cpp
index b379d0ef78d..c4e2312b664 100644
--- a/src/frontends/gguf/src/pass/lower_set_rows_stateless.cpp
+++ b/src/frontends/gguf/src/pass/lower_set_rows_stateless.cpp
@@ -11,6 +11,7 @@
#include "openvino/core/rt_info.hpp"
#include "openvino/frontend/gguf/set_rows_op.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/parameter.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/scatter_update.hpp"
#include "openvino/op/shape_of.hpp"
@@ -53,6 +54,8 @@ LowerSetRowsStateless::LowerSetRowsStateless() {
res->set_friendly_name(set_rows->get_friendly_name());
ov::copy_runtime_info(set_rows, res);
+ if (ov::as_type_ptr<ov::op::v0::Parameter>(dst.get_node_shared_ptr()))
+ res->get_rt_info()[kv_cache_write_key()] = true;
ov::replace_node(set_rows, res);
return true;
};
diff --git a/src/frontends/gguf/src/pass/lower_set_rows_stateless.hpp b/src/frontends/gguf/src/pass/lower_set_rows_stateless.hpp
index 03b85b6b06c..55425f0c656 100644
--- a/src/frontends/gguf/src/pass/lower_set_rows_stateless.hpp
+++ b/src/frontends/gguf/src/pass/lower_set_rows_stateless.hpp
@@ -4,6 +4,8 @@
#pragma once
+#include <string>
+
#include "openvino/pass/matcher_pass.hpp"
namespace ov::frontend::gguf {
@@ -16,11 +18,19 @@ namespace pass {
// frontend's normalization stage so a plain convert() yields a runnable stateless model. A caller
// wanting stateful execution registers an alternative lowering via DecoderTransformationExtension
// (which runs first and consumes the KV-cache SetRows ops before this pass sees them).
+//
+// A lowered write into a model Parameter is a KV cache write. Its output Reshape carries
+// kv_cache_write_key() in rt_info, so GGUFMakeStateful can still make it stateful after conversion.
class LowerSetRowsStateless : public ov::pass::MatcherPass {
public:
OPENVINO_MATCHER_PASS_RTTI("ov::frontend::gguf::pass::LowerSetRowsStateless")
LowerSetRowsStateless();
};
+inline const std::string& kv_cache_write_key() {
+ static const std::string key = "gguf_kv_cache_write";
+ return key;
+}
+
} // namespace pass
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/pass/make_stateful.cpp b/src/frontends/gguf/src/pass/make_stateful.cpp
index b820754f0df..bc8f6af2c72 100644
--- a/src/frontends/gguf/src/pass/make_stateful.cpp
+++ b/src/frontends/gguf/src/pass/make_stateful.cpp
@@ -28,6 +28,7 @@
#include "openvino/op/reshape.hpp"
#include "openvino/op/result.hpp"
#include "openvino/op/scaled_dot_product_attention.hpp"
+#include "openvino/op/scatter_update.hpp"
#include "openvino/op/shape_of.hpp"
#include "openvino/op/slice.hpp"
#include "openvino/op/transpose.hpp"
@@ -38,6 +39,7 @@
#include "openvino/pass/pattern/op/or.hpp"
#include "openvino/pass/pattern/op/pattern.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "pass/lower_set_rows_stateless.hpp"
#include "transformations/utils/utils.hpp"
#include "utils.hpp"
@@ -60,6 +62,14 @@ void finalize_stateful_rewrite(const std::shared_ptr<ov::Model>& model,
}
}
+void copy_cache_write_runtime_info(const std::shared_ptr<ov::Node>& write,
+ const std::shared_ptr<ov::Node>& cache,
+ const ov::NodeVector& replacements) {
+ ov::copy_runtime_info({write, cache}, replacements);
+ for (const auto& replacement : replacements)
+ replacement->get_rt_info().erase(kv_cache_write_key());
+}
+
// The axis the cache grows along. An un-preallocated cache Parameter states it by construction: it
// is the one dynamic axis (the token count), every other being a static batch / head / head-size.
// A caller that preallocates the cache must say which axis it is, since none is dynamic then.
@@ -348,18 +358,33 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {
beam_idx->output(0).set_names({m_beam_idx_name});
}
- // Only a SetRows writing into a model Parameter is a cache write; the rest (e.g. MoE routing
- // writes) are left to the default stateless lowering that runs after this pass. Collect first,
- // then rewrite, so the graph is not mutated while being walked.
- std::vector<std::shared_ptr<SetRows>> cache_writes;
+ // Only a write into a model Parameter is a cache write; the rest (e.g. MoE routing writes) are
+ // left to the default stateless lowering. A converted stateless model carries the same writes
+ // already lowered to ScatterUpdate and marked by LowerSetRowsStateless. Collect first, then
+ // rewrite, so the graph is not mutated while being walked.
+ struct CacheWrite {
+ std::shared_ptr<ov::Node> write;
+ ov::Output<ov::Node> new_rows;
+ std::shared_ptr<v0::Parameter> cache;
+ };
+ std::vector<CacheWrite> cache_writes;
for (const auto& node : model->get_ops()) {
- auto set_rows = ov::as_type_ptr<SetRows>(node);
- if (!set_rows) {
- continue;
+ CacheWrite write{node, {}, nullptr};
+ if (ov::as_type_ptr<SetRows>(node)) {
+ write.new_rows = node->input_value(0);
+ write.cache = ov::as_type_ptr<v0::Parameter>(node->input_value(2).get_node_shared_ptr());
+ } else if (node->get_rt_info().count(kv_cache_write_key())) {
+ const auto scatter = ov::as_type_ptr<v3::ScatterUpdate>(node->get_input_node_shared_ptr(0));
+ const auto flat = scatter ? ov::as_type_ptr<v1::Reshape>(scatter->get_input_node_shared_ptr(0)) : nullptr;
+ write.cache = flat ? ov::as_type_ptr<v0::Parameter>(flat->get_input_node_shared_ptr(0)) : nullptr;
+ OPENVINO_ASSERT(ov::is_type<v1::Reshape>(node) && write.cache,
+ "[GGUF] GGUFMakeStateful: malformed lowered KV cache write '",
+ node->get_friendly_name(),
+ "'");
+ write.new_rows = scatter->input_value(2);
}
- auto dst = ov::as_type_ptr<v0::Parameter>(set_rows->input_value(2).get_node_shared_ptr());
- if (dst && !m_skip_caches.count(dst->get_friendly_name())) {
- cache_writes.push_back(set_rows);
+ if (write.cache && !m_skip_caches.count(write.cache->get_friendly_name())) {
+ cache_writes.push_back(std::move(write));
}
}
// A model can have recurrent states and no KV cache at all (an all-linear-attention stack),
@@ -380,9 +405,8 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {
// Same beam_idx Gather axis for every cache; hoisted out of the loop below.
auto axis0 = v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
- for (const auto& set_rows : cache_writes) {
- auto new_rows = set_rows->input_value(0);
- auto cache_param = ov::as_type_ptr<v0::Parameter>(set_rows->input_value(2).get_node_shared_ptr());
+ for (const auto& [write, rows, cache_param] : cache_writes) {
+ auto new_rows = rows;
const auto& cache_name = cache_param->get_friendly_name();
const auto& ps = cache_param->get_partial_shape();
const auto et = cache_param->get_element_type();
@@ -438,15 +462,20 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {
auto past = std::make_shared<v8::Gather>(read_value, beam_idx, axis0);
auto concat = std::make_shared<v0::Concat>(ov::OutputVector{past, new_rows}, axis);
caches.push_back({read_value, concat.get(), init_shape});
- concat->set_friendly_name(set_rows->get_friendly_name());
- new_sinks.push_back(std::make_shared<v6::Assign>(concat, var));
+ concat->set_friendly_name(write->get_friendly_name());
+ auto assign = std::make_shared<v6::Assign>(concat, var);
+ copy_cache_write_runtime_info(
+ write,
+ cache_param,
+ {beam_idx, init, read_value, split_shape, new_rows.get_node_shared_ptr(), axis0, past, concat, assign});
+ new_sinks.push_back(assign);
// The stateless graph returns each updated cache as a Result; in the stateful form the Assign
// sink above takes that role, so those Results go. Identify them as the Results reading THIS
// write -- not by matching the cache's name, which only happens to work while the builder
// names a cache's write after the cache itself. Collect them before replace_node, while the
- // SetRows is still the node they read.
- for (const auto& consumer : set_rows->output(0).get_target_inputs()) {
+ // write is still the node they read.
+ for (const auto& consumer : write->output(0).get_target_inputs()) {
if (auto r = ov::as_type_ptr<v0::Result>(consumer.get_node()->shared_from_this())) {
results_to_remove.push_back(r);
}
@@ -454,7 +483,7 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {
// Every remaining consumer of the write (attention's read of the cache) now reads the grown
// Concat instead.
- ov::replace_node(set_rows, concat);
+ ov::replace_node(write, concat);
model->add_variables({var});
params_to_remove.push_back(cache_param);
diff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txt
index d3607f260f9..d62f3920c31 100644
--- a/src/frontends/gguf/tests/CMakeLists.txt
+++ b/src/frontends/gguf/tests/CMakeLists.txt
@@ -27,6 +27,7 @@ set(FRONTEND_SRCS
"${FE_SRC_DIR}/helper_ops/gguf_constant.cpp"
"${FE_SRC_DIR}/pass/adapt_to_genai.cpp"
"${FE_SRC_DIR}/pass/adapt_mmproj_to_genai.cpp"
+ "${FE_SRC_DIR}/genai_adaptation.cpp"
"${FE_SRC_DIR}/pass/lower_set_rows_stateless.cpp"
"${FE_SRC_DIR}/pass/isolate_precision_sensitive_outputs.cpp"
"${FE_SRC_DIR}/pass/make_stateful.cpp"
diff --git a/src/frontends/gguf/tests/test_arch_accuracy.cpp b/src/frontends/gguf/tests/test_arch_accuracy.cpp
index de7e7f9bdae..968e6811aac 100644
--- a/src/frontends/gguf/tests/test_arch_accuracy.cpp
+++ b/src/frontends/gguf/tests/test_arch_accuracy.cpp
@@ -922,6 +922,35 @@ TEST(GGUFMultimodalBackboneAdaptation, QwenAndGemmaSupportBatchesAndPagedAttenti
}
}
+TEST(GGUFMultimodalBackboneAdaptation, AdaptToGenAIReturnsDecoderModels) {
+ auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/gemma4-ple.npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ ov::frontend::gguf::FrontEnd frontend;
+ const auto input = frontend.load(temporary.path);
+ using Mode = ov::frontend::gguf::pass::AdaptToGenAI::InputMode;
+ for (const auto mode : {Mode::IDS_TO_LOGITS, Mode::EMBEDS_TO_LOGITS}) {
+ const bool embeds = mode == Mode::EMBEDS_TO_LOGITS;
+ SCOPED_TRACE(embeds);
+ const auto converted = frontend.convert(input);
+ const auto models = ov::frontend::gguf::adapt_to_genai(converted, {mode});
+ std::set<std::string> names;
+ for (const auto& [name, model] : models)
+ names.insert(name);
+ const std::set<std::string> expected =
+ embeds ? std::set<std::string>{"language", "text_embeddings", "text_embeddings_per_layer"}
+ : std::set<std::string>{"language"};
+ EXPECT_EQ(names, expected);
+ const auto& language = models.at("language");
+ EXPECT_EQ(language, converted);
+ EXPECT_FALSE(language->get_variables().empty());
+ EXPECT_NO_THROW(language->input("beam_idx"));
+ EXPECT_NO_THROW(language->input(embeds ? "inputs_embeds" : "input_ids"));
+ OV_EXPECT_THROW(ov::frontend::gguf::adapt_to_genai(language, {mode}),
+ ov::Exception,
+ testing::HasSubstr("already adapted"));
+ }
+}
+
// Gemma3/Gemma4 scale token lookups only, as in llama.cpp, so the scale belongs to the embedding
// model and injected media embeddings reach the decoder unscaled.
TEST(GGUFMultimodalBackboneAdaptation, EmbeddingModelPreservesTokenScaling) {
diff --git a/src/frontends/gguf/tests/test_extensions.cpp b/src/frontends/gguf/tests/test_extensions.cpp
index a8d6875d3df..d04e0ed9a73 100644
--- a/src/frontends/gguf/tests/test_extensions.cpp
+++ b/src/frontends/gguf/tests/test_extensions.cpp
@@ -343,6 +343,41 @@ TEST(GGUFExtensions, GGUFMakeStatefulAddsOnlyBeamIdx) {
EXPECT_EQ(stateful, stateless);
}
+// adapt_to_genai makes an already converted model stateful, so the pass also recognizes the
+// lowered ScatterUpdate write and must produce the same state as the conversion-time extension.
+class GGUFMakeStatefulLoweredCacheTests : public TransformationTestsF {
+protected:
+ void SetUp() override {
+ TransformationTestsF::SetUp();
+ manager.register_pass<pass::GGUFMakeStateful>();
+ comparator.enable(FunctionsComparator::CONST_VALUES);
+ comparator.enable(FunctionsComparator::ATTRIBUTES);
+ }
+};
+
+TEST_F(GGUFMakeStatefulLoweredCacheTests, RewritesLoweredCacheWrite) {
+ model = kv_cache_write_builder().build();
+ model_ref = kv_cache_write_builder().build_with_extensions(
+ {std::make_shared<ov::frontend::DecoderTransformationExtension>(pass::GGUFMakeStateful())});
+
+ const auto cache_result = model->get_results().front();
+ const auto cache_write = cache_result->input_value(0);
+ model->remove_result(cache_result);
+ auto converted_observation = std::make_shared<ov::op::v0::Abs>(cache_write);
+ converted_observation->output(0).set_names({"cache_observation"});
+ auto converted_result = std::make_shared<ov::op::v0::Result>(converted_observation);
+ converted_result->set_friendly_name("cache_observation");
+ model->add_results({converted_result});
+
+ const auto assign = ov::as_type_ptr<ov::op::v6::Assign>(model_ref->get_sinks().front());
+ ASSERT_TRUE(assign);
+ auto reference_observation = std::make_shared<ov::op::v0::Abs>(assign->input_value(0));
+ reference_observation->output(0).set_names({"cache_observation"});
+ auto reference_result = std::make_shared<ov::op::v0::Result>(reference_observation);
+ reference_result->set_friendly_name("cache_observation");
+ model_ref->add_results({reference_result});
+}
+
// A DecoderTransformationExtension can hold any pass, not only the ones the frontend ships: here a
// plain lambda pass, which must run during conversion (it renames the model, observable after).
TEST(GGUFExtensions, ArbitraryTransformationExtensionRuns) {
diff --git a/src/frontends/gguf/tests/test_mmproj.cpp b/src/frontends/gguf/tests/test_mmproj.cpp
index 284de52b252..d3bd017a44c 100644
--- a/src/frontends/gguf/tests/test_mmproj.cpp
+++ b/src/frontends/gguf/tests/test_mmproj.cpp
@@ -20,17 +20,29 @@
#include "model_contract.hpp"
#include "op_test_utils.hpp"
#include "openvino/frontend/gguf/adapt_mmproj_to_genai.hpp"
+#include "openvino/frontend/gguf/adapt_to_genai.hpp"
#include "openvino/frontend/gguf/extension/projector.hpp"
#include "openvino/frontend/gguf/frontend.hpp"
#include "openvino/frontend/gguf/make_stateful.hpp"
#include "openvino/op/add.hpp"
+#include "openvino/op/broadcast.hpp"
+#include "openvino/op/convert.hpp"
#include "openvino/op/gather.hpp"
#include "openvino/op/gelu.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/mvn.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reduce_sum.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/op/tensor_iterator.hpp"
+#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "openvino/openvino.hpp"
#include "openvino/pass/serialize.hpp"
+#include "transformations/rt_info/fused_names_attribute.hpp"
namespace {
class GGUFMMProj : public ::testing::Test {
@@ -440,6 +452,227 @@ TEST_F(GGUFMMProj, ProjectorCallbackCanReplaceThePrimaryGraph) {
EXPECT_FLOAT_EQ(request.get_output_tensor().data<float>()[i], 11.f);
}
+TEST_F(GGUFMMProj, GenAILayoutsPreserveRuntimeInfo) {
+ using ov::op::v0::Constant;
+ using ov::op::v0::Parameter;
+ using ov::op::v0::Result;
+
+ auto pixels = std::make_shared<Parameter>(ov::element::f32, ov::Shape{1, 3, 2, 2});
+ pixels->set_friendly_name("vision.pixel_values");
+ pixels->output(0).set_names({"vision.pixel_values"});
+ auto image_features =
+ std::make_shared<ov::op::v1::Reshape>(pixels, Constant::create(ov::element::i64, {4}, {1, 1, 1, 12}), false);
+ pixels->get_rt_info()[ov::FusedNames::get_type_info_static()] = ov::FusedNames("vision_input");
+ image_features->get_rt_info()[ov::FusedNames::get_type_info_static()] = ov::FusedNames("vision_features");
+ auto image_result = std::make_shared<Result>(image_features);
+ image_result->output(0).set_names({"vision.embeddings"});
+ image_result->get_rt_info()[ov::FusedNames::get_type_info_static()] = ov::FusedNames("vision_result");
+ auto vision = std::make_shared<ov::Model>(ov::ResultVector{image_result}, ov::ParameterVector{pixels});
+ vision->set_rt_info(std::string("custom"), {"gguf_mmproj", "vision.projector"});
+ vision->set_rt_info(std::string("batched_image"), {"gguf_mmproj", "vision.genai_layout"});
+
+ auto adapted_vision = ov::frontend::gguf::adapt_to_genai(vision).at("vision_embeddings");
+ const auto has_fused_name = [](const std::shared_ptr<ov::Node>& node, const std::string& name) {
+ const auto found = node->get_rt_info().find(ov::FusedNames::get_type_info_static());
+ if (found == node->get_rt_info().end())
+ return false;
+ const auto names = found->second.as<ov::FusedNames>().getVectorNames();
+ return std::find(names.begin(), names.end(), name) != names.end();
+ };
+ EXPECT_TRUE(has_fused_name(adapted_vision->get_parameters().front(), "vision_input"));
+ std::shared_ptr<ov::op::v0::TensorIterator> iterator;
+ for (const auto& node : adapted_vision->get_ops()) {
+ if (auto candidate = ov::as_type_ptr<ov::op::v0::TensorIterator>(node))
+ iterator = std::move(candidate);
+ }
+ ASSERT_TRUE(iterator);
+ EXPECT_TRUE(has_fused_name(iterator, "vision_features"));
+ EXPECT_TRUE(has_fused_name(iterator, "vision_result"));
+ EXPECT_TRUE(has_fused_name(adapted_vision->get_results().front(), "vision_result"));
+
+ auto features = std::make_shared<Parameter>(ov::element::f32, ov::Shape{1, 1, 4, 8});
+ features->set_friendly_name("audio.features");
+ features->output(0).set_names({"audio.features"});
+ auto audio_embeddings =
+ std::make_shared<ov::op::v1::Multiply>(features, Constant::create(ov::element::f32, {}, {1.f}));
+ auto audio_result = std::make_shared<Result>(audio_embeddings);
+ audio_result->output(0).set_names({"audio.embeddings"});
+ auto audio = std::make_shared<ov::Model>(ov::ResultVector{audio_result}, ov::ParameterVector{features});
+ audio->set_rt_info(std::string("gemma4a"), {"gguf_mmproj", "audio.projector"});
+ audio->set_rt_info(std::string("gemma4"), {"gguf_mmproj", "audio.genai_layout"});
+ features->get_rt_info()[ov::FusedNames::get_type_info_static()] = ov::FusedNames("audio_input");
+ audio_result->get_rt_info()[ov::FusedNames::get_type_info_static()] = ov::FusedNames("audio_result");
+
+ auto adapted_audio = ov::frontend::gguf::adapt_to_genai(audio).at("audio_embeddings");
+ const auto adapted_features = std::find_if(adapted_audio->get_parameters().begin(),
+ adapted_audio->get_parameters().end(),
+ [](const auto& parameter) {
+ return parameter->get_friendly_name() == "input_features";
+ });
+ ASSERT_NE(adapted_features, adapted_audio->get_parameters().end());
+ EXPECT_TRUE(has_fused_name(*adapted_features, "audio_input"));
+ size_t converts = 0;
+ size_t reductions = 0;
+ size_t slices = 0;
+ size_t transposes = 0;
+ size_t unsqueezes = 0;
+ for (const auto& node : adapted_audio->get_ops()) {
+ if (ov::is_type<ov::op::v0::Convert>(node)) {
+ ++converts;
+ EXPECT_TRUE(has_fused_name(node, "audio_input"));
+ } else if (ov::is_type<ov::op::v1::ReduceSum>(node)) {
+ ++reductions;
+ EXPECT_TRUE(has_fused_name(node, "audio_input"));
+ } else if (ov::is_type<ov::op::v8::Slice>(node)) {
+ ++slices;
+ EXPECT_TRUE(has_fused_name(node, "audio_input"));
+ } else if (ov::is_type<ov::op::v1::Transpose>(node)) {
+ ++transposes;
+ EXPECT_TRUE(has_fused_name(node, "audio_input"));
+ } else if (ov::is_type<ov::op::v0::Unsqueeze>(node)) {
+ ++unsqueezes;
+ EXPECT_TRUE(has_fused_name(node, "audio_input"));
+ }
+ }
+ EXPECT_EQ(converts, 1);
+ EXPECT_EQ(reductions, 1);
+ EXPECT_EQ(slices, 1);
+ EXPECT_EQ(transposes, 1);
+ EXPECT_EQ(unsqueezes, 1);
+
+ size_t shape_ofs = 0;
+ size_t gathers = 0;
+ size_t broadcasts = 0;
+ for (const auto& node : adapted_audio->get_ops()) {
+ if (ov::is_type<ov::op::v3::ShapeOf>(node)) {
+ ++shape_ofs;
+ EXPECT_TRUE(has_fused_name(node, "audio_result"));
+ } else if (ov::is_type<ov::op::v8::Gather>(node)) {
+ ++gathers;
+ EXPECT_TRUE(has_fused_name(node, "audio_result"));
+ } else if (ov::is_type<ov::op::v3::Broadcast>(node)) {
+ ++broadcasts;
+ EXPECT_TRUE(has_fused_name(node, "audio_result"));
+ }
+ }
+ EXPECT_EQ(shape_ofs, 1);
+ EXPECT_EQ(gathers, 1);
+ EXPECT_EQ(broadcasts, 1);
+ ASSERT_EQ(adapted_audio->get_results().size(), 2u);
+ EXPECT_TRUE(has_fused_name(adapted_audio->get_results().back(), "audio_result"));
+}
+
+TEST_F(GGUFMMProj, AudioLayoutUsesExplicitBuilderContractForAliases) {
+ using namespace ov::frontend::gguf;
+ writer.kv_bool("clip.has_audio_encoder", true);
+ writer.kv_str("clip.audio.projector_type", "gemma4a-alias");
+ ASSERT_TRUE(writer.write(path));
+
+ FrontEnd frontend;
+ auto extension = std::make_shared<ProjectorExtension>(
+ ProjectorDefinition{"clip.audio.gemma4a-alias",
+ "clip",
+ "audio",
+ "gemma4a-alias",
+ [](GgufGraphContext& graph) {
+ ProjectorResult result;
+ result.output = graph.add_input("audio.features", ov::element::f32, {1, 1, 4, 8});
+ result.audio_layout = AudioLayout::Gemma4;
+ return result;
+ },
+ {}});
+ frontend.add_extension(extension);
+ auto converted = frontend.convert(frontend.load(path));
+ EXPECT_EQ(converted->get_rt_info<std::string>({"gguf_mmproj", "audio.genai_layout"}), "gemma4");
+
+ auto adapted = adapt_to_genai(converted).at("audio_embeddings");
+ EXPECT_NO_THROW(adapted->input("input_features"));
+ EXPECT_NO_THROW(adapted->input("input_features_mask"));
+ ASSERT_EQ(adapted->get_results().size(), 2u);
+ EXPECT_EQ(adapted->output(1).get_any_name(), "attention_mask");
+}
+
+TEST_F(GGUFMMProj, AudioReplacementDoesNotInheritGemmaLayoutFromProjectorName) {
+ using namespace ov::frontend::gguf;
+ writer.kv_bool("clip.has_audio_encoder", true);
+ writer.kv_str("clip.audio.projector_type", "gemma4a");
+ ASSERT_TRUE(writer.write(path));
+
+ FrontEnd frontend;
+ auto extension = std::make_shared<ProjectorExtension>(
+ ProjectorDefinition{
+ "clip.audio.gemma4a",
+ "clip",
+ "audio",
+ "gemma4a",
+ [](GgufGraphContext& graph) {
+ return ProjectorResult{graph.add_input("replacement_features", ov::element::f32, {1, 1, 4, 8}), {}};
+ },
+ {}},
+ RegistrationMode::Replace);
+ frontend.add_extension(extension);
+ auto converted = frontend.convert(frontend.load(path));
+ EXPECT_EQ(converted->get_rt_info<std::string>({"gguf_mmproj", "audio.genai_layout"}), "unsupported");
+
+ auto adapted = adapt_to_genai(converted).at("audio_embeddings");
+ EXPECT_NO_THROW(adapted->input("replacement_features"));
+ EXPECT_THROW(adapted->input("input_features"), ov::Exception);
+ ASSERT_EQ(adapted->get_results().size(), 1u);
+}
+
+TEST_F(GGUFMMProj, AdaptToGenAIRespectsAudioAdapterModels) {
+ using namespace ov::frontend::gguf;
+ writer.kv_bool("clip.has_audio_encoder", true);
+ writer.kv_str("clip.audio.projector_type", "custom-audio");
+ ASSERT_TRUE(writer.write(path));
+
+ for (const bool named_models : {false, true}) {
+ SCOPED_TRACE(named_models);
+ FrontEnd frontend;
+ auto extension = std::make_shared<ProjectorExtension>(ProjectorDefinition{
+ "clip.audio.custom-audio",
+ "clip",
+ "audio",
+ "custom-audio",
+ [](GgufGraphContext& graph) {
+ auto input = graph.add_input("audio.custom", ov::element::f32, {1, 1, 2, 3});
+ return ProjectorResult{graph.node("GGML_OP_SCALE", {input}, 0, {{"scale", 2.f}, {"bias", 0.f}}), {}};
+ },
+ {},
+ {},
+ [named_models](const std::shared_ptr<ov::Model>&) {
+ auto make_model = [](const std::string& input_name, const std::string& output_name) {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 3});
+ input->set_friendly_name(input_name);
+ input->output(0).set_names({input_name});
+ auto output = std::make_shared<ov::op::v1::Multiply>(
+ input,
+ ov::op::v0::Constant::create(ov::element::f32, {}, {2.f}));
+ output->output(0).set_names({output_name});
+ return std::make_shared<ov::Model>(ov::OutputVector{output}, ov::ParameterVector{input});
+ };
+ auto primary = make_model("custom_audio_values", "custom_audio_features");
+ ModelMap models;
+ if (named_models)
+ models = {{"custom_audio", primary},
+ {"audio_auxiliary", make_model("auxiliary_values", "auxiliary_features")}};
+ return ModelAdapterResult{primary, std::move(models)};
+ }});
+ frontend.add_extension(extension);
+ auto converted = frontend.convert(frontend.load(path));
+ auto models = adapt_to_genai(converted);
+ if (named_models) {
+ ASSERT_EQ(models.size(), 2u);
+ EXPECT_EQ(models.at("custom_audio")->input().get_any_name(), "custom_audio_values");
+ EXPECT_EQ(models.at("audio_auxiliary")->output().get_any_name(), "auxiliary_features");
+ EXPECT_FALSE(models.count("audio_embeddings"));
+ } else {
+ ASSERT_EQ(models.size(), 1u);
+ EXPECT_EQ(models.at("audio_embeddings")->input().get_any_name(), "custom_audio_values");
+ }
+ }
+}
+
TEST_F(GGUFMMProj, EmbeddingsCallbacksOverrideBothModalitiesWithOptionalModelMaps) {
using namespace ov::frontend::gguf;
using Adapter = pass::AdaptMmprojToGenAI;
@@ -1617,6 +1850,71 @@ INSTANTIATE_TEST_SUITE_P(Reference,
"lfm2",
"lfm2_no_norm"));
+// adapt_to_genai owns the GenAI input layouts: CLIP-style encoders accept an image batch and Gemma4
+// audio accepts [1, frames, width] features with a prefix mask.
+class GGUFMMProjGenAIModels : public GGUFMMProjGenAIVisionLayout {};
+
+TEST_P(GGUFMMProjGenAIModels, MatchReference) {
+ const std::string family = GetParam();
+ const bool audio = family.find("gemma4") == 0;
+ const auto models = ov::frontend::gguf::adapt_to_genai(model);
+ ASSERT_EQ(models.size(), 1u);
+ const auto& adapted = models.at(audio ? "audio_embeddings" : "vision_embeddings");
+ const auto check = [&](const ov::Tensor& actual, const std::string& key, size_t batch) {
+ const auto& expected = array(key);
+ ASSERT_EQ(actual.get_shape(), (ov::Shape{batch, expected.shape[2], expected.shape[3]}));
+ const size_t size = expected.num_vals;
+ for (size_t b = 0; b < batch; ++b)
+ ov_gguf_test::expect_nmse_below(
+ ov_gguf_test::nmse(actual.data<const float>() + b * size, expected.data<float>(), size),
+ dynamic_accuracy_limit(GetParam()));
+ };
+ if (!audio) {
+ const auto image = tensor("inputs", ov::element::f32);
+ auto shape = image.get_shape();
+ shape[0] = 2;
+ ov::Tensor batch(ov::element::f32, shape);
+ for (size_t b = 0; b < 2; ++b)
+ std::memcpy(batch.data<float>() + b * image.get_size(), image.data<const float>(), image.get_byte_size());
+ check(infer(adapted, {{"pixel_values", batch}}).front(), "embeddings", 2);
+ return;
+ }
+ const bool unified = family == "gemma4ua";
+ for (const std::string step : {"0.", "1."}) {
+ SCOPED_TRACE(step);
+ const auto source = tensor(step + (unified ? "waveform_frames" : "features"), ov::element::f32);
+ const size_t rows = source.get_shape()[2], columns = source.get_shape()[3];
+ std::map<std::string, ov::Tensor> inputs;
+ if (unified) {
+ inputs["input_features"] = ov::Tensor(ov::element::f32, {1, rows, columns}, source.data());
+ } else {
+ // Two padded frames past the mask must not reach the encoder.
+ const size_t frames = columns + 2;
+ ov::Tensor features(ov::element::f32, {1, frames, rows});
+ ov::Tensor mask(ov::element::boolean, {1, frames});
+ std::fill_n(features.data<float>(), features.get_size(), 1e3f);
+ for (size_t t = 0; t < frames; ++t) {
+ mask.data<bool>()[t] = t < columns;
+ for (size_t m = 0; t < columns && m < rows; ++m)
+ features.data<float>()[t * rows + m] = source.data<const float>()[m * columns + t];
+ }
+ inputs = {{"input_features", features}, {"input_features_mask", mask}};
+ }
+ const auto outputs = infer(adapted, inputs);
+ ASSERT_EQ(outputs.size(), unified ? 1u : 2u);
+ check(outputs.front(), step + "embeddings", 1);
+ if (!unified) {
+ EXPECT_EQ(outputs[1].get_shape(), (ov::Shape{1, array(step + "embeddings").shape[2]}));
+ const auto* valid = outputs[1].data<const bool>();
+ EXPECT_TRUE(std::all_of(valid, valid + outputs[1].get_size(), [](bool value) {
+ return value;
+ }));
+ }
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(Reference, GGUFMMProjGenAIModels, ::testing::Values("mlp", "internvl", "gemma4a", "gemma4ua"));
+
std::pair<std::shared_ptr<ov::Model>, ov::frontend::gguf::ModelContract> component_contract_model() {
const auto parameter = [](const std::string& name, const ov::Shape& shape) {
auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);