Skip to content

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

[GGUF] Expose mmproj vision encoders in the optimum-intel layout for GenAI (#38675)

Maxim Vafin40ba3eb630d9
diff --git a/.claude/skills/ov-gguf/SKILL.md b/.claude/skills/ov-gguf/SKILL.md
index 0f5529d8c62..7ac5cbcc83e 100644
--- a/.claude/skills/ov-gguf/SKILL.md
+++ b/.claude/skills/ov-gguf/SKILL.md
@@ -9,7 +9,8 @@ description: >
ProjectorExtension; when conversion fails with "Translation for operation type GGML_OP_* is not
implemented" or an op translator/op_case in src/op/ needs work; when making a converted model
stateful or GenAI/PagedAttention-ready; or when a GGUF model converts but gives garbage, drifting
- tokens, a llama.cpp mismatch or a decode-only shape failure. Not for general llama.cpp usage or
+ tokens, a llama.cpp mismatch or a decode-only shape failure; or when running or resuming GGUF
+ frontend, backend and GenAI validation batches. Not for general llama.cpp usage or
unrelated build/CI failures.
---
@@ -25,8 +26,10 @@ converters; builders and validation differ. Registration or conversion alone nev
| Add or replace an mmproj branch | [extensions.md](../../../src/frontends/gguf/docs/extensions.md#extend-mmproj-with-a-projector-component), then the graph contracts in [mmproj.md](../../../src/frontends/gguf/docs/mmproj.md) |
| Missing ggml operation or `op_case` | [how_to_add_op.md](../../../src/frontends/gguf/docs/how_to_add_op.md) |
| Wrong numbers | [debugging_accuracy.md](../../../src/frontends/gguf/docs/debugging_accuracy.md) |
+| GenAI/mmproj token, media or PA mismatch | [multimodal integration bisection](../../../src/frontends/gguf/docs/debugging_accuracy.md#multimodal-integration-bisection) |
| Unsupported weight type | [quantization.md](../../../src/frontends/gguf/docs/quantization.md); the fix belongs in `src/quant/`, not a builder |
| Build, run tests, regenerate fixtures | [testing.md](../../../src/frontends/gguf/docs/testing.md) |
+| Run or resume GGUF validation across OpenVINO, GenAI and llama.cpp | [validation.md](references/validation.md); use existing GHA workflows and focused local tests, preserving revisions, coverage and failures |
## Easy to miss
@@ -38,7 +41,10 @@ converters; builders and validation differ. Registration or conversion alone nev
- **Test build.** New translator or builder sources go into the explicit `FRONTEND_SRCS` list in
`tests/CMakeLists.txt`, or the test binary fails to link. Run `ov_gguf_frontend_tests` unfiltered
before finishing: the op-coverage gate runs in teardown, so check the exit status.
- `GGUFArchConversion` skips silently without generated headers (`tests/gen_arch_fixtures.py --fetch`).
+ `GGUFArchConversion` skips without generated headers unless `OV_GGUF_REQUIRE_ARCH_FIXTURES=1`
+ requires them; generate them with [gen_arch_fixtures.py](../../../src/frontends/gguf/tests/gen_arch_fixtures.py) `--fetch`.
+ Check actual selected counts and skips; registration, conversion, decoder numerics and
+ GenAI media/API integration establish different levels of support.
- **References.** Layout-sensitive expectations come from real ggml CPU via a committed oracle under
`tests/`, with several heads/tokens and unequal Q/KV dimensions; NumPy or single-head tests can
share the bug. Do not tighten `expect_near` tolerances from an x86-only run.
@@ -47,7 +53,17 @@ converters; builders and validation differ. Registration or conversion alone nev
Set `OV_GGUF_Q4_K_ZP_F16=1` before the process starts. Report quantized-CPU and represented-F32
comparisons separately and keep failed results. `GGML_OPENVINO_*` variables configure only the
llama.cpp backend.
+ Inspect tensor-type inventory rather than checkpoint names. Identical quantized weights do
+ not rule out CPU arithmetic differences; exact expansions isolate them but do not waive the
+ original parity gate. Shared exported-model layout does not imply identical media geometry.
- **Shared changes.** Translator, VIEW/`op_case` or shared block changes rerun
`GGUFArchitectureAccuracy`, `GGUFArchConversion` and the mmproj suites, not just the target model.
- **Long runs.** Redirect output to a file, keep the launched PID and stop only that process. Large Q2
MoE checkpoints expand at CPU compilation; check memory before starting one.
+- **Ineffective rebuilds.** Verify graph attributes, plugin/executor parameters and the linked,
+ loaded CPU variants before repeating a sweep. Use [build and runtime identity](references/build-runtime.md)
+ for overlays or multiple worktrees; version strings and `ldd` alone do not prove execution identity.
+- **Validation batches.** Extend shared-path regression checks to tokenizer, mask and PA changes
+ with representative SDPA/PA/media/chat cases. The [validation guide](references/validation.md)
+ separates numerical parity, model quality and Optimum compatibility; a known arithmetic
+ difference remains a failed parity check unless the user changes the acceptance contract.
diff --git a/.claude/skills/ov-gguf/references/build-runtime.md b/.claude/skills/ov-gguf/references/build-runtime.md
new file mode 100644
index 00000000000..b47ac53d6bf
--- /dev/null
+++ b/.claude/skills/ov-gguf/references/build-runtime.md
@@ -0,0 +1,51 @@
+# Build and runtime identity
+
+Use this when a validation run depends on multiple worktrees, an incremental rebuild,
+an overlay install, or a dispatched plugin kernel. A source revision and version string
+alone do not identify the executed implementation.
+
+## Before diagnosing numerical output
+
+Record the intended source worktree, base build, compiler/configuration, build wrapper,
+and output directory. Prefer normal CMake/Ninja targets in an isolated build. If an
+overlay is necessary, check the actual compile and link commands:
+
+- Rebuild every translation unit affected by changed headers and macros. Include
+ generated or cross-compiled instances of a source, such as ANY, AVX2 and AVX512 CPU
+ executors; compiling only the ordinary source object may leave every dispatched
+ implementation stale. Derive the set from `compile_commands.json` and target commands.
+- Verify replacement objects occur in the final link, output is written into the
+ overlay, and symlinks resolve inside it. Writing through a symlink can replace a base
+ library. Inspect exact symlink targets before removing an overlay link.
+- If upstream was merged, account for added translation units and changed dependency
+ headers in the overlay. State which unchanged base objects are reused. Do not call an
+ overlay a full clean build or treat an old embedded version string as the new commit.
+
+After an actual inference, record resolved module paths and loaded core/frontend/plugin
+libraries. On Linux, `/proc/self/maps` from that process shows plugins loaded lazily;
+`ldd` on the executable alone does not. Hash the actual files and put those paths in the
+validation record, along with the build wrapper and explicit untracked source dependencies.
+Separate the OpenVINO runtime from the independent reference runtime.
+
+## When a pass or plugin fix seems ineffective
+
+Check the chain in order: the converted graph contains the intended attribute; the
+compiled plugin receives it; the selected executor receives it; the changed kernel
+variant is linked and loaded. Do this before a repeated full accuracy matrix.
+
+For SDPA-to-PA changes, inspect each layer's window, token-type inputs and runtime flags,
+including global layers. Test the flag's default and enabled behavior and its executor
+cache key. A flag reaching the plugin does not prove the new executor is running.
+
+## Freeze, integrate, report
+
+Keep sources, build inputs and binaries stable for each delegated batch. Fetching remote
+refs is read-only with respect to tracked files, but merges, commits and rebuilds alter
+the tested inputs: wait for validation to finish. Integrate required upstream changes
+before final validation where practical. If another merge before push changes tested
+dependencies, rebuild and run the checks justified by those changes.
+
+Use one short artifact inventory for a long task: branch heads, wrapper paths, resolved
+binary hashes, active process/session, manifests, outputs, failures and next reproducer.
+After compaction, resume from that inventory and the current summary rather than
+rebuilding or rerunning completed work. Keep separate attempts and fixture provenance.
diff --git a/.claude/skills/ov-gguf/references/validation.md b/.claude/skills/ov-gguf/references/validation.md
new file mode 100644
index 00000000000..36aff3da3e9
--- /dev/null
+++ b/.claude/skills/ov-gguf/references/validation.md
@@ -0,0 +1,137 @@
+# GGUF validation batches
+
+Use this for repeated model/configuration checks across the GGUF frontend,
+llama.cpp OpenVINO backend and GenAI. Use [testing.md](../../../../src/frontends/gguf/docs/testing.md)
+for build targets, fixture generation and individual tests. Registration or
+conversion alone does not establish accuracy or end-to-end integration.
+
+## Define the matrix and reference
+
+Record repository revisions, model/projector paths and revisions, tensor-type
+inventory, fixtures/media, prompts, generation settings, seeds, toolchain and
+runtime settings. Record hashes of the exact model, projector, media, reference
+and build wrapper files used. Verify the libraries actually loaded after
+inference; read [build and runtime identity](build-runtime.md) for overlays,
+incremental builds, multiple worktrees or dispatched CPU kernels.
+
+Specify selected scenarios, expected test counts and allowed skips, numerical
+metrics/tolerances, per-case timeouts and artifact paths. Distinguish conversion,
+decoder numerics, text quality, vision/audio, PA/SDPA and Optimum compatibility.
+Passing one scenario does not establish support for the others. Keep exclusions
+and missing coverage explicit. A quantized reference checks backend parity, not
+fidelity against an unquantized FP32/FP16/BF16 checkpoint.
+
+Pin the actual llama.cpp/ggml CPU source and build and verify OpenVINO is disabled
+in that reference. Specify inference and KV cache precision independently,
+attention backend, dynamic activation quantization, threads, sampling, chat
+template and special-token policy. Compare prompt token IDs before blaming the
+encoder or decoder. Check matching explicit caches and the product default
+separately; user properties must override a model-specific default.
+
+Inspect tensor types rather than checkpoint names: Q4_0 files can also contain
+Q4_1, Q8_0 or K-quants. When the user accepts Q4_K_M loss pending a plugin fix,
+use Q4_0 fixtures for the requested gate and retain K-quant diagnostics. Do not
+assume every Q4_0 output matches or relax other parity gates.
+
+Use the pinned quantizer to create or exactly expand fixtures when needed,
+preserving hashes, conversion revision/options and tensor inventory.
+Requantization creates a different fixture. An F16 expansion of quantized weights
+isolates arithmetic; it is not the original unquantized checkpoint and does not
+waive the failing comparison. Exercise a new quantizer through its actual CMake
+target as well as checking its output.
+
+Keep the chosen reference and criteria. Never silently change precision,
+thresholds, expected failures or coverage to obtain a pass. For performance,
+preserve hardware, load, warmup and repetition settings; noisy measurements do
+not establish a regression or improvement.
+
+## Multimodal and API coverage
+
+Choose a small discriminating matrix: synthetic square and real JPEG inputs,
+single/multi media, relevant video/audio, SDPA/PA, cached and modern chat, reset,
+cancellation and beam search where supported. Include encoder geometry and
+limits from GGUF metadata. Square smoke inputs miss resize/token-limit and
+sliding-window bugs. Combining marks, raw byte-token spellings and repeated
+newlines expose tokenizer differences hidden by ASCII-only prompts.
+
+Compare exact video frame sampling, timestamps, boundary tokens and assembled
+positions. If a pinned mtmd revision needs an adapted oracle, describe that
+adaptation and preserve its CPU frame encoder and decoder. That validates the
+assembly contract; it does not exercise an upstream video API. Test Optimum
+directory and serialized-map loading and existing processor defaults separately
+from llama parity. Shared layout does not imply identical media geometry.
+
+State replay semantics: teacher-forced greedy choices on one engine's generated
+history measure local decisions, not identical free-running sequences. Tiny or
+random fixtures can produce nonsense text while numerically agreeing. Keep
+parity, model quality and fidelity to unquantized weights as separate claims.
+
+GenAI-adapted Gemma4 image groups intentionally follow Optimum-intel's window behavior; see the
+[accepted parity gap](../../../../src/frontends/gguf/docs/mmproj.md#gemma4-image-window-parity-gap).
+Keep affected llama.cpp comparisons as diagnostics with their original gates; report
+SDPA/PA agreement and API compatibility separately. Do not attribute the semantic
+mismatch to quantization or turn it into a numerical-parity pass.
+Exercise repeated media requests with prefix caching enabled and disabled; an isolated
+prefill pass cannot establish cache-reuse correctness. Keep default-cache failures
+separate from the [image prefix-cache gap](../../../../src/frontends/gguf/docs/mmproj.md#bidirectional-image-prefix-cache-gap)
+diagnostics.
+
+For failures, follow [multimodal integration bisection](../../../../src/frontends/gguf/docs/debugging_accuracy.md#multimodal-integration-bisection):
+template/token IDs, encoder tensors, insertion/positions, masks/windows, cache
+precision, then logits on identical histories. Identical quantized weights do
+not rule out CPU activation arithmetic differences.
+
+## Execute with existing workflows
+
+Iterate on a focused local reproducer, then use the repository's GHA workflows for
+broader validation. The [frontend GTest](../../../../.github/workflows/job_cxx_unit_tests.yml),
+[model-hub](../../../../.github/workflows/job_gguf_models_tests.yml) and
+[llama.cpp backend](../../../../.github/workflows/job_gguf_llamacpp_validation.yml) jobs
+run in OpenVINO's Ubuntu workflows. [Ubuntu 22](../../../../.github/workflows/ubuntu_22.yml)
+also runs the [GenAI acceptance job](../../../../.github/workflows/job_gguf_genai_validation.yml)
+against its own OpenVINO artifacts and a pinned GenAI SHA.
+Check the workflow's actual jobs and filters before claiming coverage. A green job with a
+skipped GGUF component or no collected tests provides no GGUF evidence.
+
+Use `gh workflow run <workflow> --ref <branch>` with supported revision inputs,
+then `gh run watch <run-id> --exit-status`. Record the workflow revision, tested
+commit (including PR merge commits), companion repository SHAs and reference pin.
+Verify artifact provenance when a workflow consumes another repository's build;
+`latest_available_commit` does not identify the requested frontend revision.
+Inspect GTest XML, pytest counts/skips and acceptance reports downloaded with
+`gh run download <run-id> --dir <artifact-directory>`. Required coverage and
+numerical gates belong in the tests, rather than a second report runner.
+
+For local checks, invoke the GTest binary or pytest/acceptance script directly,
+with explicit filters and report paths. Keep commands, logs and reports outside
+the checkout, for example `~/.cache/ov-validation/<task>/`. Record resolved binary
+and library hashes, configuration and untracked source dependencies when using
+an overlay. A successful local run does not prove GHA packaging or job selection.
+
+Retain failed attempts. Use `gh run rerun <run-id> --failed` for a deliberate retry
+of transient failures; fixes require a new run at the new revision. Changed inputs
+invalidate reuse. Expand or repeat only for changed inputs, a new failure or
+missing required coverage. Stop on a user pause and retain the run IDs and logs.
+
+## Delegate and report
+
+When delegation is available and authorized, use one worker for long batches
+with the user's configured model preference. Supply a fresh compact
+brief with the [ov-gguf entrypoint](../SKILL.md), this guide, the workflow/run ID
+or exact local command, stable source/build paths, acceptance contract and artifact paths. Run directly
+if delegation is unavailable. The worker executes and reports evidence; the main
+agent owns diagnosis, fixes and acceptance. Missing prerequisites or unexpected
+results return to the main agent without expanding setup or changing criteria.
+
+Freeze sources and binaries for the batch, using an isolated worktree/build when
+needed. Wait for execution and the provenance check to finish before committing,
+merging or rebuilding those inputs. Report useful checkpoints from the workflow
+artifacts without per-test polling.
+
+Return tested revisions and runtime identity, completed/remaining cases, exact
+selected counts/skips, failures with excerpts, reproduction commands and artifact
+paths. Distinguish selected skips from filtered or unregistered suites and disclose
+standalone fixture adapters. Group equivalent errors without asserting a common
+cause. Preserve original failures and numerical differences for diagnosis; known
+arithmetic differences remain failed parity checks unless the user changes the
+acceptance contract.
diff --git a/.github/workflows/job_cxx_unit_tests.yml b/.github/workflows/job_cxx_unit_tests.yml
index 4c3e9283bdc..41bd56d87b3 100644
--- a/.github/workflows/job_cxx_unit_tests.yml
+++ b/.github/workflows/job_cxx_unit_tests.yml
@@ -130,6 +130,8 @@ jobs:
- name: GGUF frontend tests
if: fromJSON(inputs.affected-components).GGUF_FE.test
+ env:
+ OV_GGUF_REQUIRE_ARCH_FIXTURES: ${{ (inputs.os == 'ubuntu_22_04' || inputs.os == 'ubuntu_24_04') && runner.arch == 'X64' && '1' || '' }}
run: |
${{ env.SOURCE_COMMAND }} ${{ env.SETUPVARS }}
${{ env.INSTALL_TEST_DIR }}/ov_gguf_frontend_tests --gtest_print_time=1 --gtest_output=xml:${{ env.INSTALL_TEST_DIR }}/TEST-GGUFFrontend.xml
diff --git a/.github/workflows/job_gguf_genai_validation.yml b/.github/workflows/job_gguf_genai_validation.yml
new file mode 100644
index 00000000000..7a52c6e4b09
--- /dev/null
+++ b/.github/workflows/job_gguf_genai_validation.yml
@@ -0,0 +1,223 @@
+name: GGUF Frontend x GenAI acceptance
+
+on:
+ workflow_call:
+ inputs:
+ runner:
+ type: string
+ required: true
+ image:
+ type: string
+ required: true
+ run-real-models:
+ description: 'Include real-checkpoint Q4_0 accuracy tests in addition to tiny models'
+ type: boolean
+ default: false
+ genai-ref:
+ description: 'Reviewed companion GenAI commit; never use a moving branch'
+ type: string
+ required: true
+
+permissions: read-all
+
+env:
+ INSTALL_DIR: ${{ github.workspace }}/install
+ GENAI_DIR: ${{ github.workspace }}/genai
+ BUILD_DIR: ${{ github.workspace }}/genai-build
+ HF_HOME: /mount/caches/huggingface/gguf-genai
+ HF_TOKEN_PATH: /secrets/huggingface/token-secondary
+ OMP_NUM_THREADS: 4
+ OPENBLAS_NUM_THREADS: 4
+ PIP_CONSTRAINT: ${{ github.workspace }}/.github/workflows/requirements/gguf_genai.txt
+
+jobs:
+ acceptance:
+ name: GGUF GenAI acceptance
+ timeout-minutes: 120
+ runs-on: ${{ inputs.runner }}
+ container:
+ image: ${{ inputs.image }}
+ volumes:
+ - /mount:/mount
+ - /home/runner/secrets/:/secrets:ro
+ - ${{ github.workspace }}:${{ github.workspace }}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout workflow actions
+ uses: ababushk/checkout@dd591a6a2ac25618db4eda86e7e0d938f88cf01b # cherry_pick_retries
+ with:
+ sparse-checkout: |
+ .github/actions
+ .github/workflows/requirements
+ submodules: 'false'
+
+ - name: Checkout pinned GenAI
+ uses: ababushk/checkout@dd591a6a2ac25618db4eda86e7e0d938f88cf01b # cherry_pick_retries
+ with:
+ repository: mvafin/openvino.genai
+ ref: ${{ inputs.genai-ref }}
+ path: genai
+ submodules: recursive
+
+ - name: Download same-run OpenVINO package
+ uses: akashchi/download-artifact@d59a9c15fec3fdb7c9adf09464124d00f9c11415 # main
+ with:
+ name: openvino_package
+ path: ${{ env.INSTALL_DIR }}
+
+ - name: Download same-run OpenVINO developer package
+ uses: akashchi/download-artifact@d59a9c15fec3fdb7c9adf09464124d00f9c11415 # main
+ with:
+ name: openvino_developer_package
+ path: ${{ env.INSTALL_DIR }}
+
+ - name: Download same-run OpenVINO wheels
+ uses: akashchi/download-artifact@d59a9c15fec3fdb7c9adf09464124d00f9c11415 # main
+ with:
+ name: openvino_wheels
+ path: ${{ env.INSTALL_DIR }}/wheels
+
+ - name: Extract packages
+ run: |
+ pigz -dc "${INSTALL_DIR}/openvino_package.tar.gz" | tar -xf - -C "${INSTALL_DIR}"
+ mkdir -p "${INSTALL_DIR}/developer_package"
+ pigz -dc "${INSTALL_DIR}/developer_package.tar.gz" | tar -xf - -C "${INSTALL_DIR}/developer_package"
+
+ - name: Setup Python 3.11
+ uses: ./.github/actions/setup_python
+ with:
+ version: '3.11'
+ set-pip-install-path: 'false'
+ self-hosted-runner: 'true'
+ use-pip-proxy: 'true'
+
+ - name: Install same-run OpenVINO wheel
+ uses: ./.github/actions/install_ov_wheels
+ with:
+ wheels-dir-path: ${{ env.INSTALL_DIR }}/wheels
+ wheels-to-install: openvino
+
+ - name: Install acceptance dependencies
+ run: |
+ mkdir -p reports
+ python3 -m pip freeze > reports/dependencies-before.txt
+ apt-get update
+ apt-get install -y ffmpeg
+ python3 -m pip install torch==2.11.0 torchvision==0.26.0 --index-url https://download.pytorch.org/whl/cpu
+ python3 -m pip install -r "${PIP_CONSTRAINT}"
+ python3 -m pip install pillow==12.3.0
+ python3 -m pip wheel --no-build-isolation --no-deps --wheel-dir "${INSTALL_DIR}/wheels" "${GENAI_DIR}/thirdparty/openvino_tokenizers"
+ python3 -m pip install --no-deps "${INSTALL_DIR}"/wheels/openvino_tokenizers-*.whl
+ python3 - <<'PY' > "${INSTALL_DIR}/runtime-constraints.txt"
+ import importlib.metadata as m
+ import os
+ from pathlib import Path
+ print(Path(os.environ['PIP_CONSTRAINT']).read_text(), end='')
+ for package in ('openvino', 'openvino-tokenizers', 'pillow'):
+ print(package + '==' + m.version(package))
+ PY
+ python3 -m pip install -c "${INSTALL_DIR}/runtime-constraints.txt" 'optimum-intel @ git+https://github.com/huggingface/optimum-intel.git@dd4ed1a86f9c2abf34d8dce777da5b592765b644'
+ echo "PIP_CONSTRAINT=${INSTALL_DIR}/runtime-constraints.txt" >> "$GITHUB_ENV"
+
+ - name: Build pinned GenAI against same-run OpenVINO
+ id: build_genai
+ run: |
+ source "${INSTALL_DIR}/setupvars.sh"
+ cmake -S "${GENAI_DIR}" -B "${BUILD_DIR}" \
+ -DOpenVINODeveloperPackage_DIR="${INSTALL_DIR}/developer_package/cmake" \
+ -DENABLE_PYTHON=ON -DENABLE_TESTS=OFF -DENABLE_SAMPLES=OFF -DENABLE_TOOLS=OFF \
+ -DBUILD_TOKENIZERS=OFF -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_C_COMPILER_LAUNCHER= -DCMAKE_CXX_COMPILER_LAUNCHER=
+ cmake --build "${BUILD_DIR}" --target py_openvino_genai --parallel 4
+ python3 - <<'PY'
+ import os, shutil
+ from pathlib import Path
+ from openvino_tokenizers import _ext_path
+ shutil.copy2(_ext_path, Path(os.environ['BUILD_DIR']) / 'openvino_genai/libopenvino_tokenizers.so')
+ PY
+ echo "PYTHONPATH=${BUILD_DIR}" >> "$GITHUB_ENV"
+ echo "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${BUILD_DIR}/openvino_genai" >> "$GITHUB_ENV"
+ echo "GGUF_LLAMA_BUILD_DIR=${GITHUB_WORKSPACE}/llama-reference" >> "$GITHUB_ENV"
+ echo "GGUF_MMPROJ_REPORT_DIR=${GITHUB_WORKSPACE}/reports" >> "$GITHUB_ENV"
+ echo "GGUF_RUNTIME_MANIFEST=${GITHUB_WORKSPACE}/reports/runtime.json" >> "$GITHUB_ENV"
+
+ - name: Record tested revisions and artifacts
+ env:
+ GENAI_REF: ${{ inputs.genai-ref }}
+ OPENVINO_REF: ${{ github.sha }}
+ run: |
+ mkdir -p reports
+ python3 - <<'PY'
+ import hashlib, json, os, subprocess
+ from pathlib import Path
+ head = subprocess.check_output(['git', '-C', os.environ['GENAI_DIR'], 'rev-parse', 'HEAD'], text=True).strip()
+ assert head == os.environ['GENAI_REF'], (head, os.environ['GENAI_REF'])
+ install = Path(os.environ['INSTALL_DIR'])
+ archives = list(install.glob('*.tar.gz')) + list((install / 'wheels').glob('*.whl'))
+ data = {'openvino_revision': os.environ['OPENVINO_REF'], 'genai_revision': head,
+ 'workflow_run': os.environ['GITHUB_RUN_ID'],
+ 'llama_reference_revision': '03fa73cb27f5c251b9528489b18d303b1366aca4',
+ 'artifacts': {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in archives}}
+ Path('reports/runtime.json').write_text(json.dumps(data, indent=2))
+ PY
+ python3 -m pip freeze > reports/dependencies.txt
+
+ - name: Acceptance coverage and accuracy guard tests
+ run: python3 -m pytest --noconftest -v "${GENAI_DIR}/tests/python_tests/test_gguf_mmproj_validation.py" --junitxml=reports/validation.xml
+
+ - name: Generated tiny decoders, MoE and recurrent models (SDPA, PA, AUTO and continuous batching)
+ if: ${{ !cancelled() && steps.build_genai.outcome == 'success' }}
+ run: |
+ python3 -m pip install transformers==5.2.0
+ python3 -m pytest --noconftest -v "${GENAI_DIR}/tests/python_tests/test_gguf_generated.py" --junitxml=reports/generated.xml
+
+ - name: Tiny GGUF tokenizer, string and encoded inputs, beam search, streaming and saved IR (SDPA, PA and AUTO)
+ if: ${{ !cancelled() && steps.build_genai.outcome == 'success' }}
+ run: |
+ python3 -m pip install transformers==5.0.0
+ python3 -m pytest --noconftest -v "${GENAI_DIR}/tests/python_tests/test_gguf_frontend.py" --junitxml=reports/frontend.xml
+
+ - name: Tiny Gemma3 image, chat, API and Optimum loading acceptance (SDPA and PA)
+ if: ${{ !cancelled() && steps.build_genai.outcome == 'success' }}
+ run: |
+ python3 -m pip install transformers==5.0.0
+ python3 -m pytest --noconftest -v "${GENAI_DIR}/tests/python_tests/test_gguf_mmproj_acceptance.py" -k gemma3 --junitxml=reports/gemma3.xml
+
+ - name: Tiny Gemma4 image, video, audio, boundaries, chat, API and Optimum loading acceptance (SDPA and PA)
+ if: ${{ !cancelled() && steps.build_genai.outcome == 'success' }}
+ run: |
+ python3 -m pip install transformers==5.5.4
+ python3 -m pytest --noconftest -v "${GENAI_DIR}/tests/python_tests/test_gguf_mmproj_acceptance.py" -k gemma4 --junitxml=reports/gemma4.xml
+
+ - name: Tiny Muse image, video, chat, API and Optimum loading acceptance (SDPA and PA)
+ if: ${{ !cancelled() && steps.build_genai.outcome == 'success' }}
+ run: |
+ python3 -m pip install transformers==5.15.0
+ python3 -c 'from transformers import MuseGlimmerConfig, MuseGlimmerForConditionalGeneration, MuseGlimmerProcessor'
+ python3 -m pip freeze > reports/muse-dependencies.txt
+ python3 -m pytest --noconftest -v "${GENAI_DIR}/tests/python_tests/test_gguf_mmproj_acceptance.py" -k muse --junitxml=reports/muse.xml
+
+ - name: Tiny Qwen3.5 image, video, chat, API and Optimum loading acceptance (SDPA and PA)
+ if: ${{ !cancelled() && steps.build_genai.outcome == 'success' }}
+ run: |
+ python3 -m pip install transformers==5.2.0
+ python3 -m pytest --noconftest -v "${GENAI_DIR}/tests/python_tests/test_gguf_mmproj_acceptance.py" -k qwen35 --junitxml=reports/qwen35.xml
+
+ - name: Real Qwen3.5 pure Q4_0 acceptance (SDPA and PA)
+ if: ${{ inputs.run-real-models && !cancelled() && steps.build_genai.outcome == 'success' }}
+ run: |
+ python3 -m pip install transformers==5.2.0
+ python3 -m pytest --noconftest -v "${GENAI_DIR}/tests/python_tests/test_gguf_mmproj_acceptance.py" -k q4_0 --junitxml=reports/q4_0.xml
+
+ - name: Upload acceptance reports
+ if: ${{ !cancelled() }}
+ uses: ababushk/upload-artifact@ebc7d74ace101c08868aed05dba2aaf274b9a2c7 # main
+ with:
+ name: test-results-gguf-genai
+ path: |
+ reports/
+ llama-reference/configure-mmproj.log
+ llama-reference/build-mmproj.log
+ if-no-files-found: error
diff --git a/.github/workflows/requirements/gguf_genai.txt b/.github/workflows/requirements/gguf_genai.txt
new file mode 100644
index 00000000000..d5e55ce9d65
--- /dev/null
+++ b/.github/workflows/requirements/gguf_genai.txt
@@ -0,0 +1,8 @@
+# Versions validated by GGUF GenAI acceptance tests.
+pytest==9.1.1
+numpy==2.4.6
+sentencepiece==0.2.2
+accelerate==1.15.0
+gguf==0.19.0
+cmake==3.26.4
+py-build-cmake==0.4.3
diff --git a/.github/workflows/ubuntu_22.yml b/.github/workflows/ubuntu_22.yml
index c674f470e8c..846c75f1d86 100644
--- a/.github/workflows/ubuntu_22.yml
+++ b/.github/workflows/ubuntu_22.yml
@@ -540,6 +540,17 @@ jobs:
model_scope: 'nightly'
image: ${{ fromJSON(needs.docker.outputs.images).ov_test.ubuntu_22_04_x64 }}
+ GGUF_GenAI_Validation:
+ name: GGUF Frontend x GenAI acceptance
+ if: ${{ fromJSON(needs.smart_ci.outputs.affected_components).GGUF_FE.test }}
+ needs: [ Docker, Build, Smart_CI ]
+ uses: ./.github/workflows/job_gguf_genai_validation.yml
+ with:
+ 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: acb77de96aa9c89d0984c2e2d363cffb15b4f1d7
+
GGUF_LlamaCpp_Validation:
name: GGUF Frontend x llama.cpp validation
if: ${{ github.event_name != 'schedule' && fromJSON(needs.smart_ci.outputs.affected_components).GGUF_FE.test }}
@@ -720,7 +731,7 @@ jobs:
Overall_Status:
name: ci/gha_overall_status
needs: [Smart_CI, Build, Debian_Packages, Samples, Conformance, CXX_Unit_Tests, Python_Unit_Tests, TensorFlow_Layer_Tests, Pytorch_Layer_Tests,
- CPU_Functional_Tests, TensorFlow_Models_Tests_Precommit, PyTorch_Models_Tests, JAX_Models_Tests_Precommit, GGUF_Models_Tests_Precommit,
+ CPU_Functional_Tests, TensorFlow_Models_Tests_Precommit, PyTorch_Models_Tests, JAX_Models_Tests_Precommit, GGUF_Models_Tests_Precommit, GGUF_GenAI_Validation,
NVIDIA_Plugin, Openvino_tokenizers, iGPU,
Keras3_OpenVINO_Backend, iGPU_RoPE_Tests]
if: ${{ always() }}
diff --git a/src/frontends/gguf/docs/debugging_accuracy.md b/src/frontends/gguf/docs/debugging_accuracy.md
index 97b3932bfe5..a8215368bb8 100644
--- a/src/frontends/gguf/docs/debugging_accuracy.md
+++ b/src/frontends/gguf/docs/debugging_accuracy.md
@@ -12,6 +12,9 @@ there is no requirement to complete every diagnostic before inspecting the impli
Native builders and supplied cgraph decoders share converters, but have different graph construction
and state/IO adaptation. Backend environment variables do not configure native frontend inference.
See [testing](testing.md) for commands, acceptance criteria, and how to recognize skipped coverage.
+For GenAI/mmproj, use [multimodal integration bisection](#multimodal-integration-bisection).
+Before interpreting an ineffective rebuild, verify the source objects and loaded libraries;
+see [build and runtime identity](../../../../.claude/skills/ov-gguf/references/build-runtime.md).
## Reference and precision
@@ -31,6 +34,13 @@ weights preserves the file's original quantization error; it does not recover th
F32 weights. Keep these measurements separate and retain failed comparisons. See
[quantization](quantization.md) for conversion losses, native precision controls, and memory costs.
+Inspect tensor types rather than checkpoint names; a Q4_0 file can contain other quant formats.
+If inputs and graph contracts agree, exactly expand the same quantized weights with the pinned
+quantizer, compare the expansion in both engines, and compare OV compressed against OV expanded.
+Agreement of the expansions with a discrepancy only in quantized execution implicates CPU
+arithmetic; retain the original failed gate. A requantized fixture or a separately downloaded
+F16 checkpoint cannot establish parity for the original model.
+
## Localize the failing boundary
1. **Inputs:** align tokenization, prompts, chat templates, masks, positions, and preprocessing.
@@ -58,6 +68,50 @@ Near an MoE boundary, compare router logits, selected expert IDs, and the select
A small change near a tie can select another expert and amplify later differences. Identifying
this sensitivity does not waive the agreed accuracy threshold.
+## Multimodal integration bisection
+
+Freeze one failing request and the actual pinned CPU oracle. Record model/projector hashes,
+prompt/media, attention backend, inference precision, KV cache precision, activation
+quantization and thread settings. KV precision is independent of inference precision.
+Use explicit matching cache precision for numerical diagnosis and test product defaults
+separately. Do not silently change the task's first-token or replay-choice thresholds.
+
+Compare these boundaries in order, saving each buffer and its geometry:
+
+1. **Template and token IDs.** Compare the assembled prompt, special-token/BOS policy and
+ actual llama tokenizer IDs. Include combining marks, newlines and literal byte-token
+ spellings if chat fails while a plain prompt passes. For raw UTF-8 BPE, an ordinary
+ multi-character vocabulary entry may require merges; byte fallback must neither consume
+ its literal `<0xNN>` spelling nor displace an ordinary character with the same byte.
+2. **Media encoder.** Compare preprocessing geometry, token/patch limits and element-wise
+ encoder outputs. Synthetic square smoke tests can hide JPEG resizing or sequence limits.
+ Confirm frame sampling, timestamps and boundary tokens for video, and sample rate/audio
+ boundaries for audio. A documented mtmd assembly adaptation still needs the pinned CPU
+ encoder and llama decoder; label it separately from an upstream video API.
+3. **Embedding insertion and positions.** Feed the same encoder tensor to both decoders to
+ separate encoder errors from text/media insertion, per-layer features or position IDs.
+ Keep prompt IDs, token-type groups and sequence lengths identical.
+4. **Mask and window contract.** Compare local/global layers in SDPA and PA. GGUF emits
+ the existing GPT-OSS/Gemma3 sliding-mask pattern and moves mask precision conversion
+ into `Select`, preserving any intervening `Slice`. GenAI-adapted masks follow
+ Optimum-intel's window policy: same-image tokens remain visible bidirectionally even
+ beyond the sliding window, while text attention remains windowed. This differs from
+ the pinned llama.cpp Gemma4 mask; see the [known parity gap](mmproj.md#gemma4-image-window-parity-gap).
+ Restoring both policies requires an explicit serializable PA operation input or
+ attribute and device support. Runtime metadata must not control attention semantics.
+ Compare full prefill with prefix reuse separately; see the
+ [bidirectional image prefix-cache gap](mmproj.md#bidirectional-image-prefix-cache-gap).
+5. **Decoder logits.** Compare full logits, top choices and their margin on identical
+ history, then isolate cache/activation/weight arithmetic with exact expansions described under reference and precision.
+ High encoder cosine alone does not establish decoder parity or rule out a close top-1 flip.
+
+After fixing a shared tokenizer, mask, PA or executor path, run representative affected
+families with both SDPA/PA and relevant chat/media scenarios. Keep optimum-intel compatibility
+(existing loader/processor/model contracts) separate from llama numerical parity; sharing
+layout does not mean identical media geometry. Report every retained failure even if its
+arithmetic origin is understood. Tiny/random fixtures establish numerical contracts, not
+the quality of their generated prose.
+
## llama.cpp backend isolation
Use a compatible backend revision; the repository/ref used by CI are recorded in
diff --git a/src/frontends/gguf/docs/mmproj.md b/src/frontends/gguf/docs/mmproj.md
index a1fa1bcab5a..c770a92455a 100644
--- a/src/frontends/gguf/docs/mmproj.md
+++ b/src/frontends/gguf/docs/mmproj.md
@@ -106,7 +106,8 @@ the DeepStack features after the primary ones along `D`.
## Runtime metadata
Model rt_info `gguf_mmproj` keeps every source `clip.*` key and adds `<modality>.projector`,
-`<modality>.merge`, `vision.auxiliary_count`, `vision.window_size` (Muse Glimmer) and
+`<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
@@ -128,7 +129,8 @@ audio instead takes consecutive 640-sample frames from a 16 kHz waveform, withou
## Using the encoders and a language model
[`AdaptMmprojToGenAI`](../include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp) keeps one
-modality, drops the other branch's inputs and prefixes, and exposes `[1,T,D]` outputs named
+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.
@@ -139,10 +141,87 @@ mode prepares the language model for media injection:
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 without per-layer embeddings take `token_type_ids [B,T]`: image tokens attend
+- 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.
+ 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 |
+| `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.
+
+### Gemma4 image-window parity gap
+
+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.
+
+### Bidirectional image prefix-cache gap
+
+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.
Register `GenAIExtension` before converting the language model, as described in
[runtime.md](runtime.md#stateful-and-genai-conversion). In C++, with a `FrontEndManager manager`
@@ -155,7 +234,10 @@ and an already converted combined `mmproj` model:
using namespace ov::frontend::gguf::pass;
auto vision = mmproj->clone();
auto audio = mmproj->clone();
-AdaptMmprojToGenAI(AdaptMmprojToGenAI::Modality::VISION).run_on_model(vision);
+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);
auto frontend = manager.load_by_framework("gguf");
auto genai = std::make_shared<ov::frontend::gguf::GenAIExtension>(
diff --git a/src/frontends/gguf/docs/testing.md b/src/frontends/gguf/docs/testing.md
index b77db4ad14c..b60464bdcba 100644
--- a/src/frontends/gguf/docs/testing.md
+++ b/src/frontends/gguf/docs/testing.md
@@ -1,5 +1,7 @@
# Building and validating the GGUF frontend
+Run commands from the repository root. Shorthand paths below are relative to `src/frontends/gguf/`.
+
Use the repository [build prerequisites](../../../../docs/dev/build.md). GGUF defaults to enabled
(`ENABLE_OV_GGUF_FRONTEND=ON`); C++ tests require `ENABLE_TESTS=ON` and a shared-library build.
This Linux single-configuration example puts binaries and libraries in an explicit directory:
@@ -114,6 +116,24 @@ does not erase a failed comparison against quantized CPU arithmetic, and coheren
does not establish encoder accuracy or broad answer quality.
CI runs the two C++ binaries through [Smart CI's GGUF component gate](../../../../.github/workflows/job_cxx_unit_tests.yml).
+The jobs invoke GTest directly and upload XML reports. Fixture availability and
+conversion expectations are checked by the architecture suite itself. Run the
+same binaries locally with `--gtest_filter` while editing; use GHA for broader
+coverage and inspect test counts and skips in its artifacts.
[Model-hub CI](../../../../.github/workflows/job_gguf_models_tests.yml) runs checkpoint lists;
[llama.cpp compatibility CI](../../../../.github/workflows/job_gguf_llamacpp_validation.yml) records
the backend revision, operator tests, state scenarios, and exclusions. These validate different contracts.
+
+[GenAI acceptance CI](../../../../.github/workflows/job_gguf_genai_validation.yml)
+uses this workflow's OpenVINO package and wheels and a pinned companion GenAI
+commit on a 4-core/16-GB runner. Precommit runs generated tiny decoder, MoE and
+recurrent models across SDPA, PA, AUTO and continuous batching, plus tiny GGUF
+tokenizer, input, beam-search, streaming and saved-IR regressions. The multimodal
+pytest harness builds an independent pinned llama.cpp CPU oracle, converts pinned
+tiny checkpoints, and runs square/JPEG, SDPA/PA, single/multiple media, video/audio,
+chat, cancellation/reset and beam-search cases. Separate checks cover Optimum
+directory/map loading. Scheduled runs also enable the real Qwen3.5 pure Q4_0 fixture
+through `run-real-models`; precommit uses tiny models only.
+Acceptance reports record required coverage and source/precision provenance;
+Q4_K_M is excluded from accuracy gates pending the plugin fix. Known Gemma4
+window and Unified prefix-cache parity gaps remain documented in [mmproj.md](mmproj.md).
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp
index 64ed6ccdfb1..3fd7ff37ee0 100644
--- a/src/frontends/gguf/include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp
@@ -4,21 +4,38 @@
#pragma once
+#include <map>
+#include <string>
+
#include "openvino/frontend/gguf/visibility.hpp"
#include "openvino/pass/pass.hpp"
namespace ov::frontend::gguf::pass {
-/// Select an encoder from a combined mmproj and expose its GenAI embedding layout [B,T,D].
-/// Run on independent clones to obtain both modalities. The source graph contains both encoders.
+/// Select and adapt an encoder from a combined mmproj. Run on independent clones per modality.
class GGUF_FRONTEND_API AdaptMmprojToGenAI : public ov::pass::ModelPass {
public:
OPENVINO_MODEL_PASS_RTTI("ov::frontend::gguf::pass::AdaptMmprojToGenAI");
enum class Modality { VISION, AUDIO };
- explicit AdaptMmprojToGenAI(Modality modality) : m_modality(modality) {}
+ /// EMBEDDINGS retains native encoder inputs and exposes [B,T,D] features.
+ /// VISION_ENCODERS exposes the family-specific inputs used by GenAI vision encoders.
+ /// Invalid layout requirements throw without changing the supplied model.
+ enum class Layout { EMBEDDINGS, VISION_ENCODERS };
+ explicit AdaptMmprojToGenAI(Modality modality, Layout layout = Layout::EMBEDDINGS)
+ : m_modality(modality),
+ m_layout(layout) {}
bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+ /// VISION_ENCODERS exposes Optimum-intel-compatible inputs, preserving GGUF computation.
+ /// After a successful run, returns vision_embeddings and, for Qwen, vision_embeddings_pos
+ /// and vision_embeddings_merger. The supplied model is the encoder or Qwen merger.
+ const std::map<std::string, std::shared_ptr<ov::Model>>& get_vision_models() const {
+ return m_vision_models;
+ }
+
private:
Modality m_modality;
+ Layout m_layout;
+ std::map<std::string, std::shared_ptr<ov::Model>> m_vision_models;
};
} // namespace ov::frontend::gguf::pass
diff --git a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
index 897213b49c1..e22a2305cb8 100644
--- a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
@@ -253,8 +253,10 @@ public:
result.config["vision.minicpmv_version"] = std::to_string(c.version);
result.config["vision.query_count"] = std::to_string(c.queries);
}
- if (modality == "vision")
+ if (modality == "vision") {
result.config["vision.auxiliary_count"] = std::to_string(auxiliary.size());
+ result.config["vision.patch_size"] = std::to_string(c.patch);
+ }
return result;
}
diff --git a/src/frontends/gguf/src/builder/blocks/attention.cpp b/src/frontends/gguf/src/builder/blocks/attention.cpp
index 152a61bf4e2..9bed3a4ebf3 100644
--- a/src/frontends/gguf/src/builder/blocks/attention.cpp
+++ b/src/frontends/gguf/src/builder/blocks/attention.cpp
@@ -53,6 +53,8 @@ std::string attention(GraphEmitter& e,
const RopeConfig rope_config_l = cfg.layer_rope_config(il);
// Widen before multiplying the reshape dimensions.
const int64_t q_width = static_cast<int64_t>(head_size_l) * cfg.n_head;
+ // Gemma4 shared-KV layers have no K/V of their own; newer GGUF files omit those weights.
+ const bool has_own_kv = (cfg.shared_kv_layers == 0) || (il < kv.n_own_kv);
// Q/K/V projections: MUL_MAT(w, attn_norm), then conceptual reshape to heads.
// Fused-QKV archs (phi-3, minicpm) carry a single attn_qkv weight; split it into
@@ -63,6 +65,8 @@ std::string attention(GraphEmitter& e,
e.add_weight(p + "attn_v.weight");
} else if (e.has_weight(p + "attn_qkv.weight")) {
register_fused_qkv(e, cfg, il);
+ } else if (!has_own_kv) {
+ e.add_weight(p + "attn_q.weight");
} else {
e.add_weight(p + "attn_q.weight");
e.add_weight(p + "attn_k.weight");
@@ -77,8 +81,11 @@ std::string attention(GraphEmitter& e,
}
}
auto q = e.add_op("GGML_OP_MUL_MAT", p + "Qcur", {p + "attn_q.weight", attn_norm});
- auto k = e.add_op("GGML_OP_MUL_MAT", p + "Kcur", {p + "attn_k.weight", attn_norm});
- auto v = e.add_op("GGML_OP_MUL_MAT", p + "Vcur", {p + "attn_v.weight", attn_norm});
+ std::string k, v;
+ if (has_own_kv) {
+ k = e.add_op("GGML_OP_MUL_MAT", p + "Kcur", {p + "attn_k.weight", attn_norm});
+ v = e.add_op("GGML_OP_MUL_MAT", p + "Vcur", {p + "attn_v.weight", attn_norm});
+ }
// Q/K/V projection biases (qwen2 / qwen2.5: separate attn_{q,k,v}.bias; phi-3-style
// fused-QKV archs: attn_qkv.bias, already split into attn_{q,k,v}.bias by
@@ -86,14 +93,17 @@ std::string attention(GraphEmitter& e,
// Qwen35 repacks a joint Q/gate projection; retain its separate bias policy.
if (cfg.is_qwen35 ? cfg.has_qkv_bias : e.has_weight(p + "attn_q.bias")) {
q = add_bias(e, q, p + "attn_q.bias", p + "Qcur_b");
- k = add_bias(e, k, p + "attn_k.bias", p + "Kcur_b");
- v = add_bias(e, v, p + "attn_v.bias", p + "Vcur_b");
+ if (has_own_kv) {
+ k = add_bias(e, k, p + "attn_k.bias", p + "Kcur_b");
+ v = add_bias(e, v, p + "attn_v.bias", p + "Vcur_b");
+ }
}
// Full-width q/k norm (OLMoE): normalize the whole projection before splitting heads.
if (cfg.has_qk_norm && cfg.qk_norm_full) {
q = rms_norm(e, q, p + "attn_q_norm.weight", p + "Qcur_normed", cfg.rms_eps);
- k = rms_norm(e, k, p + "attn_k_norm.weight", p + "Kcur_normed", cfg.rms_eps);
+ if (has_own_kv)
+ k = rms_norm(e, k, p + "attn_k_norm.weight", p + "Kcur_normed", cfg.rms_eps);
}
// reshape Q/K/V to [1, n_tokens, n_head(_kv), head_size]
@@ -102,24 +112,29 @@ std::string attention(GraphEmitter& e,
{q},
6,
{{"reshape_target", std::vector<int64_t>{0, -1, cfg.n_head, head_size_l}}, {"special_zero", true}});
- k = e.add_op("GGML_OP_RESHAPE",
- p + "Kcur_r",
- {k},
- 6,
- {{"reshape_target", std::vector<int64_t>{0, -1, n_head_kv_l, head_size_l}}, {"special_zero", true}});
- v = e.add_op("GGML_OP_RESHAPE",
- p + "Vcur_r",
- {v},
- 6,
- {{"reshape_target", std::vector<int64_t>{0, -1, n_head_kv_l, head_size_l}}, {"special_zero", true}});
+ if (has_own_kv) {
+ k = e.add_op(
+ "GGML_OP_RESHAPE",
+ p + "Kcur_r",
+ {k},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, n_head_kv_l, head_size_l}}, {"special_zero", true}});
+ v = e.add_op(
+ "GGML_OP_RESHAPE",
+ p + "Vcur_r",
+ {v},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, n_head_kv_l, head_size_l}}, {"special_zero", true}});
+ }
// per-head q_norm / k_norm (qwen3, hunyuan, gemma4)
if (cfg.has_qk_norm && !cfg.qk_norm_full && !cfg.qk_norm_after_rope) {
q = rms_norm(e, q, p + "attn_q_norm.weight", p + "Qcur_normed", cfg.rms_eps);
- k = rms_norm(e, k, p + "attn_k_norm.weight", p + "Kcur_normed", cfg.rms_eps);
+ if (has_own_kv)
+ k = rms_norm(e, k, p + "attn_k_norm.weight", p + "Kcur_normed", cfg.rms_eps);
}
// gemma4: V gets a plain RMSNorm (no multiplicative weight, just normalize).
- if (cfg.has_v_norm) {
+ if (cfg.has_v_norm && has_own_kv) {
v = e.add_op("GGML_OP_RMS_NORM", p + "Vcur_normed", {v}, 0, {{"eps", cfg.rms_eps}});
}
@@ -138,12 +153,18 @@ std::string attention(GraphEmitter& e,
: std::vector<std::string>{k, "inp_pos"};
if (use_rope) {
q = e.add_op("GGML_OP_ROPE", p + "Qcur_rope", q_rope_in, cfg.rope_op_case, {{"rope_config", rope_config_l}});
- k = e.add_op("GGML_OP_ROPE", p + "Kcur_rope", k_rope_in, cfg.rope_op_case, {{"rope_config", rope_config_l}});
+ if (has_own_kv)
+ k = e.add_op("GGML_OP_ROPE",
+ p + "Kcur_rope",
+ k_rope_in,
+ cfg.rope_op_case,
+ {{"rope_config", rope_config_l}});
}
if (cfg.has_qk_norm && !cfg.qk_norm_full && cfg.qk_norm_after_rope) {
q = rms_norm(e, q, p + "attn_q_norm.weight", p + "Qcur_normed", cfg.rms_eps);
- k = rms_norm(e, k, p + "attn_k_norm.weight", p + "Kcur_normed", cfg.rms_eps);
+ if (has_own_kv)
+ k = rms_norm(e, k, p + "attn_k_norm.weight", p + "Kcur_normed", cfg.rms_eps);
}
if (cfg.attention_temperature_scale != 0.0f) {
@@ -171,7 +192,6 @@ std::string attention(GraphEmitter& e,
// Gemma4: layers with shared_kv_layers have no K/V of their own; they reuse the KV
// from the last layer of the same SWA type that has its own KV cache. SWA layers
// reuse the last own-KV SWA layer; global layers reuse the last own-KV global layer.
- const bool has_own_kv = (cfg.shared_kv_layers == 0) || (il < kv.n_own_kv);
int anchor_il = il;
if (!has_own_kv) {
anchor_il = is_swa_layer ? kv.anchor_swa : kv.anchor_global;
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 1d3c7e97c42..dc60e399be3 100644
--- a/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
@@ -4,25 +4,373 @@
#include "openvino/frontend/gguf/adapt_mmproj_to_genai.hpp"
+#include <limits>
+#include <stdexcept>
#include <unordered_set>
+#include "openvino/core/graph_util.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/floor_mod.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/greater_eq.hpp"
+#include "openvino/op/less.hpp"
+#include "openvino/op/logical_and.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/mvn.hpp"
#include "openvino/op/parameter.hpp"
+#include "openvino/op/range.hpp"
+#include "openvino/op/reduce_max.hpp"
+#include "openvino/op/reduce_sum.hpp"
+#include "openvino/op/reshape.hpp"
#include "openvino/op/result.hpp"
+#include "openvino/op/round.hpp"
+#include "openvino/op/scaled_dot_product_attention.hpp"
+#include "openvino/op/select.hpp"
+#include "openvino/op/slice.hpp"
#include "openvino/op/split.hpp"
#include "openvino/op/squeeze.hpp"
+#include "openvino/op/subtract.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/op/unsqueeze.hpp"
#include "pass/prune_orphaned_parameters.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf::pass {
-bool AdaptMmprojToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
- const std::string prefix = m_modality == Modality::VISION ? "vision." : "audio.";
+namespace {
+using namespace ov::op;
+using Value = ov::Output<ov::Node>;
+using Models = std::map<std::string, std::shared_ptr<ov::Model>>;
+
+Value i64(const std::vector<int64_t>& values) {
+ return v0::Constant::create(ov::element::i64, {values.size()}, values);
+}
+Value 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 mul(const Value& a, const Value& b) {
+ return std::make_shared<v1::Multiply>(a, b);
+}
+Value div(const Value& a, const Value& b) {
+ return std::make_shared<v1::Divide>(a, b);
+}
+Value mod(const Value& a, const Value& b) {
+ return std::make_shared<v1::FloorMod>(a, b);
+}
+Value add(const Value& a, int64_t b) {
+ return add(a, scalar(b));
+}
+Value mul(const Value& a, int64_t b) {
+ return mul(a, scalar(b));
+}
+Value div(const Value& a, int64_t b) {
+ return div(a, scalar(b));
+}
+Value mod(const Value& a, int64_t b) {
+ return mod(a, scalar(b));
+}
+Value reshape(const Value& value, const Value& shape) {
+ return std::make_shared<v1::Reshape>(value, shape, false);
+}
+Value as_index(const Value& value) {
+ return reshape(value, i64({1, 1, 1, -1}));
+}
+Value column(const Value& matrix, int64_t index) {
+ return std::make_shared<v8::Gather>(matrix, scalar(index), scalar(1));
+}
+Value range(const Value& count) {
+ auto stop = std::make_shared<v0::Squeeze>(count, i64({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) {
+ for (const auto& candidate : model->get_parameters()) {
+ if (candidate->get_friendly_name() == name)
+ return candidate;
+ }
+ OPENVINO_THROW("[GGUF] mmproj vision encoder has no input ", name);
+}
+
+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())
+ 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);
+}
+
+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) {
+ name_output(input, name);
+ model->add_parameters({input});
+ }
+ model->validate_nodes_and_infer_types();
+}
+
+std::shared_ptr<v0::Parameter> new_input(ov::element::Type type, const ov::PartialShape& shape) {
+ return std::make_shared<v0::Parameter>(type, shape);
+}
+
+// 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()) {
+ if (node->get_friendly_name() == name)
+ return node->output(0);
+ }
+ return {};
+}
+
+Value require_weight(const std::shared_ptr<ov::Model>& model, const std::string& tensor) {
+ auto value = weight(model, tensor);
+ OPENVINO_ASSERT(value.get_node(), "[GGUF] mmproj vision encoder has no ", tensor);
+ return value;
+}
+
+int64_t metadata(const std::shared_ptr<ov::Model>& model, const std::string& key, int64_t minimum = 1) {
+ OPENVINO_ASSERT(model->has_rt_info({"gguf_mmproj", key}), "[GGUF] missing mmproj metadata ", key);
+ const auto& attribute = model->get_rt_info<ov::Any>({"gguf_mmproj", key});
+ OPENVINO_ASSERT(attribute.is<std::string>(), "[GGUF] mmproj metadata must be a string: ", key);
+ const auto& text = attribute.as<std::string>();
+ int64_t value;
+ size_t end;
+ try {
+ value = std::stoll(text, &end);
+ } catch (const std::invalid_argument&) {
+ OPENVINO_THROW("[GGUF] invalid integer mmproj metadata ", key, ": '", text, "'");
+ } catch (const std::out_of_range&) {
+ OPENVINO_THROW("[GGUF] out-of-range integer mmproj metadata ", key, ": '", text, "'");
+ }
+ OPENVINO_ASSERT(end == text.size() && value >= minimum,
+ "[GGUF] invalid integer mmproj metadata ",
+ key,
+ ": '",
+ text,
+ "'");
+ return value;
+}
+
+Value image_from_patches(const Value& patches,
+ const Value& rows,
+ const Value& cols,
+ int64_t patch,
+ bool channels_last) {
+ const auto p = i64({patch}), c = i64({3});
+ auto grid = channels_last ? ov::OutputVector{rows, cols, p, p, c} : ov::OutputVector{rows, cols, c, p, p};
+ Value image = reshape(patches, std::make_shared<v0::Concat>(grid, 0));
+ image = std::make_shared<v1::Transpose>(
+ image,
+ i64(channels_last ? std::vector<int64_t>{4, 0, 2, 1, 3} : std::vector<int64_t>{2, 0, 3, 1, 4}));
+ return reshape(image,
+ std::make_shared<v0::Concat>(ov::OutputVector{i64({1, 3}), mul(rows, patch), mul(cols, patch)}, 0));
+}
+
+void squeeze_output(const std::shared_ptr<ov::Model>& model) {
+ auto result = model->get_results().front();
+ auto features = std::make_shared<v0::Squeeze>(result->input_value(0), i64({0}));
+ features->output(0).get_tensor().set_names({"last_hidden_state"});
+ result->input(0).replace_source_output(features);
+}
+
+// Patches fill the leading rows in raster order; padding rows have position -1.
+void gemma4_layout(const std::shared_ptr<ov::Model>& model, int64_t patch) {
+ OPENVINO_ASSERT(patch <= std::numeric_limits<int64_t>::max() / 3 / patch,
+ "[GGUF] out-of-range mmproj metadata vision.patch_size");
+ auto pixels = new_input(ov::element::f32, {1, -1, 3 * patch * patch});
+ auto positions = new_input(ov::element::i64, {1, -1, 2});
+ auto flat = std::make_shared<v0::Squeeze>(positions, i64({0}));
+ auto x = column(flat, 0), y = column(flat, 1);
+ auto count = std::make_shared<v1::ReduceSum>(
+ std::make_shared<v0::Convert>(std::make_shared<v1::GreaterEqual>(x, scalar(0)), ov::element::i64),
+ i64({0}),
+ true);
+ auto cols = add(std::make_shared<v1::ReduceMax>(x, i64({0}), true), 1);
+ auto rows = div(count, cols);
+ const auto valid = [&](const Value& value) {
+ return std::make_shared<v8::Slice>(value, i64({0}), count, i64({1}), i64({0}));
+ };
+ replace_input(model,
+ "pixel_values",
+ image_from_patches(valid(std::make_shared<v0::Squeeze>(pixels, i64({0}))), rows, cols, patch, true));
+ replace_input(model, "position_x", as_index(valid(x)));
+ replace_input(model, "position_y", as_index(valid(y)));
+ add_inputs(model, {{"pixel_values", pixels}, {"image_position_ids", positions}});
+}
+
+void muse_layout(const std::shared_ptr<ov::Model>& model, int64_t patch, int64_t window, int64_t merge) {
+ OPENVINO_ASSERT(patch <= std::numeric_limits<int64_t>::max() / 3 / patch,
+ "[GGUF] out-of-range mmproj metadata vision.patch_size");
+ OPENVINO_ASSERT(window <= std::numeric_limits<int64_t>::max() / window,
+ "[GGUF] out-of-range mmproj metadata vision.window_size");
+ OPENVINO_ASSERT(merge <= std::numeric_limits<int64_t>::max() / merge,
+ "[GGUF] out-of-range mmproj metadata vision.merge");
+ auto pixels = new_input(ov::element::f32, {-1, 3 * patch * patch});
+ auto grid = new_input(ov::element::i64, {1, 3});
+ auto thw = std::make_shared<v0::Squeeze>(grid, i64({0}));
+ Value rows = std::make_shared<v8::Gather>(thw, i64({1}), scalar(0));
+ Value cols = std::make_shared<v8::Gather>(thw, i64({2}), scalar(0));
+ 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_cols = div(add(cols, window - 1), window);
+ auto slot = range(mul(mul(div(add(rows, window - 1), window), window_cols), slots));
+ auto index_in_window = mod(slot, slots);
+ auto window_index = div(slot, slots);
+ auto top = mul(div(window_index, window_cols), window);
+ auto left = mul(mod(window_index, window_cols), window);
+ auto y = add(top, div(index_in_window, window));
+ auto x = add(left, mod(index_in_window, window));
+ auto inside =
+ std::make_shared<v1::LogicalAnd>(std::make_shared<v1::Less>(y, rows), std::make_shared<v1::Less>(x, cols));
+ Value index = std::make_shared<v1::Select>(inside, add(mul(y, cols), x), add(mul(top, cols), left));
+ replace_input(model, "patch_indices", as_index(index));
+ replace_input(model, "position_x", as_index(add(mod(index, cols), 1)));
+ replace_input(model, "position_y", as_index(add(div(index, cols), 1)));
+ auto key_mask = std::make_shared<v1::Select>(
+ inside,
+ v0::Constant::create(ov::element::f32, {}, {0.f}),
+ v0::Constant::create(ov::element::f32, {}, {-std::numeric_limits<float>::infinity()}));
+ replace_input(model, "window_mask", reshape(key_mask, i64({-1, 1, 1, slots})));
+
+ auto raster = range(mul(rows, cols));
+ auto r = div(raster, cols), c = mod(raster, cols);
+ auto slot_of = add(mul(add(mul(div(r, window), window_cols), div(c, window)), slots),
+ add(mul(mod(r, window), window), mod(c, window)));
+ replace_input(model, "output_indices", as_index(slot_of));
+ auto block = div(raster, merge * merge), within = mod(raster, merge * merge);
+ auto block_cols = div(cols, merge);
+ auto merged = add(mul(add(mul(div(block, block_cols), merge), div(within, merge)), cols),
+ add(mul(mod(block, block_cols), merge), mod(within, merge)));
+ replace_input(model, "merge_indices", as_index(merged));
+ add_inputs(model, {{"pixel_values", pixels}, {"image_grid_thw", grid}});
+ squeeze_output(model);
+}
+
+std::shared_ptr<ov::Model> single_output_model(const Value& output,
+ const std::string& name,
+ const ov::ParameterVector& inputs) {
+ auto result = std::make_shared<v0::Result>(output);
+ output.get_tensor().set_names({name});
+ return std::make_shared<ov::Model>(ov::ResultVector{result}, inputs)->clone();
+}
+
+Models qwen_layout(const std::shared_ptr<ov::Model>& model) {
+ Models models;
+ // HF flattens patches as (channel, frame, y, x).
+ auto frame = [&](const std::string& name) {
+ return std::make_shared<v0::Unsqueeze>(require_weight(model, name), i64({2}));
+ };
+ auto kernel =
+ std::make_shared<v0::Concat>(ov::OutputVector{frame("v.patch_embd.weight"), frame("v.patch_embd.weight.1")}, 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 = new_input(ov::element::f32, {-1, int64_t(patch_dim)});
+ name_output(patches, "hidden_states");
+ Value embeddings =
+ std::make_shared<v0::MatMul>(patches, reshape(kernel, i64({width, int64_t(patch_dim)})), 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 = new_input(ov::element::i64, {4, -1});
+ name_output(table_indices, "input");
+ auto table =
+ std::make_shared<v8::Gather>(require_weight(model, "v.position_embd.weight"), table_indices, scalar(0));
+ models["vision_embeddings_pos"] = single_output_model(table, "last_hidden_state", {table_indices});
+
+ auto norm_weight = require_weight(model, "v.blk.0.ln1.weight");
+ const auto consumers = norm_weight.get_target_inputs();
+ OPENVINO_ASSERT(consumers.size() == 1, "[GGUF] expected one consumer of v.blk.0.ln1.weight");
+ auto scale = consumers.begin()->get_node();
+ OPENVINO_ASSERT(ov::is_type<v1::Multiply>(scale), "[GGUF] unexpected consumer of v.blk.0.ln1.weight");
+ auto normalized = ov::as_type_ptr<v6::MVN>(
+ (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 = new_input(ov::element::f32, {-1, width});
+ // Replace the activation shared by LayerNorm and its residual path.
+ normalized->input_value(0).replace(std::make_shared<v0::Unsqueeze>(hidden_states, i64({0, 1})));
+ model->remove_parameter(parameter(model, "pixel_values"));
+ model->remove_parameter(parameter(model, "patch_indices"));
+
+ // The first column of each rotary half has frequency 1, so it holds the row or column.
+ const auto width_metadata = metadata(model, "clip.vision.embedding_length");
+ const auto heads = metadata(model, "clip.vision.attention.head_count");
+ OPENVINO_ASSERT(width_metadata == width && width_metadata % heads == 0 && width_metadata / heads % 4 == 0,
+ "[GGUF] incompatible mmproj metadata clip.vision.embedding_length and "
+ "clip.vision.attention.head_count");
+ const auto head = width_metadata / heads;
+ auto rotary = new_input(ov::element::f32, {-1, head / 2});
+ auto row = column(rotary, 0), col = column(rotary, head / 4);
+ auto positions = std::make_shared<v5::Round>(std::make_shared<v0::Concat>(ov::OutputVector{row, col, row, col}, 0),
+ v5::Round::RoundMode::HALF_TO_EVEN);
+ replace_input(model, "position_ids", as_index(positions));
+
+ auto mask = new_input(ov::element::f32, {1, -1, -1});
+ auto mask4 = std::make_shared<v0::Unsqueeze>(mask, i64({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] Qwen vision attention already has a mask");
+ auto masked = std::make_shared<v13::ScaledDotProductAttention>(sdpa->input_value(0),
+ sdpa->input_value(1),
+ sdpa->input_value(2),
+ mask4,
+ false);
+ masked->set_friendly_name(sdpa->get_friendly_name());
+ ov::replace_node(sdpa, masked);
+ }
+ }
+
+ const auto results = model->get_results();
+ squeeze_output(model);
+ if (results.size() > 1) {
+ ov::OutputVector levels;
+ for (size_t i = 1; i < results.size(); ++i) {
+ levels.push_back(results[i]->input_value(0));
+ model->remove_result(results[i]);
+ }
+ auto deepstack = std::make_shared<v0::Concat>(levels, 0);
+ deepstack->output(0).get_tensor().set_names({"deepstack_feature_lists"});
+ 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;
+}
+Models adapt_mmproj(const std::shared_ptr<ov::Model>& model,
+ AdaptMmprojToGenAI::Modality modality,
+ AdaptMmprojToGenAI::Layout layout) {
+ using Modality = AdaptMmprojToGenAI::Modality;
+ using Layout = AdaptMmprojToGenAI::Layout;
+ Models vision_models;
+ if (layout == Layout::VISION_ENCODERS)
+ OPENVINO_ASSERT(modality == Modality::VISION, "[GGUF] VISION_ENCODERS layout requires vision modality");
+ const std::string prefix = modality == Modality::VISION ? "vision." : "audio.";
std::shared_ptr<ov::op::v0::Result> selected;
for (const auto& result : model->get_results()) {
if (result->input_value(0).get_names().count(prefix + "embeddings"))
selected = result;
}
OPENVINO_ASSERT(selected, "[GGUF] mmproj has no ", prefix, "embeddings output");
+ std::string projector;
+ if (layout == Layout::VISION_ENCODERS) {
+ projector = model->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"});
+ OPENVINO_ASSERT(projector == "gemma3" || projector == "gemma4v" || projector == "gemma4uv" ||
+ projector == "muse-glimmer" || projector == "qwen3vl_merger",
+ "[GGUF] no GenAI vision layout for mmproj projector '",
+ projector,
+ "'");
+ }
auto live_before = std::make_shared<std::unordered_set<const ov::Node*>>();
SnapshotLiveParameters(live_before).run_on_model(model);
const auto results = model->get_results();
@@ -31,8 +379,8 @@ bool AdaptMmprojToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
auto embeddings = std::make_shared<ov::op::v0::Squeeze>(selected->input_value(0),
ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
size_t auxiliary_count = 0;
- if (m_modality == Modality::VISION && model->has_rt_info({"gguf_mmproj", "vision.auxiliary_count"}))
- auxiliary_count = std::stoull(model->get_rt_info<std::string>({"gguf_mmproj", "vision.auxiliary_count"}));
+ if (modality == Modality::VISION && model->has_rt_info({"gguf_mmproj", "vision.auxiliary_count"}))
+ auxiliary_count = size_t(metadata(model, "vision.auxiliary_count", 0));
if (auxiliary_count) {
auto split = std::make_shared<ov::op::v1::Split>(embeddings,
ov::op::v0::Constant::create(ov::element::i64, {}, {2}),
@@ -43,7 +391,7 @@ bool AdaptMmprojToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
}
} else {
// Only the tensor that becomes a Result is named; the Split path names output 0 instead.
- embeddings->output(0).set_names({m_modality == Modality::VISION ? "image_features" : "audio_features"});
+ embeddings->output(0).set_names({modality == Modality::VISION ? "image_features" : "audio_features"});
model->add_results({std::make_shared<ov::op::v0::Result>(embeddings)});
}
PruneParametersOrphanedSince(live_before).run_on_model(model);
@@ -53,6 +401,55 @@ bool AdaptMmprojToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
name_output(p, name.substr(prefix.size()));
}
model->validate_nodes_and_infer_types();
+ if (layout == Layout::VISION_ENCODERS) {
+ if (projector == "qwen3vl_merger") {
+ vision_models = qwen_layout(model);
+ } else {
+ if (projector == "gemma4v" || projector == "gemma4uv") {
+ gemma4_layout(model, metadata(model, "vision.patch_size"));
+ } else if (projector == "muse-glimmer") {
+ muse_layout(model,
+ metadata(model, "vision.patch_size"),
+ metadata(model, "vision.window_size"),
+ metadata(model, "vision.merge"));
+ }
+ vision_models = {{"vision_embeddings", model}};
+ }
+ }
+ return vision_models;
+}
+} // namespace
+
+bool AdaptMmprojToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ m_vision_models.clear();
+ if (m_layout == Layout::EMBEDDINGS) {
+ adapt_mmproj(model, m_modality, m_layout);
+ return true;
+ }
+ // Layout construction may fail after rewiring nodes; commit only the validated clone.
+ auto adapted = model->clone();
+ auto vision_models = adapt_mmproj(adapted, m_modality, m_layout);
+ const auto results = model->get_results();
+ const auto parameters = model->get_parameters();
+ const auto sinks = model->get_sinks();
+ const auto variables = model->get_variables();
+ for (const auto& result : results)
+ model->remove_result(result);
+ for (const auto& parameter : parameters)
+ model->remove_parameter(parameter);
+ for (const auto& sink : sinks)
+ model->remove_sink(sink);
+ for (const auto& variable : variables)
+ model->remove_variable(variable);
+ model->add_parameters(adapted->get_parameters());
+ model->add_results(adapted->get_results());
+ model->add_sinks(adapted->get_sinks());
+ model->add_variables(adapted->get_variables());
+ for (auto& [name, encoder] : vision_models) {
+ if (encoder == adapted)
+ encoder = model;
+ }
+ m_vision_models = std::move(vision_models);
return true;
}
} // namespace ov::frontend::gguf::pass
diff --git a/src/frontends/gguf/src/pass/adapt_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
index 597154b711a..8dde1593df4 100644
--- a/src/frontends/gguf/src/pass/adapt_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
@@ -11,7 +11,9 @@
#include "openvino/core/graph_util.hpp"
#include "openvino/core/rt_info.hpp"
#include "openvino/frontend/gguf/make_stateful.hpp"
+#include "openvino/frontend/gguf/tokenizer_metadata.hpp"
#include "openvino/op/add.hpp"
+#include "openvino/op/bitwise_and.hpp"
#include "openvino/op/broadcast.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
@@ -21,7 +23,7 @@
#include "openvino/op/equal.hpp"
#include "openvino/op/gated_delta_net.hpp"
#include "openvino/op/gather.hpp"
-#include "openvino/op/greater_eq.hpp"
+#include "openvino/op/greater.hpp"
#include "openvino/op/group_conv.hpp"
#include "openvino/op/less_eq.hpp"
#include "openvino/op/logical_and.hpp"
@@ -189,6 +191,42 @@ int64_t max_kv_cache_head_size(const std::shared_ptr<ov::Model>& model) {
return max_hs;
}
+// HF Gemma4 and llama.cpp look up media positions as padding.
+ov::Output<ov::Node> pad_media_placeholders(const ov::Model& model, const ov::Output<ov::Node>& ids) {
+ const auto& rt_info = model.get_rt_info();
+ const auto it = rt_info.find(gguf_tokenizer_metadata_key());
+ if (it == rt_info.end())
+ return ids;
+ const auto& config = it->second.as<std::shared_ptr<GGUFTokenizerMetadata>>()->config;
+ const auto tokens = config.find("tokens");
+ if (tokens == config.end() || !tokens->second.is<std::vector<std::string>>())
+ return ids;
+ const auto p = config.find("padding_token_id");
+ if (p == config.end())
+ return ids;
+ int64_t pad;
+ {
+ OPENVINO_ASSERT(p->second.is<ov::Tensor>(), "[GGUF] padding_token_id must be a tensor");
+ const auto& value = p->second.as<ov::Tensor>();
+ OPENVINO_ASSERT(value.get_size() == 1 && value.get_element_type().is_integral_number(),
+ "[GGUF] padding_token_id must contain one integral value");
+ pad = ov::op::v0::Constant(value).cast_vector<int64_t>().front();
+ OPENVINO_ASSERT(pad >= 0 && static_cast<uint64_t>(pad) < tokens->second.as<std::vector<std::string>>().size(),
+ "[GGUF] padding_token_id is outside the vocabulary");
+ }
+ ov::Output<ov::Node> media;
+ const auto& vocabulary = tokens->second.as<std::vector<std::string>>();
+ for (size_t id = 0; id < vocabulary.size(); ++id) {
+ if (vocabulary[id] != "<|image|>" && vocabulary[id] != "<|video|>" && vocabulary[id] != "<|audio|>")
+ continue;
+ auto match = make_shared<ov::op::v1::Equal>(ids, ov::op::v0::Constant::create(ov::element::i64, {}, {id}));
+ media = media.get_node() ? make_shared<ov::op::v1::LogicalOr>(media, match)->output(0) : match->output(0);
+ }
+ if (!media.get_node())
+ return ids;
+ return make_shared<ov::op::v1::Select>(media, ov::op::v0::Constant::create(ov::element::i64, {}, {pad}), ids);
+}
+
} // namespace
bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
@@ -261,12 +299,13 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
auto embedding = find_boundary(embedding_name);
const auto width = embedding->get_output_partial_shape(0)[3].get_length();
// Clone each lookup graph before rewiring the language model. Constants retain shared buffers.
- const auto extract = [&](const ov::Output<ov::Node>& lookup, const std::string& name) {
+ const auto extract = [&](const ov::Output<ov::Node>& lookup, const std::string& name, bool pad_media) {
auto extracted = make_shared<ov::Model>(ov::OutputVector{lookup}, ov::ParameterVector{inp_tokens})->clone();
extracted->get_rt_info() = model->get_rt_info();
auto ids = make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
name_output(ids, "input_ids");
- auto ids4 = make_shared<v0::Unsqueeze>(make_shared<v0::Convert>(ids, ov::element::i32),
+ auto lookup_ids = pad_media ? pad_media_placeholders(*model, ids) : ids->output(0);
+ auto ids4 = make_shared<v0::Unsqueeze>(make_shared<v0::Convert>(lookup_ids, ov::element::i32),
v0::Constant::create(ov::element::i64, {2}, {0, 1}));
auto old_ids = extracted->get_parameters().front();
old_ids->output(0).replace(ids4->output(0));
@@ -276,7 +315,7 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
extracted->validate_nodes_and_infer_types();
return extracted;
};
- m_embedding_model = extract(make_shared<v0::Squeeze>(embedding, axis_1), "inputs_embeds");
+ m_embedding_model = extract(make_shared<v0::Squeeze>(embedding, axis_1), "inputs_embeds", false);
auto per_layer = per_layer_name.empty() ? nullptr : find_boundary(per_layer_name);
int64_t per_layer_width = 0;
if (per_layer) {
@@ -292,7 +331,8 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
{4},
{int64_t{0}, int64_t{0}, per_layer_count, per_layer_width}),
true),
- "per_layer_inputs");
+ "per_layer_inputs",
+ true);
}
inputs_embeds = make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, -1, width});
name_output(inputs_embeds, "inputs_embeds");
@@ -326,8 +366,9 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
std::shared_ptr<v0::Parameter> token_type_ids;
const auto arch_it = model->get_rt_info().find("gguf_architecture");
const auto arch = arch_it != model->get_rt_info().end() ? arch_it->second.as<std::string>() : std::string{};
- // Gemma4 E2B/E4B, the variants with per-layer token embeddings, keep image attention causal.
- if (inputs_embeds && (arch == "gemma3" || (arch == "gemma4" && !per_layer_inputs))) {
+ const auto hidden = inputs_embeds ? inputs_embeds->get_partial_shape()[2] : ov::Dimension{};
+ const bool gemma4_causal = hidden == ov::Dimension(1536) || hidden == ov::Dimension(2560);
+ if (inputs_embeds && (arch == "gemma3" || (arch == "gemma4" && !gemma4_causal))) {
token_type_ids = make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
name_output(token_type_ids, "token_type_ids");
}
@@ -449,6 +490,10 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
};
const auto causal = make_shared<v1::LessEqual>(k_row, q_pos_col);
ov::Output<ov::Node> allowed = causal;
+ ov::Output<ov::Node> same_image;
+ ov::Output<ov::Node> causal_or_query_image = causal;
+ ov::Output<ov::Node> causal_or_key_image = causal;
+ ov::Output<ov::Node> causal_or_same_group = causal;
if (token_type_ids) {
// Only patches within the same current image can attend bidirectionally.
auto zeros = make_shared<v3::Broadcast>(v0::Constant::create(ov::element::i64, {}, {0}),
@@ -459,9 +504,14 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
auto query_groups = make_shared<v8::Slice>(groups, past_len, kv_len, one_1, one_1);
auto same_group = make_shared<v1::Equal>(as_query_col(query_groups), as_key_row(groups));
auto one = v0::Constant::create(ov::element::i64, {}, {1});
- auto images = make_shared<v1::LogicalAnd>(make_shared<v1::Equal>(as_query_col(token_type_ids), one),
- make_shared<v1::Equal>(as_key_row(key_types), one));
- allowed = make_shared<v1::LogicalOr>(allowed, make_shared<v1::LogicalAnd>(same_group, images));
+ auto query_image = make_shared<v1::Equal>(as_query_col(token_type_ids), one);
+ auto key_image = make_shared<v1::Equal>(as_key_row(key_types), one);
+ auto images = make_shared<v1::LogicalAnd>(query_image, key_image);
+ same_image = make_shared<v1::LogicalAnd>(same_group, images);
+ allowed = make_shared<v1::LogicalOr>(allowed, same_image);
+ causal_or_query_image = make_shared<v1::LogicalOr>(causal, query_image);
+ causal_or_key_image = make_shared<v1::LogicalOr>(causal, key_image);
+ causal_or_same_group = make_shared<v1::LogicalOr>(causal, same_group);
}
auto valid_keys =
make_shared<v1::NotEqual>(as_key_row(attention_mask), v0::Constant::create(ov::element::i64, {}, {0}));
@@ -474,28 +524,63 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
self_kq_mask->output(0).replace(global_mask->output(0));
}
- // Sliding-window mask: for prompts within the window this equals the full causal mask, but
- // once the context (prompt + generated tokens) exceeds it, reusing the causal mask would
- // leave every older key visible and produce wrong logits. When the model's metadata records
- // an explicit window length (see gguf_swa_window_key), AND the causal mask with "key not
- // more than window - 1 steps behind the query"; a token at position q may attend to keys in
- // [q - window + 1, q]. Absent a recorded length (e.g. gpt-oss/gemma4, whose SWA is described
- // by sinks / a per-layer pattern with no accompanying token count here), fall back to the
- // full causal mask, matching the previous behavior.
+ std::shared_ptr<v1::Select> sliding_mask;
if (auto self_kq_mask_swa = find_parameter(model, "self_kq_mask_swa")) {
ov::Output<ov::Node> swa_mask_4d = mask_4d->output(0);
const auto& rt_info = model->get_rt_info();
const auto swa_it = rt_info.find(gguf_swa_window_key());
if (swa_it != rt_info.end()) {
const auto window = swa_it->second.as<int64_t>();
- auto window_m1 = v0::Constant::create(ov::element::i32, ov::Shape{}, {static_cast<int32_t>(window - 1)});
- auto window_start = make_shared<v1::Subtract>(q_pos_col, window_m1); // [seq, 1]
- auto within_window = make_shared<v1::GreaterEqual>(k_row, window_start); // [seq, kv_len]
- auto allowed_swa = make_shared<v1::LogicalAnd>(allowed, within_window); // [seq, kv_len]
- swa_mask_4d = to_mask_4d(allowed_swa);
+ auto offset = v0::Constant::create(ov::element::i32, ov::Shape{}, {-static_cast<int32_t>(window)});
+ auto query_positions = make_shared<v0::Unsqueeze>(q_pos_col, one_1);
+ ov::Output<ov::Node> window_key_positions = make_shared<v0::Unsqueeze>(k_row, one_1);
+ if (token_type_ids) {
+ // Same-image keys bypass the window, matching Optimum-intel and existing PA semantics.
+ window_key_positions = make_shared<v1::Select>(make_shared<v0::Unsqueeze>(same_image, one_1),
+ query_positions,
+ window_key_positions);
+ }
+ auto within_window =
+ make_shared<v1::Greater>(window_key_positions, make_shared<v1::Add>(query_positions, offset));
+ // Distribute causal OR image-group conditions into the exported-model PA mask pattern.
+ auto mask =
+ make_shared<v13::BitwiseAnd>(make_shared<v0::Unsqueeze>(causal_or_query_image, one_1), within_window);
+ mask = make_shared<v13::BitwiseAnd>(mask, make_shared<v0::Unsqueeze>(causal_or_key_image, one_1));
+ mask = make_shared<v13::BitwiseAnd>(make_shared<v0::Unsqueeze>(causal_or_same_group, one_1), mask);
+ mask = make_shared<v13::BitwiseAnd>(mask, make_shared<v0::Unsqueeze>(valid_keys, one_1));
+ auto shape = make_shared<v0::Concat>(ov::OutputVector{batch_len, one_1, query_len, kv_len}, 0);
+ auto broadcast = make_shared<v3::Broadcast>(mask, shape);
+ sliding_mask = make_shared<v1::Select>(broadcast, zero_f, neg_f);
+ swa_mask_4d = sliding_mask;
}
self_kq_mask_swa->output(0).replace(swa_mask_4d);
}
+ if (sliding_mask) {
+ // Move mask precision conversion into Select so the existing PA matcher can recognize it.
+ for (const auto& node : model->get_ops()) {
+ const auto convert = ov::as_type_ptr<v0::Convert>(node);
+ if (!convert)
+ continue;
+ auto source = convert->input_value(0).get_node_shared_ptr();
+ ov::NodeVector slices;
+ while (ov::is_type<v8::Slice>(source)) {
+ slices.push_back(source);
+ source = source->input_value(0).get_node_shared_ptr();
+ }
+ if (source != sliding_mask)
+ continue;
+ const auto type = convert->get_destination_type();
+ ov::Output<ov::Node> mask = make_shared<v1::Select>(sliding_mask->input_value(0),
+ v0::Constant::create(type, {}, {0}),
+ v0::Constant::create(type, {}, {NEG_INF}));
+ for (auto it = slices.rbegin(); it != slices.rend(); ++it) {
+ auto inputs = (*it)->input_values();
+ inputs[0] = mask;
+ mask = (*it)->clone_with_new_inputs(inputs);
+ }
+ ov::replace_output_update_name(convert->output(0), mask);
+ }
+ }
if (batchable_recurrent) {
const auto& states = model->get_rt_info().at(gguf_recurrent_states_key()).as<std::vector<std::string>>();
diff --git a/src/frontends/gguf/tests/gen_arch_accuracy.py b/src/frontends/gguf/tests/gen_arch_accuracy.py
index 2cff34953d9..f36ce56349d 100644
--- a/src/frontends/gguf/tests/gen_arch_accuracy.py
+++ b/src/frontends/gguf/tests/gen_arch_accuracy.py
@@ -201,8 +201,8 @@ def write_qwen35_model(path, arch, fused_experts=False, f16=()):
def write_gemma4_model(path, opts):
"""Layers alternate sliding/full attention; E2B/E4B-style options add per-layer
- embeddings (`per_layer`) and reuse earlier KV in the last `shared_kv` layers, which keep
- their unused K/V tensors as real checkpoints do."""
+ embeddings (`per_layer`) and reuse earlier KV in the last `shared_kv` layers, which omit
+ their unused K/V tensors."""
w = gguf.GGUFWriter(path, "gemma4")
d, heads, layers, vocab, ff = 32, 4, opts.get("layers", 2), 32, 48
per_layer, shared = opts.get("per_layer", 0), opts.get("shared_kv", 0)
@@ -247,9 +247,10 @@ def write_gemma4_model(path, opts):
for name in ("attn_norm", "ffn_norm", "post_attention_norm", "post_ffw_norm"):
tensor(p + name + ".weight", (d,), True)
tensor(p + "attn_q.weight", (heads * head, d))
- tensor(p + "attn_k.weight", (kv * head, d))
- if swa:
- tensor(p + "attn_v.weight", (kv * head, d))
+ if layer < layers - shared:
+ tensor(p + "attn_k.weight", (kv * head, d))
+ if swa:
+ tensor(p + "attn_v.weight", (kv * head, d))
for name in ("q", "k"):
tensor(p + f"attn_{name}_norm.weight", (head,), True)
tensor(p + "attn_output.weight", (d, heads * head))
diff --git a/src/frontends/gguf/tests/test_adapt_to_genai.cpp b/src/frontends/gguf/tests/test_adapt_to_genai.cpp
index 9a086fda1a1..3f2cf344fea 100644
--- a/src/frontends/gguf/tests/test_adapt_to_genai.cpp
+++ b/src/frontends/gguf/tests/test_adapt_to_genai.cpp
@@ -10,14 +10,19 @@
// fixes below specifically need the exact node shapes translate_get_rows itself builds.
#include <cmath>
+#include <cstring>
#include <functional>
#include <memory>
+#include <numeric>
+#include <sstream>
#include "common_test_utils/node_builders/constant.hpp"
#include "gtest/gtest.h"
#include "op_test_utils.hpp"
+#include "openvino/core/validation_util.hpp"
#include "openvino/frontend/gguf/adapt_to_genai.hpp"
#include "openvino/frontend/gguf/make_stateful.hpp"
+#include "openvino/frontend/gguf/tokenizer_metadata.hpp"
#include "openvino/op/add.hpp"
#include "openvino/op/assign.hpp"
#include "openvino/op/broadcast.hpp"
@@ -36,13 +41,16 @@
#include "openvino/op/result.hpp"
#include "openvino/op/scaled_dot_product_attention.hpp"
#include "openvino/op/sink.hpp"
+#include "openvino/op/slice.hpp"
#include "openvino/op/squeeze.hpp"
#include "openvino/op/tanh.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "openvino/op/util/variable.hpp"
+#include "openvino/pass/constant_folding.hpp"
#include "openvino/pass/manager.hpp"
#include "openvino/pass/sdpa_to_paged_attention.hpp"
+#include "openvino/pass/serialize.hpp"
#include "utils.hpp"
using namespace ov_gguf_test;
@@ -290,6 +298,71 @@ TEST(GGUFAdaptToGenAI, EmbeddingModeMovesPerLayerTokenLookupToItsOwnModel) {
EXPECT_EQ(per_layer->output(0).get_partial_shape(), (ov::PartialShape{-1, -1, 2, 1}));
}
+TEST(GGUFAdaptToGenAI, MediaPaddingAcceptsIntegralMetadataAndRejectsInvalidValues) {
+ const auto adapt = [](const ov::Any& padding) {
+ auto m = build_minimal_gguf_model(8, 2, false, true);
+ m.pe_tok->get_rt_info()["gguf.per_layer_token_embedding"] = int64_t{2};
+ auto metadata = std::make_shared<ov::frontend::gguf::GGUFTokenizerMetadata>();
+ metadata->config["tokens"] =
+ std::vector<std::string>{"a", "b", "pad", "<|image|>", "<|video|>", "<|audio|>", "e", "f"};
+ metadata->config["padding_token_id"] = padding;
+ m.model->get_rt_info()[ov::frontend::gguf::gguf_tokenizer_metadata_key()] = metadata;
+ AdaptToGenAI pass(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ pass.run_on_model(m.model);
+ return pass.get_per_layer_embedding_model();
+ };
+ for (const auto& type : {ov::element::i8,
+ ov::element::u8,
+ ov::element::i16,
+ ov::element::u16,
+ ov::element::i32,
+ ov::element::u32,
+ ov::element::i64,
+ ov::element::u64}) {
+ SCOPED_TRACE(type);
+ const auto value = v0::Constant::create(type, {}, {2});
+ auto lookup = adapt(value->get_tensor_view());
+ ov::Tensor ids(ov::element::i64, {1, 4});
+ std::iota(ids.data<int64_t>(), ids.data<int64_t>() + 4, 3);
+ ov::TensorVector output{ov::Tensor(ov::element::f32, {1, 4, 2, 1})};
+ ASSERT_TRUE(lookup->evaluate(output, {ids}));
+ for (size_t i = 0; i < 3; ++i) {
+ EXPECT_EQ(output.front().data<float>()[2 * i], 1004.f);
+ EXPECT_EQ(output.front().data<float>()[2 * i + 1], 1005.f);
+ }
+ EXPECT_EQ(output.front().data<float>()[6], 1012.f);
+ EXPECT_EQ(output.front().data<float>()[7], 1013.f);
+ }
+ for (const auto& value : {v0::Constant::create(ov::element::i64, {0}, {}),
+ v0::Constant::create(ov::element::i64, {2}, {2, 2}),
+ v0::Constant::create(ov::element::f32, {}, {2}),
+ v0::Constant::create(ov::element::i64, {}, {-1}),
+ v0::Constant::create(ov::element::u64, {}, {uint64_t(-1)}),
+ v0::Constant::create(ov::element::i64, {}, {8})}) {
+ EXPECT_THROW(adapt(value->get_tensor_view()), ov::Exception);
+ }
+ for (const auto& value : {ov::Any{}, ov::Any{std::string{"2"}}, ov::Any{int64_t{2}}}) {
+ EXPECT_THROW(adapt(value), ov::Exception);
+ }
+}
+
+TEST(GGUFAdaptToGenAI, MediaPaddingPreservesTokenIdsWithoutPaddingMetadata) {
+ auto m = build_minimal_gguf_model(8, 2, false, true);
+ m.pe_tok->get_rt_info()["gguf.per_layer_token_embedding"] = int64_t{2};
+ auto metadata = std::make_shared<ov::frontend::gguf::GGUFTokenizerMetadata>();
+ metadata->config["tokens"] =
+ std::vector<std::string>{"a", "b", "c", "<|image|>", "<|video|>", "<|audio|>", "e", "f"};
+ m.model->get_rt_info()[ov::frontend::gguf::gguf_tokenizer_metadata_key()] = metadata;
+ AdaptToGenAI pass(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ ASSERT_TRUE(pass.run_on_model(m.model));
+ ov::Tensor ids(ov::element::i64, {1, 4});
+ std::iota(ids.data<int64_t>(), ids.data<int64_t>() + 4, 3);
+ ov::TensorVector output{ov::Tensor(ov::element::f32, {1, 4, 2, 1})};
+ ASSERT_TRUE(pass.get_per_layer_embedding_model()->evaluate(output, {ids}));
+ for (size_t i = 0; i < output.front().get_size(); ++i)
+ EXPECT_EQ(output.front().data<float>()[i], float(1006 + i));
+}
+
// An untagged token lookup cannot be moved, so the language model keeps input_ids for it.
TEST(GGUFAdaptToGenAI, EmbeddingModePreservesUntaggedAuxiliaryTokenLookup) {
auto m = build_minimal_gguf_model(4, 2, false, true);
@@ -324,6 +397,10 @@ TEST(GGUFAdaptToGenAI, BatchedMaskKeepsSequencesSeparateAndExcludesPadding) {
auto m = build_minimal_gguf_model();
auto mask = find_parameter(m.model, "self_kq_mask");
m.model->add_results({std::make_shared<v0::Result>(mask)});
+ auto swa = ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, -1, -1}, "self_kq_mask_swa");
+ m.model->add_parameters({swa});
+ m.model->add_results({std::make_shared<v0::Result>(swa)});
+ m.model->get_rt_info()[ov::frontend::gguf::pass::gguf_swa_window_key()] = int64_t{2};
ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));
ov::Core core;
auto request = core.compile_model(m.model, "CPU").create_infer_request();
@@ -345,20 +422,22 @@ TEST(GGUFAdaptToGenAI, BatchedMaskKeepsSequencesSeparateAndExcludesPadding) {
request.set_tensor("position_ids", positions);
request.set_tensor("beam_idx", beams);
request.infer();
- const auto actual = request.get_output_tensor(0);
- ASSERT_EQ(actual.get_shape(), (ov::Shape{2, 1, 3, past + 3}));
- for (size_t b = 0; b < 2; ++b) {
- // Padded query rows are ignored by generation.
- expect_mask(
- actual.data<const float>() + b * 3 * (past + 3),
- 3,
- past + 3,
- [&](size_t q, size_t k) {
- return k <= past + q && (b == 0 || k >= 2);
- },
- [&](size_t q) {
- return b == 1 && past + q < 2;
- });
+ for (size_t layer = 0; layer < 2; ++layer) {
+ const auto actual = request.get_output_tensor(layer);
+ ASSERT_EQ(actual.get_shape(), (ov::Shape{2, 1, 3, past + 3}));
+ for (size_t b = 0; b < 2; ++b) {
+ // Padded query rows are ignored by generation.
+ expect_mask(
+ actual.data<const float>() + b * 3 * (past + 3),
+ 3,
+ past + 3,
+ [&](size_t q, size_t k) {
+ return k <= past + q && (b == 0 || k >= 2) && (layer == 0 || k + 2 > past + q);
+ },
+ [&](size_t q) {
+ return b == 1 && past + q < 2;
+ });
+ }
}
}
}
@@ -376,28 +455,39 @@ TEST_P(GGUFAdaptToGenAIImageMask, RespectsLayerTypeImageGroupsAndCachedPrefix) {
AdaptToGenAI(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS).run_on_model(m.model);
// Adaptation replaces the original first result with logits; the retained mask is now first.
ov::Core core;
- auto request = core.compile_model(m.model, "CPU").create_infer_request();
- const std::vector<int64_t> types{0, 1, 1, 0, 1, 1, 0};
- for (size_t past : {0, 3}) {
- auto inputs = make_genai_inputs(types.size(), past);
- inputs.erase("input_ids");
- inputs.emplace("inputs_embeds", ov::Tensor(ov::element::f32, {1, types.size(), 2}));
- ov::Tensor token_types(ov::element::i64, {1, types.size()});
- std::copy(types.begin(), types.end(), token_types.data<int64_t>());
- inputs.emplace("token_type_ids", token_types);
- for (auto& entry : inputs)
- request.set_tensor(entry.first, entry.second);
- request.infer();
- for (size_t layer = 0; layer < 2; ++layer) {
- auto actual = request.get_output_tensor(layer);
- ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 1, types.size(), past + types.size()}));
- const bool bidirectional = layer == 1 || GetParam() == "gemma3";
- SCOPED_TRACE("layer=" + std::to_string(layer) + " past=" + std::to_string(past));
- expect_mask(actual.data<const float>(), types.size(), past + types.size(), [&](size_t q, size_t k) {
- const bool same_image = k >= past && types[q] == 1 && types[k - past] == 1 &&
- ((q <= 2 && k - past <= 2) || (q >= 4 && k - past >= 4));
- return (k <= past + q || (bidirectional && same_image)) && (layer == 0 || k + 3 > past + q);
- });
+ for (const auto& node : m.model->get_ops())
+ node->get_rt_info().clear();
+ std::stringstream xml, weights;
+ ov::pass::Serialize(xml, weights).run_on_model(m.model);
+ const auto bytes = weights.str();
+ ov::Tensor constants(ov::element::u8, {bytes.size()});
+ if (!bytes.empty())
+ std::memcpy(constants.data(), bytes.data(), bytes.size());
+ auto restored = core.read_model(xml.str(), constants);
+ for (const auto& model : {m.model, restored}) {
+ auto request = core.compile_model(model, "CPU").create_infer_request();
+ const std::vector<int64_t> types{0, 1, 1, 1, 1, 0, 1, 1, 0};
+ for (size_t past : {0, 3}) {
+ auto inputs = make_genai_inputs(types.size(), past);
+ inputs.erase("input_ids");
+ inputs.emplace("inputs_embeds", ov::Tensor(ov::element::f32, {1, types.size(), 2}));
+ ov::Tensor token_types(ov::element::i64, {1, types.size()});
+ std::copy(types.begin(), types.end(), token_types.data<int64_t>());
+ inputs.emplace("token_type_ids", token_types);
+ for (auto& entry : inputs)
+ request.set_tensor(entry.first, entry.second);
+ request.infer();
+ for (size_t layer = 0; layer < 2; ++layer) {
+ auto actual = request.get_output_tensor(layer);
+ ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 1, types.size(), past + types.size()}));
+ const bool bidirectional = layer == 1 || GetParam() == "gemma3";
+ SCOPED_TRACE("layer=" + std::to_string(layer) + " past=" + std::to_string(past));
+ expect_mask(actual.data<const float>(), types.size(), past + types.size(), [&](size_t q, size_t k) {
+ const bool same_image = k >= past && types[q] == 1 && types[k - past] == 1 &&
+ ((q <= 4 && k - past <= 4) || (q >= 6 && k - past >= 6));
+ return (k <= past + q && (layer == 0 || k + 3 > past + q)) || (bidirectional && same_image);
+ });
+ }
}
}
}
@@ -655,7 +745,10 @@ TEST(GGUFAdaptToGenAI, InpOutIdsRowSelectionCorrectUnderBothLayouts) {
// per token, without needing real RoPE weights or a llama.cpp oracle to compute an expected value.
namespace {
-std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hidden, bool auxiliary_tokens = false) {
+std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab,
+ int64_t hidden,
+ bool auxiliary_tokens = false,
+ ov::element::Type type = ov::element::f32) {
auto inp_tokens = ov::test::utils::make_param(ov::element::i32, ov::PartialShape{1, 1, 1, -1}, "inp_tokens");
auto inp_pos = ov::test::utils::make_param(ov::element::i32, ov::PartialShape{1, 1, 1, -1}, "inp_pos");
auto self_kq_mask = ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, -1, -1}, "self_kq_mask");
@@ -670,7 +763,7 @@ std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hid
table_values[v * hidden + h] = static_cast<float>(v);
}
}
- auto vocab_table = v0::Constant::create(ov::element::f32, {(size_t)vocab, (size_t)hidden}, table_values);
+ auto vocab_table = v0::Constant::create(type, {(size_t)vocab, (size_t)hidden}, table_values);
auto squeeze_01 = v0::Constant::create(ov::element::i64, {2}, {0, 1});
auto axis0 = v0::Constant::create(ov::element::i64, {1}, {0});
@@ -682,10 +775,7 @@ std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hid
embd->set_friendly_name("embd");
embd->get_rt_info()["gguf.token_embedding"] = true;
- // Flatten to [1, tokens, hidden] regardless of which axis (0 pre-fix, 1 post-fix) carries the
- // real token count -- Reshape never reorders memory, so this is correct either way (same trick
- // FixInpOutIdsRowSelect itself uses).
- auto embd_3d_shape = v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{1, -1, hidden});
+ auto squeeze_axis1 = v0::Constant::create(ov::element::i64, {1}, {1});
ov::Output<ov::Node> combined = embd;
if (auxiliary_tokens) {
auto auxiliary = std::make_shared<v8::Gather>(vocab_table, indices, axis0);
@@ -695,15 +785,15 @@ std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hid
lifted->get_rt_info()["gguf.per_layer_token_embedding"] = int64_t{2};
combined = std::make_shared<v1::Add>(embd, lifted);
}
- auto embd_3d = std::make_shared<v1::Reshape>(combined, embd_3d_shape, false);
+ auto embd_3d = std::make_shared<v0::Squeeze>(std::make_shared<v0::Convert>(combined, type), squeeze_axis1);
std::vector<float> zero_w(hidden * hidden, 0.0f);
- auto w_zero = v0::Constant::create(ov::element::f32, {(size_t)hidden, (size_t)hidden}, zero_w);
+ auto w_zero = v0::Constant::create(type, {(size_t)hidden, (size_t)hidden}, zero_w);
std::vector<float> identity_w(hidden * hidden, 0.0f);
for (int64_t i = 0; i < hidden; ++i) {
identity_w[i * hidden + i] = 1.0f;
}
- auto w_identity = v0::Constant::create(ov::element::f32, {(size_t)hidden, (size_t)hidden}, identity_w);
+ auto w_identity = v0::Constant::create(type, {(size_t)hidden, (size_t)hidden}, identity_w);
// Single-head Q/K/V projection: MatMul -> reshape to [1, tokens, 1, head_size] -> transpose to
// [1, 1, tokens, head_size].
@@ -721,10 +811,10 @@ std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hid
// Stateful KV cache: ReadValue -> Gather(beam_idx) -> Concat(-2, cur) -> Assign, exactly what
// ov::frontend::gguf::pass::MakeStateful emits for a real model.
auto make_kv_cache = [&](const ov::Output<ov::Node>& cur, const std::string& var_id) {
- auto var = std::make_shared<util::Variable>(
- util::VariableInfo{ov::PartialShape{-1, 1, -1, hidden}, ov::element::f32, var_id});
+ auto var =
+ std::make_shared<util::Variable>(util::VariableInfo{ov::PartialShape{-1, 1, -1, hidden}, type, var_id});
auto init_shape = v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, 0, hidden});
- auto init = std::make_shared<v3::Broadcast>(v0::Constant::create(ov::element::f32, {}, {0.0f}), init_shape);
+ auto init = std::make_shared<v3::Broadcast>(v0::Constant::create(type, {}, {0.0f}), init_shape);
auto read = std::make_shared<v6::ReadValue>(init, var);
auto past = std::make_shared<v8::Gather>(read, beam_idx, axis0, 0);
auto concat = std::make_shared<v0::Concat>(ov::OutputVector{past, cur}, -2);
@@ -734,11 +824,11 @@ std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hid
auto [k_concat, k_assign] = make_kv_cache(k, "attn_k_cache.0");
auto [v_concat, v_assign] = make_kv_cache(v, "attn_v_cache.0");
- auto scale = v0::Constant::create(ov::element::f32, {}, {1.0f});
+ auto scale = v0::Constant::create(type, {}, {1.0f});
auto sdpa = std::make_shared<v13::ScaledDotProductAttention>(q,
k_concat,
v_concat,
- self_kq_mask,
+ std::make_shared<v0::Convert>(self_kq_mask, type),
scale,
/*causal=*/false);
@@ -755,6 +845,142 @@ std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hid
ov::ParameterVector{inp_tokens, inp_pos, self_kq_mask, token_len_per_seq, beam_idx});
}
+class GGUFAdaptToGenAISlidingWindow : public testing::TestWithParam<std::tuple<bool, ov::element::Type, bool>> {};
+
+TEST_P(GGUFAdaptToGenAISlidingWindow, PreservedByPagedAttention) {
+ const auto& [embeds, mask_type, sliced] = GetParam();
+ auto model = build_attention_gguf_model(16, 4, false, mask_type);
+ auto mask = find_parameter(model, "self_kq_mask");
+ auto swa = ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, -1, -1}, "self_kq_mask_swa");
+ model->add_parameters({swa});
+ ov::Output<ov::Node> mask_source = swa;
+ if (sliced) {
+ mask_source = std::make_shared<v8::Slice>(swa,
+ v0::Constant::create(ov::element::i64, {1}, {0}),
+ v0::Constant::create(ov::element::i64, {1}, {1}),
+ v0::Constant::create(ov::element::i64, {1}, {1}),
+ v0::Constant::create(ov::element::i64, {1}, {1}));
+ }
+ mask->output(0).replace(mask_source);
+ model->get_rt_info()["gguf_architecture"] = std::string("gemma4");
+ model->get_rt_info()[ov::frontend::gguf::pass::gguf_swa_window_key()] = int64_t{64};
+ AdaptToGenAI(embeds ? AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS : AdaptToGenAI::InputMode::IDS_TO_LOGITS)
+ .run_on_model(model);
+ ov::pass::SDPAToPagedAttention(false, false, false).run_on_model(model);
+ size_t count = 0;
+ for (const auto& node : model->get_ordered_ops()) {
+ if (const auto pa = ov::as_type_ptr<ov::op::PagedAttentionExtension>(node)) {
+ const auto window = ov::util::get_constant_from_source(pa->input_value(10));
+ ASSERT_NE(window, nullptr);
+ EXPECT_EQ(window->cast_vector<int32_t>(), std::vector<int32_t>{64});
+ ++count;
+ }
+ }
+ EXPECT_EQ(count, 1);
+ for (const auto& node : model->get_ops()) {
+ if (const auto pa = ov::as_type_ptr<ov::op::PagedAttentionExtension>(node)) {
+ auto window_model =
+ std::make_shared<ov::Model>(ov::OutputVector{pa->input_value(10)}, ov::ParameterVector{});
+ ov::pass::ConstantFolding().run_on_model(window_model);
+ const auto window =
+ ov::as_type_ptr<v0::Constant>(window_model->get_results()[0]->get_input_node_shared_ptr(0));
+ ASSERT_NE(window, nullptr);
+ EXPECT_EQ(window->cast_vector<int32_t>(), std::vector<int32_t>{64});
+ }
+ }
+}
+
+TEST(GGUFAdaptToGenAI, ImageWindowMatchesSDPAAndPagedAttention) {
+ const size_t hidden = 4;
+ const std::vector<int32_t> types{0, 1, 1, 1, 1, 0, 1, 1, 0};
+ const auto length = types.size();
+ ov::Core core;
+ for (bool paged : {false, true}) {
+ SCOPED_TRACE(paged);
+ auto model = build_attention_gguf_model(16, hidden);
+ auto mask = find_parameter(model, "self_kq_mask");
+ auto swa = ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, -1, -1}, "self_kq_mask_swa");
+ model->add_parameters({swa});
+ mask->output(0).replace(swa->output(0));
+ model->get_rt_info()["gguf_architecture"] = std::string("gemma4");
+ model->get_rt_info()[ov::frontend::gguf::pass::gguf_swa_window_key()] = int64_t{3};
+ AdaptToGenAI(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS).run_on_model(model);
+ if (paged)
+ ov::pass::SDPAToPagedAttention(false, false, false).run_on_model(model);
+ auto compiled = core.compile_model(model,
+ "CPU",
+ ov::hint::inference_precision(ov::element::f32),
+ ov::hint::kv_cache_precision(ov::element::f32));
+ auto request = compiled.create_infer_request();
+ for (const auto& input : compiled.inputs()) {
+ const auto name = input.get_any_name();
+ if (name == "inputs_embeds") {
+ ov::Tensor tensor(ov::element::f32, paged ? ov::Shape{length, hidden} : ov::Shape{1, length, hidden});
+ for (size_t i = 0; i < tensor.get_size(); ++i)
+ tensor.data<float>()[i] = static_cast<float>(i / hidden);
+ request.set_tensor(input, tensor);
+ } else if (name == "token_type_ids" || name == "position_ids") {
+ ov::Tensor tensor(input.get_element_type(),
+ input.get_partial_shape().rank() == 1 ? ov::Shape{length} : ov::Shape{1, length});
+ for (size_t i = 0; i < length; ++i) {
+ const auto value = name == "token_type_ids" ? types[i] : static_cast<int32_t>(i);
+ if (tensor.get_element_type() == ov::element::i32)
+ tensor.data<int32_t>()[i] = value;
+ else
+ tensor.data<int64_t>()[i] = value;
+ }
+ request.set_tensor(input, tensor);
+ } else if (name == "attention_mask") {
+ ov::Tensor tensor(ov::element::i64, {1, length});
+ std::fill_n(tensor.data<int64_t>(), length, 1);
+ request.set_tensor(input, tensor);
+ } else if (name.find("key_cache.") == 0 || name.find("value_cache.") == 0) {
+ auto shape = input.get_partial_shape();
+ shape[0] = 1;
+ request.set_tensor(input, ov::Tensor(input.get_element_type(), shape.get_shape()));
+ } else {
+ std::vector<int32_t> values;
+ if (name == "beam_idx" || name == "past_lens" || name == "block_indices")
+ values = {0};
+ else if (name == "subsequence_begins")
+ values = {0, static_cast<int32_t>(length)};
+ else if (name == "block_indices_begins")
+ values = {0, 1};
+ else if (name == "max_context_len")
+ values = {static_cast<int32_t>(length)};
+ else
+ FAIL() << "Unexpected input: " << name;
+ const auto shape = input.get_partial_shape().rank() == 0 ? ov::Shape{} : ov::Shape{values.size()};
+ ov::Tensor tensor(ov::element::i32, shape);
+ std::copy(values.begin(), values.end(), tensor.data<int32_t>());
+ request.set_tensor(input, tensor);
+ }
+ }
+ request.infer();
+ const auto output = request.get_output_tensor(0);
+ ASSERT_EQ(output.get_size(), length * hidden);
+ for (size_t q = 0; q < length; ++q) {
+ float sum = 0;
+ size_t count = 0;
+ for (size_t k = 0; k < length; ++k) {
+ const bool same_image = types[q] == 1 && types[k] == 1 && ((q <= 4 && k <= 4) || (q >= 6 && k >= 6));
+ if ((k <= q && k + 3 > q) || same_image) {
+ sum += static_cast<float>(k);
+ ++count;
+ }
+ }
+ for (size_t h = 0; h < hidden; ++h)
+ EXPECT_NEAR(output.data<const float>()[q * hidden + h], sum / count, 1e-5f);
+ }
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(GGUFAdaptToGenAI,
+ GGUFAdaptToGenAISlidingWindow,
+ testing::Combine(testing::Bool(),
+ testing::Values(ov::element::f32, ov::element::f16, ov::element::bf16),
+ testing::Bool()));
+
constexpr float lm_head_soft_cap = 5.0f;
float lm_head_weight(int64_t row, int64_t col) {
@@ -922,22 +1148,36 @@ INSTANTIATE_TEST_SUITE_P(Softcap, GGUFAdaptToGenAILmHead, ::testing::Bool());
// The per-layer token lookup becomes a per_layer_inputs input, so the language model takes
// embeddings only, and the unmodified PagedAttention conversion applies as for optimum-intel.
TEST(GGUFAdaptToGenAI, PagedAttentionFlattensEmbeddingsWithPerLayerInputs) {
- auto model = build_attention_gguf_model(8, 4, true);
+ auto model = build_attention_gguf_model(8, 1536, true);
model->get_rt_info()["gguf_architecture"] = std::string("gemma4");
ASSERT_TRUE(AdaptToGenAI(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS).run_on_model(model));
ASSERT_EQ(find_parameter(model, "input_ids"), nullptr);
ASSERT_EQ(model->input("inputs_embeds").get_partial_shape().rank().get_length(), 3);
- ASSERT_EQ(model->input("per_layer_inputs").get_partial_shape(), (ov::PartialShape{-1, -1, 2, 2}));
- // Gemma4 variants with per-layer embeddings keep image attention causal.
+ ASSERT_EQ(model->input("per_layer_inputs").get_partial_shape(), (ov::PartialShape{-1, -1, 2, 768}));
+ // llama.cpp keeps E2B/E4B image attention causal.
ASSERT_EQ(find_parameter(model, "token_type_ids"), nullptr);
ASSERT_TRUE(ov::pass::SDPAToPagedAttention().run_on_model(model));
EXPECT_EQ(model->input("inputs_embeds").get_partial_shape(), (ov::PartialShape{-1, -1}));
// GenAI's continuous batching supplies per_layer_inputs as [tokens, 1, layers, width].
EXPECT_NO_THROW(
- model->reshape({{"inputs_embeds", {5, 4}}, {"per_layer_inputs", {5, 1, 2, 2}}, {"position_ids", {5}}}));
+ model->reshape({{"inputs_embeds", {5, 1536}}, {"per_layer_inputs", {5, 1, 2, 768}}, {"position_ids", {5}}}));
EXPECT_NO_THROW(model->validate_nodes_and_infer_types());
}
+class GGUFAdaptToGenAIGemma4VisionAttention : public ::testing::TestWithParam<int64_t> {};
+
+TEST_P(GGUFAdaptToGenAIGemma4VisionAttention, MatchesLlamaVariantSelection) {
+ const auto hidden = GetParam();
+ auto model = build_attention_gguf_model(8, hidden, true);
+ model->get_rt_info()["gguf_architecture"] = std::string("gemma4");
+ ASSERT_TRUE(AdaptToGenAI(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS).run_on_model(model));
+ EXPECT_EQ(find_parameter(model, "token_type_ids") == nullptr, hidden == 1536 || hidden == 2560);
+}
+
+INSTANTIATE_TEST_SUITE_P(EmbeddingWidth,
+ GGUFAdaptToGenAIGemma4VisionAttention,
+ ::testing::Values(int64_t{32}, int64_t{1536}, int64_t{2560}));
+
class GGUFAdaptToGenAIEmbeddingMode : public ::testing::TestWithParam<bool> {};
TEST_P(GGUFAdaptToGenAIEmbeddingMode, MatchesTokenModeAcrossCachedDecodeAndReset) {
diff --git a/src/frontends/gguf/tests/test_arch_accuracy.cpp b/src/frontends/gguf/tests/test_arch_accuracy.cpp
index 586a5b2a261..7365dab5bcd 100644
--- a/src/frontends/gguf/tests/test_arch_accuracy.cpp
+++ b/src/frontends/gguf/tests/test_arch_accuracy.cpp
@@ -31,6 +31,7 @@
#include "openvino/openvino.hpp"
#include "openvino/pass/manager.hpp"
#include "openvino/pass/sdpa_to_paged_attention.hpp"
+#include "quant/gguf.hpp"
namespace {
class GGUFArchitectureAccuracy : public ::testing::TestWithParam<const char*> {};
@@ -89,6 +90,17 @@ TEST(GGUFMultimodalBackboneAdaptation, QwenAndGemmaSupportBatchesAndPagedAttenti
SCOPED_TRACE(family);
auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/" + family + ".npz");
const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ if (std::string(family) == "gemma4-ple") {
+ const auto loaded = ov::frontend::gguf::get_gguf_data(temporary.path);
+ const auto& weights = std::get<1>(loaded);
+ EXPECT_EQ(weights.count("blk.0.attn_k.weight"), 1);
+ EXPECT_EQ(weights.count("blk.0.attn_v.weight"), 1);
+ EXPECT_EQ(weights.count("blk.1.attn_k.weight"), 1);
+ for (const auto* name :
+ {"blk.2.attn_k.weight", "blk.2.attn_v.weight", "blk.3.attn_k.weight", "blk.3.attn_v.weight"}) {
+ EXPECT_EQ(weights.count(name), 0) << name;
+ }
+ }
ov::frontend::gguf::FrontEnd frontend;
frontend.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());
auto model = frontend.convert(frontend.load(temporary.path));
diff --git a/src/frontends/gguf/tests/test_arch_conversion.cpp b/src/frontends/gguf/tests/test_arch_conversion.cpp
index d1237594ae5..f03452ef9ed 100644
--- a/src/frontends/gguf/tests/test_arch_conversion.cpp
+++ b/src/frontends/gguf/tests/test_arch_conversion.cpp
@@ -40,6 +40,7 @@
#include <algorithm>
#include <cctype>
#include <cstdint>
+#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <map>
@@ -364,6 +365,10 @@ TEST(GGUFArchConversionManifest, IsPresentAndComplete) {
// means the suite above skips. "Some present" is not: it means the generator ran and produced
// an incomplete set, which would silently shrink coverage to whatever happened to be written.
const size_t present = present_fixture_count();
+ const char* require_fixtures = std::getenv("OV_GGUF_REQUIRE_ARCH_FIXTURES");
+ if (require_fixtures && std::string(require_fixtures) == "1") {
+ ASSERT_EQ(present, fixtures.size()) << "CI requires every architecture fixture to be installed";
+ }
if (present != 0) {
for (const auto& f : fixtures) {
const std::string path = ov::util::path_join({fixture_dir(), f.header_file}).string();
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/README.md b/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
index c77ede2cc47..e52bb4cf0b2 100644
--- a/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
+++ b/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
@@ -10,7 +10,7 @@ OpenVINO does not participate in reference generation.
The 40 decoder fixtures and five embedding fixtures include Muse Glimmer, Qwen3.5 dense/MoE (separate and fused
expert projections, and F16 Gated-DeltaNet gate/beta projections that disable the frontend's
projection merges as mixed quantization does in real checkpoints), Gemma4 mixed-head MQA/MoE variants and an E2B/E4B-style Gemma4 with
-per-layer embeddings and shared KV layers (`gemma4-ple`). Reference revisions are:
+per-layer embeddings and shared KV layers that omit unused K/V weights (`gemma4-ple`). Reference revisions are:
| Fixtures | Upstream llama.cpp CPU oracle |
|---|---|
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-ple.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-ple.npz
index 39f934a3fcd..bac4c266648 100644
Binary files a/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-ple.npz and b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-ple.npz differ
diff --git a/src/frontends/gguf/tests/test_mmproj.cpp b/src/frontends/gguf/tests/test_mmproj.cpp
index 3fe4387c211..d15b0c1f28d 100644
--- a/src/frontends/gguf/tests/test_mmproj.cpp
+++ b/src/frontends/gguf/tests/test_mmproj.cpp
@@ -18,6 +18,11 @@
#include "openvino/frontend/gguf/adapt_mmproj_to_genai.hpp"
#include "openvino/frontend/gguf/extension/projector.hpp"
#include "openvino/frontend/gguf/frontend.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/gelu.hpp"
+#include "openvino/op/mvn.hpp"
+#include "openvino/op/unsqueeze.hpp"
#include "openvino/openvino.hpp"
#include "openvino/pass/serialize.hpp"
@@ -314,6 +319,209 @@ TEST_F(GGUFMMProj, MixedFileHasIndependentVisionAndAudioBranches) {
}
}
+TEST_F(GGUFMMProj, VisionEncoderLayoutRejectsAudioWithoutChangingModel) {
+ encoder("audio", "qwen2a");
+ auto model = convert();
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ Adapter adapter(Adapter::Modality::AUDIO, Adapter::Layout::VISION_ENCODERS);
+ OV_EXPECT_THROW(adapter.run_on_model(model), ov::Exception, testing::HasSubstr("requires vision modality"));
+ EXPECT_TRUE(adapter.get_vision_models().empty());
+ EXPECT_EQ(model->output().get_any_name(), "audio.embeddings");
+}
+
+TEST_F(GGUFMMProj, VisionEncoderLayoutRejectsMissingVisionWithoutChangingModel) {
+ encoder("audio", "qwen2a");
+ auto model = convert();
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ OV_EXPECT_THROW(adapter.run_on_model(model), ov::Exception, testing::HasSubstr("no vision.embeddings output"));
+ EXPECT_TRUE(adapter.get_vision_models().empty());
+ EXPECT_EQ(model->output().get_any_name(), "audio.embeddings");
+}
+
+TEST_F(GGUFMMProj, VisionEncoderLayoutRejectsUnsupportedProjectorWithoutChangingModel) {
+ auto arrays = cnpy::npz_load(
+ (std::filesystem::path(ov_gguf_test::test_data_dir()) / "mmproj_accuracy" / "pixtral.npz").string());
+ ov_gguf_test::TemporaryGguf fixture(ov_gguf_test::npz_array(arrays, "model"));
+ ov::frontend::gguf::FrontEnd frontend;
+ auto model = frontend.convert(frontend.load(fixture.path));
+ const auto results = model->get_results();
+ const auto parameters = model->get_parameters();
+ const auto nodes = model->get_ordered_ops();
+ const auto input_names = model->input(0).get_names();
+ const auto output_names = model->output().get_names();
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ OV_EXPECT_THROW(adapter.run_on_model(model), ov::Exception, testing::HasSubstr("no GenAI vision layout"));
+ EXPECT_TRUE(adapter.get_vision_models().empty());
+ EXPECT_EQ(model->get_results(), results);
+ EXPECT_EQ(model->get_parameters(), parameters);
+ EXPECT_EQ(model->get_ordered_ops(), nodes);
+ EXPECT_EQ(model->input(0).get_names(), input_names);
+ EXPECT_EQ(model->output().get_names(), output_names);
+ EXPECT_NO_THROW(Adapter(Adapter::Modality::VISION).run_on_model(model));
+ EXPECT_EQ(model->output().get_any_name(), "image_features");
+}
+
+std::shared_ptr<ov::Model> vision_fixture(const std::string& name) {
+ auto arrays = cnpy::npz_load(
+ (std::filesystem::path(ov_gguf_test::test_data_dir()) / "mmproj_accuracy" / (name + ".npz")).string());
+ ov_gguf_test::TemporaryGguf fixture(ov_gguf_test::npz_array(arrays, "model"));
+ ov::frontend::gguf::FrontEnd frontend;
+ return frontend.convert(frontend.load(fixture.path));
+}
+
+void expect_layout_rejection_preserves_model(const std::shared_ptr<ov::Model>& model, const std::string& requirement) {
+ const auto results = model->get_results();
+ const auto parameters = model->get_parameters();
+ const auto nodes = model->get_ordered_ops();
+ std::vector<ov::OutputVector> inputs;
+ std::vector<std::string> names;
+ std::vector<std::unordered_set<std::string>> tensor_names;
+ for (const auto& node : nodes) {
+ inputs.push_back(node->input_values());
+ names.push_back(node->get_friendly_name());
+ for (const auto& output : node->outputs())
+ tensor_names.push_back(output.get_names());
+ }
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ OV_EXPECT_THROW(adapter.run_on_model(model), ov::Exception, testing::HasSubstr(requirement));
+ EXPECT_TRUE(adapter.get_vision_models().empty());
+ EXPECT_EQ(model->get_results(), results);
+ EXPECT_EQ(model->get_parameters(), parameters);
+ EXPECT_EQ(model->get_ordered_ops(), nodes);
+ size_t output_index = 0;
+ for (size_t i = 0; i < nodes.size(); ++i) {
+ EXPECT_EQ(nodes[i]->input_values(), inputs[i]);
+ EXPECT_EQ(nodes[i]->get_friendly_name(), names[i]);
+ for (const auto& output : nodes[i]->outputs())
+ EXPECT_EQ(output.get_names(), tensor_names[output_index++]);
+ }
+ EXPECT_NO_THROW(Adapter(Adapter::Modality::VISION).run_on_model(model));
+ EXPECT_EQ(model->output(0).get_any_name(), "image_features");
+}
+
+class GGUFMMProjLayoutMetadata : public ::testing::TestWithParam<std::pair<std::string, std::string>> {};
+
+TEST_P(GGUFMMProjLayoutMetadata, RejectsInvalidMetadataWithoutChangingModel) {
+ const auto& [fixture, key] = GetParam();
+ auto source = vision_fixture(fixture);
+ for (const std::string value : {"missing",
+ "wrong_type",
+ "",
+ "invalid",
+ "2trailing",
+ "0",
+ "-1",
+ "9223372036854775808",
+ "9223372036854775807"}) {
+ SCOPED_TRACE(key + "=" + value);
+ auto model = source->clone();
+ if (value == "missing")
+ model->get_rt_info()["gguf_mmproj"].as<ov::AnyMap>().erase(key);
+ else if (value == "wrong_type")
+ model->set_rt_info(2, {"gguf_mmproj", key});
+ else
+ model->set_rt_info(value, {"gguf_mmproj", key});
+ expect_layout_rejection_preserves_model(model, key);
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(VisionEncoders,
+ GGUFMMProjLayoutMetadata,
+ ::testing::Values(std::make_pair("gemma4v", "vision.patch_size"),
+ std::make_pair("gemma4uv", "vision.patch_size"),
+ std::make_pair("muse-glimmer", "vision.patch_size"),
+ std::make_pair("muse-glimmer", "vision.window_size"),
+ std::make_pair("muse-glimmer", "vision.merge"),
+ std::make_pair("qwen3vl_merger", "clip.vision.embedding_length"),
+ std::make_pair("qwen3vl_merger", "clip.vision.attention.head_count")));
+
+TEST(GGUFMMProjLayout, RejectsMissingQwenWeightsWithoutChangingModel) {
+ auto source = vision_fixture("qwen3vl_merger");
+ for (const std::string tensor :
+ {"v.patch_embd.weight", "v.patch_embd.weight.1", "v.position_embd.weight", "v.blk.0.ln1.weight"}) {
+ SCOPED_TRACE(tensor);
+ auto model = source->clone();
+ bool found = false;
+ for (const auto& node : model->get_ordered_ops()) {
+ if (node->get_friendly_name() == tensor + "_" + tensor) {
+ node->set_friendly_name("unavailable_weight");
+ found = true;
+ }
+ }
+ ASSERT_TRUE(found);
+ expect_layout_rejection_preserves_model(model, tensor);
+ }
+}
+
+TEST(GGUFMMProjLayout, RejectsMissingQwenInputWithoutChangingModel) {
+ auto model = vision_fixture("qwen3vl_merger");
+ bool found = false;
+ for (const auto& input : model->get_parameters()) {
+ if (input->get_friendly_name() == "vision.position_ids") {
+ input->set_friendly_name("unavailable_input");
+ found = true;
+ }
+ }
+ ASSERT_TRUE(found);
+ expect_layout_rejection_preserves_model(model, "position_ids");
+}
+
+TEST(GGUFMMProjLayout, QwenPreservesLayerNormAndResidualWithEitherWeightInput) {
+ for (const bool swap_inputs : {false, true}) {
+ SCOPED_TRACE(swap_inputs);
+ auto model = vision_fixture("qwen3vl_merger");
+ for (const auto& node : model->get_ordered_ops()) {
+ if (node->get_friendly_name() != "v.blk.0.ln1.weight_v.blk.0.ln1.weight")
+ continue;
+ auto scale = node->output(0).get_target_inputs().begin()->get_node();
+ if (swap_inputs) {
+ const auto inputs = scale->input_values();
+ scale->input(0).replace_source_output(inputs[1]);
+ scale->input(1).replace_source_output(inputs[0]);
+ }
+ }
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ ASSERT_TRUE(adapter.run_on_model(model));
+ auto hidden = model->input("hidden_states");
+ const auto hidden_consumers = hidden.get_target_inputs();
+ ASSERT_EQ(hidden_consumers.size(), 1);
+ const auto activation = hidden_consumers.begin()->get_node();
+ ASSERT_TRUE(ov::is_type<ov::op::v0::Unsqueeze>(activation));
+ bool normalized = false, residual = false;
+ for (const auto& input : activation->output(0).get_target_inputs()) {
+ normalized |= ov::is_type<ov::op::v6::MVN>(input.get_node());
+ residual |= ov::is_type<ov::op::v1::Add>(input.get_node());
+ }
+ EXPECT_TRUE(normalized);
+ EXPECT_TRUE(residual);
+ }
+}
+
+TEST(GGUFMMProjLayout, RejectsUnexpectedQwenNormalizationWithoutChangingModel) {
+ for (const bool extra_weight_consumer : {false, true}) {
+ SCOPED_TRACE(extra_weight_consumer);
+ auto model = vision_fixture("qwen3vl_merger");
+ for (const auto& node : model->get_ordered_ops()) {
+ if (node->get_friendly_name() != "v.blk.0.ln1.weight_v.blk.0.ln1.weight")
+ continue;
+ const auto weight = node->output(0);
+ auto scale = weight.get_target_inputs().begin()->get_node();
+ const size_t activation_index = scale->input_value(0) == weight ? 1 : 0;
+ const auto normalized = scale->input_value(activation_index);
+ if (extra_weight_consumer)
+ scale->input(activation_index)
+ .replace_source_output(std::make_shared<ov::op::v1::Add>(normalized, weight));
+ else
+ scale->input(activation_index).replace_source_output(normalized.get_node()->input_value(0));
+ }
+ expect_layout_rejection_preserves_model(model, extra_weight_consumer ? "one consumer" : "LayerNorm");
+ }
+}
+
TEST_F(GGUFMMProj, UnsupportedSecondModalityIsNotSilentlyDiscarded) {
encoder("vision", "gemma3");
writer.kv_bool("clip.has_audio_encoder", true);
@@ -554,4 +762,185 @@ INSTANTIATE_TEST_SUITE_P(Reference,
"resampler",
"resampler_v2",
"resampler_v4"));
+class GGUFMMProjGenAIVisionLayout : public GGUFMMProjAccuracy {
+protected:
+ ov::Tensor reference(const std::string& step) {
+ auto source = model->clone();
+ std::map<std::string, ov::Tensor> inputs;
+ for (const auto& input : source->inputs()) {
+ const auto name = input.get_any_name().substr(std::string("vision.").size());
+ const auto key = step.empty() && name == "pixel_values" ? "inputs" : step + name;
+ inputs[input.get_any_name()] = tensor(key, input.get_element_type());
+ }
+ return infer(source, inputs).front();
+ }
+ int64_t metadata(const std::string& key) const {
+ return std::stoll(model->get_rt_info<std::string>({"gguf_mmproj", key}));
+ }
+ std::vector<ov::Tensor> infer(const std::shared_ptr<ov::Model>& current,
+ const std::map<std::string, ov::Tensor>& inputs) {
+ auto request = compile(current);
+ for (const auto& [name, value] : inputs)
+ request.set_tensor(name, value);
+ request.infer();
+ std::vector<ov::Tensor> outputs;
+ for (size_t i = 0; i < current->outputs().size(); ++i) {
+ const auto output = request.get_output_tensor(i);
+ outputs.emplace_back(output.get_element_type(), output.get_shape());
+ output.copy_to(outputs.back());
+ }
+ return outputs;
+ }
+};
+
+TEST_P(GGUFMMProjGenAIVisionLayout, MatchesSourceGraph) {
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ auto adapted = model->clone();
+ ASSERT_TRUE(adapter.run_on_model(adapted));
+ const auto& models = adapter.get_vision_models();
+ const auto projector = model->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"});
+ ASSERT_EQ(models.size(), projector == "qwen3vl_merger" ? 3u : 1u);
+ EXPECT_EQ(models.at(projector == "qwen3vl_merger" ? "vision_embeddings_merger" : "vision_embeddings"), adapted);
+ const auto patch = size_t(metadata("vision.patch_size"));
+ const bool steps = std::any_of(arrays.begin(), arrays.end(), [](const auto& entry) {
+ return entry.first == "0.embeddings";
+ });
+ for (const std::string& step : steps ? std::vector<std::string>{"0.", "1."} : std::vector<std::string>{""}) {
+ SCOPED_TRACE(projector + " " + step);
+ const auto image = tensor(steps ? step + "pixel_values" : "inputs", ov::element::f32);
+ const auto& shape = image.get_shape();
+ const size_t height = shape[2], width = shape[3], rows = height / patch, cols = width / patch;
+ const size_t count = rows * cols;
+ const auto pixel = [&](size_t frame, size_t channel, size_t patch_index, size_t y, size_t x) {
+ const size_t row = patch_index / cols * patch + y, col = patch_index % cols * patch + x;
+ return image.data<const float>()[((frame * 3 + channel) * height + row) * width + col];
+ };
+ std::vector<ov::Tensor> actual;
+ if (projector == "gemma3") {
+ actual = infer(models.at("vision_embeddings"), {{"pixel_values", image}});
+ } else if (projector == "gemma4v" || projector == "gemma4uv") {
+ const size_t padded = count + 3, dim = patch * patch * 3;
+ ov::Tensor values(ov::element::f32, {1, padded, dim});
+ ov::Tensor positions(ov::element::i64, {1, padded, 2});
+ std::fill_n(values.data<float>(), values.get_size(), 0.f);
+ std::fill_n(positions.data<int64_t>(), positions.get_size(), int64_t{-1});
+ const auto x = tensor(step + "position_x", ov::element::i32);
+ const auto y = tensor(step + "position_y", ov::element::i32);
+ for (size_t i = 0; i < count; ++i) {
+ positions.data<int64_t>()[2 * i] = x.data<const int32_t>()[i];
+ positions.data<int64_t>()[2 * i + 1] = y.data<const int32_t>()[i];
+ for (size_t py = 0; py < patch; ++py)
+ for (size_t px = 0; px < patch; ++px)
+ for (size_t c = 0; c < 3; ++c)
+ values.data<float>()[i * dim + (py * patch + px) * 3 + c] = pixel(0, c, i, py, px);
+ }
+ actual =
+ infer(models.at("vision_embeddings"), {{"pixel_values", values}, {"image_position_ids", positions}});
+ } else if (projector == "muse-glimmer") {
+ const size_t dim = 3 * patch * patch;
+ ov::Tensor values(ov::element::f32, {count, dim});
+ for (size_t i = 0; i < count; ++i)
+ for (size_t c = 0; c < 3; ++c)
+ for (size_t py = 0; py < patch; ++py)
+ for (size_t px = 0; px < patch; ++px)
+ values.data<float>()[i * dim + (c * patch + py) * patch + px] = pixel(0, c, i, py, px);
+ ov::Tensor grid(ov::element::i64, {1, 3});
+ grid.data<int64_t>()[0] = 1;
+ grid.data<int64_t>()[1] = int64_t(rows);
+ grid.data<int64_t>()[2] = int64_t(cols);
+ actual = infer(models.at("vision_embeddings"), {{"pixel_values", values}, {"image_grid_thw", grid}});
+ } else {
+ ASSERT_EQ(projector, "qwen3vl_merger");
+ const auto order = tensor("patch_indices", ov::element::i32);
+ const size_t dim = 6 * patch * patch;
+ ov::Tensor hidden(ov::element::f32, {count, dim});
+ for (size_t j = 0; j < count; ++j)
+ for (size_t c = 0; c < 3; ++c)
+ for (size_t t = 0; t < 2; ++t)
+ for (size_t py = 0; py < patch; ++py)
+ for (size_t px = 0; px < patch; ++px)
+ hidden.data<float>()[j * dim + ((c * 2 + t) * patch + py) * patch + px] =
+ pixel(t, c, size_t(order.data<const int32_t>()[j]), py, px);
+ auto embeddings = infer(models.at("vision_embeddings"), {{"hidden_states", hidden}}).front();
+ const size_t embedding_width = embeddings.get_shape()[1];
+
+ const auto& pos_model = models.at("vision_embeddings_pos");
+ size_t side = 0;
+ for (const auto& node : pos_model->get_ordered_ops()) {
+ if (ov::is_type<ov::op::v8::Gather>(node))
+ side = size_t(std::lround(std::sqrt(double(node->get_input_shape(0)[0]))));
+ }
+ ASSERT_GT(side, 1u);
+ ov::Tensor indices(ov::element::i64, {4, count});
+ std::vector<float> weights(4 * count);
+ for (size_t i = 0; i < count; ++i) {
+ const float h = rows > 1 ? float(i / cols) * float(side - 1) / float(rows - 1) : 0.f;
+ const float w = cols > 1 ? float(i % cols) * float(side - 1) / float(cols - 1) : 0.f;
+ const size_t h0 = size_t(h), w0 = size_t(w);
+ const size_t h1 = std::min(h0 + 1, side - 1), w1 = std::min(w0 + 1, side - 1);
+ const float dh = h - float(h0), dw = w - float(w0);
+ const size_t corners[] = {h0 * side + w0, h0 * side + w1, h1 * side + w0, h1 * side + w1};
+ const float corner_weights[] = {(1 - dh) * (1 - dw), (1 - dh) * dw, dh * (1 - dw), dh * dw};
+ for (size_t k = 0; k < 4; ++k) {
+ indices.data<int64_t>()[k * count + i] = int64_t(corners[k]);
+ weights[k * count + i] = corner_weights[k];
+ }
+ }
+ const auto table = infer(pos_model, {{"input", indices}}).front();
+ for (size_t j = 0; j < count; ++j) {
+ const size_t i = size_t(order.data<const int32_t>()[j]);
+ for (size_t k = 0; k < 4; ++k)
+ for (size_t d = 0; d < embedding_width; ++d)
+ embeddings.data<float>()[j * embedding_width + d] +=
+ weights[k * count + i] * table.data<const float>()[(k * count + i) * embedding_width + d];
+ }
+
+ const auto head = metadata("clip.vision.embedding_length") / metadata("clip.vision.attention.head_count");
+ const size_t half = size_t(head / 4);
+ const auto ids = tensor("position_ids", ov::element::i32);
+ ov::Tensor rotary(ov::element::f32, {count, 2 * half});
+ for (size_t j = 0; j < count; ++j)
+ for (size_t q = 0; q < half; ++q) {
+ const float frequency = std::pow(10000.f, -float(q) / float(half));
+ rotary.data<float>()[j * 2 * half + q] = float(ids.data<const int32_t>()[j]) * frequency;
+ rotary.data<float>()[j * 2 * half + half + q] =
+ float(ids.data<const int32_t>()[count + j]) * frequency;
+ }
+ ov::Tensor mask(ov::element::f32, {1, count, count});
+ std::fill_n(mask.data<float>(), mask.get_size(), 0.f);
+ actual = infer(models.at("vision_embeddings_merger"),
+ {{"hidden_states", embeddings}, {"attention_mask", mask}, {"rotary_pos_emb", rotary}});
+ }
+ const auto expected = reference(step);
+ const auto oracle = tensor(step + "embeddings", ov::element::f32);
+ ASSERT_EQ(oracle.get_size(), expected.get_size());
+ const size_t tokens = expected.get_shape()[2], packed = expected.get_shape()[3];
+ size_t offset = 0;
+ for (const auto& output : actual) {
+ const size_t levels =
+ output.get_shape().size() == 3 && output.get_shape()[0] != 1 ? output.get_shape()[0] : 1;
+ const size_t level_width = output.get_shape().back();
+ ASSERT_EQ(output.get_size(), levels * tokens * level_width);
+ ov_gguf_test::Nmse metric, oracle_metric;
+ for (size_t level = 0; level < levels; ++level)
+ for (size_t t = 0; t < tokens; ++t)
+ for (size_t d = 0; d < level_width; ++d) {
+ const auto value = output.data<const float>()[(level * tokens + t) * level_width + d];
+ const auto index = t * packed + offset + level * level_width + d;
+ metric.add(value, expected.data<const float>()[index]);
+ oracle_metric.add(value, oracle.data<const float>()[index]);
+ }
+ ov_gguf_test::expect_nmse_below(metric, 1e-10);
+ ov_gguf_test::expect_nmse_below(oracle_metric, 1e-5);
+ offset += levels * level_width;
+ }
+ EXPECT_EQ(offset, packed);
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ Reference,
+ GGUFMMProjGenAIVisionLayout,
+ ::testing::Values("gemma3", "gemma4v", "gemma4v_one_sided", "gemma4uv", "muse-glimmer", "qwen3vl_merger"));
} // namespace