Skip to content

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

[GGUF] Move architecture-specific behavior into extensible builders (#39229)

Maxim Vafin7b74de45c140
diff --git a/.claude/skills/ov-gguf/SKILL.md b/.claude/skills/ov-gguf/SKILL.md
index d45de1907ca..a5e4f2ed5ea 100644
--- a/.claude/skills/ov-gguf/SKILL.md
+++ b/.claude/skills/ov-gguf/SKILL.md
@@ -25,11 +25,26 @@ converters; builders and validation differ. Registration or conversion alone nev
| Add or port an architecture | [architectures.md](../../../src/frontends/gguf/docs/architectures.md) and the [family contract](references/validation.md#family-contract); [extensions.md](../../../src/frontends/gguf/docs/extensions.md) when shipping it as a plugin |
| Add or replace an mmproj branch | [extensions.md](../../../src/frontends/gguf/docs/extensions.md#extend-mmproj-with-a-projector-component), then the graph contracts in [mmproj.md](../../../src/frontends/gguf/docs/mmproj.md) and [multimodal contracts](references/validation.md#multimodal-contracts) |
| Missing ggml operation or `op_case` | [how_to_add_op.md](../../../src/frontends/gguf/docs/how_to_add_op.md) |
+| Validate generated-text or quantized-model quality | [WWB validation](references/wwb.md); compare both backends against the same saved reference while preserving numerical and integration gates |
| 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) and [multimodal contracts](references/validation.md#multimodal-contracts) |
| Unsupported weight type | [quantization.md](../../../src/frontends/gguf/docs/quantization.md); the fix belongs in `src/quant/`, not a builder |
| Build, run tests, regenerate fixtures | [testing.md](../../../src/frontends/gguf/docs/testing.md) |
| Run or resume GGUF validation across OpenVINO, GenAI and llama.cpp | [validation.md](references/validation.md); use existing GHA workflows and focused local tests, preserving revisions, coverage and failures |
+| Preflight test selection, fixtures or an overlay link | [executable checks](references/preflight.md); verify required cases and link inputs before a broad batch |
+
+## Architecture ownership
+
+- Keep all architecture-specific computation and decisions under `src/builder/`: metadata schemas,
+ aliases/defaults, topology, operation selection, layouts, and architecture-specific adaptation.
+- Built-ins and `ArchitectureExtension`/`ProjectorExtension` must use the same configuration and
+ builder contracts. An extension must be able to replace or override every architecture-specific
+ behavior without editing parser, quantization, translator, or generic adaptation code.
+- Code outside `src/builder/` should be reusable between OpenVINO GenAI and the llama.cpp OpenVINO
+ backend. Consume explicit operation parameters and builder/decoder-declared model contracts;
+ do not dispatch on architecture names, projector names, or guessed model variants there.
+ Keep file-format/quantization mechanics and GGML operation semantics generic. Architecture
+ identifiers may be propagated for diagnostics, and specialized adapters belong to their builder.
## Easy to miss
@@ -44,7 +59,9 @@ converters; builders and validation differ. Registration or conversion alone nev
`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.
+ GenAI media/API integration establish different levels of support. Use the
+ [coverage helper](references/preflight.md#test-selection-and-required-fixtures) for repeated batches;
+ zero selected tests or suppressed required cases are missing coverage.
- **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.
@@ -60,8 +77,8 @@ converters; builders and validation differ. Registration or conversion alone nev
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.
+- **Long runs.** Redirect output to a file, keep the launched PID and stop only that process. Large quantized
+ MoE checkpoints can 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.
diff --git a/.claude/skills/ov-gguf/references/build-runtime.md b/.claude/skills/ov-gguf/references/build-runtime.md
index 506d944b310..ccdf7e6af4f 100644
--- a/.claude/skills/ov-gguf/references/build-runtime.md
+++ b/.claude/skills/ov-gguf/references/build-runtime.md
@@ -17,6 +17,9 @@ overlay is necessary, check the actual compile and link 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.
+- Use the [link audit](preflight.md#overlay-link-inputs) to require replacement objects exactly
+ once and reject superseded objects. Verify added test IDs in the final binary; compilation
+ alone does not establish that a test was linked.
- 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.
diff --git a/.claude/skills/ov-gguf/references/preflight.md b/.claude/skills/ov-gguf/references/preflight.md
new file mode 100644
index 00000000000..b584c6345c4
--- /dev/null
+++ b/.claude/skills/ov-gguf/references/preflight.md
@@ -0,0 +1,101 @@
+# Executable validation preflight
+
+Use these helpers for repeated batches or fragile overlays, alongside the existing test
+harness. They check coverage and link inputs; numerical gates remain in the tests.
+Save every attempt outside the checkout. Run scripts with Python 3.9 or newer.
+In the examples, `skill_scripts` points to this skill's `scripts/` directory and
+`validation_reports` to the task's artifact directory outside the checkout.
+
+## Compiler warning policy
+
+Match the relevant CI warning configuration when compiling changed frontend code and tests,
+including `CMAKE_COMPILE_WARNING_AS_ERROR` where enabled. Record the compiler and effective
+flags; a successful run on one toolchain does not establish another's buildability. Brace
+conditional assertion macros and use checked or known-safe integer conversions in tensor writes.
+
+## Test selection and required fixtures
+
+Capture `--gtest_list_tests` from the actual binary with the same filter and environment
+as the subsequent run. Check its exit code before using the listing. Define a contract
+with exact IDs or glob patterns (`*`, `?`, `[abc]`), required counts and absolute fixture paths:
+
+Example contract; replace the patterns, counts and paths with the requested scenarios:
+
+```json
+{
+ "selections": [
+ {"pattern": "*", "count": 2},
+ {"pattern": "DecoderChecks.PrefillAndCachedDecode", "count": 1},
+ {"pattern": "EmbeddingChecks.TokenLookup", "count": 1}
+ ],
+ "required_files": ["/task/fixtures/decoder.npz"],
+ "allowed_skips": []
+}
+```
+
+Use counts established from the requested scenarios, not counts copied from an incomplete
+listing. Include a `*` selection when the total must be exact. Overlapping selections are
+independent checks. Allowed skips apply only to optional coverage; required scenarios that
+skip remain incomplete. File presence does not establish fixture validity or model identity.
+
+```bash
+python "$skill_scripts/check_test_coverage.py" --contract "$validation_reports/coverage.json" \
+ --listing "$validation_reports/selected-tests.txt" --output "$validation_reports/preflight.json"
+```
+
+After execution, retain the test process exit code and summarize its XML using the helper
+from this skill revision. The JSON includes selected IDs, excluding suppressed/notrun
+cases. GTest IDs are `classname.name`; pytest IDs use the XML's corresponding names.
+
+```bash
+python "$skill_scripts/summarize_tests.py" "$validation_reports/tests.xml" \
+ --output "$validation_reports/test-summary.json" --process-exit 0
+python "$skill_scripts/check_test_coverage.py" --contract "$validation_reports/coverage.json" \
+ --listing "$validation_reports/selected-tests.txt" --summary "$validation_reports/test-summary.json" \
+ --output "$validation_reports/coverage-result.json"
+```
+
+Replace `0` with the recorded process exit code. Summary-only checks can be used for pytest
+with contracts derived from its XML IDs. With both inputs, listed and executed ID multisets
+must match. Missing cases, duplicate cases, unexpected skips, suite/test failures and missing
+or nonzero process status fail the coverage check. It does not replace runtime identity or
+prove that a stale XML file belongs to the attempt: use unique paths and preserve input hashes.
+
+## Overlay link inputs
+
+Prefer normal CMake/Ninja targets. If an overlay is necessary, save its actual single
+compiler-driver link command using POSIX shell quoting in a text file. List the required replacement objects and
+superseded objects that must be absent:
+
+```json
+{
+ "required_objects": ["/task/overlay/translation-unit.o"],
+ "forbidden_objects": ["/task/base/translation-unit.o"]
+}
+```
+
+```bash
+python "$skill_scripts/audit_link.py" --command-file "$validation_reports/link-command.txt" \
+ --directory /task/build --contract "$validation_reports/link-contract.json" \
+ --output "$validation_reports/link-audit.json"
+```
+
+The helper reads but never executes the command. It expands response files relative to the
+link working directory, canonicalizes object paths, rejects duplicate/missing/forbidden
+objects and refuses shell command sequences or unresolved shell expansions (parameters,
+globs, braces and tildes). Record expanded arguments; the helper never evaluates shell
+expressions. Single-quote or escape literal shell characters, for example `'$ORIGIN'` in
+a linker rpath. Response-file contents are parsed as literal arguments without shell
+expansion. Supply the inner compiler command when a
+wrapper prints `cd ... && ...`; do not pass a build script. Full findings stay in JSON;
+the printed summary is bounded. A passing link audit does not prove objects are freshly
+compiled, dependency-complete or present inside archives. Rebuild all translation units
+affected by headers/macros using build dependencies, then verify new case registration
+and [runtime identity](build-runtime.md) separately.
+
+Both checks return nonzero on violated contracts or malformed inputs. The XML summarizer
+returns parsing status only. Exercise the helpers with:
+
+```bash
+python -m unittest discover -s "$skill_scripts/tests" -v
+```
diff --git a/.claude/skills/ov-gguf/references/validation.md b/.claude/skills/ov-gguf/references/validation.md
index 89dc313f44e..bd0fdaf0c3c 100644
--- a/.claude/skills/ov-gguf/references/validation.md
+++ b/.claude/skills/ov-gguf/references/validation.md
@@ -17,6 +17,11 @@ an unimplemented contract remains outstanding work, not an implicit scope reduct
Test layout-sensitive recurrent paths with batching early, alongside single-sequence numerics.
Include multiple heads/tokens and unequal Q/KV dimensions where applicable.
+Complete a coherent family stage before expanding implementation, preserving remaining
+contracts in the manifest. Exercise the actual consumer constructor and a small prefill/decode
+early, including draft/target pairing or media insertion when applicable. Test default settings
+and supported overrides; conversion and factory fixtures do not exercise consumer restrictions.
+
## Multimodal contracts
Before connecting generation, record the pinned reference contract for each requested
@@ -46,6 +51,10 @@ incremental builds, multiple worktrees or dispatched CPU kernels.
Use one reusable runner and task manifest, extending the existing harness where available.
Update the manifest at milestones and input/environment changes; retain commands, completed
checks, failure signatures and the next diagnostic so handoffs can resume without full logs.
+Diagnose the first differing boundary on identical inputs and record the predicted observation
+before each experiment. Reassess the boundary, reference and loaded runtime after repeated
+unchanged or inconclusive attempts before another sweep. Keep failed numerical results and
+assess generated-text quality with [WWB](wwb.md) separately when that evaluation is requested.
Specify selected scenarios, per-case environments, expected test counts and allowed skips,
existing numerical metrics/tolerances, timeouts and artifact paths. Keep runtime identity,
completed cases and failed attempts in its reports; preserve the tests' acceptance gates
@@ -62,10 +71,11 @@ 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.
+Inspect tensor types rather than checkpoint names: a nominal quantization can contain mixed
+weight types. Validate the requested original checkpoint; substituting another quantization
+creates a different fixture. When quantization-quality evaluation is requested, compare both
+backends with the same original-weight floating reference using [WWB](wwb.md). Retain the
+original numerical gates and failures.
Use the pinned quantizer to create or exactly expand fixtures when needed,
preserving hashes, conversion revision/options and tensor inventory.
@@ -87,6 +97,7 @@ unfiltered unit suite. Record precision, KV precision and activation quantizatio
| Scenario | Zero-point setting | Acceptance |
|---|---|---|
| Unfiltered frontend unit suite | Unset `OV_GGUF_Q4_K_ZP_F16` | Default test expectations, required fixtures and op coverage |
+| Generated-text quality / WWB | Use and record the selected checkpoint environment | [Same-reference quality comparison](wwb.md); numerical and integration gates remain separate |
| Strict quantized checkpoint comparison | `OV_GGUF_Q4_K_ZP_F16=1` | Original full-logit or feature parity gate |
| Represented-F32 diagnostic | Explicit environment and tensor-type inventory | Arithmetic isolation; does not replace quantized parity |
@@ -111,15 +122,12 @@ 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.
+Document intentional consumer/reference differences in the applicable frontend guide and
+retain affected comparisons with their original gates. Report SDPA/PA agreement and API
+compatibility separately; distinguish semantic mismatches from quantization differences.
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.
+prefill does not establish cache-reuse correctness. Keep default-cache failures separate
+from results using explicitly disabled caches.
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
@@ -147,6 +155,11 @@ 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.
+Before repeated local batches, check selected IDs/counts and required fixtures with the
+[coverage preflight](preflight.md#test-selection-and-required-fixtures). Retain post-run coverage
+checks too: an absent or suppressed required test remains missing coverage even with exit zero.
+Audit overlay link inputs when using a custom link command.
+
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
diff --git a/.claude/skills/ov-gguf/references/wwb.md b/.claude/skills/ov-gguf/references/wwb.md
new file mode 100644
index 00000000000..a4ec55905a2
--- /dev/null
+++ b/.claude/skills/ov-gguf/references/wwb.md
@@ -0,0 +1,59 @@
+# Generated-text quality with WWB
+
+Use WhoWhatBench (WWB) when generated-text quality or quantization loss is part of the task.
+Keep numerical parity, operation/layout, state/cache and API acceptance separate. Text quality
+scores do not validate projector, media or speech-output contracts and do not waive an existing
+numerical gate.
+
+## Reference and comparison
+
+For quantization-quality evaluation, use the same saved reference answers from original
+prequantization floating weights for both backends. A pinned publisher floating GGUF or an HF
+export can supply that reference. An expansion of quantized values isolates arithmetic and
+cannot measure loss against original weights. Record reference ancestry, immutable revisions,
+file hashes, conversion options and tensor-type inventories; verify architecture, tensor shapes
+and tokenizer tables agree.
+
+Generate native llama.cpp and GenAI answers using the exact same requested quantized file and
+score them against that saved reference. Pin WWB, the metric and any scoring encoder revision.
+Check the installed CLI/backend capabilities before a batch. Semantic similarity measures
+agreement with reference answers, not percentage correctness; choose metrics and material-loss
+criteria appropriate to the task before inspecting results.
+
+Use representative prompts for the requested languages/tasks and enough generation to expose
+drift. Record prompt provenance/count and token limits. Preflight one prompt through generation
+and scoring; verify identical-answer scoring reaches the metric's expected maximum. A short
+teacher-forced replay does not establish free-running quality.
+
+## Inputs and execution
+
+Audit prompt token IDs and stopping behavior first. Match rendered template bytes, special-token
+policy, EOG IDs, context, sampling/penalties, attention and KV precision, and record arithmetic
+settings independently. For strict CPU comparisons use the established F32 inference and
+disabled dynamic-quantization settings. Set checkpoint-specific zero-point modes before launch;
+keep them unset for the unfiltered unit suite.
+
+If default string-input paths differ, retain that failure and label any comparison using matched
+encoded inputs. Also test the supported default path for affected prompts; forced inputs alone
+do not establish tokenizer or API parity. Start each independent prompt with fresh state.
+
+Save reference and backend answers as CSVs with `prompts,answers`; verify equal row counts,
+prompt strings and row order before scoring. Use a compatible pinned WWB adapter or a native
+helper built against the pinned backend headers. If scoring dependencies differ from inference,
+use an isolated environment and record the actual metric entrypoint without changing it.
+
+Keep fixtures and runtime stable. Reuse saved answers only when model, prompt, generation and
+runtime evidence match; record reused and regenerated counts. An input-path or stop-policy
+change also requires evidence that saved answers remain valid. Keep separate attempt outputs.
+
+## Report
+
+Report both backend scores against the same reference, their gap, and per-prompt results.
+Inspect low-score answers and large gaps for incoherence, repetition, task failure or truncation.
+State the tested checkpoint, device, quantization, configuration, prompt count and token limit.
+Retain answers, token histories, scoring inputs, commands and runtime/model hashes.
+
+Report numerical parity, quality and integration outcomes independently. Preserve failures and
+missing coverage; similar text scores do not establish image/audio, long-context or another
+device's behavior. Apply the task's agreed acceptance criteria rather than inventing a universal
+threshold or requiring identical free-running tokens.
diff --git a/.claude/skills/ov-gguf/scripts/audit_link.py b/.claude/skills/ov-gguf/scripts/audit_link.py
new file mode 100644
index 00000000000..ee953f4d538
--- /dev/null
+++ b/.claude/skills/ov-gguf/scripts/audit_link.py
@@ -0,0 +1,363 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""Audit a recorded compiler link command without executing it."""
+
+import argparse
+from collections import Counter
+import json
+import os
+from pathlib import Path
+import shlex
+import sys
+
+
+OBJECT_SUFFIXES = (".o", ".obj")
+MAX_RESPONSE_DEPTH = 128
+OUTPUT_OPTIONS = {"-o", "--output"}
+PATH_OPTIONS = {
+ "-D", "-I", "-L", "-MF", "-MT", "-MQ", "-T", "-U",
+ "--Map", "--dynamic-linker", "--entry", "--output", "--rpath",
+ "--rpath-link", "--script", "--soname", "--sysroot", "--undefined",
+ "-dynamic-linker", "-e", "-include", "-imacros", "-isystem",
+ "-isysroot", "-iquote", "-idirafter", "-Map", "-rpath", "-rpath-link",
+ "-soname", "-u", "-z",
+}
+
+
+class AuditInputError(ValueError):
+ pass
+
+
+def canonical_path(value, directory):
+ path = Path(value)
+ if not path.is_absolute():
+ path = directory / path
+ return path.resolve()
+
+
+def aliases(first, second):
+ if first.resolve() == second.resolve():
+ return True
+ try:
+ return os.path.samefile(first, second)
+ except OSError:
+ return False
+
+
+def parse_command(command):
+ tokens = []
+ token = []
+ started = False
+ quote = None
+ index = 0
+ operators = ";&|<>()"
+ while index < len(command):
+ char = command[index]
+ if quote == "'":
+ if char == "'":
+ quote = None
+ else:
+ token.append(char)
+ index += 1
+ continue
+ if char == "\\":
+ if index + 1 == len(command):
+ raise AuditInputError("cannot parse command text: trailing escape")
+ escaped = command[index + 1]
+ if quote == '"' and escaped not in '$`"\\\n':
+ token.append(char)
+ index += 1
+ continue
+ if escaped != "\n":
+ token.append(escaped)
+ started = True
+ index += 2
+ continue
+ if quote == '"':
+ if char == '"':
+ quote = None
+ elif char == "`" or (char == "$" and index + 1 < len(command) and command[index + 1] == "("):
+ raise AuditInputError("command substitution is not allowed")
+ elif char == "$":
+ raise AuditInputError("shell parameter expansion is not allowed; record literal arguments")
+ else:
+ token.append(char)
+ index += 1
+ continue
+ if char in "'\"":
+ quote = char
+ started = True
+ elif char == "#" and not started:
+ newline = command.find("\n", index)
+ if newline < 0:
+ break
+ index = newline
+ continue
+ elif char == "`" or (char == "$" and index + 1 < len(command) and command[index + 1] == "("):
+ raise AuditInputError("command substitution is not allowed")
+ elif char == "$":
+ raise AuditInputError("shell parameter expansion is not allowed; record literal arguments")
+ elif char in "*?[{}~":
+ raise AuditInputError(
+ "shell pathname, brace and tilde expansions are not allowed; record literal arguments"
+ )
+ elif char in operators:
+ raise AuditInputError("shell operators and multiple commands are not allowed")
+ elif char == "\n" and command[index + 1 :].strip():
+ raise AuditInputError("multiple shell commands are not allowed")
+ elif char in " \t\n":
+ if started:
+ tokens.append("".join(token))
+ token = []
+ started = False
+ else:
+ token.append(char)
+ started = True
+ index += 1
+ if quote:
+ raise AuditInputError("cannot parse command text: unterminated quote")
+ if started:
+ tokens.append("".join(token))
+ if not tokens:
+ raise AuditInputError("command text is empty")
+ return tokens
+
+
+def normalize_linker_tokens(tokens):
+ normalized = []
+ index = 0
+ while index < len(tokens):
+ token = tokens[index]
+ if token == "-Xlinker":
+ if index + 1 >= len(tokens):
+ raise AuditInputError("-Xlinker is missing its argument")
+ normalized.append(tokens[index + 1])
+ index += 2
+ continue
+ if token.startswith("-Wl,"):
+ normalized.extend(part for part in token[4:].split(",") if part)
+ else:
+ normalized.append(token)
+ index += 1
+ return normalized
+
+
+def load_contract(path, directory):
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, json.JSONDecodeError) as error:
+ raise AuditInputError(f"cannot read contract JSON: {error}")
+ if not isinstance(data, dict):
+ raise AuditInputError("contract must be a JSON object")
+ if "required_objects" not in data:
+ raise AuditInputError("contract is missing required_objects")
+ required = data["required_objects"]
+ forbidden = data.get("forbidden_objects")
+ if not isinstance(required, list) or not required:
+ raise AuditInputError("required_objects must be a nonempty list of object paths")
+ if not isinstance(forbidden, list):
+ raise AuditInputError("forbidden_objects must be a list of object paths")
+
+ result = {}
+ for key, values in (("required_objects", required), ("forbidden_objects", forbidden)):
+ paths = []
+ for value in values:
+ if not isinstance(value, str) or not value.strip():
+ raise AuditInputError(f"{key} entries must be nonempty path strings")
+ path_value = canonical_path(value, directory)
+ if path_value.suffix not in OBJECT_SUFFIXES:
+ raise AuditInputError(f"{key} entry is not an .o/.obj path: {value}")
+ paths.append(str(path_value))
+ if len(paths) != len(set(paths)):
+ raise AuditInputError(f"{key} contains duplicate paths")
+ result[key] = paths
+ overlap = sorted(set(result["required_objects"]) & set(result["forbidden_objects"]))
+ if overlap:
+ raise AuditInputError(f"objects cannot be both required and forbidden: {overlap[0]}")
+ return result
+
+
+def expand_responses(tokens, directory, responses, stack=()):
+ expanded = []
+ for token in normalize_linker_tokens(tokens):
+ if not token.startswith("@"):
+ expanded.append(token)
+ continue
+ name = token[1:]
+ if not name:
+ raise AuditInputError("response-file reference has an empty path")
+ response = canonical_path(name, directory)
+ responses.add(response)
+ if response in stack:
+ chain = " -> ".join(str(item) for item in stack + (response,))
+ raise AuditInputError(f"response-file cycle: {chain}")
+ if len(stack) >= MAX_RESPONSE_DEPTH:
+ raise AuditInputError(f"response-file nesting exceeds {MAX_RESPONSE_DEPTH} levels")
+ try:
+ contents = response.read_text(encoding="utf-8")
+ except (OSError, UnicodeError) as error:
+ raise AuditInputError(f"cannot read response file {response}: {error}")
+ try:
+ nested = shlex.split(contents, comments=False, posix=True)
+ except ValueError as error:
+ raise AuditInputError(f"cannot parse response file {response}: {error}")
+ expanded.extend(expand_responses(nested, directory, responses, stack + (response,)))
+ return expanded
+
+
+def object_occurrences(tokens, directory):
+ objects = []
+ skip_next = False
+ for token in tokens:
+ if skip_next:
+ skip_next = False
+ continue
+ if token in PATH_OPTIONS:
+ skip_next = True
+ continue
+ if token in OUTPUT_OPTIONS:
+ skip_next = True
+ continue
+ if token.startswith("-") or not token.endswith(OBJECT_SUFFIXES):
+ continue
+ objects.append(str(canonical_path(token, directory)))
+ return Counter(objects)
+
+
+def audit(command_file, contract_file, directory, output_file):
+ report = {
+ "passed": False,
+ "cwd": str(directory),
+ "command_file": str(command_file.resolve()),
+ "contract_file": str(contract_file.resolve()),
+ "output": str(output_file.resolve()),
+ "counts": {"command_tokens": 0, "expanded_tokens": 0, "response_files": 0,
+ "object_occurrences": 0, "unique_objects": 0},
+ "objects": [],
+ "response_files": [],
+ "violations": [],
+ "parse_errors": [],
+ "scope": (
+ "Checks only recorded object paths; does not establish source/header dependencies "
+ "or runtime loaded identity."
+ ),
+ }
+ inputs = {command_file.resolve(), contract_file.resolve()}
+ responses = set()
+ response_discovery_complete = False
+
+ try:
+ if not directory.is_dir():
+ raise AuditInputError(f"working directory is not a directory: {directory}")
+ raw_command = command_file.read_text(encoding="utf-8")
+ command_tokens = parse_command(raw_command)
+ report["counts"]["command_tokens"] = len(command_tokens)
+ expanded = expand_responses(command_tokens, directory, responses)
+ response_discovery_complete = True
+ report["counts"]["expanded_tokens"] = len(expanded)
+ report["counts"]["response_files"] = len(responses)
+ report["response_files"] = sorted(str(path) for path in responses)
+ counts = object_occurrences(expanded, directory)
+ inputs.update(Path(path) for path in counts)
+ report["counts"]["object_occurrences"] = sum(counts.values())
+ report["counts"]["unique_objects"] = len(counts)
+ report["objects"] = [{"path": path, "count": count} for path, count in sorted(counts.items())]
+ contract = load_contract(contract_file, directory)
+
+ for path, count in sorted(counts.items()):
+ if count > 1:
+ report["violations"].append({
+ "kind": "duplicate_object",
+ "path": path,
+ "count": count,
+ "message": f"object appears {count} times: {path}",
+ })
+ for path in contract["required_objects"]:
+ count = counts[path]
+ if count != 1:
+ report["violations"].append({
+ "kind": "required_object_count",
+ "path": path,
+ "expected": 1,
+ "actual": count,
+ "message": f"required object appears {count} times; expected exactly once: {path}",
+ })
+ for path in contract["forbidden_objects"]:
+ count = counts[path]
+ if count:
+ report["violations"].append({
+ "kind": "forbidden_object",
+ "path": path,
+ "actual": count,
+ "message": f"forbidden object appears {count} times: {path}",
+ })
+ except (ValueError, OSError, UnicodeError, RuntimeError) as error:
+ report["parse_errors"].append(str(error))
+ inputs.update(responses)
+ report["counts"]["response_files"] = len(responses)
+ report["response_files"] = sorted(str(path) for path in responses)
+
+ report["passed"] = not report["violations"] and not report["parse_errors"]
+ return report, inputs, response_discovery_complete
+
+
+def write_report(requested, report, inputs):
+ destination = requested.resolve()
+ collision = any(aliases(destination, path) for path in inputs)
+ if collision:
+ report["parse_errors"].append("output path aliases an input file")
+ report["passed"] = False
+ return None
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ report["output"] = str(destination)
+ destination.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ return destination
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--command-file", required=True, type=Path)
+ parser.add_argument("--directory", required=True, type=Path)
+ parser.add_argument("--contract", required=True, type=Path)
+ parser.add_argument("--output", required=True, type=Path)
+ args = parser.parse_args(argv)
+
+ directory = args.directory.resolve()
+ command_file = args.command_file.resolve()
+ contract_file = args.contract.resolve()
+ output_file = args.output.resolve()
+ report, inputs, response_discovery_complete = audit(
+ command_file, contract_file, directory, output_file
+ )
+ destination = (
+ write_report(output_file, report, inputs)
+ if response_discovery_complete else None
+ )
+ first_violations = report["violations"][:5]
+ remaining = max(0, 5 - len(first_violations))
+ first_violations.extend(
+ {"kind": "parse_error", "message": issue}
+ for issue in report["parse_errors"][:remaining]
+ )
+ summary = {
+ "passed": report["passed"],
+ "counts": report["counts"],
+ "violations": len(report["violations"]),
+ "parse_errors": len(report["parse_errors"]),
+ "first_violations": first_violations,
+ "omitted_violations": max(0, len(report["violations"]) + len(report["parse_errors"]) - 5),
+ "details": str(destination) if destination else None,
+ }
+ if destination is None:
+ summary["output_refused"] = str(output_file)
+ if not response_discovery_complete:
+ summary["output_refusal_reason"] = "response-file discovery was incomplete"
+ print(json.dumps(summary, sort_keys=True))
+ if report["parse_errors"]:
+ return 2
+ return 0 if report["passed"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.claude/skills/ov-gguf/scripts/check_test_coverage.py b/.claude/skills/ov-gguf/scripts/check_test_coverage.py
new file mode 100644
index 00000000000..e352b8759e2
--- /dev/null
+++ b/.claude/skills/ov-gguf/scripts/check_test_coverage.py
@@ -0,0 +1,169 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""Check selected GTest IDs and fixture prerequisites before/after a validation batch."""
+
+import argparse
+from collections import Counter
+from fnmatch import fnmatchcase
+import json
+import os
+from pathlib import Path
+
+
+def listed_ids(text):
+ suite = None
+ result = []
+ for line in text.splitlines():
+ value = line.split("#", 1)[0].strip()
+ if not value:
+ continue
+ if not line[0].isspace():
+ suite = value if value.endswith(".") and " " not in value else None
+ elif suite and " " not in value:
+ result.append(suite + value)
+ return result
+
+
+def aliases(first, second):
+ try:
+ if first.resolve() == second.resolve():
+ return True
+ except (OSError, RuntimeError, ValueError) as error:
+ raise ValueError(f"cannot safely resolve path {first}: {error}") from error
+ try:
+ return os.path.samefile(first, second)
+ except (FileNotFoundError, NotADirectoryError):
+ return False
+ except (OSError, ValueError) as error:
+ raise ValueError(f"cannot safely compare paths {first} and {second}: {error}") from error
+
+
+def check(contract, listing=None, summary=None):
+ selections = contract.get("selections")
+ if not isinstance(selections, list) or not selections:
+ raise ValueError("contract requires nonempty selections")
+ for selection in selections:
+ if (not isinstance(selection, dict) or not isinstance(selection.get("pattern"), str)
+ or not selection["pattern"] or type(selection.get("count")) is not int
+ or selection["count"] < 1):
+ raise ValueError("each selection requires a pattern and positive integer count")
+ for key in ("allowed_skips", "required_files"):
+ values = contract.get(key, [])
+ if not isinstance(values, list) or any(not isinstance(value, str) or not value for value in values):
+ raise ValueError(key + " must contain nonempty strings")
+ violations = []
+ ids = listed_ids(listing) if listing is not None else None
+ if ids is not None:
+ if not ids:
+ violations.append("listing selected zero tests")
+ for name, count in Counter(ids).items():
+ if count != 1:
+ violations.append("duplicate listed ID: " + name)
+ executed, skipped = [], []
+ if summary is not None:
+ if type(summary.get("process_exit")) is not int or summary["process_exit"] != 0:
+ violations.append("test process exit is missing or nonzero")
+ if summary.get("parse_errors"):
+ violations.append("test summary has XML parse errors")
+ reports = summary.get("reports")
+ if not isinstance(reports, list) or not reports:
+ raise ValueError("summary requires nonempty reports")
+ for report in reports:
+ names = report["selected_ids"]
+ if not isinstance(names, list) or any(not isinstance(name, str) or not name for name in names):
+ raise ValueError("selected_ids must contain nonempty strings")
+ if report["counts"].get("selected") != len(names):
+ raise ValueError("selected count and IDs disagree")
+ if report.get("suite_errors"):
+ violations.append("test report has suite errors")
+ executed.extend(names)
+ skipped.extend(item["id"] for item in report["skips"])
+ if report["counts"].get("failed", 0) or report["counts"].get("errors", 0):
+ violations.append("test report has failed cases")
+ if not executed:
+ violations.append("test reports selected zero tests")
+ for name, count in Counter(executed).items():
+ if count != 1:
+ violations.append("duplicate executed ID: " + name)
+ if ids is not None and Counter(ids) != Counter(executed):
+ violations.append("listed and executed IDs differ")
+ for name in skipped:
+ if name not in executed:
+ raise ValueError("skipped ID absent from selected IDs")
+ if not any(fnmatchcase(name, pattern) for pattern in contract.get("allowed_skips", [])):
+ violations.append("unexpected skip: " + name)
+ stages = {"listed": ids, "executed": executed if summary is not None else None}
+ counts = {}
+ for stage, names in stages.items():
+ if names is None:
+ continue
+ counts[stage] = len(names)
+ for selection in selections:
+ count = sum(fnmatchcase(name, selection["pattern"]) for name in names)
+ if count != selection["count"]:
+ violations.append(f"{stage} {selection['pattern']}: expected {selection['count']}, got {count}")
+ missing = [name for name in contract.get("required_files", []) if not Path(name).is_file()]
+ violations.extend("missing required file: " + name for name in missing)
+ return {"counts": counts, "listed_ids": ids, "executed_ids": executed,
+ "skipped_ids": skipped, "violations": violations}
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--contract", required=True, type=Path)
+ parser.add_argument("--listing", type=Path, help="Output of the actual filtered binary --gtest_list_tests")
+ parser.add_argument("--summary", type=Path, help="Full summarize_tests.py JSON from this attempt")
+ parser.add_argument("--output", required=True, type=Path)
+ args = parser.parse_args()
+ if args.listing is None and args.summary is None:
+ parser.error("provide --listing and/or --summary")
+ inputs = [path for path in (args.contract, args.listing, args.summary) if path is not None]
+
+ def refuse_output(reason):
+ print(json.dumps({"counts": {}, "violations": [reason], "omitted_violations": 0,
+ "details": None, "output_refused": True, "reason": reason}))
+ return 2
+
+ try:
+ if any(aliases(args.output, path) for path in inputs):
+ return refuse_output("output must not overwrite an input")
+ except ValueError as error:
+ return refuse_output(str(error))
+ try:
+ contract = json.loads(args.contract.read_text())
+ except (OSError, ValueError) as error:
+ return refuse_output("cannot read or parse contract: " + str(error))
+ if not isinstance(contract, dict):
+ return refuse_output("contract must be an object")
+ required_files = contract.get("required_files", [])
+ if (not isinstance(required_files, list)
+ or any(not isinstance(name, str) or not name for name in required_files)):
+ return refuse_output("required_files must contain nonempty strings")
+ fixture_paths = [Path(name) for name in required_files]
+ try:
+ for path in fixture_paths:
+ if aliases(path, args.output):
+ return refuse_output("output must not overwrite a required fixture")
+ except ValueError as error:
+ return refuse_output(str(error))
+ if any(not path.is_absolute() for path in fixture_paths):
+ return refuse_output("required_files must use absolute paths")
+ try:
+ result = check(contract, args.listing.read_text() if args.listing else None,
+ json.loads(args.summary.read_text()) if args.summary else None)
+ except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
+ result = {"counts": {}, "violations": [str(error)], "input_error": True}
+ result["inputs"] = {"path": str(args.contract.resolve()),
+ "listing": str(args.listing.resolve()) if args.listing else None,
+ "summary": str(args.summary.resolve()) if args.summary else None}
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(json.dumps(result, indent=2) + "\n")
+ print(json.dumps({"counts": result["counts"], "violations": result["violations"][:5],
+ "omitted_violations": max(0, len(result["violations"]) - 5),
+ "details": str(args.output.resolve())}))
+ return 2 if result.get("input_error") else 1 if result["violations"] else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.claude/skills/ov-gguf/scripts/runtime_identity.py b/.claude/skills/ov-gguf/scripts/runtime_identity.py
index 2c4dc852cf2..1a32cbe644c 100644
--- a/.claude/skills/ov-gguf/scripts/runtime_identity.py
+++ b/.claude/skills/ov-gguf/scripts/runtime_identity.py
@@ -14,18 +14,17 @@ import re
def record_identity(expected, output, pid=None):
pid = os.getpid() if pid is None else int(pid)
report = {"pid": pid, "expected": expected, "mapped_libraries": [], "errors": []}
+ protected = (
+ [entry.get("path") for entry in expected.values() if isinstance(entry, dict)]
+ if isinstance(expected, dict) else []
+ )
+ mapped = {}
try:
- libraries = {}
- for label, entry in expected.items():
- path = Path(entry["path"])
- digest = entry["sha256"]
- if not path.is_absolute() or not re.fullmatch(r"[0-9a-fA-F]{64}", digest):
- raise ValueError(f"{label}: expected an absolute path and SHA-256")
- libraries[label] = (path.resolve(strict=True), digest.lower())
- if not libraries:
- raise ValueError("expected library manifest is empty")
- expected_names = {path.name for path, _ in libraries.values()}
- mapped = {}
+ expected_names = set()
+ for name in protected:
+ if isinstance(name, (str, os.PathLike)):
+ path = Path(name)
+ expected_names.update((path.name, path.resolve().name))
for line in Path(f"/proc/{pid}/maps").read_text().splitlines():
fields = line.split(maxsplit=5)
if len(fields) != 6 or not fields[5].startswith("/"):
@@ -35,13 +34,41 @@ def record_identity(expected, output, pid=None):
path = Path(name.removesuffix(" (deleted)"))
if path.name.startswith("libopenvino") or path.name in expected_names:
mapped[path.resolve()] = deleted
+ except (OSError, ValueError, RuntimeError) as error:
+ raise RuntimeError(f"cannot discover mapped libraries; refusing report output: {error}") from error
+ output_path = Path(output)
+ protected.extend(mapped)
+ for name in protected:
+ if not isinstance(name, (str, os.PathLike)):
+ continue
+ library_path = Path(name)
+ same_file = output_path.resolve() == library_path.resolve()
+ if output_path.exists() and library_path.exists():
+ same_file = same_file or os.path.samefile(output_path, library_path)
+ if same_file:
+ raise ValueError("output must not overwrite an expected or mapped library")
+ report["mapped_libraries"] = [
+ {"path": str(path), "sha256": None, "deleted": deleted}
+ for path, deleted in sorted(mapped.items())
+ ]
+ try:
+ if not isinstance(expected, dict):
+ raise ValueError("expected library manifest must be an object")
+ libraries = {}
+ for label, entry in expected.items():
+ path = Path(entry["path"])
+ digest = entry["sha256"]
+ if not path.is_absolute() or not re.fullmatch(r"[0-9a-fA-F]{64}", digest):
+ raise ValueError(f"{label}: expected an absolute path and SHA-256")
+ libraries[label] = (path.resolve(strict=True), digest.lower())
+ if not libraries:
+ raise ValueError("expected library manifest is empty")
hashes = {}
- for path, deleted in sorted(mapped.items()):
- digest = None if deleted else hashlib.sha256(path.read_bytes()).hexdigest()
+ for entry in report["mapped_libraries"]:
+ path = Path(entry["path"])
+ digest = None if entry["deleted"] else hashlib.sha256(path.read_bytes()).hexdigest()
hashes[path] = digest
- report["mapped_libraries"].append(
- {"path": str(path), "sha256": digest, "deleted": deleted}
- )
+ entry["sha256"] = digest
for label, (path, digest) in libraries.items():
if path not in hashes:
report["errors"].append(f"{label}: expected library is not mapped: {path}")
@@ -50,7 +77,7 @@ def record_identity(expected, output, pid=None):
except (OSError, KeyError, TypeError, ValueError) as error:
report["errors"].append(str(error))
report["passed"] = not report["errors"]
- Path(output).write_text(json.dumps(report, indent=2) + "\n")
+ output_path.write_text(json.dumps(report, indent=2) + "\n")
if not report["passed"]:
raise RuntimeError("; ".join(report["errors"]))
return report
@@ -62,6 +89,11 @@ def main():
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--pid", type=int, default=os.getpid())
args = parser.parse_args()
+ same_file = args.output.resolve() == args.expected.resolve()
+ if args.output.exists() and args.expected.exists():
+ same_file = same_file or os.path.samefile(args.output, args.expected)
+ if same_file:
+ parser.error("output must not overwrite the expected library manifest")
record_identity(json.loads(args.expected.read_text()), args.output, args.pid)
diff --git a/.claude/skills/ov-gguf/scripts/summarize_tests.py b/.claude/skills/ov-gguf/scripts/summarize_tests.py
index b4230f8df9d..45967140c86 100644
--- a/.claude/skills/ov-gguf/scripts/summarize_tests.py
+++ b/.claude/skills/ov-gguf/scripts/summarize_tests.py
@@ -6,6 +6,7 @@
import argparse
from collections import Counter
import json
+import os
from pathlib import Path
import re
import xml.etree.ElementTree as ET
@@ -17,19 +18,29 @@ def signature(message):
return " ".join((useful or lines)[:2])[:320] or "No message provided"
+def aliases(first, second):
+ if first.resolve() == second.resolve():
+ return True
+ try:
+ return os.path.samefile(first, second)
+ except OSError:
+ return False
+
+
def summarize(path):
root = ET.parse(path).getroot()
for node in root.iter():
node.tag = node.tag.rsplit("}", 1)[-1]
cases = list(root.iter("testcase"))
counts = Counter(selected=0, passed=0, failed=0, errors=0, skipped=0, not_run=0)
- failures, skips = [], []
+ failures, skips, selected_ids = [], [], []
for case in cases:
if case.get("status") == "notrun" or case.get("result") == "suppressed":
counts["not_run"] += 1
continue
counts["selected"] += 1
name = ".".join(filter(None, (case.get("classname"), case.get("name"))))
+ selected_ids.append(name)
errors = case.findall("error")
failed = case.findall("failure")
skipped = case.findall("skipped")
@@ -45,7 +56,7 @@ def summarize(path):
for node in list(suite)
if node.tag in ("failure", "error")
]
- return {"path": str(path.resolve()), "counts": dict(counts), "failures": failures,
+ return {"path": str(path.resolve()), "counts": dict(counts), "selected_ids": selected_ids, "failures": failures,
"skips": skips, "suite_errors": suite_errors}
@@ -55,7 +66,7 @@ def main():
parser.add_argument("--output", required=True, type=Path, help="Full JSON details; must differ from input reports")
parser.add_argument("--process-exit", type=int, help="Recorded exit code of the test process")
args = parser.parse_args()
- if args.output.resolve() in {path.resolve() for path in args.reports}:
+ if any(aliases(args.output, path) for path in args.reports):
parser.error("output must not overwrite an input report")
reports, errors = [], []
for path in args.reports:
diff --git a/.claude/skills/ov-gguf/scripts/tests/test_audit_link.py b/.claude/skills/ov-gguf/scripts/tests/test_audit_link.py
new file mode 100644
index 00000000000..9f8df08317a
--- /dev/null
+++ b/.claude/skills/ov-gguf/scripts/tests/test_audit_link.py
@@ -0,0 +1,287 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+
+SCRIPT = Path(__file__).resolve().parents[1] / "audit_link.py"
+
+
+class AuditLinkTest(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.root = Path(self.temp.name)
+ self.cwd = self.root / "build"
+ self.cwd.mkdir()
+ self.command = self.root / "command.txt"
+ self.contract = self.root / "contract.json"
+
+ def tearDown(self):
+ self.temp.cleanup()
+
+ def write_contract(self, required=None, forbidden=None):
+ data = {
+ "required_objects": ["lib/required.o"] if required is None else required,
+ "forbidden_objects": [] if forbidden is None else forbidden,
+ }
+ self.contract.write_text(json.dumps(data), encoding="utf-8")
+
+ def run_audit(self, command, output=None):
+ self.command.write_text(command, encoding="utf-8")
+ output = self.root / "report.json" if output is None else Path(output)
+ result = subprocess.run(
+ [sys.executable, str(SCRIPT), "--command-file", str(self.command),
+ "--directory", str(self.cwd), "--contract", str(self.contract),
+ "--output", str(output)],
+ cwd=self.root, text=True, capture_output=True, check=False,
+ )
+ summary = json.loads(result.stdout) if result.stdout else {}
+ report = summary if summary["details"] is None else json.loads(
+ Path(summary["details"]).read_text(encoding="utf-8")
+ )
+ return result, summary, report
+
+ def test_missing_required_object_fails(self):
+ self.write_contract()
+ result, summary, report = self.run_audit("c++ lib/other.o -o app")
+ self.assertEqual(result.returncode, 1)
+ self.assertFalse(report["passed"])
+ self.assertEqual(summary["violations"], 1)
+ self.assertEqual(report["violations"][0]["kind"], "required_object_count")
+ self.assertEqual(report["violations"][0]["actual"], 0)
+
+ def test_duplicate_object_fails(self):
+ self.write_contract()
+ result, summary, report = self.run_audit("c++ lib/required.o lib/required.o -o app")
+ self.assertEqual(result.returncode, 1)
+ self.assertEqual(summary["violations"], 2)
+ self.assertEqual(report["objects"][0]["count"], 2)
+ self.assertEqual({item["kind"] for item in report["violations"]},
+ {"duplicate_object", "required_object_count"})
+
+ def test_forbidden_object_fails(self):
+ self.write_contract(forbidden=["lib/forbidden.obj"])
+ result, _, report = self.run_audit("c++ lib/required.o lib/forbidden.obj -o app")
+ self.assertEqual(result.returncode, 1)
+ self.assertEqual(report["violations"][0]["kind"], "forbidden_object")
+
+ def test_nested_responses_use_command_directory(self):
+ self.write_contract()
+ response_dir = self.cwd / "args"
+ response_dir.mkdir()
+ (response_dir / "outer.rsp").write_text("@nested.rsp", encoding="utf-8")
+ (self.cwd / "nested.rsp").write_text("lib/required.o -o app", encoding="utf-8")
+ result, _, report = self.run_audit("c++ @args/outer.rsp")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertTrue(report["passed"])
+ self.assertEqual(report["counts"]["response_files"], 2)
+
+ def test_wl_response_is_expanded(self):
+ self.write_contract()
+ (self.cwd / "link.rsp").write_text("lib/required.o", encoding="utf-8")
+ result, _, report = self.run_audit("c++ -Wl,@link.rsp -o app")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(report["counts"]["object_occurrences"], 1)
+
+ def test_xlinker_object_is_counted_and_option_values_are_skipped(self):
+ self.write_contract()
+ command = (
+ "c++ lib/required.o -Xlinker -o -Xlinker output.o "
+ "-Xlinker -T -Xlinker lib/script.o"
+ )
+ result, _, report = self.run_audit(command)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(report["counts"]["object_occurrences"], 1)
+
+ def test_missing_response_is_parse_error(self):
+ self.write_contract()
+ result, summary, _ = self.run_audit("c++ @missing.rsp")
+ self.assertEqual(result.returncode, 2)
+ self.assertEqual(summary["parse_errors"], 1)
+ self.assertIn("cannot read response file", summary["first_violations"][0]["message"])
+
+ def test_response_cycle_is_parse_error(self):
+ self.write_contract()
+ (self.cwd / "first.rsp").write_text("@second.rsp", encoding="utf-8")
+ (self.cwd / "second.rsp").write_text("@first.rsp", encoding="utf-8")
+ result, summary, _ = self.run_audit("c++ @first.rsp")
+ self.assertEqual(result.returncode, 2)
+ self.assertIn("response-file cycle", summary["first_violations"][0]["message"])
+
+ def test_incomplete_response_discovery_refuses_output_after_xlinker_error(self):
+ self.write_contract()
+ response = self.cwd / "args.rsp"
+ original = b"lib/required.o\n"
+ response.write_bytes(original)
+ result, summary, _ = self.run_audit("c++ @args.rsp -Xlinker", output=response)
+
+ self.assertEqual(result.returncode, 2)
+ self.assertEqual(response.read_bytes(), original)
+ self.assertEqual(summary["parse_errors"], 1)
+ self.assertIn("-Xlinker is missing its argument", summary["first_violations"][0]["message"])
+ self.assertIsNone(summary["details"])
+ self.assertEqual(summary["output_refusal_reason"], "response-file discovery was incomplete")
+
+ def test_incomplete_nested_response_discovery_refuses_output(self):
+ self.write_contract()
+ (self.cwd / "outer.rsp").write_text('@nested.rsp "unterminated', encoding="utf-8")
+ nested = self.cwd / "nested.rsp"
+ original = b"preserve nested response\n"
+ nested.write_bytes(original)
+ result, summary, _ = self.run_audit("c++ @outer.rsp", output=nested)
+
+ self.assertEqual(result.returncode, 2)
+ self.assertEqual(nested.read_bytes(), original)
+ self.assertEqual(summary["parse_errors"], 1)
+ self.assertIn("cannot parse response file", summary["first_violations"][0]["message"])
+ self.assertIsNone(summary["details"])
+ self.assertEqual(summary["output_refusal_reason"], "response-file discovery was incomplete")
+
+ def test_shell_operators_and_substitution_are_rejected(self):
+ self.write_contract()
+ for command in ("c++ lib/required.o; touch marker", 'c++ "$(touch marker)" lib/required.o'):
+ with self.subTest(command=command):
+ result, _, report = self.run_audit(command)
+ self.assertEqual(result.returncode, 2)
+ self.assertTrue(report["parse_errors"])
+ self.assertFalse((self.root / "marker").exists())
+
+ def test_unresolved_shell_inputs_are_rejected(self):
+ self.write_contract(forbidden=["base/old.o"])
+ base = self.cwd / "base"
+ base.mkdir()
+ (base / "old.o").write_bytes(b"old object")
+ for argument in ("base/*.o", "base/old.?", "base/[o]ld.o", "base/{old,new}.o",
+ "~/old.o", "$BASE_DIR/old.o", '"$BASE_DIR/old.o"',
+ "${BASE_DIR}/old.o", "$OBJECTS"):
+ with self.subTest(argument=argument):
+ result, summary, report = self.run_audit(f"c++ lib/required.o {argument} -o app")
+ self.assertEqual(result.returncode, 2)
+ self.assertFalse(report["passed"])
+ self.assertIn("expansion", summary["first_violations"][0]["message"])
+
+ def test_quoted_and_escaped_shell_characters_are_literal(self):
+ for argument in ("'literal/*.o'", '"literal/*.o"', r"literal/\*.o",
+ "'literal/$NAME.o'", r"literal/\$NAME.o", r'"literal/\$NAME.o"'):
+ with self.subTest(argument=argument):
+ self.write_contract(required=["lib/required.o", "literal/" +
+ ("*.o" if "*" in argument else "$NAME.o")])
+ result, _, report = self.run_audit(
+ f'c++ lib/required.o {argument} -Wl,-rpath,"\\$ORIGIN" -o app'
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertTrue(report["passed"])
+
+ def test_double_quoted_escaped_dollar_cannot_hide_forbidden_object(self):
+ self.write_contract(forbidden=["literal/$NAME.o"])
+ result, _, report = self.run_audit(r'c++ lib/required.o "literal/\$NAME.o" -o app')
+ self.assertEqual(result.returncode, 1)
+ self.assertEqual(report["violations"][0]["kind"], "forbidden_object")
+ self.assertEqual(report["violations"][0]["path"], str(self.cwd / "literal/$NAME.o"))
+
+ def test_comments_and_continuations_follow_shell_word_boundaries(self):
+ for argument, object_path in (("literal#dir/old.o", "literal#dir/old.o"),
+ ("literal/ol\\\nd.o", "literal/old.o"),
+ ('"literal/ol\\\nd.o"', "literal/old.o"),
+ (r'literal/\ #dir/old.o', "literal/ #dir/old.o"),
+ (r'"literal/\`NAME.o"', "literal/`NAME.o")):
+ with self.subTest(argument=argument):
+ self.write_contract(forbidden=[object_path])
+ result, _, report = self.run_audit(f"c++ lib/required.o {argument} # trailing comment")
+ self.assertEqual(result.returncode, 1)
+ self.assertEqual(report["violations"][0]["kind"], "forbidden_object")
+
+ def test_parameter_expansion_after_literal_hash_is_rejected(self):
+ self.write_contract()
+ result, summary, _ = self.run_audit(r"c++ lib/required.o literal/\ #dir/$OBJECTS")
+ self.assertEqual(result.returncode, 2)
+ self.assertIn("parameter expansion", summary["first_violations"][0]["message"])
+
+ def test_unterminated_quotes_and_trailing_escapes_are_rejected(self):
+ self.write_contract()
+ for command in ('c++ "lib/required.o', "c++ lib/required.o\\"):
+ with self.subTest(command=command):
+ result, _, report = self.run_audit(command)
+ self.assertEqual(result.returncode, 2)
+ self.assertFalse(report["passed"])
+
+ def test_response_file_shell_characters_remain_literal(self):
+ self.write_contract(required=["lib/required.o", "literal/*.o", "literal/$NAME.o"])
+ (self.cwd / "args.rsp").write_text("lib/required.o literal/*.o literal/$NAME.o", encoding="utf-8")
+ result, _, report = self.run_audit("c++ @args.rsp -o app")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertTrue(report["passed"])
+
+ def test_output_collision_preserves_command_and_refuses_output(self):
+ self.write_contract()
+ original = "c++ lib/required.o"
+ self.command.write_text(original, encoding="utf-8")
+ result, summary, report = self.run_audit(original, output=self.command)
+ self.assertEqual(result.returncode, 2)
+ self.assertEqual(self.command.read_text(encoding="utf-8"), original)
+ self.assertIsNone(summary["details"])
+ self.assertTrue(any("aliases" in issue["message"] for issue in summary["first_violations"]))
+ self.assertEqual(report["parse_errors"], 1)
+
+ def test_output_collision_preserves_contract(self):
+ self.write_contract()
+ original = self.contract.read_text(encoding="utf-8")
+ result, summary, report = self.run_audit("c++ lib/required.o", output=self.contract)
+ self.assertEqual(result.returncode, 2)
+ self.assertEqual(self.contract.read_text(encoding="utf-8"), original)
+ self.assertIsNone(summary["details"])
+ self.assertTrue(any("aliases" in issue["message"] for issue in summary["first_violations"]))
+ self.assertEqual(report["parse_errors"], 1)
+
+ def test_output_collision_preserves_response(self):
+ self.write_contract()
+ response = self.cwd / "args.rsp"
+ response.write_text("lib/required.o", encoding="utf-8")
+ original = response.read_text(encoding="utf-8")
+ result, summary, report = self.run_audit("c++ @args.rsp", output=response)
+ self.assertEqual(result.returncode, 2)
+ self.assertEqual(response.read_text(encoding="utf-8"), original)
+ self.assertIsNone(summary["details"])
+ self.assertTrue(any("aliases" in issue["message"] for issue in summary["first_violations"]))
+ self.assertEqual(report["parse_errors"], 1)
+
+ def test_output_collision_preserves_objects_even_with_invalid_contract(self):
+ object_file = self.cwd / "lib/replacement.o"
+ object_file.parent.mkdir()
+ original = b"\x7fELF\x00object contents"
+ object_file.write_bytes(original)
+ symlink = self.root / "symlink.json"
+ symlink.symlink_to(object_file)
+ hardlink = self.root / "hardlink.json"
+ os.link(object_file, hardlink)
+ response = self.cwd / "args.rsp"
+ response.write_text("lib/replacement.o", encoding="utf-8")
+ for malformed in (False, True):
+ self.write_contract(required=["lib/replacement.o"])
+ if malformed:
+ self.contract.write_text("{invalid json", encoding="utf-8")
+ for command in ("c++ lib/replacement.o", "c++ @args.rsp"):
+ for output in (object_file, symlink, hardlink):
+ with self.subTest(malformed=malformed, command=command, output=output):
+ result, summary, _ = self.run_audit(command, output=output)
+ self.assertEqual(result.returncode, 2)
+ self.assertEqual(object_file.read_bytes(), original)
+ self.assertIsNone(summary["details"])
+ self.assertTrue(any("aliases" in issue["message"]
+ for issue in summary["first_violations"]))
+
+ def test_malformed_required_list_is_parse_error(self):
+ self.write_contract(required=[])
+ result, _, report = self.run_audit("c++ lib/required.o")
+ self.assertEqual(result.returncode, 2)
+ self.assertIn("required_objects must be a nonempty list", report["parse_errors"][0])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.claude/skills/ov-gguf/scripts/tests/test_runtime_identity.py b/.claude/skills/ov-gguf/scripts/tests/test_runtime_identity.py
new file mode 100644
index 00000000000..445a41dfdf1
--- /dev/null
+++ b/.claude/skills/ov-gguf/scripts/tests/test_runtime_identity.py
@@ -0,0 +1,152 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import ctypes
+import hashlib
+import importlib.util
+import json
+import mmap
+import os
+from pathlib import Path
+import tempfile
+import subprocess
+import sys
+import unittest
+from unittest import mock
+
+
+spec = importlib.util.spec_from_file_location("runtime_identity", Path(__file__).parents[1] / "runtime_identity.py")
+runtime = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(runtime)
+
+
[email protected](Path("/proc/self/maps").is_file(), "Linux process maps required")
+class RuntimeIdentityTests(unittest.TestCase):
+ def test_cli_preserves_expected_manifest(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ expected, alias = path / "expected.json", path / "alias.json"
+ expected.write_text('{}')
+ os.link(expected, alias)
+ for output in (expected, alias):
+ result = subprocess.run([sys.executable, runtime.__file__, "--expected", str(expected),
+ "--output", str(output)], capture_output=True)
+ self.assertEqual(result.returncode, 2)
+ self.assertEqual(expected.read_text(), '{}')
+
+ def test_report_preserves_expected_library_aliases_with_invalid_hash(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ library = path / "library.so"
+ original = b"KEEP LIBRARY BYTES"
+ library.write_bytes(original)
+ symlink, hardlink = path / "symlink.json", path / "hardlink.json"
+ symlink.symlink_to(library)
+ os.link(library, hardlink)
+ expected = {"fixture": {"path": str(library), "sha256": "invalid"}}
+ for output in (library, symlink, hardlink):
+ with self.subTest(output=output):
+ with self.assertRaisesRegex(ValueError, "must not overwrite"):
+ runtime.record_identity(expected, output)
+ self.assertEqual(library.read_bytes(), original)
+
+ def test_report_preserves_mapped_library_not_in_manifest(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ mapped, expected_library = path / "libopenvino_fixture.so", path / "expected.so"
+ original = b"KEEP MAPPED LIBRARY BYTES"
+ mapped.write_bytes(original)
+ expected_library.write_bytes(b"EXPECTED")
+ expected = {"fixture": {"path": str(expected_library),
+ "sha256": hashlib.sha256(expected_library.read_bytes()).hexdigest()}}
+ with mapped.open("rb") as stream, mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ):
+ with self.assertRaisesRegex(ValueError, "must not overwrite"):
+ runtime.record_identity(expected, mapped)
+ self.assertEqual(mapped.read_bytes(), original)
+
+ def test_report_preserves_mapped_aliases_after_manifest_failure(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ mapped, expected_library = path / "libopenvino_fixture.so", path / "expected.so"
+ original = b"KEEP MAPPED LIBRARY BYTES"
+ mapped.write_bytes(original)
+ expected_library.write_bytes(b"EXPECTED")
+ symlink, hardlink = path / "symlink.json", path / "hardlink.json"
+ symlink.symlink_to(mapped)
+ os.link(mapped, hardlink)
+ manifests = (
+ {"fixture": {"path": str(expected_library), "sha256": "invalid"}},
+ {"fixture": {"path": str(path / "missing.so"), "sha256": "0" * 64}},
+ {},
+ )
+ with mapped.open("rb") as stream, mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ):
+ for expected in manifests:
+ for output in (mapped, symlink, hardlink):
+ with self.subTest(expected=expected, output=output):
+ with self.assertRaisesRegex(ValueError, "must not overwrite"):
+ runtime.record_identity(expected, output)
+ self.assertEqual(mapped.read_bytes(), original)
+
+ def test_hash_failure_keeps_all_mappings_and_protects_output(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ first, second = path / "libopenvino_first.so", path / "libopenvino_second.so"
+ first.write_bytes(b"FIRST")
+ second.write_bytes(b"SECOND")
+ expected = {"fixture": {"path": str(first), "sha256": "0" * 64}}
+ output = path / "report.json"
+ read_bytes = Path.read_bytes
+
+ def fail_first_hash(library):
+ if library == first:
+ raise OSError("fixture hash failure")
+ return read_bytes(library)
+
+ with first.open("rb") as stream1, second.open("rb") as stream2, \
+ mmap.mmap(stream1.fileno(), 0, access=mmap.ACCESS_READ), \
+ mmap.mmap(stream2.fileno(), 0, access=mmap.ACCESS_READ), \
+ mock.patch.object(Path, "read_bytes", fail_first_hash):
+ with self.assertRaisesRegex(RuntimeError, "fixture hash failure"):
+ runtime.record_identity(expected, output)
+ report = json.loads(output.read_text())
+ self.assertFalse(report["passed"])
+ self.assertTrue({str(first), str(second)}.issubset(
+ {entry["path"] for entry in report["mapped_libraries"]}
+ ))
+ with self.assertRaisesRegex(ValueError, "must not overwrite"):
+ runtime.record_identity(expected, second)
+ self.assertEqual(first.read_bytes(), b"FIRST")
+ self.assertEqual(second.read_bytes(), b"SECOND")
+
+ def test_mapping_discovery_failure_refuses_report_output(self):
+ with tempfile.TemporaryDirectory() as directory:
+ output = Path(directory) / "report.json"
+ with mock.patch.object(Path, "read_text", side_effect=OSError("fixture maps failure")):
+ with self.assertRaisesRegex(RuntimeError, "refusing report output"):
+ runtime.record_identity({}, output)
+ self.assertFalse(output.exists())
+
+ def test_actual_mapped_library_and_wrong_hash(self):
+ library = ctypes.CDLL("libm.so.6")
+ paths = [Path(line.split(maxsplit=5)[5]) for line in Path("/proc/self/maps").read_text().splitlines()
+ if len(line.split(maxsplit=5)) == 6 and line.split(maxsplit=5)[5].startswith("/")
+ and Path(line.split(maxsplit=5)[5]).name.startswith("libm.so")]
+ self.assertTrue(paths)
+ mapped = paths[0].resolve()
+ expected = {"math": {"path": str(mapped), "sha256": hashlib.sha256(mapped.read_bytes()).hexdigest()}}
+ with tempfile.TemporaryDirectory() as directory:
+ output = Path(directory) / "identity.json"
+ self.assertTrue(runtime.record_identity(expected, output)["passed"])
+ alias = Path(directory) / "math-alias.so"
+ alias.symlink_to(mapped)
+ expected["math"]["path"] = str(alias)
+ self.assertTrue(runtime.record_identity(expected, output)["passed"])
+ expected["math"]["sha256"] = "0" * 64
+ with self.assertRaises(RuntimeError):
+ runtime.record_identity(expected, output)
+ self.assertFalse(json.loads(output.read_text())["passed"])
+ self.assertIsNotNone(library)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.claude/skills/ov-gguf/scripts/tests/test_test_coverage.py b/.claude/skills/ov-gguf/scripts/tests/test_test_coverage.py
new file mode 100644
index 00000000000..ba042a60701
--- /dev/null
+++ b/.claude/skills/ov-gguf/scripts/tests/test_test_coverage.py
@@ -0,0 +1,228 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import importlib.util
+import json
+import os
+from pathlib import Path
+import tempfile
+import subprocess
+import sys
+import unittest
+
+
+def load(name):
+ spec = importlib.util.spec_from_file_location(name, Path(__file__).parents[1] / (name + ".py"))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+coverage = load("check_test_coverage")
+summarizer = load("summarize_tests")
+
+
+class CoverageTests(unittest.TestCase):
+ def setUp(self):
+ self.contract = {"selections": [{"pattern": "*", "count": 2},
+ {"pattern": "Arch/Graph.*", "count": 1}]}
+ self.listing = "Running main()\nArch/Graph. # TypeParam = int\n Decode/0 # GetParam() = x\nAPI.\n Reset\n"
+
+ def summary(self, skip=False):
+ xml = '<testsuites><testsuite><testcase classname="Arch/Graph" name="Decode/0"/>'
+ xml += '<testcase classname="API" name="Reset">' + ('<skipped message="no model"/>' if skip else '')
+ xml += '</testcase></testsuite></testsuites>'
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "tests.xml"
+ path.write_text(xml)
+ return {"process_exit": 0, "parse_errors": [], "reports": [summarizer.summarize(path)]}
+
+ def test_real_xml_ids_match_typed_listing(self):
+ self.assertEqual(coverage.check(self.contract, self.listing, self.summary())["violations"], [])
+
+ def test_wrong_filter_and_missing_registration(self):
+ self.assertTrue(coverage.check(self.contract, "API.\n Reset\n")["violations"])
+ self.assertTrue(coverage.check(self.contract, "Running main()\n")["violations"])
+
+ def test_stale_executable_missing_new_test(self):
+ summary = self.summary()
+ summary["reports"][0]["selected_ids"].pop()
+ summary["reports"][0]["counts"]["selected"] -= 1
+ self.assertIn("listed and executed IDs differ", coverage.check(self.contract, self.listing, summary)["violations"])
+
+ def test_skip_requires_explicit_allowance(self):
+ self.assertTrue(coverage.check(self.contract, self.listing, self.summary(True))["violations"])
+ self.contract["allowed_skips"] = ["API.Reset"]
+ self.assertEqual(coverage.check(self.contract, self.listing, self.summary(True))["violations"], [])
+
+ def test_process_failure_and_duplicate_reports(self):
+ summary = self.summary()
+ summary["process_exit"] = 1
+ self.assertTrue(coverage.check(self.contract, self.listing, summary)["violations"])
+ summary["process_exit"] = 0
+ summary["reports"] *= 2
+ self.assertTrue(coverage.check(self.contract, self.listing, summary)["violations"])
+
+ def test_required_fixture(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "model.gguf"
+ self.contract["required_files"] = [str(path)]
+ self.assertTrue(coverage.check(self.contract, self.listing)["violations"])
+ path.write_bytes(b"GGUF")
+ self.assertEqual(coverage.check(self.contract, self.listing)["violations"], [])
+
+ def test_invalid_count(self):
+ for count in (0, True, "2"):
+ with self.assertRaises(ValueError):
+ coverage.check({"selections": [{"pattern": "*", "count": count}]}, self.listing)
+
+ def test_cli_preserves_fixture_and_input(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ fixture, contract, listing = path / "model.gguf", path / "contract.json", path / "listing.txt"
+ fixture.write_bytes(b"GGUF")
+ self.contract["required_files"] = [str(fixture)]
+ contract.write_text(json.dumps(self.contract))
+ listing.write_text(self.listing)
+ original = {target: target.read_bytes() for target in (fixture, contract, listing)}
+ for output in (fixture, contract, listing):
+ result = subprocess.run([sys.executable, coverage.__file__, "--contract", str(contract),
+ "--listing", str(listing), "--output", str(output)], capture_output=True)
+ self.assertEqual(result.returncode, 2)
+ self.assertEqual(json.loads(result.stdout)["output_refused"], True)
+ self.assertEqual({target: target.read_bytes() for target in original}, original)
+
+ def test_cli_malformed_contract_retains_error(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ contract, listing, output = path / "contract.json", path / "listing.txt", path / "result.json"
+ contract.write_text('{"selections": []}')
+ listing.write_text(self.listing)
+ result = subprocess.run([sys.executable, coverage.__file__, "--contract", str(contract),
+ "--listing", str(listing), "--output", str(output)], capture_output=True)
+ self.assertEqual(result.returncode, 2)
+ report = json.loads(output.read_text())
+ self.assertTrue(report["input_error"])
+ self.assertEqual(json.loads(result.stdout)["details"], str(output.resolve()))
+
+ def test_cli_relative_required_file_and_later_fixture_alias_refuses_output(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ model, contract, listing = path / "model.gguf", path / "contract.json", path / "listing.txt"
+ original = b"MODEL BYTES MUST SURVIVE"
+ model.write_bytes(original)
+ contract.write_text(json.dumps({"selections": self.contract["selections"],
+ "required_files": ["relative.gguf", str(model)]}))
+ listing.write_text(self.listing)
+ result = subprocess.run([sys.executable, coverage.__file__, "--contract", str(contract),
+ "--listing", str(listing), "--output", str(model)], capture_output=True)
+ self.assertEqual(result.returncode, 2)
+ diagnostic = json.loads(result.stdout)
+ self.assertIsNone(diagnostic["details"])
+ self.assertTrue(diagnostic["output_refused"])
+ self.assertIn("required fixture", diagnostic["reason"])
+ self.assertEqual(model.read_bytes(), original)
+
+ def test_cli_malformed_required_files_refuses_without_writing(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ output, contract, listing = path / "result.json", path / "contract.json", path / "listing.txt"
+ original = b"KEEP EXISTING OUTPUT"
+ output.write_bytes(original)
+ listing.write_text(self.listing)
+ malformed = ("not a list", [None], [""], [str(output), None])
+ for required_files in malformed:
+ with self.subTest(required_files=required_files):
+ contract.write_text(json.dumps({"selections": self.contract["selections"],
+ "required_files": required_files}))
+ result = subprocess.run([sys.executable, coverage.__file__, "--contract", str(contract),
+ "--listing", str(listing), "--output", str(output)], capture_output=True)
+ self.assertEqual(result.returncode, 2)
+ diagnostic = json.loads(result.stdout)
+ self.assertIsNone(diagnostic["details"])
+ self.assertTrue(diagnostic["output_refused"])
+ self.assertTrue(diagnostic["reason"])
+ self.assertEqual(output.read_bytes(), original)
+
+ def test_cli_unreadable_contract_discovery_refuses_without_writing(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ contract, listing, output = path / "contract.json", path / "listing.txt", path / "result.json"
+ listing.write_text(self.listing)
+ original = b"KEEP EXISTING OUTPUT"
+ output.write_bytes(original)
+ for contents in ("{broken", "[]"):
+ with self.subTest(contents=contents):
+ contract.write_text(contents)
+ result = subprocess.run([sys.executable, coverage.__file__, "--contract", str(contract),
+ "--listing", str(listing), "--output", str(output)], capture_output=True)
+ self.assertEqual(result.returncode, 2)
+ diagnostic = json.loads(result.stdout)
+ self.assertIsNone(diagnostic["details"])
+ self.assertTrue(diagnostic["output_refused"])
+ self.assertTrue(diagnostic["reason"])
+ self.assertEqual(output.read_bytes(), original)
+
+ def test_cli_fixture_symlink_and_hardlink_aliases_refuse_output(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ model, contract, listing = path / "model.gguf", path / "contract.json", path / "listing.txt"
+ model.write_bytes(b"KEEP MODEL BYTES")
+ contract.write_text(json.dumps({"selections": self.contract["selections"],
+ "required_files": [str(model)]}))
+ listing.write_text(self.listing)
+ for kind in ("symlink", "hardlink"):
+ with self.subTest(kind=kind):
+ output = path / (kind + "-output")
+ if kind == "symlink":
+ output.symlink_to(model)
+ else:
+ os.link(model, output)
+ result = subprocess.run([sys.executable, coverage.__file__, "--contract", str(contract),
+ "--listing", str(listing), "--output", str(output)], capture_output=True)
+ self.assertEqual(result.returncode, 2)
+ diagnostic = json.loads(result.stdout)
+ self.assertIsNone(diagnostic["details"])
+ self.assertTrue(diagnostic["output_refused"])
+ self.assertEqual(model.read_bytes(), b"KEEP MODEL BYTES")
+ self.assertEqual(output.read_bytes(), b"KEEP MODEL BYTES")
+ output.unlink()
+ first_link, second_link = path / "loop-a", path / "loop-b"
+ first_link.symlink_to(second_link)
+ second_link.symlink_to(first_link)
+ output = path / "loop-output.json"
+ output.write_bytes(b"KEEP OUTPUT BYTES")
+ contract.write_text(json.dumps({"selections": self.contract["selections"],
+ "required_files": [str(first_link)]}))
+ result = subprocess.run([sys.executable, coverage.__file__, "--contract", str(contract),
+ "--listing", str(listing), "--output", str(output)], capture_output=True)
+ self.assertEqual(result.returncode, 2)
+ diagnostic = json.loads(result.stdout)
+ self.assertIsNone(diagnostic["details"])
+ self.assertTrue(diagnostic["output_refused"])
+ self.assertIn("cannot safely resolve", diagnostic["reason"])
+ self.assertEqual(output.read_bytes(), b"KEEP OUTPUT BYTES")
+
+ def test_hardlink_output_preserves_coverage_inputs_and_xml(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory)
+ contract, listing, output = path / "contract.json", path / "listing.txt", path / "result.json"
+ original = json.dumps(self.contract)
+ contract.write_text(original)
+ listing.write_text(self.listing)
+ os.link(contract, output)
+ result = subprocess.run([sys.executable, coverage.__file__, "--contract", str(contract),
+ "--listing", str(listing), "--output", str(output)], capture_output=True)
+ self.assertEqual(result.returncode, 2)
+ self.assertEqual(contract.read_text(), original)
+ xml, alias = path / "tests.xml", path / "xml-alias.json"
+ xml.write_text('<testsuites/>')
+ os.link(xml, alias)
+ result = subprocess.run([sys.executable, summarizer.__file__, str(xml),
+ "--output", str(alias)], capture_output=True)
+ self.assertEqual(result.returncode, 2)
+ self.assertEqual(xml.read_text(), '<testsuites/>')
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/workflows/job_gguf_llamacpp_validation.yml b/.github/workflows/job_gguf_llamacpp_validation.yml
index b6e9c940267..d1a54488e9e 100644
--- a/.github/workflows/job_gguf_llamacpp_validation.yml
+++ b/.github/workflows/job_gguf_llamacpp_validation.yml
@@ -28,7 +28,7 @@ env:
# ggml-openvino decoder/backend fixes this frontend snapshot requires. Bump alongside any
# GGUF-frontend change that needs a matching llama.cpp-side update.
LLAMA_CPP_REPO: mvafin/llama.cpp
- LLAMA_CPP_REF: 3d677aadec0487430ad59bd3d4a9fc7211721f0f
+ LLAMA_CPP_REF: 9631fc03fbd5f7c6490b9552e622a213411e1459
INSTALL_DIR: ${{ github.workspace }}/install
SCCACHE_DIR: ${{ github.workspace }}/.sccache
@@ -100,14 +100,25 @@ jobs:
OV_GGUF_Q4_K_ZP_F16: "1"
run: |
source ${{ env.INSTALL_DIR }}/setupvars.sh
- # Keep the operator suite enabled. The pinned llama.cpp revision also labels its
- # all-architecture state suite and multi-sequence recurrent rollback tests as main.
- # Those exercise unsupported backend layouts (Qwen3.5 multi-sequence replay,
- # Nemotron-H packed SSM state, and DeepSeek V4); validate supported state paths below.
+ # Keep operators enabled; run supported model/state fixtures below instead of
+ # sweeping recurrent layouts this backend cannot execute.
ctest --test-dir llama.cpp/build -L main \
- -E '^test-(opt|llama-archs|recurrent-state-rollback(-nemotron-h|-dsv4)?|save-load-state)$' \
+ -E '^test-(opt|llama-archs|recurrent-state-rollback(-nemotron-h|-dsv4)?|save-load-state|llama-context)$' \
--output-on-failure --timeout 2000
+ - name: Validate context state on supported llama.cpp models
+ env:
+ OV_GGUF_Q4_K_ZP_F16: "1"
+ run: |
+ source ${{ env.INSTALL_DIR }}/setupvars.sh
+ # Failed-restore isolation (rf) already fails for these two models before this PR.
+ for model in llama-dense qwen2-dense; do
+ timeout 2000 llama.cpp/build/bin/test-llama-context \
+ -m "llama.cpp/build/tests/test-models/${model}.gguf" --test '^(?!rf$).*'
+ done
+ timeout 2000 llama.cpp/build/bin/test-llama-context \
+ -m llama.cpp/build/tests/test-models/qwen3-dense.gguf
+
- name: Validate state save/load on supported llama.cpp models
env:
OV_GGUF_Q4_K_ZP_F16: "1"
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/decoder_options.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/decoder_options.hpp
index ba59cfa952b..92939db3f30 100644
--- a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/decoder_options.hpp
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/decoder_options.hpp
@@ -5,7 +5,10 @@
#pragma once
#include <optional>
+#include <string>
+#include <vector>
+#include "openvino/frontend/gguf/builder/metadata.hpp"
#include "openvino/frontend/gguf/decoder.hpp"
#include "openvino/frontend/gguf/visibility.hpp"
@@ -13,8 +16,139 @@ namespace ov::frontend::gguf {
enum class RopeMode { Normal, Neox, Interleaved };
-// Architecture overrides; unset options retain detection. Dimensions and derived plans stay internal.
+enum class NormalizationKind { Rms, Layer };
+enum class FfnActivation { SwiGlu, GeGlu, ReluSquared };
+enum class RecurrentKind { None, GatedDeltaNet };
+enum class ExpertRouting { Softmax = 1, Sigmoid = 2 };
+
+struct GGUF_FRONTEND_API DecoderShape {
+ int layers = 0;
+ int embedding = 0;
+ int query_heads = 0;
+ int kv_heads = 0;
+ int head_size = 0;
+ std::vector<uint32_t> kv_heads_per_layer;
+ int per_layer_embedding = 0;
+ int shared_kv_layers = 0;
+};
+
+struct GGUF_FRONTEND_API DecoderNormalization {
+ NormalizationKind kind = NormalizationKind::Rms;
+ float epsilon = 0.0f;
+ float post_epsilon = 0.0f;
+ bool post_only = false;
+ bool qk_after_rope = false;
+ std::optional<bool> qk_full_width;
+ std::optional<bool> qk_norm;
+ bool value_norm = false;
+ bool embedding_norm = false;
+ std::string attention_key = "attn_norm.weight";
+ std::string ffn_key = "ffn_norm.weight";
+ std::string attention_post_key = "post_attention_norm.weight";
+ std::string ffn_post_key = "post_ffw_norm.weight";
+ std::optional<bool> attention_post;
+ std::optional<bool> ffn_post;
+};
+
+struct GGUF_FRONTEND_API DecoderScales {
+ float embedding = 1.0f;
+ float residual = 1.0f;
+ float logits = 1.0f;
+ bool token_embeddings_only = false;
+ float attention = 0.0f;
+ float attention_temperature = 0.0f;
+ float attention_soft_cap = 0.0f;
+ float logits_soft_cap = 0.0f;
+};
+
+struct GGUF_FRONTEND_API DecoderAttention {
+ RopeMode rope_mode = RopeMode::Normal;
+ RopeConfig rope{};
+ RopeConfig sliding_rope{};
+ float yarn_log_multiplier = 0.0f;
+ bool sliding_window = false;
+ int window_size = 0;
+ int sliding_period = 2;
+ std::vector<int32_t> sliding_layers;
+ int sliding_head_size = 0;
+ bool rope_on_sliding_only = false;
+ int rope_skip_period = 0;
+ bool sliding_on_attention_layers = false;
+ bool interleaved_q_gate = false;
+ std::optional<bool> fused_qkv;
+ std::optional<bool> output_gate;
+ std::optional<bool> qkv_bias;
+ std::optional<bool> output_bias;
+ std::optional<bool> sinks;
+};
+
+struct GGUF_FRONTEND_API DecoderExperts {
+ int count = 0;
+ int used = 0;
+ int dense_lead = 0;
+ int layer_step = 1;
+ int groups = 1;
+ int groups_used = 1;
+ ExpertRouting routing = ExpertRouting::Softmax;
+ float weights_scale = 0.0f;
+ bool normalize_weights = false;
+ std::optional<bool> enabled;
+ std::optional<bool> softmax_after_topk;
+ std::optional<bool> swiglu_oai;
+};
+
+struct GGUF_FRONTEND_API DecoderHybrid {
+ RecurrentKind kind = RecurrentKind::None;
+ int conv_kernel = 0;
+ int state_size = 0;
+ int group_count = 0;
+ int time_step_rank = 0;
+ int inner_size = 0;
+ int full_attention_interval = 4;
+ int nextn_layers = 0;
+ std::vector<int32_t> recurrent_layers;
+};
+
+// Sparse overrides describe layer inputs; execution and cache plans remain internal.
+struct GGUF_FRONTEND_API DecoderLayerOverrides {
+ std::optional<int> query_heads;
+ std::optional<int> kv_heads;
+ std::optional<int> head_size;
+ std::optional<float> attention_scale;
+ std::optional<RopeConfig> rope;
+ std::optional<bool> sliding_window;
+ std::optional<bool> recurrent;
+ std::optional<bool> experts;
+};
+
+struct GGUF_FRONTEND_API DecoderParameters {
+ std::string architecture;
+ DecoderShape dimensions;
+ DecoderNormalization normalization;
+ DecoderScales scales;
+ DecoderAttention attention;
+ DecoderExperts experts;
+ DecoderHybrid hybrid;
+ FfnActivation activation = FfnActivation::SwiGlu;
+ bool embedding_model = false;
+ int pooling_type = 0;
+ bool causal_attention = true;
+ ModelContract model_contract{};
+ std::vector<DecoderLayerOverrides> layers;
+};
+
+// Read generic GGUF fields using explicitly selected semantics and defaults.
+GGUF_FRONTEND_API DecoderParameters read_decoder_parameters(const GgufMetadata& metadata,
+ DecoderParameters defaults = {});
+
+// Compatibility overrides; family defaults are selected by the builder before these apply.
struct GGUF_FRONTEND_API DecoderOptions {
+ std::optional<NormalizationKind> normalization;
+ std::optional<float> norm_epsilon;
+ std::optional<float> embedding_scale;
+ std::optional<float> residual_scale;
+ std::optional<float> logit_scale;
+ std::optional<float> attention_scale;
std::optional<bool> qk_norm_after_rope;
std::optional<bool> post_norm_only;
std::optional<bool> normalize_expert_weights;
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp
index b49efa7a131..6ef6b54ca30 100644
--- a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp
@@ -32,6 +32,8 @@ public:
const GgufMetadata& metadata() const;
// Call once before using decoder blocks; optional for other families.
// Options are validated before deriving execution plans and graph metadata.
+ DecoderDimensions configure_decoder(const DecoderParameters& parameters);
+ void configure_model_contract(const ModelContract& contract);
DecoderDimensions configure_decoder(RopeMode rope, const DecoderOptions& options = {});
DecoderLayerParameters decoder_layer_parameters(int layer) const;
GgufValue decoder_attention(int layer, const GgufValue& normalized_input);
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/architecture.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/architecture.hpp
index 89f94666bcb..f6644961318 100644
--- a/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/architecture.hpp
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/architecture.hpp
@@ -36,6 +36,10 @@ GGUF_FRONTEND_API ArchitectureDefinition make_decoder_architecture(std::string a
RopeMode rope,
DecoderOptionsFn options = {});
+using DecoderParametersFn = std::function<DecoderParameters(const BuildContext&)>;
+GGUF_FRONTEND_API ArchitectureDefinition make_decoder_architecture(std::string architecture,
+ DecoderParametersFn parameters);
+
class GGUF_FRONTEND_API ArchitectureExtension : public ov::Extension {
public:
OPENVINO_RTTI("gguf::ArchitectureExtension", "", ov::Extension);
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/projector.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/projector.hpp
index 6523cbdecb5..45d61cb8177 100644
--- a/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/projector.hpp
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/projector.hpp
@@ -5,15 +5,24 @@
#pragma once
#include <map>
+#include <optional>
#include "openvino/frontend/gguf/builder/graph_context.hpp"
#include "openvino/frontend/gguf/extension/architecture.hpp"
+#include "openvino/frontend/gguf/model_adapter.hpp"
namespace ov::frontend::gguf {
+// Recipes use resolved vision.patch_size/window_size/merge and clip.* dimensions in config.
+enum class ProjectorLayout { Unsupported, Image, PaddedPatches, WindowedPatches, SplitMerger, PackedPatches };
+
struct GGUF_FRONTEND_API ProjectorResult {
GgufValue output;
std::map<std::string, std::string> config;
+ // Overrides the definition; Image keeps the inputs supplied by build().
+ std::optional<ProjectorLayout> genai_layout;
+ // Overrides the definition; an explicit empty callback selects the serializable recipe.
+ std::optional<ModelAdapterFn> genai_adapter;
};
struct GGUF_FRONTEND_API ProjectorDefinition {
@@ -25,6 +34,8 @@ struct GGUF_FRONTEND_API ProjectorDefinition {
std::string projector_type;
BuildFn build;
ArchitectureDefinition::MatchFn match;
+ std::optional<ProjectorLayout> genai_layout;
+ ModelAdapterFn genai_adapter;
};
class GGUF_FRONTEND_API ProjectorExtension : public ArchitectureExtension {
diff --git a/src/frontends/gguf/docs/architectures.md b/src/frontends/gguf/docs/architectures.md
index 2be6d8e06bc..b8aab743f08 100644
--- a/src/frontends/gguf/docs/architectures.md
+++ b/src/frontends/gguf/docs/architectures.md
@@ -10,12 +10,19 @@ a `ModelBuilder` factory and an optional metadata predicate. The built-in catalo
promoted unchanged. Registration and packaging are covered in [extensions.md](extensions.md).
A vision/audio branch inside an mmproj file is a [projector component](extensions.md#extend-mmproj-with-a-projector-component), not an architecture.
+All architecture-specific decisions belong in `src/builder/`: metadata schemas and defaults,
+topology, operation selection, model contracts and specialized adapters. Built-in and extension
+factories use the same interfaces, so an extension can override every architecture-specific
+behavior. File parsing, quantization, translators and generic adaptation code consume explicit
+parameters and contracts and remain reusable by GenAI and the llama.cpp OpenVINO backend.
+
## Choose the smallest implementation
| Requirement | Implementation |
|---|---|
| Existing decoder topology, new name | Catalog row or `make_decoder_architecture(name, rope)` |
-| Decoder facts that tensors/metadata cannot determine | Add a callback returning `DecoderOptions` |
+| Complete decoder semantics or metadata defaults | Add a callback returning `DecoderParameters` |
+| Small overrides of the convenience decoder defaults | Add a callback returning `DecoderOptions` |
| Custom layer order using existing sublayers | `ModelBuilder` with `configure_decoder`, `decoder_attention`, `decoder_ffn` |
| Different model family | `ModelBuilder` with generic operations; follow [porting from llama.cpp](#port-from-llamacpp) |
@@ -60,10 +67,41 @@ describe ordering and routing facts, not execution plans. Unset fields keep nati
callback runs before dependent SWA, RoPE and KV configuration is resolved. For example, EXAONE4's
`post_attention_norm` is a post-norm, while GPT-OSS uses the same name for a pre-FFN norm.
+### Supply complete decoder parameters
+
+The typed overload bypasses built-in name policy, including for a replacement of a built-in:
+
+```cpp
+using namespace ov::frontend::gguf;
+auto definition = make_decoder_architecture("my-layernorm", [](const BuildContext& context) {
+ DecoderParameters defaults;
+ defaults.normalization.kind = NormalizationKind::Layer;
+ auto parameters = read_decoder_parameters(context.metadata, defaults);
+ parameters.scales.embedding = 2.0f;
+ parameters.activation = FfnActivation::ReluSquared;
+ return parameters;
+});
+```
+
+`DecoderParameters` groups dimensions, normalization, scaling, attention/RoPE/SWA, experts,
+recurrent layers and the model contract. `layers` is empty or describes every trunk layer
+(optionally including trailing NextN layers); each entry overrides selected layer parameters.
+A custom topology calls `configure_decoder(parameters)` before reusing decoder blocks.
+Complete parameters and overrides are validated before dependent plans are derived.
+
+`ModelContract` declares recurrent batching and image-attention semantics consumed by generic
+GenAI adaptation. Decoder configuration exports it automatically; other builders may call
+`configure_model_contract(contract)`. The common `GgufDecoder::get_model_contract()` accessor
+also lets the llama.cpp adapter supply resolved facts. Architecture names are diagnostic data.
+An explicit `batchable_recurrent` value overrides structural inference; leave it unset to infer
+batching from generic operation capabilities. All three states survive IR serialization.
+
### Auto-detected features
-`decoder_config_from_meta()` reads hyperparameters once and `DecoderConfig` resolves them; the
-topology builder never rereads metadata.
+`read_decoder_parameters()` reads generic metadata through the schema/defaults chosen by the
+architecture factory; `DecoderConfig` validates those typed inputs and derives layer and cache
+plans. Built-in family policy lives in `builder/arch/decoder_family.cpp`. The old normalized-map
+helpers remain internal migration adapters under builder. The topology never rereads metadata.
| Feature | Detected from |
|---|---|
@@ -81,6 +119,13 @@ topology builder never rereads metadata.
| Sliding-window attention | `attention.sliding_window(_pattern)`, or sinks |
| Per-layer KV heads | `attention.head_count_kv` as an array |
+MiniCPM's `logit_scale` is a divisor. When the key is absent, the builder uses
+`embedding_length / 256`, giving the model's `256 / embedding_length` output multiplier.
+This deliberately corrects the inverted fallback in unpatched llama.cpp, which defaults the
+divisor to `256 / embedding_length`. The llama.cpp branch used by frontend validation carries
+the same correction; `minicpm-default.npz` captures its CPU logits without the metadata key.
+Files with an explicit `logit_scale` retain its value.
+
Per-layer variation goes through `DecoderConfig` accessors, not inline ternaries in `build_layer()`:
`layer_is_swa`, `layer_is_moe`, `layer_head_size`, `layer_n_head_kv`, `layer_kq_scale`,
`layer_rope_config` and `is_recurrent_layer`. Extend them for a new per-layer dimension.
@@ -92,8 +137,8 @@ extensions include MoE routing (`blocks::moe_ffn()`), gpt-oss sinks and OAI SwiG
LayerNorm and ReLU² FFN, gemma2/3 post-norms and soft-caps, gemma4 per-layer embeddings and shared KV,
and qwen35 Gated DeltaNet layers that return the same sublayer output as attention. To add one:
-1. Add detection in `DecoderConfig`. Prefer weight presence; use `arch == "..."` only when the tensor
- table is ambiguous (for example GeGLU versus SwiGLU).
+1. Describe the feature in `DecoderParameters`. Select architecture-specific values in the owning
+ family helper or extension factory; retain only unambiguous structural detection in `DecoderConfig`.
2. Emit it behind that flag in the relevant `blocks/` function, or in `DecoderBuilder::build_layer()`
when it changes sublayer order.
3. Add a converter only if a GGML operation is missing; see [how_to_add_op.md](how_to_add_op.md).
diff --git a/src/frontends/gguf/docs/extensions.md b/src/frontends/gguf/docs/extensions.md
index 18b51d86564..448c0911fa6 100644
--- a/src/frontends/gguf/docs/extensions.md
+++ b/src/frontends/gguf/docs/extensions.md
@@ -23,6 +23,13 @@ device backend. Extensions attached to an `ov::BaseOpExtension` and shared-libra
unwrapped; a bare custom operation supplies no GGML converter. `TelemetryExtension` is stored but
never invoked; other types are ignored.
+GenAI integration in [PR #4683](https://github.com/openvinotoolkit/openvino.genai/pull/4683)
+accepts extension objects or library paths through `ov::genai::extensions(...)` in C++, or
+library paths through `extensions=[...]` in Python. For `LLMPipeline` and
+`ContinuousBatchingPipeline`, also select `GGUF_READER="FRONTEND"`. Extensions are registered
+before loading on every GGUF frontend, including both language and projector frontends in
+`VLMPipeline`.
+
## Lifecycle
Use one frontend instance for registration, loading and conversion:
@@ -68,6 +75,12 @@ frontend->add_extension(std::make_shared<ArchitectureExtension>(definition));
`ArchitectureExtension(ArchitectureDefinition)` also accepts a custom `ModelBuilder` factory with no
RoPE mode. See [architectures.md](architectures.md) for options, builders, porting and validation.
+A callback returning `DecoderParameters` gives full control over decoder dimensions,
+normalization, scales, layer/RoPE/SWA settings, routing and model contracts. It bypasses the
+convenience helper's built-in architecture defaults; see [complete parameters](architectures.md#supply-complete-decoder-parameters).
+A custom whole-model factory can replace topology using generic graph operations or the shared
+blocks through `configure_decoder(parameters)`.
+
### Matching and replacement
A handler matches on `general.architecture`, then its optional predicate. Handlers with different
@@ -92,7 +105,7 @@ selects branches as described in [mmproj.md](mmproj.md#files-with-vision-and-aud
outputs `vision.embeddings` / `audio.embeddings` and finishes the model.
A `ProjectorDefinition` has `id`, `architecture`, `modality` (`vision` or `audio`),
-`projector_type`, `build` and optional `match`. `build` appends to the shared `GgufGraphContext` and
+`projector_type`, `build` and optional `match`, `genai_layout` and `genai_adapter`. `build` appends to the shared `GgufGraphContext` and
returns `ProjectorResult`: the output and optional string configuration under the modality prefix.
It must not call `finish()` or register the primary output; extra inputs need unique names. A
predicate may distinguish variants of one resolved type; two matching handlers are an error.
@@ -130,6 +143,26 @@ To replace one built-in branch, reuse its id (for example `clip.vision.gemma3`)
component list comes from `ArchRegistry::projectors().supported_projectors()`. An architecture other
than `clip` would also need its own whole-model coordinator.
+The builder selects GenAI layout explicitly with `genai_layout`. Recipes describe input
+semantics (`Image`, `PaddedPatches`, `WindowedPatches`, `SplitMerger`) and are serialized with the
+model; generic adaptation never selects them by projector name. `build_builtin_projector()`
+returns the recipe matching its graph. A result's explicit recipe overrides the definition.
+
+A custom `genai_adapter` runs for both `EMBEDDINGS` and `VISION_ENCODERS` after generic extraction
+of the selected modality. It receives an independent model clone and returns `ModelAdapterResult`:
+the primary graph in `model` and optional named graphs in `models`. It can replace the entire
+input graph. `EMBEDDINGS` supports vision and audio and permits an empty map; when a map is
+returned, it must contain the primary graph. `VISION_ENCODERS` requires vision modality and a
+nonempty map containing the primary graph. Every map entry needs a nonempty name and a nonnull
+graph. All returned graphs are validated before the pass commits the result, so callback failures
+leave the supplied graph unchanged. A result callback overrides the definition callback; an
+explicitly empty result callback selects generic adaptation and, for `VISION_ENCODERS`, the recipe.
+
+Its implementation belongs to the owning builder or external extension. Callback lifetime is
+retained with the extension library, and callback attributes are removed from committed graphs.
+Callbacks are excluded from IR serialization; use a
+serializable recipe when adaptation must work after reloading an unadapted IR.
+
## Add or override an operation converter
Register an `ov::frontend::ConversionExtension` whose converter takes `const NodeContext&` and returns
@@ -197,3 +230,8 @@ Load the actual library, convert a matching file and compare with the reference
| Missing operation converter | Register the exact string on the same frontend before `convert()` |
| Cache remains stateless | Register `GenAIExtension` for GenAI IO, or `GGUFMakeStateful` for GGUF IO, before `convert()` |
| Outputs differ from the reference | Follow [debugging_accuracy.md](debugging_accuracy.md) |
+
+GenAI C++ callers can forward extension objects or shared-library paths using
+`ov::genai::extensions(...)`; Python uses `extensions=[...]` for library paths. Select
+`GGUF_READER="FRONTEND"` when using the language-model pipelines. These extensions are
+registered on each GGUF frontend before loading.
diff --git a/src/frontends/gguf/docs/mmproj.md b/src/frontends/gguf/docs/mmproj.md
index a96c21f176c..0499c25746e 100644
--- a/src/frontends/gguf/docs/mmproj.md
+++ b/src/frontends/gguf/docs/mmproj.md
@@ -20,6 +20,7 @@ numerical fixture checked against the llama.cpp CPU encoder (see
| Vision | `internvl` | InternViT, class token, pixel-shuffle merge |
| Vision | `resampler` | MiniCPM-V resampler, `clip.minicpmv_version` 2-6 and 100045 |
| Vision | `minicpmv4_6` | window attention, two-stage merging |
+| Vision | `minicpmv4_7` | window-attention and direct 2x2 merging; packed-patch GenAI layout |
| Vision | `qwen2vl_merger`, `qwen2.5vl_merger`, `qwen3vl_merger` | temporal pairs, M-RoPE, windows (2.5), DeepStack (3) |
| Vision | `pixtral` | 2D RoPE, patch merger, row separators |
| Vision | `phi4` | dynamic resolution, resized positions |
@@ -166,6 +167,7 @@ preprocessing uses llama.cpp geometry and token limits:
| `gemma3` | `vision_embeddings` | `pixel_values [1,3,S,S]` |
| `gemma4v`, `gemma4uv` | `vision_embeddings` | `pixel_values [1,P,patch*patch*3]` with patches in raster order, then padding; `image_position_ids [1,P,2]` as (x, y), -1 for padding |
| `muse-glimmer` | `vision_embeddings` | `pixel_values [rows*cols,3*patch*patch]`, `image_grid_thw [1,3]`; window, merge and position indices are derived in the graph |
+| `minicpmv4_7` | `vision_embeddings` | packed `pixel_values [1,3,patch,N*patch]`, `position_ids [N]`, `patch_grid [2]`, `merge_index`; the two-stage merger also uses `window_index` |
| `qwen3vl_merger` | `vision_embeddings`, `vision_embeddings_pos`, `vision_embeddings_merger` | flattened patches `hidden_states`; position-table indices `input [4,N]`; `hidden_states`, `attention_mask [1,N,N]`, `rotary_pos_emb [N,head/2]` |
The adapted vision graphs preserve llama.cpp computation: Gemma4 retains GELU_QUICK unless the
diff --git a/src/frontends/gguf/docs/supported_models.md b/src/frontends/gguf/docs/supported_models.md
index 833beb0b168..fae37b46f84 100644
--- a/src/frontends/gguf/docs/supported_models.md
+++ b/src/frontends/gguf/docs/supported_models.md
@@ -23,6 +23,7 @@ with the [strict accuracy settings](quantization.md#accuracy-controls) (`OV_GGUF
| Architecture | Notes | Real checkpoint | Choices |
|---|---|---|---|
+| `afmoe` | Dense lead, routed/shared experts, sigmoid gating, pre/post norms, three sliding layers then one global NoPE layer; F32 oracle fixture | — | |
| `bailingmoe2` | Sigmoid routing, biased/grouped selection, shared experts | Ling-mini-2.0 Q2_K | 12/13 |
| `deepseek2-ocr` | Language backbone: dense lead layers, shared/routed experts | DeepSeek-OCR-2 Q4_K_M | 13/13 |
| `ernie4_5-moe` | Interleaved MoE, biased selection, normalized weights, shared experts | ERNIE-4.5-21B-A3B-PT Q4_K_M | 12/13 |
diff --git a/src/frontends/gguf/examples/architecture_extension/extension.cpp b/src/frontends/gguf/examples/architecture_extension/extension.cpp
index 6d99d128192..3c7252f159b 100644
--- a/src/frontends/gguf/examples/architecture_extension/extension.cpp
+++ b/src/frontends/gguf/examples/architecture_extension/extension.cpp
@@ -4,5 +4,14 @@
#include "projector.hpp"
-OPENVINO_CREATE_EXTENSIONS(std::vector<ov::Extension::Ptr>{
- std::make_shared<ov::frontend::gguf::ArchitectureExtension>(example::projector_architecture())});
+namespace {
+std::vector<ov::Extension::Ptr> make_projector_extensions() {
+ const auto architecture =
+ std::make_shared<ov::frontend::gguf::ArchitectureExtension>(example::projector_architecture());
+ const auto projector =
+ std::make_shared<ov::frontend::gguf::ProjectorExtension>(example::vision_projector_component());
+ return {architecture, projector};
+}
+} // namespace
+
+OPENVINO_CREATE_EXTENSIONS(make_projector_extensions());
diff --git a/src/frontends/gguf/examples/architecture_extension/projector.cpp b/src/frontends/gguf/examples/architecture_extension/projector.cpp
index a942cdad774..10e745189c0 100644
--- a/src/frontends/gguf/examples/architecture_extension/projector.cpp
+++ b/src/frontends/gguf/examples/architecture_extension/projector.cpp
@@ -6,6 +6,9 @@
#include "openvino/core/except.hpp"
#include "openvino/frontend/gguf/builder/graph_context.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/result.hpp"
namespace example {
namespace {
@@ -36,4 +39,27 @@ ov::frontend::gguf::ArchitectureDefinition projector_architecture() {
return std::make_shared<Projector>(context);
}};
}
+ov::frontend::gguf::ProjectorDefinition vision_projector_component() {
+ using namespace ov::frontend::gguf;
+ return {
+ "clip.vision.example-adapter",
+ "clip",
+ "vision",
+ "example-adapter",
+ [](GgufGraphContext& graph) {
+ const auto weight = graph.tensors().require("projection.weight");
+ const auto input = graph.add_input("vision.embeddings_input", ov::element::f32, {1, 1, -1, weight.ne(0)});
+ return ProjectorResult{graph.node("GGML_OP_MUL_MAT", {weight, input}), {}, ProjectorLayout::Image};
+ },
+ {},
+ {},
+ [](const std::shared_ptr<ov::Model>& model) {
+ auto result = model->get_results().front();
+ auto output = std::make_shared<ov::op::v1::Add>(result->input_value(0),
+ ov::op::v0::Constant::create(ov::element::f32, {}, {7.f}));
+ output->output(0).set_names({"last_hidden_state"});
+ result->input(0).replace_source_output(output);
+ return ModelAdapterResult{model, {{"custom_vision", model}}};
+ }};
+}
} // namespace example
diff --git a/src/frontends/gguf/examples/architecture_extension/projector.hpp b/src/frontends/gguf/examples/architecture_extension/projector.hpp
index 594631aed51..762f8ce3020 100644
--- a/src/frontends/gguf/examples/architecture_extension/projector.hpp
+++ b/src/frontends/gguf/examples/architecture_extension/projector.hpp
@@ -5,7 +5,9 @@
#pragma once
#include "openvino/frontend/gguf/extension/architecture.hpp"
+#include "openvino/frontend/gguf/extension/projector.hpp"
namespace example {
ov::frontend::gguf::ArchitectureDefinition projector_architecture();
-}
+ov::frontend::gguf::ProjectorDefinition vision_projector_component();
+} // namespace example
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp
index 2ccb32ea88a..b68b26b7050 100644
--- a/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp
@@ -9,16 +9,25 @@
#include <functional>
#include <map>
#include <memory>
+#include <optional>
#include <string>
#include <vector>
#include "openvino/core/any.hpp"
#include "openvino/core/node.hpp"
#include "openvino/frontend/decoder.hpp"
+#include "openvino/frontend/gguf/model_adapter.hpp"
#include "openvino/frontend/gguf/visibility.hpp"
namespace ov::frontend::gguf {
+struct ModelContract {
+ enum class ImageAttentionMode { CAUSAL, GLOBAL_AND_SLIDING, SLIDING_ONLY };
+
+ std::optional<bool> batchable_recurrent;
+ ImageAttentionMode image_attention = ImageAttentionMode::CAUSAL;
+};
+
// Typed RoPE configuration, replacing the raw gguf `op_params`/`rope_params` int32 array
// the translators used to dereference by byte offset. A decoder is responsible for
// producing this (the llama.cpp cgraph decoder by parsing ggml's layout, a future
@@ -159,6 +168,22 @@ public:
return empty;
}
+ /// \brief Resolved model semantics for shared conversion and runtime adaptation.
+ virtual ModelContract get_model_contract() const {
+ return {};
+ }
+
+ /// \brief Architecture identifier for diagnostics and converted-model metadata.
+ virtual std::string get_architecture() const {
+ return {};
+ }
+
+ /// \brief Builder-provided graph adapters applied during model conversion.
+ virtual const ModelAdapters& get_model_adapters() const {
+ static const ModelAdapters empty;
+ return empty;
+ }
+
// RoPE configuration, exposed through get_attribute<RopeConfig>("rope_config"):
// - at model scope (via InputModel::get_rope_config), used by TranslateSession::preprocess
// to pre-build the shared rope sin/cos table (skipped when RopeConfig::n_dims == 0, i.e.
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/model_adapter.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/model_adapter.hpp
new file mode 100644
index 00000000000..f0880b4833e
--- /dev/null
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/model_adapter.hpp
@@ -0,0 +1,36 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <functional>
+#include <map>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "openvino/core/extension.hpp"
+#include "openvino/core/model.hpp"
+
+namespace ov::frontend::gguf {
+
+using ModelMap = std::map<std::string, std::shared_ptr<ov::Model>>;
+
+struct ModelAdapterResult {
+ std::shared_ptr<ov::Model> model;
+ ModelMap models;
+};
+
+// The supplied graph is an independent clone; the result identifies the graph to commit.
+using ModelAdapterFn = std::function<ModelAdapterResult(const std::shared_ptr<ov::Model>&)>;
+
+struct ModelAdapter {
+ // Destroy the callback before releasing the libraries that implement it.
+ std::vector<ov::Extension::Ptr> lifetime;
+ ModelAdapterFn transform;
+};
+
+using ModelAdapters = std::map<std::string, std::shared_ptr<ModelAdapter>>;
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/api/graph_context.cpp b/src/frontends/gguf/src/builder/api/graph_context.cpp
index 7b3315f469e..a98e44164ed 100644
--- a/src/frontends/gguf/src/builder/api/graph_context.cpp
+++ b/src/frontends/gguf/src/builder/api/graph_context.cpp
@@ -39,26 +39,29 @@ const GgufMetadata& GgufGraphContext::metadata() const {
}
DecoderDimensions GgufGraphContext::configure_decoder(RopeMode rope, const DecoderOptions& options) {
+ return configure_decoder(resolve_decoder_parameters(metadata(), rope, options));
+}
+
+DecoderDimensions GgufGraphContext::configure_decoder(const DecoderParameters& parameters) {
m_impl->check_open();
OPENVINO_ASSERT(!m_impl->decoder, "[GGUF] decoder is already configured");
- auto normalized = decoder_config_from_meta(detail::MetadataAccess::get(metadata()).map);
- m_impl->emitter.configure_hadamard(normalized);
- auto config = std::make_unique<DecoderConfig>(normalized, m_impl->build_ctx.weights->weights, rope, options);
- auto& graph = *m_impl->emitter.graph();
- graph.has_rope = true;
- graph.rope_config = config->rope_config;
- graph.use_per_op_rope = config->use_per_op_rope;
- graph.swa_window_size = config->swa_window_size;
+ auto config = std::make_unique<DecoderConfig>(parameters, m_impl->build_ctx.weights->weights);
+ config->configure_graph(m_impl->emitter, metadata());
const DecoderDimensions dimensions{config->n_layer, config->n_embd, config->rms_eps};
m_impl->kv = blocks::KvCachePlan::build(*config);
m_impl->decoder = std::move(config);
return dimensions;
}
+void GgufGraphContext::configure_model_contract(const ModelContract& contract) {
+ m_impl->check_open();
+ m_impl->emitter.graph()->model_contract = contract;
+}
+
DecoderLayerParameters GgufGraphContext::decoder_layer_parameters(int layer) const {
m_impl->check_layer(layer);
const auto& cfg = *m_impl->decoder;
- return {cfg.n_head,
+ return {cfg.layer_n_head(layer),
cfg.layer_n_head_kv(layer),
cfg.layer_head_size(layer),
cfg.layer_kq_scale(layer),
diff --git a/src/frontends/gguf/src/builder/api/metadata.cpp b/src/frontends/gguf/src/builder/api/metadata.cpp
index 94802c4d08a..b9305161a65 100644
--- a/src/frontends/gguf/src/builder/api/metadata.cpp
+++ b/src/frontends/gguf/src/builder/api/metadata.cpp
@@ -4,6 +4,8 @@
#include "openvino/frontend/gguf/builder/metadata.hpp"
+#include <algorithm>
+#include <limits>
#include <type_traits>
#include "builder/api/metadata_store.hpp"
@@ -24,6 +26,15 @@ std::vector<T> tensor_values(const ov::Tensor& tensor) {
if (type == ov::element::string || type.is_dynamic() ||
(!type.is_integral() && !(std::is_floating_point_v<T> && type.is_real())))
return {};
+ if constexpr (std::is_integral_v<T>) {
+ if (type == ov::element::u64) {
+ const auto* data = tensor.data<const uint64_t>();
+ if (std::any_of(data, data + tensor.get_size(), [](uint64_t value) {
+ return value > static_cast<uint64_t>(std::numeric_limits<T>::max());
+ }))
+ return {};
+ }
+ }
return ov::op::v0::Constant(tensor).cast_vector<T>();
}
diff --git a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp b/src/frontends/gguf/src/builder/arch/decoder_builder.cpp
index 31e8fad61c4..feefae6c101 100644
--- a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/decoder_builder.cpp
@@ -17,6 +17,7 @@
#include <cmath>
+#include "builder/api/metadata_store.hpp"
#include "builder/blocks/common.hpp"
#include "builder/blocks/ffn.hpp"
#include "builder/blocks/gated_delta_net.hpp"
@@ -39,21 +40,11 @@ namespace {
constexpr int64_t D = -1;
} // namespace
-DecoderBuilder::DecoderBuilder(const std::map<std::string, GGUFMetaData>& config,
- std::unordered_map<std::string, ov::Tensor>& weights,
- std::unordered_map<std::string, GgufTensorType>& qtypes,
- std::optional<RopeMode> rope,
- const DecoderOptions& options,
- const std::unordered_map<std::string, CreatorFunction>* translators)
- : m_cfg(config, weights, rope, options),
- m_emit(weights, qtypes, m_cfg.arch, translators),
+DecoderBuilder::DecoderBuilder(const BuildContext& context, const DecoderParameters& parameters)
+ : m_cfg(parameters, context.weights->weights),
+ m_emit(context.weights->weights, context.weights->qtypes, context.arch, context.weights->translators),
m_kv(blocks::KvCachePlan::build(m_cfg)) {
- m_emit.configure_hadamard(config);
- auto& graph = *m_emit.graph();
- graph.has_rope = true;
- graph.rope_config = m_cfg.rope_config;
- graph.use_per_op_rope = m_cfg.use_per_op_rope;
- graph.swa_window_size = m_cfg.swa_window_size;
+ m_cfg.configure_graph(m_emit, context.metadata);
}
void DecoderBuilder::build_inputs() {
@@ -243,11 +234,14 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
const std::string attn_norm =
m_cfg.post_norm_only ? cur : norm(m_emit, cur, p + m_cfg.attn_norm_key, p + "attn_norm", m_cfg.rms_eps);
- if (m_cfg.is_qwen35 && m_cfg.is_recurrent_layer(il)) {
+ if (m_cfg.is_recurrent_layer(il)) {
// Hybrid stack: 3 of every 4 layers replace attention with a Gated DeltaNet block.
// It produces the same thing the attention path does -- the sublayer output before
// the residual -- so the shared FFN tail below is reused verbatim.
- const std::string gdn_out = blocks::gated_delta_net(m_emit, m_cfg, il, attn_norm);
+ std::string gdn_out = blocks::gated_delta_net(m_emit, m_cfg, il, attn_norm);
+ if (m_cfg.residual_scale != 1.0f) {
+ gdn_out = blocks::scale(m_emit, gdn_out, m_cfg.residual_scale, p + "attn_out_scaled");
+ }
std::string sa = inpSA;
std::string ao = gdn_out;
if (selects_output_rows(il)) {
@@ -255,7 +249,7 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
sa = m_emit.add_op("GGML_OP_GET_ROWS", p + "inpSA_g", {inpSA, "inp_out_ids"});
}
auto ffn_inp_r = m_emit.add_op("GGML_OP_ADD", p + "ffn_inp", {ao, sa});
- auto ffn_norm_r = blocks::rms_norm(m_emit, ffn_inp_r, p + m_cfg.ffn_norm_key, p + "ffn_norm", m_cfg.rms_eps);
+ auto ffn_norm_r = norm(m_emit, ffn_inp_r, p + m_cfg.ffn_norm_key, p + "ffn_norm", m_cfg.rms_eps);
// Mirror the non-recurrent FFN dispatch below: Qwen3-Next is MoE for every trunk layer
// (llama.cpp routes both the GDN and full-attention layers through build_moe_ffn), so a
// real model has no per-layer dense FFN tensors here and dense_ffn's weight_tensor lookup
@@ -264,6 +258,9 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
auto down_r = is_moe_layer_r ? blocks::moe_ffn(m_emit, m_cfg, p, ffn_norm_r)
: m_cfg.is_geglu ? blocks::geglu_ffn(m_emit, m_cfg, p, ffn_norm_r)
: blocks::dense_ffn(m_emit, m_cfg, p, ffn_norm_r);
+ if (m_cfg.residual_scale != 1.0f) {
+ down_r = blocks::scale(m_emit, down_r, m_cfg.residual_scale, p + "ffn_out_scaled");
+ }
return m_emit.add_op("GGML_OP_ADD", p + "l_out", {down_r, ffn_inp_r});
}
diff --git a/src/frontends/gguf/src/builder/arch/decoder_builder.hpp b/src/frontends/gguf/src/builder/arch/decoder_builder.hpp
index af5a250c515..642380a023a 100644
--- a/src/frontends/gguf/src/builder/arch/decoder_builder.hpp
+++ b/src/frontends/gguf/src/builder/arch/decoder_builder.hpp
@@ -18,27 +18,10 @@
namespace ov::frontend::gguf {
-// Whole-model builder for the causal decoder family: the "llama family" of dense and MoE
-// decoder-only transformers (llama-3, qwen2/2.5/3, phi-3, minicpm, gemma 1-4, gpt-oss, OLMoE,
-// qwen3moe, the qwen35 hybrid Gated-DeltaNet stack, ...).
-//
-// ONE builder covers all of them. Per-architecture differences are resolved into DecoderConfig by
-// structural detection on the GGUF tensor table, so enabling a same-family architecture is a name
-// in arch_registry.cpp and no code here. This is a deliberate departure from llama.cpp's
-// one-file-per-architecture layout, which exists there because each architecture must enumerate
-// its tensors by hand; the GGUF frontend derives them instead.
-//
-// Emits the STATELESS graph: KV caches are plain model Parameters written by GGML_OP_SET_ROWS and
-// read back as Results, and every activation keeps ggml's rank-4 shape. A caller that wants an
-// OpenVINO KV cache registers ov::frontend::gguf::pass::MakeStateful as a transformation extension.
+// Whole-model topology for configured dense, expert and hybrid decoder layers.
class DecoderBuilder : public ModelBuilder {
public:
- DecoderBuilder(const std::map<std::string, GGUFMetaData>& config,
- std::unordered_map<std::string, ov::Tensor>& weights,
- std::unordered_map<std::string, GgufTensorType>& qtypes,
- std::optional<RopeMode> rope = {},
- const DecoderOptions& options = {},
- const std::unordered_map<std::string, CreatorFunction>* translators = nullptr);
+ DecoderBuilder(const BuildContext& context, const DecoderParameters& parameters);
std::shared_ptr<GgufGraph> build() override;
diff --git a/src/frontends/gguf/src/builder/arch/decoder_family.cpp b/src/frontends/gguf/src/builder/arch/decoder_family.cpp
new file mode 100644
index 00000000000..b5fc0c38004
--- /dev/null
+++ b/src/frontends/gguf/src/builder/arch/decoder_family.cpp
@@ -0,0 +1,138 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <algorithm>
+#include <cmath>
+#include <initializer_list>
+#include <limits>
+
+#include "builder/arch_registry.hpp"
+#include "builder/decoder_metadata.hpp"
+#include "openvino/core/except.hpp"
+
+namespace ov::frontend::gguf {
+namespace {
+bool is_one_of(const std::string& arch, std::initializer_list<const char*> names) {
+ return std::any_of(names.begin(), names.end(), [&arch](const char* name) {
+ return arch == name;
+ });
+}
+} // namespace
+
+DecoderParameters decoder_family_defaults(const std::string& arch, int layers, int embedding, int heads) {
+ DecoderParameters p;
+ p.architecture = arch;
+ p.attention.rope_mode = arch_uses_neox_rope(arch) ? RopeMode::Neox : RopeMode::Normal;
+ p.embedding_model = arch == "llama-embed";
+ if (arch == "jais2") {
+ p.normalization.kind = NormalizationKind::Layer;
+ p.activation = FfnActivation::ReluSquared;
+ }
+ if (is_one_of(arch, {"gemma", "gemma2", "gemma3", "gemma4"})) {
+ p.activation = FfnActivation::GeGlu;
+ p.scales.embedding = std::sqrt(static_cast<float>(embedding));
+ }
+ if (arch == "afmoe")
+ p.scales.embedding = std::sqrt(static_cast<float>(embedding));
+ if (arch.rfind("minicpm", 0) == 0) {
+ p.scales.embedding = 12.0f;
+ p.scales.residual = 1.4f / std::sqrt(static_cast<float>(layers));
+ // logit_scale is a divisor; correct upstream's inverted missing-key default.
+ p.scales.logits = static_cast<float>(embedding) / 256.0f;
+ }
+ p.normalization.qk_after_rope = is_one_of(arch, {"hunyuan-dense", "hunyuan-moe", "maincoder"});
+ p.normalization.post_only = arch == "exaone4";
+ p.normalization.value_norm = arch == "gemma4";
+ if (arch == "gemma4") {
+ p.normalization.qk_full_width = false;
+ p.scales.attention = 1.0f;
+ } else if (arch == "gemma2" && layers == 46 && heads > 0) {
+ p.scales.attention = 1.0f / std::sqrt(static_cast<float>(embedding / heads));
+ }
+ p.scales.token_embeddings_only = is_one_of(arch, {"gemma3", "gemma4"});
+ p.attention.sliding_window = p.scales.token_embeddings_only;
+ p.attention.window_size = (arch == "gemma2" || (arch == "exaone4" && layers == 64)) ? 4096 : 0;
+ p.attention.sliding_period = arch == "gemma3" ? 6
+ : arch == "plamo3" ? 8
+ : (arch == "afmoe" || arch == "exaone4" || arch == "exaone-moe") ? 4
+ : 2;
+ if (is_one_of(arch, {"gemma3", "plamo3"}))
+ p.attention.sliding_rope.freq_base = 10000.0f;
+ // Zero inherits the global scale; local Gemma RoPE retains its training scale.
+ if (is_one_of(arch, {"gemma3", "gemma4"}))
+ p.attention.sliding_rope.freq_scale = 1.0f;
+ if (arch == "muse-glimmer") {
+ p.normalization.embedding_norm = true;
+ p.normalization.post_epsilon = 1e-8f;
+ }
+ p.attention.rope_on_sliding_only =
+ arch == "muse-glimmer" || arch == "exaone-moe" || (arch == "exaone4" && layers == 64);
+ if (is_one_of(arch, {"afmoe", "smollm3"}))
+ p.attention.rope_skip_period = 4;
+ p.experts.normalize_weights =
+ is_one_of(arch, {"hunyuan-moe", "minimax-m2", "qwen3moe", "qwen35moe", "ernie4_5-moe", "mellum", "gemma4"});
+ if (is_one_of(arch, {"afmoe", "glm4moe"}))
+ p.experts.routing = ExpertRouting::Sigmoid;
+ if (is_one_of(arch, {"qwen35", "qwen35moe"})) {
+ p.hybrid.kind = RecurrentKind::GatedDeltaNet;
+ p.attention.rope_mode = RopeMode::Interleaved;
+ p.attention.interleaved_q_gate = true;
+ p.attention.fused_qkv = false;
+ p.attention.output_gate = true;
+ p.normalization.qk_norm = true;
+ p.normalization.qk_full_width = false;
+ p.model_contract.batchable_recurrent = true;
+ }
+ if (is_one_of(arch, {"lfm2", "lfm2moe"})) {
+ p.attention.sliding_on_attention_layers = true;
+ p.model_contract.batchable_recurrent = true;
+ }
+ if (arch == "gemma3")
+ p.model_contract.image_attention = ModelContract::ImageAttentionMode::GLOBAL_AND_SLIDING;
+ if (arch == "gemma4" && embedding != 1536 && embedding != 2560)
+ p.model_contract.image_attention = ModelContract::ImageAttentionMode::SLIDING_ONLY;
+ return p;
+}
+
+DecoderParameters resolve_decoder_parameters(const GgufMetadata& metadata,
+ RopeMode rope,
+ const DecoderOptions& options) {
+ const auto architecture = metadata.get_str("general.architecture");
+ OPENVINO_ASSERT(architecture, "[GGUF] missing or non-string general.architecture");
+ const auto dimension = [&](const std::string& suffix) {
+ auto value = metadata.get_int(*architecture + "." + suffix);
+ if (!value && suffix == "attention.head_count") {
+ const auto heads = metadata.get_int_array(*architecture + "." + suffix);
+ if (!heads.empty())
+ value = *std::max_element(heads.begin(), heads.end());
+ }
+ OPENVINO_ASSERT(value && *value > 0 && *value <= std::numeric_limits<int>::max(),
+ "[GGUF] invalid required decoder dimension '",
+ *architecture,
+ ".",
+ suffix,
+ "'");
+ return static_cast<int>(*value);
+ };
+ auto defaults = decoder_family_defaults(*architecture,
+ dimension("block_count"),
+ dimension("embedding_length"),
+ dimension("attention.head_count"));
+ defaults.attention.rope_mode = rope;
+ if (options.normalization)
+ defaults.normalization.kind = *options.normalization;
+ if (options.norm_epsilon)
+ defaults.normalization.epsilon = *options.norm_epsilon;
+ auto p = read_decoder_parameters(metadata, defaults);
+ // llama.cpp always renormalizes top-K weights for these built-in families.
+ p.experts.normalize_weights = defaults.experts.normalize_weights || p.experts.normalize_weights;
+ if (p.architecture.rfind("minicpm", 0) == 0 && p.scales.logits != 0.0f)
+ p.scales.logits = 1.0f / p.scales.logits;
+ if (p.architecture == "lfm2moe")
+ p.experts.weights_scale = 0.0f;
+ apply_decoder_options(p, options);
+ return p;
+}
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/arch/dspark_builder.cpp b/src/frontends/gguf/src/builder/arch/dspark_builder.cpp
index af49bd74d84..ac33d91a5ff 100644
--- a/src/frontends/gguf/src/builder/arch/dspark_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/dspark_builder.cpp
@@ -12,6 +12,7 @@
#include "builder/blocks/common.hpp"
#include "builder/blocks/ffn.hpp"
#include "builder/decoder_config.hpp"
+#include "builder/metadata_checks.hpp"
namespace ov::frontend::gguf {
namespace {
@@ -19,18 +20,14 @@ class DSparkBuilder : public ModelBuilder {
public:
explicit DSparkBuilder(const BuildContext& context)
: m_metadata(context.metadata),
- m_config(decoder_config_from_meta(detail::MetadataAccess::get(context.metadata).map),
- context.weights->weights,
- RopeMode::Neox),
+ m_config(resolve_decoder_parameters(context.metadata, RopeMode::Neox), context.weights->weights),
m_emitter(context.weights->weights, context.weights->qtypes, context.arch, context.weights->translators) {}
std::shared_ptr<GgufGraph> build() override {
using ov::element::f32;
using ov::element::i32;
const auto required_int = [&](const std::string& name) {
- const auto value = m_metadata.get_int("dspark.dspark." + name);
- OPENVINO_ASSERT(value && *value > 0, "[GGUF] invalid DSpark ", name);
- return *value;
+ return require_positive_int(m_metadata, "dspark.dspark." + name, "DSpark");
};
const auto block = required_int("block_size");
OPENVINO_ASSERT(block <= 4096, "[GGUF] DSpark block_size exceeds the supported maximum of 4096");
@@ -45,9 +42,7 @@ public:
OPENVINO_ASSERT(!m_metadata.get_bool("dspark.dspark.hidden_correction").value_or(false),
"[GGUF] DSpark hidden correction is not supported");
auto& e = m_emitter;
- auto& graph = *e.graph();
- graph.has_rope = true;
- graph.rope_config = m_config.rope_config;
+ m_config.configure_graph(e, m_metadata);
const auto kv = blocks::KvCachePlan::build(m_config);
e.add_input("inp_tokens", i32, ps({1, 1, 1, block}));
e.add_input("inp_pos", i32, ps({1, 1, 1, -1}));
@@ -118,6 +113,7 @@ public:
logits_value.set_names({"logits"});
auto hidden_value = e.value(hidden);
hidden_value.set_names({"dspark.hidden"});
+ auto& graph = *e.graph();
graph.model_output_names.insert(graph.model_output_names.begin(), {logits, hidden});
std::string latent;
if (markov_rank > 0) {
@@ -147,6 +143,7 @@ public:
confidence_value.set_names({"dspark.confidence_score"});
graph.model_output_names.push_back(confidence);
}
+ e.validate_hadamard();
return e.graph();
}
diff --git a/src/frontends/gguf/src/builder/arch/lfm2_builder.cpp b/src/frontends/gguf/src/builder/arch/lfm2_builder.cpp
index ea09a1dcf37..d23944319e2 100644
--- a/src/frontends/gguf/src/builder/arch/lfm2_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/lfm2_builder.cpp
@@ -7,6 +7,7 @@
#include <cmath>
#include <limits>
+#include "builder/decoder_metadata.hpp"
#include "openvino/frontend/gguf/builder/graph_context.hpp"
namespace ov::frontend::gguf {
@@ -23,7 +24,8 @@ public:
"[GGUF] noncausal LFM2 embedding models require a centered convolution builder");
DecoderOptions options;
options.normalize_expert_weights = true;
- const auto dims = g.configure_decoder(RopeMode::Neox, options);
+ const auto parameters = resolve_decoder_parameters(g.metadata(), RopeMode::Neox, options);
+ const auto dims = g.configure_decoder(parameters);
OPENVINO_ASSERT(dims.layers > 0 && dims.embedding > 0,
"[GGUF] LFM2 requires positive layer and embedding counts");
g.build_inp_pos();
diff --git a/src/frontends/gguf/src/builder/arch/mamba_builder.cpp b/src/frontends/gguf/src/builder/arch/mamba_builder.cpp
index c212d0e318d..9a6d736dab4 100644
--- a/src/frontends/gguf/src/builder/arch/mamba_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/mamba_builder.cpp
@@ -7,6 +7,8 @@
#include <cmath>
#include <limits>
+#include "builder/decoder_metadata.hpp"
+#include "builder/metadata_checks.hpp"
#include "openvino/frontend/gguf/builder/graph_context.hpp"
namespace ov::frontend::gguf {
@@ -21,13 +23,7 @@ public:
std::shared_ptr<GgufGraph> build() override {
const auto positive = [&](const std::string& suffix) {
- const auto key = g.arch() + "." + suffix;
- const auto value = g.metadata().get_int(key);
- OPENVINO_ASSERT(value && *value > 0 && *value <= std::numeric_limits<int>::max(),
- "[GGUF] Mamba2 requires positive metadata '",
- key,
- "'");
- return *value;
+ return require_positive_int(g.metadata(), g.arch() + "." + suffix, "Mamba2");
};
const auto layers = positive("block_count");
const auto inner = positive("ssm.inner_size");
@@ -40,10 +36,7 @@ public:
"and conv_kernel > 1");
const auto head_dim = inner / heads;
const auto conv_dim = inner + 2 * groups * state_size;
- const auto eps_value = g.metadata().get_float(g.arch() + ".attention.layer_norm_rms_epsilon");
- OPENVINO_ASSERT(eps_value && std::isfinite(*eps_value) && *eps_value > 0,
- "[GGUF] Mamba2 requires a positive RMS normalization epsilon");
- const auto eps = static_cast<float>(*eps_value);
+ const auto eps = require_positive_float(g.metadata(), g.arch() + ".attention.layer_norm_rms_epsilon", "Mamba2");
auto weights = g.tensors();
const bool hybrid = g.arch() == "nemotron_h";
if (hybrid) {
@@ -51,7 +44,7 @@ public:
"[GGUF] Nemotron-H MoE is not supported by the dense builder");
DecoderOptions options;
options.rope_skip_period = 1; // Nemotron-H attention has no positional embedding.
- g.configure_decoder(RopeMode::Normal, options);
+ g.configure_decoder(resolve_decoder_parameters(g.metadata(), RopeMode::Normal, options));
g.build_attn_inp_kv();
}
auto cur = g.build_inp_embd(weights.require("token_embd.weight"));
diff --git a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
index eb0c06855c4..484fe770999 100644
--- a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
@@ -13,8 +13,10 @@
#include "builder/api/metadata_store.hpp"
#include "builder/gguf_graph.hpp"
+#include "builder/metadata_checks.hpp"
#include "builder/projector_registry.hpp"
#include "openvino/frontend/gguf/builder/graph_context.hpp"
+#include "projector_adapter.hpp"
namespace ov::frontend::gguf {
namespace {
@@ -75,6 +77,7 @@ constexpr ProjectorTopology projector_catalog[] = {
{"audio", "lfm2a", EncoderTopology::LFM2_AUDIO},
{"audio", "gemma4ua", EncoderTopology::UNIFIED_AUDIO},
{"vision", "minicpmv4_6", EncoderTopology::MINICPM46},
+ {"vision", "minicpmv4_7", EncoderTopology::MINICPM46},
{"vision", "gemma3", EncoderTopology::SIGLIP, SWAPPED_FFN},
{"vision", "idefics3", EncoderTopology::SIGLIP, SWAPPED_FFN},
{"vision", "janus_pro", EncoderTopology::SIGLIP},
@@ -110,12 +113,7 @@ bool rms_encoder(const EncoderConfig& c) {
}
int64_t positive(const GgufMetadata& meta, const std::string& key) {
- const auto value = meta.get_int(key);
- OPENVINO_ASSERT(value && *value > 0 && *value <= std::numeric_limits<int>::max(),
- "[GGUF] mmproj requires a positive integer '",
- key,
- "'");
- return *value;
+ return require_positive_int(meta, key, "mmproj");
}
EncoderConfig config(const GgufMetadata& meta, const std::string& modality, const std::string& projector) {
@@ -156,9 +154,8 @@ EncoderConfig config(const GgufMetadata& meta, const std::string& modality, cons
: *std::max_element(c.feature_layers.begin(), c.feature_layers.end());
}
OPENVINO_ASSERT(c.width % c.heads == 0, "[GGUF] mmproj embedding width must be divisible by head count");
- const auto eps = meta.get_float(key + "attention.layer_norm_epsilon");
- OPENVINO_ASSERT(eps && std::isfinite(*eps) && *eps > 0, "[GGUF] invalid ", key, "attention.layer_norm_epsilon");
- c.eps = c.topology == EncoderTopology::GEMMA4_AUDIO ? 1e-6f : static_cast<float>(*eps);
+ const float eps = require_positive_float(meta, key + "attention.layer_norm_epsilon", "mmproj");
+ c.eps = c.topology == EncoderTopology::GEMMA4_AUDIO ? 1e-6f : eps;
const bool gelu = meta.get_bool("clip.use_gelu").value_or(false);
const bool silu = meta.get_bool("clip.use_silu").value_or(false);
OPENVINO_ASSERT(!(gelu && silu), "[GGUF] mmproj cannot enable both GELU and SiLU");
@@ -198,8 +195,8 @@ EncoderConfig config(const GgufMetadata& meta, const std::string& modality, cons
if (c.topology == EncoderTopology::MINICPM46) {
auto layers = meta.get_int_array(key + "wa_layer_indexes");
c.window_pattern = layers.empty() ? 0 : layers.front();
- OPENVINO_ASSERT(c.merge == 4 && c.window_pattern >= 0 && c.window_pattern < c.layers,
- "[GGUF] invalid minicpmv4_6 merger configuration");
+ OPENVINO_ASSERT((c.merge == 2 || c.merge == 4) && c.window_pattern >= 0 && c.window_pattern < c.layers,
+ "[GGUF] invalid MiniCPM-V merger configuration");
}
return c;
}
@@ -251,6 +248,13 @@ public:
c.rms = rms_encoder(c);
clippable = c.topology == EncoderTopology::GEMMA4 || c.topology == EncoderTopology::GEMMA4_AUDIO;
ProjectorResult result;
+ if (c.topology == EncoderTopology::MINICPM46) {
+ const auto positions = g.tensors().require("v.position_embd.weight").ne(1);
+ const auto side = int64_t(std::sqrt(double(positions)));
+ OPENVINO_ASSERT(positions > 0 && side * side == positions,
+ "[GGUF] MiniCPM-V requires a square learned position grid");
+ result.config["vision.position_grid_size"] = std::to_string(side);
+ }
result.output = modality == "vision" ? vision(c) : audio(c);
result.config[modality + ".merge"] = std::to_string(c.merge);
if (c.topology == EncoderTopology::MUSE_GLIMMER)
@@ -714,6 +718,14 @@ private:
auto pixels = g.add_input("vision.pixel_values", ov::element::f32, {1, 3, -1, -1});
auto x = patch_embeddings(convolution(pixels, "v.patch_embd.weight", c.patch), c.width);
auto learned = gather_rows(g.tensors().require("v.position_embd.weight"), "position_ids");
+ if (c.merge == 2) {
+ x = vit(x, c, learned);
+ std::array<GgufValue, 4> parts;
+ for (int i = 0; i < 4; ++i)
+ parts[i] = gather_rows(x, "merger.indices." + std::to_string(i));
+ auto cat = concat(concat(concat(parts[0], parts[1]), parts[2]), parts[3]);
+ return ffn(norm(cat, "mm.input_norm", c.eps), "mm.up", "mm.down", "GGML_UNARY_OP_GELU_ERF");
+ }
x = vit(x, c, learned, {}, {}, {}, 0, c.window_pattern + 1, false);
const std::string p = "v.vit_merger.";
auto z = gather_rows(norm(x, p + "ln1", c.eps), "window_indices");
@@ -1199,6 +1211,7 @@ public:
encoders.push_back(definition);
}
OPENVINO_ASSERT(!encoders.empty(), "[GGUF] mmproj has no encoder");
+ ModelAdapters adapters;
std::map<std::string, std::string> branch_config;
branch_config["vision.auxiliary_count"] = "0";
for (const auto& definition : encoders) {
@@ -1211,8 +1224,18 @@ public:
branch_config[entry.first] = entry.second;
}
branch_config[definition->modality + ".projector"] = definition->projector_type;
+ const auto layout =
+ result.genai_layout.value_or(definition->genai_layout.value_or(ProjectorLayout::Unsupported));
+ branch_config[definition->modality + ".genai_layout"] = projector_layout_name(layout);
+ auto callback = result.genai_adapter.value_or(definition->genai_adapter);
+ if (callback) {
+ auto adapter = std::make_shared<ModelAdapter>();
+ adapter->transform = std::move(callback);
+ adapters[definition->modality + ".embeddings"] = std::move(adapter);
+ }
}
auto graph = g.finish();
+ graph->model_adapters = std::move(adapters);
const auto number = [](auto value) {
std::ostringstream stream;
stream.precision(std::numeric_limits<double>::max_digits10);
@@ -1263,7 +1286,13 @@ private:
ProjectorResult build_builtin_projector(GgufGraphContext& graph,
const std::string& modality,
const std::string& projector_type) {
- return BuiltinProjectorBuilder(graph).build(modality, projector_type);
+ auto result = BuiltinProjectorBuilder(graph).build(modality, projector_type);
+ if (modality == "vision") {
+ const auto layout = builtin_projector_layout(projector_type);
+ if (layout != ProjectorLayout::Unsupported)
+ result.genai_layout = layout;
+ }
+ return result;
}
std::vector<ProjectorDefinition> builtin_projectors() {
diff --git a/src/frontends/gguf/src/builder/arch/projector_adapter.cpp b/src/frontends/gguf/src/builder/arch/projector_adapter.cpp
new file mode 100644
index 00000000000..b1a269de1b9
--- /dev/null
+++ b/src/frontends/gguf/src/builder/arch/projector_adapter.cpp
@@ -0,0 +1,530 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "projector_adapter.hpp"
+
+#include <limits>
+#include <stdexcept>
+#include <utility>
+
+#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/equal.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/scatter_update.hpp"
+#include "openvino/op/select.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "utils.hpp"
+
+namespace ov::frontend::gguf {
+namespace {
+using namespace ov::op;
+using Value = ov::Output<ov::Node>;
+using Models = ProjectorModels;
+
+Value range(const Value& count) {
+ auto axis = v0::Constant::create(ov::element::i64, {1}, {0});
+ auto start = v0::Constant::create(ov::element::i64, {}, {0});
+ auto step = v0::Constant::create(ov::element::i64, {}, {1});
+ auto stop = std::make_shared<v0::Squeeze>(count, axis);
+ auto indices = std::make_shared<v4::Range>(start, stop, step, ov::element::i64);
+ return indices;
+}
+
+std::shared_ptr<v0::Parameter> parameter(const std::shared_ptr<ov::Model>& model, const std::string& name) {
+ auto candidate = find_parameter(model, name);
+ OPENVINO_ASSERT(candidate, "[GGUF] mmproj vision encoder has no input ", name);
+ return candidate;
+}
+
+Value flat_index(const Value& value) {
+ auto index_shape = v0::Constant::create(ov::element::i64, {4}, {1, 1, 1, -1});
+ return std::make_shared<v1::Reshape>(value, index_shape, false);
+}
+
+void require_square_fits(int64_t value, int64_t factor, const char* key) {
+ OPENVINO_ASSERT(value <= std::numeric_limits<int64_t>::max() / factor / value,
+ "[GGUF] out-of-range mmproj metadata ",
+ key);
+}
+
+void replace_input(const std::shared_ptr<ov::Model>& model, const std::string& name, Value value) {
+ auto source = parameter(model, name);
+ if (value.get_element_type() != source->get_element_type()) {
+ auto converted = std::make_shared<v0::Convert>(value, source->get_element_type());
+ value = converted;
+ }
+ 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();
+}
+
+// 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;
+}
+
+Value image_from_patches(const Value& patches,
+ const Value& rows,
+ const Value& cols,
+ int64_t patch,
+ bool channels_last) {
+ auto p = v0::Constant::create(ov::element::i64, {1}, {patch});
+ auto c = v0::Constant::create(ov::element::i64, {1}, {3});
+ auto grid = channels_last ? ov::OutputVector{rows, cols, p, p, c} : ov::OutputVector{rows, cols, c, p, p};
+ auto grid_shape = std::make_shared<v0::Concat>(grid, 0);
+ auto patch_grid = std::make_shared<v1::Reshape>(patches, grid_shape, false);
+ auto order =
+ v0::Constant::create(ov::element::i64,
+ {5},
+ channels_last ? std::vector<int64_t>{4, 0, 2, 1, 3} : std::vector<int64_t>{2, 0, 3, 1, 4});
+ auto image_grid = std::make_shared<v1::Transpose>(patch_grid, order);
+ auto batch_channels = v0::Constant::create(ov::element::i64, {2}, {1, 3});
+ auto patch_size = v0::Constant::create(ov::element::i64, {}, {patch});
+ auto height = std::make_shared<v1::Multiply>(rows, patch_size);
+ auto width = std::make_shared<v1::Multiply>(cols, patch_size);
+ auto image_shape = std::make_shared<v0::Concat>(ov::OutputVector{batch_channels, height, width}, 0);
+ auto image = std::make_shared<v1::Reshape>(image_grid, image_shape, false);
+ return image;
+}
+
+void squeeze_output(const std::shared_ptr<ov::Model>& model) {
+ auto result = model->get_results().front();
+ auto axis = v0::Constant::create(ov::element::i64, {1}, {0});
+ auto features = std::make_shared<v0::Squeeze>(result->input_value(0), axis);
+ 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 padded_patch_layout(const std::shared_ptr<ov::Model>& model, int64_t patch) {
+ require_square_fits(patch, 3, "vision.patch_size");
+ auto pixels = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, -1, 3 * patch * patch});
+ auto positions = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{1, -1, 2});
+ auto zero_axis = v0::Constant::create(ov::element::i64, {1}, {0});
+ auto one_step = v0::Constant::create(ov::element::i64, {1}, {1});
+ auto zero = v0::Constant::create(ov::element::i64, {}, {0});
+ auto one = v0::Constant::create(ov::element::i64, {}, {1});
+ auto flat = std::make_shared<v0::Squeeze>(positions, zero_axis);
+ auto x = std::make_shared<v8::Gather>(flat, zero, one);
+ auto y = std::make_shared<v8::Gather>(flat, one, one);
+ auto nonnegative = std::make_shared<v1::GreaterEqual>(x, zero);
+ auto valid_rows = std::make_shared<v0::Convert>(nonnegative, ov::element::i64);
+ auto count = std::make_shared<v1::ReduceSum>(valid_rows, zero_axis, true);
+ auto maximum_x = std::make_shared<v1::ReduceMax>(x, zero_axis, true);
+ auto cols = std::make_shared<v1::Add>(maximum_x, one);
+ auto rows = std::make_shared<v1::Divide>(count, cols);
+ auto flat_pixels = std::make_shared<v0::Squeeze>(pixels, zero_axis);
+ auto valid_pixels = std::make_shared<v8::Slice>(flat_pixels, zero_axis, count, one_step, zero_axis);
+ auto valid_x = std::make_shared<v8::Slice>(x, zero_axis, count, one_step, zero_axis);
+ auto valid_y = std::make_shared<v8::Slice>(y, zero_axis, count, one_step, zero_axis);
+ auto image = image_from_patches(valid_pixels, rows, cols, patch, true);
+ auto position_x = flat_index(valid_x);
+ auto position_y = flat_index(valid_y);
+ replace_input(model, "pixel_values", image);
+ replace_input(model, "position_x", position_x);
+ replace_input(model, "position_y", position_y);
+ add_inputs(model, {{"pixel_values", pixels}, {"image_position_ids", positions}});
+}
+
+void windowed_patch_layout(const std::shared_ptr<ov::Model>& model, int64_t patch, int64_t window, int64_t merge) {
+ require_square_fits(patch, 3, "vision.patch_size");
+ require_square_fits(window, 1, "vision.window_size");
+ require_square_fits(merge, 1, "vision.merge");
+ auto pixels = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 3 * patch * patch});
+ auto grid = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{1, 3});
+ auto zero_axis = v0::Constant::create(ov::element::i64, {1}, {0});
+ auto row_index = v0::Constant::create(ov::element::i64, {1}, {1});
+ auto col_index = v0::Constant::create(ov::element::i64, {1}, {2});
+ auto zero = v0::Constant::create(ov::element::i64, {}, {0});
+ auto one = v0::Constant::create(ov::element::i64, {}, {1});
+ auto thw = std::make_shared<v0::Squeeze>(grid, zero_axis);
+ auto rows = std::make_shared<v8::Gather>(thw, row_index, zero);
+ auto cols = std::make_shared<v8::Gather>(thw, col_index, zero);
+ auto image = image_from_patches(pixels, rows, cols, patch, false);
+ replace_input(model, "pixel_values", image);
+
+ // Slots outside the image repeat the window's first patch and are masked out as keys.
+ const int64_t slots = window * window;
+ auto window_size = v0::Constant::create(ov::element::i64, {}, {window});
+ auto window_padding = v0::Constant::create(ov::element::i64, {}, {window - 1});
+ auto window_slots = v0::Constant::create(ov::element::i64, {}, {slots});
+ auto padded_cols = std::make_shared<v1::Add>(cols, window_padding);
+ auto window_cols = std::make_shared<v1::Divide>(padded_cols, window_size);
+ auto padded_rows = std::make_shared<v1::Add>(rows, window_padding);
+ auto window_rows = std::make_shared<v1::Divide>(padded_rows, window_size);
+ auto window_count = std::make_shared<v1::Multiply>(window_rows, window_cols);
+ auto slot_count = std::make_shared<v1::Multiply>(window_count, window_slots);
+ auto slot = range(slot_count);
+ auto index_in_window = std::make_shared<v1::FloorMod>(slot, window_slots);
+ auto window_index = std::make_shared<v1::Divide>(slot, window_slots);
+ auto window_row = std::make_shared<v1::Divide>(window_index, window_cols);
+ auto window_col = std::make_shared<v1::FloorMod>(window_index, window_cols);
+ auto top = std::make_shared<v1::Multiply>(window_row, window_size);
+ auto left = std::make_shared<v1::Multiply>(window_col, window_size);
+ auto row_in_window = std::make_shared<v1::Divide>(index_in_window, window_size);
+ auto col_in_window = std::make_shared<v1::FloorMod>(index_in_window, window_size);
+ auto y = std::make_shared<v1::Add>(top, row_in_window);
+ auto x = std::make_shared<v1::Add>(left, col_in_window);
+ auto inside_rows = std::make_shared<v1::Less>(y, rows);
+ auto inside_cols = std::make_shared<v1::Less>(x, cols);
+ auto inside = std::make_shared<v1::LogicalAnd>(inside_rows, inside_cols);
+ auto row_offset = std::make_shared<v1::Multiply>(y, cols);
+ auto patch_index = std::make_shared<v1::Add>(row_offset, x);
+ auto top_offset = std::make_shared<v1::Multiply>(top, cols);
+ auto first_patch = std::make_shared<v1::Add>(top_offset, left);
+ auto index = std::make_shared<v1::Select>(inside, patch_index, first_patch);
+ auto patch_indices = flat_index(index);
+ auto patch_x = std::make_shared<v1::FloorMod>(index, cols);
+ auto patch_y = std::make_shared<v1::Divide>(index, cols);
+ auto offset_x = std::make_shared<v1::Add>(patch_x, one);
+ auto offset_y = std::make_shared<v1::Add>(patch_y, one);
+ auto position_x = flat_index(offset_x);
+ auto position_y = flat_index(offset_y);
+ replace_input(model, "patch_indices", patch_indices);
+ replace_input(model, "position_x", position_x);
+ replace_input(model, "position_y", position_y);
+ auto unmasked = v0::Constant::create(ov::element::f32, {}, {0.f});
+ auto masked = v0::Constant::create(ov::element::f32, {}, {-std::numeric_limits<float>::infinity()});
+ auto key_mask = std::make_shared<v1::Select>(inside, unmasked, masked);
+ auto mask_shape = v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{-1, 1, 1, slots});
+ auto window_mask = std::make_shared<v1::Reshape>(key_mask, mask_shape, false);
+ replace_input(model, "window_mask", window_mask);
+
+ auto patch_count = std::make_shared<v1::Multiply>(rows, cols);
+ auto raster = range(patch_count);
+ auto r = std::make_shared<v1::Divide>(raster, cols);
+ auto c = std::make_shared<v1::FloorMod>(raster, cols);
+ auto raster_window_row = std::make_shared<v1::Divide>(r, window_size);
+ auto raster_window_col = std::make_shared<v1::Divide>(c, window_size);
+ auto raster_window_offset = std::make_shared<v1::Multiply>(raster_window_row, window_cols);
+ auto raster_window_index = std::make_shared<v1::Add>(raster_window_offset, raster_window_col);
+ auto raster_slot_offset = std::make_shared<v1::Multiply>(raster_window_index, window_slots);
+ auto raster_row_in_window = std::make_shared<v1::FloorMod>(r, window_size);
+ auto raster_col_in_window = std::make_shared<v1::FloorMod>(c, window_size);
+ auto raster_row_offset = std::make_shared<v1::Multiply>(raster_row_in_window, window_size);
+ auto raster_index_in_window = std::make_shared<v1::Add>(raster_row_offset, raster_col_in_window);
+ auto slot_of = std::make_shared<v1::Add>(raster_slot_offset, raster_index_in_window);
+ auto output_indices = flat_index(slot_of);
+ replace_input(model, "output_indices", output_indices);
+ auto merge_size = v0::Constant::create(ov::element::i64, {}, {merge});
+ auto merge_slots = v0::Constant::create(ov::element::i64, {}, {merge * merge});
+ auto block = std::make_shared<v1::Divide>(raster, merge_slots);
+ auto within = std::make_shared<v1::FloorMod>(raster, merge_slots);
+ auto block_cols = std::make_shared<v1::Divide>(cols, merge_size);
+ auto block_row = std::make_shared<v1::Divide>(block, block_cols);
+ auto block_col = std::make_shared<v1::FloorMod>(block, block_cols);
+ auto block_top = std::make_shared<v1::Multiply>(block_row, merge_size);
+ auto block_left = std::make_shared<v1::Multiply>(block_col, merge_size);
+ auto row_in_block = std::make_shared<v1::Divide>(within, merge_size);
+ auto col_in_block = std::make_shared<v1::FloorMod>(within, merge_size);
+ auto merged_row = std::make_shared<v1::Add>(block_top, row_in_block);
+ auto merged_col = std::make_shared<v1::Add>(block_left, col_in_block);
+ auto merged_row_offset = std::make_shared<v1::Multiply>(merged_row, cols);
+ auto merged = std::make_shared<v1::Add>(merged_row_offset, merged_col);
+ auto merge_indices = flat_index(merged);
+ replace_input(model, "merge_indices", merge_indices);
+ 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});
+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, inputs);
+ return model->clone();
+}
+
+Models split_merger_layout(const std::shared_ptr<ov::Model>& model) {
+ Models models;
+ // HF flattens patches as (channel, frame, y, x).
+ auto first_weight = require_weight(model, "v.patch_embd.weight");
+ auto second_weight = require_weight(model, "v.patch_embd.weight.1");
+ auto frame_axis = v0::Constant::create(ov::element::i64, {1}, {2});
+ auto first_frame = std::make_shared<v0::Unsqueeze>(first_weight, frame_axis);
+ auto second_frame = std::make_shared<v0::Unsqueeze>(second_weight, frame_axis);
+ auto kernel = std::make_shared<v0::Concat>(ov::OutputVector{first_frame, second_frame}, 2);
+ const auto& kernel_shape = kernel->get_output_partial_shape(0);
+ const auto width = kernel_shape[0].get_length();
+ const auto patch_dim = ov::shape_size(kernel_shape.get_shape()) / width;
+ auto patches = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, int64_t(patch_dim)});
+ name_output(patches, "hidden_states");
+ auto kernel_shape_2d = v0::Constant::create(ov::element::i64, {2}, {width, int64_t(patch_dim)});
+ auto kernel_2d = std::make_shared<v1::Reshape>(kernel, kernel_shape_2d, false);
+ auto projection = std::make_shared<v0::MatMul>(patches, kernel_2d, false, true);
+ Value embeddings = projection;
+ if (auto bias = weight(model, "v.patch_embd.bias"); bias.get_node()) {
+ auto biased = std::make_shared<v1::Add>(embeddings, bias);
+ embeddings = biased;
+ }
+ models["vision_embeddings"] = single_output_model(embeddings, "last_hidden_state", {patches});
+
+ auto table_indices = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{4, -1});
+ name_output(table_indices, "input");
+ auto position_weight = require_weight(model, "v.position_embd.weight");
+ auto zero = v0::Constant::create(ov::element::i64, {}, {0});
+ auto table = std::make_shared<v8::Gather>(position_weight, table_indices, zero);
+ 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 = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, width});
+ auto batch_axes = v0::Constant::create(ov::element::i64, {2}, {0, 1});
+ auto hidden_states_4d = std::make_shared<v0::Unsqueeze>(hidden_states, batch_axes);
+ // Replace the activation shared by LayerNorm and its residual path.
+ normalized->input_value(0).replace(hidden_states_4d);
+ model->remove_parameter(parameter(model, "pixel_values"));
+ model->remove_parameter(parameter(model, "patch_indices"));
+
+ // The first column of each rotary half has frequency 1, so it holds the row or column.
+ const auto width_metadata = mmproj_int_metadata(model, "clip.vision.embedding_length");
+ const auto heads = mmproj_int_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 = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, head / 2});
+ auto col_index = v0::Constant::create(ov::element::i64, {}, {head / 4});
+ auto one = v0::Constant::create(ov::element::i64, {}, {1});
+ auto row = std::make_shared<v8::Gather>(rotary, zero, one);
+ auto col = std::make_shared<v8::Gather>(rotary, col_index, one);
+ auto coordinates = std::make_shared<v0::Concat>(ov::OutputVector{row, col, row, col}, 0);
+ auto positions = std::make_shared<v5::Round>(coordinates, v5::Round::RoundMode::HALF_TO_EVEN);
+ auto position_ids = flat_index(positions);
+ replace_input(model, "position_ids", position_ids);
+
+ auto mask = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, -1, -1});
+ auto zero_axis = v0::Constant::create(ov::element::i64, {1}, {0});
+ auto mask4 = std::make_shared<v0::Unsqueeze>(mask, zero_axis);
+ for (const auto& node : model->get_ordered_ops()) {
+ if (auto sdpa = ov::as_type_ptr<v13::ScaledDotProductAttention>(node)) {
+ OPENVINO_ASSERT(sdpa->get_input_size() == 3, "[GGUF] split-merger vision attention already has a mask");
+ 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"});
+ auto deepstack_result = std::make_shared<v0::Result>(deepstack);
+ model->add_results({deepstack_result});
+ }
+ add_inputs(model, {{"hidden_states", hidden_states}, {"attention_mask", mask}, {"rotary_pos_emb", rotary}});
+ models["vision_embeddings_merger"] = model;
+ return models;
+}
+void packed_patch_layout(const std::shared_ptr<ov::Model>& model, int64_t patch, int64_t merge) {
+ require_square_fits(patch, 3, "vision.patch_size");
+ OPENVINO_ASSERT(merge == 2 || merge == 4, "[GGUF] invalid packed-patch merge size");
+ auto pixels = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, 3, patch, -1});
+ auto positions = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1});
+ auto window_index = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1});
+ auto merge_index = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1});
+ auto grid = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{2});
+ auto zero = v0::Constant::create(ov::element::i64, {}, {0});
+ auto row_index = v0::Constant::create(ov::element::i64, {1}, {0});
+ auto col_index = v0::Constant::create(ov::element::i64, {1}, {1});
+ auto rows = std::make_shared<v8::Gather>(grid, row_index, zero);
+ auto cols = std::make_shared<v8::Gather>(grid, col_index, zero);
+ auto strip_shape = v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{1, 3, patch, -1, patch});
+ auto strip = std::make_shared<v1::Reshape>(pixels, strip_shape, false);
+ auto strip_order = v0::Constant::create(ov::element::i64, {5}, {0, 3, 1, 2, 4});
+ auto reordered = std::make_shared<v1::Transpose>(strip, strip_order);
+ auto packed_shape = v0::Constant::create(ov::element::i64, {2}, std::vector<int64_t>{-1, 3 * patch * patch});
+ auto packed = std::make_shared<v1::Reshape>(reordered, packed_shape, false);
+ auto image = image_from_patches(packed, rows, cols, patch, false);
+ replace_input(model, "pixel_values", image);
+ auto flat_positions = flat_index(positions);
+ replace_input(model, "position_ids", flat_positions);
+ auto merge_count = std::make_shared<v3::ShapeOf>(merge_index);
+ auto four_steps = v0::Constant::create(ov::element::i64, {1}, {4});
+ for (int64_t i = 0; i < 4; ++i) {
+ auto start = v0::Constant::create(ov::element::i64, {1}, {i});
+ auto index = std::make_shared<v8::Slice>(merge_index, start, merge_count, four_steps, row_index);
+ auto flat = flat_index(index);
+ replace_input(model, "merger.indices." + std::to_string(i), flat);
+ }
+ if (merge == 4) {
+ auto flat_window = flat_index(window_index);
+ replace_input(model, "window_indices", flat_window);
+ auto count = std::make_shared<v3::ShapeOf>(window_index);
+ auto ordered = range(count);
+ auto inverse = std::make_shared<v3::ScatterUpdate>(ordered, window_index, ordered, zero);
+ auto flat_inverse = flat_index(inverse);
+ replace_input(model, "inverse_window_indices", flat_inverse);
+ auto four = v0::Constant::create(ov::element::i64, {}, {4});
+ auto group = std::make_shared<v1::Divide>(ordered, four);
+ auto query_group = std::make_shared<v0::Unsqueeze>(group, col_index);
+ auto key_group = std::make_shared<v0::Unsqueeze>(group, row_index);
+ auto same_group = std::make_shared<v1::Equal>(query_group, key_group);
+ auto visible = v0::Constant::create(ov::element::f32, {}, {0.0f});
+ auto hidden = v0::Constant::create(ov::element::f32, {}, {-std::numeric_limits<float>::infinity()});
+ auto mask = std::make_shared<v1::Select>(same_group, visible, hidden);
+ auto batch_heads = v0::Constant::create(ov::element::i64, {2}, {1, 1});
+ auto mask_shape = std::make_shared<v0::Concat>(ov::OutputVector{batch_heads, count, count}, 0);
+ auto attention_mask = std::make_shared<v1::Reshape>(mask, mask_shape, false);
+ replace_input(model, "attention_mask", attention_mask);
+ for (int64_t i = 0; i < 4; ++i) {
+ auto start = v0::Constant::create(ov::element::i64, {1}, {i});
+ auto index = std::make_shared<v8::Slice>(window_index, start, count, four_steps, row_index);
+ auto flat = flat_index(index);
+ replace_input(model, "vit_merger.indices." + std::to_string(i), flat);
+ }
+ }
+ add_inputs(model,
+ {{"pixel_values", pixels},
+ {"position_ids", positions},
+ {"window_index", window_index},
+ {"merge_index", merge_index},
+ {"patch_grid", grid}});
+ squeeze_output(model);
+}
+
+constexpr std::pair<ProjectorLayout, const char*> layout_names[] = {
+ {ProjectorLayout::Unsupported, "unsupported"},
+ {ProjectorLayout::Image, "image"},
+ {ProjectorLayout::PaddedPatches, "padded_patches"},
+ {ProjectorLayout::WindowedPatches, "windowed_patches"},
+ {ProjectorLayout::SplitMerger, "split_merger"},
+ {ProjectorLayout::PackedPatches, "packed_patches"},
+};
+
+ProjectorLayout read_projector_layout(const std::shared_ptr<ov::Model>& model) {
+ if (!model->has_rt_info({"gguf_mmproj", "vision.genai_layout"})) {
+ OPENVINO_ASSERT(model->has_rt_info({"gguf_mmproj", "vision.projector"}),
+ "[GGUF] no GenAI vision layout contract");
+ const auto projector = model->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"});
+ const auto layout = builtin_projector_layout(projector);
+ OPENVINO_ASSERT(layout != ProjectorLayout::Unsupported,
+ "[GGUF] no GenAI vision layout for mmproj projector '",
+ projector,
+ "'");
+ return layout;
+ }
+ const auto name = model->get_rt_info<std::string>({"gguf_mmproj", "vision.genai_layout"});
+ for (const auto& [layout, layout_name] : layout_names) {
+ if (layout != ProjectorLayout::Unsupported && name == layout_name)
+ return layout;
+ }
+ OPENVINO_THROW("[GGUF] no GenAI vision layout for mmproj contract '", name, "'");
+}
+} // namespace
+
+std::string projector_layout_name(ProjectorLayout layout) {
+ for (const auto& [candidate, name] : layout_names) {
+ if (candidate == layout)
+ return name;
+ }
+ OPENVINO_THROW("[GGUF] invalid GenAI projector layout contract");
+}
+
+ProjectorLayout builtin_projector_layout(const std::string& projector_type) {
+ if (projector_type == "gemma3" || projector_type == "lfm2")
+ return ProjectorLayout::Image;
+ if (projector_type == "gemma4v" || projector_type == "gemma4uv")
+ return ProjectorLayout::PaddedPatches;
+ if (projector_type == "muse-glimmer")
+ return ProjectorLayout::WindowedPatches;
+ if (projector_type == "qwen3vl_merger")
+ return ProjectorLayout::SplitMerger;
+ if (projector_type == "minicpmv4_7")
+ return ProjectorLayout::PackedPatches;
+ return ProjectorLayout::Unsupported;
+}
+
+void require_projector_layout(const std::shared_ptr<ov::Model>& model) {
+ read_projector_layout(model);
+}
+
+ProjectorModels adapt_projector_layout(const std::shared_ptr<ov::Model>& model) {
+ switch (read_projector_layout(model)) {
+ case ProjectorLayout::Image:
+ break;
+ case ProjectorLayout::PaddedPatches:
+ padded_patch_layout(model, mmproj_int_metadata(model, "vision.patch_size"));
+ break;
+ case ProjectorLayout::WindowedPatches:
+ windowed_patch_layout(model,
+ mmproj_int_metadata(model, "vision.patch_size"),
+ mmproj_int_metadata(model, "vision.window_size"),
+ mmproj_int_metadata(model, "vision.merge"));
+ break;
+ case ProjectorLayout::SplitMerger:
+ return split_merger_layout(model);
+ case ProjectorLayout::PackedPatches:
+ packed_patch_layout(model,
+ mmproj_int_metadata(model, "vision.patch_size"),
+ mmproj_int_metadata(model, "vision.merge"));
+ break;
+ case ProjectorLayout::Unsupported:
+ OPENVINO_THROW("[GGUF] no GenAI vision layout contract");
+ }
+ return {{"vision_embeddings", model}};
+}
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/arch/projector_adapter.hpp b/src/frontends/gguf/src/builder/arch/projector_adapter.hpp
new file mode 100644
index 00000000000..50e39cb59d9
--- /dev/null
+++ b/src/frontends/gguf/src/builder/arch/projector_adapter.hpp
@@ -0,0 +1,24 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <map>
+#include <memory>
+#include <string>
+
+#include "openvino/core/model.hpp"
+#include "openvino/frontend/gguf/extension/projector.hpp"
+
+namespace ov::frontend::gguf {
+
+using ProjectorModels = std::map<std::string, std::shared_ptr<ov::Model>>;
+
+std::string projector_layout_name(ProjectorLayout layout);
+// Vision GenAI layout of a built-in projector type; Unsupported for other types.
+ProjectorLayout builtin_projector_layout(const std::string& projector_type);
+void require_projector_layout(const std::shared_ptr<ov::Model>& model);
+ProjectorModels adapt_projector_layout(const std::shared_ptr<ov::Model>& model);
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/arch_registry.cpp b/src/frontends/gguf/src/builder/arch_registry.cpp
index 750410dbfc9..616306f78bf 100644
--- a/src/frontends/gguf/src/builder/arch_registry.cpp
+++ b/src/frontends/gguf/src/builder/arch_registry.cpp
@@ -35,6 +35,7 @@ struct ArchitectureEntry {
const char* id = nullptr;
};
const ArchitectureEntry architectures[] = {
+ {"afmoe", RopeMode::Neox},
{"bailingmoe2", RopeMode::Neox},
{"clip",
make_mmproj_builder,
diff --git a/src/frontends/gguf/src/builder/blocks/attention.cpp b/src/frontends/gguf/src/builder/blocks/attention.cpp
index 8b6ddda245c..e1fdf03db9c 100644
--- a/src/frontends/gguf/src/builder/blocks/attention.cpp
+++ b/src/frontends/gguf/src/builder/blocks/attention.cpp
@@ -50,21 +50,22 @@ std::string attention(GraphEmitter& e,
const bool is_swa_layer = cfg.layer_is_swa(il);
const int head_size_l = cfg.layer_head_size(il);
const int n_head_kv_l = cfg.layer_n_head_kv(il);
+ const int n_head_l = cfg.layer_n_head(il);
const float kq_scale = cfg.layer_kq_scale(il);
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;
+ const int64_t q_width = static_cast<int64_t>(head_size_l) * n_head_l;
// 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
// separate q/k/v weights so the rest of the layer is architecture-agnostic.
- if (cfg.is_qwen35) {
- register_qwen35_q_gate(e, cfg, il);
+ if (cfg.interleaved_q_gate) {
+ register_interleaved_q_gate(e, cfg, il);
e.add_weight(p + "attn_k.weight");
e.add_weight(p + "attn_v.weight");
- } else if (e.has_weight(p + "attn_qkv.weight")) {
+ } else if (cfg.fused_qkv_override.value_or(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");
@@ -85,7 +86,7 @@ std::string attention(GraphEmitter& e,
if (e.weight_emitted(p + "attn_q_gate.weight")) {
const auto joint = e.add_op("GGML_OP_MUL_MAT", p + "q_gate", {p + "attn_q_gate.weight", attn_norm});
const auto projections =
- split_interleaved_projection(e, joint, {p + "Qcur", p + "attn_gate_joint"}, cfg.n_head, head_size_l);
+ split_interleaved_projection(e, joint, {p + "Qcur", p + "attn_gate_joint"}, n_head_l, head_size_l);
q = projections[0];
gate = projections[1];
} else {
@@ -101,7 +102,7 @@ std::string attention(GraphEmitter& e,
// fused-QKV archs: attn_qkv.bias, already split into attn_{q,k,v}.bias by
// register_fused_qkv above).
// 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")) {
+ if (cfg.qkv_bias_override.value_or(cfg.interleaved_q_gate ? cfg.has_qkv_bias : e.has_weight(p + "attn_q.bias"))) {
q = add_bias(e, q, p + "attn_q.bias", p + "Qcur_b");
if (has_own_kv) {
k = add_bias(e, k, p + "attn_k.bias", p + "Kcur_b");
@@ -121,7 +122,7 @@ std::string attention(GraphEmitter& e,
p + "Qcur_r",
{q},
6,
- {{"reshape_target", std::vector<int64_t>{0, -1, cfg.n_head, head_size_l}}, {"special_zero", true}});
+ {{"reshape_target", std::vector<int64_t>{0, -1, n_head_l, head_size_l}}, {"special_zero", true}});
if (has_own_kv) {
k = e.add_op(
"GGML_OP_RESHAPE",
@@ -331,7 +332,8 @@ std::string attention(GraphEmitter& e,
// output projection (+ optional bias)
e.add_weight(p + "attn_output.weight");
auto attn_out = e.add_op("GGML_OP_MUL_MAT", p + "attn_out", {p + "attn_output.weight", attn_2d});
- if (cfg.is_qwen35 ? cfg.has_attn_out_bias : e.has_weight(p + "attn_output.bias")) {
+ if (cfg.output_bias_override.value_or(cfg.interleaved_q_gate ? cfg.has_attn_out_bias
+ : e.has_weight(p + "attn_output.bias"))) {
attn_out = add_bias(e, attn_out, p + "attn_output.bias", p + "attn_out_b");
}
return attn_out;
diff --git a/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp b/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp
index 93642453808..4dc7f837c42 100644
--- a/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp
+++ b/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp
@@ -12,8 +12,8 @@ namespace ov::frontend::gguf::blocks {
void register_fused_qkv(GraphEmitter& e, const DecoderConfig& cfg, int il) {
const std::string p = "blk." + std::to_string(il) + ".";
- const size_t n_q = static_cast<size_t>(cfg.n_head) * cfg.head_size;
- const size_t n_kv = static_cast<size_t>(cfg.n_head_kv) * cfg.head_size;
+ const size_t n_q = static_cast<size_t>(cfg.layer_n_head(il)) * cfg.layer_head_size(il);
+ const size_t n_kv = static_cast<size_t>(cfg.layer_n_head_kv(il)) * cfg.layer_head_size(il);
auto parts = split_fused_qkv_extracted(p + "attn_qkv", e.weights(), e.qtypes(), n_q, n_kv, n_kv);
const std::array<std::string, 3> names = {p + "attn_q.weight", p + "attn_k.weight", p + "attn_v.weight"};
for (size_t i = 0; i < 3; ++i) {
@@ -33,7 +33,7 @@ void register_fused_qkv(GraphEmitter& e, const DecoderConfig& cfg, int il) {
}
}
-void register_qwen35_q_gate(GraphEmitter& e, const DecoderConfig& cfg, int il) {
+void register_interleaved_q_gate(GraphEmitter& e, const DecoderConfig& cfg, int il) {
const std::string p = "blk." + std::to_string(il) + ".";
e.inherit_hadamard(p + "attn_q_gate.weight", p + "attn_q.weight");
e.add_weight_from(p + "attn_q_gate.weight", p + "attn_q");
diff --git a/src/frontends/gguf/src/builder/blocks/qkv_repack.hpp b/src/frontends/gguf/src/builder/blocks/qkv_repack.hpp
index 803859ab659..a1028cf6d15 100644
--- a/src/frontends/gguf/src/builder/blocks/qkv_repack.hpp
+++ b/src/frontends/gguf/src/builder/blocks/qkv_repack.hpp
@@ -15,6 +15,6 @@ namespace ov::frontend::gguf::blocks {
void register_fused_qkv(GraphEmitter& e, const DecoderConfig& cfg, int il);
// Preserve the interleaved Q/gate weight for a joint projection.
-void register_qwen35_q_gate(GraphEmitter& e, const DecoderConfig& cfg, int il);
+void register_interleaved_q_gate(GraphEmitter& e, const DecoderConfig& cfg, int il);
} // namespace ov::frontend::gguf::blocks
diff --git a/src/frontends/gguf/src/builder/decoder_config.cpp b/src/frontends/gguf/src/builder/decoder_config.cpp
index 4c5aa53109a..731badae4af 100644
--- a/src/frontends/gguf/src/builder/decoder_config.cpp
+++ b/src/frontends/gguf/src/builder/decoder_config.cpp
@@ -1,368 +1,260 @@
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
-// Architecture detection for the dense/MoE decoder family: turn the parsed GGUF metadata and
-// tensor table into the flat DecoderConfig the topology builder reads.
-//
-// Ground truth for each rule is llama.cpp's per-architecture hparam loading
-// (src/models/*.cpp::load_arch_hparams) and llm_graph_context.
#include "builder/decoder_config.hpp"
#include <algorithm>
#include <cmath>
-#include <variant>
+#include <limits>
-#include "arch_registry.hpp"
+#include "builder/arch_registry.hpp"
+#include "builder/graph_emitter.hpp"
+#include "builder/metadata_checks.hpp"
#include "openvino/core/except.hpp"
namespace ov::frontend::gguf {
-
namespace {
-
-int cfg_int(const std::map<std::string, GGUFMetaData>& config, const std::string& k) {
- auto it = config.find(k);
- OPENVINO_ASSERT(it != config.end(), "[GGUF] internal: missing config key '", k, "'");
- const auto* v = std::get_if<int>(&it->second);
- OPENVINO_ASSERT(v, "[GGUF] internal: config key '", k, "' is not an int");
- return *v;
+bool same_rope(const RopeConfig& a, const RopeConfig& b) {
+ return a.per_op == b.per_op && a.n_ctx_orig == b.n_ctx_orig && a.n_dims == b.n_dims && a.freq_base == b.freq_base &&
+ a.freq_scale == b.freq_scale && a.ext_factor == b.ext_factor && a.attn_factor == b.attn_factor &&
+ a.beta_fast == b.beta_fast && a.beta_slow == b.beta_slow && a.sections == b.sections;
}
-float cfg_float(const std::map<std::string, GGUFMetaData>& config, const std::string& k) {
- auto it = config.find(k);
- OPENVINO_ASSERT(it != config.end(), "[GGUF] internal: missing config key '", k, "'");
- const auto* v = std::get_if<float>(&it->second);
- OPENVINO_ASSERT(v, "[GGUF] internal: config key '", k, "' is not a float");
- return *v;
+void validate_rope(const RopeConfig& rope, int head_size) {
+ OPENVINO_ASSERT(rope.n_dims >= 0 && rope.n_dims % 2 == 0 && rope.n_dims <= head_size,
+ "[GGUF] RoPE dimensions must be nonnegative, even and fit the attention head");
+ if (rope.n_dims > 0) {
+ require_positive_finite(rope.freq_base, "RoPE frequency base");
+ require_positive_finite(rope.freq_scale, "RoPE frequency scale");
+ }
}
-
} // namespace
-DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
- const std::unordered_map<std::string, ov::Tensor>& weights,
- std::optional<RopeMode> rope,
- const DecoderOptions& options) {
+DecoderConfig::DecoderConfig(const DecoderParameters& p, const std::unordered_map<std::string, ov::Tensor>& weights) {
const auto has = [&weights](const std::string& name) {
return weights.count(name) > 0;
};
- const auto cfg_i = [&config](const std::string& k) {
- return cfg_int(config, k);
+ arch = p.architecture;
+ model_contract = p.model_contract;
+ n_layer = p.dimensions.layers;
+ n_embd = p.dimensions.embedding;
+ const int query_heads = p.dimensions.query_heads;
+ const int kv_heads = p.dimensions.kv_heads;
+ head_size = p.dimensions.head_size;
+ const auto& kv_heads_per_layer = p.dimensions.kv_heads_per_layer;
+ n_embd_per_layer = p.dimensions.per_layer_embedding;
+ shared_kv_layers = p.dimensions.shared_kv_layers;
+ const int n_layer_nextn = p.hybrid.nextn_layers;
+ OPENVINO_ASSERT(n_layer > 0 && n_embd > 0 && query_heads > 0 && kv_heads >= 0 && head_size > 0,
+ "[GGUF] invalid decoder dimensions");
+ OPENVINO_ASSERT(n_layer_nextn >= 0 && n_layer_nextn < n_layer,
+ "[GGUF] invalid number of NextN blocks: ",
+ n_layer_nextn);
+ const int stored_layers = n_layer;
+ n_layer -= n_layer_nextn;
+ const auto valid_layer_count = [&](size_t count) {
+ return count == 0 || count == static_cast<size_t>(n_layer) || count == static_cast<size_t>(stored_layers);
};
- const auto cfg_f = [&config](const std::string& k) {
- return cfg_float(config, k);
+ OPENVINO_ASSERT(valid_layer_count(p.layers.size()) && valid_layer_count(kv_heads_per_layer.size()) &&
+ valid_layer_count(p.attention.sliding_layers.size()) &&
+ valid_layer_count(p.hybrid.recurrent_layers.size()),
+ "[GGUF] per-layer settings must describe every decoder layer");
+ rms_eps = p.normalization.epsilon;
+ require_positive_finite(rms_eps, "normalization epsilon");
+ layer_norm = p.normalization.kind == NormalizationKind::Layer;
+ relu_squared_ffn = p.activation == FfnActivation::ReluSquared;
+ is_geglu = p.activation == FfnActivation::GeGlu;
+ embedding_model = p.embedding_model;
+ pooling_type = p.pooling_type;
+ causal_attention = p.causal_attention;
+ OPENVINO_ASSERT(!embedding_model || (pooling_type >= 0 && pooling_type <= 3),
+ "[GGUF] unsupported embedding pooling type: ",
+ pooling_type);
+ qk_norm_after_rope = p.normalization.qk_after_rope;
+ post_norm_only = p.normalization.post_only;
+ has_v_norm = p.normalization.value_norm;
+ scaleless_embd_norm = p.normalization.embedding_norm;
+ post_norm_eps = p.normalization.post_epsilon;
+ if (post_norm_eps != 0.0f)
+ require_positive_finite(post_norm_eps, "post-norm epsilon");
+ attn_norm_key = p.normalization.attention_key;
+ ffn_norm_key = p.normalization.ffn_key;
+ attn_post_norm_key = p.normalization.attention_post_key;
+ ffn_post_norm_key = p.normalization.ffn_post_key;
+ const bool gated_delta_net = p.hybrid.kind == RecurrentKind::GatedDeltaNet;
+ ssm_conv_kernel = p.hybrid.conv_kernel;
+ ssm_state_size = p.hybrid.state_size;
+ ssm_group_count = p.hybrid.group_count;
+ ssm_dt_rank = p.hybrid.time_step_rank;
+ ssm_inner_size = p.hybrid.inner_size;
+ n_expert = p.experts.count;
+ n_expert_used = p.experts.used;
+ const int dense_lead = p.experts.dense_lead;
+ const int moe_layer_step = std::max(1, p.experts.layer_step);
+ expert_groups = std::max(1, p.experts.groups);
+ expert_groups_used = std::max(1, p.experts.groups_used);
+ moe_sigmoid_gating = p.experts.routing == ExpertRouting::Sigmoid;
+ expert_weights_scale = p.experts.weights_scale;
+ expert_weights_norm = p.experts.normalize_weights;
+ embedding_scale = p.scales.embedding;
+ residual_scale = p.scales.residual;
+ logit_scale = p.scales.logits;
+ embedding_scale_tokens_only = p.scales.token_embeddings_only;
+ const float attention_scale = p.scales.attention;
+ attention_temperature_scale = p.scales.attention_temperature;
+ attn_soft_cap = p.scales.attention_soft_cap;
+ final_logit_soft_cap = p.scales.logits_soft_cap;
+ for (const auto value : {embedding_scale,
+ residual_scale,
+ logit_scale,
+ attention_scale,
+ attention_temperature_scale,
+ attn_soft_cap,
+ final_logit_soft_cap,
+ expert_weights_scale})
+ OPENVINO_ASSERT(std::isfinite(value), "[GGUF] decoder scales must be finite");
+ const int head_size_swa = p.attention.sliding_head_size;
+ swa_window_size = p.attention.window_size;
+ swa_layer_pattern = p.attention.sliding_period;
+ const auto& swa_layer_flags = p.attention.sliding_layers;
+ has_swa = p.attention.sliding_window || swa_window_size > 0 || !swa_layer_flags.empty();
+ rope_on_swa_only = p.attention.rope_on_sliding_only;
+ rope_skip_period = p.attention.rope_skip_period;
+ OPENVINO_ASSERT(rope_skip_period >= 0, "[GGUF] RoPE skip period must be nonnegative");
+ OPENVINO_ASSERT(swa_window_size >= 0 && swa_layer_pattern >= 0, "[GGUF] invalid sliding-window settings");
+ rope_config = p.attention.rope;
+ auto rope_config_swa = p.attention.sliding_rope;
+ if (rope_config_swa.n_dims == 0)
+ rope_config_swa = rope_config;
+ rope_freq_base_swa = rope_config_swa.freq_base;
+ OPENVINO_ASSERT(attention_temperature_scale == 0.0f || rope_config.n_ctx_orig > 0,
+ "[GGUF] Attention temperature scaling requires a positive original context length");
+ const float yarn_log_mul = p.attention.yarn_log_multiplier;
+ if (rope_config.ext_factor != 0.0f && yarn_log_mul != 0.0f && rope_config.freq_scale < 1.0f) {
+ const float magnitude = 1.0f + 0.1f * yarn_log_mul * std::log(1.0f / rope_config.freq_scale);
+ rope_config.attn_factor /= magnitude;
+ rope_config_swa.attn_factor /= magnitude;
+ }
+ rope_op_case = p.attention.rope_mode == RopeMode::Interleaved ? ROPE_OP_CASE_IMROPE
+ : p.attention.rope_mode == RopeMode::Neox ? ROPE_OP_CASE_NEOX
+ : ROPE_OP_CASE_NORMAL;
+ if (rope_op_case == ROPE_OP_CASE_IMROPE) {
+ rope_config.is_imrope = true;
+ rope_config_swa.is_imrope = true;
+ rope_config_swa.sections = rope_config.sections;
+ }
+ OPENVINO_ASSERT(rope_config.is_imrope == (rope_op_case == ROPE_OP_CASE_IMROPE),
+ "[GGUF] RoPE configuration must match the selected position layout");
+ has_sinks = p.attention.sinks.value_or(has("blk.0.attn_sinks.weight"));
+ has_swa = has_swa || has_sinks;
+ const bool periodic_swa = has_swa;
+ const int probe = (std::max(0, dense_lead) / moe_layer_step + 1) * moe_layer_step - 1;
+ const auto expert_prefix = "blk." + std::to_string(probe) + ".";
+ const bool is_moe = p.experts.enabled.value_or(has(expert_prefix + "ffn_gate_exps.weight") ||
+ has(expert_prefix + "ffn_gate_up_exps.weight"));
+ const auto layer_overrides = [&p](int il) -> const DecoderLayerOverrides* {
+ return p.layers.empty() ? nullptr : &p.layers.at(il);
};
-
- n_layer = cfg_i("layer_num");
- n_head = cfg_i("head_num");
- n_head_kv = cfg_i("head_num_kv");
- head_size = cfg_i("head_size");
- n_embd = cfg_i("hidden_size");
- rms_eps = cfg_f("rms_norm_eps");
- if (config.count("head_num_kv_per_layer")) {
- if (auto* t = std::get_if<ov::Tensor>(&config.at("head_num_kv_per_layer"))) {
- const auto* data = t->data<uint32_t>();
- n_head_kv_per_layer.assign(data, data + t->get_size());
- }
+ const auto periodic_or_listed_swa = [&](int il) {
+ if (!swa_layer_flags.empty())
+ return swa_layer_flags.at(il) != 0;
+ return periodic_swa && swa_layer_pattern > 0 && il % swa_layer_pattern < swa_layer_pattern - 1;
+ };
+ // Layers flagged by explicit overrides or the period/flag rules decide whether the model uses
+ // SWA at all; attention-only SWA layouts then follow it.
+ for (int il = 0; il < n_layer; ++il) {
+ const auto* o = layer_overrides(il);
+ has_swa = has_swa ||
+ (o && o->sliding_window ? *o->sliding_window
+ : !p.attention.sliding_on_attention_layers && periodic_or_listed_swa(il));
}
-
- arch = std::get<std::string>(config.at("architecture"));
- embedding_model = arch == "llama-embed";
- if (embedding_model) {
- pooling_type = cfg_i("pooling_type");
- causal_attention = cfg_i("causal_attention") != 0;
- OPENVINO_ASSERT(pooling_type >= 0 && pooling_type <= 3,
- "[GGUF] unsupported embedding pooling type: ",
- pooling_type);
+ m_layers.resize(n_layer);
+ for (int il = 0; il < n_layer; ++il) {
+ const auto* o = layer_overrides(il);
+ auto& layer = m_layers[il];
+ layer.n_head = o && o->query_heads ? *o->query_heads : query_heads;
+ layer.n_head_kv = o && o->kv_heads ? *o->kv_heads
+ : !kv_heads_per_layer.empty() ? static_cast<int>(kv_heads_per_layer.at(il))
+ : kv_heads;
+ layer.swa = o && o->sliding_window ? *o->sliding_window
+ : p.attention.sliding_on_attention_layers ? has_swa && layer.n_head_kv > 0
+ : periodic_or_listed_swa(il);
+ layer.head_size = o && o->head_size ? *o->head_size
+ : layer.swa && head_size_swa > 0 ? head_size_swa
+ : head_size;
+ layer.kq_scale = o && o->attention_scale ? *o->attention_scale
+ : attention_scale != 0.0f ? attention_scale
+ : 1.0f / std::sqrt(static_cast<float>(layer.head_size));
+ layer.rope = o && o->rope ? *o->rope : layer.swa ? rope_config_swa : rope_config;
+ layer.moe = o && o->experts ? *o->experts : is_moe && il >= dense_lead && (il + 1) % moe_layer_step == 0;
+ layer.recurrent = o && o->recurrent ? *o->recurrent
+ : !gated_delta_net ? false
+ : !p.hybrid.recurrent_layers.empty() ? p.hybrid.recurrent_layers.at(il) != 0
+ : p.hybrid.full_attention_interval > 0 &&
+ (il + 1) % p.hybrid.full_attention_interval != 0;
}
- layer_norm = arch == "jais2";
- relu_squared_ffn = arch == "jais2";
-
- // Per-architecture structure, auto-detected from the GGUF tensor table (layer 0).
std::string attention_probe = "blk.0.";
+ int attention_layer = 0;
for (int layer = 0; layer < n_layer; ++layer) {
const auto prefix = "blk." + std::to_string(layer) + ".";
if (has(prefix + "attn_q_norm.weight")) {
attention_probe = prefix;
+ attention_layer = layer;
break;
}
}
- has_qk_norm = has(attention_probe + "attn_q_norm.weight");
- // q/k norm width: per-head (head_size, applied after reshape -> qwen3/hunyuan/gemma4)
- // vs full projection width (n_head*head_size, applied before reshape -> OLMoE).
- // For gemma4, norm width equals per-layer head_size (may differ by SWA/global); always
- // per-head. For OLMoE, norm width equals n_head*head_size. Detect by checking against
- // the global head_size; but for gemma4 override to per-head since it has mixed head sizes.
- if (has_qk_norm) {
- const size_t qn = weights.at(attention_probe + "attn_q_norm.weight").get_shape()[0];
- qk_norm_full = (arch != "gemma4") && (qn != static_cast<size_t>(head_size));
- }
- n_dense_lead = cfg_i("n_layer_dense_lead");
- moe_layer_step = std::max(1, cfg_i("moe_layer_step"));
- // Inspect the first routed layer, accounting for both dense lead layers and MoE stride.
- {
- const int probe = (std::max(0, n_dense_lead) / moe_layer_step + 1) * moe_layer_step - 1;
- const std::string pp = "blk." + std::to_string(probe) + ".";
- is_moe = has(pp + "ffn_gate_exps.weight") || has(pp + "ffn_gate_up_exps.weight");
+ has_qk_norm = p.normalization.qk_norm.value_or(has(attention_probe + "attn_q_norm.weight"));
+ if (has_qk_norm && has(attention_probe + "attn_q_norm.weight")) {
+ const auto& shape = weights.at(attention_probe + "attn_q_norm.weight").get_shape();
+ OPENVINO_ASSERT(!shape.empty(), "[GGUF] empty Q normalization weight");
+ qk_norm_full = shape[0] != static_cast<size_t>(layer_head_size(attention_layer));
}
- // Gemma/Gemma2 use GeGLU (GELU-gated FFN). Detected by arch name since other archs
- // in the supported set (llama, qwen2, qwen3, phi3) all use SwiGLU.
- is_geglu = arch == "gemma" || arch == "gemma2" || arch == "gemma3" || arch == "gemma4";
- // gemma4 only: V projection is also RMSNorm'd (no weight, just normalize). gemma3 has
- // Q/K norm but NO V norm -- llama.cpp src/models/gemma3.cpp norms Qcur/Kcur only and
- // sends Vcur straight to the cache (gemma4.cpp:227 adds the extra ggml_rms_norm on V).
- has_v_norm = (arch == "gemma4");
- n_expert = cfg_i("expert_count");
- n_expert_used = cfg_i("expert_used_count");
- expert_groups = std::max(1, cfg_i("expert_groups"));
- expert_groups_used = std::max(1, cfg_i("expert_groups_used"));
- has_moe_gate_bias = has("blk.0.ffn_gate_inp.bias"); // gpt-oss
- has_moe_expert_bias = has("blk.0.ffn_gate_exps.bias"); // gpt-oss
- has_sinks = has("blk.0.attn_sinks.weight"); // gpt-oss
- qk_norm_after_rope =
- options.qk_norm_after_rope.value_or(arch == "hunyuan-dense" || arch == "hunyuan-moe" || arch == "maincoder");
- post_norm_only = options.post_norm_only.value_or(arch == "exaone4");
- // EXAONE4 has only post-norms; GPT-OSS names its pre-FFN norm post_attention_norm.
+ qk_norm_full = p.normalization.qk_full_width.value_or(qk_norm_full);
+ has_moe_gate_bias = has(expert_prefix + "ffn_gate_inp.bias");
+ has_moe_expert_bias = has(expert_prefix + "ffn_gate_exps.bias");
+ moe_softmax_weight = p.experts.softmax_after_topk.value_or(has_moe_gate_bias);
+ moe_swiglu_oai = p.experts.swiglu_oai.value_or(has_moe_gate_bias);
+ interleaved_q_gate = p.attention.interleaved_q_gate;
+ qkv_bias_override = p.attention.qkv_bias;
+ output_bias_override = p.attention.output_bias;
+ fused_qkv_override = p.attention.fused_qkv;
+ has_qkv_bias = p.attention.qkv_bias.value_or(has("blk.0.attn_q.bias") || has("blk.0.attn_qkv.bias"));
+ has_attn_out_bias = p.attention.output_bias.value_or(has("blk.0.attn_output.bias"));
+ has_attn_gate = p.attention.output_gate.value_or(has("blk.0.attn_gate.weight"));
+ has_rope_freqs = has("rope_freqs.weight");
if (!has("blk.0." + attn_post_norm_key) && has("blk.0.post_attention_norm"))
attn_post_norm_key = "post_attention_norm";
if (!has("blk.0." + ffn_post_norm_key) && has("blk.0.post_ffw_norm"))
ffn_post_norm_key = "post_ffw_norm";
- has_attn_post_norm = has("blk.0." + attn_post_norm_key) &&
- (post_norm_only || (has("blk.0.attn_norm.weight") && has("blk.0.ffn_norm.weight")));
- has_ffn_post_norm = has("blk.0." + ffn_post_norm_key) && (post_norm_only || has("blk.0.ffn_norm.weight"));
- if (!post_norm_only && !has("blk.0.ffn_norm.weight") && has("blk.0.post_attention_norm.weight"))
+ has_attn_post_norm = p.normalization.attention_post.value_or(
+ has("blk.0." + attn_post_norm_key) &&
+ (post_norm_only || (has("blk.0." + attn_norm_key) && has("blk.0." + ffn_norm_key))));
+ has_ffn_post_norm = p.normalization.ffn_post.value_or(has("blk.0." + ffn_post_norm_key) &&
+ (post_norm_only || has("blk.0." + ffn_norm_key)));
+ if (!post_norm_only && !has("blk.0." + ffn_norm_key) && has("blk.0.post_attention_norm.weight"))
ffn_norm_key = "post_attention_norm.weight";
- moe_sigmoid_gating = cfg_i("expert_gating_func") == 2;
- // gpt-oss uses "softmax-after-topk" gating + the OAI gated activation; OLMoE uses
- // softmax-before-topk + plain SwiGLU. Detect by weight-tensor presence so the logic
- // extends to future architectures without touching this file.
- moe_swiglu_oai = has_moe_gate_bias; // gate_inp bias is OAI-gating-specific
- moe_softmax_weight = has_moe_gate_bias; // same tensor signals softmax-after-topk
- // SWA is present if sinks (gpt-oss), per-layer flags (gemma4), or has_swa was set
- // from the GGUF metadata (smollm3, exaone-moe, gemma3, and future archs that set
- // attention.sliding_window_pattern / attention.sliding_window).
- has_swa = has_sinks || (arch == "gemma3") || (arch == "gemma4") || cfg_i("has_swa") != 0;
- has_fused_qkv = has("blk.0.attn_qkv.weight"); // phi-3, minicpm
- has_qkv_bias = has("blk.0.attn_q.bias") || has("blk.0.attn_qkv.bias");
- has_attn_out_bias = has("blk.0.attn_output.bias");
- has_rope_freqs = has("rope_freqs.weight");
- // muse-glimmer: sigmoid output gate on the attention sublayer. The gate is projected
- // from the SAME pre-attention normed hidden the Q/K/V projections consume, so it is
- // wired inside the layer right before the output projection.
- has_attn_gate = has("blk.0.attn_gate.weight");
- // muse-glimmer applies a weightless RMSNorm to the token embeddings before layer 0
- // (llama.cpp src/models/muse-glimmer.cpp: build_norm(inpL, nullptr, nullptr, RMS, -1)),
- // ropes only its sliding-window layers (global layers are NoPE), and post-norms with a
- // tighter eps (post_norm_eps = 1e-8) than the pre-norms use.
- const bool is_muse_glimmer = arch == "muse-glimmer";
- scaleless_embd_norm = is_muse_glimmer;
- rope_on_swa_only = is_muse_glimmer || arch == "exaone-moe" || (arch == "exaone4" && n_layer == 64);
- rope_skip_period = options.rope_skip_period.value_or(arch == "smollm3" ? 4 : 0);
- OPENVINO_ASSERT(rope_skip_period >= 0, "[GGUF] RoPE skip period must be nonnegative");
- post_norm_eps = is_muse_glimmer ? 1e-8f : 0.0f; // 0 -> reuse rms_eps
-
- // ---- qwen35 (Qwen3.5/3.6): hybrid Gated-DeltaNet + full attention ----
- // Layers alternate: every full_attention_interval-th layer is full attention, the rest
- // run a linear-attention (GDN) block. llama.cpp src/models/qwen35.cpp.
- is_qwen35 = arch == "qwen35" || arch == "qwen35moe";
- ssm_conv_kernel = cfg_i("ssm_conv_kernel");
- ssm_state_size = cfg_i("ssm_state_size");
- ssm_group_count = cfg_i("ssm_group_count");
- ssm_dt_rank = cfg_i("ssm_time_step_rank");
- ssm_inner_size = cfg_i("ssm_inner_size");
- full_attn_interval = cfg_i("full_attention_interval");
- // NextN/MTP blocks live past the main stack and are not executed in a normal forward
- // pass, so the layer loop must stop before them (llama.cpp runs 0..n_layer(), where
- // n_layer() already excludes them; the GGUF block_count counts them in).
- n_layer_nextn = cfg_i("nextn_predict_layers");
- if (config.count("recurrent_layer_flags")) {
- if (const auto* v = std::get_if<std::vector<int32_t>>(&config.at("recurrent_layer_flags")))
- recurrent_layer_flags = *v;
- }
- if (config.count("rope_sections")) {
- if (const auto* v = std::get_if<std::vector<int32_t>>(&config.at("rope_sections")))
- rope_sections = *v;
- }
- if (is_qwen35) {
- // blk.0 is a RECURRENT layer whose attn_qkv.weight is the GDN q/k/v/z projection, not
- // a fused attention QKV -- the generic probe above would mistake it for phi-3-style
- // fused QKV and try to split it by attention head counts. Likewise blk.0's
- // attn_gate.weight is the GDN output gate (z), not an attention gate.
- has_fused_qkv = false;
- // qwen35's full-attention layers DO have a sigmoid attention output gate, and it is
- // the same construction muse-glimmer uses -- projected from the pre-attention normed
- // hidden, sigmoid'd, multiplied into the merged attention output before wo. The only
- // difference is where the weight lives: qwen35 interleaves it per head inside attn_q
- // rather than storing a separate tensor, so register_qwen35_q_gate() de-interleaves it
- // into blk.N.attn_q.weight + blk.N.attn_gate.weight and the shared path handles it.
- has_attn_gate = true;
- // Per-head QK-norm on the full-attention layers. Auto-detection probes blk.0, which is
- // recurrent and carries no attn_q_norm, so set it explicitly.
- has_qk_norm = true;
- qk_norm_full = false;
- // qwen35's pre-FFN norm key ("post_attention_norm.weight", HF's
- // post_attention_layernorm) already falls out of the generic rule above: attn_norm
- // exists, ffn_norm does not, which is the gpt-oss pattern.
- }
- // Trailing MTP/NextN blocks are excluded from the decoder trunk.
- OPENVINO_ASSERT(n_layer_nextn >= 0 && n_layer_nextn < n_layer,
- "[GGUF] invalid number of NextN blocks: ",
- n_layer_nextn);
- n_layer -= n_layer_nextn;
-
- // Per-architecture scalars from metadata (1.0 / 0.0 when absent -> no-op).
- embedding_scale = cfg_f("embedding_scale");
- embedding_scale_tokens_only = arch == "gemma3" || arch == "gemma4";
- residual_scale = cfg_f("residual_scale");
- logit_scale = cfg_f("logit_scale");
- attention_scale = cfg_f("attention_scale"); // 0 -> 1/sqrt(head_size)
- expert_weights_scale = cfg_f("expert_weights_scale"); // 0 -> 1.0 no-op
- // llama.cpp's LFM2 MoE loader leaves the routing scale unset.
- if (arch == "lfm2moe")
- expert_weights_scale = 0.0f;
- // These llama.cpp builders require normalization independently of optional GGUF metadata.
- expert_weights_norm = options.normalize_expert_weights.value_or(
- arch == "hunyuan-moe" || arch == "minimax-m2" || arch == "qwen3moe" || arch == "qwen35moe" ||
- arch == "ernie4_5-moe" || arch == "mellum" || arch == "gemma4" || cfg_i("expert_weights_norm") != 0);
- rope_freq_base_swa = cfg_f("rope_freq_base_swa");
- swa_layer_pattern = cfg_i("swa_layer_pattern");
- // Gemma4: per-layer SWA boolean flags (non-empty when swa_layer_pattern==0).
- if (config.count("swa_layer_flags"))
- swa_layer_flags = std::get<std::vector<int32_t>>(config.at("swa_layer_flags"));
- attn_soft_cap = cfg_f("attn_logit_softcapping"); // 0 -> no soft-cap
- final_logit_soft_cap = cfg_f("final_logit_softcapping"); // 0 -> no soft-cap
- // Gemma4: per-layer input embeddings and shared KV layers.
- n_embd_per_layer = cfg_i("n_embd_per_layer");
- shared_kv_layers = cfg_i("shared_kv_layers");
- // Gemma4: SWA layers use a smaller head size than global attention layers.
- head_size_swa = cfg_i("head_size_swa");
- rope_dim_swa = cfg_i("rope_dimension_count_swa");
- swa_window_size = cfg_i("swa_window_size");
-
- // Interleaved M-RoPE (qwen35 / qwen3vl) is its own mode, so it must be decided here rather
- // than in the per-arch block above -- this assignment runs later and would overwrite it.
- rope_op_case = is_qwen35 ? ROPE_OP_CASE_IMROPE
- : arch_uses_neox_rope(arch) ? ROPE_OP_CASE_NEOX
- : ROPE_OP_CASE_NORMAL;
-
- rope_config.n_dims = cfg_i("rope_dimension_count");
- rope_config.n_ctx_orig = cfg_i("rope_n_ctx_orig");
- rope_config.freq_base = cfg_f("rope_freq_base");
- rope_config.freq_scale = cfg_f("rope_freq_scale");
- rope_config.ext_factor = cfg_f("rope_ext_factor");
- rope_config.attn_factor = 1.0f;
- rope_config.beta_fast = cfg_f("rope_yarn_beta_fast");
- rope_config.beta_slow = cfg_f("rope_yarn_beta_slow");
- const float yarn_log_mul = cfg_f("rope_yarn_log_mul");
- if (rope_config.ext_factor != 0.0f && yarn_log_mul != 0.0f && rope_config.freq_scale < 1.0f) {
- // The RoPE translator already applies YaRN's default magnitude factor.
- rope_config.attn_factor /= 1.0f + 0.1f * yarn_log_mul * std::log(1.0f / rope_config.freq_scale);
- }
- attention_temperature_scale = cfg_f("attention_temperature_scale");
- OPENVINO_ASSERT(attention_temperature_scale == 0.0f || rope_config.n_ctx_orig > 0,
- "[GGUF] Attention temperature scaling requires a positive original context length");
- // Gemma4: separate rope config for SWA layers (different freq_base and n_dims).
- rope_config_swa = rope_config;
- rope_config_swa.freq_base = cfg_f("rope_freq_base_swa");
- rope_config_swa.n_dims = cfg_i("rope_dimension_count_swa");
- // Gemma local attention uses the training default, independently of global
- // linear RoPE scaling (for example 1/8 in Gemma3 4B).
- if (arch == "gemma3" || arch == "gemma4")
- rope_config_swa.freq_scale = 1.0f;
- if (options.geglu)
- is_geglu = *options.geglu;
- if (options.value_norm)
- has_v_norm = *options.value_norm;
- if (options.embedding_norm)
- scaleless_embd_norm = *options.embedding_norm;
- if (options.rope_on_swa_only)
- rope_on_swa_only = *options.rope_on_swa_only;
- if (options.post_norm_epsilon) {
- OPENVINO_ASSERT(std::isfinite(*options.post_norm_epsilon) && *options.post_norm_epsilon > 0,
- "[GGUF] post-norm epsilon must be finite and positive");
- post_norm_eps = *options.post_norm_epsilon;
- }
- if (options.swa_rope_frequency_base) {
- OPENVINO_ASSERT(std::isfinite(*options.swa_rope_frequency_base) && *options.swa_rope_frequency_base > 0,
- "[GGUF] SWA RoPE frequency base must be finite and positive");
- rope_freq_base_swa = rope_config_swa.freq_base = *options.swa_rope_frequency_base;
- }
- if (options.swa_rope_dimensions) {
- OPENVINO_ASSERT(*options.swa_rope_dimensions > 0 && *options.swa_rope_dimensions % 2 == 0 &&
- *options.swa_rope_dimensions <= (head_size_swa > 0 ? head_size_swa : head_size),
- "[GGUF] SWA RoPE dimensions must be positive, even and fit the attention head");
- rope_dim_swa = rope_config_swa.n_dims = *options.swa_rope_dimensions;
- }
- if (options.sliding_window) {
- OPENVINO_ASSERT(*options.sliding_window > 0, "[GGUF] sliding window must be positive");
- swa_window_size = *options.sliding_window;
- has_swa = true;
- }
- if (rope) {
- rope_op_case = *rope == RopeMode::Interleaved ? ROPE_OP_CASE_IMROPE
- : *rope == RopeMode::Neox ? ROPE_OP_CASE_NEOX
- : ROPE_OP_CASE_NORMAL;
- }
- // Per-op sin/cos is required whenever SWA and global layers differ in any rope
- // parameter that feeds the shared sin/cos table: n_dims (gemma4) OR freq_base (gemma3,
- // whose SWA layers rope at 10000 vs the global 1000000). Without it every layer would
- // share the global table and SWA layers would be roped wrong.
- const bool swa_dims_differ = rope_dim_swa > 0 && rope_dim_swa != rope_config.n_dims;
- const bool swa_freq_differs = rope_config_swa.freq_base != rope_config.freq_base;
- const bool swa_scale_differs = rope_config_swa.freq_scale != rope_config.freq_scale;
- if (has_swa && (swa_dims_differ || swa_freq_differs || swa_scale_differs)) {
- use_per_op_rope = true;
- }
- // M-RoPE: inp_pos carries 4 sections per token and only the first n_dims of each head
- // are rotated (qwen35: head_size 256, rope.dimension_count 64). Build sin/cos per ROPE op
- // rather than from the shared table, whose layout assumes the single-section full-head
- // case (see RopeConfig::is_imrope / use_per_op_rope).
- if (rope_op_case == ROPE_OP_CASE_IMROPE) {
- rope_config.is_imrope = true;
- OPENVINO_ASSERT(rope_sections.size() <= rope_config.sections.size(), "[GGUF] too many M-RoPE sections");
- std::copy(rope_sections.begin(), rope_sections.end(), rope_config.sections.begin());
- use_per_op_rope = true;
- }
-}
-
-bool DecoderConfig::layer_is_moe(int il) const {
- return is_moe && il >= n_dense_lead && (il + 1) % moe_layer_step == 0;
-}
-
-bool DecoderConfig::layer_is_swa(int il) const {
- if (arch == "lfm2" || arch == "lfm2moe")
- return has_swa && layer_n_head_kv(il) > 0;
- if (!swa_layer_flags.empty()) {
- return il < static_cast<int>(swa_layer_flags.size()) && swa_layer_flags[il] != 0;
+ for (int layer = 0; layer < n_layer; ++layer) {
+ const auto& settings = m_layers[layer];
+ OPENVINO_ASSERT(settings.n_head > 0 && settings.n_head_kv >= 0 && settings.head_size > 0,
+ "[GGUF] invalid per-layer dimensions at layer ",
+ layer);
+ validate_rope(settings.rope, settings.head_size);
+ OPENVINO_ASSERT(std::isfinite(settings.kq_scale), "[GGUF] nonfinite per-layer attention scale");
+ OPENVINO_ASSERT(settings.rope.is_imrope == rope_config.is_imrope,
+ "[GGUF] per-layer RoPE must use the shared position layout");
+ use_per_op_rope = use_per_op_rope || !same_rope(settings.rope, rope_config);
}
- return has_swa && swa_layer_pattern > 0 && (il % swa_layer_pattern < (swa_layer_pattern - 1));
-}
-
-int DecoderConfig::layer_head_size(int il) const {
- return (layer_is_swa(il) && head_size_swa > 0) ? head_size_swa : head_size;
-}
-
-int DecoderConfig::layer_n_head_kv(int il) const {
- return (!n_head_kv_per_layer.empty() && il < static_cast<int>(n_head_kv_per_layer.size()))
- ? static_cast<int>(n_head_kv_per_layer[il])
- : n_head_kv;
-}
-
-float DecoderConfig::layer_kq_scale(int il) const {
- return attention_scale != 0.0f ? attention_scale : 1.0f / std::sqrt(static_cast<float>(layer_head_size(il)));
-}
-
-RopeConfig DecoderConfig::layer_rope_config(int il) const {
- return layer_is_swa(il) ? rope_config_swa : rope_config;
+ use_per_op_rope = use_per_op_rope || rope_op_case == ROPE_OP_CASE_IMROPE || rope_config.per_op;
}
-bool DecoderConfig::is_recurrent_layer(int il) const {
- if (!is_qwen35) {
- return false;
- }
- if (il < static_cast<int>(recurrent_layer_flags.size())) {
- return recurrent_layer_flags[il] != 0;
- }
- return full_attn_interval > 0 && ((il + 1) % full_attn_interval != 0);
+void DecoderConfig::configure_graph(GraphEmitter& emitter, const GgufMetadata& metadata) const {
+ emitter.configure_hadamard(decoder_weight_transform_metadata(metadata, ssm_dt_rank, ssm_group_count));
+ auto& graph = *emitter.graph();
+ graph.has_rope = true;
+ graph.rope_config = rope_config;
+ graph.use_per_op_rope = use_per_op_rope;
+ graph.swa_window_size = swa_window_size;
+ graph.model_contract = model_contract;
}
-
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/decoder_config.hpp b/src/frontends/gguf/src/builder/decoder_config.hpp
index cc25af93533..c0a8abf6578 100644
--- a/src/frontends/gguf/src/builder/decoder_config.hpp
+++ b/src/frontends/gguf/src/builder/decoder_config.hpp
@@ -8,29 +8,32 @@
#include <unordered_map>
#include <vector>
-#include "openvino/frontend/gguf/builder/decoder_options.hpp"
+#include "builder/decoder_metadata.hpp"
#include "openvino/frontend/gguf/decoder.hpp"
#include "openvino/runtime/tensor.hpp"
#include "quant/gguf.hpp"
namespace ov::frontend::gguf {
+class GraphEmitter;
+
// Internal configuration resolved from metadata, tensor shapes and architecture semantics.
// Extensions override ambiguous semantics through DecoderOptions before dependent plans are built.
struct DecoderConfig {
- // Resolve the whole description from the parsed metadata (already normalized by
- // config_from_meta) and the parser's tensor table.
- DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
- const std::unordered_map<std::string, ov::Tensor>& weights,
- std::optional<RopeMode> rope = {},
- const DecoderOptions& options = {});
+ DecoderConfig(const DecoderParameters& parameters, const std::unordered_map<std::string, ov::Tensor>& weights);
+
+ // Sets the graph's RoPE, SWA and model-contract state and configures the weight transforms.
+ void configure_graph(GraphEmitter& emitter, const GgufMetadata& metadata) const;
std::string arch;
+ ModelContract model_contract{};
+ bool interleaved_q_gate = false;
+ std::optional<bool> qkv_bias_override;
+ std::optional<bool> output_bias_override;
+ std::optional<bool> fused_qkv_override;
// ---- core dimensions ----
int n_layer = 0;
- int n_head = 0;
- int n_head_kv = 0;
int head_size = 0;
int n_embd = 0;
float rms_eps = 0.0f;
@@ -39,7 +42,6 @@ struct DecoderConfig {
bool causal_attention = true;
bool layer_norm = false;
bool relu_squared_ffn = false;
- std::vector<uint32_t> n_head_kv_per_layer; // non-empty when head_count_kv varies by layer
// ---- auto-detected per-architecture structure ----
bool has_qk_norm = false;
@@ -49,8 +51,6 @@ struct DecoderConfig {
bool has_qkv_bias = false;
bool has_attn_out_bias = false;
bool has_rope_freqs = false;
- bool has_fused_qkv = false;
- bool is_moe = false;
bool has_moe_gate_bias = false;
bool moe_softmax_weight = false; // softmax AFTER top-k (gpt-oss) rather than before
bool moe_swiglu_oai = false; // OAI gated activation (gpt-oss)
@@ -72,16 +72,11 @@ struct DecoderConfig {
float post_norm_eps = 0.0f; // eps for post-attn/post-FFN norms (0 -> rms_eps)
// ---- qwen35 (hybrid Gated-DeltaNet + full attention) ----
- bool is_qwen35 = false;
- int ssm_conv_kernel = 0; // d_conv
- int ssm_state_size = 0; // head_k_dim / head_v_dim
- int ssm_group_count = 0; // num_k_heads
- int ssm_dt_rank = 0; // num_v_heads
- int ssm_inner_size = 0; // d_inner = num_v_heads * head_v_dim
- int full_attn_interval = 0; // full attention when (il + 1) % interval == 0
- int n_layer_nextn = 0; // trailing MTP blocks, not executed
- std::vector<int32_t> rope_sections; // M-RoPE per-axis section widths
- std::vector<int32_t> recurrent_layer_flags; // explicit per-layer recurrent flags
+ int ssm_conv_kernel = 0; // d_conv
+ int ssm_state_size = 0; // head_k_dim / head_v_dim
+ int ssm_group_count = 0; // num_k_heads
+ int ssm_dt_rank = 0; // num_v_heads
+ int ssm_inner_size = 0; // d_inner = num_v_heads * head_v_dim
// Pre-norm key suffixes; GPT-OSS uses post_attention_norm for its pre-FFN norm.
std::string attn_norm_key{"attn_norm.weight"};
@@ -90,8 +85,6 @@ struct DecoderConfig {
// ---- MoE / scalar metadata ----
int n_expert = 0;
int n_expert_used = 0;
- int n_dense_lead = 0;
- int moe_layer_step = 1;
bool moe_sigmoid_gating = false;
int expert_groups = 1;
int expert_groups_used = 1;
@@ -100,7 +93,6 @@ struct DecoderConfig {
bool embedding_scale_tokens_only = false;
float residual_scale = 1.0f;
float logit_scale = 1.0f;
- float attention_scale = 0.0f; // 0 -> 1/sqrt(head_size)
float attention_temperature_scale = 0.0f;
float expert_weights_scale = 0.0f; // 0 -> 1.0 no-op
bool expert_weights_norm = false; // renormalize top-K gate weights to sum to 1 (qwen3moe etc.)
@@ -110,11 +102,8 @@ struct DecoderConfig {
// ---- SWA / gemma4 ----
float rope_freq_base_swa = 0.0f;
int swa_layer_pattern = 2;
- std::vector<int32_t> swa_layer_flags; // gemma4: per-layer SWA flags (1=SWA, 0=global)
- int n_embd_per_layer = 0; // gemma4: per-layer embedding projection dimension
- int shared_kv_layers = 0; // gemma4: N trailing layers that share KV from earlier layers
- int head_size_swa = 0; // gemma4: head size for SWA layers (differs from global)
- int rope_dim_swa = 0; // gemma4: rope dims for SWA layers
+ int n_embd_per_layer = 0; // gemma4: per-layer embedding projection dimension
+ int shared_kv_layers = 0; // gemma4: N trailing layers that share KV from earlier layers
// Sliding-window length in tokens, when the GGUF metadata carries an explicit
// "<arch>.attention.sliding_window" value (0 -> not present, e.g. an SWA layout described only
// by sinks or a per-layer boolean pattern with no accompanying token count).
@@ -123,36 +112,54 @@ struct DecoderConfig {
// ---- RoPE ----
int rope_op_case = 0;
RopeConfig rope_config{};
- RopeConfig rope_config_swa{};
bool use_per_op_rope = false;
// ---- Per-layer hyperparameter accessors ----
- // Centralize the per-layer derivations that vary by architecture (SWA layers, variable head
- // counts). They are the single source of truth, so the topology loop stays declarative.
- // If a new arch adds a per-layer dimension, extend these rather than inlining a ternary.
-
- // Whether attention layer `il` uses a sliding window. gemma4 carries an explicit per-layer
- // boolean array; gpt-oss/gemma3/smollm3 use a period (il is SWA unless it is the last in each
- // period, matching llama.cpp set_swa_pattern(period, dense_first=false)).
- bool layer_is_swa(int il) const;
- bool layer_is_moe(int il) const;
-
- // Head size for layer `il`. gemma4 SWA layers use a smaller head size than global layers.
- int layer_head_size(int il) const;
-
+ // Per-layer values are resolved once in the constructor (explicit layer overrides win over the
+ // metadata-derived rules), so the topology loop stays declarative.
+
+ // Whether attention layer `il` uses a sliding window.
+ bool layer_is_swa(int il) const {
+ return m_layers.at(il).swa;
+ }
+ bool layer_is_moe(int il) const {
+ return m_layers.at(il).moe;
+ }
+ // True when layer `il` is a linear-attention (recurrent) layer.
+ bool is_recurrent_layer(int il) const {
+ return m_layers.at(il).recurrent;
+ }
+ int layer_head_size(int il) const {
+ return m_layers.at(il).head_size;
+ }
+ int layer_n_head(int il) const {
+ return m_layers.at(il).n_head;
+ }
// KV head count for layer `il` (some archs, e.g. Deci-style, vary head_count_kv per layer).
- int layer_n_head_kv(int il) const;
-
- // Attention (softmax) scale for layer `il`. An explicit metadata scale wins; otherwise use
- // 1/sqrt(layer_head_size(il)) so SWA and global layers each get the head-size-correct scale.
- float layer_kq_scale(int il) const;
-
- // RoPE config for layer `il` (gemma4 SWA layers rope with a different freq_base / n_dims).
- RopeConfig layer_rope_config(int il) const;
-
- // True when layer `il` is a linear-attention (recurrent) layer. An explicit per-layer flag
- // array wins over the interval rule, matching llama.cpp's load order.
- bool is_recurrent_layer(int il) const;
+ int layer_n_head_kv(int il) const {
+ return m_layers.at(il).n_head_kv;
+ }
+ // Attention (softmax) scale: an explicit scale wins, otherwise 1/sqrt(layer head size).
+ float layer_kq_scale(int il) const {
+ return m_layers.at(il).kq_scale;
+ }
+ // RoPE config for layer `il` (e.g. gemma4 SWA layers use a different freq_base / n_dims).
+ const RopeConfig& layer_rope_config(int il) const {
+ return m_layers.at(il).rope;
+ }
+
+private:
+ struct LayerSettings {
+ bool swa = false;
+ bool moe = false;
+ bool recurrent = false;
+ int head_size = 0;
+ int n_head = 0;
+ int n_head_kv = 0;
+ float kq_scale = 0.0f;
+ RopeConfig rope{};
+ };
+ std::vector<LayerSettings> m_layers;
};
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/decoder_metadata.cpp b/src/frontends/gguf/src/builder/decoder_metadata.cpp
new file mode 100644
index 00000000000..b473df7f805
--- /dev/null
+++ b/src/frontends/gguf/src/builder/decoder_metadata.cpp
@@ -0,0 +1,316 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "builder/decoder_metadata.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <limits>
+
+#include "builder/api/metadata_store.hpp"
+#include "builder/arch/decoder_builder.hpp"
+#include "builder/metadata_checks.hpp"
+#include "openvino/core/except.hpp"
+
+namespace ov::frontend::gguf {
+namespace {
+int integer(const GgufMetadata& m, const std::string& key, int fallback, bool required = false) {
+ if (!m.has(key)) {
+ OPENVINO_ASSERT(!required, "[GGUF] required metadata key is missing: '", key, "'");
+ return fallback;
+ }
+ const auto value = m.get_int(key);
+ OPENVINO_ASSERT(value && *value >= std::numeric_limits<int>::min() && *value <= std::numeric_limits<int>::max(),
+ "[GGUF] invalid integer metadata key '",
+ key,
+ "'");
+ return static_cast<int>(*value);
+}
+float real(const GgufMetadata& m, const std::string& key, float fallback, bool required = false) {
+ if (!m.has(key)) {
+ OPENVINO_ASSERT(!required, "[GGUF] required metadata key is missing: '", key, "'");
+ return fallback;
+ }
+ const auto value = m.get_float(key);
+ OPENVINO_ASSERT(value && std::isfinite(*value) && std::abs(*value) <= std::numeric_limits<float>::max(),
+ "[GGUF] invalid floating-point metadata key '",
+ key,
+ "'");
+ return static_cast<float>(*value);
+}
+bool flag(const GgufMetadata& m, const std::string& key, bool fallback) {
+ if (!m.has(key))
+ return fallback;
+ const auto value = m.get_bool(key);
+ OPENVINO_ASSERT(value, "[GGUF] invalid boolean metadata key '", key, "'");
+ return *value;
+}
+std::vector<int32_t> integers(const GgufMetadata& m, const std::string& key) {
+ if (!m.has(key))
+ return {};
+ const auto values = m.get_int_array(key);
+ OPENVINO_ASSERT(!values.empty(), "[GGUF] invalid integer array metadata key '", key, "'");
+ std::vector<int32_t> result;
+ result.reserve(values.size());
+ for (const auto value : values) {
+ OPENVINO_ASSERT(value >= std::numeric_limits<int32_t>::min() && value <= std::numeric_limits<int32_t>::max(),
+ "[GGUF] integer array metadata key '",
+ key,
+ "' exceeds int32 range");
+ result.push_back(static_cast<int32_t>(value));
+ }
+ return result;
+}
+} // namespace
+
+DecoderParameters read_decoder_parameters(const GgufMetadata& m, DecoderParameters p) {
+ const auto architecture = m.get_str("general.architecture");
+ OPENVINO_ASSERT(architecture, "[GGUF] missing or non-string general.architecture");
+ p.architecture = *architecture;
+ const auto key = [&](const std::string& suffix) {
+ return p.architecture + "." + suffix;
+ };
+ auto& d = p.dimensions;
+ d.layers = integer(m, key("block_count"), d.layers, d.layers == 0);
+ d.embedding = integer(m, key("embedding_length"), d.embedding, d.embedding == 0);
+ const auto query_key = key("attention.head_count");
+ std::vector<int32_t> query_heads;
+ if (m.has(query_key) && !m.get_int(query_key)) {
+ query_heads = integers(m, query_key);
+ OPENVINO_ASSERT(d.layers > 0 && query_heads.size() == static_cast<size_t>(d.layers),
+ "[GGUF] query head counts must describe every decoder layer");
+ d.query_heads = *std::max_element(query_heads.begin(), query_heads.end());
+ OPENVINO_ASSERT(p.layers.empty() || p.layers.size() == query_heads.size(),
+ "[GGUF] per-layer settings must describe every decoder layer");
+ p.layers.resize(query_heads.size());
+ for (size_t layer = 0; layer < query_heads.size(); ++layer) {
+ OPENVINO_ASSERT(query_heads[layer] >= 0, "[GGUF] negative query head count");
+ if (query_heads[layer] > 0)
+ p.layers[layer].query_heads = query_heads[layer];
+ }
+ } else {
+ d.query_heads = integer(m, query_key, d.query_heads, d.query_heads == 0);
+ }
+ OPENVINO_ASSERT(d.layers > 0 && d.embedding > 0 && d.query_heads > 0,
+ "[GGUF] decoder dimensions and attention.head_count must be positive");
+ d.head_size = integer(m, key("attention.key_length"), d.head_size > 0 ? d.head_size : d.embedding / d.query_heads);
+ const auto kv_key = key("attention.head_count_kv");
+ if (m.has(kv_key) && !m.get_int(kv_key)) {
+ const auto heads = integers(m, kv_key);
+ d.kv_heads_per_layer.clear();
+ for (const auto count : heads) {
+ OPENVINO_ASSERT(count >= 0, "[GGUF] negative per-layer KV head count");
+ d.kv_heads_per_layer.push_back(static_cast<uint32_t>(count));
+ }
+ d.kv_heads = static_cast<int>(*std::max_element(heads.begin(), heads.end()));
+ } else {
+ d.kv_heads = integer(m, kv_key, d.kv_heads > 0 ? d.kv_heads : d.query_heads);
+ }
+ const auto norm_key = key(p.normalization.kind == NormalizationKind::Layer ? "attention.layer_norm_epsilon"
+ : "attention.layer_norm_rms_epsilon");
+ p.normalization.epsilon = real(m, norm_key, p.normalization.epsilon, p.normalization.epsilon == 0.0f);
+ const auto pooling_key = key("pooling_type");
+ const auto pooling = m.get_int(pooling_key);
+ // llama.cpp stores its unset pooling enum as an unsigned -1.
+ p.pooling_type =
+ pooling && *pooling == std::numeric_limits<uint32_t>::max() ? -1 : integer(m, pooling_key, p.pooling_type);
+ p.causal_attention = flag(m, key("attention.causal"), p.causal_attention);
+ auto& a = p.attention;
+ a.rope.freq_base = real(m, key("rope.freq_base"), a.rope.freq_base > 0 ? a.rope.freq_base : 10000.0f);
+ const float factor = real(m, key("rope.scaling.factor"), 0.0f);
+ a.rope.freq_scale = a.rope.freq_scale > 0 ? a.rope.freq_scale : 1.0f;
+ if (factor != 0.0f) {
+ OPENVINO_ASSERT(factor > 0.0f, "[GGUF] RoPE scaling factor must be finite and positive");
+ const double inverse = 1.0 / static_cast<double>(factor);
+ OPENVINO_ASSERT(inverse <= std::numeric_limits<float>::max(),
+ "[GGUF] RoPE factor reciprocal exceeds float range");
+ a.rope.freq_scale = static_cast<float>(inverse);
+ }
+ if (m.has(key("rope.scaling.type"))) {
+ const auto type = m.get_str(key("rope.scaling.type"));
+ OPENVINO_ASSERT(type, "[GGUF] invalid rope.scaling.type");
+ a.rope.ext_factor = *type == "yarn" ? 1.0f : 0.0f;
+ }
+ a.rope.beta_fast = real(m, key("rope.scaling.yarn_beta_fast"), a.rope.beta_fast > 0 ? a.rope.beta_fast : 32.0f);
+ a.rope.beta_slow = real(m, key("rope.scaling.yarn_beta_slow"), a.rope.beta_slow > 0 ? a.rope.beta_slow : 1.0f);
+ a.yarn_log_multiplier = real(m, key("rope.scaling.yarn_log_multiplier"), a.yarn_log_multiplier);
+ a.rope.attn_factor = a.rope.attn_factor == 0.0f ? 1.0f : a.rope.attn_factor;
+ const int context = integer(m, key("context_length"), 2048);
+ a.rope.n_ctx_orig =
+ integer(m, key("rope.scaling.original_context_length"), a.rope.n_ctx_orig > 0 ? a.rope.n_ctx_orig : context);
+ const int rope_dims = integer(m, key("rope.dimension_count"), a.rope.n_dims);
+ a.rope.n_dims = rope_dims > 0 ? rope_dims : d.head_size;
+ a.sliding_head_size =
+ integer(m, key("attention.key_length_swa"), a.sliding_head_size > 0 ? a.sliding_head_size : d.head_size);
+ a.sliding_rope.n_dims =
+ integer(m, key("rope.dimension_count_swa"), a.sliding_rope.n_dims > 0 ? a.sliding_rope.n_dims : a.rope.n_dims);
+ a.sliding_rope.freq_base =
+ real(m, key("rope.freq_base_swa"), a.sliding_rope.freq_base > 0 ? a.sliding_rope.freq_base : a.rope.freq_base);
+ if (a.sliding_rope.freq_scale == 0.0f)
+ a.sliding_rope.freq_scale = a.rope.freq_scale;
+ a.sliding_rope.n_ctx_orig = a.rope.n_ctx_orig;
+ a.sliding_rope.ext_factor = a.rope.ext_factor;
+ a.sliding_rope.attn_factor = a.rope.attn_factor;
+ a.sliding_rope.beta_fast = a.rope.beta_fast;
+ a.sliding_rope.beta_slow = a.rope.beta_slow;
+ if (m.has(key("attention.sliding_window"))) {
+ const auto value = m.get_int(key("attention.sliding_window"));
+ OPENVINO_ASSERT(value && *value >= 0 && *value <= std::numeric_limits<uint32_t>::max(),
+ "[GGUF] invalid attention.sliding_window");
+ if (*value > 0 && *value != std::numeric_limits<uint32_t>::max()) {
+ OPENVINO_ASSERT(*value <= std::numeric_limits<int>::max(), "[GGUF] sliding window exceeds int range");
+ a.window_size = static_cast<int>(*value);
+ }
+ }
+ const auto pattern = key("attention.sliding_window_pattern");
+ if (m.has(pattern)) {
+ const auto& stored_pattern = detail::MetadataAccess::get(m).map.at(pattern);
+ const auto* tensor = std::get_if<ov::Tensor>(&stored_pattern);
+ const bool boolean_pattern = tensor && tensor->get_element_type() == ov::element::boolean;
+ if (!boolean_pattern && m.get_int(pattern)) {
+ a.sliding_period = integer(m, pattern, a.sliding_period);
+ a.sliding_layers.clear();
+ } else {
+ a.sliding_layers = integers(m, pattern);
+ a.sliding_period = 0;
+ }
+ a.sliding_window = true;
+ }
+ a.sliding_window = a.sliding_window || a.window_size > 0 || !a.sliding_layers.empty();
+ d.per_layer_embedding = integer(m, key("embedding_length_per_layer_input"), d.per_layer_embedding);
+ d.shared_kv_layers = integer(m, key("attention.shared_kv_layers"), d.shared_kv_layers);
+ auto& e = p.experts;
+ e.count = integer(m, key("expert_count"), e.count);
+ e.used = integer(m, key("expert_used_count"), e.used);
+ e.dense_lead = integer(m, key("leading_dense_block_count"), e.dense_lead);
+ e.layer_step = integer(m, key("interleave_moe_layer_step"), e.layer_step);
+ e.groups = integer(m, key("expert_group_count"), e.groups);
+ e.groups_used = integer(m, key("expert_group_used_count"), e.groups_used);
+ // Zero is llama.cpp's "unspecified" gating function; keep the family default.
+ if (const int gating = integer(m, key("expert_gating_func"), 0))
+ e.routing = static_cast<ExpertRouting>(gating);
+ e.weights_scale = real(m, key("expert_weights_scale"), e.weights_scale);
+ e.normalize_weights = flag(m, key("expert_weights_norm"), e.normalize_weights);
+ auto& scales = p.scales;
+ scales.embedding = real(m, key("embedding_scale"), scales.embedding);
+ scales.residual = real(m, key("residual_scale"), scales.residual);
+ // llama.cpp treats zero metadata scales as unspecified, with no multiplication.
+ if (scales.embedding == 0.0f && m.has(key("embedding_scale")))
+ scales.embedding = 1.0f;
+ if (scales.residual == 0.0f && m.has(key("residual_scale")))
+ scales.residual = 1.0f;
+ scales.logits = real(m, key("logit_scale"), scales.logits);
+ scales.attention = real(m, key("attention.scale"), scales.attention);
+ scales.attention_temperature = real(m, key("attention.temperature_scale"), scales.attention_temperature);
+ scales.attention_soft_cap = real(m, key("attn_logit_softcapping"), scales.attention_soft_cap);
+ scales.logits_soft_cap = real(m, key("final_logit_softcapping"), scales.logits_soft_cap);
+ auto& hybrid = p.hybrid;
+ hybrid.conv_kernel = integer(m, key("ssm.conv_kernel"), hybrid.conv_kernel);
+ hybrid.state_size = integer(m, key("ssm.state_size"), hybrid.state_size);
+ hybrid.group_count = integer(m, key("ssm.group_count"), hybrid.group_count);
+ hybrid.time_step_rank = integer(m, key("ssm.time_step_rank"), hybrid.time_step_rank);
+ hybrid.inner_size = integer(m, key("ssm.inner_size"), hybrid.inner_size);
+ hybrid.full_attention_interval = integer(m, key("full_attention_interval"), hybrid.full_attention_interval);
+ hybrid.nextn_layers = integer(m, key("nextn_predict_layers"), hybrid.nextn_layers);
+ const auto recurrent_key = key("attention.recurrent_layers");
+ if (m.has(recurrent_key)) {
+ if (const auto value = m.get_int(recurrent_key)) {
+ OPENVINO_ASSERT(*value == 0 || *value == 1, "[GGUF] invalid recurrent layer flag");
+ hybrid.recurrent_layers.assign(d.layers, static_cast<int32_t>(*value));
+ } else {
+ hybrid.recurrent_layers = integers(m, recurrent_key);
+ }
+ }
+ for (size_t layer = 0; layer < query_heads.size(); ++layer)
+ OPENVINO_ASSERT(query_heads[layer] > 0 ||
+ (hybrid.recurrent_layers.size() == query_heads.size() && hybrid.recurrent_layers[layer]) ||
+ (d.kv_heads_per_layer.size() == query_heads.size() && d.kv_heads_per_layer[layer] == 0),
+ "[GGUF] zero query head count requires a layer without attention");
+ if (m.has(key("rope.dimension_sections"))) {
+ const auto sections = integers(m, key("rope.dimension_sections"));
+ OPENVINO_ASSERT(sections.size() <= a.rope.sections.size(), "[GGUF] too many M-RoPE sections");
+ std::copy(sections.begin(), sections.end(), a.rope.sections.begin());
+ }
+ return p;
+}
+
+void apply_decoder_options(DecoderParameters& p, const DecoderOptions& o) {
+ if (o.normalization)
+ p.normalization.kind = *o.normalization;
+ if (o.norm_epsilon)
+ p.normalization.epsilon = *o.norm_epsilon;
+ if (o.embedding_scale)
+ p.scales.embedding = *o.embedding_scale;
+ if (o.residual_scale)
+ p.scales.residual = *o.residual_scale;
+ if (o.logit_scale)
+ p.scales.logits = *o.logit_scale;
+ if (o.attention_scale)
+ p.scales.attention = *o.attention_scale;
+ if (o.qk_norm_after_rope)
+ p.normalization.qk_after_rope = *o.qk_norm_after_rope;
+ if (o.post_norm_only)
+ p.normalization.post_only = *o.post_norm_only;
+ if (o.normalize_expert_weights)
+ p.experts.normalize_weights = *o.normalize_expert_weights;
+ if (o.value_norm)
+ p.normalization.value_norm = *o.value_norm;
+ if (o.embedding_norm)
+ p.normalization.embedding_norm = *o.embedding_norm;
+ if (o.rope_on_swa_only)
+ p.attention.rope_on_sliding_only = *o.rope_on_swa_only;
+ if (o.rope_skip_period)
+ p.attention.rope_skip_period = *o.rope_skip_period;
+ if (o.geglu)
+ p.activation = *o.geglu ? FfnActivation::GeGlu : FfnActivation::SwiGlu;
+ if (o.post_norm_epsilon) {
+ require_positive_finite(*o.post_norm_epsilon, "post-norm epsilon");
+ p.normalization.post_epsilon = *o.post_norm_epsilon;
+ }
+ if (o.swa_rope_frequency_base) {
+ require_positive_finite(*o.swa_rope_frequency_base, "SWA RoPE frequency base");
+ p.attention.sliding_rope.freq_base = *o.swa_rope_frequency_base;
+ }
+ if (o.swa_rope_dimensions) {
+ const int head_size =
+ p.attention.sliding_head_size > 0 ? p.attention.sliding_head_size : p.dimensions.head_size;
+ OPENVINO_ASSERT(
+ *o.swa_rope_dimensions > 0 && *o.swa_rope_dimensions % 2 == 0 && *o.swa_rope_dimensions <= head_size,
+ "[GGUF] SWA RoPE dimensions must be positive, even and fit the attention head");
+ p.attention.sliding_rope.n_dims = *o.swa_rope_dimensions;
+ }
+ if (o.sliding_window) {
+ OPENVINO_ASSERT(*o.sliding_window > 0, "[GGUF] sliding window must be positive");
+ p.attention.window_size = *o.sliding_window;
+ p.attention.sliding_window = true;
+ }
+}
+
+std::map<std::string, GGUFMetaData> decoder_weight_transform_metadata(const GgufMetadata& metadata,
+ int value_heads,
+ int key_heads) {
+ std::map<std::string, GGUFMetaData> result;
+ for (const auto& [key, value] : detail::MetadataAccess::get(metadata).map)
+ if (key.compare(0, 15, "prism.hadamard.") == 0)
+ result[key] = value;
+ result["ssm_time_step_rank"] = value_heads;
+ result["ssm_group_count"] = key_heads;
+ return result;
+}
+
+ArchitectureDefinition::BuilderFactory decoder_builder_factory(DecoderParametersFn parameters) {
+ OPENVINO_ASSERT(parameters, "[GGUF] decoder architecture requires a parameter factory");
+ return [parameters = std::move(parameters)](const BuildContext& ctx) {
+ OPENVINO_ASSERT(ctx.weights, "[GGUF] decoder builder requires a weight table");
+ return std::make_shared<DecoderBuilder>(ctx, parameters(ctx));
+ };
+}
+
+ArchitectureDefinition::BuilderFactory decoder_builder_factory(RopeMode rope, DecoderOptionsFn options) {
+ return decoder_builder_factory(DecoderParametersFn([rope, options = std::move(options)](const BuildContext& ctx) {
+ return resolve_decoder_parameters(ctx.metadata, rope, options ? options(ctx.metadata) : DecoderOptions{});
+ }));
+}
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/decoder_metadata.hpp b/src/frontends/gguf/src/builder/decoder_metadata.hpp
new file mode 100644
index 00000000000..78d77116e92
--- /dev/null
+++ b/src/frontends/gguf/src/builder/decoder_metadata.hpp
@@ -0,0 +1,23 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/frontend/gguf/extension/architecture.hpp"
+#include "quant/gguf.hpp"
+
+namespace ov::frontend::gguf {
+
+DecoderParameters decoder_family_defaults(const std::string& architecture, int layers, int embedding, int heads);
+DecoderParameters resolve_decoder_parameters(const GgufMetadata& metadata,
+ RopeMode rope,
+ const DecoderOptions& options = {});
+void apply_decoder_options(DecoderParameters& parameters, const DecoderOptions& options);
+std::map<std::string, GGUFMetaData> decoder_weight_transform_metadata(const GgufMetadata& metadata,
+ int value_heads,
+ int key_heads);
+ArchitectureDefinition::BuilderFactory decoder_builder_factory(RopeMode rope, DecoderOptionsFn options);
+ArchitectureDefinition::BuilderFactory decoder_builder_factory(DecoderParametersFn parameters);
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp b/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp
index e713d27b27b..202a04e59eb 100644
--- a/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp
+++ b/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp
@@ -137,4 +137,16 @@ const ov::AnyMap& GgufBuilderDecoder::get_mmproj_config() const {
return m_graph->mmproj_config;
}
+const ModelAdapters& GgufBuilderDecoder::get_model_adapters() const {
+ return m_graph->model_adapters;
+}
+
+ModelContract GgufBuilderDecoder::get_model_contract() const {
+ return m_graph->model_contract;
+}
+
+std::string GgufBuilderDecoder::get_architecture() const {
+ return m_graph->architecture;
+}
+
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp b/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp
index 770a0608206..f716ffbb60c 100644
--- a/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp
+++ b/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp
@@ -47,6 +47,9 @@ public:
const std::vector<std::pair<std::string, std::string>>& get_recurrent_states() const override;
const ov::AnyMap& get_tokenizer_config() const override;
const ov::AnyMap& get_mmproj_config() const override;
+ ModelContract get_model_contract() const override;
+ const ModelAdapters& get_model_adapters() const override;
+ std::string get_architecture() const override;
private:
std::shared_ptr<GgufGraph> m_graph;
diff --git a/src/frontends/gguf/src/builder/gguf_graph.hpp b/src/frontends/gguf/src/builder/gguf_graph.hpp
index df14cf7ef99..9c430184317 100644
--- a/src/frontends/gguf/src/builder/gguf_graph.hpp
+++ b/src/frontends/gguf/src/builder/gguf_graph.hpp
@@ -41,6 +41,8 @@ struct GgufOp {
// a parsed GGUF file; consumed by GgufBuilderDecoder.
struct GgufGraph {
std::string architecture;
+ ModelContract model_contract;
+ ModelAdapters model_adapters;
std::vector<GgufOp> nodes;
std::shared_ptr<TensorMap> values = std::make_shared<TensorMap>();
diff --git a/src/frontends/gguf/src/builder/legacy_model_contract.hpp b/src/frontends/gguf/src/builder/legacy_model_contract.hpp
new file mode 100644
index 00000000000..31add2be2a0
--- /dev/null
+++ b/src/frontends/gguf/src/builder/legacy_model_contract.hpp
@@ -0,0 +1,228 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <optional>
+#include <string>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include "openvino/core/except.hpp"
+#include "openvino/core/model.hpp"
+#include "openvino/frontend/gguf/decoder.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/convert_like.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/shape_of.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"
+
+namespace ov::frontend::gguf {
+
+inline std::shared_ptr<ov::op::v8::Gather> token_embedding_lookup(const std::shared_ptr<ov::Node>& node) {
+ const auto unsqueeze = ov::as_type_ptr<ov::op::v0::Unsqueeze>(node);
+ if (!unsqueeze)
+ return nullptr;
+ auto source = unsqueeze->input_value(0).get_node_shared_ptr();
+ if (const auto convert = ov::as_type_ptr<ov::op::v0::Convert>(source))
+ source = convert->input_value(0).get_node_shared_ptr();
+ auto gather = ov::as_type_ptr<ov::op::v8::Gather>(source);
+ if (const auto reshape = ov::as_type_ptr<ov::op::v1::Reshape>(source)) {
+ const auto multiply = ov::as_type_ptr<ov::op::v1::Multiply>(reshape->get_input_node_shared_ptr(0));
+ if (multiply)
+ gather = ov::as_type_ptr<ov::op::v8::Gather>(multiply->get_input_node_shared_ptr(1));
+ }
+ if (!gather)
+ return nullptr;
+ auto indices = gather->input_value(1).get_node_shared_ptr();
+ if (const auto squeeze = ov::as_type_ptr<ov::op::v0::Squeeze>(indices))
+ indices = squeeze->input_value(0).get_node_shared_ptr();
+ const auto parameter = ov::as_type_ptr<ov::op::v0::Parameter>(indices);
+ return parameter && parameter->output(0).get_names().count("inp_tokens") ? gather : nullptr;
+}
+
+struct LegacyEmbeddingBoundaries {
+ std::shared_ptr<ov::Node> token;
+ std::shared_ptr<ov::Node> per_layer;
+ int64_t per_layer_count = 0;
+};
+
+inline bool has_legacy_embedding_name(const ov::Node& node, const std::string& name) {
+ const auto& friendly_name = node.get_friendly_name();
+ const auto suffix = "_" + name;
+ return friendly_name == name ||
+ (friendly_name.size() > suffix.size() &&
+ friendly_name.compare(friendly_name.size() - suffix.size(), suffix.size(), suffix) == 0);
+}
+
+inline LegacyEmbeddingBoundaries resolve_legacy_embedding_boundaries(const std::shared_ptr<ov::Model>& model,
+ bool find_token,
+ bool find_per_layer) {
+ LegacyEmbeddingBoundaries boundaries;
+ const auto architecture = model->has_rt_info({"gguf_architecture"})
+ ? model->get_rt_info<std::string>({"gguf_architecture"})
+ : std::string{};
+ const auto operations = model->get_ops();
+ const auto depends_on = [](const std::shared_ptr<ov::Node>& source, const std::shared_ptr<ov::Node>& target) {
+ std::vector<std::shared_ptr<ov::Node>> pending{source};
+ std::unordered_set<const ov::Node*> visited;
+ while (!pending.empty()) {
+ const auto current = pending.back();
+ pending.pop_back();
+ if (current == target)
+ return true;
+ if (!visited.insert(current.get()).second)
+ continue;
+ for (const auto& input : current->input_values())
+ pending.push_back(input.get_node_shared_ptr());
+ }
+ return false;
+ };
+ const auto find_lookup = [&](const std::string& weight_name) {
+ std::shared_ptr<ov::Node> found;
+ const std::string lookup_name = weight_name == "token_embd.weight" ? "embd" : "pe_tok_flat";
+ for (const auto& node : operations) {
+ const auto lookup = token_embedding_lookup(node);
+ if (!lookup)
+ continue;
+ auto table = lookup->get_input_node_shared_ptr(0);
+ if (!has_legacy_embedding_name(*table, weight_name)) {
+ if (const auto squeeze = ov::as_type_ptr<ov::op::v0::Squeeze>(table))
+ table = squeeze->get_input_node_shared_ptr(0);
+ if (!has_legacy_embedding_name(*table, weight_name))
+ continue;
+ }
+ if (weight_name == "token_embd.weight" && has_legacy_embedding_name(*table, "per_layer_token_embd.weight"))
+ continue;
+ OPENVINO_ASSERT(!found, "[GGUF] ambiguous legacy embedding lookup ", weight_name);
+ found = node;
+ std::unordered_map<const ov::Node*, std::pair<bool, bool>> dependencies;
+ std::function<std::pair<bool, bool>(const std::shared_ptr<ov::Node>&)> token_only;
+ token_only = [&](const std::shared_ptr<ov::Node>& current) -> std::pair<bool, bool> {
+ if (current == node)
+ return {true, true};
+ if (const auto saved = dependencies.find(current.get()); saved != dependencies.end())
+ return saved->second;
+ bool valid = ov::is_type<ov::op::v0::Constant>(current) || ov::is_type<ov::op::v1::Add>(current) ||
+ ov::is_type<ov::op::v8::Gather>(current) || ov::is_type<ov::op::v0::MatMul>(current) ||
+ ov::is_type<ov::op::v1::Subtract>(current) || ov::is_type<ov::op::v1::Multiply>(current) ||
+ ov::is_type<ov::op::v0::Concat>(current) || ov::is_type<ov::op::v1::Split>(current) ||
+ ov::is_type<ov::op::v1::Reshape>(current) || ov::is_type<ov::op::v1::Transpose>(current) ||
+ ov::is_type<ov::op::v0::Convert>(current) ||
+ ov::is_type<ov::op::v1::ConvertLike>(current) ||
+ ov::is_type<ov::op::v0::ShapeOf>(current) || ov::is_type<ov::op::v3::ShapeOf>(current);
+ bool from_lookup = false;
+ for (const auto& input : current->input_values()) {
+ const auto dependency = token_only(input.get_node_shared_ptr());
+ valid = valid && dependency.first;
+ from_lookup = from_lookup || dependency.second;
+ }
+ return dependencies.emplace(current.get(), std::make_pair(valid, from_lookup)).first->second;
+ };
+ for (const auto& candidate : operations) {
+ if (!has_legacy_embedding_name(*candidate, lookup_name) ||
+ (lookup_name == "embd" && has_legacy_embedding_name(*candidate, "per_layer_embd")))
+ continue;
+ const auto dependency = token_only(candidate);
+ if (!dependency.second)
+ continue;
+ OPENVINO_ASSERT(
+ dependency.first && candidate->get_output_size() == 1 &&
+ candidate->get_output_partial_shape(0).compatible(node->get_output_partial_shape(0)),
+ "[GGUF] unsupported legacy token-only embedding endpoint ",
+ lookup_name);
+ if (depends_on(candidate, found)) {
+ found = candidate;
+ } else {
+ OPENVINO_ASSERT(depends_on(found, candidate),
+ "[GGUF] ambiguous legacy complete embedding endpoint ",
+ lookup_name);
+ }
+ }
+ }
+ return found;
+ };
+ const auto find_scaled = [&](const std::shared_ptr<ov::Node>& lookup, const std::string& name) {
+ std::shared_ptr<ov::Node> found;
+ for (const auto& node : operations) {
+ const auto multiply = ov::as_type_ptr<ov::op::v1::Multiply>(node);
+ if (!multiply || !has_legacy_embedding_name(*multiply, name) ||
+ multiply->get_input_node_shared_ptr(0) != lookup)
+ continue;
+ const auto scale = ov::as_type_ptr<ov::op::v0::Constant>(multiply->get_input_node_shared_ptr(1));
+ if (!scale || !scale->get_shape().empty())
+ continue;
+ OPENVINO_ASSERT(!found, "[GGUF] ambiguous legacy scaled embedding boundary ", name);
+ found = node;
+ }
+ return found;
+ };
+ if (find_token) {
+ boundaries.token = find_lookup("token_embd.weight");
+ if (boundaries.token && (architecture == "gemma3" || architecture == "gemma4")) {
+ if (const auto scaled = find_scaled(boundaries.token, "embd_scaled"))
+ boundaries.token = scaled;
+ }
+ }
+ if (find_per_layer && architecture == "gemma4") {
+ const auto lookup = find_lookup("per_layer_token_embd.weight");
+ if (!lookup)
+ return boundaries;
+ const auto scaled = find_scaled(lookup, "pe_tok_flat_scaled");
+ if (!scaled)
+ return boundaries;
+ for (const auto& node : operations) {
+ const auto split = ov::as_type_ptr<ov::op::v1::Reshape>(node);
+ if (!split || !has_legacy_embedding_name(*split, "pe_tok_split") ||
+ split->get_input_node_shared_ptr(0) != scaled || !split->get_special_zero())
+ continue;
+ const auto target = ov::as_type_ptr<ov::op::v0::Constant>(split->get_input_node_shared_ptr(1));
+ if (!target)
+ continue;
+ const auto dimensions = target->cast_vector<int64_t>();
+ const auto& shape = scaled->get_output_partial_shape(0);
+ if (dimensions.size() != 4 || dimensions[0] != 0 || dimensions[1] != -1 || dimensions[2] <= 0 ||
+ dimensions[3] <= 0 || shape.rank() != 4 || shape[3].is_dynamic() ||
+ shape[3].get_length() / dimensions[2] != dimensions[3] || shape[3].get_length() % dimensions[2] != 0)
+ continue;
+ OPENVINO_ASSERT(!boundaries.per_layer, "[GGUF] ambiguous legacy per-layer embedding split");
+ boundaries.per_layer = scaled;
+ boundaries.per_layer_count = dimensions[2];
+ }
+ }
+ return boundaries;
+}
+
+inline ModelContract resolve_legacy_model_contract(const std::shared_ptr<ov::Model>& model,
+ std::optional<int64_t> embedding_width) {
+ ModelContract contract;
+ if (!model->has_rt_info({"gguf_architecture"}))
+ return contract;
+ const auto architecture = model->get_rt_info<std::string>({"gguf_architecture"});
+ if (architecture == "lfm2" || architecture == "lfm2moe")
+ contract.batchable_recurrent = true;
+ if (architecture == "gemma3")
+ contract.image_attention = ModelContract::ImageAttentionMode::GLOBAL_AND_SLIDING;
+ if (architecture == "gemma4" && embedding_width && *embedding_width != 1536 && *embedding_width != 2560)
+ contract.image_attention = ModelContract::ImageAttentionMode::SLIDING_ONLY;
+ return contract;
+}
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/metadata_checks.hpp b/src/frontends/gguf/src/builder/metadata_checks.hpp
new file mode 100644
index 00000000000..0abe0dcccae
--- /dev/null
+++ b/src/frontends/gguf/src/builder/metadata_checks.hpp
@@ -0,0 +1,44 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cmath>
+#include <cstdint>
+#include <limits>
+#include <string>
+
+#include "openvino/core/except.hpp"
+#include "openvino/frontend/gguf/builder/metadata.hpp"
+
+namespace ov::frontend::gguf {
+
+inline void require_positive_finite(double value, const std::string& what) {
+ OPENVINO_ASSERT(std::isfinite(value) && value > 0, "[GGUF] ", what, " must be finite and positive");
+}
+
+// `what` names the consumer in the error, e.g. "Mamba2 metadata".
+inline int64_t require_positive_int(const GgufMetadata& metadata, const std::string& key, const std::string& what) {
+ const auto value = metadata.get_int(key);
+ OPENVINO_ASSERT(value && *value > 0 && *value <= std::numeric_limits<int>::max(),
+ "[GGUF] ",
+ what,
+ " requires a positive integer '",
+ key,
+ "'");
+ return *value;
+}
+
+inline float require_positive_float(const GgufMetadata& metadata, const std::string& key, const std::string& what) {
+ const auto value = metadata.get_float(key);
+ OPENVINO_ASSERT(value && std::isfinite(*value) && *value > 0,
+ "[GGUF] ",
+ what,
+ " requires a positive finite number '",
+ key,
+ "'");
+ return static_cast<float>(*value);
+}
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/extension/architecture.cpp b/src/frontends/gguf/src/extension/architecture.cpp
index cfd046c950f..ea19cd891db 100644
--- a/src/frontends/gguf/src/extension/architecture.cpp
+++ b/src/frontends/gguf/src/extension/architecture.cpp
@@ -4,8 +4,7 @@
#include "openvino/frontend/gguf/extension/architecture.hpp"
-#include "builder/api/metadata_store.hpp"
-#include "builder/arch/decoder_builder.hpp"
+#include "builder/decoder_metadata.hpp"
#include "openvino/core/except.hpp"
namespace ov::frontend::gguf {
@@ -17,17 +16,14 @@ bool ArchitectureDefinition::matches(const GgufMetadata& metadata) const {
ArchitectureDefinition make_decoder_architecture(std::string architecture, RopeMode rope, DecoderOptionsFn options) {
ArchitectureDefinition definition;
definition.id = definition.architecture = std::move(architecture);
- definition.factory = [rope, options = std::move(options)](const BuildContext& ctx) {
- OPENVINO_ASSERT(ctx.weights, "[GGUF] decoder builder requires a weight table");
- const auto overrides = options ? options(ctx.metadata) : DecoderOptions{};
- auto config = decoder_config_from_meta(detail::MetadataAccess::get(ctx.metadata).map);
- return std::make_shared<DecoderBuilder>(config,
- ctx.weights->weights,
- ctx.weights->qtypes,
- rope,
- overrides,
- ctx.weights->translators);
- };
+ definition.factory = decoder_builder_factory(rope, std::move(options));
+ return definition;
+}
+
+ArchitectureDefinition make_decoder_architecture(std::string architecture, DecoderParametersFn parameters) {
+ ArchitectureDefinition definition;
+ definition.id = definition.architecture = std::move(architecture);
+ definition.factory = decoder_builder_factory(std::move(parameters));
return definition;
}
diff --git a/src/frontends/gguf/src/frontend.cpp b/src/frontends/gguf/src/frontend.cpp
index d45076a5d15..4e2a6391e0c 100644
--- a/src/frontends/gguf/src/frontend.cpp
+++ b/src/frontends/gguf/src/frontend.cpp
@@ -110,6 +110,12 @@ std::shared_ptr<Model> FrontEnd::convert(const InputModel::Ptr& model) const {
auto conversion_input = gguf_model;
if (gguf_model->m_builder) {
auto graph = gguf_model->m_builder(ops);
+ for (const auto& [output, adapter] : graph->model_adapters) {
+ if (adapter)
+ adapter->lifetime.insert(adapter->lifetime.end(),
+ gguf_model->m_extensions.begin(),
+ gguf_model->m_extensions.end());
+ }
conversion_input = std::make_shared<gguf::InputModel>(std::make_shared<GgufBuilderDecoder>(graph));
}
auto transformations = m_impl->transformation_extensions;
diff --git a/src/frontends/gguf/src/model_adapter_attribute.hpp b/src/frontends/gguf/src/model_adapter_attribute.hpp
new file mode 100644
index 00000000000..def7dbe1002
--- /dev/null
+++ b/src/frontends/gguf/src/model_adapter_attribute.hpp
@@ -0,0 +1,39 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/core/runtime_attribute.hpp"
+#include "openvino/frontend/gguf/model_adapter.hpp"
+
+namespace ov::frontend::gguf {
+
+class ModelAdapterAttribute : public ov::RuntimeAttribute {
+public:
+ OPENVINO_RTTI("gguf.model_adapter", "0", ov::RuntimeAttribute);
+
+ explicit ModelAdapterAttribute(std::shared_ptr<ModelAdapter> adapter) : adapter(std::move(adapter)) {}
+
+ bool visit_attributes(ov::AttributeVisitor&) override {
+ return false;
+ }
+
+ bool is_deterministic() const override {
+ return false;
+ }
+
+ std::shared_ptr<ModelAdapter> adapter;
+};
+
+inline std::shared_ptr<ModelAdapter> get_model_adapter(const std::shared_ptr<ov::Node>& node) {
+ const auto found = node->get_rt_info().find(ModelAdapterAttribute::get_type_info_static());
+ return found == node->get_rt_info().end() ? nullptr : found->second.as<ModelAdapterAttribute>().adapter;
+}
+
+inline void remove_model_adapters(const std::shared_ptr<ov::Model>& model) {
+ for (const auto& node : model->get_ops())
+ node->get_rt_info().erase(ModelAdapterAttribute::get_type_info_static());
+}
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/model_contract.hpp b/src/frontends/gguf/src/model_contract.hpp
new file mode 100644
index 00000000000..6e33b220d51
--- /dev/null
+++ b/src/frontends/gguf/src/model_contract.hpp
@@ -0,0 +1,61 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "builder/legacy_model_contract.hpp"
+#include "openvino/core/except.hpp"
+#include "openvino/core/model.hpp"
+#include "openvino/frontend/gguf/decoder.hpp"
+
+namespace ov::frontend::gguf {
+
+inline void write_model_contract(const std::shared_ptr<ov::Model>& model, const ModelContract& contract) {
+ std::string image_attention;
+ switch (contract.image_attention) {
+ case ModelContract::ImageAttentionMode::CAUSAL:
+ image_attention = "causal";
+ break;
+ case ModelContract::ImageAttentionMode::GLOBAL_AND_SLIDING:
+ image_attention = "global_and_sliding";
+ break;
+ case ModelContract::ImageAttentionMode::SLIDING_ONLY:
+ image_attention = "sliding_only";
+ break;
+ default:
+ OPENVINO_THROW("[GGUF] invalid image attention contract");
+ }
+ const std::string recurrent = !contract.batchable_recurrent ? "auto"
+ : *contract.batchable_recurrent ? "true"
+ : "false";
+ model->get_rt_info()["gguf_model_contract"] =
+ ov::AnyMap{{"batchable_recurrent", recurrent}, {"image_attention", image_attention}};
+}
+
+inline ModelContract read_model_contract(const std::shared_ptr<ov::Model>& model,
+ std::optional<int64_t> embedding_width = std::nullopt) {
+ if (!model->has_rt_info({"gguf_model_contract"}))
+ return resolve_legacy_model_contract(model, embedding_width);
+ ModelContract contract;
+ if (model->has_rt_info({"gguf_model_contract", "batchable_recurrent"})) {
+ const auto value = model->get_rt_info<std::string>({"gguf_model_contract", "batchable_recurrent"});
+ OPENVINO_ASSERT(value == "true" || value == "false" || value == "auto",
+ "[GGUF] invalid recurrent batching contract");
+ if (value != "auto")
+ contract.batchable_recurrent = value == "true";
+ }
+ if (model->has_rt_info({"gguf_model_contract", "image_attention"})) {
+ const auto value = model->get_rt_info<std::string>({"gguf_model_contract", "image_attention"});
+ if (value == "global_and_sliding") {
+ contract.image_attention = ModelContract::ImageAttentionMode::GLOBAL_AND_SLIDING;
+ } else if (value == "sliding_only") {
+ contract.image_attention = ModelContract::ImageAttentionMode::SLIDING_ONLY;
+ } else {
+ OPENVINO_ASSERT(value == "causal", "[GGUF] invalid image attention contract");
+ }
+ }
+ return contract;
+}
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/op/add_id.cpp b/src/frontends/gguf/src/op/add_id.cpp
index 23864934180..94143ee63d6 100644
--- a/src/frontends/gguf/src/op/add_id.cpp
+++ b/src/frontends/gguf/src/op/add_id.cpp
@@ -12,8 +12,11 @@
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
#include "openvino/op/gather.hpp"
+#include "openvino/op/greater_eq.hpp"
#include "openvino/op/reshape.hpp"
+#include "openvino/op/select.hpp"
#include "openvino/op/shape_of.hpp"
+#include "openvino/op/unsqueeze.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf::op {
@@ -32,7 +35,9 @@ ov::Output<ov::Node> reshape_add_id_input_to_2d(const ov::Output<ov::Node>& inpu
return input;
}
auto shape = std::make_shared<ov::op::v3::ShapeOf>(input, ov::element::i64);
- return std::make_shared<ov::op::v1::Reshape>(input, gather_dims(shape, dims), false);
+ auto target_shape = gather_dims(shape, dims);
+ auto reshaped_input = std::make_shared<ov::op::v1::Reshape>(input, target_shape, false);
+ return reshaped_input;
}
} // namespace
@@ -55,18 +60,29 @@ OutputVector translate_add_id(const NodeContext& context) {
ids = std::make_shared<ov::op::v0::Convert>(ids, ov::element::i32);
}
+ ov::Output<ov::Node> safe_ids = ids;
+ std::shared_ptr<ov::op::v1::GreaterEqual> valid_ids;
+ if (!has_nonnegative_indices(ids)) {
+ auto zero_id = ov::op::v0::Constant::create(ids.get_element_type(), ov::Shape{}, {0});
+ valid_ids = std::make_shared<ov::op::v1::GreaterEqual>(ids, zero_id);
+ safe_ids = std::make_shared<ov::op::v1::Select>(valid_ids, ids, zero_id);
+ }
auto gather_axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
- ov::Output<ov::Node> selected_bias = std::make_shared<ov::op::v8::Gather>(bias, ids, gather_axis);
- selected_bias =
- std::make_shared<ov::op::v1::Reshape>(selected_bias,
- std::make_shared<ov::op::v3::ShapeOf>(input, ov::element::i64),
- false);
+ auto gathered_bias = std::make_shared<ov::op::v8::Gather>(bias, safe_ids, gather_axis);
+ auto input_shape = std::make_shared<ov::op::v3::ShapeOf>(input, ov::element::i64);
+ ov::Output<ov::Node> selected_bias = std::make_shared<ov::op::v1::Reshape>(gathered_bias, input_shape, false);
if (selected_bias.get_element_type() != input.get_element_type()) {
selected_bias = std::make_shared<ov::op::v0::Convert>(selected_bias, input.get_element_type());
}
- ov::Output<ov::Node> res = std::make_shared<ov::op::v1::Add>(input, selected_bias);
+ auto added = std::make_shared<ov::op::v1::Add>(input, selected_bias);
+ ov::Output<ov::Node> res = added;
+ if (valid_ids) {
+ auto embedding_axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {-1});
+ auto valid_rows = std::make_shared<ov::op::v0::Unsqueeze>(valid_ids, embedding_axis);
+ res = std::make_shared<ov::op::v1::Select>(valid_rows, added, input);
+ }
return rename_outputs_with_suffix({std::move(res)}, context.get_name());
}
diff --git a/src/frontends/gguf/src/op/mul_mat_id.cpp b/src/frontends/gguf/src/op/mul_mat_id.cpp
index a73e0192956..716ac332336 100644
--- a/src/frontends/gguf/src/op/mul_mat_id.cpp
+++ b/src/frontends/gguf/src/op/mul_mat_id.cpp
@@ -17,9 +17,11 @@
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
#include "openvino/op/gather.hpp"
+#include "openvino/op/greater_eq.hpp"
#include "openvino/op/matmul.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/reshape.hpp"
+#include "openvino/op/select.hpp"
#include "openvino/op/shape_of.hpp"
#include "openvino/op/slice.hpp"
#include "openvino/op/transpose.hpp"
@@ -340,22 +342,35 @@ OutputVector translate_mul_mat_id(const NodeContext& context) {
activations = std::make_shared<ov::op::v0::Convert>(activations, ov::element::f32);
}
auto ids = context.get_input(2);
-
- if (expert_weights.get_element_type() == ov::element::u8 && expert_weights.get_partial_shape().rank().is_static() &&
- expert_weights.get_partial_shape().rank().get_length() == 5) {
- return rename_outputs_with_suffix({translate_mul_mat_id_mxfp4_packed(expert_weights, activations, ids)},
- context.get_name());
+ if (ids.get_element_type() != ov::element::i32 && ids.get_element_type() != ov::element::i64) {
+ ids = std::make_shared<ov::op::v0::Convert>(ids, ov::element::i32);
+ }
+ ov::Output<ov::Node> safe_ids = ids;
+ std::shared_ptr<ov::op::v1::GreaterEqual> valid_ids;
+ if (!has_nonnegative_indices(ids)) {
+ auto zero_id = ov::op::v0::Constant::create(ids.get_element_type(), ov::Shape{}, {0});
+ valid_ids = std::make_shared<ov::op::v1::GreaterEqual>(ids, zero_id);
+ safe_ids = std::make_shared<ov::op::v1::Select>(valid_ids, ids, zero_id);
}
- // The CPU GatherMatmul node requires constant-backed weights. Real .gguf models feed a
- // (possibly compressed) Constant weight leaf -> use the fused GatherMatmul path (compressed,
- // memory-bounded). A non-constant weights input (single-op tests, dynamic producers) can't use
- // GatherMatmul on CPU, so fall back to the portable Gather + MatMul lowering.
ov::Output<ov::Node> result;
- if (ov::op::util::is_on_path<ov::op::v0::Constant>(expert_weights)) {
- result = translate_mul_mat_id_gathermatmul(expert_weights, activations, ids);
+ if (expert_weights.get_element_type() == ov::element::u8 && expert_weights.get_partial_shape().rank().is_static() &&
+ expert_weights.get_partial_shape().rank().get_length() == 5) {
+ result = translate_mul_mat_id_mxfp4_packed(expert_weights, activations, safe_ids);
+ } else if (ov::op::util::is_on_path<ov::op::v0::Constant>(expert_weights)) {
+ result = translate_mul_mat_id_gathermatmul(expert_weights, activations, safe_ids);
} else {
- result = translate_mul_mat_id_generic(expert_weights, activations, ids);
+ result = translate_mul_mat_id_generic(expert_weights, activations, safe_ids);
+ }
+ if (valid_ids) {
+ auto result_shape = std::make_shared<ov::op::v3::ShapeOf>(result, ov::element::i64);
+ auto row_dimensions = gather_dims(result_shape, {0, 1, 2});
+ auto embedding_dimension = const_i64({1});
+ auto mask_shape =
+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{row_dimensions, embedding_dimension}, 0);
+ auto valid_rows = std::make_shared<ov::op::v1::Reshape>(valid_ids, mask_shape, false);
+ auto zero_result = ov::op::v0::Constant::create(result.get_element_type(), ov::Shape{}, {0});
+ result = std::make_shared<ov::op::v1::Select>(valid_rows, result, zero_result);
}
return rename_outputs_with_suffix({std::move(result)}, context.get_name());
}
diff --git a/src/frontends/gguf/src/op/scale.cpp b/src/frontends/gguf/src/op/scale.cpp
index 92d4f4cf460..2b8f47c0d33 100644
--- a/src/frontends/gguf/src/op/scale.cpp
+++ b/src/frontends/gguf/src/op/scale.cpp
@@ -10,6 +10,7 @@
#include "openvino/op/add.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/slice.hpp"
#include "utils.hpp"
@@ -25,6 +26,10 @@ OutputVector translate_scale(const NodeContext& context) {
auto scale_node = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{}, std::vector<float>{scale});
ov::Output<ov::Node> value = context.get_input(0);
+ const auto output_type = value.get_element_type();
+ if (output_type == ov::element::f16 || output_type == ov::element::bf16) {
+ value = std::make_shared<ov::op::v0::Convert>(value, ov::element::f32);
+ }
bool updated_cache = false;
if (context.get_op_case() == 1 && context.has_input("cache_rs_reset_idx") &&
context.has_input("cache_rs_reset_len")) {
@@ -54,6 +59,9 @@ OutputVector translate_scale(const NodeContext& context) {
} else {
res = scaled.get_node_shared_ptr();
}
+ if (res->get_output_element_type(0) != output_type) {
+ res = std::make_shared<ov::op::v0::Convert>(res, output_type);
+ }
return rename_outputs_with_suffix({std::move(res)}, context.get_name());
}
diff --git a/src/frontends/gguf/src/op/view.cpp b/src/frontends/gguf/src/op/view.cpp
index 76e1a30ec71..9921939ee3b 100644
--- a/src/frontends/gguf/src/op/view.cpp
+++ b/src/frontends/gguf/src/op/view.cpp
@@ -324,9 +324,54 @@ OutputVector translate_view(const NodeContext& context) {
const auto src_strides = context.get_attribute<std::vector<int64_t>>("view_input_strides", {});
const auto dst_strides = context.get_attribute<std::vector<int64_t>>("view_output_strides", {});
const int64_t byte_offset = context.get_attribute<int64_t>("view_offset_bytes", 0);
+ const int64_t block_size = context.get_attribute<int64_t>("view_block_size", 1);
- if (src_shape.size() == dst_shape.size() && src_shape.size() == src_strides.size() &&
- src_strides == dst_strides && byte_offset >= 0) {
+ const auto element_size = context.get_input(0).get_element_type().size();
+ const auto is_contiguous = [element_size](const ov::Shape& shape, const std::vector<int64_t>& strides) {
+ if (shape.size() != strides.size() || strides.empty() || strides[0] != static_cast<int64_t>(element_size)) {
+ return false;
+ }
+ int64_t expected_stride = static_cast<int64_t>(element_size);
+ for (size_t d = 0; d < shape.size(); ++d) {
+ const auto dim = static_cast<int64_t>(shape[shape.size() - 1 - d]);
+ if (dim > 1 && strides[d] != expected_stride) {
+ return false;
+ }
+ expected_stride *= dim;
+ }
+ return true;
+ };
+ if (byte_offset >= 0 && element_size > 0 && byte_offset % element_size == 0 &&
+ is_contiguous(src_shape, src_strides) && is_contiguous(dst_shape, dst_strides)) {
+ const int64_t start = byte_offset / element_size;
+ const int64_t count = static_cast<int64_t>(ov::shape_size(dst_shape));
+ const int64_t source_count = static_cast<int64_t>(ov::shape_size(src_shape));
+ if (start <= source_count && count <= source_count - start && (start != 0 || count != source_count)) {
+ auto flat_shape = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});
+ auto flat = std::make_shared<ov::op::v1::Reshape>(context.get_input(0), flat_shape, false);
+ auto starts = ov::op::v0::Constant::create(ov::element::i64, {1}, {start});
+ auto stops = ov::op::v0::Constant::create(ov::element::i64, {1}, {start + count});
+ auto steps = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
+ auto axes = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
+ auto selected = std::make_shared<ov::op::v8::Slice>(flat, starts, stops, steps, axes);
+ auto target = ov::op::v0::Constant::create(ov::element::i64, {dst_shape.size()}, dst_shape);
+ auto result = std::make_shared<ov::op::v1::Reshape>(selected, target, false);
+ return rename_outputs_with_suffix({std::move(result)}, context.get_name());
+ }
+ }
+
+ bool same_strides = src_shape.size() == dst_shape.size() && src_shape.size() == src_strides.size() &&
+ src_strides.size() == dst_strides.size();
+ if (same_strides) {
+ for (size_t d = 0; d < src_shape.size(); ++d) {
+ const auto axis = src_shape.size() - 1 - d;
+ if (dst_shape[axis] > 1 && src_strides[d] != dst_strides[d]) {
+ same_strides = false;
+ break;
+ }
+ }
+ }
+ if (same_strides && byte_offset >= 0 && block_size > 0) {
std::vector<int64_t> starts(src_shape.size(), 0);
std::vector<size_t> dims(src_shape.size());
std::iota(dims.begin(), dims.end(), 0);
@@ -343,6 +388,9 @@ OutputVector translate_view(const NodeContext& context) {
}
starts[d] = remaining / src_strides[d];
remaining %= src_strides[d];
+ if (d == 0) {
+ starts[d] *= block_size;
+ }
if (starts[d] < 0 || starts[d] + static_cast<int64_t>(dst_shape[src_shape.size() - 1 - d]) >
static_cast<int64_t>(src_shape[src_shape.size() - 1 - d])) {
valid = false;
@@ -362,12 +410,17 @@ OutputVector translate_view(const NodeContext& context) {
end[ov_axis] = begin[ov_axis] + static_cast<int64_t>(dst_shape[ov_axis]);
axes[ov_axis] = static_cast<int64_t>(ov_axis);
}
- auto result = std::make_shared<ov::op::v8::Slice>(
- context.get_input(0),
- ov::op::v0::Constant::create(ov::element::i64, {begin.size()}, begin),
- ov::op::v0::Constant::create(ov::element::i64, {end.size()}, end),
- ov::op::v0::Constant::create(ov::element::i64, {step.size()}, step),
- ov::op::v0::Constant::create(ov::element::i64, {axes.size()}, axes));
+ auto begin_node = ov::op::v0::Constant::create(ov::element::i64, {begin.size()}, begin);
+ auto end_node = ov::op::v0::Constant::create(ov::element::i64, {end.size()}, end);
+ auto step_node = ov::op::v0::Constant::create(ov::element::i64, {step.size()}, step);
+ auto axes_node = ov::op::v0::Constant::create(ov::element::i64, {axes.size()}, axes);
+ auto data = context.get_input(0);
+ if (data.get_partial_shape().rank().is_static() &&
+ data.get_partial_shape().rank().get_length() != static_cast<int64_t>(src_shape.size())) {
+ auto source_shape = ov::op::v0::Constant::create(ov::element::i64, {src_shape.size()}, src_shape);
+ data = std::make_shared<ov::op::v1::Reshape>(data, source_shape, false);
+ }
+ auto result = std::make_shared<ov::op::v8::Slice>(data, begin_node, end_node, step_node, axes_node);
return rename_outputs_with_suffix({std::move(result)}, context.get_name());
}
@@ -375,7 +428,7 @@ OutputVector translate_view(const NodeContext& context) {
// the outer planes. Flatten the two innermost ggml dimensions for that case.
if (src_shape.size() == 4 && src_shape[0] == dst_shape[0] && src_shape[1] == dst_shape[1] &&
src_strides[0] > 0 && byte_offset % src_strides[0] == 0) {
- const int64_t begin_elem = byte_offset / src_strides[0];
+ const int64_t begin_elem = (byte_offset / src_strides[0]) * block_size;
const int64_t src_plane = static_cast<int64_t>(src_shape[2] * src_shape[3]);
const int64_t dst_plane = static_cast<int64_t>(dst_shape[2] * dst_shape[3]);
if (begin_elem >= 0 && begin_elem + dst_plane <= src_plane) {
@@ -400,7 +453,7 @@ OutputVector translate_view(const NodeContext& context) {
}
if (src_shape.size() == dst_shape.size() && src_shape.size() == src_strides.size() &&
- src_strides.size() == dst_strides.size() && byte_offset >= 0) {
+ src_strides.size() == dst_strides.size() && byte_offset >= 0 && block_size > 0) {
std::vector<int64_t> starts(src_shape.size(), 0);
std::vector<int64_t> steps(src_shape.size(), 1);
std::vector<size_t> dims(src_shape.size());
@@ -419,6 +472,13 @@ OutputVector translate_view(const NodeContext& context) {
steps[d] = dst_strides[d] / src_strides[d];
starts[d] = remaining / src_strides[d];
remaining %= src_strides[d];
+ if (d == 0) {
+ if (starts[d] > std::numeric_limits<int64_t>::max() / block_size) {
+ valid = false;
+ break;
+ }
+ starts[d] *= block_size;
+ }
const size_t ov_axis = src_shape.size() - 1 - d;
const int64_t last = starts[d] + steps[d] * (static_cast<int64_t>(dst_shape[ov_axis]) - 1);
if (starts[d] < 0 || last >= static_cast<int64_t>(src_shape[ov_axis])) {
@@ -439,12 +499,18 @@ OutputVector translate_view(const NodeContext& context) {
end[ov_axis] = begin[ov_axis] + step[ov_axis] * (static_cast<int64_t>(dst_shape[ov_axis]) - 1) + 1;
axes[ov_axis] = static_cast<int64_t>(ov_axis);
}
- auto result = std::make_shared<ov::op::v8::Slice>(
- context.get_input(0),
- ov::op::v0::Constant::create(ov::element::i64, {begin.size()}, begin),
- ov::op::v0::Constant::create(ov::element::i64, {end.size()}, end),
- ov::op::v0::Constant::create(ov::element::i64, {step.size()}, step),
- ov::op::v0::Constant::create(ov::element::i64, {axes.size()}, axes));
+ auto begin_node = ov::op::v0::Constant::create(ov::element::i64, {begin.size()}, begin);
+ auto end_node = ov::op::v0::Constant::create(ov::element::i64, {end.size()}, end);
+ auto step_node = ov::op::v0::Constant::create(ov::element::i64, {step.size()}, step);
+ auto axes_node = ov::op::v0::Constant::create(ov::element::i64, {axes.size()}, axes);
+ auto data = context.get_input(0);
+ if (data.get_partial_shape().rank().is_static() &&
+ data.get_partial_shape().rank().get_length() != static_cast<int64_t>(src_shape.size())) {
+ auto source_shape = ov::op::v0::Constant::create(ov::element::i64, {src_shape.size()}, src_shape);
+ auto restored = std::make_shared<ov::op::v1::Reshape>(data, source_shape, false);
+ data = restored;
+ }
+ auto result = std::make_shared<ov::op::v8::Slice>(data, begin_node, end_node, step_node, axes_node);
return rename_outputs_with_suffix({std::move(result)}, context.get_name());
}
}
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 6a19ed7e3e9..971eaa9890e 100644
--- a/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
@@ -4,373 +4,47 @@
#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 "builder/arch/projector_adapter.hpp"
+#include "model_adapter_attribute.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 {
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, "'");
+std::shared_ptr<ov::op::v0::Result> embedding_result(const std::shared_ptr<ov::Model>& model,
+ AdaptMmprojToGenAI::Modality modality) {
+ const std::string prefix = modality == AdaptMmprojToGenAI::Modality::VISION ? "vision." : "audio.";
+ 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(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();
+ OPENVINO_ASSERT(selected, "[GGUF] mmproj has no ", prefix, "embeddings output");
+ return selected;
}
-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) {
+ModelAdapterResult 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" || projector == "lfm2",
- "[GGUF] no GenAI vision layout for mmproj projector '",
- projector,
- "'");
- }
+ const auto selected = embedding_result(model, modality);
+ const auto adapter = get_model_adapter(selected);
+ if (layout == Layout::VISION_ENCODERS && !adapter)
+ require_projector_layout(model);
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();
@@ -380,7 +54,7 @@ Models adapt_mmproj(const std::shared_ptr<ov::Model>& model,
ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
size_t auxiliary_count = 0;
if (modality == Modality::VISION && model->has_rt_info({"gguf_mmproj", "vision.auxiliary_count"}))
- auxiliary_count = size_t(metadata(model, "vision.auxiliary_count", 0));
+ auxiliary_count = size_t(mmproj_int_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}),
@@ -401,34 +75,40 @@ Models adapt_mmproj(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}};
- }
+ if (adapter) {
+ OPENVINO_ASSERT(adapter->transform, "[GGUF] invalid projector adapter callback");
+ return adapter->transform(model);
}
- return vision_models;
+ if (layout == Layout::VISION_ENCODERS)
+ vision_models = adapt_projector_layout(model);
+ return {model, std::move(vision_models)};
}
} // namespace
bool AdaptMmprojToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
m_vision_models.clear();
- if (m_layout == Layout::EMBEDDINGS) {
+ if (m_layout == Layout::EMBEDDINGS && !get_model_adapter(embedding_result(model, m_modality))) {
adapt_mmproj(model, m_modality, m_layout);
+ remove_model_adapters(model);
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);
+ // Callbacks and layout construction may fail after rewiring the independent clone.
+ auto adaptation = adapt_mmproj(model->clone(), m_modality, m_layout);
+ auto adapted = std::move(adaptation.model);
+ auto vision_models = std::move(adaptation.models);
+ OPENVINO_ASSERT(adapted && (m_layout == Layout::EMBEDDINGS || !vision_models.empty()),
+ "[GGUF] projector adapter returned no models");
+ bool primary = vision_models.empty();
+ for (const auto& [name, encoder] : vision_models) {
+ OPENVINO_ASSERT(!name.empty() && encoder, "[GGUF] projector adapter returned an invalid model");
+ encoder->validate_nodes_and_infer_types();
+ primary |= encoder == adapted;
+ }
+ OPENVINO_ASSERT(primary, "[GGUF] projector adapter omitted its primary model");
+ adapted->validate_nodes_and_infer_types();
+ remove_model_adapters(adapted);
+ for (const auto& [name, encoder] : vision_models)
+ remove_model_adapters(encoder);
const auto results = model->get_results();
const auto parameters = model->get_parameters();
const auto sinks = model->get_sinks();
@@ -445,6 +125,7 @@ bool AdaptMmprojToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
model->add_results(adapted->get_results());
model->add_sinks(adapted->get_sinks());
model->add_variables(adapted->get_variables());
+ model->get_rt_info() = adapted->get_rt_info();
for (auto& [name, encoder] : vision_models) {
if (encoder == adapted)
encoder = model;
diff --git a/src/frontends/gguf/src/pass/adapt_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
index dd4d7a097ad..efb602ae5d2 100644
--- a/src/frontends/gguf/src/pass/adapt_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
@@ -8,6 +8,7 @@
#include <memory>
#include <vector>
+#include "model_contract.hpp"
#include "openvino/core/graph_util.hpp"
#include "openvino/core/rt_info.hpp"
#include "openvino/frontend/gguf/make_stateful.hpp"
@@ -88,33 +89,7 @@ public:
ov::matcher_pass_callback callback = [](ov::pass::pattern::Matcher& m) {
auto unsqueeze = m.get_match_root();
- // translate_get_rows optionally inserts a Convert between the Gather and the
- // Unsqueeze (output dtype mismatch); look through it structurally instead of
- // relying on naming.
- auto node = unsqueeze->input_value(0).get_node_shared_ptr();
- if (auto convert = ov::as_type_ptr<v0::Convert>(node)) {
- node = convert->input_value(0).get_node_shared_ptr();
- }
- auto gather = ov::as_type_ptr<v8::Gather>(node);
- if (const auto reshape = ov::as_type_ptr<v1::Reshape>(node)) {
- const auto multiply = ov::as_type_ptr<v1::Multiply>(reshape->get_input_node_shared_ptr(0));
- if (multiply)
- gather = ov::as_type_ptr<v8::Gather>(multiply->get_input_node_shared_ptr(1));
- }
- if (!gather) {
- return false;
- }
-
- // The indices feeding the Gather are Squeeze(inp_tokens, [0,1]) (see
- // translate_get_rows); trace back through that Squeeze to confirm this call site is
- // actually rooted at the "inp_tokens" parameter, not some unrelated Gather/Unsqueeze
- // pair elsewhere in the graph (e.g. FixInpOutIdsRowSelect's call sites).
- auto indices_node = gather->input_value(1).get_node_shared_ptr();
- if (auto squeeze = ov::as_type_ptr<v0::Squeeze>(indices_node)) {
- indices_node = squeeze->input_value(0).get_node_shared_ptr();
- }
- auto param = ov::as_type_ptr<v0::Parameter>(indices_node);
- if (!param || param->output(0).get_names().count("inp_tokens") == 0) {
+ if (!token_embedding_lookup(unsqueeze)) {
return false;
}
@@ -253,14 +228,14 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
auto token_len_per_seq = find_parameter(model, "token_len_per_seq");
const bool has_recurrent_states = model->get_rt_info().count(gguf_recurrent_states_key()) != 0;
const auto operations = model->get_ops();
- const auto architecture = model->get_rt_info().find("gguf_architecture");
- const bool lfm2 =
- architecture != model->get_rt_info().end() &&
- (architecture->second.as<std::string>() == "lfm2" || architecture->second.as<std::string>() == "lfm2moe");
+ auto contract = read_model_contract(model);
+ const auto has_gated_delta_net = [&] {
+ return std::any_of(operations.begin(), operations.end(), [](const auto& node) {
+ return ov::is_type<internal::GatedDeltaNet>(node);
+ });
+ };
const bool batchable_recurrent =
- has_recurrent_states && (lfm2 || std::any_of(operations.begin(), operations.end(), [](const auto& node) {
- return ov::is_type<internal::GatedDeltaNet>(node);
- }));
+ has_recurrent_states && (contract.batchable_recurrent ? *contract.batchable_recurrent : has_gated_delta_net());
const bool recurrent_only = !inp_pos && !self_kq_mask && has_recurrent_states;
if (!inp_tokens || (!recurrent_only && !self_kq_mask)) {
return false;
@@ -282,6 +257,16 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
per_layer_count = it->second.as<int64_t>();
}
}
+ if (embedding_name.empty() || per_layer_name.empty()) {
+ const auto legacy =
+ resolve_legacy_embedding_boundaries(model, embedding_name.empty(), per_layer_name.empty());
+ if (legacy.token)
+ embedding_name = legacy.token->get_friendly_name();
+ if (legacy.per_layer) {
+ per_layer_name = legacy.per_layer->get_friendly_name();
+ per_layer_count = legacy.per_layer_count;
+ }
+ }
OPENVINO_ASSERT(!embedding_name.empty(), "[GGUF] missing native token embedding boundary");
}
@@ -362,6 +347,9 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
}
}
+ if (inputs_embeds)
+ contract = read_model_contract(model, inputs_embeds->get_partial_shape()[2].get_length());
+
// ---- new genai inputs: input_ids / attention_mask / position_ids [b, seq] i64 ----
// Recurrent state buffers currently hold one sequence. Keep that constraint explicit.
auto input_ids = make_shared<v0::Parameter>(
@@ -376,11 +364,7 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
multimodal_positions ? ov::PartialShape{4, -1, -1} : ov::PartialShape{-1, -1});
name_output(position_ids, "position_ids");
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{};
- 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))) {
+ if (inputs_embeds && contract.image_attention != ModelContract::ImageAttentionMode::CAUSAL) {
token_type_ids = make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
name_output(token_type_ids, "token_type_ids");
}
@@ -530,8 +514,8 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
allowed = make_shared<v1::LogicalAnd>(allowed, valid_keys);
auto mask_4d = to_mask_4d(allowed);
if (self_kq_mask) {
- // Gemma4 permits bidirectional image attention only in sliding-window layers.
- const bool causal_global = token_type_ids && arch == "gemma4";
+ const bool causal_global =
+ token_type_ids && contract.image_attention == ModelContract::ImageAttentionMode::SLIDING_ONLY;
auto global_mask = causal_global ? to_mask_4d(make_shared<v1::LogicalAnd>(causal, valid_keys)) : mask_4d;
self_kq_mask->output(0).replace(global_mask->output(0));
}
diff --git a/src/frontends/gguf/src/quant/gguf.cpp b/src/frontends/gguf/src/quant/gguf.cpp
index 2395dfa73c6..765dc69c40b 100644
--- a/src/frontends/gguf/src/quant/gguf.cpp
+++ b/src/frontends/gguf/src/quant/gguf.cpp
@@ -347,88 +347,6 @@ static const ov::Tensor& metadata_scalar_tensor(const std::unordered_map<std::st
return *tensor;
}
-float metadata_to_float(const std::unordered_map<std::string, GGUFMetaData>& metadata, const std::string& key) {
- const auto& tensor = metadata_scalar_tensor(metadata, key, ov::element::f32);
- return *(tensor.data<ov::element_type_traits<ov::element::f32>::value_type>());
-}
-
-int metadata_to_int(const std::unordered_map<std::string, GGUFMetaData>& metadata, const std::string& key) {
- // GGUF stores these counts as u32; reinterpret as i32 (values fit comfortably).
- const auto& tensor = metadata_scalar_tensor(metadata, key, ov::element::u32);
- return static_cast<int>(*(tensor.data<ov::element_type_traits<ov::element::u32>::value_type>()));
-}
-
-// `metadata_to_int`/`metadata_to_float`, but returning `default_value` when `key` is absent
-// instead of asserting. Most per-architecture scalars below are optional this way: llama.cpp's
-// hparam loading has the same "missing key -> compile-time default" convention per key.
-int metadata_to_int_or(const std::unordered_map<std::string, GGUFMetaData>& metadata,
- const std::string& key,
- int default_value) {
- return metadata.count(key) ? metadata_to_int(metadata, key) : default_value;
-}
-
-float metadata_to_float_or(const std::unordered_map<std::string, GGUFMetaData>& metadata,
- const std::string& key,
- float default_value) {
- return metadata.count(key) ? metadata_to_float(metadata, key) : default_value;
-}
-
-// GGUF stores true/false flags (e.g. "<arch>.expert_weights_norm") as a 1-byte
-// element::boolean scalar tensor, not the u32 metadata_to_int reinterprets; reading it through
-// metadata_to_int would read 4 bytes out of a 1-byte allocation. Read the boolean storage
-// directly instead.
-bool metadata_to_bool_or(const std::unordered_map<std::string, GGUFMetaData>& metadata,
- const std::string& key,
- bool default_value) {
- if (!metadata.count(key)) {
- return default_value;
- }
- const auto& tensor = metadata_scalar_tensor(metadata, key, ov::element::boolean);
- return *(tensor.data<ov::element_type_traits<ov::element::boolean>::value_type>()) != 0;
-}
-
-// Read a metadata array of integer elements as a vector<int32_t>, empty when the key is absent.
-// GGUF writers disagree on the element type for the same key (llama.cpp emits
-// rope.dimension_sections as INT32 and attention.recurrent_layers as UINT32, and boolean arrays
-// carry the sliding-window pattern), so accept any 1- or 4-byte integer encoding.
-// `max_n` caps how many entries are taken (rope.dimension_sections reads at most 4).
-std::vector<int32_t> metadata_to_i32_vector(const std::unordered_map<std::string, GGUFMetaData>& metadata,
- const std::string& key,
- size_t max_n = std::numeric_limits<size_t>::max()) {
- std::vector<int32_t> out;
- auto it = metadata.find(key);
- if (it == metadata.end()) {
- return out;
- }
- const auto* t = std::get_if<ov::Tensor>(&it->second);
- OPENVINO_ASSERT(t && t->data(), "[GGUF] metadata key '", key, "' is not an array as expected");
- const auto& et = t->get_element_type();
- OPENVINO_ASSERT(et.is_integral() && (et.size() == 1 || et.size() == 4),
- "[GGUF] metadata key '",
- key,
- "' is not an integer array as expected, got ",
- et);
- const auto* bytes = static_cast<const uint8_t*>(t->data());
- const size_t n = std::min(t->get_size(), max_n);
- out.reserve(n);
- for (size_t i = 0; i < n; ++i) {
- if (et == ov::element::boolean) {
- // Only a boolean array normalizes to 0/1. A byte-sized INTEGER array keeps its
- // value: these keys carry counts and widths (a rope section of 32 must not
- // become 1), not just flags.
- out.push_back(bytes[i] ? 1 : 0);
- } else if (et.size() == 1) {
- out.push_back(et.is_signed() ? static_cast<int32_t>(static_cast<int8_t>(bytes[i]))
- : static_cast<int32_t>(bytes[i]));
- } else {
- int32_t v = 0;
- std::memcpy(&v, bytes + i * 4, sizeof(v));
- out.push_back(v);
- }
- }
- return out;
-}
-
} // namespace
ov::Shape get_shape(const GgufTensor& tensor) {
@@ -865,272 +783,4 @@ GGUFLoad get_gguf_data(const std::vector<std::filesystem::path>& paths) {
return load_gguf_files(std::move(files));
}
-std::map<std::string, GGUFMetaData> decoder_config_from_meta(
- const std::unordered_map<std::string, GGUFMetaData>& metadata) {
- std::map<std::string, GGUFMetaData> config;
- // The architecture key drives every other key lookup; fail with a clear message (not a bare
- // std::out_of_range / std::bad_variant_access) if the file carries no / a non-string one.
- auto arch_it = metadata.find("general.architecture");
- OPENVINO_ASSERT(arch_it != metadata.end(),
- "[GGUF] file has no 'general.architecture' metadata key; not a valid GGUF model file");
- const auto* arch_ptr = std::get_if<std::string>(&arch_it->second);
- OPENVINO_ASSERT(arch_ptr, "[GGUF] 'general.architecture' metadata is not a string");
- const std::string arch = *arch_ptr;
- config["architecture"] = arch;
- config["layer_num"] = metadata_to_int(metadata, arch + ".block_count");
- const int head_count = metadata_to_int(metadata, arch + ".attention.head_count");
- // Validate this independently of key_length: head_count is also used by the builder and,
- // when key_length is absent, is the divisor for the head-size fallback below.
- OPENVINO_ASSERT(head_count > 0, "[GGUF] '", arch, ".attention.head_count' must be positive");
- config["head_num"] = head_count;
- config["head_size"] = metadata.count(arch + ".attention.key_length")
- ? metadata_to_int(metadata, arch + ".attention.key_length")
- : (metadata_to_int(metadata, arch + ".embedding_length") / head_count);
- {
- const std::string kv_key = arch + ".attention.head_count_kv";
- if (metadata.count(kv_key)) {
- const auto& kv_val = metadata.at(kv_key);
- if (auto* t = std::get_if<ov::Tensor>(&kv_val)) {
- if (t->get_shape().size() == 1 && t->get_shape()[0] > 1) {
- // Per-layer array: store as a config tensor for use in the builder.
- config["head_num_kv_per_layer"] = *t;
- // Global default = the most common value (max over the array).
- const auto* data = t->data<uint32_t>();
- int global_kv = static_cast<int>(*std::max_element(data, data + t->get_size()));
- config["head_num_kv"] = global_kv;
- } else {
- config["head_num_kv"] = metadata_to_int(metadata, kv_key);
- }
- }
- } else {
- config["head_num_kv"] = metadata_to_int(metadata, arch + ".attention.head_count");
- }
- }
- config["hidden_size"] = metadata_to_int(metadata, arch + ".embedding_length");
- config["max_position_embeddings"] = metadata_to_int_or(metadata, arch + ".context_length", 2048);
- config["pooling_type"] = metadata_to_int_or(metadata, arch + ".pooling_type", 0);
- config["causal_attention"] = metadata_to_bool_or(metadata, arch + ".attention.causal", true) ? 1 : 0;
- config["rms_norm_eps"] = metadata_to_float(
- metadata,
- arch + (arch == "jais2" ? ".attention.layer_norm_epsilon" : ".attention.layer_norm_rms_epsilon"));
- config["rope_freq_base"] = metadata_to_float_or(metadata, arch + ".rope.freq_base", 10000.0f);
- // Advisory: the dominant quant type of the file. Purely informational -- every weight carries
- // its own type in the tensor info, which is what the dequant path uses. Optional because
- // llama.cpp's own model writer (llama_model_saver, the source of the per-arch test fixtures)
- // does not emit it; requiring it would reject files llama.cpp itself considers valid.
- config["file_type"] = metadata_to_int_or(metadata, "general.file_type", 0);
-
- // RoPE YaRN scaling: freq_scale = 1/factor (default 1.0 = no scaling), ext_factor = 1.0
- // for YARN type (0.0 otherwise), n_ctx_orig from rope.scaling.original_context_length.
- // Mirrors llama.cpp: hparams.rope_freq_scale_train = 1/ropescale; ext_factor = (yarn?1:0).
- {
- const float ropescale = metadata_to_float_or(metadata, arch + ".rope.scaling.factor", 0.0f);
- float freq_scale = 1.0f;
- if (ropescale != 0.0f) {
- OPENVINO_ASSERT(std::isfinite(ropescale) && ropescale > 0.0f,
- "[GGUF] '",
- arch,
- ".rope.scaling.factor' must be finite and positive");
- const double inverse = 1.0 / static_cast<double>(ropescale);
- OPENVINO_ASSERT(inverse <= std::numeric_limits<float>::max(),
- "[GGUF] '",
- arch,
- ".rope.scaling.factor' reciprocal exceeds the float range");
- freq_scale = static_cast<float>(inverse);
- }
- config["rope_freq_scale"] = freq_scale;
-
- const bool is_yarn = metadata.count(arch + ".rope.scaling.type") &&
- std::get<std::string>(metadata.at(arch + ".rope.scaling.type")) == "yarn";
- config["rope_ext_factor"] = is_yarn ? 1.0f : 0.0f;
- config["rope_yarn_beta_fast"] = metadata_to_float_or(metadata, arch + ".rope.scaling.yarn_beta_fast", 32.0f);
- config["rope_yarn_beta_slow"] = metadata_to_float_or(metadata, arch + ".rope.scaling.yarn_beta_slow", 1.0f);
- config["rope_yarn_log_mul"] = metadata_to_float_or(metadata, arch + ".rope.scaling.yarn_log_multiplier", 0.0f);
- config["attention_temperature_scale"] =
- metadata_to_float_or(metadata, arch + ".attention.temperature_scale", 0.0f);
-
- // n_ctx_orig: use rope.scaling.original_context_length when present; fall back to
- // context_length (the training context, which is also n_ctx_train in llama.cpp).
- config["rope_n_ctx_orig"] = metadata_to_int_or(metadata,
- arch + ".rope.scaling.original_context_length",
- std::get<int>(config["max_position_embeddings"]));
- }
-
- // Number of rope dimensions (n_rot); defaults to head_size. Some archs (e.g. partial-
- // rotary models) set it smaller. A value of 0 means "no RoPE" or full rotation —
- // treat as head_size to avoid division-by-zero and empty-vector crashes downstream.
- {
- const int rope_dims = metadata_to_int_or(metadata, arch + ".rope.dimension_count", 0);
- config["rope_dimension_count"] = (rope_dims > 0) ? rope_dims : std::get<int>(config["head_size"]);
- }
- // Gemma4: SWA layers use a smaller head size (and fewer rope dims) than global layers.
- // key_length_swa / value_length_swa / rope.dimension_count_swa default to key_length.
- config["head_size_swa"] =
- metadata_to_int_or(metadata, arch + ".attention.key_length_swa", std::get<int>(config["head_size"]));
- config["rope_dimension_count_swa"] =
- metadata_to_int_or(metadata, arch + ".rope.dimension_count_swa", std::get<int>(config["rope_dimension_count"]));
- // Gemma4: per-layer embedding dimension (0 = absent / not used).
- config["n_embd_per_layer"] = metadata_to_int_or(metadata, arch + ".embedding_length_per_layer_input", 0);
- // Gemma4: number of layers that have their own KV cache (from the start).
- // shared_kv_layers trailing layers reuse KV from the preceding full-KV layer.
- // 0 = all layers have KV (default for non-Gemma4 architectures).
- config["shared_kv_layers"] = metadata_to_int_or(metadata, arch + ".attention.shared_kv_layers", 0);
-
- // Mixture-of-experts config (0 when dense).
- config["expert_count"] = metadata_to_int_or(metadata, arch + ".expert_count", 0);
- config["expert_used_count"] = metadata_to_int_or(metadata, arch + ".expert_used_count", 0);
- config["expert_feed_forward_length"] = metadata_to_int_or(metadata, arch + ".expert_feed_forward_length", 0);
- // Hybrid MoE: first N layers are dense, remainder use MoE routing.
- // Mirrors llama.cpp hparams.n_layer_dense_lead (deepseek2-ocr, ernie4_5-moe, glm4moe).
- config["n_layer_dense_lead"] = metadata_to_int_or(metadata, arch + ".leading_dense_block_count", 0);
- // Shared (always-active) experts: run in parallel with routed experts, outputs summed.
- // Mirrors llama.cpp hparams.n_expert_shared (deepseek2-ocr, bailingmoe2, exaone-moe).
- config["expert_shared_count"] = metadata_to_int_or(metadata, arch + ".expert_shared_count", 0);
-
- // Per-architecture scalars (MiniCPM family). MiniCPM bakes these into hparams with
- // backward-compatible defaults when the GGUF lacks the keys (older exports); newer
- // exports carry the keys and override. Other archs default to 1.0 (no-op).
- const bool is_minicpm = arch.rfind("minicpm", 0) == 0;
- // Gemma/Gemma2/Gemma3/Gemma4 scale embeddings by sqrt(n_embd) before the first layer.
- const bool is_gemma = arch == "gemma" || arch == "gemma2" || arch == "gemma3" || arch == "gemma4";
- const float def_embedding_scale =
- is_minicpm ? 12.0f : (is_gemma ? std::sqrt(static_cast<float>(std::get<int>(config["hidden_size"]))) : 1.0f);
- const float def_residual_scale =
- is_minicpm ? 1.4f / std::sqrt(static_cast<float>(std::get<int>(config["layer_num"]))) : 1.0f;
- const float def_logit_scale = is_minicpm ? 256.0f / static_cast<float>(std::get<int>(config["hidden_size"])) : 1.0f;
- config["embedding_scale"] = metadata_to_float_or(metadata, arch + ".embedding_scale", def_embedding_scale);
- config["residual_scale"] = metadata_to_float_or(metadata, arch + ".residual_scale", def_residual_scale);
- const float logit_scale = metadata_to_float_or(metadata, arch + ".logit_scale", def_logit_scale);
- // MiniCPM shares llama.cpp's Granite graph, which divides logits by this scale.
- config["logit_scale"] = is_minicpm && logit_scale != 0.0f ? 1.0f / logit_scale : logit_scale;
- // Hybrid linear-attention (Gated DeltaNet) parameters: qwen35 / qwen3next / kimi-linear.
- // 0 for every non-SSM architecture, which is what the builder tests against.
- auto ssm_key = [&](const std::string& k) {
- return metadata_to_int_or(metadata, arch + "." + k, 0);
- };
- config["ssm_conv_kernel"] = ssm_key("ssm.conv_kernel");
- config["ssm_state_size"] = ssm_key("ssm.state_size");
- config["ssm_group_count"] = ssm_key("ssm.group_count");
- config["ssm_time_step_rank"] = ssm_key("ssm.time_step_rank");
- config["ssm_inner_size"] = ssm_key("ssm.inner_size");
- // Every full_attention_interval-th layer is full attention, the rest are recurrent:
- // llama.cpp qwen35 is_recr(il) = (il < n_layer) && ((il + 1) % interval != 0).
- // llama.cpp defaults the interval to 4 when the GGUF omits the key, so match that rather
- // than rejecting the model (llama.cpp src/models/qwen35.cpp load_arch_hparams).
- config["full_attention_interval"] = metadata_to_int_or(metadata, arch + ".full_attention_interval", 4);
- // NextN / MTP: extra decoder blocks stored past the main stack and NOT executed in a normal
- // forward pass. The builder must stop its layer loop before them.
- config["nextn_predict_layers"] = ssm_key("nextn_predict_layers");
- // Explicit per-layer recurrent flags. llama.cpp consults this FIRST and only falls back to
- // full_attention_interval when it is absent (src/models/qwen35.cpp load_arch_hparams).
- config["recurrent_layer_flags"] = metadata_to_i32_vector(metadata, arch + ".attention.recurrent_layers");
-
- // M-RoPE section widths (qwen35 / qwen3vl): 4 per-axis rotary section sizes.
- config["rope_sections"] = metadata_to_i32_vector(metadata, arch + ".rope.dimension_sections", 4);
-
- // Optional explicit attention (softmax) scale; 0 -> use 1/sqrt(head_size).
- // Gemma4 uses scale=1.0 (no pre-attn scaling), per llama.cpp hparams.f_attention_scale=1.0.
- // Gemma3 (like gemma/gemma2) uses 1/sqrt(n_embd_head_k); llama.cpp applies it as a
- // Qcur pre-scale with build_attn(scale=1.0), which is numerically 1/sqrt(head_size) --
- // exactly the default branch here, so gemma3 must NOT force scale=1.0.
- const float def_attention_scale = arch == "gemma4" ? 1.0f
- : arch == "gemma2" && std::get<int>(config["layer_num"]) == 46
- ? 1.0f / std::sqrt(static_cast<float>(std::get<int>(config["hidden_size"]) /
- std::get<int>(config["head_num"])))
- : 0.0f;
- config["attention_scale"] = metadata_to_float_or(metadata, arch + ".attention.scale", def_attention_scale);
-
- // gpt-oss SWA: separate RoPE frequency base for sliding-window attention layers.
- // Defaults to the global rope_freq_base when the key is absent (non-SWA or legacy models),
- // EXCEPT gemma3: llama.cpp's gemma3 loader keeps the struct default 10000.0 when the key is
- // absent (it does not reset to the global base first, unlike gemma2/gemma4/cohere2/etc.), so
- // gemma3 SWA layers rope at freq_base=10000 while global layers use 1000000. See
- // llama.cpp src/models/gemma3.cpp load_arch_hparams.
- const float def_freq_base_swa =
- (arch == "gemma3" || arch == "plamo3") ? 10000.0f : std::get<float>(config["rope_freq_base"]);
- config["rope_freq_base_swa"] = metadata_to_float_or(metadata, arch + ".rope.freq_base_swa", def_freq_base_swa);
-
- // has_swa: true when the GGUF carries either a sliding_window_pattern or a
- // sliding_window (a finite window length), indicating SWA is active. The builder uses
- // this to add the self_kq_mask_swa input and route SWA layers to the windowed mask.
- // Architectures that always use sinks (gpt-oss) or per-layer flags (gemma4) are handled
- // separately inside the builder; has_swa catches newly-added archs like smollm3.
- //
- // The same "positive finite" value, when present, is also the window's length in tokens
- // (swa_window_size below): a token at position q may then attend to keys in
- // [q - swa_window_size + 1, q], which AdaptToGenAI needs to build a correctly windowed
- // self_kq_mask_swa instead of reusing the full causal mask.
- uint32_t swa_window_value =
- (arch == "gemma2" || (arch == "exaone4" && std::get<int>(config["layer_num"]) == 64)) ? 4096 : 0;
- if (metadata.count(arch + ".attention.sliding_window")) {
- const auto& t = std::get<ov::Tensor>(metadata.at(arch + ".attention.sliding_window"));
- const uint32_t v = *t.data<uint32_t>();
- // A value of 0 or UINT32_MAX typically means "no SWA"; treat only positive finite
- // values as a real window.
- if (v > 0 && v < 0xFFFFFFFFu) {
- swa_window_value = v;
- }
- }
- config["has_swa"] = (metadata.count(arch + ".attention.sliding_window_pattern") || swa_window_value > 0) ? 1 : 0;
- config["swa_window_size"] = static_cast<int>(swa_window_value);
-
- // gpt-oss SWA: alternation period (default 2: even layers are SWA). Matches llama.cpp's
- // set_swa_pattern(swa_period, dense_first=false): il is SWA if il % period < period - 1.
- // Gemma4: sliding_window_pattern is a boolean array (one entry per layer); stored as
- // an ov::Tensor of element::boolean. Detect by checking the variant type.
- if (metadata.count(arch + ".attention.sliding_window_pattern")) {
- const auto& v = metadata.at(arch + ".attention.sliding_window_pattern");
- if (std::holds_alternative<ov::Tensor>(v)) {
- const auto& t = std::get<ov::Tensor>(v);
- if (t.get_element_type() == ov::element::boolean) {
- // Boolean array: convert to vector<int32_t> (1=SWA, 0=global) for the builder.
- config["swa_layer_flags"] =
- metadata_to_i32_vector(metadata, arch + ".attention.sliding_window_pattern");
- config["swa_layer_pattern"] = 0; // 0 = use per-layer flags, not period
- } else {
- config["swa_layer_pattern"] = metadata_to_int(metadata, arch + ".attention.sliding_window_pattern");
- config["swa_layer_flags"] = std::vector<int32_t>{};
- }
- } else {
- config["swa_layer_pattern"] = metadata_to_int(metadata, arch + ".attention.sliding_window_pattern");
- config["swa_layer_flags"] = std::vector<int32_t>{};
- }
- } else {
- // No explicit pattern key. gemma3 defaults to period 6 (llama.cpp gemma3 load_arch_hparams
- // passes swa_period=6 to get_key_or_arr); gpt-oss and others default to 2.
- config["swa_layer_pattern"] = arch == "gemma3" ? 6
- : arch == "plamo3" ? 8
- : (arch == "exaone4" || arch == "exaone-moe") ? 4
- : 2;
- config["swa_layer_flags"] = std::vector<int32_t>{};
- }
-
- // gpt-oss MoE: optional per-expert routing weight scale applied after softmax (0 = 1.0 no-op).
- config["expert_weights_scale"] = metadata_to_float_or(metadata, arch + ".expert_weights_scale", 0.0f);
-
- // Routing metadata; architecture-required normalization is resolved in DecoderConfig.
- config["moe_layer_step"] = metadata_to_int_or(metadata, arch + ".interleave_moe_layer_step", 1);
- config["expert_groups"] = metadata_to_int_or(metadata, arch + ".expert_group_count", 1);
- config["expert_groups_used"] = metadata_to_int_or(metadata, arch + ".expert_group_used_count", 1);
- auto expert_gating_func = metadata_to_int_or(metadata, arch + ".expert_gating_func", arch == "glm4moe" ? 2 : 1);
- if (arch == "glm4moe" && expert_gating_func == 0)
- expert_gating_func = 2;
- config["expert_gating_func"] = expert_gating_func;
- config["expert_weights_norm"] = metadata_to_bool_or(metadata, arch + ".expert_weights_norm", false) ? 1 : 0;
-
- // Gemma2 attention soft-cap: tanh(QK^T * (1/cap)) * cap applied inside the attention.
- // 0.0 means no soft-cap (default for all non-Gemma2 architectures).
- config["attn_logit_softcapping"] = metadata_to_float_or(metadata, arch + ".attn_logit_softcapping", 0.0f);
-
- // Gemma2/Gemma3 final logit soft-cap applied after lm_head: tanh(x/cap)*cap.
- // 0.0 means no soft-cap.
- config["final_logit_softcapping"] = metadata_to_float_or(metadata, arch + ".final_logit_softcapping", 0.0f);
-
- for (const auto& [key, value] : metadata) {
- if (key.compare(0, 15, "prism.hadamard.") == 0)
- config[key] = value;
- }
- return config;
-}
-
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/quant/gguf.hpp b/src/frontends/gguf/src/quant/gguf.hpp
index e29329fe5cf..f1b664782fa 100644
--- a/src/frontends/gguf/src/quant/gguf.hpp
+++ b/src/frontends/gguf/src/quant/gguf.hpp
@@ -138,18 +138,6 @@ void dequant_row_q6_k_f32_for_test(const uint8_t* row, size_t cols, float* y);
GGUFLoad get_gguf_data(const std::filesystem::path& file);
GGUFLoad get_gguf_data(const std::vector<std::filesystem::path>& files);
-// Extract the DECODER-family architecture config (architecture, layer_num, head_num, head_size,
-// head_num_kv, hidden_size, max_position_embeddings, rms_norm_eps, rope_freq_base, file_type, ...)
-// from parsed metadata.
-//
-// Every key it reads is prefixed with the LLM architecture name ("<arch>.block_count",
-// "<arch>.attention.head_count", ...), so it is only meaningful for a causal-decoder GGUF. Call
-// detect_model_kind() first: an mmproj file names its architecture "clip" and carries "clip.*"
-// keys instead, and would fail here on a missing block_count. A future non-decoder family gets its
-// own reader next to this one rather than extending it.
-std::map<std::string, GGUFMetaData> decoder_config_from_meta(
- const std::unordered_map<std::string, GGUFMetaData>& metadata);
-
// Reverse of the GGML dimension order (GGUF stores dims fastest-first).
ov::Shape get_shape(const GgufTensor& tensor);
diff --git a/src/frontends/gguf/src/translate_session.cpp b/src/frontends/gguf/src/translate_session.cpp
index 0579bc5c615..449a62af964 100644
--- a/src/frontends/gguf/src/translate_session.cpp
+++ b/src/frontends/gguf/src/translate_session.cpp
@@ -15,6 +15,8 @@
#include "builder/gguf_builder_decoder.hpp"
#include "hadamard_sign_folding.hpp"
#include "input_model.hpp"
+#include "model_adapter_attribute.hpp"
+#include "model_contract.hpp"
#include "node_context.hpp"
#include "openvino/core/graph_util.hpp"
#include "openvino/core/node.hpp"
@@ -295,14 +297,25 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
}
}
- // The architecture and projector metadata select what the GenAI adapters change, including
- // adapters registered as transformation extensions.
- if (builder)
- resulting_model->get_rt_info()["gguf_architecture"] = builder->get_attribute("architecture");
+ write_model_contract(resulting_model, gguf_model_decoder->get_model_contract());
+ if (const auto architecture = gguf_model_decoder->get_architecture(); !architecture.empty())
+ resulting_model->get_rt_info()["gguf_architecture"] = architecture;
if (!gguf_model_decoder->get_mmproj_config().empty()) {
resulting_model->get_rt_info()["gguf_mmproj"] = gguf_model_decoder->get_mmproj_config();
}
+ for (const auto& [output, adapter] : gguf_model_decoder->get_model_adapters()) {
+ OPENVINO_ASSERT(adapter && adapter->transform, "[GGUF] invalid model adapter for ", output);
+ bool found = false;
+ for (const auto& result : resulting_model->get_results()) {
+ if (!result->input_value(0).get_tensor().get_names().count(output))
+ continue;
+ result->get_rt_info()[ModelAdapterAttribute::get_type_info_static()] = ModelAdapterAttribute(adapter);
+ found = true;
+ }
+ OPENVINO_ASSERT(found, "[GGUF] model adapter has no output ", output);
+ }
+
if (builder) {
resulting_model = resulting_model->clone();
}
diff --git a/src/frontends/gguf/src/utils.cpp b/src/frontends/gguf/src/utils.cpp
index 0fe5e8e0cfd..d8137bc3471 100644
--- a/src/frontends/gguf/src/utils.cpp
+++ b/src/frontends/gguf/src/utils.cpp
@@ -38,11 +38,32 @@
#include "openvino/op/subtract.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/util/topk_base.hpp"
#include "openvino/op/variadic_split.hpp"
#include "transformations/rt_info/disable_precision_conversion.hpp"
namespace ov::frontend::gguf {
+bool has_nonnegative_indices(const ov::Output<ov::Node>& output) {
+ auto current = output;
+ while (true) {
+ const auto node = current.get_node_shared_ptr();
+ if (ov::is_type<ov::op::util::TopKBase>(node))
+ return current.get_index() == 1;
+ if (const auto convert = ov::as_type_ptr<ov::op::v0::Convert>(node)) {
+ const auto source_type = convert->get_input_element_type(0);
+ const auto target_type = convert->get_output_element_type(0);
+ if (source_type != target_type && !(source_type == ov::element::i32 && target_type == ov::element::i64))
+ return false;
+ } else if (!ov::is_type<ov::op::v1::Reshape>(node) && !ov::is_type<ov::op::v1::Transpose>(node) &&
+ !ov::is_type<ov::op::v0::Squeeze>(node) && !ov::is_type<ov::op::v0::Unsqueeze>(node) &&
+ !ov::is_type<ov::op::v8::Slice>(node)) {
+ return false;
+ }
+ current = node->input_value(0);
+ }
+}
+
namespace {
constexpr char hadamard_marker[] = "gguf_hadamard_block";
@@ -264,6 +285,29 @@ std::shared_ptr<ov::op::v0::Parameter> find_parameter(const std::shared_ptr<ov::
return nullptr;
}
+int64_t mmproj_int_metadata(const std::shared_ptr<ov::Model>& model, const std::string& key, int64_t minimum) {
+ 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;
+}
+
int non_cont_dim(std::vector<size_t> ne, std::vector<size_t> nb) {
const auto dim = static_cast<int>(nb.size() - 1);
size_t bytes = nb[dim];
diff --git a/src/frontends/gguf/src/utils.hpp b/src/frontends/gguf/src/utils.hpp
index 05605b308f4..978c097be48 100644
--- a/src/frontends/gguf/src/utils.hpp
+++ b/src/frontends/gguf/src/utils.hpp
@@ -10,6 +10,7 @@
#include "node_context.hpp"
#include "openvino/core/node.hpp"
#include "openvino/core/node_vector.hpp"
+#include "openvino/op/convert.hpp"
#include "openvino/op/shape_of.hpp"
#include "openvino/op/topk.hpp"
@@ -37,6 +38,9 @@ std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> get_glu_inputs(const NodeC
/// Returns nullptr if the model has no such Parameter.
std::shared_ptr<ov::op::v0::Parameter> find_parameter(const std::shared_ptr<ov::Model>& model, const std::string& name);
+/// \brief Read an integer string attribute from the model's `gguf_mmproj` rt_info; must be >= `minimum`.
+int64_t mmproj_int_metadata(const std::shared_ptr<ov::Model>& model, const std::string& key, int64_t minimum = 1);
+
int non_cont_dim(std::vector<size_t> ne, std::vector<size_t> nb);
template <typename T>
@@ -72,6 +76,8 @@ void name_output(const ov::Output<ov::Node>& out, const std::string& name);
// then return the same vector without an extra copy.
OutputVector rename_outputs_with_suffix(OutputVector outputs, const std::string& suffix);
+bool has_nonnegative_indices(const ov::Output<ov::Node>& output);
+
// GGML TOP_K and ARGSORT return I32 indices, which are OpenVINO TopK's second output.
ov::Output<ov::Node> make_topk_indices(const ov::Output<ov::Node>& input,
const ov::Output<ov::Node>& k,
@@ -98,7 +104,22 @@ OutputVector translate_1to1_match_1_input(const NodeContext& context) {
template <typename T>
OutputVector translate_1to1_match_2_inputs(const NodeContext& context) {
num_inputs_check(context, 2, 2);
- auto res = std::make_shared<T>(context.get_input(0), context.get_input(1));
+ auto lhs = context.get_input(0);
+ auto rhs = context.get_input(1);
+ const auto output_type = lhs.get_element_type();
+ const bool promote =
+ output_type != rhs.get_element_type() && output_type.is_real() && rhs.get_element_type().is_real();
+ if (promote) {
+ const auto compute_type = output_type == ov::element::f64 || rhs.get_element_type() == ov::element::f64
+ ? ov::element::f64
+ : ov::element::f32;
+ lhs = std::make_shared<ov::op::v0::Convert>(lhs, compute_type);
+ rhs = std::make_shared<ov::op::v0::Convert>(rhs, compute_type);
+ }
+ ov::Output<ov::Node> res = std::make_shared<T>(lhs, rhs);
+ if (promote && res.get_element_type().is_real() && res.get_element_type() != output_type) {
+ res = std::make_shared<ov::op::v0::Convert>(res, output_type);
+ }
return rename_outputs_with_suffix({std::move(res)}, context.get_name());
}
} // namespace op
diff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txt
index b600be6ecb0..cfe50612469 100644
--- a/src/frontends/gguf/tests/CMakeLists.txt
+++ b/src/frontends/gguf/tests/CMakeLists.txt
@@ -39,6 +39,9 @@ set(FRONTEND_SRCS
"${FE_SRC_DIR}/builder/arch_registry.cpp"
"${FE_SRC_DIR}/builder/projector_registry.cpp"
"${FE_SRC_DIR}/builder/decoder_config.cpp"
+ "${FE_SRC_DIR}/builder/decoder_metadata.cpp"
+ "${FE_SRC_DIR}/builder/arch/decoder_family.cpp"
+ "${FE_SRC_DIR}/builder/arch/projector_adapter.cpp"
"${FE_SRC_DIR}/builder/model_kind.cpp"
"${FE_SRC_DIR}/extension/architecture.cpp"
"${FE_SRC_DIR}/extension/projector.cpp"
diff --git a/src/frontends/gguf/tests/gen_arch_accuracy.py b/src/frontends/gguf/tests/gen_arch_accuracy.py
index 189e18d6295..cb1b9518359 100644
--- a/src/frontends/gguf/tests/gen_arch_accuracy.py
+++ b/src/frontends/gguf/tests/gen_arch_accuracy.py
@@ -19,6 +19,8 @@ import numpy as np
from mmproj_fixtures import finish, save_npz
CASES = {
+ "afmoe": {"qk": True, "moe": True, "shared": True, "lead": 1, "post": True,
+ "swa": True, "gate": True, "selection_bias": True, "sigmoid": True, "layers": 4},
"lfm2": {},
"lfm2-tied": {"architecture": "lfm2", "tied": True},
"lfm2-swa": {"architecture": "lfm2", "swa": True, "kernel": 4},
@@ -26,6 +28,7 @@ CASES = {
"lfm2moe": {"moe": True, "lead": 1},
"lfm2moe-all-experts": {"architecture": "lfm2moe", "moe": True, "sigmoid": True, "expert_scale": 2.5},
"qwen35": {}, "qwen35moe": {},
+ "qwen35-zero-scales": {"architecture": "qwen35", "zero_scales": True},
"qwen35moe-fused": {"architecture": "qwen35moe", "fused_experts": True},
# Real checkpoints quantize attn_gate apart from ssm_beta/ssm_alpha: F16 here selects the
# frontend's beta+alpha-only merge, and an F16 beta in layer 2 selects separate projections.
@@ -46,6 +49,7 @@ CASES = {
"minimax-m2": {"moe": True, "full_qk": True, "selection_bias": True, "rope_dims": 4, "sigmoid": True},
"plamo3": {"qk": True, "fused": True, "fused_ffn": True, "post": True, "bare_post": True, "swa": True}, "qwen2": {"bias": True}, "qwen3": {"qk": True},
"phi3": {"fused": True, "fused_ffn": True}, "minicpm": {},
+ "minicpm-default": {"architecture": "minicpm", "default_logit_scale": True},
"olmoe": {"moe": True, "full_qk": True},
"hunyuan-dense": {"qk": True}, "hunyuan-moe": {"qk": True, "moe": True, "shared": True},
"qwen3moe": {"qk": True, "moe": True},
@@ -88,8 +92,9 @@ def write_mamba2_model(path, opts, arch="mamba2"):
w.add_context_length(128)
w.add_embedding_length(d)
w.add_block_count(4 if hybrid else 2)
- w.add_head_count(4 if hybrid else 0)
+ w.add_head_count([4, 4, 0, 0] if hybrid else 0)
if hybrid:
+ w.add_layer_norm_eps(1e-5)
w.add_head_count_kv([0, 2, 0, 0])
w.add_feed_forward_length([0, 0, 48, 0])
w.add_key_length(8)
@@ -137,7 +142,7 @@ def write_mamba2_model(path, opts, arch="mamba2"):
finish(w)
-def write_qwen35_model(path, arch, fused_experts=False, f16=(), hadamard=False):
+def write_qwen35_model(path, arch, fused_experts=False, f16=(), hadamard=False, zero_scales=False):
w = gguf.GGUFWriter(path, arch)
d, head, heads, kv, ff, vocab = 32, 16, 4, 2, 48, 32
state, groups, vheads, kernel = 8, 2, 4, 4
@@ -160,6 +165,9 @@ def write_qwen35_model(path, arch, fused_experts=False, f16=(), hadamard=False):
"state_size": state, "conv_kernel": kernel}.items():
w.add_uint32(arch + ".ssm." + key, value)
w.add_uint32(arch + ".full_attention_interval", 4)
+ if zero_scales:
+ w.add_embedding_scale(0.0)
+ w.add_residual_scale(0.0)
if hadamard:
names = ["output.weight"]
for layer in range(4):
@@ -364,7 +372,7 @@ def write_model(path, arch, opts):
if arch == "gemma4":
return write_gemma4_model(path, opts)
if arch in ("qwen35", "qwen35moe"):
- return write_qwen35_model(path, arch, opts.get("fused_experts", False), opts.get("f16", ()), opts.get("hadamard", False))
+ return write_qwen35_model(path, arch, opts.get("fused_experts", False), opts.get("f16", ()), opts.get("hadamard", False), opts.get("zero_scales", False))
if arch in ("mamba2", "nemotron_h"):
return write_mamba2_model(path, opts, arch)
w = gguf.GGUFWriter(path, arch)
@@ -406,7 +414,7 @@ def write_model(path, arch, opts):
w.add_attn_temperature_scale(opts.get("temperature", 0.0))
if opts.get("swa"):
w.add_sliding_window(2)
- w.add_sliding_window_pattern(2)
+ w.add_sliding_window_pattern(4 if arch == "afmoe" else 2)
if arch == "plamo3":
w.add_rope_freq_base_swa(100.0)
if opts.get("softcap"):
@@ -414,6 +422,8 @@ def write_model(path, arch, opts):
w.add_final_logit_softcapping(3.0)
if arch == "muse-glimmer":
w.add_logit_scale(1.0)
+ if arch == "minicpm" and not opts.get("default_logit_scale"):
+ w.add_logit_scale(d / 256.0)
if opts.get("moe"):
w.add_expert_count(4)
w.add_expert_used_count(2)
diff --git a/src/frontends/gguf/tests/gen_mmproj_accuracy.py b/src/frontends/gguf/tests/gen_mmproj_accuracy.py
index 46e8dcbb60f..aff9a887e08 100644
--- a/src/frontends/gguf/tests/gen_mmproj_accuracy.py
+++ b/src/frontends/gguf/tests/gen_mmproj_accuracy.py
@@ -27,7 +27,7 @@ SINGLE_GRID = ("gemma3", "gemma3_fused", "gemma3_legacy", "idefics3", "janus_pro
# Single-grid models rerun here on two grids with different token counts.
REGRIDDED = ("qwen2.5vl_merger_grids", "resampler_grids")
TWO_GRID = ("muse-glimmer", "pixtral", "pixtral_merge", "phi4", "lfm2", "lfm2_no_norm", "lfm2a", "gemma4v", "gemma4uv", "gemma4uv_low_contrast",
- "gemma4ua", "gemma4v_one_sided", "minicpmv4_6", "gemma4a", "deepseekocr", "deepseekocr2",
+ "gemma4ua", "gemma4v_one_sided", "minicpmv4_6", "minicpmv4_7", "minicpmv4_7_4x", "gemma4a", "deepseekocr", "deepseekocr2",
"deepseekocr_resize", "deepseekocr_overview", "deepseekocr2_overview", *REGRIDDED)
@@ -275,9 +275,10 @@ def single_grid_width(projector):
return 128 if projector.startswith("resampler") else 12 if projector == "qwen3vl_merger" else 6
-VARIANTS = ("_resize", "_overview", "_one_sided", "_low_contrast")
+VARIANTS = ("_4x", "_resize", "_overview", "_one_sided", "_low_contrast")
# mmproj_ops_oracle output file -> test_data .npy name.
OPS_EXPECTATIONS = {
+ "view_q8_input": "view_q8_input", "view_q8_34": "view_q8_34", "view_q8_102": "view_q8_102",
"window_input": "mmproj_window_input", "windows": "mmproj_windows", "restored": "mmproj_restored",
"relative_table": "mmproj_relative_table", "relative": "mmproj_relative",
"vision": "vision_rope_expected", "imrope": "multimodal_imrope_expected",
@@ -425,7 +426,7 @@ def write_grid_model(path, family):
else:
w.add_uint32(key + "image_size", 8)
w.add_uint32(key + "patch_size", 24 if low_contrast else 2)
- w.add_uint32(key + "projector.scale_factor", 4 if family == "minicpmv4_6" else 2)
+ w.add_uint32(key + "projector.scale_factor", 4 if family in {"minicpmv4_6", "minicpmv4_7"} and "_4x" not in variants else 2)
w.add_uint32(key + "image_min_pixels", 16)
w.add_uint32(key + "image_max_pixels", 4096)
w.add_array(key + "image_mean", [.5, .5, .5])
@@ -504,16 +505,19 @@ def write_grid_model(path, family):
w.add_uint32(key + "spatial_merge_size", 2)
norm("mm.input_norm", width, False)
linear("mm.patch_merger", width * 4, width, False)
- elif family == "minicpmv4_6":
+ elif family in {"minicpmv4_6", "minicpmv4_7"}:
tensor("v.position_embd.weight", (4900, width))
w.add_array(key + "wa_layer_indexes", [0])
p = "v.vit_merger."
- norm(p + "ln1", width)
- for name in ("attn_q", "attn_k", "attn_v", "attn_out"):
- linear(p + name, width, width)
- norm(p + "ds_ln", width * 4)
- linear(p + "ds_ffn_up", width * 4, hidden)
- linear(p + "ds_ffn_down", hidden, width)
+ if "_4x" not in variants:
+ norm(p + "ln1", width)
+ for name in ("attn_q", "attn_k", "attn_v", "attn_out"):
+ linear(p + name, width, width)
+ norm(p + "ds_ln", width * 4)
+ linear(p + "ds_ffn_up", width * 4, hidden)
+ linear(p + "ds_ffn_down", hidden, width)
+ if family == "minicpmv4_7":
+ tensor("v.tok_embd_sep", (4, output))
norm("mm.input_norm", width * 4)
linear("mm.up", width * 4, hidden)
linear("mm.down", hidden, output)
@@ -600,14 +604,18 @@ def grid_inputs(family, width, height):
if family.startswith(("pixtral", "gemma4")):
result.update(position_x=cols.astype(np.int32).reshape(1, 1, 1, -1),
position_y=rows.astype(np.int32).reshape(1, 1, 1, -1))
- if family == "minicpmv4_6":
+ if family in {"minicpmv4_6", "minicpmv4_7"}:
result["position_ids"] = (70 * (70 * rows // h) + 70 * cols // w).astype(np.int32).reshape(1, 1, 1, -1)
order = merge_window_order(h, w)
result["window_indices"] = np.array(order, np.int32).reshape(1, 1, 1, -1)
result["inverse_window_indices"] = np.argsort(order).astype(np.int32).reshape(1, 1, 1, -1)
index = np.arange(h * w) // 4
result["attention_mask"] = np.where(index[:, None] == index[None], 0, np.finfo(np.float32).min).astype(np.float32)[None, None]
- for name, dh, dw in (("vit_merger", h, w), ("merger", h // 2, w // 2)):
+ mergers = (("merger", h, w),) if "_4x" in variants else (("vit_merger", h, w), ("merger", h // 2, w // 2))
+ if "_4x" in variants:
+ for key in ("window_indices", "inverse_window_indices", "attention_mask"):
+ result.pop(key)
+ for name, dh, dw in mergers:
for i, (dy, dx) in enumerate(((0, 0), (0, 1), (1, 0), (1, 1))):
result[f"{name}.indices.{i}"] = np.array([(y + dy) * dw + x + dx
for y in range(0, dh, 2) for x in range(0, dw, 2)], np.int32).reshape(1, 1, 1, -1)
diff --git a/src/frontends/gguf/tests/mmproj_ops_oracle.cpp b/src/frontends/gguf/tests/mmproj_ops_oracle.cpp
index 62612704e5e..bce0c376081 100644
--- a/src/frontends/gguf/tests/mmproj_ops_oracle.cpp
+++ b/src/frontends/gguf/tests/mmproj_ops_oracle.cpp
@@ -55,6 +55,32 @@ int geometry(const std::filesystem::path& directory) {
return 0;
}
+int quantized_view(const std::filesystem::path& directory) {
+ auto* ctx = ggml_init({64 * 1024 * 1024, nullptr, false});
+ auto* input = ggml_new_tensor_2d(ctx, GGML_TYPE_Q8_0, 64, 4);
+ std::vector<float> values(256);
+ for (size_t i = 0; i < values.size(); ++i)
+ values[i] = 127.f * float(1 + i / 32);
+ ggml_quantize_chunk(GGML_TYPE_Q8_0, values.data(), input->data, 0, 4, 64, nullptr);
+ std::ofstream source(directory / "view_q8_input.bin", std::ios::binary);
+ source.write(reinterpret_cast<const char*>(values.data()), values.size() * sizeof(float));
+ int status = 0;
+ for (const size_t offset : {34u, 102u}) {
+ auto* view = ggml_view_2d(ctx, input, 32, 2, input->nb[1] * 2, offset);
+ auto* output = ggml_cast(ctx, view, GGML_TYPE_F32);
+ auto* graph = ggml_new_graph(ctx);
+ ggml_build_forward_expand(graph, output);
+ if (ggml_graph_compute_with_ctx(ctx, graph, 2) != GGML_STATUS_SUCCESS) {
+ status = 3;
+ break;
+ }
+ std::ofstream file(directory / ("view_q8_" + std::to_string(offset) + ".bin"), std::ios::binary);
+ file.write(static_cast<char*>(output->data), ggml_nbytes(output));
+ }
+ ggml_free(ctx);
+ return status;
+}
+
// One op per mode: vision/imrope RoPE, antialiased bilinear resize variants, or 2D im2col.
int single_op(const std::string& mode, const std::filesystem::path& output) {
const bool vision = mode == "vision";
@@ -133,6 +159,7 @@ int main(int argc, char** argv) {
const std::filesystem::path directory(argv[1]);
std::filesystem::create_directories(directory);
int status = geometry(directory);
+ status = status ? status : quantized_view(directory);
for (const char* mode :
{"vision", "imrope", "resize", "resize_corners", "resize_down", "resize_down_corners", "im2col7", "im2col9"})
status = status ? status : single_op(mode, directory / (std::string(mode) + ".bin"));
diff --git a/src/frontends/gguf/tests/test_adapt_to_genai.cpp b/src/frontends/gguf/tests/test_adapt_to_genai.cpp
index 9cc47463922..c8421065074 100644
--- a/src/frontends/gguf/tests/test_adapt_to_genai.cpp
+++ b/src/frontends/gguf/tests/test_adapt_to_genai.cpp
@@ -18,6 +18,7 @@
#include "common_test_utils/node_builders/constant.hpp"
#include "gtest/gtest.h"
+#include "model_contract.hpp"
#include "node_context.hpp"
#include "op_test_utils.hpp"
#include "openvino/core/validation_util.hpp"
@@ -32,6 +33,7 @@
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
#include "openvino/op/divide.hpp"
+#include "openvino/op/gated_delta_net.hpp"
#include "openvino/op/gather.hpp"
#include "openvino/op/matmul.hpp"
#include "openvino/op/multiply.hpp"
@@ -446,11 +448,30 @@ TEST(GGUFAdaptToGenAI, BatchedMaskKeepsSequencesSeparateAndExcludesPadding) {
}
}
-class GGUFAdaptToGenAIImageMask : public testing::TestWithParam<std::string> {};
+using ImageAttentionMode = ov::frontend::gguf::ModelContract::ImageAttentionMode;
+
+static void image_attention_contract(const std::shared_ptr<ov::Model>& model, ImageAttentionMode mode) {
+ ov::frontend::gguf::ModelContract contract;
+ contract.image_attention = mode;
+ ov::frontend::gguf::write_model_contract(model, contract);
+}
+
+static std::shared_ptr<ov::Model> reload_ir_model(const std::shared_ptr<ov::Model>& model) {
+ std::stringstream xml, weights;
+ ov::pass::Serialize(xml, weights).run_on_model(model);
+ const auto bytes = weights.str();
+ ov::Tensor constants(ov::element::u8, {bytes.size()});
+ if (!bytes.empty())
+ std::memcpy(constants.data(), bytes.data(), bytes.size());
+ return ov::Core{}.read_model(xml.str(), constants);
+}
+
+class GGUFAdaptToGenAIImageMask : public testing::TestWithParam<ImageAttentionMode> {};
TEST_P(GGUFAdaptToGenAIImageMask, RespectsLayerTypeImageGroupsAndCachedPrefix) {
auto m = build_minimal_gguf_model();
- m.model->get_rt_info()["gguf_architecture"] = GetParam();
+ image_attention_contract(m.model, GetParam());
+ m.model->get_rt_info()["gguf_architecture"] = std::string("custom-image-decoder");
m.model->get_rt_info()[ov::frontend::gguf::pass::gguf_swa_window_key()] = int64_t{3};
auto mask = find_parameter(m.model, "self_kq_mask");
auto swa_mask = ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, -1, -1}, "self_kq_mask_swa");
@@ -484,7 +505,7 @@ TEST_P(GGUFAdaptToGenAIImageMask, RespectsLayerTypeImageGroupsAndCachedPrefix) {
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";
+ const bool bidirectional = layer == 1 || GetParam() == ImageAttentionMode::GLOBAL_AND_SLIDING;
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 &&
@@ -496,11 +517,12 @@ TEST_P(GGUFAdaptToGenAIImageMask, RespectsLayerTypeImageGroupsAndCachedPrefix) {
}
}
-INSTANTIATE_TEST_SUITE_P(Gemma,
+INSTANTIATE_TEST_SUITE_P(Contract,
GGUFAdaptToGenAIImageMask,
- testing::Values(std::string("gemma3"), std::string("gemma4")),
- [](const testing::TestParamInfo<std::string>& info) {
- return info.param;
+ testing::Values(ImageAttentionMode::GLOBAL_AND_SLIDING, ImageAttentionMode::SLIDING_ONLY),
+ [](const testing::TestParamInfo<ImageAttentionMode>& info) {
+ return info.param == ImageAttentionMode::GLOBAL_AND_SLIDING ? "GlobalAndSliding"
+ : "SlidingOnly";
});
TEST(GGUFAdaptToGenAI, EmbeddingModeMapsGenAIMultimodalPositionsToGGML) {
@@ -902,7 +924,7 @@ TEST_P(GGUFAdaptToGenAISlidingWindow, PreservedByPagedAttention) {
v0::Constant::create(ov::element::i64, {1}, {1}));
}
mask->output(0).replace(mask_source);
- model->get_rt_info()["gguf_architecture"] = std::string("gemma4");
+ image_attention_contract(model, ImageAttentionMode::SLIDING_ONLY);
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);
@@ -950,7 +972,7 @@ TEST_P(GGUFAdaptToGenAIImageWindow, MatchesSDPAAndPagedAttention) {
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");
+ image_attention_contract(model, ImageAttentionMode::SLIDING_ONLY);
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)
@@ -1239,7 +1261,7 @@ INSTANTIATE_TEST_SUITE_P(Softcap, GGUFAdaptToGenAILmHead, ::testing::Bool());
// embeddings only, and the unmodified PagedAttention conversion applies as for optimum-intel.
TEST(GGUFAdaptToGenAI, PagedAttentionFlattensEmbeddingsWithPerLayerInputs) {
auto model = build_attention_gguf_model(8, 1536, true);
- model->get_rt_info()["gguf_architecture"] = std::string("gemma4");
+ image_attention_contract(model, ImageAttentionMode::CAUSAL);
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);
@@ -1254,19 +1276,472 @@ TEST(GGUFAdaptToGenAI, PagedAttentionFlattensEmbeddingsWithPerLayerInputs) {
EXPECT_NO_THROW(model->validate_nodes_and_infer_types());
}
-class GGUFAdaptToGenAIGemma4VisionAttention : public ::testing::TestWithParam<int64_t> {};
+class GGUFAdaptToGenAIImageAttentionContract
+ : public ::testing::TestWithParam<std::tuple<int64_t, ImageAttentionMode>> {};
-TEST_P(GGUFAdaptToGenAIGemma4VisionAttention, MatchesLlamaVariantSelection) {
- const auto hidden = GetParam();
+TEST_P(GGUFAdaptToGenAIImageAttentionContract, UsesDeclaredSemanticsForAnyEmbeddingWidth) {
+ const auto& [hidden, mode] = GetParam();
auto model = build_attention_gguf_model(8, hidden, true);
- model->get_rt_info()["gguf_architecture"] = std::string("gemma4");
+ image_attention_contract(model, mode);
+ model->get_rt_info()["gguf_architecture"] = std::string("custom-image-decoder");
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);
+ EXPECT_EQ(find_parameter(model, "token_type_ids") == nullptr, mode == ImageAttentionMode::CAUSAL);
}
INSTANTIATE_TEST_SUITE_P(EmbeddingWidth,
- GGUFAdaptToGenAIGemma4VisionAttention,
- ::testing::Values(int64_t{32}, int64_t{1536}, int64_t{2560}));
+ GGUFAdaptToGenAIImageAttentionContract,
+ ::testing::Combine(::testing::Values(int64_t{32}, int64_t{1536}, int64_t{2560}),
+ ::testing::Values(ImageAttentionMode::CAUSAL,
+ ImageAttentionMode::GLOBAL_AND_SLIDING,
+ ImageAttentionMode::SLIDING_ONLY)));
+
+TEST(GGUFAdaptToGenAI, ModelContractSurvivesIRReloadBeforeAdaptation) {
+ for (const auto batchable : std::vector<std::optional<bool>>{std::nullopt, false, true}) {
+ auto model = build_attention_gguf_model(8, 4);
+ ov::frontend::gguf::ModelContract contract;
+ contract.image_attention = ImageAttentionMode::SLIDING_ONLY;
+ contract.batchable_recurrent = batchable;
+ ov::frontend::gguf::write_model_contract(model, contract);
+ for (const auto& node : model->get_ops())
+ node->get_rt_info().clear();
+ std::stringstream xml, weights;
+ ov::pass::Serialize(xml, weights).run_on_model(model);
+ const auto bytes = weights.str();
+ ov::Tensor constants(ov::element::u8, {bytes.size()});
+ if (!bytes.empty())
+ std::memcpy(constants.data(), bytes.data(), bytes.size());
+ auto restored = ov::Core{}.read_model(xml.str(), constants);
+ const auto restored_contract = ov::frontend::gguf::read_model_contract(restored);
+ EXPECT_EQ(restored_contract.image_attention, ImageAttentionMode::SLIDING_ONLY);
+ EXPECT_EQ(restored_contract.batchable_recurrent, batchable);
+ ASSERT_TRUE(AdaptToGenAI(AdaptToGenAI::InputMode::IDS_TO_LOGITS).run_on_model(restored));
+ EXPECT_NE(find_parameter(restored, "input_ids"), nullptr);
+ }
+}
+
+TEST(GGUFAdaptToGenAI, LegacyRecurrentContractSurvivesIRReloadBeforeAdaptation) {
+ for (const std::string architecture : {"lfm2", "lfm2moe", "qwen35", "custom-recurrent-decoder"}) {
+ SCOPED_TRACE(architecture);
+ auto model = build_minimal_gguf_model().model;
+ model->get_rt_info()["gguf_architecture"] = architecture;
+ model->get_rt_info()[ov::frontend::gguf::pass::gguf_recurrent_states_key()] = std::vector<std::string>{};
+ auto restored = reload_ir_model(model);
+ ASSERT_FALSE(restored->has_rt_info({"gguf_model_contract"}));
+ ASSERT_EQ(restored->get_rt_info<std::string>({"gguf_architecture"}), architecture);
+ const bool batchable = architecture == "lfm2" || architecture == "lfm2moe";
+ EXPECT_EQ(ov::frontend::gguf::read_model_contract(restored).batchable_recurrent,
+ batchable ? std::optional<bool>{true} : std::nullopt);
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(restored));
+ EXPECT_EQ(restored->input("input_ids").get_partial_shape()[0],
+ batchable ? ov::Dimension::dynamic() : ov::Dimension{1});
+ }
+}
+
+class GGUFAdaptToGenAILegacyImageContract
+ : public testing::TestWithParam<std::tuple<std::string, int64_t, ImageAttentionMode>> {};
+
+TEST_P(GGUFAdaptToGenAILegacyImageContract, ReloadsOldSchemaAndKeepsGlobalAndSlidingMasks) {
+ const auto& [architecture, hidden, mode] = GetParam();
+ auto m = build_minimal_gguf_model(4, hidden);
+ const auto lookup = m.embd->get_input_node_shared_ptr(0);
+ const auto table = lookup->get_input_node_shared_ptr(0);
+ table->set_friendly_name("token_embd.weight");
+ m.model->get_rt_info()["gguf_architecture"] = architecture;
+ m.model->get_rt_info()[ov::frontend::gguf::pass::gguf_swa_window_key()] = int64_t{1};
+ auto global_mask = find_parameter(m.model, "self_kq_mask");
+ auto sliding_mask =
+ ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, -1, -1}, "self_kq_mask_swa");
+ auto global_result = std::make_shared<v0::Result>(global_mask);
+ auto sliding_result = std::make_shared<v0::Result>(sliding_mask);
+ m.model->add_parameters({sliding_mask});
+ m.model->add_results({global_result, sliding_result});
+ auto restored = reload_ir_model(m.model);
+ ASSERT_FALSE(restored->has_rt_info({"gguf_model_contract"}));
+ ASSERT_EQ(restored->get_rt_info<std::string>({"gguf_architecture"}), architecture);
+ for (const auto& node : restored->get_ops())
+ ASSERT_EQ(node->get_rt_info().count("gguf.token_embedding"), 0);
+ EXPECT_EQ(ov::frontend::gguf::read_model_contract(restored, hidden).image_attention, mode);
+ AdaptToGenAI adapter(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ ASSERT_TRUE(adapter.run_on_model(restored));
+ ASSERT_NE(adapter.get_embedding_model(), nullptr);
+ ASSERT_EQ(find_parameter(restored, "input_ids"), nullptr);
+ EXPECT_EQ(restored->input("inputs_embeds").get_partial_shape(), (ov::PartialShape{-1, -1, hidden}));
+ EXPECT_EQ(find_parameter(restored, "token_type_ids") == nullptr, mode == ImageAttentionMode::CAUSAL);
+ auto inputs = make_genai_inputs(3);
+ inputs.erase("input_ids");
+ ov::Tensor embeddings(ov::element::f32, {1, 3, static_cast<size_t>(hidden)});
+ std::fill_n(embeddings.data<float>(), embeddings.get_size(), 0.f);
+ inputs.emplace("inputs_embeds", embeddings);
+ if (mode != ImageAttentionMode::CAUSAL) {
+ ov::Tensor token_types(ov::element::i64, {1, 3});
+ const std::vector<int64_t> types{1, 1, 0};
+ std::copy(types.begin(), types.end(), token_types.data<int64_t>());
+ inputs.emplace("token_type_ids", token_types);
+ }
+ ov::Core core;
+ auto request = core.compile_model(restored, "CPU").create_infer_request();
+ for (const auto& [name, tensor] : inputs)
+ request.set_tensor(name, tensor);
+ request.infer();
+ for (size_t layer = 0; layer < 2; ++layer) {
+ const auto mask = request.get_output_tensor(layer);
+ ASSERT_EQ(mask.get_shape(), (ov::Shape{1, 1, 3, 3}));
+ expect_mask(mask.data<const float>(), 3, 3, [&, mode = mode](size_t q, size_t k) {
+ const bool image_attention = mode == ImageAttentionMode::GLOBAL_AND_SLIDING ||
+ (layer == 1 && mode == ImageAttentionMode::SLIDING_ONLY);
+ return (k <= q && (layer == 0 || k + 1 > q)) || (image_attention && q < 2 && k < 2);
+ });
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ ArchitectureAndWidth,
+ GGUFAdaptToGenAILegacyImageContract,
+ testing::Values(std::make_tuple(std::string{"gemma3"}, int64_t{32}, ImageAttentionMode::GLOBAL_AND_SLIDING),
+ std::make_tuple(std::string{"gemma3"}, int64_t{1536}, ImageAttentionMode::GLOBAL_AND_SLIDING),
+ std::make_tuple(std::string{"gemma3"}, int64_t{2560}, ImageAttentionMode::GLOBAL_AND_SLIDING),
+ std::make_tuple(std::string{"gemma4"}, int64_t{32}, ImageAttentionMode::SLIDING_ONLY),
+ std::make_tuple(std::string{"gemma4"}, int64_t{1536}, ImageAttentionMode::CAUSAL),
+ std::make_tuple(std::string{"gemma4"}, int64_t{2560}, ImageAttentionMode::CAUSAL),
+ std::make_tuple(std::string{"gemma4"}, int64_t{3072}, ImageAttentionMode::SLIDING_ONLY)));
+
+TEST(GGUFAdaptToGenAI, ExplicitPartialContractPreventsLegacyRecurrentFallbackAfterIRReload) {
+ const std::vector<ov::AnyMap> contracts{ov::AnyMap{},
+ ov::AnyMap{{"batchable_recurrent", std::string{"auto"}}},
+ ov::AnyMap{{"batchable_recurrent", std::string{"false"}}},
+ ov::AnyMap{{"image_attention", std::string{"global_and_sliding"}}}};
+ for (const std::string architecture : {"lfm2", "lfm2moe"}) {
+ for (const auto& contract : contracts) {
+ SCOPED_TRACE(architecture);
+ auto model = build_minimal_gguf_model().model;
+ model->get_rt_info()["gguf_architecture"] = architecture;
+ model->get_rt_info()["gguf_model_contract"] = contract;
+ model->get_rt_info()[ov::frontend::gguf::pass::gguf_recurrent_states_key()] = std::vector<std::string>{};
+ auto restored = reload_ir_model(model);
+ ASSERT_TRUE(restored->has_rt_info({"gguf_model_contract"}));
+ EXPECT_NE(ov::frontend::gguf::read_model_contract(restored).batchable_recurrent, std::optional<bool>{true});
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(restored));
+ EXPECT_EQ(restored->input("input_ids").get_partial_shape()[0], ov::Dimension{1});
+ }
+ }
+}
+
+TEST(GGUFAdaptToGenAI, ExplicitPartialContractPreventsLegacyImageFallbackAfterIRReload) {
+ const std::vector<ov::AnyMap> contracts{ov::AnyMap{},
+ ov::AnyMap{{"batchable_recurrent", std::string{"true"}}},
+ ov::AnyMap{{"image_attention", std::string{"causal"}}}};
+ for (const std::string architecture : {"gemma3", "gemma4"}) {
+ for (const auto& contract : contracts) {
+ SCOPED_TRACE(architecture);
+ auto m = build_minimal_gguf_model(4, 32);
+ const auto lookup = m.embd->get_input_node_shared_ptr(0);
+ const auto table = lookup->get_input_node_shared_ptr(0);
+ table->set_friendly_name("token_embd.weight");
+ m.model->get_rt_info()["gguf_architecture"] = architecture;
+ m.model->get_rt_info()["gguf_model_contract"] = contract;
+ auto restored = reload_ir_model(m.model);
+ ASSERT_TRUE(restored->has_rt_info({"gguf_model_contract"}));
+ EXPECT_EQ(ov::frontend::gguf::read_model_contract(restored, 32).image_attention,
+ ImageAttentionMode::CAUSAL);
+ ASSERT_TRUE(AdaptToGenAI(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS).run_on_model(restored));
+ EXPECT_EQ(find_parameter(restored, "token_type_ids"), nullptr);
+ }
+ }
+}
+
+static MinimalGgufModel build_scaled_legacy_gguf_model(const std::string& architecture, bool per_layer) {
+ auto m = build_minimal_gguf_model(4, 4);
+ const auto squeeze_axes = v0::Constant::create(ov::element::i64, {2}, {0, 1});
+ const auto lookup = m.embd->get_input_node_shared_ptr(0);
+ const auto original_table = ov::as_type_ptr<v0::Constant>(lookup->get_input_node_shared_ptr(0));
+ const auto values = original_table->cast_vector<float>();
+ const auto table = v0::Constant::create(ov::element::f32, {1, 1, 4, 4}, values);
+ table->set_friendly_name("Constant_legacy_token_embd.weight");
+ const auto squeezed_table = std::make_shared<v0::Squeeze>(table, squeeze_axes);
+ lookup->input(0).replace_source_output(squeezed_table);
+ m.embd->set_friendly_name("Unsqueeze_legacy_lookup");
+ m.embd->get_rt_info().erase("gguf.token_embedding");
+ const auto converted = std::make_shared<v0::Convert>(m.embd, ov::element::f32);
+ converted->set_friendly_name("Convert_legacy_embd");
+ const auto scale = v0::Constant::create(ov::element::f32, {}, {2.f});
+ const auto scaled = std::make_shared<v1::Multiply>(converted, scale);
+ scaled->set_friendly_name("Multiply_legacy_embd_scaled");
+ scaled->get_rt_info()["gguf.token_embedding"] = true;
+ const auto logits = m.model->get_results().front()->get_input_node_shared_ptr(0);
+ logits->input(0).replace_source_output(scaled);
+ if (per_layer) {
+ std::vector<float> per_layer_values(24);
+ std::iota(per_layer_values.begin(), per_layer_values.end(), 100.f);
+ const auto pe_table = v0::Constant::create(ov::element::f32, {1, 1, 4, 6}, per_layer_values);
+ pe_table->set_friendly_name("Constant_legacy_per_layer_token_embd.weight");
+ const auto pe_table_squeezed = std::make_shared<v0::Squeeze>(pe_table, squeeze_axes);
+ const auto indices = std::make_shared<v0::Squeeze>(m.inp_tokens, squeeze_axes);
+ const auto axis0 = v0::Constant::create(ov::element::i64, {1}, {0});
+ const auto gathered = std::make_shared<v8::Gather>(pe_table_squeezed, indices, axis0);
+ m.pe_tok = std::make_shared<v0::Unsqueeze>(gathered, axis0);
+ m.pe_tok->set_friendly_name("Unsqueeze_legacy_pe_tok_lookup");
+ const auto pe_converted = std::make_shared<v0::Convert>(m.pe_tok, ov::element::f32);
+ pe_converted->set_friendly_name("Convert_legacy_pe_tok_flat");
+ const auto per_layer_scale = std::sqrt(2.f);
+ const auto pe_scale = v0::Constant::create(ov::element::f32, {}, {per_layer_scale});
+ const auto pe_scaled = std::make_shared<v1::Multiply>(pe_converted, pe_scale);
+ pe_scaled->set_friendly_name("Multiply_legacy_pe_tok_flat_scaled");
+ pe_scaled->get_rt_info()["gguf.per_layer_token_embedding"] = int64_t{3};
+ const auto split_shape = v0::Constant::create(ov::element::i64, {4}, {0, -1, 3, 2});
+ const auto split = std::make_shared<v1::Reshape>(pe_scaled, split_shape, true);
+ split->set_friendly_name("Reshape_legacy_pe_tok_split");
+ const auto transpose_axes = v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3});
+ const auto layer_major = std::make_shared<v1::Transpose>(split, transpose_axes);
+ layer_major->set_friendly_name("Transpose_legacy_pe_tok");
+ const auto reduce_axes = v0::Constant::create(ov::element::i64, {2}, {1, 3});
+ const auto pe_sum = std::make_shared<v1::ReduceSum>(layer_major, reduce_axes, true);
+ const auto combined = std::make_shared<v1::Add>(logits, pe_sum);
+ m.model->get_results().front()->input(0).replace_source_output(combined);
+ }
+ m.model->get_rt_info()["gguf_architecture"] = architecture;
+ m.model->validate_nodes_and_infer_types();
+ return m;
+}
+
+class GGUFAdaptToGenAILegacyScaledEmbedding : public testing::TestWithParam<std::pair<std::string, bool>> {};
+
+TEST_P(GGUFAdaptToGenAILegacyScaledEmbedding, ReloadPreservesTokenScalingAndInjectedMediaValues) {
+ const auto& [architecture, per_layer] = GetParam();
+ auto m = build_scaled_legacy_gguf_model(architecture, per_layer);
+ auto restored = reload_ir_model(m.model);
+ ASSERT_FALSE(restored->has_rt_info({"gguf_model_contract"}));
+ for (const auto& node : restored->get_ops()) {
+ ASSERT_EQ(node->get_rt_info().count("gguf.token_embedding"), 0);
+ ASSERT_EQ(node->get_rt_info().count("gguf.per_layer_token_embedding"), 0);
+ }
+ auto inputs = make_genai_inputs(3);
+ const std::map<std::string, ov::Tensor> lookup_inputs{{"input_ids", inputs.at("input_ids")}};
+ for (const auto& model : {m.model, restored}) {
+ AdaptToGenAI adapter(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ ASSERT_TRUE(adapter.run_on_model(model));
+ ASSERT_EQ(find_parameter(model, "input_ids"), nullptr);
+ const auto embedding_model = adapter.get_embedding_model();
+ ASSERT_NE(embedding_model, nullptr);
+ const auto embeddings = run_on_cpu(embedding_model, lookup_inputs);
+ ASSERT_EQ(embeddings.get_shape(), (ov::Shape{1, 3, 4}));
+ for (size_t i = 0; i < embeddings.get_size(); ++i)
+ EXPECT_FLOAT_EQ(embeddings.data<const float>()[i], 2.f * static_cast<float>(i));
+ if (per_layer) {
+ EXPECT_EQ(model->input("per_layer_inputs").get_partial_shape(), (ov::PartialShape{-1, -1, 3, 2}));
+ const auto per_layer_model = adapter.get_per_layer_embedding_model();
+ ASSERT_NE(per_layer_model, nullptr);
+ const auto per_layer_embeddings = run_on_cpu(per_layer_model, lookup_inputs);
+ ASSERT_EQ(per_layer_embeddings.get_shape(), (ov::Shape{1, 3, 3, 2}));
+ for (size_t i = 0; i < per_layer_embeddings.get_size(); ++i)
+ EXPECT_NEAR(per_layer_embeddings.data<const float>()[i],
+ std::sqrt(2.f) * (100.f + static_cast<float>(i)),
+ 1e-4f);
+ }
+ auto decoder_inputs = inputs;
+ decoder_inputs.erase("input_ids");
+ ov::Tensor injected(ov::element::f32, {1, 3, 4});
+ std::fill_n(injected.data<float>(), injected.get_size(), 7.f);
+ decoder_inputs.emplace("inputs_embeds", injected);
+ ov::Tensor token_types(ov::element::i64, {1, 3});
+ std::fill_n(token_types.data<int64_t>(), token_types.get_size(), 1);
+ decoder_inputs.emplace("token_type_ids", token_types);
+ if (per_layer) {
+ ov::Tensor injected_per_layer(ov::element::f32, {1, 3, 3, 2});
+ std::fill_n(injected_per_layer.data<float>(), injected_per_layer.get_size(), 11.f);
+ decoder_inputs.emplace("per_layer_inputs", injected_per_layer);
+ }
+ const auto actual = run_on_cpu(model, decoder_inputs);
+ ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 3, 1}));
+ for (size_t i = 0; i < actual.get_size(); ++i)
+ EXPECT_FLOAT_EQ(actual.data<const float>()[i], 28.f + (per_layer ? 66.f : 0.f));
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(NativeBoundary,
+ GGUFAdaptToGenAILegacyScaledEmbedding,
+ testing::Values(std::make_pair(std::string{"gemma3"}, false),
+ std::make_pair(std::string{"gemma4"}, true)));
+
+TEST(GGUFAdaptToGenAI, LegacyBoundaryFallbackKeepsExplicitMarkersAuthoritative) {
+ auto m = build_scaled_legacy_gguf_model("gemma4", true);
+ for (const auto& node : m.model->get_ops()) {
+ node->get_rt_info().erase("gguf.token_embedding");
+ node->get_rt_info().erase("gguf.per_layer_token_embedding");
+ }
+ m.embd->get_rt_info()["gguf.token_embedding"] = true;
+ m.pe_tok->get_rt_info()["gguf.per_layer_token_embedding"] = int64_t{3};
+ AdaptToGenAI adapter(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ ASSERT_TRUE(adapter.run_on_model(m.model));
+ const auto embedding_model = adapter.get_embedding_model();
+ auto inputs = make_genai_inputs(3);
+ const std::map<std::string, ov::Tensor> lookup_inputs{{"input_ids", inputs.at("input_ids")}};
+ const auto embeddings = run_on_cpu(embedding_model, lookup_inputs);
+ for (size_t i = 0; i < embeddings.get_size(); ++i)
+ EXPECT_FLOAT_EQ(embeddings.data<const float>()[i], static_cast<float>(i));
+ const auto per_layer_model = adapter.get_per_layer_embedding_model();
+ ASSERT_NE(per_layer_model, nullptr);
+ const auto per_layer_embeddings = run_on_cpu(per_layer_model, lookup_inputs);
+ for (size_t i = 0; i < per_layer_embeddings.get_size(); ++i)
+ EXPECT_FLOAT_EQ(per_layer_embeddings.data<const float>()[i], 100.f + static_cast<float>(i));
+}
+
+class GGUFAdaptToGenAILegacyHadamardEmbedding
+ : public testing::TestWithParam<std::tuple<bool, ov::element::Type, bool>> {};
+
+TEST_P(GGUFAdaptToGenAILegacyHadamardEmbedding, ReloadExtractsCompleteInverseGetRowsEndpoint) {
+ const auto& [signed_transform, weight_type, matrix_endpoint] = GetParam();
+ auto m = build_minimal_gguf_model(4, 4);
+ std::vector<float> latent_values(16);
+ std::iota(latent_values.begin(), latent_values.end(), 1.f);
+ const auto table = v0::Constant::create(weight_type, {1, 1, 4, 4}, latent_values);
+ table->set_friendly_name("Constant_native_token_embd.weight");
+ const std::vector<TensorDesc> input_descriptions{{"token_embd.weight", weight_type, {1, 1, 4, 4}},
+ {"inp_tokens", ov::element::i32, {1, 1, 1, -1}}};
+ const std::vector<TensorDesc> extra_inputs;
+ const TensorDesc output_description{"embd", ov::element::f32, {1, 1, -1, 4}};
+ std::map<std::string, ov::Any> attributes{{"hadamard_block", int64_t{4}}, {"hadamard_inverse", true}};
+ if (signed_transform) {
+ ov::Tensor signs(ov::element::f32, {4});
+ const std::vector<float> sign_values{-1.f, 1.f, -1.f, 1.f};
+ std::copy(sign_values.begin(), sign_values.end(), signs.data<float>());
+ attributes.emplace("hadamard_signs", signs);
+ }
+ const auto decoder = std::make_shared<SingleOpDecoder>("GGML_OP_GET_ROWS",
+ input_descriptions,
+ extra_inputs,
+ output_description,
+ attributes);
+ auto tensor_map = std::make_shared<ov::frontend::gguf::TensorMap>();
+ (*tensor_map)["token_embd.weight"] = table;
+ (*tensor_map)["inp_tokens"] = m.inp_tokens;
+ const ov::frontend::gguf::NodeContext context(decoder, tensor_map);
+ const auto translated = ov::frontend::gguf::op::translate_get_rows(context);
+ ASSERT_EQ(translated.size(), 1);
+ auto endpoint = translated.front().get_node_shared_ptr();
+ if (matrix_endpoint) {
+ endpoint->set_friendly_name("inverse_embedding");
+ const auto identity =
+ v0::Constant::create(ov::element::f32, {4, 4}, {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1});
+ const auto matrix = std::make_shared<v0::MatMul>(endpoint, identity, false, false);
+ matrix->set_friendly_name("embd");
+ endpoint = matrix;
+ }
+ endpoint->get_rt_info()["gguf.token_embedding"] = true;
+ const auto logits = m.model->get_results().front()->get_input_node_shared_ptr(0);
+ logits->input(0).replace_source_output(endpoint);
+ m.model->get_rt_info()["gguf_architecture"] = std::string{"qwen35"};
+ m.model->validate_nodes_and_infer_types();
+ const auto restored = reload_ir_model(m.model);
+ for (const auto& node : restored->get_ops())
+ ASSERT_EQ(node->get_rt_info().count("gguf.token_embedding"), 0);
+ AdaptToGenAI direct_adapter(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ AdaptToGenAI restored_adapter(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ ASSERT_TRUE(direct_adapter.run_on_model(m.model));
+ ASSERT_TRUE(restored_adapter.run_on_model(restored));
+ auto inputs = make_genai_inputs(3);
+ const std::map<std::string, ov::Tensor> lookup_inputs{{"input_ids", inputs.at("input_ids")}};
+ const auto direct_embedding_model = direct_adapter.get_embedding_model();
+ const auto restored_embedding_model = restored_adapter.get_embedding_model();
+ ASSERT_NE(direct_embedding_model, nullptr);
+ ASSERT_NE(restored_embedding_model, nullptr);
+ const auto direct_embeddings = run_on_cpu(direct_embedding_model, lookup_inputs);
+ const auto restored_embeddings = run_on_cpu(restored_embedding_model, lookup_inputs);
+ ASSERT_EQ(direct_embeddings.get_shape(), (ov::Shape{1, 3, 4}));
+ ASSERT_EQ(restored_embeddings.get_shape(), direct_embeddings.get_shape());
+ float latent_difference = 0.f;
+ for (size_t i = 0; i < direct_embeddings.get_size(); ++i) {
+ EXPECT_NEAR(restored_embeddings.data<const float>()[i], direct_embeddings.data<const float>()[i], 1e-4f);
+ latent_difference += std::abs(direct_embeddings.data<const float>()[i] - latent_values[i]);
+ }
+ EXPECT_GT(latent_difference, 1.f);
+ inputs.erase("input_ids");
+ ov::Tensor injected(ov::element::f32, {1, 3, 4});
+ const std::vector<float> injected_values{7.f, 11.f, 13.f, 17.f};
+ for (size_t i = 0; i < injected.get_size(); ++i)
+ injected.data<float>()[i] = injected_values[i % 4];
+ inputs.emplace("inputs_embeds", injected);
+ for (const auto& model : {m.model, restored}) {
+ EXPECT_EQ(find_parameter(model, "input_ids"), nullptr);
+ const auto actual = run_on_cpu(model, inputs);
+ ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 3, 1}));
+ for (size_t i = 0; i < actual.get_size(); ++i)
+ EXPECT_FLOAT_EQ(actual.data<const float>()[i], 48.f);
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(InverseSignsAndWeightType,
+ GGUFAdaptToGenAILegacyHadamardEmbedding,
+ testing::Combine(testing::Bool(),
+ testing::Values(ov::element::f32, ov::element::f16),
+ testing::Bool()));
+
+TEST(GGUFAdaptToGenAI, LegacyCompleteEmbeddingEndpointRejectsSeparateBranches) {
+ auto m = build_minimal_gguf_model();
+ const auto lookup = m.embd->get_input_node_shared_ptr(0);
+ const auto table = lookup->get_input_node_shared_ptr(0);
+ table->set_friendly_name("token_embd.weight");
+ const auto left = std::make_shared<v0::Convert>(m.embd, ov::element::f32);
+ const auto right = std::make_shared<v0::Convert>(m.embd, ov::element::f32);
+ left->set_friendly_name("Convert_left_embd");
+ right->set_friendly_name("Convert_right_embd");
+ const auto left_result = std::make_shared<v0::Result>(left);
+ const auto right_result = std::make_shared<v0::Result>(right);
+ m.model->add_results({left_result, right_result});
+ const auto restored = reload_ir_model(m.model);
+ AdaptToGenAI adapter(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ EXPECT_THROW(adapter.run_on_model(restored), ov::Exception);
+}
+
+TEST(GGUFAdaptToGenAI, LegacyCompleteEmbeddingEndpointIgnoresPerLayerSuffix) {
+ auto m = build_minimal_gguf_model();
+ const auto lookup = m.embd->get_input_node_shared_ptr(0);
+ const auto table = lookup->get_input_node_shared_ptr(0);
+ table->set_friendly_name("token_embd.weight");
+ const auto per_layer = std::make_shared<v0::Convert>(m.embd, ov::element::f32);
+ per_layer->set_friendly_name("Convert_native_per_layer_embd");
+ const auto result = std::make_shared<v0::Result>(per_layer);
+ m.model->add_results({result});
+ const auto restored = reload_ir_model(m.model);
+ const auto legacy = ov::frontend::gguf::resolve_legacy_embedding_boundaries(restored, true, false);
+ ASSERT_NE(legacy.token, nullptr);
+ EXPECT_EQ(legacy.token->get_friendly_name(), m.embd->get_friendly_name());
+}
+
+TEST(GGUFAdaptToGenAI, RecurrentBatchingUsesDeclaredContract) {
+ for (const bool batchable : {false, true}) {
+ auto model = build_minimal_gguf_model().model;
+ model->get_rt_info()[ov::frontend::gguf::pass::gguf_recurrent_states_key()] = std::vector<std::string>{};
+ model->get_rt_info()["gguf_architecture"] = std::string("custom-recurrent-decoder");
+ ov::frontend::gguf::ModelContract contract;
+ contract.batchable_recurrent = batchable;
+ ov::frontend::gguf::write_model_contract(model, contract);
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(model));
+ EXPECT_EQ(model->input("input_ids").get_partial_shape()[0],
+ batchable ? ov::Dimension::dynamic() : ov::Dimension{1});
+ }
+}
+
+TEST(GGUFAdaptToGenAI, ExplicitRecurrentContractOverridesGatedDeltaNetInference) {
+ for (const auto batchable : std::vector<std::optional<bool>>{std::nullopt, false, true}) {
+ auto model = build_minimal_gguf_model().model;
+ const auto data = v0::Constant::create(ov::element::f32, {1, 1, 1, 1}, {1.f});
+ const auto gate = v0::Constant::create(ov::element::f32, {1, 1, 1}, {1.f});
+ const auto gdn = std::make_shared<ov::op::internal::GatedDeltaNet>(data, data, data, data, gate, gate);
+ const auto axes = v0::Constant::create(ov::element::i64, {4}, {0, 1, 2, 3});
+ const auto sum = std::make_shared<v1::ReduceSum>(gdn->output(0), axes, false);
+ const auto result = model->get_results().front();
+ const auto combined = std::make_shared<v1::Add>(result->input_value(0), sum);
+ result->input(0).replace_source_output(combined);
+ model->get_rt_info()[ov::frontend::gguf::pass::gguf_recurrent_states_key()] = std::vector<std::string>{};
+ ov::frontend::gguf::ModelContract contract;
+ contract.batchable_recurrent = batchable;
+ ov::frontend::gguf::write_model_contract(model, contract);
+ EXPECT_EQ(ov::frontend::gguf::read_model_contract(model).batchable_recurrent, batchable);
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(model));
+ EXPECT_EQ(model->input("input_ids").get_partial_shape()[0],
+ batchable.value_or(true) ? ov::Dimension::dynamic() : ov::Dimension{1});
+ }
+}
class GGUFAdaptToGenAIEmbeddingMode : public ::testing::TestWithParam<bool> {};
diff --git a/src/frontends/gguf/tests/test_arch_accuracy.cpp b/src/frontends/gguf/tests/test_arch_accuracy.cpp
index c0d8ef478fb..a01b1f3dbd6 100644
--- a/src/frontends/gguf/tests/test_arch_accuracy.cpp
+++ b/src/frontends/gguf/tests/test_arch_accuracy.cpp
@@ -15,6 +15,8 @@
#include "builder/api/metadata_store.hpp"
#include "builder/arch/decoder_builder.hpp"
#include "builder/arch/dspark_builder.hpp"
+#include "builder/decoder_config.hpp"
+#include "builder/decoder_metadata.hpp"
#include "builder/gguf_builder_decoder.hpp"
#include "builder/gguf_graph.hpp"
#include "builder/graph_emitter.hpp"
@@ -50,6 +52,83 @@
namespace {
class GGUFArchitectureAccuracy : public ::testing::TestWithParam<const char*> {};
+TEST(GGUFAFMoE, MissingAndZeroRoutingUseSigmoidDefaults) {
+ using namespace ov::frontend::gguf;
+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/afmoe.npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ auto loaded = get_gguf_data(temporary.path);
+ auto& metadata = std::get<0>(loaded);
+ const auto& weights = std::get<1>(loaded);
+ metadata.erase("afmoe.attention.sliding_window_pattern");
+ metadata.erase("afmoe.expert_weights_norm");
+ for (const bool explicit_zero : {false, true}) {
+ SCOPED_TRACE(explicit_zero);
+ metadata.erase("afmoe.expert_gating_func");
+ if (explicit_zero) {
+ ov::Tensor zero(ov::element::u32, {});
+ *zero.data<uint32_t>() = 0;
+ metadata["afmoe.expert_gating_func"] = zero;
+ }
+ detail::MetadataStore store{metadata};
+ const auto parameters = resolve_decoder_parameters(GgufMetadata(store), RopeMode::Neox);
+ EXPECT_FLOAT_EQ(parameters.scales.embedding, std::sqrt(32.0f));
+ EXPECT_EQ(parameters.experts.routing, ExpertRouting::Sigmoid);
+ EXPECT_FALSE(parameters.experts.normalize_weights);
+ const DecoderConfig config(parameters, weights);
+ EXPECT_TRUE(config.has_qk_norm);
+ EXPECT_FALSE(config.qk_norm_after_rope);
+ EXPECT_TRUE(config.has_attn_gate);
+ EXPECT_TRUE(config.has_attn_post_norm);
+ EXPECT_TRUE(config.has_ffn_post_norm);
+ EXPECT_EQ(config.rope_skip_period, 4);
+ for (int layer = 0; layer < 4; ++layer) {
+ EXPECT_EQ(config.layer_is_swa(layer), layer < 3);
+ EXPECT_EQ(config.layer_is_moe(layer), layer > 0);
+ }
+ }
+}
+
+TEST(GGUFAFMoE, ExplicitRoutingWindowAndRopeOverrides) {
+ using namespace ov::frontend::gguf;
+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/afmoe.npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ auto loaded = get_gguf_data(temporary.path);
+ auto& metadata = std::get<0>(loaded);
+ ov::Tensor routing(ov::element::u32, {});
+ *routing.data<uint32_t>() = 1;
+ metadata["afmoe.expert_gating_func"] = routing;
+ ov::Tensor period(ov::element::u32, {});
+ *period.data<uint32_t>() = 2;
+ metadata["afmoe.attention.sliding_window_pattern"] = period;
+ ov::Tensor embedding_scale(ov::element::f32, {});
+ *embedding_scale.data<float>() = 3.0f;
+ metadata["afmoe.embedding_scale"] = embedding_scale;
+ detail::MetadataStore store{metadata};
+ DecoderOptions options;
+ options.rope_skip_period = 2;
+ auto parameters = resolve_decoder_parameters(GgufMetadata(store), RopeMode::Neox, options);
+ EXPECT_FLOAT_EQ(parameters.scales.embedding, 3.0f);
+ EXPECT_EQ(parameters.experts.routing, ExpertRouting::Softmax);
+ EXPECT_TRUE(parameters.experts.normalize_weights);
+ const DecoderConfig config(parameters, std::get<1>(loaded));
+ EXPECT_EQ(config.rope_skip_period, 2);
+ for (int layer = 0; layer < 4; ++layer)
+ EXPECT_EQ(config.layer_is_swa(layer), layer % 2 == 0);
+ parameters.attention.sliding_layers = {0, 1, 0, 1};
+ const DecoderConfig listed(parameters, std::get<1>(loaded));
+ for (int layer = 0; layer < 4; ++layer)
+ EXPECT_EQ(listed.layer_is_swa(layer), layer % 2 == 1);
+ parameters.attention.sliding_layers.clear();
+ parameters.attention.sliding_window = false;
+ parameters.attention.window_size = 0;
+ const DecoderConfig global(parameters, std::get<1>(loaded));
+ for (int layer = 0; layer < 4; ++layer)
+ EXPECT_FALSE(global.layer_is_swa(layer));
+ options.rope_skip_period = 0;
+ const auto with_rope = resolve_decoder_parameters(GgufMetadata(store), RopeMode::Neox, options);
+ EXPECT_EQ(DecoderConfig(with_rope, std::get<1>(loaded)).rope_skip_period, 0);
+}
+
TEST(GGUFDSparkAccuracy, ConfidenceAndMarkovHeadsAreIndependent) {
using namespace ov::frontend::gguf;
const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/dspark.npz");
@@ -153,7 +232,12 @@ TEST(GGUFHadamardMetadata, MissingAndMistypedFieldsNameTheInvalidKey) {
const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/bonsai2-hadamard.npz");
const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
auto loaded = get_gguf_data(temporary.path);
- const auto config = decoder_config_from_meta(std::get<0>(loaded));
+ auto& metadata = std::get<0>(loaded);
+ detail::MetadataStore store{metadata};
+ const GgufMetadata view(store);
+ const auto parameters = resolve_decoder_parameters(view, RopeMode::Normal);
+ const auto config =
+ decoder_weight_transform_metadata(view, parameters.hybrid.time_step_rank, parameters.hybrid.group_count);
GraphEmitter valid(std::get<1>(loaded), std::get<2>(loaded), "qwen35");
EXPECT_NO_THROW(valid.configure_hadamard(config));
for (const std::string key : {"prism.hadamard.version",
@@ -670,8 +754,11 @@ TEST(GGUFMultimodalBackboneAdaptation, TernaryAttentionGatesRestoreRankBeforeSig
auto& gate = weights.at("blk.0.attn_gate.weight");
gate = ov::Tensor(type, gate.get_shape());
const auto& metadata = std::get<0>(loaded);
- const auto config = decoder_config_from_meta(metadata);
- DecoderBuilder builder(config, weights, std::get<2>(loaded));
+ detail::MetadataStore store{metadata};
+ const auto parameters = resolve_decoder_parameters(GgufMetadata(store), RopeMode::Neox);
+ detail::WeightStore tensors{weights, std::get<2>(loaded)};
+ const BuildContext context{GgufMetadata(store), parameters.architecture, &tensors};
+ DecoderBuilder builder(context, parameters);
const auto graph = builder.build();
const auto node = std::find_if(graph->nodes.begin(), graph->nodes.end(), [](const auto& op) {
return op.name == "blk.0.attn_gate";
@@ -1236,7 +1323,7 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
}
past += tokens.size();
}
- if (mamba) {
+ if (mamba || std::string(GetParam()) == "afmoe") {
const auto states = request.query_state();
ASSERT_FALSE(states.empty());
for (auto state : states)
@@ -1250,7 +1337,7 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
EXPECT_EQ(std::max_element(actual, actual + vocab) - actual,
std::max_element(reference.begin(), reference.begin() + vocab) - reference.begin());
else
- EXPECT_LT(metric.value(), 1e-5) << "Fresh prefill after resetting recurrent states";
+ EXPECT_LT(metric.value(), 1e-5) << "Fresh prefill after resetting states";
}
if (real_checkpoint) {
EXPECT_GE(matching_tokens * 10, schedule.size() * 9) << "Fewer than 90% of greedy choices match";
@@ -1259,7 +1346,9 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
INSTANTIATE_TEST_SUITE_P(Architectures,
GGUFArchitectureAccuracy,
- ::testing::Values("qwen35",
+ ::testing::Values("afmoe",
+ "qwen35",
+ "qwen35-zero-scales",
"lfm2",
"lfm2-tied",
"lfm2-swa",
@@ -1281,6 +1370,7 @@ INSTANTIATE_TEST_SUITE_P(Architectures,
"qwen3",
"phi3",
"minicpm",
+ "minicpm-default",
"olmoe",
"hunyuan-dense",
"hunyuan-moe",
diff --git a/src/frontends/gguf/tests/test_arch_conversion.cpp b/src/frontends/gguf/tests/test_arch_conversion.cpp
index cb2c68546e0..605179a11b2 100644
--- a/src/frontends/gguf/tests/test_arch_conversion.cpp
+++ b/src/frontends/gguf/tests/test_arch_conversion.cpp
@@ -182,20 +182,20 @@ struct Fingerprint {
const std::map<std::string, Fingerprint>& fingerprints() {
static const std::map<std::string, Fingerprint> fp{
{"mamba2-dense.gguf.hdr", {241, 6}}, {"nemotron_h-dense.gguf.hdr", {254, 8}},
- {"bailingmoe2-moe.gguf.hdr", {506, 10}}, {"ernie4_5-moe-moe.gguf.hdr", {481, 10}},
- {"exaone4-dense.gguf.hdr", {432, 11}}, {"gemma-dense.gguf.hdr", {382, 10}},
- {"gemma2-dense.gguf.hdr", {432, 11}}, {"glm4moe-moe.gguf.hdr", {518, 10}},
- {"gpt-oss-moe.gguf.hdr", {608, 11}}, {"hunyuan-dense-dense.gguf.hdr", {431, 10}},
- {"hunyuan-moe-moe.gguf.hdr", {617, 10}}, {"llama-dense.gguf.hdr", {415, 10}},
+ {"bailingmoe2-moe.gguf.hdr", {496, 10}}, {"ernie4_5-moe-moe.gguf.hdr", {471, 10}},
+ {"exaone4-dense.gguf.hdr", {422, 11}}, {"gemma-dense.gguf.hdr", {372, 10}},
+ {"gemma2-dense.gguf.hdr", {422, 11}}, {"glm4moe-moe.gguf.hdr", {508, 10}},
+ {"gpt-oss-moe.gguf.hdr", {598, 11}}, {"hunyuan-dense-dense.gguf.hdr", {421, 10}},
+ {"hunyuan-moe-moe.gguf.hdr", {607, 10}}, {"llama-dense.gguf.hdr", {405, 10}},
{"lfm2-dense.gguf.hdr", {307, 9}}, {"lfm2moe-moe.gguf.hdr", {382, 8}},
- {"llama-moe.gguf.hdr", {542, 10}}, {"maincoder-dense.gguf.hdr", {447, 10}},
+ {"llama-moe.gguf.hdr", {532, 10}}, {"maincoder-dense.gguf.hdr", {437, 10}},
{"minicpm-dense.gguf.hdr", {413, 10}}, {"minicpm-moe.gguf.hdr", {540, 10}},
- {"minimax-m2-moe.gguf.hdr", {582, 10}}, {"mistral3-dense.gguf.hdr", {415, 10}},
- {"mistral3-moe.gguf.hdr", {542, 10}}, {"olmoe-moe.gguf.hdr", {570, 10}},
- {"phi3-dense.gguf.hdr", {368, 10}}, {"qwen2-dense.gguf.hdr", {383, 10}},
- {"qwen3-dense.gguf.hdr", {431, 10}}, {"qwen3moe-moe.gguf.hdr", {582, 10}},
- {"qwen35-dense.gguf.hdr", {412, 10}}, {"qwen35moe-moe.gguf.hdr", {584, 10}},
- {"smollm3-dense.gguf.hdr", {399, 10}}, {"jais2-dense.gguf.hdr", {344, 10}},
+ {"minimax-m2-moe.gguf.hdr", {572, 10}}, {"mistral3-dense.gguf.hdr", {405, 10}},
+ {"mistral3-moe.gguf.hdr", {532, 10}}, {"olmoe-moe.gguf.hdr", {560, 10}},
+ {"phi3-dense.gguf.hdr", {358, 10}}, {"qwen2-dense.gguf.hdr", {373, 10}},
+ {"qwen3-dense.gguf.hdr", {421, 10}}, {"qwen3moe-moe.gguf.hdr", {572, 10}},
+ {"qwen35-dense.gguf.hdr", {406, 10}}, {"qwen35moe-moe.gguf.hdr", {578, 10}},
+ {"smollm3-dense.gguf.hdr", {389, 10}}, {"jais2-dense.gguf.hdr", {334, 10}},
};
return fp;
}
diff --git a/src/frontends/gguf/tests/test_architecture_extension.cpp b/src/frontends/gguf/tests/test_architecture_extension.cpp
index e902d713b05..aaa4666a192 100644
--- a/src/frontends/gguf/tests/test_architecture_extension.cpp
+++ b/src/frontends/gguf/tests/test_architecture_extension.cpp
@@ -13,6 +13,8 @@
#include <string>
#include <vector>
+#include "builder/api/metadata_store.hpp"
+#include "builder/gguf_graph.hpp"
#include "common_test_utils/common_utils.hpp"
#include "common_test_utils/file_utils.hpp"
#include "common_test_utils/test_assertions.hpp"
@@ -64,7 +66,10 @@ private:
};
// Small nonzero fixture shared by registration, structure, and stateful numerical tests.
-std::string write_decoder_gguf(const std::string& dir, const std::string& arch = "qwen3", uint32_t layers = 2) {
+std::string write_decoder_gguf(const std::string& dir,
+ const std::string& arch = "qwen3",
+ uint32_t layers = 2,
+ bool layer_norm = false) {
const auto path = ov::util::path_join({dir, arch + ".gguf"}).string();
GgufWriter writer;
writer.kv_str("general.architecture", arch);
@@ -74,7 +79,7 @@ std::string write_decoder_gguf(const std::string& dir, const std::string& arch =
writer.kv_u32(arch + ".attention.head_count_kv", 1);
writer.kv_u32(arch + ".rope.dimension_count", 4);
writer.kv_u32(arch + ".context_length", 32);
- writer.kv_f32(arch + ".attention.layer_norm_rms_epsilon", 1e-5f);
+ writer.kv_f32(arch + (layer_norm ? ".attention.layer_norm_epsilon" : ".attention.layer_norm_rms_epsilon"), 1e-5f);
writer.kv_f32(arch + ".rope.scaling.factor", 4.f);
writer.kv_f32(arch + ".attn_logit_softcapping", 2.f);
writer.kv_u32(arch + ".attention.sliding_window", 2);
@@ -83,9 +88,13 @@ std::string write_decoder_gguf(const std::string& dir, const std::string& arch =
};
weight("token_embd.weight", {8, 16});
weight("output_norm.weight", {8}, true);
+ if (layer_norm)
+ weight("output_norm.bias", {8});
for (uint32_t layer = 0; layer < layers; ++layer) {
const auto prefix = "blk." + std::to_string(layer) + ".";
weight(prefix + "attn_norm.weight", {8}, true);
+ if (layer_norm)
+ weight(prefix + "attn_norm.bias", {8});
weight(prefix + "attn_q.weight", {8, 8});
weight(prefix + "attn_k.weight", {8, 4});
weight(prefix + "attn_v.weight", {8, 4});
@@ -93,6 +102,8 @@ std::string write_decoder_gguf(const std::string& dir, const std::string& arch =
weight(prefix + "attn_q_norm.weight", {4}, true);
weight(prefix + "attn_k_norm.weight", {4}, true);
weight(prefix + "ffn_norm.weight", {8}, true);
+ if (layer_norm)
+ weight(prefix + "ffn_norm.bias", {8});
weight(prefix + "ffn_gate.weight", {8, 12});
weight(prefix + "ffn_up.weight", {8, 12});
weight(prefix + "ffn_down.weight", {12, 8});
@@ -577,3 +588,118 @@ TEST(GGUFArchitectureExtension, ConverterRegisteredAfterLoadInfersBuilderValues)
}
}
}
+
+TEST(GGUFArchitectureExtension, TypedUnknownLayerNormFactoryControlsScalesAndLayerRope) {
+ using namespace ov::frontend::gguf;
+ ScratchDir scratch;
+ const auto path = write_decoder_gguf(scratch.path(), "custom-normalization", 2, true);
+ ASSERT_FALSE(path.empty());
+ const auto definition = make_decoder_architecture("custom-normalization", [](const BuildContext& context) {
+ DecoderParameters defaults;
+ defaults.normalization.kind = NormalizationKind::Layer;
+ auto parameters = read_decoder_parameters(context.metadata, defaults);
+ parameters.attention.rope_mode = RopeMode::Neox;
+ parameters.scales.embedding = 2.5f;
+ parameters.scales.residual = 0.375f;
+ parameters.scales.logits = 0.75f;
+ parameters.layers.resize(2);
+ parameters.layers[0].sliding_window = false;
+ parameters.layers[1].sliding_window = true;
+ auto local = parameters.attention.rope;
+ local.freq_base = 32000.f;
+ local.freq_scale = 0.5f;
+ parameters.layers[1].rope = local;
+ return parameters;
+ });
+ auto loaded = get_gguf_data(path);
+ auto& [metadata, weights, qtypes, mappings] = loaded;
+ detail::MetadataStore store{metadata};
+ detail::WeightStore tensors{weights, qtypes};
+ const BuildContext context{GgufMetadata(store), "custom-normalization", &tensors};
+ const auto graph = definition.factory(context)->build();
+ EXPECT_TRUE(graph->use_per_op_rope);
+ const auto op = [&](const std::string& name) -> const GgufOp& {
+ const auto found = std::find_if(graph->nodes.begin(), graph->nodes.end(), [&](const GgufOp& node) {
+ return node.name == name;
+ });
+ OPENVINO_ASSERT(found != graph->nodes.end(), "missing expected operation ", name);
+ return *found;
+ };
+ EXPECT_EQ(op("blk.0.attn_norm.norm").op_type, "GGML_OP_NORM");
+ EXPECT_FLOAT_EQ(op("embd_scaled").attributes.at("scale").as<float>(), 2.5f);
+ EXPECT_FLOAT_EQ(op("blk.0.attn_out_scaled").attributes.at("scale").as<float>(), 0.375f);
+ EXPECT_FLOAT_EQ(op("result_output_scaled").attributes.at("scale").as<float>(), 0.75f);
+ const auto extension = std::make_shared<ArchitectureExtension>(definition);
+ const auto converted = convert_with(path, {extension});
+ ASSERT_TRUE(converted);
+ EXPECT_EQ(converted->output(0).get_partial_shape().rank().get_length(), 4);
+}
+
+TEST(GGUFArchitectureExtension, TypedGatedDeltaNetFactoryScalesBothResidualBranches) {
+ using namespace ov::frontend::gguf;
+ ScratchDir scratch;
+ const auto path = write_decoder_gguf(scratch.path(), "custom-recurrent");
+ ASSERT_FALSE(path.empty());
+ auto loaded = get_gguf_data(path);
+ auto& [metadata, weights, qtypes, mappings] = loaded;
+ for (int layer = 0; layer < 2; ++layer) {
+ const auto prefix = "blk." + std::to_string(layer) + ".";
+ const std::map<std::string, ov::Shape> shapes{{"attn_qkv.weight", {12, 8}},
+ {"attn_gate.weight", {4, 8}},
+ {"ssm_alpha.weight", {1, 8}},
+ {"ssm_beta.weight", {1, 8}},
+ {"ssm_conv1d.weight", {12, 3}},
+ {"ssm_a", {1}},
+ {"ssm_dt.bias", {1}},
+ {"ssm_norm.weight", {4}},
+ {"ssm_out.weight", {8, 4}}};
+ for (const auto& [name, shape] : shapes) {
+ ov::Tensor weight(ov::element::f32, shape);
+ std::fill_n(weight.data<float>(), weight.get_size(), 0.1f);
+ weights[prefix + name] = weight;
+ }
+ }
+ detail::MetadataStore store{metadata};
+ detail::WeightStore tensors{weights, qtypes};
+ const BuildContext context{GgufMetadata(store), "custom-recurrent", &tensors};
+ for (float scale : {1.0f, 0.375f}) {
+ const auto definition = make_decoder_architecture("custom-recurrent", [scale](const BuildContext& context) {
+ auto parameters = read_decoder_parameters(context.metadata);
+ parameters.hybrid.kind = RecurrentKind::GatedDeltaNet;
+ parameters.hybrid.conv_kernel = 3;
+ parameters.hybrid.state_size = 4;
+ parameters.hybrid.group_count = 1;
+ parameters.hybrid.time_step_rank = 1;
+ parameters.hybrid.inner_size = 4;
+ parameters.hybrid.recurrent_layers = {1, 1};
+ parameters.scales.residual = scale;
+ return parameters;
+ });
+ const auto graph = definition.factory(context)->build();
+ const auto op = [&](const std::string& name) -> const GgufOp& {
+ const auto found = std::find_if(graph->nodes.begin(), graph->nodes.end(), [&](const GgufOp& node) {
+ return node.name == name;
+ });
+ OPENVINO_ASSERT(found != graph->nodes.end(), "missing expected operation ", name);
+ return *found;
+ };
+ for (int layer = 0; layer < 2; ++layer) {
+ const auto prefix = "blk." + std::to_string(layer) + ".";
+ const auto expected_attention = scale == 1.0f ? prefix + "linear_attn_out" : prefix + "attn_out_scaled";
+ const auto expected_ffn = scale == 1.0f ? prefix + "ffn_out" : prefix + "ffn_out_scaled";
+ if (scale != 1.0f) {
+ for (const auto& name : {"attn_out_scaled", "ffn_out_scaled"}) {
+ EXPECT_EQ(op(prefix + name).op_type, "GGML_OP_SCALE");
+ EXPECT_FLOAT_EQ(op(prefix + name).attributes.at("scale").as<float>(), scale);
+ }
+ }
+ if (layer == 0) {
+ EXPECT_EQ(op(prefix + "ffn_inp").input_names.front(), expected_attention);
+ } else {
+ EXPECT_EQ(op(prefix + "attn_out_g").input_names.front(), expected_attention);
+ EXPECT_EQ(op(prefix + "ffn_inp").input_names.front(), prefix + "attn_out_g");
+ }
+ EXPECT_EQ(op(prefix + "l_out").input_names, (std::vector<std::string>{expected_ffn, prefix + "ffn_inp"}));
+ }
+ }
+}
diff --git a/src/frontends/gguf/tests/test_architecture_library.cpp b/src/frontends/gguf/tests/test_architecture_library.cpp
index daba0e552c6..feb00facd8e 100644
--- a/src/frontends/gguf/tests/test_architecture_library.cpp
+++ b/src/frontends/gguf/tests/test_architecture_library.cpp
@@ -5,9 +5,11 @@
#include <filesystem>
#include <numeric>
+#include "../src/model_adapter_attribute.hpp"
#include "common_test_utils/file_utils.hpp"
#include "gguf_writer.hpp"
#include "gtest/gtest.h"
+#include "openvino/frontend/gguf/adapt_mmproj_to_genai.hpp"
#include "openvino/frontend/gguf/frontend.hpp"
#include "projector.hpp"
@@ -54,3 +56,53 @@ TEST(GGUFArchitectureLibrary, ExternalModuleMatchesDirectRegistrationAcrossToken
}
}
}
+
+TEST(GGUFArchitectureLibrary, ProjectorAdapterRetainsItsLibraryUntilExecutionCompletes) {
+ const auto path =
+ std::filesystem::temp_directory_path() / (ov::test::utils::generateTestFilePrefix() + "_adapter.gguf");
+ struct RemoveFile {
+ std::filesystem::path path;
+ ~RemoveFile() {
+ std::error_code error;
+ std::filesystem::remove(path, error);
+ }
+ } cleanup{path};
+ ov_gguf_test::GgufWriter writer;
+ writer.kv_str("general.architecture", "clip");
+ writer.kv_bool("clip.has_vision_encoder", true);
+ writer.kv_str("clip.vision.projector_type", "example-adapter");
+ writer.tensor("projection.weight", {2, 3}, {1, 2, 3, 4, 5, 6});
+ ASSERT_TRUE(writer.write(path.string()));
+ std::shared_ptr<ov::frontend::gguf::ModelAdapter> holder;
+ std::shared_ptr<ov::Model> model;
+ {
+ ov::frontend::gguf::FrontEnd frontend;
+ const auto library = std::filesystem::path(ov::test::utils::getExecutableDirectory()) / ARCH_EXTENSION_LIBRARY;
+ static_cast<ov::frontend::FrontEnd&>(frontend).add_extension(library.string());
+ model = frontend.convert(frontend.load(path.string()));
+ }
+ holder = ov::frontend::gguf::get_model_adapter(model->get_results().front());
+ ASSERT_NE(holder, nullptr);
+ ASSERT_FALSE(holder->lifetime.empty());
+ std::weak_ptr<ov::Extension> owner = holder->lifetime.front();
+ EXPECT_FALSE(owner.expired());
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ ASSERT_TRUE(adapter.run_on_model(model));
+ EXPECT_EQ(adapter.get_vision_models().at("custom_vision"), model);
+ EXPECT_EQ(ov::frontend::gguf::get_model_adapter(model->get_results().front()), nullptr);
+ for (const size_t tokens : {1u, 3u, 7u}) {
+ ov::Tensor input(ov::element::f32, {1, 1, tokens, 2});
+ std::iota(input.data<float>(), input.data<float>() + input.get_size(), 1.f);
+ ov::TensorVector outputs{ov::Tensor(ov::element::f32, {1, tokens, 3})};
+ ASSERT_TRUE(model->evaluate(outputs, {input}));
+ for (size_t t = 0; t < tokens; ++t)
+ for (size_t c = 0; c < 3; ++c)
+ EXPECT_FLOAT_EQ(outputs[0].data<float>()[t * 3 + c],
+ float((2 * t + 1) * (2 * c + 1) + (2 * t + 2) * (2 * c + 2) + 7));
+ }
+ adapter = Adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ model.reset();
+ holder.reset();
+ EXPECT_TRUE(owner.expired());
+}
diff --git a/src/frontends/gguf/tests/test_builder_api.cpp b/src/frontends/gguf/tests/test_builder_api.cpp
index 3f43f8a3a8a..730f985bfbf 100644
--- a/src/frontends/gguf/tests/test_builder_api.cpp
+++ b/src/frontends/gguf/tests/test_builder_api.cpp
@@ -45,6 +45,9 @@ struct Environment {
*t.data<float>() = value;
metadata[key] = t;
}
+ DecoderParameters parameters(RopeMode rope = RopeMode::Normal, const DecoderOptions& options = {}) const {
+ return resolve_decoder_parameters(context.metadata, rope, options);
+ }
void architecture(const std::string& name) {
std::unordered_map<std::string, GGUFMetaData> renamed;
for (const auto& entry : metadata)
@@ -285,11 +288,10 @@ TEST(GGUFBuilderAPI, DecoderOptionsAreResolvedBeforeRopePlans) {
TEST(GGUFBuilderAPI, RopeScalingDefaultsAndPositiveFactors) {
Environment env;
env.decoder();
- EXPECT_FLOAT_EQ(std::get<float>(decoder_config_from_meta(env.metadata).at("rope_freq_scale")), 1.0f);
+ EXPECT_FLOAT_EQ(env.parameters().attention.rope.freq_scale, 1.0f);
for (const float factor : {0.0f, 1.0f, 4.0f}) {
env.real("test.rope.scaling.factor", factor);
- EXPECT_FLOAT_EQ(std::get<float>(decoder_config_from_meta(env.metadata).at("rope_freq_scale")),
- factor == 0.0f ? 1.0f : 1.0f / factor);
+ EXPECT_FLOAT_EQ(env.parameters().attention.rope.freq_scale, factor == 0.0f ? 1.0f : 1.0f / factor);
}
}
@@ -302,7 +304,7 @@ TEST(GGUFBuilderAPI, RejectsInvalidRopeScalingFactors) {
Environment env;
env.decoder();
env.real("test.rope.scaling.factor", factor);
- EXPECT_THROW(decoder_config_from_meta(env.metadata), ov::Exception);
+ EXPECT_THROW(env.parameters(), ov::Exception);
}
}
@@ -494,7 +496,7 @@ TEST(GGUFBuilderAPI, Gemma2DefaultsIncludeSlidingWindowAnd27BAttentionScale) {
env.integer("test.attention.head_count", 32);
env.integer("test.attention.key_length", 128);
env.architecture("gemma2");
- DecoderConfig config(decoder_config_from_meta(env.metadata), env.weights);
+ DecoderConfig config(env.parameters(), env.weights);
EXPECT_EQ(config.swa_window_size, 4096);
EXPECT_TRUE(config.layer_is_swa(0));
EXPECT_FALSE(config.layer_is_swa(1));
@@ -512,7 +514,63 @@ TEST(GGUFBuilderAPI, Gemma2RejectsZeroAttentionHeadsWithOrWithoutKeyLength) {
env.integer("test.attention.key_length", 128);
}
env.architecture("gemma2");
- EXPECT_THROW(decoder_config_from_meta(env.metadata), ov::Exception);
+ EXPECT_THROW(env.parameters(), ov::Exception);
+ }
+}
+
+TEST(GGUFBuilderAPI, SlidingPolicyIsResolvedBeforeInferringNormalizationWidth) {
+ for (const bool sinks : {false, true}) {
+ for (const bool full_width : {false, true}) {
+ SCOPED_TRACE(sinks);
+ SCOPED_TRACE(full_width);
+ Environment env;
+ env.decoder();
+ auto parameters = read_decoder_parameters(env.context.metadata);
+ parameters.dimensions.head_size = 128;
+ parameters.attention.sliding_head_size = 64;
+ parameters.attention.sliding_period = 2;
+ parameters.attention.window_size = sinks ? 0 : 16;
+ if (sinks) {
+ env.weights["blk.0.attn_sinks.weight"] = ov::Tensor(ov::element::f32, {4});
+ }
+ env.weights["blk.0.attn_q_norm.weight"] = ov::Tensor(ov::element::f32, {full_width ? 256u : 64u});
+ DecoderConfig config(parameters, env.weights);
+ EXPECT_TRUE(config.layer_is_swa(0));
+ EXPECT_EQ(config.layer_head_size(0), 64);
+ EXPECT_EQ(config.layer_head_size(1), 128);
+ EXPECT_TRUE(config.has_qk_norm);
+ EXPECT_EQ(config.qk_norm_full, full_width);
+ parameters.normalization.qk_full_width = !full_width;
+ EXPECT_EQ(DecoderConfig(parameters, env.weights).qk_norm_full, !full_width);
+ }
+ }
+}
+
+TEST(GGUFBuilderAPI, OneLayerBooleanSlidingPatternRemainsALayerFlag) {
+ for (const bool sliding : {false, true}) {
+ SCOPED_TRACE(sliding);
+ Environment env;
+ env.decoder();
+ env.integer("test.block_count", 1);
+ env.integer("test.attention.key_length", 128);
+ env.integer("test.attention.key_length_swa", 64);
+ env.integer("test.rope.dimension_count", 64);
+ env.real("test.rope.freq_base", 32000.f);
+ env.real("test.rope.freq_base_swa", 10000.f);
+ ov::Tensor pattern(ov::element::boolean, {1});
+ *pattern.data<char>() = sliding;
+ env.metadata["test.attention.sliding_window_pattern"] = pattern;
+ const auto parameters = read_decoder_parameters(env.context.metadata);
+ EXPECT_EQ(parameters.attention.sliding_layers, (std::vector<int32_t>{sliding ? 1 : 0}));
+ EXPECT_EQ(parameters.attention.sliding_period, 0);
+ DecoderConfig config(parameters, env.weights);
+ EXPECT_EQ(config.layer_is_swa(0), sliding);
+ EXPECT_EQ(config.layer_head_size(0), sliding ? 64 : 128);
+ EXPECT_FLOAT_EQ(config.layer_rope_config(0).freq_base, sliding ? 10000.f : 32000.f);
+ env.integer("test.attention.sliding_window_pattern", 2);
+ const auto periodic = read_decoder_parameters(env.context.metadata);
+ EXPECT_TRUE(periodic.attention.sliding_layers.empty());
+ EXPECT_EQ(periodic.attention.sliding_period, 2);
}
}
@@ -525,7 +583,7 @@ TEST(GGUFBuilderAPI, SlidingWindowDefaultsMatchExaoneMoeAndPlamo3) {
env.integer("test.attention.sliding_window", 128);
env.real("test.rope.freq_base", 1000000.f);
env.architecture(family);
- DecoderConfig config(decoder_config_from_meta(env.metadata), env.weights);
+ DecoderConfig config(env.parameters(), env.weights);
const bool exaone = std::string(family) == "exaone-moe";
EXPECT_EQ(config.swa_layer_pattern, exaone ? 4 : 8);
EXPECT_TRUE(config.layer_is_swa(0));
@@ -539,11 +597,11 @@ TEST(GGUFBuilderAPI, Glm4MoeDefaultsToSigmoidRouting) {
Environment env;
env.decoder();
env.architecture("glm4moe");
- EXPECT_TRUE(DecoderConfig(decoder_config_from_meta(env.metadata), env.weights).moe_sigmoid_gating);
+ EXPECT_TRUE(DecoderConfig(env.parameters(), env.weights).moe_sigmoid_gating);
env.integer("glm4moe.expert_gating_func", 0);
- EXPECT_TRUE(DecoderConfig(decoder_config_from_meta(env.metadata), env.weights).moe_sigmoid_gating);
+ EXPECT_TRUE(DecoderConfig(env.parameters(), env.weights).moe_sigmoid_gating);
env.integer("glm4moe.expert_gating_func", 1);
- EXPECT_FALSE(DecoderConfig(decoder_config_from_meta(env.metadata), env.weights).moe_sigmoid_gating);
+ EXPECT_FALSE(DecoderConfig(env.parameters(), env.weights).moe_sigmoid_gating);
}
TEST(GGUFBuilderAPI, ErnieInterleavesDenseAndExpertLayers) {
@@ -570,7 +628,7 @@ TEST(GGUFBuilderAPI, ErnieInterleavesDenseAndExpertLayers) {
for (uint32_t dense_lead : {0u, 1u}) {
SCOPED_TRACE(dense_lead);
env.integer("ernie4_5-moe.leading_dense_block_count", dense_lead);
- DecoderConfig config(decoder_config_from_meta(env.metadata), env.weights);
+ DecoderConfig config(env.parameters(), env.weights);
EXPECT_FALSE(config.layer_is_moe(0));
EXPECT_TRUE(config.layer_is_moe(1));
EXPECT_FALSE(config.layer_is_moe(2));
@@ -593,7 +651,7 @@ TEST(GGUFBuilderAPI, Exaone64LayerDefaultsIncludeLocalRopeAndSlidingWindow) {
env.decoder();
env.integer("test.block_count", 64);
env.architecture("exaone4");
- DecoderConfig config(decoder_config_from_meta(env.metadata), env.weights);
+ DecoderConfig config(env.parameters(), env.weights);
EXPECT_TRUE(config.post_norm_only);
EXPECT_TRUE(config.rope_on_swa_only);
EXPECT_EQ(config.swa_window_size, 4096);
@@ -611,14 +669,13 @@ TEST(GGUFBuilderAPI, ArchitectureOptionsOverrideAmbiguousTensorSemantics) {
options.post_norm_only = true;
options.normalize_expert_weights = true;
options.rope_skip_period = 4;
- DecoderConfig config(decoder_config_from_meta(env.metadata), env.weights, RopeMode::Neox, options);
+ DecoderConfig config(env.parameters(RopeMode::Neox, options), env.weights);
EXPECT_TRUE(config.qk_norm_after_rope);
EXPECT_TRUE(config.post_norm_only);
EXPECT_TRUE(config.expert_weights_norm);
EXPECT_EQ(config.rope_skip_period, 4);
options.rope_skip_period = -1;
- EXPECT_THROW(DecoderConfig(decoder_config_from_meta(env.metadata), env.weights, RopeMode::Neox, options),
- ov::Exception);
+ EXPECT_THROW(DecoderConfig(env.parameters(RopeMode::Neox, options), env.weights), ov::Exception);
}
TEST(GGUFBuilderAPI, DevstralReadsYarnAndAttentionTemperatureMetadata) {
@@ -632,13 +689,13 @@ TEST(GGUFBuilderAPI, DevstralReadsYarnAndAttentionTemperatureMetadata) {
env.integer("test.rope.scaling.original_context_length", 8192);
env.real("test.attention.temperature_scale", 0.1f);
env.architecture("mistral3");
- DecoderConfig config(decoder_config_from_meta(env.metadata), env.weights);
+ DecoderConfig config(env.parameters(), env.weights);
EXPECT_FLOAT_EQ(config.rope_config.beta_fast, 4.0f);
EXPECT_FLOAT_EQ(config.rope_config.beta_slow, 1.0f);
EXPECT_FLOAT_EQ(config.rope_config.attn_factor, 1.0f / (1.0f + 0.1f * std::log(48.0f)));
EXPECT_FLOAT_EQ(config.attention_temperature_scale, 0.1f);
env.integer("mistral3.rope.scaling.original_context_length", 0);
- EXPECT_THROW(DecoderConfig(decoder_config_from_meta(env.metadata), env.weights), ov::Exception);
+ EXPECT_THROW(DecoderConfig(env.parameters(), env.weights), ov::Exception);
}
TEST(GGUFBuilderAPI, BroadcastAndConcatShapesComeFromOpenVINO) {
@@ -884,3 +941,259 @@ TEST(GGUFBuilderAPI, CastAndIm2colRequireExplicitDestinationType) {
EXPECT_EQ(output.type(), ov::element::f16);
}
}
+
+TEST(GGUFBuilderAPI, MiniCpmLogitScaleUsesDivisorWithAndWithoutMetadata) {
+ Environment env;
+ env.decoder();
+ env.integer("test.embedding_length", 2304);
+ env.architecture("minicpm");
+ EXPECT_FLOAT_EQ(env.parameters().scales.logits, 1.0f / 9.0f);
+ env.real("minicpm.logit_scale", 9.0f);
+ EXPECT_FLOAT_EQ(env.parameters().scales.logits, 1.0f / 9.0f);
+ env.real("minicpm.logit_scale", 4.0f);
+ EXPECT_FLOAT_EQ(env.parameters().scales.logits, 0.25f);
+ DecoderOptions options;
+ options.logit_scale = 0.75f;
+ EXPECT_FLOAT_EQ(env.parameters(RopeMode::Normal, options).scales.logits, 0.75f);
+}
+
+TEST(GGUFBuilderAPI, ExpertNormalizationMetadataOverridesBuilderDefaults) {
+ for (const bool normalize_by_default : {false, true}) {
+ SCOPED_TRACE(normalize_by_default);
+ Environment env;
+ env.decoder();
+ DecoderParameters defaults;
+ defaults.experts.normalize_weights = normalize_by_default;
+ EXPECT_EQ(read_decoder_parameters(env.context.metadata, defaults).experts.normalize_weights,
+ normalize_by_default);
+ for (const bool normalize : {false, true}) {
+ SCOPED_TRACE(normalize);
+ ov::Tensor normalization(ov::element::boolean, {});
+ *normalization.data<char>() = normalize;
+ env.metadata["test.expert_weights_norm"] = normalization;
+ EXPECT_EQ(read_decoder_parameters(env.context.metadata, defaults).experts.normalize_weights, normalize);
+ }
+ }
+}
+
+TEST(GGUFBuilderAPI, BuiltinExpertNormalizationPreservesLlamaPolicyAndOptions) {
+ for (const auto* architecture :
+ {"hunyuan-moe", "minimax-m2", "qwen3moe", "qwen35moe", "ernie4_5-moe", "mellum", "gemma4"}) {
+ SCOPED_TRACE(architecture);
+ Environment env;
+ env.decoder();
+ env.architecture(architecture);
+ EXPECT_TRUE(env.parameters().experts.normalize_weights);
+ ov::Tensor normalization(ov::element::boolean, {});
+ *normalization.data<char>() = false;
+ env.metadata[std::string(architecture) + ".expert_weights_norm"] = normalization;
+ EXPECT_TRUE(env.parameters().experts.normalize_weights);
+ DecoderOptions options;
+ options.normalize_expert_weights = false;
+ EXPECT_FALSE(env.parameters(RopeMode::Normal, options).experts.normalize_weights);
+ }
+}
+
+TEST(GGUFBuilderAPI, ZeroMetadataScalesDisableMultiplication) {
+ Environment env;
+ env.decoder();
+ DecoderParameters defaults;
+ defaults.scales.embedding = 12.0f;
+ defaults.scales.residual = 1.4f;
+ auto parameters = read_decoder_parameters(env.context.metadata, defaults);
+ EXPECT_FLOAT_EQ(parameters.scales.embedding, 12.0f);
+ EXPECT_FLOAT_EQ(parameters.scales.residual, 1.4f);
+ defaults.scales.embedding = 0.0f;
+ defaults.scales.residual = 0.0f;
+ parameters = read_decoder_parameters(env.context.metadata, defaults);
+ EXPECT_FLOAT_EQ(parameters.scales.embedding, 0.0f);
+ EXPECT_FLOAT_EQ(parameters.scales.residual, 0.0f);
+ for (float scale : {0.0f, 0.5f, 2.0f}) {
+ env.real("test.embedding_scale", scale);
+ env.real("test.residual_scale", scale);
+ parameters = read_decoder_parameters(env.context.metadata, defaults);
+ EXPECT_FLOAT_EQ(parameters.scales.embedding, scale == 0.0f ? 1.0f : scale);
+ EXPECT_FLOAT_EQ(parameters.scales.residual, scale == 0.0f ? 1.0f : scale);
+ }
+}
+
+TEST(GGUFBuilderAPI, TypedCustomLayerNormScalesAndLayerSettingsAreResolvedTogether) {
+ Environment env;
+ env.decoder();
+ env.metadata.erase("test.attention.layer_norm_rms_epsilon");
+ env.real("test.attention.layer_norm_epsilon", 3e-4f);
+ env.real("test.rope.scaling.factor", 4.0f);
+ env.architecture("custom-layernorm");
+ DecoderParameters defaults;
+ defaults.normalization.kind = NormalizationKind::Layer;
+ auto parameters = read_decoder_parameters(env.context.metadata, defaults);
+ parameters.scales.embedding = 2.5f;
+ parameters.scales.residual = 0.375f;
+ parameters.scales.logits = 0.75f;
+ parameters.scales.attention = 0.25f;
+ parameters.attention.window_size = 17;
+ parameters.layers.resize(2);
+ parameters.layers[0].sliding_window = false;
+ parameters.layers[1].sliding_window = true;
+ parameters.layers[1].query_heads = 8;
+ parameters.layers[1].kv_heads = 2;
+ parameters.layers[1].head_size = 4;
+ parameters.layers[1].attention_scale = 0.625f;
+ auto local_rope = parameters.attention.rope;
+ local_rope.n_dims = 4;
+ local_rope.freq_base = 32000.f;
+ local_rope.freq_scale = 0.5f;
+ parameters.layers[1].rope = local_rope;
+ parameters.model_contract.batchable_recurrent = true;
+ parameters.model_contract.image_attention = ModelContract::ImageAttentionMode::SLIDING_ONLY;
+ DecoderConfig resolved(parameters, env.weights);
+ EXPECT_TRUE(resolved.layer_norm);
+ EXPECT_FLOAT_EQ(resolved.rms_eps, 3e-4f);
+ EXPECT_FLOAT_EQ(resolved.embedding_scale, 2.5f);
+ EXPECT_FLOAT_EQ(resolved.residual_scale, 0.375f);
+ EXPECT_FLOAT_EQ(resolved.logit_scale, 0.75f);
+ EXPECT_FLOAT_EQ(resolved.layer_kq_scale(0), 0.25f);
+ EXPECT_FLOAT_EQ(resolved.layer_kq_scale(1), 0.625f);
+ GgufGraphContext graph(env.context);
+ const auto dimensions = graph.configure_decoder(parameters);
+ EXPECT_EQ(dimensions.layers, 2);
+ EXPECT_FLOAT_EQ(dimensions.norm_epsilon, resolved.rms_eps);
+ const auto global = graph.decoder_layer_parameters(0);
+ const auto local = graph.decoder_layer_parameters(1);
+ EXPECT_FALSE(global.sliding_window);
+ EXPECT_TRUE(local.sliding_window);
+ EXPECT_EQ(local.query_heads, 8);
+ EXPECT_EQ(local.kv_heads, 2);
+ EXPECT_EQ(local.head_size, 4);
+ EXPECT_FLOAT_EQ(local.attention_scale, resolved.layer_kq_scale(1));
+ EXPECT_FLOAT_EQ(global.rope.freq_scale, 0.25f);
+ EXPECT_FLOAT_EQ(local.rope.freq_base, 32000.f);
+ EXPECT_FLOAT_EQ(local.rope.freq_scale, 0.5f);
+ auto input = graph.add_input("x", ov::element::f32, {1, 1, 1, 32});
+ graph.set_output(input);
+ const auto built = graph.finish();
+ EXPECT_TRUE(built->use_per_op_rope);
+ EXPECT_EQ(built->swa_window_size, 17);
+ EXPECT_TRUE(built->model_contract.batchable_recurrent);
+ EXPECT_EQ(built->model_contract.image_attention, ModelContract::ImageAttentionMode::SLIDING_ONLY);
+}
+
+TEST(GGUFBuilderAPI, TypedSettingsRejectPartialLayersAndIncompatiblePresentMetadata) {
+ Environment env;
+ env.decoder();
+ auto parameters = read_decoder_parameters(env.context.metadata);
+ parameters.layers.resize(1);
+ EXPECT_THROW(DecoderConfig(parameters, env.weights), ov::Exception);
+ parameters.layers.resize(2);
+ parameters.layers[1].head_size = 0;
+ EXPECT_THROW(DecoderConfig(parameters, env.weights), ov::Exception);
+ env.metadata["test.embedding_scale"] = std::string("invalid");
+ EXPECT_THROW(read_decoder_parameters(env.context.metadata), ov::Exception);
+}
+
+TEST(GGUFBuilderAPI, ConvenienceOptionsSelectUnknownLayerNormBeforeMetadataReading) {
+ Environment env;
+ env.decoder();
+ env.metadata.erase("test.attention.layer_norm_rms_epsilon");
+ env.real("test.attention.layer_norm_epsilon", 2e-4f);
+ DecoderOptions options;
+ options.normalization = NormalizationKind::Layer;
+ options.embedding_scale = 3.0f;
+ GgufGraphContext graph(env.context);
+ EXPECT_FLOAT_EQ(graph.configure_decoder(RopeMode::Normal, options).norm_epsilon, 2e-4f);
+}
+
+TEST(GGUFBuilderAPI, LayerRopeOriginalContextUsesItsOwnTable) {
+ Environment env;
+ env.decoder();
+ auto parameters = read_decoder_parameters(env.context.metadata);
+ EXPECT_FALSE(DecoderConfig(parameters, env.weights).use_per_op_rope);
+ parameters.layers.resize(2);
+ auto rope = parameters.attention.rope;
+ rope.n_ctx_orig += 128;
+ parameters.layers[1].rope = rope;
+ DecoderConfig config(parameters, env.weights);
+ EXPECT_TRUE(config.use_per_op_rope);
+ EXPECT_EQ(config.layer_rope_config(1).n_ctx_orig, rope.n_ctx_orig);
+}
+
+TEST(GGUFBuilderAPI, UnsignedMetadataOverflowCannotWrapToSignedValues) {
+ Environment env;
+ env.decoder();
+ ov::Tensor scalar(ov::element::u64, {});
+ scalar.data<uint64_t>()[0] = uint64_t{1} << 63;
+ env.metadata["test.embedding_length"] = scalar;
+ EXPECT_FALSE(env.context.metadata.get_int("test.embedding_length"));
+ EXPECT_THROW(read_decoder_parameters(env.context.metadata), ov::Exception);
+ ov::Tensor values(ov::element::u64, {2});
+ values.data<uint64_t>()[0] = 1;
+ values.data<uint64_t>()[1] = (uint64_t{1} << 63) + 1;
+ env.metadata["test.attention.head_count_kv"] = values;
+ EXPECT_TRUE(env.context.metadata.get_int_array("test.attention.head_count_kv").empty());
+}
+
+TEST(GGUFBuilderAPI, UnsetPoolingSentinelIsPreservedWithoutRelaxingDimensionChecks) {
+ Environment env;
+ env.decoder();
+ ov::Tensor sentinel(ov::element::u32, {});
+ sentinel.data<uint32_t>()[0] = std::numeric_limits<uint32_t>::max();
+ env.metadata["test.pooling_type"] = sentinel;
+ EXPECT_EQ(read_decoder_parameters(env.context.metadata).pooling_type, -1);
+ env.metadata["test.embedding_length"] = sentinel;
+ EXPECT_THROW(read_decoder_parameters(env.context.metadata), ov::Exception);
+}
+
+TEST(GGUFBuilderAPI, LayerRopeCannotChangeTheSharedPositionLayout) {
+ Environment env;
+ env.decoder();
+ auto parameters = read_decoder_parameters(env.context.metadata);
+ parameters.layers.resize(2);
+ auto rope = parameters.attention.rope;
+ rope.is_imrope = true;
+ parameters.layers[1].rope = rope;
+ EXPECT_THROW(DecoderConfig(parameters, env.weights), ov::Exception);
+}
+
+TEST(GGUFBuilderAPI, ScalarRecurrentMetadataAppliesToEveryLayer) {
+ Environment env;
+ env.decoder();
+ for (const int value : {0, 1}) {
+ env.integer("test.attention.recurrent_layers", value);
+ auto parameters = read_decoder_parameters(env.context.metadata);
+ EXPECT_EQ(parameters.hybrid.recurrent_layers, (std::vector<int32_t>{value, value}));
+ EXPECT_NO_THROW(DecoderConfig(parameters, env.weights));
+ }
+}
+
+TEST(GGUFBuilderAPI, QueryHeadArraysDescribeHybridAndVariableWidthLayers) {
+ Environment env;
+ env.decoder();
+ ov::Tensor heads(ov::element::u32, {2});
+ heads.data<uint32_t>()[0] = 2;
+ heads.data<uint32_t>()[1] = 1;
+ env.metadata["test.attention.head_count"] = heads;
+ auto parameters = read_decoder_parameters(env.context.metadata);
+ EXPECT_EQ(parameters.dimensions.query_heads, 2);
+ EXPECT_EQ(DecoderConfig(parameters, env.weights).layer_n_head(1), 1);
+ heads.data<uint32_t>()[1] = 0;
+ EXPECT_THROW(read_decoder_parameters(env.context.metadata), ov::Exception);
+ env.integer("test.attention.recurrent_layers", 1);
+ parameters = read_decoder_parameters(env.context.metadata);
+ EXPECT_NO_THROW(DecoderConfig(parameters, env.weights));
+}
+
+TEST(GGUFBuilderAPI, ZeroQueryAndKvHeadsDescribeLayersWithoutAttention) {
+ Environment env;
+ env.decoder();
+ ov::Tensor query_heads(ov::element::u32, {2});
+ query_heads.data<uint32_t>()[0] = 2;
+ query_heads.data<uint32_t>()[1] = 0;
+ ov::Tensor kv_heads(ov::element::u32, {2});
+ kv_heads.data<uint32_t>()[0] = 1;
+ kv_heads.data<uint32_t>()[1] = 0;
+ env.metadata["test.attention.head_count"] = query_heads;
+ env.metadata["test.attention.head_count_kv"] = kv_heads;
+ EXPECT_NO_THROW(DecoderConfig(read_decoder_parameters(env.context.metadata), env.weights));
+ kv_heads.data<uint32_t>()[1] = 1;
+ EXPECT_THROW(read_decoder_parameters(env.context.metadata), ov::Exception);
+}
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 03d5f9a97af..49ae735cf0d 100644
--- a/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
+++ b/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
@@ -108,3 +108,10 @@ and random seed 20261014. They cover four hybrid layers, four query/two KV heads
three/four-tap convolution caches, a two-token attention window, dense leading layers,
selection bias and normalized softmax/sigmoid expert weights. The sigmoid case includes
expert-scale metadata that llama.cpp's LFM2 MoE loader ignores.
+
+`afmoe.npz` was extracted from OpenVINO donor `c4a023aeac0302c283295ba241ddee5af5ca4a0b`.
+It covers four layers (one dense, three routed/shared MoE), four query/two KV heads,
+pre/post RMS norms, QK norm, sigmoid attention gating and biased normalized sigmoid
+expert selection. The three cached batches cross a two-token sliding window; every
+fourth layer uses global attention without RoPE. The generator uses seed 20260907. Regeneration against the local CPU oracle built
+from llama.cpp `4b3951de9c87f66768e0fce4043756cc49efc20b` reproduced the NPZ byte for byte.
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/afmoe.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/afmoe.npz
new file mode 100644
index 00000000000..6713354f608
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/afmoe.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/minicpm-default.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/minicpm-default.npz
new file mode 100644
index 00000000000..93d5d24583c
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/minicpm-default.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/minicpm.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/minicpm.npz
index 1f87fa3f178..b0398bb3d13 100644
Binary files a/src/frontends/gguf/tests/test_data/arch_accuracy/minicpm.npz and b/src/frontends/gguf/tests/test_data/arch_accuracy/minicpm.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/nemotron_h.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/nemotron_h.npz
index 39d3eba4606..f1d6350b350 100644
Binary files a/src/frontends/gguf/tests/test_data/arch_accuracy/nemotron_h.npz and b/src/frontends/gguf/tests/test_data/arch_accuracy/nemotron_h.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35-zero-scales.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35-zero-scales.npz
new file mode 100644
index 00000000000..0d81e33071c
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35-zero-scales.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md b/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md
index 034a55564ea..58d8c52907d 100644
--- a/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md
+++ b/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md
@@ -23,7 +23,7 @@ vision/interleaved RoPE, antialiased bilinear resize and 2D im2col.
## Reference revision
-All fixtures and op expectations come from llama.cpp
+Base fixtures and op expectations come from llama.cpp
[`03fa73cb27f5c251b9528489b18d303b1366aca4`](https://github.com/ggml-org/llama.cpp/commit/03fa73cb27f5c251b9528489b18d303b1366aca4),
which has aligned-corner position interpolation, the Muse Glimmer encoder, and a `ggml_clamp`
that no longer clamps its source in place. The Gemma4 fixtures clip only the Q input, so
@@ -66,3 +66,8 @@ optional input LayerNorm at 16x8 and 8x24 pixels, through both native and embedd
`lfm2a` uses the same pinned llama.cpp CPU oracle, with 49 and 101 feature frames.
It exercises depthwise subsampling, relative attention shift and temporal convolution.
The dynamic test returns to the first shape to check request reuse.
+
+`minicpmv4_7` and `minicpmv4_7_4x` are extracted from PR #39000. The pinned
+llama.cpp CPU references at `098ce526b546b5a190327c1da82929cee051b9ac`
+cover the window-attention and direct 2x2 merger paths,
+with unequal image grids and packed-patch GenAI input adaptation.
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/minicpmv4_7.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/minicpmv4_7.npz
new file mode 100644
index 00000000000..5d7aecb883b
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/minicpmv4_7.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/minicpmv4_7_4x.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/minicpmv4_7_4x.npz
new file mode 100644
index 00000000000..bcefc216b1b
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/minicpmv4_7_4x.npz differ
diff --git a/src/frontends/gguf/tests/test_data/view_q8_102.npy b/src/frontends/gguf/tests/test_data/view_q8_102.npy
new file mode 100644
index 00000000000..3b8b00d4ac2
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/view_q8_102.npy differ
diff --git a/src/frontends/gguf/tests/test_data/view_q8_34.npy b/src/frontends/gguf/tests/test_data/view_q8_34.npy
new file mode 100644
index 00000000000..f14e6fd7980
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/view_q8_34.npy differ
diff --git a/src/frontends/gguf/tests/test_data/view_q8_input.npy b/src/frontends/gguf/tests/test_data/view_q8_input.npy
new file mode 100644
index 00000000000..ee6a5e94363
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/view_q8_input.npy differ
diff --git a/src/frontends/gguf/tests/test_data/view_q8_reference.json b/src/frontends/gguf/tests/test_data/view_q8_reference.json
new file mode 100644
index 00000000000..e4b25cc158e
--- /dev/null
+++ b/src/frontends/gguf/tests/test_data/view_q8_reference.json
@@ -0,0 +1,52 @@
+{
+ "oracle": "mmproj_ops_oracle.cpp:quantized_view",
+ "llama_revision": "9631fc03fbd5f7c6490b9552e622a213411e1459",
+ "input_shape_ggml": [
+ 64,
+ 4
+ ],
+ "view_shape_ggml": [
+ 32,
+ 2
+ ],
+ "row_stride_bytes": 136,
+ "offsets_bytes": [
+ 34,
+ 102
+ ],
+ "fixtures": [
+ {
+ "file": "view_q8_input.npy",
+ "shape": [
+ 256
+ ],
+ "sha256": "451ed7e5d587800cf4e874cbcfc3cf1f82404db588c3123fc0f85b30b0f1cf3e",
+ "range": [
+ 127.0,
+ 1016.0
+ ]
+ },
+ {
+ "file": "view_q8_34.npy",
+ "shape": [
+ 64
+ ],
+ "sha256": "0b509ced8574c1d3d49f9548a237a48818305383d3f4c2160c34a8dfac07874d",
+ "range": [
+ 254.0,
+ 762.0
+ ]
+ },
+ {
+ "file": "view_q8_102.npy",
+ "shape": [
+ 64
+ ],
+ "sha256": "68ffe1b0c48e57f31af6920555e59b2e35c93d6bec2e21ea61cb4108dbb1baf3",
+ "range": [
+ 508.0,
+ 1016.0
+ ]
+ }
+ ]
+}
diff --git a/src/frontends/gguf/tests/test_mmproj.cpp b/src/frontends/gguf/tests/test_mmproj.cpp
index 5421885b414..77b5c0ce22c 100644
--- a/src/frontends/gguf/tests/test_mmproj.cpp
+++ b/src/frontends/gguf/tests/test_mmproj.cpp
@@ -14,6 +14,7 @@
#include "common_test_utils/test_assertions.hpp"
#include "gguf_writer.hpp"
#include "gtest/gtest.h"
+#include "model_adapter_attribute.hpp"
#include "op_test_utils.hpp"
#include "openvino/frontend/gguf/adapt_mmproj_to_genai.hpp"
#include "openvino/frontend/gguf/extension/projector.hpp"
@@ -21,6 +22,7 @@
#include "openvino/op/add.hpp"
#include "openvino/op/gather.hpp"
#include "openvino/op/gelu.hpp"
+#include "openvino/op/multiply.hpp"
#include "openvino/op/mvn.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "openvino/openvino.hpp"
@@ -44,7 +46,7 @@ protected:
void weight(const std::string& name, const std::vector<uint64_t>& dims, bool norm = false) {
writer.filled_tensor(name, dims, norm, 0.01f);
}
- void encoder(const std::string& modality, const std::string& projector) {
+ void encoder(const std::string& modality, const std::string& projector, uint64_t positions = 16) {
const auto meta = "clip." + modality + ".";
const auto p = modality == "vision" ? std::string("v.") : std::string("a.");
writer.kv_bool("clip.has_" + modality + "_encoder", true);
@@ -55,7 +57,7 @@ protected:
writer.kv_u32(meta + "projection_dim", 6);
writer.kv_u32(meta + "attention.head_count", 2);
writer.kv_f32(meta + "attention.layer_norm_epsilon", 1e-5f);
- weight(p + "position_embd.weight", {8, 16});
+ weight(p + "position_embd.weight", {8, positions});
for (const auto* n : {"ln1", "ln2"}) {
weight(p + "blk.0." + n + ".weight", {8}, true);
weight(p + "blk.0." + n + ".bias", {8});
@@ -89,6 +91,23 @@ protected:
}
};
+TEST_F(GGUFMMProj, MiniCPMLearnedPositionGridIsIndependentOfResizeMetadata) {
+ encoder("vision", "minicpmv4_7", 4900);
+ weight("mm.up.weight", {32, 12});
+ weight("mm.down.weight", {12, 6});
+ auto model = convert();
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.position_grid_size"}), "70");
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "clip.vision.image_size"}), "8");
+ ov::serialize(model, path + ".xml", path + ".bin");
+ auto restored = ov::Core{}.read_model(path + ".xml");
+ EXPECT_EQ(restored->get_rt_info<std::string>({"gguf_mmproj", "vision.position_grid_size"}), "70");
+}
+
+TEST_F(GGUFMMProj, MiniCPMRejectsNonSquareLearnedPositionGrid) {
+ encoder("vision", "minicpmv4_7", 15);
+ OV_EXPECT_THROW(convert(), ov::Exception, testing::HasSubstr("square learned position grid"));
+}
+
TEST_F(GGUFMMProj, ExtensionAddsOneBranchAlongsideBuiltinVision) {
using namespace ov::frontend::gguf;
encoder("vision", "gemma3");
@@ -143,6 +162,11 @@ TEST_F(GGUFMMProj, ExtensionReusesBuiltinProjectorAndReplacementIsExplicit) {
auto model = frontend.convert(frontend.load(path));
EXPECT_EQ(model->output().get_shape(), (ov::Shape{1, 1, 4, 6}));
EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"}), "custom-gemma3");
+ using Adapter = pass::AdaptMmprojToGenAI;
+ auto adapted = model->clone();
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ ASSERT_TRUE(adapter.run_on_model(adapted));
+ EXPECT_EQ(adapter.get_vision_models().at("vision_embeddings"), adapted);
EXPECT_THROW(frontend.add_extension(std::make_shared<ProjectorExtension>(definition)), ov::Exception);
definition.build = [](GgufGraphContext& graph) {
return ProjectorResult{graph.add_input("replacement", ov::element::f32, {1, 1, 2, 3}), {}};
@@ -154,6 +178,245 @@ TEST_F(GGUFMMProj, ExtensionReusesBuiltinProjectorAndReplacementIsExplicit) {
ov::Exception);
}
+TEST_F(GGUFMMProj, CustomProjectorOverridesSerializableGenAILayout) {
+ using namespace ov::frontend::gguf;
+ using Adapter = pass::AdaptMmprojToGenAI;
+ writer.kv_bool("clip.has_vision_encoder", true);
+ writer.kv_str("clip.vision.projector_type", "custom-layout");
+ ASSERT_TRUE(writer.write(path));
+ ProjectorDefinition definition{
+ "clip.vision.custom-layout",
+ "clip",
+ "vision",
+ "custom-layout",
+ [](GgufGraphContext& graph) {
+ auto input = graph.add_input("vision.custom_pixels", ov::element::f32, {1, 1, 2, 3});
+ return ProjectorResult{graph.node("GGML_OP_SCALE", {input}, 0, {{"scale", 2.f}, {"bias", 0.f}}),
+ {},
+ ProjectorLayout::Image};
+ },
+ {},
+ ProjectorLayout::PaddedPatches};
+ FrontEnd frontend;
+ auto extension = std::make_shared<ProjectorExtension>(definition);
+ frontend.add_extension(extension);
+ auto model = frontend.convert(frontend.load(path));
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.genai_layout"}), "image");
+ ov::serialize(model, path + ".xml", path + ".bin");
+ auto restored = ov::Core{}.read_model(path + ".xml");
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ ASSERT_TRUE(adapter.run_on_model(restored));
+ ASSERT_EQ(adapter.get_vision_models().size(), 1);
+ EXPECT_EQ(adapter.get_vision_models().at("vision_embeddings"), restored);
+ EXPECT_EQ(restored->input().get_any_name(), "custom_pixels");
+ auto request = ov::Core{}.compile_model(restored, "CPU").create_infer_request();
+ std::fill_n(request.get_input_tensor().data<float>(), 6, 3.f);
+ request.infer();
+ EXPECT_EQ(request.get_output_tensor().get_shape(), (ov::Shape{1, 2, 3}));
+ for (size_t i = 0; i < 6; ++i)
+ EXPECT_FLOAT_EQ(request.get_output_tensor().data<float>()[i], 6.f);
+
+ definition.build = [](GgufGraphContext& graph) {
+ return ProjectorResult{graph.add_input("vision.replacement", ov::element::f32, {1, 1, 2, 3}), {}};
+ };
+ definition.genai_layout = ProjectorLayout::Image;
+ auto replacement_extension = std::make_shared<ProjectorExtension>(definition, RegistrationMode::Replace);
+ frontend.add_extension(replacement_extension);
+ auto replacement = frontend.convert(frontend.load(path));
+ EXPECT_EQ(replacement->get_rt_info<std::string>({"gguf_mmproj", "vision.genai_layout"}), "image");
+ ASSERT_TRUE(adapter.run_on_model(replacement));
+ EXPECT_EQ(replacement->input().get_any_name(), "replacement");
+}
+
+TEST_F(GGUFMMProj, ArbitraryProjectorCallbacksOverrideRecipesAndDefinitions) {
+ using namespace ov::frontend::gguf;
+ using Adapter = pass::AdaptMmprojToGenAI;
+ writer.kv_bool("clip.has_vision_encoder", true);
+ writer.kv_str("clip.vision.projector_type", "custom-callback");
+ ASSERT_TRUE(writer.write(path));
+ const auto scale = [](float factor) -> ModelAdapterFn {
+ return [factor](const std::shared_ptr<ov::Model>& model) {
+ auto result = model->get_results().front();
+ auto multiplier = ov::op::v0::Constant::create(ov::element::f32, {}, {factor});
+ auto output = std::make_shared<ov::op::v1::Multiply>(result->input_value(0), multiplier);
+ output->output(0).set_names({"custom_features"});
+ result->input(0).replace_source_output(output);
+ return ModelAdapterResult{model, {{"custom_vision", model}}};
+ };
+ };
+ for (const int selection : {0, 1, 2}) {
+ SCOPED_TRACE(selection);
+ std::optional<ModelAdapterFn> callback;
+ if (selection == 1)
+ callback = scale(5.f);
+ else if (selection == 2)
+ callback = ModelAdapterFn{};
+ ProjectorDefinition definition{
+ "clip.vision.custom-callback",
+ "clip",
+ "vision",
+ "custom-callback",
+ [callback](GgufGraphContext& graph) {
+ auto input = graph.add_input("vision.custom_pixels", ov::element::f32, {1, 1, 2, 3});
+ return ProjectorResult{graph.node("GGML_OP_SCALE", {input}, 0, {{"scale", 2.f}, {"bias", 0.f}}),
+ {},
+ ProjectorLayout::Image,
+ callback};
+ },
+ {},
+ ProjectorLayout::PaddedPatches,
+ scale(3.f)};
+ FrontEnd frontend;
+ auto extension = std::make_shared<ProjectorExtension>(definition);
+ frontend.add_extension(extension);
+ auto model = frontend.convert(frontend.load(path));
+ ov::serialize(model, path + ".xml", path + ".bin");
+ auto restored = ov::Core{}.read_model(path + ".xml");
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ ASSERT_TRUE(adapter.run_on_model(restored));
+ auto baseline = ov::Core{}.compile_model(restored, "CPU").create_infer_request();
+ std::fill_n(baseline.get_input_tensor().data<float>(), 6, 1.f);
+ baseline.infer();
+ EXPECT_FLOAT_EQ(baseline.get_output_tensor().data<float>()[0], 2.f);
+ ASSERT_TRUE(adapter.run_on_model(model));
+ EXPECT_EQ(adapter.get_vision_models().at(selection == 2 ? "vision_embeddings" : "custom_vision"), model);
+ auto request = ov::Core{}.compile_model(model, "CPU").create_infer_request();
+ std::fill_n(request.get_input_tensor().data<float>(), 6, 1.f);
+ request.infer();
+ for (size_t i = 0; i < 6; ++i)
+ EXPECT_FLOAT_EQ(request.get_output_tensor().data<float>()[i],
+ selection == 0 ? 6.f
+ : selection == 1 ? 10.f
+ : 2.f);
+ // Release the memory-mapped IR before rewriting its weights on Windows.
+ baseline = ov::InferRequest{};
+ restored.reset();
+ EXPECT_NO_THROW(ov::serialize(model, path + ".xml", path + ".bin"));
+ }
+}
+
+TEST_F(GGUFMMProj, ProjectorCallbackCanReplaceThePrimaryGraph) {
+ using namespace ov::frontend::gguf;
+ writer.kv_bool("clip.has_vision_encoder", true);
+ writer.kv_str("clip.vision.projector_type", "custom-replacement");
+ ASSERT_TRUE(writer.write(path));
+ ProjectorDefinition definition{
+ "clip.vision.custom-replacement",
+ "clip",
+ "vision",
+ "custom-replacement",
+ [](GgufGraphContext& graph) {
+ return ProjectorResult{graph.add_input("vision.source", ov::element::f32, {1, 1, 2, 3}), {}};
+ },
+ {},
+ {},
+ [](const std::shared_ptr<ov::Model>&) {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 3});
+ input->set_friendly_name("callback_values");
+ input->output(0).set_names({"callback_values"});
+ auto bias = ov::op::v0::Constant::create(ov::element::f32, {}, {7.f});
+ auto output = std::make_shared<ov::op::v1::Add>(input, bias);
+ output->output(0).set_names({"callback_features"});
+ auto replacement = std::make_shared<ov::Model>(ov::OutputVector{output}, ov::ParameterVector{input});
+ replacement->set_rt_info(std::string("replacement"), {"custom_adapter"});
+ return ModelAdapterResult{replacement, {{"custom_replacement", replacement}}};
+ }};
+ FrontEnd frontend;
+ auto extension = std::make_shared<ProjectorExtension>(definition);
+ frontend.add_extension(extension);
+ auto model = frontend.convert(frontend.load(path));
+ using Adapter = pass::AdaptMmprojToGenAI;
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ ASSERT_TRUE(adapter.run_on_model(model));
+ EXPECT_EQ(adapter.get_vision_models().at("custom_replacement"), model);
+ EXPECT_EQ(model->input().get_any_name(), "callback_values");
+ EXPECT_EQ(model->get_rt_info<std::string>({"custom_adapter"}), "replacement");
+ auto request = ov::Core{}.compile_model(model, "CPU").create_infer_request();
+ ov::Tensor data(ov::element::f32, {2, 3});
+ std::fill_n(data.data<float>(), data.get_size(), 4.f);
+ request.set_input_tensor(data);
+ request.infer();
+ for (size_t i = 0; i < 6; ++i)
+ EXPECT_FLOAT_EQ(request.get_output_tensor().data<float>()[i], 11.f);
+}
+
+TEST_F(GGUFMMProj, EmbeddingsCallbacksOverrideBothModalitiesWithOptionalModelMaps) {
+ using namespace ov::frontend::gguf;
+ using Adapter = pass::AdaptMmprojToGenAI;
+ for (const std::string modality : {"vision", "audio"}) {
+ writer.kv_bool("clip.has_" + modality + "_encoder", true);
+ writer.kv_str("clip." + modality + ".projector_type", "custom-embeddings");
+ }
+ ASSERT_TRUE(writer.write(path));
+ for (const bool named_models : {false, true}) {
+ SCOPED_TRACE(named_models);
+ std::map<std::string, size_t> calls;
+ std::shared_ptr<ov::Model> working;
+ FrontEnd frontend;
+ for (const std::string modality : {"vision", "audio"}) {
+ ProjectorDefinition definition{
+ "clip." + modality + ".custom-embeddings",
+ "clip",
+ modality,
+ "custom-embeddings",
+ [modality](GgufGraphContext& graph) {
+ auto input = graph.add_input(modality + ".custom_values", ov::element::f32, {1, 1, 2, 3});
+ return ProjectorResult{graph.node("GGML_OP_SCALE", {input}, 0, {{"scale", 2.f}, {"bias", 0.f}}),
+ {}};
+ },
+ {},
+ {},
+ [modality, named_models, &calls, &working](const std::shared_ptr<ov::Model>& model) {
+ ++calls[modality];
+ EXPECT_NE(model, working);
+ EXPECT_EQ(working->outputs().size(), 2);
+ EXPECT_EQ(model->inputs().size(), 1);
+ EXPECT_EQ(model->input().get_any_name(), "custom_values");
+ EXPECT_EQ(model->output().get_any_name(),
+ modality == "vision" ? "image_features" : "audio_features");
+ EXPECT_EQ(model->output().get_shape(), (ov::Shape{1, 2, 3}));
+ auto multiplier =
+ ov::op::v0::Constant::create(ov::element::f32, {}, {modality == "vision" ? 3.f : 5.f});
+ auto output = std::make_shared<ov::op::v1::Multiply>(model->get_results().front()->input_value(0),
+ multiplier);
+ output->output(0).set_names({"custom_features"});
+ auto replacement = std::make_shared<ov::Model>(ov::OutputVector{output}, model->get_parameters());
+ replacement->set_rt_info(modality, {"custom_adapter"});
+ return ModelAdapterResult{
+ replacement,
+ named_models ? ModelMap{{"custom_" + modality, replacement}} : ModelMap{}};
+ }};
+ auto extension = std::make_shared<ProjectorExtension>(definition);
+ frontend.add_extension(extension);
+ }
+ auto original = frontend.convert(frontend.load(path));
+ for (const std::string modality : {"vision", "audio"}) {
+ SCOPED_TRACE(modality);
+ working = original->clone();
+ Adapter adapter(modality == "vision" ? Adapter::Modality::VISION : Adapter::Modality::AUDIO);
+ ASSERT_TRUE(adapter.run_on_model(working));
+ EXPECT_EQ(calls[modality], 1);
+ EXPECT_EQ(calls[modality == "vision" ? "audio" : "vision"], modality == "vision" ? 0 : 1);
+ EXPECT_EQ(working->get_rt_info<std::string>({"custom_adapter"}), modality);
+ if (named_models)
+ EXPECT_EQ(adapter.get_vision_models().at("custom_" + modality), working);
+ else
+ EXPECT_TRUE(adapter.get_vision_models().empty());
+ for (const auto& node : working->get_ops())
+ EXPECT_FALSE(get_model_adapter(node));
+ auto request = ov::Core{}.compile_model(working, "CPU").create_infer_request();
+ std::fill_n(request.get_input_tensor().data<float>(), 6, 4.f);
+ request.infer();
+ for (size_t i = 0; i < 6; ++i)
+ EXPECT_FLOAT_EQ(request.get_output_tensor().data<float>()[i], modality == "vision" ? 24.f : 40.f);
+ EXPECT_NO_THROW(ov::serialize(working, path + ".xml", path + ".bin"));
+ }
+ EXPECT_EQ(original->outputs().size(), 2);
+ EXPECT_EQ(original->input("vision.custom_values").get_shape(), (ov::Shape{1, 1, 2, 3}));
+ EXPECT_EQ(original->input("audio.custom_values").get_shape(), (ov::Shape{1, 1, 2, 3}));
+ }
+}
+
TEST_F(GGUFMMProj, ExtensionReplacesOnlyOneBuiltinComponent) {
using namespace ov::frontend::gguf;
encoder("vision", "gemma3");
@@ -371,7 +634,9 @@ std::shared_ptr<ov::Model> vision_fixture(const std::string& name) {
return frontend.convert(frontend.load(fixture.path));
}
-void expect_layout_rejection_preserves_model(const std::shared_ptr<ov::Model>& model, const std::string& requirement) {
+void expect_adaptation_rejection_preserves_model(const std::shared_ptr<ov::Model>& model,
+ ov::frontend::gguf::pass::AdaptMmprojToGenAI& adapter,
+ const std::string& requirement) {
const auto results = model->get_results();
const auto parameters = model->get_parameters();
const auto nodes = model->get_ordered_ops();
@@ -384,8 +649,6 @@ void expect_layout_rejection_preserves_model(const std::shared_ptr<ov::Model>& m
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);
@@ -398,10 +661,209 @@ void expect_layout_rejection_preserves_model(const std::shared_ptr<ov::Model>& m
for (const auto& output : nodes[i]->outputs())
EXPECT_EQ(output.get_names(), tensor_names[output_index++]);
}
+}
+
+void expect_layout_rejection_preserves_model(const std::shared_ptr<ov::Model>& model, const std::string& requirement) {
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ expect_adaptation_rejection_preserves_model(model, adapter, requirement);
EXPECT_NO_THROW(Adapter(Adapter::Modality::VISION).run_on_model(model));
EXPECT_EQ(model->output(0).get_any_name(), "image_features");
}
+TEST_F(GGUFMMProj, VisionEncoderLayoutRestoresLegacySerializedRecipes) {
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ for (const std::string projector : {"gemma3", "gemma4v", "gemma4uv", "muse-glimmer", "qwen3vl_merger", "lfm2"}) {
+ SCOPED_TRACE(projector);
+ auto source = vision_fixture(projector);
+ auto current = source->clone();
+ Adapter current_adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ ASSERT_TRUE(current_adapter.run_on_model(current));
+ source->get_rt_info()["gguf_mmproj"].as<ov::AnyMap>().erase("vision.genai_layout");
+ ov::serialize(source, path + ".xml", path + ".bin");
+ auto restored = ov::Core{}.read_model(path + ".xml");
+ ASSERT_FALSE(restored->has_rt_info({"gguf_mmproj", "vision.genai_layout"}));
+ ASSERT_EQ(restored->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"}), projector);
+ Adapter legacy_adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ ASSERT_TRUE(legacy_adapter.run_on_model(restored));
+ const auto& current_models = current_adapter.get_vision_models();
+ const auto& legacy_models = legacy_adapter.get_vision_models();
+ ASSERT_EQ(legacy_models.size(), current_models.size());
+ for (const auto& [name, expected] : current_models) {
+ ASSERT_TRUE(legacy_models.count(name));
+ const auto& actual = legacy_models.at(name);
+ ASSERT_EQ(actual->inputs().size(), expected->inputs().size());
+ ASSERT_EQ(actual->outputs().size(), expected->outputs().size());
+ for (size_t i = 0; i < actual->inputs().size(); ++i) {
+ EXPECT_EQ(actual->input(i).get_names(), expected->input(i).get_names());
+ EXPECT_EQ(actual->input(i).get_partial_shape(), expected->input(i).get_partial_shape());
+ EXPECT_EQ(actual->input(i).get_element_type(), expected->input(i).get_element_type());
+ }
+ for (size_t i = 0; i < actual->outputs().size(); ++i) {
+ EXPECT_EQ(actual->output(i).get_names(), expected->output(i).get_names());
+ EXPECT_EQ(actual->output(i).get_partial_shape(), expected->output(i).get_partial_shape());
+ EXPECT_EQ(actual->output(i).get_element_type(), expected->output(i).get_element_type());
+ }
+ }
+ }
+}
+
+TEST_F(GGUFMMProj, ExplicitVisionLayoutOverridesLegacyProjectorRecipe) {
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ auto source = vision_fixture("gemma4v");
+ source->set_rt_info(std::string("image"), {"gguf_mmproj", "vision.genai_layout"});
+ source->get_rt_info()["gguf_mmproj"].as<ov::AnyMap>().erase("vision.patch_size");
+ ov::serialize(source, path + ".xml", path + ".bin");
+ auto restored = ov::Core{}.read_model(path + ".xml");
+ ASSERT_EQ(restored->get_rt_info<std::string>({"gguf_mmproj", "vision.genai_layout"}), "image");
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ ASSERT_TRUE(adapter.run_on_model(restored));
+ ASSERT_EQ(adapter.get_vision_models().size(), 1);
+ EXPECT_EQ(adapter.get_vision_models().at("vision_embeddings"), restored);
+ ASSERT_EQ(restored->inputs().size(), source->inputs().size());
+ for (size_t i = 0; i < restored->inputs().size(); ++i) {
+ EXPECT_EQ(restored->input(i).get_any_name(), source->input(i).get_any_name().substr(7));
+ EXPECT_EQ(restored->input(i).get_partial_shape(), source->input(i).get_partial_shape());
+ EXPECT_EQ(restored->input(i).get_element_type(), source->input(i).get_element_type());
+ }
+ EXPECT_EQ(restored->output().get_any_name(), "image_features");
+}
+
+TEST_F(GGUFMMProj, ExplicitUnsupportedVisionLayoutRejectsLegacyProjectorRecipe) {
+ encoder("vision", "gemma3");
+ auto source = convert();
+ for (const std::string layout : {"unsupported", "invalid", ""}) {
+ SCOPED_TRACE(layout);
+ auto model = source->clone();
+ model->set_rt_info(layout, {"gguf_mmproj", "vision.genai_layout"});
+ expect_layout_rejection_preserves_model(model, "no GenAI vision layout for mmproj contract");
+ }
+}
+
+TEST_F(GGUFMMProj, LegacyVisionLayoutRejectsUnknownOrMissingProjector) {
+ encoder("vision", "gemma3");
+ auto source = convert();
+ source->get_rt_info()["gguf_mmproj"].as<ov::AnyMap>().erase("vision.genai_layout");
+ for (const std::string projector : {"custom", ""}) {
+ SCOPED_TRACE(projector);
+ auto model = source->clone();
+ if (projector.empty())
+ model->get_rt_info()["gguf_mmproj"].as<ov::AnyMap>().erase("vision.projector");
+ else
+ model->set_rt_info(projector, {"gguf_mmproj", "vision.projector"});
+ expect_layout_rejection_preserves_model(model, "no GenAI vision layout");
+ }
+}
+
+TEST_F(GGUFMMProj, ProjectorCallbackFailuresPreserveTheOriginalGraph) {
+ using namespace ov::frontend::gguf;
+ writer.kv_bool("clip.has_vision_encoder", true);
+ writer.kv_str("clip.vision.projector_type", "custom-failure");
+ ASSERT_TRUE(writer.write(path));
+ for (const int failure : {0, 1, 2, 3, 4}) {
+ SCOPED_TRACE(failure);
+ ProjectorDefinition definition{
+ "clip.vision.custom-failure",
+ "clip",
+ "vision",
+ "custom-failure",
+ [](GgufGraphContext& graph) {
+ return ProjectorResult{graph.add_input("vision.source", ov::element::f32, {1, 1, 2, 3}), {}};
+ },
+ {},
+ {},
+ [failure](const std::shared_ptr<ov::Model>& model) -> ModelAdapterResult {
+ model->get_parameters().front()->set_friendly_name("rewired_clone");
+ if (failure == 0)
+ OPENVINO_THROW("custom callback failure");
+ if (failure == 1)
+ return {};
+ if (failure == 2)
+ return {model, {{"primary", model}, {"invalid", nullptr}}};
+ if (failure == 4)
+ return {model, {}};
+ auto output = ov::op::v0::Constant::create(ov::element::f32, {}, {1.f});
+ auto result = std::make_shared<ov::op::v0::Result>(output);
+ auto other = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{});
+ return {model, {{"other", other}}};
+ }};
+ FrontEnd frontend;
+ auto extension = std::make_shared<ProjectorExtension>(definition);
+ frontend.add_extension(extension);
+ auto model = frontend.convert(frontend.load(path));
+ using Adapter = pass::AdaptMmprojToGenAI;
+ Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
+ expect_adaptation_rejection_preserves_model(model,
+ adapter,
+ failure == 0 ? "custom callback failure"
+ : failure == 1 || failure == 4 ? "returned no models"
+ : failure == 2 ? "invalid model"
+ : "omitted its primary model");
+ }
+}
+
+TEST_F(GGUFMMProj, EmbeddingsCallbackFailuresPreserveBothModalities) {
+ using namespace ov::frontend::gguf;
+ using Adapter = pass::AdaptMmprojToGenAI;
+ for (const std::string modality : {"vision", "audio"}) {
+ SCOPED_TRACE(modality);
+ writer.kv_bool("clip.has_" + modality + "_encoder", true);
+ writer.kv_str("clip." + modality + ".projector_type", "custom-failure");
+ }
+ ASSERT_TRUE(writer.write(path));
+ for (const std::string modality : {"vision", "audio"}) {
+ SCOPED_TRACE(modality);
+ for (const int failure : {0, 1, 2, 3, 4, 5, 6}) {
+ SCOPED_TRACE(failure);
+ FrontEnd frontend;
+ for (const std::string branch : {"vision", "audio"}) {
+ ProjectorDefinition definition{
+ "clip." + branch + ".custom-failure",
+ "clip",
+ branch,
+ "custom-failure",
+ [branch](GgufGraphContext& graph) {
+ return ProjectorResult{graph.add_input(branch + ".source", ov::element::f32, {1, 1, 2, 3}), {}};
+ },
+ {},
+ {},
+ [failure](const std::shared_ptr<ov::Model>& model) -> ModelAdapterResult {
+ model->get_parameters().front()->set_friendly_name("rewired_clone");
+ if (failure == 0)
+ OPENVINO_THROW("custom callback failure");
+ if (failure == 1)
+ return {};
+ if (failure == 2)
+ return {model, {{"primary", model}, {"invalid", nullptr}}};
+ if (failure == 3)
+ return {model, {{"", model}}};
+ auto other = model->clone();
+ if (failure == 4)
+ return {model, {{"other", other}}};
+ auto invalid = failure == 5 ? model : other;
+ auto result = invalid->get_results().front();
+ auto bias = ov::op::v0::Constant::create(ov::element::f32, {1, 2, 3}, {1.f});
+ auto output = std::make_shared<ov::op::v1::Add>(result->input_value(0), bias);
+ result->input(0).replace_source_output(output);
+ invalid->get_parameters().front()->set_partial_shape({1, 1, 2, 5});
+ return {model, failure == 5 ? ModelMap{} : ModelMap{{"primary", model}, {"other", other}}};
+ }};
+ auto extension = std::make_shared<ProjectorExtension>(definition);
+ frontend.add_extension(extension);
+ }
+ auto model = frontend.convert(frontend.load(path));
+ Adapter adapter(modality == "vision" ? Adapter::Modality::VISION : Adapter::Modality::AUDIO);
+ expect_adaptation_rejection_preserves_model(model,
+ adapter,
+ failure == 0 ? "custom callback failure"
+ : failure == 1 ? "returned no models"
+ : failure == 2 || failure == 3 ? "invalid model"
+ : failure == 4 ? "omitted its primary model"
+ : "Argument shapes are inconsistent");
+ }
+ }
+}
+
class GGUFMMProjLayoutMetadata : public ::testing::TestWithParam<std::pair<std::string, std::string>> {};
TEST_P(GGUFMMProjLayoutMetadata, RejectsInvalidMetadataWithoutChangingModel) {
@@ -679,6 +1141,65 @@ TEST_P(GGUFMMProjAccuracy, EmbeddingsMatchLlamaCPU) {
}
class GGUFMMProjDynamicAccuracy : public GGUFMMProjAccuracy {};
+class GGUFMMProjMiniCpmPackedAccuracy : public GGUFMMProjAccuracy {};
+
+TEST_P(GGUFMMProjMiniCpmPackedAccuracy, PackedGridsMatchLlamaCPU) {
+ const std::string family = GetParam();
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ auto adapted = model->clone();
+ Adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS).run_on_model(adapted);
+ auto request = compile(adapted);
+ const size_t patch = 2;
+ for (const auto step : {0, 1, 0}) {
+ const auto prefix = std::to_string(step) + ".";
+ const auto& source = array(prefix + "pixel_values");
+ const auto rows = source.shape[2] / patch;
+ const auto cols = source.shape[3] / patch;
+ ov::Tensor packed(ov::element::f32, {1, 3, patch, rows * cols * patch});
+ for (size_t channel = 0; channel < 3; ++channel)
+ for (size_t y = 0; y < rows; ++y)
+ for (size_t x = 0; x < cols; ++x)
+ for (size_t dy = 0; dy < patch; ++dy)
+ for (size_t dx = 0; dx < patch; ++dx)
+ packed.data<float>()[(channel * patch + dy) * rows * cols * patch + (y * cols + x) * patch +
+ dx] =
+ source.data<float>()[(channel * rows * patch + y * patch + dy) * cols * patch +
+ x * patch + dx];
+ request.set_tensor("pixel_values", packed);
+ ov::Tensor positions(ov::element::i64, {rows * cols});
+ const auto& position_values = array(prefix + "position_ids");
+ std::copy_n(position_values.data<int32_t>(), rows * cols, positions.data<int64_t>());
+ request.set_tensor("position_ids", positions);
+ ov::Tensor grid(ov::element::i64, {2});
+ grid.data<int64_t>()[0] = rows;
+ grid.data<int64_t>()[1] = cols;
+ request.set_tensor("patch_grid", grid);
+ const auto interleave = [&](const std::string& name) {
+ const auto count = array(prefix + name + ".indices.0").num_vals;
+ ov::Tensor indices(ov::element::i64, {count * 4});
+ for (size_t part = 0; part < 4; ++part) {
+ const auto& values = array(prefix + name + ".indices." + std::to_string(part));
+ for (size_t i = 0; i < count; ++i)
+ indices.data<int64_t>()[i * 4 + part] = values.data<int32_t>()[i];
+ }
+ return indices;
+ };
+ request.set_tensor("merge_index", interleave("merger"));
+ const bool windowed = family == "minicpmv4_7";
+ request.set_tensor("window_index", interleave(windowed ? "vit_merger" : "merger"));
+ request.infer();
+ const auto output = request.get_output_tensor();
+ const auto& expected = array(prefix + "embeddings");
+ ASSERT_EQ(output.get_shape(), (ov::Shape{expected.shape[2], expected.shape[3]}));
+ ov_gguf_test::expect_nmse_below(
+ ov_gguf_test::nmse(output.data<const float>(), expected.data<float>(), output.get_size()),
+ 1e-5);
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(Reference,
+ GGUFMMProjMiniCpmPackedAccuracy,
+ ::testing::Values("minicpmv4_7", "minicpmv4_7_4x"));
// The low-contrast fixture's patch projection cancels to rounding noise, which differs with the
// platform's summation order (3e-5 on ARM64). Dropping its recentering raises the error to 1e-3.
@@ -732,6 +1253,8 @@ INSTANTIATE_TEST_SUITE_P(Reference,
"gemma4uv_low_contrast",
"gemma4ua",
"minicpmv4_6",
+ "minicpmv4_7",
+ "minicpmv4_7_4x",
"gemma4a",
"deepseekocr",
"deepseekocr2",
diff --git a/src/frontends/gguf/tests/test_ops.cpp b/src/frontends/gguf/tests/test_ops.cpp
index 6e95a35f3b0..112a08d7d13 100644
--- a/src/frontends/gguf/tests/test_ops.cpp
+++ b/src/frontends/gguf/tests/test_ops.cpp
@@ -14,15 +14,22 @@
#include "op_table.hpp"
#include "op_test_utils.hpp"
+#include "openvino/core/type/bfloat16.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/divide.hpp"
#include "openvino/op/extractimagepatches.hpp"
#include "openvino/op/eye.hpp"
+#include "openvino/op/greater_eq.hpp"
#include "openvino/op/multiply.hpp"
+#include "openvino/op/reshape.hpp"
#include "openvino/op/result.hpp"
#include "openvino/op/selective_ssm.hpp"
#include "openvino/op/slice.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/subtract.hpp"
#include "openvino/op/topk.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/op/unsqueeze.hpp"
#include "openvino/pass/manager.hpp"
#include "transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp"
#include "transformations/convert_precision.hpp"
@@ -305,6 +312,37 @@ TEST(GGUFOps, Scale) {
expect_near(out, expected);
}
+TEST(GGUFOps, ScaleBf16ComputesInF32) {
+ const std::vector<float> values{1, 1.25f, -2, 3.5f};
+ ov::Tensor x(ov::element::bf16, {1, 4});
+ for (size_t i = 0; i < values.size(); ++i) {
+ x.data<ov::bfloat16>()[i] = ov::bfloat16(values[i]);
+ }
+ for (const auto& scale_bias : {std::pair<float, float>{2.0f, 1.0f}, {0.5f, 0.0f}, {1.003f, 0.001f}}) {
+ SCOPED_TRACE(::testing::Message() << scale_bias.first << ", " << scale_bias.second);
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_SCALE")
+ .input("x", ov::element::bf16, {1, 4})
+ .output("out", ov::element::bf16, {1, 4})
+ .attr<float>("scale", scale_bias.first)
+ .attr<float>("bias", scale_bias.second)
+ .build();
+ auto out = run_on_cpu(model, {{"x", x}});
+ ASSERT_EQ(out.get_element_type(), ov::element::bf16);
+ auto output_convert =
+ ov::as_type_ptr<ov::op::v0::Convert>(model->get_results()[0]->input_value(0).get_node_shared_ptr());
+ ASSERT_TRUE(output_convert);
+ auto arithmetic_model =
+ std::make_shared<ov::Model>(ov::OutputVector{output_convert->input_value(0)}, model->get_parameters());
+ ov::TensorVector arithmetic_outputs{ov::Tensor(ov::element::f32, {1, 4})};
+ ASSERT_TRUE(arithmetic_model->evaluate(arithmetic_outputs, {x}));
+ for (size_t i = 0; i < values.size(); ++i) {
+ const float expected = scale_bias.first * values[i] + scale_bias.second;
+ EXPECT_FLOAT_EQ(arithmetic_outputs[0].data<float>()[i], expected);
+ }
+ }
+}
+
// RMS norm over the last axis (eps in op-params slot 0).
TEST(GGUFOps, RmsNorm) {
const float eps = 1e-6f;
@@ -748,6 +786,82 @@ TEST(GGUFOps, ViewDefaultIsPassThrough) {
expect_near(out, x, 0.0f);
}
+TEST(GGUFOps, ViewQuantizedBlockOffsetWithSingletonStrides) {
+ std::vector<float> values(128);
+ std::iota(values.begin(), values.end(), 0.0f);
+ for (int64_t offset : {34, 102}) {
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_VIEW")
+ .input("x", ov::element::f32, {1, 1, 2, 64})
+ .output("out", ov::element::f32, {1, 1, 1, 32})
+ .attr<std::vector<int64_t>>("view_input_strides", {34, 68, 136, 136})
+ .attr<std::vector<int64_t>>("view_output_strides", {34, 136, 136, 136})
+ .attr<int64_t>("view_offset_bytes", offset)
+ .attr<int64_t>("view_block_size", 32)
+ .build();
+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({1, 1, 2, 64}, values)}});
+ EXPECT_EQ(out.get_shape(), (ov::Shape{1, 1, 1, 32}));
+ const size_t start = offset == 34 ? 32 : 96;
+ const std::vector<float> expected(values.begin() + start, values.begin() + start + 32);
+ expect_near(out, expected, 0.0f);
+ }
+}
+
+TEST(GGUFOps, ViewQuantizedBlockOffsetWithStridedRows) {
+ const auto values = load_npy<float>("view_q8_input");
+ for (const auto& input_shape : {ov::Shape{1, 1, 4, 64}, ov::Shape{4, 64}}) {
+ SCOPED_TRACE(input_shape.size());
+ for (const int64_t offset : {34, 102}) {
+ SCOPED_TRACE(offset);
+ auto decoder = SingleOpBuilder()
+ .op("GGML_OP_VIEW")
+ .input("x", ov::element::f32, {1, 1, 4, 64})
+ .output("out", ov::element::f32, {1, 1, 2, 32})
+ .attr<std::vector<int64_t>>("view_input_strides", {34, 68, 272, 272})
+ .attr<std::vector<int64_t>>("view_output_strides", {34, 136, 272, 272})
+ .attr<int64_t>("view_offset_bytes", offset)
+ .attr<int64_t>("view_block_size", 32)
+ .decoder();
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, input_shape);
+ input->output(0).set_names({"x"});
+ auto tensors = std::make_shared<ov::frontend::gguf::TensorMap>();
+ (*tensors)["x"] = input;
+ ov::frontend::gguf::NodeContext context(decoder, tensors);
+ auto outputs = ov::frontend::gguf::op::translate_view(context);
+ auto result = std::make_shared<ov::op::v0::Result>(outputs.front());
+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{input});
+ const auto out = run_on_cpu(model, {{"x", make_f32_tensor(input_shape, values)}});
+ EXPECT_EQ(out.get_shape(), (ov::Shape{1, 1, 2, 32}));
+ expect_near(out, load_npy<float>("view_q8_" + std::to_string(offset)), 0.0f);
+ }
+ }
+}
+
+TEST(GGUFOps, ViewContiguousBatchWindowMergesHeads) {
+ const ov::Shape input_shape{2, 7, 4, 128};
+ const ov::Shape output_shape{1, 1, 7, 512};
+ const size_t batch_elements = ov::shape_size(output_shape);
+ std::vector<float> x(ov::shape_size(input_shape));
+ for (size_t i = 0; i < x.size(); ++i) {
+ x[i] = static_cast<float>(i);
+ }
+ for (int64_t batch : {int64_t{0}, int64_t{1}}) {
+ auto model =
+ SingleOpBuilder()
+ .op("GGML_OP_VIEW")
+ .input("x", ov::element::f32, input_shape)
+ .output("out", ov::element::f32, output_shape)
+ .attr<std::vector<int64_t>>("view_input_strides", {4, 512, 2048, 14336})
+ .attr<std::vector<int64_t>>("view_output_strides", {4, 2048, 14336, 14336})
+ .attr<int64_t>("view_offset_bytes", batch * static_cast<int64_t>(batch_elements * sizeof(float)))
+ .build();
+ auto out = run_on_cpu(model, {{"x", make_f32_tensor(input_shape, x)}});
+ ASSERT_EQ(out.get_shape(), output_shape);
+ const auto begin = x.begin() + batch * batch_elements;
+ expect_near(out, std::vector<float>(begin, begin + batch_elements), 0.0f);
+ }
+}
+
// View op_case 3: the decoder resolves ggml's ne/nb/offset into a {axis, start, len} slice plus the
// view's own output layout. Here it selects columns [1, 3) of a [1,1,2,4] source.
TEST(GGUFOps, ViewCase3SlicesAndReshapes) {
@@ -936,6 +1050,127 @@ TEST(GGUFOps, AddId) {
expect_near(out, expected);
}
+TEST(GGUFOps, ExpertIdsFromTopKOnlyMaskAfterArithmetic) {
+ for (bool add_bias : {false, true}) {
+ for (bool skipped : {false, true}) {
+ SCOPED_TRACE(add_bias);
+ SCOPED_TRACE(skipped);
+ auto scores = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, 2, 3});
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 2, 1, 2});
+ auto k = ov::op::v0::Constant::create(ov::element::i64, {}, {1});
+ auto topk = std::make_shared<ov::op::v11::TopK>(scores,
+ k,
+ -1,
+ ov::op::v11::TopK::Mode::MAX,
+ ov::op::v11::TopK::SortType::SORT_VALUES,
+ ov::element::i32);
+ ov::Output<ov::Node> ids = topk->output(1);
+ if (skipped) {
+ auto offset = ov::op::v0::Constant::create(ov::element::i32, {}, {3});
+ ids = std::make_shared<ov::op::v1::Subtract>(ids, offset);
+ }
+ const ov::Shape weight_shape = add_bias ? ov::Shape{1, 1, 3, 2} : ov::Shape{1, 3, 2, 2};
+ auto weights = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, weight_shape);
+ auto decoder = SingleOpBuilder()
+ .op(add_bias ? "GGML_OP_ADD_ID" : "GGML_OP_MUL_MAT_ID")
+ .input(add_bias ? "x" : "weights",
+ ov::element::f32,
+ add_bias ? input->get_partial_shape() : weights->get_partial_shape())
+ .input(add_bias ? "weights" : "x",
+ ov::element::f32,
+ add_bias ? weights->get_partial_shape() : input->get_partial_shape())
+ .input("ids", ov::element::i32, {1, 1, 2, 1})
+ .output("out", ov::element::f32, {1, 2, 1, 2})
+ .decoder();
+ auto tensors = std::make_shared<ov::frontend::gguf::TensorMap>();
+ (*tensors)["x"] = input;
+ (*tensors)["weights"] = weights;
+ (*tensors)["ids"] = ids;
+ ov::frontend::gguf::NodeContext context(decoder, tensors);
+ auto outputs = add_bias ? ov::frontend::gguf::op::translate_add_id(context)
+ : ov::frontend::gguf::op::translate_mul_mat_id(context);
+ auto result = std::make_shared<ov::op::v0::Result>(outputs.front());
+ auto model =
+ std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{scores, input, weights});
+ size_t masks = 0;
+ for (const auto& node : model->get_ordered_ops())
+ masks += ov::is_type<ov::op::v1::GreaterEqual>(node);
+ EXPECT_EQ(masks, skipped ? 1u : 0u);
+ scores->output(0).set_names({"scores"});
+ input->output(0).set_names({"x"});
+ weights->output(0).set_names({"weights"});
+ const std::vector<float> weight_values = add_bias ? std::vector<float>{10, 20, 30, 40, 50, 60}
+ : std::vector<float>{1, 0, 0, 1, 2, 0, 0, 2, 3, 0, 0, 3};
+ auto output = run_on_cpu(model,
+ {{"scores", make_f32_tensor({1, 1, 2, 3}, {1, 2, 3, 3, 2, 1})},
+ {"x", make_f32_tensor({1, 2, 1, 2}, {1, 2, 3, 4})},
+ {"weights", make_f32_tensor(weight_shape, weight_values)}});
+ const std::vector<float> expected =
+ skipped ? (add_bias ? std::vector<float>{1, 2, 3, 4} : std::vector<float>{0, 0, 0, 0})
+ : (add_bias ? std::vector<float>{51, 62, 13, 24} : std::vector<float>{3, 6, 3, 4});
+ expect_near(output, expected);
+ }
+ }
+}
+
+TEST(GGUFOps, NonnegativeIndicesPreserveSafeWrappers) {
+ auto scores = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{2, 3});
+ auto k = ov::op::v0::Constant::create(ov::element::i64, {}, {1});
+ auto topk = std::make_shared<ov::op::v11::TopK>(scores,
+ k,
+ -1,
+ ov::op::v11::TopK::Mode::MAX,
+ ov::op::v11::TopK::SortType::SORT_VALUES,
+ ov::element::i32);
+ EXPECT_FALSE(ov::frontend::gguf::has_nonnegative_indices(topk->output(0)));
+ auto order = ov::op::v0::Constant::create(ov::element::i64, {2}, {1, 0});
+ auto transpose = std::make_shared<ov::op::v1::Transpose>(topk->output(1), order);
+ auto shape = ov::op::v0::Constant::create(ov::element::i64, {1}, {2});
+ auto reshape = std::make_shared<ov::op::v1::Reshape>(transpose, shape, false);
+ auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
+ auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(reshape, axis);
+ auto squeeze = std::make_shared<ov::op::v0::Squeeze>(unsqueeze, axis);
+ auto start = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
+ auto stop = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
+ auto step = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
+ auto slice = std::make_shared<ov::op::v8::Slice>(squeeze, start, stop, step, axis);
+ auto widen = std::make_shared<ov::op::v0::Convert>(slice, ov::element::i64);
+ EXPECT_TRUE(ov::frontend::gguf::has_nonnegative_indices(widen));
+ auto narrow = std::make_shared<ov::op::v0::Convert>(widen, ov::element::i32);
+ EXPECT_FALSE(ov::frontend::gguf::has_nonnegative_indices(narrow));
+ auto real = std::make_shared<ov::op::v0::Convert>(slice, ov::element::f32);
+ EXPECT_FALSE(ov::frontend::gguf::has_nonnegative_indices(real));
+}
+
+TEST(GGUFOps, AddIdSkippedExperts) {
+ const std::vector<float> x{-0.0f, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
+ const std::vector<float> bias{10, 20, 30, 40, 50, 60};
+ const std::vector<int32_t> ids{-1, 2, -1, -1, 0, 1};
+ const std::vector<float> expected{-0.0f, 2, 53, 64, 5, 6, 7, 8, 19, 30, 41, 52};
+ for (bool flattened : {false, true}) {
+ SCOPED_TRACE(flattened);
+ const ov::Shape bias_shape = flattened ? ov::Shape{3, 2} : ov::Shape{1, 1, 3, 2};
+ const ov::Shape ids_shape = flattened ? ov::Shape{3, 2} : ov::Shape{1, 1, 3, 2};
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_ADD_ID")
+ .input("x", ov::element::f32, {1, 3, 2, 2})
+ .input("bias", ov::element::f32, bias_shape)
+ .input("ids", ov::element::i32, ids_shape)
+ .output("out", ov::element::f32, {1, 3, 2, 2})
+ .build();
+
+ ov::Tensor ids_tensor(ov::element::i32, ids_shape);
+ std::copy(ids.begin(), ids.end(), ids_tensor.data<int32_t>());
+ auto out = run_on_cpu(model,
+ {{"x", make_f32_tensor({1, 3, 2, 2}, x)},
+ {"bias", make_f32_tensor(bias_shape, bias)},
+ {"ids", ids_tensor}});
+ EXPECT_EQ(out.get_shape(), (ov::Shape{1, 3, 2, 2}));
+ expect_near(out, expected);
+ EXPECT_TRUE(std::signbit(out.data<float>()[0]));
+ }
+}
+
// Pad: constant (zero) pad on the last axis.
TEST(GGUFOps, Pad) {
// Pad last axis by 1 at the end: op_params[0]=begin(dim0), [1]=end(dim0) in ggml order.
@@ -1123,6 +1358,121 @@ TEST(GGUFOps, MulMatIdActivationsPerExpert) {
expect_near(out, expected, 1e-4f);
}
+struct MulMatIdSkippedIdsCase {
+ bool constant_weights;
+ bool per_expert_activations;
+ ov::element::Type ids_type;
+};
+
+class GGUFMulMatIdSkippedIds : public ::testing::TestWithParam<MulMatIdSkippedIdsCase> {};
+
+TEST_P(GGUFMulMatIdSkippedIds, MatchesReference) {
+ using namespace ov::frontend::gguf;
+ const auto c = GetParam();
+ const ov::Shape weights_shape{1, 3, 2, 2};
+ const size_t activation_slots = c.per_expert_activations ? 2 : 1;
+ const ov::PartialShape activations_shape{1, -1, static_cast<int64_t>(activation_slots), 2};
+ const ov::PartialShape ids_shape{1, 1, -1, 2};
+ const std::vector<float> weights_data{1, 0, 0, 1, 2, 0, 0, 2, 3, 0, 0, 3};
+ auto decoder = SingleOpBuilder()
+ .op("GGML_OP_MUL_MAT_ID")
+ .input("w", ov::element::f32, weights_shape)
+ .input("a", ov::element::f32, activations_shape)
+ .input("ids", c.ids_type, ids_shape)
+ .output("out", ov::element::f32, {1, -1, 2, 2})
+ .decoder();
+ auto activations = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, activations_shape);
+ auto ids = std::make_shared<ov::op::v0::Parameter>(c.ids_type, ids_shape);
+ activations->output(0).set_names({"a"});
+ ids->output(0).set_names({"ids"});
+ ov::ParameterVector parameters{activations, ids};
+ std::shared_ptr<ov::Node> weights;
+ if (c.constant_weights) {
+ weights = ov::op::v0::Constant::create(ov::element::f32, weights_shape, weights_data);
+ } else {
+ auto weights_input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, weights_shape);
+ weights_input->output(0).set_names({"w"});
+ weights = weights_input;
+ parameters.push_back(weights_input);
+ }
+ auto tensors = std::make_shared<TensorMap>();
+ (*tensors)["w"] = weights;
+ (*tensors)["a"] = activations;
+ (*tensors)["ids"] = ids;
+ NodeContext context(decoder, tensors);
+ auto outputs = op::translate_mul_mat_id(context);
+ auto model = std::make_shared<ov::Model>(outputs, parameters);
+ const auto operations = model->get_ops();
+ EXPECT_EQ(std::any_of(operations.begin(),
+ operations.end(),
+ [](const auto& node) {
+ return std::string(node->get_type_name()) == "GatherMatmul";
+ }),
+ c.constant_weights);
+
+ ov::Core core;
+ auto compiled = core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32));
+ auto request = compiled.create_infer_request();
+ if (!c.constant_weights) {
+ request.set_tensor("w", make_f32_tensor(weights_shape, weights_data));
+ }
+ const std::vector<float> activation_data =
+ c.per_expert_activations ? std::vector<float>{1, 2, 3, 4, 5, 6, 7, 8} : std::vector<float>{1, 2, 3, 4};
+ const std::vector<float> positive_expected = c.per_expert_activations ? std::vector<float>{1, 2, 6, 8, 15, 18, 7, 8}
+ : std::vector<float>{1, 2, 2, 4, 9, 12, 3, 4};
+ const std::vector<std::vector<int64_t>> scenarios{{0, 1, 2, 0}, {-1, 1, 2, -1}, {-1, -1, -1, -1}, {}};
+ for (const auto& selected_ids : scenarios) {
+ SCOPED_TRACE(::testing::PrintToString(selected_ids));
+ const size_t tokens = selected_ids.size() / 2;
+ auto data = activation_data;
+ auto expected = positive_expected;
+ data.resize(tokens * activation_slots * 2);
+ expected.resize(tokens * 4);
+ for (size_t i = 0; i < selected_ids.size(); ++i) {
+ if (selected_ids[i] < 0) {
+ expected[2 * i] = 0;
+ expected[2 * i + 1] = 0;
+ }
+ }
+ if (!selected_ids.empty() && std::all_of(selected_ids.begin(), selected_ids.end(), [](int64_t id) {
+ return id < 0;
+ })) {
+ std::fill(data.begin(), data.end(), std::nanf(""));
+ }
+ ov::Tensor ids_tensor(c.ids_type, ov::Shape{1, 1, tokens, 2});
+ if (c.ids_type == ov::element::i64) {
+ std::copy(selected_ids.begin(), selected_ids.end(), ids_tensor.data<int64_t>());
+ } else {
+ for (size_t i = 0; i < selected_ids.size(); ++i) {
+ ids_tensor.data<int32_t>()[i] = static_cast<int32_t>(selected_ids[i]);
+ }
+ }
+ request.set_tensor("a", make_f32_tensor({1, tokens, activation_slots, 2}, data));
+ request.set_tensor("ids", ids_tensor);
+ request.infer();
+ auto out = request.get_output_tensor();
+ EXPECT_EQ(out.get_shape(), (ov::Shape{1, tokens, 2, 2}));
+ expect_near(out, expected, 0.0f);
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(GGUFOps,
+ GGUFMulMatIdSkippedIds,
+ ::testing::Values(MulMatIdSkippedIdsCase{false, false, ov::element::i32},
+ MulMatIdSkippedIdsCase{false, false, ov::element::i64},
+ MulMatIdSkippedIdsCase{false, true, ov::element::i32},
+ MulMatIdSkippedIdsCase{false, true, ov::element::i64},
+ MulMatIdSkippedIdsCase{true, false, ov::element::i32},
+ MulMatIdSkippedIdsCase{true, false, ov::element::i64},
+ MulMatIdSkippedIdsCase{true, true, ov::element::i32},
+ MulMatIdSkippedIdsCase{true, true, ov::element::i64}),
+ [](const ::testing::TestParamInfo<MulMatIdSkippedIdsCase>& info) {
+ const auto& c = info.param;
+ return std::string(c.constant_weights ? "Constant" : "Dynamic") +
+ (c.per_expert_activations ? "PerExpert" : "Shared") +
+ (c.ids_type == ov::element::i64 ? "I64" : "I32");
+ });
+
// MulMatId over an empty token axis. Every non-final chunk of a chunked prefill produces no logits, so
// its inp_out_ids gather leaves the last layer's activations with 0 rows; that empty extent must flow
// through to an empty result rather than being broadcast up to n_used (which OpenVINO rejects).
@@ -1974,6 +2324,27 @@ TEST(GGUFOps, MulMatIdMxfp4Packed) {
}
// token0 (expert1): row0=3.0*1=3, row1=4.0*1=4 ; token1 (expert0): row0=1.0, row1=2.0
expect_near(out, expected, 1e-4f);
+
+ const std::vector<std::vector<int32_t>> skipped_scenarios{{1, -1}, {-1, -1}};
+ for (const auto& selected_ids : skipped_scenarios) {
+ SCOPED_TRACE(::testing::PrintToString(selected_ids));
+ std::copy(selected_ids.begin(), selected_ids.end(), ids_t.data<int32_t>());
+ auto skipped_activations = a;
+ for (size_t t = 0; t < selected_ids.size(); ++t) {
+ if (selected_ids[t] < 0) {
+ std::fill_n(skipped_activations.begin() + t * cols, cols, std::nanf(""));
+ }
+ }
+ auto skipped_out =
+ run_on_cpu(model,
+ {{"w", w_t},
+ {"a", make_f32_tensor({1, (size_t)n_tokens, 1, (size_t)cols}, skipped_activations)},
+ {"ids", ids_t}});
+ EXPECT_EQ(skipped_out.get_shape(), (ov::Shape{1, (size_t)n_tokens, 1, (size_t)m}));
+ expect_near(skipped_out,
+ selected_ids[0] < 0 ? std::vector<float>{0, 0, 0, 0} : std::vector<float>{3, 4, 0, 0},
+ 0.0f);
+ }
}
// MulMat: batched matmul A @ B^T. The translator binds B=input(0), A=input(1) and emits
@@ -3459,6 +3830,48 @@ TEST(GGUFOps, AddMixedPrecisionPreservesLeftType) {
}
}
+TEST(GGUFOps, BinaryMixedPrecisionBroadcast) {
+ const std::vector<float> values{1, 1.25f, -2, 3.5f, 0.5f, -4};
+ const std::vector<float> rhs{1.003f, 0.997f, -0.501f};
+ for (const std::string op : {"GGML_OP_SUB", "GGML_OP_MUL"}) {
+ SCOPED_TRACE(op);
+ for (const auto type : {ov::element::bf16, ov::element::f16}) {
+ SCOPED_TRACE(type);
+ auto model = SingleOpBuilder()
+ .op(op)
+ .input("a", type, {2, 3})
+ .input("b", ov::element::f32, {1, 3})
+ .output("out", type, {2, 3})
+ .build();
+ ov::Tensor a(type, {2, 3});
+ for (size_t i = 0; i < values.size(); ++i) {
+ if (type == ov::element::bf16) {
+ a.data<ov::bfloat16>()[i] = ov::bfloat16(values[i]);
+ } else {
+ a.data<ov::float16>()[i] = ov::float16(values[i]);
+ }
+ }
+ auto out = run_on_cpu(model, {{"a", a}, {"b", make_f32_tensor({1, 3}, rhs)}});
+ ASSERT_EQ(out.get_element_type(), type);
+ EXPECT_EQ(out.get_shape(), (ov::Shape{2, 3}));
+ auto output_convert =
+ ov::as_type_ptr<ov::op::v0::Convert>(model->get_results()[0]->input_value(0).get_node_shared_ptr());
+ ASSERT_TRUE(output_convert);
+ auto arithmetic_model =
+ std::make_shared<ov::Model>(ov::OutputVector{output_convert->input_value(0)}, model->get_parameters());
+ ov::TensorVector arithmetic_outputs{ov::Tensor(ov::element::f32, {2, 3})};
+ ASSERT_TRUE(arithmetic_model->evaluate(arithmetic_outputs, {a, make_f32_tensor({1, 3}, rhs)}));
+ for (size_t i = 0; i < values.size(); ++i) {
+ const float expected = op == "GGML_OP_SUB" ? values[i] - rhs[i % 3] : values[i] * rhs[i % 3];
+ EXPECT_FLOAT_EQ(arithmetic_outputs[0].data<float>()[i], expected);
+ if (type == ov::element::f16) {
+ EXPECT_EQ(float(out.data<ov::float16>()[i]), float(ov::float16(expected)));
+ }
+ }
+ }
+ }
+}
+
TEST(GGUFOps, SwigluClampF16RoundsOnce) {
auto model = SingleOpBuilder()
.op("GGML_GLU_OP_SWIGLU_CLAMP")