OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GGUF FE] Native .gguf graph builder (#37421)
Maxim Vafined58b4fb054d
diff --git a/.claude/skills/ov-gguf-add-architecture/SKILL.md b/.claude/skills/ov-gguf-add-architecture/SKILL.mdnew file mode 100644index 00000000000..de1ece74838--- /dev/null+++ b/.claude/skills/ov-gguf-add-architecture/SKILL.md@@ -0,0 +1,15 @@+---+name: ov-gguf-add-architecture+description: >+ Enable a new model architecture/family in the OpenVINO GGUF frontend's native .gguf builder,+ or check whether a GGUF model is supported. Use when the user asks to enable, support or bring+ up a GGUF/llama.cpp model (llama, qwen, phi, gemma, MoE and similar decoder-only families),+ when a .gguf file is rejected as an unsupported architecture, or when working on+ arch_registry / DecoderBuilder in src/frontends/gguf/src/builder/. Do NOT use for adding+ a single ggml op translator or for debugging wrong output from an already-supported model.+---++1. Read [src/frontends/gguf/docs/adding_an_architecture.md](../../../src/frontends/gguf/docs/adding_an_architecture.md) — most architectures in the transformer family need **no code**, only a `general.architecture` string added to `arch_registry.cpp` plus the correct RoPE type. It also lists exactly which structural features are auto-detected from the tensor table and metadata, and how to verify a new arch.+2. Check [src/frontends/gguf/docs/supported_models.md](../../../src/frontends/gguf/docs/supported_models.md) first to see whether the architecture is already accepted and how support was verified.+3. Only if the family is structurally novel, consult the "10% case" section before adding builder code.+4. Verify as that document prescribes, including the graph-fingerprint check, and re-run the other supported architectures after any change to shared builder logic.diff --git a/.claude/skills/ov-gguf-debug-accuracy/SKILL.md b/.claude/skills/ov-gguf-debug-accuracy/SKILL.mdnew file mode 100644index 00000000000..503b9815e0a--- /dev/null+++ b/.claude/skills/ov-gguf-debug-accuracy/SKILL.md@@ -0,0 +1,15 @@+---+name: ov-gguf-debug-accuracy+description: >+ Debug wrong or degraded output from a GGUF model running through the OpenVINO GGUF frontend or+ the ggml-openvino backend. Use when a GGUF model converts but produces garbage, repeated or+ drifting tokens, a cosine-similarity cliff between layers, output that diverges from llama.cpp+ CPU, or a broadcast/shape crash that appears only at decode or only for one architecture. Do+ NOT use for ops that fail to convert at all ("Translation for operation type ... is not+ implemented"), or for build and CMake failures.+---++1. Read [src/frontends/gguf/docs/debugging_accuracy.md](../../../src/frontends/gguf/docs/debugging_accuracy.md) — the coarse-to-fine bisection strategy, the ggml-CPU oracle technique, the catalogue of bug archetypes with their generalizable lessons, the debug env vars, and the checklist.+2. Apply its one governing rule before anything else: every accuracy claim is a comparison against the **real llama.cpp CPU implementation**, never a hand-derived reference. If you are about to write out an op's math to form an expectation, generate it from ggml instead.+3. Work the bisection steps in order and do not open a debugger until they have cornered the bug. Check the bug archetypes first when a cosine cliff or dynamic-shape crash points near one.+4. After any fix to a shared path — especially a VIEW or `op_case` predicate — re-run the other supported architectures and confirm their classification and output are unchanged.diff --git a/.claude/skills/ov-gguf-enable-op/SKILL.md b/.claude/skills/ov-gguf-enable-op/SKILL.mdnew file mode 100644index 00000000000..7bbe765ef04--- /dev/null+++ b/.claude/skills/ov-gguf-enable-op/SKILL.md@@ -0,0 +1,15 @@+---+name: ov-gguf-enable-op+description: >+ Enable a ggml operation in the OpenVINO GGUF frontend by adding or fixing an op translator.+ Use when conversion fails with "Translation for operation type GGML_OP_* is not implemented",+ when the user asks to add/implement/fix a GGUF or ggml op translator or an op_case, or when+ working on src/frontends/gguf/src/op/. Do NOT use for enabling a new model architecture+ (that is usually just a name in arch_registry.cpp), for wrong numerical output from an op that+ already converts, or for GGUF quantization format work.+---++1. Read [src/frontends/gguf/docs/how_to_add_op.md](../../../src/frontends/gguf/docs/how_to_add_op.md) — the five-file checklist (including the test CMake source list, which is not globbed), the `NodeContext` API, the mandatory op-coverage gate, where reference values must come from, and the build/test commands (`-DENABLE_OV_GGUF_FRONTEND=ON`).+2. Confirm a translator is really what is missing: a new architecture usually needs only a name in `arch_registry.cpp`, and a structurally different use of an existing op is an `op_case`. Both are covered in that document.+3. Find the closest existing op with `grep -n "GGML_" src/frontends/gguf/src/op_table.cpp` and the closest test with `grep -n "^TEST(" src/frontends/gguf/tests/test_ops.cpp`, then read only those ranges — do not read `test_ops.cpp` in full.+4. Implement, then build and run `ov_gguf_frontend_tests` — filtered while iterating, unfiltered before finishing so the coverage gate runs.diff --git a/.github/components.yml b/.github/components.ymlindex 513ad55186e..54d1e08d131 100644--- a/.github/components.yml+++ b/.github/components.yml@@ -109,6 +109,8 @@ PROXY:build: []GGUF_FE:+ revalidate:+ - CPU # the per-op tests compile and infer their converted graphs on the CPU pluginbuild:- CPUdiff --git a/.github/labeler.yml b/.github/labeler.ymlindex eb4194e5808..b5ce7ca635c 100644--- a/.github/labeler.yml+++ b/.github/labeler.yml@@ -71,6 +71,11 @@- 'src/frontends/common/include/openvino/frontend/extension.hpp'- 'src/frontends/common/include/openvino/frontend/extension/**/*'+'category: GGUF FE':+- 'src/frontends/gguf/**/*'+- 'tests/model_hub_tests/gguf/**/*'+- 'tests/requirements_gguf'+'category: GPU':- 'src/plugins/intel_gpu/**/*'- 'thirdparty/ocl/**/*'@@ -157,7 +162,8 @@- 'tests/requirements_tensorflow'- any: ['tests/model_hub_tests/**','!tests/model_hub_tests/pytorch/**/*',- '!tests/model_hub_tests/jax/**/*']+ '!tests/model_hub_tests/jax/**/*',+ '!tests/model_hub_tests/gguf/**/*']'category: TFL FE':- 'src/frontends/tensorflow_lite/**/*'@@ -173,7 +179,8 @@- 'tests/requirements_pytorch'- any: ['tests/model_hub_tests/**','!tests/model_hub_tests/tensorflow/**/*',- '!tests/model_hub_tests/jax/**/*']+ '!tests/model_hub_tests/jax/**/*',+ '!tests/model_hub_tests/gguf/**/*']'category: JAX FE':- 'src/frontends/jax/**/*'@@ -181,7 +188,8 @@- 'tests/layer_tests/jax_tests/**/*'- any: ['tests/model_hub_tests/**','!tests/model_hub_tests/tensorflow/**/*',- '!tests/model_hub_tests/pytorch/**/*']+ '!tests/model_hub_tests/pytorch/**/*',+ '!tests/model_hub_tests/gguf/**/*']'category: tools':- any: ['tools/**',diff --git a/.github/workflows/gguf_llamacpp_validation.yml b/.github/workflows/gguf_llamacpp_validation.ymlnew file mode 100644index 00000000000..49d32b219eb--- /dev/null+++ b/.github/workflows/gguf_llamacpp_validation.yml@@ -0,0 +1,120 @@+name: GGUF Frontend x llama.cpp validation++# Smart CI: only build/test when the GGUF frontend itself (or this workflow) changes. The+# frontend is consumed directly by llama.cpp's ggml-openvino backend, which has its own, much+# stricter accuracy tolerance (test-backend-ops) than genai; this job is the only place that+# exercises that path against a freshly built frontend before it reaches either consumer.+on:+ pull_request:+ paths:+ - 'src/frontends/gguf/**'+ - '.github/workflows/gguf_llamacpp_validation.yml'+ push:+ branches:+ - 'mvafin/gguf/**'+ paths:+ - 'src/frontends/gguf/**'+ workflow_dispatch:+ inputs:+ llama_cpp_ref:+ description: 'llama.cpp commit/branch to test against'+ type: string+ required: false+ default: ''++concurrency:+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}+ cancel-in-progress: true++permissions: read-all++env:+ # mvafin/llama.cpp@ov-frontend-swap-llamacpp-sync, pinned to the commit that carries the+ # 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: 16fb7d9d326a3fe69a331ce5fbe7a679a1a281bb+ OV_INSTALL_DIR: ${{ github.workspace }}/ov_install++jobs:+ gguf-llamacpp-tests:+ name: Build GGUF frontend and run llama.cpp tests+ runs-on: ubuntu-24.04+ timeout-minutes: 180+ steps:+ - name: Checkout OpenVINO+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ submodules: recursive++ - name: Install build dependencies+ run: sudo -E ./install_build_dependencies.sh++ - name: Cache ccache+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0+ with:+ path: ~/.ccache+ key: gguf-llamacpp-ccache-${{ runner.os }}-${{ github.base_ref || github.ref_name }}-${{ github.sha }}+ restore-keys: |+ gguf-llamacpp-ccache-${{ runner.os }}-${{ github.base_ref || github.ref_name }}-+ gguf-llamacpp-ccache-${{ runner.os }}-++ - name: Configure OpenVINO (CPU plugin + GGUF frontend only)+ run: |+ cmake -G Ninja -B build \+ -DCMAKE_BUILD_TYPE=Release \+ -DCMAKE_INSTALL_PREFIX=${{ env.OV_INSTALL_DIR }} \+ -DCMAKE_C_COMPILER_LAUNCHER=ccache \+ -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \+ -DENABLE_INTEL_CPU=ON \+ -DENABLE_INTEL_GPU=OFF \+ -DENABLE_INTEL_NPU=OFF \+ -DENABLE_OV_GGUF_FRONTEND=ON \+ -DENABLE_OV_ONNX_FRONTEND=OFF \+ -DENABLE_OV_PADDLE_FRONTEND=OFF \+ -DENABLE_OV_PYTORCH_FRONTEND=OFF \+ -DENABLE_OV_TF_FRONTEND=OFF \+ -DENABLE_OV_TF_LITE_FRONTEND=OFF \+ -DENABLE_OV_JAX_FRONTEND=OFF \+ -DENABLE_SAMPLES=OFF \+ -DENABLE_TESTS=OFF \+ -DENABLE_PYTHON=OFF \+ -DENABLE_WHEEL=OFF \+ -DENABLE_DOCS=OFF++ - name: Build and install OpenVINO+ run: |+ cmake --build build --parallel "$(nproc)"+ cmake --install build++ - name: Checkout llama.cpp+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ repository: ${{ env.LLAMA_CPP_REPO }}+ ref: ${{ inputs.llama_cpp_ref || env.LLAMA_CPP_REF }}+ path: llama.cpp++ - name: Configure llama.cpp against the freshly built OpenVINO+ run: |+ source ${{ env.OV_INSTALL_DIR }}/setupvars.sh+ cmake -G Ninja -S llama.cpp -B llama.cpp/build \+ -DCMAKE_BUILD_TYPE=Release \+ -DGGML_OPENVINO=ON++ - name: Build llama.cpp+ run: cmake --build llama.cpp/build --parallel "$(nproc)"++ - name: Run llama.cpp tests against the ggml-openvino backend+ env:+ # Q4_K's zero-point defaults to an integer (u8) constant for production (genai) speed.+ # llama.cpp's test-backend-ops compares against an f32 CPU reference within a tolerance+ # the rounded u8 zero-point can miss, so request the faithful f16 zero-point here. See+ # gguf_zero_point_type in src/frontends/gguf/src/quant/weights.cpp.+ OV_GGUF_Q4_K_ZP_F16: "1"+ run: |+ source ${{ env.OV_INSTALL_DIR }}/setupvars.sh+ # test-llama-archs needs an arch fixture this frontend snapshot doesn't carry; excluded+ # to match llama.cpp's own upstream CI (see ci/run.sh) until that lands separately.+ ctest --test-dir llama.cpp/build -L main \+ -E "test-opt|test-llama-archs" \+ --output-on-failure --timeout 2000diff --git a/.github/workflows/job_build_linux.yml b/.github/workflows/job_build_linux.ymlindex 346121a1f02..d560c50a17c 100644--- a/.github/workflows/job_build_linux.yml+++ b/.github/workflows/job_build_linux.yml@@ -90,6 +90,11 @@ on:type: booleanrequired: falsedefault: false+ generate-gguf-fixtures:+ description: 'Whether to generate the GGUF per-architecture test fixtures from llama.cpp into the tests artifact. Off by default: only useful where this build feeds job_cxx_unit_tests.yml'+ type: boolean+ required: false+ default: falsepermissions: read-all@@ -259,6 +264,25 @@ jobs:if: ${{ inputs.build-samples }}run: cmake --install ${BUILD_DIR} --config ${{ env.CMAKE_BUILD_TYPE }} --prefix ${INSTALL_DIR} --component samples_bin+ # The GGUF per-architecture fixtures are GGUF headers emitted by llama.cpp's test-llama-archs.+ # They are generated here rather than committed, and land in the tests artifact so the test job+ # (which has neither a source checkout nor cmake) can consume them like any other test data.+ # Where they are absent the arch test suite skips itself, so this is test data, not a build+ # dependency -- which is what keeps llama.cpp out of OpenVINO's dependency graph.+ #+ # llama.cpp is pinned inside gen_arch_fixtures.py and only moves when the fixtures are+ # deliberately refreshed: the generator writes whatever KVs llama.cpp currently defines, so+ # following upstream would change every fixture's bytes -- and break the pinned graph+ # fingerprints -- on an unrelated llama.cpp commit.+ - name: Generate GGUF arch fixtures+ if: ${{ inputs.generate-gguf-fixtures && fromJSON(inputs.affected-components).GGUF_FE.test }}+ run: |+ python3 -m pip install --no-cache-dir gguf+ python3 ${OPENVINO_REPO}/src/frontends/gguf/tests/gen_arch_fixtures.py \+ --fetch \+ --out-dir ${INSTALL_TEST_DIR}/tests/test_data/arch_fixtures \+ -j $(nproc)+- name: Install Python wheels for the main Pythonif: ${{ ! inputs.build-additional-python-packages }}run: cmake --install ${BUILD_DIR} --config ${{ env.CMAKE_BUILD_TYPE }} --prefix ${INSTALL_WHEELS_DIR} --component python_wheelsdiff --git a/.github/workflows/job_gguf_models_tests.yml b/.github/workflows/job_gguf_models_tests.ymlnew file mode 100644index 00000000000..954be774041--- /dev/null+++ b/.github/workflows/job_gguf_models_tests.yml@@ -0,0 +1,116 @@+name: GGUF Models tests++on:+ workflow_call:+ inputs:+ runner:+ description: 'Machine on which the tests would run'+ type: string+ required: true+ image:+ description: 'Docker image to use for the job'+ type: string+ required: false+ default: null+ model_scope:+ description: 'Scope of models for testing.'+ type: string+ required: true++permissions: read-all++env:+ HF_HUB_CACHE_LIN: /mount/caches/huggingface+ HF_HUB_CACHE_WIN: "C:\\mount\\caches\\huggingface"+ HF_TOKEN_PATH_LIN: /secrets/huggingface/token-secondary+ HF_TOKEN_PATH_WIN: "C:\\mount\\secrets\\huggingface\\token-secondary"++jobs:+ GGUF_Models_Tests:+ name: GGUF Models tests+ # The nightly scope downloads several 7B-30B checkpoints, so it needs far more time+ # than the precommit scope (18 models of <=~4B).+ timeout-minutes: ${{ inputs.model_scope == 'precommit' && 60 || 240 }}+ runs-on: ${{ inputs.runner }}+ container:+ image: ${{ inputs.image }}+ volumes:+ - /mount:/mount+ - /home/runner/secrets/:/secrets:ro+ - ${{ github.workspace }}:${{ github.workspace }} # Needed as ${{ github.workspace }} is not working correctly when using Docker+ defaults:+ run:+ shell: bash+ env:+ DEBIAN_FRONTEND: noninteractive # to prevent apt-get from waiting user input+ INSTALL_DIR: ${{ github.workspace }}/install+ INSTALL_TEST_DIR: ${{ github.workspace }}/install/tests+ MODEL_HUB_TESTS_INSTALL_DIR: ${{ github.workspace }}/install/tests/model_hub_tests+ USE_SYSTEM_CACHE: False # Using remote HuggingFace cache+ HF_HUB_VERBOSITY: debug+ steps:+ # checkout action cleans up the workspace and have to be the first step+ - name: Fetch custom actions+ uses: ababushk/checkout@dd591a6a2ac25618db4eda86e7e0d938f88cf01b # cherry_pick_retries+ timeout-minutes: 15+ with:+ sparse-checkout: |+ .github/actions+ sparse-checkout-cone-mode: false+ submodules: 'false'++ - name: Download OpenVINO artifacts (wheels)+ uses: akashchi/download-artifact@d59a9c15fec3fdb7c9adf09464124d00f9c11415 # main+ with:+ name: openvino_wheels+ path: ${{ env.INSTALL_DIR }}++ - name: Download OpenVINO artifacts (tests)+ uses: akashchi/download-artifact@d59a9c15fec3fdb7c9adf09464124d00f9c11415 # main+ with:+ name: openvino_tests+ path: ${{ env.INSTALL_DIR }}++ - name: Setup Variables+ run: |+ echo "HF_HUB_CACHE=${{ runner.os == 'Linux' && env.HF_HUB_CACHE_LIN || env.HF_HUB_CACHE_WIN }}" >> "$GITHUB_ENV"+ echo "HUGGINGFACE_HUB_CACHE=${{ runner.os == 'Linux' && env.HF_HUB_CACHE_LIN || env.HF_HUB_CACHE_WIN }}" >> "$GITHUB_ENV"+ echo "HF_TOKEN_PATH=${{ runner.os == 'Linux' && env.HF_TOKEN_PATH_LIN || env.HF_TOKEN_PATH_WIN }}" >> "$GITHUB_ENV"++ - name: Extract OpenVINO packages and tests+ run: pigz -dc openvino_tests.tar.gz | tar -xf - -v+ working-directory: ${{ env.INSTALL_DIR }}++ - name: Setup Python 3.11+ uses: ./.github/actions/setup_python+ with:+ version: '3.11'+ set-pip-install-path: 'false'+ self-hosted-runner: ${{ contains(inputs.runner, 'aks') }}+ use-pip-proxy: ${{ contains(inputs.runner, 'aks') }}++ - name: Install OpenVINO Python wheels+ uses: ./.github/actions/install_ov_wheels+ with:+ wheels-dir-path: ${{ env.INSTALL_DIR }}+ wheels-to-install: 'openvino'++ - name: Install GGUF Models tests requirements+ run: python3 -m pip install -r ${INSTALL_TEST_DIR}/requirements_gguf++ - name: GGUF Models Tests from Hugging Face+ run: |+ export PYTHONPATH=${MODEL_HUB_TESTS_INSTALL_DIR}:$PYTHONPATH+ python3 -m pytest ${MODEL_HUB_TESTS_INSTALL_DIR}/gguf/ -m ${TYPE} --html=${INSTALL_TEST_DIR}/TEST-gguf_model_"${TYPE}"_tests.html --self-contained-html -v+ env:+ TYPE: ${{ inputs.model_scope == 'precommit' && 'precommit' || 'nightly' }}+ TEST_DEVICE: CPU++ - name: Upload Test Results+ uses: ababushk/upload-artifact@ebc7d74ace101c08868aed05dba2aaf274b9a2c7 # main+ if: ${{ !cancelled() }}+ with:+ name: test-results-gguf-models-${{ inputs.model_scope }}+ path: |+ ${{ env.INSTALL_TEST_DIR }}/TEST*.html+ if-no-files-found: 'error'diff --git a/.github/workflows/linux_sanitizers.yml b/.github/workflows/linux_sanitizers.ymlindex 258618af73f..0eadda413e7 100644--- a/.github/workflows/linux_sanitizers.yml+++ b/.github/workflows/linux_sanitizers.yml@@ -194,6 +194,7 @@ jobs:-DENABLE_OV_PYTORCH_FRONTEND=ON \-DENABLE_OV_JAX_FRONTEND=ON \-DENABLE_OV_ONNX_FRONTEND=ON \+ -DENABLE_OV_GGUF_FRONTEND=ON \-DENABLE_INTEL_NPU=OFF \-DENABLE_ONEDNN_FOR_GPU=OFF \-DCMAKE_COMPILE_WARNING_AS_ERROR=OFF \@@ -220,6 +221,17 @@ jobs:cmake -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -P ${BUILD_DIR}/cmake_install.cmake --config ${{ env.CMAKE_BUILD_TYPE }}cmake -DCMAKE_INSTALL_PREFIX=${INSTALL_TEST_DIR} -DCOMPONENT=tests -P ${BUILD_DIR}/cmake_install.cmake --config ${{ env.CMAKE_BUILD_TYPE }}+ # Same generated test data as the regular Linux build (see job_build_linux.yml); running the 101+ # per-architecture conversions under the sanitizers is the highest-value place for them. The+ # generator's own llama.cpp build is not instrumented, which is fine -- only its output is used.+ - name: Generate GGUF arch fixtures+ run: |+ python3 -m pip install --no-cache-dir gguf+ python3 ${OPENVINO_REPO}/src/frontends/gguf/tests/gen_arch_fixtures.py \+ --fetch \+ --out-dir ${INSTALL_TEST_DIR}/tests/test_data/arch_fixtures \+ -j $(nproc)+- name: Remove unused files to free spacerun: rm -rf ${BUILD_DIR}/*@@ -350,6 +362,13 @@ jobs:${INSTALL_TEST_DIR}/ov_conditional_compilation_tests --gtest_print_time=1 \--gtest_output=xml:${INSTALL_TEST_DIR}/TEST-ConditionalCompilation.xml+ - name: GGUF frontend tests+ if: ${{ !cancelled() }}+ run: |+ source ${INSTALL_DIR}/setupvars.sh+ ${INSTALL_TEST_DIR}/ov_gguf_frontend_tests --gtest_print_time=1 \+ --gtest_output=xml:${INSTALL_TEST_DIR}/TEST-GGUFFrontend.xml+- name: IR frontend testsif: ${{ !cancelled() }}run: |diff --git a/.github/workflows/ubuntu_22.yml b/.github/workflows/ubuntu_22.ymlindex 263cb6c96d8..0c6b26e8a37 100644--- a/.github/workflows/ubuntu_22.yml+++ b/.github/workflows/ubuntu_22.yml@@ -132,6 +132,7 @@ jobs:build-rpm-packages: falsebuild-additional-python-packages: truebuild-samples: true+ generate-gguf-fixtures: truetarget-branch: ${{ inputs.target-branch }}cmake-options: >--G 'Ninja Multi-Config'@@ -494,6 +495,26 @@ jobs:model_scope: 'precommit'image: ${{ fromJSON(needs.docker.outputs.images).ov_test.ubuntu_22_04_x64 }}+ GGUF_Models_Tests_Precommit:+ name: GGUF Models tests+ if: ${{ github.event_name != 'schedule' && fromJSON(needs.smart_ci.outputs.affected_components).GGUF_FE.test }}+ needs: [ Docker, Build, Smart_CI ]+ uses: ./.github/workflows/job_gguf_models_tests.yml+ with:+ runner: 'aks-linux-8-cores-32gb'+ model_scope: 'precommit'+ image: ${{ fromJSON(needs.docker.outputs.images).ov_test.ubuntu_22_04_x64 }}++ GGUF_Models_Tests_Nightly:+ name: GGUF Models Nightly tests+ if: ${{ github.event_name == 'schedule' }}+ needs: [ Docker, Build, Smart_CI ]+ uses: ./.github/workflows/job_gguf_models_tests.yml+ with:+ runner: 'aks-linux-16-cores-64gb'+ model_scope: 'nightly'+ image: ${{ fromJSON(needs.docker.outputs.images).ov_test.ubuntu_22_04_x64 }}+NVIDIA_Plugin:name: NVIDIA pluginneeds: [ Docker, Build, Smart_CI ]@@ -661,7 +682,8 @@ jobs:Overall_Status:name: ci/gha_overall_statusneeds: [Smart_CI, Build, Debian_Packages, Samples, Conformance, CXX_Unit_Tests, Python_Unit_Tests, TensorFlow_Layer_Tests, Pytorch_Layer_Tests,- CPU_Functional_Tests, TensorFlow_Models_Tests_Precommit, PyTorch_Models_Tests, JAX_Models_Tests_Precommit, NVIDIA_Plugin, Openvino_tokenizers, iGPU,+ CPU_Functional_Tests, TensorFlow_Models_Tests_Precommit, PyTorch_Models_Tests, JAX_Models_Tests_Precommit, GGUF_Models_Tests_Precommit,+ NVIDIA_Plugin, Openvino_tokenizers, iGPU,Keras3_OpenVINO_Backend, iGPU_RoPE_Tests]if: ${{ always() }}runs-on: ubuntu-latestdiff --git a/.github/workflows/ubuntu_24.yml b/.github/workflows/ubuntu_24.ymlindex 7d0d36fc8d0..2ff8cd9bb1a 100644--- a/.github/workflows/ubuntu_24.yml+++ b/.github/workflows/ubuntu_24.yml@@ -110,6 +110,7 @@ jobs:build-contrib: truebuild-additional-python-packages: truebuild-samples: true+ generate-gguf-fixtures: truetarget-branch: ${{ inputs.target-branch }}cmake-options: >--G 'Ninja Multi-Config'diff --git a/src/frontends/common/src/manager.cpp b/src/frontends/common/src/manager.cppindex a97616829fb..9ea2c93d3f7 100644--- a/src/frontends/common/src/manager.cpp+++ b/src/frontends/common/src/manager.cpp@@ -19,9 +19,10 @@ using namespace ov;using namespace ov::frontend;namespace {-// Frontends for direct linkage only: loadable, but never listed by available_front_ends() nor-// auto-selected by load_by_model / load_by_framework. A manager-side list (not a plugin-info flag)-// keeps the public FrontEndPluginInfo struct / ABI unchanged.+// Hidden frontends are absent from available_front_ends() and skipped by load_by_model, so they+// are never picked up implicitly (notably by core.read_model), but stay loadable on explicit+// request via load_by_framework(). Kept manager-side to leave FrontEndPluginInfo's ABI unchanged.+// "gguf" is listed because reading GGUF through core.read_model is not supported yet.bool is_hidden_frontend(const std::string& name) {static const std::set<std::string> hidden_frontends = {"gguf"};return hidden_frontends.count(name) != 0;@@ -71,10 +72,7 @@ public:// Load plugins until we found the right onefor (auto& plugin : m_plugins) {OPENVINO_ASSERT(plugin.load(), "Cannot load frontend ", plugin.get_name_from_file());- // Hidden frontends are not selectable by name through the generic API.- if (is_hidden_frontend(plugin.get_creator().m_name)) {- continue;- }+ // Not filtered by is_hidden_frontend: asking for a frontend by name is explicit.if (plugin.get_creator().m_name == framework) {return make_frontend(plugin);}diff --git a/src/frontends/gguf/.gitignore b/src/frontends/gguf/.gitignorenew file mode 100644index 00000000000..f671f608a0a--- /dev/null+++ b/src/frontends/gguf/.gitignore@@ -0,0 +1,3 @@+# The root .gitignore's "[Bb]uild*/" rule (meant for CMake build output dirs) also matches+# the src/builder/ source directory by name. Re-include it; this is tracked source code.+!src/builderdiff --git a/src/frontends/gguf/docs/adding_an_architecture.md b/src/frontends/gguf/docs/adding_an_architecture.mdnew file mode 100644index 00000000000..ad9aadb6a4f--- /dev/null+++ b/src/frontends/gguf/docs/adding_an_architecture.md@@ -0,0 +1,153 @@+# Adding a new architecture to the GGUF frontend++The native `.gguf` path builds an OpenVINO graph from a GGUF file with **no llama.cpp+dependency**. It emits nodes in the GGML op vocabulary (`GGML_OP_MUL_MAT`, `GGML_OP_ROPE`,+`GGML_OP_FLASH_ATTN_EXT`, ...) that reproduce llama.cpp's cgraph topology, so the same op+translators (`src/op/*.cpp`) run for both the native path and the llama.cpp cgraph path.++## How the builder is laid out++`src/builder/` is layered; each layer knows strictly less than the one above it:++| File | Responsibility | Knows about |+|---|---|---|+| [`graph_emitter.hpp`](../src/builder/graph_emitter.hpp) | `add_op` / `add_input` / `add_weight` + shape & type bookkeeping | nothing about transformers |+| [`blocks/`](../src/builder/blocks) | reusable graph fragments: `common` (norm/scale/bias), `ffn` (dense/GeGLU/MoE), `attention`, `gated_delta_net`, `qkv_repack` | a decoder layer |+| [`decoder_config.hpp`](../src/builder/decoder_config.hpp) | all per-architecture detection + per-layer accessors | one model's hyperparameters |+| [`arch/decoder_builder.cpp`](../src/builder/arch/decoder_builder.cpp) | the order a decoder is assembled in | the whole decoder family |+| [`arch_registry.cpp`](../src/builder/arch_registry.cpp) | which architectures are accepted, and their RoPE mode | names only |+| [`model_kind.hpp`](../src/builder/model_kind.hpp) | which model *family* a file holds | raw metadata |+| [`gguf_builder.cpp`](../src/builder/gguf_builder.cpp) | parse → detect family → dispatch to a `ModelBuilder` | the entry point |++A single generic `DecoderBuilder` covers the whole "llama family" of decoder-only transformers.+This is deliberately **not** llama.cpp's one-file-per-architecture layout: llama.cpp needs that+because every architecture enumerates its tensors by hand, whereas this builder derives them from+the tensor table, so a same-family architecture costs zero lines of code.++## The 90% case: add a name++Most new architectures in the transformer family need **no code** — the builder auto-detects+their structure from the GGUF tensor table and metadata. To enable one, add its+`general.architecture` string to `verified_archs()` (or `experimental_archs()`) in+[`arch_registry.cpp`](../src/builder/arch_registry.cpp):++```cpp+const std::set<std::string>& experimental_archs() {+ static const std::set<std::string> archs = {+ "llama-embed", "exaone4", ...,+ "your-arch", // <-- add here+ };+ return archs;+}+```++Then check whether RoPE is NEOX (rotate-halves) or NORMAL (rotate consecutive pairs) for the+arch and, if NEOX, add it to `arch_uses_neox_rope()` in the same file (mirror+`llama_model_rope_type` in llama.cpp). That is the whole change for a same-family arch.++### What is auto-detected (no code needed)++`DecoderConfig` infers structure from the presence of layer-0 weight tensors and from metadata:++| Feature | Detected from |+|---|---|+| Per-head Q/K norm (qwen3, hunyuan) | `blk.0.attn_q_norm.weight` |+| Full-width Q/K norm (OLMoE) | `attn_q_norm.weight` width == `n_head*head_size` |+| Q/K/V projection biases (qwen2) | `blk.0.attn_q.bias` |+| Output-projection bias | `blk.0.attn_output.bias` |+| Fused QKV (phi-3, minicpm) | `blk.0.attn_qkv.weight` |+| Fused gate+up FFN (phi-3) | absence of `blk.0.ffn_gate.weight` |+| MoE routing (OLMoE, gpt-oss, qwen3moe) | `blk.<lead>.ffn_gate_exps.weight` |+| Shared experts | `expert_shared_count` metadata + `ffn_*_shexp.weight` |+| Hybrid dense-lead MoE | `leading_dense_block_count` metadata |+| RoPE freq factors (llama-3, phi-3) | `rope_freqs.weight` |+| Scalar scales (minicpm) | `embedding_scale` / `residual_scale` / `logit_scale` metadata |+| Soft-caps (gemma2/3) | `attn_logit_softcapping` / `final_logit_softcapping` metadata |+| Sliding-window attention | `attention.sliding_window(_pattern)` metadata, or sinks |+| Per-layer KV heads | `attention.head_count_kv` as an array |++All hyperparameters are read once in `decoder_config_from_meta()`+([`src/quant/gguf.cpp`](../src/quant/gguf.cpp)) and resolved once in `DecoderConfig`; the topology+builder never re-reads GGUF metadata.++## Per-layer values: use the accessors, don't inline++Architectures with per-layer variation (SWA layers, variable KV heads, per-layer head sizes)+are handled by the per-layer accessors on `DecoderConfig` — the single source of truth,+so the topology stays declarative:++- `layer_is_swa(il)` — sliding-window layer? (per-layer flag array or period)+- `layer_head_size(il)` — head size (SWA layers may differ, e.g. gemma4)+- `layer_n_head_kv(il)` — KV head count (may vary per layer)+- `layer_kq_scale(il)` — attention softmax scale (`1/sqrt(layer_head_size(il))` unless overridden)+- `layer_rope_config(il)` — RoPE config (SWA layers may use a different freq_base / n_dims)+- `is_recurrent_layer(il)` — linear-attention (GDN) layer of a hybrid stack++If a new arch adds a per-layer dimension, extend these accessors rather than adding a new+inline ternary in `build_layer()`.++## The 10% case: structurally novel architectures need code++The generic decoder builder assumes the standard block: `norm -> QKV -> RoPE -> attention ->+norm -> FFN/MoE -> residual`. Architectures that break this shape need a new detected flag on+`DecoderConfig` plus a branch in the relevant block. Examples of what required code in the past:++- **MoE routing** — `blocks::moe_ffn()` (`MUL_MAT_ID` lowering, top-k, gated activation).+- **gpt-oss** — attention sinks (5th `FLASH_ATTN_EXT` input), OAI gated activation+ (`GGML_GLU_OP_SWIGLU_OAI`), softmax-after-topk gating.+- **gemma2/3** — post-attention / post-FFN norms, attention & final-logit soft-caps.+- **gemma4** — per-layer input embeddings, shared-KV layers, per-op RoPE (SWA vs global differ).+- **qwen35** — a hybrid stack where 3 of every 4 layers are a Gated DeltaNet block+ (`blocks::gated_delta_net()`) instead of attention. It returns the same thing the attention+ block returns — the sublayer output before the residual — so the shared FFN tail is reused.++To add such a feature:+1. Add a detection line in `DecoderConfig`'s constructor (prefer weight-presence over an+ arch-name check — it generalizes to future archs; only fall back to `arch == "..."` when the+ tensor table is genuinely ambiguous, e.g. GeGLU-vs-SwiGLU).+2. Add the emission behind that flag in the relevant `blocks/` function, or in+ `DecoderBuilder::build_layer()` when it is about the ORDER of sublayers rather than their+ contents.+3. Add the op translator in `src/op/` if the feature needs a GGML op not yet handled, and+ register it in `op_table.cpp`.++## Adding a new model FAMILY (mmproj, audio, encoder-decoder)++An architecture is data; a **family** is code. A family is a distinct graph shape with its own+inputs and its own notion of a layer — a vision/mmproj encoder and an audio encoder are each one,+and neither is a causal decoder. Do **not** add flags to `DecoderConfig` for them.++Instead:++1. Detect it in [`model_kind.cpp`](../src/builder/model_kind.cpp). mmproj files set+ `general.architecture = "clip"` and carry `clip.has_vision_encoder` / `clip.has_audio_encoder`+ (llama.cpp `tools/mtmd/clip-impl.h`), so `detect_model_kind()` already classifies them; the+ check runs *before* any decoder hyperparameter is read, because those keys do not exist there.+2. Add a metadata reader next to `decoder_config_from_meta()` for that family's key layout, and a+ config struct next to `DecoderConfig`.+3. Subclass [`ModelBuilder`](../src/builder/model_builder.hpp) in `arch/`, reusing `GraphEmitter`+ and `blocks/common`. A ViT needs its own attention — non-causal, no KV cache, no RoPE — so it+ will not reuse `blocks::attention`; this is the same split llama.cpp makes between+ `llm_graph_context` and `clip_graph`.+4. Add a branch in `build_ggml_graph_from_gguf()`.++Nothing in the decoder family changes.++The downstream side already tolerates a non-decoder graph: `TranslateSession`'s LLM-specific+preprocessing is self-gating (`add_rope_sin_cos` only fires when `inp_pos` exists,+`add_sliced_mask` only when the mask and `token_len_per_seq` inputs exist), and the LLM-specific+passes (`MakeStateful`, `AdaptToGenAI`) are caller-registered rather than built in.++## Verifying a new architecture++1. **Converts + compiles**: convert through the frontend, then `core.compile_model(m, "CPU")`.+ The frontend is not auto-selectable, so ask for it by name:+ `fe = FrontEndManager().load_by_framework("gguf"); m = fe.convert(fe.load("model.gguf"))`.+2. **Graph is sane**: check the op-type histogram — attention should collapse to a single SDPA op+ and MoE routing to a single grouped-matmul op, not a long chain of primitives.+3. **Numerics**: run generation through OpenVINO GenAI (`greedy_causal_lm model.gguf "..."`) and+ compare to native llama.cpp (`build-ref/bin/llama-cli`) on the same prompt — the greedy tokens+ should match (small drift after ~dozens of tokens is expected from kernel differences).+4. **No graph regression** for existing archs: `tests/test_arch_conversion.cpp` converts every+ architecture fixture and asserts a pinned `(op count, input count)` fingerprint, so any+ restructuring of a supported architecture shows up there.diff --git a/src/frontends/gguf/docs/how_to_add_op.md b/src/frontends/gguf/docs/how_to_add_op.mdnew file mode 100644index 00000000000..8f5f0c87fa4--- /dev/null+++ b/src/frontends/gguf/docs/how_to_add_op.md@@ -0,0 +1,175 @@+# Adding an op translator to the GGUF frontend++Procedure for enabling a ggml operation. For the *concepts* behind it — the two decoder paths, the+`GGML_OP_NONE` weight convention, `op_case` numbering, the memory model — read+`frontend_design.md` first; this document does not repeat them.++Related: [adding_an_architecture.md](adding_an_architecture.md) (enabling a model family, which+usually needs *no* new op), [debugging_accuracy.md](debugging_accuracy.md) (when a translator+converts but produces wrong numbers).++## Before writing a translator++Check that an op translator is actually what is missing:++- **A new architecture** normally needs only an entry in `arch_registry.cpp` — see+ [adding_an_architecture.md](adding_an_architecture.md). Reach for a translator only when the graph+ genuinely contains a ggml op the table does not have.+- **A structurally different use of an existing op** is an `op_case`, not a new translator. Read the+ `op_case` section of `frontend_design.md` before adding a case — a case that+ exists only to mean "this came from the builder" is a defect.+- Both decoder paths (native builder and llama.cpp cgraph) share translator bodies, so a change here+ affects both. Keep the body path-agnostic; branch on `op_case`, never on "which decoder made this".++## Checklist++| # | File | Change |+|---|------|--------|+| 1 | `src/op/<name>.cpp` | New translator function |+| 2 | [`src/op_table.hpp`](../src/op_table.hpp) | `GGUF_OP_CONVERTER(translate_<name>);` declaration |+| 3 | [`src/op_table.cpp`](../src/op_table.cpp) | `{"GGML_OP_<NAME>", op::translate_<name>},` (list is alphabetical) |+| 4 | [`tests/CMakeLists.txt`](../tests/CMakeLists.txt) | Add `"${FE_SRC_DIR}/op/<name>.cpp"` to `FRONTEND_SRCS` |+| 5 | [`tests/test_ops.cpp`](../tests/test_ops.cpp) | `TEST(GGUFOps, <Name>)` — **mandatory**, see the coverage gate below |++> **Step 4 is mandatory and easy to miss.** `src/CMakeLists.txt` builds the library via+> `ov_add_frontend`, which picks up new sources automatically — but the test binary compiles the+> frontend sources from an **explicit list with no GLOB**. Omitting this yields an undefined symbol+> at link time, after a full compile.++If the op maps 1:1 onto a single OpenVINO op with the same operand order, skip steps 1, 2 and 4 and+register a template from [`src/utils.hpp`](../src/utils.hpp) directly in `op_table.cpp`:++```cpp+{"GGML_OP_SUB", op::translate_1to1_match_2_inputs<v1::Subtract>},+{"GGML_UNARY_OP_TANH", op::translate_1to1_match_1_input<v0::Tanh>},+```++## Translator shape++```cpp+OutputVector translate_<name>(const NodeContext& context) {+ num_inputs_check(context, 1, 2); // min / max operand count++ float eps = context.get_attribute<float>("eps");+ int op_case = context.get_op_case();++ std::shared_ptr<ov::Node> res = ...;++ return rename_outputs_with_suffix({res}, context.get_name());+}+```++Always finish with `rename_outputs_with_suffix(..., context.get_name())`: the walk stores results in+the `TensorMap` under the decoder's output names, and stable friendly names are what the passes and+the graph-fingerprint gate rely on.++`NodeContext` ([`src/node_context.hpp`](../src/node_context.hpp)):++| Call | Purpose |+|------|---------|+| `get_input(idx)` / `get_input(name)` | Operand as `Output<Node>` |+| `has_input(name)` | Test an optional operand first |+| `get_input_size()` | Actual operand count |+| `get_input_shape(idx)` / `get_output_shape()` | **Static ggml** shape — use when the live OV shape is dynamic (KV-cache path) |+| `get_input_view_element_offset(idx)` | Element (not byte) offset for a ggml VIEW operand |+| `get_op_case()` | Structural variant (convenience wrapper, defaults to 0) |+| `get_output_type()` | Declared output element type |+| `get_attribute<T>(name[, default])` | Any other typed op parameter |++Helpers in [`src/utils.hpp`](../src/utils.hpp): `num_inputs_check`, `get_dimensions`,+`rename_outputs_with_suffix`, `make_sin_cos` (RoPE), `process_view_input`.++Insert a `Convert` to `get_output_type()` when the op may change element type (`CONCAT`, `CPY`,+`SET_ROWS`, `GET_ROWS`) rather than assuming the input type. Prefer `ov::op::vX::OpName` over+`opsetX::OpName`, per the repository convention.++## Test, and the coverage gate++[`tests/test_op_coverage.cpp`](../tests/test_op_coverage.cpp) asserts that **every op registered in+`op_table.cpp` is exercised by some test**. Registering a translator without a test fails the suite;+the gate exists because `GGML_UNARY_OP_GELU_QUICK` once shipped with the wrong formula precisely+because nothing converted it. The exemption list is for ops whose *nature* makes a single-op test+meaningless — not for ops that are merely awkward to test.++The gate only asserts when the full suite runs, so a narrowing `--gtest_filter` silently skips it.+**Run the binary unfiltered before pushing.**++```cpp+TEST(GGUFOps, Scale) {+ auto model = SingleOpBuilder()+ .op("GGML_OP_SCALE")+ .input("x", ov::element::f32, {2, 4})+ .output("out", ov::element::f32, {2, 4})+ .attr<float>("scale", 2.5f)+ .attr<float>("bias", 1.0f)+ .build();++ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, 4}, x)}});+ expect_near(out, expected);+}+```++`SingleOpBuilder` drives the real `FrontEnd::convert` through an in-memory `SingleOpDecoder`, so no+`.gguf` file is involved. Helpers are in [`op_test_utils.hpp`](../tests/op_test_utils.hpp).++**Where the expected values come from matters more than the test's shape.** Per the one rule in+[debugging_accuracy.md](debugging_accuracy.md), the reference must come from real ggml, not from+your own reading of the op's math:++- Simple elementwise ops with an unambiguous closed form — compute inline in the test.+- Anything with layout, geometry or head structure (rope, conv, attention, views) — generate the+ reference from ggml-CPU: an `.npy` fixture via `gen_ggml_reference.c`,+ or a standalone oracle such as `ssm_conv_oracle.c` / `imrope_oracle.c`, and paste its output with a+ comment naming the oracle.++Test at realistic dimensions. With one head many layout orders coincide, so a single-head test can+pass against a wrong reference.++`expect_near(actual, expected, atol = 1e-4f, rtol = 2e-3f)` combines absolute and relative+tolerance. **Do not tighten `rtol`**: ARM CPU runs the graph in fp16 by default, and a tolerance+tuned only on fp32 x86 will fail there.++To find the closest existing example without reading the whole (large) file:++```bash+grep -n "^TEST(" src/frontends/gguf/tests/test_ops.cpp+```++## Build and run++The frontend is **off by default** (`ENABLE_OV_GGUF_FRONTEND` in+[`cmake/features.cmake`](../../../../cmake/features.cmake)); without it the test target does not+exist.++```bash+cmake -B build -DENABLE_OV_GGUF_FRONTEND=ON -DENABLE_TESTS=ON+cmake --build build --target ov_gguf_frontend_tests -j$(nproc)++# iterate on one op ...+./build/bin/*/*/ov_gguf_frontend_tests --gtest_filter='GGUFOps.<Name>*'+# ... then unfiltered, so the coverage gate actually runs+./build/bin/*/*/ov_gguf_frontend_tests+```++CI runs the same binary in the "GGUF frontend tests" step of+[`job_cxx_unit_tests.yml`](../../../../.github/workflows/job_cxx_unit_tests.yml), ungated by Smart CI.++For a change that touches a shared translator or a VIEW/`op_case` predicate, also re-run the+graph-fingerprint check ([`tests/graph_fingerprint.py`](../tests/graph_fingerprint.py)) across the+supported architectures: a guard that fixes one arch can reject another's legitimately-contiguous+view.++## Bringing up a model that hits a missing op++Conversion aborts on the **first** unsupported op with:++```+Translation for operation type GGML_OP_<NAME> is not implemented.+```++Enabling one op per run is the slow path. Instead diff the model's op vocabulary against the keys of+`get_supported_ops()` to get the full set at once, group the ops that collapse into+`translate_1to1_match_*` one-liners, and implement only the remainder as real translators.++A different error, `Number of <op> outputs greater than number of converted outputs`, means the+translator returned the wrong number of outputs — not that the op is unsupported.diff --git a/src/frontends/gguf/docs/supported_models.md b/src/frontends/gguf/docs/supported_models.mdindex 6e9bddc14c3..fa3132d62d0 100644--- a/src/frontends/gguf/docs/supported_models.md+++ b/src/frontends/gguf/docs/supported_models.md@@ -44,6 +44,148 @@ A run counts as verification only when the output is coherent (e.g. completes"...is Paris") and consistent with the pure-ggml CPU backend on the same prompt. A modelthat loads but emits garbage (e.g. `hunyuan`) is **not** counted as supported.+## Architectures accepted by the native `.gguf` builder++Everything above is about the **llama.cpp cgraph** path. This section covers the *other*+decoder — the native `.gguf` builder (`DecoderBuilder` in+[`src/builder/arch/decoder_builder.cpp`](../src/builder/arch/decoder_builder.cpp)), which is what+OpenVINO GenAI uses. The two paths share all op+translators but have separate architecture lists.++The builder's accept-list is the union of two sets, both defined in+[`src/builder/arch_registry.cpp`](../src/builder/arch_registry.cpp):++- **`verified_archs()`** — convert + compile + generation checked against a reference on a+ real checkpoint.+- **`experimental_archs()`** — expected to work via the builder's GGUF-tensor-table+ auto-detection, but not end-to-end verified. These convert and emit a one-time+ `OPENVINO_WARN` so callers know they are best-effort.++Anything not in either set is rejected with an explicit `OPENVINO_ASSERT` at load time+rather than converting into a silently wrong graph.++### `verified_archs()` — 10 architectures++| Architecture | Notes |+|---|---|+| `llama` | llama-2 / llama-3 |+| `qwen2` | qwen2 / qwen2.5 |+| `qwen3` | QK-norm |+| `phi3` | fused QKV |+| `minicpm` | NORMAL rope + scalar embedding/residual/logit scales |+| `olmoe` | OLMoE 1B-7B (MoE) |+| `qwen35` | Qwen3.5/3.6 (and the Ternary-Bonsai backbone): hybrid Gated-DeltaNet + full attention, M-RoPE, interleaved query+gate projection. Greedy / batch 1 only |+| `gpt-oss` | MoE + attention sinks + SWA + OAI gated activation |+| `gemma3` | post-norms + final logit soft-cap |+| `gemma4` | SWA, per-layer embeddings, shared KV |++### `experimental_archs()` — 20 architectures++| Architecture | Notes |+|---|---|+| `llama-embed` | Bidirectional LLaMA (embedding model, no causal mask) |+| `exaone4` | EXAONE 4.0: NEOX rope, post-norms (attn + ffn) |+| `plamo3` | PLaMo-3: NEOX rope, post-norms (attn + ffn) |+| `smollm3` | SmolLM3: NORMAL rope + SWA |+| `hunyuan-moe` | NEOX rope, MoE routing, QK-norm |+| `glm4moe` | GLM 4.5 MoE: 1 dense lead layer, MoE + attn post-norm |+| `exaone-moe` | EXAONE MoE: SWA + MoE, shared expert |+| `minimax-m2` | Minimax M2: pure MoE |+| `ernie4_5-moe` | Ernie 4.5 MoE: NORMAL rope, dense lead layers + MoE stride |+| `bailingmoe2` | BailingMoe V2: MoE + shared expert + QK-norm |+| `maincoder` | Maincoder-1B: NORMAL rope, QK-norm (auto-detected) |+| `mistral3` | Ministral-3B: NORMAL rope, dense |+| `muse-glimmer` | Muse Glimmer (Meta Onyx): NORMAL rope on SWA layers only (global layers are NoPE), sigmoid attention output gate, QK-norm, pre+post norms, final logit soft-cap |+| `mellum` | JetBrains Mellum: pure MoE |+| `deepseek2-ocr` | DeepSeekOCR: dense lead layers + MoE |+| `jais2` | JAIS-2: dense (biases auto-detected) |+| `hunyuan-dense` | Demoted from `verified_archs()`: degenerate output through the builder (see below) |+| `qwen3moe` | Qwen3 MoE; same topology as `olmoe`. Demoted: degenerate output through the builder |+| `gemma` | Gemma 2B / 7B. Demoted: throws through the builder (see below) |+| `gemma2` | post-norms + attention soft-cap. Demoted: degenerate output through the builder |++RoPE flavor is **not** in these tables because it is a separate switch: archs listed in+`arch_uses_neox_rope()` use NEOX (rotate-halves), everything else uses NORMAL (rotate+consecutive pairs). Adding an arch to the accept-list without also classifying its RoPE is+the most common way to get a model that loads and produces garbage.++### Measured status through OpenVINO GenAI++Every architecture above was run through GenAI on CPU (`gguf_arch_check`, greedy, SDPA+backend) on the checkpoint named below. "Generates" means the model answered *"The capital+of France is"* correctly and coherently; **`llama.cpp` ref** is the same `.gguf` through+`llama-cli` on the default ggml CPU backend, which distinguishes a frontend bug from a+model/checkpoint that is simply weak on the prompt.++| Arch | Set | Model used | GenAI | llama.cpp ref |+|---|---|---|---|---|+| `llama` | verified | Llama-3.2-1B-Instruct Q4_K_M | generates | generates |+| `qwen2` | verified | Qwen2.5-0.5B-Instruct Q4_K_M | generates | generates |+| `qwen3` | verified | Qwen3-0.6B Q8_0 | generates (reasoning preamble) | same |+| `phi3` | verified | Phi-3-mini-4k-instruct Q4 | generates | generates |+| `minicpm` | verified | MiniCPM-2B-dpo Q4_K_M | generates | generates |+| `hunyuan-dense` | experimental | Hunyuan-0.5B-Instruct Q4_K_M | **degenerate** | generates |+| `olmoe` | verified | OLMoE-1B-7B-Instruct Q4_K_M | generates | generates |+| `qwen3moe` | experimental | Qwen3-0.9B-A0.6B Q4_K_M | **degenerate** | generates |+| `gpt-oss` | verified | gpt-oss-20b MXFP4 | generates (harmony format) | same |+| `gemma` | experimental | gemma-2b Q4_K_M | **throws** (SDPA shape mismatch) | degenerate too |+| `gemma2` | experimental | gemma-2-2b-it Q4_K_M | **degenerate** | generates |+| `gemma3` | verified | gemma-3-1b-it Q4_K_M | generates | generates |+| `gemma4` | verified | gemma-4-E4B-it Q4_K_M | generates | generates |+| `llama-embed` | experimental | llama-nemotron-embed-1b-v2 Q4_K_M | repeats (embedding model) | degenerate too |+| `exaone4` | experimental | EXAONE-4.0-1.2B Q4_K_M | **degenerate** | generates |+| `plamo3` | experimental | plamo-3-nict-2b-base Q4_K_M | **degenerate** | degenerate too |+| `smollm3` | experimental | SmolLM3-3B Q4_K_M | generates (reasoning preamble) | same |+| `maincoder` | experimental | Maincoder-1B Q4_K_M | generates | generates |+| `mistral3` | experimental | Ministral-3-3B-Instruct-2512 Q4_K_M | generates | generates |+| `muse-glimmer` | experimental | Muse-Glimmer-30B Q4_0 | generates | generates |+| `qwen35` | verified | Qwen3.5-0.8B Q8_0 | generates | generates |+| `qwen35` (Bonsai) | verified | Ternary-Bonsai-27B Q2_g64 | generates | generates |+| `deepseek2-ocr` | experimental | deepseek-ocr-2 Q4_K_M | generates | generates |+| `ernie4_5-moe` | experimental | ERNIE-4.5-21B-A3B Q4_K_M | **degenerate** (blank) | generates |+| `bailingmoe2` | experimental | Ling-mini-2.0 Q2_K | generates | generates |+| `mellum` | experimental | Mellum2-12B-A2.5B-Instruct Q4_K_M | generates | generates |+| `hunyuan-moe` | experimental | — | not tested (no checkpoint) | — |+| `glm4moe` | experimental | — | not tested (smallest GLM-4.5-Air ≈ 40 GiB) | — |+| `exaone-moe` | experimental | — | not tested (smallest ≈ 9 GiB, 32B) | — |+| `minimax-m2` | experimental | — | not tested (smallest ≈ 78 GiB) | — |+| `jais2` | experimental | — | not tested (no checkpoint) | — |++Two caveats on reading this table. `llama-embed` is an *embedding* model, so degenerate+greedy completion is expected of it, not a defect. `gemma` (v1 base) and `plamo3` (base, not+instruct) are degenerate on the reference too, so those rows are checkpoint/prompt artifacts+rather than frontend bugs.++That leaves **5 architectures that generate correctly under llama.cpp but not through the+builder** — `hunyuan-dense`, `qwen3moe`, `gemma2`, `exaone4` and `ernie4_5-moe` (blank output) —+i.e. real conversion defects, plus `gemma`, which throws instead of converting cleanly.+`hunyuan-dense`, `qwen3moe`, `gemma2` and `gemma` were previously misclassified as+`verified_archs()`; they have been moved to `experimental_archs()` (and now emit the one-time+`OPENVINO_WARN`) until the underlying defects are fixed and re-verified.++**`qwen35` is greedy / batch-1 only.** The recurrent conv and delta states are a single+static-shaped block with no batch axis, and `MakeStateful` does not reorder them by `beam_idx` the+way it reorders a KV cache. Beam search or batch > 1 therefore **fails at inference** with a shape+mismatch on the conv window's `Concat` — it does not silently mix state across beams, so no wrong+output can be produced. Prefix caching and PagedAttention are unavailable for the same reason: a+recurrent state cannot be re-derived from a cached prefix, and cannot be paged. Verified+token-for-token against llama.cpp on two real checkpoints (Qwen3.5-0.8B Q8_0, Ternary-Bonsai-27B+Q2_g64), with final-logits agreement within 1.0% / 0.12% of llama.cpp — in line with the noise+already present on the *verified* `qwen3` arch through the same harness.++A packaging gotcha worth knowing: **`Ternary-Bonsai-27B-Q2_0.gguf` is not upstream `Q2_0`** — it+does not load in llama.cpp either. It's packed **g128** (one f16 scale per 128 weights) while+`GGML_TYPE_Q2_0` is **g64** (18 bytes per 64 weights); use `Ternary-Bonsai-27B-Q2_g64.gguf`+instead. The frontend rejects the mispacked file safely (`data runs past EOF`) rather than+dequantizing garbage.++`muse-glimmer`'s row was decided by the *tokenizer*, not the graph: the converted graph reproduces+llama.cpp token-for-token, but GenAI's GGUF tokenizer builder only honored+`tokenizer.ggml.add_bos_token` on the SentencePiece path, silently dropping the leading BOS on the+BPE (`gpt2`) path that this (BOS-sensitive) model uses. Same gap affected `llama3`/`mistral3` the+same way; fixed in `gguf_tokenizer.cpp` by emitting BOS/EOS as a `CombineSegments` segment on every+tokenizer path.+## Adding a new architectureSupport for a new architecture is a combination of:@@ -53,3 +195,9 @@ Support for a new architecture is a combination of:the weight path (`src/quant/weights.cpp`).3. **Real-model verification** — run a real `.gguf` end-to-end as above before adding thearchitecture to the Supported table.++For the native builder specifically, see+[`adding_an_architecture.md`](adding_an_architecture.md) — for a same-family arch the change+is usually just adding the name to `experimental_archs()` plus the `arch_uses_neox_rope()`+classification, and promotion to `verified_archs()` should require the GenAI-vs-llama.cpp+comparison above.diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/adapt_to_genai.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/adapt_to_genai.hppnew file mode 100644index 00000000000..ca53c581678--- /dev/null+++ b/src/frontends/gguf/include/openvino/frontend/gguf/adapt_to_genai.hpp@@ -0,0 +1,65 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/frontend/gguf/visibility.hpp"+#include "openvino/pass/pass.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace pass {++/// \brief Rewrite a GGUF-frontend model's llama.cpp-style IO into the OpenVINO GenAI+/// LLMPipeline IO contract, so the model can be driven by genai's stateful pipeline.+///+/// The GGUF frontend emits a stateful decoder with the gguf IO contract:+/// inputs : inp_tokens [1,1,1,D] i32, inp_pos [1,1,1,D] i32, inp_out_ids [1,1,1,D] i32,+/// self_kq_mask [1,1,D,D] f32 (+ self_kq_mask_swa for gpt-oss SWA),+/// token_len_per_seq [1] i64, plus beam_idx [D] i32 from the make-stateful pass+/// output : logits [1,1,seq,vocab]+///+/// genai's StatefulLLMPipeline instead feeds:+/// inputs : input_ids [b,seq] i64, attention_mask [b,kv_len] i64,+/// position_ids [b,seq] i64, beam_idx [b] i32+/// output : logits [b,seq,vocab]+///+/// This pass prepends a subgraph deriving the gguf inputs from the genai ones, rewires the gguf+/// Parameters to it, and reshapes the logits to [b,seq,vocab]. The model must already be stateful:+/// the KV-cache sinks are preserved, and beam_idx (created by the make-stateful pass) passes+/// through unchanged since genai sets that tensor itself.+///+/// If the required gguf inputs are absent (e.g. the model is already in genai form), the+/// pass is a no-op and returns false.+///+/// LAYOUT POLYMORPHISM (why the leading dims are derived, never pinned).+/// The result must be valid under both attention backends, which disagree about where the token+/// count lives: plain SDPA feeds input_ids as [1, tokens], while ov::pass::SDPAToPagedAttention+/// rewrites it to rank-1 [tokens] and unsqueezes, so the body sees [tokens, 1]. Both are the same+/// buffer -- ggml's layout is [batch, tokens, heads, head_size] with batch == 1 -- so one graph+/// serves both PROVIDED no node pins the leading two dims. Hence deriving them from the live+/// input_ids here, and reshaping with special_zero in the translators. No backend flag needed.+class GGUF_FRONTEND_API AdaptToGenAI : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ov::frontend::gguf::pass::AdaptToGenAI");++ /// \brief Which genai input contract to expose.+ /// IdsToLogits : input_ids -> logits (text LLMPipeline). The only mode implemented today.+ /// EmbedsToLogits: inputs_embeds -> logits (reserved for the VLM language model, where+ /// image+text embeddings are merged outside the graph). Not yet implemented.+ enum class InputMode { IdsToLogits, EmbedsToLogits };++ explicit AdaptToGenAI(InputMode mode = InputMode::IdsToLogits) : m_mode(mode) {}++ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;++private:+ InputMode m_mode;+};++} // namespace pass+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hppindex f9bbad9f59d..35e2146bd3c 100644--- a/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp+++ b/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp@@ -129,6 +129,29 @@ public:return empty_node_map();}+ // GGUF tokenizer metadata (the file's `tokenizer.*` keys), attached to the converted model's+ // rt_info so a downstream consumer (OpenVINO GenAI) can build the tokenizer without reopening+ // the .gguf. Empty when the decoder carries no tokenizer metadata.+ virtual const ov::AnyMap& get_tokenizer_config() const {+ static const ov::AnyMap empty;+ return empty;+ }++ // Recurrent states, as {input name, output name} pairs: a linear-attention architecture+ // (qwen35's Gated DeltaNet) carries a conv window and a delta matrix per recurrent layer,+ // which the stateless graph exposes as a Parameter read at the start of a step and a Result+ // holding its value at the end.+ //+ // These are NOT KV caches. A cache grows along a token axis and is written by SET_ROWS, so+ // MakeStateful can find it by walking those writes and appending with a Concat; a recurrent+ // state has no token axis and is overwritten wholesale, so nothing in the graph marks it.+ // Hence this explicit pairing rather than a name convention: the decoder is the only thing+ // that knows which Result feeds which Parameter back.+ virtual const std::vector<std::pair<std::string, std::string>>& get_recurrent_states() const {+ static const std::vector<std::pair<std::string, std::string>> 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/make_stateful.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/make_stateful.hppindex 0619bcab32b..26fc1467f9c 100644--- a/src/frontends/gguf/include/openvino/frontend/gguf/make_stateful.hpp+++ b/src/frontends/gguf/include/openvino/frontend/gguf/make_stateful.hpp@@ -13,6 +13,58 @@namespace ov::frontend::gguf::pass {+/// \brief Turn the frontend's stateless GGUF model into an OpenVINO stateful one.+///+/// The frontend always converts to a STATELESS graph -- every KV cache is a Parameter written by a+/// SetRows placeholder and read back as a Result -- mirroring how optimum-intel exports. Being+/// stateful is a caller concern, so register this as a DecoderTransformationExtension:+///+/// ov::frontend::gguf::FrontEnd fe;+/// fe.add_extension(std::make_shared<ov::frontend::DecoderTransformationExtension>(+/// ov::frontend::gguf::pass::GGUFMakeStateful()));+/// auto model = fe.convert(fe.load(decoder_or_gguf_path));+///+/// Extensions run ahead of the built-in LowerSetRowsStateless, so this pass claims the KV-cache+/// SetRows ops and the default stateless lowering only sees the rest (e.g. MoE routing writes).+///+/// Per KV cache it replaces the Parameter/Result pair with a Variable + ReadValue(empty init) ++/// Gather(beam_idx) + Concat(past, this step's rows) + Assign. Only a SetRows writing to a model+/// Parameter is converted.+///+/// Two details that are load-bearing rather than cosmetic:+/// - `beam_idx` is ADDED here, not taken from the decoder: ggml has no counterpart, so declaring+/// it in a decoder would leave a consumer-less input on the stateless graph.+/// - the ReadValue init must be empty: CPU's stateful_sdpa_fusion folds the cache into+/// ScaledDotProductAttentionWithKVCache, whose MemoryInputSDPA aborts on zero parent edges.+///+/// Scope: this grows the cache and deliberately does not touch the attention mask. The native+/// builder emits a dynamically sized mask, which needs no change; a graph that preallocates a+/// fixed mask window must be re-sliced by the caller, as the llama.cpp backend does.+/// Key under which the frontend records the model's recurrent (overwritten, non-appending) states+/// in rt_info, as a flat list of alternating {input name, output name}. Linear-attention+/// architectures (qwen35's Gated DeltaNet) carry a conv window and a delta matrix per recurrent+/// layer. Unlike a KV cache these have no token axis and no SetRows write marking them in the+/// graph, so the pairing has to be carried explicitly; see GgufDecoder::get_recurrent_states.+GGUF_FRONTEND_API const std::string& gguf_recurrent_states_key();++/// LIMITATION -- recurrent states are batch-1 and are NOT reordered by beam_idx. Unlike a KV+/// cache, which this pass gathers by beam_idx before appending, a recurrent state is a single+/// static-shaped block with no batch axis to reorder. Beam search or batch > 1 therefore fails at+/// inference with a shape mismatch on the state's Concat rather than silently mixing state across+/// beams; greedy, batch-1 generation is the supported mode for a linear-attention architecture.+///+/// Key under which the frontend records that the model uses interleaved M-RoPE (qwen35 /+/// qwen3vl). Such a model expects inp_pos to carry FOUR position sections per token, so a consumer+/// feeding it plain per-token positions (as OpenVINO GenAI does) has to expand them first.+GGUF_FRONTEND_API const std::string& gguf_imrope_key();++/// Key under which the frontend records the model's sliding-window length in tokens (int64_t),+/// when the GGUF metadata carries an explicit value. Recorded so AdaptToGenAI can build a+/// correctly windowed self_kq_mask_swa (rather than reusing the full causal mask) without+/// re-reading the .gguf file. Absent from rt_info when the model has no SWA, or its SWA is+/// described only by sinks / a per-layer boolean pattern with no accompanying token count.+GGUF_FRONTEND_API const std::string& gguf_swa_window_key();+class GGUF_FRONTEND_API GGUFMakeStateful : public ov::pass::ModelPass {public:OPENVINO_MODEL_PASS_RTTI("gguf::GGUFMakeStateful");diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/tokenizer_metadata.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/tokenizer_metadata.hppnew file mode 100644index 00000000000..7c1b9c7af8d--- /dev/null+++ b/src/frontends/gguf/include/openvino/frontend/gguf/tokenizer_metadata.hpp@@ -0,0 +1,58 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/core/any.hpp"+#include "openvino/core/runtime_attribute.hpp"+#include "openvino/frontend/gguf/visibility.hpp"++namespace ov {+namespace frontend {+namespace gguf {++/// \brief Carries the GGUF tokenizer metadata (the `tokenizer.*` ggml keys) on a converted+/// model's runtime info, so a downstream consumer (e.g. OpenVINO GenAI) can build the+/// OpenVINO tokenizer/detokenizer without re-opening the .gguf file.+///+/// The payload is an ov::AnyMap keyed by the tokenizer metadata sub-key (the part after the+/// last dot of `tokenizer.ggml.*` / `tokenizer.chat_template`, e.g. "model", "tokens",+/// "merges", "scores", "token_type", "pre", "bos_token_id", "eos_token_id", "chat_template").+/// Each value holds exactly one of:+/// - std::string (e.g. "model" = "gpt2"/"llama"/"gemma4", "pre", "chat_template")+/// - std::vector<std::string> (e.g. "tokens", "merges")+/// - ov::Tensor (arrays like "scores"/"token_type", and scalars such as+/// "*_token_id" stored as a shape-{} tensor)+/// which mirrors the GGUF metadata variant both the frontend and GenAI already use.+///+/// This attribute is intentionally **non-serializable**: it is heavy (full vocab + merges) and+/// only meaningful in-memory between conversion and tokenizer construction. `is_copyable()`+/// returns false so it is dropped on clone, and `to_string()` is empty so that if the model is+/// serialized the IR writer emits an empty placeholder the deserializer ignores rather than+/// dumping the vocab into the XML.+class GGUF_FRONTEND_API GGUFTokenizerMetadata : public ov::RuntimeAttribute {+public:+ OPENVINO_RTTI("gguf_tokenizer_metadata", "0", ov::RuntimeAttribute);++ GGUFTokenizerMetadata() = default;+ explicit GGUFTokenizerMetadata(ov::AnyMap config) : config(std::move(config)) {}++ bool is_copyable() const override {+ return false;+ }++ std::string to_string() const override {+ return {};+ }++ /// tokenizer sub-key -> value (string / vector<string> / Tensor)+ ov::AnyMap config;+};++/// Runtime-info key under which GGUFTokenizerMetadata is stored on the model.+GGUF_FRONTEND_API const std::string& gguf_tokenizer_metadata_key();++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/CMakeLists.txt b/src/frontends/gguf/src/CMakeLists.txtindex 9b515ea667c..fd8c994233e 100644--- a/src/frontends/gguf/src/CMakeLists.txt+++ b/src/frontends/gguf/src/CMakeLists.txt@@ -2,9 +2,13 @@# SPDX-License-Identifier: Apache-2.0#-# LINKABLE_FRONTEND (no SKIP_INSTALL): installs the library + headers alongside the other-# frontends so a direct linker -- the llama.cpp ggml-openvino backend -- can link-# openvino::frontend::gguf and feed it a live GgufDecoder.+# The GGUF frontend converts GGUF models to OpenVINO. It installs the library + headers alongside+# the other frontends (LINKABLE_FRONTEND, no SKIP_INSTALL) so direct linkers -- the llama.cpp+# ggml-openvino backend and OpenVINO GenAI -- can link openvino::frontend::gguf, and it is+# discoverable via FrontEndManager so core.read_model("model.gguf") selects it by the .gguf+# extension + GGUF magic (see supported_impl / get_front_end_data in frontend.cpp). Two ingest+# paths converge on the same op translators: a live GgufDecoder (cgraph path) and a native+# .gguf-file builder.ov_add_frontend(NAME ggufLINKABLE_FRONTENDFILEDESCRIPTION "FrontEnd to convert GGUF models"diff --git a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp b/src/frontends/gguf/src/builder/arch/decoder_builder.cppnew file mode 100644index 00000000000..bbaa0f90cfc--- /dev/null+++ b/src/frontends/gguf/src/builder/arch/decoder_builder.cpp@@ -0,0 +1,412 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Topology of the causal decoder family, in the GGML op vocabulary.+//+// Ground truth for the shape of the graph: llama.cpp src/models/{llama,qwen2,qwen3,phi3,minicpm,+// hunyuan-*,gemma*,gpt-oss,olmoe,qwen35}.cpp and the build_norm / build_qkv / build_attn /+// build_attn_mha / build_ffn expansions in src/llama-graph.cpp, plus the KV-cache cpy_k/get_k+// (SET_ROWS + VIEW) in src/llama-kv-cache.cpp. Op-case values follow+// ggml-decoder.cpp::compute_op_case.+//+// Everything architecture-specific has already been resolved into DecoderConfig, and every+// repeated fragment lives in blocks/, so this file is only the ORDER in which a decoder is+// assembled: inputs -> embeddings -> N x (norm, attention|GDN, norm, FFN|MoE) -> norm -> lm_head.++#include "builder/arch/decoder_builder.hpp"++#include <cmath>++#include "builder/blocks/common.hpp"+#include "builder/blocks/ffn.hpp"+#include "builder/blocks/gated_delta_net.hpp"+#include "openvino/op/parameter.hpp"++namespace ov {+namespace frontend {+namespace gguf {++using ov::element::f32;+using ov::element::i32;+using ov::element::i64;++namespace {+// Dynamic token length, used for model-input Parameters only.+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, gguf_tensor_type>& qtypes)+ : m_cfg(config, weights),+ m_emit(weights, qtypes, m_cfg.arch),+ m_kv(blocks::KvCachePlan::build(m_cfg)) {+ 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;+}++void DecoderBuilder::build_inputs() {+ // Names match the cgraph decoder's get_graph_input_ov_name; gguf uses i32 for token/position/+ // index inputs.+ m_emit.add_input("inp_tokens", i32, ps({1, 1, 1, D}));+ m_emit.add_input("inp_pos", i32, ps({1, 1, 1, D}));+ m_emit.add_input("inp_out_ids", i32, ps({1, 1, 1, D}));+ m_emit.add_input("self_kq_mask", f32, ps({1, 1, D, D}));+ // gpt-oss alternates sliding-window / full attention; the windowed mask is a separate+ // input. Only added when the model uses SWA.+ if (m_cfg.has_swa) {+ m_emit.add_input("self_kq_mask_swa", f32, ps({1, 1, D, D}));+ }+ // No beam_idx here. It is a beam-search cache-reorder index for an OpenVINO STATEFUL cache,+ // which ggml has no equivalent of -- so the cgraph decoder does not produce one either, and a+ // builder that declared it would give the two decoders different stateless IO. The pass that+ // creates the state creates it (MakeStateful), because that is where its only consumer, the+ // Gather on the past, is emitted.++ // KV-cache update index (consumed by SET_ROWS; unused in the stateful Concat branch).+ m_emit.add_input("inp_kv_idx", i32, ps({1, 1, 1, D}));+ m_emit.set_tensor_meta("inp_kv_idx", ps({1, 1, 1, T}), i32);++ // token_len_per_seq: number of new tokens per sequence; used by TranslateSession's mask+ // slicing (add_sliced_mask) to build KQ_mask_sliced. An extra (Parameter) input.+ auto p = std::make_shared<ov::op::v0::Parameter>(i64, ps({1}));+ p->set_friendly_name("token_len_per_seq");+ p->output(0).set_names({"token_len_per_seq"});+ m_emit.add_extra_input_node("token_len_per_seq", p);+}++std::string DecoderBuilder::build_embeddings() {+ // GET_ROWS(token_embd.weight, inp_tokens) -> "embd"+ m_emit.add_weight("token_embd.weight");+ m_emit.set_tensor_meta("inp_tokens", ps({1, 1, 1, T}), i32);+ std::string cur = m_emit.add_op("GGML_OP_GET_ROWS",+ "embd",+ {"token_embd.weight", "inp_tokens"},+ ps({1, 1, T, m_cfg.n_embd}),+ f32);+ // MiniCPM scales the embeddings by a constant.+ if (m_cfg.embedding_scale != 1.0f) {+ cur = blocks::scale(m_emit, cur, m_cfg.embedding_scale, "embd_scaled");+ }+ // muse-glimmer normalizes the token embeddings with a WEIGHTLESS RMSNorm before layer 0+ // (build_norm with a null weight -> plain ggml_rms_norm, no multiplicative term).+ if (m_cfg.scaleless_embd_norm) {+ cur = m_emit.add_op("GGML_OP_RMS_NORM",+ "embd_normed",+ {cur},+ m_emit.shape_of_tensor(cur),+ f32,+ 0,+ {{"eps", m_cfg.rms_eps}});+ }+ return cur;+}++void DecoderBuilder::build_per_layer_embeddings(const std::string& embd) {+ // Gemma4: per-layer token embeddings are built before the layer loop and stored as a+ // 4D tensor "per_layer_embd" of shape [n_layer, T, n_embd_per_layer] (ggml logical order).+ // Inside each layer the VIEW op extracts the il-th slice [1, T, n_embd_per_layer].+ // The projection norm is applied per-slice (over the n_embd_per_layer dim).+ //+ // Topology (mirrors llama.cpp build_inp_per_layer + project_per_layer_inputs):+ // pe_tok = GET_ROWS(per_layer_token_embd, inp_tokens) -> [1, n_layer, T, n_embd_per_layer]+ // scaled by sqrt(n_embd_per_layer)+ // pe_proj = MUL_MAT(per_layer_model_proj, cur_embd) -> [1, n_layer, T, n_embd_per_layer]+ // scaled by 1/sqrt(n_embd) + RMS_NORM(per_layer_proj_norm)+ // per_layer_embd = (pe_proj + pe_tok) * 1/sqrt(2) -> [1, n_layer, T, n_embd_per_layer]+ const int n_layer = m_cfg.n_layer;+ const int pe = m_cfg.n_embd_per_layer;++ // Turn a flat per-token per-layer embedding [1, 1, T, n_layer * pe] into the layer-major+ // [1, n_layer, T, pe] the per-layer VIEW slices from.+ //+ // The data is contiguous as [T, n_layer, pe] (one row per token), so this is a reshape that+ // splits the last axis followed by a transpose of the two middle axes -- a single reshape+ // straight to the target would be wrong for T > 1. Emitted as the same two steps ggml uses+ // (ggml_reshape_3d, then ggml_cont(ggml_permute)), so both reach the shared op cases: RESHAPE+ // case 1 splits the last dim into [.., n_layer, pe] and PERMUTE case 1 is the {0,2,1,3}+ // transpose. Fusing them into one node would need a builder-only case for the transpose. No+ // CONT node: translate_cont's PERMUTE case is a pass-through, since translate_permute already+ // emitted a real Transpose, so ggml's ggml_cont would convert to nothing here.+ auto reshape_to_layer_major = [&](const std::string& flat, const std::string& name) {+ const auto& flat_shape = m_emit.shape_of_tensor(flat);+ const int64_t t = flat_shape[2].is_static() ? flat_shape[2].get_length() : 1;+ auto split = m_emit.add_op("GGML_OP_RESHAPE", name + "_split", {flat}, ps({1, t, n_layer, pe}), f32, 1);+ return m_emit.add_op("GGML_OP_PERMUTE", name, {split}, ps({1, n_layer, t, pe}), f32, 1);+ };++ m_emit.add_weight("per_layer_token_embd.weight");+ m_emit.add_weight("per_layer_model_proj.weight");+ m_emit.add_weight("per_layer_proj_norm.weight");+ const int pe_total = pe * n_layer;++ // Token embedding lookup: [1,1,T, pe_total] -> reshape to [1, n_layer, T, pe]+ auto pe_flat = m_emit.add_op("GGML_OP_GET_ROWS",+ "pe_tok_flat",+ {"per_layer_token_embd.weight", "inp_tokens"},+ ps({1, 1, T, pe_total}),+ f32);+ const float pe_scale = std::sqrt(static_cast<float>(pe));+ pe_flat = blocks::scale(m_emit, pe_flat, pe_scale, "pe_tok_flat_scaled");+ auto pe_tok = reshape_to_layer_major(pe_flat, "pe_tok");++ // Model projection: MUL_MAT(per_layer_model_proj, embd) -> [1,1,T, pe_total]+ // per_layer_model_proj is [n_embd, pe_total] -> output [pe_total] per token+ auto proj_flat = m_emit.add_op("GGML_OP_MUL_MAT",+ "pe_proj_flat",+ {"per_layer_model_proj.weight", embd},+ ps({1, 1, T, pe_total}),+ f32);+ const float proj_scale = 1.0f / std::sqrt(static_cast<float>(m_cfg.n_embd));+ proj_flat = blocks::scale(m_emit, proj_flat, proj_scale, "pe_proj_flat_scaled");++ // Reshape to [1, n_layer, T, pe] for per-slice RMS_NORM+ auto proj_4d = reshape_to_layer_major(proj_flat, "pe_proj_4d");++ // RMS_NORM + per_layer_proj_norm weight (applied over last dim = pe)+ auto proj_norm = m_emit.add_op("GGML_OP_RMS_NORM",+ "pe_proj_rms",+ {proj_4d},+ ps({1, n_layer, T, pe}),+ f32,+ 0,+ {{"eps", m_cfg.rms_eps}});+ m_emit.set_tensor_meta("per_layer_proj_norm.weight", ps({1, 1, 1, pe}), f32);+ auto proj_normed = m_emit.add_op("GGML_OP_MUL",+ "pe_proj_normed",+ {proj_norm, "per_layer_proj_norm.weight"},+ ps({1, n_layer, T, pe}),+ f32);++ // Sum token embd + projection, scale by 1/sqrt(2)+ auto pe_sum = m_emit.add_op("GGML_OP_ADD", "pe_sum", {proj_normed, pe_tok}, ps({1, n_layer, T, pe}), f32);+ const float inv_sqrt2 = 1.0f / std::sqrt(2.0f);+ m_emit.add_op("GGML_OP_SCALE",+ "per_layer_embd",+ {pe_sum},+ ps({1, n_layer, T, pe}),+ f32,+ 0,+ {{"scale", inv_sqrt2}, {"bias", 0.0f}});+}++std::string DecoderBuilder::inject_per_layer_embedding(int il, const std::string& cur, const std::string& inpSA) {+ // Gemma4: each layer takes a slice of the pre-projected per-layer embedding (shape+ // [1,1,T,n_embd_per_layer]), gates it through inp_gate.weight (GELU), multiplies by the+ // per-layer slice, projects back to n_embd, post-norms, then adds residual.+ // per_layer_token_embd (global) is pre-projected before the loop.+ const std::string p = "blk." + std::to_string(il) + ".";+ const int pe = m_cfg.n_embd_per_layer;++ // Slice out this layer's [1,1,T,pe] chunk (dim 1 at index il). The second input is passed+ // purely as a shape reference: per_layer_embd is stored layer-major, so the slice's token axis+ // does not necessarily sit where the layer activation keeps its own, and the ops below combine+ // the two elementwise. See the op_case 104 note in op/view.cpp.+ //+ // It has to be a tensor that still carries every token. At the last layer `cur` has already+ // been filtered down to the output rows by the GET_ROWS in the attention tail, while+ // per_layer_embd always holds all T of them, so using `cur` there would ask op_case 104 to+ // reinterpret T*D values into 1*D. Use the layer's unfiltered input instead and let the+ // GET_ROWS below do the filtering.+ const std::string& pl_shape_ref = (il == m_cfg.n_layer - 1) ? inpSA : cur;+ const std::string pl_slice = p + "per_layer_slice";+ m_emit.add_op("GGML_OP_VIEW",+ pl_slice,+ {"per_layer_embd", pl_shape_ref},+ ps({1, 1, T, pe}),+ f32,+ 104, // layer-index slice using the "layer_idx" attribute+ {{"layer_idx", int64_t(il)}});++ // At the last layer, cur is already filtered to 1 token via inp_out_ids. Mirror llama.cpp+ // gemma4.cpp:347-349: also filter pl_slice so the MUL doesn't broadcast it back to the full+ // sequence length.+ std::string pl_slice_used = pl_slice;+ if (il == m_cfg.n_layer - 1) {+ pl_slice_used = p + "per_layer_slice_sel";+ m_emit.add_op("GGML_OP_GET_ROWS", pl_slice_used, {pl_slice, "inp_out_ids"}, ps({1, 1, T, pe}), f32);+ }++ // gate: cur -> inp_gate.weight -> GELU -> [1,1,T,pe]+ m_emit.add_weight(p + "inp_gate.weight");+ auto gated =+ m_emit.add_op("GGML_OP_MUL_MAT", p + "inp_gate_mm", {p + "inp_gate.weight", cur}, ps({1, 1, T, pe}), f32);+ gated = m_emit.add_op("GGML_UNARY_OP_GELU", p + "inp_gate_gelu", {gated}, ps({1, 1, T, pe}), f32);++ // elementwise multiply by per-layer slice+ auto mul_pe = m_emit.add_op("GGML_OP_MUL", p + "pe_mul", {gated, pl_slice_used}, ps({1, 1, T, pe}), f32);++ // project back to n_embd+ m_emit.add_weight(p + "proj.weight");+ auto pe_proj =+ m_emit.add_op("GGML_OP_MUL_MAT", p + "pe_proj", {p + "proj.weight", mul_pe}, ps({1, 1, T, m_cfg.n_embd}), f32);++ // post-norm + residual add+ pe_proj = blocks::rms_norm(m_emit, pe_proj, p + "post_norm.weight", p + "pe_post_norm", m_cfg.rms_eps);+ return m_emit.add_op("GGML_OP_ADD", p + "pe_out", {cur, pe_proj}, ps({1, 1, T, m_cfg.n_embd}), f32);+}++std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {+ const std::string p = "blk." + std::to_string(il) + ".";+ const std::string inpSA = layer_in;+ std::string cur = layer_in;++ // eps for the post-attention / post-FFN norms; 0 in the config means "reuse rms_eps"+ // (muse-glimmer's post-norms use a tighter 1e-8 than its pre-norms).+ const float post_eps = m_cfg.post_norm_eps > 0.0f ? m_cfg.post_norm_eps : m_cfg.rms_eps;++ // attn_norm (key varies by arch: "attn_norm.weight" for most, "post_attention_norm.weight"+ // for exaone4)+ const std::string attn_norm =+ blocks::rms_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)) {+ // 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, T);+ std::string sa = inpSA;+ std::string ao = gdn_out;+ if (il == m_cfg.n_layer - 1) {+ ao = m_emit.add_op("GGML_OP_GET_ROWS",+ p + "attn_out_g",+ {gdn_out, "inp_out_ids"},+ ps({1, 1, T, m_cfg.n_embd}),+ f32);+ sa = m_emit.add_op("GGML_OP_GET_ROWS",+ p + "inpSA_g",+ {inpSA, "inp_out_ids"},+ ps({1, 1, T, m_cfg.n_embd}),+ f32);+ }+ auto ffn_inp_r = m_emit.add_op("GGML_OP_ADD", p + "ffn_inp", {ao, sa}, ps({1, 1, T, m_cfg.n_embd}), f32);+ 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);+ // 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+ // would assert.+ const bool is_moe_layer_r = m_cfg.is_moe && (il >= m_cfg.n_dense_lead);+ auto down_r = is_moe_layer_r ? blocks::moe_ffn(m_emit, m_cfg, p, ffn_norm_r, T)+ : m_cfg.is_geglu ? blocks::geglu_ffn(m_emit, m_cfg, p, ffn_norm_r, T)+ : blocks::dense_ffn(m_emit, m_cfg, p, ffn_norm_r, T);+ return m_emit.add_op("GGML_OP_ADD", p + "l_out", {down_r, ffn_inp_r}, ps({1, 1, T, m_cfg.n_embd}), f32);+ }++ std::string attn_out = blocks::attention(m_emit, m_cfg, m_kv, il, attn_norm, T);++ // MiniCPM scales the attention sublayer output before the residual add.+ if (m_cfg.residual_scale != 1.0f) {+ attn_out = blocks::scale(m_emit, attn_out, m_cfg.residual_scale, p + "attn_out_scaled");+ }+ std::string sa = inpSA;+ std::string ao = attn_out;+ if (il == m_cfg.n_layer - 1) {+ ao = m_emit.add_op("GGML_OP_GET_ROWS",+ p + "attn_out_g",+ {attn_out, "inp_out_ids"},+ ps({1, 1, T, m_cfg.n_embd}),+ f32);+ sa = m_emit.add_op("GGML_OP_GET_ROWS", p + "inpSA_g", {inpSA, "inp_out_ids"}, ps({1, 1, T, m_cfg.n_embd}), f32);+ }+ // Gemma2: post-attention RMSNorm applied to the sublayer output before residual add.+ // Applied after GET_ROWS so the selected-token path matches gemma2.cpp's order.+ if (m_cfg.has_attn_post_norm) {+ ao = blocks::rms_norm(m_emit, ao, p + "post_attention_norm.weight", p + "attn_post_norm", post_eps);+ }++ auto ffn_inp = m_emit.add_op("GGML_OP_ADD", p + "ffn_inp", {ao, sa}, ps({1, 1, T, m_cfg.n_embd}), f32);++ // Pre-FFN/MoE norm. Key varies by arch (ffn_norm_key is resolved in DecoderConfig).+ auto ffn_norm = blocks::rms_norm(m_emit, ffn_inp, p + m_cfg.ffn_norm_key, p + "ffn_norm", m_cfg.rms_eps);++ // Hybrid MoE: lead layers (il < n_dense_lead) are always dense regardless of is_moe.+ const bool is_moe_layer = m_cfg.is_moe && (il >= m_cfg.n_dense_lead);+ std::string down = is_moe_layer ? blocks::moe_ffn(m_emit, m_cfg, p, ffn_norm, T)+ : m_cfg.is_geglu ? blocks::geglu_ffn(m_emit, m_cfg, p, ffn_norm, T)+ : blocks::dense_ffn(m_emit, m_cfg, p, ffn_norm, T);+ // MiniCPM scales the FFN sublayer output before the residual add.+ if (m_cfg.residual_scale != 1.0f) {+ down = blocks::scale(m_emit, down, m_cfg.residual_scale, p + "ffn_out_scaled");+ }+ // Gemma2: post-FFN RMSNorm applied to the FFN output before residual add.+ if (m_cfg.has_ffn_post_norm) {+ down = blocks::rms_norm(m_emit, down, p + "post_ffw_norm.weight", p + "ffn_post_norm", post_eps);+ }++ cur = m_emit.add_op("GGML_OP_ADD", p + "l_out", {down, ffn_inp}, ps({1, 1, T, m_cfg.n_embd}), f32);++ if (m_cfg.n_embd_per_layer > 0) {+ cur = inject_per_layer_embedding(il, cur, inpSA);+ }++ // Gemma4: per-layer output scale (layer_output_scale.weight is a scalar [1]).+ if (m_emit.has_weight(p + "layer_output_scale.weight")) {+ m_emit.add_named_weight(p + "layer_output_scale.weight");+ cur = m_emit.add_op("GGML_OP_MUL",+ p + "scaled_out",+ {cur, p + "layer_output_scale.weight"},+ m_emit.shape_of_tensor(cur),+ f32);+ }+ return cur;+}++std::string DecoderBuilder::build_head(const std::string& in) {+ // final norm + lm_head+ std::string cur = blocks::rms_norm(m_emit, in, "output_norm.weight", "result_norm", m_cfg.rms_eps);++ const std::string lm_head_w = m_emit.has_weight("output.weight") ? "output.weight" : "token_embd.weight";+ m_emit.add_weight(lm_head_w);+ const int n_vocab = static_cast<int>(m_emit.weight_tensor(lm_head_w).get_shape()[0]); // rows = vocab+ auto logits = m_emit.add_op("GGML_OP_MUL_MAT", "result_output", {lm_head_w, cur}, ps({1, 1, T, n_vocab}), f32);+ // MiniCPM scales the logits (1/(n_embd/dim_model_base)).+ if (m_cfg.logit_scale != 1.0f) {+ logits = blocks::scale(m_emit, logits, m_cfg.logit_scale, "result_output_scaled");+ }+ // Gemma2/Gemma3 final logit soft-cap: tanh(logits / cap) * cap.+ if (m_cfg.final_logit_soft_cap != 0.0f) {+ logits = blocks::scale(m_emit, logits, 1.0f / m_cfg.final_logit_soft_cap, "logits_softcap_scaled");+ logits =+ m_emit.add_op("GGML_UNARY_OP_TANH", "logits_softcap_tanh", {logits}, m_emit.shape_of_tensor(logits), f32);+ logits = blocks::scale(m_emit, logits, m_cfg.final_logit_soft_cap, "result_output_softcapped");+ }+ return logits;+}++std::shared_ptr<GgufGraph> DecoderBuilder::build() {+ build_inputs();++ std::string cur = build_embeddings();++ // rope freq factors (llama-3 long context, phi-3): an optional 3rd ROPE input.+ if (m_cfg.has_rope_freqs) {+ m_emit.add_weight("rope_freqs.weight");+ }++ // kq_scale, head size, KV heads and rope config are all computed per-layer inside the loop+ // via the DecoderConfig accessors, so SWA and global layers each get the correct+ // head-size-dependent values (e.g. gemma4 SWA layers use head_size_swa).++ if (m_cfg.n_embd_per_layer > 0) {+ build_per_layer_embeddings(cur);+ }++ for (int il = 0; il < m_cfg.n_layer; ++il) {+ cur = build_layer(il, cur);+ }++ const std::string logits = build_head(cur);++ // logits is the primary output; the cache_k/v_l* outputs (appended per layer above)+ // become Assign sinks via MakeStateful.+ auto graph = m_emit.graph();+ graph->model_output_names.insert(graph->model_output_names.begin(), logits);+ return graph;+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/arch/decoder_builder.hpp b/src/frontends/gguf/src/builder/arch/decoder_builder.hppnew file mode 100644index 00000000000..018c8a96b95--- /dev/null+++ b/src/frontends/gguf/src/builder/arch/decoder_builder.hpp@@ -0,0 +1,75 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <map>+#include <memory>+#include <string>+#include <unordered_map>++#include "builder/blocks/attention.hpp"+#include "builder/decoder_config.hpp"+#include "builder/graph_emitter.hpp"+#include "builder/model_builder.hpp"+#include "quant/gguf.hpp"++namespace ov {+namespace frontend {+namespace 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.+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, gguf_tensor_type>& qtypes);++ std::shared_ptr<GgufGraph> build() override;++private:+ // Model inputs shared by every layer (tokens, positions, masks, KV update index).+ void build_inputs();++ // Token embedding lookup plus the optional embedding scale / weightless norm.+ std::string build_embeddings();++ // gemma4: the per-layer input embeddings, pre-projected once before the layer loop.+ void build_per_layer_embeddings(const std::string& embd);++ // One decoder layer; `cur` is the layer input, returns the layer output.+ std::string build_layer(int il, const std::string& cur);++ // gemma4: per-layer embedding injection appended after the FFN residual.+ std::string inject_per_layer_embedding(int il, const std::string& cur, const std::string& inpSA);++ // Final norm, lm_head, and the optional logit scale / soft-cap.+ std::string build_head(const std::string& cur);++ DecoderConfig m_cfg;+ GraphEmitter m_emit;+ blocks::KvCachePlan m_kv;++ // Per-node output shapes are STATIC, like the cgraph decoder (which builds the graph for a+ // concrete token length). We use a representative token length T; the translators emit dynamic+ // reshapes (-1 / 0) where needed, and MakeStateful + the dynamic input Parameters carry the+ // real dynamic-ness. T affects only the per-node shape metadata.+ static constexpr int64_t T = 1;+};++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/arch_registry.cpp b/src/frontends/gguf/src/builder/arch_registry.cppnew file mode 100644index 00000000000..d213b97d692--- /dev/null+++ b/src/frontends/gguf/src/builder/arch_registry.cpp@@ -0,0 +1,97 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// The native builder's architecture accept list, and the one per-architecture property that+// cannot be derived from the GGUF tensor table (the RoPE mode).+//+// Adding a same-family architecture is a one-line change here and nothing else: the decoder+// builder derives everything else -- QK-norm, biases, fused QKV, MoE routing, SWA, soft-caps --+// from the tensor table and metadata. See docs/adding_an_architecture.md.++#include "arch_registry.hpp"++namespace ov {+namespace frontend {+namespace gguf {++bool arch_uses_neox_rope(const std::string& arch) {+ return arch == "qwen2" || arch == "qwen3" || arch == "phi3" || arch == "hunyuan-dense" || arch == "gpt-oss" ||+ arch == "gemma" || arch == "gemma2" || arch == "gemma3" || arch == "gemma4" || arch == "olmoe" ||+ // H2 2025 dense additions+ arch == "exaone4" || arch == "plamo3" || arch == "mellum" ||+ // H2 2025 MoE additions+ arch == "hunyuan-moe" || arch == "glm4moe" || arch == "bailingmoe2" || arch == "exaone-moe" ||+ arch == "minimax-m2" ||+ // H2 2025 VL backbone / other+ arch == "jais2" || arch == "deepseek2-ocr";+}++const std::set<std::string>& verified_archs() {+ static const std::set<std::string> archs = {+ "llama", // llama-2 / llama-3+ "qwen2", // qwen2 / qwen2.5+ "qwen3",+ "phi3", // phi-3 (fused QKV)+ "minicpm", // NORMAL rope + scalar scales+ "olmoe", // OLMoE 1B-7B (MoE)+ // Qwen3.5/3.6 hybrid: Gated-DeltaNet linear attention on 3 of every 4 layers, full+ // attention with M-RoPE and an interleaved query+gate projection on the rest. Verified+ // token-exact against llama.cpp on Qwen3.5-0.8B-Q8_0 and Ternary-Bonsai-27B-Q2_g64.+ // GREEDY / BATCH 1 ONLY: the recurrent conv and delta states are not reordered by+ // beam_idx and have a static batch of 1, so beam search or batch > 1 fails at inference+ // (a Concat shape mismatch on the conv window) rather than producing wrong output.+ "qwen35",+ "gpt-oss", // MoE + sinks + SWA+ "gemma3", // Gemma 3: post-norms + final logit soft-cap+ "gemma4", // Gemma 4: SWA, per-layer embeddings, shared KV+ };+ return archs;+}++const std::set<std::string>& experimental_archs() {+ static const std::set<std::string> archs = {+ // H2 2025: dense+ "llama-embed", // Bidirectional LLaMA (embedding, no causal mask)+ "exaone4", // EXAONE 4.0: NEOX rope, post-norms (attn+ffn)+ "plamo3", // PLaMo-3: NEOX rope, post-norms (attn+ffn)+ "smollm3", // SmolLM3: NORMAL rope + SWA+ // H2 2025: MoE+ "hunyuan-moe", // Hunyuan MoE: NEOX rope, MoE routing, QK-norm+ "glm4moe", // GLM 4.5 MoE: NEOX rope, 1 dense lead layer, MoE + attn post-norm+ "exaone-moe", // EXAONE MoE: NEOX rope, SWA + MoE, shared expert+ "minimax-m2", // Minimax M2: NEOX rope, pure MoE+ "ernie4_5-moe", // Ernie 4.5 MoE: NORMAL rope, dense lead layers + MoE stride+ "bailingmoe2", // BailingMoe V2: NEOX rope, MoE + shared expert + QK-norm+ // 2026: dense+ "maincoder", // Maincoder-1B: NORMAL rope, QK-norm (auto-detected)+ "mistral3", // Ministral-3B: NORMAL rope, dense+ "muse-glimmer", // Muse Glimmer (Meta Onyx): NORMAL rope on SWA layers only (global+ // layers are NoPE), sigmoid attention output gate, QK-norm,+ // pre+post norms, final logit soft-cap+ // 2026: MoE+ "mellum", // JetBrains Mellum: NEOX rope, pure MoE+ "deepseek2-ocr", // DeepSeekOCR: NEOX rope, dense lead layers + MoE+ "jais2", // JAIS-2: NEOX rope, dense (biases auto-detected)+ // Demoted from verified_archs(): the GenAI-vs-llama.cpp measured status (see+ // docs/supported_models.md) found these produce degenerate output (or, for `gemma`,+ // throw) through the native builder despite passing conversion. Re-promote once fixed.+ "hunyuan-dense",+ "qwen3moe", // Qwen3 MoE: same topology as olmoe+ "gemma", // Gemma 2B / 7B+ "gemma2", // Gemma 2: post-norms + attention soft-cap+ };+ return archs;+}++const std::set<std::string>& supported_archs() {+ static const std::set<std::string> archs = [] {+ std::set<std::string> a = verified_archs();+ a.insert(experimental_archs().begin(), experimental_archs().end());+ return a;+ }();+ return archs;+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/arch_registry.hpp b/src/frontends/gguf/src/builder/arch_registry.hppnew file mode 100644index 00000000000..59edd3ef231--- /dev/null+++ b/src/frontends/gguf/src/builder/arch_registry.hpp@@ -0,0 +1,41 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <set>+#include <string>++namespace ov {+namespace frontend {+namespace gguf {++// gguf ROPE op-case (see ggml-decoder.cpp::compute_op_case). The high 16 bits encode the+// mode: NORMAL=0 (llama/minicpm: rotate consecutive pairs), NEOX=1 (qwen/phi/hunyuan:+// rotate halves). The input is not a VIEW here so the low bits stay 0.+constexpr int ROPE_OP_CASE_NORMAL = 0x00000000;+constexpr int ROPE_OP_CASE_NEOX = 0x00010000;+// IMROPE=2: interleaved multimodal rope (qwen35 / qwen3vl). inp_pos carries 4 mrope sections.+constexpr int ROPE_OP_CASE_IMROPE = 0x00020000;++// Architectures whose rope is NEOX (rotate-halves); everything else in the supported set+// uses NORMAL (rotate consecutive pairs). Mirrors llama_model_rope_type.+bool arch_uses_neox_rope(const std::string& arch);++// Architectures END-TO-END VERIFIED on the generic decoder builder: convert + compile + generation+// checked against the reference (native llama.cpp / HF) on a real checkpoint. Safe to rely on.+const std::set<std::string>& verified_archs();++// Architectures EXPECTED to work via the generic builder's GGUF-tensor-table auto-detection, but+// NOT yet end-to-end verified on a real checkpoint. Enabled (they convert), but conversion emits a+// one-time warning so callers know they are best-effort. Promote to verified_archs() once a model+// of the family has been checked against the reference. See docs/adding_an_architecture.md.+const std::set<std::string>& experimental_archs();++// All architectures the native builder accepts = verified + experimental.+const std::set<std::string>& supported_archs();++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/blocks/attention.cpp b/src/frontends/gguf/src/builder/blocks/attention.cppnew file mode 100644index 00000000000..9fc7aacd331--- /dev/null+++ b/src/frontends/gguf/src/builder/blocks/attention.cpp@@ -0,0 +1,303 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "builder/blocks/attention.hpp"++#include <map>+#include <vector>++#include "builder/blocks/common.hpp"+#include "builder/blocks/qkv_repack.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace blocks {++using ov::element::f32;++namespace {+// Dynamic token length, used for model-input Parameters only.+constexpr int64_t D = -1;+} // namespace++KvCachePlan KvCachePlan::build(const DecoderConfig& cfg) {+ KvCachePlan plan;+ plan.n_own_kv = cfg.n_layer - cfg.shared_kv_layers;+ if (cfg.shared_kv_layers > 0) {+ for (int i = plan.n_own_kv - 1; i >= 0; --i) {+ const bool i_is_swa = cfg.layer_is_swa(i);+ if (plan.anchor_swa < 0 && i_is_swa)+ plan.anchor_swa = i;+ if (plan.anchor_global < 0 && !i_is_swa)+ plan.anchor_global = i;+ if (plan.anchor_swa >= 0 && plan.anchor_global >= 0)+ break;+ }+ }+ return plan;+}++std::string attention(GraphEmitter& e,+ const DecoderConfig& cfg,+ const KvCachePlan& kv,+ int il,+ const std::string& attn_norm,+ int64_t T) {+ const std::string p = "blk." + std::to_string(il) + ".";+ auto& graph = *e.graph();++ // Per-layer hyperparameters (SWA vs global head size / rope / scale; per-layer KV heads).+ // See the DecoderConfig accessors for the arch-specific derivation rules.+ 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 float kq_scale = cfg.layer_kq_scale(il);+ const RopeConfig rope_config_l = cfg.layer_rope_config(il);++ // 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);+ e.add_weight(p + "attn_k.weight");+ e.add_weight(p + "attn_v.weight");+ } else if (cfg.has_fused_qkv) {+ register_fused_qkv(e, cfg, il);+ } else {+ e.add_weight(p + "attn_q.weight");+ e.add_weight(p + "attn_k.weight");+ // MQA tie-V: some global attention layers (e.g. gemma4-12B every 6th layer) have+ // head_count_kv==1 and no separate attn_v.weight; V shares K's weight tensor.+ if (e.has_weight(p + "attn_v.weight")) {+ e.add_weight(p + "attn_v.weight");+ } else {+ // MQA tie-V: emit a separate attn_v.weight GGML_OP_NONE leaf that reuses K's+ // extracted tensors, so attn_v.weight resolves in the tensor map like any weight.+ e.add_weight_from(p + "attn_v.weight", p + "attn_k");+ }+ }+ auto q = e.add_op("GGML_OP_MUL_MAT",+ p + "Qcur",+ {p + "attn_q.weight", attn_norm},+ ps({1, 1, T, head_size_l * cfg.n_head}),+ f32);+ auto k = e.add_op("GGML_OP_MUL_MAT",+ p + "Kcur",+ {p + "attn_k.weight", attn_norm},+ ps({1, 1, T, head_size_l * n_head_kv_l}),+ f32);+ auto v = e.add_op("GGML_OP_MUL_MAT",+ p + "Vcur",+ {p + "attn_v.weight", attn_norm},+ ps({1, 1, T, head_size_l * n_head_kv_l}),+ f32);++ // Q/K/V projection biases (qwen2 / qwen2.5: separate attn_{q,k,v}.bias; phi-3-style+ // fused-QKV archs: attn_qkv.bias, already split into attn_{q,k,v}.bias by+ // register_fused_qkv above).+ if (cfg.has_qkv_bias) {+ q = add_bias(e, q, p + "attn_q.bias", p + "Qcur_b");+ k = add_bias(e, k, p + "attn_k.bias", p + "Kcur_b");+ v = add_bias(e, v, p + "attn_v.bias", p + "Vcur_b");+ }++ // Full-width q/k norm (OLMoE): normalize the whole projection before splitting heads.+ if (cfg.has_qk_norm && cfg.qk_norm_full) {+ q = rms_norm(e, q, p + "attn_q_norm.weight", p + "Qcur_normed", cfg.rms_eps);+ k = rms_norm(e, k, p + "attn_k_norm.weight", p + "Kcur_normed", cfg.rms_eps);+ }++ // reshape Q/K/V to [1, n_tokens, n_head(_kv), head_size]+ q = e.add_op("GGML_OP_RESHAPE", p + "Qcur_r", {q}, ps({1, T, cfg.n_head, head_size_l}), f32, 1);+ k = e.add_op("GGML_OP_RESHAPE", p + "Kcur_r", {k}, ps({1, T, n_head_kv_l, head_size_l}), f32, 1);+ v = e.add_op("GGML_OP_RESHAPE", p + "Vcur_r", {v}, ps({1, T, n_head_kv_l, head_size_l}), f32, 1);++ // per-head q_norm / k_norm (qwen3, hunyuan, gemma4)+ if (cfg.has_qk_norm && !cfg.qk_norm_full) {+ q = rms_norm(e, q, p + "attn_q_norm.weight", p + "Qcur_normed", cfg.rms_eps);+ k = rms_norm(e, k, p + "attn_k_norm.weight", p + "Kcur_normed", cfg.rms_eps);+ }+ // gemma4: V gets a plain RMSNorm (no multiplicative weight, just normalize).+ if (cfg.has_v_norm) {+ v = e.add_op("GGML_OP_RMS_NORM",+ p + "Vcur_normed",+ {v},+ ps({1, T, n_head_kv_l, head_size_l}),+ f32,+ 0,+ {{"eps", cfg.rms_eps}});+ }++ // RoPE (NEOX). rope_freqs.weight (per-dim frequency factor) is an optional 3rd input.+ // For gemma4: global layers use rope_freqs (proportional/NTK scaling), SWA layers don't.+ // muse-glimmer ropes ONLY its sliding-window layers; its global layers are NoPE+ // (llama.cpp muse-glimmer.cpp: `const bool use_rope = hparams.is_swa(il)`).+ const bool use_rope = !cfg.rope_on_swa_only || is_swa_layer;+ const bool use_rope_freqs = cfg.has_rope_freqs && !is_swa_layer;+ const std::vector<std::string> q_rope_in = use_rope_freqs+ ? std::vector<std::string>{q, "inp_pos", "rope_freqs.weight"}+ : std::vector<std::string>{q, "inp_pos"};+ const std::vector<std::string> k_rope_in = use_rope_freqs+ ? std::vector<std::string>{k, "inp_pos", "rope_freqs.weight"}+ : std::vector<std::string>{k, "inp_pos"};+ if (use_rope) {+ q = e.add_op("GGML_OP_ROPE",+ p + "Qcur_rope",+ q_rope_in,+ ps({1, T, cfg.n_head, head_size_l}),+ f32,+ cfg.rope_op_case,+ {{"rope_config", rope_config_l}});+ k = e.add_op("GGML_OP_ROPE",+ p + "Kcur_rope",+ k_rope_in,+ ps({1, T, n_head_kv_l, head_size_l}),+ f32,+ cfg.rope_op_case,+ {{"rope_config", rope_config_l}});+ }++ // ---- KV cache store ----+ // Gemma4: layers with shared_kv_layers have no K/V of their own; they reuse the KV+ // from the last layer of the same SWA type that has its own KV cache. SWA layers+ // reuse the last own-KV SWA layer; global layers reuse the last own-KV global layer.+ const bool has_own_kv = (cfg.shared_kv_layers == 0) || (il < kv.n_own_kv);+ int anchor_il = il;+ if (!has_own_kv) {+ anchor_il = is_swa_layer ? kv.anchor_swa : kv.anchor_global;+ if (anchor_il < 0)+ anchor_il = kv.n_own_kv - 1; // fallback+ }+ const std::string kc = "cache_k_l" + std::to_string(anchor_il);+ const std::string vc = "cache_v_l" + std::to_string(anchor_il);++ if (has_own_kv) {+ // Per-layer f16 KV cache Parameters. The K/V read back out of a cache are f16, and so is+ // Q after its convert in the translator, so the FLASH_ATTN inputs agree.+ const ov::PartialShape cache_shape = ps({1, D, n_head_kv_l, head_size_l});+ if (!e.has_model_input(kc)) {+ e.add_input(kc, ov::element::f16, cache_shape);+ e.add_input(vc, ov::element::f16, cache_shape);+ }+ e.set_tensor_meta(kc, ps({1, T, n_head_kv_l, head_size_l}), ov::element::f16);+ e.set_tensor_meta(vc, ps({1, T, n_head_kv_l, head_size_l}), ov::element::f16);++ // SET_ROWS(cur, idx, cache) -> the cache with this step's rows written in. Lowered by+ // the frontend to a stateless ScatterUpdate, or by the caller-registered MakeStateful+ // extension to a ReadValue/Concat/Assign OpenVINO state.+ k = e.add_op("GGML_OP_SET_ROWS",+ kc,+ {k, "inp_kv_idx", kc},+ ps({1, T, n_head_kv_l, head_size_l}),+ ov::element::f16);+ v = e.add_op("GGML_OP_SET_ROWS",+ vc,+ {v, "inp_kv_idx", vc},+ ps({1, T, n_head_kv_l, head_size_l}),+ ov::element::f16);+ // The written-through caches are model outputs, so the stateless graph returns each+ // updated cache as a Result (which MakeStateful, when registered, turns into an Assign+ // sink paired with the cache's ReadValue).+ graph.model_output_names.push_back(kc);+ graph.model_output_names.push_back(vc);+ } else {+ // Shared-KV layer: K/V have already been set in the anchor layer's SET_ROWS.+ // Use the anchor's combined cache. If the current layer has a smaller head size+ // (SWA shared layer vs a global anchor), slice K/V to the layer's head_size along+ // the last dim, mirroring llama.cpp's ggml_view_4d with n_embd_head_k(il).+ const ov::PartialShape& anchor_kc_shape = e.shape_of_tensor(kc); // [1, T, n_kv, anchor_head]+ const int64_t anchor_hs = anchor_kc_shape[3].is_static() ? anchor_kc_shape[3].get_length() : cfg.head_size;+ if (head_size_l < static_cast<int>(anchor_hs)) {+ // Shrink the last (head-size) axis to head_size_l. This is a plain single-axis shrink+ // at offset 0, which is exactly what the shared VIEW op_case 3 does -- and what the+ // cgraph decoder assigns to llama.cpp's corresponding ggml_view_4d with+ // n_embd_head_k(il) -- so describe it the way that case expects rather than with a+ // builder-only case: "view_slice" = {ov_axis, start, len} plus the input's own shape.+ // No "view_reshape": the sliced shape already is this node's output shape.+ const ov::PartialShape slice_shape = ps({1, T, n_head_kv_l, head_size_l});+ const std::vector<int64_t> hs_slice{3, 0, int64_t(head_size_l)};+ k = e.add_op("GGML_OP_VIEW",+ p + "k_hslice",+ {kc},+ slice_shape,+ ov::element::f16,+ 3,+ {{"view_slice", hs_slice}, {"input_ggml_shape", e.static_shape_of(kc)}});+ v = e.add_op("GGML_OP_VIEW",+ p + "v_hslice",+ {vc},+ slice_shape,+ ov::element::f16,+ 3,+ {{"view_slice", hs_slice}, {"input_ggml_shape", e.static_shape_of(vc)}});+ } else {+ k = kc;+ v = vc;+ }+ }++ // NOTE: q/k/v stay in the ggml-natural [1, n_tokens, n_head(_kv), head_size] layout+ // here. The PERMUTE to [1, n_head, n_tokens, head_size] is done INSIDE the FLASH_ATTN+ // translator, AFTER the GQA broadcast of K/V. That ordering -- Concat -> GQA tile ->+ // single Transpose -> SDPA -- is the exact shape the CPU plugin's stateful_sdpa_fusion+ // matches (its multi-query-bcst sits on the concat output, before one transpose), so+ // the attention fuses into ScaledDotProductAttentionWithKVCache. Permuting before the+ // tile (the old order) put the transpose between concat and tile and blocked the fuse.++ // FLASH_ATTN_EXT(q, k, v, mask[, sinks]) -> [1, n_tokens, n_head, head_size].+ // gpt-oss: SWA layers use the sliding-window mask; plus a per-head sink logit.+ const std::string mask_name = is_swa_layer ? "self_kq_mask_swa" : "self_kq_mask";+ std::vector<std::string> attn_in = {q, k, v, mask_name};+ if (cfg.has_sinks) {+ e.add_named_weight(p + "attn_sinks.weight");+ attn_in.push_back(p + "attn_sinks.weight");+ }+ std::map<std::string, ov::Any> attn_attrs = {{"scale", kq_scale}};+ if (cfg.attn_soft_cap != 0.0f) {+ attn_attrs["kq_soft_cap"] = cfg.attn_soft_cap;+ }+ auto attn = e.add_op("GGML_OP_FLASH_ATTN_EXT",+ p + "kqv",+ attn_in,+ ps({1, T, cfg.n_head, head_size_l}),+ f32,+ 100, // builder layout: q/k/v are ggml-natural [1, T, n_head, head_size]+ std::move(attn_attrs));++ // reshape back to [1, 1, n_tokens, n_head*head_size]+ auto attn_2d =+ e.add_op("GGML_OP_RESHAPE", p + "kqv_merged", {attn}, ps({1, 1, T, cfg.n_head * head_size_l}), f32, 2);++ // muse-glimmer: sigmoid output gate. The gate is a projection of the PRE-attention+ // normed hidden (the same `attn_norm` tensor Q/K/V come from), squashed by sigmoid and+ // multiplied elementwise into the merged attention output before the wo projection.+ if (cfg.has_attn_gate) {+ e.add_weight(p + "attn_gate.weight");+ auto gate = e.add_op("GGML_OP_MUL_MAT",+ p + "attn_gate",+ {p + "attn_gate.weight", attn_norm},+ ps({1, 1, T, cfg.n_head * head_size_l}),+ f32);+ gate = e.add_op("GGML_UNARY_OP_SIGMOID", p + "attn_gate_sig", {gate}, e.shape_of_tensor(gate), f32);+ attn_2d = e.add_op("GGML_OP_MUL", p + "kqv_gated", {attn_2d, gate}, e.shape_of_tensor(attn_2d), f32);+ }++ // 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},+ ps({1, 1, T, cfg.n_embd}),+ f32);+ if (cfg.has_attn_out_bias) {+ attn_out = add_bias(e, attn_out, p + "attn_output.bias", p + "attn_out_b");+ }+ return attn_out;+}++} // namespace blocks+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/blocks/attention.hpp b/src/frontends/gguf/src/builder/blocks/attention.hppnew file mode 100644index 00000000000..1724d116e0e--- /dev/null+++ b/src/frontends/gguf/src/builder/blocks/attention.hpp@@ -0,0 +1,48 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>++#include "builder/decoder_config.hpp"+#include "builder/graph_emitter.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace blocks {++// Per-layer KV-cache routing, precomputed once for the whole stack.+//+// gemma4 shares KV across layers: the trailing `shared_kv_layers` layers have no K/V of their own+// and reuse the cache of the last own-KV layer of the SAME sliding-window type. Everything else+// leaves this at its defaults, where every layer owns its cache.+struct KvCachePlan {+ int n_own_kv = 0; // first n_own_kv layers have their own KV cache+ int anchor_swa = -1; // last own-KV sliding-window layer, or -1+ int anchor_global = -1; // last own-KV global layer, or -1++ // Build the plan for `cfg`; mirrors llama.cpp's layer_reuse_cb.+ static KvCachePlan build(const DecoderConfig& cfg);+};++// The attention sublayer of one decoder layer: Q/K/V projections (+ optional biases and Q/K/V+// norms), RoPE, the KV-cache store, FLASH_ATTN_EXT, the optional sigmoid output gate, and the+// output projection (+ optional bias).+//+// `attn_norm` is the pre-attention normed hidden. Returns the sublayer output tensor name BEFORE+// the residual add, matching what gated_delta_net() returns for the recurrent layers, so the+// decoder's shared FFN tail consumes either interchangeably.+std::string attention(GraphEmitter& e,+ const DecoderConfig& cfg,+ const KvCachePlan& kv,+ int il,+ const std::string& attn_norm,+ int64_t T);++} // namespace blocks+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/blocks/common.cpp b/src/frontends/gguf/src/builder/blocks/common.cppnew file mode 100644index 00000000000..517a752084b--- /dev/null+++ b/src/frontends/gguf/src/builder/blocks/common.cpp@@ -0,0 +1,46 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "builder/blocks/common.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace blocks {++std::string rms_norm(GraphEmitter& e,+ const std::string& in,+ const std::string& weight,+ const std::string& out_prefix,+ float eps) {+ e.add_weight(weight);+ auto norm = e.add_op("GGML_OP_RMS_NORM",+ out_prefix + ".rms",+ {in},+ e.shape_of_tensor(in),+ ov::element::f32,+ 0,+ {{"eps", eps}});+ return e.add_op("GGML_OP_MUL", out_prefix, {norm, weight}, e.shape_of_tensor(in), ov::element::f32);+}++std::string scale(GraphEmitter& e, const std::string& x, float factor, const std::string& name) {+ return e.add_op("GGML_OP_SCALE",+ name,+ {x},+ e.shape_of_tensor(x),+ ov::element::f32,+ 0,+ {{"scale", factor}, {"bias", 0.0f}});+}++std::string add_bias(GraphEmitter& e, const std::string& x, const std::string& bias_weight, const std::string& name) {+ e.add_named_weight(bias_weight);+ return e.add_op("GGML_OP_ADD", name, {x, bias_weight}, e.shape_of_tensor(x), ov::element::f32);+}++} // namespace blocks+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/blocks/common.hpp b/src/frontends/gguf/src/builder/blocks/common.hppnew file mode 100644index 00000000000..b79961fb29f--- /dev/null+++ b/src/frontends/gguf/src/builder/blocks/common.hpp@@ -0,0 +1,40 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>++#include "builder/graph_emitter.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace blocks {++// Small, architecture-agnostic graph fragments shared by every model family.+//+// They are free functions over GraphEmitter rather than methods on a builder so a future+// non-decoder family (mmproj/vision, audio) can reuse them without inheriting any LLM+// hyperparameters. Anything that needs to know about heads, layers or KV caches belongs in a+// decoder-specific block instead (see ffn.hpp / attention.hpp).++// RMS_NORM followed by elementwise MUL with the norm weight (llama.cpp build_norm, LLM_NORM_RMS).+// `eps` is the epsilon fed to the RMS_NORM op.+std::string rms_norm(GraphEmitter& e,+ const std::string& in,+ const std::string& weight,+ const std::string& out_prefix,+ float eps);++// Scale a tensor by a constant: GGML_OP_SCALE with attr "scale" (and bias 0).+std::string scale(GraphEmitter& e, const std::string& x, float factor, const std::string& name);++// Elementwise add of a (broadcast) bias weight: GGML_OP_ADD(x, bias_weight).+std::string add_bias(GraphEmitter& e, const std::string& x, const std::string& bias_weight, const std::string& name);++} // namespace blocks+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/blocks/ffn.cpp b/src/frontends/gguf/src/builder/blocks/ffn.cppnew file mode 100644index 00000000000..0310ac18230--- /dev/null+++ b/src/frontends/gguf/src/builder/blocks/ffn.cpp@@ -0,0 +1,290 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "builder/blocks/ffn.hpp"++#include <limits>++#include "builder/blocks/common.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace blocks {++using ov::element::f32;++namespace {++// "<name>.weight" -> "<name>.bias": every weight tensor in this file follows that naming+// convention, so a projection's bias weight name can always be derived from its own.+std::string bias_weight_name(const std::string& weight_name) {+ static const std::string suffix = ".weight";+ return weight_name.substr(0, weight_name.size() - suffix.size()) + ".bias";+}++} // namespace++// GATE/UP projection -> SwiGLU, shared by dense_ffn's non-fused branch and moe_ffn's shared-expert+// branch (deepseek2-ocr, bailingmoe2, exaone-moe): the same shape in both, differing only in+// weight-name prefix and (dense only) an optional per-projection bias. The DOWN projection that+// follows is left to the caller, since its bias/output-merging conventions differ between the two+// (a plain residual-style output for dense_ffn vs an ADD into the routed experts' sum for MoE).+// Callers supply the exact op names so each keeps its own established naming (ffn_* vs shexp_*); a+// bias ADD op, when emitted, is named "<gate_name|up_name>_b" and reads "<weight_name>.bias".+std::string swiglu_gate_up(GraphEmitter& e,+ const std::string& gate_w,+ const std::string& up_w,+ const std::string& ffn_norm,+ int64_t T,+ const std::string& gate_name,+ const std::string& up_name,+ const std::string& glu_name,+ bool has_bias) {+ e.add_weight(gate_w);+ const int n_ff = static_cast<int>(e.weight_tensor(gate_w).get_shape()[0]);+ auto gate = e.add_op("GGML_OP_MUL_MAT", gate_name, {gate_w, ffn_norm}, ps({1, 1, T, n_ff}), f32);+ if (has_bias) {+ gate = add_bias(e, gate, bias_weight_name(gate_w), gate_name + "_b");+ }+ e.add_weight(up_w);+ auto up = e.add_op("GGML_OP_MUL_MAT", up_name, {up_w, ffn_norm}, ps({1, 1, T, n_ff}), f32);+ if (has_bias) {+ up = add_bias(e, up, bias_weight_name(up_w), up_name + "_b");+ }+ return e.add_op("GGML_GLU_OP_SWIGLU", glu_name, {gate, up}, ps({1, 1, T, n_ff}), f32, 0, {{"swapped", false}});+}++std::string geglu_ffn(GraphEmitter& e,+ const DecoderConfig& cfg,+ const std::string& p,+ const std::string& ffn_norm,+ int64_t T) {+ e.add_weight(p + "ffn_gate.weight");+ e.add_weight(p + "ffn_up.weight");+ e.add_weight(p + "ffn_down.weight");+ const int n_ff = static_cast<int>(e.weight_tensor(p + "ffn_gate.weight").get_shape()[0]);+ auto gate =+ e.add_op("GGML_OP_MUL_MAT", p + "ffn_gate", {p + "ffn_gate.weight", ffn_norm}, ps({1, 1, T, n_ff}), f32);+ auto up = e.add_op("GGML_OP_MUL_MAT", p + "ffn_up", {p + "ffn_up.weight", ffn_norm}, ps({1, 1, T, n_ff}), f32);+ auto glu =+ e.add_op("GGML_GLU_OP_GEGLU", p + "ffn_geglu", {gate, up}, ps({1, 1, T, n_ff}), f32, 0, {{"swapped", false}});+ return e.add_op("GGML_OP_MUL_MAT", p + "ffn_out", {p + "ffn_down.weight", glu}, ps({1, 1, T, cfg.n_embd}), f32);+}++std::string dense_ffn(GraphEmitter& e,+ const DecoderConfig& cfg,+ const std::string& p,+ const std::string& ffn_norm,+ int64_t T) {+ e.add_weight(p + "ffn_up.weight");+ e.add_weight(p + "ffn_down.weight");+ const bool fused_ffn = !e.has_weight(p + "ffn_gate.weight"); // phi-3: fused gate+up+ const bool has_ffn_bias = e.has_weight(p + "ffn_up.bias");+ std::string glu;+ if (fused_ffn) {+ const int up2 = static_cast<int>(e.weight_tensor(p + "ffn_up.weight").get_shape()[0]); // 2*n_ff+ auto up = e.add_op("GGML_OP_MUL_MAT", p + "ffn_up", {p + "ffn_up.weight", ffn_norm}, ps({1, 1, T, up2}), f32);+ glu = e.add_op("GGML_GLU_OP_SWIGLU",+ p + "ffn_swiglu",+ {up},+ ps({1, 1, T, up2 / 2}),+ f32,+ 0,+ {{"swapped", false}});+ } else {+ glu = swiglu_gate_up(e,+ p + "ffn_gate.weight",+ p + "ffn_up.weight",+ ffn_norm,+ T,+ p + "ffn_gate",+ p + "ffn_up",+ p + "ffn_swiglu",+ has_ffn_bias);+ }+ auto out = e.add_op("GGML_OP_MUL_MAT", p + "ffn_out", {p + "ffn_down.weight", glu}, ps({1, 1, T, cfg.n_embd}), f32);+ if (has_ffn_bias) {+ out = add_bias(e, out, p + "ffn_down.bias", p + "ffn_out_b");+ }+ return out;+}++std::string moe_ffn(GraphEmitter& e,+ const DecoderConfig& cfg,+ const std::string& p,+ const std::string& ffn_norm,+ int64_t T) {+ const int E = cfg.n_expert, K = cfg.n_expert_used;+ const int n_ff = static_cast<int>(e.weight_tensor(p + "ffn_gate_exps.weight").get_shape()[1]);++ // --- router: logits [1,1,T,E] = gate_inp · x ---+ e.add_weight(p + "ffn_gate_inp.weight");+ auto logits =+ e.add_op("GGML_OP_MUL_MAT", p + "moe_logits", {p + "ffn_gate_inp.weight", ffn_norm}, ps({1, 1, T, E}), f32);+ if (cfg.has_moe_gate_bias) {+ logits = add_bias(e, logits, p + "ffn_gate_inp.bias", p + "moe_logits_b");+ }++ // gating: softmax (OLMoE) or softmax-after-topk (gpt-oss "softmax_weight").+ std::string probs = logits;+ if (!cfg.moe_softmax_weight) {+ probs = e.add_op("GGML_OP_SOFT_MAX",+ p + "moe_probs",+ {logits},+ ps({1, 1, T, E}),+ f32,+ 0,+ {{"softmax_axis", int64_t(-1)}});+ }++ // top-k expert selection -> indices [1,1,T,K] (i32).+ auto selected = e.add_op("GGML_OP_TOP_K", p + "moe_topk", {probs}, ps({1, 1, T, K}), ov::element::i32);++ // weights = gather probs by selected; op_case 10 returns a per-expert column+ // [1,T,K,1] (robust to dynamic T). gpt-oss softmaxes over the K (expert) axis.+ auto weights = e.add_op("GGML_OP_GET_ROWS", p + "moe_w", {probs, selected}, ps({1, T, K, 1}), f32, 10);+ if (cfg.moe_softmax_weight) {+ weights = e.add_op("GGML_OP_SOFT_MAX",+ p + "moe_w_sm",+ {weights},+ ps({1, T, K, 1}),+ f32,+ 0,+ {{"softmax_axis", int64_t(2)}});+ }+ // Renormalize the selected top-K gating weights to sum to 1 (llama.cpp build_moe_ffn's+ // norm_w path, e.g. qwen3moe/glm4moe/bailingmoe2). On the softmax-before-topk path the+ // weights above are a slice of a softmax over all E experts, so the K<E kept values no+ // longer sum to 1 without this; the softmax-after-topk (gpt-oss) path already sums to 1+ // and needs no correction. weights is [1,T,K,1]; transpose K to the last axis, SUM_ROWS,+ // clamp away from 0 (matches llama.cpp's 6.1e-5 floor), then DIV back (broadcasts the+ // [1,T,1,1] sum over K via repeat_input_to_match).+ if (cfg.expert_weights_norm && !cfg.moe_softmax_weight) {+ auto w_tr = e.add_op("GGML_OP_TRANSPOSE", p + "moe_w_tr", {weights}, ps({1, T, 1, K}), f32);+ auto w_sum = e.add_op("GGML_OP_SUM_ROWS", p + "moe_w_sum", {w_tr}, ps({1, T, 1, 1}), f32);+ w_sum = e.add_op("GGML_OP_CLAMP",+ p + "moe_w_sum_clamped",+ {w_sum},+ ps({1, T, 1, 1}),+ f32,+ 0,+ {{"clamp_min", 6.1e-5f}, {"clamp_max", std::numeric_limits<float>::max()}});+ weights = e.add_op("GGML_OP_DIV", p + "moe_w_norm", {weights, w_sum}, ps({1, T, K, 1}), f32);+ }++ // gpt-oss expert_weights_scale: optional constant multiplier applied after softmax+ // (mirrors llama.cpp build_moe_ffn w_scale != 0 && w_scale != 1.0 path).+ if (cfg.expert_weights_scale != 0.0f && cfg.expert_weights_scale != 1.0f) {+ weights = scale(e, weights, cfg.expert_weights_scale, p + "moe_w_scaled");+ }++ // expert FFN via MUL_MAT_ID. The routed input x is broadcast to K slots; the+ // translator gathers each token's selected expert matrices. gpt-oss adds per-expert+ // biases (ADD_ID gathers the selected experts' bias rows).+ e.add_weight(p + "ffn_gate_exps.weight");+ e.add_weight(p + "ffn_up_exps.weight");+ e.add_weight(p + "ffn_down_exps.weight");+ const bool eb = cfg.has_moe_expert_bias;+ auto up = e.add_op("GGML_OP_MUL_MAT_ID",+ p + "moe_up",+ {p + "ffn_up_exps.weight", ffn_norm, selected},+ ps({1, T, K, n_ff}),+ f32);+ if (eb) {+ e.add_named_weight(p + "ffn_up_exps.bias");+ up = e.add_op("GGML_OP_ADD_ID",+ p + "moe_up_b",+ {up, p + "ffn_up_exps.bias", selected},+ ps({1, T, K, n_ff}),+ f32);+ }+ auto gate = e.add_op("GGML_OP_MUL_MAT_ID",+ p + "moe_gate",+ {p + "ffn_gate_exps.weight", ffn_norm, selected},+ ps({1, T, K, n_ff}),+ f32);+ if (eb) {+ e.add_named_weight(p + "ffn_gate_exps.bias");+ gate = e.add_op("GGML_OP_ADD_ID",+ p + "moe_gate_b",+ {gate, p + "ffn_gate_exps.bias", selected},+ ps({1, T, K, n_ff}),+ f32);+ }+ std::string act;+ if (cfg.moe_swiglu_oai) {+ act = e.add_op("GGML_GLU_OP_SWIGLU_OAI",+ p + "moe_act",+ {gate, up},+ ps({1, T, K, n_ff}),+ f32,+ 0,+ // Attribute names must match the cgraph decoder's (ggml-decoder.cpp), which+ // is the external contract the shared translators read: glu_alpha/glu_limit.+ {{"swapped", false}, {"glu_alpha", 1.702f}, {"glu_limit", 7.0f}});+ } else {+ act = e.add_op("GGML_GLU_OP_SWIGLU",+ p + "moe_act",+ {gate, up},+ ps({1, T, K, n_ff}),+ f32,+ 0,+ {{"swapped", false}});+ }+ auto experts = e.add_op("GGML_OP_MUL_MAT_ID",+ p + "moe_down",+ {p + "ffn_down_exps.weight", act, selected},+ ps({1, T, K, cfg.n_embd}),+ f32);+ if (eb) {+ e.add_named_weight(p + "ffn_down_exps.bias");+ experts = e.add_op("GGML_OP_ADD_ID",+ p + "moe_down_b",+ {experts, p + "ffn_down_exps.bias", selected},+ ps({1, T, K, cfg.n_embd}),+ f32);+ }++ // Weighted sum over the K selected experts. weights is [1,T,K,1] (per-expert col).+ // experts [1,T,K,n_embd] * weights -> [1,T,K,n_embd]+ // TRANSPOSE last two axes -> [1,T,n_embd,K]; SUM_ROWS over K -> [1,T,n_embd,1]+ // RESHAPE (dynamic) -> [1,1,T,n_embd].+ // The reshape is op_case 5: collapse to [1, 1, -1, n_embd], the token axis staying dynamic.+ // That is the case the cgraph decoder would assign to this same reshape too -- ggml ne+ // [1,n_embd,T,1] -> [n_embd,T,1,1] satisfies both of its case-5 predicates -- so the shared+ // case applies as-is and needs no builder-specific numbering.+ auto weighted = e.add_op("GGML_OP_MUL", p + "moe_weighted", {experts, weights}, ps({1, T, K, cfg.n_embd}), f32);+ auto tr = e.add_op("GGML_OP_TRANSPOSE", p + "moe_tr", {weighted}, ps({1, T, cfg.n_embd, K}), f32);+ auto summed = e.add_op("GGML_OP_SUM_ROWS", p + "moe_sum", {tr}, ps({1, T, cfg.n_embd, 1}), f32);+ auto moe_out = e.add_op("GGML_OP_RESHAPE", p + "moe_out", {summed}, ps({1, 1, T, cfg.n_embd}), f32, 5);++ // Shared experts (deepseek2-ocr, bailingmoe2, exaone-moe): always-active experts whose+ // output is added to the routed experts' weighted sum. Uses plain SwiGLU dense FFN with+ // ffn_{gate,up,down}_shexp.weight (n_ff_shared = shexp rows). Output added to moe_out.+ if (cfg.n_expert_shared > 0 && e.has_weight(p + "ffn_gate_shexp.weight")) {+ auto s_act = swiglu_gate_up(e,+ p + "ffn_gate_shexp.weight",+ p + "ffn_up_shexp.weight",+ ffn_norm,+ T,+ p + "shexp_gate",+ p + "shexp_up",+ p + "shexp_act",+ /*has_bias=*/false);+ e.add_weight(p + "ffn_down_shexp.weight");+ auto s_down = e.add_op("GGML_OP_MUL_MAT",+ p + "shexp_out",+ {p + "ffn_down_shexp.weight", s_act},+ ps({1, 1, T, cfg.n_embd}),+ f32);+ moe_out = e.add_op("GGML_OP_ADD", p + "moe_shared_out", {moe_out, s_down}, ps({1, 1, T, cfg.n_embd}), f32);+ }+ return moe_out;+}++} // namespace blocks+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/blocks/ffn.hpp b/src/frontends/gguf/src/builder/blocks/ffn.hppnew file mode 100644index 00000000000..1f9b1a671ae--- /dev/null+++ b/src/frontends/gguf/src/builder/blocks/ffn.hpp@@ -0,0 +1,51 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>++#include "builder/decoder_config.hpp"+#include "builder/graph_emitter.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace blocks {++// Feed-forward sublayers of the decoder block, mirroring llm_graph_context::build_ffn /+// build_moe_ffn. `prefix` is the layer prefix ("blk.<il>."), `ffn_norm` the pre-FFN normed hidden,+// and `T` the representative static token length. Each returns the sublayer output tensor name,+// before the residual add.++// Dense SwiGLU FFN (llama/qwen/phi3/minicpm). Supports the fused gate+up projection (phi-3, no+// ffn_gate.weight) and optional per-projection biases (pangu-embedded), both auto-detected from+// the weight table.+std::string dense_ffn(GraphEmitter& e,+ const DecoderConfig& cfg,+ const std::string& prefix,+ const std::string& ffn_norm,+ int64_t T);++// Dense GeGLU FFN (Gemma/Gemma2). Same layout as SwiGLU but uses GELU activation.+std::string geglu_ffn(GraphEmitter& e,+ const DecoderConfig& cfg,+ const std::string& prefix,+ const std::string& ffn_norm,+ int64_t T);++// Mixture-of-experts FFN (OLMoE / gpt-oss / qwen3moe), mirroring llm_graph_context::build_moe_ffn.+// Routing: logits = gate_inp·x; probs = softmax/identity; pick top-k experts; per-token expert+// matmuls via MUL_MAT_ID; gated activation; weighted sum over the used experts; plus the optional+// always-active shared experts.+std::string moe_ffn(GraphEmitter& e,+ const DecoderConfig& cfg,+ const std::string& prefix,+ const std::string& ffn_norm,+ int64_t T);++} // namespace blocks+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp b/src/frontends/gguf/src/builder/blocks/gated_delta_net.cppnew file mode 100644index 00000000000..a073565411f--- /dev/null+++ b/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp@@ -0,0 +1,176 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "builder/blocks/gated_delta_net.hpp"++#include <vector>++#include "builder/blocks/common.hpp"+#include "openvino/core/except.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace blocks {++std::string gated_delta_net(GraphEmitter& e,+ const DecoderConfig& cfg,+ int il,+ const std::string& attn_norm,+ int64_t T) {+ using ov::element::f32;+ const std::string p = "blk." + std::to_string(il) + ".";+ auto& graph = *e.graph();++ const int64_t d_conv = cfg.ssm_conv_kernel;+ const int64_t S = cfg.ssm_state_size; // head_k_dim == head_v_dim+ const int64_t H_k = cfg.ssm_group_count; // num_k_heads+ const int64_t H_v = cfg.ssm_dt_rank; // num_v_heads+ OPENVINO_ASSERT(H_v > 0 && cfg.ssm_inner_size % H_v == 0,+ "[GGUF] Gated-DeltaNet: ssm_inner_size (",+ cfg.ssm_inner_size,+ ") is not evenly divisible by ssm_time_step_rank (",+ H_v,+ ")");+ const int64_t head_v = cfg.ssm_inner_size / H_v; // head_v_dim+ const int64_t key_dim = S * H_k;+ const int64_t value_dim = head_v * H_v;+ const int64_t conv_dim = 2 * key_dim + value_dim;++ // ---- input projections ----+ e.add_weight(p + "attn_qkv.weight");+ auto qkv =+ e.add_op("GGML_OP_MUL_MAT", p + "qkv_mixed", {p + "attn_qkv.weight", attn_norm}, ps({1, 1, T, conv_dim}), f32);+ e.add_weight(p + "attn_gate.weight");+ auto z = e.add_op("GGML_OP_MUL_MAT", p + "z", {p + "attn_gate.weight", attn_norm}, ps({1, 1, T, value_dim}), f32);++ // beta = sigmoid(ssm_beta @ x), one scalar per v-head+ e.add_weight(p + "ssm_beta.weight");+ auto beta = e.add_op("GGML_OP_MUL_MAT", p + "beta", {p + "ssm_beta.weight", attn_norm}, ps({1, 1, T, H_v}), f32);+ beta = e.add_op("GGML_UNARY_OP_SIGMOID", p + "beta_sig", {beta}, ps({1, 1, T, H_v}), f32);+ beta = e.add_op("GGML_OP_RESHAPE", p + "beta_4d", {beta}, ps({1, T, H_v, 1}), f32, 1);++ // g = softplus(ssm_alpha @ x + ssm_dt.bias) * ssm_a (ggml: -A_log.exp() * softplus)+ e.add_weight(p + "ssm_alpha.weight");+ auto alpha = e.add_op("GGML_OP_MUL_MAT", p + "alpha", {p + "ssm_alpha.weight", attn_norm}, ps({1, 1, T, H_v}), f32);+ e.add_named_weight(p + "ssm_dt.bias");+ alpha = e.add_op("GGML_OP_ADD", p + "alpha_biased", {alpha, p + "ssm_dt.bias"}, ps({1, 1, T, H_v}), f32);+ alpha = e.add_op("GGML_UNARY_OP_SOFTPLUS", p + "alpha_sp", {alpha}, ps({1, 1, T, H_v}), f32);+ e.add_named_weight(p + "ssm_a");+ auto g = e.add_op("GGML_OP_MUL", p + "gate", {alpha, p + "ssm_a"}, ps({1, 1, T, H_v}), f32);+ g = e.add_op("GGML_OP_RESHAPE", p + "gate_4d", {g}, ps({1, T, H_v, 1}), f32, 1);++ // ---- causal depthwise conv over [conv state | this step's tokens] ----+ // conv_state holds the trailing d_conv-1 columns of the previous step's conv input.+ const std::string cs = "conv_state_l" + std::to_string(il);+ if (!e.has_model_input(cs)) {+ e.add_input(cs, f32, ps({1, 1, conv_dim, d_conv - 1}));+ }+ e.set_tensor_meta(cs, ps({1, 1, conv_dim, d_conv - 1}), f32);++ // [1,1,T,conv_dim] -> [1,1,conv_dim,T] so the conv window grows along the last axis.+ auto qkv_t = e.add_op("GGML_OP_TRANSPOSE", p + "qkv_t", {qkv}, ps({1, 1, conv_dim, T}), f32);+ auto conv_in = e.add_op("GGML_OP_CONCAT",+ p + "conv_in",+ {cs, qkv_t},+ ps({1, 1, conv_dim, d_conv - 1 + T}),+ f32,+ 0,+ {{"concat_axis", int{0}}});++ // Next step's state is the trailing d_conv-1 columns of this window.+ const std::vector<int64_t> tail_slice{3, -(d_conv - 1), d_conv - 1};+ auto cs_out = e.add_op("GGML_OP_VIEW",+ cs + "_out",+ {conv_in},+ ps({1, 1, conv_dim, d_conv - 1}),+ f32,+ 3,+ {{"view_slice", tail_slice}, {"input_ggml_shape", e.static_shape_of(conv_in)}});+ graph.model_output_names.push_back(cs_out);+ graph.recurrent_states.emplace_back(cs, cs_out);++ e.add_named_weight(p + "ssm_conv1d.weight");+ auto conv =+ e.add_op("GGML_OP_SSM_CONV", p + "conv_out", {conv_in, p + "ssm_conv1d.weight"}, ps({1, 1, T, conv_dim}), f32);+ conv = e.add_op("GGML_UNARY_OP_SILU", p + "conv_silu", {conv}, ps({1, 1, T, conv_dim}), f32);++ // ---- split the conv output into q | k | v and normalize q/k ----+ auto slice_heads = [&](const std::string& name, int64_t off, int64_t width, int64_t heads, int64_t dim) {+ const std::vector<int64_t> sl{3, off, width};+ auto s = e.add_op("GGML_OP_VIEW",+ p + name + "_s",+ {conv},+ ps({1, 1, T, width}),+ f32,+ 3,+ {{"view_slice", sl}, {"input_ggml_shape", e.static_shape_of(conv)}});+ return e.add_op("GGML_OP_RESHAPE", p + name, {s}, ps({1, T, heads, dim}), f32, 1);+ };+ auto q = slice_heads("q_conv", 0, key_dim, H_k, S);+ auto k = slice_heads("k_conv", key_dim, key_dim, H_k, S);+ auto v = slice_heads("v_conv", 2 * key_dim, value_dim, H_v, head_v);+ q = e.add_op("GGML_OP_L2_NORM", p + "q_l2", {q}, ps({1, T, H_k, S}), f32, 0, {{"eps", cfg.rms_eps}});+ k = e.add_op("GGML_OP_L2_NORM", p + "k_l2", {k}, ps({1, T, H_k, S}), f32, 0, {{"eps", cfg.rms_eps}});++ // ---- recurrent delta rule ----+ // ggml state layout is [B, H_v, value_dim, key_dim]; the translator transposes it for+ // the fused op and transposes the new state back, so the Parameter keeps ggml's layout.+ const std::string ss = "ssm_state_l" + std::to_string(il);+ if (!e.has_model_input(ss)) {+ e.add_input(ss, f32, ps({1, H_v, head_v, S}));+ }+ e.set_tensor_meta(ss, ps({1, H_v, head_v, S}), f32);++ auto gdn = e.add_op("GGML_OP_GATED_DELTA_NET",+ p + "gdn",+ {q, k, v, g, beta, ss},+ ps({1, 1, T + head_v, head_v * H_v}),+ f32,+ 0,+ {{"gdn_state_slots", int64_t{1}}});++ // The op packs [attn rows | new-state rows]; op_case 4 slices them apart. The attn view's+ // token axis is marked -1 explicitly rather than left as the representative T: the consumer+ // replaces the FIRST dim equal to the token count, and with T == 1 that would match the+ // leading batch dim and move the tokens into dim 0 for the rest of the model.+ const std::vector<int64_t> attn_view{0, head_v};+ const std::vector<int64_t> state_view{1, head_v};+ auto attn = e.add_op("GGML_OP_VIEW",+ p + "gdn_attn",+ {gdn},+ ps({1, T, H_v, head_v}),+ f32,+ 4,+ {{"gdn_view", attn_view}, {"view_reshape", std::vector<int64_t>{1, -1, H_v, head_v}}});+ auto new_state = e.add_op("GGML_OP_VIEW",+ ss + "_out",+ {gdn},+ ps({1, H_v, head_v, S}),+ f32,+ 4,+ {{"gdn_view", state_view}, {"view_reshape", std::vector<int64_t>{1, H_v, head_v, S}}});+ graph.model_output_names.push_back(new_state);+ graph.recurrent_states.emplace_back(ss, new_state);++ // ---- gated output norm + projection ----+ // build_norm_gated: rms_norm(attn, ssm_norm) * silu(z), normalizing the head_v axis.+ auto out = rms_norm(e, attn, p + "ssm_norm.weight", p + "gdn_norm", cfg.rms_eps);+ auto z_4d = e.add_op("GGML_OP_RESHAPE", p + "z_4d", {z}, ps({1, T, H_v, head_v}), f32, 1);+ auto z_silu = e.add_op("GGML_UNARY_OP_SILU", p + "z_silu", {z_4d}, ps({1, T, H_v, head_v}), f32);+ out = e.add_op("GGML_OP_MUL", p + "gdn_gated", {out, z_silu}, ps({1, T, H_v, head_v}), f32);+ out = e.add_op("GGML_OP_RESHAPE", p + "gdn_merged", {out}, ps({1, 1, T, value_dim}), f32, 2);++ e.add_weight(p + "ssm_out.weight");+ return e.add_op("GGML_OP_MUL_MAT",+ p + "linear_attn_out",+ {p + "ssm_out.weight", out},+ ps({1, 1, T, cfg.n_embd}),+ f32);+}++} // namespace blocks+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/blocks/gated_delta_net.hpp b/src/frontends/gguf/src/builder/blocks/gated_delta_net.hppnew file mode 100644index 00000000000..bd5d45d45c2--- /dev/null+++ b/src/frontends/gguf/src/builder/blocks/gated_delta_net.hpp@@ -0,0 +1,31 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>++#include "builder/decoder_config.hpp"+#include "builder/graph_emitter.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace blocks {++// qwen35 linear-attention (Gated DeltaNet) layer.+// Mirrors llama.cpp src/models/qwen35.cpp build_layer_attn_linear + delta-net-base.cpp.+// `attn_norm` is the pre-attention normed hidden; returns the sublayer output BEFORE the residual+// add, i.e. exactly what the shared decoder tail expects in place of attn_out.+//+// The two recurrent states are plain model Parameters written through to Results, matching how the+// builder treats KV caches: the frontend always emits a STATELESS graph and leaves statefulness to+// the consumer. Unlike a KV cache these are OVERWRITTEN, not appended, so they carry no token axis+// and MakeStateful's Concat path does not apply to them.+std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, const std::string& attn_norm, int64_t T);++} // namespace blocks+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp b/src/frontends/gguf/src/builder/blocks/qkv_repack.cppnew file mode 100644index 00000000000..ce4d2027983--- /dev/null+++ b/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp@@ -0,0 +1,73 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "builder/blocks/qkv_repack.hpp"++#include <array>+#include <unordered_map>++#include "quant/weights.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace blocks {++namespace {++// Re-key the sliced tensors from "<src_base>.<part>.weight" to "<dst_base>.weight" so+// emit_weight_op's sub-key extraction (weight/scales/zp) and translate_weight's make_weight_node+// see the node's own base name.+std::unordered_map<std::string, ov::Tensor> rekey(const std::unordered_map<std::string, ov::Tensor>& extracted,+ const std::string& dst_base) {+ std::unordered_map<std::string, ov::Tensor> out;+ for (const auto& kv : extracted) {+ auto dot = kv.first.rfind('.');+ out[dst_base + "." + kv.first.substr(dot + 1)] = kv.second;+ }+ return out;+}++} // namespace++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;+ 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"};+ const std::array<int64_t, 3> rows = {(int64_t)n_q, (int64_t)n_kv, (int64_t)n_kv};+ for (size_t i = 0; i < 3; ++i) {+ const std::string base = p + "attn_" + std::string(1, "qkv"[i]); // blk.N.attn_q etc.+ e.emit_weight_op(names[i], rekey(parts[i].extracted, base), parts[i].qtype, ps({1, 1, rows[i], cfg.n_embd}));+ }++ // Some fused-QKV archs (e.g. phi-3) also carry a single attn_qkv.bias; split it into+ // attn_{q,k,v}.bias the same way so attention()'s plain add_bias lookup finds them. Not every+ // fused-QKV arch has a bias, so only split when the fused tensor is actually present.+ if (e.weights().count(p + "attn_qkv.bias")) {+ auto bias_parts = split_fused_qkv_bias(p + "attn_qkv", e.weights(), n_q, n_kv, n_kv);+ const std::array<std::string, 3> bias_names = {p + "attn_q.bias", p + "attn_k.bias", p + "attn_v.bias"};+ for (size_t i = 0; i < 3; ++i) {+ e.weights()[bias_names[i]] = bias_parts[i];+ }+ }+}++void register_qwen35_q_gate(GraphEmitter& e, const DecoderConfig& cfg, int il) {+ const std::string p = "blk." + std::to_string(il) + ".";+ auto parts = split_interleaved_q_gate(p + "attn_q", e.weights(), e.qtypes(), static_cast<size_t>(cfg.head_size));+ const std::array<std::string, 2> names = {p + "attn_q.weight", p + "attn_gate.weight"};+ const std::array<std::string, 2> suffix = {"q", "gate"};+ const int64_t rows = static_cast<int64_t>(cfg.n_head) * cfg.head_size;+ for (size_t i = 0; i < 2; ++i) {+ const std::string base = p + "attn_" + suffix[i];+ e.emit_weight_op(names[i], rekey(parts[i].extracted, base), parts[i].qtype, ps({1, 1, rows, cfg.n_embd}));+ }+}++} // namespace blocks+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/blocks/qkv_repack.hpp b/src/frontends/gguf/src/builder/blocks/qkv_repack.hppnew file mode 100644index 00000000000..c2aece9e6ec--- /dev/null+++ b/src/frontends/gguf/src/builder/blocks/qkv_repack.hpp@@ -0,0 +1,35 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>++#include "builder/decoder_config.hpp"+#include "builder/graph_emitter.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace blocks {++// Weight-level repacking that happens before any op is emitted for a layer, so the rest of the+// attention path only ever sees the plain blk.<il>.attn_{q,k,v}.weight / attn_gate.weight nodes and+// stays architecture-agnostic.++// Split a fused blk.<il>.attn_qkv weight into separate q/k/v weight nodes registered under+// blk.<il>.attn_{q,k,v}.weight. Rows split as [n_head*head_size | n_head_kv*head_size x2].+void register_fused_qkv(GraphEmitter& e, const DecoderConfig& cfg, int il);++// qwen35 full-attention layers: attn_q packs query and attention-output gate interleaved per head+// ([q_h0 | gate_h0 | q_h1 | ...], stride 2*head_size). De-interleave into the plain+// blk.N.attn_q.weight / blk.N.attn_gate.weight the shared attention path expects, so the graph+// never sees the interleaving. llama.cpp does the same split with two strided views+// (src/models/qwen35.cpp build_layer_attn).+void register_qwen35_q_gate(GraphEmitter& e, const DecoderConfig& cfg, int il);++} // namespace blocks+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/decoder_config.cpp b/src/frontends/gguf/src/builder/decoder_config.cppnew file mode 100644index 00000000000..0a8aba6f475--- /dev/null+++ b/src/frontends/gguf/src/builder/decoder_config.cpp@@ -0,0 +1,303 @@+// 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 "decoder_config.hpp"++#include <algorithm>+#include <cmath>+#include <variant>++#include "arch_registry.hpp"+#include "openvino/core/except.hpp"++namespace ov {+namespace frontend {+namespace 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;+}++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;+}++} // namespace++DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,+ 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);+ };+ const auto cfg_f = [&config](const std::string& k) {+ return cfg_float(config, k);+ };++ 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());+ }+ }++ arch = std::get<std::string>(config.at("architecture"));++ // Per-architecture structure, auto-detected from the GGUF tensor table (layer 0).+ has_qk_norm = has("blk.0.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("blk.0.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");+ // Detect MoE from the first non-dense-lead layer (layer 0 may be dense even in MoE models).+ {+ const int probe = std::max(0, n_dense_lead);+ const std::string pp = "blk." + std::to_string(probe) + ".";+ is_moe = has(pp + "ffn_gate_exps.weight");+ }+ // 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");+ n_expert_shared = cfg_i("expert_shared_count");+ 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+ // Gemma2/Gemma4: per-layer post-attention and post-FFN RMSNorm applied after the sublayer+ // output and before the residual add. Detected from the tensor table at layer 0.+ //+ // Key naming ambiguity across architectures:+ // Gemma2/Gemma4: attn_norm (pre-attn) + ffn_norm (pre-FFN)+ // + post_attention_norm (post-attn) + post_ffw_norm (post-FFN)+ // gpt-oss: attn_norm (pre-attn) + post_attention_norm (pre-FFN, no ffn_norm!)+ // exaone4: post_attention_norm (pre-attn!) + post_ffw_norm (pre-FFN!) — no attn_norm+ //+ // Rule: post_attention_norm is a true POST-attn norm only when both attn_norm.weight+ // AND ffn_norm.weight also exist. Same for post_ffw_norm as a true POST-FFN norm.+ {+ const bool has_attn_norm_w = has("blk.0.attn_norm.weight");+ const bool has_ffn_norm_w = has("blk.0.ffn_norm.weight");+ has_attn_post_norm = has("blk.0.post_attention_norm.weight") && has_attn_norm_w && has_ffn_norm_w;+ has_ffn_post_norm = has("blk.0.post_ffw_norm.weight") && has_ffn_norm_w;++ // Compute effective pre-attn and pre-FFN norm key suffixes.+ // Standard: "attn_norm.weight" / "ffn_norm.weight".+ // exaone4: "post_attention_norm.weight" / "post_ffw_norm.weight".+ // gpt-oss: "attn_norm.weight" / "post_attention_norm.weight".+ if (!has_attn_norm_w && has("blk.0.post_attention_norm.weight")) {+ attn_norm_key = "post_attention_norm.weight"; // exaone4+ }+ if (!has_ffn_norm_w) {+ if (has("blk.0.post_ffw_norm.weight")) {+ ffn_norm_key = "post_ffw_norm.weight"; // exaone4+ } else if (has("blk.0.post_attention_norm.weight")) {+ ffn_norm_key = "post_attention_norm.weight"; // gpt-oss+ }+ }+ }+ // 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;+ 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";+ 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.+ // MTP/NextN blocks are stored past the main stack and are not part of a normal+ // forward pass, so the layer loop must not walk into them.+ n_layer -= n_layer_nextn;+ OPENVINO_ASSERT(n_layer > 0, "[GGUF] qwen35: no trunk layers left after excluding NextN blocks");+ }++ // Per-architecture scalars from metadata (1.0 / 0.0 when absent -> no-op).+ embedding_scale = cfg_f("embedding_scale");+ 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+ expert_weights_norm = 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 = 32.0f;+ rope_config.beta_slow = 1.0f;+ // 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");+ // 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;+ if (has_swa && (swa_dims_differ || swa_freq_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;+ use_per_op_rope = true;+ }+}++bool DecoderConfig::layer_is_swa(int il) const {+ if (!swa_layer_flags.empty()) {+ return il < static_cast<int>(swa_layer_flags.size()) && swa_layer_flags[il] != 0;+ }+ 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;+}++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);+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/decoder_config.hpp b/src/frontends/gguf/src/builder/decoder_config.hppnew file mode 100644index 00000000000..15bacf2cc93--- /dev/null+++ b/src/frontends/gguf/src/builder/decoder_config.hpp@@ -0,0 +1,153 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <map>+#include <string>+#include <unordered_map>+#include <vector>++#include "openvino/frontend/gguf/decoder.hpp"+#include "openvino/runtime/tensor.hpp"+#include "quant/gguf.hpp"++namespace ov {+namespace frontend {+namespace gguf {++// Everything the decoder topology needs to know about ONE model, resolved once up front.+//+// This is the GGUF frontend's equivalent of llama.cpp's llama_hparams plus its per-arch+// load_arch_hparams: a flat, already-decided description of the model, so the topology builder in+// arch/decoder_builder.cpp never re-derives anything and reads declaratively.+//+// Almost every field is DETECTED, not hard-coded per architecture: the presence of a layer-0+// weight tensor decides whether the model has QK-norm, projection biases, fused QKV, MoE routing,+// attention sinks, post-norms and so on. That is what lets a new same-family architecture be+// enabled by adding its name to arch_registry.cpp and writing no code at all. Only a handful of+// genuinely tensor-table-ambiguous properties (GeGLU vs SwiGLU, gemma4's V-norm) fall back to an+// architecture-name check; prefer weight presence when adding a new one.+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::string arch;++ // ---- 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;+ 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;+ bool qk_norm_full = false; // norm width is n_head*head_size (OLMoE) rather than per-head+ 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)+ bool has_moe_expert_bias = false;+ bool has_sinks = false;+ bool has_swa = false;+ bool has_attn_post_norm = false;+ bool has_ffn_post_norm = false;+ bool is_geglu = false;+ bool has_v_norm = false; // gemma4: V is also RMSNorm'd like K++ // muse-glimmer specifics+ bool has_attn_gate = false; // sigmoid gate multiplied into the attention output+ bool scaleless_embd_norm = false; // weightless RMSNorm on the token embeddings+ bool rope_on_swa_only = false; // global (non-SWA) layers are NoPE+ 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++ // Norm key suffixes; overridden for archs that use non-standard naming (exaone4, gpt-oss).+ std::string attn_norm_key{"attn_norm.weight"};+ std::string ffn_norm_key{"ffn_norm.weight"};++ // ---- MoE / scalar metadata ----+ int n_expert = 0;+ int n_expert_used = 0;+ int n_dense_lead = 0;+ int n_expert_shared = 0;+ float embedding_scale = 1.0f;+ float residual_scale = 1.0f;+ float logit_scale = 1.0f;+ float attention_scale = 0.0f; // 0 -> 1/sqrt(head_size)+ 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.)+ float attn_soft_cap = 0.0f;+ float final_logit_soft_cap = 0.0f;++ // ---- 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+ // 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).+ int swa_window_size = 0;++ // ---- 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;++ // Head size for layer `il`. gemma4 SWA layers use a smaller head size than global layers.+ int layer_head_size(int il) const;++ // 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;+};++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/gguf_builder.cpp b/src/frontends/gguf/src/builder/gguf_builder.cppnew file mode 100644index 00000000000..8a2392304e7--- /dev/null+++ b/src/frontends/gguf/src/builder/gguf_builder.cpp@@ -0,0 +1,105 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Entry point of the native GGUF -> GgufGraph path: parse the container, decide which model FAMILY+// the file holds, and hand it to that family's ModelBuilder. No llama.cpp / gguf dependency.+//+// The emitted nodes use the GGML op vocabulary and reproduce llama.cpp's cgraph topology, so the+// resulting GgufGraph drives the same op translators as the llama.cpp cgraph path.+//+// Layering (see docs/adding_an_architecture.md):+// graph_emitter.hpp arch-agnostic "how do I write a node"+// blocks/ reusable graph fragments (norm, ffn, attention, gated delta net)+// decoder_config.hpp all per-architecture detection for the decoder family+// arch/decoder_builder the decoder family's topology+// arch_registry.hpp which architectures are accepted, and their RoPE mode+// model_kind.hpp which family a file belongs to+//+// Adding an ARCHITECTURE of an existing family is a name in arch_registry.cpp.+// Adding a FAMILY (mmproj vision/audio, encoder-decoder) is a new ModelBuilder subclass plus a+// branch in build_ggml_graph_from_gguf below; nothing existing changes.++#include "gguf_builder.hpp"++#include <memory>+#include <type_traits>++#include "builder/arch/decoder_builder.hpp"+#include "builder/arch_registry.hpp"+#include "builder/model_builder.hpp"+#include "builder/model_kind.hpp"+#include "gguf_graph.hpp"+#include "openvino/core/except.hpp"+#include "openvino/util/log.hpp"+#include "quant/gguf.hpp"++namespace ov {+namespace frontend {+namespace gguf {++namespace {++// Pull the `tokenizer.*` ggml metadata into an ov::AnyMap keyed by the sub-key after the last+// dot (e.g. "tokenizer.ggml.tokens" -> "tokens", "tokenizer.chat_template" -> "chat_template").+// Each GGUF metadata variant is mapped to the ov::Any types a downstream tokenizer builder+// consumes: std::string / std::vector<std::string> / ov::Tensor (arrays and shape-{} scalars).+ov::AnyMap extract_tokenizer_config(const std::unordered_map<std::string, GGUFMetaData>& metadata) {+ const std::string prefix = "tokenizer.";+ ov::AnyMap cfg;+ for (const auto& [key, value] : metadata) {+ if (key.compare(0, prefix.size(), prefix) != 0) {+ continue;+ }+ const auto sub_key = key.substr(key.find_last_of('.') + 1);+ std::visit(+ [&](const auto& v) {+ using T = std::decay_t<decltype(v)>;+ if constexpr (std::is_same_v<T, std::monostate>) {+ // skip empty+ } else {+ cfg[sub_key] = v;+ }+ },+ value);+ }+ return cfg;+}++} // namespace++std::shared_ptr<GgufGraph> build_ggml_graph_from_gguf(const std::string& file) {+ auto [metadata, weights, qtypes, mmap, quant_buf] = get_gguf_data(file);++ // Decide the family FIRST: the metadata key layout differs per family, so reading any+ // decoder hyperparameter before this point would misreport an mmproj file as a broken LLM.+ const ModelKind kind = detect_model_kind(metadata);+ OPENVINO_ASSERT(kind == ModelKind::Decoder,+ "[GGUF] this file holds a ",+ model_kind_name(kind),+ " model; the native GGUF builder currently implements the decoder family only. "+ "Support is added by implementing a ModelBuilder subclass for that family (see "+ "builder/model_builder.hpp).");++ auto config = decoder_config_from_meta(metadata);++ const std::string arch = std::get<std::string>(config.at("architecture"));+ OPENVINO_ASSERT(supported_archs().count(arch),+ "[GGUF] native GGUF builder does not support architecture '",+ arch,+ "'. See supported_archs() in builder/arch_registry.cpp for the full list.");+ if (experimental_archs().count(arch)) {+ OPENVINO_WARN("[GGUF] architecture '",+ arch,+ "' is experimental: it is built by structural auto-detection but has not been "+ "end-to-end verified against a reference. Validate accuracy before relying on it.");+ }++ std::unique_ptr<ModelBuilder> builder = std::make_unique<DecoderBuilder>(config, weights, qtypes);+ auto graph = builder->build();+ graph->tokenizer_config = extract_tokenizer_config(metadata);+ return graph;+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/gguf_builder.hpp b/src/frontends/gguf/src/builder/gguf_builder.hppnew file mode 100644index 00000000000..eb5a62209fe--- /dev/null+++ b/src/frontends/gguf/src/builder/gguf_builder.hpp@@ -0,0 +1,24 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <string>++namespace ov {+namespace frontend {+namespace gguf {++struct GgufGraph; // defined in gguf_graph.hpp; only used here as a shared_ptr return type++// Build a GgufGraph natively from a .gguf file (no llama.cpp / gguf dependency).+// Parses the container, then dispatches to a per-architecture builder that emits nodes in+// the GGML op vocabulary reproducing llama.cpp's cgraph topology for that architecture.+// Throws if the architecture is not supported natively.+std::shared_ptr<GgufGraph> build_ggml_graph_from_gguf(const std::string& file);++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp b/src/frontends/gguf/src/builder/gguf_builder_decoder.cppnew file mode 100644index 00000000000..5c75b42011c--- /dev/null+++ b/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp@@ -0,0 +1,206 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "gguf_builder_decoder.hpp"++#include <algorithm>++#include "openvino/core/except.hpp"++namespace ov {+namespace frontend {+namespace gguf {++GgufBuilderDecoder::GgufBuilderDecoder(std::shared_ptr<GgufGraph> graph) : m_graph(std::move(graph)) {}++const GgufOp& GgufBuilderDecoder::node() const {+ OPENVINO_ASSERT(m_node_idx >= 0 && static_cast<size_t>(m_node_idx) < m_graph->nodes.size(),+ "[gguf] node index out of range: ",+ m_node_idx);+ return m_graph->nodes[m_node_idx];+}++// ---- Per-node typed attribute ----+//+// In addition to keys stored in GgufOp::attributes, the following reserved keys are+// served so external converters can access per-input/output metadata through the public+// base NodeContext::get_attribute<T>() interface without including internal headers:+//+// "input_shape[N]" -> ov::PartialShape for input N (0-based)+// "input_type[N]" -> ov::element::Type for input N+// "input_stride[N]" -> std::vector<size_t> for input N+// "input_view_offset[N]" -> int64_t for input N+// "output_shape" -> ov::PartialShape of the node output+// "output_type" -> ov::element::Type of the node output+// "rope_config" -> RopeConfig (model-scope RoPE config; see get_attribute below)+// "swa_window_size" -> int (model-scope sliding-window length in tokens; 0 -> not+// configured in this model's metadata; see get_attribute below)++static bool parse_indexed_key(const std::string& name, const std::string& prefix, size_t& out_idx) {+ if (name.size() <= prefix.size() + 2)+ return false;+ if (name.compare(0, prefix.size(), prefix) != 0)+ return false;+ if (name[prefix.size()] != '[' || name.back() != ']')+ return false;+ try {+ out_idx = static_cast<size_t>(std::stoul(name.substr(prefix.size() + 1, name.size() - prefix.size() - 2)));+ return true;+ } catch (...) {+ return false;+ }+}++ov::Any GgufBuilderDecoder::get_attribute(const std::string& name) const {+ // RoPE config is queried at model scope (TranslateSession::preprocess, to build the shared+ // sin/cos table) and at node scope (each ROPE op's own config). At MODEL scope (no bound node)+ // expose the graph's config with per_op / n_dims==0 encoding "no shared table". At NODE scope+ // fall through to the node's own "rope_config" attribute -- the builder stores a per-node+ // config on each ROPE op (e.g. gemma4 SWA layers use a different freq_base / n_dims), so the+ // node value must win over the graph default.+ if (name == "rope_config" && m_node_idx < 0) {+ RopeConfig cfg = m_graph->rope_config;+ cfg.per_op = m_graph->use_per_op_rope;+ if (!m_graph->has_rope) {+ cfg.n_dims = 0;+ }+ return cfg;+ }++ // Sliding-window length, queried at model scope only (TranslateSession, to record it in+ // rt_info for AdaptToGenAI; see gguf_swa_window_key).+ if (name == "swa_window_size" && m_node_idx < 0) {+ return m_graph->swa_window_size;+ }++ const auto& n = node();++ // Reserved keys for per-input metadata+ size_t idx = 0;+ if (parse_indexed_key(name, "input_shape", idx)) {+ if (idx < n.input_names.size()) {+ auto it = n.input_shapes.find(n.input_names[idx]);+ if (it != n.input_shapes.end())+ return it->second;+ }+ return {};+ }+ if (parse_indexed_key(name, "input_type", idx)) {+ if (idx < n.input_names.size()) {+ auto it = n.input_types.find(n.input_names[idx]);+ if (it != n.input_types.end())+ return it->second;+ }+ return {};+ }+ if (parse_indexed_key(name, "input_stride", idx)) {+ if (idx < n.input_names.size()) {+ auto it = n.input_strides.find(n.input_names[idx]);+ if (it != n.input_strides.end())+ return it->second;+ }+ return {};+ }+ if (parse_indexed_key(name, "input_view_offset", idx)) {+ if (idx < n.input_names.size()) {+ auto it = n.input_view_offsets.find(n.input_names[idx]);+ return it != n.input_view_offsets.end() ? ov::Any(it->second) : ov::Any(int64_t{0});+ }+ return {};+ }++ // Reserved keys for per-output metadata+ if (name == "output_shape")+ return n.output_shape;+ if (name == "output_type")+ return n.output_type;++ // Per-node op case (the op translators read it via get_attribute<int>("op_case", 0)).+ if (name == "op_case")+ return n.op_case;++ // Named op attributes+ auto it = n.attributes.find(name);+ return it != n.attributes.end() ? it->second : ov::Any{};+}++// ---- Per-input metadata ----++PartialShape GgufBuilderDecoder::get_input_shape(const std::string& name) const {+ const auto& m = node().input_shapes;+ auto it = m.find(name);+ OPENVINO_ASSERT(it != m.end(), "[gguf] no input shape for '", name, "'");+ return it->second;+}++int64_t GgufBuilderDecoder::get_input_view_element_offset(const std::string& name) const {+ // The builder does not emit strided VIEW inputs (it materializes slices as explicit ops), so+ // there is no view offset to convert; the stored offsets, when present, are already in+ // elements. Return 0 when the input is not a view.+ const auto& m = node().input_view_offsets;+ auto it = m.find(name);+ return it == m.end() ? 0 : it->second;+}++size_t GgufBuilderDecoder::get_input_size() const {+ return node().input_names.size();+}++std::vector<std::string> GgufBuilderDecoder::get_input_names() const {+ return node().input_names;+}++// ---- Per-node output metadata ----++PartialShape GgufBuilderDecoder::get_output_shape() const {+ return node().output_shape;+}++std::vector<std::string> GgufBuilderDecoder::get_output_names() const {+ return {node().output_name};+}++// ---- Op type / name ----++const std::string& GgufBuilderDecoder::get_op_type() const {+ return node().op_type;+}++const std::string& GgufBuilderDecoder::get_op_name() const {+ return node().name;+}++void GgufBuilderDecoder::visit_subgraph(std::function<void(std::shared_ptr<GgufDecoder>)> node_visitor) const {+ for (size_t i = 0; i < m_graph->nodes.size(); i++) {+ auto per_node = std::make_shared<GgufBuilderDecoder>(*this);+ per_node->m_node_idx = static_cast<int>(i);+ node_visitor(per_node);+ }+}++// ---- Model-level I/O ----++const std::map<std::string, std::shared_ptr<ov::Node>>& GgufBuilderDecoder::get_model_inputs() const {+ return m_graph->model_inputs;+}++const std::map<std::string, std::shared_ptr<ov::Node>>& GgufBuilderDecoder::get_model_extra_inputs() const {+ return m_graph->model_extra_inputs;+}++std::vector<std::string> GgufBuilderDecoder::get_model_output_names() const {+ return m_graph->model_output_names;+}++const std::vector<std::pair<std::string, std::string>>& GgufBuilderDecoder::get_recurrent_states() const {+ return m_graph->recurrent_states;+}++const ov::AnyMap& GgufBuilderDecoder::get_tokenizer_config() const {+ return m_graph->tokenizer_config;+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp b/src/frontends/gguf/src/builder/gguf_builder_decoder.hppnew file mode 100644index 00000000000..8252236412e--- /dev/null+++ b/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp@@ -0,0 +1,59 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>++#include "gguf_graph.hpp"+#include "openvino/frontend/gguf/decoder.hpp"++namespace ov {+namespace frontend {+namespace gguf {++// GgufDecoder implementation over a GgufGraph built natively from a .gguf file (no+// llama.cpp / gguf dependency). It is the OpenVINO-side counterpart of llama.cpp's+// cgraph-backed GgmlOvDecoder: both feed the same op translators / TranslateSession.+//+// The whole-graph constructor wraps a complete GgufGraph. Following the node-scoped+// GgufDecoder contract, visit_subgraph hands the translator a per-node view by cloning+// this decoder with a fixed node index (m_node_idx); every per-node accessor then reads+// the node it is bound to, so no node index is threaded through the interface.+class GgufBuilderDecoder : public GgufDecoder {+public:+ explicit GgufBuilderDecoder(std::shared_ptr<GgufGraph> graph);++ // Per-node accessors (bound to the node this decoder instance was cloned for).+ ov::Any get_attribute(const std::string& name) const override;+ PartialShape get_input_shape(const std::string& name) const override;+ int64_t get_input_view_element_offset(const std::string& name) const override;+ size_t get_input_size() const override;+ std::vector<std::string> get_input_names() const override;+ PartialShape get_output_shape() const override;+ std::vector<std::string> get_output_names() const override;+ const std::string& get_op_type() const override;+ const std::string& get_op_name() const override;++ void visit_subgraph(std::function<void(std::shared_ptr<GgufDecoder>)> node_visitor) const override;++ // Model-level I/O.+ const std::map<std::string, std::shared_ptr<ov::Node>>& get_model_inputs() const override;+ const std::map<std::string, std::shared_ptr<ov::Node>>& get_model_extra_inputs() const override;+ std::vector<std::string> get_model_output_names() const override;+ const std::vector<std::pair<std::string, std::string>>& get_recurrent_states() const override;+ const ov::AnyMap& get_tokenizer_config() const override;++private:+ std::shared_ptr<GgufGraph> m_graph;+ // Index of the node this decoder instance is bound to. -1 for the whole-graph decoder+ // (only model-scope queries are valid on it).+ int m_node_idx = -1;++ const GgufOp& node() const;+};++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/gguf_graph.hpp b/src/frontends/gguf/src/builder/gguf_graph.hppnew file mode 100644index 00000000000..cf910d21486--- /dev/null+++ b/src/frontends/gguf/src/builder/gguf_graph.hpp@@ -0,0 +1,91 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <map>+#include <memory>+#include <string>+#include <vector>++#include "openvino/core/any.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/partial_shape.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/frontend/gguf/decoder.hpp"++namespace ov {+namespace frontend {+namespace gguf {++// One operation node in the GGUF-built graph, expressed in the GGML op vocabulary+// ("GGML_OP_MUL_MAT", "GGML_OP_ROPE", ...). It mirrors exactly what the GgufDecoder+// interface exposes per node, so GgufBuilderDecoder is a thin accessor over it. The arch+// builder fills these by construction, so all per-op parameters are typed attributes (no+// raw gguf op_params layout).+struct GgufOp {+ std::string op_type; // e.g. "GGML_OP_MUL_MAT"+ std::string name; // unique node/op name+ std::vector<std::string> input_names; // producer tensor names (weights / inputs / other nodes)+ std::string output_name; // this node's output tensor name+ ov::PartialShape output_shape;+ ov::element::Type output_type = ov::element::dynamic;+ int op_case = 0;++ // Per-input shape/stride/type and view-offset, keyed by input name. Populated for the+ // inputs that translators query (shapes for MUL_MAT/RESHAPE, view offsets for VIEW).+ std::map<std::string, ov::PartialShape> input_shapes;+ std::map<std::string, std::vector<size_t>> input_strides;+ std::map<std::string, ov::element::Type> input_types;+ std::map<std::string, int64_t> input_view_offsets;++ // Typed scalar/struct op attributes consumed by translators via get_attribute<T>+ // (e.g. "eps", "scale", "bias", "max_bias", "swapped", "rope_config").+ std::map<std::string, ov::Any> attributes;+};++// The whole model as a flat, topologically-ordered list of GgufOp nodes plus the+// model-level I/O the decoder reports. Built by an architecture builder (e.g. qwen3) from+// a parsed GGUF file; consumed by GgufBuilderDecoder.+struct GgufGraph {+ std::vector<GgufOp> nodes;++ // Model inputs (Parameters) and extra inputs (e.g. attention_size; Parameter or Constant).+ // Same semantics as the corresponding GgufDecoder getters. Weights are not here: they are+ // emitted into `nodes` as GGML_OP_NONE leaves (see emit_weight_op).+ std::map<std::string, std::shared_ptr<ov::Node>> model_inputs;+ std::map<std::string, std::shared_ptr<ov::Node>> model_extra_inputs;+ std::vector<std::string> model_output_names;++ // Recurrent (overwritten, non-appending) states as {input name, output name} pairs; see+ // GgufDecoder::get_recurrent_states. Empty for every architecture without linear attention.+ std::vector<std::pair<std::string, std::string>> recurrent_states;++ bool has_rope = false;+ RopeConfig rope_config;++ // When true, each ROPE op builds its own sin/cos table from its per-op rope_config+ // (useful when different layers need different n_dims, e.g. gemma4 SWA vs global).+ // TranslateSession::add_rope_sin_cos skips the shared table when this is set.+ bool use_per_op_rope = false;++ // Sliding-window length in tokens, from the GGUF metadata (0 -> not configured: either the+ // model has no SWA, or its SWA is described only by sinks / a per-layer boolean pattern with+ // no explicit token count). TranslateSession records this in rt_info (see+ // pass::gguf_swa_window_key) so AdaptToGenAI can build a correctly windowed self_kq_mask_swa+ // instead of reusing the full causal mask.+ int swa_window_size = 0;++ // GGUF tokenizer metadata (the `tokenizer.*` keys), keyed by the sub-key after the last+ // dot (e.g. "model", "tokens", "merges", "scores", "token_type", "pre", "bos_token_id",+ // "chat_template"). Values are std::string / std::vector<std::string> / ov::Tensor,+ // mirroring the GGUF metadata variant. Attached to the model's (non-serializable) rt_info+ // by TranslateSession so a downstream consumer can build the tokenizer without re-reading+ // the .gguf. Empty if the file carries no tokenizer metadata.+ ov::AnyMap tokenizer_config;+};++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/graph_emitter.cpp b/src/frontends/gguf/src/builder/graph_emitter.cppnew file mode 100644index 00000000000..333422c9560--- /dev/null+++ b/src/frontends/gguf/src/builder/graph_emitter.cpp@@ -0,0 +1,240 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "graph_emitter.hpp"++#include "openvino/core/except.hpp"+#include "openvino/op/constant.hpp"++namespace ov {+namespace frontend {+namespace gguf {++namespace {++// Split "<something>.weight" into "<something>"; return the name unchanged when it does not end+// in ".weight" (biases and other plain tensors keep their full name as the base).+std::string strip_weight_suffix(const std::string& name) {+ static const std::string suffix = ".weight";+ const bool ends_with_weight =+ name.size() > suffix.size() && name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0;+ return ends_with_weight ? name.substr(0, name.size() - suffix.size()) : name;+}++} // namespace++GraphEmitter::GraphEmitter(std::unordered_map<std::string, ov::Tensor>& weights,+ std::unordered_map<std::string, gguf_tensor_type>& qtypes,+ std::string arch)+ : m_weights(weights),+ m_qtypes(qtypes),+ m_arch(std::move(arch)),+ m_graph(std::make_shared<GgufGraph>()) {}++const ov::Tensor& GraphEmitter::weight_tensor(const std::string& name) const {+ auto it = m_weights.find(name);+ OPENVINO_ASSERT(it != m_weights.end(),+ "[GGUF] model is missing expected weight tensor '",+ name,+ "' for architecture '",+ m_arch,+ "'");+ return it->second;+}++int64_t GraphEmitter::weight_rows(const std::string& name) const {+ auto it = m_weights.find(name);+ if (it == m_weights.end()) {+ return 1;+ }+ const auto& s = it->second.get_shape();+ return s.empty() ? 1 : static_cast<int64_t>(s[0]);+}++const ov::PartialShape& GraphEmitter::shape_of_tensor(const std::string& name) const {+ auto it = m_tensor_shapes.find(name);+ OPENVINO_ASSERT(it != m_tensor_shapes.end(), "[GGUF] internal: no shape recorded for '", name, "'");+ return it->second;+}++ov::Shape GraphEmitter::static_shape_of(const std::string& tensor_name) const {+ const auto& shape = shape_of_tensor(tensor_name);+ OPENVINO_ASSERT(shape.is_static(),+ "[GGUF] internal: shape of '",+ tensor_name,+ "' is dynamic (",+ shape,+ "), cannot be used as a static input shape");+ return shape.to_shape();+}++void GraphEmitter::set_tensor_meta(const std::string& name, const ov::PartialShape& shape, ov::element::Type type) {+ m_tensor_shapes[name] = shape;+ m_tensor_types[name] = type;+}++std::string GraphEmitter::add_op(const std::string& op_type,+ const std::string& name,+ const std::vector<std::string>& inputs,+ const ov::PartialShape& out_shape,+ ov::element::Type out_type,+ int op_case,+ std::map<std::string, ov::Any> attrs) {+ GgufOp op;+ op.op_type = op_type;+ op.name = name;+ op.input_names = inputs;+ op.output_name = name;+ op.output_shape = out_shape;+ op.output_type = out_type;+ op.op_case = op_case;+ op.attributes = std::move(attrs);+ // Fill per-input shape/type from known producers so translators that query them+ // (MUL_MAT, RESHAPE) get sane values.+ for (const auto& in : inputs) {+ if (auto it = m_tensor_shapes.find(in); it != m_tensor_shapes.end()) {+ op.input_shapes[in] = it->second;+ }+ if (auto it = m_tensor_types.find(in); it != m_tensor_types.end()) {+ op.input_types[in] = it->second;+ }+ }+ m_tensor_shapes[name] = out_shape;+ m_tensor_types[name] = out_type;+ m_graph->nodes.push_back(std::move(op));+ return name;+}++std::shared_ptr<ov::op::v0::Parameter> GraphEmitter::add_input(const std::string& name,+ ov::element::Type type,+ const ov::PartialShape& shape) {+ auto p = std::make_shared<ov::op::v0::Parameter>(type, shape);+ p->set_friendly_name(name);+ p->output(0).set_names({name});+ m_graph->model_inputs[name] = p;+ return p;+}++void GraphEmitter::add_extra_input(const std::string& name, int64_t value) {+ auto c = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {value});+ c->set_friendly_name(name);+ m_graph->model_extra_inputs[name] = c;+}++void GraphEmitter::add_extra_input_node(const std::string& name, const std::shared_ptr<ov::Node>& node) {+ m_graph->model_extra_inputs[name] = node;+}++void GraphEmitter::emit_weight_op(const std::string& node_name,+ const std::unordered_map<std::string, ov::Tensor>& extracted,+ gguf_tensor_type qtype,+ const ov::PartialShape& shape_4d) {+ if (m_emitted_weights.count(node_name)) {+ return;+ }+ m_emitted_weights.insert(node_name);++ GgufOp op;+ op.op_type = "GGML_OP_NONE";+ op.name = node_name;+ op.output_name = node_name;+ op.output_shape = shape_4d;+ op.output_type = ov::element::f32;+ // translate_weight rebuilds the make_weight_node(base, weights, qtypes) inputs from these:+ // "gguf.blob.<sub>" -> extracted tensor (<sub> in {weight, scales, zp}), and the qtype id.+ op.attributes["gguf_weight"] = true; // marks this GGML_OP_NONE leaf as a weight+ op.attributes["gguf_qtype"] = static_cast<int>(qtype);+ for (const auto& kv : extracted) {+ const std::string& full = kv.first; // "<base>.weight" / ".scales" / ".zp"+ auto dot = full.rfind('.');+ std::string sub = (dot == std::string::npos) ? full : full.substr(dot + 1);+ op.attributes["gguf.blob." + sub] = kv.second;+ }+ m_graph->nodes.push_back(std::move(op));++ m_tensor_shapes[node_name] = shape_4d;+ m_tensor_types[node_name] = ov::element::f32;+}++void GraphEmitter::add_weight(const std::string& ggml_name) {+ if (m_emitted_weights.count(ggml_name)) {+ return;+ }+ const std::string base = strip_weight_suffix(ggml_name);++ // Collect the parser's extracted tensors for this weight (weight [+ scales [+ zp]]).+ std::unordered_map<std::string, ov::Tensor> extracted;+ for (const char* sub : {".weight", ".scales", ".zp"}) {+ auto it = m_weights.find(base + sub);+ if (it != m_weights.end()) {+ extracted[base + sub] = it->second;+ }+ }+ gguf_tensor_type qtype = GGUF_TYPE_F16;+ if (auto it = m_qtypes.find(base + ".qtype"); it != m_qtypes.end()) {+ qtype = it->second;+ }++ // Shape padded to the decoder's rank-4 convention; the extents matter only as the+ // per-input shape/type for translators (MUL_MAT) that index dims [1] and [3].+ int64_t rows = 1, cols = 1;+ if (auto it = m_weights.find(ggml_name); it != m_weights.end()) {+ const auto& s = it->second.get_shape(); // [rows, cols(packed)]+ rows = s.size() >= 1 ? static_cast<int64_t>(s[0]) : 1;+ cols = s.size() >= 2 ? static_cast<int64_t>(s[1]) : 1;+ }+ emit_weight_op(ggml_name, extracted, qtype, ov::PartialShape({1, 1, rows, cols}));+}++void GraphEmitter::add_weight_from(const std::string& node_name, const std::string& src_base) {+ if (m_emitted_weights.count(node_name)) {+ return;+ }+ const std::string dst_base = strip_weight_suffix(node_name);+ std::unordered_map<std::string, ov::Tensor> extracted;+ for (const char* sub : {".weight", ".scales", ".zp"}) {+ auto it = m_weights.find(src_base + sub);+ if (it != m_weights.end()) {+ extracted[dst_base + sub] = it->second;+ }+ }+ gguf_tensor_type qtype = GGUF_TYPE_F16;+ if (auto it = m_qtypes.find(src_base + ".qtype"); it != m_qtypes.end()) {+ qtype = it->second;+ }+ int64_t rows = 1, cols = 1;+ if (auto it = m_weights.find(src_base + ".weight"); it != m_weights.end()) {+ const auto& s = it->second.get_shape();+ rows = s.size() >= 1 ? static_cast<int64_t>(s[0]) : 1;+ cols = s.size() >= 2 ? static_cast<int64_t>(s[1]) : 1;+ }+ emit_weight_op(node_name, extracted, qtype, ov::PartialShape({1, 1, rows, cols}));+}++void GraphEmitter::add_named_weight(const std::string& ggml_name) {+ if (m_emitted_weights.count(ggml_name)) {+ return;+ }+ auto it = m_weights.find(ggml_name);+ OPENVINO_ASSERT(it != m_weights.end(), "[GGUF] weight not found in gguf: ", ggml_name);+ const ov::Tensor& w = it->second;+ // Map the OV element type back to the ggml float qtype so translate_weight rebuilds a plain+ // Constant of the right precision.+ gguf_tensor_type qtype = w.get_element_type() == ov::element::f32 ? GGUF_TYPE_F32+ : w.get_element_type() == ov::element::bf16 ? GGUF_TYPE_BF16+ : GGUF_TYPE_F16;+ // emit_weight_op re-keys by the last '.'; a bias ends in ".bias", so key it as ".weight"+ // explicitly (make_weight_node's plain-Constant path reads "<base>.weight").+ std::unordered_map<std::string, ov::Tensor> extracted{{ggml_name + ".weight", w}};+ const auto& s = w.get_shape();+ int64_t n = s.empty() ? 1 : static_cast<int64_t>(s[0]);+ // 2-D plain weights (qwen35's ssm_conv1d, OV [conv_dim, d_conv]) keep both extents;+ // 1-D ones (biases, norm scales) are the common case and stay a trailing vector.+ const ov::PartialShape shape = s.size() == 2 ? ps({1, 1, n, static_cast<int64_t>(s[1])}) : ps({1, 1, 1, n});+ emit_weight_op(ggml_name, extracted, qtype, shape);+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/graph_emitter.hpp b/src/frontends/gguf/src/builder/graph_emitter.hppnew file mode 100644index 00000000000..ea18ed0b975--- /dev/null+++ b/src/frontends/gguf/src/builder/graph_emitter.hpp@@ -0,0 +1,164 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <map>+#include <memory>+#include <set>+#include <string>+#include <unordered_map>+#include <vector>++#include "gguf_graph.hpp"+#include "openvino/core/any.hpp"+#include "openvino/core/partial_shape.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/runtime/tensor.hpp"+#include "quant/gguf.hpp"++namespace ov {+namespace frontend {+namespace gguf {++// Appends nodes to a GgufGraph and tracks the shape/type of every tensor emitted so far.+//+// This is the whole "how do I write a node" layer, and it knows nothing about transformers,+// attention or any architecture: it is the GGUF-frontend counterpart of ggml's ggml_context ++// ggml_build_forward_expand. Everything above it (the block library in blocks/, the per-family+// topology builders in arch/) is expressed purely in terms of these calls, which is what lets a+// non-decoder family (mmproj/vision, audio) reuse it verbatim.+//+// Owns the emit-time bookkeeping the graph itself does not carry:+// - tensor shapes/types, so add_op can fill each node's per-input shape/type metadata for the+// translators that query it (MUL_MAT, RESHAPE, VIEW);+// - the set of already-emitted weight leaves, so a weight referenced by several ops (or tied,+// e.g. MQA tie-V) is emitted exactly once.+class GraphEmitter {+public:+ // `weights` / `qtypes` are the parser's tensor tables; they are referenced, not copied, and+ // must outlive the emitter.+ GraphEmitter(std::unordered_map<std::string, ov::Tensor>& weights,+ std::unordered_map<std::string, gguf_tensor_type>& qtypes,+ std::string arch);++ // ---- graph under construction ----+ const std::shared_ptr<GgufGraph>& graph() const {+ return m_graph;+ }++ // ---- weight-table queries ----+ bool has_weight(const std::string& name) const {+ return m_weights.count(name) > 0;+ }++ // Look up a weight tensor by GGUF name, failing with the tensor NAME if the GGUF is missing it+ // (a bare .at(name) throws std::out_of_range with no context). Used wherever a builder reads a+ // weight's shape to size an op; a missing expected tensor means the file does not match the+ // detected architecture.+ const ov::Tensor& weight_tensor(const std::string& name) const;++ // First extent of a weight's OV shape (its row count), 1 when the weight is absent/scalar.+ int64_t weight_rows(const std::string& name) const;++ std::unordered_map<std::string, ov::Tensor>& weights() {+ return m_weights;+ }+ std::unordered_map<std::string, gguf_tensor_type>& qtypes() {+ return m_qtypes;+ }++ // ---- emitted-tensor queries ----+ const ov::PartialShape& shape_of_tensor(const std::string& name) const;++ // Static shape of an already-emitted tensor, for ops whose translator needs its input's own+ // layout (VIEW op_case 3's "input_ggml_shape", which it uses to restore that layout before+ // slicing). Per-node shapes are static except for the model-input Parameters, so a dynamic dim+ // here means the caller asked about a tensor this cannot describe.+ ov::Shape static_shape_of(const std::string& tensor_name) const;++ // Record a shape/type for a tensor the emitter did not create itself (a model input reused as+ // an op input at a representative token length).+ void set_tensor_meta(const std::string& name, const ov::PartialShape& shape, ov::element::Type type);++ bool has_model_input(const std::string& name) const {+ return m_graph->model_inputs.count(name) > 0;+ }++ // ---- emission ----++ // Append one op node. `inputs` are producer tensor names (weights / model inputs / earlier node+ // outputs). Returns the output tensor name (== node name).+ std::string add_op(const std::string& op_type,+ const std::string& name,+ const std::vector<std::string>& inputs,+ const ov::PartialShape& out_shape,+ ov::element::Type out_type,+ int op_case = 0,+ std::map<std::string, ov::Any> attrs = {});++ std::shared_ptr<ov::op::v0::Parameter> add_input(const std::string& name,+ ov::element::Type type,+ const ov::PartialShape& shape);++ void add_extra_input(const std::string& name, int64_t value);++ void add_extra_input_node(const std::string& name, const std::shared_ptr<ov::Node>& node);++ // Emit a weight as a GGML_OP_NONE leaf node carrying the parser's already-extracted tensors+ // (`<base>.weight` [+ `.scales` [+ `.zp`]] + qtype) as node attributes. translate_weight+ // rebuilds the weights/qtypes maps from these attributes and calls make_weight_node(base,+ // weights, qtypes). Routing weights through GGML_OP_NONE makes that the single weight-loading+ // API, shared with the llama.cpp cgraph decoder (which marks the same leaf with raw ggml bytes+ // instead), and keeps the compressed decompression subgraph -- built lazily in translate_weight+ // during the walk -- rather than materializing an ov::Node eagerly here.+ // `node_name` is the tensor name translators reference (the GGML_OP_NONE output);+ // `extracted` maps "<base>.weight"/".scales"/".zp" -> tensor; `qtype` is the ggml type.+ void emit_weight_op(const std::string& node_name,+ const std::unordered_map<std::string, ov::Tensor>& extracted,+ gguf_tensor_type qtype,+ const ov::PartialShape& shape_4d);++ // `ggml_name` is the full tensor name ending in ".weight" (the name translators reference).+ void add_weight(const std::string& ggml_name);++ // Emit a weight node `node_name` (ends in ".weight") reusing the parser's extracted tensors of+ // another weight `src_base` (base without ".weight"). Used for MQA tie-V, where V shares K's+ // weight tensor; the two GGML_OP_NONE leaves reference the same underlying ov::Tensor blobs+ // (cheap: SharedBuffer views into the parser's single quant buffer).+ void add_weight_from(const std::string& node_name, const std::string& src_base);++ // Emit a plain (non-quantized) weight stored under its full GGUF name, e.g. a bias tensor+ // "blk.N.attn_q.bias" (no ".weight" suffix). It flows through the same GGML_OP_NONE ++ // translate_weight path; make_weight_node treats an F16/F32/BF16 blob as a plain Constant.+ void add_named_weight(const std::string& ggml_name);++ bool weight_emitted(const std::string& name) const {+ return m_emitted_weights.count(name) > 0;+ }++private:+ std::unordered_map<std::string, ov::Tensor>& m_weights;+ std::unordered_map<std::string, gguf_tensor_type>& m_qtypes;+ // Architecture name, used only to make a missing-tensor diagnostic actionable.+ std::string m_arch;++ std::shared_ptr<GgufGraph> m_graph;+ std::map<std::string, ov::PartialShape> m_tensor_shapes;+ std::map<std::string, ov::element::Type> m_tensor_types;+ // Names of weights already emitted as GGML_OP_NONE leaves, so a weight referenced by several+ // ops (or tied, e.g. MQA tie-V) is emitted once.+ std::set<std::string> m_emitted_weights;+};++// Shapes are kept in the OpenVINO/GGML logical order [ne3, ne2, ne1, ne0] (reverse of GGUF+// on-disk order), matching the decoder's get_shape(). The translators consume them as-is.+inline ov::PartialShape ps(std::vector<int64_t> dims) {+ return ov::PartialShape(std::move(dims));+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/model_builder.hpp b/src/frontends/gguf/src/builder/model_builder.hppnew file mode 100644index 00000000000..1c1dd9e83e5--- /dev/null+++ b/src/frontends/gguf/src/builder/model_builder.hpp@@ -0,0 +1,40 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>++#include "builder/gguf_graph.hpp"++namespace ov {+namespace frontend {+namespace gguf {++// Base class for a whole-model graph builder: one subclass per MODEL FAMILY, not per architecture.+//+// A family is a distinct graph SHAPE with its own inputs, its own block vocabulary and its own+// notion of a "layer": the causal decoder stack (DecoderBuilder, arch/decoder_builder.hpp) is one;+// a vision/mmproj encoder or an audio encoder would each be another. Within a family, individual+// architectures are data, not code -- they are detected from the GGUF tensor table and metadata+// (see DecoderConfig) and enabled by name in arch_registry.cpp.+//+// This mirrors llama.cpp's split between llm_graph_context (LLMs) and clip_graph (mmproj), where+// each family has its own base and its own build_norm/build_ffn/build_attn vocabulary, rather than+// one builder growing flags for structurally unrelated models.+//+// To add a family: subclass this, implement build(), and dispatch to it from+// build_ggml_graph_from_gguf() on the detected ModelKind. Nothing in the existing families needs+// to change, and the arch-agnostic pieces (GraphEmitter, blocks/common) are reused as-is.+class ModelBuilder {+public:+ virtual ~ModelBuilder() = default;++ // Emit the whole model and return the finished graph.+ virtual std::shared_ptr<GgufGraph> build() = 0;+};++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/model_kind.cpp b/src/frontends/gguf/src/builder/model_kind.cppnew file mode 100644index 00000000000..8233c295ff5--- /dev/null+++ b/src/frontends/gguf/src/builder/model_kind.cpp@@ -0,0 +1,68 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "builder/model_kind.hpp"++#include <variant>++namespace ov {+namespace frontend {+namespace gguf {++namespace {++// Read a GGUF bool-ish metadata key. The parser stores every scalar as a shape-{} ov::Tensor, so a+// GGUF_VALUE_TYPE_BOOL arrives as an element::boolean tensor; accept an integer tensor too, since+// some writers emit these flags as u8/u32. Absent or non-scalar means false.+bool meta_flag(const std::unordered_map<std::string, GGUFMetaData>& metadata, const std::string& key) {+ auto it = metadata.find(key);+ if (it == metadata.end()) {+ return false;+ }+ const auto* t = std::get_if<ov::Tensor>(&it->second);+ if (!t || t->get_size() != 1) {+ return false;+ }+ if (t->get_element_type() == ov::element::boolean) {+ return *t->data<char>() != 0;+ }+ if (t->get_element_type() == ov::element::u8) {+ return *t->data<uint8_t>() != 0;+ }+ if (t->get_element_type() == ov::element::u32) {+ return *t->data<uint32_t>() != 0;+ }+ return false;+}++} // namespace++ModelKind detect_model_kind(const std::unordered_map<std::string, GGUFMetaData>& metadata) {+ // Check the clip.* flags before the architecture: an mmproj file's general.architecture is+ // "clip", which is not an LLM architecture name, and reading any "<arch>.block_count"-style+ // key on it would fail with a misleading "missing config key" error.+ if (meta_flag(metadata, "clip.has_vision_encoder")) {+ return ModelKind::Vision;+ }+ if (meta_flag(metadata, "clip.has_audio_encoder")) {+ return ModelKind::Audio;+ }+ return ModelKind::Decoder;+}++const char* model_kind_name(ModelKind kind) {+ switch (kind) {+ case ModelKind::Vision:+ return "vision (mmproj)";+ case ModelKind::Audio:+ return "audio (mmproj)";+ case ModelKind::Decoder:+ default:+ return "decoder";+ }+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/builder/model_kind.hpp b/src/frontends/gguf/src/builder/model_kind.hppnew file mode 100644index 00000000000..f543aa4b0aa--- /dev/null+++ b/src/frontends/gguf/src/builder/model_kind.hpp@@ -0,0 +1,42 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>+#include <unordered_map>++#include "quant/gguf.hpp"++namespace ov {+namespace frontend {+namespace gguf {++// Which FAMILY of model a .gguf file holds. This is the first thing the builder decides, before+// any hyperparameter is read, because the metadata key layout itself differs per family: a causal+// decoder carries "<arch>.block_count" / "<arch>.attention.head_count", while an mmproj file+// carries "clip.*" keys and none of those.+//+// It is deliberately NOT the architecture. Architectures within a family (llama, qwen3, gemma4,+// ...) are data, detected from the tensor table; families are code, one ModelBuilder subclass+// each.+enum class ModelKind {+ Decoder, // causal decoder-only LLM: the "llama family" (dense + MoE + hybrid recurrent)+ Vision, // mmproj vision encoder + projector (clip.has_vision_encoder)+ Audio, // mmproj audio encoder + projector (clip.has_audio_encoder)+};++// Classify a parsed GGUF file from its raw metadata.+//+// mmproj files written by llama.cpp set general.architecture = "clip" and carry+// clip.has_vision_encoder / clip.has_audio_encoder (see llama.cpp tools/mtmd/clip-impl.h+// KEY_HAS_VISION_ENC / KEY_HAS_AUDIO_ENC); every LLM GGUF names its own architecture instead.+ModelKind detect_model_kind(const std::unordered_map<std::string, GGUFMetaData>& metadata);++// Human-readable name for a kind, used in diagnostics.+const char* model_kind_name(ModelKind kind);++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/frontend.cpp b/src/frontends/gguf/src/frontend.cppindex 4c6330fa4d4..3f294c21dc2 100644--- a/src/frontends/gguf/src/frontend.cpp+++ b/src/frontends/gguf/src/frontend.cpp@@ -4,9 +4,15 @@#include "openvino/frontend/gguf/frontend.hpp"+#include <filesystem>+#include <fstream>++#include "builder/gguf_builder.hpp"+#include "builder/gguf_builder_decoder.hpp"#include "input_model.hpp"#include "op_table.hpp"#include "openvino/core/so_extension.hpp"+#include "openvino/frontend/common/path_util.hpp"#include "openvino/frontend/extension/conversion.hpp"#include "openvino/frontend/extension/decoder_transformation.hpp"#include "openvino/frontend/extension/telemetry.hpp"@@ -18,8 +24,10 @@ namespace ov {namespace frontend {namespace gguf {-// The frontend converts a live GgufDecoder -- supplied by a direct linker, currently the llama.cpp-// ggml-openvino backend -- through the op translators below.+// This frontend has two ingest paths, both converging on the same GgufDecoder + op translators:+// 1. a live GgufDecoder passed in by a direct linker (the llama.cpp ggml-openvino cgraph path);+// 2. a .gguf file path (the OpenVINO-native path): the frontend parses the container and builds+// the transformer graph per-architecture via the native builder (see load_impl Path 2).//// Discoverability: "gguf" is in manager.cpp's is_hidden_frontend list, so it is not advertised by// available_front_ends() and not auto-selected by load_by_model (core.read_model(".gguf") does@@ -52,6 +60,17 @@ std::unordered_map<std::string, CreatorFunction> merged_ops(return ops;}+// True if the file at `path` begins with the GGUF magic ("GGUF").+bool has_gguf_magic(const std::filesystem::path& path) {+ std::ifstream f(path, std::ios::binary);+ if (!f) {+ return false;+ }+ char magic[4] = {};+ f.read(magic, sizeof(magic));+ return f.gcount() == 4 && magic[0] == 'G' && magic[1] == 'G' && magic[2] == 'U' && magic[3] == 'F';+}+} // namespaceFrontEnd::FrontEnd() : m_impl(std::make_shared<Impl>()) {}@@ -97,18 +116,47 @@ void FrontEnd::add_extension(const std::shared_ptr<ov::Extension>& extension) {}bool FrontEnd::supported_impl(const std::vector<ov::Any>& variants) const {- return !variants.empty() && variants[0].is<std::shared_ptr<GgufDecoder>>();+ // Two accepted inputs:+ // 1. a GgufDecoder (the llama.cpp cgraph path passes one in directly), or+ // 2. a path to a .gguf file (the OpenVINO-native path; sniff the GGUF magic).+ if (variants.empty()) {+ return false;+ }+ if (variants[0].is<std::shared_ptr<GgufDecoder>>()) {+ return true;+ }+ if (auto path = ov::frontend::get_path_from_any(variants[0])) {+ std::filesystem::path model_path = std::move(*path);+ return model_path.extension() == ".gguf" && has_gguf_magic(model_path);+ }+ return false;}InputModel::Ptr FrontEnd::load_impl(const std::vector<ov::Any>& variants) const {FRONT_END_GENERAL_CHECK(!variants.empty(),"GGUF Frontend requires at least one parameter in model representation.");- FRONT_END_GENERAL_CHECK(variants[0].is<std::shared_ptr<GgufDecoder>>(),- "GGUF Frontend supports loading from a GgufDecoder only.");- auto decoder = variants[0].as<std::shared_ptr<GgufDecoder>>();- FRONT_END_GENERAL_CHECK(decoder, "Couldn't cast ov::Any to std::shared_ptr<GgufDecoder>");- return std::make_shared<InputModel>(decoder);+ // Path 1: a GgufDecoder passed in directly (e.g. llama.cpp cgraph decoder).+ if (variants[0].is<std::shared_ptr<GgufDecoder>>()) {+ auto decoder = variants[0].as<std::shared_ptr<GgufDecoder>>();+ FRONT_END_GENERAL_CHECK(decoder, "Couldn't cast ov::Any to std::shared_ptr<GgufDecoder>");+ return std::make_shared<InputModel>(decoder);+ }++ // Path 2: a .gguf file path -> native builder -> GgufBuilderDecoder.+ if (auto path = ov::frontend::get_path_from_any(variants[0])) {+ std::filesystem::path model_path = std::move(*path);+ FRONT_END_GENERAL_CHECK(model_path.extension() == ".gguf",+ "GGUF Frontend file loading expects a .gguf file, got: ",+ model_path.string());+ auto graph = build_ggml_graph_from_gguf(model_path.string());+ auto decoder = std::make_shared<GgufBuilderDecoder>(graph);+ return std::make_shared<InputModel>(decoder);+ }++ FRONT_END_GENERAL_CHECK(false,+ "GGUF Frontend doesn't support the provided model representation. Provide a GgufDecoder "+ "or a path to a .gguf file.");}} // namespace ggufdiff --git a/src/frontends/gguf/src/input_model.cpp b/src/frontends/gguf/src/input_model.cppindex 3237a219d14..f6a65289b09 100644--- a/src/frontends/gguf/src/input_model.cpp+++ b/src/frontends/gguf/src/input_model.cpp@@ -20,6 +20,10 @@ std::vector<std::string> InputModel::get_model_output_names() const {return m_decoder->get_model_output_names();}+const std::vector<std::pair<std::string, std::string>>& InputModel::get_recurrent_states() const {+ return m_decoder->get_recurrent_states();+}+RopeConfig InputModel::get_rope_config() const {// A decoder bound to a full LLM graph exposes "rope_config"; a decoder wrapping a bare op /// small cgraph (the former "naive" path) has no such attribute. Return a default configdiff --git a/src/frontends/gguf/src/input_model.hpp b/src/frontends/gguf/src/input_model.hppindex 2bc1af43539..c5224c43b54 100644--- a/src/frontends/gguf/src/input_model.hpp+++ b/src/frontends/gguf/src/input_model.hpp@@ -33,6 +33,7 @@ public:// Model-scope topology (forwarded to the underlying decoder's model-scope accessors).const std::map<std::string, std::shared_ptr<ov::Node>>& get_model_inputs() const;std::vector<std::string> get_model_output_names() const;+ const std::vector<std::pair<std::string, std::string>>& get_recurrent_states() const;RopeConfig get_rope_config() const;void visit_subgraph(const std::function<void(std::shared_ptr<GgufDecoder>)>& node_visitor) const;diff --git a/src/frontends/gguf/src/op/cont.cpp b/src/frontends/gguf/src/op/cont.cppindex 3e252b9a251..82e68f26ec3 100644--- a/src/frontends/gguf/src/op/cont.cpp+++ b/src/frontends/gguf/src/op/cont.cpp@@ -53,6 +53,7 @@ OutputVector translate_cont(const NodeContext & context) {if (!tgt.empty()) {auto tgt_node = ov::op::v0::Constant::create(ov::element::i64, {tgt.size()}, tgt);res = std::make_shared<ov::op::v1::Reshape>(input, tgt_node, false);+ res.get_node_shared_ptr()->set_friendly_name("cont_reshape_" + context.get_name());return rename_outputs_with_suffix({res}, context.get_name());}res = input;diff --git a/src/frontends/gguf/src/op/cpy.cpp b/src/frontends/gguf/src/op/cpy.cppindex d6659d04ca0..a474b91c35f 100644--- a/src/frontends/gguf/src/op/cpy.cpp+++ b/src/frontends/gguf/src/op/cpy.cpp@@ -6,12 +6,20 @@#include "op_table.hpp"#include "utils.hpp"+#include <climits>#include <cstdint>#include <memory>#include <vector>+#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/gather.hpp"+#include "openvino/op/reduce_prod.hpp"#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/slice.hpp"namespace ov {namespace frontend {@@ -19,6 +27,130 @@ namespace gguf {namespace op {OutputVector translate_cpy(const NodeContext & context) {+ const int op_case = context.get_op_case();+ const auto input_shape = context.get_input_shape(0);+ const auto output_shape = context.get_output_shape();++ if (op_case == 1 &&+ (context.get_input_size() == 1 || !context.has_input(context.get_input_names()[1]))) {+ ov::Output<ov::Node> value = context.get_input(0);+ // The translated GDN value intentionally has a dynamic packed-row axis, while the CPY's+ // declared input layout may already be reinterpreted as the destination cache. Get the+ // actual packed row width directly from the producing GGML tensor metadata.+ const int64_t packed_width = context.get_attribute<int64_t>("gdn_packed_width", -1);+ FRONT_END_OP_CONVERSION_CHECK(packed_width > 0, "GDN cache copy requires a static packed-row width");+ const int64_t state_rows = static_cast<int64_t>(ov::shape_size(output_shape.to_shape())) /+ packed_width;+ value = std::make_shared<ov::op::v8::Slice>(+ value,+ ov::op::v0::Constant::create(ov::element::i64, {1}, {-state_rows}),+ ov::op::v0::Constant::create(ov::element::i64, {1}, {INT_MAX}),+ ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),+ ov::op::v0::Constant::create(ov::element::i64, {1}, {2}));+ if (value.get_element_type() != context.get_output_type()) {+ value = std::make_shared<ov::op::v0::Convert>(value, context.get_output_type());+ }+ auto target = ov::op::v0::Constant::create(ov::element::i64, {output_shape.size()}, output_shape.to_shape());+ auto res = std::make_shared<ov::op::v1::Reshape>(value, target, false);+ return rename_outputs_with_suffix({res}, context.get_name());+ }++ if (op_case == 3 && input_shape.is_static() && ov::shape_size(input_shape.to_shape()) == 0) {+ return {context.get_input(1)};+ }++ if (op_case == 4) {+ ov::Output<ov::Node> src = context.get_input(0);+ auto base = context.get_input(1);++ int64_t n_elems = 1;+ for (const auto & dim : input_shape.to_shape()) {+ n_elems *= static_cast<int64_t>(dim);+ }++ const int64_t begin_val = context.get_attribute<int64_t>("cpy_output_offset_elems", 0);+ const int64_t end_val = begin_val + n_elems;+ auto flat_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, 1, -1});+ src = std::make_shared<ov::op::v1::Reshape>(src, flat_shape, false);+ if (src.get_element_type() != context.get_output_type()) {+ src = std::make_shared<ov::op::v0::Convert>(src, context.get_output_type());+ }++ auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto begin = ov::op::v0::Constant::create(ov::element::i64, {1}, {begin_val});+ auto end = ov::op::v0::Constant::create(ov::element::i64, {1}, {end_val});+ auto int_max = ov::op::v0::Constant::create(ov::element::i64, {1}, {INT_MAX});+ auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {3});+ auto head_part = std::make_shared<ov::op::v8::Slice>(base, zero, begin, one, axis);+ auto tail_part = std::make_shared<ov::op::v8::Slice>(base, end, int_max, one, axis);+ auto res = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{head_part, src, tail_part}, 3);+ return rename_outputs_with_suffix({res}, context.get_name());+ }++ const std::string writeback_name = context.get_attribute<std::string>("rs_writeback_name", context.get_name());+ const std::string slot_begin_name = "rs_slot_begin_" + writeback_name;+ if (context.has_input(slot_begin_name) && op_case >= 1 && op_case <= 3) {+ const int64_t slot_axis = 2;+ auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto int_max = ov::op::v0::Constant::create(ov::element::i64, {1}, {INT_MAX});+ auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {slot_axis});+ const int64_t feature_width = output_shape[3].get_length();+ auto reshape_writeback = [&](const ov::Output<ov::Node>& value) {+ auto value_shape = std::make_shared<ov::op::v3::ShapeOf>(value, ov::element::i64);+ auto total = std::make_shared<ov::op::v1::ReduceProd>(+ value_shape, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}), true);+ auto rows = std::make_shared<ov::op::v1::Divide>(+ total, ov::op::v0::Constant::create(ov::element::i64, {1}, {feature_width}));+ auto target = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{ov::op::v0::Constant::create(ov::element::i64, {2}, {1, 1}),+ rows,+ ov::op::v0::Constant::create(ov::element::i64, {1}, {feature_width})},+ 0);+ return std::make_shared<ov::op::v1::Reshape>(value, target, false);+ };++ ov::Output<ov::Node> src;+ auto begin = context.get_input(slot_begin_name);+ if (op_case == 1) {+ const int64_t packed_width = context.get_attribute<int64_t>("gdn_packed_width", -1);+ FRONT_END_OP_CONVERSION_CHECK(packed_width > 0, "GDN writeback requires a static packed-row width");+ const int64_t state_rows = output_shape[3].get_length() / packed_width;+ auto src_begin = ov::op::v0::Constant::create(ov::element::i64, {1}, {-state_rows});+ auto state_part =+ std::make_shared<ov::op::v8::Slice>(context.get_input(0), src_begin, int_max, one, axis);+ src = reshape_writeback(state_part);+ src.get_node_shared_ptr()->set_friendly_name("gdn_writeback_source_" + context.get_name());+ } else if (op_case == 2) {+ const int64_t window_size = input_shape[3].get_length();+ auto src_begin = context.get_input("rs_src_begin_" + writeback_name);+ auto src_end = std::make_shared<ov::op::v1::Add>(+ src_begin, ov::op::v0::Constant::create(ov::element::i64, {1}, {window_size}));+ auto window = std::make_shared<ov::op::v8::Slice>(+ context.get_input(0), src_begin, src_end, one,+ ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));+ src = reshape_writeback(window);+ src.get_node_shared_ptr()->set_friendly_name("conv_writeback_source_" + context.get_name());+ } else {+ src = context.get_input(0);+ }++ if (src.get_element_type() != context.get_output_type()) {+ src = std::make_shared<ov::op::v0::Convert>(src, context.get_output_type());+ }++ auto base = context.get_input(1);+ auto src_len = std::make_shared<ov::op::v8::Gather>(+ std::make_shared<ov::op::v3::ShapeOf>(src, ov::element::i64), axis,+ ov::op::v0::Constant::create(ov::element::i64, {}, {0}));+ auto end = std::make_shared<ov::op::v1::Add>(begin, src_len);+ auto head_part = std::make_shared<ov::op::v8::Slice>(base, zero, begin, one, axis);+ auto tail_part = std::make_shared<ov::op::v8::Slice>(base, end, int_max, one, axis);+ auto res = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{head_part, src, tail_part}, slot_axis);+ return rename_outputs_with_suffix({res}, context.get_name());+ }+ov::Output<ov::Node> res =std::make_shared<ov::op::v0::Convert>(context.get_input(0), context.get_attribute<ov::element::Type>("output_type"));diff --git a/src/frontends/gguf/src/op/get_rows.cpp b/src/frontends/gguf/src/op/get_rows.cppindex d2b5b204664..f83e74f1605 100644--- a/src/frontends/gguf/src/op/get_rows.cpp+++ b/src/frontends/gguf/src/op/get_rows.cpp@@ -29,6 +29,21 @@ OutputVector translate_get_rows(const NodeContext& context) {auto data = context.get_input(0);auto indices = context.get_input(1);+ if (op_case == 3) {+ return {data};+ }++ if (op_case == 4) {+ auto flat_indices = std::make_shared<ov::op::v0::Squeeze>(+ indices, ov::op::v0::Constant::create(ov::element::i64, {3}, {0, 1, 2}));+ auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {2});+ res = std::make_shared<ov::op::v8::Gather>(data, flat_indices, axis);+ if (res.get_element_type() != context.get_output_type()) {+ res = std::make_shared<ov::op::v0::Convert>(res, context.get_output_type());+ }+ return rename_outputs_with_suffix({res}, context.get_name());+ }+// MoE gating-weight gather (op_case 10): data = probs [1,1,T,E], indices = selected experts// [1,1,T,K]; per-row (GatherElements) gather over the expert axis picks each token's K// selected-expert probs -> [1,1,T,K], distinct from the embedding-style row gather below.diff --git a/src/frontends/gguf/src/op/mulmat.cpp b/src/frontends/gguf/src/op/mulmat.cppindex a84de78fe12..d6852284d49 100644--- a/src/frontends/gguf/src/op/mulmat.cpp+++ b/src/frontends/gguf/src/op/mulmat.cpp@@ -89,6 +89,11 @@ OutputVector translate_mulmat(const NodeContext & context) {res = std::make_shared<ov::op::v0::MatMul>(A, B, false, transpose_b);+ const auto output_type = context.get_output_type();+ if (res.get_element_type() != output_type) {+ res = std::make_shared<ov::op::v0::Convert>(res, output_type);+ }+return rename_outputs_with_suffix({res}, context.get_name());}diff --git a/src/frontends/gguf/src/op/permute.cpp b/src/frontends/gguf/src/op/permute.cppindex 67ecff63b97..bf29c2c68f8 100644--- a/src/frontends/gguf/src/op/permute.cpp+++ b/src/frontends/gguf/src/op/permute.cpp@@ -12,7 +12,9 @@#include "openvino/op/add.hpp"#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"+#include "openvino/op/gather.hpp"#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"#include "openvino/op/slice.hpp"#include "openvino/op/transpose.hpp"#include "utils.hpp"@@ -31,7 +33,8 @@ OutputVector translate_permute(const NodeContext& context) {ov::Output<Node> res;auto src = context.get_input(0);- auto perm = ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3});+ auto perm_order = context.get_attribute<std::vector<int64_t>>("perm", {0, 2, 1, 3});+ auto perm = ov::op::v0::Constant::create(ov::element::i64, {perm_order.size()}, perm_order);if (op_case == 1) {res = std::make_shared<ov::op::v1::Transpose>(src, perm);@@ -49,8 +52,13 @@ OutputVector translate_permute(const NodeContext& context) {// in an all-constant pattern that survives shape inference; both are metadata-only, so// this costs no extra data movement.auto neg_one = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});+ auto src_shape = std::make_shared<ov::op::v3::ShapeOf>(src, ov::element::i64);+ auto seq_count = std::make_shared<ov::op::v8::Gather>(+ src_shape,+ ov::op::v0::Constant::create(ov::element::i64, {1}, {0}),+ ov::op::v0::Constant::create(ov::element::i64, {}, {0}));auto seq_pattern =- std::make_shared<ov::op::v0::Concat>(ov::OutputVector{context.get_input("n_seq_active"), neg_one}, 0);+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{seq_count, neg_one}, 0);auto by_seq = std::make_shared<ov::op::v1::Reshape>(src, seq_pattern, false);auto head_pattern =@@ -69,18 +77,42 @@ OutputVector translate_permute(const NodeContext& context) {auto output_shape = context.get_output_shape().to_shape();int64_t head_size = output_shape[3];int64_t n_heads = output_shape[1];- int64_t ctx_per_seq = cache_shape[2].is_static() ? cache_shape[2].get_length() : -1;- int64_t n_seq = cache_shape[1].get_length();- Output<Node> attention_size;- if (!context.has_input("attention_size")) {- attention_size = ov::op::v0::Constant::create(ov::element::i64, {1}, {output_shape[2]});- } else if (op_case == 2) {- attention_size = context.get_input("attention_size");- } else {- attention_size = context.get_input("attention_size_swa");+ // Validation/integration graphs can surface the cache VIEW as an already expanded+ // [n_seq, ctx, n_head, head_size] tensor. In that form no layout-restoring Reshape is+ // needed; applying the legacy flattened-cache reshape would multiply the element count by+ // n_head (most visibly with several parallel sequences).+ const bool cache_is_expanded = cache_shape.rank().is_static() && cache_shape.rank().get_length() == 4 &&+ cache_shape[2].is_static() && cache_shape[3].is_static() &&+ cache_shape[2].get_length() == n_heads &&+ cache_shape[3].get_length() == head_size;+ if (cache_is_expanded) {+ ov::Output<Node> active_cache = src;+ const int64_t n_seq = cache_shape[0].is_static() ? cache_shape[0].get_length() : -1;+ if (n_seq != 1) {+ auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ Output<Node> seq_active_start;+ Output<Node> seq_active_end;+ if (context.has_input("seq_active_start")) {+ seq_active_start = context.get_input("seq_active_start");+ seq_active_end = context.get_input("seq_active_end");+ } else {+ const int64_t start = context.get_attribute<int64_t>("view_seq_offset", 0);+ seq_active_start = ov::op::v0::Constant::create(ov::element::i64, {1}, {start});+ seq_active_end = ov::op::v0::Constant::create(+ ov::element::i64, {1}, {start + static_cast<int64_t>(output_shape[0])});+ }+ active_cache = std::make_shared<ov::op::v8::Slice>(+ src, seq_active_start, seq_active_end, one, zero);+ }+ res = std::make_shared<ov::op::v1::Transpose>(active_cache, perm);+ return rename_outputs_with_suffix({res}, context.get_name());}+ int64_t ctx_per_seq = cache_shape[2].is_static() ? cache_shape[2].get_length() : -1;+ int64_t n_seq = cache_shape[1].get_length();+Output<Node> seq_active_start;Output<Node> seq_active_end;if (context.has_input("seq_active_start")) {@@ -98,8 +130,8 @@ OutputVector translate_permute(const NodeContext& context) {// 1. reshape to [n_seq, ctx_per_seq, n_heads, head_size]// 2. slice out the active sequences- // 3. slice out the attention part in each sequence- // 4. permute+ // 3. permute. The cache input is already bound with the runtime+ // attention extent; masked positions remain harmless.auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});@@ -107,9 +139,16 @@ OutputVector translate_permute(const NodeContext& context) {src,ov::op::v0::Constant::create(ov::element::i64, {4}, {n_seq, ctx_per_seq, n_heads, head_size}),false);- auto slice1 = std::make_shared<ov::op::v8::Slice>(src_reshaped, seq_active_start, seq_active_end, one, zero);- auto slice2 = std::make_shared<ov::op::v8::Slice>(slice1, zero, attention_size, one, one);- res = std::make_shared<ov::op::v1::Transpose>(slice2, perm);+ // A singleton cache can only have the active range [0, 1). Avoid expressing that no-op as+ // a runtime-bounded Slice: the CPU plugin can infer an empty first dimension for this+ // otherwise-static case, which then propagates through SDPA as a zero-token output. Keep+ // the slice for genuine multi-sequence caches where selecting the active window matters.+ ov::Output<Node> active_cache = src_reshaped;+ if (n_seq != 1) {+ active_cache =+ std::make_shared<ov::op::v8::Slice>(src_reshaped, seq_active_start, seq_active_end, one, zero);+ }+ res = std::make_shared<ov::op::v1::Transpose>(active_cache, perm);}return rename_outputs_with_suffix({res}, context.get_name());}diff --git a/src/frontends/gguf/src/op/rope.cpp b/src/frontends/gguf/src/op/rope.cppindex d9dedc5dc01..d2f91d50c72 100644--- a/src/frontends/gguf/src/op/rope.cpp+++ b/src/frontends/gguf/src/op/rope.cpp@@ -89,6 +89,11 @@ OutputVector translate_rope(const NodeContext& context) {data = std::make_shared<ov::op::v1::Reshape>(data, make_bhsd_shape(), true);}+ const auto output_type = context.get_output_type();+ if (data.get_element_type() != ov::element::f32) {+ data = std::make_shared<ov::op::v0::Convert>(data, ov::element::f32);+ }+if (mode == TYPE_NORMAL) {// Emit the Flux-style interleaved RoPE pattern so ov::pass::RoPEFusionFlux// folds this subgraph into ov::op::internal::RoPE → GPU ocl::rope::opt kernel.@@ -96,14 +101,27 @@ OutputVector translate_rope(const NodeContext& context) {// After the VIEW prologue the data is already [B,L,n_heads,head_size].const int64_t n_heads = static_cast<int64_t>(output_shape[2]);const int64_t head_size = static_cast<int64_t>(output_shape[3]);- const int64_t half = head_size / 2;+ const int64_t n_rot = rope_config.n_dims > 0 ? rope_config.n_dims : head_size;+ const int64_t half = n_rot / 2;++ ov::Output<ov::Node> rotary_data = data;+ ov::Output<ov::Node> pass_through;+ if (n_rot < head_size) {+ auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});+ auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto n_rot_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {n_rot});+ auto head_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {head_size});+ rotary_data = std::make_shared<ov::op::v8::Slice>(data, zero, n_rot_c, one, axis);+ pass_through = std::make_shared<ov::op::v8::Slice>(data, n_rot_c, head_c, one, axis);+ }// Reshape to [B, L, n_heads, half, 2] to expose interleaved pairs (reinterprets any// incoming rank in element order, so no separate rank lift is needed). The leading 0 copies// the input's batch dim (special_zero) so the token axis stays where the caller had it.auto paired_shape =ov::op::v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{0, -1, n_heads, half, 2});- auto x_paired = std::make_shared<ov::op::v1::Reshape>(data, paired_shape, true);+ auto x_paired = std::make_shared<ov::op::v1::Reshape>(rotary_data, paired_shape, true);auto split_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {-1LL});auto data_split = std::make_shared<ov::op::v1::Split>(x_paired, split_axis, 2);@@ -114,7 +132,9 @@ OutputVector translate_rope(const NodeContext& context) {auto x1_neg = std::make_shared<ov::op::v1::Multiply>(x1, neg_one_f);auto x_rotated_paired = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{x1_neg, x0}, -1);- auto x_rotated = std::make_shared<ov::op::v1::Reshape>(x_rotated_paired, make_bhsd_shape(), true);+ auto rotary_shape = ov::op::v0::Constant::create(+ ov::element::i64, {4}, std::vector<int64_t>{0, -1, n_heads, n_rot});+ auto x_rotated = std::make_shared<ov::op::v1::Reshape>(x_rotated_paired, rotary_shape, true);// Expand cos/sin from [B, L, 1, half] to [B, L, 1, head_size].auto expand_cos_sin = [&](ov::Output<ov::Node> cs) -> ov::Output<ov::Node> {@@ -125,15 +145,18 @@ OutputVector translate_rope(const NodeContext& context) {auto bcast = std::make_shared<ov::op::v3::Broadcast>(cs_unsq, bcast_target, ov::op::BroadcastType::BIDIRECTIONAL);auto flat = ov::op::v0::Constant::create(- ov::element::i64, {4}, std::vector<int64_t>{0, 0, 0, head_size});+ ov::element::i64, {4}, std::vector<int64_t>{0, 0, 0, n_rot});return std::make_shared<ov::op::v1::Reshape>(bcast, flat, /*special_zero=*/true);};auto cos_full = expand_cos_sin(cos_theta_node);auto sin_full = expand_cos_sin(sin_theta_node);- auto y1 = std::make_shared<ov::op::v1::Multiply>(data, cos_full);+ auto y1 = std::make_shared<ov::op::v1::Multiply>(rotary_data, cos_full);auto y2 = std::make_shared<ov::op::v1::Multiply>(x_rotated, sin_full);- res = std::make_shared<ov::op::v1::Add>(y1, y2);+ ov::Output<ov::Node> rotated = std::make_shared<ov::op::v1::Add>(y1, y2);+ res = n_rot < head_size+ ? std::make_shared<ov::op::v0::Concat>(ov::OutputVector{rotated, pass_through}, -1)+ : rotated;} else if (mode == TYPE_NEOX) {// Partial rotary (ggml n_dims < head_dim): only the first n_dims of every head are// rotated; the remaining tail is passed through unchanged. cos/sin have width n_dims/2,@@ -260,6 +283,10 @@ OutputVector translate_rope(const NodeContext& context) {// Fail cleanly on an unmapped mode rather than dereferencing a null res downstream.FRONT_END_CHECK_IMPLEMENTED(res.get_node_shared_ptr() != nullptr, "Unsupported ROPE mode");+ if (res.get_element_type() != output_type) {+ res = std::make_shared<ov::op::v0::Convert>(res, output_type);+ }+return rename_outputs_with_suffix({res}, context.get_name());}diff --git a/src/frontends/gguf/src/op/scale.cpp b/src/frontends/gguf/src/op/scale.cppindex 8dfaf2c41b8..ae614a8350a 100644--- a/src/frontends/gguf/src/op/scale.cpp+++ b/src/frontends/gguf/src/op/scale.cpp@@ -2,9 +2,12 @@// SPDX-License-Identifier: Apache-2.0//+#include <climits>#include "openvino/op/add.hpp"+#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/multiply.hpp"+#include "openvino/op/slice.hpp"#include <vector>#include "node_context.hpp"@@ -24,7 +27,27 @@ OutputVector translate_scale(const NodeContext& context) {float bias = context.get_attribute<float>("bias", 0.0f);auto scale_node = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{}, std::vector<float>{scale});- auto scaled = std::make_shared<ov::op::v1::Multiply>(context.get_input(0), scale_node);+ ov::Output<ov::Node> value = context.get_input(0);+ bool updated_cache = false;+ if (context.get_op_case() == 1 && context.has_input("cache_rs_reset_idx") &&+ context.has_input("cache_rs_reset_len")) {+ auto begin = context.get_input("cache_rs_reset_idx");+ auto end = std::make_shared<ov::op::v1::Add>(begin, context.get_input("cache_rs_reset_len"));+ auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto int_max = ov::op::v0::Constant::create(ov::element::i64, {1}, {INT_MAX});+ auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {2});+ auto head = std::make_shared<ov::op::v8::Slice>(value, zero, begin, one, axis);+ auto middle = std::make_shared<ov::op::v8::Slice>(value, begin, end, one, axis);+ auto tail = std::make_shared<ov::op::v8::Slice>(value, end, int_max, one, axis);+ auto scaled_middle = std::make_shared<ov::op::v1::Multiply>(middle, scale_node);+ value = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{head, scaled_middle, tail}, 2);+ updated_cache = true;+ }+ ov::Output<ov::Node> scaled = value;+ if (!updated_cache) {+ scaled = std::make_shared<ov::op::v1::Multiply>(value, scale_node);+ }std::shared_ptr<ov::Node> res;if (bias != 0.0f) {@@ -32,7 +55,7 @@ OutputVector translate_scale(const NodeContext& context) {std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{}, std::vector<float>{bias});res = std::make_shared<ov::op::v1::Add>(scaled, bias_node);} else {- res = scaled;+ res = scaled.get_node_shared_ptr();}return rename_outputs_with_suffix({res}, context.get_name());diff --git a/src/frontends/gguf/src/op/softmax.cpp b/src/frontends/gguf/src/op/softmax.cppindex 3bd58e03235..d8f7d3be0b3 100644--- a/src/frontends/gguf/src/op/softmax.cpp+++ b/src/frontends/gguf/src/op/softmax.cpp@@ -131,10 +131,16 @@ OutputVector translate_soft_max(const NodeContext& context) {ov::Output<ov::Node> biased_input = scaled_input;if (max_bias > 0.0f) {// ALiBi: per-head slope[h] applied to the mask (ggml ggml_compute_forward_soft_max_f32).- // n_head is dim 0 (head count) -- read only that dim, since the token dim may be dynamic.- FRONT_END_OP_CONVERSION_CHECK(in_ps.rank().is_static() && in_ps[0].is_static(),+ // ggml's head dimension is always ne[2] regardless of rank; reversing ggml's dims to OV+ // order puts it at (rank - 3) -- axis 1 for the usual 4D [batch, head, token, kv] layout,+ // axis 0 when a leading batch/repetition dim of 1 is omitted (rank 3).+ FRONT_END_OP_CONVERSION_CHECK(in_ps.rank().is_static() && in_ps.rank().get_length() >= 3,+ "SOFT_MAX ALiBi requires a static rank of at least 3");+ const int64_t rank = in_ps.rank().get_length();+ const int64_t head_axis = rank - 3;+ FRONT_END_OP_CONVERSION_CHECK(in_ps[head_axis].is_static(),"SOFT_MAX ALiBi requires a static head-count dimension");- const uint32_t n_head = static_cast<uint32_t>(in_ps[0].get_length());+ const uint32_t n_head = static_cast<uint32_t>(in_ps[head_axis].get_length());const uint32_t n_head_log2 = 1u << static_cast<uint32_t>(std::floor(std::log2(n_head)));const float m0 = std::pow(2.0f, -max_bias / static_cast<float>(n_head_log2));const float m1 = std::pow(2.0f, -(max_bias / 2.0f) / static_cast<float>(n_head_log2));@@ -142,8 +148,10 @@ OutputVector translate_soft_max(const NodeContext& context) {for (uint32_t h = 0; h < n_head; ++h) {slopes[h] = h < n_head_log2 ? std::pow(m0, static_cast<float>(h + 1)) : std::pow(m1, static_cast<float>(2 * (h - n_head_log2) + 1));}+ ov::Shape slope_shape(rank, 1);+ slope_shape[head_axis] = n_head;auto slope_node = std::make_shared<ov::op::v0::Constant>(output_type,- ov::Shape{n_head, 1, 1},+ slope_shape,slopes);auto slope_mask = std::make_shared<ov::op::v1::Multiply>(mask_node_sliced, slope_node);biased_input = std::make_shared<ov::op::v1::Add>(scaled_input, slope_mask);diff --git a/src/frontends/gguf/src/op/view.cpp b/src/frontends/gguf/src/op/view.cppindex 866e7d5140f..240806b064a 100644--- a/src/frontends/gguf/src/op/view.cpp+++ b/src/frontends/gguf/src/op/view.cpp@@ -2,7 +2,9 @@// SPDX-License-Identifier: Apache-2.0//+#include <algorithm>#include <limits>+#include <numeric>#include <vector>#include "op_table.hpp"@@ -65,6 +67,15 @@ void place_dynamic_token_axis(std::vector<int64_t> & tgt, const ov::PartialShapeOutputVector translate_view(const NodeContext & context) {num_inputs_check(context, 1, 2);+ const auto output_shape = context.get_output_shape();+ const auto input_shape = context.get_input_shape(0);+ if ((output_shape.is_static() && ov::shape_size(output_shape.to_shape()) == 0) ||+ (input_shape.is_static() && ov::shape_size(input_shape.to_shape()) == 0)) {+ // Empty recurrent-cache reorder views have no values and their CPY+ // consumer is routed directly to the cache base tensor.+ return {context.get_input(0)};+ }+if (context.get_op_case() == 2) {auto dst_shape = context.get_output_shape().to_shape();return rename_outputs_with_suffix(@@ -120,6 +131,7 @@ OutputVector translate_view(const NodeContext & context) {place_dynamic_token_axis(tgt, sliced.get_partial_shape());auto res = std::make_shared<ov::op::v1::Reshape>(sliced, ov::op::v0::Constant::create(ov::element::i64, {tgt.size()}, tgt), false);+ res->set_friendly_name("gdn_view_reshape_" + context.get_name());return rename_outputs_with_suffix({res}, context.get_name());}return rename_outputs_with_suffix({sliced}, context.get_name());@@ -187,6 +199,13 @@ OutputVector translate_view(const NodeContext & context) {ov::Output<ov::Node> result = input;if (slice.size() == 3) {const int64_t axis = slice[0], start = slice[1], len = slice[2];+ if (axis >= 0 && static_cast<size_t>(axis) < input_ggml_shape.size() &&+ start >= static_cast<int64_t>(input_ggml_shape[axis])) {+ // A one-past-end recurrent cache view represents an empty+ // slot-reorder destination. Its CPY consumer is routed to the+ // cache base, so no standalone slice is needed.+ return {input};+ }auto begin = ov::op::v0::Constant::create(ov::element::i64, {1}, {start});// A negative start is an end-anchored TAIL slice (conv_state_last: last d_conv-1 columns// of a dynamic-length conv window); its end must run to the axis end, not start+len (which@@ -209,6 +228,7 @@ OutputVector translate_view(const NodeContext & context) {place_dynamic_token_axis(tgt, result.get_partial_shape());result = std::make_shared<ov::op::v1::Reshape>(result, ov::op::v0::Constant::create(ov::element::i64, {tgt.size()}, tgt), false);+ result.get_node_shared_ptr()->set_friendly_name("view_reshape_" + context.get_name());}// A view that neither restores rank, slices nor reshapes is a pass-through: the value is// still the producer's output, so renaming it here would rename a node owned by another@@ -263,6 +283,149 @@ OutputVector translate_view(const NodeContext & context) {}return rename_outputs_with_suffix({sliced.get_node_shared_ptr()}, context.get_name());}++ // Generic llama.cpp view. A view that preserves the source strides is a rectangular crop of+ // the logical source tensor; its byte offset identifies the first element. This covers the+ // ordinary multi-axis views used by backend validation without specializing their consumers.+ if (input_shape.is_static() && output_shape.is_static()) {+ const auto src_shape = input_shape.to_shape();+ const auto dst_shape = output_shape.to_shape();+ 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);++ if (src_shape.size() == dst_shape.size() && src_shape.size() == src_strides.size() &&+ src_strides == dst_strides && byte_offset >= 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);+ std::sort(dims.begin(), dims.end(), [&](size_t a, size_t b) {+ return src_strides[a] > src_strides[b];+ });++ int64_t remaining = byte_offset;+ bool valid = true;+ for (size_t d : dims) {+ if (src_strides[d] <= 0) {+ valid = false;+ break;+ }+ starts[d] = remaining / src_strides[d];+ remaining %= src_strides[d];+ 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;+ break;+ }+ }+ valid = valid && remaining == 0;++ if (valid) {+ std::vector<int64_t> begin(src_shape.size());+ std::vector<int64_t> end(src_shape.size());+ std::vector<int64_t> axes(src_shape.size());+ std::vector<int64_t> step(src_shape.size(), 1);+ for (size_t ov_axis = 0; ov_axis < src_shape.size(); ++ov_axis) {+ const size_t ggml_dim = src_shape.size() - 1 - ov_axis;+ begin[ov_axis] = starts[ggml_dim];+ 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));+ return rename_outputs_with_suffix({result}, context.get_name());+ }++ // A ggml view may start inside a row and continue into the next row while preserving+ // 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 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) {+ auto flat_shape = ov::op::v0::Constant::create(+ ov::element::i64,+ {3},+ std::vector<int64_t>{static_cast<int64_t>(src_shape[0]),+ static_cast<int64_t>(src_shape[1]),+ src_plane});+ auto flat = std::make_shared<ov::op::v1::Reshape>(context.get_input(0), flat_shape, false);+ auto selected = std::make_shared<ov::op::v8::Slice>(+ flat,+ ov::op::v0::Constant::create(ov::element::i64, {1}, {begin_elem}),+ ov::op::v0::Constant::create(ov::element::i64, {1}, {begin_elem + dst_plane}),+ ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),+ ov::op::v0::Constant::create(ov::element::i64, {1}, {2}));+ 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({result}, context.get_name());+ }+ }+ }++ if (src_shape.size() == dst_shape.size() && src_shape.size() == src_strides.size() &&+ src_strides.size() == dst_strides.size() && byte_offset >= 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());+ std::iota(dims.begin(), dims.end(), 0);+ std::sort(dims.begin(), dims.end(), [&](size_t a, size_t b) {+ return src_strides[a] > src_strides[b];+ });++ int64_t remaining = byte_offset;+ bool valid = true;+ for (size_t d : dims) {+ if (src_strides[d] <= 0 || dst_strides[d] <= 0 || dst_strides[d] % src_strides[d] != 0) {+ valid = false;+ break;+ }+ steps[d] = dst_strides[d] / src_strides[d];+ starts[d] = remaining / src_strides[d];+ remaining %= src_strides[d];+ 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])) {+ valid = false;+ break;+ }+ }++ if (valid && remaining == 0) {+ std::vector<int64_t> begin(src_shape.size());+ std::vector<int64_t> end(src_shape.size());+ std::vector<int64_t> step(src_shape.size());+ std::vector<int64_t> axes(src_shape.size());+ for (size_t ov_axis = 0; ov_axis < src_shape.size(); ++ov_axis) {+ const size_t ggml_dim = src_shape.size() - 1 - ov_axis;+ begin[ov_axis] = starts[ggml_dim];+ step[ov_axis] = steps[ggml_dim];+ 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));+ return rename_outputs_with_suffix({result}, context.get_name());+ }+ }++ if (byte_offset == 0 && ov::shape_size(src_shape) == ov::shape_size(dst_shape)) {+ auto target = ov::op::v0::Constant::create(ov::element::i64, {dst_shape.size()}, dst_shape);+ auto result = std::make_shared<ov::op::v1::Reshape>(context.get_input(0), target, false);+ return rename_outputs_with_suffix({result}, context.get_name());+ }+ }return {context.get_input(0)};}diff --git a/src/frontends/gguf/src/op_table.cpp b/src/frontends/gguf/src/op_table.cppindex a2fd557301c..b6afba509ee 100644--- a/src/frontends/gguf/src/op_table.cpp+++ b/src/frontends/gguf/src/op_table.cpp@@ -55,8 +55,6 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {{"GGML_OP_MUL", op::translate_1to1_match_2_inputs<v1::Multiply>},{"GGML_OP_MUL_MAT", op::translate_mulmat},{"GGML_OP_MUL_MAT_ID", op::translate_mul_mat_id},- // A GGML_OP_NONE leaf is a weight if the decoder marks it as one (see translate_weight);- // otherwise it is a model input, resolved to a Parameter before the walk.{"GGML_OP_NONE", op::translate_weight},{"GGML_OP_NORM", op::translate_norm},{"GGML_OP_PAD", op::translate_pad},diff --git a/src/frontends/gguf/src/pass/adapt_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_to_genai.cppnew file mode 100644index 00000000000..60dd0ee7a2e--- /dev/null+++ b/src/frontends/gguf/src/pass/adapt_to_genai.cpp@@ -0,0 +1,307 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/frontend/gguf/adapt_to_genai.hpp"+#include "openvino/frontend/gguf/make_stateful.hpp"++#include <memory>+#include <unordered_map>++#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/greater_eq.hpp"+#include "openvino/op/less_eq.hpp"+#include "openvino/op/logical_and.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/range.hpp"+#include "openvino/op/read_value.hpp"+#include "openvino/op/reduce_prod.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/tile.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/op/select.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/runtime/properties.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace pass {++namespace {++using std::make_shared;++// f16 lowest, matches genai's causal-mask "-inf" fill.+constexpr float NEG_INF = -65504.0f;++std::shared_ptr<ov::op::v0::Constant> const_i64(const std::vector<int64_t>& values) {+ return ov::op::v0::Constant::create(ov::element::i64, ov::Shape{values.size()}, values);+}++// Find a Parameter whose output tensor names (or friendly name) match `name`.+std::shared_ptr<ov::op::v0::Parameter> find_param(const std::shared_ptr<ov::Model>& model,+ const std::string& name) {+ for (const auto& p : model->get_parameters()) {+ const auto& names = p->output(0).get_names();+ if (names.count(name) || p->get_friendly_name() == name) {+ return p;+ }+ }+ return nullptr;+}++void name_output(const ov::Output<ov::Node>& out, const std::string& name) {+ out.get_node_shared_ptr()->set_friendly_name(name);+ out.get_node_shared_ptr()->output(0).set_names({name});+}++// Largest attention head size across the stateful KV caches (the ReadValue last dim). The+// frontend emits f16 KV caches mirroring llama.cpp, but the CPU plugin defaults+// KV_CACHE_PRECISION to u8 (dynamic-quantized) -- faster and accurate enough for the common+// head sizes used by llama/qwen/phi3/gpt-oss (64-128). For large head sizes the u8+// quantization injects enough per-step error to compound across autoregressive decode into+// divergence and eventually NaN (observed on gemma4, global-attention head_size=512).+int64_t max_kv_cache_head_size(const std::shared_ptr<ov::Model>& model) {+ int64_t max_hs = 0;+ for (const auto& op : model->get_ops()) {+ if (!ov::as_type_ptr<ov::op::v6::ReadValue>(op)) {+ continue;+ }+ const auto& ps = op->get_output_partial_shape(0);+ if (ps.rank().is_static() && ps[ps.rank().get_length() - 1].is_static()) {+ max_hs = std::max(max_hs, ps[ps.rank().get_length() - 1].get_length());+ }+ }+ return max_hs;+}++} // namespace++bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {+ OPENVINO_ASSERT(m_mode == InputMode::IdsToLogits,+ "[gguf] AdaptToGenAI: only InputMode::IdsToLogits is implemented; "+ "EmbedsToLogits (VLM language model) is reserved for future work.");++ // The gguf inputs we rewire. inp_tokens/inp_pos/self_kq_mask/token_len_per_seq are+ // required; if they are absent the model is not a gguf-IO model (e.g. already adapted),+ // so this pass is a no-op.+ auto inp_tokens = find_param(model, "inp_tokens");+ auto inp_pos = find_param(model, "inp_pos");+ auto self_kq_mask = find_param(model, "self_kq_mask");+ auto token_len_per_seq = find_param(model, "token_len_per_seq");+ if (!inp_tokens || !inp_pos || !self_kq_mask || !token_len_per_seq) {+ return false;+ }++ // ---- new genai inputs: input_ids / attention_mask / position_ids [b, seq] i64 ----+ auto input_ids = make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});+ name_output(input_ids, "input_ids");+ auto attention_mask = make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});+ name_output(attention_mask, "attention_mask");+ auto position_ids = make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});+ name_output(position_ids, "position_ids");++ // beam_idx (i32 [D]) is added by the make-stateful pass, next to the Gather that reads it; genai+ // sets it via set_tensor("beam_idx"). Keep that Parameter so its wiring is preserved. Its absence+ // means the model is not stateful, which the genai contract requires.+ auto beam_idx = find_param(model, "beam_idx");+ OPENVINO_ASSERT(beam_idx,+ "[gguf] AdaptToGenAI: model has no 'beam_idx' input, so it is not stateful. "+ "Register a make-stateful transformation extension (e.g. "+ "ov::frontend::gguf::pass::MakeStateful) before converting.");++ // ---- token_len_per_seq = number of tokens in input_ids -> [1] ----+ // The token count is the ELEMENT COUNT of input_ids, not any single dimension of it. genai feeds+ // [batch, seq] (batch == 1), but SDPAToPagedAttention rewrites this Parameter to rank-1 [tokens]+ // and splices an Unsqueeze(axis=1) in front of its consumers, making it [tokens, 1]. Reading+ // dim 1 would then yield 1 for every prompt, collapsing the causal mask and the logits to a+ // single token; reading dim 0 breaks the un-rewritten case. ReduceProd is correct under both.+ auto ids_shape = make_shared<ov::op::v3::ShapeOf>(input_ids, ov::element::i64);+ auto seq_len = make_shared<ov::op::v1::ReduceProd>(ids_shape, const_i64({0}), true); // [1]+ token_len_per_seq->output(0).replace(seq_len->output(0));++ // The two gguf rank-4 input kinds carry the (batch, tokens) pair on different axes, so they get+ // different lifts. Both are written so the genai Parameter's own leading dims flow through+ // instead of being replaced by literals -- that is the whole mechanism by which one graph serves+ // both attention backends (see the layout note on the class).+ //+ // INDEX vectors (inp_tokens, inp_out_ids): consumed by get_rows, which squeezes the two leading+ // axes and gathers rows. The gathered result inherits the indices' trailing 2D shape, so the+ // indices must present exactly the Parameter's own [batch, seq]: prepend two 1s.+ // SDPA: [1,1,1,tokens] -> squeeze -> [1,tokens] -> embd [1,tokens,n_embd]+ // PA : [1,1,tokens,1] -> squeeze -> [tokens,1] -> embd [tokens,1,n_embd]+ const auto shape_1_1_batch_seq = make_shared<ov::op::v0::Concat>(ov::OutputVector{const_i64({1, 1}), ids_shape}, 0);++ // ACTIVATION-like inputs (inp_pos): consumed by make_sin_cos, which transposes {0,3,1,2} to put+ // the token axis at 1, yielding cos/sin [batch, tokens, 1, n_rot/2] that broadcast against the+ // roped [batch, heads, tokens, head_size]. special_zero's 0 copies dim 0 and -1 absorbs the rest.+ // SDPA: [1,1,1,tokens] -> cos/sin [1,tokens,1,half]+ // PA : [tokens,1,1,1] -> cos/sin [tokens,1,1,half], which broadcasts against [tokens,H,1,S]+ const auto shape_keep0_1_1_rest = const_i64({0, 1, 1, -1});++ auto tokens_i32 = make_shared<ov::op::v0::Convert>(input_ids, ov::element::i32);+ auto tokens_4d = make_shared<ov::op::v1::Reshape>(tokens_i32, shape_1_1_batch_seq, false);+ inp_tokens->output(0).replace(tokens_4d->output(0));++ ov::Output<ov::Node> pos_i32 = make_shared<ov::op::v0::Convert>(position_ids, ov::element::i32);+ // M-RoPE (qwen35): inp_pos carries FOUR position sections per token, laid out section-major --+ // make_sin_cos reshapes it to {..,4,tokens} and transposes. GenAI supplies one position per+ // token, so tile it 4x along the token axis. All four sections hold the same value here: the+ // per-section split only differs for image/video input, and a text-only prompt has no spatial+ // axes to differ on (llama.cpp fills all sections with the text position likewise).+ if (model->get_rt_info().count(gguf_imrope_key())) {+ auto tile_repeats = const_i64({1, 4});+ pos_i32 = make_shared<ov::op::v0::Tile>(pos_i32, tile_repeats);+ }+ auto pos_4d = make_shared<ov::op::v1::Reshape>(pos_i32, shape_keep0_1_1_rest, true);+ inp_pos->output(0).replace(pos_4d->output(0));++ // ---- self_kq_mask [1,1,seq,kv_len] f32: 0 where attended, -inf above causal ----+ // kv_len = attention_mask length (= past + seq). query absolute positions = position_ids[0].+ auto am_shape = make_shared<ov::op::v3::ShapeOf>(attention_mask, ov::element::i64);+ auto kv_len = make_shared<ov::op::v8::Gather>(am_shape, const_i64({1}), const_i64({0})); // [1]++ // Flatten position_ids to [seq] via a shape-independent Reshape({-1}) rather than Squeeze(axis=0):+ // PA also rewrites position_ids to rank-1 and Unsqueezes it to [seq,1], where squeezing axis 0+ // would fail (or drop the wrong axis).+ auto q_pos =+ make_shared<ov::op::v0::Convert>(make_shared<ov::op::v1::Reshape>(position_ids, const_i64({-1}), false),+ ov::element::i32); // [seq]+ auto q_pos_col =+ make_shared<ov::op::v1::Reshape>(q_pos,+ make_shared<ov::op::v0::Concat>(ov::OutputVector{seq_len, const_i64({1})}, 0),+ false); // [seq, 1]++ auto zero_i32 = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});+ auto one_i32 = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {1});+ auto kv_len_i32 = make_shared<ov::op::v0::Squeeze>(make_shared<ov::op::v0::Convert>(kv_len, ov::element::i32),+ const_i64({0})); // scalar+ auto k_range = make_shared<ov::op::v4::Range>(zero_i32, kv_len_i32, one_i32, ov::element::i32); // [kv_len]+ auto k_row =+ make_shared<ov::op::v1::Reshape>(k_range,+ make_shared<ov::op::v0::Concat>(ov::OutputVector{const_i64({1}), kv_len}, 0),+ false); // [1, kv_len]++ auto allowed = make_shared<ov::op::v1::LessEqual>(k_row, q_pos_col); // [seq, kv_len] bool+ auto zero_f = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});+ auto neg_f = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {NEG_INF});+ auto mask2d = make_shared<ov::op::v1::Select>(allowed, zero_f, neg_f); // [seq, kv_len] f32+ auto mask_4d = make_shared<ov::op::v1::Reshape>(+ mask2d,+ make_shared<ov::op::v0::Concat>(ov::OutputVector{const_i64({1, 1}), seq_len, kv_len}, 0),+ false); // [1, 1, seq, kv_len]+ self_kq_mask->output(0).replace(mask_4d->output(0));++ // Sliding-window mask: for prompts within the window this equals the full causal mask, but+ // once the context (prompt + generated tokens) exceeds it, reusing the causal mask would+ // leave every older key visible and produce wrong logits. When the model's metadata records+ // an explicit window length (see gguf_swa_window_key), AND the causal mask with "key not+ // more than window - 1 steps behind the query"; a token at position q may attend to keys in+ // [q - window + 1, q]. Absent a recorded length (e.g. gpt-oss/gemma4, whose SWA is described+ // by sinks / a per-layer pattern with no accompanying token count here), fall back to the+ // full causal mask, matching the previous behavior.+ if (auto self_kq_mask_swa = find_param(model, "self_kq_mask_swa")) {+ ov::Output<ov::Node> swa_mask_4d = mask_4d->output(0);+ const auto& rt_info = model->get_rt_info();+ const auto swa_it = rt_info.find(gguf_swa_window_key());+ if (swa_it != rt_info.end()) {+ const auto window = swa_it->second.as<int64_t>();+ auto window_m1 =+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {static_cast<int32_t>(window - 1)});+ auto window_start = make_shared<ov::op::v1::Subtract>(q_pos_col, window_m1); // [seq, 1]+ auto within_window = make_shared<ov::op::v1::GreaterEqual>(k_row, window_start); // [seq, kv_len]+ auto allowed_swa = make_shared<ov::op::v1::LogicalAnd>(allowed, within_window); // [seq, kv_len]+ auto mask2d_swa = make_shared<ov::op::v1::Select>(allowed_swa, zero_f, neg_f); // [seq, kv_len]+ swa_mask_4d = make_shared<ov::op::v1::Reshape>(+ mask2d_swa,+ make_shared<ov::op::v0::Concat>(ov::OutputVector{const_i64({1, 1}), seq_len, kv_len}, 0),+ false); // [1, 1, seq, kv_len]+ }+ self_kq_mask_swa->output(0).replace(swa_mask_4d);+ }++ // inp_out_ids selects which rows the output head runs on. Emit the LAST row only: genai reads+ // just the final token's logits, so projecting every prompt position to vocab costs an extra+ // (tokens - 1) x hidden x vocab matmul per prefill.+ //+ // get_rows lowers to Gather(activation, ids, axis=1, batch_dims=1), i.e. act[i, ids[i, j]], so+ // the last row is ids == ids_shape[1] - 1 in an [ids_shape[0], 1] vector. That is correct in+ // both layouts: default ids_shape is [1, tokens], giving [1,1] holding tokens - 1; under+ // SDPAToPagedAttention it is [tokens, 1], so this evaluates to 0 -- the identity that layout+ // needs, since it already carries one token per row.+ if (auto inp_out_ids = find_param(model, "inp_out_ids")) {+ auto batch_dim =+ make_shared<ov::op::v8::Gather>(ids_shape, const_i64({0}), const_i64({0})); // [1]: ids_shape[0]+ auto seq_dim =+ make_shared<ov::op::v8::Gather>(ids_shape, const_i64({1}), const_i64({0})); // [1]: ids_shape[1]+ auto last_index = make_shared<ov::op::v0::Convert>(+ make_shared<ov::op::v1::Subtract>(seq_dim, const_i64({1})),+ ov::element::i32); // [1]: ids_shape[1] - 1+ auto out_grid = make_shared<ov::op::v3::Broadcast>(+ last_index,+ make_shared<ov::op::v0::Concat>(ov::OutputVector{batch_dim, const_i64({1})}, 0)); // [batch, 1]+ auto out_ids = make_shared<ov::op::v1::Reshape>(+ out_grid,+ make_shared<ov::op::v0::Concat>(ov::OutputVector{const_i64({1, 1}), batch_dim, const_i64({1})}, 0),+ false);+ inp_out_ids->output(0).replace(out_ids->output(0));+ }++ // ---- logits: rank-4 [.., .., .., vocab] -> [b, seq, vocab] ----+ // genai always wants [batch, seq, vocab] regardless of which axis the body kept the tokens on,+ // and both layouts hold seq*vocab contiguous values, so collapse everything ahead of vocab into+ // the sequence axis with a fixed batch of 1. (batch > 1 is not part of the genai stateful+ // contract this pass targets; token_len_per_seq above is likewise a whole-input token count.)+ auto old_result = model->get_results()[0];+ auto logits_src = old_result->input_value(0);+ auto vocab = make_shared<ov::op::v8::Gather>(make_shared<ov::op::v3::ShapeOf>(logits_src, ov::element::i64),+ const_i64({-1}),+ const_i64({0})); // [1]+ auto logits_3d = make_shared<ov::op::v1::Reshape>(+ logits_src,+ make_shared<ov::op::v0::Concat>(ov::OutputVector{const_i64({1, -1}), vocab}, 0),+ false); // [1, seq, vocab]+ name_output(logits_3d, "logits");+ auto new_result = make_shared<ov::op::v0::Result>(logits_3d);+ new_result->set_friendly_name("logits");++ model->add_results({new_result});+ model->remove_result(old_result);++ // Swap the input list to the genai contract. beam_idx is kept as-is; every other old+ // gguf Parameter has had its output rewired (consumers now read the derived subgraph),+ // so removing it is safe.+ model->add_parameters({input_ids, attention_mask, position_ids});+ const auto params_snapshot = model->get_parameters(); // copy: remove_parameter mutates the list+ for (const auto& p : params_snapshot) {+ if (p == input_ids || p == attention_mask || p == position_ids || p == beam_idx) {+ continue;+ }+ model->remove_parameter(p);+ }++ // Pin the runtime KV-cache precision to f16 for large-head models so decode matches both+ // prefill and llama.cpp; mainstream small-head models keep the faster u8 default. This is a+ // consumer-side optimization policy (genai), not a property the frontend bakes into the model.+ constexpr int64_t kU8SafeHeadSize = 128;+ if (max_kv_cache_head_size(model) > kU8SafeHeadSize) {+ model->set_rt_info(ov::element::f16, {"runtime_options", ov::hint::kv_cache_precision.name()});+ }++ model->validate_nodes_and_infer_types();+ return true;+}++} // namespace pass+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/pass/make_stateful.cpp b/src/frontends/gguf/src/pass/make_stateful.cppindex 228fc5a534d..fb570946aae 100644--- a/src/frontends/gguf/src/pass/make_stateful.cpp+++ b/src/frontends/gguf/src/pass/make_stateful.cpp@@ -72,6 +72,102 @@ int64_t resolve_append_axis(const ov::PartialShape& ps, const std::string& cache} // namespace+const std::string& gguf_recurrent_states_key() {+ static const std::string key = "gguf_recurrent_states";+ return key;+}++const std::string& gguf_imrope_key() {+ static const std::string key = "gguf_is_imrope";+ return key;+}++const std::string& gguf_swa_window_key() {+ static const std::string key = "gguf_swa_window_size";+ return key;+}++// Rewrite the recurrent (overwritten, non-appending) states into OpenVINO Variables.+//+// A KV cache is found by walking the SetRows writes and is grown with a Concat along its token+// axis. A recurrent state has neither: it is read whole at the start of a step and replaced whole+// at the end, so the graph carries nothing that marks it and the pairing arrives via rt_info (see+// gguf_recurrent_states_key). The rewrite is correspondingly simpler -- ReadValue -> ... -> Assign+// with no Concat, and no beam Gather, since there is no past to reorder.+//+// Their shapes are fully static, so the init is a real zeros Constant. Zero is also the correct+// initial value: ggml starts a sequence with a zeroed conv window and delta matrix.+static bool make_recurrent_states_stateful(const std::shared_ptr<ov::Model>& model) {+ auto it = model->get_rt_info().find(gguf_recurrent_states_key());+ if (it == model->get_rt_info().end()) {+ return false;+ }+ const auto flat = it->second.as<std::vector<std::string>>();+ if (flat.empty() || flat.size() % 2 != 0) {+ return false;+ }++ ov::ParameterVector params_to_remove;+ ov::ResultVector results_to_remove;+ ov::SinkVector new_sinks;++ for (size_t i = 0; i + 1 < flat.size(); i += 2) {+ const std::string& in_name = flat[i];+ const std::string& out_name = flat[i + 1];++ auto param = find_param(model, in_name);+ if (!param) {+ continue; // already rewritten (a second run of this pass)+ }+ const auto& ps = param->get_partial_shape();+ OPENVINO_ASSERT(ps.is_static(),+ "[GGUF] GGUFMakeStateful: recurrent state '",+ in_name,+ "' must have a fully static shape, got ",+ ps);++ // The Result holding this state's new value: the one whose producing node carries the+ // state's output name. The builder names that node after the state (see the VIEW cases),+ // which is why those names have to survive translation.+ std::shared_ptr<ov::op::v0::Result> state_result;+ for (const auto& r : model->get_results()) {+ const auto producer = r->get_input_node_shared_ptr(0);+ if (producer->get_friendly_name().find(out_name) != std::string::npos) {+ state_result = r;+ break;+ }+ }+ OPENVINO_ASSERT(state_result,+ "[GGUF] GGUFMakeStateful: no Result produces recurrent state '",+ out_name,+ "'");++ const auto et = param->get_element_type();+ auto var = std::make_shared<ov::op::util::Variable>(ov::op::util::VariableInfo{ps, et, in_name});+ auto init = ov::op::v0::Constant::create(et, ps.to_shape(), std::vector<float>(1, 0.0f));+ auto read_value = std::make_shared<ov::op::v6::ReadValue>(init, var);+ read_value->set_friendly_name(in_name);+ ov::replace_node(param, read_value);++ new_sinks.push_back(std::make_shared<ov::op::v6::Assign>(state_result->input_value(0), var));+ model->add_variables({var});+ results_to_remove.push_back(state_result);+ params_to_remove.push_back(param);+ }++ if (params_to_remove.empty()) {+ return false;+ }+ for (const auto& r : results_to_remove) {+ model->remove_result(r);+ }+ model->add_sinks(new_sinks);+ for (const auto& p : params_to_remove) {+ model->remove_parameter(p);+ }+ return true;+}+bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {// beam_idx reorders the past cache along the batch axis for beam search (identity at batch 1 /// beam_idx [0], but emitting it is what lets CPU's stateful_sdpa_fusion match). It belongs to@@ -101,8 +197,10 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {cache_writes.push_back(set_rows);}}+ // A model can have recurrent states and no KV cache at all (an all-linear-attention stack),+ // so the recurrent rewrite must not sit behind this early return.if (cache_writes.empty()) {- return false;+ return make_recurrent_states_stateful(model);}ov::ParameterVector params_to_remove;@@ -205,6 +303,9 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {model->remove_parameter(p);}+ // Recurrent states are independent of the KV caches; a hybrid stack (qwen35) has both.+ make_recurrent_states_stateful(model);+model->validate_nodes_and_infer_types();return true;}diff --git a/src/frontends/gguf/src/pass/prune_orphaned_parameters.cpp b/src/frontends/gguf/src/pass/prune_orphaned_parameters.cppnew file mode 100644index 00000000000..fede1b156d3--- /dev/null+++ b/src/frontends/gguf/src/pass/prune_orphaned_parameters.cpp@@ -0,0 +1,65 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "pass/prune_orphaned_parameters.hpp"++#include <algorithm>++#include "openvino/core/model.hpp"++namespace ov::frontend::gguf {+namespace pass {+namespace {++// A Parameter can have non-empty target_inputs() yet be practically dead if its consumer isn't+// reachable from any Result/Sink. get_ordered_ops() is rooted at Results/Sinks, so use it instead+// of target_inputs() to find genuinely-live parameters.+std::unordered_set<const ov::Node*> live_parameters(const std::shared_ptr<ov::Model>& model) {+ std::unordered_set<const ov::Node*> ordered_nodes;+ for (const auto& node : model->get_ordered_ops()) {+ ordered_nodes.insert(node.get());+ }+ std::unordered_set<const ov::Node*> live;+ for (const auto& param : model->get_parameters()) {+ const auto& targets = param->output(0).get_target_inputs();+ const bool has_live_consumer = std::any_of(targets.begin(), targets.end(), [&](const ov::Input<ov::Node>& in) {+ return ordered_nodes.count(in.get_node()) != 0;+ });+ if (has_live_consumer) {+ live.insert(param.get());+ }+ }+ return live;+}++} // namespace++SnapshotLiveParameters::SnapshotLiveParameters(std::shared_ptr<std::unordered_set<const ov::Node*>> out)+ : m_out(std::move(out)) {}++bool SnapshotLiveParameters::run_on_model(const std::shared_ptr<ov::Model>& model) {+ *m_out = live_parameters(model);+ return false;+}++PruneParametersOrphanedSince::PruneParametersOrphanedSince(+ std::shared_ptr<std::unordered_set<const ov::Node*>> live_before)+ : m_live_before(std::move(live_before)) {}++bool PruneParametersOrphanedSince::run_on_model(const std::shared_ptr<ov::Model>& model) {+ const auto live_after = live_parameters(model);+ // remove_parameter() mutates the model's parameter list, so snapshot it before iterating.+ const auto parameters = model->get_parameters();+ bool changed = false;+ for (const auto& param : parameters) {+ if (m_live_before->count(param.get()) && !live_after.count(param.get())) {+ model->remove_parameter(param);+ changed = true;+ }+ }+ return changed;+}++} // namespace pass+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/pass/prune_orphaned_parameters.hpp b/src/frontends/gguf/src/pass/prune_orphaned_parameters.hppnew file mode 100644index 00000000000..cad855cd262--- /dev/null+++ b/src/frontends/gguf/src/pass/prune_orphaned_parameters.hpp@@ -0,0 +1,41 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <unordered_set>++#include "openvino/core/node.hpp"+#include "openvino/pass/pass.hpp"++namespace ov::frontend::gguf {+namespace pass {++// Records which model Parameters currently have a live consumer, for a paired+// PruneParametersOrphanedSince to compare against later.+class SnapshotLiveParameters : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ov::frontend::gguf::pass::SnapshotLiveParameters");+ explicit SnapshotLiveParameters(std::shared_ptr<std::unordered_set<const ov::Node*>> out);+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;++private:+ std::shared_ptr<std::unordered_set<const ov::Node*>> m_out;+};++// Drops a Parameter that was live in the paired snapshot but no longer is, without touching one+// some earlier, unrelated pass already left disconnected.+class PruneParametersOrphanedSince : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ov::frontend::gguf::pass::PruneParametersOrphanedSince");+ explicit PruneParametersOrphanedSince(std::shared_ptr<std::unordered_set<const ov::Node*>> live_before);+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;++private:+ std::shared_ptr<std::unordered_set<const ov::Node*>> m_live_before;+};++} // namespace pass+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/quant/gguf.cpp b/src/frontends/gguf/src/quant/gguf.cppnew file mode 100644index 00000000000..bac9e83c344--- /dev/null+++ b/src/frontends/gguf/src/quant/gguf.cpp@@ -0,0 +1,1110 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Native GGUF container parser. Replaces the third-party gguflib dependency: the file is+// memory-mapped via ov::load_mmap_object and parsed directly per the GGUF v2/v3 format+// (https://github.com/ggml-org/ggml/blob/master/docs/gguf.md). No llama.cpp / ggml+// dependency.++#include "gguf.hpp"+#include "weights.hpp"++#include <cmath>+#include <cstdint>+#include <cstring>+#include <optional>++#include "openvino/core/except.hpp"+#include "openvino/core/type/element_type_traits.hpp"+#include "openvino/runtime/aligned_buffer.hpp"+#include "openvino/runtime/shared_buffer.hpp"+#include "openvino/util/math_util.hpp"+#include "openvino/util/mmap_object.hpp"++namespace ov {+namespace frontend {+namespace gguf {++namespace {++constexpr uint32_t GGUF_MAGIC = 0x46554747; // "GGUF" little-endian+constexpr uint64_t GGUF_DEFAULT_ALIGNMENT = 32;++// (items_per_block, bytes_per_block) per gguf_tensor_type, indexed by the type id.+struct TypeTraits {+ uint32_t items_per_block;+ uint32_t bytes_per_block;+};++TypeTraits type_traits(uint32_t type) {+ switch (type) {+ case GGUF_TYPE_F32:+ return {1, 4};+ case GGUF_TYPE_F16:+ return {1, 2};+ case GGUF_TYPE_Q4_0:+ return {32, 18};+ case GGUF_TYPE_Q4_1:+ return {32, 20};+ case GGUF_TYPE_Q5_0:+ return {32, 22};+ case GGUF_TYPE_Q5_1:+ return {32, 24};+ case GGUF_TYPE_Q8_0:+ return {32, 34};+ case GGUF_TYPE_Q8_1:+ return {32, 40};+ case GGUF_TYPE_Q2_K:+ return {256, 84};+ case GGUF_TYPE_Q2_0:+ return {64, 18}; // f16 scale + 64x 2-bit codes (16 bytes)+ case GGUF_TYPE_Q3_K:+ return {256, 110};+ case GGUF_TYPE_Q4_K:+ return {256, 144};+ case GGUF_TYPE_Q5_K:+ return {256, 176};+ case GGUF_TYPE_Q6_K:+ return {256, 210};+ case GGUF_TYPE_Q8_K:+ return {256, 292};+ case GGUF_TYPE_I8:+ return {1, 1};+ case GGUF_TYPE_I16:+ return {1, 2};+ case GGUF_TYPE_I32:+ return {1, 4};+ case GGUF_TYPE_I64:+ return {1, 8};+ case GGUF_TYPE_F64:+ return {1, 8};+ case GGUF_TYPE_BF16:+ return {1, 2};+ case GGUF_TYPE_MXFP4:+ return {32, 17}; // 1-byte E8M0 scale + 16 bytes (32x 4-bit)+ default:+ return {0, 0};+ }+}++std::optional<ov::element::Type> gguf_type_to_dtype(uint32_t gguf_type) {+ switch (gguf_type) {+ case GGUF_TYPE_F64:+ return ov::element::f64;+ case GGUF_TYPE_F32:+ return ov::element::f32;+ case GGUF_TYPE_F16:+ return ov::element::f16;+ case GGUF_TYPE_BF16:+ return ov::element::bf16;+ case GGUF_TYPE_I8:+ return ov::element::i8;+ case GGUF_TYPE_I16:+ return ov::element::i16;+ case GGUF_TYPE_I32:+ return ov::element::i32;+ case GGUF_TYPE_I64:+ return ov::element::i64;+ default:+ return std::nullopt;+ }+}++// Sequential little-endian reader over the mmaped file. Bounds-checked on every read.+class Cursor {+public:+ Cursor(const uint8_t* data, uint64_t size) : m_data(data), m_size(size) {}++ uint64_t offset() const {+ return m_off;+ }+ const uint8_t* ptr() const {+ return m_data + m_off;+ }++ // Bytes left before the end of the mapped file. m_off never exceeds m_size (every mutator+ // below asserts that before advancing it), so this cannot underflow.+ uint64_t remaining() const {+ return m_size - m_off;+ }++ template <typename T>+ T read() {+ OPENVINO_ASSERT(sizeof(T) <= remaining(), "[load_gguf] unexpected end of file");+ T v;+ std::memcpy(&v, m_data + m_off, sizeof(T));+ m_off += sizeof(T);+ return v;+ }++ std::string read_string() {+ uint64_t len = read<uint64_t>();+ // Checked against `remaining()` (a subtraction), not `m_off + len` (an addition): len is+ // an attacker-controlled 64-bit value from the file and could otherwise overflow the+ // addition, wrapping it back under m_size and defeating the bounds check.+ OPENVINO_ASSERT(len <= remaining(), "[load_gguf] string runs past end of file");+ std::string s(reinterpret_cast<const char*>(m_data + m_off), static_cast<size_t>(len));+ m_off += len;+ return s;+ }++ void skip(uint64_t n) {+ OPENVINO_ASSERT(n <= remaining(), "[load_gguf] skip past end of file");+ m_off += n;+ }++private:+ const uint8_t* m_data;+ uint64_t m_size;+ uint64_t m_off = 0;+};++size_t value_type_size(uint32_t type) {+ switch (type) {+ case GGUF_VALUE_TYPE_UINT8:+ case GGUF_VALUE_TYPE_INT8:+ case GGUF_VALUE_TYPE_BOOL:+ return 1;+ case GGUF_VALUE_TYPE_UINT16:+ case GGUF_VALUE_TYPE_INT16:+ return 2;+ case GGUF_VALUE_TYPE_UINT32:+ case GGUF_VALUE_TYPE_INT32:+ case GGUF_VALUE_TYPE_FLOAT32:+ return 4;+ case GGUF_VALUE_TYPE_UINT64:+ case GGUF_VALUE_TYPE_INT64:+ case GGUF_VALUE_TYPE_FLOAT64:+ return 8;+ default:+ return 0; // string / array handled separately+ }+}++ov::element::Type value_type_to_dtype(uint32_t type) {+ switch (type) {+ case GGUF_VALUE_TYPE_UINT8:+ return ov::element::u8;+ case GGUF_VALUE_TYPE_INT8:+ return ov::element::i8;+ case GGUF_VALUE_TYPE_UINT16:+ return ov::element::u16;+ case GGUF_VALUE_TYPE_INT16:+ return ov::element::i16;+ case GGUF_VALUE_TYPE_UINT32:+ return ov::element::u32;+ case GGUF_VALUE_TYPE_INT32:+ return ov::element::i32;+ case GGUF_VALUE_TYPE_FLOAT32:+ return ov::element::f32;+ case GGUF_VALUE_TYPE_BOOL:+ return ov::element::boolean;+ case GGUF_VALUE_TYPE_UINT64:+ return ov::element::u64;+ case GGUF_VALUE_TYPE_INT64:+ return ov::element::i64;+ case GGUF_VALUE_TYPE_FLOAT64:+ return ov::element::f64;+ default:+ OPENVINO_THROW("[load_gguf] unexpected scalar metadata type ", type);+ }+}++// Read a single metadata value of `type` at the cursor into `out`.+void read_metadata_value(Cursor& cur, uint32_t type, GGUFMetaData& out) {+ if (type == GGUF_VALUE_TYPE_STRING) {+ out = cur.read_string();+ return;+ }+ if (type == GGUF_VALUE_TYPE_ARRAY) {+ uint32_t elem_type = cur.read<uint32_t>();+ uint64_t len = cur.read<uint64_t>();+ OPENVINO_ASSERT(elem_type != GGUF_VALUE_TYPE_ARRAY, "[load_gguf] nested arrays are not supported.");+ if (elem_type == GGUF_VALUE_TYPE_STRING) {+ // Each string costs at least 8 bytes (its own length prefix), so this bounds the+ // vector allocation below the same way the fixed-size branch bounds its Tensor.+ OPENVINO_ASSERT(len <= cur.remaining() / sizeof(uint64_t),+ "[load_gguf] string array length ",+ len,+ " overflows the remaining file size");+ std::vector<std::string> strs(len);+ for (auto& s : strs) {+ s = cur.read_string();+ }+ out = std::move(strs);+ return;+ }+ auto dtype = value_type_to_dtype(elem_type);+ const size_t elem_size = value_type_size(elem_type);+ // `len` and `elem_size` are both attacker-controlled (elem_size indirectly, via+ // elem_type) and size a Tensor allocation and a memcpy below; validate `len` against the+ // cursor's remaining bytes -- via a division, not `len * elem_size`, which could itself+ // overflow and wrap under the real remaining size -- before allocating or copying+ // anything.+ OPENVINO_ASSERT(len <= cur.remaining() / elem_size,+ "[load_gguf] array length ",+ len,+ " overflows the remaining file size");+ const size_t nbytes = static_cast<size_t>(len) * elem_size;+ ov::Tensor t(dtype, ov::Shape{static_cast<size_t>(len)});+ std::memcpy(t.data(), cur.ptr(), nbytes);+ cur.skip(nbytes);+ out = std::move(t);+ return;+ }+ // Scalar: store as a shape-{} ov::Tensor of the right element type.+ auto dtype = value_type_to_dtype(type);+ ov::Tensor t(dtype, ov::Shape(0));+ const size_t nbytes = value_type_size(type);+ OPENVINO_ASSERT(nbytes <= cur.remaining(), "[load_gguf] scalar metadata value runs past end of file");+ std::memcpy(t.data(), cur.ptr(), nbytes);+ cur.skip(nbytes);+ out = std::move(t);+}++// Zero-copy view into the mmap for a non-quantized tensor. Uses the dev-API+// Tensor(view, so) constructor so that the mmap shared_ptr is stored in _so and keeps+// the mapping alive for the full lifetime of the returned tensor (and any Constant that+// wraps it via Constant(const Tensor&) -> SharedBuffer<Tensor>).+ov::Tensor extract_tensor_data(const gguf_tensor& tensor, const std::shared_ptr<ov::MappedMemory>& mmap) {+ auto dtype = gguf_type_to_dtype(tensor.type);+ OPENVINO_ASSERT(dtype.has_value(),+ "[load_gguf] tensor '",+ std::string(tensor.name, tensor.namelen),+ "' has unsupported non-quantized type ",+ tensor.type);+ auto shape = get_shape(tensor);+ ov::Tensor view(dtype.value(), shape, const_cast<void*>(static_cast<const void*>(tensor.weights_data)));+ // Attach the mmap shared_ptr as _so so the mapping stays alive for the tensor's lifetime.+ return ov::Tensor(view, mmap);+}++// Fetch a metadata value as an ov::Tensor of the expected element type, failing with the KEY NAME+// on any failure mode: the key is absent, it is present but not a scalar tensor, or its element+// type doesn't match (so a caller can't read past a smaller-than-expected stored type, e.g. a+// 1-byte BOOL where a 4-byte scalar is expected).+static const ov::Tensor& metadata_scalar_tensor(const std::unordered_map<std::string, GGUFMetaData>& metadata,+ const std::string& key,+ const ov::element::Type& expected_type) {+ auto it = metadata.find(key);+ OPENVINO_ASSERT(it != metadata.end(), "[GGUF] required metadata key is missing: '", key, "'");+ const auto* tensor = std::get_if<ov::Tensor>(&it->second);+ OPENVINO_ASSERT(tensor && tensor->data() && tensor->get_element_type() == expected_type,+ "[GGUF] metadata key '",+ key,+ "' is not a ",+ expected_type,+ " scalar as expected");+ 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;+}++} // namespace++ov::Shape get_shape(const gguf_tensor& tensor) {+ ov::Shape shape;+ // GGUF stores dimensions fastest-varying first; the logical (GGML) order is reversed.+ for (int i = static_cast<int>(tensor.ndim) - 1; i >= 0; i--) {+ shape.push_back(tensor.dim[i]);+ }+ return shape;+}++GGUFLoad get_gguf_data(const std::string& file) {+ std::unordered_map<std::string, GGUFMetaData> metadata;+ std::unordered_map<std::string, ov::Tensor> arrays;+ std::unordered_map<std::string, gguf_tensor_type> qtype;++ auto mapped = ov::load_mmap_object(file);+ OPENVINO_ASSERT(mapped && mapped->data(), "[load_gguf] failed to mmap '", file, "'");+ const auto* base = reinterpret_cast<const uint8_t*>(mapped->data());+ const uint64_t fsize = mapped->size();++ Cursor cur(base, fsize);++ // ---- Header ----+ uint32_t magic = cur.read<uint32_t>();+ OPENVINO_ASSERT(magic == GGUF_MAGIC, "[load_gguf] '", file, "' is not a GGUF file (bad magic)");+ uint32_t version = cur.read<uint32_t>();+ OPENVINO_ASSERT(version == 2 || version == 3, "[load_gguf] unsupported GGUF version ", version);+ uint64_t tensor_count = cur.read<uint64_t>();+ uint64_t kv_count = cur.read<uint64_t>();++ // ---- Metadata kv pairs ----+ for (uint64_t i = 0; i < kv_count; i++) {+ std::string key = cur.read_string();+ uint32_t vtype = cur.read<uint32_t>();+ auto& slot = metadata.insert({key, GGUFMetaData{}}).first->second;+ read_metadata_value(cur, vtype, slot);+ }++ uint64_t alignment = GGUF_DEFAULT_ALIGNMENT;+ if (auto it = metadata.find("general.alignment"); it != metadata.end()) {+ if (auto* t = std::get_if<ov::Tensor>(&it->second)) {+ alignment = *(t->data<ov::element_type_traits<ov::element::u32>::value_type>());+ }+ }+ // The GGUF spec requires alignment to be a non-zero power of two; it is also used below as a+ // modulo divisor, so an unvalidated 0 (a perfectly well-formed u32 scalar KV) would be an+ // uncatchable SIGFPE crash in read_model on a crafted or corrupt file.+ OPENVINO_ASSERT(alignment != 0 && (alignment & (alignment - 1)) == 0,+ "[load_gguf] invalid general.alignment ",+ alignment);++ // ---- Tensor info section ----+ struct TensorInfo {+ std::string name;+ uint32_t type = 0;+ uint32_t ndim = 0;+ uint64_t dim[4] = {1, 1, 1, 1};+ uint64_t offset = 0;+ };+ // A minimal tensor-info record (0-length name, ndim=0) is 8 (name len) + 4 (ndim) + 4 (type) ++ // 8 (offset) = 24 bytes; bound the file-controlled `tensor_count` by that before sizing the+ // vector, so a tiny malformed file can't request an effectively unbounded allocation.+ OPENVINO_ASSERT(tensor_count <= cur.remaining() / 24,+ "[load_gguf] tensor count ",+ tensor_count,+ " overflows the remaining file size");+ std::vector<TensorInfo> infos(tensor_count);+ for (uint64_t i = 0; i < tensor_count; i++) {+ TensorInfo& ti = infos[i];+ ti.name = cur.read_string();+ ti.ndim = cur.read<uint32_t>();+ OPENVINO_ASSERT(ti.ndim <= 4, "[load_gguf] tensor '", ti.name, "' has unsupported ndim ", ti.ndim);+ for (uint32_t d = 0; d < ti.ndim; d++) {+ ti.dim[d] = cur.read<uint64_t>();+ }+ ti.type = cur.read<uint32_t>();+ ti.offset = cur.read<uint64_t>();+ }++ // Tensor data starts at the next `alignment`-aligned offset after the info section.+ uint64_t data_off = cur.offset();+ if (uint64_t rem = data_off % alignment) {+ data_off += alignment - rem;+ }++ // Helper: for a quantized tensor, compute (weights_bytes, scale_bytes, zp_bytes).+ // Symmetric types (Q4_0, Q8_0, Q5_0, Q6_K): zp_bytes = 0.+ // Asymmetric types (Q4_1, Q4_K): zp u4 packed (same count as scales, half the bytes).+ // Asymmetric Q5_K: zp u8 (one byte per sub-block, same count as scales).+ //+ // Every dim comes straight from the file, so shape products (and the total below) use+ // ov::util::mul_overflow/add_overflow instead of raw `*=`/`+=`: wrapped products could+ // otherwise under-size quant_buf while the fill functions still write the real,+ // attacker-controlled shape into it.+ auto size_prod = [](const ov::Shape& s) -> size_t {+ size_t result = 1;+ for (auto d : s) {+ size_t next = 0;+ OPENVINO_ASSERT(!ov::util::mul_overflow(result, static_cast<size_t>(d), next),+ "[load_gguf] tensor element count overflows size_t");+ result = next;+ }+ return result;+ };+ auto quant_sizes = [&size_prod](const TensorInfo& ti) -> std::tuple<size_t, size_t, size_t> {+ auto shape = [&]() {+ ov::Shape s;+ for (int i = static_cast<int>(ti.ndim) - 1; i >= 0; --i)+ s.push_back(ti.dim[i]);+ return s;+ }();+ OPENVINO_ASSERT(!shape.empty(), "[load_gguf] tensor '", ti.name, "' is quantized but has rank 0");++ if (ti.type == GGUF_TYPE_Q8_K) {+ // Q8_K: 256 i8 weights + f32 scale + 16 i16 bsums (ignored) per block.+ const size_t nelems = size_prod(shape);+ const size_t n_blocks = nelems / 256;+ return {nelems, n_blocks * sizeof(float), 0}; // w_bytes, s_bytes(f32), no zp+ }++ if (ti.type == GGUF_TYPE_MXFP4) {+ const size_t nelems = size_prod(shape);+ const size_t cols = shape.back();+ OPENVINO_ASSERT(cols != 0, "[load_gguf] tensor '", ti.name, "' has a zero-sized dimension");+ const size_t groups = cols / 32;+ size_t rows = nelems / cols;+ const size_t w_bytes = (nelems + 1) / 2; // f4e2m1: 4-bit+ const size_t s_bytes = rows * groups; // f8e8m0: 1 byte/group+ return {w_bytes, s_bytes, 0};+ }++ const size_t w_nelems = size_prod(shape);++ // Q2_K: u2 (4 per byte), 16 sub-blocks of 16 per super-block.+ if (ti.type == GGUF_TYPE_Q2_K) {+ const size_t w_bytes = (w_nelems + 3) / 4; // u2: 4 values per byte+ auto scale_shape = shape;+ scale_shape.back() /= 16;+ const size_t s_nelems = size_prod(scale_shape);+ return {w_bytes, s_nelems * sizeof(uint16_t), s_nelems}; // zp: u8 per sub-block+ }++ // Q2_0: u2 (4 per byte), one f16 scale per 64 weights, constant zero-point of 1.+ if (ti.type == GGUF_TYPE_Q2_0) {+ const size_t w_bytes = (w_nelems + 3) / 4; // u2: 4 values per byte+ auto scale_shape = shape;+ scale_shape.back() /= 64;+ const size_t s_nelems = size_prod(scale_shape);+ return {w_bytes, s_nelems * sizeof(uint16_t), s_nelems}; // zp: u8 per block+ }++ // Q3_K: i4 packed (2 per byte), 16 sub-blocks of 16 per super-block.+ if (ti.type == GGUF_TYPE_Q3_K) {+ const size_t w_bytes = (w_nelems + 1) / 2; // i4: 2 values per byte+ auto scale_shape = shape;+ scale_shape.back() /= 16;+ const size_t s_nelems = size_prod(scale_shape);+ return {w_bytes, s_nelems * sizeof(uint16_t), 0}; // symmetric: no zp+ }++ // Weights: i8 or u8 stored in byte arrays (not u32-packed anymore for sym; u32 only for 4-bit).+ // 4-bit types: Q4_0(i4 in u32), Q4_1(u4 in u32), Q4_K(u4 in u32).+ // 8-bit types: Q8_0(i8), Q5_0(i8), Q5_1(i8), Q5_K(i8), Q6_K(i8).+ const bool is_4bit = (ti.type == GGUF_TYPE_Q4_0 || ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q4_K);+ uint64_t weights_per_byte = is_4bit ? 2 : 1;+ // Q6_K: 16 weights per sub-block (16 sub-blocks × 16 = 256 per super-block).+ uint64_t weights_per_block = (ti.type == GGUF_TYPE_Q6_K) ? 16 : 32;++ size_t w_bytes;+ if (is_4bit) {+ // u32-packed nibbles: floor((n+7)/8)*4 bytes+ w_bytes = ((w_nelems / weights_per_byte) / 4) * sizeof(uint32_t);+ } else {+ // i8 byte per element+ w_bytes = w_nelems;+ }++ auto scale_shape = shape;+ scale_shape.back() /= weights_per_block;+ const size_t s_nelems = size_prod(scale_shape);+ const size_t s_bytes = s_nelems * sizeof(uint16_t);++ // Zero-point bytes:+ // Symmetric (Q4_0, Q8_0, Q5_0, Q6_K): no zp.+ // Q4_1, Q4_K: u4 zp — same element count as scales, packed 2/byte.+ // Q5_K, Q5_1: u8 zp — one byte per sub-block.+ size_t z_bytes = 0;+ if (ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q4_K) {+ z_bytes = (s_nelems + 1) / 2; // u4 packed+ } else if (ti.type == GGUF_TYPE_Q5_K || ti.type == GGUF_TYPE_Q5_1) {+ z_bytes = s_nelems; // u8+ }+ return {w_bytes, s_bytes, z_bytes};+ };++ // ---- Pass 1: total bytes needed for all repacked quantized data ----+ size_t total_quant_bytes = 0;+ for (const auto& ti : infos) {+ const bool is_quant = ti.type == GGUF_TYPE_Q4_0 || ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q5_0 ||+ ti.type == GGUF_TYPE_Q5_1 || ti.type == GGUF_TYPE_Q8_0 || ti.type == GGUF_TYPE_Q2_K ||+ ti.type == GGUF_TYPE_Q3_K || ti.type == GGUF_TYPE_Q4_K || ti.type == GGUF_TYPE_Q5_K ||+ ti.type == GGUF_TYPE_Q6_K || ti.type == GGUF_TYPE_Q8_K || ti.type == GGUF_TYPE_MXFP4 ||+ ti.type == GGUF_TYPE_Q2_0;+ if (!is_quant)+ continue;+ auto [wb, sb, bb] = quant_sizes(ti);+ size_t sum = 0;+ OPENVINO_ASSERT(!ov::util::add_overflow(wb, sb, sum) && !ov::util::add_overflow(sum, bb, sum) &&+ !ov::util::add_overflow(total_quant_bytes, sum, total_quant_bytes),+ "[load_gguf] total quantized buffer size overflows size_t");+ }++ // Single allocation for all repacked quantized data (IR-frontend AlignedBuffer pattern).+ auto quant_buf = std::make_shared<ov::AlignedBuffer>(total_quant_bytes > 0 ? total_quant_bytes : 1);++ // ---- Pass 2: materialize tensors, slicing into quant_buf for quantized ones ----+ size_t quant_offset = 0;+ for (const auto& ti : infos) {+ gguf_tensor tensor;+ tensor.name = ti.name.data();+ tensor.namelen = ti.name.size();+ tensor.type = ti.type;+ tensor.ndim = ti.ndim;+ uint64_t nelem = 1;+ for (uint32_t d = 0; d < ti.ndim; d++) {+ tensor.dim[d] = ti.dim[d];+ nelem *= ti.dim[d];+ }+ tensor.num_weights = nelem;+ tensor.offset = ti.offset;++ auto tr = type_traits(ti.type);+ OPENVINO_ASSERT(tr.bytes_per_block != 0, "[load_gguf] tensor '", ti.name, "' has unsupported type ", ti.type);+ // ggml requires the innermost (block) dimension to be a whole number of blocks (e.g.+ // ne[0] % 256 == 0 for Q6_K). Without this, a crafted or truncated file's flooring+ // integer division below silently produces a `bsize` that disagrees with the+ // independently-flooring `scale_shape` computed in quant_sizes, letting fill_* write+ // scales past the end of its (too-small) AlignedBuffer slice.+ OPENVINO_ASSERT(ti.dim[0] % tr.items_per_block == 0,+ "[load_gguf] tensor '",+ ti.name,+ "' innermost dimension ",+ ti.dim[0],+ " is not a multiple of its block size ",+ tr.items_per_block);+ tensor.bsize = (nelem / tr.items_per_block) * tr.bytes_per_block;++ // Subtraction-based bounds checks: ti.offset comes straight from the file, so a crafted+ // value must not be allowed to wrap either addition below back into a valid-looking range.+ OPENVINO_ASSERT(data_off <= fsize, "[load_gguf] tensor data section starts past EOF");+ OPENVINO_ASSERT(ti.offset <= fsize - data_off, "[load_gguf] tensor '", ti.name, "' offset runs past EOF");+ uint64_t abs_off = data_off + ti.offset;+ OPENVINO_ASSERT(tensor.bsize <= fsize - abs_off, "[load_gguf] tensor '", ti.name, "' data runs past EOF");+ tensor.weights_data = base + abs_off;++ const std::string& name = ti.name;+ constexpr std::string_view weight_suffix = ".weight";+ const bool has_weight_suffix =+ name.size() >= weight_suffix.size() &&+ name.compare(name.size() - weight_suffix.size(), weight_suffix.size(), weight_suffix) == 0;+ // For tensors ending in ".weight" strip the suffix so make_weight_node keys are+ // "blk.N.attn_q" (not "blk.N.attn_q.weight"). For quantized non-weight tensors+ // (e.g. gpt-oss "blk.N.attn_k.bias") keep the full name as the prefix; the builder+ // looks up scales/qtype as name + ".scales" / name + ".qtype".+ const std::string name_prefix =+ has_weight_suffix ? name.substr(0, name.length() - weight_suffix.length()) : name;+ if (ti.type == GGUF_TYPE_Q4_0) {+ // Symmetric: i4 weights (XORed u4) + f16 scales, no bias tensor.+ auto [wb, sb, bb] = quant_sizes(ti);+ char* buf_ptr = quant_buf->get_ptr<char>();+ auto shape = get_shape(tensor);+ auto weights_shape = shape;+ weights_shape.back() /= 8; // u32 packs 8 i4 nibbles+ auto scale_shape = shape;+ scale_shape.back() /= 32;++ std::shared_ptr<void> so_buf(quant_buf);+ ov::Tensor w_view(ov::element::u32, weights_shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor weights(w_view, so_buf);+ quant_offset += wb;+ ov::Tensor s_view(ov::element::f16, scale_shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor scales(s_view, so_buf);+ quant_offset += sb;++ gguf_fill_q4_0(tensor, weights, scales);+ mapped->hint_evict(abs_off, tensor.bsize);++ arrays.emplace(name, std::move(weights));+ arrays.emplace(name_prefix + ".scales", std::move(scales));+ qtype.emplace(name_prefix + ".qtype", GGUF_TYPE_Q4_0);+ } else if (ti.type == GGUF_TYPE_Q3_K) {+ // Symmetric: i4 weights (2 per byte) + f16 scales. No zero-point.+ auto [wb, sb, zb] = quant_sizes(ti);+ (void)zb;+ char* buf_ptr = quant_buf->get_ptr<char>();++ auto shape = get_shape(tensor);+ auto scale_shape = shape;+ scale_shape.back() /= 16; // 16 sub-blocks per super-block++ std::shared_ptr<void> so_buf(quant_buf);+ ov::Tensor w_view(ov::element::i4, shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor weights(w_view, so_buf);+ quant_offset += wb;+ ov::Tensor s_view(ov::element::f16, scale_shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor scales(s_view, so_buf);+ quant_offset += sb;++ gguf_fill_sym(tensor, weights, scales);+ mapped->hint_evict(abs_off, tensor.bsize);++ arrays.emplace(name, std::move(weights));+ arrays.emplace(name_prefix + ".scales", std::move(scales));+ qtype.emplace(name_prefix + ".qtype", GGUF_TYPE_Q3_K);+ } else if (ti.type == GGUF_TYPE_Q2_K) {+ // Asymmetric: u2 weights (4 per byte) + f16 scales + u8 zp per sub-block.+ auto [wb, sb, zb] = quant_sizes(ti);+ char* buf_ptr = quant_buf->get_ptr<char>();++ auto shape = get_shape(tensor);+ auto scale_shape = shape;+ scale_shape.back() /= 16; // 16 sub-blocks per super-block++ std::shared_ptr<void> so_buf(quant_buf);+ ov::Tensor w_view(ov::element::u2, shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor weights(w_view, so_buf);+ quant_offset += wb;+ ov::Tensor s_view(ov::element::f16, scale_shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor scales(s_view, so_buf);+ quant_offset += sb;+ // Fractional zp (= min/scale) in the scale's element type -- see the Q4_K/Q5_K branch.+ ov::Tensor zp(scales.get_element_type(), scale_shape);+ quant_offset += zb;++ gguf_fill_asym(tensor, weights, scales, zp);+ mapped->hint_evict(abs_off, tensor.bsize);++ arrays.emplace(name, std::move(weights));+ arrays.emplace(name_prefix + ".scales", std::move(scales));+ arrays.emplace(name_prefix + ".zp", std::move(zp));+ qtype.emplace(name_prefix + ".qtype", GGUF_TYPE_Q2_K);+ } else if (ti.type == GGUF_TYPE_Q2_0) {+ // Ternary: u2 weights (4 per byte) + one f16 scale per 64 + integer zp of exactly 1.+ // ggml packs Q2_0 codes LSB-first, 4 per byte -- the same order OpenVINO's u2 Constant+ // expects -- so the code bytes are copied verbatim, no repacking.+ auto [wb, sb, zb] = quant_sizes(ti);+ char* buf_ptr = quant_buf->get_ptr<char>();++ auto shape = get_shape(tensor);+ auto scale_shape = shape;+ scale_shape.back() /= 64; // one scale per 64-weight block++ std::shared_ptr<void> so_buf(quant_buf);+ ov::Tensor w_view(ov::element::u2, shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor weights(w_view, so_buf);+ quant_offset += wb;+ ov::Tensor s_view(ov::element::f16, scale_shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor scales(s_view, so_buf);+ quant_offset += sb;+ // Integer zero-point: (code - 1) * scale, so zp is the constant 1 for every block.+ ov::Tensor zp(ov::element::u8, scale_shape);+ quant_offset += zb;++ gguf_fill_q2_0(tensor, weights, scales, zp);+ mapped->hint_evict(abs_off, tensor.bsize);++ arrays.emplace(name, std::move(weights));+ arrays.emplace(name_prefix + ".scales", std::move(scales));+ arrays.emplace(name_prefix + ".zp", std::move(zp));+ qtype.emplace(name_prefix + ".qtype", GGUF_TYPE_Q2_0);+ } else if (ti.type == GGUF_TYPE_Q8_K) {+ // Q8_K: 256 weights/block, f32 scale (NOT f16), 16 i16 bsums (ignored).+ // block_q8_K: [f32 d][i8 qs[256]][i16 bsums[16]] = 4+256+32 = 292 bytes.+ auto [wb, sb, zb] = quant_sizes(ti);+ (void)zb;+ char* buf_ptr = quant_buf->get_ptr<char>();++ auto shape = get_shape(tensor);+ auto scale_shape = shape;+ scale_shape.back() /= 256; // one f32 scale per 256-weight block++ std::shared_ptr<void> so_buf(quant_buf);+ ov::Tensor w_view(ov::element::i8, shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor weights_t(w_view, so_buf);+ quant_offset += wb;+ ov::Tensor s_view(ov::element::f32, scale_shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor scales_t(s_view, so_buf);+ quant_offset += sb;++ gguf_fill_sym(tensor, weights_t, scales_t);+ mapped->hint_evict(abs_off, tensor.bsize);++ arrays.emplace(name, std::move(weights_t));+ arrays.emplace(name_prefix + ".scales", std::move(scales_t));+ qtype.emplace(name_prefix + ".qtype", GGUF_TYPE_Q8_K);+ } else if (ti.type == GGUF_TYPE_Q8_0 || ti.type == GGUF_TYPE_Q5_0 || ti.type == GGUF_TYPE_Q6_K) {+ // Symmetric: i8 weights (no u32 packing) + f16 scales. No zero-point.+ auto [wb, sb, zb] = quant_sizes(ti);+ (void)zb;+ char* buf_ptr = quant_buf->get_ptr<char>();++ auto shape = get_shape(tensor);+ const uint64_t weights_per_block = (ti.type == GGUF_TYPE_Q6_K) ? 16 : 32;+ auto scale_shape = shape;+ scale_shape.back() /= weights_per_block;++ std::shared_ptr<void> so_buf(quant_buf);+ ov::Tensor w_view(ov::element::i8, shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor weights(w_view, so_buf);+ quant_offset += wb;+ ov::Tensor s_view(ov::element::f16, scale_shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor scales(s_view, so_buf);+ quant_offset += sb;++ gguf_fill_sym(tensor, weights, scales);+ mapped->hint_evict(abs_off, tensor.bsize);++ arrays.emplace(name, std::move(weights));+ arrays.emplace(name_prefix + ".scales", std::move(scales));+ qtype.emplace(name_prefix + ".qtype", static_cast<gguf_tensor_type>(ti.type));+ } else if (ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q4_K || ti.type == GGUF_TYPE_Q5_K ||+ ti.type == GGUF_TYPE_Q5_1) {+ // Asymmetric: weights + f16 scales + integer zp.+ // 4-bit (Q4_1, Q4_K): u32-packed u4 weights, u4 zp.+ // 8-bit (Q5_K, Q5_1): i8 weights, u8 zp.+ auto [wb, sb, zb] = quant_sizes(ti);+ char* buf_ptr = quant_buf->get_ptr<char>();++ auto shape = get_shape(tensor);+ const bool is_4bit = (ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q4_K);+ const uint64_t weights_per_block = 32;++ auto weights_shape = shape;+ if (is_4bit)+ weights_shape.back() /= 8; // u32 packs 8 u4+ auto scale_shape = shape;+ scale_shape.back() /= weights_per_block;++ std::shared_ptr<void> so_buf(quant_buf);+ ov::element::Type w_elem = is_4bit ? ov::element::u32 : ov::element::i8;+ ov::Tensor w_view(w_elem, is_4bit ? weights_shape : shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor weights(w_view, so_buf);+ quant_offset += wb;+ ov::Tensor s_view(ov::element::f16, scale_shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor scales(s_view, so_buf);+ quant_offset += sb;+ // Both ingest paths must agree on the zero-point representation; see+ // gguf_zero_point_type in quant/weights.hpp for why it matters.+ const auto zp_elem = gguf_zero_point_type(name, static_cast<gguf_tensor_type>(ti.type));+ // Only Q4_K's integer zp actually rounds: Q2_0's zero-point is the exact integer 1.+ if (zp_elem == ov::element::u8 && ti.type == GGUF_TYPE_Q4_K) {+ notify_lossy_weight_approximation(LossyWeightApproximation::IntegerZeroPoint);+ }+ ov::Tensor zp(zp_elem, scale_shape);+ quant_offset += zb;++ gguf_fill_asym(tensor, weights, scales, zp);+ mapped->hint_evict(abs_off, tensor.bsize);++ arrays.emplace(name, std::move(weights));+ arrays.emplace(name_prefix + ".scales", std::move(scales));+ arrays.emplace(name_prefix + ".zp", std::move(zp));+ qtype.emplace(name_prefix + ".qtype", static_cast<gguf_tensor_type>(ti.type));+ } else if (ti.type == GGUF_TYPE_MXFP4) {+ // MXFP4: slice weight (f4e2m1) + scale (f8e8m0) out of quant_buf.+ auto [wb, sb, dummy_bb] = quant_sizes(ti);+ (void)dummy_bb;+ char* buf_ptr = quant_buf->get_ptr<char>();++ auto shape = get_shape(tensor);+ const size_t cols = shape.back();+ size_t nelems = 1;+ for (auto d : shape)+ nelems *= d;+ const size_t groups = cols / 32;+ ov::Shape scale_shape = shape;+ scale_shape.back() = groups;++ std::shared_ptr<void> so_buf(quant_buf);+ ov::Tensor w_view(ov::element::f4e2m1, shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor weights(w_view, so_buf);+ quant_offset += wb;++ ov::Tensor s_view(ov::element::f8e8m0, scale_shape, static_cast<void*>(buf_ptr + quant_offset));+ ov::Tensor scales(s_view, so_buf);+ quant_offset += sb;++ gguf_fill_mxfp4(tensor, weights, scales);+ mapped->hint_evict(abs_off, tensor.bsize);++ constexpr std::string_view weight_suffix = ".weight";+ const std::string prefix = name.substr(0, name.length() - weight_suffix.length());+ arrays.emplace(name, std::move(weights));+ arrays.emplace(prefix + ".scales", std::move(scales));+ qtype.emplace(prefix + ".qtype", GGUF_TYPE_MXFP4);+ } else {+ ov::Tensor loaded = extract_tensor_data(tensor, mapped); // zero-copy mmap view+ OPENVINO_ASSERT(arrays.emplace(name, loaded).second, "[load_gguf] duplicate tensor name '", name, "'");+ constexpr std::string_view weight_suffix = ".weight";+ if (name.size() >= weight_suffix.size()) {+ const std::string name_prefix = name.substr(0, name.length() - weight_suffix.length());+ qtype.emplace(name_prefix + ".qtype", static_cast<gguf_tensor_type>(ti.type));+ }+ }+ }++ return {metadata, arrays, qtype, mapped, quant_buf};+}++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");+ config["head_num"] = metadata_to_int(metadata, arch + ".attention.head_count");+ // When key_length is absent, head_size falls back to embedding_length / head_count, which+ // runs before supported_archs() can reject anything; a malformed/adversarial file with+ // head_count == 0 would otherwise be an uncatchable SIGFPE crash rather than a clear error.+ if (!metadata.count(arch + ".attention.key_length")) {+ OPENVINO_ASSERT(std::get<int>(config["head_num"]) > 0,+ "[GGUF] '",+ arch,+ ".attention.head_count' must be positive");+ }+ config["head_size"] = metadata.count(arch + ".attention.key_length")+ ? metadata_to_int(metadata, arch + ".attention.key_length")+ : (metadata_to_int(metadata, arch + ".embedding_length") /+ metadata_to_int(metadata, arch + ".attention.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["rms_norm_eps"] = metadata_to_float(metadata, arch + ".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);+ config["rope_freq_scale"] = ropescale == 0.0f ? 1.0f : 1.0f / ropescale;++ 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;++ // 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);+ config["logit_scale"] = metadata_to_float_or(metadata, arch + ".logit_scale", def_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).+ {+ std::vector<int32_t> recr;+ const std::string key = arch + ".attention.recurrent_layers";+ if (metadata.count(key)) {+ const auto& t = std::get<ov::Tensor>(metadata.at(key));+ const auto* p = t.data<uint32_t>();+ for (size_t i = 0; i < t.get_size(); ++i)+ recr.push_back(static_cast<int32_t>(p[i]));+ }+ config["recurrent_layer_flags"] = recr;+ }++ // M-RoPE section widths (qwen35 / qwen3vl): 4 per-axis rotary section sizes.+ {+ std::vector<int32_t> sections;+ const std::string key = arch + ".rope.dimension_sections";+ if (metadata.count(key)) {+ const auto& t = std::get<ov::Tensor>(metadata.at(key));+ const auto* p = t.data<uint32_t>();+ for (size_t i = 0; i < t.get_size() && i < 4; ++i)+ sections.push_back(static_cast<int32_t>(p[i]));+ }+ config["rope_sections"] = sections;+ }++ // 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 : 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") ? 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 = 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.+ const size_t n = t.get_size();+ std::vector<int32_t> swa_flags(n);+ const auto* bdata = t.data<uint8_t>();+ for (size_t i = 0; i < n; ++i)+ swa_flags[i] = bdata[i] ? 1 : 0;+ config["swa_layer_flags"] = swa_flags;+ 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 : 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);++ // qwen3moe/glm4moe/bailingmoe2 MoE: renormalize the selected top-K gate weights to sum to 1+ // (llama.cpp build_moe_ffn's norm_w / "norm_topk_prob"); absent -> no renormalization.+ 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);++ return config;+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/quant/gguf.hpp b/src/frontends/gguf/src/quant/gguf.hppindex 3f7aa7986c4..12b6992ae2a 100644--- a/src/frontends/gguf/src/quant/gguf.hpp+++ b/src/frontends/gguf/src/quant/gguf.hpp@@ -85,6 +85,16 @@ struct gguf_tensor {using GGUFMetaData =std::variant<std::monostate, float, int, ov::Tensor, std::string, std::vector<std::string>, std::vector<int32_t>>;+// GGUFLoad result: (metadata, tensor arrays, qtype map, mmap, quant_buf).+// - mmap: must stay alive while arrays tensors are used (non-quantized tensors are mmap views).+// - quant_buf: single AlignedBuffer holding all repacked quantized weight/scale/bias data;+// tensors in `arrays` for quantized weights are SharedBuffer slices into this buffer.+using GGUFLoad = std::tuple<std::unordered_map<std::string, GGUFMetaData>,+ std::unordered_map<std::string, ov::Tensor>,+ std::unordered_map<std::string, gguf_tensor_type>,+ std::shared_ptr<ov::MappedMemory>,+ std::shared_ptr<ov::AlignedBuffer>>;+// Fill pre-allocated i4 weights (u32-packed, XORed for i4 sign) and f16 scales from a// Q4_0 tensor. No bias: Q4_0 is symmetric (zp = -8*scale is implicit, not stored).void gguf_fill_q4_0(const gguf_tensor& tensor, ov::Tensor& weights, ov::Tensor& scales);@@ -122,10 +132,23 @@ void dequant_row_q4_k_f32_for_test(const uint8_t* row, size_t cols, float* y);void dequant_row_q5_k_f32_for_test(const uint8_t* row, size_t cols, float* y);void dequant_row_q6_k_f32_for_test(const uint8_t* row, size_t cols, float* y);-// Extract the 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.-std::map<std::string, GGUFMetaData> config_from_meta(const std::unordered_map<std::string, GGUFMetaData>& metadata);+// Parse a GGUF file: returns (metadata, tensors-by-ggml-name, qtype map, mmap, quant_buf).+// Non-quantized tensors are zero-copy views into the mmap (mmap must outlive arrays use).+// Quantized tensors are SharedBuffer slices of a single AlignedBuffer (quant_buf) so all+// repacked weight/scale/bias data lives in one allocation (IR-frontend pattern).+GGUFLoad get_gguf_data(const std::string& file);++// 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 gguf_tensor& tensor);diff --git a/src/frontends/gguf/src/quant/weights.cpp b/src/frontends/gguf/src/quant/weights.cppindex 5eb8e87ddaa..cdb5e9d7b59 100644--- a/src/frontends/gguf/src/quant/weights.cpp+++ b/src/frontends/gguf/src/quant/weights.cpp@@ -13,7 +13,10 @@#include <array>#include <cctype>#include <cmath>+#include <cstdlib>#include <cstring>+#include <iostream>+#include <mutex>#include <vector>#include "openvino/core/except.hpp"@@ -52,6 +55,17 @@ ov::Tensor slice_rows(const ov::Tensor& t, size_t r0, size_t r1) {return out;}+// Copy elements [r0, r1) out of a 1D tensor. Used for a fused attn_qkv.bias, which -- unlike the+// weight -- is a plain unquantized array, so a byte-range copy is exact regardless of dtype.+ov::Tensor slice_1d(const ov::Tensor& t, size_t r0, size_t r1) {+ const auto& s = t.get_shape();+ OPENVINO_ASSERT(s.size() == 1 && r1 <= s[0] && r0 <= r1, "[GGUF] bad 1D slice");+ ov::Tensor out(t.get_element_type(), ov::Shape{r1 - r0});+ const size_t elem_bytes = t.get_byte_size() / s[0];+ std::memcpy(out.data(), static_cast<const uint8_t*>(t.data()) + r0 * elem_bytes, (r1 - r0) * elem_bytes);+ return out;+}+// Gather rows in a repeating per-block pattern: for every `block` consecutive rows, take// [offset, offset + take) into the result. Used to de-interleave qwen35's attn_q, which packs// query and gate per head as [q_h0 | gate_h0 | q_h1 | gate_h1 | ...].@@ -127,9 +141,11 @@ std::shared_ptr<ov::Node> make_q4_0(const std::string& name,}// Symmetric 8-bit (Q8_0, Q5_0, Q6_K): i8 weights (pre-centered) + per-group f16 scale.-// No zero-point. Emits: Multiply(Convert(i8_const, f16), scale) [-> Reshape].+// Q6_K uses explicit f32 arithmetic to preserve the reference dequantization accuracy; the other+// formats use the compressed-weight decomposition.std::shared_ptr<ov::Node> make_sym_int8(const std::string& name,- const std::unordered_map<std::string, ov::Tensor>& weights) {+ const std::unordered_map<std::string, ov::Tensor>& weights,+ gguf_tensor_type qtype) {ov::Tensor weight = get(weights, name + ".weight"); // i8 byte per elementov::Tensor scales = get(weights, name + ".scales");@@ -147,6 +163,13 @@ std::shared_ptr<ov::Node> make_sym_int8(const std::string& name,auto final_shape_node =std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);+ if (qtype == GGUF_TYPE_Q6_K) {+ auto values = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f32);+ auto scales_f32 = std::make_shared<ov::op::v0::Convert>(scales_node, ov::element::f32);+ auto dequant = std::make_shared<ov::op::v1::Multiply>(values, scales_f32);+ return std::make_shared<ov::op::v1::Reshape>(dequant, final_shape_node, false);+ }+auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),scales_node->output(0),{},@@ -154,13 +177,13 @@ std::shared_ptr<ov::Node> make_sym_int8(const std::string& name,return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);}-// 4-bit asymmetric (Q4_1/Q4_K): u4 weights + per-group f16 scale + u8 integer zero-points.-// Emits: Multiply(Subtract(Convert(u4_const, f16), zp_u8), scale) [-> Reshape].+// 4-bit asymmetric (Q4_1/Q4_K): u4 weights + per-group scale and zero-point. Fractional f16+// zero-points use explicit f32 dequantization; exact integer zero-points keep the compressed path.std::shared_ptr<ov::Node> make_int4(const std::string& name,const std::unordered_map<std::string, ov::Tensor>& weights) {ov::Tensor weight = get(weights, name + ".weight"); // u32-packed u4ov::Tensor scales = get(weights, name + ".scales");- ov::Tensor zp_t = get(weights, name + ".zp"); // u8 integer zero-points+ ov::Tensor zp_t = get(weights, name + ".zp");ov::Shape orig_shape = weight.get_shape();orig_shape.back() *= sizeof(uint32_t) / sizeof(uint8_t) * 2; // u32 packs 8 u4@@ -179,6 +202,15 @@ std::shared_ptr<ov::Node> make_int4(const std::string& name,auto final_shape_node =std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);+ if (zp_t.get_element_type() == ov::element::f16) {+ auto values = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f32);+ auto scales_f32 = std::make_shared<ov::op::v0::Convert>(scales_node, ov::element::f32);+ auto zp_f32 = std::make_shared<ov::op::v0::Convert>(zp_node, ov::element::f32);+ auto dequant = std::make_shared<ov::op::v1::Multiply>(+ std::make_shared<ov::op::v1::Subtract>(values, zp_f32), scales_f32);+ return std::make_shared<ov::op::v1::Reshape>(dequant, final_shape_node, false);+ }+auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),scales_node->output(0),zp_node->output(0),@@ -269,6 +301,15 @@ std::shared_ptr<ov::Node> make_asym_int8(const std::string& name,auto final_shape_node =std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);+ if (zp_t.get_element_type() == ov::element::f16) {+ auto values = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f32);+ auto scales_f32 = std::make_shared<ov::op::v0::Convert>(scales_node, ov::element::f32);+ auto zp_f32 = std::make_shared<ov::op::v0::Convert>(zp_node, ov::element::f32);+ auto dequant = std::make_shared<ov::op::v1::Multiply>(+ std::make_shared<ov::op::v1::Subtract>(values, zp_f32), scales_f32);+ return std::make_shared<ov::op::v1::Reshape>(dequant, final_shape_node, false);+ }+auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),scales_node->output(0),zp_node->output(0),@@ -423,19 +464,67 @@ bool needs_q8_0_c_requant(const std::string& name, gguf_tensor_type qtype) {if (name.rfind("token_embd.weight", 0) == 0 || name.rfind("output.weight", 0) == 0) {return true;}- return qtype == GGUF_TYPE_Q6_K || qtype == GGUF_TYPE_Q5_K;+ return qtype == GGUF_TYPE_Q5_K;+}++// Opt-in switch: represent Q4_K's asymmetric zero-point as a faithful f16 constant instead of+// the default integer (u8) one. Left unset, production (genai) keeps the u8 zero-point for the+// ~2x faster compressed-FC dequant; llama.cpp's test-backend-ops compares against an f32+// reference with a tolerance the rounded u8 zero-point can miss, so its CI sets this to trade+// that speedup for exact accuracy. See gguf_zero_point_type.+bool q4_k_f16_zero_point_enabled() {+ static const bool enabled = [] {+ const char* env = std::getenv("OV_GGUF_Q4_K_ZP_F16");+ return env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0;+ }();+ return enabled;}} // namespace+void notify_lossy_weight_approximation(LossyWeightApproximation kind) {+ // Written to std::cerr, NOT OPENVINO_WARN: the latter expands to a no-op unless the build sets+ // ENABLE_OPENVINO_DEBUG (cmake/features.cmake defaults it OFF), so in every shipped build it+ // reaches nobody -- and this notice exists precisely to reach the user. It is a deliberate,+ // permanent, at-most-once-per-process diagnostic, not leftover tracing.+ //+ // One flag per kind, so a model that hits both approximations reports both -- but each at most+ // once, however many thousands of weights are affected.+ static std::once_flag requant_once;+ static std::once_flag zero_point_once;++ switch (kind) {+ case LossyWeightApproximation::Q8_0_C_Requant:+ std::call_once(requant_once, [] {+ std::cerr << "[GGUF] accuracy notice: the token embedding / output / Q6_K / Q5_K weights are "+ "requantized channel-wise to Q8_0_C (one int8 scale per row). This is lossy, so results "+ "may differ slightly from the original GGUF weights. It reproduces the llama.cpp "+ "ggml-openvino backend's weight pipeline. Reported once per process."+ << std::endl;+ });+ break;+ case LossyWeightApproximation::IntegerZeroPoint:+ std::call_once(zero_point_once, [] {+ std::cerr << "[GGUF] accuracy notice: Q4_K weights use an integer (u8) zero-point, which rounds each "+ "sub-block's minimum to a multiple of its scale. This is lossy, so results may differ "+ "slightly from the original GGUF weights. It keeps the dequantization foldable into an "+ "int8 MatMul, which is roughly twice as fast at prefill. Reported once per process."+ << std::endl;+ });+ break;+ }+}+ov::element::Type gguf_zero_point_type(const std::string& name, gguf_tensor_type qtype) {// The CPU compressed-FullyConnected fast path only folds the dequant when the zero-point is an// INTEGER constant; a fractional f16 one leaves a ~2x slower kernel. Q4_K carries the matmul- // weights of modern models and Q2_0's zp is the exact integer 1, so both use u8. The others- // keep a faithful f16 zp: their zp = min/scale can exceed u8 range, and rounding it injects- // error into every weight. Tensors that are requantized to Q8_0_C are excluded -- their dequant- // feeds the channel-wise path, not a compressed FC.- const bool integer_zp = (qtype == GGUF_TYPE_Q4_K || qtype == GGUF_TYPE_Q2_0);+ // weights of modern models and Q2_0's zp is the exact integer 1, so both use u8 by default. The+ // others keep a faithful f16 zp: their zp = min/scale can exceed u8 range, and rounding it+ // injects error into every weight. Tensors that are requantized to Q8_0_C are excluded --+ // their dequant feeds the channel-wise path, not a compressed FC. Q4_K's u8 zp can be switched+ // back to a faithful f16 one via OV_GGUF_Q4_K_ZP_F16 (see q4_k_f16_zero_point_enabled).+ const bool integer_zp =+ qtype == GGUF_TYPE_Q2_0 || (qtype == GGUF_TYPE_Q4_K && !q4_k_f16_zero_point_enabled());return (integer_zp && !needs_q8_0_c_requant(name, qtype)) ? ov::element::u8 : ov::element::f16;}@@ -474,7 +563,7 @@ std::shared_ptr<ov::Node> make_weight_node(const std::string& base,case GGUF_TYPE_Q8_0:case GGUF_TYPE_Q6_K:case GGUF_TYPE_Q8_K:- node = make_sym_int8(base, weights);+ node = make_sym_int8(base, weights, qtype);break;case GGUF_TYPE_F16:case GGUF_TYPE_F32:@@ -564,6 +653,18 @@ std::array<FusedQkvPart, 3> split_fused_qkv_extracted(return out;}+std::array<ov::Tensor, 3> split_fused_qkv_bias(const std::string& base,+ const std::unordered_map<std::string, ov::Tensor>& weights,+ size_t n_q,+ size_t n_k,+ size_t n_v) {+ const ov::Tensor& b = get(weights, base + ".bias");+ const auto& s = b.get_shape();+ OPENVINO_ASSERT(s.size() == 1, "[GGUF] fused qkv bias for ", base, " is not 1D");+ OPENVINO_ASSERT(n_q + n_k + n_v == s[0], "[GGUF] fused qkv bias row mismatch for ", base);+ return {slice_1d(b, 0, n_q), slice_1d(b, n_q, n_q + n_k), slice_1d(b, n_q + n_k, s[0])};+}+// qwen35: attn_q packs the query and the attention output gate interleaved per head, as// [q_h0 | gate_h0 | q_h1 | gate_h1 | ...] with a stride of 2*head_dim rows. De-interleave it// into two plain weights so the graph sees ordinary projections. Returns {query, gate}.@@ -618,6 +719,34 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,const std::string base = "weight";+ if (qtype == GGUF_TYPE_Q4_1 || qtype == GGUF_TYPE_Q5_1) {+ ov::Tensor decoded(ov::element::f32, logical_shape);+ auto* out = decoded.data<float>();+ const auto* src = static_cast<const uint8_t*>(data.data());+ const size_t block_bytes = qtype == GGUF_TYPE_Q4_1 ? 20 : 24;+ const size_t blocks = rows * cols / 32;+ for (size_t b = 0; b < blocks; ++b) {+ const uint8_t* block = src + b * block_bytes;+ uint16_t d_bits, m_bits;+ std::memcpy(&d_bits, block, sizeof(d_bits));+ std::memcpy(&m_bits, block + 2, sizeof(m_bits));+ const float d = static_cast<float>(ov::float16::from_bits(d_bits));+ const float m = static_cast<float>(ov::float16::from_bits(m_bits));+ uint32_t qh = 0;+ const uint8_t* qs = block + 4;+ if (qtype == GGUF_TYPE_Q5_1) {+ std::memcpy(&qh, block + 4, sizeof(qh));+ qs = block + 8;+ }+ for (size_t j = 0; j < 32; ++j) {+ const uint8_t lo = j < 16 ? (qs[j] & 0x0f) : (qs[j - 16] >> 4);+ const uint8_t q = lo | (qtype == GGUF_TYPE_Q5_1 ? ((qh >> j) & 1) << 4 : 0);+ out[b * 32 + j] = d * static_cast<float>(q) + m;+ }+ }+ return std::make_shared<ov::op::v0::Constant>(decoded);+ }+// Non-quantized weights: wrap the bytes directly as a Constant of the matching type.if (qtype == GGUF_TYPE_F32 || qtype == GGUF_TYPE_F16 || qtype == GGUF_TYPE_BF16) {ov::element::Type et = qtype == GGUF_TYPE_F32 ? ov::element::f32@@ -657,6 +786,13 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,// requant path (token_embd/output) also keeps f16 -- its dequant feeds channel-wise Q8_0_C.const bool requant = needs_q8_0_c_requant(name, qtype);const ov::element::Type zp_type = gguf_zero_point_type(name, qtype);+ if (requant) {+ notify_lossy_weight_approximation(LossyWeightApproximation::Q8_0_C_Requant);+ }+ // Only Q4_K's integer zp actually rounds: Q2_0's zero-point is the exact integer 1.+ if (zp_type == ov::element::u8 && qtype == GGUF_TYPE_Q4_K) {+ notify_lossy_weight_approximation(LossyWeightApproximation::IntegerZeroPoint);+ }// K-quant requant sources: the fused dequant -> Q8_0_C streams from the raw bytes, so skip the// full-tensor gguf_fill_* extraction below (it would be discarded) and return before the switch.@@ -670,6 +806,17 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,}switch (qtype) {+ case GGUF_TYPE_MXFP4: {+ // 2D here means a bare MXFP4 tensor from the llama.cpp cgraph path (e.g. test-backend-ops+ // op tests), not a stored MoE expert weight -- those stay rank>2 and are intercepted+ // earlier in translate_weight() to keep them packed for MUL_MAT_ID.+ ov::Tensor weights(ov::element::f4e2m1, ov::Shape{rows, cols});+ ov::Tensor scales(ov::element::f8e8m0, ov::Shape{rows, sub_blocks_per_row(32)});+ gguf_fill_mxfp4(tensor, weights, scales);+ w[base + ".weight"] = weights;+ w[base + ".scales"] = scales;+ break;+ }case GGUF_TYPE_Q4_0: {ov::Tensor weights(ov::element::u32, ov::Shape{rows, cols / 8});ov::Tensor scales(ov::element::f16, ov::Shape{rows, sub_blocks_per_row(32)});diff --git a/src/frontends/gguf/src/quant/weights.hpp b/src/frontends/gguf/src/quant/weights.hppindex 5c6486d6eab..311ab571088 100644--- a/src/frontends/gguf/src/quant/weights.hpp+++ b/src/frontends/gguf/src/quant/weights.hpp@@ -19,8 +19,30 @@ namespace ov::frontend::gguf {// Element type of the zero-point constant for an asymmetric quantized weight. Both ingest// paths must agree on this: it decides whether the CPU folds the dequant into the MatMul.+// Q4_K defaults to an integer (u8) zero-point (faster, lossy); set the environment variable+// OV_GGUF_Q4_K_ZP_F16=1 to use a faithful f16 zero-point instead (llama.cpp's test-backend-ops+// CI does this to meet its accuracy tolerance).ov::element::Type gguf_zero_point_type(const std::string& name, gguf_tensor_type qtype);+// A lossy weight approximation the frontend deliberately makes, reported to the user once so a+// later accuracy investigation starts from the right place.+enum class LossyWeightApproximation {+ // token_embd / output / Q6_K / Q5_K tensors requantized channel-wise to Q8_0_C.+ Q8_0_C_Requant,+ // Q4_K asymmetric weights expressed with an INTEGER (u8) zero-point, which forces each+ // sub-block's min to a multiple of its scale.+ IntegerZeroPoint,+};++// Warn -- ONCE per process and per approximation kind -- that weights are being converted with a+// lossy approximation, so generated text may differ slightly from the original GGUF weights.+//+// Once per process rather than once per model: the message describes a fixed property of the+// conversion strategy, not of one tensor or one file, and a model has thousands of affected+// weights (every Q4_K matmul), so anything finer-grained would bury the log. Call it at the point+// the approximation is actually PERFORMED, not where its parameters are queried.+void notify_lossy_weight_approximation(LossyWeightApproximation kind);+// Build the OpenVINO node for a GGUF weight with base name `base` (the tensor name without// the trailing ".weight", e.g. "blk.0.attn_q" or "token_embd"). Quantized weights become a// low-bitness compressed subgraph (u4/u8 weights + zero-point + f16 scale, Convert ->@@ -73,6 +95,15 @@ std::array<FusedQkvPart, 3> split_fused_qkv_extracted(size_t n_k,size_t n_v);+// Row-slice a fused `<base>.bias` (plain, unquantized 1D tensor) into q/k/v parts, using the+// same row ranges as split_fused_qkv_extracted. Callers only invoke this when `<base>.bias`+// is present -- not every fused-QKV arch has one.+std::array<ov::Tensor, 3> split_fused_qkv_bias(const std::string& base,+ const std::unordered_map<std::string, ov::Tensor>& weights,+ size_t n_q,+ size_t n_k,+ size_t n_v);+// De-interleave a qwen35 `<base>` attn_q weight, which packs the query and the attention output// gate per head as [q_h0 | gate_h0 | q_h1 | gate_h1 | ...], into two plain projections.// Returns {query, gate}, keyed "<base>.q.*" and "<base>.gate.*".diff --git a/src/frontends/gguf/src/tokenizer_metadata.cpp b/src/frontends/gguf/src/tokenizer_metadata.cppnew file mode 100644index 00000000000..b596c51b002--- /dev/null+++ b/src/frontends/gguf/src/tokenizer_metadata.cpp@@ -0,0 +1,18 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/frontend/gguf/tokenizer_metadata.hpp"++namespace ov {+namespace frontend {+namespace gguf {++const std::string& gguf_tokenizer_metadata_key() {+ static const std::string key = "gguf_tokenizer_metadata";+ return key;+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/translate_session.cpp b/src/frontends/gguf/src/translate_session.cppindex 83b67dd3ce4..fa3638e4d95 100644--- a/src/frontends/gguf/src/translate_session.cpp+++ b/src/frontends/gguf/src/translate_session.cpp@@ -10,6 +10,7 @@#include <map>#include <memory>#include <set>+#include <unordered_set>#include "input_model.hpp"#include "node_context.hpp"@@ -17,6 +18,7 @@#include "openvino/core/node.hpp"#include "openvino/core/rt_info/weightless_caching_attributes.hpp"#include "openvino/frontend/gguf/make_stateful.hpp"+#include "openvino/frontend/gguf/tokenizer_metadata.hpp"#include "openvino/op/add.hpp"#include "openvino/op/broadcast.hpp"#include "openvino/op/concat.hpp"@@ -26,6 +28,7 @@#include "openvino/op/cos.hpp"#include "openvino/op/divide.hpp"#include "openvino/op/gather.hpp"+#include "openvino/op/loop.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/parameter.hpp"#include "openvino/op/range.hpp"@@ -37,7 +40,10 @@#include "openvino/op/strided_slice.hpp"#include "openvino/op/transpose.hpp"#include "openvino/pass/constant_folding.hpp"+#include "openvino/pass/manager.hpp"#include "pass/lower_set_rows_stateless.hpp"+#include "pass/prune_orphaned_parameters.hpp"+#include "transformations/common_optimizations/fuse_gated_delta_net.hpp"#include "transformations/common_optimizations/nop_elimination.hpp"#include "transformations/fp16_compression/mark_decompression_convert_constant_folding.hpp"#include "transformations/op_conversions/convert_convertlike.hpp"@@ -52,20 +58,15 @@ using namespace ov::op;namespace {void add_sliced_mask(TensorMap& tensor_map) {- // Slice the full attention mask down to the current token window for the attention ops.- // For static (fixed-shape) models the slice bounds are constants, so this folds to a- // fixed-size slice -- there is no separate static pass-through branch.+ // Publish the decoder's runtime-sized attention mask under the shared name+ // consumed by the attention translators.auto create_sliced_mask = [&](const std::string& mask_name, const std::string& sliced_name) {- if ((tensor_map.find(mask_name) != tensor_map.end()) &&- (tensor_map.find("token_len_per_seq") != tensor_map.end())) {- auto token_len_per_seq = tensor_map.at("token_len_per_seq").get_node_shared_ptr();+ if (tensor_map.find(mask_name) != tensor_map.end()) {auto mask = tensor_map.at(mask_name).get_node_shared_ptr();- auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});- auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});- auto two = ov::op::v0::Constant::create(ov::element::i64, {1}, {2});+ // The decoder binds the mask with its current runtime shape, so its+ // token axis already is the active token window.std::shared_ptr<ov::Node> mask_sliced =- std::make_shared<ov::op::v8::Slice>(mask, zero, token_len_per_seq, one, two);- mask_sliced = std::make_shared<ov::op::v0::Convert>(mask_sliced, ov::element::f16);+ std::make_shared<ov::op::v0::Convert>(mask, ov::element::f16);mask_sliced->set_friendly_name(sliced_name);tensor_map.insert({sliced_name, mask_sliced->output(0)});}@@ -140,6 +141,10 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo// consumer at translate time; a pass that ends up not consuming one leaves it dangling, which// later constant folding removes.std::set<ov::Node*> deferred_use_params;+ // get_model_inputs() already folds in get_model_extra_inputs()'s entries (per the decoder.hpp+ // contract), so the same Parameter can show up in both loops below; skip re-adding it or it+ // ends up registered on the model twice, under two different indices.+ std::set<ov::Node*> seen_params;for (const auto& it : gguf_model_decoder->get_model_inputs()) {// Not every decoder splits auxiliary inputs into get_model_extra_inputs(): one that still@@ -148,13 +153,16 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo// Parameter into `params`.if (auto param = std::dynamic_pointer_cast<ov::op::v0::Parameter>(it.second)) {params.push_back(param);+ seen_params.insert(param.get());}(*tensor_map)[it.first] = it.second;}for (const auto& it : gguf_model_decoder->get_model_extra_inputs()) {if (auto p = std::dynamic_pointer_cast<ov::op::v0::Parameter>(it.second)) {- params.push_back(p);+ if (seen_params.insert(p.get()).second) {+ params.push_back(p);+ }deferred_use_params.insert(p.get());}(*tensor_map)[it.first] = it.second;@@ -234,8 +242,68 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo}resulting_model = std::make_shared<Model>(results, used_params);+ // M-RoPE models need 4 position sections per token, which changes the position_ids contract a+ // GenAI-facing consumer has to satisfy; record it so AdaptToGenAI can adapt (it runs on the+ // model alone and cannot ask the decoder).+ {+ const auto rc_any = gguf_model_decoder->get_attribute("rope_config");+ if (!rc_any.empty() && rc_any.as<RopeConfig>().is_imrope) {+ resulting_model->get_rt_info()[pass::gguf_imrope_key()] = true;+ }+ }++ // Sliding-window length, when the metadata carries one; AdaptToGenAI needs it to build a+ // correctly windowed self_kq_mask_swa instead of reusing the full causal mask (it runs on the+ // model alone and cannot ask the decoder).+ {+ const auto swa_any = gguf_model_decoder->get_attribute("swa_window_size");+ if (!swa_any.empty() && swa_any.as<int>() > 0) {+ resulting_model->get_rt_info()[pass::gguf_swa_window_key()] = static_cast<int64_t>(swa_any.as<int>());+ }+ }++ // Record the recurrent (overwritten, non-appending) states BEFORE transformations: a caller+ // that registered MakeStateful runs it inside apply_transformations, and unlike a KV cache+ // these carry nothing in the graph that identifies them (see gguf_recurrent_states_key).+ // Flattened to alternating {input, output} because rt_info takes an ov::Any.+ {+ const auto& rs = gguf_model_decoder->get_recurrent_states();+ if (!rs.empty()) {+ std::vector<std::string> flat;+ flat.reserve(rs.size() * 2);+ for (const auto& kv : rs) {+ flat.push_back(kv.first);+ flat.push_back(kv.second);+ }+ resulting_model->get_rt_info()[pass::gguf_recurrent_states_key()] = flat;+ }+ }+resulting_model = apply_transformations(resulting_model);+ // Auxiliary Parameters are kept through normalization in case a transformation extension+ // creates their only consumer; drop any still disconnected afterwards (a plugin requires+ // every declared model input to reach a node in the execution graph).+ std::set<ov::Node*> ordered_nodes;+ for (const auto& node : resulting_model->get_ordered_ops()) {+ ordered_nodes.insert(node.get());+ }+ const auto transformed_params = resulting_model->get_parameters();+ for (const auto& param : transformed_params) {+ if (ordered_nodes.count(param.get()) == 0) {+ resulting_model->remove_parameter(param);+ }+ }++ // Attach GGUF tokenizer metadata (the file's tokenizer.* keys) to the model's rt_info as a+ // non-serializable attribute, so a downstream consumer (OpenVINO GenAI) can build the+ // tokenizer without reopening the .gguf. Empty when the decoder carries no tokenizer config.+ const auto& tok_cfg = gguf_model_decoder->get_tokenizer_config();+ if (!tok_cfg.empty()) {+ resulting_model->get_rt_info()[gguf_tokenizer_metadata_key()] =+ std::make_shared<GGUFTokenizerMetadata>(tok_cfg);+ }+// Set WeightlessCacheAttribute on large constants to avoid unnecessary memory copies// in the NPUW plugin. Without this attribute, NPUW's LazyTensor constructor// (lazy_tensor.cpp, op::Const::Const) will memcpy every constant "in case export@@ -286,6 +354,22 @@ std::shared_ptr<Model> TranslateSession::apply_transformations(std::shared_ptr<M// StateManagementPattern, which admits no Convert between the KV-cache Concat and SDPA, and so// silently disables the PagedAttention backend for every GGUF model.manager.register_pass<ov::pass::EliminateConvert>();++ // Fuse a standalone Loop-based Gated Delta Net recurrence here (not in a plugin, which can't+ // remove a Parameter without violating its I/O port-count invariant), only for models with a+ // Loop: GatedDeltaNetFusion also bundles TransposeFuse, a generic cleanup that would otherwise+ // touch every architecture's op count.+ const auto ordered_ops = model->get_ordered_ops();+ const auto has_loop = std::any_of(ordered_ops.begin(), ordered_ops.end(), [](const std::shared_ptr<ov::Node>& node) {+ return ov::is_type<ov::op::v5::Loop>(node);+ });+ if (has_loop) {+ auto live_before_gdn = std::make_shared<std::unordered_set<const ov::Node*>>();+ manager.register_pass<pass::SnapshotLiveParameters>(live_before_gdn);+ manager.register_pass<ov::pass::GatedDeltaNetFusion>();+ manager.register_pass<pass::PruneParametersOrphanedSince>(live_before_gdn);+ }+manager.run_passes(model);return model;}diff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txtindex f02ad946907..ffd117c3312 100644--- a/src/frontends/gguf/tests/CMakeLists.txt+++ b/src/frontends/gguf/tests/CMakeLists.txt@@ -14,10 +14,26 @@ set(FRONTEND_SRCS"${FE_SRC_DIR}/translate_session.cpp""${FE_SRC_DIR}/utils.cpp""${FE_SRC_DIR}/helper_ops/set_rows_op.cpp"+ "${FE_SRC_DIR}/pass/adapt_to_genai.cpp""${FE_SRC_DIR}/pass/lower_set_rows_stateless.cpp""${FE_SRC_DIR}/pass/make_stateful.cpp"+ "${FE_SRC_DIR}/pass/prune_orphaned_parameters.cpp"+ "${FE_SRC_DIR}/tokenizer_metadata.cpp"+ "${FE_SRC_DIR}/quant/gguf.cpp""${FE_SRC_DIR}/quant/gguf_quants.cpp""${FE_SRC_DIR}/quant/weights.cpp"+ "${FE_SRC_DIR}/builder/gguf_builder.cpp"+ "${FE_SRC_DIR}/builder/gguf_builder_decoder.cpp"+ "${FE_SRC_DIR}/builder/graph_emitter.cpp"+ "${FE_SRC_DIR}/builder/arch_registry.cpp"+ "${FE_SRC_DIR}/builder/decoder_config.cpp"+ "${FE_SRC_DIR}/builder/model_kind.cpp"+ "${FE_SRC_DIR}/builder/arch/decoder_builder.cpp"+ "${FE_SRC_DIR}/builder/blocks/attention.cpp"+ "${FE_SRC_DIR}/builder/blocks/common.cpp"+ "${FE_SRC_DIR}/builder/blocks/ffn.cpp"+ "${FE_SRC_DIR}/builder/blocks/gated_delta_net.cpp"+ "${FE_SRC_DIR}/builder/blocks/qkv_repack.cpp""${FE_SRC_DIR}/op/add_id.cpp""${FE_SRC_DIR}/op/argsort.cpp""${FE_SRC_DIR}/op/clamp.cpp"@@ -62,6 +78,7 @@ set(FRONTEND_SRCS)set(TEST_SRCS+ "${CMAKE_CURRENT_SOURCE_DIR}/test_arch_conversion.cpp""${CMAKE_CURRENT_SOURCE_DIR}/test_dequant_vs_ggml.cpp""${CMAKE_CURRENT_SOURCE_DIR}/test_extensions.cpp""${CMAKE_CURRENT_SOURCE_DIR}/test_op_coverage.cpp"@@ -95,7 +112,14 @@ ov_add_test_target()# Install the reference data next to the test binary (found via getExecutableDirectory()):-# *.npy op/dequant references.+# *.npy op/dequant references, plus the per-architecture fixture manifest.+#+# The manifest's companion *.gguf.hdr fixtures are deliberately NOT here: they are generated from+# llama.cpp by tests/gen_arch_fixtures.py into this same directory (see the "Generate GGUF arch+# fixtures" step in .github/workflows/job_build_linux.yml). The manifest itself IS installed --+# it carries the reviewed per-architecture expectation for each fixture, which is source, not+# generated output. Where no fixtures were generated the arch suite skips itself; see+# test_arch_conversion.cpp.install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/test_data"DESTINATION testsCOMPONENT testsdiff --git a/src/frontends/gguf/tests/gen_arch_fixtures.py b/src/frontends/gguf/tests/gen_arch_fixtures.pynew file mode 100644index 00000000000..0150810b759--- /dev/null+++ b/src/frontends/gguf/tests/gen_arch_fixtures.py@@ -0,0 +1,241 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++"""Produce the per-architecture GGUF conversion fixtures consumed by test_arch_conversion.cpp.++A fixture is a GGUF *header*: everything before min(tensor.data_offset), i.e. the magic, the KV+metadata and the tensor table. That is the entire input to architecture detection and graph+construction -- the weight bytes that follow contribute nothing to the shape of the converted model,+so the C++ test rebuilds a loadable .gguf by appending the recorded number of zero bytes. Headers+are ~25 KB each; the full models they come from are 559 MB.++The upstream source of the models is llama.cpp's `test-llama-archs`, which walks every architecture+it knows and saves a tiny random model for each. This script wraps it end to end:++ # from a checkout you already have (nothing is cloned):+ python3 gen_arch_fixtures.py --llama-src <llama.cpp>++ # or let it fetch the pinned commit itself (this is what CI does):+ python3 gen_arch_fixtures.py --fetch --out-dir <dir>++llama.cpp is pinned to LLAMA_CPP_COMMIT below and stays there until a fixture refresh is+deliberately made. The pin is load-bearing, not hygiene: `test-llama-archs` writes whatever KVs+llama.cpp currently defines, so upstream adding one shifts the bytes of *every* fixture at once+(measured: between 86a9c79f8 and a head 13 days later, all 101 headers changed because three+`attention.indexer.*` KVs were added, and two new architectures appeared). Tracking a moving+upstream would therefore turn an unrelated llama.cpp commit into a red OpenVINO precommit. Bump the+pin as its own reviewed change, and say so in the commit message so the provenance stays traceable.++The headers are seed-independent -- verified byte-identical for `-s 1` and `-s 999` -- because the+seed only feeds weight values. Pinning one anyway (below) costs nothing and keeps the run+deterministic.++Requires the `gguf` Python package (llama.cpp's gguf-py) to read back the generated files.+"""++import argparse+import glob+import os+import shutil+import subprocess+import sys+import tempfile++# Pinned llama.cpp revision. MUST be a commit on ggml-org/llama.cpp master: --fetch clones from+# there, so a SHA that only exists in a fork makes CI fail with "couldn't find remote ref".+LLAMA_CPP_COMMIT = "86a9c79f866799eb0e7e89c03578ccfbcc5d808e"+LLAMA_CPP_REPO = "https://github.com/ggml-org/llama.cpp.git"+# The generator's own default seed is std::random_device, i.e. non-reproducible. Pin it: it does not+# affect the header bytes, but it keeps the whole run deterministic.+SEED = 1++HERE = os.path.dirname(os.path.abspath(__file__))+FIXTURE_DIR = os.path.join(HERE, "test_data", "arch_fixtures")++MANIFEST_HEADER = """\+# GGUF per-architecture conversion fixtures -- see gen_arch_fixtures.py (generator) and+# test_arch_conversion.cpp (consumer). Generated from llama.cpp {commit} at seed {seed}.+#+# One line per fixture:+# <file> <data_bytes> <expectation>+#+# <file> header-only fixture in this directory; the loadable .gguf is <file> followed by+# <data_bytes> zero bytes (all fixture tensors are F32, so no dequant is involved).+# <expectation> what conversion must do, and the test asserts exactly this:+# convert converts cleanly. The graph fingerprint is pinned in test_arch_conversion.cpp.+# reject the architecture is not on the builder's accept list, so conversion must fail with+# that specific diagnostic -- not a crash, and not a silent wrong-graph success.+# broken a supported architecture that currently fails to convert: a real defect, recorded so+# it cannot be forgotten. The test asserts it STILL FAILS; fixing the defect turns this+# line into a failure telling you to promote it to `convert`.+"""+++def run(cmd, **kwargs):+ """Run a command, echoing it first so a CI log shows exactly what happened."""+ print("+ " + " ".join(cmd), flush=True)+ subprocess.run(cmd, check=True, **kwargs)+++def fetch_llama_cpp(dest):+ """Shallow-fetch the pinned commit into dest. ~35 MB, a few seconds.++ A bare `clone --depth 1` cannot take a SHA, and a full clone of llama.cpp is large and slow, so+ fetch the one commit explicitly: init + fetch --depth 1 <sha>. This requires the SHA to be+ reachable on the remote, which is why LLAMA_CPP_COMMIT must be an upstream commit.+ """+ os.makedirs(dest, exist_ok=True)+ run(["git", "init", "-q", dest])+ run(["git", "-C", dest, "remote", "add", "origin", LLAMA_CPP_REPO])+ run(["git", "-C", dest, "fetch", "-q", "--depth", "1", "origin", LLAMA_CPP_COMMIT])+ run(["git", "-C", dest, "checkout", "-q", "FETCH_HEAD"])+ return dest+++def build_generator(src, build_dir, jobs):+ """Configure and build only the test-llama-archs target.++ LLAMA_BUILD_TESTS=ON is required -- the target is a test, and upstream's own release builds turn+ tests off, which is why no prebuilt llama.cpp package ships it. Everything else is off: the+ examples, tools and server are not needed to save a model.+ """+ run([+ "cmake", "-S", src, "-B", build_dir,+ "-DCMAKE_BUILD_TYPE=Release",+ "-DLLAMA_BUILD_TESTS=ON",+ "-DLLAMA_BUILD_EXAMPLES=OFF",+ "-DLLAMA_BUILD_TOOLS=OFF",+ "-DLLAMA_BUILD_SERVER=OFF",+ ])+ cmd = ["cmake", "--build", build_dir, "--target", "test-llama-archs"]+ if jobs:+ cmd += ["-j", str(jobs)]+ run(cmd)+ exe = os.path.join(build_dir, "bin", "test-llama-archs")+ if not os.path.isfile(exe):+ sys.exit(f"error: build succeeded but {exe} is missing")+ return exe+++def run_generator(exe, out_dir):+ run([exe, "-s", str(SEED), "-o", out_dir], stdout=subprocess.DEVNULL)+ files = sorted(glob.glob(os.path.join(out_dir, "*.gguf")))+ if not files:+ sys.exit("error: generator produced no .gguf files")+ return files+++def strip_to_header(path, out_path):+ """Write everything before the first tensor's data offset; return (header_len, data_len, arch)."""+ import gguf++ reader = gguf.GGUFReader(path)+ if not reader.tensors:+ return None+ header_len = min(t.data_offset for t in reader.tensors)+ total = os.path.getsize(path)+ with open(path, "rb") as src, open(out_path, "wb") as dst:+ dst.write(src.read(header_len))+ arch_field = reader.fields["general.architecture"]+ arch = str(bytes(arch_field.parts[-1]), "utf-8")+ return header_len, total - header_len, arch+++def read_expectations(manifest):+ """Existing <file> -> <expectation> mapping, or {} if there is no manifest yet."""+ previous = {}+ if not os.path.exists(manifest):+ return previous+ with open(manifest) as f:+ for line in f:+ line = line.strip()+ if not line or line.startswith("#"):+ continue+ parts = line.split()+ if len(parts) >= 3:+ previous[parts[0]] = parts[2]+ return previous+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ src = ap.add_mutually_exclusive_group(required=True)+ src.add_argument("--llama-src", help="existing llama.cpp checkout to build from")+ src.add_argument("--fetch", action="store_true",+ help=f"shallow-fetch the pinned commit ({LLAMA_CPP_COMMIT[:12]}) into a temp dir")+ ap.add_argument("--out-dir", default=FIXTURE_DIR,+ help="where to write the .gguf.hdr fixtures and manifest.txt (default: the "+ "in-tree test_data/arch_fixtures)")+ ap.add_argument("--llama-build", help="reuse this build directory instead of a temp one")+ ap.add_argument("-j", "--jobs", type=int, default=os.cpu_count(), help="parallel build jobs")+ ap.add_argument("--keep", action="store_true", help="keep the full generated .gguf files")+ args = ap.parse_args()++ work = tempfile.mkdtemp(prefix="gguf_arch_fixtures_")+ try:+ src_dir = args.llama_src+ if args.fetch:+ src_dir = fetch_llama_cpp(os.path.join(work, "llama.cpp"))+ else:+ # An arbitrary checkout may sit at any revision, and the fixture bytes depend on it.+ # Report what we actually built so a mismatch with the pin is visible in the log.+ rev = subprocess.run(["git", "-C", src_dir, "rev-parse", "HEAD"],+ capture_output=True, text=True).stdout.strip()+ if rev and rev != LLAMA_CPP_COMMIT:+ print(f"warning: {src_dir} is at {rev[:12]}, not the pinned {LLAMA_CPP_COMMIT[:12]}; "+ f"the fixtures will differ from the committed ones", flush=True)++ exe = build_generator(src_dir, args.llama_build or os.path.join(work, "build"), args.jobs)++ models = os.path.join(work, "models")+ os.makedirs(models, exist_ok=True)+ files = run_generator(exe, models)+ print(f"generated {len(files)} models in {models}")++ out_dir = os.path.abspath(args.out_dir)+ os.makedirs(out_dir, exist_ok=True)+ manifest = os.path.join(out_dir, "manifest.txt")+ # Preserve reviewed expectations before the stale fixtures are removed.+ previous = read_expectations(manifest)+ for stale in glob.glob(os.path.join(out_dir, "*.gguf.hdr")):+ os.remove(stale)++ entries = []+ for path in files:+ name = os.path.basename(path) + ".hdr"+ result = strip_to_header(path, os.path.join(out_dir, name))+ if result is None:+ print(f" skip {os.path.basename(path)}: no tensors")+ continue+ header_len, data_len, arch = result+ entries.append((name, data_len, arch))+ print(f" {name}: header {header_len} B, data {data_len} B, arch {arch}")++ # Expectations are NOT inferred from the frontend here -- that would make the fixtures assert+ # whatever the frontend currently does, which is not a test. Preserve the reviewed+ # expectation from the existing manifest and default new fixtures to `reject`, which is+ # correct for any architecture the builder's accept list does not name. A new architecture+ # that should convert is then a deliberate, reviewable one-word manifest edit.+ with open(manifest, "w") as f:+ f.write(MANIFEST_HEADER.format(commit=LLAMA_CPP_COMMIT, seed=SEED))+ for name, data_len, _arch in sorted(entries):+ expectation = previous.get(name, "reject")+ if name not in previous:+ print(f" NEW fixture {name}: defaulted to `reject`; review it")+ f.write(f"{name} {data_len} {expectation}\n")++ total = sum(os.path.getsize(os.path.join(out_dir, n)) for n, _, _ in entries)+ print(f"\nwrote {len(entries)} headers ({total / 1024:.1f} KB raw) + manifest to {out_dir}")++ dropped = set(previous) - {n for n, _, _ in entries}+ if dropped:+ print(f"note: {len(dropped)} fixture(s) disappeared upstream and were dropped: {sorted(dropped)}")+ finally:+ if args.keep:+ print(f"work directory kept: {work}")+ else:+ shutil.rmtree(work, ignore_errors=True)+++if __name__ == "__main__":+ main()diff --git a/src/frontends/gguf/tests/graph_fingerprint.py b/src/frontends/gguf/tests/graph_fingerprint.pynew file mode 100644index 00000000000..0811b665fa9--- /dev/null+++ b/src/frontends/gguf/tests/graph_fingerprint.py@@ -0,0 +1,61 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+#+# Graph-fingerprint regression tool for the GGUF frontend's native builder.+#+# The fingerprint is a sha256 over the sorted (op_type, output_partial_shape) pairs of every op in+# the converted ov::Model, plus the sorted model input names. It is a cheap, exact regression gate:+# any builder change that alters the produced graph for a given model changes its fingerprint, and+# any change that is meant to be graph-neutral (refactor, robustness, renaming) must leave every+# fingerprint unchanged.+#+# Usage (baseline / manual):+# PYTHONPATH=<ov>/bin/intel64/Release/python LD_LIBRARY_PATH=<ov>/bin/intel64/Release \+# python3 graph_fingerprint.py model_a.gguf model_b.gguf ...+#+# It prints "<name> <sighash>" per model. Save the output as the baseline; after a change, re-run+# and diff. The pytest wrapper (test_graph_fingerprint.py) automates this against a JSON baseline+# and is gated on GGUF_FINGERPRINT_MODELS being set (so CI skips when no local models are present).++import hashlib+import sys++import openvino as ov+from openvino.frontend import FrontEndManager+++def convert_gguf(model_path: str):+ """Convert a .gguf through the GGUF frontend.++ The frontend is not auto-selectable (see is_hidden_frontend in+ src/frontends/common/src/manager.cpp), so core.read_model(".gguf") does not reach it and it+ has to be requested by name.+ """+ fe = FrontEndManager().load_by_framework("gguf")+ return fe.convert(fe.load(model_path))+++def fingerprint(model_path: str) -> dict:+ m = convert_gguf(model_path)+ sig = []+ for op in m.get_ops():+ shape = str(op.get_output_partial_shape(0)) if op.get_output_size() > 0 else ""+ sig.append(op.get_type_name() + "|" + shape)+ inputs = sorted(list(i.get_names())[0] if i.get_names() else "?" for i in m.inputs)+ outputs = sorted(list(o.get_names())[0] if o.get_names() else "?" for o in m.outputs)+ h = hashlib.sha256("\n".join(sorted(sig)).encode()).hexdigest()[:16]+ return {"sighash": h, "num_ops": len(m.get_ops()), "inputs": inputs, "outputs": outputs}+++def main(argv):+ if len(argv) < 2:+ print("usage: graph_fingerprint.py <model.gguf> [<model.gguf> ...]", file=sys.stderr)+ return 2+ for path in argv[1:]:+ fp = fingerprint(path)+ print(f"{path}\t{fp['sighash']}\tops={fp['num_ops']}\tinputs={fp['inputs']}")+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv))diff --git a/src/frontends/gguf/tests/test_arch_conversion.cpp b/src/frontends/gguf/tests/test_arch_conversion.cppnew file mode 100644index 00000000000..8adcaa2b657--- /dev/null+++ b/src/frontends/gguf/tests/test_arch_conversion.cpp@@ -0,0 +1,349 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Per-architecture conversion tests for the native .gguf builder path (FrontEnd::load(path) ->+// build_ggml_graph_from_gguf -> GgufBuilderDecoder -> convert).+//+// The single-op tests in test_ops.cpp cover translators in isolation; nothing there exercises+// architecture detection, the GGUF metadata reader, or the builder's whole-graph assembly. This+// file does, over every architecture llama.cpp can emit a model for -- 101 fixtures -- and asserts a+// definite outcome for each:+//+// convert the graph builds, and its fingerprint (op count / input count) matches the pinned+// value, so a refactor that quietly restructures a supported architecture is caught.+// reject the architecture is not on the builder's accept list, so conversion must fail with+// that specific diagnostic. This turns "unsupported" from a claim in a doc into a+// machine-checked fact, and distinguishes a clean rejection from a crash or -- worse --+// a silent success producing a wrong graph.+// broken a supported architecture that currently does NOT convert. The test asserts it still+// fails, so the defect is recorded rather than forgotten, and FIXING it makes this test+// fail with an instruction to promote the fixture to `convert`. An xfail that silently+// passes is how a known-broken list rots into a permanent excuse list.+//+// == Fixtures ==+// test_data/arch_fixtures/*.gguf.hdr are GGUF *headers* only: the bytes before the first tensor's+// data offset, i.e. magic + KV metadata + tensor table. That is the whole input to architecture+// detection and graph construction; the weight bytes after it do not affect the converted graph's+// structure. Each is turned back into a loadable .gguf here by appending the manifest's recorded+// number of zero bytes. Full models would be 559 MB; the headers are ~25 KB each.+//+// The headers are GENERATED, not committed: tests/gen_arch_fixtures.py builds llama.cpp's+// test-llama-archs at a pinned commit and strips its output. CI does this in the Linux build job+// (.github/workflows/job_build_linux.yml) and ships the result in the tests artifact. The+// manifest, by contrast, IS committed -- it carries the reviewed expectation per architecture.+//+// So on a platform where the generator did not run, the manifest is present but its fixtures are+// not. That is a legitimate configuration and the suite skips itself (see present_fixture_count());+// a manifest entry missing its file while OTHER fixtures exist is a broken generation and fails.+// Running the generator locally into test_data/arch_fixtures makes the suite live in-tree too.++#include <algorithm>+#include <cctype>+#include <cstdint>+#include <filesystem>+#include <fstream>+#include <map>+#include <sstream>+#include <string>+#include <vector>++#include "common_test_utils/common_utils.hpp"+#include "common_test_utils/file_utils.hpp"+#include "gtest/gtest.h"+#include "op_test_utils.hpp"+#include "openvino/frontend/gguf/frontend.hpp"+#include "openvino/util/file_util.hpp"++using namespace ov_gguf_test;++namespace {++enum class Expectation { Convert, Reject, Broken };++struct ArchFixture {+ std::string header_file; // e.g. "llama-dense.gguf.hdr"+ size_t data_bytes = 0; // zero bytes to append to rebuild a loadable .gguf+ Expectation expectation = Expectation::Reject;+};++std::string fixture_dir() {+ return ov::util::path_join({test_data_dir(), "arch_fixtures"}).string();+}++// Parse test_data/arch_fixtures/manifest.txt: "<file> <data_bytes> <expectation>", '#' comments.+std::vector<ArchFixture> read_manifest() {+ const std::string path = ov::util::path_join({fixture_dir(), "manifest.txt"}).string();+ std::ifstream in(path);+ if (!in) {+ // Returning empty would silently reduce this file to zero tests, so make it loud. The+ // suite below turns this into a failure via ManifestIsPresentAndComplete.+ return {};+ }+ std::vector<ArchFixture> fixtures;+ std::string line;+ while (std::getline(in, line)) {+ if (line.empty() || line[0] == '#') {+ continue;+ }+ std::istringstream ls(line);+ ArchFixture f;+ std::string expectation;+ if (!(ls >> f.header_file >> f.data_bytes >> expectation)) {+ continue;+ }+ if (expectation == "convert") {+ f.expectation = Expectation::Convert;+ } else if (expectation == "reject") {+ f.expectation = Expectation::Reject;+ } else if (expectation == "broken") {+ f.expectation = Expectation::Broken;+ } else {+ continue; // unknown keyword; ManifestIsPresentAndComplete catches the resulting gap+ }+ fixtures.push_back(f);+ }+ return fixtures;+}++// Whether the generated *.gguf.hdr fixtures are present at all.+//+// Counted rather than checked as a boolean so a PARTIAL generation is distinguishable from no+// generation: none present means the generator did not run on this platform (skip), some present+// means it ran and produced an incomplete set (a failure, asserted in ManifestIsPresentAndComplete).+size_t count_present_fixtures(const std::vector<ArchFixture>& fixtures) {+ size_t present = 0;+ for (const auto& f : fixtures) {+ if (ov::util::file_exists(ov::util::path_join({fixture_dir(), f.header_file}).string())) {+ ++present;+ }+ }+ return present;+}++// Cached: every parameterized test consults this, and there are ~101 of them.+size_t present_fixture_count() {+ static const size_t count = count_present_fixtures(read_manifest());+ return count;+}++// Reconstruct a loadable .gguf from a header fixture: header bytes followed by data_bytes zeros.+//+// Zero-filling is exact for these fixtures, not an approximation: every tensor llama.cpp's model+// saver writes here is F32, so no dequantization is involved and no block-scale field can be made+// invalid by a zero. The values themselves are irrelevant -- this test asserts graph structure, and+// the converted graph is built from the metadata and tensor table alone.+std::string materialize(const ArchFixture& fixture, const std::string& dir) {+ const std::string src = ov::util::path_join({fixture_dir(), fixture.header_file}).string();+ std::ifstream in(src, std::ios::binary);+ if (!in) {+ return {};+ }+ std::vector<char> header((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());++ // Drop the ".hdr" suffix so the path ends in .gguf, which the frontend requires.+ std::string name = fixture.header_file;+ const std::string suffix = ".hdr";+ if (name.size() > suffix.size() && name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0) {+ name.resize(name.size() - suffix.size());+ }+ const std::string dst = ov::util::path_join({dir, name}).string();++ std::ofstream out(dst, std::ios::binary);+ if (!out) {+ return {};+ }+ out.write(header.data(), static_cast<std::streamsize>(header.size()));+ // Chunked zero-fill: a fixture's data section can be tens of MB.+ const std::vector<char> zeros(64 * 1024, 0);+ size_t remaining = fixture.data_bytes;+ while (remaining > 0) {+ const size_t chunk = std::min(remaining, zeros.size());+ out.write(zeros.data(), static_cast<std::streamsize>(chunk));+ remaining -= chunk;+ }+ out.close();+ return out ? dst : std::string{};+}++// Graph fingerprints for the fixtures expected to convert: {op count, input count}.+//+// Pinned so that a refactor which restructures a supported architecture's graph has to be an+// explicit, reviewed change to these numbers rather than an invisible one. They are a structural+// signature, not a correctness claim -- numerical accuracy per architecture is a separate tier that+// needs real checkpoints (docs/testing_architecture.md).+struct Fingerprint {+ size_t ops;+ size_t inputs;+};++const std::map<std::string, Fingerprint>& fingerprints() {+ static const std::map<std::string, Fingerprint> fp{+ {"bailingmoe2-moe.gguf.hdr", {457, 10}}, {"ernie4_5-moe-moe.gguf.hdr", {431, 10}},+ {"exaone4-dense.gguf.hdr", {402, 11}}, {"gemma-dense.gguf.hdr", {349, 10}},+ {"gemma2-dense.gguf.hdr", {399, 11}}, {"glm4moe-moe.gguf.hdr", {469, 10}},+ {"gpt-oss-moe.gguf.hdr", {558, 11}}, {"hunyuan-dense-dense.gguf.hdr", {400, 10}},+ {"hunyuan-moe-moe.gguf.hdr", {518, 10}}, {"llama-dense.gguf.hdr", {384, 10}},+ {"llama-moe.gguf.hdr", {490, 10}}, {"maincoder-dense.gguf.hdr", {416, 10}},+ {"minicpm-dense.gguf.hdr", {382, 10}}, {"minicpm-moe.gguf.hdr", {488, 10}},+ {"minimax-m2-moe.gguf.hdr", {518, 10}}, {"mistral3-dense.gguf.hdr", {384, 10}},+ {"mistral3-moe.gguf.hdr", {490, 10}}, {"olmoe-moe.gguf.hdr", {518, 10}},+ {"phi3-dense.gguf.hdr", {364, 10}}, {"qwen2-dense.gguf.hdr", {352, 10}},+ {"qwen3-dense.gguf.hdr", {400, 10}}, {"qwen3moe-moe.gguf.hdr", {534, 10}},+ {"qwen35-dense.gguf.hdr", {387, 10}}, {"smollm3-dense.gguf.hdr", {368, 10}},+ };+ return fp;+}++// A scratch directory that outlives one test, so the reconstructed .gguf can be written once per+// test and removed afterwards without leaving multi-MB files behind on failure.+class ScratchDir {+public:+ ScratchDir() : m_path(ov::test::utils::generateTestFilePrefix() + "_gguf_arch") {+ ov::util::create_directory_recursive(std::filesystem::path(m_path));+ }+ ~ScratchDir() {+ ov::test::utils::removeDir(m_path);+ }+ const std::string& path() const {+ return m_path;+ }++private:+ std::string m_path;+};++class GGUFArchConversion : public ::testing::TestWithParam<ArchFixture> {};++TEST_P(GGUFArchConversion, MatchesManifestExpectation) {+ const ArchFixture fixture = GetParam();+ if (present_fixture_count() == 0) {+ GTEST_SKIP() << "no arch fixtures in " << fixture_dir()+ << " -- generate them with tests/gen_arch_fixtures.py --fetch";+ }+ ScratchDir scratch;+ const std::string model_path = materialize(fixture, scratch.path());+ ASSERT_FALSE(model_path.empty()) << "could not materialize fixture " << fixture.header_file;++ ov::frontend::gguf::FrontEnd fe;+ std::shared_ptr<ov::Model> model;+ std::string error;+ try {+ model = fe.convert(fe.load(model_path));+ } catch (const std::exception& e) {+ error = e.what();+ }+ ov::test::utils::removeFile(model_path);++ switch (fixture.expectation) {+ case Expectation::Convert: {+ ASSERT_TRUE(model) << "expected " << fixture.header_file << " to convert, but it failed:\n" << error;+ const auto it = fingerprints().find(fixture.header_file);+ ASSERT_NE(it, fingerprints().end())+ << fixture.header_file << " is marked `convert` in the manifest but has no fingerprint entry in "+ << "test_arch_conversion.cpp; add one.";+ EXPECT_EQ(model->get_ops().size(), it->second.ops)+ << "graph op count for " << fixture.header_file << " changed. If the new structure is intended, "+ << "update fingerprints() -- and say why in the commit message.";+ EXPECT_EQ(model->inputs().size(), it->second.inputs)+ << "graph input count for " << fixture.header_file << " changed; see fingerprints().";+ break;+ }+ case Expectation::Reject: {+ // The accept list must be what rejects it: a different failure means the file broke the+ // reader or the builder somewhere it should never have reached.+ ASSERT_FALSE(model) << fixture.header_file << " is marked `reject` but converted successfully. If the "+ << "builder now supports this architecture, add it to verified/experimental_archs() "+ << "and change the manifest line to `convert` with a fingerprint.";+ EXPECT_NE(error.find("native GGUF builder does not support architecture"), std::string::npos)+ << fixture.header_file << " failed for a reason other than the architecture accept list, which means "+ << "it got further into the builder than it should. Actual error:\n"+ << error;+ break;+ }+ case Expectation::Broken: {+ // XPASS is a failure on purpose: a `broken` entry that starts converting must be promoted,+ // not left to accumulate as a permanent excuse.+ ASSERT_FALSE(model) << fixture.header_file << " is marked `broken` but now converts. The defect is fixed: "+ << "change its manifest line to `convert` and add its fingerprint to fingerprints().";+ // Not an accept-list rejection -- that is what makes it a defect rather than an unsupported+ // architecture.+ EXPECT_EQ(error.find("native GGUF builder does not support architecture"), std::string::npos)+ << fixture.header_file << " is marked `broken` but is actually rejected by the accept list; it should "+ << "be `reject`.";+ break;+ }+ }+}++std::string fixture_test_name(const ::testing::TestParamInfo<ArchFixture>& info) {+ // "llama-dense.gguf.hdr" -> "llama_dense"; gtest names allow only [A-Za-z0-9_].+ std::string name = info.param.header_file;+ const auto dot = name.find(".gguf");+ if (dot != std::string::npos) {+ name.resize(dot);+ }+ for (auto& c : name) {+ if (!std::isalnum(static_cast<unsigned char>(c))) {+ c = '_';+ }+ }+ return name;+}++INSTANTIATE_TEST_SUITE_P(GGUFArchs, GGUFArchConversion, ::testing::ValuesIn(read_manifest()), fixture_test_name);++// The manifest is read at static-init time to instantiate the suite above, so a missing or truncated+// manifest would quietly produce zero tests instead of a failure. Assert its shape explicitly.+TEST(GGUFArchConversionManifest, IsPresentAndComplete) {+ const auto fixtures = read_manifest();+ ASSERT_FALSE(fixtures.empty()) << "no fixtures parsed from " << fixture_dir()+ << "/manifest.txt -- is the test_data directory installed?";+ // Guards against a manifest that parses but lost most of its lines.+ EXPECT_GE(fixtures.size(), 90u) << "manifest has far fewer fixtures than the ~101 architectures llama.cpp "+ << "emits; regenerate with gen_arch_fixtures.py";++ // Fixture files are generated, so "none present" is a valid platform configuration and only+ // means the suite above skips. "Some present" is not: it means the generator ran and produced+ // an incomplete set, which would silently shrink coverage to whatever happened to be written.+ const size_t present = present_fixture_count();+ if (present != 0) {+ for (const auto& f : fixtures) {+ const std::string path = ov::util::path_join({fixture_dir(), f.header_file}).string();+ EXPECT_TRUE(ov::util::file_exists(path))+ << "manifest lists " << f.header_file << " but the file is missing, while " << present << " of "+ << fixtures.size() << " fixtures are present -- fixture generation was incomplete. Re-run "+ << "tests/gen_arch_fixtures.py (CI: the 'Generate GGUF arch fixtures' build step).";+ }+ } else {+ GTEST_LOG_(INFO) << "no fixture files in " << fixture_dir()+ << "; the GGUFArchs suite is skipped on this platform";+ }++ // Manifest/fingerprint consistency is checked whether or not the fixtures were generated: both+ // are committed source, so a mismatch is a bug on every platform.+ size_t convertible = 0;+ for (const auto& f : fixtures) {+ if (f.expectation == Expectation::Convert) {+ ++convertible;+ EXPECT_NE(fingerprints().count(f.header_file), 0u)+ << f.header_file << " is `convert` but has no fingerprint entry";+ }+ }+ EXPECT_GT(convertible, 0u) << "no fixture is expected to convert, which would make this suite vacuous";++ // Every fingerprint must correspond to a live manifest entry, so stale entries cannot linger+ // after a fixture is dropped upstream.+ for (const auto& entry : fingerprints()) {+ bool found = false;+ for (const auto& f : fixtures) {+ if (f.header_file == entry.first && f.expectation == Expectation::Convert) {+ found = true;+ break;+ }+ }+ EXPECT_TRUE(found) << "fingerprints() has a stale entry for " << entry.first+ << " (no matching `convert` line in the manifest)";+ }+}++} // namespacediff --git a/src/frontends/gguf/tests/test_data/arch_fixtures/.gitignore b/src/frontends/gguf/tests/test_data/arch_fixtures/.gitignorenew file mode 100644index 00000000000..0810a353096--- /dev/null+++ b/src/frontends/gguf/tests/test_data/arch_fixtures/.gitignore@@ -0,0 +1,4 @@+# The *.gguf.hdr fixtures are generated by ../../gen_arch_fixtures.py, not committed -- see the+# manifest header and test_arch_conversion.cpp. Running the generator in-tree is the supported way+# to make the arch suite live locally, so keep its output out of `git status`.+*.gguf.hdrdiff --git a/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt b/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txtnew file mode 100644index 00000000000..7ba44736506--- /dev/null+++ b/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt@@ -0,0 +1,116 @@+# GGUF per-architecture conversion fixtures -- see gen_arch_fixtures.py (generator, run offline) and+# test_arch_conversion.cpp (consumer). Generated from llama.cpp 476c01efe88aad7880a8132d5d3a415f2ca75139 at seed 1.+#+# One line per fixture:+# <file> <data_bytes> <expectation>+#+# <file> header-only fixture in this directory; the loadable .gguf is <file> followed by+# <data_bytes> zero bytes (all fixture tensors are F32, so no dequant is involved).+# <expectation> what conversion must do, and the test asserts exactly this:+# convert converts cleanly. The graph fingerprint is pinned in test_arch_conversion.cpp.+# reject the architecture is not on the builder's accept list, so conversion must fail with+# that specific diagnostic -- not a crash, and not a silent wrong-graph success.+# broken a supported architecture that currently fails to convert: a real defect, recorded so+# it cannot be forgotten. The test asserts it STILL FAILS; fixing the defect turns this+# line into a failure telling you to promote it to `convert`.+arcee-dense.gguf.hdr 3944448 reject+arctic-moe.gguf.hdr 8669440 reject+baichuan-dense.gguf.hdr 4730752 reject+bailingmoe-moe.gguf.hdr 9453824 reject+bailingmoe2-moe.gguf.hdr 7087968 convert+bloom-dense.gguf.hdr 3958272 reject+chatglm-dense.gguf.hdr 4730624 reject+codeshell-dense.gguf.hdr 3956480 reject+cogvlm-dense.gguf.hdr 9181056 reject+command-r-dense.gguf.hdr 4597632 reject+dbrx-moe.gguf.hdr 7087744 reject+deci-dense.gguf.hdr 4741248 reject+deepseek-moe.gguf.hdr 7092288 reject+deepseek2-moe.gguf.hdr 4403296 reject+deepseek32-moe.gguf.hdr 4733152 reject+dots1-moe.gguf.hdr 7094368 reject+dream-dense.gguf.hdr 4731264 reject+ernie4_5-moe-moe.gguf.hdr 5914528 convert+ernie4_5-moe.gguf.hdr 4732800 reject+exaone-dense.gguf.hdr 4731008 reject+exaone4-dense.gguf.hdr 4733056 convert+falcon-dense.gguf.hdr 3942912 reject+falcon-h1-dense.gguf.hdr 8985152 reject+gemma-dense.gguf.hdr 4599680 convert+gemma2-dense.gguf.hdr 4603776 convert+glm-dsa-moe.gguf.hdr 4733152 reject+glm4-dense.gguf.hdr 4734720 reject+glm4moe-moe.gguf.hdr 7094368 convert+gpt-oss-moe.gguf.hdr 7112704 convert+gpt2-dense.gguf.hdr 4087296 reject+gptneox-dense.gguf.hdr 3956224 reject+granite-dense.gguf.hdr 4741248 reject+granite-moe.gguf.hdr 7096448 reject+granitehybrid-dense.gguf.hdr 5810272 reject+granitemoe-dense.gguf.hdr 4741248 reject+granitemoe-moe.gguf.hdr 7096448 reject+grok-moe.gguf.hdr 9457920 reject+grovemoe-moe.gguf.hdr 8669056 reject+hunyuan-dense-dense.gguf.hdr 4732800 convert+hunyuan-moe-moe.gguf.hdr 9455872 convert+hunyuan_vl-dense.gguf.hdr 4732800 reject+hy_v3-moe.gguf.hdr 11815360 reject+internlm2-dense.gguf.hdr 4730752 reject+jais-dense.gguf.hdr 4745856 reject+jais2-dense.gguf.hdr 3956480 broken+jamba-dense.gguf.hdr 6061856 reject+kimi-linear-moe.gguf.hdr 2833984 reject+lfm2-dense.gguf.hdr 4731520 reject+lfm2moe-moe.gguf.hdr 5913248 reject+llada-dense.gguf.hdr 4735104 reject+llada-moe-moe.gguf.hdr 7096192 reject+llama-dense.gguf.hdr 4741248 convert+llama-moe.gguf.hdr 7096448 convert+llama4-moe.gguf.hdr 13921664 reject+maincoder-dense.gguf.hdr 4732800 convert+mamba-dense.gguf.hdr 5029120 reject+mamba2-dense.gguf.hdr 4509120 reject+minicpm-dense.gguf.hdr 4741248 convert+minicpm-moe.gguf.hdr 7096448 convert+minicpm3-dense.gguf.hdr 7616512 reject+minimax-m2-moe.gguf.hdr 7098304 convert+mistral3-dense.gguf.hdr 4741248 convert+mistral3-moe.gguf.hdr 7096448 convert+mistral4-moe.gguf.hdr 4403296 reject+mpt-dense.gguf.hdr 4094464 reject+nemotron-dense.gguf.hdr 3956480 reject+nemotron_h-dense.gguf.hdr 4230240 reject+nemotron_h_moe-dense.gguf.hdr 4230240 reject+olmo-dense.gguf.hdr 4725632 reject+olmoe-moe.gguf.hdr 7098240 convert+openelm-dense.gguf.hdr 4595328 reject+orion-dense.gguf.hdr 4735872 reject+paddleocr-moe.gguf.hdr 4732800 reject+pangu-embedded-dense.gguf.hdr 4733056 reject+phi2-dense.gguf.hdr 3952896 reject+phi3-dense.gguf.hdr 4731136 convert+phimoe-moe.gguf.hdr 7102336 reject+plamo-dense.gguf.hdr 4728704 reject+plamo2-dense.gguf.hdr 5920096 reject+qwen-dense.gguf.hdr 3550848 reject+qwen2-dense.gguf.hdr 4731264 convert+qwen2moe-moe.gguf.hdr 9455872 reject+qwen2vl-dense.gguf.hdr 4731264 reject+qwen3-dense.gguf.hdr 4733824 convert+qwen35-dense.gguf.hdr 5271040 convert+qwen35moe-moe.gguf.hdr 9995904 reject+qwen3moe-moe.gguf.hdr 7096192 convert+qwen3next-moe.gguf.hdr 11044416 reject+qwen3vl-dense.gguf.hdr 4733824 reject+qwen3vlmoe-moe.gguf.hdr 7096192 reject+refact-dense.gguf.hdr 4741248 reject+refact-moe.gguf.hdr 7096448 reject+rnd1-moe.gguf.hdr 7096192 reject+seed_oss-dense.gguf.hdr 4730752 reject+smallthinker-moe.gguf.hdr 7094144 reject+smollm3-dense.gguf.hdr 4730752 convert+stablelm-dense.gguf.hdr 4739968 reject+starcoder-dense.gguf.hdr 4087296 reject+starcoder2-dense.gguf.hdr 3956480 reject+talkie-dense.gguf.hdr 4725760 reject+xverse-dense.gguf.hdr 4730752 rejectdiff --git a/src/frontends/gguf/tests/test_extensions.cpp b/src/frontends/gguf/tests/test_extensions.cppindex 4c2835e7343..a83309bc616 100644--- a/src/frontends/gguf/tests/test_extensions.cpp+++ b/src/frontends/gguf/tests/test_extensions.cpp@@ -34,6 +34,7 @@#include "openvino/op/multiply.hpp"#include "openvino/op/negative.hpp"#include "openvino/op/read_value.hpp"+#include "openvino/op/result.hpp"#include "openvino/op/scatter_update.hpp"using namespace ov_gguf_test;@@ -355,3 +356,100 @@ TEST(GGUFExtensions, ArbitraryTransformationExtensionRuns) {EXPECT_EQ(model->get_friendly_name(), "touched_by_extension");}++// ── GGUFMakeStateful: recurrent (non-appending) state rewrite ───────────────────────────────────+//+// qwen35's Gated-DeltaNet layers carry a conv window and a delta matrix per layer: unlike a KV+// cache these have no token axis and are overwritten wholesale each step, so nothing in the graph+// marks them the way a SetRows write marks a cache -- the decoder pairs a state's Parameter and+// Result explicitly via get_recurrent_states(), and TranslateSession records that pairing in+// rt_info (gguf_recurrent_states_key) before any DecoderTransformationExtension runs (see+// translate_session.cpp). SingleOpDecoder models exactly one ggml op, which cannot also carry a+// separate KV-cache SetRows, so these tests build the rt_info directly on a hand-built model and+// run GGUFMakeStateful as an ov::pass::ModelPass, bypassing FrontEnd::convert entirely.+namespace {++// A model with one static-shape Parameter/Result recurrent-state pair, optionally alongside a KV+// cache SetRows write (kv_cache_write_builder's shape) to model a hybrid stack. state_out is an+// arbitrary op fed by the state Parameter; its friendly name is what+// make_recurrent_states_stateful matches a Result's producer against (see make_stateful.cpp).+std::shared_ptr<ov::Model> recurrent_state_model(bool with_kv_cache) {+ auto state_in = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 2, 4});+ state_in->set_friendly_name("state_in");+ auto state_out = std::make_shared<ov::op::v0::Abs>(state_in);+ state_out->set_friendly_name("state_out");+ auto state_result = std::make_shared<ov::op::v0::Result>(state_out);++ ov::ParameterVector params{state_in};+ ov::ResultVector results{state_result};++ if (with_kv_cache) {+ // Matches translate_set_rows's own invariant: it Converts `data` to the destination's+ // element type before constructing SetRows, so data and cache always agree here too.+ auto data = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, -1, 2, 4});+ auto idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{1, 1, 1, -1});+ auto cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, -1, 2, 4});+ cache->set_friendly_name("cache");+ auto set_rows = std::make_shared<SetRows>(data, idx, cache);+ auto cache_result = std::make_shared<ov::op::v0::Result>(set_rows);+ params.insert(params.end(), {data, idx, cache});+ results.push_back(cache_result);+ }++ auto model = std::make_shared<ov::Model>(results, params);+ std::vector<std::string> flat{"state_in", "state_out"};+ model->get_rt_info()[pass::gguf_recurrent_states_key()] = flat;+ return model;+}++} // namespace++// A recurrent-only model (no KV cache at all -- an all-linear-attention stack) still gets its+// state rewritten: the early "cache_writes.empty()" return in run_on_model must not skip it.+TEST(GGUFExtensions, GGUFMakeStatefulRewritesRecurrentOnlyState) {+ auto model = recurrent_state_model(/*with_kv_cache=*/false);++ pass::GGUFMakeStateful pass;+ EXPECT_TRUE(pass.run_on_model(model));++ ASSERT_EQ(model->get_variables().size(), 1);+ EXPECT_EQ(model->get_sinks().size(), 1);+ for (const auto& p : model->get_parameters()) {+ EXPECT_NE(p->get_friendly_name(), "state_in");+ }+ for (const auto& r : model->get_results()) {+ EXPECT_EQ(r->get_input_node_shared_ptr(0)->get_friendly_name().find("state_out"), std::string::npos);+ }+}++// qwen35 is exactly this: a hybrid stack with both a KV cache (full-attention layers) and a+// recurrent state (Gated-DeltaNet layers). Both must be rewritten by the same pass invocation.+TEST(GGUFExtensions, GGUFMakeStatefulRewritesHybridKvAndRecurrentState) {+ auto model = recurrent_state_model(/*with_kv_cache=*/true);++ pass::GGUFMakeStateful pass;+ EXPECT_TRUE(pass.run_on_model(model));++ ASSERT_EQ(model->get_variables().size(), 2);+ EXPECT_EQ(model->get_sinks().size(), 2);+ for (const auto& p : model->get_parameters()) {+ EXPECT_NE(p->get_friendly_name(), "state_in");+ EXPECT_NE(p->get_friendly_name(), "cache");+ }+}++// Running the pass twice (e.g. a caller that registers it on an already-stateful model, or a+// re-entrant conversion) must not duplicate the rewrite: the state Parameter is already gone, so+// the second run's rt_info-guided lookup must find nothing left to rewrite rather than throwing or+// creating a second Variable for the same state.+TEST(GGUFExtensions, GGUFMakeStatefulRecurrentRewriteIsIdempotent) {+ auto model = recurrent_state_model(/*with_kv_cache=*/false);++ pass::GGUFMakeStateful pass;+ ASSERT_TRUE(pass.run_on_model(model));+ ASSERT_EQ(model->get_variables().size(), 1);++ EXPECT_FALSE(pass.run_on_model(model));+ EXPECT_EQ(model->get_variables().size(), 1);+ EXPECT_EQ(model->get_sinks().size(), 1);+}diff --git a/src/frontends/gguf/tests/test_graph_fingerprint.py b/src/frontends/gguf/tests/test_graph_fingerprint.pynew file mode 100644index 00000000000..a7826c1b06b--- /dev/null+++ b/src/frontends/gguf/tests/test_graph_fingerprint.py@@ -0,0 +1,54 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+#+# Gated graph-fingerprint regression test for the GGUF frontend native builder.+#+# The GGUF files are multi-GB and cannot ship in-repo, so this test is OPT-IN: it runs only when+# GGUF_FINGERPRINT_MODELS points at local models. It converts each model through the frontend+# (requested by name, since it is not auto-selectable) and asserts the graph fingerprint matches+# any unintended change to the produced graph for a supported architecture.+#+# GGUF_FINGERPRINT_MODELS format: semicolon-separated entries "name=path=expected_sighash"+# (the expected hash is optional; when omitted the test just asserts the model converts and prints+# the observed hash so it can be recorded as the baseline).+#+# Example:+# GGUF_FINGERPRINT_MODELS="qwen3=/models/Qwen3-0.6B-Q8_0.gguf=87cf7f3b0742a6cd" \+# PYTHONPATH=<ov>/python LD_LIBRARY_PATH=<ov> pytest test_graph_fingerprint.py -v++import os++import pytest++from graph_fingerprint import fingerprint++_SPEC = os.environ.get("GGUF_FINGERPRINT_MODELS", "").strip()+++def _parse_spec(spec):+ cases = []+ for entry in spec.split(";"):+ entry = entry.strip()+ if not entry:+ continue+ parts = entry.split("=")+ name, path = parts[0], parts[1]+ expected = parts[2] if len(parts) > 2 else None+ cases.append((name, path, expected))+ return cases+++_CASES = _parse_spec(_SPEC)++[email protected](not _CASES, reason="set GGUF_FINGERPRINT_MODELS=name=path[=hash];... to run")[email protected]("name,path,expected", _CASES, ids=[c[0] for c in _CASES])+def test_graph_fingerprint(name, path, expected):+ assert os.path.exists(path), f"model not found: {path}"+ fp = fingerprint(path)+ print(f"\n{name}: sighash={fp['sighash']} ops={fp['num_ops']} inputs={fp['inputs']}")+ if expected:+ assert fp["sighash"] == expected, (+ f"{name} graph fingerprint changed: got {fp['sighash']}, expected {expected}. "+ f"The builder produced a different graph for this architecture."+ )diff --git a/src/frontends/gguf/tests/test_weights.cpp b/src/frontends/gguf/tests/test_weights.cppindex 1685b34f48c..3add208795c 100644--- a/src/frontends/gguf/tests/test_weights.cpp+++ b/src/frontends/gguf/tests/test_weights.cpp@@ -15,6 +15,7 @@#include <cstring>#include "op_test_utils.hpp"+#include "quant/weights.hpp"using namespace ov_gguf_test;@@ -176,8 +177,6 @@ TEST(GGUFWeightPlain, BF16) {EXPECT_NEAR(a[i], static_cast<float>(vals[i]), 1e-6f);}-// Contract tests for the two ggml types that are NOT supported as stored GGUF *weights*.-//// Q8_K is a ggml intermediate activation-quantization type: it only ever appears as the// on-the-fly quantized activation in a dot product, never as a weight tensor stored in a .gguf.// The frontend therefore does not accept it as a weight -- gguf_type_from_name knows the name@@ -198,20 +197,62 @@ TEST(GGUFWeightUnsupported, Q8KIsNotAStoredWeight) {});}-// MXFP4 is supported ONLY as rank-5 MoE-packed expert weights ([1,n_expert,m,k_blocks,17]),-// which MUL_MAT_ID dequantizes on-graph (see GGUFOps.MulMatIdMxfp4Packed). A plain 2D MXFP4-// weight is not a shape the frontend produces, so make_weight_node rejects it. This pins that-// the standalone-dequant path is intentionally absent (the packed path is the supported one).-TEST(GGUFWeightUnsupported, Mxfp4TwoDimIsNotAStoredWeight) {- // 1 block (17 bytes) covers 32 weights.+// A stored MoE expert weight is rank>2 ([1,n_expert,m,k]) and stays PACKED for MUL_MAT_ID (see+// GGUFOps.MulMatIdMxfp4Packed). But the llama.cpp cgraph path (e.g. test-backend-ops' GET_ROWS /+// MUL_MAT op tests) also feeds bare 2D MXFP4 tensors that are not stored weights at all, so+// make_weight_node must dequantize those too. f4e2m1 nibble -> value mirrors kF4E2M1 in+// test_ops.cpp; scale byte 127 -> e8m0 exponent 0 -> 2^0 = 1.0.+TEST(GGUFWeight, Mxfp4TwoDim) {+ static const float kF4E2M1[16] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f,+ -0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f};+ // 1 row, 1 block (32 cols): byte0 = e8m0 scale, bytes1..16 = nibble-packed codes (low nibble+ // = element i, high nibble = element i+16, for i in [0,16)).ov::Tensor data(ov::element::u8, ov::Shape{17});- std::memset(data.data(), 0, data.get_byte_size());- EXPECT_ANY_THROW({- SingleOpBuilder()- .op("GGML_OP_NONE")- .output("w", ov::element::f32, {1, 32})- .attr<ov::Tensor>("data", data)- .attr<std::string>("quant_type", "MXFP4")- .build();- });+ auto* bytes = data.data<uint8_t>();+ bytes[0] = 127;+ for (size_t i = 0; i < 16; ++i)+ bytes[1 + i] = static_cast<uint8_t>((i << 4) | i);++ auto model = SingleOpBuilder()+ .op("GGML_OP_NONE")+ .output("w", ov::element::f32, {1, 32})+ .attr<ov::Tensor>("data", data)+ .attr<std::string>("quant_type", "MXFP4")+ .build();++ auto out = run_on_cpu(model, {});+ ASSERT_EQ(out.get_size(), 32u);+ const float* a = out.data<float>();+ for (size_t j = 0; j < 32; ++j)+ EXPECT_FLOAT_EQ(a[j], kF4E2M1[j % 16]) << "element " << j;+}++// Regression for a fused-QKV bias (e.g. phi-3's blk.N.attn_qkv.bias) being silently dropped:+// register_fused_qkv split the fused weight into q/k/v parts but never touched a fused bias, so+// attention()'s add_bias calls (gated on !has_fused_qkv) never ran for these archs, and the+// bias never made it into the graph. split_fused_qkv_bias must slice the fused bias into+// exactly the q/k/v parts the weight split uses (n_q, n_k, n_v rows in that order).+TEST(GGUFFusedQkvBias, SplitsIntoExpectedRanges) {+ constexpr size_t n_q = 4, n_k = 2, n_v = 2;+ ov::Tensor bias(ov::element::f32, ov::Shape{n_q + n_k + n_v});+ auto* data = bias.data<float>();+ for (size_t i = 0; i < n_q + n_k + n_v; ++i) {+ data[i] = static_cast<float>(i);+ }+ std::unordered_map<std::string, ov::Tensor> weights{{"blk.0.attn_qkv.bias", bias}};++ auto parts = ov::frontend::gguf::split_fused_qkv_bias("blk.0.attn_qkv", weights, n_q, n_k, n_v);++ ASSERT_EQ(parts[0].get_shape(), ov::Shape{n_q});+ ASSERT_EQ(parts[1].get_shape(), ov::Shape{n_k});+ ASSERT_EQ(parts[2].get_shape(), ov::Shape{n_v});+ for (size_t i = 0; i < n_q; ++i) {+ EXPECT_FLOAT_EQ(parts[0].data<float>()[i], static_cast<float>(i));+ }+ for (size_t i = 0; i < n_k; ++i) {+ EXPECT_FLOAT_EQ(parts[1].data<float>()[i], static_cast<float>(n_q + i));+ }+ for (size_t i = 0; i < n_v; ++i) {+ EXPECT_FLOAT_EQ(parts[2].data<float>()[i], static_cast<float>(n_q + n_k + i));+ }}diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex 6eccbd6bdcb..b341fb62dee 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -8,5 +8,5 @@ add_subdirectory(samples_tests)add_subdirectory(e2e_tests)add_subdirectory(memory_tests)-install(FILES requirements_pytorch requirements_tensorflow requirements_onnx requirements_jax+install(FILES requirements_pytorch requirements_tensorflow requirements_onnx requirements_jax requirements_ggufDESTINATION tests COMPONENT tests EXCLUDE_FROM_ALL)diff --git a/tests/model_hub_tests/gguf/conftest.py b/tests/model_hub_tests/gguf/conftest.pynew file mode 100644index 00000000000..70d8accf63b--- /dev/null+++ b/tests/model_hub_tests/gguf/conftest.py@@ -0,0 +1,12 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import inspect++from models_hub_common.utils import get_params+++def pytest_generate_tests(metafunc):+ test_gen_attrs_names = list(inspect.signature(get_params).parameters)+ params = get_params()+ metafunc.parametrize(test_gen_attrs_names, params, scope="function")diff --git a/tests/model_hub_tests/gguf/gguf_models_nightly b/tests/model_hub_tests/gguf/gguf_models_nightlynew file mode 100644index 00000000000..3694dba5add--- /dev/null+++ b/tests/model_hub_tests/gguf/gguf_models_nightly@@ -0,0 +1,30 @@+# List of larger models (roughly 7B-30B parameters) used to verify the GGUF frontend converts,+# compiles, and runs a single forward step correctly for each supported architecture that has+# no small (<=4B) checkpoint available.+#+# Format: arch,repo_id,filename[,mark,reason]+# arch - architecture name (matches src/frontends/gguf/docs/supported_models.md)+# repo_id - Hugging Face Hub repo hosting the .gguf file+# filename - the specific .gguf file to download from that repo+# mark - optional: "skip" or "xfail"+# reason - required if mark is set+#+# See src/frontends/gguf/docs/supported_models.md for the full architecture list and the+# checkpoints this project validates them against.+#+# Runner sizing: these convert + compile in-process, so the driving cost is the peak+# resident memory recorded in that document's memory table (the largest entry kept here,+# muse-glimmer, peaks around 37 GiB) -- hence the 16-core/64 GiB nightly runner.+olmoe,allenai/OLMoE-1B-7B-0924-Instruct-GGUF,olmoe-1b-7b-0924-instruct-q4_0.gguf+muse-glimmer,unsloth/Muse-Glimmer-30B-GGUF,Muse-Glimmer-30B-UD-Q4_K_XL.gguf+qwen35-bonsai,prism-ml/Ternary-Bonsai-27B-gguf,Ternary-Bonsai-27B-Q2_g64.gguf+ernie4_5-moe,bartowski/baidu_ERNIE-4.5-21B-A3B-PT-GGUF,baidu_ERNIE-4.5-21B-A3B-PT-Q4_K_M.gguf+bailingmoe2,bartowski/inclusionAI_Ling-mini-2.0-GGUF,inclusionAI_Ling-mini-2.0-Q4_K_M.gguf+mellum,bartowski/Mellum2-12B-A2.5B-Instruct-GGUF,Mellum2-12B-A2.5B-Instruct-Q4_K_M.gguf+deepseek2-ocr,aditya00196/DeepSeek-OCR-2-Q4_K_M.gguf,DeepSeek-OCR-2-Q4_K_M.gguf+gpt-oss,unsloth/gpt-oss-20b-GGUF,gpt-oss-20b-Q4_K_M.gguf,skip,"Needs ~120 GiB peak anon RAM to convert+compile (see the memory table in supported_models.md); the largest CI runner is 64 GiB"+hunyuan-moe,,,skip,"No small checkpoint publicly available (see supported_models.md)"+glm4moe,,,skip,"Smallest checkpoint (GLM-4.5-Air) is ~40 GiB, impractical even for nightly"+exaone-moe,,,skip,"Smallest checkpoint is ~9 GiB / 32B, not currently validated (see supported_models.md)"+minimax-m2,,,skip,"Smallest checkpoint is ~78 GiB, impractical even for nightly"+jais2,,,skip,"No small checkpoint publicly available (see supported_models.md)"diff --git a/tests/model_hub_tests/gguf/gguf_models_precommit b/tests/model_hub_tests/gguf/gguf_models_precommitnew file mode 100644index 00000000000..540ce58288e--- /dev/null+++ b/tests/model_hub_tests/gguf/gguf_models_precommit@@ -0,0 +1,35 @@+# List of small models (roughly <=4B parameters) used to verify the GGUF frontend converts,+# compiles, and runs a single forward step correctly for each supported architecture.+#+# Format: arch,repo_id,filename[,mark,reason]+# arch - architecture name (matches src/frontends/gguf/docs/supported_models.md)+# repo_id - Hugging Face Hub repo hosting the .gguf file+# filename - the specific .gguf file to download from that repo+# mark - optional: "skip" or "xfail"+# reason - required if mark is set+#+# See src/frontends/gguf/docs/supported_models.md for the full architecture list and the+# checkpoints this project validates them against; entries below prefer the smallest+# available quantization of the same (or an equivalently small) checkpoint.+#+# Runner sizing: these convert + compile in-process, so the driving cost is the peak+# resident memory recorded in that document's memory table (the largest entry here,+# gemma4, peaks around 12 GiB) -- hence the 8-core/32 GiB precommit runner.+llama,bartowski/Llama-3.2-1B-Instruct-GGUF,Llama-3.2-1B-Instruct-Q4_K_M.gguf+qwen2,Qwen/Qwen2.5-0.5B-Instruct-GGUF,qwen2.5-0.5b-instruct-q4_k_m.gguf+qwen3,Qwen/Qwen3-0.6B-GGUF,Qwen3-0.6B-Q8_0.gguf+phi3,bartowski/Phi-3-mini-4k-instruct-GGUF,Phi-3-mini-4k-instruct-Q4_K_M.gguf+minicpm,runfuture/MiniCPM-2B-dpo-q4km-gguf,MiniCPM-2B-dpo-q4km-gguf.gguf+hunyuan-dense,bartowski/tencent_Hunyuan-0.5B-Instruct-GGUF,tencent_Hunyuan-0.5B-Instruct-Q4_K_M.gguf+qwen3moe,mradermacher/Qwen3-0.9B-A0.6B-GGUF,Qwen3-0.9B-A0.6B.Q4_K_M.gguf+gemma,RichardErkhov/google_-_gemma-2b-it-gguf,gemma-2b-it.Q4_K_M.gguf+gemma2,bartowski/gemma-2-2b-it-GGUF,gemma-2-2b-it-Q4_K_M.gguf+gemma3,unsloth/gemma-3-1b-it-GGUF,gemma-3-1b-it-Q4_K_M.gguf+gemma4,unsloth/gemma-4-E4B-it-GGUF,gemma-4-E4B-it-Q4_K_M.gguf+llama-embed,sabafallah/llama-nemotron-embed-1b-v2-GGUF,llama-nemotron-embed-1b-v2-Q4_K_M.gguf+exaone4,LGAI-EXAONE/EXAONE-4.0-1.2B-GGUF,EXAONE-4.0-1.2B-Q4_K_M.gguf+plamo3,mmnga-o/plamo-3-nict-2b-base-gguf,plamo-3-nict-2b-base-Q4_K_M.gguf+smollm3,bartowski/HuggingFaceTB_SmolLM3-3B-GGUF,HuggingFaceTB_SmolLM3-3B-Q4_K_M.gguf+maincoder,mradermacher/Maincoder-1B-GGUF,Maincoder-1B.Q4_K_M.gguf+mistral3,mradermacher/Ministral-3b-instruct-GGUF,Ministral-3b-instruct.Q4_K_M.gguf+qwen35,ggml-org/Qwen3.5-0.8B-GGUF,Qwen3.5-0.8B-Q4_0.ggufdiff --git a/tests/model_hub_tests/gguf/test_gguf.py b/tests/model_hub_tests/gguf/test_gguf.pynew file mode 100644index 00000000000..9b7567bb7e1--- /dev/null+++ b/tests/model_hub_tests/gguf/test_gguf.py@@ -0,0 +1,56 @@+# -*- coding: utf-8 -*-+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+#+# Verifies the GGUF frontend against real .gguf checkpoints downloaded from the Hugging Face+# Hub, one per architecture listed in src/frontends/gguf/docs/supported_models.md.+#+# Each test downloads one .gguf file, converts it with core.read_model(), compiles it, and+# runs a single forward step (one new token, no prior context -- see utils.py for why that is+# enough to exercise the frontend's default stateless lowering without extra setup). The+# check is deliberately shallow: a finite, correctly shaped logits tensor. It does not build a+# tokenizer or run more than one step, since this suite is about frontend conversion/inference+# correctness, not generation quality or text coherence (which+# src/frontends/gguf/tests/compare_with_llama.py and the GenAI-based harness described in+# supported_models.md already cover for the architectures where that matters).+#+# gguf_models_precommit lists the small (<=~4B parameter) architectures, run on every commit.+# gguf_models_nightly lists the rest (up to ~30B), run nightly given their download size.++import os++import pytest++from models_hub_common.constants import clean_hf_cache_dir, hf_cache_dir+from models_hub_common.utils import cleanup_dir+from utils import assert_valid_logits, parse_gguf_model_list, run_gguf_model+++class TestGGUF:+ def teardown_method(self):+ if clean_hf_cache_dir:+ cleanup_dir(hf_cache_dir)++ def run(self, arch, repo_id, filename, mark, reason, ie_device):+ assert mark in (None, "skip", "xfail"), f"Unknown mark {mark!r} for {arch}"+ if mark == "skip":+ pytest.skip(reason)+ if mark == "xfail":+ pytest.xfail(reason)++ logits = run_gguf_model(repo_id, filename, device=ie_device)+ assert_valid_logits(logits)++ @pytest.mark.parametrize(+ "arch,repo_id,filename,mark,reason",+ parse_gguf_model_list(os.path.join(os.path.dirname(__file__), "gguf_models_precommit")))+ @pytest.mark.precommit+ def test_gguf_precommit(self, arch, repo_id, filename, mark, reason, ie_device):+ self.run(arch, repo_id, filename, mark, reason, ie_device)++ @pytest.mark.parametrize(+ "arch,repo_id,filename,mark,reason",+ parse_gguf_model_list(os.path.join(os.path.dirname(__file__), "gguf_models_nightly")))+ @pytest.mark.nightly+ def test_gguf_nightly(self, arch, repo_id, filename, mark, reason, ie_device):+ self.run(arch, repo_id, filename, mark, reason, ie_device)diff --git a/tests/model_hub_tests/gguf/utils.py b/tests/model_hub_tests/gguf/utils.pynew file mode 100644index 00000000000..b2d978af738--- /dev/null+++ b/tests/model_hub_tests/gguf/utils.py@@ -0,0 +1,159 @@+# -*- coding: utf-8 -*-+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import csv++import numpy as np+import openvino as ov+from openvino.frontend import FrontEndManager++from models_hub_common.constants import hf_cache_dir+++def parse_gguf_model_list(file_name: str):+ """Parse a gguf_models_* list file into (arch, repo_id, filename, mark, reason) tuples.++ Each non-comment, non-empty line is "arch,repo_id,filename[,mark,reason]" (mark/reason+ may be present but empty). repo_id/filename are empty for a fully skipped entry that has+ no runnable checkpoint at all (see gguf_models_nightly).+ """+ models = []+ with open(file_name, "r") as f_in:+ for row in csv.reader(f_in):+ if not row or not row[0] or row[0].startswith("#"):+ continue+ row = [item.strip() for item in row]+ row += [""] * (5 - len(row))+ arch, repo_id, filename, mark, reason = row[:5]+ models.append((arch, repo_id, filename, mark or None, reason or None))+ return models+++def gguf_hub_download(repo_id: str, filename: str) -> str:+ """Download one .gguf file from the HF hub into the shared HF cache dir."""+ from huggingface_hub import hf_hub_download++ return hf_hub_download(repo_id=repo_id, filename=filename, cache_dir=hf_cache_dir)+++def _kv_cache_head_count(compiled_model) -> int:+ """Number of KV heads, read from any cache_k_* input port's static heads dim.++ All per-layer KV caches use the same [1, ctx, n_head_kv, head_size] layout (see+ src/frontends/gguf/src/builder/blocks/attention.cpp), so any one of them gives the count+ needed to size inp_kv_idx below. Falls back to 1 if the model has no KV cache at all+ (e.g. a purely recurrent / linear-attention stack).+ """+ for port in compiled_model.inputs:+ name = next(iter(port.get_names()), "")+ if name.startswith("cache_k_"):+ heads_dim = port.get_partial_shape()[2]+ if heads_dim.is_static:+ return heads_dim.get_length()+ return 1+++def build_single_token_inputs(compiled_model, token_id: int = 1, is_imrope: bool = False):+ """Build a minimal, single-new-token input feed for the GGUF frontend's stateless IO+ contract (inp_tokens / inp_pos / inp_out_ids / self_kq_mask[_swa] / token_len_per_seq /+ inp_kv_idx), plus zero-filled tensors for every other input the model declares (per-layer+ KV caches and, for hybrid/recurrent architectures such as qwen35, the fully-static conv /+ delta state Parameters).++ This deliberately does not model real multi-token generation or attend to any real+ prompt/tokenizer: with T=1 (one new token, no prior context) every KV cache write covers+ the cache in full, so the frontend's default (caller-extension-free) SetRows lowering+ -- a plain ScatterUpdate over the whole cache -- is well-defined without requiring the+ caller to also register the MakeStateful extension. That keeps this check to exactly+ what "verify basic correctness" needs: the model converts, compiles, and produces a+ finite, correctly shaped output for one forward pass.++ is_imrope selects the interleaved M-RoPE position layout (qwen35 / qwen3vl), read from+ the model's "gguf_is_imrope" rt_info by the caller (CompiledModel does not expose+ rt_info, so this must be read from the ov.Model before compiling): such a model expects+ inp_pos to carry 4 position sections per token instead of 1.+ """+ n_head_kv = _kv_cache_head_count(compiled_model)+ n_pos_sections = 4 if is_imrope else 1+ feed = {}+ for port in compiled_model.inputs:+ name = next(iter(port.get_names()), None)+ assert name, "GGUF model input port has no name"++ if name == "inp_tokens":+ feed[name] = ov.Tensor(np.array([[[[token_id]]]], dtype=np.int32))+ elif name == "inp_pos":+ feed[name] = ov.Tensor(np.zeros((1, 1, 1, n_pos_sections), dtype=np.int32))+ elif name == "inp_out_ids":+ feed[name] = ov.Tensor(np.array([[[[0]]]], dtype=np.int32))+ elif name in ("self_kq_mask", "self_kq_mask_swa"):+ feed[name] = ov.Tensor(np.zeros((1, 1, 1, 1), dtype=np.float32))+ elif name == "token_len_per_seq":+ feed[name] = ov.Tensor(np.array([1], dtype=np.int64))+ elif name == "beam_idx":+ feed[name] = ov.Tensor(np.zeros((1,), dtype=np.int32))+ elif name == "inp_kv_idx":+ # One write index per (new token, kv head): translate_set_rows flattens the new+ # rows to [.., 1, tokens * n_head_kv, row_size] before the default ScatterUpdate+ # lowering, so indices must cover that same flattened extent.+ feed[name] = ov.Tensor(np.arange(n_head_kv, dtype=np.int32).reshape(1, 1, 1, n_head_kv))+ else:+ # Any other input (a per-layer KV cache, or a recurrent/linear-attention state+ # such as qwen35's Gated-DeltaNet conv window and delta matrix): zero-fill,+ # resolving the one dynamic (token/context) axis, if any, to T=1.+ partial_shape = port.get_partial_shape()+ shape = [d.get_length() if d.is_static else 1 for d in partial_shape]+ dtype = port.get_element_type().to_dtype()+ feed[name] = ov.Tensor(np.zeros(shape, dtype=dtype))+ return feed+++def convert_gguf_model(path: str) -> ov.Model:+ """Convert a .gguf into an ov.Model through the GGUF frontend.++ The frontend is deliberately not auto-selectable (see is_hidden_frontend in+ src/frontends/common/src/manager.cpp), so core.read_model(".gguf") does not resolve to it and+ the frontend has to be asked for by name. Nothing else is needed: the frontend runs its own+ normalization inside convert(), and the only step read_model would add on top,+ update_v10_model, applies solely to legacy IR v10 models.+ """+ fe = FrontEndManager().load_by_framework("gguf")+ return fe.convert(fe.load(path))+++def run_gguf_model(repo_id: str, filename: str, device: str = "CPU"):+ """Download, convert, compile, and run one forward step of a .gguf model.++ Returns the raw logits tensor as a numpy array. Raises on any conversion / compilation /+ inference failure; the caller is expected to additionally sanity-check the result (shape,+ finiteness) -- see assert_valid_logits below.+ """+ path = gguf_hub_download(repo_id, filename)+ core = ov.Core()+ model = convert_gguf_model(path)+ is_imrope = False+ if "gguf_is_imrope" in model.get_rt_info():+ is_imrope = bool(model.get_rt_info(["gguf_is_imrope"]).get())+ compiled_model = core.compile_model(model, device)+ request = compiled_model.create_infer_request()+ feed = build_single_token_inputs(compiled_model, is_imrope=is_imrope)+ outputs = request.infer(feed)+ return next(iter(outputs.values()))+++def assert_valid_logits(logits: np.ndarray):+ """Basic correctness: a real (non-empty), finite tensor of logits over some vocabulary.++ Deliberately does not check the actual predicted token / text: this suite verifies the+ frontend converts and runs each supported architecture, not that any given (quantized,+ single-token, no-history) forward pass produces a meaningful continuation.+ """+ assert logits.size > 0, "model produced an empty output tensor"+ assert np.isfinite(logits).all(), "model output contains NaN/Inf"+ vocab_size = logits.shape[-1]+ assert vocab_size > 1, f"output's last dim ({vocab_size}) does not look like a vocab axis"+ # argmax must be a valid vocabulary index -- mostly a sanity check on the shape/dtype+ # plumbing above, since any finite tensor trivially satisfies this.+ best = int(logits.reshape(-1, vocab_size)[-1].argmax())+ assert 0 <= best < vocab_sizediff --git a/tests/requirements_gguf b/tests/requirements_ggufnew file mode 100644index 00000000000..b40c5a7c188--- /dev/null+++ b/tests/requirements_gguf@@ -0,0 +1,11 @@+# Requirements for the GGUF frontend model hub tests (tests/model_hub_tests/gguf).+#+# The tests only need numpy (to build input tensors), pytest, and huggingface_hub (to+# download the .gguf checkpoints). No tokenizer / transformers / framework dependency:+# the suite feeds synthetic token ids and checks conversion + a single forward step,+# not generated text.+numpy==1.26.4; python_version < "3.12"+numpy==2.2.1; python_version >= "3.12"+pytest==7.0.1+pytest-html==4.2.0+huggingface-hub==0.25.2