Commit 18264f8ee for llama.cpp
commit 18264f8ee545896fbca793f5ddeb48b4e53d5d4b
Author: Ravi Panchumarthy <ravi.panchumarthy@intel.com>
Date: Wed Dec 2 07:54:50 2026 -0800
openvino: update to OV 2026.5, CI fixes, add model support, add mtmd support (#33505)
* ggml-openvino: translate recurrent cache replay graphs
Assisted-by: Codex
* ggml-openvino: use host USM for 4-D KV on integrated GPUs
Assisted-by: Codex
* Revert "ggml-openvino: use host USM for 4-D KV on integrated GPUs"
This reverts commit 575db27dd93e70e5ee5aa44edb49c6e8236d43cc.
* ggml-openvino: key compiled replay graphs by declared control shapes
Assisted-by: Codex
* ggml-openvino: represent replay writes with Assign sinks
* ggml-openvino: document writable replay graph contract
* ggml-openvino: remove legacy native recurrent cache ops
* ggml-openvino: document replay graph selection during prefill
* ggml-openvino: enable Qwen3.5 and Gemma4 image inputs
Reuse Qwen vision graphs across image resolutions with runtime spatial
shapes and interpolation targets. Support Gemma spatial positions,
normalized vision attention and variable image-embedding counts.
Preserve recurrent cache state and sequence grouping during parallel
serving, using the native single-output cache-update contract. Keep
KV head dimensions fixed after relayout when applying dynamic axes.
Validated image requests and four-slot unified/split KV serving for
Qwen3.5 and Gemma4 E2B on OpenVINO CPU and GPU. Vision and recurrent
backend regressions passed 21/21 on each device.
(cherry picked from commit d64dcb5594db74c0f03945cac668aefcca75e0b1)
* ggml-openvino: keep allocation IDs out of persistent cache signatures
Store weight allocation generations separately from graph descriptors.
Private cache keys retain allocation isolation, while dynamic model
fingerprints stay stable when the same source weights are reloaded.
* ggml-openvino: preserve explicit F32 MatMul precision per node
Honor GGML_PREC_F32 on MatMul src1 with node precision guards and precision-sensitive input paths, including grouped-query attention. Keep other branches at their configured precision. Probe the runtime helper and include precision guards in cache identities.
Validated on the local OpenVINO 2026.5.1 CPU/GPU runtime: 12/12 F32 precision cases under CPU default, CPU BF16 and GPU FP16 hints; mixed-precision branches and cached F32/default/F32 transitions; five real audio preprocessing lengths per device.
* ggml-openvino: remove the node precision availability guard
The official OpenVINO 2026.4.1 Runtime SDK exports the node precision helper. Remove its link probe and conditional fallback while retaining the Runtime SDK declaration shim and the recurrent-cache-op guard.
Validated the downloaded SDK with a compiled/linked API probe and 12/12 F32 MatMul cases on default CPU and FP16-hint GPU. The local 2026.5.1 build also passes 12/12 on each device. An additional 2026.4.1 CPU BF16-hint check has seven precision failures, independent of this availability-guard removal.
* ggml-openvino: document pending audio dynamics and preprocessing caching
Assisted-by: Codex
* ggml-openvino: declare the node precision helper in mulmat
Move the exported helper declaration into mulmat.cpp and remove the single-consumer precision_control.hpp header.
Validated builds and 12/12 F32 MatMul cases on CPU/GPU with both the local OpenVINO build and the official 2026.4.1 Runtime SDK.
Assisted-by: Codex
* ggml-openvino: Enable MOE models on NPU for Qwen3.6-35B-A3B
NPUW, the partitioning layer of the NPU plugin, has its own MoE support.
It isolates the experts into functions and runs only the routed experts for
each token, with the router on the host (the `HOST_ROUTED` mode).
This PR translates the MoE block of a model into the form NPUW recognises,
and sets the NPUW properties for that mode.
* ggml-openvino: find the moe block once per decoder for the npu config
ov_graph_compute_static scanned every node of the graph for a MoE block on
each call, cache hits included, to choose the NPUW MoE properties.
set_input_output already matches each MoE block when the decoder is built,
so it now records the result in GgmlOvDecoder::has_moe_block(), and the
properties are added from that flag when a graph compiles. The properties
are the same as before.
* ggml-openvino: docs: OpenVINO version and Linux memory setting for MoE models on the NPU
* ggml-openvino: fix the build_rs state move on the dynamic path
* ggml-openvino: check the input rank before slicing packed views
* ggml-openvino: repeat the soft_max mask over broadcast dims
* ci : run OpenVINO self-hosted job on the PTL runner with Ubuntu 26.04
* docker : use Ubuntu 26.04 for the OpenVINO image
* docs : pick the OpenVINO archive for the Ubuntu version
* ci : set a 120 min timeout on the OpenVINO self-hosted job
* ggml-openvino: use the in-place 4-D KV cache by default with OpenVINO 2026.5 or later
* openvino: fix the clang-format of the KV_4D version check
* openvino: update OpenVINO to 2026.5 and GPU/NPU drivers
* openvino: skip GPU convolutions that OpenVINO 2026.5 gets wrong
* docs : update the OpenVINO validation system and NPU limitations
* docs : move GGML_OPENVINO_ENABLE_KV_4D to the default optimizations
* docs : fix OpenVINO docs inconsistencies
* ggml-openvino: support folded MoE weight scales and fused MoE for Q4_0 experts
Gemma 4 26B-A4B stopped loading on the OpenVINO backend after #28898 folded
the per-expert ffn_down_exps.scale into ggml_mul_mat_id_ext. supports_op
rejected every op with a folded scale, so the down experts were placed on the
CPU, whose MUL_MAT_ID then asserted on the expert ids produced by OpenVINO
(repack.cpp: i02 >= 0 && i02 < n_as), on every OpenVINO device.
- supports_op: accept the MUL_MAT_ID weight scale (src[3]). Keep rejecting
the activation scale, a scale on a dense MUL_MAT, and scaled MXFP4 experts.
- translate_mul_mat_id: pick each slot's weight scale by its expert id and
multiply it into the result (per-tensor, per-expert and
per-channel-per-expert, as on CPU). A per-expert scale gets the router
weights' shape, so FuseMoeCompressedFusedGateUp still folds it into the
routing weights.
- GPU: convert Q4_0 MoE experts to Q4_1_64 as for Q4_K/Q5_K/Q6_K, so the
plugin fuses them into MOECompressed instead of the slow GatherMatmul
prefill path.
gemma-4-26B-A4B-it QAT Q4_0 on an Arc B390 GPU, 8k prompt: loads and answers
correctly; prefill 65 -> 1179 tok/s, decode 21.4 tok/s.
* openvino: fix MUL_MAT_ID weight scale views and skipped slots
* ggml-openvino: keep the Q5_0 layout instead of converting it to Q4_0_64
* ggml-openvino: swap the dynamic dim in TRANSPOSE also when both dims have the same size
* ggml-openvino: support REPEAT to an empty dim and GET_ROWS on an empty tiled batch
* openvino: drop test-backend-ops changes
* ggml-openvino: release host weight buffers by default on GPU and restore them from the model file
* openvino: keep scaled MUL_MAT_ID out of the tiled MoE path
* ggml-openvino: reshape the MUL_MAT_ID activations of a one-token static graph
* openvino: reject in-place UNARY on a non-contiguous view
* docs : update OpenVINO validated models (#475)
* docs : update OpenVINO validated models
* docs : add Qwen3-VL image sample
* ggml-openvino: reconvert decoder when a one-token graph is reused with more tokens
* ggml-openvino: reconvert ambiguous one-token graphs and release old model
A one-token graph is ambiguous only when a layer has a single KV head
(MLA's compressed KV or MQA): the head and token dimensions then have
identical sizes and strides.
Reconvert only these graphs. Before compiling the replacement, release
the original one-token model, including its shared cache entry, infer
request, and replay writebacks. This avoids compiling and retaining two
copies of the model weights on the device.
* ggml-openvino: do not interpret a view's token dim as heads
process_view_input_new has two head-splitting paths that interpret
view dimension 1 as the head dimension.
For one-token graphs, a plain column split such as LFM2's and
Nemotron-H's [n, n_tokens] views of a [3n, n_tokens] projection can
have the same shapes and strides as the packed-head layouts expected
by these paths. The resulting reshape places tokens on the wrong axis.
Apply the head splits only when the decoder's dynamic dimension is
not dimension 1. Add get_view_input_dynamic_dim() to expose this
information.
* openvino: keep one-token models apart in the compiled model cache
* docs : reorganize OpenVINO developer docs
* openvino: pin the ubuntu24 archive in the build cache job
* openvino: name the ubuntu24 flavor in the OpenVINO cache key
* docs : stop the Ubuntu build script on unsupported versions
---------
Co-authored-by: Yu, Zijun <zijun.yu@intel.com>
Co-authored-by: yzhou51 <yaowei.zhou@intel.com>
Co-authored-by: Suhas Somashekar <suhas.somashekar@intel.com>
Co-authored-by: Anisha Kulkarni <anisha.dattatraya.kulkarni@intel.com>
Co-authored-by: Sabnis, Omkar <omkar.sabnis@intel.com>
diff --git a/.devops/openvino.Dockerfile b/.devops/openvino.Dockerfile
index be2891742..2ecdab5d4 100644
--- a/.devops/openvino.Dockerfile
+++ b/.devops/openvino.Dockerfile
@@ -1,18 +1,17 @@
-ARG OPENVINO_VERSION_MAJOR=2026.4.1
-ARG OPENVINO_VERSION_FULL=2026.4.1.22982.07f9c262b05
-ARG UBUNTU_VERSION=24.04
+ARG OPENVINO_VERSION_MAJOR=2026.5
+ARG OPENVINO_VERSION_FULL=2026.5.0.23836.73088206582
+ARG UBUNTU_VERSION=26.04
# Intel GPU driver versions. https://github.com/intel/compute-runtime/releases
-ARG IGC_VERSION=v2.42.6
-ARG IGC_VERSION_FULL=2_2.42.6+23070
-ARG COMPUTE_RUNTIME_VERSION=26.40.40196.8
-ARG COMPUTE_RUNTIME_VERSION_FULL=26.40.40196.8-0
+ARG IGC_VERSION=v2.43.9
+ARG IGC_VERSION_FULL=2_2.43.9+23453
+ARG COMPUTE_RUNTIME_VERSION=26.44.40734.8
+ARG COMPUTE_RUNTIME_VERSION_FULL=26.44.40734.8-0
ARG IGDGMM_VERSION=22.10.2
# Intel NPU driver versions. https://github.com/intel/linux-npu-driver/releases
-ARG NPU_DRIVER_VERSION=v1.38.0
-ARG NPU_DRIVER_FULL=v1.38.0.20260910-34487311128
-ARG LIBZE1_VERSION=1.32.0-1~24.04~ppa1
+ARG NPU_DRIVER_VERSION=v1.39.1
+ARG NPU_DRIVER_FULL=v1.39.1.20261119-44517102376
# Optional proxy build arguments
ARG http_proxy=
@@ -69,17 +68,17 @@ RUN apt-get update && \
rm -rf /var/lib/apt/lists/*
# OpenVINO toolkit and GPU/NPU drivers are cached via BuildKit cache mounts to avoid re-downloading on rebuilds.
-# Install OpenVINO for Ubuntu 24.04.
+# Install OpenVINO for Ubuntu 26.04.
ARG OPENVINO_VERSION_MAJOR
ARG OPENVINO_VERSION_FULL
RUN --mount=type=cache,target=/var/cache/openvino,sharing=locked \
mkdir -p /opt/intel && \
- TGZ=/var/cache/openvino/openvino_toolkit_ubuntu24_${OPENVINO_VERSION_FULL}_x86_64.tgz && \
+ TGZ=/var/cache/openvino/openvino_toolkit_ubuntu26_${OPENVINO_VERSION_FULL}_x86_64.tgz && \
if [ ! -f "$TGZ" ]; then \
- wget -O "$TGZ" https://storage.openvinotoolkit.org/repositories/openvino/packages/${OPENVINO_VERSION_MAJOR}/linux/openvino_toolkit_ubuntu24_${OPENVINO_VERSION_FULL}_x86_64.tgz; \
+ wget -O "$TGZ" https://storage.openvinotoolkit.org/repositories/openvino/packages/${OPENVINO_VERSION_MAJOR}/linux/openvino_toolkit_ubuntu26_${OPENVINO_VERSION_FULL}_x86_64.tgz; \
fi && \
tar -xf "$TGZ" -C /opt/intel/ && \
- mv /opt/intel/openvino_toolkit_ubuntu24_${OPENVINO_VERSION_FULL}_x86_64 /opt/intel/openvino_${OPENVINO_VERSION_MAJOR} && \
+ mv /opt/intel/openvino_toolkit_ubuntu26_${OPENVINO_VERSION_FULL}_x86_64 /opt/intel/openvino_${OPENVINO_VERSION_MAJOR} && \
cd /opt/intel/openvino_${OPENVINO_VERSION_MAJOR} && \
echo "Y" | ./install_dependencies/install_openvino_dependencies.sh && \
cd - && \
@@ -172,20 +171,15 @@ RUN --mount=type=cache,target=/var/cache/intel-gpu,sharing=locked \
# Install NPU drivers
ARG NPU_DRIVER_VERSION
ARG NPU_DRIVER_FULL
-ARG LIBZE1_VERSION
RUN --mount=type=cache,target=/var/cache/intel-npu,sharing=locked \
set -eux; \
- TGZ=/var/cache/intel-npu/linux-npu-driver-${NPU_DRIVER_FULL}-ubuntu2404.tar.gz; \
+ TGZ=/var/cache/intel-npu/linux-npu-driver-${NPU_DRIVER_FULL}-ubuntu2604.tar.gz; \
if [ ! -f "$TGZ" ]; then \
- wget -q -O "$TGZ" https://github.com/intel/linux-npu-driver/releases/download/${NPU_DRIVER_VERSION}/linux-npu-driver-${NPU_DRIVER_FULL}-ubuntu2404.tar.gz; \
+ wget -q -O "$TGZ" https://github.com/intel/linux-npu-driver/releases/download/${NPU_DRIVER_VERSION}/linux-npu-driver-${NPU_DRIVER_FULL}-ubuntu2604.tar.gz; \
fi; \
- DEB=/var/cache/intel-npu/libze1_${LIBZE1_VERSION}_amd64.deb; \
- if [ ! -f "$DEB" ]; then \
- wget -q -O "$DEB" https://snapshot.ppa.launchpadcontent.net/kobuk-team/intel-graphics/ubuntu/20260830T100000Z/pool/main/l/level-zero-loader/libze1_${LIBZE1_VERSION}_amd64.deb; \
- fi; \
- mkdir /tmp/npu/ && cd /tmp/npu/ && tar -xf "$TGZ" && cp "$DEB" .; \
+ mkdir /tmp/npu/ && cd /tmp/npu/ && tar -xf "$TGZ"; \
apt-get update; \
- apt-get install -y --no-install-recommends ./*.deb; \
+ apt-get install -y --no-install-recommends ./*.deb libze1; \
rm -rf /tmp/npu/ /var/lib/apt/lists/*
COPY --from=build /app/lib/ /app/
diff --git a/.github/actions/linux-setup-openvino/action.yml b/.github/actions/linux-setup-openvino/action.yml
index 46a659a82..28985eab7 100644
--- a/.github/actions/linux-setup-openvino/action.yml
+++ b/.github/actions/linux-setup-openvino/action.yml
@@ -10,6 +10,10 @@ inputs:
version_full:
description: "OpenVINO full version (e.g., 2025.3.0.19807.44526285f24)"
required: true
+ ubuntu_version:
+ description: "Ubuntu major version of the OpenVINO archive (e.g., 24)"
+ required: false
+ default: "24"
runs:
using: "composite"
@@ -18,7 +22,7 @@ runs:
id: setup
uses: ./.github/actions/unarchive-tar
with:
- url: https://storage.openvinotoolkit.org/repositories/openvino/packages/${{ inputs.version_major }}/linux/openvino_toolkit_ubuntu24_${{ inputs.version_full }}_x86_64.tgz
+ url: https://storage.openvinotoolkit.org/repositories/openvino/packages/${{ inputs.version_major }}/linux/openvino_toolkit_ubuntu${{ inputs.ubuntu_version }}_${{ inputs.version_full }}_x86_64.tgz
path: ${{ inputs.path }}
type: z
strip: 1
diff --git a/.github/workflows/build-cache.yml b/.github/workflows/build-cache.yml
index 6de8138b2..ab02b25a4 100644
--- a/.github/workflows/build-cache.yml
+++ b/.github/workflows/build-cache.yml
@@ -45,8 +45,8 @@ jobs:
env:
# Sync versions in build-openvino.yml, ci-self-hosted-openvino.yml, release.yml, release-publish.yml, build-cache.yml, .devops/openvino.Dockerfile, docs/backend/OPENVINO.md
- OPENVINO_VERSION_MAJOR: "2026.4.1"
- OPENVINO_VERSION_FULL: "2026.4.1.22982.07f9c262b05"
+ OPENVINO_VERSION_MAJOR: "2026.5"
+ OPENVINO_VERSION_FULL: "2026.5.0.23836.73088206582"
steps:
- name: Clone
@@ -58,7 +58,7 @@ jobs:
id: cache-openvino
with:
path: ./openvino_toolkit
- key: cache-gha-openvino-toolkit-v${{ env.OPENVINO_VERSION_FULL }}-${{ runner.os }}
+ key: cache-gha-openvino-toolkit-ubuntu24-v${{ env.OPENVINO_VERSION_FULL }}-${{ runner.os }}
- name: Setup OpenVINO Toolkit
if: steps.cache-openvino.outputs.cache-hit != 'true'
@@ -67,14 +67,16 @@ jobs:
path: ./openvino_toolkit
version_major: ${{ env.OPENVINO_VERSION_MAJOR }}
version_full: ${{ env.OPENVINO_VERSION_FULL }}
+ # Ubuntu 24.04 archive: the OpenVINO job in release.yml runs on ubuntu-24.04 and reads this cache
+ ubuntu_version: "24"
windows-2022-openvino-cache:
runs-on: windows-2022
env:
# Sync versions in build-openvino.yml, ci-self-hosted-openvino.yml, release.yml, release-publish.yml, build-cache.yml, .devops/openvino.Dockerfile, docs/backend/OPENVINO.md
- OPENVINO_VERSION_MAJOR: "2026.4.1"
- OPENVINO_VERSION_FULL: "2026.4.1.22982.07f9c262b05"
+ OPENVINO_VERSION_MAJOR: "2026.5"
+ OPENVINO_VERSION_FULL: "2026.5.0.23836.73088206582"
steps:
- name: Clone
diff --git a/.github/workflows/build-openvino.yml b/.github/workflows/build-openvino.yml
index 9e092b52b..87bc82518 100644
--- a/.github/workflows/build-openvino.yml
+++ b/.github/workflows/build-openvino.yml
@@ -50,8 +50,8 @@ jobs:
env:
# Sync versions in build-openvino.yml, ci-self-hosted-openvino.yml, release.yml, release-publish.yml, build-cache.yml, .devops/openvino.Dockerfile, docs/backend/OPENVINO.md
- OPENVINO_VERSION_MAJOR: "2026.4.1"
- OPENVINO_VERSION_FULL: "2026.4.1.22982.07f9c262b05"
+ OPENVINO_VERSION_MAJOR: "2026.5"
+ OPENVINO_VERSION_FULL: "2026.5.0.23836.73088206582"
steps:
- name: Clone
diff --git a/.github/workflows/ci-self-hosted-openvino.yml b/.github/workflows/ci-self-hosted-openvino.yml
index f2df28a42..7ec8e17e9 100644
--- a/.github/workflows/ci-self-hosted-openvino.yml
+++ b/.github/workflows/ci-self-hosted-openvino.yml
@@ -49,12 +49,13 @@ env:
jobs:
gpu-openvino-low-perf:
- runs-on: [self-hosted, Linux, Intel, OpenVINO]
+ runs-on: [self-hosted, Linux, OpenVINO, PTL]
+ timeout-minutes: 120
env:
# Sync versions in build-openvino.yml, ci-self-hosted-openvino.yml, release.yml, release-publish.yml, build-cache.yml, .devops/openvino.Dockerfile, docs/backend/OPENVINO.md
- OPENVINO_VERSION_MAJOR: "2026.4.1"
- OPENVINO_VERSION_FULL: "2026.4.1.22982.07f9c262b05"
+ OPENVINO_VERSION_MAJOR: "2026.5"
+ OPENVINO_VERSION_FULL: "2026.5.0.23836.73088206582"
steps:
- name: Clone
@@ -67,6 +68,7 @@ jobs:
path: ./openvino_toolkit
version_major: ${{ env.OPENVINO_VERSION_MAJOR }}
version_full: ${{ env.OPENVINO_VERSION_FULL }}
+ ubuntu_version: "26"
- name: Install OpenVINO dependencies
run: |
diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml
index 3efa82e44..ad670ead1 100644
--- a/.github/workflows/release-publish.yml
+++ b/.github/workflows/release-publish.yml
@@ -180,7 +180,7 @@ jobs:
- [Ubuntu x64 (CUDA 13)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-ubuntu-cuda-13.5-x64.tar.gz) - [CUDA 13.5 libraries](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/cudart-llama-${{ steps.tag.outputs.name }}-bin-ubuntu-cuda-13.5-x64.tar.gz)
- [Ubuntu arm64 (CUDA 13)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-ubuntu-cuda-13.5-arm64.tar.gz) - [CUDA 13.5 libraries](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/cudart-llama-${{ steps.tag.outputs.name }}-bin-ubuntu-cuda-13.5-arm64.tar.gz)
- [Ubuntu x64 (ROCm 10.0)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-ubuntu-rocm-10.0-x64.tar.gz)
- - [Ubuntu x64 (OpenVINO)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-ubuntu-openvino-2026.4.1-x64.tar.gz)
+ - [Ubuntu x64 (OpenVINO)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-ubuntu-openvino-2026.5-x64.tar.gz)
- [Ubuntu x64 (SYCL FP32)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-ubuntu-sycl-fp32-x64.tar.gz)
- [Ubuntu x64 (SYCL FP16)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-ubuntu-sycl-fp16-x64.tar.gz)
- [Linux arm64 (Snapdragon: CPU, Adreno GPU, Hexagon NPU)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-linux-arm64-snapdragon.tar.gz) - [setup guide](https://github.com/ggml-org/llama.cpp/blob/master/docs/backend/snapdragon/linux.md)
@@ -198,7 +198,7 @@ jobs:
- [Windows arm64 (CUDA 13)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-win-cuda-13.5-arm64.zip) - [CUDA 13.5 DLLs](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/cudart-llama-bin-win-cuda-13.5-arm64.zip)
- [Windows x64 (Vulkan)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-win-vulkan-x64.zip)
- [Windows arm64 (Vulkan)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-win-vulkan-arm64.zip)
- - [Windows x64 (OpenVINO)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-win-openvino-2026.4.1-x64.zip)
+ - [Windows x64 (OpenVINO)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-win-openvino-2026.5-x64.zip)
- [Windows x64 (SYCL)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-win-sycl-x64.zip)
- [Windows x64 (ROCm 10.0)](https://github.com/ggml-org/llama.cpp/releases/download/${{ steps.tag.outputs.name }}/llama-${{ steps.tag.outputs.name }}-bin-win-rocm-10.0-x64.zip)
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 11c97ea2c..1f45ed967 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -658,8 +658,8 @@ jobs:
env:
# Sync versions in build-openvino.yml, ci-self-hosted-openvino.yml, release.yml, release-publish.yml, build-cache.yml, .devops/openvino.Dockerfile, docs/backend/OPENVINO.md
- OPENVINO_VERSION_MAJOR: "2026.4.1"
- OPENVINO_VERSION_FULL: "2026.4.1.22982.07f9c262b05"
+ OPENVINO_VERSION_MAJOR: "2026.5"
+ OPENVINO_VERSION_FULL: "2026.5.0.23836.73088206582"
steps:
- name: Clone
@@ -691,7 +691,7 @@ jobs:
id: cache-openvino
with:
path: ./openvino_toolkit
- key: cache-gha-openvino-toolkit-v${{ env.OPENVINO_VERSION_FULL }}-${{ runner.os }}
+ key: cache-gha-openvino-toolkit-ubuntu24-v${{ env.OPENVINO_VERSION_FULL }}-${{ runner.os }}
- name: Setup OpenVINO Toolkit
if: steps.cache-openvino.outputs.cache-hit != 'true'
@@ -700,6 +700,7 @@ jobs:
path: ./openvino_toolkit
version_major: ${{ env.OPENVINO_VERSION_MAJOR }}
version_full: ${{ env.OPENVINO_VERSION_FULL }}
+ ubuntu_version: "24"
- name: Install OpenVINO dependencies
run: |
@@ -767,8 +768,8 @@ jobs:
env:
# Sync versions in build-openvino.yml, ci-self-hosted-openvino.yml, release.yml, release-publish.yml, build-cache.yml, .devops/openvino.Dockerfile, docs/backend/OPENVINO.md
- OPENVINO_VERSION_MAJOR: "2026.4.1"
- OPENVINO_VERSION_FULL: "2026.4.1.22982.07f9c262b05"
+ OPENVINO_VERSION_MAJOR: "2026.5"
+ OPENVINO_VERSION_FULL: "2026.5.0.23836.73088206582"
steps:
- name: Clone
diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md
index f645f25d3..0449a5d3a 100644
--- a/docs/backend/OPENVINO.md
+++ b/docs/backend/OPENVINO.md
@@ -64,7 +64,7 @@ export GGML_OPENVINO_DEVICE=GPU
./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
```
-The [Ubuntu Build Script](#ubuntu-build-script) and the [Windows Build Script](#windows-build-script) do the setup in one step: they install the prerequisites and the OpenVINO Runtime, and build llama.cpp with the OpenVINO backend.
+The [Ubuntu Build Script](#ubuntu-build-script) and the [Windows Build Script](#windows-build-script) do the setup in one step: they install the build prerequisites and the OpenVINO Runtime, and build llama.cpp with the OpenVINO backend. They do not install the GPU and NPU drivers (the Ubuntu script installs only the `intel-opencl-icd` package of the distribution); see [Prerequisites](#0-prerequisites).
See [Build Instructions](#build-instructions) for Windows and Docker, and [Runtime Configuration](#runtime-configuration) for the environment variables.
@@ -86,7 +86,7 @@ Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvin
- `Q4_0`
- `Q4_1`
- `Q4_K`
-- `Q5_0` (converted at runtime, see the details below)
+- `Q5_0`
- `Q5_1`
- `Q5_K` (converted at runtime, see the details below)
- `Q6_K` (converted at runtime, see the details below)
@@ -101,26 +101,28 @@ Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvin
- A quantized token embedding (`token_embd.weight`) and output weight (`output.weight`) are converted to `Q8_0_C`.
**CPU and GPU:**
-- `Q4_0`, `Q4_1`, `Q4_K`, `Q5_1` and `Q8_0` tensors keep their layout: weights, scales and zero points are extracted directly.
+- `Q4_0`, `Q4_1`, `Q4_K`, `Q5_0`, `Q5_1` and `Q8_0` tensors keep their layout: weights, scales and zero points are extracted directly.
- `Q5_K` and `Q6_K` tensors are converted to `Q8_0_C`. `GGML_OPENVINO_REQUANT_KQUANT` selects a 4-bit layout instead.
-- `Q5_0` tensors are converted to `Q4_0_64`.
**GPU:**
-- `Q4_K`, `Q5_K` and `Q6_K` MoE expert tensors are converted to `Q4_1_64`. This lets the GPU plugin use its fused MoE op, which is much faster for prompt processing. `GGML_OPENVINO_REQUANT_KQUANT` does not change this. `GGML_OPENVINO_MOE_OP=0` turns the fused MoE op off.
+- `Q4_K`, `Q5_K` and `Q6_K` MoE expert tensors, and `Q4_0` ones whose row width is a multiple of 64, are converted to `Q4_1_64`. This lets the GPU plugin use its fused MoE op, which is much faster for prompt processing. `GGML_OPENVINO_REQUANT_KQUANT` does not change this. `GGML_OPENVINO_MOE_OP=0` turns the fused MoE op off.
+- `Q5_0`, `Q5_1` and `Q8_0` MoE expert tensors are converted to `Q4_0_64` (`Q8_0_C` when the row width is not a multiple of 64). This works around a GPU plugin defect with grouped 8-bit expert weights. `GGML_OPENVINO_REQUANT_KQUANT=native` keeps them at 8 bits.
**NPU:**
-- All other quantized tensors are requantized to `Q4_0_128`.
+- All other quantized tensors are requantized to `Q4_0_128`, or to `Q4_0_C` when the row width is not a multiple of 128.
- For a `Q6_K` token embedding, `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout. When it is set, it also applies to a `Q4_K` or `Q5_K` token embedding.
- The validated models use `Q4_K_M` files.
**Layout names:**
- `Q8_0_C`: 8-bit, one scale per row.
- `Q4_0_128` and `Q4_0_64`: 4-bit, symmetric, one scale per 128 or 64 weights.
+- `Q4_0_C`: 4-bit, symmetric, one scale per row.
+- `Q4_1_64`: 4-bit, asymmetric, one scale and one zero point per 64 weights.
**Additional Notes:**
-- Both `Q4_0` and `Q4_1` models use `Q6_K` for the token embedding tensor and the final matmul weight tensor (often the same tensor)
-- `Q4_0` models may produce some `Q4_1` tensors if an imatrix is provided during quantization using `llama-quantize`
-- `Q4_K_M` models may include both `Q6_K` and `Q5_K` tensors (observed in Phi-3)
+- `Q4_0` and `Q4_1` models use `Q6_K` for the output weight, and for the token embedding only when it is the same tensor as the output weight.
+- `Q4_0` models may produce some `Q4_1` tensors if an imatrix is provided during quantization using `llama-quantize`.
+- `Q4_K_M` models may include both `Q6_K` and `Q5_K` tensors (observed in Phi-3).
</details>
@@ -138,12 +140,12 @@ The OpenVINO backend works with the standard llama.cpp tools listed below. Tool
## Validated Models
-The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® Core™ Ultra Series 2 (Lunar Lake). The OpenVINO backend is expected to work on a broader range of [Intel hardware](https://docs.openvino.ai/2026/about-openvino/release-notes-openvino/system-requirements.html), [model precisions](#supported-model-precisions), [llama.cpp tools](#supported-llamacpp-tools) and model architectures.
+The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® Core™ Ultra Series 3 (Panther Lake). The OpenVINO backend is expected to work on a broader range of [Intel hardware](https://docs.openvino.ai/2026/about-openvino/release-notes-openvino/system-requirements.html), [model precisions](#supported-model-precisions), [llama.cpp tools](#supported-llamacpp-tools) and model architectures.
**Legend & Test Configuration:**
- **Status:** ✓ = Passed | ~ = Accuracy issues | ✗ = Failed or Unsupported
- **Execution mode:** stateless (`GGML_OPENVINO_STATEFUL_EXECUTION=0`) on every device.
-- **Validation system:** Intel® Core™ Ultra 7 258V (Lunar Lake) | 32 GB RAM | Ubuntu 26.04.1 | Intel Graphics Compiler 2.42.6 | Intel OpenCL GPU Driver 26.40.40196.8-0 | Intel NPU Driver 1.38.0.
+- **Validation system:** Intel® Core™ Ultra X7 358H (Panther Lake) | 64 GB RAM | Ubuntu 26.04.1 | Intel Graphics Compiler 2.43.9 | Intel OpenCL GPU Driver 26.44.40734.8-0 | Intel NPU Driver 1.39.1.
- See [Known Limitations](#known-limitations) for context on observed failures.
<details open>
@@ -161,6 +163,7 @@ The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® C
| [bartowski/Qwen_Qwen3-1.7B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3-1.7B-GGUF) | ✓ | ✓ | ✓ |
| [Qwen/Qwen3-4B-Q4_K_M](https://huggingface.co/Qwen/Qwen3-4B-GGUF) | ✓ | ✓ | ✓ |
| [lm-kit/Qwen3-8B-Q4_K_M](https://huggingface.co/lm-kit/qwen-3-8b-instruct-gguf) | ✓ | ✓ | ✓ |
+| [unsloth/Qwen3-VL-4B-Instruct-Q4_K_M](https://huggingface.co/unsloth/Qwen3-VL-4B-Instruct-GGUF) | ✓ | ✓ | ✓ |
| [bartowski/Qwen_Qwen3.5-0.8B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-0.8B-GGUF) | ✓ | ✓ | ✓ |
| [bartowski/Qwen_Qwen3.5-2B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-2B-GGUF) | ✓ | ✓ | ✓ |
| [bartowski/Qwen_Qwen3.5-4B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-4B-GGUF) | ✓ | ✓ | ✓ |
@@ -169,7 +172,7 @@ The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® C
| [unsloth/gemma-3-4b-it-Q4_K_M](https://huggingface.co/unsloth/gemma-3-4b-it-GGUF) | ✓ | ✓ | ✓ |
| [bartowski/google_gemma-4-E2B-it-Q4_K_M](https://huggingface.co/bartowski/google_gemma-4-E2B-it-GGUF) | ✓ | ✓ | ✓ |
| [bartowski/google_gemma-4-E4B-it-Q4_K_M](https://huggingface.co/bartowski/google_gemma-4-E4B-it-GGUF) | ✓ | ✓ | ✓ |
-| [bartowski/gemma-4-12B-it-Q4_K_M](https://huggingface.co/bartowski/gemma-4-12B-it-GGUF) | ✓ | ✓ | ✗ |
+| [bartowski/gemma-4-12B-it-Q4_K_M](https://huggingface.co/bartowski/gemma-4-12B-it-GGUF) | ✓ | ✓ | ✓ |
| | | | |
| [bartowski/Phi-3-mini-4k-instruct-Q4_K_M](https://huggingface.co/bartowski/Phi-3-mini-4k-instruct-GGUF) | ✓ | ✓ | ✓ |
| [bartowski/Phi-3.5-mini-instruct-Q4_K_M](https://huggingface.co/bartowski/Phi-3.5-mini-instruct-GGUF) | ✓ | ✓ | ✓ |
@@ -184,7 +187,7 @@ The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® C
| | | | |
| [ibm-granite/granite-4.0-350m-Q4_K_M](https://huggingface.co/ibm-granite/granite-4.0-350m-GGUF) | ✓ | ✓ | ✓ |
| [ibm-granite/granite-4.0-micro-Q4_K_M](https://huggingface.co/ibm-granite/granite-4.0-micro-GGUF) | ✓ | ✓ | ✓ |
-| [ibm-granite/granite-4.0-1b-Q4_K_M](https://huggingface.co/ibm-granite/granite-4.0-1b-GGUF) | ✓ | ✓ | ~ |
+| [ibm-granite/granite-4.0-1b-Q4_K_M](https://huggingface.co/ibm-granite/granite-4.0-1b-GGUF) | ✓ | ✓ | ✓ |
| [ibm-research/granite-3.2-8b-instruct-Q4_K_M](https://huggingface.co/ibm-research/granite-3.2-8b-instruct-GGUF) | ✓ | ✓ | ✓ |
| | | | |
| [HuggingFaceTB/smollm2-1.7b-instruct-q4_k_m](https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct-GGUF) | ✓ | ✓ | ✓ |
@@ -193,7 +196,7 @@ The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® C
| [bartowski/tencent_Hunyuan-7B-Instruct-Q4_K_M](https://huggingface.co/bartowski/tencent_Hunyuan-7B-Instruct-GGUF) | ✓ | ✓ | ✓ |
| [LGAI-EXAONE/EXAONE-3.5-7.8B-Instruct-Q4_K_M](https://huggingface.co/LGAI-EXAONE/EXAONE-3.5-7.8B-Instruct-GGUF) | ✓ | ✓ | ✓ |
| [bartowski/prism-ml_Bonsai-8B-unpacked-Q4_K_M](https://huggingface.co/bartowski/prism-ml_Bonsai-8B-unpacked-GGUF) | ✓ | ✓ | ✓ |
-| [LiquidAI/LFM2.5-2.6B-Q4_K_M](https://huggingface.co/LiquidAI/LFM2.5-2.6B-GGUF) | ✓ | ✓ | ✗ |
+| [LiquidAI/LFM2.5-2.6B-Q4_K_M](https://huggingface.co/LiquidAI/LFM2.5-2.6B-GGUF) | ✓ | ✓ | ✓ |
| [bartowski/inclusionAI_Ling-mini-2.0-Q4_K_M](https://huggingface.co/bartowski/inclusionAI_Ling-mini-2.0-GGUF) | ✓ | ✓ | ✗ |
| [tiiuae/Falcon-H1-0.5B-Instruct-Q4_K_M](https://huggingface.co/tiiuae/Falcon-H1-0.5B-Instruct-GGUF) | ✓ | ✓ | ✗ |
| | | | |
@@ -219,7 +222,7 @@ Build tools (Git, CMake, Ninja):
```bash
sudo apt-get update
-sudo apt-get install -y build-essential libcurl4-openssl-dev libtbb12 cmake ninja-build python3-pip curl wget tar
+sudo apt-get install -y build-essential libcurl4-openssl-dev libssl-dev libtbb12 cmake ninja-build python3-pip curl wget tar git
```
OpenCL:
@@ -284,6 +287,8 @@ cmake -B build/ReleaseOV -G Ninja -DCMAKE_BUILD_TYPE=Release -DGGML_OPENVINO=ON
cmake --build build/ReleaseOV --parallel
```
+Adjust the `setupvars.sh` path to the directory where OpenVINO Runtime is installed. The Ubuntu build script below installs it to `/opt/intel/openvino`.
+
<details>
<summary><b>Build on Windows</b></summary>
@@ -320,21 +325,27 @@ chmod +x build-llamacpp-ov.sh
# ============================================
set -euo pipefail
-OPENVINO_VERSION_MAJOR="2026.4.1"
-OPENVINO_VERSION_FULL="2026.4.1.22982.07f9c262b05"
+OPENVINO_VERSION_MAJOR="2026.5"
+OPENVINO_VERSION_FULL="2026.5.0.23836.73088206582"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OPENVINO_INSTALL_DIR="/opt/intel/openvino_${OPENVINO_VERSION_MAJOR}"
OPENVINO_LINK_DIR="/opt/intel/openvino"
OPENVINO_TGZ="${SCRIPT_DIR}/openvino.tgz"
-OPENVINO_URL="https://storage.openvinotoolkit.org/repositories/openvino/packages/${OPENVINO_VERSION_MAJOR}/linux/openvino_toolkit_ubuntu24_${OPENVINO_VERSION_FULL}_x86_64.tgz"
+UBUNTU_MAJOR="$(. /etc/os-release && echo "${VERSION_ID%%.*}")" # 22, 24 or 26
+OPENVINO_URL="https://storage.openvinotoolkit.org/repositories/openvino/packages/${OPENVINO_VERSION_MAJOR}/linux/openvino_toolkit_ubuntu${UBUNTU_MAJOR}_${OPENVINO_VERSION_FULL}_x86_64.tgz"
+
+case "${UBUNTU_MAJOR}" in
+ 22|24|26) ;;
+ *) echo "Unsupported Ubuntu version ${UBUNTU_MAJOR}: OpenVINO archives exist for Ubuntu 22, 24 and 26." >&2; exit 1 ;;
+esac
echo "============================================"
echo "Installing prerequisites (apt)..."
echo "============================================"
sudo apt-get update
sudo apt-get install -y \
- build-essential libcurl4-openssl-dev libtbb12 \
+ build-essential libcurl4-openssl-dev libssl-dev libtbb12 \
cmake ninja-build python3-pip \
curl wget tar git
@@ -362,7 +373,7 @@ if [[ -f "${OPENVINO_INSTALL_DIR}/setupvars.sh" ]]; then
echo "OpenVINO ${OPENVINO_VERSION_MAJOR} already installed at ${OPENVINO_INSTALL_DIR}. Skipping download."
else
echo "OpenVINO not found at ${OPENVINO_INSTALL_DIR}. Starting download..."
- curl -L -o "${OPENVINO_TGZ}" "${OPENVINO_URL}"
+ curl -fL -o "${OPENVINO_TGZ}" "${OPENVINO_URL}"
echo "Extracting OpenVINO to ${OPENVINO_INSTALL_DIR}..."
sudo mkdir -p "${OPENVINO_INSTALL_DIR}"
@@ -418,14 +429,14 @@ echo " ./build/ReleaseOV/bin/llama-cli -m model.gguf"
```
> [!NOTE]
-> The script pins OpenVINO `2026.4.1` via the `OPENVINO_VERSION_MAJOR` / `OPENVINO_VERSION_FULL` variables at the top — edit them to track a different release.
+> The script pins OpenVINO `2026.5` via the `OPENVINO_VERSION_MAJOR` / `OPENVINO_VERSION_FULL` variables at the top — edit them to track a different release.
</details>
#### Windows Build Script
For Windows users, the following `.bat` script automates the prerequisite installs (Git, Ninja, CMake, Visual Studio 2022 Build Tools, vcpkg + OpenCL), the OpenVINO Runtime download/extract, and the Ninja-based llama.cpp build.
-Save the following as `build-llamacpp-ov.bat` next to where you want the `llama.cpp` to land, then run it from either **Command Prompt** or **PowerShell**:
+Save the following as `build-llamacpp-ov.bat` next to where you want the `llama.cpp` folder to land, then run it from either **Command Prompt** or **PowerShell**:
```cmd
:: Command Prompt
@@ -448,8 +459,8 @@ REM ============================================
REM llama.cpp OpenVINO Build Script (Ninja)
REM ============================================
-set "OPENVINO_VERSION_MAJOR=2026.4.1"
-set "OPENVINO_VERSION_FULL=2026.4.1.22982.07f9c262b05"
+set "OPENVINO_VERSION_MAJOR=2026.5"
+set "OPENVINO_VERSION_FULL=2026.5.0.23836.73088206582"
set "SCRIPT_DIR=%~dp0"
set "VCPKG_DIR=C:\vcpkg"
@@ -575,7 +586,7 @@ echo ============================================
REM Locate Visual Studio Build Tools vcvars64.bat
set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"
if exist "%VSWHERE%" (
- for /f "usebackq tokens=*" %%i in (`"%VSWHERE%" -latest -products Microsoft.VisualStudio.Product.BuildTools -property installationPath`) do (
+ for /f "usebackq tokens=*" %%i in (`"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do (
set "VS_PATH=%%i"
)
)
@@ -620,7 +631,7 @@ echo Binaries: %CD%\build\ReleaseOV\bin
echo.
echo NOTE: To run, source setupvars.bat and pick a device:
echo call "C:\Intel\openvino\setupvars.bat"
-echo set GGML_OPENVINO_DEVICE=CPU ^&^& REM or GPU / NPU
+echo set GGML_OPENVINO_DEVICE=CPU^&^& REM or GPU / NPU
echo build\ReleaseOV\bin\llama-cli.exe -m model.gguf
echo.
@@ -628,7 +639,7 @@ endlocal
```
> [!NOTE]
-> The script pins OpenVINO `2026.4.1` via the `OPENVINO_VERSION_MAJOR` / `OPENVINO_VERSION_FULL` variables at the top — edit them to track a different release. From any new shell, source the matching `setupvars` script via the junction — `call "C:\Intel\openvino\setupvars.bat"` from `cmd`, or `& "C:\Intel\openvino\setupvars.ps1"` from PowerShell. If `winget` cannot register Visual Studio Build Tools on first run, install them once manually and re-run the script from an elevated **Developer Command Prompt for VS 2022**.
+> The script pins OpenVINO `2026.5` via the `OPENVINO_VERSION_MAJOR` / `OPENVINO_VERSION_FULL` variables at the top — edit them to track a different release. From any new shell, source the matching `setupvars` script via the junction — `call "C:\Intel\openvino\setupvars.bat"` from `cmd`, or `& "C:\Intel\openvino\setupvars.ps1"` from PowerShell. If `winget` cannot register Visual Studio Build Tools on first run, install them once manually and re-run the script from an elevated **Developer Command Prompt for VS 2022**.
</details>
@@ -676,7 +687,7 @@ export GGML_OPENVINO_DEVICE=GPU
# To run in chat mode:
./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
# To run llama-bench:
-GGML_OPENVINO_DEVICE=GPU ./build/ReleaseOV/bin/llama-bench -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
+./build/ReleaseOV/bin/llama-bench -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
# NPU: keep context small to avoid failures from very large model context windows.
export GGML_OPENVINO_DEVICE=NPU
@@ -715,7 +726,7 @@ build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.ggu
> [!NOTE]
> - Select the OpenVINO device with `GGML_OPENVINO_DEVICE`, not with `-dev`.
-> - On systems with multiple GPUs, use `GPU.0` or `GPU.1` to explicitly target specific GPU.
+> - On systems with multiple GPUs, use `GPU.0` or `GPU.1` to target a specific GPU.
> - To split a model across several GPUs, set a comma-separated list, e.g. `GPU.0,GPU.1`, and use `-sm layer`.
> - A device that is not available is an error (no fallback to CPU). The error message lists the available OpenVINO devices with their names.
> - Run `llama-cli --list-devices` to see the valid values: each OpenVINO device shows the `GGML_OPENVINO_DEVICE=<value>` to set, and `(selected)` marks the active one.
@@ -730,15 +741,15 @@ You can build and run llama.cpp with OpenVINO backend using Docker.
```bash
# Build the base runtime image with compiled shared libraries and minimal dependencies.
-docker build -t llama-openvino:base -f .devops/openvino.Dockerfile .
+docker build --target=base -t llama-openvino:base -f .devops/openvino.Dockerfile .
# Build the complete image with all binaries, Python tools, gguf-py library, and model conversion utilities.
docker build --target=full -t llama-openvino:full -f .devops/openvino.Dockerfile .
-# Build a minimal CLI-only image containing just the llama-cli executable.
+# Build a minimal CLI image with the llama, llama-cli and llama-completion executables.
docker build --target=light -t llama-openvino:light -f .devops/openvino.Dockerfile .
-# Builds a server-only image with llama-server executable, health check endpoint, and REST API support.
+# Build a server-only image with llama-server executable, health check endpoint, and REST API support.
docker build --target=server -t llama-openvino:server -f .devops/openvino.Dockerfile .
# If you are behind a proxy:
@@ -823,7 +834,7 @@ export GGML_OPENVINO_EXACT_ZERO_POINT=1 # Boolean: 1 (on) or 0 (off)
```
- The backend reads the variables once, at start. Unset or empty means the default.
-- To lower the memory a model needs, see [Tips for Memory Optimization](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#tips-for-memory-optimization).
+- To lower the memory a model needs, see [Memory optimization](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#memory-optimization).
- A value that is not valid stops the backend. A `GGML_OPENVINO_*` name that the backend does not know gives a warning:
```text
@@ -857,11 +868,15 @@ export GGML_OPENVINO_CPU_CONFIG="INFERENCE_PRECISION_HINT=f16"
```
- Property names and values are those of OpenVINO, for example `YES` and `NO`. They are not the `1` and `0` of the `GGML_OPENVINO_*` variables.
-- The backend applies the variable last, so it overrides the properties that the backend sets.
+- The backend applies the variable last, so it overrides the properties that the backend sets. Exception: `CACHE_DIR` and `CACHE_MODE` with `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`.
- OpenVINO checks the properties when the model loads. If it rejects one, the load fails and the error names the variable.
- All properties and their values are in the OpenVINO documentation: [NPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/npu-device.html), [GPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html), [CPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/cpu-device.html).
- NPU: the backend sets several properties by default. They are listed in the [developer documentation](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#npu-plugin-properties).
-- GPU and CPU: the backend sets no property, except `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE` when `GGML_OPENVINO_CACHE_DIR` is set.
+- GPU and CPU: the backend sets no property, except:
+ - `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE` when `GGML_OPENVINO_CACHE_DIR` is set.
+ - With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`: no `CACHE_DIR`, and `CACHE_MODE=OPTIMIZE_SPEED`. This overrides the same properties in `GGML_OPENVINO_GPU_CONFIG` and `GGML_OPENVINO_CPU_CONFIG`.
+ - `ENABLE_PROFILING` with `GGML_OPENVINO_PROFILING=2` or higher.
+ - `EXECUTION_MODE_HINT` on the small graphs of op tests.
`NPU_COMPILER_TYPE` selects the NPU compiler. Both forms below work; use the first one. If both are set, `GGML_OPENVINO_NPU_CONFIG` takes precedence.
@@ -883,12 +898,12 @@ The defaults fit most models. The variables below trade one property for another
|---|---|---|---|---|
| `GGML_OPENVINO_PREFILL_CHUNK_SIZE` | NPU | Integer | `256` | Number of tokens that the NPU processes in one prefill step. A larger value can make long prompts faster, and makes the first load longer. Zero or a negative value means the default. Example: `GGML_OPENVINO_PREFILL_CHUNK_SIZE=512`. |
| `GGML_OPENVINO_KV_ONLY_PREFILL` | NPU | Boolean | `1` | For models whose last layers reuse the KV cache of an earlier layer (Gemma 3n and Gemma 4 E2B/E4B): compile the prefill with only the KV-cache writes as outputs, which drops those layers and the output layer from it, and compute the output token of a batch with one decode step. Takes effect only without `GGML_OPENVINO_NPU_HFA_PREFILL`, and not for models with recurrent state; with decode KV windows (`GGML_OPENVINO_NPU_BLOB_PREBUILD=1`) the output step runs the decode graph of the window that covers the output token. A batch that needs more than one output token switches to the full prefill. `0` turns it off. |
-| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | How a `Q6_K` `token_embd.weight` is stored for the NPU: `q8_0_c` (8-bit, one scale per row), `f16`, `q4_0_128` (4-bit, one scale per 128 weights) or `q4_0_c` (4-bit, one scale per row). The 4-bit layouts use less memory at some cost in accuracy; `f16` uses more memory. Keep the default unless memory is tight. When set, it also applies to a `Q4_K` or `Q5_K` `token_embd.weight`, which otherwise keeps the 8-bit layout of the other weights; with a tied output layer (Gemma 4 E2B) `q4_0_128` stores it in about half the memory. |
+| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | How a `Q6_K` `token_embd.weight` is stored for the NPU: `q8_0_c` (8-bit, one scale per row), `f16`, `q4_0_128` (4-bit, one scale per 128 weights) or `q4_0_c` (4-bit, one scale per row). The 4-bit layouts use less memory at some cost in accuracy; `f16` uses more memory. Keep the default unless memory is tight. When set, it also applies to a `Q4_K` or `Q5_K` `token_embd.weight`, which is otherwise stored as `q8_0_c`; with a tied output layer (Gemma 4 E2B) `q4_0_128` stores it in about half the memory. On the Panther Lake NPU, `f16` and `q4_0_128` can give wrong output. |
| `GGML_OPENVINO_NPU_HOST_GATHER` | NPU | Boolean | `0` | Look up the rows of large embedding tables (64 MiB or more) on the host, from the GGUF data, and pass them to the NPU graph as an input, instead of binding the whole table to the NPU. A table used only for such lookups, such as the per-layer embedding table of Gemma 3n and Gemma 4 E2B/E4B, is then not converted for the NPU at all. Lowers memory and decode time for such models. |
-| `GGML_OPENVINO_GDN_DECOMPOSE` | all | Boolean | auto | Translate `GATED_DELTA_NET` (Qwen3.5) into MatMul operations instead of the OpenVINO `GatedDeltaNet` op. Unset: on for the Lunar Lake NPU, off elsewhere. `0` turns it off, `1` turns it on for any device. Try `1` for Qwen3.5 on the Panther Lake NPU. |
-| `GGML_OPENVINO_MANUAL_GQA_ATTN` | CPU, GPU | Boolean | on for GPU | Build grouped-query attention from separate MatMul operations. Unset: on for GPU, off for CPU and NPU. `1` turns it on, `0` turns it off. Try `1` on the CPU for faster decode. |
-| `GGML_OPENVINO_REQUANT_KQUANT` | CPU, GPU | String | `not set` | Requantize `Q6_K` and `Q5_K` weights to a 4-bit layout instead of `Q8_0_C`: faster decode for lower accuracy. One of `q4_asym64`, `q4_asym64_all` (also `Q4_K`), `q4_sym128`, `q4_sym128_all` (also `Q4_K`) or `native` (no requantization). On GPU with `Q4_K_M` files use `q4_asym64_all`, because `q4_asym64` does not compile there. |
-| `GGML_OPENVINO_EXACT_ZERO_POINT` | CPU, GPU | Boolean | `0` | Keep the exact zero point of asymmetric weights (`Q4_1`, `Q4_K`, `Q5_1`, `Q5_K`) instead of rounding it to an integer. This improves accuracy and lowers speed. Use it when accuracy matters more than speed. |
+| `GGML_OPENVINO_GDN_DECOMPOSE` | all | Boolean | auto | Translate `GATED_DELTA_NET` (Qwen3.5) into MatMul operations instead of the OpenVINO `GatedDeltaNet` op. Unset: on for the Lunar Lake NPU, off elsewhere. `0` turns it off, `1` turns it on. It takes effect only on the static path (NPU, or `GGML_OPENVINO_FORCE_STATIC=1`). Try `1` for Qwen3.5 on the Panther Lake NPU. |
+| `GGML_OPENVINO_MANUAL_GQA_ATTN` | all | Boolean | on for GPU | Build grouped-query attention from separate MatMul operations. Unset: on for GPU, off for CPU and NPU. `1` turns it on, `0` turns it off. Try `1` on the CPU for faster decode. |
+| `GGML_OPENVINO_REQUANT_KQUANT` | CPU, GPU | String | `not set` | Requantize `Q6_K` and `Q5_K` weights to a 4-bit layout instead of `Q8_0_C`: faster decode for lower accuracy. One of `q4_asym64`, `q4_asym64_all` (also `Q4_K`, `Q8_0`, `Q5_1` and `Q5_0`), `q4_sym128`, `q4_sym128_all` (also `Q4_K`) or `native` (no requantization). On GPU with `Q4_K_M` files use `q4_asym64_all`, because `q4_asym64` does not compile there. |
+| `GGML_OPENVINO_EXACT_ZERO_POINT` | CPU, GPU | Boolean | `0` | Keep the exact zero point of asymmetric weights (`Q4_1`, `Q4_K`, `Q5_1`, and `Q5_K` with `GGML_OPENVINO_REQUANT_KQUANT=native`) instead of rounding it to an integer. Requantized tensors keep an integer zero point; MoE expert weights always use the exact zero point. This improves accuracy and lowers speed. Use it when accuracy matters more than speed. |
</details>
@@ -920,13 +935,13 @@ export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
-| `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` | CPU, GPU | Boolean | `0` | Require an existing cached model and skip the weight upload and the compilation. Needs mmap model loading (the default on Linux and Windows) and a model that runs fully on OpenVINO. |
+| `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` | CPU, GPU | Boolean | `0` | Require an existing cached model and skip the weight upload and the compilation. Needs mmap model loading (the default on Linux and Windows) and a model that runs fully on OpenVINO. Does not work for MoE models on CPU, which are not written to the cache. |
| `GGML_OPENVINO_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` with an existing cache. Use the memory-mapped GGUF file as the model buffer, which lowers the host memory peak. Fails if a cached model is missing, for example after a change of the model, `-c` or another setting; run once without it to build the cache. |
| `GGML_OPENVINO_CACHE_DIR` | all | String | `not set` | Directory for the cache of the OpenVINO plugin itself. `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` is the recommended cache. |
- One directory can hold the cached models of different models and settings.
- NPU, with the default settings: the first prompt writes the prefill model of every KV window up to `-c`, so later runs with the same `-c` find a cached model for any prompt length.
-- See [Compiled model cache](../../ggml/src/ggml-openvino/README.md#compiled-model-cache) for the workflow and the restrictions.
+- See [Compiled model cache](../../ggml/src/ggml-openvino/dev_doc/README.md#compiled-model-cache) for the workflow and the restrictions.
</details>
@@ -942,7 +957,7 @@ export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
- CPU and GPU only; it has no effect on the NPU.
- One slot only (`-np 1`).
- State save and restore, sequence rewind, context shift and recurrent rollback are not supported.
-- Qwen3.5 needs a graph that runs fully on OpenVINO, with model caching on.
+- Models with recurrent state (for example Qwen3.5) need a graph that runs fully on OpenVINO, with the in-process cache on (`GGML_OPENVINO_DISABLE_CACHE` unset).
- A prompt that starts at position 0 resets all states.
</details>
@@ -988,11 +1003,16 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.
**General (all devices)**
-- Llama.cpp OpenVINO backend currently supports a subset of GGML ops and text-only models. Unsupported ops or unsupported op shapes/cases fail during OpenVINO translation.
-- Multimodal features (audio/image/video) are a work in progress.
+- Llama.cpp OpenVINO backend currently supports a subset of GGML ops. Unsupported ops or unsupported op shapes/cases fail during OpenVINO translation.
+- Image input is experimental: Qwen3.5 and Gemma 4 E2B image input runs on CPU and GPU. NPU: work in progress, image input fails because of dynamic shapes. See [Multimodal](../../ggml/src/ggml-openvino/dev_doc/README.md#multimodal). Audio input is a work in progress.
+- Qwen3-VL image input ([Multimodal](../../ggml/src/ggml-openvino/dev_doc/README.md#multimodal)):
+ - CPU: needs a 32 GB system (peak about 14 GB of RAM).
+ - GPU on a 16 GB system: the default `-ub 512` runs out of memory.
+ - **Workaround:** `-ub 128` or `--image-max-tokens 256`.
+ - NPU: work in progress.
- Embedding models: reranking models are not validated.
- Llama.cpp tool coverage across CPU/GPU/NPU is not uniform.
-- Mamba-based models (e.g. Falcon-H1): `llama-perplexity` with several sequences per batch fails; set `-b` to the same value as `-c`. GPU accuracy is slightly lower than CPU.
+- Mamba-based models (e.g. Falcon-H1): `llama-perplexity` with several sequences per batch fails; set `-b` to the same value as `-c`. On CPU and GPU, the perplexity is slightly higher than with the ggml CPU backend.
**GPU-specific**
@@ -1028,13 +1048,39 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.
- Mamba-based models (e.g. Falcon-H1) fail on the NPU with `Failed to set tensor` (element type mismatch).
- Lunar Lake NPU: decode slows down sharply when the context is large. The context size at which this starts depends on the model.
- **Workaround:** Pass the smallest context that fits the use, e.g. `-c 512`, or `-c 256` for larger models.
-- Panther Lake NPU: the load of a Qwen3.5 model can end with a segmentation fault in the NPU compiler of OpenVINO 2026.4.1.
- - **Workaround:** Set `GGML_OPENVINO_NPU_CONFIG=COMPILATION_NUM_THREADS=1`.
- Panther Lake NPU: `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=f16` and `q4_0_128` can give wrong output. Keep the default.
- Lunar Lake NPU: `granite-4.0-1b` gives wrong output. The activations of the model exceed the FP16 range, and the NPU computes in FP16. The model runs correctly on CPU and GPU.
- Lunar Lake NPU: `gemma-4-12B` does not run. The first inference fails with `ZE_RESULT_ERROR_UNINITIALIZED` from the NPU driver. The model runs on CPU and GPU.
+- Lunar Lake NPU with NPU driver 1.39.1: `gemma-4-E2B` and `gemma-4-E4B` do not run. The compilation in the NPU driver fails with `ZE_RESULT_ERROR_INVALID_ARGUMENT`. NPU driver 1.38.0 runs them, and the models run on CPU and GPU. The Docker image installs NPU driver 1.39.1.
+ - **Workaround:** Use NPU driver 1.38.0.
- The first load of a model on the NPU compiles it for the device, which can take minutes for large models.
- **Workaround:** Use the [compiled model cache](#compiled-model-cache).
+- `Ling-mini-2.0` (MoE with a sigmoid router) does not run on the NPU. The compilation in the NPU driver fails with `Cannot create GatherMatmul layer ... from unsupported opset`. The model runs on CPU and GPU.
+- MoE models with a softmax router and SwiGLU experts (for example Qwen3.6-35B-A3B) run on the NPU through the MoE support of NPUW: only the routed experts run for each token, with the router on the host. Tested with `Qwen3.6-35B-A3B-Q4_0` on Panther Lake (Windows) and Lunar Lake (Windows, Ubuntu) systems with 32 GB.
+ - Requires OpenVINO 2026.5 or later. These models depend on two NPUW changes that 2026.4.1 does not have, [#38123](https://github.com/openvinotoolkit/openvino/pull/38123) (MoE mixing scores) and [#38124](https://github.com/openvinotoolkit/openvino/pull/38124) (batched MoE matching). With 2026.4.1 the model runs without an error, but the output is wrong.
+ - A 35B MoE model needs nearly all of a 32 GB system: the backend and NPUW each hold a copy of the weights (about 18 GB each), and the NPU can address 18 GB of the shared memory. Use a small context and these settings:
+
+ ```bash
+ export GGML_OPENVINO_DEVICE=NPU
+ export GGML_OPENVINO_PREFILL_CHUNK_SIZE=128
+ export GGML_OPENVINO_NPU_CONFIG="NPUW_WEIGHTS_BANK_ALLOC=CPU,NPUW_FUNCALL_ASYNC=NO,COMPILATION_NUM_THREADS=1"
+ ./build/ReleaseOV/bin/llama-cli -m Qwen_Qwen3.6-35B-A3B-Q4_0.gguf -c 256
+ ```
+
+ ```bat
+ REM Windows
+ set GGML_OPENVINO_DEVICE=NPU
+ set GGML_OPENVINO_PREFILL_CHUNK_SIZE=128
+ set GGML_OPENVINO_NPU_CONFIG=NPUW_WEIGHTS_BANK_ALLOC=CPU,NPUW_FUNCALL_ASYNC=NO,COMPILATION_NUM_THREADS=1
+ build\ReleaseOV\bin\llama-cli.exe -m Qwen_Qwen3.6-35B-A3B-Q4_0.gguf -c 256
+ ```
+
+ - `NPUW_WEIGHTS_BANK_ALLOC=CPU` keeps the NPUW copy of the weights in host memory instead of the NPU-addressable memory, at some cost in speed.
+ - `NPUW_FUNCALL_ASYNC=NO` and `COMPILATION_NUM_THREADS=1` lower the memory peak. `GGML_OPENVINO_COMPILATION_NUM_THREADS=1` is an older name for the second one.
+ - The backend sets `NPUW_MOE_POOL_SIZE=0` and `NPUW_MOE_TOKEN_CHUNK_SIZE=16` itself for MoE models (see the [developer documentation](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#npu-plugin-properties)). Without them the load can hang on a 32 GB system.
+ - The NPU compiler type can stay unset: models with `GATED_DELTA_NET` layers, such as Qwen3.6, then compile with the compiler in OpenVINO. `NPU_COMPILER_TYPE=PREFER_PLUGIN` gives the same result.
+ - Linux: the NPU reports almost all of the system memory, so `--fit` keeps every weight in the backend, and a 32 GB system swaps heavily. Pass `--fit-target 16384`: `--fit` then leaves part of the expert weights in the memory-mapped model file, as it does on Windows, where the NPU reports 16 GB. The graph still runs on the NPU alone.
+ - `llama-perplexity` with these models: use a `-c` of at most twice `GGML_OPENVINO_PREFILL_CHUNK_SIZE` (for example `-c 256` with a chunk size of 128). The output rows of the last layer must not exceed the chunk size.
> [!NOTE]
> The OpenVINO backend is actively under development. Fixes and improvements are underway, and this document will continue to be updated.
diff --git a/ggml/src/ggml-openvino/CMakeLists.txt b/ggml/src/ggml-openvino/CMakeLists.txt
index 250593a38..a33da0677 100644
--- a/ggml/src/ggml-openvino/CMakeLists.txt
+++ b/ggml/src/ggml-openvino/CMakeLists.txt
@@ -27,21 +27,3 @@ endif()
if (WIN32)
target_link_libraries(ggml-openvino PRIVATE psapi)
endif()
-
-# Released runtimes retain the ordinary cache translators.
-include(CheckCXXSourceCompiles)
-include(CMakePushCheckState)
-unset(GGML_OPENVINO_HAS_CACHE_UPDATE CACHE)
-cmake_push_check_state(RESET)
-set(CMAKE_REQUIRED_LIBRARIES openvino::runtime)
-set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op")
-check_cxx_source_compiles("#include <recurrent_cache_update.hpp>
-int main() {
- auto conv = std::make_shared<ov::op::internal::RecurrentConvCacheUpdate>(ov::OutputVector{}, 3);
- auto gdn = std::make_shared<ov::op::internal::RecurrentGatedDeltaNetUpdate>(ov::OutputVector{});
-}"
- GGML_OPENVINO_HAS_CACHE_UPDATE)
-cmake_pop_check_state()
-if(GGML_OPENVINO_HAS_CACHE_UPDATE)
- target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_CACHE_UPDATE=1)
-endif()
diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md
deleted file mode 100644
index 497cf46df..000000000
--- a/ggml/src/ggml-openvino/README.md
+++ /dev/null
@@ -1,97 +0,0 @@
-# Qwen MTP
-
-The default Qwen3.5/Qwen3.6 GPU path is dynamic stateless execution with in-place fused recurrent ops and stable MTP sampling. Build against the matching OpenVINO runtime/GPU plugin with independent `RecurrentConvCacheUpdate` and `RecurrentGatedDeltaNetUpdate` ops. The native Update ops return computation results and update writable cache inputs in place, including rollback snapshots where required. No recurrent/sampling opt-in flag is needed on supported graphs. See the [development documentation index](dev_doc/README.md) for the implementation and the MTP sampling graph.
-
-Use `--spec-type draft-mtp --spec-draft-n-max 2` with a GGUF that contains MTP weights. Parallel execution uses `-np` and `--kv-unified`. CPU snapshot execution, NPU execution, and forced static MTP are not supported.
-
-Stateless recurrent execution uses the same reset, reorder, and partial cache-writeback paths at every slot capacity, including one slot without MTP.
-
-The matched stateless GPU path uses `RecurrentConvCacheUpdate` and
-`RecurrentGatedDeltaNetUpdate`. Each cache is a writable Parameter backed by one
-stable caller-owned USM allocation. The ops return only convolution or attention;
-there are no recurrent cache Results. Required source rows are staged before
-writes, preserving resets, cyclic reorders and rollback. Cache readers must be
-exclusive, including Reshape aliases.
-`GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains the ordinary cache decomposition.
-Unmatched snapshot GDN uses ordinary GDN token prefixes with functional writeback.
-Build both repos against the matching single-output op spec. Translation revision
-15 requires regenerating compiled-model blobs once without cache-only mode.
-
-Cache-only MTP serving still requires the separate OpenVINO dynamic output-binding fix (PR #39354). Removing recurrent cache Results does not eliminate that independent trigger in imported MTP graphs.
-
-Set `GGML_OPENVINO_ENABLE_KV_4D=1` to enable the upstream stateless in-place
-attention KV update pattern where eligible. It binds full-capacity cache tensors
-and lets the GPU fusion expose the live prefix to attention. The current upstream
-eligibility check supports one physical stream (including unified KV); explicit
-split multi-slot KV retains the ordinary full-cache path. This option does not
-change recurrent cache handling. Unified KV is recommended for multi-slot GPU
-execution because it enables this in-place attention update.
-
-The recommended Qwen3.6-35B-A3B Q4_K_M setup uses GPU with `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all` and `GGML_OPENVINO_NATIVE_SOFTPLUS=1`. Leave `GGML_OPENVINO_KV_SLICE` at its default (`1`). See [attention KV layout](dev_doc/OPENVINO-RECURRENT-CACHE.md#attention-kv-layout) for eligibility.
-
-`q4_asym64_all` converts Q4_K/Q5_K/Q6_K/Q8_0/Q5_1 weights, including dense Q8_0 projections, to asymmetric INT4 with group size 64. `token_embd.weight` and `output.weight` retain symmetric channel-wise INT8. Q8_0/Q5_1 rows whose width is not divisible by 64 also use channel-wise INT8. This follows the primary/backup precision scheme of NNCF `INT4_ASYM`, `ratio=1.0`, `group_size=64`, `backup_mode=INT8_SYM` for these supported source types; it requantizes GGUF values rather than the original floating-point model and leaves floating-point weights unchanged. Earlier versions kept dense Q8_0 at INT8/group-32. Repopulate compiled-model caches without cache-only mode after this change; the cache fingerprint invalidates the old precision policy.
-
-See the [implementation guide](dev_doc/OPENVINO-RECURRENT-CACHE.md) for buffer ownership and rollback.
-
-# Compiled model cache
-
-`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` exports compiled CPU/GPU graphs with their weights. It bypasses the plugin-level `GGML_OPENVINO_CACHE_DIR` and uses `OPTIMIZE_SPEED`, so weightless caching is disabled.
-
-One directory can hold blobs for different models and compilation settings. Run each intended workload once to export its dynamic graph:
-
-```sh
-GGML_OPENVINO_DEVICE=GPU \
-GGML_OPENVINO_NATIVE_SOFTPLUS=1 \
-GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \
-GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/path/to/qwen-cache \
-./build/ReleaseOV/bin/llama-bench -m /path/to/model.gguf -r 1
-```
-
-`GGML_OPENVINO_SPILL_DIR` remains optional for this first run. Wait for the `model cache WROTE` message and completion of the workload before stopping it. Compatible prefill and decode graphs share one blob and manifest. A graph with different ports or incompatible shapes gets an exact entry instead; interrupted exports are not cache hits.
-
-On later runs, supply the same compilation settings and enable `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1`:
-
-```sh
-GGML_OPENVINO_DEVICE=GPU \
-GGML_OPENVINO_NATIVE_SOFTPLUS=1 \
-GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \
-GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/path/to/qwen-cache \
-GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \
-./build/ReleaseOV/bin/llama-bench -m /path/to/model.gguf -r 1
-```
-
-Cache-only mode allocates backend address space without filling weight pages. On Windows, this also uses system commit capacity. The model-buffer size in the loader log is this virtual size. Weight uploads only record source identity; they do not read or requantize the weights. Graph conversion and compilation are skipped. Runtime buffers are still allocated and populated normally.
-
-Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_EXACT_ZERO_POINT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`, `GGML_OPENVINO_ENABLE_KV_4D`, and `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode.
-
-`GGML_OPENVINO_KV_SLICE` is a runtime binding option for dynamic graphs and can differ between cache population and cache-only runs. The same dynamic compiled graph accepts full-capacity and live-prefix attention K/V tensors. Slicing is enabled by default for contiguous ordinary K/V roots with one allocated stream, one active sequence at offset zero, and no sliding-window attention. Recurrent convolution/GDN caches and their rollback snapshots always retain their full stored row bank. Other layouts use full bindings. Repopulate caches made before this option was removed from the fingerprint once without cache-only mode.
-
-A missing or incompatible graph fails with an error instead of compiling with absent weights. The fingerprint uses the dynamic graph's topology, ports, model parameters, weights, settings, and OpenVINO version; changing only dynamic token or KV sizes does not require a new entry. A different workload can still require another graph; populate it first without cache-only mode.
-
-## MTP sampling and active slots
-
-Qwen3.5/Qwen3.6 MTP uses a pure top-k backend sampler. Dynamic stateless execution retains its sampling branches for every configured slot and output row, including inactive branches. One packed `sampling_rows` input selects logits rows at runtime. Graph node names and candidate-output ports stay fixed, so changing the active subset of four slots reuses the same compiled draft model instead of creating up to 15 variants.
-
-Active candidate IDs and scores are written to the normal GGML outputs. Inactive branches read row 0 (the padding row when there are no logits) and write to private scratch tensors (device USM on GPU), without changing sampler state or touching inactive GGML buffers. The top-k computations remain separate per branch; this trades some extra sampling work for a stable graph interface. Other sampler chains retain their existing branch-selection behavior.
-
-This is one draft model per compatible graph configuration, not one compiled blob for the whole server. The trunk and other graph stages still have their own entries. Different sampler configurations, recurrent capacities, rollback modes or incompatible KV layouts can require additional models. Cache-only mode still requires initial preparation; changing just the active subset no longer requires exhaustive subset priming.
-
-The generic recurrent-cache translation invalidates blobs made with the former single-slot shortcuts. Run once without `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` to populate compatible entries before enabling cache-only mode again.
-
-## Restrictions
-
-- Cache-only mode requires Linux or Windows and mmap loading (`--load-mode mmap`, or the default when all selected devices support mmap). Do not use tensor validation or mlock when trying to avoid weight reads.
-- On Windows, the backend commits virtual memory for its buffers without touching weight pages. Large models can still reach the system commit limit.
-- The model must execute entirely on OpenVINO, with dynamic CPU/GPU graphs and in-process caching enabled. Static/NPU execution and CPU fallback are unsupported in cache-only mode.
-- GGUF metadata, tokenizer data, tensor descriptors, and graph construction are still needed. The llama.cpp loader is unchanged: depending on its prefetch settings, it may request pages with `MAP_POPULATE` or read-ahead on Linux, or `PrefetchVirtualMemory` on Windows. Non-mmap loading also reads the payload before the backend sees it.
-- File identity, size, modification/change timestamps, tensor offsets, graph structure, settings, and OpenVINO version identify cache entries. Linux uses device/inode and Windows uses volume serial/file index. Replacing, copying, or modifying a GGUF invalidates its entries. This avoids reading weight bytes and ties the cache to the local source files. Keep those files unchanged throughout loading and inference.
-- Use the same target device and compatible OpenVINO/plugin installation. Import support depends on the plugin; the tested CPU plugin cannot import MoE graphs containing `GatherMatmulCompressed`. GPU MoE and CPU dense graph imports were tested.
-- Blobs contain weights and can approach model size for each compiled graph. Import still reads those blobs and initializes the device.
-
-# KV-only prefill
-
-On the static path (NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`), models whose tail layers read an earlier layer's KV get a KV-only prefill by default; `GGML_OPENVINO_KV_ONLY_PREFILL=0` turns it off. It compiles the static prefill graph with only the KV-cache writes as outputs (`openvino/pass/keep_cache_results.cpp`). Everything that only feeds the logits is dropped from it: for models whose tail layers read an earlier layer's KV (Gemma 3n/4 E-series) that is every KV-shared layer, plus the LM head. When the batch needs logits, the decode graph is then run once on the output token; it rewrites that token's KV rows and computes the dropped layers against the complete cache. It is used only when attention ops of the graph share a KV cache tensor and the graph has no recurrent state. If a batch needs more than one output token, or the output step fails, the backend logs a warning and uses the full prefill from then on.
-
-# NPU host gather
-
-`GGML_OPENVINO_NPU_HOST_GATHER=1` (NPU, opt-in) gathers the rows of large host-resident embedding tables (at least 64 MiB, raw GGUF data) on the host. The static graph gets the gathered rows through an `ggml_host_rows_<node>` input instead of an OpenVINO Gather over the table. NPUW otherwise lifts the table to a function input, and gathering from an input that large costs about as much as streaming the whole table every call (21.6 ms of Gemma 4 E2B decode). A table used only for such lookups (the Gemma 3n/4 per-layer embedding table) is not converted or bound to the NPU at all.
diff --git a/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md b/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md
index ef50e153d..22ed8bbba 100644
--- a/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md
+++ b/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md
@@ -1,6 +1,35 @@
-# Stable multislot MTP graph
+# Stable multi-slot MTP graph
-The captured UD draft graph contains 107 nodes regardless of which of four slots are active. It is the single MTP attention/MoE layer, not the recurrent trunk. Two speculative tokens require two consecutive draft calls, batched over active sequences.
+The MTP draft graph of Qwen3.5/Qwen3.6 keeps the same node names and candidate-output ports for every subset of active slots, so one compiled draft model serves all subsets.
+
+Contents:
+
+- [Sampler behavior](#sampler-behavior)
+- [Graph layout](#graph-layout)
+- [Active slots](#active-slots)
+- [Runtime row selection](#runtime-row-selection)
+- [Compiled models and the cache](#compiled-models-and-the-cache)
+- [Reading graph dumps](#reading-graph-dumps)
+
+## Sampler behavior
+
+- Qwen3.5/Qwen3.6 MTP uses a pure top-k backend sampler.
+- Dynamic stateless execution keeps the sampling branches for every configured slot and output row, including inactive branches.
+- One packed `sampling_rows` input selects the logits rows at runtime.
+- Graph node names and candidate-output ports stay fixed. A change of the active subset of four slots therefore reuses the same compiled draft model, instead of creating up to 15 variants.
+- Active candidate IDs and scores are written to the normal GGML outputs.
+- Inactive branches read row 0 (the padding row when there are no logits) and write to private scratch tensors (device USM on GPU). They do not change sampler state or acceptance, and do not touch inactive GGML buffers.
+- The backend does not change the original cgraph or execute inactive stateful sampler chains.
+- Only the small sampling branches stay at configured capacity. The expensive draft layer, the MTP layer and the output projection, processes the N active rows.
+- The top-k computations stay separate per branch, not yet one batched TopK. This trades some extra sampling work for a stable graph interface.
+- Other sampler chains keep their existing branch-selection behavior.
+
+## Graph layout
+
+The captured UD draft graph contains 107 nodes regardless of which of four slots are active.
+
+- It is the single MTP attention/MoE layer, not the recurrent trunk.
+- Two speculative tokens require two consecutive draft calls, batched over active sequences.
```text
MTP token IDs + input hidden state
@@ -16,7 +45,11 @@ MTP token IDs + input hidden state
+-- 102-106: slot 3 sampling
```
-Each branch contains VIEW, two Reshapes, TopK (ten candidate IDs), and GET_ROWS (their scores). Ten is the candidate count, not the speculative-token count.
+- Each branch contains VIEW, two Reshapes, TopK (ten candidate IDs) and GET_ROWS (their scores).
+- Ten is the candidate count, not the speculative-token count.
+- The observed draft interface has 10 inputs and 12 outputs: eight candidate ID/score outputs, hidden state, full logits and two KV Results.
+
+## Active slots
| Active slots | Sampling COMPUTE flags, slots 0-3 | Raw/current nodes | Old filtered nodes | Packed sampling_rows |
|---|---|---:|---:|---|
@@ -24,9 +57,24 @@ Each branch contains VIEW, two Reshapes, TopK (ten candidate IDs), and GET_ROWS
| 0,2 | `[1,0,1,0]` | 107 | 97 | `[0,0,1,0]` |
| All four | `[1,1,1,1]` | 107 | 107 | `[0,1,2,3]` |
-Old counts apply the old COMPUTE filter to the captures. Unselected nodes remain in the raw cgraph. Previously, removing them changed translated topology, slot-specific row Parameter names and output ports; even equal-sized subsets such as `{0,1}` and `{0,2}` differed. This could trigger up to 15 draft variants, with compilation/import on first use or a missing-cache error in cache-only mode.
+- Old counts apply the old COMPUTE filter to the captures.
+- Unselected nodes remain in the raw cgraph.
+
+<details>
+<summary>Why the graph keeps inactive branches</summary>
+
+The old COMPUTE filter removed the unselected nodes. That changed the translated topology, the slot-specific row Parameter names and the output ports; even equal-sized subsets such as `{0,1}` and `{0,2}` differed. This could trigger up to 15 draft variants, with compilation/import on first use or a missing-cache error in cache-only mode.
+
+</details>
+
+## Runtime row selection
+
+- All pure top-k branches remain. Their names include stable graph ordinals even when inactive.
+- One int64 `sampling_rows` Parameter supplies row indices at runtime.
+- The vector is not an active mask. Host-side COMPUTE flags select normal versus scratch output destinations.
+- PAD provides a valid row when there are no logits.
-Now all pure top-k branches remain. Their names include stable graph ordinals even when inactive. One int64 `sampling_rows` Parameter supplies row indices at runtime. For `{0,2}`, the two logits rows belong to slots 0 and 2:
+For active slots `{0,2}`, the two logits rows belong to slots 0 and 2:
```text
sampling_rows = [0, 0, 1, 0]
@@ -36,10 +84,17 @@ slot 2 -> row 1 -> normal candidate buffers
slot 3 -> row 0 -> private scratch, ignored
```
-The vector is not an active mask. Host-side COMPUTE flags select normal versus scratch output destinations. PAD provides a valid row when there are no logits. Inactive outputs use device USM on GPU and do not affect sampler state or acceptance. Other sampler chains retain their selected-branch semantics.
+## Compiled models and the cache
-Only small sampling work executes for inactive slots. The MTP layer and output projection still process N active rows. Top-k is separate per branch, not yet one batched TopK. The observed draft interface has 10 inputs and 12 outputs: eight candidate ID/score outputs, hidden state, full logits and two KV Results.
+- One draft model exists per compatible graph configuration, not one compiled blob for the whole server. One compatible draft graph is shared across active subsets.
+- The trunk and other graph stages still have their own entries. Genuinely different graph stages and configurations remain separate.
+- Different sampler configurations, recurrent capacities, rollback modes or incompatible KV layouts can require additional models.
+- Cache-only mode still requires initial preparation: prepare compatible blobs once, then use cache-only mode. A change of the active subset needs no extra preparation.
+- The first import and runtime preparation still have a cost.
-Dump shapes use GGML order `[width, rows, dim2, dim3]`; OV reverses it. `view_offs` is in bytes: one logits row occupies `248320 * 4 = 993280` bytes. Buffer labels describe GGML storage, not the device executing imported GPU operations.
+## Reading graph dumps
-The captures used cache-only mode, four slots, context 8192 and the default two-token MTP settings.
+- Dump shapes use GGML order `[width, rows, dim2, dim3]`. OpenVINO reverses it.
+- `view_offs` is in bytes: one logits row occupies `248320 * 4 = 993280` bytes.
+- Buffer labels describe GGML storage, not the device that executes imported GPU operations.
+- Capture conditions: cache-only mode, four slots, context 8192 and the default two-token MTP settings.
diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md
index 7dfb742b1..010ee88a3 100644
--- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md
+++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md
@@ -1,62 +1,166 @@
-# Current Qwen GPU implementation
+# Qwen recurrent cache on GPU
-The default Qwen3.5/Qwen3.6 path is dynamic stateless execution with `RecurrentConvCacheUpdate`, `RecurrentGatedDeltaNetUpdate`, and stable pure-top-k MTP translation. It supports one or multiple slots and rollback. The implementation applies to `qwen35` and `qwen35moe`; the reference model is the UD Qwen3.6-35B-A3B MTP GGUF.
+The default Qwen3.5/Qwen3.6 MTP path uses pending-token replay, dynamic stateless execution and stable pure-top-k sampling. When MTP discards a suffix, the next batch replays the retained tokens before it processes new tokens.
-Build against the matching OpenVINO runtime/GPU plugin with single-output Update ops. Configure `GGML_OPENVINO_DEVICE=GPU`, native softplus, and the documented requantization policy. The cache translation revision is 15. Historical measurements retain their original source revisions.
+- Applies to `qwen35` and `qwen35moe`, with one or multiple slots.
+- Reference model: the UD Qwen3.6-35B-A3B MTP GGUF model file.
+- Setup: `GGML_OPENVINO_DEVICE=GPU` and the documented requantization policy ([Qwen MTP](README.md#qwen-mtp)).
+- The matching GPU plugin structurally fuses complete replay groups into its internal convolution and Gated Delta Net ops.
-The separate dynamic output-binding fix in OpenVINO PR #39354 remains required for cache-only MTP serving. Native cache-op export/import tests pass without it, but Qwen3.6 imported MTP graphs still trigger the missing-input-memory error without the fix.
+Contents:
+
+- [Buffer ownership and operation boundaries](#buffer-ownership-and-operation-boundaries)
+- [Replay graph contract](#replay-graph-contract)
+- [Convolution cache stores](#convolution-cache-stores)
+- [Attention KV layout](#attention-kv-layout)
+- [Stable MTP sampling](#stable-mtp-sampling)
+- [Validation](#validation)
+- [Debugging and source map](#debugging-and-source-map)
## Buffer ownership and operation boundaries
| State | Storage and lifetime | Update path |
|---|---|---|
| Attention K/V | Full caller-owned USM allocation, sized by context and KV layout | Native stateless KV fusion when eligible; SDPA consumes the live prefix |
-| Convolution `cache_r` | Full caller-owned USM row bank, sized by slot/snapshot capacity | Fused reset, original-row gather/reorder, convolution and ordered history/snapshot writes |
-| GDN `cache_s` | Full caller-owned USM row bank, sized by slot/snapshot capacity | Fused reset, original-row gather/reorder, GDN and ordered final/snapshot writes |
+| Convolution `cache_r` | Caller-owned USM row bank with history and pending columns | Fused reset, original-row gather/reorder, convolution and ordered history/pending writes |
+| GDN `cache_s`, `cache_spk`, `cache_spv`, `cache_spgb` | Caller-owned USM row banks with committed state and pending token inputs | Fused reset, original-row gather/reorder, GDN and ordered state/pending writes |
| Runtime controls | Reused USM host storage on GPU | Row maps, offsets and write controls remain runtime inputs |
| Protected source rows | Private device scratch | Staged before writes to protect cycles, duplicate sources and overlaps |
| Inactive sampling results | Private device-USM scratch | Discarded without touching inactive GGML output buffers |
-Attention context capacity does not set recurrent-cache size. Each cache input Parameter binds a stable writable allocation; recurrent cache Results are omitted. There are no rotation banks or pointer swaps.
+- Recurrent-cache size depends on slot capacity and pending-token capacity.
+- Each fused cache input Parameter binds a caller-owned writable allocation.
-The GPU plugin uses two stages: first preserve required original rows in scratch while applying logical reset and precision rounding; then compute and perform ordered writes. This avoids overwriting a source before another destination has read it. Identity reorder sources need no scratch writes. In-place execution removes the spare full output bank, not every cache read or internal memory transaction.
+The GPU plugin uses two stages:
-`RecurrentConvCacheUpdate` has nine inputs, including depthwise weights, and returns convolution `[1,B,T,C]`. `RecurrentGatedDeltaNetUpdate` returns attention and writes the newest `min(T,snapshot_count)` states into its cache input, newest first. Neither op returns a cache tensor.
+1. It preserves the required original rows in scratch while it applies logical reset and precision rounding.
+2. It computes and performs the ordered writes.
-## Convolution cache stores
+- This order avoids overwriting a source before another destination has read it.
+- Identity reorder sources need no scratch writes.
+- In-place execution removes the spare full output bank, not every cache read or internal memory transaction.
+
+| Op | Returns | Writes |
+|---|---|---|
+| `RecurrentConvCacheReplayUpdate` | Convolution `[1,B,T,C]` | History and pending columns |
+| `RecurrentGatedDeltaNetReplayUpdate` | Attention | Committed state and pending K, V, gate and beta |
+
+Both kernels write their cache inputs directly.
+
+## Replay graph contract
+
+Graph selection:
+
+- Qwen selects the recurrent graph when the target context is created.
+- `n_rs_seq=0` selects the ordinary graph.
+- With `--spec-type draft-mtp` and a positive draft limit, `n_rs_seq` is the draft limit, and `rs_replay` selects the replay graph even for a fresh prefill.
+- Both forms use `GGML_OP_GATED_DELTA_NET`. The replay form sets `op_params[1]` to the pending-token capacity and adds inputs for pending K, V, gate/beta and the per-sequence replay count.
+- A fresh prompt supplies a replay count of zero.
+- Prefill microbatches longer than `n_rs_seq + 1` tokens per sequence commit their final state.
+- The unfused OpenVINO graph processes current tokens in a `Loop` and uses a bounded unrolled recurrence for the retained prefix.
+
+Standard-op graph and `Assign` sinks:
+
+- The backend emits a standard-op graph for each complete dynamic stateless replay group.
+- The computation feeds later layers, and the updated banks feed standard `Assign` sinks.
+- Fusion requires each bank to be a direct FP32 `Parameter` of shape `[1, 1, slots, features]`, backed by caller-owned writable GPU USM.
+- The backend opts each bank into in-place fusion by giving its sink the variable ID `__ggml_replay_cache_<Parameter friendly name>`.
+
+GPU fusion:
+
+- The GPU plugin requires the transformed model to preserve its `Result` count. Sinks express writeback separately from that output interface.
+- The pass can replace the computation and remove its matched sinks and variables while keeping the Results. The internal op then writes through the original input binding. This avoids the GPU runtime changes that would be needed to alias a cache output to its input.
+- The variable ID supplies the write permission. `RecurrentReplayFusion` still matches the computation, row controls, reset, reordering and writeback structure, and requires exclusive bank readers and a live computation output.
+- The kernel checks for overlapping buffer ranges.
+
+Writeback without fusion:
+
+- When a sink remains, including on a GPU plugin without this pass, llama.cpp uses `query_state()` to find it and copies its state to the original GGML bank after inference.
+- Mixed-precision execution of that graph can round bank values.
-`build_conv_state_store` emits one CPY for the final history when rollback is disabled. With rollback enabled, it emits one SET_ROWS from overlapping `[history, window, channel, sequence]` views into strided snapshot planes. Window starts advance in time while destination planes descend, so plane zero holds the newest history. The fixed ARANGE/scale/cast chain supplies this descending slot order.
+Source of the replay pattern:
-The backend recognizes this structure and refreshes source starts, cache heads, sequence counts, window counts and plane strides on every batch. Native fusion passes runtime `[source column, destination slot]` pairs to the existing convolution op; the pair-count dimension is dynamic. Functional translation gathers the same windows, scatters them into the full cache, and preserves unwritten slots and features. The native op spec is unchanged.
+- The backend builds the graph in [`openvino/op/recurrent_replay_graph.hpp`](../openvino/op/recurrent_replay_graph.hpp).
+- The GPU matcher in `src/plugins/intel_gpu/src/plugin/transformations/recurrent_replay_fusion.cpp` compares it to a reference built from the OpenVINO copy of `recurrent_replay_graph.hpp` in the same directory.
-## Generic fallback and restrictions
+When upstream modeling changes the GGML graph:
-Writable cache inputs must be GPU RemoteTensors with exclusive graph readers, optionally through Reshape aliases. The GPU plugin rejects shared cache readers and computed cache banks. Other inputs and the computation output must not overlap the cache. The frontend skips fusion for unmatched cache reads and retains functional cache writeback. Restore or clear state after a failed inference before retrying.
+1. Adapt the backend recognition and check what it emits.
+2. If the emitted replay pattern or its semantics change, update the reference and the relevant matcher and kernel logic with the translation.
+3. Verify that the graph still fuses and that the standard-op writeback still works.
-`GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains ordinary cache decomposition. Naive graphs skip full-model recurrence fusion. Unmatched snapshot GDN uses ordinary GDN token prefixes to preserve state outputs. The fused path requires the matching native runtime; otherwise dynamic CPU and GPU execution uses ordinary GDN. Stateful and NPU MTP are outside this change.
+## Convolution cache stores
+
+- The structural replay graph gathers history using the retained-token count, concatenates live input, and uses one grouped convolution.
+- A slice selects history and pending columns for the next batch.
+- `ScatterNDUpdate` produces the updated bank for the `Assign` sink.
+- Row maps, replay counts and reset rows are runtime inputs.
## Attention KV layout
-`GGML_OPENVINO_ENABLE_KV_4D=1` enables eligible native stateless in-place attention updates. The current eligibility covers one physical stream, including unified KV. Explicit split multi-slot KV retains the full-cache path and can be much slower even with only one active slot. Use `--kv-unified` for multi-slot OV GPU serving.
+| Variable | Default | Scope | Description |
+|---|---|---|---|
+| `GGML_OPENVINO_ENABLE_KV_4D` | On with OpenVINO 2026.5 or later | GPU | Eligible native stateless in-place attention updates |
+| `GGML_OPENVINO_KV_SLICE` | `1` | Dynamic CPU and GPU; static NPU | Binding switch on dynamic CPU and GPU; base of the compiled KV windows on static NPU |
+| `GGML_OPENVINO_GPU_KV_ROUND_UP` | `1` | Dynamic stateless GPU | Attended-width rounding |
-Leave `GGML_OPENVINO_KV_SLICE` at its default (`1`). Live-prefix slicing applies to eligible ordinary attention K/V roots, not recurrent caches. In-place KV fusion can bind the full allocation while exposing a live prefix internally. KV-slice on/off is a runtime binding choice and does not require different compiled blobs; incompatible graph layouts/capacities can still do so.
+`GGML_OPENVINO_ENABLE_KV_4D`:
-## Stable MTP sampling
+- Uses the upstream stateless in-place attention KV update pattern where eligible. It binds full-capacity cache tensors and lets the GPU fusion expose the live prefix to attention.
+- `0` turns it off. `1` turns it on with older OpenVINO versions.
+- The current eligibility covers one physical stream, including unified KV.
+- Explicit split multi-slot KV keeps the full-cache path and can be much slower, even with only one active slot.
+- It does not change recurrent cache handling.
+- Use `--kv-unified` for multi-slot OV GPU serving. Unified KV enables this in-place attention update.
+
+`GGML_OPENVINO_KV_SLICE` on dynamic CPU and GPU:
+
+- Eligible root: a contiguous ordinary attention K/V root with one allocated stream, one active sequence at offset zero, and no sliding-window attention. For it, the backend binds a view of the allocation sized to the attended prefix.
+- Recurrent convolution/GDN caches and their rollback snapshots always keep their full stored row bank. Sliding-window attention and other layouts use the full binding.
+- The 4-D in-place attention path binds the full allocation first and exposes the attended prefix inside the graph.
+- Dynamic compiled blobs can accept either eligible binding, so the value can differ between cache population and cache-only runs.
+
+`GGML_OPENVINO_KV_SLICE` on static NPU:
+
+- Selects the base of the compiled KV windows. The default base is 1024; an explicit multiple of 256 changes it.
+- The window is the smallest `base * 2^k` that covers the attended length, capped by the context.
-The [graph walkthrough](MTP-SAMPLING-GRAPH.md) describes the fixed sampling interface. The backend keeps pure top-k branches for all configured slots, packs runtime row indices, and uses scratch for inactive outputs. It does not change the original cgraph or execute inactive stateful sampler chains. Only the small sampling branches stay at configured capacity; the expensive draft layer processes active rows.
+`GGML_OPENVINO_GPU_KV_ROUND_UP` on dynamic stateless GPU:
-One compatible draft graph is shared across active subsets. Trunk and genuinely different graph stages/configurations remain separate. Prepare a compatible revision-15 cache once, then use cache-only mode. Exhaustive active-subset priming is no longer required, though first-use model import and runtime preparation still have a cost.
+- Controls the attended width separately from prefix binding.
+- `0`: the decoder uses the GGML mask width. Ordinary GGML attention KV already pads it in steps of 256 rows.
+- `1` (default): power-of-two windows when the graph input has more than 16 tokens, and coarser aligned steps for smaller batches. The step starts at 256 rows and doubles whenever the width reaches eight times the current step.
+- Example: at 33,024 GGML rows, the added rounding can expand attention to 40,960 rows for decode or 65,536 for a larger prefill input, subject to the context cap.
+- Added mask columns contain negative infinity.
+
+## Stable MTP sampling
+
+The fixed sampling interface, the handling of inactive slots and the reuse of compiled draft models are in [MTP-SAMPLING-GRAPH.md](MTP-SAMPLING-GRAPH.md).
## Validation
-Native OV tests cover shape/attribute serialization, reset, cycles, duplicates, overlapping writes, mixed precision, changing shapes, writable cache input rebinding, exclusive Reshapes, shared readers, host/device USM and export/import. Convolution is checked against a host reference; GDN uses an independent cache mapping around ordinary GDN. See `docs/dev/qwen35-llamacpp-recurrent-cache.md` and `recurrent_cache_update.cpp` in the OV checkout for contracts and tests.
+- Validation checks the convolution bank that the caller mutated against the expected reset, reorder and history writes.
+- The four-layer Qwen3.6 model exercises replay at one and four active sequences.
## Debugging and source map
-- `ggml-decoder.cpp`: dynamic dimensions, control inputs, output names and `cgraph_ov.txt` dump.
-- `utils.cpp`: compute-branch filtering, compiled reuse and input/output binding.
-- `openvino/recurrent_cache_fusion.cpp`: structural pattern matching and native Update op translation.
-- `openvino/translate_session.cpp`: runtime sampling aliases and model construction.
-- OV `recurrent_cache_update` implementation: writable-input validation, source staging and GPU computation.
+Backend files, relative to `ggml/src/ggml-openvino/`, and OpenVINO GPU plugin parts:
+
+| File | Content |
+|---|---|
+| `ggml-decoder.cpp` | Dynamic dimensions, control inputs, output names and the `cgraph_ov.txt` dump |
+| `utils.cpp` | Compute-branch filtering, compiled reuse and input/output binding |
+| `openvino/recurrent_replay_fusion.cpp` | GGML group recognition and standard-op replay translation |
+| `openvino/translate_session.cpp` | Runtime sampling aliases and model construction |
+| OV `recurrent_replay_fusion.cpp` and `recurrent_cache_replay` | Structural matching, writable-input validation, source staging and GPU computation |
+
+`GGML_OPENVINO_DUMP_CGRAPH=1`:
+
+- Dumps the raw graph before filtering, with COMPUTE/OUTPUT flags and byte offsets.
+- Overwrites `cgraph_ov.txt` on each call.
+- Enable dumps only for diagnosis. Use the captured examples for a static view.
+
+Profiling:
-`GGML_OPENVINO_DUMP_CGRAPH=1` dumps the raw graph before filtering. It includes COMPUTE/OUTPUT flags and byte offsets and overwrites `cgraph_ov.txt` on each call. Enable dumps only for diagnosis; use the captured examples for a static view. GPU profiles and OpenCL copy traces add overhead, and lack of an explicit copy call does not prove zero traffic inside a kernel.
+- GPU profiles and OpenCL copy traces add overhead.
+- The lack of an explicit copy call does not prove zero traffic inside a kernel.
diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
index 57deb264e..67c695575 100644
--- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
+++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
@@ -2,12 +2,22 @@
The variables for users, and the rules for values, are in [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md#runtime-configuration). This file lists the other `GGML_OPENVINO_*` variables. They are for debugging, comparisons and experiments, and they can change or be removed.
+Contents:
+
+- [Debug output](#debug-output)
+- [Switches for default optimizations](#switches-for-default-optimizations)
+- [Experimental options](#experimental-options)
+- [Memory optimization](#memory-optimization)
+- [NPU plugin properties](#npu-plugin-properties)
+- [GPU and CPU plugin properties](#gpu-and-cpu-plugin-properties)
+- [Older variable names](#older-variable-names)
+
## Debug output
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
| `GGML_OPENVINO_DUMP_CGRAPH` | all | Boolean | `0` | Dump the GGML compute graph to `cgraph_ov.txt`. |
-| `GGML_OPENVINO_DUMP_IR` | all | Boolean | `0` | Write the OpenVINO IR files, with timestamps. |
+| `GGML_OPENVINO_DUMP_IR` | all | Boolean | `0` | Write the OpenVINO IR files, with timestamps (`IR_naive.xml` for the small graphs of op tests). |
| `GGML_OPENVINO_DEBUG_INPUT` | all | Boolean | `0` | Print the input tensors. |
| `GGML_OPENVINO_DEBUG_OUTPUT` | all | Boolean | `0` | Print the output tensors. |
| `GGML_OPENVINO_DEBUG_NODE` | all | String | `not set` | Add the named graph nodes as outputs of the compiled model. Separate several names with commas. |
@@ -17,7 +27,7 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO
| `GGML_OPENVINO_LOG_SUPPORTS_OP` | all | Integer | `0` | Log what `supports_op` accepts and rejects. `1`: summary at exit. `2`: also each call (the first calls are missing). |
| `GGML_OPENVINO_DIAG_GRAPH_IO` | all | Boolean | `0` | When binding a tensor or `infer()` throws, log the graph key and the shapes of the model and the bound tensors. |
| `GGML_OPENVINO_DISABLE_CACHE` | all | Boolean | `0` | Turn the in-process cache of compiled models and decoders off. |
-| `GGML_OPENVINO_FULL_GRAPH_KEY` | all | Boolean | `0` | Add the external inputs of a graph to the key of the in-process cache. By default the key is the node count and the names of the first and last nodes. Use it when two different graphs could share that key. |
+| `GGML_OPENVINO_FULL_GRAPH_KEY` | all | Boolean | `0` | Add the external inputs of a graph to the key of the in-process cache. By default the key holds the node and leaf counts, the names of the first and last nodes, and some graph markers (output flags, sampler rows, weight buffers), but not the external inputs. Use it when two different graphs could share that key. |
| `GGML_OPENVINO_LOG_SWA_LAYERS` | all | Boolean | `0` | Log the attention extent of each layer and which layers use sliding-window attention, on an `ov-swa:` line at the WARN level. |
| `GGML_OPENVINO_NPUW_DUMP_SUBS` | NPU | String | `not set` | Dump NPUW subgraphs: `YES` (all), `MIN` (unique function bodies), `last`, or indices such as `0,2`. |
| `GGML_OPENVINO_NPUW_DUMP_SUBS_DIR` | NPU | String | `not set` | Directory for the NPUW subgraph dumps. |
@@ -54,7 +64,8 @@ Each variable turns off an optimization that is on by default, or sets its stren
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
-| `GGML_OPENVINO_KV_SLICE` | all | Integer | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. `0`: off. `1`: on, KV window base 1024. `N` (a multiple of 256): on, KV window base `N`. CPU and GPU: a view over the cache (any non-zero value just turns it on). Static path (NPU): the prefill graph is compiled at the smallest `N * 2^k` rows (clamped to the context) that cover the attended length; a loaded prefill graph of a larger window also serves a shorter prompt (with `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`, only the exact window); the decode KV windows of `GGML_OPENVINO_NPU_BLOB_PREBUILD` use the same base. With `0`, `llama-bench -d` fails on the NPU. Use the same value in the run that writes the cache and in the runs that read it. |
+| `GGML_OPENVINO_KV_SLICE` | all | Integer | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. `0`: off. `1`: on, KV window base 1024. `N` (a multiple of 256): on, KV window base `N`. Dynamic CPU and GPU use a valid positive value to bind eligible ordinary attention KV as a view of the attended prefix. The 4-D GPU binding takes precedence. Dynamic compiled blobs support both bindings. Static path (NPU): the prefill graph is compiled at the smallest `N * 2^k` rows (clamped to the context) that cover the attended length; a loaded prefill graph of a larger window also serves a shorter prompt (with `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`, only the exact window); the decode KV windows of `GGML_OPENVINO_NPU_BLOB_PREBUILD` use the same base. With `0`, `llama-bench -d` fails on the NPU. Use the same value in the run that writes the cache and in the runs that read it. |
+| `GGML_OPENVINO_GPU_KV_ROUND_UP` | GPU | Boolean | `1` | Controls the extra attended-width rounding on dynamic stateless GPU. With `1`, a graph input over 16 tokens uses the next power-of-two window and smaller batches use an aligned step that grows with the attended length. With `0`, the decoder uses the original GGML mask width. This setting is separate from prefix binding. |
| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | With `GGML_OPENVINO_KV_SLICE` on, decode attends the smallest `N * 2^k` rows (`N` from `GGML_OPENVINO_KV_SLICE`) that cover the next position, with one decode graph for each window, and the prefill windows are aligned to them. Every decode window is built, or read from the cache, on the first call. With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, the first prompt also writes (or reads) the prefill graph of every window; only the prefill graph in use stays loaded, unless `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` or `GGML_OPENVINO_NPU_KV_ON_DEMAND=1` keeps them all loaded. `0`, or `GGML_OPENVINO_KV_SLICE=0`: one decode graph attends the whole context, and prefill graphs are built on first use. Use the same value in the run that writes the cache and in the runs that read it. |
| `GGML_OPENVINO_NPU_FAST_MASK` | NPU | Boolean | `1` | Write the prefill attention mask directly into the input tensor, without an intermediate copy. The result is identical. |
| `GGML_OPENVINO_NPU_L0_HOST_TENSORS` | NPU | Boolean | `1` | Keep the KV cache and the compute buffers in Level Zero host memory, so the plugin reads them without an extra copy. Falls back to plain host memory if the allocation is not available. |
@@ -63,8 +74,9 @@ Each variable turns off an optimization that is on by default, or sets its stren
| `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK` | CPU, GPU | Boolean | `0` | By default the model reads the sequence count and the attended KV length from the shape of the KQ mask, so the GPU plugin can select its fused attention kernel. `1` passes them as separate inputs. |
| `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT` | CPU, GPU | Boolean | `0` | Stateful execution only. By default the sequence axis of the KV state is moved so that new tokens are appended in place. `1` keeps the original layout. |
| `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS` | GPU | Boolean | `0` | By default an output tensor in a GPU buffer is bound directly to the infer request when its shape and type match. `1` turns this off. |
-| `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE` | GPU | Boolean | `0` | Stateless execution only, with an OpenVINO build newer than 2026.4.1 (2026.4.1 does not build the fusion). By default the recurrent-state cache updates (Qwen3.5, LFM2) are fused into the OpenVINO model. `1` keeps the separate copies. |
+| `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE` | GPU | Boolean | `0` | `1` disables the OpenVINO backend's recurrent replay translation, so replay ops require another eligible GGML backend. For an unfused OpenVINO replay graph, leave this at `0` and use a GPU plugin without the replay fusion pass. |
| `GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN` | GPU | Boolean | `0` | By default the operands of an element-wise op get the same rank, which works around a GPU plugin defect when the op is fused into RMS norm (gemma-4 in stateful execution gave wrong output). `1` turns the workaround off. |
+| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | auto | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Unset: on with OpenVINO 2026.5 or later, off with older versions (much slower there). `0` forces it off, a positive value forces it on. With OpenVINO 2026.5, `GGML_OPENVINO_ENABLE_KV_4D=0` can stop a process that runs two models on the GPU at the same time (`CL_OUT_OF_RESOURCES`). |
```bash
# Find out whether an optimization causes a wrong result: turn it off and compare the output
@@ -74,24 +86,23 @@ GGML_OPENVINO_DEVICE=NPU GGML_OPENVINO_NPU_FAST_MASK=0 \
## Experimental options
-These options are off by default. They are not validated for general use: some help on one model or device and give a wrong or slower result on another.
+Most of these options are off by default. They are not validated for general use: some help on one model or device and give a wrong or slower result on another.
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
-| `GGML_OPENVINO_NPU_DECODE_UNFOLD` | NPU | Boolean | `0` | Set `NPUW_UNFOLD_IREQS=YES` on the decode graph only. An explicit `GGML_OPENVINO_NPUW_UNFOLD_IREQS` or `GGML_OPENVINO_NPU_CONFIG` value takes precedence. |
-| `GGML_OPENVINO_NPU_KV_ON_DEMAND` | NPU | Boolean | `0` | Keep the ggml KV buffer non-resident and bind storage for each layer that grows with the rows in use, so a large `-c` costs memory only for the context that is reached. K is stored head-major and V transposed, as OpenVINO GenAI does. `llama-perplexity` fails with it. |
+| `GGML_OPENVINO_NPU_DECODE_UNFOLD` | NPU | Boolean | `0` | Set `NPUW_UNFOLD_IREQS=YES` on the decode graph only. An explicit `GGML_OPENVINO_NPUW_UNFOLD_IREQS` or `GGML_OPENVINO_NPU_CONFIG` value takes precedence. No effect on graphs with a MoE block, which get `NPUW_UNFOLD_IREQS=NO`. |
+| `GGML_OPENVINO_NPU_KV_ON_DEMAND` | NPU | Boolean | `0` | Keep the ggml KV buffer non-resident and bind storage for each layer that grows with the rows in use, so a large `-c` costs memory only for the context that is reached. With `GGML_OPENVINO_NPU_BLOB_PREBUILD` and `GGML_OPENVINO_KV_SLICE` on (the defaults), K is stored head-major and V transposed, as OpenVINO GenAI does. `llama-perplexity` fails with it. |
| `GGML_OPENVINO_NPU_REQUANT_POLICY` | NPU | String | `group-128` | Layout of requantized weights: `group-128` (`Q4_0_128`) or `channel-wise` (`Q4_0_C`, lower accuracy). |
| `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK` | all | Integer | `16` | Tokens in one chunk when `GGML_OPENVINO_GDN_DECOMPOSE` is on. A power of 2 from 2 to 128; other values use `16`. |
| `GGML_OPENVINO_GDN_NATIVE_STATE` | NPU | Boolean | `0` | Keep the `GATED_DELTA_NET` state in the layout of the OpenVINO op instead of the GGML layout. Every `GATED_DELTA_NET` must then run on the OpenVINO backend; the load aborts if one would run on the CPU backend. Saved states and `GGML_OPENVINO_DEBUG_NODE` dumps hold the OpenVINO layout. `test-backend-ops` fails with it. |
-| `GGML_OPENVINO_FORCE_STATIC` | CPU, GPU | Boolean | `0` | Run the static-shape path of the NPU on the CPU or the GPU, to separate translation bugs from NPU plugin or driver problems. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. |
+| `GGML_OPENVINO_FORCE_STATIC` | CPU, GPU | Boolean | `0` | Run the static-shape path of the NPU on the CPU or the GPU, to separate translation bugs from NPU plugin or driver problems. This includes the NPU translation of MoE blocks, which computes every expert on the CPU or the GPU and is slow. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. |
| `GGML_OPENVINO_ENABLE_FALLBACK` | all | Boolean | `0` | Detect graphs that the scheduler splits between OpenVINO and another backend, and translate them as partial graphs, without the compiled model cache. By default every graph is treated as a complete model graph. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. |
-| `GGML_OPENVINO_ROPE_F32_ANGLE` | GPU | Boolean | `0` | Keep the RoPE angle in f32 under the f16 hint, for long prompts. Validated on one model. On CPU, `test-backend-ops -o ROPE` fails with it. |
+| `GGML_OPENVINO_ROPE_F32_ANGLE` | all | Boolean | `0` | Keep the RoPE angle in f32 under the f16 hint, for long prompts. Validated on one model on the GPU. On CPU, `test-backend-ops -o ROPE` fails with it. |
| `GGML_OPENVINO_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op instead of the default `relu(x) + log(1 + exp(-abs(x)))`. |
| `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | all | Boolean | `0` | Use `ScatterElementsUpdate` instead of `ScatterUpdate` for single-row KV writes in stateless execution. |
-| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | `0` | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Needs an OpenVINO build newer than 2026.4.1; do not use it with 2026.4.1. |
-| `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | `0` | Turn on `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, `GGML_OPENVINO_RELEASE_WEIGHTS`, unless they are set. |
+| `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | unset | When set, the default of `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, `GGML_OPENVINO_RELEASE_WEIGHTS`. |
| `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. |
-| `GGML_OPENVINO_RELEASE_WEIGHTS` | GPU | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Release the host weight buffers when the compiled model holds its own copy. Needs stable graph shapes; do not use it for workloads that compile again. |
+| `GGML_OPENVINO_RELEASE_WEIGHTS` | GPU | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE`, `1` if that is unset | Release the host weight buffers when the compiled model holds its own copy. Before a new graph is compiled, or when the host reads a weight, they are written again from the model file. Weights loaded without mmap (`-lm none`) stay in host memory. Linux only. |
| `GGML_OPENVINO_SPILL_DIR` | all | String | `not set` | Directory for a disk-backed weight buffer, so its pages can be reclaimed under memory pressure. It must be on real storage, not on tmpfs (`/tmp` on many systems). It is not part of the key of the compiled model cache and is ignored in cache-only mode. |
| `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. |
@@ -105,7 +116,7 @@ export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # later runs: log shows "model cache HIT"
```
-## Tips for Memory Optimization
+## Memory optimization
With the default settings, the GPU and CPU plugins keep their own copy of the weights next to the backend's copy while a model compiles. On integrated GPUs both copies are in system RAM. The settings below lower that peak. They do not change the output.
@@ -126,10 +137,9 @@ export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1
```
```bash
-# GPU, one long-running model (llama-server): release the host copy of the weights after compilation.
-# One model per process; a graph that must compile again later stops the run.
+# GPU: keep the host copy of the weights after compilation (it is released by default).
export GGML_OPENVINO_DEVICE=GPU
-export GGML_OPENVINO_MEMORY_OPTIMIZE=1
+export GGML_OPENVINO_RELEASE_WEIGHTS=0
```
```bash
@@ -149,7 +159,7 @@ export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
- A cache hit without `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1` shortens the load, but it uses about as much memory as a run without the cache.
- MoE models are not written to the cache on CPU, so cache-only mode does not work for them on CPU.
- `GGML_OPENVINO_SPILL_DIR` is ignored on Windows and in cache-only mode.
-- `-lm none` (no mmap) does not lower the memory in use, and it turns cache-only mode off.
+- `-lm none` (no mmap) does not lower the memory in use, and cache-only mode stops with an error with it: cache-only mode needs mmap loading.
## NPU plugin properties
@@ -166,19 +176,31 @@ The backend sets the properties below for the NPU. `GGML_OPENVINO_NPU_CONFIG` ca
| `NPUW_FOLD` | Boolean | `YES` | `NO` | Compile the repeating blocks of the model once and reuse them. |
| `NPUW_FUNCALL_FOR_ALL` | Boolean | `YES` | `NO` | Make every part of the model a function, not only the repeating blocks. |
| `NPUW_FUNCALL_ASYNC` | Boolean | `YES` | `NO` | Run a function and the preparation of the next one as a pipeline. |
-| `NPUW_WEIGHTS_BANK` | String | `shared` | empty | Name of the weights bank. Graphs with the same name share one copy of the weights. |
+| `NPUW_WEIGHTS_BANK` | String | `shared`; with `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, a bank of the model (`ggml-wl-model-<fingerprint>` or `ggml-wl-shared-<fingerprints>`) | empty | Name of the weights bank. Graphs with the same name share one copy of the weights. |
| `NPUW_DQ` | Boolean | `YES` | `NO` | Apply the dynamic quantization transformations in the plugin. |
| `NPUW_DQ_FULL` | Boolean | `NO` | `YES` | Apply the full dynamic quantization pipeline in the plugin. |
| `NPU_COMPILER_DYNAMIC_QUANTIZATION` | Boolean | `YES` | `NO` | Dynamic quantization in the NPU compiler. |
| `NPU_COMPILER_TYPE` | String | `DRIVER` | `PREFER_PLUGIN` | The NPU compiler: `DRIVER` (in the NPU driver), `PLUGIN` (in OpenVINO) or `PREFER_PLUGIN` (`PLUGIN` when it is available, `DRIVER` if not). Models with `GATED_DELTA_NET` layers (Qwen3.5) compile with `PLUGIN` unless the user sets this property. |
| `NPUW_CACHE_DIR` | String | value of `GGML_OPENVINO_CACHE_DIR` | empty | Directory for the compiled parts. |
-Other properties that are useful with `GGML_OPENVINO_NPU_CONFIG`. The backend does not set them.
+Graphs with a MoE block (softmax router and SwiGLU experts, translated into the batched form that NPUW recognises) also get the properties below. They make NPUW run only the routed experts, with the router on the host (the `HOST_ROUTED` mode of `NPUW_LLM_*_MOE_HINT`). `GGML_OPENVINO_NPU_CONFIG` can change them.
+
+| Property | Type | Backend default | OpenVINO default | Description |
+|---|---|---|---|---|
+| `NPUW_ONLINE_PIPELINE` | String | `REP` | `REG` | Partitioning pipeline. `REP` finds the repeating blocks, which the MoE support needs. |
+| `NPUW_ONLINE_ISOLATE` | String | `MOE` added | empty | Isolate the experts into their own functions. Added to a value that is already set. |
+| `NPUW_ONLINE_KEEP_BLOCKS_TAGGED` | String | `expert` added | empty | Keep the isolated experts even below the repeating-block threshold. |
+| `NPUW_ONLINE_KEEP_BLOCK_SIZE` | Integer | `4` | `10` | Smallest repeating block that is kept. |
+| `NPUW_UNFOLD_IREQS` | Boolean | `NO` | `NO` | One infer request for each part. |
+| `NPUW_MOE_TOKEN_CHUNK_SIZE` | Integer | `16` | `0` | Tokens per expert call in prefill. `0` compiles 8 sizes (16 to 512); one small size uses less memory. |
+| `NPUW_MOE_POOL_SIZE` | Integer | `0` | `8` | Infer requests per MoE layer kept for decode, each bound to a set of experts. With 40 MoE layers, the default of 8 fills the NPU memory of a 32 GB system and the load hangs. |
+
+Other properties for `GGML_OPENVINO_NPU_CONFIG`. The backend does not set them, except in the cases that the table names.
| Property | Type | Backend default | OpenVINO default | Description |
|---|---|---|---|---|
| `COMPILATION_NUM_THREADS` | Integer | `not set` | number of CPU cores | Threads of the NPU compiler. A lower value lowers the host memory peak when a large model compiles. |
-| `NPUW_UNFOLD_IREQS` | Boolean | `not set` | `NO` | One infer request for each part, also for repeating blocks. |
+| `NPUW_UNFOLD_IREQS` | Boolean | `not set`; `NO` on graphs with a MoE block; `YES` on the decode graph with `GGML_OPENVINO_NPU_DECODE_UNFOLD=1` | `NO` | One infer request for each part, also for repeating blocks. |
| `LOG_LEVEL` | String | `not set` | `LOG_ERROR` | Log level of the NPU plugin, for example `LOG_INFO`. |
Set properties with `GGML_OPENVINO_NPU_CONFIG`:
@@ -188,7 +210,8 @@ export GGML_OPENVINO_DEVICE=NPU
export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=1,LOG_LEVEL=LOG_INFO"
```
-List the properties of the installed NPU plugin:
+<details>
+<summary>C++ sample: list the properties of the installed NPU plugin</summary>
```cpp
// List the properties of the installed NPU plugin with their current values
@@ -198,42 +221,48 @@ for (const auto & name : core.get_property("NPU", ov::supported_properties)) {
}
```
+</details>
+
- All NPU properties: [OpenVINO NPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/npu-device.html).
- `NPUW_*` options, with type and default: `src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc` in the OpenVINO source.
- Graphs without a KV cache compile without NPUW: the backend removes `NPU_USE_NPUW` and the `NPUW_*` keys for them.
### Example: gemma-4 E2B with the model cache
-`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` saves the model compiled for the NPU, so only the first start compiles it. Run step 1 once, then start the model as in step 2 every later time.
-
-#### Step 1: first run, compile and save the model
-
-```bash
-# This start takes longer: the backend compiles the model for the NPU and saves it in the cache directory
-# (with -lv 4 the log shows "no usable cached blobs ... compiling and exporting").
-# Use the model as usual, then exit with /exit.
-export GGML_OPENVINO_DEVICE=NPU
-export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
-export GGML_OPENVINO_NPU_HOST_GATHER=1 # optional: faster generation, less memory and disk; the output can differ slightly
-export GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=q4_0_128 # optional: slightly less memory; may lower accuracy
-export GGML_OPENVINO_PREFILL_CHUNK_SIZE=512 # optional: can make long prompts faster; makes the first run longer
-./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
-```
-
-#### Step 2: later runs, load the model from the cache
-
-```bash
-# Use the same exports as in step 1 (repeat them in a new shell) and the same command.
-# The backend loads the compiled model instead of compiling it, so the model starts much faster
-# (with -lv 4 the log shows "model cache HIT"). A changed setting or -c value compiles and saves again,
-# or stops with an error when GGML_OPENVINO_SELF_CONTAINED_MMAP=1 is set.
-export GGML_OPENVINO_SELF_CONTAINED_MMAP=1 # optional, later runs only: slightly shorter start; fails without the cache of step 1
-./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
-```
+`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` saves the model compiled for the NPU, so only the first start compiles it.
+
+1. Run once to compile and save the model:
+
+ ```bash
+ # This start takes longer: the backend compiles the model for the NPU and saves it in the cache directory
+ # (with -lv 4 the log shows "no usable cached blobs ... compiling and exporting").
+ # Use the model as usual, then exit with /exit.
+ export GGML_OPENVINO_DEVICE=NPU
+ export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
+ export GGML_OPENVINO_NPU_HOST_GATHER=1 # optional: faster generation, less memory and disk; the output can differ slightly
+ export GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=q4_0_128 # optional: slightly less memory; may lower accuracy; wrong output on the Panther Lake NPU
+ export GGML_OPENVINO_PREFILL_CHUNK_SIZE=512 # optional: can make long prompts faster; makes the first run longer
+ ./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
+ ```
+
+2. On every later start, load the model from the cache:
+
+ ```bash
+ # Use the same exports as in step 1 (repeat them in a new shell) and the same command.
+ # The backend loads the compiled model instead of compiling it, so the model starts much faster
+ # (with -lv 4 the log shows "model cache HIT"). A changed setting or -c value compiles and saves again,
+ # or stops with an error when GGML_OPENVINO_SELF_CONTAINED_MMAP=1 is set.
+ export GGML_OPENVINO_SELF_CONTAINED_MMAP=1 # optional, later runs only: slightly shorter start; fails without the cache of step 1
+ ./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
+ ```
## GPU and CPU plugin properties
-The backend sets no GPU or CPU property, except `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE` when `GGML_OPENVINO_CACHE_DIR` is set.
+GPU and CPU: the backend sets no property, except:
+ - `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE` when `GGML_OPENVINO_CACHE_DIR` is set.
+ - With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`: no `CACHE_DIR`, and `CACHE_MODE=OPTIMIZE_SPEED`. This overrides the same properties in `GGML_OPENVINO_GPU_CONFIG` and `GGML_OPENVINO_CPU_CONFIG`.
+ - `ENABLE_PROFILING` with `GGML_OPENVINO_PROFILING=2` or higher.
+ - `EXECUTION_MODE_HINT` on the small graphs of op tests.
```bash
# CPU in FP16, to compare with the GPU and the NPU, which compute in FP16
diff --git a/ggml/src/ggml-openvino/dev_doc/README.md b/ggml/src/ggml-openvino/dev_doc/README.md
index 4b1021e74..f08f6a999 100644
--- a/ggml/src/ggml-openvino/dev_doc/README.md
+++ b/ggml/src/ggml-openvino/dev_doc/README.md
@@ -1,8 +1,188 @@
-# OpenVINO Qwen development documentation
+# OpenVINO backend developer documentation
-The default supported Qwen3.5/Qwen3.6 GPU path is **dynamic stateless execution with in-place fused recurrent ops and stable MTP sampling**. Unified KV is the recommended multi-slot layout because it enables native in-place attention KV updates. No new inference switch is needed for the recurrent/sampling default.
+These pages cover the internals of the OpenVINO backend on CPU, GPU and NPU, and the options for development and debugging. Build steps, device selection, validated models and the user-facing environment variables are in [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md).
-- [Backend setup and cache usage](../README.md): runtime requirements, environment settings and restrictions.
-- [Implementation](OPENVINO-RECURRENT-CACHE.md): buffer ownership, fusion, rollback, fallback and source map.
-- [Multislot MTP graph](MTP-SAMPLING-GRAPH.md): why active-slot variants occurred and how stable translation works.
-- [Environment variables for development](OpenVINO-ENV-VARS.md): debug output, switches for default optimizations, experimental options, plugin properties and older variable names.
+| Document | Content |
+|---|---|
+| This page | Qwen MTP, compiled model cache, KV-only prefill, NPU host gather, multimodal input |
+| [OpenVINO-ENV-VARS.md](OpenVINO-ENV-VARS.md) | Debug output, switches for default optimizations, experimental options, memory optimization, plugin properties, older variable names |
+| [OPENVINO-RECURRENT-CACHE.md](OPENVINO-RECURRENT-CACHE.md) | Qwen recurrent cache on GPU: buffer ownership, replay graph contract, attention KV layout, source map |
+| [MTP-SAMPLING-GRAPH.md](MTP-SAMPLING-GRAPH.md) | Multi-slot MTP draft graph: sampler behavior, graph layout, active slots, runtime row selection, compiled-model reuse |
+
+Contents of this page:
+
+- [Qwen MTP](#qwen-mtp)
+- [Compiled model cache](#compiled-model-cache)
+- [KV-only prefill](#kv-only-prefill)
+- [NPU host gather](#npu-host-gather)
+- [Multimodal](#multimodal)
+
+## Qwen MTP
+
+The OpenVINO backend translates Qwen recurrent replay for complete dynamic stateless GPU graphs and supports stable MTP sampling.
+
+Requirements:
+
+- Dynamic stateless GPU execution. OpenVINO replay requires it.
+- A GGUF model file that contains MTP weights.
+
+Options:
+
+- MTP: `--spec-type draft-mtp --spec-draft-n-max 2`.
+- Parallel execution: `-np` and `--kv-unified`. Unified KV cache is the recommended layout for multi-slot GPU execution. See [Attention KV layout](OPENVINO-RECURRENT-CACHE.md#attention-kv-layout).
+
+Recommended setup for Qwen3.6-35B-A3B Q4_K_M:
+
+- Device: GPU.
+- `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all`.
+- `GGML_OPENVINO_KV_SLICE` at its default (`1`). See [Attention KV layout](OPENVINO-RECURRENT-CACHE.md#attention-kv-layout) for eligibility.
+
+`q4_asym64_all` requantization:
+
+- Converts Q4_K, Q5_K, Q6_K, Q8_0, Q5_1 and Q5_0 weights, including dense Q8_0 projections, to asymmetric INT4 with group size 64.
+- `token_embd.weight` and `output.weight` keep symmetric channel-wise INT8.
+- Q8_0, Q5_1 and Q5_0 rows whose width is not divisible by 64 also use channel-wise INT8.
+- Follows the primary/backup precision scheme of [NNCF](https://github.com/openvinotoolkit/nncf) `INT4_ASYM` with `ratio=1.0`, `group_size=64` and `backup_mode=INT8_SYM` for these supported source types.
+- Requantizes the GGUF values, not the original floating-point model. Floating-point weights stay unchanged.
+
+Limitations:
+
+- Cache-only MTP serving requires the separate OpenVINO dynamic output-binding fix ([openvino#39354](https://github.com/openvinotoolkit/openvino/pull/39354)). Removing the recurrent cache Results does not remove that independent trigger in imported MTP graphs.
+
+Implementation details:
+
+- Buffer ownership, replay cache writeback through `Assign` sinks, and the GPU replay fusion: [Replay graph contract](OPENVINO-RECURRENT-CACHE.md#replay-graph-contract).
+- In-place attention KV update (`GGML_OPENVINO_ENABLE_KV_4D`) and `GGML_OPENVINO_KV_SLICE`: [Attention KV layout](OPENVINO-RECURRENT-CACHE.md#attention-kv-layout).
+- MTP sampling across active slots: [MTP-SAMPLING-GRAPH.md](MTP-SAMPLING-GRAPH.md).
+
+## Compiled model cache
+
+`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` exports compiled CPU and GPU graphs with their weights.
+
+- It bypasses the plugin-level `GGML_OPENVINO_CACHE_DIR` and uses `OPTIMIZE_SPEED`, so weightless caching is disabled.
+- One directory can hold blobs for different models and compilation settings.
+
+1. Run each intended workload once to export its dynamic graph:
+
+ ```sh
+ GGML_OPENVINO_DEVICE=GPU \
+ GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \
+ GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/path/to/qwen-cache \
+ ./build/ReleaseOV/bin/llama-bench -m /path/to/model.gguf -r 1
+ ```
+
+ - `GGML_OPENVINO_SPILL_DIR` remains optional for this first run.
+ - Wait for the `model cache WROTE` message and for the workload to complete before stopping it. Interrupted exports are not cache hits.
+ - Compatible prefill and decode graphs share one blob and manifest. A graph with different ports or incompatible shapes gets an exact entry instead.
+
+2. On later runs, supply the same compilation settings and set `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1`:
+
+ ```sh
+ GGML_OPENVINO_DEVICE=GPU \
+ GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \
+ GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/path/to/qwen-cache \
+ GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \
+ ./build/ReleaseOV/bin/llama-bench -m /path/to/model.gguf -r 1
+ ```
+
+Cache-only mode:
+
+- Allocates backend address space without filling weight pages. On Windows, this also uses system commit capacity. The model-buffer size in the loader log is this virtual size.
+- Weight uploads only record the source identity. They do not read or requantize the weights.
+- Skips graph conversion and compilation. Runtime buffers are still allocated and populated normally.
+- Fails with an error for a missing or incompatible graph, instead of compiling with absent weights.
+- Uses the settings of the current process. A different workload can still require another graph: populate it first without cache-only mode.
+
+Settings that must stay exactly the same between the runs, including set versus unset. A different value selects another cache entry, and cache-only mode then fails:
+
+- `GGML_OPENVINO_GPU_CONFIG`, `GGML_OPENVINO_CPU_CONFIG`, `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_EXACT_ZERO_POINT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_MANUAL_GQA_ATTN`
+- `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_KV_SCATTER_ELEMENTS`
+- `GGML_OPENVINO_GDN_NATIVE_STATE`, `GGML_OPENVINO_GDN_DECOMPOSE`, `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK`
+- `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`
+- `GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN`, `GGML_OPENVINO_ROPE_F32_ANGLE`, `GGML_OPENVINO_DEBUG_NODE`
+- `GGML_OPENVINO_ENABLE_KV_4D` (its effective value).
+- `GGML_OPENVINO_PROFILING`: only whether it is `2` or more.
+- On GPU, also `GGML_OPENVINO_MOE_OP=0` if used.
+- `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE`: not part of the cache key, but `1` makes the backend reject the replay cache stores. The graph is then split, and cache-only mode does not support split graphs.
+
+Settings that can differ:
+
+- `GGML_OPENVINO_SPILL_DIR`: optional on the first run and ignored in cache-only mode. Host-weight release is disabled in cache-only mode.
+- `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`: changes only the output bindings.
+- `GGML_OPENVINO_KV_SLICE`: a runtime binding option for dynamic graphs. The same dynamic compiled graph accepts full-capacity and live-prefix attention K/V tensors. Eligibility: [Attention KV layout](OPENVINO-RECURRENT-CACHE.md#attention-kv-layout).
+
+Cache entries:
+
+- The fingerprint uses the dynamic graph's topology, ports, model parameters, weights, settings and OpenVINO version.
+- Changing only the dynamic token or KV sizes does not require a new entry.
+- MTP draft graphs: a change of the active slot subset reuses the same compiled draft model. See [Compiled models and the cache](MTP-SAMPLING-GRAPH.md#compiled-models-and-the-cache).
+
+### Restrictions
+
+- Cache-only mode requires Linux or Windows and mmap loading (`--load-mode mmap`, or the default when all selected devices support mmap). Do not use tensor validation or mlock when trying to avoid weight reads.
+- On Windows, the backend commits virtual memory for its buffers without touching weight pages. Large models can still reach the system commit limit.
+- The model must execute entirely on OpenVINO, with dynamic CPU or GPU graphs and in-process caching enabled. Static (NPU) execution and CPU fallback are not supported in cache-only mode.
+- GGUF metadata, tokenizer data, tensor descriptors and graph construction are still needed. The llama.cpp loader is unchanged: depending on its prefetch settings, it may request pages with `MAP_POPULATE` or read-ahead on Linux, or `PrefetchVirtualMemory` on Windows. Non-mmap loading also reads the payload before the backend sees it.
+- Cache entries are identified by file identity, size, modification and change timestamps, tensor offsets, graph structure, settings and OpenVINO version. Linux uses device and inode; Windows uses volume serial and file index. Replacing, copying or modifying a GGUF model file invalidates its entries. This avoids reading weight bytes and ties the cache to the local source files. Keep those files unchanged throughout loading and inference.
+- Use the same target device and a compatible OpenVINO and plugin installation. Import support depends on the plugin: the tested CPU plugin cannot import MoE graphs that contain `GatherMatmulCompressed`. GPU MoE and CPU dense graph imports were tested.
+- Blobs contain weights and can approach the model size for each compiled graph. Import still reads those blobs and initializes the device.
+
+## KV-only prefill
+
+On the static path (NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`), models whose tail layers read the KV cache of an earlier layer (Gemma 3n/4 E-series) get a KV-only prefill by default.
+
+- The static prefill graph is compiled with only the KV-cache writes as outputs (`openvino/pass/keep_cache_results.cpp`).
+- Everything that only feeds the logits is dropped from that graph: every KV-shared layer, plus the LM head.
+- When the batch needs logits, the decode graph runs once on the output token. It rewrites the KV rows of that token and computes the dropped layers against the complete cache.
+- It is used only when attention ops of the graph share a KV cache tensor and the graph has no recurrent state.
+- If a batch needs more than one output token, or the output step fails, the backend logs a warning and uses the full prefill from then on.
+
+Environment variables:
+
+- `GGML_OPENVINO_KV_ONLY_PREFILL=0` turns it off.
+
+## NPU host gather
+
+`GGML_OPENVINO_NPU_HOST_GATHER=1` (NPU only, off by default) gathers the rows of large host-resident embedding tables on the host.
+
+- Applies to tables of at least 64 MiB with raw GGUF data.
+- The static graph gets the gathered rows through a `ggml_host_rows_<node>` input instead of an OpenVINO `Gather` over the table.
+- Without it, NPUW lifts the table to a function input. Gathering from an input that large costs about as much as streaming the whole table on every call.
+- A table used only for such lookups (the Gemma 3n/4 per-layer embedding table) is not converted or bound to the NPU at all.
+
+## Multimodal
+
+Image input is experimental.
+
+- Qwen3.5 and Gemma4 E2B image input runs on OpenVINO CPU and GPU with their matching projectors.
+- Four-slot serving was validated with unified and split KV.
+- Qwen3.5 reuses its vision graph across image resolutions. Gemma4 uses resolution-specific encoder graphs.
+
+Limitations:
+
+- NPU: work in progress. Image input fails because of dynamic shapes.
+- Gemma4 audio is not enabled. Preprocessing and Conformer still need dynamic length/block handling, runtime padding and view/state offsets, and cross-length compiled-model reuse.
+- The small weightless preprocessing graph runs uncached because of the node-count heuristic of the naive path.
+
+Gemma4 E2B image input on GPU or CPU:
+
+```bash
+# Gemma4 E2B image input on GPU (or CPU). The chat template of the model needs --jinja.
+# The projector (mmproj) file is in the same Hugging Face repository as the model.
+# The model writes its reasoning before the answer.
+export GGML_OPENVINO_DEVICE=GPU
+./build/ReleaseOV/bin/llama-mtmd-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf \
+ --mmproj mmproj-google_gemma-4-E2B-it-f16.gguf --jinja -c 4096 \
+ --image cat.jpg -p "What animal is in this image?"
+```
+
+Qwen3-VL-4B image input on GPU:
+
+```bash
+# Qwen3-VL-4B image input on GPU. Model and projector: https://huggingface.co/unsloth/Qwen3-VL-4B-Instruct-GGUF
+# -ub 128 keeps the image prefill within the memory of a 16 GB system (or use --image-max-tokens 256).
+export GGML_OPENVINO_DEVICE=GPU
+./build/ReleaseOV/bin/llama-mtmd-cli -m Qwen3-VL-4B-Instruct-Q4_K_M.gguf \
+ --mmproj mmproj-F16.gguf --jinja -c 4096 -ub 128 \
+ --image tools/mtmd/test-1.jpeg -p "Describe this image in one sentence."
+```
diff --git a/ggml/src/ggml-openvino/device/npu_config.cpp b/ggml/src/ggml-openvino/device/npu_config.cpp
index 637083066..0c469adac 100644
--- a/ggml/src/ggml-openvino/device/npu_config.cpp
+++ b/ggml/src/ggml-openvino/device/npu_config.cpp
@@ -78,6 +78,35 @@ ov::AnyMap ggml_openvino_npu_gdn_config(const ov::AnyMap & base) {
return gdn_config;
}
+ov::AnyMap ggml_openvino_npu_moe_config(const ov::AnyMap & base) {
+ ov::AnyMap moe_config = base;
+ // Same properties as the HOST_ROUTED hint of the NPUW LLM pipeline (apply_moe_config)
+ moe_config.insert({"NPUW_ONLINE_PIPELINE", "REP"});
+ moe_config.insert({"NPUW_ONLINE_KEEP_BLOCK_SIZE", "4"});
+ moe_config.insert({"NPUW_UNFOLD_IREQS", "NO"});
+ // NPUW keeps a pool of 8 infer requests per MoE layer for decode, caching the requests bound to a set of
+ // experts. Each one holds NPU memory: with 40 MoE layers (Qwen3.6-35B-A3B) the pool fills the 18 GB the NPU can
+ // address on a 32 GB system and the load hangs. A cache hit needs the same experts as an earlier token, which is
+ // rare with 256 experts, so the pool is off by default.
+ moe_config.insert({"NPUW_MOE_POOL_SIZE", "0"});
+ // Prefill runs the routed experts in chunks of tokens. By default NPUW compiles 8 chunk sizes (16 to 512); a
+ // 128-token chunk gives each of 256 experts about 4 tokens, so one small size is enough.
+ moe_config.insert({"NPUW_MOE_TOKEN_CHUNK_SIZE", "16"});
+ // tags are appended to the ones that are set
+ auto append_tag = [&](const char * key, const std::string & tag) {
+ auto it = moe_config.find(key);
+ const std::string current = it == moe_config.end() ? "" : it->second.as<std::string>();
+ if (current.empty()) {
+ moe_config[key] = tag;
+ } else if (("," + current + ",").find("," + tag + ",") == std::string::npos) {
+ moe_config[key] = current + "," + tag;
+ }
+ };
+ append_tag("NPUW_ONLINE_KEEP_BLOCKS_TAGGED", "expert");
+ append_tag("NPUW_ONLINE_ISOLATE", "MOE");
+ return moe_config;
+}
+
ov::AnyMap ggml_openvino_npu_without_npuw(const ov::AnyMap & config) {
ov::AnyMap out;
for (const auto & kv : config) {
@@ -94,7 +123,12 @@ ov::AnyMap ggml_openvino_npu_prefill_config(const ov::AnyMap & base, const GgmlO
if (ggml_openvino_npu_hfa_prefill_enabled()) {
prefill_config["NPUW_ATTN_HISTORY_SIZE_INPUT"] = decoder.get_hfa_history_input_name();
prefill_config["NPUW_ONLINE_PIPELINE"] = "REP";
- prefill_config["NPUW_ONLINE_ISOLATE"] = "ATTN";
+ // keep the tags of a MoE graph
+ const auto isolate = prefill_config.find("NPUW_ONLINE_ISOLATE");
+ prefill_config["NPUW_ONLINE_ISOLATE"] =
+ isolate != prefill_config.end() && !isolate->second.as<std::string>().empty() ?
+ "ATTN," + isolate->second.as<std::string>() :
+ std::string("ATTN");
prefill_config["NPUW_ONLINE_KEEP_BLOCK_SIZE"] = "4";
prefill_config["NPUW_UNFOLD_IREQS"] = "NO";
prefill_config["NPUW_ATTN"] = "HFA";
diff --git a/ggml/src/ggml-openvino/device/npu_config.h b/ggml/src/ggml-openvino/device/npu_config.h
index 89f41da54..0773422e2 100644
--- a/ggml/src/ggml-openvino/device/npu_config.h
+++ b/ggml/src/ggml-openvino/device/npu_config.h
@@ -25,6 +25,12 @@ ov::AnyMap ggml_openvino_npu_gdn_config(const ov::AnyMap & base);
// True when ggml_openvino_npu_gdn_config() switches the compiler. Part of the model cache key.
bool ggml_openvino_npu_gdn_uses_plugin_compiler();
+// Graphs with a MoE block in the batched form (see translate_moe_tiled). NPUW isolates the
+// experts into functions and runs only the routed experts per token, with the router on the host (the HOST_ROUTED mode of
+// NPUW_LLM_*_MOE_HINT, which only the NPUW LLM pipeline sets itself), with one expert chunk size and no expert request
+// pool. Keys the environment already sets (GGML_OPENVINO_NPU_CONFIG) are kept.
+ov::AnyMap ggml_openvino_npu_moe_config(const ov::AnyMap & base);
+
// Static prefill graph. With GGML_OPENVINO_NPU_HFA_PREFILL, switches NPUW to the HFA attention pipeline.
ov::AnyMap ggml_openvino_npu_prefill_config(const ov::AnyMap & base, const GgmlOvDecoder & decoder);
diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp
index 1eb7ae9fc..31b1aa9f1 100644
--- a/ggml/src/ggml-openvino/ggml-decoder.cpp
+++ b/ggml/src/ggml-openvino/ggml-decoder.cpp
@@ -6,6 +6,7 @@
#include "ggml-quants.h"
#include "ggml.h"
#include "utils.h"
+#include "openvino/utils.h"
#include <algorithm>
#include <cassert>
@@ -33,6 +34,7 @@
#include <stdexcept>
#include <string>
#include <unordered_map>
+#include <unordered_set>
#include <vector>
static std::set<std::string> collect_graph_output_names(const ggml_cgraph * cgraph) {
@@ -83,6 +85,7 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph,
validate_cgraph();
m_built_output_names = collect_graph_output_names(cgraph);
+ m_token_dim_ambiguous = m_compute_params.input_len == 1 && m_model_params.has_single_kv_head();
set_input_output();
compute_node_dynamic_dims();
@@ -220,6 +223,32 @@ bool GgmlOvDecoder::is_conv_state_snapshot_writeback(const ggml_tensor * node) {
dest->view_offs / row <= dest->nb[1] / row - size_t(dest->ne[3]);
}
+bool GgmlOvDecoder::is_rs_cache_gather(const ggml_tensor * node) {
+ if (node == nullptr || node->op != GGML_OP_GET_ROWS || node->src[0] == nullptr ||
+ node->src[0]->op != GGML_OP_RESHAPE || !is_recurrent_cache(node->src[0]->src[0])) {
+ return false;
+ }
+ const ggml_tensor * rows = node->src[1];
+ return rows != nullptr && rows->op == GGML_OP_VIEW && rows->view_offs == 0 && rows->src[0] != nullptr &&
+ rows->src[0]->op == GGML_OP_NONE && (rows->ne[0] == 0 || rows->ne[0] == rows->src[0]->ne[0]);
+}
+
+bool GgmlOvDecoder::is_rs_cache_read(const ggml_cgraph * cgraph, const ggml_tensor * node) {
+ if (node == nullptr || node->op != GGML_OP_VIEW || node->src[0] == nullptr || node->src[0]->op != GGML_OP_RESHAPE ||
+ !is_recurrent_cache(node->src[0]->src[0]) || node->ne[0] != node->src[0]->ne[0] || node->ne[1] < 1 ||
+ node->ne[2] != 1 || node->ne[3] != 1 || node->nb[1] != node->src[0]->nb[1] ||
+ node->view_offs % node->src[0]->nb[1] != 0) {
+ return false;
+ }
+ for (int i = 0; i < cgraph->n_nodes; i++) {
+ const ggml_tensor * user = cgraph->nodes[i];
+ if (is_inplace_op(user) && (user->op == GGML_OP_CPY ? user->src[1] : user->src[0]) == node) {
+ return false;
+ }
+ }
+ return true;
+}
+
// MoE expert aggregation (build_moe_ffn in llama-graph.cpp): each expert plane is
// `ggml_view_2d(experts, n_embd, n_tokens, experts->nb[2], i*experts->nb[1])` and the planes
// are summed with a chain of ADDs: moe_out = ((view_0 + view_1) + view_2) + ... + view_{n-1}.
@@ -267,6 +296,96 @@ bool is_moe_expert_sum_add(const ggml_tensor * node) {
return base != nullptr && base->ne[1] > 1 && plane_indices.size() == static_cast<size_t>(base->ne[1]);
}
+// Walks the graph that build_moe_ffn emits for a softmax router with SwiGLU experts:
+// probs = softmax(logits); ids = top_k(probs); w = get_rows(probs, ids); [w = w / clamp(sum_rows(w))]
+// out = sum_i(down(swiglu(gate(x, ids), up(x, ids)), ids)[i] * w[i])
+// and returns false for any other shape of the block (bias on the router, sigmoid gating, scaled weights, GELU ...).
+bool match_moe_block(const ggml_tensor * sum_add, moe_block & block) {
+ // build_moe_ffn reshapes the router probs and the weights between the steps matched below
+ auto skip_reshape = [](const ggml_tensor * t) {
+ while (t != nullptr && t->op == GGML_OP_RESHAPE) {
+ t = t->src[0];
+ }
+ return t;
+ };
+
+ if (sum_add->op != GGML_OP_ADD || !is_moe_expert_sum_add(sum_add)) {
+ return false;
+ }
+ const ggml_tensor * plane = sum_add;
+ while (plane->op == GGML_OP_ADD) {
+ plane = plane->src[0];
+ }
+ const ggml_tensor * weighted = plane->src[0];
+ if (weighted == nullptr || weighted->op != GGML_OP_MUL) {
+ return false;
+ }
+ const ggml_tensor * down = weighted->src[0];
+ if (down == nullptr || down->op != GGML_OP_MUL_MAT_ID) {
+ return false;
+ }
+ const ggml_tensor * glu = down->src[1];
+ if (glu == nullptr || glu->op != GGML_OP_GLU || ggml_get_glu_op(glu) != GGML_GLU_OP_SWIGLU ||
+ ggml_get_op_params_i32(glu, 1) != 0) {
+ return false;
+ }
+ const ggml_tensor * gate = glu->src[0];
+ const ggml_tensor * up = glu->src[1];
+ const ggml_tensor * ids = down->src[2];
+ if (gate == nullptr || up == nullptr || gate->op != GGML_OP_MUL_MAT_ID || up->op != GGML_OP_MUL_MAT_ID ||
+ gate->src[1] != up->src[1] || gate->src[2] != ids || up->src[2] != ids) {
+ return false;
+ }
+ // translate_moe_tiled applies no scale of ggml_mul_mat_id_ext
+ for (const ggml_tensor * mm : {gate, up, down}) {
+ if (ggml_get_src_scale(mm, 0) || ggml_get_src_scale(mm, 1)) {
+ return false;
+ }
+ }
+ // ids = view(argsort(probs)) or top_k(probs)
+ const ggml_tensor * selection = ids;
+ while (selection != nullptr && selection->op == GGML_OP_VIEW) {
+ selection = selection->src[0];
+ }
+ if (selection == nullptr || (selection->op != GGML_OP_ARGSORT && selection->op != GGML_OP_TOP_K) ||
+ selection->src[0] == nullptr || selection->src[0]->op != GGML_OP_SOFT_MAX) {
+ return false;
+ }
+ const ggml_tensor * probs = selection->src[0];
+
+ const ggml_tensor * w = skip_reshape(weighted->src[1]);
+ const ggml_tensor * clamp = nullptr;
+ if (w != nullptr && w->op == GGML_OP_DIV) {
+ const ggml_tensor * den = w->src[1];
+ if (den == nullptr || den->op != GGML_OP_CLAMP || den->src[0] == nullptr ||
+ den->src[0]->op != GGML_OP_SUM_ROWS || skip_reshape(den->src[0]->src[0]) != skip_reshape(w->src[0])) {
+ return false;
+ }
+ float bounds[2];
+ memcpy(bounds, den->op_params, sizeof(bounds));
+ if (bounds[1] < 1e30f) {
+ return false; // only a lower bound is translated
+ }
+ clamp = den;
+ w = skip_reshape(w->src[0]);
+ }
+ if (w == nullptr || w->op != GGML_OP_GET_ROWS || w->src[1] != ids || skip_reshape(w->src[0]) != probs) {
+ return false;
+ }
+ if (gate->src[0]->ne[2] != probs->ne[0] || gate->src[0]->ne[2] <= ids->ne[0]) {
+ return false;
+ }
+
+ block.probs = probs;
+ block.x = gate->src[1];
+ block.gate = gate->src[0];
+ block.up = up->src[0];
+ block.down = down->src[0];
+ block.down_out = down;
+ block.clamp = clamp;
+ return true;
+}
+
std::string GgmlOvDecoder::get_tensor_name(const ggml_cgraph * cgraph, const ggml_tensor * tensor) {
if (tensor == nullptr) {
return "";
@@ -302,12 +421,24 @@ static std::string get_tensor_ov_name(const ggml_cgraph * cgraph, const ggml_ten
return GgmlOvDecoder::get_tensor_name(cgraph, tensor);
}
+std::string GgmlOvDecoder::get_position_input_ov_name(const ggml_tensor * tensor) const {
+ // Keep independent spatial position tensors on independent ports.
+ for (int i = 0; i < m_cgraph->n_nodes; ++i) {
+ const auto * node = m_cgraph->nodes[i];
+ if (node->op == GGML_OP_ROPE) {
+ if (node->src[1] != tensor) { return get_tensor_name(m_cgraph, tensor); }
+ break;
+ }
+ }
+ return "inp_pos";
+}
+
static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder,
const ggml_cgraph * cgraph,
const ggml_tensor * tensor,
const ggml_tensor * op) {
if (GgmlOvDecoder::is_inp_pos(tensor, op)) {
- return "inp_pos";
+ return decoder->get_position_input_ov_name(tensor);
}
if (GgmlOvDecoder::is_inp_emb(tensor, op)) {
return "embd";
@@ -353,6 +484,8 @@ static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder,
}
void GgmlOvDecoder::set_input_output() {
+ m_moe_tiled_replaced.clear();
+ m_has_moe_block = false;
for (int node_n = 0; node_n < m_cgraph->n_nodes; node_n++) {
auto * node = m_cgraph->nodes[node_n];
@@ -404,6 +537,29 @@ void GgmlOvDecoder::set_input_output() {
}
}
+ // The expert sum of a MoE block also reads the router, the input and the expert weights (translate_moe_tiled).
+ moe_block block;
+ if (ggml_openvino_moe_tiled_enabled() && match_moe_block(node, block)) {
+ m_has_moe_block = true;
+ for (const ggml_tensor * t : {block.probs, block.x, block.gate, block.up, block.down, block.down_out, block.clamp}) {
+ if (t != nullptr) {
+ auto name = get_tensor_ov_name(m_cgraph, t);
+ current_node_info.node_inputs[name] = const_cast<ggml_tensor *>(t);
+ current_node_info.node_inputs_names.push_back(name);
+ }
+ }
+ // the ADD chain below this node and its expert-plane VIEWs
+ for (const ggml_tensor * cur = node; cur->op == GGML_OP_ADD; cur = cur->src[0]) {
+ if (cur != node) {
+ m_moe_tiled_replaced.insert(cur);
+ }
+ m_moe_tiled_replaced.insert(cur->src[1]);
+ if (cur->src[0]->op != GGML_OP_ADD) {
+ m_moe_tiled_replaced.insert(cur->src[0]);
+ }
+ }
+ }
+
m_node_info_list.push_back(current_node_info);
}
}
@@ -435,6 +591,29 @@ bool GgmlOvDecoder::is_gdn_out_prescaled(const ggml_tensor * gdn) const {
return has_norm;
}
+static bool is_gdn_output_gate_view(const ggml_tensor * node, const ggml_cgraph * graph) {
+ if (node->op != GGML_OP_VIEW || !ggml_is_contiguous(node) || node->view_offs != 0 ||
+ !node->src[0] || node->src[0]->op != GGML_OP_MUL_MAT ||
+ ggml_nelements(node) != ggml_nelements(node->src[0])) {
+ return false;
+ }
+ for (int i = 0; i < graph->n_nodes; ++i) {
+ const auto * consumer = graph->nodes[i];
+ if (consumer->op != GGML_OP_MUL || std::memcmp(node->ne, consumer->ne, sizeof(node->ne)) != 0) { continue; }
+ for (int j = 0; j < 2; ++j) {
+ const auto * gate = consumer->src[j];
+ const auto * norm = consumer->src[1 - j];
+ if (gate->op != GGML_OP_UNARY || gate->src[0] != node) { continue; }
+ if (norm->op == GGML_OP_MUL) { norm = norm->src[0]; }
+ if (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_VIEW &&
+ norm->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
int op_case = 0;
switch (node->op) {
@@ -485,6 +664,9 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
seq = node;
}
recurrent_sequence = seq == node;
+ } else if (concat->op == GGML_OP_CONT && concat->src[0]->op == GGML_OP_TRANSPOSE) {
+ const auto * cols = concat->src[0]->src[0];
+ recurrent_sequence = cols->op == GGML_OP_CONCAT && cols->op_params[0] == 1 && cols->src[1] == node;
}
} else if (consumer->op == GGML_OP_UNARY && ggml_get_unary_op(consumer) == GGML_UNARY_OP_SOFTPLUS) {
const auto * biased = consumer->src[0];
@@ -664,6 +846,11 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
if (node->src[1]->op == GGML_OP_VIEW) {
op_case = node->src[1]->view_offs == 0 ? 1 : 2;
}
+ // op_case 3: every s_copy row (is_rs_cache_gather). States in place map the ubatch cells to
+ // themselves, so the whole gather moves nothing, like the empty one.
+ if (!m_is_static && m_compute_params.s_copy_active_slot_len != -1 && is_rs_cache_gather(node)) {
+ op_case = 3;
+ }
} else if (is_get_rows_batched_4d(node)) {
// with one token the batch dims look like a 3D gather; the tracked token dim tells them apart
const auto it = m_node_dynamic_dims.find(const_cast<ggml_tensor *>(node));
@@ -699,16 +886,28 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
break;
}
case GGML_OP_VIEW: {
+ if (!m_naive && !m_is_static && is_gdn_output_gate_view(node, m_cgraph)) {
+ return 5;
+ }
if (is_sampling_view(node)) {
return 3;
}
- if (node->view_offs == 0 && node->src[0]->op == GGML_OP_GET_ROWS &&
- is_recurrent_cache(node->src[0]->src[0]) && node->ne[0] == node->src[0]->ne[0] &&
- node->ne[2] == 1 && node->ne[3] == 1 && m_compute_params.s_copy_active_slot_len != -1) {
+ if (m_moe_tiled_replaced.count(node)) {
+ return 1; // identity: expert-plane view of an expert sum replaced by translate_moe_tiled
+ }
+ if (node->view_offs == 0 && node->src[0]->op == GGML_OP_GET_ROWS && is_recurrent_cache(node->src[0]->src[0]) &&
+ node->ne[0] == node->src[0]->ne[0] && node->ne[2] == 1 && node->ne[3] == 1 &&
+ m_compute_params.s_copy_active_slot_len != -1 && (m_is_static || !is_rs_cache_gather(node->src[0]))) {
// build_rs gathers active and inactive rows together; consumers need only the
// active prefix, whose length changes independently of the gather's row count.
+ // The rows moved into the cache are sliced by the writeback (rs_src_begin) instead.
return 4;
}
+ if (!m_is_static && m_compute_params.s_copy_active_slot_len != -1 &&
+ m_compute_params.rs_read_slots.count(get_tensor_ov_name(m_cgraph, node)) != 0) {
+ // the ubatch states read from the cache, at a first slot that moves with the batch
+ return 6;
+ }
if (is_direct_gdn_view(node)) {
// The GDN translator publishes native attention/state outputs under these VIEW names.
op_case = 2;
@@ -856,7 +1055,15 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
break;
}
case GGML_OP_ADD: {
- if (is_moe_expert_sum_add(node)) {
+ if (m_moe_tiled_replaced.count(node)) {
+ op_case = 4; // inner ADD of an expert sum replaced by translate_moe_tiled
+ break;
+ }
+ moe_block block;
+ if (ggml_openvino_moe_tiled_enabled() && match_moe_block(node, block)) {
+ // The whole MoE block in the batched form: 2 with the weights as they are, 3 normalized and clamped
+ op_case = block.clamp != nullptr ? 3 : 2;
+ } else if (is_moe_expert_sum_add(node)) {
// Outermost ADD of a MoE expert-plane sum chain: translated as a single
// ReduceSum over the base tensor instead of N-1 chained Adds over N Slices.
op_case = 1;
@@ -947,9 +1154,114 @@ static const ggml_tensor * softmax_scores_source(const ggml_tensor * scores) {
return scores;
}
-std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgraph * cgraph, bool is_static) {
+std::vector<int64_t> GgmlOvDecoder::vision_reshape_pattern(const ggml_tensor * node) {
+ const auto * src = node->src[0];
+ if (node->op == GGML_OP_CONT && std::memcmp(node->ne, src->ne, sizeof(node->ne)) == 0) {
+ // No reshape is emitted; all dimensions come directly from the input.
+ return {-2, -2, -2, -2};
+ }
+ if (node->ne[2] == 1 && node->ne[3] == 1) {
+ return {1, 1, -1, node->ne[0]};
+ }
+ if (node->op == GGML_OP_RESHAPE && src->op == GGML_OP_MUL_MAT && src->src[0] &&
+ src->src[0]->op == GGML_OP_RESHAPE && src->src[0]->src[0]->op == GGML_OP_IM2COL &&
+ node->ne[2] == 1 && node->ne[3] == src->ne[1]) {
+ // Unflatten patch convolution: [channels, 1, patch_height, patch_width].
+ return {node->ne[3], 1, -2, -2};
+ }
+ if (node->op == GGML_OP_RESHAPE && src->op == GGML_OP_CONT && src->ne[3] == 1 &&
+ node->ne[0] == src->ne[0] && node->ne[1] == src->ne[1] && node->ne[2] * node->ne[3] == src->ne[2]) {
+ // Split rows into fixed-size merge groups while retaining both grid axes.
+ return {-2, node->ne[2], -2, node->ne[0]};
+ }
+ if (node->op == GGML_OP_CONT && src->ne[3] == 1 && node->ne[3] == 1 &&
+ node->ne[2] == src->ne[2] && node->ne[0] * node->ne[1] == src->ne[0] * src->ne[1]) {
+ // Merge adjacent patch features into each column; the feature width is fixed.
+ return {1, -2, -2, node->ne[0]};
+ }
+ return {-2, -2, -2, -2};
+}
+
+bool GgmlOvDecoder::is_dynamic_vision_graph(const ggml_cgraph * cgraph) {
+ bool image_patches = false, vision_rope = false, attention = false;
+ // Recognize the operation patterns covered by the dynamic patch-encoder path.
+ // Reject language graphs before allocating the set used to check external sources.
+ for (int i = 0; i < cgraph->n_nodes; ++i) {
+ const auto * node = cgraph->nodes[i];
+ switch (node->op) {
+ case GGML_OP_NONE: case GGML_OP_RESHAPE: case GGML_OP_PERMUTE: case GGML_OP_CONT:
+ case GGML_OP_VIEW: case GGML_OP_MUL_MAT: case GGML_OP_ADD: case GGML_OP_MUL:
+ case GGML_OP_NORM: case GGML_OP_RMS_NORM: case GGML_OP_UNARY: case GGML_OP_CPY:
+ break;
+ case GGML_OP_IM2COL:
+ if (node->op_params[6] != 1) { return false; }
+ image_patches |= node->src[1] && node->src[1]->op == GGML_OP_NONE &&
+ (node->src[1]->flags & GGML_TENSOR_FLAG_INPUT);
+ break;
+ case GGML_OP_UPSCALE:
+ // Spatial position-grid interpolation; channel/batch resampling stays static.
+ if (node->ne[2] != node->src[0]->ne[2] || node->ne[3] != node->src[0]->ne[3]) { return false; }
+ break;
+ case GGML_OP_ROPE:
+ if (node->op_params[2] != GGML_ROPE_TYPE_VISION) { return false; }
+ vision_rope = true;
+ break;
+ case GGML_OP_FLASH_ATTN_EXT:
+ if (node->src[3] || node->src[4]) { return false; }
+ attention = true;
+ break;
+ default:
+ return false;
+ }
+ }
+ if (!image_patches || !vision_rope || !attention) {
+ return false;
+ }
+ std::unordered_set<const ggml_tensor *> nodes;
+ nodes.reserve(cgraph->n_nodes);
+ for (int i = 0; i < cgraph->n_nodes; ++i) {
+ nodes.insert(cgraph->nodes[i]);
+ }
+ // Require declared inputs or weights at graph boundaries before enabling spatial reuse.
+ for (int i = 0; i < cgraph->n_nodes; ++i) {
+ for (const auto * src : cgraph->nodes[i]->src) {
+ if (!src || nodes.count(src)) { continue; }
+ const auto * root = src->view_src ? src->view_src : src;
+ if (!(root->flags & GGML_TENSOR_FLAG_INPUT) &&
+ !(root->buffer && root->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) { return false; }
+ }
+ }
+ return true;
+}
+
+std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgraph * cgraph,
+ bool is_static,
+ bool dynamic_vision) {
ModelParams model_params;
ComputeParams compute_params;
+ model_params.is_dynamic_vision = !is_static && dynamic_vision;
+ if (model_params.is_dynamic_vision) {
+ for (int i = 0; i < cgraph->n_nodes; ++i) {
+ const auto * node = cgraph->nodes[i];
+ const auto name = get_tensor_ov_name(cgraph, node);
+ const auto * root = node->view_src ? node->view_src : node;
+ const bool weight = root->buffer && root->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS;
+ if ((node->op == GGML_OP_RESHAPE || node->op == GGML_OP_CONT) && !weight) {
+ const auto shape = get_shape(node);
+ compute_params.vision_shapes["vision_shape_" + name] = {shape.begin(), shape.end()};
+ }
+ if (node->op == GGML_OP_UPSCALE) {
+ compute_params.vision_shapes["vision_size_" + name] = {node->ne[1], node->ne[0]};
+ if ((node->op_params[0] & 0xff) == GGML_SCALE_MODE_BILINEAR &&
+ (node->op_params[0] & GGML_SCALE_FLAG_ANTIALIAS)) {
+ compute_params.vision_projections["vision_y_" + name] =
+ ov::frontend::ggml::bilinear_antialias_projection(node->src[0]->ne[1], node->ne[1], false);
+ compute_params.vision_projections["vision_x_" + name] =
+ ov::frontend::ggml::bilinear_antialias_projection(node->src[0]->ne[0], node->ne[0], true);
+ }
+ }
+ }
+ }
auto get_attention_pattern_case = [](const ggml_tensor * node) -> int {
if (node == nullptr) {
return -1;
@@ -1360,6 +1672,10 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
compute_params.cache_rs_reset_len = ggml_nelements(node) / node->view_src->ne[0];
compute_params.cache_rs_reset_idx = node->src[0]->view_offs / node->view_src->nb[1];
}
+ if (!is_static && is_rs_cache_read(cgraph, node)) {
+ compute_params.rs_read_slots[get_tensor_ov_name(cgraph, node)] =
+ (int64_t) (node->view_offs / node->src[0]->nb[1]);
+ }
// Capture the destination slot block of every recurrent state cache writeback, plus the
// source window needed by conv state and packed GDN rollback writes. The active sequences
// occupy a contiguous slot block [begin, begin + n_seqs) of the cache; these offsets move
@@ -1372,7 +1688,7 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
const bool is_extra_view = node->src[0]->op == GGML_OP_VIEW &&
node->src[0]->src[0]->op == GGML_OP_GET_ROWS;
const bool is_extra = node->src[0]->op == GGML_OP_GET_ROWS || is_extra_view;
- const bool is_gdn_rollback = is_gdn && is_same_shape(node->src[0], node->src[1]);
+ const bool is_gdn_rollback = is_gdn && node->src[0]->src[0]->op_params[1] == 0 && is_same_shape(node->src[0], node->src[1]);
const ggml_tensor * dest_view = node->src[1];
const ggml_tensor * cache = node->view_src;
@@ -1394,6 +1710,11 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
writeback.src_begin = (int) (node->src[0]->view_offs / node->src[0]->view_src->nb[1]);
} else if (is_extra_view) {
writeback.src_begin = (int) (node->src[0]->view_offs / row_bytes);
+ if (!is_static && is_rs_cache_gather(node->src[0]->src[0])) {
+ // the OV gather keeps the n_rs - rows states that build_rs skips (GET_ROWS op_case 3)
+ const ggml_tensor * rows = node->src[0]->src[0]->src[1];
+ writeback.src_begin += (int) (rows->src[0]->ne[0] - rows->ne[0]);
+ }
}
compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback;
}
@@ -1454,7 +1775,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
// The GPU plugin keeps device memory for each KV length it sees, and llama.cpp grows the KV length in steps of
// 256. Round it up (ggml_openvino_gpu_kv_window), so that a long context uses a few lengths and not one per step.
// The KQ mask input is padded to this length with -inf (convert_ggml_input_to_ov).
- if (!is_static && ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") &&
+ if (!is_static && ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_GPU_KV_ROUND_UP", 1) &&
+ !ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") &&
!compute_params.mask_name.empty() && compute_params.attention_size > 0 && model_params.ctx_per_seq > 0) {
compute_params.attention_size = ggml_openvino_gpu_kv_window(compute_params.attention_size,
model_params.ctx_per_seq, compute_params.input_len);
@@ -1488,6 +1810,11 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
ov::PartialShape input_shape;
bool kv_layout_4d = false;
+ if (m_model_params.is_dynamic_vision && input && op->op == GGML_OP_IM2COL &&
+ input == op->src[1]) {
+ return ov::PartialShape{input->ne[3], input->ne[2], -1, -1};
+ }
+
if (is_inp_tok(input, op) || is_inp_pos(input, op)) {
// tokens or positions
int len = m_is_static ? (m_is_prefill ? m_prefill_chunk_size : 1) : -1;
@@ -1702,6 +2029,22 @@ void GgmlOvDecoder::add_extra_inputs() {
m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1}, value, force_parameter || !m_is_static, {}, -1};
};
+ for (const auto & [name, shape] : m_compute_params.vision_shapes) {
+ m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{shape.size()}, 0, true, {}, -1};
+ }
+ for (int i = 0; i < m_cgraph->n_nodes && !m_compute_params.vision_projections.empty(); ++i) {
+ const auto * node = m_cgraph->nodes[i];
+ if (node->op != GGML_OP_UPSCALE) { continue; }
+ const auto name = get_tensor_ov_name(m_cgraph, node);
+ if (m_compute_params.vision_projections.count("vision_y_" + name) == 0) { continue; }
+ m_model_extra_inputs["vision_y_" + name] = {ov::element::f32,
+ ov::Shape{size_t(node->ne[1]), size_t(node->src[0]->ne[1])}, 0, true, {}, -1,
+ ov::PartialShape{-1, node->src[0]->ne[1]}};
+ m_model_extra_inputs["vision_x_" + name] = {ov::element::f32,
+ ov::Shape{size_t(node->src[0]->ne[0]), size_t(node->ne[0])}, 0, true, {}, -1,
+ ov::PartialShape{node->src[0]->ne[0], -1}};
+ }
+
if (m_compute_params.attention_size != -1) {
create_1d_input("attention_size", m_compute_params.attention_size);
}
@@ -1804,6 +2147,11 @@ void GgmlOvDecoder::add_extra_inputs() {
}
}
+ if (m_compute_params.s_copy_active_slot_len != -1) {
+ for (const auto & [node_name, slot] : m_compute_params.rs_read_slots) {
+ create_1d_input("rs_slot_begin_" + node_name, slot);
+ }
+ }
for (const auto & [node_name, writeback] : m_compute_params.rs_writebacks) {
create_1d_input("rs_slot_begin_" + node_name, writeback.slot_begin);
if (!m_is_static && writeback.src_begin >= 0) {
@@ -1817,62 +2165,51 @@ void GgmlOvDecoder::add_extra_inputs() {
create_1d_input("rs_window_count_" + node_name, writeback.window_count);
}
}
-#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
m_compute_params.recurrent_controls.clear();
- // Naive graphs have no full-model cache fusion and node cases are not initialized here.
if (!m_naive && !m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() &&
!ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) {
for (int i = 0; i < m_cgraph->n_nodes; ++i) {
- const auto node = m_cgraph->nodes[i];
- const auto op_case = m_node_info_list[i].node_op_case;
- if (node->op == GGML_OP_CPY && (op_case == 10 || op_case == 12)) {
- m_model_extra_inputs["rs_update_" + get_tensor_ov_name(m_cgraph, node)] =
- {ov::element::i64, ov::Shape{1, 1, 1, 4}, 0, true, {}, -1};
- }
- }
- for (const auto & [name, write] : m_compute_params.rs_writebacks) {
- if (write.src_begin >= 0) {
- auto & values = m_compute_params.recurrent_controls["rs_offsets_" + name];
- values = {write.slot_begin, write.src_begin};
- m_model_extra_inputs["rs_offsets_" + name] =
- {ov::element::i64, ov::Shape{1, 1, 1, 2}, 0, true, {}, -1};
- }
- }
- for (int i = 0; i < m_cgraph->n_nodes; ++i) {
- const auto concat = m_cgraph->nodes[i];
- if (concat->op != GGML_OP_CONCAT || !concat->src[0] || concat->src[0]->op != GGML_OP_RESHAPE ||
- !concat->src[0]->src[0] || concat->src[0]->src[0]->op != GGML_OP_VIEW ||
- concat->src[0]->src[0]->src[0]->op != GGML_OP_GET_ROWS) {
- continue;
- }
- std::vector<int64_t> values;
- for (int j = i + 1; j < m_cgraph->n_nodes; ++j) {
- const auto write = m_cgraph->nodes[j];
- if ((is_conv_state_writeback(write) || is_conv_state_snapshot_writeback(write)) &&
- write->src[0]->src[0] == concat) {
- const auto it = m_compute_params.rs_writebacks.find(get_tensor_ov_name(m_cgraph, write));
- if (it == m_compute_params.rs_writebacks.end()) {
- values.clear();
- break;
- }
- const auto & wb = it->second;
- const int64_t count = wb.window_count >= 0 ? wb.window_count : 1;
- for (int64_t w = 0; w < count; ++w) {
- values.push_back(wb.src_begin + w);
- values.push_back(wb.slot_begin + (count - 1 - w) *
- (wb.window_count >= 0 ? wb.snapshot_stride : 0));
- }
- break;
+ const auto gdn = m_cgraph->nodes[i];
+ if (gdn->op != GGML_OP_GATED_DELTA_NET || gdn->op_params[1] <= 0) continue;
+ const auto B = gdn->src[2]->ne[3];
+ const ggml_tensor * rows = gdn->src[5];
+ while (rows && (rows->op == GGML_OP_VIEW || rows->op == GGML_OP_RESHAPE)) rows = rows->src[0];
+ if (!rows || rows->op != GGML_OP_GET_ROWS) continue;
+ rows = rows->src[1];
+ while (rows && rows->op == GGML_OP_VIEW) rows = rows->src[0];
+ if (!rows || rows->type != GGML_TYPE_I32 || !rows->data || !gdn->src[9]->data) continue;
+ const ggml_tensor * root = gdn->src[5];
+ while (root && (root->op == GGML_OP_VIEW || root->op == GGML_OP_RESHAPE || root->op == GGML_OP_GET_ROWS)) root = root->src[0];
+ int64_t head = -1, reset_begin = 0, reset_count = 0;
+ for (int j = 0; j < m_cgraph->n_nodes; ++j) {
+ const auto t = m_cgraph->nodes[j];
+ if (t->view_src != root) continue;
+ if (t->op == GGML_OP_CPY && t->src[0]->op == GGML_OP_VIEW && t->src[0]->src[0] == gdn)
+ head = t->src[1]->view_offs / root->nb[1];
+ if (is_recurrent_cache_reset(t)) {
+ reset_begin = t->src[0]->view_offs / root->nb[1];
+ reset_count = ggml_nelements(t->src[0]) / root->ne[0];
}
}
- if (!values.empty()) {
- const auto name = "rs_windows_" + get_tensor_ov_name(m_cgraph, concat);
- m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1, 1, values.size() / 2, 2}, 0, true, {}, -1};
- m_compute_params.recurrent_controls[name] = std::move(values);
- }
+ if (head < 0) continue;
+ auto & map = m_compute_params.recurrent_controls["rs_replay_rows"];
+ auto & control = m_compute_params.recurrent_controls["rs_replay_control"];
+ auto & resets = m_compute_params.recurrent_controls["rs_replay_reset"];
+ map.clear(); control.clear(); resets.clear();
+ const auto * copy = static_cast<const int32_t *>(rows->data);
+ for (int64_t j = 0; j < ggml_nelements(rows); ++j) {
+ if (j < B || head + j != copy[j]) { map.push_back(head + j); map.push_back(copy[j]); }
+ }
+ const auto * counts = static_cast<const int32_t *>(gdn->src[9]->data);
+ for (int64_t j = 0; j < B; ++j) control.push_back(counts[j]);
+ control.push_back(gdn->op_params[2]);
+ for (int64_t j = 0; j < reset_count; ++j) resets.push_back(reset_begin + j);
+ m_model_extra_inputs["rs_replay_rows"] = {ov::element::i64, ov::Shape{1, 1, map.size() / 2, 2}, 0, true, {}, -1, ov::PartialShape{1, 1, -1, 2}};
+ m_model_extra_inputs["rs_replay_control"] = {ov::element::i64, ov::Shape{1, 1, 1, control.size()}, 0, true, {}, -1, ov::PartialShape{1, 1, 1, -1}};
+ m_model_extra_inputs["rs_replay_reset"] = {ov::element::i64, ov::Shape{1, 1, 1, resets.size()}, 0, true, {}, -1, ov::PartialShape{1, 1, 1, -1}};
+ break;
}
}
-#endif
if (!m_is_static && !m_compute_params.sampling_rows.empty()) {
m_model_extra_inputs["sampling_rows"] =
{ov::element::i64, ov::Shape{m_compute_params.sampling_rows.size()}, 0, true, {}, -1};
@@ -2093,8 +2430,8 @@ const ggml_tensor * GgmlOvDecoder::get_tensor_used_op(const ggml_tensor * tensor
}
bool GgmlOvDecoder::is_kvcache_4d(const ggml_tensor * cache) const {
- static const bool enabled = ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_KV_4D") > 0;
- if (!enabled || m_is_static || m_is_stateful || m_model_is_splitted || !ggml_openvino_is_gpu()) {
+ if (!ggml_openvino_kv_4d_enabled() || m_is_static || m_is_stateful || m_model_is_splitted ||
+ !ggml_openvino_is_gpu()) {
return false;
}
// `-fa off` (transposed V cache): keep the [1, 1, ctx, n_heads_kv * head_size] layout. The 4-D K cache breaks the
@@ -2828,6 +3165,15 @@ int32_t GgmlOvDecoder::get_op_dynamic_dim(int node_idx) const {
return it->second;
}
+int32_t GgmlOvDecoder::get_view_input_dynamic_dim(int node_idx, const std::string & name, size_t view_index) const {
+ auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
+ if (it == m_node_info_list[node_idx].node_inputs_views.end() || view_index >= it->second.size()) {
+ return -1;
+ }
+ auto dim = m_node_dynamic_dims.find(it->second[view_index].second);
+ return dim == m_node_dynamic_dims.end() ? -1 : dim->second;
+}
+
const std::string & GgmlOvDecoder::get_op_name(int node_idx) const {
return m_node_info_list[node_idx].node_name;
}
@@ -3036,7 +3382,12 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
}
break;
}
- case GGML_OP_TRANSPOSE:
+ case GGML_OP_TRANSPOSE: {
+ // dims 0 and 1 swap, also when they have the same size (MLA: 512 head dim and 512 KV cells)
+ const int src_dim = m_node_dynamic_dims[node->src[0]];
+ m_node_dynamic_dims[node] = src_dim == 0 || src_dim == 1 ? 1 - src_dim : src_dim;
+ break;
+ }
case GGML_OP_RESHAPE: {
if (is_same_shape(node->src[0], node)) {
m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h
index 4c2106df9..ec017a8f5 100644
--- a/ggml/src/ggml-openvino/ggml-decoder.h
+++ b/ggml/src/ggml-openvino/ggml-decoder.h
@@ -35,6 +35,7 @@ struct ModelParams {
bool has_rs_rollback = false;
bool mixed_rope_params = false;
bool is_cacheless_attn = false;
+ bool is_dynamic_vision = false;
// the graph writes a transposed V cache (`-fa off`: one value element per row, tokens along the row)
bool v_trans = false;
// the graph has FLASH_ATTN_EXT with logit soft-capping (gemma-2)
@@ -77,6 +78,19 @@ struct ModelParams {
}
bool kv_buffer_changed(const ModelParams & other) const { return kv_buffer_ctx_id != other.kv_buffer_ctx_id; }
+
+ // one KV head in some layer (MLA's compressed KV, MQA)
+ bool has_single_kv_head() const {
+ if (n_heads_kv == 1) {
+ return true;
+ }
+ for (const auto & layer : n_heads_kv_per_layer) {
+ if (layer.second == 1) {
+ return true;
+ }
+ }
+ return false;
+ }
};
struct ComputeParams {
@@ -140,6 +154,11 @@ struct ComputeParams {
std::map<std::string, int64_t> sampling_rows;
std::map<std::string, int64_t> gdn_attention_rows;
std::map<std::string, std::vector<int64_t>> recurrent_controls;
+ // GGML layout metadata that cannot be recovered after flattening a vision grid.
+ std::map<std::string, std::vector<int64_t>> vision_shapes;
+ std::map<std::string, std::vector<float>> vision_projections;
+ // First cache slot of each read of the ubatch states from the cache (is_rs_cache_read), per batch.
+ std::map<std::string, int64_t> rs_read_slots;
};
// defined below; declared here because GgmlOvDecoder uses it inline
@@ -148,8 +167,27 @@ std::optional<int> extract_layer_from_name(const std::string & name);
// detects the MoE expert-plane-sum ADD chain (see definition); used by supports_op too
bool is_moe_expert_sum_add(const ggml_tensor * node);
+// The tensors of one MoE block (build_moe_ffn: softmax router, top-k, SwiGLU experts, weighted expert sum), found from the
+// outermost ADD of the expert sum. Used to translate the block as a whole (see translate_moe_tiled).
+struct moe_block {
+ const ggml_tensor * probs = nullptr; // router SOFT_MAX
+ const ggml_tensor * x = nullptr; // input of the gate and up projections
+ const ggml_tensor * gate = nullptr; // expert weights [k, m, n_expert]
+ const ggml_tensor * up = nullptr;
+ const ggml_tensor * down = nullptr;
+ const ggml_tensor * down_out = nullptr; // MUL_MAT_ID of the down projection, [n_embd, n_expert_used, n_tokens]
+ const ggml_tensor * clamp = nullptr; // CLAMP of the weight sum when the top-k weights are normalized
+};
+bool match_moe_block(const ggml_tensor * sum_add, moe_block & block);
+
class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder {
public:
+ static bool is_dynamic_vision_graph(const ggml_cgraph * cgraph);
+ // OV order: -2 reads the runtime target; -1 infers one extent; nonnegative values are invariant.
+ static std::vector<int64_t> vision_reshape_pattern(const ggml_tensor * node);
+ std::vector<int64_t> get_vision_reshape_pattern(int node_idx) const override {
+ return vision_reshape_pattern(m_node_info_list[node_idx].node);
+ }
static std::string get_tensor_name(const ggml_cgraph * cgraph, const ggml_tensor * tensor);
struct NodeInfo {
ggml_tensor * node;
@@ -269,6 +307,10 @@ public:
virtual int32_t get_op_dynamic_dim(int node_idx) const override;
+ virtual int32_t get_view_input_dynamic_dim(int node_idx,
+ const std::string & name,
+ size_t view_index) const override;
+
virtual void visit_subgraph(
std::function<void(std::shared_ptr<GgmlDecoder>, int node_idx)> node_visitor) const override;
@@ -362,10 +404,13 @@ public:
virtual bool is_prefill() const override { return m_is_prefill; }
- int get_static_n_tokens() const { return m_is_prefill ? m_prefill_chunk_size : 1; }
+ virtual int get_static_n_tokens() const override { return m_is_prefill ? m_prefill_chunk_size : 1; }
virtual bool is_splited_model() const override { return m_model_is_splitted; }
+ // The graph has a MoE block that translate_moe_tiled translates (found in set_input_output)
+ bool has_moe_block() const { return m_has_moe_block; }
+
ov::PartialShape get_graph_input_shape(const ggml_tensor * op,
const ggml_tensor * input,
int dynamic_dim_index = -1) const;
@@ -447,7 +492,10 @@ public:
void clear_model_weights() { m_model_weights.clear(); }
- static std::pair<ModelParams, ComputeParams> compute_llm_params(ggml_cgraph * cgraph, bool is_static);
+ // The execution path supplies the structural vision classification once per compute.
+ static std::pair<ModelParams, ComputeParams> compute_llm_params(ggml_cgraph * cgraph,
+ bool is_static,
+ bool dynamic_vision = false);
const ModelParams & get_model_params() const { return m_model_params; }
@@ -487,6 +535,12 @@ public:
// as outputs, and the compiled model's Results are fixed at compile time.
bool has_same_graph_io(const ggml_cgraph * cgraph) const;
+ // Can this decoder run a graph with n_tokens tokens? The dynamic dims are read from the shapes. With one token and
+ // one KV head, the head dim and the token dim have the same size and stride (MLA's reshape_3d(kv, n, 1, n_tokens)).
+ bool can_run_tokens(int n_tokens) const { return !m_token_dim_ambiguous || n_tokens == 1; }
+
+ bool is_token_dim_ambiguous() const { return m_token_dim_ambiguous; }
+
static bool is_inp_tok(const ggml_tensor * tensor, const ggml_tensor * op) {
return op->op == GGML_OP_GET_ROWS && tensor == op->src[1] && op->src[0]->op == GGML_OP_NONE;
}
@@ -526,7 +580,10 @@ public:
tensor->ne[3] != 1 || (tensor->buffer != nullptr && tensor->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) {
return false;
}
- return (op->op == GGML_OP_RMS_NORM || op->op == GGML_OP_L2_NORM) && op->src[0] == tensor &&
+ // Gemma applies per-token scaling to supplied image embeddings.
+ const bool scaled_input = op->op == GGML_OP_MUL && (tensor->flags & GGML_TENSOR_FLAG_INPUT) &&
+ is_inp_scale_rows(op->src[1], op);
+ return (op->op == GGML_OP_RMS_NORM || op->op == GGML_OP_L2_NORM || scaled_input) && op->src[0] == tensor &&
(tensor->op == GGML_OP_NONE || tensor->op == GGML_OP_CPY);
}
@@ -553,7 +610,10 @@ public:
// per-token embedding scale [1, n_tokens] (inp->scale_rows in llama-graph.cpp)
static bool is_inp_scale_rows(const ggml_tensor * tensor, const ggml_tensor * op) {
- return op->op == GGML_OP_MUL && tensor == op->src[1] && strcmp(tensor->name, "inp_scale_rows") == 0;
+ return tensor && op->op == GGML_OP_MUL && tensor == op->src[1] &&
+ (tensor->flags & GGML_TENSOR_FLAG_INPUT) && tensor->type == GGML_TYPE_F32 &&
+ tensor->ne[0] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1 &&
+ op->src[0]->ne[1] == tensor->ne[1] && op->src[0]->ne[2] == 1 && op->src[0]->ne[3] == 1;
}
static bool is_rope_freqs_weight(const ggml_tensor * tensor, const ggml_tensor * op) {
@@ -563,7 +623,8 @@ public:
static bool is_recurrent_cache(const ggml_tensor * tensor) {
return tensor != nullptr && (strncmp(tensor->name, "cache_r_l", strlen("cache_r_l")) == 0 ||
strncmp(tensor->name, "cache_s_l", strlen("cache_s_l")) == 0 ||
- strncmp(tensor->name, "cache_ple_r_l", strlen("cache_ple_r_l")) == 0);
+ strncmp(tensor->name, "cache_ple_r_l", strlen("cache_ple_r_l")) == 0 ||
+ strncmp(tensor->name, "cache_sp", strlen("cache_sp")) == 0);
}
static bool is_recurrent_cache_reset(const ggml_tensor * node) {
@@ -571,6 +632,14 @@ public:
return is_scale_or_fill && node->view_src != nullptr && is_recurrent_cache(node->view_src);
}
+ // build_rs gathers the states to move into the ubatch cells from the cache: the index list is an offset-0
+ // VIEW of the s_copy leaf with all its rows, or none when the states are already in place
+ static bool is_rs_cache_gather(const ggml_tensor * node);
+
+ // build_rs reads the ubatch states from the cache after the move: a whole-row VIEW of the reshaped cache.
+ // The zeroed state and the move destination are views of the same shape, written by an in-place op.
+ static bool is_rs_cache_read(const ggml_cgraph * cgraph, const ggml_tensor * node);
+
static bool is_gdn_snapshot_writeback(const ggml_tensor * node) {
if (!(node != nullptr && node->op == GGML_OP_CPY && node->src[0] != nullptr &&
node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr &&
@@ -744,6 +813,8 @@ public:
op->src[0]->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY;
}
+ std::string get_position_input_ov_name(const ggml_tensor * tensor) const;
+
private:
void set_input_output();
int compute_op_case(const ggml_tensor * node) const;
@@ -771,11 +842,18 @@ private:
std::set<std::string> m_model_output_names;
// The output set the compiled model was built from, for has_same_graph_io().
std::set<std::string> m_built_output_names;
+ // The model was converted from a one-token graph of a model with one KV head, for can_run_tokens().
+ bool m_token_dim_ambiguous = false;
bool m_kv_only_outputs = false;
std::map<std::string, const ggml_tensor *> m_host_gather_rows;
std::vector<NodeInfo> m_node_info_list;
std::map<ggml_tensor *, int> m_node_dynamic_dims;
std::set<const ggml_tensor *> m_kvcache_4d;
+ // The expert-plane VIEWs and inner ADDs of the expert sums that translate_moe_tiled replaces. They are not
+ // used, and are translated as pass-throughs: building them can fail, e.g. a VIEW of the last layer whose row
+ // count (the output rows) differs from the one its static shape was derived with.
+ std::set<const ggml_tensor *> m_moe_tiled_replaced;
+ bool m_has_moe_block = false;
struct kv_tensor_entry {
const void * data = nullptr;
diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
index 054d78c31..e9e431162 100644
--- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
+++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
@@ -10,10 +10,12 @@
#include <cctype>
#include <cerrno>
#include <climits>
+#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <mutex>
+#include <openvino/core/version.hpp>
#include <openvino/runtime/intel_gpu/ocl/ocl.hpp>
#include <openvino/runtime/intel_npu/level_zero/level_zero.hpp>
#include <openvino/runtime/properties.hpp>
@@ -193,6 +195,7 @@ constexpr env_var env_vars[] = {
{"GGML_OPENVINO_GDN_DECOMPOSE", env_type::BOOL},
{"GGML_OPENVINO_NPU_L0_HOST_TENSORS", env_type::BOOL},
{"GGML_OPENVINO_KV_SLICE", env_type::INT},
+ {"GGML_OPENVINO_GPU_KV_ROUND_UP", env_type::BOOL},
{"GGML_OPENVINO_NPU_HFA_PREFILL", env_type::BOOL},
{"GGML_OPENVINO_NPU_DECODE_UNFOLD", env_type::BOOL},
{"GGML_OPENVINO_SELF_CONTAINED_MMAP", env_type::BOOL},
@@ -585,6 +588,10 @@ bool ggml_openvino_gdn_decompose_enabled() {
return ggml_openvino_getenv_int("GGML_OPENVINO_GDN_DECOMPOSE", ggml_openvino_npu_is_4000() ? 1 : 0) > 0;
}
+bool ggml_openvino_moe_tiled_enabled() {
+ return ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC") != 0;
+}
+
int ggml_openvino_gdn_decompose_chunk() {
const int chunk = ggml_openvino_getenv_int("GGML_OPENVINO_GDN_DECOMPOSE_CHUNK");
if (chunk >= 2 && chunk <= 128 && (chunk & (chunk - 1)) == 0) {
@@ -611,9 +618,10 @@ bool ggml_openvino_reduce_compile_mem_enabled() {
}
bool ggml_openvino_release_weights_enabled() {
+ // the weights are written again from the model file before a new compile, so release by default
return ggml_openvino_is_gpu() &&
ggml_openvino_getenv_int("GGML_OPENVINO_RELEASE_WEIGHTS",
- ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE")) != 0;
+ ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE", 1)) != 0;
}
// Check if running on NPU
@@ -934,6 +942,22 @@ bool ggml_openvino_shape_from_mask_enabled() {
return ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK") == 0;
}
+bool ggml_openvino_kv_4d_enabled() {
+ // GGML_OPENVINO_ENABLE_KV_4D unset: on with OpenVINO 2026.5 or later. The GPU plugin updates the 4-D cache in
+ // place from that version (openvino#37569); 2026.4 and older run this layout much slower.
+ static const bool enabled = [] {
+ if (ggml_openvino_getenv_str("GGML_OPENVINO_ENABLE_KV_4D") != nullptr) {
+ return ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_KV_4D") > 0;
+ }
+ const char * build = ov::get_openvino_version().buildNumber;
+ int major = 0;
+ int minor = 0;
+ return build != nullptr && std::sscanf(build, "%d.%d", &major, &minor) == 2 &&
+ (major > 2026 || (major == 2026 && minor >= 5));
+ }();
+ return enabled;
+}
+
size_t ggml_openvino_max_alloc_size(const std::string & device) {
const auto & gpu_contexts = ggml_openvino_get_device_config().gpu_contexts;
auto it = gpu_contexts.find(device);
@@ -972,6 +996,11 @@ clEnqueueMemcpyINTEL_fn ggml_openvino_get_clEnqueueMemcpyINTEL() {
return ggml_openvino_get_device_config().cl_mem_cpy_fn;
}
+// Q5_0, Q5_1 and Q8_0 keep their weights as 8-bit values and follow the same rules.
+static bool is_8bit_layout(ggml_type type) {
+ return type == GGML_TYPE_Q5_0 || type == GGML_TYPE_Q5_1 || type == GGML_TYPE_Q8_0;
+}
+
// Get requantization type for a tensor type (returns nullopt if no requant needed)
std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor * tensor, bool no_requant) {
if (no_requant) {
@@ -1000,12 +1029,12 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
// GGML_OPENVINO_REQUANT_KQUANT selects a 4-bit target instead. Names are
// q4_<sym|asym><group>[_all]: <sym|asym> says whether a per-group zero point is kept, <group>
// is the group size. The _all suffix includes Q4_K; q4_asym64_all also includes
- // ordinary Q8_0/Q5_1 linear weights, matching the INT4_ASYM/group-64 primary precision
+ // ordinary Q8_0/Q5_1/Q5_0 linear weights, matching the INT4_ASYM/group-64 primary precision
// used by NNCF with ratio=1.0. Embedding/output retain the channel-wise INT8 overrides above:
// q4_sym128 Q6_K/Q5_K -> Q4_0_128 (u4, group 128, symmetric)
// q4_sym128_all and Q4_K too -- drops Q4_K's per-32 zero point, which costs some accuracy
// q4_asym64 Q6_K/Q5_K -> Q4_1_64 (u4, group 64, asymmetric)
- // q4_asym64_all Q6_K/Q5_K/Q4_K/Q8_0/Q5_1 -> Q4_1_64 (u4, group 64, asymmetric)
+ // q4_asym64_all Q6_K/Q5_K/Q4_K/Q8_0/Q5_1/Q5_0 -> Q4_1_64 (u4, group 64, asymmetric)
// native no requantization at all (keep Q6_K/Q5_K as they are)
//
// q4_asym64 leaves Q4_K at its native group 32. Use q4_asym64_all to keep the group size uniform.
@@ -1025,7 +1054,8 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
// TODO: temporary workaround for slow GPU-plugin GatherMatmul prefill above 16 tokens.
// Q4_1_64 experts let the plugin fuse the MoE into MOECompressed.
if (ggml_openvino_is_gpu() && tensor->ne[2] > 1 && strstr(tensor->name, "exps") != nullptr &&
- (tensor->type == GGML_TYPE_Q4_K || tensor->type == GGML_TYPE_Q5_K || tensor->type == GGML_TYPE_Q6_K)) {
+ (tensor->type == GGML_TYPE_Q4_K || tensor->type == GGML_TYPE_Q5_K || tensor->type == GGML_TYPE_Q6_K ||
+ (tensor->type == GGML_TYPE_Q4_0 && tensor->ne[0] % 64 == 0))) {
return ExtraQuantType::Q4_1_64;
}
@@ -1037,22 +1067,19 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
return ExtraQuantType::Q4_1_64;
}
}
- // Include dense Q8_0/Q5_1 in the explicit all-asymmetric policy. Keep the default GPU
+ // Include dense Q8_0/Q5_1/Q5_0 in the explicit all-asymmetric policy. Keep the default GPU
// workaround below restricted to MoE experts: ordinary grouped INT8 MatMul is supported.
- if (asym64_all && (tensor->type == GGML_TYPE_Q5_1 || tensor->type == GGML_TYPE_Q8_0)) {
+ if (asym64_all && is_8bit_layout(tensor->type)) {
// A group must fit within each row. Use backup channel-wise INT8 for incompatible
- // widths (Q8_0/Q5_1 allow rows of 32 weights); every affected Qwen3.6 row is divisible by 64.
+ // widths (Q8_0/Q5_1/Q5_0 allow rows of 32 weights); every affected Qwen3.6 row is divisible by 64.
return tensor->ne[0] % 64 == 0 ? ExtraQuantType::Q4_1_64 : ExtraQuantType::Q8_0_C;
}
- if (tensor->type == GGML_TYPE_Q5_0) {
- return group64(ExtraQuantType::Q4_0_64);
- }
- // MoE expert weights (3D, ne[2] = n_expert) stored as Q5_1/Q8_0 are the expert-side
+ // MoE expert weights (3D, ne[2] = n_expert) stored as Q5_1/Q8_0/Q5_0 are the expert-side
// equivalent of Q6_K/Q5_K: kept at 8 bits by default while the rest of the model is at 4
// (gemma-4 26B-A4B keeps its down projection there). Send them to 4 bits under the same
// option, at group 64 rather than 128: the down expert has k=704, which 64 divides
// (704/64 = 11) and 128 does not.
- if (tensor->ne[2] > 1 && (tensor->type == GGML_TYPE_Q5_1 || tensor->type == GGML_TYPE_Q8_0)) {
+ if (tensor->ne[2] > 1 && is_8bit_layout(tensor->type)) {
if (sym128 || sym128_all) {
return group64(ExtraQuantType::Q4_0_64);
}
diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h
index 7c4d1bdb6..2f805bb42 100644
--- a/ggml/src/ggml-openvino/ggml-openvino-extra.h
+++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h
@@ -232,6 +232,9 @@ bool ggml_openvino_shape_from_mask_enabled();
// Manual GQA attention instead of SDPA (GGML_OPENVINO_MANUAL_GQA_ATTN, on GPU by default)
bool ggml_openvino_manual_gqa_enabled();
+// Bind the stateless GPU KV cache in the 4-D in-place layout (see GgmlOvDecoder::is_kvcache_4d)
+bool ggml_openvino_kv_4d_enabled();
+
// GDN q pre-scale for eligible graphs on the NPU static path. On by default;
// GGML_OPENVINO_GDN_Q_SCALE=0 (or a negative or non-numeric value) turns it off.
bool ggml_openvino_gdn_prescale_enabled();
@@ -256,6 +259,13 @@ bool ggml_openvino_npu_is_4000();
// Snapshot (MTP) graphs still use the op.
bool ggml_openvino_gdn_decompose_enabled();
+// Translate the MoE block of a model (router, experts, expert sum) into the batched form of the NPUW MoE support:
+// every expert is computed (Tile + batched MatMul) and weighted by scattered router scores, and NPUW runs only the
+// routed experts. The NPU has no GatherMatmul.
+// On for the NPU, and with GGML_OPENVINO_FORCE_STATIC on the CPU or the GPU, which then computes every expert: that
+// mode reproduces the NPU path to check the translation.
+bool ggml_openvino_moe_tiled_enabled();
+
// Tokens per chunk of the decomposed GATED_DELTA_NET: GGML_OPENVINO_GDN_DECOMPOSE_CHUNK,
// a power of 2 in [2, 128], default 16.
int ggml_openvino_gdn_decompose_chunk();
@@ -264,13 +274,11 @@ int ggml_openvino_gdn_decompose_chunk();
size_t ggml_openvino_max_alloc_size(const std::string & device);
// Host weight-buffer release (GGML_OPENVINO_RELEASE_WEIGHTS, GPU only).
-// register: record a host weight buffer (idempotent per data pointer).
-// release: madvise(MADV_DONTNEED) all registered buffers, dropping their RSS.
-// released: true once release has run (used to fail-fast on post-release recompile).
-void ggml_openvino_register_weight_buffer(void * data, size_t size);
+// release: madvise(MADV_DONTNEED) the buffers whose weights all came from the model file, dropping their RSS.
+// restore: write the released buffers again from the model file; false (logged) if the file cannot be read.
void ggml_openvino_unregister_weight_buffer(const void * data);
void ggml_openvino_release_weight_buffers();
-bool ggml_openvino_weight_buffers_released();
+bool ggml_openvino_restore_weight_buffers();
// Get requantization type for a tensor type (returns nullopt if no requant needed)
std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor * tensor, bool no_requant = false);
diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp
index 7f592b3c4..def89208a 100644
--- a/ggml/src/ggml-openvino/ggml-openvino.cpp
+++ b/ggml/src/ggml-openvino/ggml-openvino.cpp
@@ -22,6 +22,7 @@
#include <memory>
#include <mutex>
#include <openvino/core/type/element_type.hpp>
+#include <openvino/core/version.hpp>
#include <openvino/op/constant.hpp>
#include <openvino/op/convert.hpp>
#include <openvino/op/parameter.hpp>
@@ -43,6 +44,7 @@
# include <windows.h>
# include <psapi.h>
#else
+# include <fcntl.h>
# include <sys/mman.h>
# include <unistd.h>
#endif
@@ -290,35 +292,164 @@ struct ggml_backend_openvino_buffer_type_context {
//
// We do NOT free the buffer (ggml owns its lifetime and tensors still point
// into it); instead madvise(MADV_DONTNEED) drops the resident pages while
-// keeping the mapping valid. A later recompile would re-read these Constants
-// from now-zeroed memory and produce garbage, so once released we fail fast
-// if the cache-miss compile branch is reached again (see utils.cpp).
+// keeping the mapping valid. Every write into a weight buffer is recorded with
+// its place in the model file, so the weights are written again from the file
+// before the next compile or host read. A buffer with a write that did not come
+// from a file mapping (-lm none) is never released.
namespace {
+struct ov_weight_write {
+ ggml_tensor * tensor;
+ size_t offset;
+ size_t size;
+ size_t file; // index in ov_weight_buffer_registry::files
+ uint64_t file_offset;
+ // written by process_weight_tensor, else copied
+ bool processed;
+};
+
+struct ov_weight_file {
+ std::string path;
+ uint64_t identity;
+};
+
+struct ov_weight_buffer {
+ void * data;
+ size_t size;
+ std::vector<ov_weight_write> writes;
+ bool restorable = true;
+ bool released = false;
+};
+
struct ov_weight_buffer_registry {
std::mutex mutex;
- // (data, size) of every non-remote weight buffer, for madvise.
- std::vector<std::pair<void *, size_t>> buffers;
- bool released = false;
+ std::vector<ov_weight_buffer> buffers;
+ std::vector<ov_weight_file> files;
+ // the weights are read on the host at run time (an op on another backend), so they stay in host memory
+ bool keep = false;
};
ov_weight_buffer_registry & ov_weight_registry() {
static ov_weight_buffer_registry reg;
return reg;
}
-} // namespace
-void ggml_openvino_register_weight_buffer(void * data, size_t size) {
- if (data == nullptr || size == 0) {
- return;
+ov_weight_buffer & ov_weight_buffer_of(ov_weight_buffer_registry & reg, void * data, size_t size) {
+ for (auto & b : reg.buffers) {
+ if (b.data == data) {
+ return b;
+ }
+ }
+ reg.buffers.push_back({data, size, {}});
+ return reg.buffers.back();
+}
+
+#ifdef __linux__
+bool ov_read_file(int fd, uint64_t offset, uint8_t * dst, size_t size) {
+ while (size > 0) {
+ const ssize_t n = pread(fd, dst, size, (off_t) offset);
+ if (n <= 0) {
+ if (n < 0 && errno == EINTR) {
+ continue;
+ }
+ return false;
+ }
+ dst += n;
+ offset += (uint64_t) n;
+ size -= (size_t) n;
+ }
+ return true;
+}
+#endif
+
+// Write the released buffers again from the model files. Call with reg.mutex held.
+bool ov_restore_weight_buffers(ov_weight_buffer_registry & reg) {
+#ifdef __linux__
+ std::vector<int> fds(reg.files.size(), -1);
+ auto close_fds = [&fds]() {
+ for (int fd : fds) {
+ if (fd >= 0) {
+ close(fd);
+ }
+ }
+ };
+ size_t total = 0;
+ std::vector<uint8_t> src;
+ for (auto & b : reg.buffers) {
+ if (!b.released) {
+ continue;
+ }
+ for (const auto & w : b.writes) {
+ const auto & file = reg.files[w.file];
+ if (fds[w.file] < 0) {
+ fds[w.file] = open(file.path.c_str(), O_RDONLY | O_CLOEXEC);
+ if (fds[w.file] < 0 || ggml_openvino_file_identity(fds[w.file]) != file.identity) {
+ GGML_LOG_ERROR("%s: %s is missing or changed since the model was loaded\n", __func__,
+ file.path.c_str());
+ close_fds();
+ return false;
+ }
+ }
+ src.resize(w.size);
+ if (!ov_read_file(fds[w.file], w.file_offset, src.data(), w.size)) {
+ GGML_LOG_ERROR("%s: cannot read %s: %s\n", __func__, file.path.c_str(), strerror(errno));
+ close_fds();
+ return false;
+ }
+ if (w.processed) {
+ try {
+ process_weight_tensor(w.tensor, src.data(), w.tensor->data);
+ } catch (const std::exception & e) {
+ GGML_LOG_ERROR("%s: failed to process weight tensor %s: %s\n", __func__, w.tensor->name, e.what());
+ close_fds();
+ return false;
+ }
+ } else {
+ memcpy((char *) w.tensor->data + w.offset, src.data(), w.size);
+ }
+ total += w.size;
+ }
+ b.released = false;
+ }
+ close_fds();
+ if (total > 0) {
+ GGML_LOG_INFO("%s: wrote %zu MB of host weights again from the model file\n", __func__, total / 1024 / 1024);
}
+#else
+ GGML_UNUSED(reg);
+#endif
+ return true;
+}
+} // namespace
+
+// Record a write into a host weight buffer and where |data| sits in the mapped model file. A write that is not a copy
+// of file-mapped bytes (|data| null) or into a host buffer that other backends read directly keeps the buffer resident.
+static void ggml_openvino_record_weight_write(ggml_backend_buffer_t buffer,
+ ggml_tensor * tensor,
+ size_t offset,
+ const void * data,
+ size_t size,
+ bool processed) {
+ auto * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
auto & reg = ov_weight_registry();
std::lock_guard<std::mutex> lock(reg.mutex);
- for (const auto & b : reg.buffers) {
- if (b.first == data) {
- return; // already registered
- }
+ auto & b = ov_weight_buffer_of(reg, ctx->data, ctx->size);
+ ctx->weight_registered = true;
+ const ggml_openvino_source_mapping * m = data != nullptr && !ggml_backend_buffer_is_host(buffer) ?
+ ggml_openvino_find_source_mapping(data, size, ctx->source_mappings) :
+ nullptr;
+ if (m == nullptr || m->path.empty()) {
+ b.restorable = false;
+ return;
+ }
+ size_t file = 0;
+ while (file < reg.files.size() && (reg.files[file].path != m->path || reg.files[file].identity != m->identity)) {
+ file++;
}
- reg.buffers.emplace_back(data, size);
+ if (file == reg.files.size()) {
+ reg.files.push_back({m->path, m->identity});
+ }
+ b.writes.push_back(
+ {tensor, offset, size, file, m->offset + (reinterpret_cast<uintptr_t>(data) - m->begin), processed});
}
void ggml_openvino_unregister_weight_buffer(const void * data) {
@@ -328,44 +459,65 @@ void ggml_openvino_unregister_weight_buffer(const void * data) {
auto & reg = ov_weight_registry();
std::lock_guard<std::mutex> lock(reg.mutex);
reg.buffers.erase(std::remove_if(reg.buffers.begin(), reg.buffers.end(),
- [data](const std::pair<void *, size_t> & b) { return b.first == data; }),
+ [data](const ov_weight_buffer & b) { return b.data == data; }),
reg.buffers.end());
}
-bool ggml_openvino_weight_buffers_released() {
- auto & reg = ov_weight_registry();
- std::lock_guard<std::mutex> lock(reg.mutex);
- return reg.released;
-}
-
void ggml_openvino_release_weight_buffers() {
auto & reg = ov_weight_registry();
std::lock_guard<std::mutex> lock(reg.mutex);
- if (reg.released) {
+ if (reg.keep) {
return;
}
size_t total = 0;
-#if !defined(_WIN32)
- for (const auto & b : reg.buffers) {
+ size_t count = 0;
+#ifdef __linux__
+ for (auto & b : reg.buffers) {
+ if (b.released || !b.restorable) {
+ continue;
+ }
// Align down/up to page boundaries so madvise only drops whole pages
// fully owned by this buffer.
const size_t page = (size_t) sysconf(_SC_PAGESIZE);
- const uintptr_t ustart = reinterpret_cast<uintptr_t>(b.first);
+ const uintptr_t ustart = reinterpret_cast<uintptr_t>(b.data);
const size_t offset_to_page = (page - (ustart & (page - 1))) & (page - 1);
- if (b.second > offset_to_page) {
- const size_t aligned_len = (b.second - offset_to_page) & ~(page - 1);
+ if (b.size > offset_to_page) {
+ const size_t aligned_len = (b.size - offset_to_page) & ~(page - 1);
if (aligned_len > 0) {
- char * astart = static_cast<char *>(b.first) + offset_to_page;
+ char * astart = static_cast<char *>(b.data) + offset_to_page;
if (madvise(astart, aligned_len, MADV_DONTNEED) == 0) {
total += aligned_len;
+ b.released = true;
+ count++;
}
}
}
}
#endif
- reg.released = true;
- GGML_LOG_INFO("%s: released %zu MB of host weight buffers (%zu buffers)\n", __func__, total / 1024 / 1024,
- reg.buffers.size());
+ if (count > 0) {
+ GGML_LOG_INFO("%s: released %zu MB of host weight buffers (%zu buffers)\n", __func__, total / 1024 / 1024,
+ count);
+ }
+}
+
+bool ggml_openvino_restore_weight_buffers() {
+ auto & reg = ov_weight_registry();
+ std::lock_guard<std::mutex> lock(reg.mutex);
+ return ov_restore_weight_buffers(reg);
+}
+
+// The host weights are read at run time: write them again if released, and keep them from now on.
+static void ggml_openvino_keep_weight_buffers() {
+ auto & reg = ov_weight_registry();
+ std::lock_guard<std::mutex> lock(reg.mutex);
+ if (reg.keep) {
+ return;
+ }
+ if (!ov_restore_weight_buffers(reg)) {
+ GGML_ABORT("ggml-openvino: cannot write the released host weights again");
+ }
+ reg.keep = true;
+ GGML_LOG_INFO("%s: host weights are read at run time, so they stay in host memory\n", __func__);
}
// Buffer interface functions
@@ -492,6 +644,9 @@ static void ggml_backend_openvino_buffer_memset_tensor(ggml_backend_buffer_t buf
size_t size) {
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
+ if (buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && !ctx->is_remote) {
+ ggml_openvino_record_weight_write(buffer, tensor, offset, nullptr, size, false);
+ }
if (ctx->is_remote) {
// For remote (device) buffers, use OpenCL USM memfill
@@ -648,21 +803,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
ggml_openvino_set_extra(ctx, tensor, extra);
- // Register the host buffer so its pages can be dropped after the GPU
- // plugin has its own device copy (GGML_OPENVINO_RELEASE_WEIGHTS).
+ // the host pages can be dropped once the GPU plugin has its own device copy (GGML_OPENVINO_RELEASE_WEIGHTS)
if (!ctx->is_remote) {
- // Weights are set once at model load. Setting a weight after a release
- // means a second model is loading while the first's compiled graph is
- // pinned — that graph would be wrongly reused with this model's key.
- // Fail loud rather than return silently-wrong results.
- if (ggml_openvino_weight_buffers_released()) {
- GGML_ABORT(
- "ggml-openvino: loading a new model while GGML_OPENVINO_RELEASE_WEIGHTS pinned a previous "
- "model's compiled graph. This mode supports a single model per process; unset it for "
- "multi-model runs.");
- }
- ggml_openvino_register_weight_buffer(ctx->data, ctx->size);
- ctx->weight_registered = true;
+ ggml_openvino_record_weight_write(buffer, tensor, offset, data, size, true);
}
if (!ctx->external_memory) {
@@ -671,6 +814,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
} catch (const std::exception & e) {
GGML_LOG_ERROR("%s: failed to process weight tensor for %s: %s\n", __func__, tensor->name, e.what());
memcpy((char *) tensor->data + offset, data, size);
+ if (!ctx->is_remote) {
+ ggml_openvino_record_weight_write(buffer, tensor, offset, data, size, false);
+ }
}
} else {
// Non-weight tensor (KV cache, activations, etc.) - copy data. test-backend-ops also goes here
@@ -691,6 +837,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
GGML_OPENVINO_KV_WRITE)) {
memcpy((char *) tensor->data + offset, data, size);
}
+ if (is_weight_buffer && !ctx->is_remote) {
+ ggml_openvino_record_weight_write(buffer, tensor, offset, data, size, false);
+ }
if (ggml_openvino_extra_unchanged(ctx, tensor)) {
return;
@@ -775,6 +924,9 @@ static void ggml_backend_openvino_buffer_get_tensor(ggml_backend_buffer_t buffer
if (ggml_openvino_model_cache_only() && buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) {
GGML_ABORT("ggml-openvino: cannot read unloaded weights in cache-only mode");
}
+ if (buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && !ctx->is_remote) {
+ ggml_openvino_keep_weight_buffers();
+ }
if (ggml_is_quantized(tensor->type) && tensor->view_src == nullptr && tensor->extra != nullptr &&
static_cast<const ggml_openvino_extra_base *>(tensor->extra)->type != ggml_openvino_extra_base::Type::TENSOR) {
@@ -809,6 +961,9 @@ static bool ggml_backend_openvino_buffer_cpy_tensor(ggml_backend_buffer_t buffer
ggml_tensor * dst) {
GGML_ASSERT(src != nullptr && dst != nullptr);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
+ if (buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && !ctx->is_remote) {
+ ggml_openvino_record_weight_write(buffer, dst, 0, nullptr, ggml_nbytes(dst), false);
+ }
if (ctx->is_remote) {
// For remote (device) buffers, use OpenCL USM memcpy
@@ -867,6 +1022,9 @@ static bool ggml_backend_openvino_buffer_cpy_tensor(ggml_backend_buffer_t buffer
static void ggml_backend_openvino_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
GGML_ASSERT(ctx->data != nullptr);
+ if (buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && !ctx->is_remote) {
+ ggml_openvino_record_weight_write(buffer, nullptr, 0, nullptr, ctx->size, false);
+ }
if (ctx->is_remote) {
cl_command_queue queue = ggml_openvino_get_cl_queue(ggml_openvino_get_available_devices()[ctx->device]);
auto mem_fill_fn = ggml_openvino_get_clEnqueueMemFillINTEL();
@@ -1135,15 +1293,9 @@ static void ggml_backend_openvino_free(ggml_backend_t backend) {
r_ctx->clear_caches();
std::lock_guard<std::mutex> cache_lock(cache->mutex);
if (--cache->backend_count == 0) {
- // If host weight buffers were released (GGML_OPENVINO_RELEASE_WEIGHTS), the
- // dropped pages can never be repopulated, so a recompile is impossible. Keep
- // the compiled-model cache alive across backend teardown so the next context
- // reuses it instead of recompiling against zeroed weights.
- if (!ggml_openvino_weight_buffers_released()) {
- cache->graphs.clear();
- std::lock_guard<std::mutex> fingerprints_lock(g_fallback_fingerprints_mutex);
- g_fallback_fingerprints.clear();
- }
+ cache->graphs.clear();
+ std::lock_guard<std::mutex> fingerprints_lock(g_fallback_fingerprints_mutex);
+ g_fallback_fingerprints.clear();
}
}
@@ -1542,12 +1694,20 @@ static bool is_supported_flash_attn_pattern(const ggml_tensor * op) {
// PERMUTE -> RESHAPE -> base (view_src==nullptr) (whisper Q)
// VIEW -> base (view_src==nullptr) (whisper K/V from kv_pad)
// PERMUTE -> VIEW -> RESHAPE -> base (Q of a layer without RoPE, e.g. SmolLM3)
+ // PERMUTE -> ROPE (view_src==nullptr) (cacheless vision Q/K)
+ // PERMUTE -> RMS_NORM (view_src==nullptr) (Gemma4 vision V)
for (int i = 0; i < 3; i++) {
const ggml_tensor * src = op->src[i];
if (src->op == GGML_OP_PERMUTE) {
if (src->src[0] == nullptr) {
return false;
}
+ if (src->src[0]->op == GGML_OP_ROPE && src->src[0]->view_src == nullptr) {
+ continue;
+ }
+ if (i == 2 && src->src[0]->op == GGML_OP_RMS_NORM && src->src[0]->view_src == nullptr) {
+ continue;
+ }
// MLA: Q = PERMUTE -> CONCAT(q_nope_absorbed, q_pe); V = PERMUTE -> VIEW -> VIEW -> K cache
// (V is the first kv_lora_rank values of each K cache row)
if (i == 0 && src->src[0]->op == GGML_OP_CONCAT) {
@@ -1588,6 +1748,13 @@ static bool is_gemma3n_flash_attn_pattern(const ggml_tensor * op) {
return false;
}
+ // Gemma4 vision rotates the two head halves with consecutive spatial RoPEs.
+ const auto * q = op->src[0];
+ if (q->op == GGML_OP_PERMUTE && q->src[0]->op == GGML_OP_ROPE &&
+ q->src[0]->src[0] && q->src[0]->src[0]->op == GGML_OP_ROPE) {
+ return false;
+ }
+
const ggml_tensor * q_base =
op->src[0] != nullptr && op->src[0]->src[0] != nullptr ? op->src[0]->src[0]->src[0] : nullptr;
const ggml_tensor * k_base =
@@ -1634,6 +1801,25 @@ static bool tensor_view_fits_src_buffer(const ggml_tensor * tensor) {
return tensor_nbytes <= src_nbytes - tensor->view_offs;
}
+static bool supports_replay_cache_banks() {
+ return ggml_openvino_is_gpu() && !ggml_openvino_is_static() && !is_stateful_enabled() &&
+ !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE");
+}
+
+static bool is_replay_input_store(const ggml_tensor * op) {
+ if (op->op != GGML_OP_CPY || !op->view_src || strncmp(op->view_src->name, "cache_sp", 8) != 0 ||
+ op->type != GGML_TYPE_F32 || op->src[0]->op != GGML_OP_VIEW || op->src[1]->op != GGML_OP_VIEW ||
+ !supports_replay_cache_banks()) {
+ return false;
+ }
+ const auto dst = op->src[1];
+ const auto base = dst->src[0];
+ // Pending prefixes keep the full bank row stride; the complete replay fusion owns this store.
+ return base && base->op == GGML_OP_RESHAPE && base->src[0] == op->view_src &&
+ dst->ne[0] <= base->ne[0] && dst->ne[1] == base->ne[1] && dst->ne[2] <= base->ne[2] &&
+ dst->nb[0] == base->nb[0] && dst->nb[1] == base->nb[1] && dst->nb[2] == base->nb[2] && dst->nb[3] == base->nb[3];
+}
+
static bool cpy_output_view_is_supported(const ggml_tensor * op) {
if (op->view_src == nullptr) {
return true;
@@ -1644,7 +1830,7 @@ static bool cpy_output_view_is_supported(const ggml_tensor * op) {
}
return ggml_nbytes(op) == 0 || ggml_is_contiguous(op) || GgmlOvDecoder::is_conv_state_writeback(op) ||
- GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op);
+ GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op) || is_replay_input_store(op);
}
// SET_ROWS writes whole rows of a contiguous destination. Other destination views (e.g. a permuted view of a
@@ -1686,6 +1872,21 @@ static bool tensor_name_starts_with(const ggml_tensor * tensor, const char * pre
return tensor != nullptr && strncmp(tensor->name, prefix, strlen(prefix)) == 0;
}
+// The GPU plugin of OpenVINO 2026.5 computes some convolutions wrongly when the kernel is a runtime input, as in
+// test-backend-ops: CONV_TRANSPOSE_1D and CONV_TRANSPOSE_2D with stride 1, and CONV_2D with a 1x1 f16 kernel and
+// padding. 2026.4 computes them right. Such ops run on another backend. Remove this check once a fixed OpenVINO
+// release is pinned.
+static bool gpu_has_conv_defect() {
+ static const bool affected_version = [] {
+ const char * build = ov::get_openvino_version().buildNumber;
+ int major = 0;
+ int minor = 0;
+ return build != nullptr && std::sscanf(build, "%d.%d", &major, &minor) == 2 &&
+ (major > 2026 || (major == 2026 && minor >= 5));
+ }();
+ return affected_version && ggml_openvino_is_gpu();
+}
+
static bool is_msa_block_mask_expansion(const ggml_tensor * op) {
if (tensor_name_starts_with(op, "msa_")) {
return true;
@@ -1973,8 +2174,11 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
break;
}
case GGML_OP_MUL_MAT: {
- if (ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32) {
- return {false, "MUL_MAT with a BF16 or F32 src1 precision is not supported"};
+ if (ggml_prec_get_src(op, 1) == GGML_PREC_BF16) {
+ return {false, "MUL_MAT with a BF16 src1 precision is not supported"};
+ }
+ if (ggml_prec_get_src(op, 1) == GGML_PREC_F32 && ggml_openvino_is_npu()) {
+ return {false, "MUL_MAT with F32 src1 precision requires CPU or GPU"};
}
if (ggml_openvino_is_gpu() && op->src[0] != nullptr && op->src[1] != nullptr &&
ggml_is_quantized(op->src[0]->type) && strcmp(op->src[0]->name, "a") == 0 &&
@@ -2090,7 +2294,15 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
return {false, reason};
}
if (((const int32_t *) op->op_params)[1] != 0) {
- return {false, "GATED_DELTA_NET with replay of pending tokens is not supported"};
+ bool banks = true;
+ for (int port : {5, 6, 7, 8}) {
+ const auto * source = op->src[port];
+ while (source && (source->op == GGML_OP_VIEW || source->op == GGML_OP_RESHAPE || source->op == GGML_OP_GET_ROWS)) source = source->src[0];
+ banks &= GgmlOvDecoder::is_recurrent_cache(source);
+ }
+ if (!banks || !supports_replay_cache_banks()) {
+ return {false, "GATED_DELTA_NET replay requires the dynamic stateless GPU cache-bank translation"};
+ }
}
break;
}
@@ -2138,6 +2350,10 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
if (padded_w < dilated_kw || padded_h < dilated_kh) {
return {false, "CONV_2D padded input is smaller than kernel"};
}
+ if (op->op == GGML_OP_CONV_2D && op->src[0]->ne[0] == 1 && op->src[0]->ne[1] == 1 &&
+ op->src[0]->type == GGML_TYPE_F16 && (p0 > 0 || p1 > 0) && gpu_has_conv_defect()) {
+ return {false, "CONV_2D with a padded 1x1 f16 kernel is wrong on this OpenVINO GPU plugin"};
+ }
break;
}
case GGML_OP_CONV_3D: {
@@ -2179,6 +2395,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
if (has_non_contiguous_view_input(op)) {
return {false, "CONV_TRANSPOSE with non-contiguous view input is not supported"};
}
+ if (op->op_params[0] == 1 && gpu_has_conv_defect()) {
+ return {false, "CONV_TRANSPOSE with stride 1 is wrong on this OpenVINO GPU plugin"};
+ }
break;
}
case GGML_OP_IM2COL: {
@@ -2289,6 +2508,10 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg
if (op->type == GGML_TYPE_F32 && ggml_get_unary_op(op) == GGML_UNARY_OP_EXPM1) {
return {false, "UNARY_EXPM1 with F32 type is not supported"};
}
+ // The result is copied back densely, so an in-place UNARY on a strided view would be written wrongly.
+ if (op->view_src != nullptr && !ggml_is_contiguous(op)) {
+ return {false, "UNARY in place on a non-contiguous view is not supported"};
+ }
break;
}
case GGML_OP_GLU: {
@@ -2409,7 +2632,17 @@ struct supports_op_tally {
} // namespace
static bool ggml_backend_openvino_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
- if (ggml_get_src_scale(op, 0)) {
+ // A matmul with scale tensors (ggml_mul_mat_ext / ggml_mul_mat_id_ext, #28898) is supported as long as:
+ // - it is a MUL_MAT_ID,
+ // - only the weight scale (ggml_get_src_scale(op, 0)) is set, not the activation scale,
+ // - the weight scale is contiguous (a strided or permuted scale gives wrong results), and
+ // - the expert weights are not MXFP4.
+ // translate_mul_mat_id then multiplies the weight scale into the result, e.g. the per-expert
+ // ffn_down_exps.scale of gemma-4 26B-A4B. Any other scaled matmul is rejected and runs on another
+ // backend: translate_mulmat and the MXFP4 path of translate_mul_mat_id do not apply scales.
+ if (ggml_get_src_scale(op, 1) ||
+ (ggml_get_src_scale(op, 0) && (op->op != GGML_OP_MUL_MAT_ID || op->src[0]->type == GGML_TYPE_MXFP4 ||
+ !ggml_is_contiguous(ggml_get_src_scale(op, 0))))) {
return false;
}
diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp
index 74ba8a1ce..338b81aa5 100644
--- a/ggml/src/ggml-openvino/model-cache.cpp
+++ b/ggml/src/ggml-openvino/model-cache.cpp
@@ -175,6 +175,32 @@ void ggml_openvino_model_cache_init() {
}
}
+#ifdef __linux__
+static uint64_t file_identity(const struct stat & st) {
+ uint64_t identity = FNV_OFFSET;
+ identity = fnv1a_u64(identity, st.st_dev);
+ identity = fnv1a_u64(identity, st.st_ino);
+ identity = fnv1a_u64(identity, st.st_size);
+ identity = fnv1a_u64(identity, st.st_mtim.tv_sec);
+ identity = fnv1a_u64(identity, st.st_mtim.tv_nsec);
+ identity = fnv1a_u64(identity, st.st_ctim.tv_sec);
+ identity = fnv1a_u64(identity, st.st_ctim.tv_nsec);
+ return identity;
+}
+#endif
+
+uint64_t ggml_openvino_file_identity(int fd) {
+#ifdef __linux__
+ struct stat st;
+ if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
+ return file_identity(st);
+ }
+#else
+ GGML_UNUSED(fd);
+#endif
+ return 0;
+}
+
const ggml_openvino_source_mapping * ggml_openvino_find_source_mapping(const void * data, size_t size,
std::vector<ggml_openvino_source_mapping> & mappings) {
const uintptr_t address = reinterpret_cast<uintptr_t>(data);
@@ -198,7 +224,7 @@ const ggml_openvino_source_mapping * ggml_openvino_find_source_mapping(const voi
&offset, &dev_major, &dev_minor, &inode, &path_start) != 7 || inode == 0) {
continue;
}
- ggml_openvino_source_mapping m{uintptr_t(begin), uintptr_t(end), offset, FNV_OFFSET, permissions[1] != 'w'};
+ ggml_openvino_source_mapping m{uintptr_t(begin), uintptr_t(end), offset, FNV_OFFSET, permissions[1] != 'w', {}};
if (!contains(m)) {
continue;
}
@@ -208,13 +234,8 @@ const ggml_openvino_source_mapping * ggml_openvino_find_source_mapping(const voi
major(st.st_dev) != dev_major || minor(st.st_dev) != dev_minor) {
break;
}
- m.identity = fnv1a_u64(m.identity, st.st_dev);
- m.identity = fnv1a_u64(m.identity, st.st_ino);
- m.identity = fnv1a_u64(m.identity, st.st_size);
- m.identity = fnv1a_u64(m.identity, st.st_mtim.tv_sec);
- m.identity = fnv1a_u64(m.identity, st.st_mtim.tv_nsec);
- m.identity = fnv1a_u64(m.identity, st.st_ctim.tv_sec);
- m.identity = fnv1a_u64(m.identity, st.st_ctim.tv_nsec);
+ m.identity = file_identity(st);
+ m.path = path;
mappings.push_back(m);
return &mappings.back();
}
@@ -249,7 +270,7 @@ const ggml_openvino_source_mapping * ggml_openvino_find_source_mapping(const voi
// A view created read-only can never be made writable.
const bool read_only = (memory.AllocationProtect & (PAGE_READONLY | PAGE_EXECUTE_READ)) != 0;
ggml_openvino_source_mapping m{begin, begin + static_cast<uintptr_t>(file_size), 0,
- fnv1a(FNV_OFFSET, "win32", 5), read_only};
+ fnv1a(FNV_OFFSET, "win32", 5), read_only, {}};
if (contains(m)) {
m.identity = fnv1a_u64(m.identity, info.dwVolumeSerialNumber);
m.identity = fnv1a_u64(m.identity, (uint64_t(info.nFileIndexHigh) << 32) | info.nFileIndexLow);
@@ -334,7 +355,10 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph,
// Version 9 hashes GGML_OPENVINO_ROPE_F32_ANGLE, which became opt-in.
// Version 10 hashes only whether GGML_OPENVINO_PROFILING is 2 or more (it then compiles with enable_profiling),
// and no longer GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS, which only changes the output bindings.
- h = fnv1a_u64(h, 10);
+ // Version 11 honors explicit F32 MatMul input precision with node-level guards.
+ // Version 12 keeps the Q5_0 layout (was Q4_0_64).
+ // Version 13 keeps models converted from an ambiguous one-token graph apart (see can_run_tokens()).
+ h = fnv1a_u64(h, 13);
h = fnv1a(h, graph_signature.data(), graph_signature.size());
for (const char * name : cache_settings) {
const char * value = ggml_openvino_getenv_str(name, "");
diff --git a/ggml/src/ggml-openvino/model-cache.h b/ggml/src/ggml-openvino/model-cache.h
index 355f8feeb..eca46a815 100644
--- a/ggml/src/ggml-openvino/model-cache.h
+++ b/ggml/src/ggml-openvino/model-cache.h
@@ -37,8 +37,13 @@ struct ggml_openvino_source_mapping {
uint64_t identity;
// The mapping cannot be written, so its pages always hold the file's bytes.
bool read_only;
+ // The mapped file (Linux), empty when unknown.
+ std::string path;
};
+// Identity of the open file |fd| (Linux), the same value find_source_mapping() stores; 0 if unknown.
+uint64_t ggml_openvino_file_identity(int fd);
+
// Find the file mapping that holds [data, data + size), or nullptr. Cache mappings for one buffer lifetime.
const ggml_openvino_source_mapping * ggml_openvino_find_source_mapping(const void * data, size_t size,
std::vector<ggml_openvino_source_mapping> & mappings);
diff --git a/ggml/src/ggml-openvino/openvino/decoder.h b/ggml/src/ggml-openvino/openvino/decoder.h
index 3a05c8b43..a26ce617b 100644
--- a/ggml/src/ggml-openvino/openvino/decoder.h
+++ b/ggml/src/ggml-openvino/openvino/decoder.h
@@ -26,6 +26,8 @@ struct ModelExtraInputInfo {
// when set, the value is read from dimension shape_axis of this model input instead of a Parameter
std::string shape_source;
int64_t shape_axis = -1;
+ // Optional model shape for runtime controls whose allocation changes per compute.
+ PartialShape parameter_shape = PartialShape::dynamic();
};
class GgmlDecoder : public DecoderBase {
@@ -129,11 +131,16 @@ public:
virtual bool is_prefill() const = 0;
+ // Tokens of a static graph: the prefill chunk size or 1 for decode
+ virtual int get_static_n_tokens() const = 0;
+
virtual bool is_splited_model() const = 0;
virtual int is_swa_layer(int layer) const = 0;
virtual int32_t get_op_dynamic_dim(int node_idx) const = 0;
+ virtual int32_t get_view_input_dynamic_dim(int node_idx, const std::string & name, size_t view_index) const = 0;
+ virtual std::vector<int64_t> get_vision_reshape_pattern(int node_idx) const = 0;
};
} // namespace ggml
diff --git a/ggml/src/ggml-openvino/openvino/node_context.h b/ggml/src/ggml-openvino/openvino/node_context.h
index 51f7f6352..a11573216 100644
--- a/ggml/src/ggml-openvino/openvino/node_context.h
+++ b/ggml/src/ggml-openvino/openvino/node_context.h
@@ -46,6 +46,7 @@ public:
std::string get_output_name() const { return m_output_names[0]; }
PartialShape get_output_shape() const { return m_decoder->get_output_shape(m_node_idx); }
+ std::vector<int64_t> get_vision_reshape_pattern() const { return m_decoder->get_vision_reshape_pattern(m_node_idx); }
int32_t * get_input_op_params(size_t index) const {
return m_decoder->get_input_op_params(m_node_idx, m_input_names[index]);
@@ -97,6 +98,10 @@ public:
int32_t get_op_dynamic_dim() const { return m_decoder->get_op_dynamic_dim(m_node_idx); }
+ int32_t get_view_input_dynamic_dim(size_t index, size_t view_index) const {
+ return m_decoder->get_view_input_dynamic_dim(m_node_idx, m_input_names[index], view_index);
+ }
+
int32_t * get_output_op_params() const { return m_decoder->get_output_op_params(m_node_idx); }
size_t get_output_op_offset() const { return m_decoder->get_output_op_offset(m_node_idx); }
@@ -120,9 +125,9 @@ public:
auto base_it = m_tensor_map->find(base_name);
// A multi-output translator can publish a VIEW directly without materializing
// its packed parent (GatedDeltaNet attention/state). In that case the VIEW is the
- // authoritative value. The node comparison retains the existing resolved-VIEW path.
+ // authoritative value. Compare output ports as well as nodes for resolved Split views.
if (base_it == m_tensor_map->end() ||
- view_it->second.get_node_shared_ptr() != base_it->second.get_node_shared_ptr()) {
+ view_it->second != base_it->second) {
return view_it->second;
}
return base_it->second;
@@ -160,6 +165,8 @@ public:
bool is_prefill() const { return m_decoder->is_prefill(); }
+ int get_static_n_tokens() const { return m_decoder->get_static_n_tokens(); }
+
int get_ssm_state_size() const { return m_decoder->get_ssm_state_size(); }
private:
diff --git a/ggml/src/ggml-openvino/openvino/op/add.cpp b/ggml/src/ggml-openvino/openvino/op/add.cpp
index 84bc85618..fea6384fb 100644
--- a/ggml/src/ggml-openvino/openvino/op/add.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/add.cpp
@@ -15,6 +15,14 @@ namespace ggml {
namespace op {
OutputVector translate_add(const NodeContext & context) {
+ if (context.get_op_case() == 2 || context.get_op_case() == 3) {
+ return translate_moe_tiled(context);
+ }
+ if (context.get_op_case() == 4) {
+ // Inner ADD of an expert sum that translate_moe_tiled replaces: not used, so pass input 0 through
+ // instead of building the Add and the slices of its VIEW inputs.
+ return {context.get_input(0)};
+ }
num_inputs_check(context, 2, 2);
if (context.get_op_case() == 1) {
diff --git a/ggml/src/ggml-openvino/openvino/op/cont.cpp b/ggml/src/ggml-openvino/openvino/op/cont.cpp
index 9888f6b93..7ea7ee083 100644
--- a/ggml/src/ggml-openvino/openvino/op/cont.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/cont.cpp
@@ -18,6 +18,16 @@ OutputVector translate_cont(const NodeContext & context) {
auto src_shape = context.get_input_shape(0).to_shape();
auto dst_shape = context.get_output_shape().to_shape();
+ if (context.has_input("vision_shape_" + context.get_name())) {
+ auto input = process_view_input_new(context, 0);
+ // CONT without a layout change already has its runtime shape.
+ if (src_shape == dst_shape) {
+ return rename_outputs_with_suffix({input}, context.get_name());
+ }
+ auto target = vision_reshape_target(context);
+ return rename_outputs_with_suffix({std::make_shared<ov::op::v1::Reshape>(input, target, false)}, context.get_name());
+ }
+
if (context.get_op_dynamic_dim() != -1) {
dst_shape[3 - context.get_op_dynamic_dim()] = -1;
}
diff --git a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp
index ea223973f..cd6ef1ac5 100644
--- a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp
@@ -389,7 +389,9 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
res = std::make_shared<ov::op::v1::Transpose>(
sdpa, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));
} else {
- auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, scale_node, causal);
+ // SDPA's fourth input is a mask; use a neutral mask to pass the requested scale as input five.
+ auto neutral_mask = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {0.0f});
+ auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, neutral_mask, scale_node, causal);
res = std::make_shared<ov::op::v1::Transpose>(
sdpa, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));
}
diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp
index eef3874fa..92648e212 100644
--- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp
@@ -1,11 +1,9 @@
#include "gated_delta_net.hpp"
#include "../node_context.h"
+#include "recurrent_replay_graph.hpp"
#include "../op_table.h"
#include "../utils.h"
-#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
-#include "recurrent_cache_update.hpp"
-#endif
#include "ggml-openvino/ggml-openvino-extra.h"
#include <cmath>
@@ -30,6 +28,7 @@
#include <openvino/op/maximum.hpp>
#include <openvino/op/minimum.hpp>
#include <openvino/op/multiply.hpp>
+#include <openvino/op/normalize_l2.hpp>
#include <openvino/op/parameter.hpp>
#include <openvino/op/range.hpp>
#include <openvino/op/reduce_mean.hpp>
@@ -402,7 +401,9 @@ static OutputVector translate_gdn_snapshots(const Output<Node> & q,
return {attention, states};
}
-static OutputVector translate_gdn(const NodeContext & context, const OutputVector * cache_inputs) {
+OutputVector translate_gated_delta_net(const NodeContext & context) {
+ FRONT_END_OP_CONVERSION_CHECK(context.get_output_op_params()[1] == 0,
+ "GATED_DELTA_NET replay requires a complete recurrent cache group");
auto v_shape = context.get_input_shape(2).to_shape(); // [B, T, H_v, S_v]
auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k]
@@ -411,7 +412,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
const bool kda = context.get_input_shape(3)[3] != 1;
if (kda && !gdn_per_key_gate_supported()) {
// the reference loop reads and writes the state in the ggml layout, one state per call
- FRONT_END_OP_CONVERSION_CHECK(!cache_inputs && context.get_output_op_params()[0] == 1 &&
+ FRONT_END_OP_CONVERSION_CHECK(context.get_output_op_params()[0] == 1 &&
!ggml_openvino_gdn_native_state_enabled(),
"GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 "
"gate for recurrent caches, state snapshots or the native state layout");
@@ -479,7 +480,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
// resets and slot copies move whole states, and supports_op aborts instead of falling back to CPU.
const bool native_state = ggml_openvino_gdn_native_state_enabled();
auto state_perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, 1, 3, 2});
- if (!native_state && !cache_inputs && snapshot_count == 1) {
+ if (!native_state && snapshot_count == 1) {
state = std::make_shared<ov::op::v1::Transpose>(state, state_perm);
}
@@ -514,21 +515,6 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
g = std::make_shared<ov::op::v1::Multiply>(g, mask);
}
-#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
- if (cache_inputs) {
- OutputVector args{q, k, v, (*cache_inputs)[0], g, beta};
- args.insert(args.end(), cache_inputs->begin() + 1, cache_inputs->end());
- auto fused = std::make_shared<ov::op::internal::RecurrentGatedDeltaNetUpdate>(
- args, fuse_qk_l2norm, q_eps, k_eps, snapshot_count);
- fused->set_friendly_name(context.get_name() + "/RecurrentGatedDeltaNetUpdate");
- // The matched state VIEW is consumed only by the overridden full-cache
- // writeback. Route that cache directly instead of materializing snapshots.
- if (context.get_output_names().size() == 3) {
- return {fused->output(0), fused->output(0), (*cache_inputs)[0]};
- }
- return {fused->output(0), (*cache_inputs)[0]};
- }
-#endif
Output<Node> attn_4d, states;
if (snapshot_count > 1) {
@@ -570,15 +556,31 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
return rename_outputs_with_suffix({res}, context.get_name());
}
-OutputVector translate_gated_delta_net(const NodeContext & context) {
- return translate_gdn(context, nullptr);
-}
-
-#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
-OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs) {
- return translate_gdn(context, &cache_inputs);
+OutputVector translate_recurrent_gated_delta_net_replay(const NodeContext & context, const OutputVector & banks) {
+ auto q = context.get_input(0), k = context.get_input(1);
+ const auto shape = context.get_input_shape(2);
+ auto v = process_view_input(context, 2, shape[2].get_length() * shape[3].get_length(), 3);
+ if (context.get_view_input_size(2)) {
+ v = std::make_shared<ov::op::v0::Squeeze>(v, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
+ v = std::make_shared<ov::op::v1::Reshape>(v, ov::op::v0::Constant::create(ov::element::i64, {4},
+ std::vector<int64_t>{0, 0, shape[2].get_length(), shape[3].get_length()}), true);
+ }
+ if (context.get_op_case() == 1 && ggml_openvino_gdn_prescale_enabled()) {
+ q = std::make_shared<ov::op::v1::Multiply>(q,
+ ov::op::v0::Constant::create(ov::element::f32, {1}, {ggml_openvino_gdn_q_scale()}));
+ } else {
+ Output<Node> raw_q, raw_k;
+ float q_eps, k_eps;
+ if (match_gdn_l2_norm(q, raw_q, q_eps) && match_gdn_l2_norm(k, raw_k, k_eps)) {
+ auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});
+ q = std::make_shared<ov::op::v0::NormalizeL2>(raw_q, axis, q_eps, ov::op::EpsMode::ADD);
+ k = std::make_shared<ov::op::v0::NormalizeL2>(raw_k, axis, k_eps, ov::op::EpsMode::ADD);
+ }
+ }
+ return ov::recurrent_replay::build({
+ q, k, v, banks[0], context.get_input(3), context.get_input(4),
+ banks[1], banks[2], banks[3], banks[4], banks[5], banks[6]}, false);
}
-#endif
static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
num_inputs_check(context, 6, 6);
diff --git a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp
index 59c0fb094..402d14b99 100644
--- a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp
@@ -14,13 +14,37 @@
#include <openvino/op/reshape.hpp>
#include <openvino/op/shape_of.hpp>
#include <openvino/op/slice.hpp>
+#include <openvino/op/tile.hpp>
#include <openvino/op/unsqueeze.hpp>
+#include <optional>
namespace ov {
namespace frontend {
namespace ggml {
namespace op {
+namespace {
+
+// Source of a 4-D Tile that repeats one slice along axis 1 only (ggml_repeat_4d of a single token)
+std::optional<ov::Output<ov::Node>> get_batch_tile_source(const ov::Output<ov::Node> & data) {
+ auto tile = ov::as_type_ptr<ov::op::v0::Tile>(data.get_node_shared_ptr());
+ if (!tile) {
+ return std::nullopt;
+ }
+ auto repeats = ov::as_type_ptr<ov::op::v0::Constant>(tile->get_input_node_shared_ptr(1));
+ const auto & source_shape = tile->get_input_partial_shape(0);
+ if (!repeats || source_shape.rank() != 4 || !source_shape[1].is_static() || source_shape[1].get_length() != 1) {
+ return std::nullopt;
+ }
+ const auto counts = repeats->cast_vector<int64_t>();
+ if (counts.size() != 4 || counts[0] != 1 || counts[2] != 1 || counts[3] != 1) {
+ return std::nullopt;
+ }
+ return tile->input_value(0);
+}
+
+} // namespace
+
OutputVector translate_get_rows(const NodeContext & context) {
num_inputs_check(context, 2, 2);
@@ -70,6 +94,9 @@ OutputVector translate_get_rows(const NodeContext & context) {
auto end = ov::op::v0::Constant::create(ov::element::i64, {1}, {INT_MAX});
indices = std::make_shared<ov::op::v8::Slice>(s_copy, len, end, step, axis);
}
+ } else if (op_case == 3) {
+ // every s_copy row, also when the VIEW is empty (ggml-decoder.cpp, is_rs_cache_gather)
+ indices = context.get_input(1);
} else {
indices = process_view_input_new(context, 1);
}
@@ -123,6 +150,7 @@ OutputVector translate_get_rows(const NodeContext & context) {
res = std::make_shared<ov::op::v8::Gather>(data, indices, axis);
} else {
auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {1});
+ const auto data_4d = data;
data = std::make_shared<ov::op::v1::Reshape>(
data, get_dimensions(data.get_node_shared_ptr(), {1, 2, 3}), false);
// data: [batch, rows, ...], indices: [batch, n] - this is a batched gather
@@ -150,10 +178,17 @@ OutputVector translate_get_rows(const NodeContext & context) {
// instead collapse the redundant data batch to 1 and broadcast 1->dynamic to
// match the indices batch. Mathematically identical (the slices are equal),
// and the whole graph stays dynamic.
- 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 axis0 = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
- auto data_b1 = std::make_shared<ov::op::v8::Slice>(data, zero, one, one, axis0); // [1, rows, ...]
+ // Take the slice before the tiling: the tiled batch is empty in a ubatch without outputs (gemma-4)
+ ov::Output<ov::Node> data_b1;
+ if (auto source = get_batch_tile_source(data_4d)) {
+ data_b1 = std::make_shared<ov::op::v1::Reshape>(
+ *source, get_dimensions(std::make_shared<ov::op::v3::ShapeOf>(*source), {1, 2, 3}), false);
+ } else {
+ 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 axis0 = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
+ data_b1 = std::make_shared<ov::op::v8::Slice>(data, zero, one, one, axis0); // [1, rows, ...]
+ }
auto idx_shape = std::make_shared<ov::op::v3::ShapeOf>(indices, ov::element::i64);
auto idx_batch = get_dimensions(idx_shape, {0}); // [batch] (dynamic)
diff --git a/ggml/src/ggml-openvino/openvino/op/im2col.cpp b/ggml/src/ggml-openvino/openvino/op/im2col.cpp
index 469d1de1f..e27802382 100644
--- a/ggml/src/ggml-openvino/openvino/op/im2col.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/im2col.cpp
@@ -13,6 +13,8 @@
#include <openvino/op/pad.hpp>
#include <openvino/op/reshape.hpp>
#include <openvino/op/slice.hpp>
+#include <openvino/op/shape_of.hpp>
+#include <openvino/op/gather.hpp>
#include <openvino/op/transpose.hpp>
#include <openvino/op/util/attr_types.hpp>
@@ -78,14 +80,13 @@ OutputVector translate_im2col(const NodeContext & context) {
auto t1 = std::make_shared<ov::op::v1::Transpose>(patches, perm1);
// [N, OH, OW, KH*KW*IC] → [N, OH, OW, KH*KW, IC]
- const ov::Shape out_shape = t1->get_output_shape(0);
- const size_t N = out_shape[0];
- const size_t OH = out_shape[1];
- const size_t OW = out_shape[2];
- auto reshape1_shape = ov::op::v0::Constant::create(
- ov::element::i64, ov::Shape{5},
- std::vector<int64_t>{static_cast<int64_t>(N), static_cast<int64_t>(OH), static_cast<int64_t>(OW),
- static_cast<int64_t>(KH * KW), static_cast<int64_t>(IC)});
+ auto spatial_shape = std::make_shared<ov::op::v8::Gather>(
+ std::make_shared<ov::op::v3::ShapeOf>(t1, ov::element::i64),
+ ov::op::v0::Constant::create(ov::element::i64, {3}, {0, 1, 2}),
+ ov::op::v0::Constant::create(ov::element::i64, {}, {0}));
+ auto reshape1_shape = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{spatial_shape,
+ ov::op::v0::Constant::create(ov::element::i64, {2},
+ std::vector<int64_t>{int64_t(KH * KW), int64_t(IC)})}, 0);
auto r1 = std::make_shared<ov::op::v1::Reshape>(t1, reshape1_shape, false);
// [N, OH, OW, KH*KW, IC] → [N, OH, OW, IC, KH*KW]
@@ -93,13 +94,13 @@ OutputVector translate_im2col(const NodeContext & context) {
auto t2 = std::make_shared<ov::op::v1::Transpose>(r1, perm2);
// flatten back to [N, OH, OW, IC*KH*KW]
- auto r2_shape = ov::op::v0::Constant::create(
- ov::element::i64, ov::Shape{4},
- std::vector<int64_t>{static_cast<int64_t>(N), static_cast<int64_t>(OH), static_cast<int64_t>(OW),
- static_cast<int64_t>(IC * KH * KW)});
+ auto r2_shape = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{spatial_shape,
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(IC * KH * KW)})}, 0);
res = std::make_shared<ov::op::v1::Reshape>(t2, r2_shape, false);
if (!is_2D) {
+ const auto out_shape = t1->get_output_shape(0);
+ const size_t N = out_shape[0], OW = out_shape[2];
// [N, 1, OW, IC * KW] -> [1, N, OW, IC * KW]
auto final_reshape_shape = ov::op::v0::Constant::create(
ov::element::i64, ov::Shape{4},
diff --git a/ggml/src/ggml-openvino/openvino/op/moe_tiled.cpp b/ggml/src/ggml-openvino/openvino/op/moe_tiled.cpp
new file mode 100644
index 000000000..0c6b5b333
--- /dev/null
+++ b/ggml/src/ggml-openvino/openvino/op/moe_tiled.cpp
@@ -0,0 +1,168 @@
+#include "../node_context.h"
+#include "../op_table.h"
+#include "../utils.h"
+
+#include <cstdint>
+#include <memory>
+#include <openvino/op/ops.hpp>
+#include <vector>
+
+namespace ov {
+namespace frontend {
+namespace ggml {
+namespace op {
+
+namespace {
+
+ov::Output<ov::Node> const_i32(const std::vector<int32_t> & values) {
+ return ov::op::v0::Constant::create(ov::element::i32, ov::Shape{values.size()}, values);
+}
+
+ov::Output<ov::Node> const_i32_scalar(int32_t value) {
+ return ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {value});
+}
+
+// Expert weights as [n_expert, rows, cols] in the type of the activations
+ov::Output<ov::Node> expert_weights_3d(ov::Output<ov::Node> weights,
+ int64_t n_expert,
+ const ov::element::Type & type) {
+ const auto rank = weights.get_partial_shape().rank();
+ FRONT_END_OP_CONVERSION_CHECK(rank.is_static(), "Expected static rank for MoE expert weights");
+ if (rank.get_length() == 4) {
+ const auto shape = weights.get_partial_shape();
+ FRONT_END_OP_CONVERSION_CHECK(shape.is_static(), "Expected static shape for MoE expert weights");
+ weights = std::make_shared<ov::op::v1::Reshape>(
+ weights,
+ const_i32({static_cast<int32_t>(n_expert), static_cast<int32_t>(shape[2].get_length()),
+ static_cast<int32_t>(shape[3].get_length())}),
+ false);
+ }
+ if (weights.get_element_type() != type) {
+ weights = std::make_shared<ov::op::v0::Convert>(weights, type);
+ }
+ return weights;
+}
+
+} // namespace
+
+// The MoE block in the batched form that the NPUW MoE support (intel_npu/src/plugin/npuw/moe*) looks for; the same graph
+// optimum-intel exports for Qwen3-30B-A3B. Every expert is computed for every token and the result is weighted by the
+// router scores scattered to all experts (0 for a not selected one); NPUW runs only the routed experts.
+//
+// router: probs -> TopK(K) -> [ReduceSum -> Maximum -> Divide] -> ScatterElementsUpdate(zeros, ids, scores)
+// -> Transpose -> Reshape [n_expert, 1, n_tokens] -> Unsqueeze = scores [n_expert, 1, n_tokens, 1]
+// experts: x -> Tile -> Reshape [n_expert, n_tokens, n_embd] -> MatMul(gate) -> Swish, MatMul(up) -> Multiply
+// -> MatMul(down) -> Reshape [n_expert, 1, n_tokens, n_embd] -> Multiply(scores) -> ReduceSum(axis 0)
+//
+// Inputs of the node (see GgmlOvDecoder::set_input_output): the two ADD operands, then router probs, x, the gate, up and
+// down expert weights, the down MUL_MAT_ID (for the number of used experts) and, for op case 3, the CLAMP of the weights.
+OutputVector translate_moe_tiled(const NodeContext & context) {
+ const bool normalize = context.get_op_case() == 3;
+ num_inputs_check(context, normalize ? 9 : 8, normalize ? 9 : 8);
+
+ auto probs = context.get_input(2);
+ auto x = context.get_input(3);
+ const auto act_type = x.get_element_type();
+
+ // ggml [n_embd, n_ff, n_expert] and [n_ff, n_embd, n_expert] -> OV [1, n_expert, rows, cols]
+ const auto gate_shape = context.get_input_shape(4);
+ FRONT_END_OP_CONVERSION_CHECK(gate_shape.rank().is_static() && gate_shape.rank().get_length() == 4 &&
+ gate_shape.is_static(),
+ "MoE expert weights need a static 4D shape");
+ const int64_t n_expert = gate_shape[1].get_length();
+ const int64_t n_embd = gate_shape[3].get_length();
+ // down MUL_MAT_ID: ggml [n_embd, n_expert_used, n_tokens] -> OV [1, n_tokens, n_expert_used, n_embd]
+ const auto used_shape = context.get_input_shape(7);
+ FRONT_END_OP_CONVERSION_CHECK(used_shape[2].is_static(), "MoE needs a static number of used experts");
+ const int32_t n_used = static_cast<int32_t>(used_shape[2].get_length());
+
+ auto gate_w = expert_weights_3d(context.get_input(4), n_expert, act_type);
+ auto up_w = expert_weights_3d(context.get_input(5), n_expert, act_type);
+ auto down_w = expert_weights_3d(context.get_input(6), n_expert, act_type);
+
+ ov::Output<ov::Node> x_2d =
+ std::make_shared<ov::op::v1::Reshape>(x, const_i32({-1, static_cast<int32_t>(n_embd)}), false);
+ ov::Output<ov::Node> probs_2d =
+ std::make_shared<ov::op::v1::Reshape>(probs, const_i32({-1, static_cast<int32_t>(n_expert)}), false);
+
+ // In a static graph the last layer can run on fewer tokens than the graph: its rows are selected by the output ids
+ // (1 row in the prefill graph). Pad the block to the tokens of the graph, so that it is the same as the block of the
+ // other layers: NPUW only lowers MoE blocks that it folds into one repeated function. The padded rows are zero and
+ // are dropped after the block.
+ int64_t n_rows = -1;
+ int64_t n_pad = 0;
+ if (context.is_static()) {
+ const auto rows = x_2d.get_partial_shape()[0];
+ FRONT_END_OP_CONVERSION_CHECK(rows.is_static(), "MoE needs a static number of tokens in a static graph");
+ n_rows = rows.get_length();
+ n_pad = context.get_static_n_tokens() - n_rows;
+ }
+ if (n_pad > 0) {
+ auto pad = [&](const ov::Output<ov::Node> & input) {
+ return std::make_shared<ov::op::v12::Pad>(
+ input, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, 0}),
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {n_pad, int64_t{0}}),
+ ov::op::v0::Constant::create(input.get_element_type(), ov::Shape{}, {0.0f}), ov::op::PadMode::CONSTANT);
+ };
+ x_2d = pad(x_2d);
+ probs_2d = pad(probs_2d);
+ }
+
+ // Router
+ auto topk = std::make_shared<ov::op::v11::TopK>(probs_2d, const_i32_scalar(n_used), 1,
+ ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::SORT_VALUES,
+ ov::element::i32);
+ ov::Output<ov::Node> scores = topk->output(0);
+ if (normalize) {
+ float clamp_min;
+ memcpy(&clamp_min, context.get_input_op_params(8), sizeof(clamp_min));
+ auto sum = std::make_shared<ov::op::v1::ReduceSum>(scores, const_i32({1}), true);
+ auto denominator = std::make_shared<ov::op::v1::Maximum>(
+ sum, ov::op::v0::Constant::create(scores.get_element_type(), ov::Shape{}, {clamp_min}));
+ scores = std::make_shared<ov::op::v1::Divide>(scores, denominator);
+ }
+ auto zeros = std::make_shared<ov::op::v3::Broadcast>(
+ ov::op::v0::Constant::create(scores.get_element_type(), ov::Shape{}, {0.0f}),
+ std::make_shared<ov::op::v3::ShapeOf>(probs_2d, ov::element::i32), ov::op::BroadcastType::NUMPY);
+ auto scatter = std::make_shared<ov::op::v12::ScatterElementsUpdate>(zeros, topk->output(1), scores,
+ const_i32_scalar(1));
+ auto transposed = std::make_shared<ov::op::v1::Transpose>(scatter, const_i32({1, 0}));
+ auto reshaped = std::make_shared<ov::op::v1::Reshape>(transposed, const_i32({static_cast<int32_t>(n_expert), 1, -1}),
+ false);
+ auto router_scores = std::make_shared<ov::op::v0::Unsqueeze>(reshaped, const_i32_scalar(3));
+
+ // Experts
+ auto tiled = std::make_shared<ov::op::v0::Tile>(x_2d, const_i32({static_cast<int32_t>(n_expert), 1}));
+ auto expert_in = std::make_shared<ov::op::v1::Reshape>(
+ tiled, const_i32({static_cast<int32_t>(n_expert), -1, static_cast<int32_t>(n_embd)}), false);
+ auto gate_out = std::make_shared<ov::op::v0::MatMul>(expert_in, gate_w, false, true);
+ auto activated = std::make_shared<ov::op::v4::Swish>(gate_out);
+ auto up_out = std::make_shared<ov::op::v0::MatMul>(expert_in, up_w, false, true);
+ auto merged = std::make_shared<ov::op::v1::Multiply>(activated, up_out);
+ auto down_out = std::make_shared<ov::op::v0::MatMul>(merged, down_w, false, true);
+ auto expert_out = std::make_shared<ov::op::v1::Reshape>(
+ down_out, const_i32({static_cast<int32_t>(n_expert), 1, -1, static_cast<int32_t>(n_embd)}), false);
+ auto weighted = std::make_shared<ov::op::v1::Multiply>(expert_out, router_scores);
+ ov::Output<ov::Node> reduced = std::make_shared<ov::op::v1::ReduceSum>(weighted, const_i32({0}), false);
+ if (n_pad > 0) {
+ // [1, tokens, n_embd]: keep the rows of the block
+ reduced = std::make_shared<ov::op::v8::Slice>(
+ reduced, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}),
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {n_rows}),
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}),
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}));
+ }
+
+ // ggml [n_embd, n_tokens] -> OV [1, 1, n_tokens, n_embd]
+ ov::Output<ov::Node> result = std::make_shared<ov::op::v1::Reshape>(
+ reduced, const_i32({1, 1, -1, static_cast<int32_t>(n_embd)}), false);
+ if (result.get_element_type() != context.get_output_type()) {
+ result = std::make_shared<ov::op::v0::Convert>(result, context.get_output_type());
+ }
+ return rename_outputs_with_suffix({result}, context.get_name());
+}
+
+} // namespace op
+} // namespace ggml
+} // namespace frontend
+} // namespace ov
diff --git a/ggml/src/ggml-openvino/openvino/op/mul_mat_id.cpp b/ggml/src/ggml-openvino/openvino/op/mul_mat_id.cpp
index 5a06035ef..ada9c7a7f 100644
--- a/ggml/src/ggml-openvino/openvino/op/mul_mat_id.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/mul_mat_id.cpp
@@ -26,6 +26,7 @@
#include <openvino/op/matmul.hpp>
#include <openvino/op/maximum.hpp>
#include <openvino/op/multiply.hpp>
+#include <openvino/op/not_equal.hpp>
#include <openvino/op/reduce_logical_or.hpp>
#include <openvino/op/reduce_sum.hpp>
#include <openvino/op/reshape.hpp>
@@ -263,8 +264,52 @@ ov::Output<ov::Node> translate_mul_mat_id_mxfp4_packed(const NodeContext & conte
} // namespace
+// Weight scale of ggml_mul_mat_id_ext (src[3]): per-tensor [1], per-expert [n_expert] or
+// per-channel-per-expert [n_out, n_expert] in GGML order. Picks each slot's scale by its expert id and
+// multiplies it into result, as the CPU backend does after its matmul.
+// ids: [n_tokens, n_used]
+// result: [1, n_tokens, n_used, n_out], or [n_tokens, n_used, n_out] on the stateful path
+// The form is told apart by the element count against the expert weights' dims, as the CPU backend does
+// (ggml_compute_forward_mul_mat_id_scale), not by the shape the scale tensor happens to carry.
+static ov::Output<ov::Node> apply_weight_scale(const ov::Output<ov::Node> & result,
+ ov::Output<ov::Node> scale,
+ const ov::Output<ov::Node> & ids,
+ int64_t n_expert,
+ int64_t n_out) {
+ const auto & ps = scale.get_partial_shape();
+ FRONT_END_OP_CONVERSION_CHECK(ps.is_static(), "Expected a static shape for the MUL_MAT_ID weight scale");
+ const int64_t n_scale = static_cast<int64_t>(ov::shape_size(ps.to_shape()));
+ if (scale.get_element_type() != result.get_element_type()) {
+ scale = std::make_shared<ov::op::v0::Convert>(scale, result.get_element_type());
+ }
+ if (n_scale == 1) {
+ auto scalar = std::make_shared<ov::op::v1::Reshape>(scale, const_i64({1}), false);
+ return std::make_shared<ov::op::v1::Multiply>(result, scalar);
+ }
+ // Lookup table indexed by expert id: [n_expert], or [n_expert, n_out] (GGML [n_out, n_expert] reversed).
+ std::vector<int64_t> dims;
+ if (n_scale == n_expert) {
+ dims = { n_expert };
+ } else if (n_scale == n_expert * n_out) {
+ dims = { n_expert, n_out };
+ }
+ FRONT_END_OP_CONVERSION_CHECK(!dims.empty(), "MUL_MAT_ID weight scale shape ", ps, " fits neither n_expert=",
+ n_expert, " nor n_expert x n_out=", n_expert, "x", n_out);
+ auto table = std::make_shared<ov::op::v1::Reshape>(scale, const_i64(dims), false);
+ ov::Output<ov::Node> picked = std::make_shared<ov::op::v8::Gather>(table, ids, const_i64({0}));
+ if (dims.size() == 1) {
+ picked = std::make_shared<ov::op::v0::Unsqueeze>(picked, const_i64({-1})); // [n_tokens, n_used, 1]
+ }
+ // Same rank as result, so the per-expert scale has the router weights' shape [1, n_tokens, n_used, 1]:
+ // FuseMoeCompressedFusedGateUp folds it into the routing weights only when the shapes match.
+ if (result.get_partial_shape().rank().get_length() == 4) {
+ picked = std::make_shared<ov::op::v0::Unsqueeze>(picked, const_i64({0}));
+ }
+ return std::make_shared<ov::op::v1::Multiply>(result, picked);
+}
+
OutputVector translate_mul_mat_id(const NodeContext & context) {
- num_inputs_check(context, 3, 3);
+ num_inputs_check(context, 3, 4);
auto expert_weights = process_view_input_new(context, 0);
auto activations = process_view_input_new(context, 1);
@@ -348,8 +393,24 @@ OutputVector translate_mul_mat_id(const NodeContext & context) {
if (result.get_element_type() != output_type) {
result = std::make_shared<ov::op::v0::Convert>(result, output_type);
}
+ if (context.get_input_size() > 3) {
+ // Expert weights are GGML [k, n_out, n_expert], i.e. [..., n_expert, n_out, k] here.
+ const auto weights_shape = context.get_input_shape(0);
+ const auto rank = weights_shape.rank();
+ FRONT_END_OP_CONVERSION_CHECK(rank.is_static() && rank.get_length() >= 3 &&
+ weights_shape[rank.get_length() - 3].is_static() &&
+ weights_shape[rank.get_length() - 2].is_static(),
+ "Expected static n_expert and n_out for a scaled MUL_MAT_ID, got ",
+ weights_shape);
+ const int64_t n_expert = weights_shape[rank.get_length() - 3].get_length();
+ const int64_t n_out = weights_shape[rank.get_length() - 2].get_length();
+ result = apply_weight_scale(result, process_view_input_new(context, 3), ids, n_expert, n_out);
+ }
if (keep) {
- result = std::make_shared<ov::op::v1::Multiply>(result, *keep);
+ // Select, not Multiply: a skipped slot stays zero even when the weight scale is infinite.
+ auto zero = ov::op::v0::Constant::create(result.get_element_type(), ov::Shape{}, {0});
+ result =
+ std::make_shared<ov::op::v1::Select>(std::make_shared<ov::op::v1::NotEqual>(*keep, zero), result, zero);
}
return rename_outputs_with_suffix({result}, context.get_name());
diff --git a/ggml/src/ggml-openvino/openvino/op/mulmat.cpp b/ggml/src/ggml-openvino/openvino/op/mulmat.cpp
index 45fc1a547..4ef1c7871 100644
--- a/ggml/src/ggml-openvino/openvino/op/mulmat.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/mulmat.cpp
@@ -1,6 +1,7 @@
#include "../node_context.h"
#include "../op_table.h"
#include "../utils.h"
+#include "ggml.h"
#include <cstdint>
#include <memory>
@@ -16,9 +17,13 @@
#include <openvino/op/transpose.hpp>
#include <openvino/op/unsqueeze.hpp>
#include <openvino/op/util/op_types.hpp>
+#include <openvino/op/util/precision_sensitive_attribute.hpp>
#include <vector>
namespace ov {
+// Runtime SDKs omit the transformation header but export this helper.
+OPENVINO_API void disable_conversion(const std::shared_ptr<Node> & node, const element::Type & to);
+
namespace frontend {
namespace ggml {
namespace op {
@@ -33,10 +38,32 @@ OutputVector translate_mulmat(const NodeContext & context) {
// the stateful V cache with `-fa off` is not transposed (see permute)
const bool transpose_b = B.get_node()->get_rt_info().count(GGML_OV_V_TOKEN_MAJOR) == 0;
- if (A.get_element_type() != B.get_element_type()) {
+ // MUL_MAT stores the minimum src1 precision in op_params[3].
+ const auto * params = context.get_output_op_params();
+ const bool preserve_f32 = params != nullptr && params[3] == GGML_PREC_F32;
+ if (preserve_f32) {
+ if (A.get_element_type() != ov::element::f32) {
+ A = std::make_shared<ov::op::v0::Convert>(A, ov::element::f32);
+ }
+ if (B.get_element_type() != ov::element::f32) {
+ B = std::make_shared<ov::op::v0::Convert>(B, ov::element::f32);
+ }
+ } else if (A.get_element_type() != B.get_element_type()) {
B = std::make_shared<ov::op::v0::Convert>(B, context.get_input_type(1));
}
+ auto make_matmul = [&](const ov::Output<ov::Node> & a, const ov::Output<ov::Node> & b) {
+ auto node = std::make_shared<ov::op::v0::MatMul>(a, b, false, transpose_b);
+ if (preserve_f32) {
+ // Keep this MatMul and its input layout/conversion paths in F32; other branches keep their precision.
+ ov::disable_conversion(node, ov::element::f16);
+ ov::disable_conversion(node, ov::element::bf16);
+ ov::mark_as_precision_sensitive(node->input(0));
+ ov::mark_as_precision_sensitive(node->input(1));
+ }
+ return node;
+ };
+
auto B_shape = context.get_input_shape(0).to_shape();
auto A_shape = context.get_input_shape(1).to_shape();
int64_t A_batch = A_shape[1];
@@ -68,7 +95,7 @@ OutputVector translate_mulmat(const NodeContext & context) {
A_reshape->get_input_partial_shape(0)[1] == batch_small) {
A_grouped = A_reshape->input_value(0);
}
- ov::Output<Node> res = std::make_shared<ov::op::v0::MatMul>(A_grouped, B, false, transpose_b);
+ ov::Output<Node> res = make_matmul(A_grouped, B);
res = std::make_shared<ov::op::v1::Reshape>(
res, ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, batch_large, -1, 0}),
true);
@@ -107,7 +134,7 @@ OutputVector translate_mulmat(const NodeContext & context) {
A = Z;
}
- ov::Output<Node> res = std::make_shared<ov::op::v0::MatMul>(A, B, false, transpose_b);
+ ov::Output<Node> res = make_matmul(A, B);
const auto output_type = context.get_output_type();
if (res.get_element_type() != output_type) {
diff --git a/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp
deleted file mode 100644
index a4daf8c86..000000000
--- a/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright (C) 2026 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-#pragma once
-#include "openvino/op/op.hpp"
-
-namespace ov::op::internal {
-/// Qwen3.5/Qwen3.6 llama.cpp convolution and generic cache_r maintenance.
-/// Inputs: original cache, active rows, extra rows, reset begin/length,
-/// extra offsets, QKV [1,B,C,T], windows and depthwise weights.
-/// Nine inputs; output 0 is convolution [1,B,T,C].
-/// Cache input 0 is a writable GPU RemoteTensor, updated in place.
-/// Other inputs and output 0 must not overlap its allocation.
-/// The cache must be a Parameter or an exclusive Reshape alias; no other op
-/// may read it in the same inference. Required original rows are staged before
-/// reset, reorder and window writes, preserving cycles and duplicate sources.
-/// A failed inference may partially modify the cache; clear or restore it before retrying.
-class OPENVINO_API RecurrentConvCacheUpdate : public Op {
-public:
- OPENVINO_OP("RecurrentConvCacheUpdate", "internal")
- RecurrentConvCacheUpdate() = default;
- RecurrentConvCacheUpdate(const OutputVector & args, int64_t history);
- void validate_and_infer_types() override;
- bool visit_attributes(AttributeVisitor &) override;
- std::shared_ptr<Node> clone_with_new_inputs(const OutputVector &) const override;
-
- int64_t get_history() const { return m_history; }
-
-private:
- int64_t m_history = 0;
-};
-
-/// Qwen3.5/Qwen3.6 llama.cpp GDN and generic cache_s maintenance.
-/// Twelve inputs: Q/K/V, cache, gate/beta,
-/// active/extra rows, reset begin/length, extra offsets, ordered write control.
-/// The only output is attention [B,T,H,V]. Cache input 3 is updated in place
-/// under the same writable-input contract as RecurrentConvCacheUpdate.
-/// snapshot_count saves the newest min(T,count) states in cache, newest first.
-/// Active/nonidentity rows are staged before writes; identity rows need no copy.
-class OPENVINO_API RecurrentGatedDeltaNetUpdate : public Op {
-public:
- OPENVINO_OP("RecurrentGatedDeltaNetUpdate", "internal")
- RecurrentGatedDeltaNetUpdate() = default;
- RecurrentGatedDeltaNetUpdate(const OutputVector & args,
- bool fuse_qk_l2norm = false,
- float q_l2_norm_eps = 1e-6f,
- float k_l2_norm_eps = 1e-6f,
- int64_t snapshot_count = 1);
- void validate_and_infer_types() override;
- bool visit_attributes(AttributeVisitor &) override;
- std::shared_ptr<Node> clone_with_new_inputs(const OutputVector &) const override;
-
- bool get_fuse_qk_l2norm() const { return m_fuse_qk_l2norm; }
-
- float get_q_l2_norm_eps() const { return m_q_l2_norm_eps; }
-
- float get_k_l2_norm_eps() const { return m_k_l2_norm_eps; }
-
- int64_t get_snapshot_count() const { return m_snapshot_count; }
-
-private:
- bool m_fuse_qk_l2norm = false;
- float m_q_l2_norm_eps = 1e-6f, m_k_l2_norm_eps = 1e-6f;
- int64_t m_snapshot_count = 1;
-};
-} // namespace ov::op::internal
diff --git a/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp
new file mode 100644
index 000000000..e4b6777c2
--- /dev/null
+++ b/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp
@@ -0,0 +1,228 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+#pragma once
+
+#include "openvino/opsets/opset13.hpp"
+#include "openvino/core/model.hpp"
+#include "openvino/core/visibility.hpp"
+#include <limits>
+#include <cmath>
+#include <unordered_set>
+
+namespace ov {
+// The runtime exports this transformation attribute even when its header is not installed.
+#ifndef OPENVINO_STATIC_LIBRARY
+OPENVINO_CORE_IMPORTS
+#endif
+void disable_conversion(const std::shared_ptr<Node>& node, const element::Type& to);
+}
+
+namespace ov::recurrent_replay {
+// OpenVINO's GPU RecurrentReplayFusion checks this emitted graph against its
+// reference replay graph. Keep the patterns in both repositories in sync.
+namespace ops = ov::opset13;
+using Value = ov::Output<ov::Node>;
+
+inline Value scalar(int64_t n) { return ops::Constant::create(element::i64, {}, {n}); }
+inline Value vec(std::vector<int64_t> v) { return ops::Constant::create(element::i64, {v.size()}, v); }
+inline Value fp(float x) { return ops::Constant::create(element::f32, {}, {x}); }
+inline Value f32(Value x) {
+ return x.get_element_type() == element::f32 ? x : Value(std::make_shared<ops::Convert>(x, element::f32));
+}
+inline Value gather(Value x, Value i, int axis, int batch = 0) {
+ return std::make_shared<ops::Gather>(x, i, scalar(axis), batch);
+}
+inline Value unsqueeze(Value x, int axis) { return std::make_shared<ops::Unsqueeze>(x, scalar(axis)); }
+inline Value squeeze(Value x, int axis) { return std::make_shared<ops::Squeeze>(x, scalar(axis)); }
+inline Value reshape(Value x, std::vector<int64_t> dims) { return std::make_shared<ops::Reshape>(x, vec(dims), true); }
+inline Value dim(Value x, int axis) { return gather(std::make_shared<ops::ShapeOf>(x, element::i64), scalar(axis), 0); }
+inline Value cat(OutputVector xs, int axis) { return std::make_shared<ops::Concat>(xs, axis); }
+inline Value slice(Value x, Value begin, Value end, int axis) {
+ return std::make_shared<ops::Slice>(x, unsqueeze(begin, 0), unsqueeze(end, 0), vec({1}), vec({axis}));
+}
+inline Value slice_end() { return scalar(std::numeric_limits<int64_t>::max()); }
+inline Value add(Value x, Value y) { return std::make_shared<ops::Add>(x, y); }
+inline Value mul(Value x, Value y) { return std::make_shared<ops::Multiply>(x, y); }
+inline Value swap_time_channels(Value x) { return std::make_shared<ops::Transpose>(x, vec({0, 2, 1})); }
+inline Value linear(Value count) { return std::make_shared<ops::Range>(scalar(0), count, scalar(1), element::i64); }
+
+struct RowSelection {
+ Value sources, destinations, extra_src, extra_dst, resets, counts, keep;
+ RowSelection(Value rows, Value control, Value reset, Value batch) {
+ rows = reshape(rows, {-1, 2});
+ auto src = gather(rows, scalar(1), 1);
+ auto dst = gather(rows, scalar(0), 1);
+ sources = slice(src, scalar(0), batch, 0);
+ destinations = slice(dst, scalar(0), batch, 0);
+ extra_src = slice(src, batch, slice_end(), 0);
+ extra_dst = slice(dst, batch, slice_end(), 0);
+ resets = reshape(reset, {-1});
+ auto flags = reshape(control, {-1});
+ counts = slice(flags, scalar(0), batch, 0);
+ keep = std::make_shared<ops::NotEqual>(gather(flags, scalar(-1), 0), scalar(0));
+ }
+};
+
+// A bank is logically [slots, features]. Gather original rows before any stores;
+// active stores only replace their written features in the destination row.
+struct Bank {
+ Value cleared, sources, destinations, extra_values;
+ const RowSelection& rows;
+ Bank(Value input, const RowSelection& r) : rows(r) {
+ auto flat = squeeze(squeeze(input, 0), 0);
+ auto reset_shape = cat({unsqueeze(dim(r.resets, 0), 0), unsqueeze(dim(flat, 1), 0)}, 0);
+ auto zeros = std::make_shared<ops::Broadcast>(fp(0), reset_shape);
+ cleared = std::make_shared<ops::ScatterNDUpdate>(flat, unsqueeze(r.resets, 1), zeros);
+ sources = gather(cleared, r.sources, 0);
+ destinations = gather(cleared, r.destinations, 0);
+ extra_values = gather(cleared, r.extra_src, 0);
+ }
+ Value write(Value active) const {
+ // One destination per row-map entry. GGML generates these in slot order,
+ // including the inactive rows that need a copy.
+ auto indices = unsqueeze(cat({rows.destinations, rows.extra_dst}, 0), 1);
+ auto values = cat({reshape(active, {0, -1}), extra_values}, 0);
+ auto result = std::make_shared<ops::ScatterNDUpdate>(cleared, indices, values);
+ return unsqueeze(unsqueeze(result, 0), 0);
+ }
+};
+inline Value store_prefix(Value original, Value prefix) {
+ return cat({prefix, slice(original, dim(prefix, 1), slice_end(), 1)}, 1);
+}
+
+inline OutputVector conv_body(const OutputVector& a) {
+ auto x = squeeze(a[2], 0);
+ const auto channels = a[3].get_partial_shape()[2].get_length();
+ const auto taps = a[3].get_partial_shape()[3].get_length();
+ RowSelection rows(a[1], a[4], a[5], dim(x, 0));
+ Bank bank(a[0], rows);
+ auto history = reshape(bank.sources, {0, -1, channels});
+ auto indices = add(unsqueeze(rows.counts, 1), unsqueeze(linear(scalar(taps - 1)), 0));
+ auto window = gather(history, indices, 1, 1);
+ auto columns = cat({window, f32(x)}, 1);
+ auto weights = reshape(f32(a[3]), {channels, 1, 1, taps});
+ auto convolved = std::make_shared<ops::GroupConvolution>(swap_time_channels(columns), weights, Strides{1},
+ CoordinateDiff{0}, CoordinateDiff{0}, Strides{1});
+ Value result = unsqueeze(swap_time_channels(convolved), 0);
+ if (a[2].get_element_type() != element::f32)
+ result = std::make_shared<ops::Convert>(result, a[2].get_element_type());
+ // Keep the history and pending tokens, or commit only the last history window.
+ auto begin = std::make_shared<ops::Select>(rows.keep, scalar(0), dim(x, 1));
+ auto update = slice(columns, begin, slice_end(), 1);
+ return {result, bank.write(store_prefix(reshape(bank.destinations, {0, -1, channels}), update))};
+}
+
+inline Value expand_heads(Value x, int64_t heads, int64_t expanded) {
+ if (heads == expanded)
+ return x;
+ std::vector<int64_t> indices(expanded);
+ for (int64_t h = 0; h < expanded; ++h)
+ indices[h] = h % heads;
+ return gather(x, vec(indices), 2);
+}
+inline Value dot(Value state, Value key) {
+ return std::make_shared<ops::ReduceSum>(mul(state, unsqueeze(key, 2)), scalar(3), false);
+}
+inline Value step(Value state, Value key, Value value, Value gate, Value beta) {
+ auto decayed = mul(state, unsqueeze(std::make_shared<ops::Exp>(gate), 2));
+ auto delta = mul(beta, std::make_shared<ops::Subtract>(value, dot(decayed, key)));
+ return add(decayed, mul(unsqueeze(delta, 3), unsqueeze(key, 2)));
+}
+inline OutputVector current_tokens(Value state, Value q, Value k, Value v, Value g, Value beta, float scale) {
+ auto idx = std::make_shared<ops::Parameter>(element::i64, PartialShape{});
+ auto carried = std::make_shared<ops::Parameter>(element::f32, state.get_partial_shape());
+ ParameterVector params{idx, carried};
+ OutputVector inputs{q, k, v, g, beta}, token;
+ for (const auto& input : inputs) {
+ auto p = std::make_shared<ops::Parameter>(input.get_element_type(), input.get_partial_shape());
+ params.push_back(p);
+ token.push_back(gather(p, idx, 1));
+ }
+ auto next = step(carried, token[1], token[2], token[3], token[4]);
+ auto attention = unsqueeze(mul(dot(next, token[0]), fp(scale)), 1);
+ auto yes = ops::Constant::create(element::boolean, {}, {true});
+ auto body = std::make_shared<Model>(OutputVector{yes, next, attention}, params);
+ auto loop = std::make_shared<ops::Loop>(dim(v, 1), yes);
+ loop->set_function(body);
+ loop->set_special_body_ports({0, 0});
+ loop->set_merged_input(carried, state, next);
+ for (size_t i = 0; i < inputs.size(); ++i)
+ loop->set_invariant_input(params[i + 2], inputs[i]);
+ return {loop->get_concatenated_slices(attention, 0, 1, 1, -1, 1), loop->get_iter_value(next, -1)};
+}
+
+inline OutputVector gdn_body(const OutputVector& a) {
+ const auto qshape = a[0].get_partial_shape(), kshape = a[1].get_partial_shape(), vshape = a[2].get_partial_shape();
+ const int64_t Hq = qshape[2].get_length(), Hk = kshape[2].get_length(), Hv = vshape[2].get_length();
+ const int64_t K = kshape[3].get_length(), V = vshape[3].get_length(), G = a[4].get_partial_shape()[3].get_length();
+ const int64_t P = a[6].get_partial_shape()[3].get_length() / (Hk * K);
+ RowSelection rows(a[9], a[10], a[11], dim(a[2], 0));
+ Bank states(a[3], rows), keys(a[6], rows), values(a[7], rows), gates(a[8], rows);
+ Value state = reshape(states.sources, {0, Hv, V, K});
+ auto pk = expand_heads(reshape(keys.sources, {0, P, Hk, K}), Hk, Hv);
+ auto pv = reshape(values.sources, {0, P, Hv, V});
+ auto pgb = reshape(gates.sources, {0, 2 * P, Hv, G});
+ for (int64_t t = 0; t < P; ++t) {
+ auto time = scalar(t);
+ auto b = slice(gather(pgb, scalar(P + t), 1), scalar(0), scalar(1), 2);
+ auto next = step(state, gather(pk, time, 1), gather(pv, time, 1), gather(pgb, time, 1), b);
+ auto active = reshape(std::make_shared<ops::Greater>(rows.counts, time), {-1, 1, 1, 1});
+ state = std::make_shared<ops::Select>(active, next, state);
+ }
+ auto q = expand_heads(f32(a[0]), Hq, Hv), k = expand_heads(f32(a[1]), Hk, Hv);
+ auto computed = current_tokens(state, q, k, f32(a[2]), f32(a[4]), f32(a[5]), 1.0f / std::sqrt(float(K)));
+ auto save = [&](Value x) { return slice(f32(x), scalar(0), scalar(P), 1); };
+ auto saved_g = save(a[4]), saved_b = save(a[5]);
+ auto gb = reshape(gates.destinations, {0, 2 * P, Hv, G});
+ auto gb_gate = slice(gb, scalar(0), scalar(P), 1), gb_beta = slice(gb, scalar(P), slice_end(), 1);
+ if (G > 1) {
+ auto old_prefix = slice(gb_beta, scalar(0), dim(saved_b, 1), 1);
+ saved_b = cat({saved_b, slice(old_prefix, scalar(1), slice_end(), 3)}, 3);
+ }
+ Value output = computed[0];
+ if (a[0].get_element_type() != element::f32)
+ output = std::make_shared<ops::Convert>(output, a[0].get_element_type());
+ auto committed = std::make_shared<ops::Select>(rows.keep, state, computed[1]);
+ return {output, states.write(committed),
+ keys.write(store_prefix(reshape(keys.destinations, {0, P, Hk, K}), save(a[1]))),
+ values.write(store_prefix(reshape(values.destinations, {0, P, Hv, V}), save(a[2]))),
+ gates.write(cat({store_prefix(gb_gate, saved_g), store_prefix(gb_beta, saved_b)}, 1))};
+}
+
+inline OutputVector build(const OutputVector& args, bool conv) {
+ auto outputs = conv ? conv_body(args) : gdn_body(args);
+ const auto bank_ports = conv ? std::vector<size_t>{0} : std::vector<size_t>{3, 6, 7, 8};
+ for (const auto port : bank_ports) {
+ auto bank = args[port];
+ while (ov::is_type<ops::Reshape>(bank.get_node())) {
+ ov::disable_conversion(bank.get_node_shared_ptr(), element::f16);
+ bank = bank.get_node()->input_value(0);
+ }
+ ov::disable_conversion(bank.get_node_shared_ptr(), element::f16);
+ }
+ // Keep the functional replay state in FP32 under the GPU's mixed-precision
+ // policy. Stop at the replay inputs to preserve the upstream precision policy.
+ std::unordered_set<const Node*> visited;
+ for (const auto& arg : args) {
+ visited.insert(arg.get_node());
+ }
+ auto pending = outputs;
+ while (!pending.empty()) {
+ const auto node = pending.back().get_node_shared_ptr();
+ pending.pop_back();
+ if (!visited.insert(node.get()).second) {
+ continue;
+ }
+ ov::disable_conversion(node, element::f16);
+ if (const auto loop = ov::as_type_ptr<ops::Loop>(node)) {
+ for (const auto& body_node : loop->get_function()->get_ordered_ops()) {
+ ov::disable_conversion(body_node, element::f16);
+ }
+ }
+ for (const auto& input : node->input_values()) {
+ pending.push_back(input);
+ }
+ }
+ return outputs;
+}
+} // namespace ov::recurrent_replay
diff --git a/ggml/src/ggml-openvino/openvino/op/repeat.cpp b/ggml/src/ggml-openvino/openvino/op/repeat.cpp
index b7aeaa24f..3174ebba1 100644
--- a/ggml/src/ggml-openvino/openvino/op/repeat.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/repeat.cpp
@@ -16,7 +16,7 @@ namespace ggml {
namespace op {
// GGML_OP_REPEAT tiles src[0] to fill the destination shape. Every destination
-// dimension is an integer multiple of the corresponding source dimension.
+// dimension is an integer multiple of the corresponding source dimension (zero included).
OutputVector translate_repeat(const NodeContext & context) {
num_inputs_check(context, 1, 2);
@@ -30,7 +30,7 @@ OutputVector translate_repeat(const NodeContext & context) {
const int64_t input_dim = input_shape[axis];
const int64_t output_dim = output_shape[axis];
- FRONT_END_OP_CONVERSION_CHECK(input_dim > 0 && output_dim > 0 && output_dim % input_dim == 0,
+ FRONT_END_OP_CONVERSION_CHECK(input_dim > 0 && output_dim >= 0 && output_dim % input_dim == 0,
"REPEAT input shape ", input_shape, " cannot tile to match ", output_shape);
repeats[axis] = output_dim / input_dim;
diff --git a/ggml/src/ggml-openvino/openvino/op/reshape.cpp b/ggml/src/ggml-openvino/openvino/op/reshape.cpp
index 203d3d396..2f33fdb2c 100644
--- a/ggml/src/ggml-openvino/openvino/op/reshape.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/reshape.cpp
@@ -19,12 +19,21 @@ namespace op {
OutputVector translate_reshape(const NodeContext & context) {
num_inputs_check(context, 1, 1);
- if (context.get_input(0).get_partial_shape().is_static() &&
+ if (context.has_input("vision_shape_" + context.get_name())) {
+ auto target = vision_reshape_target(context);
+ auto res = std::make_shared<ov::op::v1::Reshape>(context.get_input(0), target, false);
+ return rename_outputs_with_suffix({res}, context.get_name());
+ }
+
+ const int op_case = context.get_op_case();
+ // The activations of a MUL_MAT_ID (case 1) are reshaped even with the same ggml shape: in a one-token graph
+ // [n_embd, 1] -> [n_embd, 1, 1] keeps the shape, but the tokens that a static graph pads must still move from dim 1
+ // to dim 2.
+ if (op_case != 1 && context.get_input(0).get_partial_shape().is_static() &&
context.get_input_shape(0) == context.get_output_shape()) {
return {context.get_input(0)};
}
- const int op_case = context.get_op_case();
const auto output_shape = context.get_output_shape().to_shape();
std::vector<int64_t> shape(output_shape.begin(), output_shape.end());
std::shared_ptr<ov::Node> new_shape_node;
diff --git a/ggml/src/ggml-openvino/openvino/op/softmax.cpp b/ggml/src/ggml-openvino/openvino/op/softmax.cpp
index 546987fd7..0c6e935b8 100644
--- a/ggml/src/ggml-openvino/openvino/op/softmax.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/softmax.cpp
@@ -116,6 +116,29 @@ OutputVector translate_soft_max(const NodeContext & context) {
mask = std::make_shared<ov::op::v0::Convert>(mask, logits.get_element_type());
}
+ // ggml repeats the mask over dims 2 and 3 (i02 % ne12, i03 % ne13); numpy broadcasting covers only size 1
+ const auto & mask_pshape = mask.get_partial_shape();
+ const auto & logits_pshape = logits.get_partial_shape();
+ if (mask_pshape.rank().is_static() && mask_pshape.rank().get_length() == 4 &&
+ logits_pshape.rank().is_static() && logits_pshape.rank().get_length() == 4) {
+ std::vector<int64_t> repeats{1, 1, 1, 1};
+ bool need_tile = false;
+ for (size_t i = 0; i < 2; ++i) {
+ if (mask_pshape[i].is_static() && logits_pshape[i].is_static()) {
+ const int64_t m = mask_pshape[i].get_length();
+ const int64_t a = logits_pshape[i].get_length();
+ if (m > 1 && a != m && a % m == 0) {
+ repeats[i] = a / m;
+ need_tile = true;
+ }
+ }
+ }
+ if (need_tile) {
+ mask = std::make_shared<ov::op::v0::Tile>(mask,
+ ov::op::v0::Constant::create(ov::element::i64, {4}, repeats));
+ }
+ }
+
if (max_bias > 0.0f) {
auto out_shape = context.get_output_shape().to_shape();
FRONT_END_CHECK_IMPLEMENTED(out_shape.size() == 4, "OpenVINO softmax ALiBi path expects rank-4 tensor");
diff --git a/ggml/src/ggml-openvino/openvino/op/upscale.cpp b/ggml/src/ggml-openvino/openvino/op/upscale.cpp
index 03f3a91b2..e9050e039 100644
--- a/ggml/src/ggml-openvino/openvino/op/upscale.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/upscale.cpp
@@ -26,7 +26,8 @@ OutputVector translate_upscale(const NodeContext & context) {
const auto input_shape = context.get_input_shape(0).to_shape();
const auto output_shape = context.get_output_shape().to_shape();
- if (input_shape == output_shape) {
+ const bool dynamic = context.has_input("vision_size_" + context.get_name());
+ if (!dynamic && input_shape == output_shape) {
return rename_outputs_with_suffix({input}, context.get_name());
}
@@ -49,7 +50,7 @@ OutputVector translate_upscale(const NodeContext & context) {
}
// Spatial interpolation for ne[1] and ne[0] (OV axes 2 and 3)
- if (input_shape[2] != output_shape[2] || input_shape[3] != output_shape[3]) {
+ if (dynamic || input_shape[2] != output_shape[2] || input_shape[3] != output_shape[3]) {
const int32_t * op_params = context.get_output_op_params();
const int32_t mode_flags = op_params != nullptr ? op_params[0] : 0;
@@ -63,65 +64,17 @@ OutputVector translate_upscale(const NodeContext & context) {
const size_t H_out = output_shape[2];
const size_t W_out = output_shape[3];
- const float pixel_offset = 0.5f;
-
- // Height projection: [H_out, H_in]
- std::vector<float> Wy_data(H_out * H_in, 0.0f);
- const float sf1 = static_cast<float>(H_out) / H_in;
- const float support1 = std::max(1.0f, 1.0f / sf1);
- const float invscale1 = 1.0f / support1;
-
- for (size_t i1 = 0; i1 < H_out; ++i1) {
- const float y = (static_cast<float>(i1) + pixel_offset) / sf1;
- const auto y_start = static_cast<int64_t>(y - support1 + pixel_offset);
- const size_t y_min = y_start > 0 ? static_cast<size_t>(y_start) : 0;
- const auto y_end = static_cast<int64_t>(y + support1 + pixel_offset);
- const size_t y_max = y_end > 0 ? std::min<size_t>(static_cast<size_t>(y_end), H_in) : 0;
-
- float total_weight = 0.0f;
- for (size_t sy = y_min; sy < y_max; ++sy) {
- float diff = std::abs((static_cast<float>(sy) - y + pixel_offset) * invscale1);
- float weight = std::max(1.0f - diff, 0.0f);
- Wy_data[i1 * H_in + sy] = weight;
- total_weight += weight;
- }
- if (total_weight > 0.0f) {
- for (size_t sy = y_min; sy < y_max; ++sy) {
- Wy_data[i1 * H_in + sy] /= total_weight;
- }
- }
+ ov::Output<Node> Wy_node, Wx_node;
+ if (dynamic) {
+ Wy_node = context.get_input("vision_y_" + context.get_name());
+ Wx_node = context.get_input("vision_x_" + context.get_name());
+ } else {
+ Wy_node = ov::op::v0::Constant::create(ov::element::f32, {H_out, H_in},
+ bilinear_antialias_projection(H_in, H_out, false));
+ Wx_node = ov::op::v0::Constant::create(ov::element::f32, {W_in, W_out},
+ bilinear_antialias_projection(W_in, W_out, true));
}
- // Width projection: [W_in, W_out]
- std::vector<float> Wx_data(W_in * W_out, 0.0f);
- const float sf0 = static_cast<float>(W_out) / W_in;
- const float support0 = std::max(1.0f, 1.0f / sf0);
- const float invscale0 = 1.0f / support0;
-
- for (size_t i0 = 0; i0 < W_out; ++i0) {
- const float x = (static_cast<float>(i0) + pixel_offset) / sf0;
- const auto x_start = static_cast<int64_t>(x - support0 + pixel_offset);
- const size_t x_min = x_start > 0 ? static_cast<size_t>(x_start) : 0;
- const auto x_end = static_cast<int64_t>(x + support0 + pixel_offset);
- const size_t x_max = x_end > 0 ? std::min<size_t>(static_cast<size_t>(x_end), W_in) : 0;
-
- float total_weight = 0.0f;
- for (size_t sx = x_min; sx < x_max; ++sx) {
- float diff = std::abs((static_cast<float>(sx) - x + pixel_offset) * invscale0);
- float weight = std::max(1.0f - diff, 0.0f);
- Wx_data[sx * W_out + i0] = weight;
- total_weight += weight;
- }
- if (total_weight > 0.0f) {
- for (size_t sx = x_min; sx < x_max; ++sx) {
- Wx_data[sx * W_out + i0] /= total_weight;
- }
- }
- }
-
- auto Wy_node = ov::op::v0::Constant::create(ov::element::f32, {H_out, H_in}, Wy_data);
- auto Wx_node = ov::op::v0::Constant::create(ov::element::f32, {W_in, W_out}, Wx_data);
-
auto res_y = std::make_shared<ov::op::v0::MatMul>(Wy_node, res);
res = std::make_shared<ov::op::v0::MatMul>(res_y, Wx_node);
} else {
@@ -163,7 +116,8 @@ OutputVector translate_upscale(const NodeContext & context) {
static_cast<float>(output_shape[3]) / static_cast<float>(input_shape[3]),
};
- auto target_shape_node = ov::op::v0::Constant::create(ov::element::i64, {2}, target_shape_vec);
+ ov::Output<Node> target_shape_node = dynamic ? context.get_input("vision_size_" + context.get_name()) :
+ ov::op::v0::Constant::create(ov::element::i64, {2}, target_shape_vec);
auto scales_node = ov::op::v0::Constant::create(ov::element::f32, {2}, scales_vec);
auto axes_node = ov::op::v0::Constant::create(ov::element::i64, {2}, {2, 3});
diff --git a/ggml/src/ggml-openvino/openvino/op/view.cpp b/ggml/src/ggml-openvino/openvino/op/view.cpp
index 4ebe9c4b4..da4097161 100644
--- a/ggml/src/ggml-openvino/openvino/op/view.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/view.cpp
@@ -1,6 +1,7 @@
#include "../op_table.h"
#include "../utils.h"
+#include <openvino/op/add.hpp>
#include <openvino/op/concat.hpp>
#include <openvino/op/constant.hpp>
#include <openvino/op/gather.hpp>
@@ -16,6 +17,17 @@ namespace op {
OutputVector translate_view(const NodeContext & context) {
num_inputs_check(context, 1, 1);
+ if (context.get_op_case() == 5) {
+ const auto shape = context.get_output_shape();
+ // Keep the output gate grouped like GDN: [active sequences, tokens per sequence, heads, width].
+ auto target = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{
+ context.get_input("s_copy_active_slot_len"),
+ ov::op::v0::Constant::create(ov::element::i64, {3},
+ std::vector<int64_t>{-1, shape[2].get_length(), shape[3].get_length()})}, 0);
+ return rename_outputs_with_suffix({std::make_shared<ov::op::v1::Reshape>(context.get_input(0), target, false)},
+ context.get_name());
+ }
+
if (context.get_op_case() == 3) {
auto row = context.get_input("sampling_row_" + context.get_name());
auto selected = std::make_shared<ov::op::v8::Gather>(context.get_input(0), row,
@@ -36,6 +48,17 @@ OutputVector translate_view(const NodeContext & context) {
return rename_outputs_with_suffix({active}, context.get_name());
}
+ if (context.get_op_case() == 6) {
+ // build_rs moved the ubatch states into their cache slots: read that slot block of the cache
+ auto input = context.get_input(0);
+ auto begin = context.get_input("rs_slot_begin_" + context.get_name());
+ auto end = std::make_shared<ov::op::v1::Add>(begin, context.get_input("s_copy_active_slot_len"));
+ auto active = std::make_shared<ov::op::v8::Slice>(
+ input, begin, end, ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {input.get_partial_shape().rank().get_length() - 2}));
+ return rename_outputs_with_suffix({active}, context.get_name());
+ }
+
if (context.get_op_case() == 1) {
// Static-mode identity pass-through for VIEWs over a GATED_DELTA_NET combined output or
// the conv_input CONCAT; the consuming op (CPY/RMS_NORM) does its own runtime-correct
diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h
index 766ca4e6f..37acac0ef 100644
--- a/ggml/src/ggml-openvino/openvino/op_table.h
+++ b/ggml/src/ggml-openvino/openvino/op_table.h
@@ -22,6 +22,7 @@ GGML_OP_CONVERTER(translate_im2col);
GGML_OP_CONVERTER(translate_im2col_3d);
GGML_OP_CONVERTER(translate_mulmat);
GGML_OP_CONVERTER(translate_mul_mat_id);
+GGML_OP_CONVERTER(translate_moe_tiled);
GGML_OP_CONVERTER(translate_permute);
GGML_OP_CONVERTER(translate_reshape);
GGML_OP_CONVERTER(translate_rms_norm);
@@ -54,9 +55,7 @@ GGML_OP_CONVERTER(translate_ssm_scan);
GGML_OP_CONVERTER(translate_gated_delta_net);
// The device runs GatedDeltaNet with a gate per key dimension; otherwise the translator falls back to its reference loop
bool gdn_per_key_gate_supported();
-#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
-OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs);
-#endif
+OutputVector translate_recurrent_gated_delta_net_replay(const NodeContext & context, const OutputVector & banks);
GGML_OP_CONVERTER(translate_repeat);
GGML_OP_CONVERTER(translate_cumsum);
GGML_OP_CONVERTER(translate_set);
diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp
deleted file mode 100644
index a3b56bb5e..000000000
--- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp
+++ /dev/null
@@ -1,313 +0,0 @@
-#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
-# include "recurrent_cache_fusion.h"
-
-# include "../ggml-openvino-extra.h"
-# include "ggml-impl.h"
-# include "op/recurrent_cache_update.hpp"
-# include "op_table.h"
-# include "utils.h"
-
-# include <openvino/op/concat.hpp>
-# include <openvino/op/constant.hpp>
-# include <openvino/op/convert.hpp>
-# include <openvino/op/parameter.hpp>
-# include <openvino/op/reshape.hpp>
-# include <openvino/op/slice.hpp>
-
-namespace ov::frontend::ggml {
-RecurrentCacheFusion::RecurrentCacheFusion(const std::shared_ptr<GgmlDecoder> & decoder,
- const std::shared_ptr<TensorMap> & tensors) :
- m_decoder(decoder),
- m_tensors(tensors) {
- if (!ggml_openvino_is_gpu() || decoder->is_static() || decoder->is_stateful() || decoder->is_splited_model() ||
- ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) {
- return;
- }
- auto actual = std::dynamic_pointer_cast<GgmlOvDecoder>(decoder);
- if (!actual || actual->m_naive || !tensors->count("cache_rs_reset_idx") || !tensors->count("cache_rs_reset_len") ||
- !tensors->count("s_copy_active_slot_len")) {
- return;
- }
- const auto graph = actual->get_cgraph();
- std::map<const ggml_tensor *, int> indices;
- for (int i = 0; i < graph->n_nodes; ++i) {
- indices[graph->nodes[i]] = i;
- }
- for (int i = 0; i < graph->n_nodes; ++i) {
- const auto cp = graph->nodes[i];
- if (cp->op != GGML_OP_CPY || decoder->get_op_case(i) != 3 || !cp->src[0] || cp->src[0]->op != GGML_OP_VIEW ||
- !cp->src[0]->src[0] || cp->src[0]->src[0]->op != GGML_OP_GET_ROWS) {
- continue;
- }
- const auto gather = cp->src[0]->src[0];
- const auto root = cp->view_src;
- if (!root || (root->type != GGML_TYPE_F32 && root->type != GGML_TYPE_F16) || root->ne[2] != 1 ||
- root->ne[3] != 1 || gather->src[0]->op != GGML_OP_RESHAPE || gather->src[0]->src[0] != root ||
- gather->src[1]->op != GGML_OP_NONE || gather->src[1]->type != GGML_TYPE_I32) {
- continue;
- }
- Group group;
- group.gather = indices.at(gather);
- group.remainder = i;
- for (int j = 0; j < group.gather; ++j) {
- const auto node = graph->nodes[j];
- if (GgmlOvDecoder::is_recurrent_cache_reset(node) &&
- node->view_src == root && decoder->get_op_case(j) == 1) {
- // SCALE stores (scale, bias); FILL stores its value first and leaves the second parameter 0.
- float scale, bias;
- memcpy(&scale, node->op_params, sizeof(float));
- memcpy(&bias, node->op_params + 1, sizeof(float));
- if (scale == 0 && bias == 0) {
- group.reset = j;
- }
- }
- }
- if (group.reset < 0) {
- continue;
- }
- // build_conv_state_store emits one CPY without rollback or one SET_ROWS with rollback.
- for (int j = i + 1; j < graph->n_nodes; ++j) {
- const auto node = graph->nodes[j];
- if (node->op != GGML_OP_CONCAT || node->op_params[0] != 0 || !node->src[0] ||
- node->src[0]->op != GGML_OP_RESHAPE) {
- continue;
- }
- const auto active = node->src[0]->src[0];
- if (active && active->op == GGML_OP_VIEW && active->src[0] == gather && active->view_offs == 0 &&
- node->src[0]->ne[3] == 1 && node->src[0]->ne[0] * node->src[0]->ne[1] == root->ne[0]) {
- group.concat = j;
- for (int k = j + 1; k < graph->n_nodes; ++k) {
- const auto write = graph->nodes[k];
- const bool copy = GgmlOvDecoder::is_conv_state_writeback(write);
- const bool slots = GgmlOvDecoder::is_conv_state_snapshot_writeback(write);
- if ((copy || slots) && write->view_src == root && write->src[0]->src[0] == node &&
- write->src[0]->ne[0] == node->src[0]->ne[0] &&
- write->src[0]->ne[slots ? 2 : 1] == node->src[0]->ne[1] &&
- (slots ? write->src[2] : write->src[1])->view_offs % root->nb[1] == 0) {
- if (group.writeback >= 0) {
- group.writeback = -1;
- break;
- }
- group.writeback = k;
- }
- }
- break;
- }
- }
- if (group.concat >= 0) {
- if (group.writeback < 0) {
- continue;
- }
- for (int j = group.concat + 1; j < graph->n_nodes; ++j) {
- const auto node = graph->nodes[j];
- if (node->op == GGML_OP_SSM_CONV && node->src[0] == graph->nodes[group.concat] && node->src[1] &&
- node->src[1]->op == GGML_OP_NONE &&
- node->src[1]->ne[0] == graph->nodes[group.concat]->src[0]->ne[0] + 1 &&
- node->src[1]->ne[1] == graph->nodes[group.concat]->src[0]->ne[1] && node->src[1]->ne[2] == 1 &&
- node->src[1]->ne[3] == 1) {
- if (group.compute >= 0) {
- group.compute = -1;
- break;
- }
- group.compute = j;
- }
- }
- } else {
- for (int j = i + 1; j < graph->n_nodes; ++j) {
- const auto node = graph->nodes[j];
- if (node->op != GGML_OP_GATED_DELTA_NET || !node->src[5] || node->src[5]->op != GGML_OP_RESHAPE) {
- continue;
- }
- const auto active = node->src[5]->src[0];
- if (!active || active->op != GGML_OP_VIEW || active->src[0] != gather || active->view_offs != 0 ||
- node->src[5]->ne[0] * node->src[5]->ne[1] * node->src[5]->ne[2] != root->ne[0] ||
- decoder->get_output_names(j).size() < 2) {
- continue;
- }
- group.compute = j;
- for (int k = j + 1; k < graph->n_nodes; ++k) {
- const auto write = graph->nodes[k];
- if (write->op == GGML_OP_CPY && write->view_src == root && write->src[0] &&
- write->src[0]->op == GGML_OP_VIEW && write->src[0]->src[0] == node &&
- (decoder->get_op_case(k) == 10 || decoder->get_op_case(k) == 12)) {
- if (group.writeback >= 0) {
- group.writeback = -1;
- break;
- }
- group.writeback = k;
- }
- }
- break;
- }
- if (group.writeback < 0 || !tensors->count("rs_update_" + decoder->get_op_name(group.writeback))) {
- continue;
- }
- }
- if (group.compute < 0) {
- continue;
- }
- bool complete = tensors->count("rs_slot_begin_" + decoder->get_op_name(i)) &&
- tensors->count("rs_src_begin_" + decoder->get_op_name(i));
- if (group.concat >= 0) {
- complete &= tensors->count("rs_windows_" + decoder->get_op_name(group.concat));
- const auto & name = decoder->get_op_name(group.writeback);
- complete &= tensors->count("rs_slot_begin_" + name) && tensors->count("rs_src_begin_" + name);
- }
- for (int j = 0; j < graph->n_nodes && complete; ++j) {
- const auto node = graph->nodes[j];
- // Other cache readers or writers require functional translation.
- for (int source = 0; source < GGML_MAX_SRC; ++source) {
- const auto input = node->src[source];
- if (!input || (input != root && input->view_src != root)) {
- continue;
- }
- const bool alias = node->op == GGML_OP_VIEW || node->op == GGML_OP_RESHAPE;
- const bool matched_read = j == group.gather || j == group.reset;
- const bool destination = (node->op == GGML_OP_CPY && source == 1) ||
- (GgmlOvDecoder::is_conv_state_snapshot_writeback(node) && source == 2);
- if (!alias && !matched_read && !destination) {
- complete = false;
- }
- }
- if (node->view_src == root &&
- (node->op == GGML_OP_SCALE || node->op == GGML_OP_CPY || node->op == GGML_OP_SET_ROWS) &&
- j != group.reset && j != group.remainder && j != group.writeback) {
- complete = false;
- }
- }
- // Every read of the gathered state or convolution input must belong to
- // this recurrence. Shared readers retain the ordinary GGML translation.
- const auto compute = graph->nodes[group.compute];
- const auto active = group.concat >= 0 ? graph->nodes[group.concat]->src[0]->src[0] : compute->src[5]->src[0];
- const auto reshaped = group.concat >= 0 ? graph->nodes[group.concat]->src[0] : compute->src[5];
- for (int j = group.gather + 1; j < graph->n_nodes && complete; ++j) {
- const auto node = graph->nodes[j];
- for (int source = 0; source < GGML_MAX_SRC; ++source) {
- const auto input = node->src[source];
- if (!input) {
- continue;
- }
- if (input == gather && node != active && node != graph->nodes[group.remainder]->src[0]) {
- complete = false;
- }
- if (input == active && node != reshaped) {
- complete = false;
- }
- if (input == reshaped && node != (group.concat >= 0 ? graph->nodes[group.concat] : compute)) {
- complete = false;
- }
- if (group.concat >= 0 && input == graph->nodes[group.concat] && node != compute) {
- complete &= node == graph->nodes[group.writeback]->src[0];
- }
- if (input == compute && group.concat < 0 && node->op != GGML_OP_VIEW) {
- complete = false;
- }
- if (group.concat < 0 && input == graph->nodes[group.writeback]->src[0] &&
- node != graph->nodes[group.writeback]) {
- complete = false;
- }
- }
- }
- if (!complete) {
- continue;
- }
- group.root_name = GgmlOvDecoder::get_tensor_name(graph, root);
- const auto id = m_groups.size();
- for (int n : {group.reset, group.gather, group.remainder}) {
- m_nodes[n] = id;
- }
- if (group.concat >= 0) {
- m_nodes[group.concat] = id;
- }
- m_nodes[group.compute] = id;
- if (group.writeback >= 0) {
- m_nodes[group.writeback] = id;
- }
- m_groups.push_back(std::move(group));
- }
-}
-
-OutputVector RecurrentCacheFusion::translate(int index, const NodeContext & context) {
- const auto it = m_nodes.find(index);
- if (it == m_nodes.end()) {
- return {};
- }
- auto & group = m_groups[it->second];
- using namespace ov::op;
- auto constant = [](std::initializer_list<size_t> shape, std::initializer_list<int64_t> values) {
- return v0::Constant::create(element::i64, Shape(shape), std::vector<int64_t>(values));
- };
- auto metadata = [&](const std::string & name) -> Output<Node> {
- return std::make_shared<v1::Reshape>(context.get_input(name), constant({4}, {1, 1, 1, 1}), false);
- };
- if (index == group.reset) {
- group.old_cache = context.get_input(0);
- auto root = group.old_cache.get_node_shared_ptr();
- while (ov::is_type<v1::Reshape>(root)) {
- root = root->input_value(0).get_node_shared_ptr();
- }
- group.enabled = ov::is_type<v0::Parameter>(root);
- if (!group.enabled) {
- return {};
- }
- return {group.old_cache};
- }
- if (!group.enabled) {
- return {};
- }
- NodeContext gather_context(m_decoder, m_tensors, group.gather);
- auto rows = process_view_input_new(gather_context, 1);
- const auto remainder_name = m_decoder->get_op_name(group.remainder);
- auto offsets = std::make_shared<v0::Concat>(OutputVector{context.get_input("rs_slot_begin_" + remainder_name),
- context.get_input("rs_src_begin_" + remainder_name)},
- 0);
- OutputVector inputs{group.old_cache,
- rows,
- rows,
- metadata("cache_rs_reset_idx"),
- metadata("cache_rs_reset_len"),
- context.has_input("rs_offsets_" + remainder_name) ?
- context.get_input("rs_offsets_" + remainder_name) :
- std::make_shared<v1::Reshape>(offsets, constant({4}, {1, 1, 1, 2}), false)};
- inputs[1] = context.has_input("rs_active_rows") ?
- context.get_input("rs_active_rows") :
- std::make_shared<v8::Slice>(rows, constant({1}, {0}), context.get_input("s_copy_active_slot_len"),
- constant({1}, {1}), constant({1}, {3}));
- if (index == group.gather) {
- // Ordinary nodes keep intermediate translation shapes valid. They become
- // unreachable once the complete recurrence is replaced by its fused op.
- return op::translate_get_rows(context);
- }
- if (index == group.remainder) {
- return {group.old_cache};
- }
- if (index == group.concat) {
- inputs.push_back(process_view_input_new(context, 1));
- // Runtime pairs [source column, destination slot] cover the current CPY or SET_ROWS store.
- inputs.push_back(context.get_input("rs_windows_" + context.get_name()));
- const auto history = context.get_input_shape(0)[3].get_length();
- NodeContext compute_context(m_decoder, m_tensors, group.compute);
- const auto channels = context.get_input_shape(0)[2].get_length();
- inputs.push_back(std::make_shared<v1::Reshape>(compute_context.get_input(1),
- constant({4}, {1, 1, channels, history + 1}), false));
- auto fused = std::make_shared<internal::RecurrentConvCacheUpdate>(inputs, history);
- fused->set_friendly_name(compute_context.get_name() + "/RecurrentConvCacheUpdate");
- group.conv = fused->output(0);
- return op::translate_concat(context);
- }
- if (index == group.compute) {
- if (group.concat >= 0) {
- return {group.conv};
- }
- inputs.push_back(context.get_input("rs_update_" + m_decoder->get_op_name(group.writeback)));
- return op::translate_recurrent_gated_delta_net(context, inputs);
- }
- return {group.old_cache};
-}
-
-bool RecurrentCacheFusion::is_inplace_output(const std::string & name) const {
- return std::any_of(m_groups.begin(), m_groups.end(),
- [&](const Group & group) { return group.enabled && group.root_name == name; });
-}
-} // namespace ov::frontend::ggml
-#endif
diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h
deleted file mode 100644
index 1d9d494ac..000000000
--- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h
+++ /dev/null
@@ -1,26 +0,0 @@
-#pragma once
-#include "../ggml-decoder.h"
-#include "node_context.h"
-
-namespace ov::frontend::ggml {
-// Match complete build_rs groups before replacing reset/reorder. Unmatched graphs retain
-// their ordinary translators, including CPU, static and released-runtime execution.
-class RecurrentCacheFusion {
-public:
- RecurrentCacheFusion(const std::shared_ptr<GgmlDecoder> & decoder, const std::shared_ptr<TensorMap> & tensors);
- OutputVector translate(int index, const NodeContext & context);
- bool is_inplace_output(const std::string & name) const;
-private:
- struct Group {
- int reset = -1, gather = -1, remainder = -1, concat = -1, compute = -1, writeback = -1;
- std::string root_name;
- bool enabled = false;
- Output<Node> old_cache, conv;
- };
-
- std::shared_ptr<GgmlDecoder> m_decoder;
- std::shared_ptr<TensorMap> m_tensors;
- std::vector<Group> m_groups;
- std::map<int, size_t> m_nodes;
-};
-} // namespace ov::frontend::ggml
diff --git a/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.cpp b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.cpp
new file mode 100644
index 000000000..e387e1c77
--- /dev/null
+++ b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.cpp
@@ -0,0 +1,217 @@
+#include "recurrent_replay_fusion.h"
+
+#include "../ggml-openvino-extra.h"
+#include "ggml-impl.h"
+#include "op/recurrent_replay_graph.hpp"
+#include "op_table.h"
+#include "utils.h"
+
+#include <openvino/op/constant.hpp>
+#include <openvino/op/parameter.hpp>
+#include <openvino/op/reshape.hpp>
+
+namespace ov::frontend::ggml {
+namespace {
+const ggml_tensor * cache_root(const ggml_tensor * node) {
+ while (node && (node->op == GGML_OP_VIEW || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_GET_ROWS)) {
+ node = node->src[0];
+ }
+ return node && node->op == GGML_OP_NONE && GgmlOvDecoder::is_recurrent_cache(node) ? node : nullptr;
+}
+} // namespace
+
+RecurrentReplayFusion::RecurrentReplayFusion(const std::shared_ptr<GgmlDecoder> & decoder,
+ const std::shared_ptr<TensorMap> & tensors) :
+ m_decoder(decoder),
+ m_tensors(tensors) {
+ auto actual = std::dynamic_pointer_cast<GgmlOvDecoder>(decoder);
+ if (!actual || actual->m_naive || decoder->is_static() || decoder->is_stateful() || decoder->is_splited_model() ||
+ !ggml_openvino_is_gpu() || ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE") ||
+ !tensors->count("rs_replay_rows")) {
+ return;
+ }
+ m_graph = actual->get_cgraph();
+ for (int i = 0; i < m_graph->n_nodes; ++i) {
+ const auto node = m_graph->nodes[i];
+ Group group;
+ group.compute = i;
+ if (node->op == GGML_OP_GATED_DELTA_NET && node->op_params[1] > 0) {
+ for (int port : {5, 6, 7, 8}) {
+ group.banks.push_back(cache_root(node->src[port]));
+ }
+ } else if (node->op == GGML_OP_SSM_CONV && node->src[0]->op == GGML_OP_CONT &&
+ node->src[0]->src[0]->op == GGML_OP_TRANSPOSE) {
+ const auto cols = node->src[0]->src[0]->src[0];
+ if (cols->op != GGML_OP_CONCAT || cols->op_params[0] != 1 || cols->src[0]->op != GGML_OP_GET_ROWS) {
+ continue;
+ }
+ group.conv = true;
+ group.current = cols->src[1];
+ group.banks.push_back(cache_root(cols->src[0]->src[0]));
+ } else {
+ continue;
+ }
+ if (std::any_of(group.banks.begin(), group.banks.end(), [](const ggml_tensor * bank) {
+ return !bank || bank->type != GGML_TYPE_F32 || bank->ne[2] != 1 || bank->ne[3] != 1;
+ })) {
+ continue;
+ }
+ auto is_bank = [&](const ggml_tensor * t) {
+ return std::find(group.banks.begin(), group.banks.end(), t) != group.banks.end();
+ };
+ // Collect only cache-owned paths. Current-token producers remain outside this group.
+ std::function<void(const ggml_tensor *)> collect = [&](const ggml_tensor * t) {
+ if (!t || t->op == GGML_OP_NONE || t == group.current || is_bank(t) || !group.consumed.insert(t).second) {
+ return;
+ }
+ for (int port = 0; port < (t->op == GGML_OP_GET_ROWS ? 1 : GGML_MAX_SRC); ++port) {
+ if (t->src[port]) {
+ collect(t->src[port]);
+ }
+ }
+ };
+ if (group.conv) {
+ collect(node->src[0]);
+ } else {
+ for (int port : {5, 6, 7, 8}) {
+ collect(node->src[port]);
+ }
+ }
+ std::map<const ggml_tensor *, int> resets, writes;
+ for (int j = 0; j < m_graph->n_nodes; ++j) {
+ const auto t = m_graph->nodes[j];
+ if (!is_bank(t->view_src)) {
+ continue;
+ }
+ if (GgmlOvDecoder::is_recurrent_cache_reset(t)) {
+ float value;
+ memcpy(&value, t->op_params, sizeof(value));
+ if (value != 0) {
+ continue;
+ }
+ ++resets[t->view_src];
+ collect(t);
+ } else if (t->op == GGML_OP_CPY) {
+ const auto src = t->src[0];
+ const bool extra =
+ src->op == GGML_OP_VIEW && src->src[0]->op == GGML_OP_GET_ROWS && cache_root(src) == t->view_src;
+ bool update = false;
+ if (group.conv) {
+ update = src->op == GGML_OP_VIEW && src->src[0] == node->src[0]->src[0]->src[0];
+ } else {
+ update = src->op == GGML_OP_VIEW && src->src[0] == node;
+ for (int port : {1, 2, 3, 4}) {
+ update |= src->op == GGML_OP_VIEW && src->src[0] == node->src[port];
+ }
+ }
+ if (!extra && !update) {
+ continue;
+ }
+ if (update) {
+ ++writes[t->view_src];
+ }
+ group.consumed.insert(t);
+ collect(t->src[1]);
+ group.consumed.insert(src);
+ if (extra) {
+ collect(src);
+ }
+ }
+ }
+ bool complete = true;
+ for (const auto bank : group.banks) {
+ complete &= resets[bank] == 1 && writes[bank] == (bank == group.banks.back() && !group.conv ? 2 : 1);
+ }
+ group.consumed.insert(node);
+ // A bank reader or writer outside this group would race with the implicit stores.
+ for (int j = 0; j < m_graph->n_nodes && complete; ++j) {
+ const auto t = m_graph->nodes[j];
+ if (group.consumed.count(t)) {
+ continue;
+ }
+ if (is_bank(t->view_src) && t->op != GGML_OP_VIEW && t->op != GGML_OP_RESHAPE) {
+ complete = false;
+ }
+ for (int port = 0; port < GGML_MAX_SRC; ++port) {
+ const auto src = t->src[port];
+ if (!src || is_bank(src) == false) {
+ continue;
+ }
+ if (t->op != GGML_OP_VIEW && t->op != GGML_OP_RESHAPE) {
+ complete = false;
+ }
+ }
+ }
+ if (!complete) {
+ continue;
+ }
+ const auto id = m_groups.size();
+ for (int j = 0; j < m_graph->n_nodes; ++j) {
+ if (group.consumed.count(m_graph->nodes[j])) {
+ m_nodes[j] = id;
+ }
+ }
+ m_groups.push_back(std::move(group));
+ }
+ if (ggml_openvino_getenv_int("GGML_OPENVINO_DUMP_CGRAPH")) {
+ const auto conv =
+ std::count_if(m_groups.begin(), m_groups.end(), [](const Group & group) { return group.conv; });
+ GGML_LOG_INFO("ggml-openvino: replay fusion: %zu convolution, %zu GDN groups\n", size_t(conv),
+ m_groups.size() - conv);
+ }
+}
+
+OutputVector RecurrentReplayFusion::translate(int index, const NodeContext & context) {
+ const auto found = m_nodes.find(index);
+ if (found == m_nodes.end()) {
+ return {};
+ }
+ const auto & group = m_groups[found->second];
+ using namespace ov::op;
+ auto bank_input = [&](const ggml_tensor * t) -> Output<Node> {
+ const auto name = GgmlOvDecoder::get_tensor_name(m_graph, t);
+ const auto found = m_tensors->find(name);
+ FRONT_END_OP_CONVERSION_CHECK(found != m_tensors->end(), "Replay input missing: ", name, " while translating ",
+ context.get_name());
+ return found->second;
+ };
+ if (index != group.compute) {
+ const auto node = m_graph->nodes[index];
+ auto root = cache_root(node);
+ if (!root && node->view_src &&
+ std::find(group.banks.begin(), group.banks.end(), node->view_src) != group.banks.end()) {
+ root = node->view_src;
+ }
+ return OutputVector(context.get_output_names().size(), bank_input(root ? root : group.banks[0]));
+ }
+ OutputVector banks;
+ for (const auto bank : group.banks) {
+ auto input = bank_input(bank);
+ auto source = input.get_node_shared_ptr();
+ while (ov::is_type<v1::Reshape>(source)) {
+ source = source->input_value(0).get_node_shared_ptr();
+ }
+ FRONT_END_OP_CONVERSION_CHECK(ov::is_type<v0::Parameter>(source),
+ "Replay banks require writable Parameter storage");
+ banks.push_back(input);
+ }
+ auto rows = context.get_input("rs_replay_rows"), control = context.get_input("rs_replay_control"),
+ reset = context.get_input("rs_replay_reset");
+ if (group.conv) {
+ auto x = bank_input(group.current);
+ const auto history = m_graph->nodes[index]->src[1]->ne[0] - 1;
+ auto pattern =
+ v0::Constant::create(element::i64, Shape{4}, std::vector<int64_t>{1, 1, group.current->ne[0], history + 1});
+ auto weights = std::make_shared<v1::Reshape>(context.get_input(1), pattern, false);
+ auto replay = ov::recurrent_replay::build({banks[0], rows, x, weights, control, reset}, true);
+ m_updated_banks[GgmlOvDecoder::get_tensor_name(m_graph, group.banks[0])] = replay[1];
+ return {replay[0]};
+ }
+ auto outputs = op::translate_recurrent_gated_delta_net_replay(
+ context, {banks[0], banks[1], banks[2], banks[3], rows, control, reset});
+ for (size_t i = 0; i < group.banks.size(); ++i) {
+ m_updated_banks[GgmlOvDecoder::get_tensor_name(m_graph, group.banks[i])] = outputs[i + 1];
+ }
+ return {outputs[0], outputs[1]};
+}
+} // namespace ov::frontend::ggml
diff --git a/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h
new file mode 100644
index 000000000..d02e9049c
--- /dev/null
+++ b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h
@@ -0,0 +1,34 @@
+#pragma once
+#include "../ggml-decoder.h"
+#include "node_context.h"
+
+#include <set>
+#include <string_view>
+
+namespace ov::frontend::ggml {
+// Assign variables with this prefix opt a caller-owned remote bank into writable-input fusion.
+inline constexpr std::string_view replay_cache_state_prefix = "__ggml_replay_cache_";
+
+class RecurrentReplayFusion {
+public:
+ RecurrentReplayFusion(const std::shared_ptr<GgmlDecoder> &, const std::shared_ptr<TensorMap> &);
+ OutputVector translate(int index, const NodeContext & context);
+
+ const std::map<std::string, Output<Node>> & updated_banks() const { return m_updated_banks; }
+private:
+ struct Group {
+ int compute = -1;
+ bool conv = false;
+ const ggml_tensor * current = nullptr;
+ std::vector<const ggml_tensor *> banks;
+ std::set<const ggml_tensor *> consumed;
+ };
+
+ std::shared_ptr<GgmlDecoder> m_decoder;
+ std::shared_ptr<TensorMap> m_tensors;
+ const ggml_cgraph * m_graph = nullptr;
+ std::vector<Group> m_groups;
+ std::map<int, size_t> m_nodes;
+ std::map<std::string, Output<Node>> m_updated_banks;
+};
+} // namespace ov::frontend::ggml
diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp
index 1c43c8ae0..5c5a6a8bd 100644
--- a/ggml/src/ggml-openvino/openvino/translate_session.cpp
+++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp
@@ -5,9 +5,7 @@
#include "ggml-openvino/openvino/node_context.h"
#include "ggml-openvino/openvino/utils.h"
#include "input_model.h"
-#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
-#include "recurrent_cache_fusion.h"
-#endif
+#include "recurrent_replay_fusion.h"
#include "pass/mark_decompression_convert_constant_folding.h"
#include "pass/mark_dequantization_subgraph.h"
#include "pass_registry/pipeline.h"
@@ -24,6 +22,7 @@
#include <openvino/core/type.hpp>
#include <openvino/core/type/element_type.hpp>
#include <openvino/op/add.hpp>
+#include <openvino/op/assign.hpp>
#include <openvino/op/broadcast.hpp>
#include <openvino/op/concat.hpp>
#include <openvino/op/constant.hpp>
@@ -74,11 +73,8 @@ std::shared_ptr<ov::op::v0::Parameter> create_parameter(const std::string & name
std::shared_ptr<ov::Node> create_extra_input(const std::string & name, const ModelExtraInputInfo & input_info) {
if (input_info.is_parameter) {
- ov::PartialShape shape(input_info.shape);
- // One SET_ROWS emits min(tokens, snapshot capacity) windows on each batch.
- if (name.compare(0, 11, "rs_windows_") == 0) {
- shape[2] = ov::Dimension::dynamic();
- }
+ const auto shape = input_info.parameter_shape.rank().is_static() ? input_info.parameter_shape :
+ ov::PartialShape(input_info.shape);
auto param_node = std::make_shared<ov::op::v0::Parameter>(input_info.type, shape);
param_node->set_friendly_name(name);
param_node->output(0).get_tensor().set_names({name});
@@ -302,9 +298,7 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
}
}
-#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
- RecurrentCacheFusion recurrent_fusion(ggml_model_decoder, tensor_map);
-#endif
+ RecurrentReplayFusion replay_fusion(ggml_model_decoder, tensor_map);
auto translate_node = [&](const std::shared_ptr<GgmlDecoder> & decoder, int node_idx) {
auto operation_type = decoder->get_op_type(node_idx);
if (operation_type == "GGML_OP_NONE") {
@@ -325,10 +319,7 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
FRONT_END_OP_CONVERSION_CHECK(it != m_translator_map.end(), "Translation for operation type ", operation_type,
" is not implemented.");
NodeContext node_context(decoder, tensor_map, node_idx);
- ov::OutputVector converted_outputs;
-#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
- converted_outputs = recurrent_fusion.translate(node_idx, node_context);
-#endif
+ auto converted_outputs = replay_fusion.translate(node_idx, node_context);
if (converted_outputs.empty()) {
converted_outputs = it->second(node_context);
}
@@ -390,15 +381,24 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
}
ggml_model_decoder->visit_subgraph(node_visitor);
+ ov::SinkVector sinks;
+ const auto actual_decoder = std::dynamic_pointer_cast<GgmlOvDecoder>(ggml_model_decoder);
+ for (const auto & updated : replay_fusion.updated_banks()) (*tensor_map)[updated.first] = updated.second;
for (const auto & name : ggml_model_decoder->get_model_output_names()) {
-#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
- if (recurrent_fusion.is_inplace_output(name)) {
- // The fused kernel updates the bound cache input; no cache Result is needed.
- continue;
- }
-#endif
FRONT_END_GENERAL_CHECK(tensor_map->find(name) != tensor_map->end(),
"Output name not found in tensor map: ", name);
+ if (const auto bank = replay_fusion.updated_banks().find(name);
+ bank != replay_fusion.updated_banks().end() && actual_decoder &&
+ ggml_openvino_buffer_is_remote(actual_decoder->get_model_outputs().at(name))) {
+ const auto & update = bank->second;
+ // Let the Assign input determine the state type. GPU precision conversion can rewrite
+ // declared variable types even when the precision-sensitive input stays in FP32.
+ auto variable = std::make_shared<ov::op::util::Variable>(ov::op::util::VariableInfo{
+ update.get_partial_shape(), element::dynamic, std::string(replay_cache_state_prefix) + name});
+ auto assign = std::make_shared<v6::Assign>(update, variable);
+ sinks.push_back(assign);
+ continue;
+ }
auto result = std::make_shared<v0::Result>(tensor_map->at(name));
result->set_friendly_name(name);
results.push_back(result);
@@ -450,7 +450,7 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
used_params.push_back(param);
}
}
- resulting_model = std::make_shared<Model>(results, used_params);
+ resulting_model = std::make_shared<Model>(results, sinks, used_params);
apply_transformations(resulting_model);
diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp
index 0a5d5b8c0..25377fc3a 100644
--- a/ggml/src/ggml-openvino/openvino/utils.cpp
+++ b/ggml/src/ggml-openvino/openvino/utils.cpp
@@ -38,6 +38,48 @@ namespace ov {
namespace frontend {
namespace ggml {
+ov::Output<Node> vision_reshape_target(const NodeContext & context) {
+ auto runtime = context.get_input("vision_shape_" + context.get_name());
+ const auto pattern = context.get_vision_reshape_pattern();
+ ov::OutputVector dimensions;
+ for (size_t axis = 0; axis < pattern.size(); ++axis) {
+ if (pattern[axis] == -2) {
+ dimensions.push_back(std::make_shared<ov::op::v8::Gather>(runtime,
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(axis)}),
+ ov::op::v0::Constant::create(ov::element::i64, {}, {0})));
+ } else {
+ dimensions.push_back(ov::op::v0::Constant::create(ov::element::i64, {1}, {pattern[axis]}));
+ }
+ }
+ return std::make_shared<ov::op::v0::Concat>(dimensions, 0);
+}
+
+std::vector<float> bilinear_antialias_projection(size_t input_size, size_t output_size, bool transpose) {
+ std::vector<float> weights(input_size * output_size, 0.0f);
+ const float scale = static_cast<float>(output_size) / input_size;
+ const float support = std::max(1.0f, 1.0f / scale);
+ const float invscale = 1.0f / support;
+ for (size_t out = 0; out < output_size; ++out) {
+ const float center = (static_cast<float>(out) + 0.5f) / scale;
+ const auto start = static_cast<int64_t>(center - support + 0.5f);
+ const auto end = static_cast<int64_t>(center + support + 0.5f);
+ const size_t begin = start > 0 ? static_cast<size_t>(start) : 0;
+ const size_t finish = end > 0 ? std::min<size_t>(end, input_size) : 0;
+ float sum = 0.0f;
+ for (size_t in = begin; in < finish; ++in) {
+ const float weight = std::max(1.0f - std::abs((static_cast<float>(in) - center + 0.5f) * invscale), 0.0f);
+ weights[transpose ? in * output_size + out : out * input_size + in] = weight;
+ sum += weight;
+ }
+ if (sum > 0.0f) {
+ for (size_t in = begin; in < finish; ++in) {
+ weights[transpose ? in * output_size + out : out * input_size + in] /= sum;
+ }
+ }
+ }
+ return weights;
+}
+
void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max_inputs) {
auto input_size = context.get_input_size();
FRONT_END_OP_CONVERSION_CHECK(input_size >= min_inputs, "Got less inputs than expected");
@@ -558,9 +600,22 @@ ov::Output<ov::Node> process_view_input_new(const NodeContext & context, int inp
return std::make_shared<ov::op::v1::Reshape>(part, target, false);
}
+ // A translated VIEW is authoritative; packed-projection slicing applies only to its unresolved base.
+ const auto view_name = context.get_view_input_name(input_index, 0);
+ const auto base_name = context.get_view_input_src_name(input_index, view_input_size - 1);
+ if (context.has_input(view_name) &&
+ (!context.has_input(base_name) || context.get_input(view_name) != context.get_input(base_name))) {
+ return input;
+ }
+
+ // The two head splits below read the view's dim 1 as heads. With one token, a plain column split (LFM2's
+ // [n, n_tokens] of [3n, n_tokens]) has the same shapes and strides, so they apply only when dim 1 is not the
+ // token dim.
+ const bool head_split = context.get_view_input_dynamic_dim(input_index, 0) != 1;
+
// Integer router views can share these strides when their row count is zero.
// Packed projections can store query and gate in separate halves of each head.
- if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real()) {
+ if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real() && head_split) {
const auto source = context.get_view_input_src_ggml_shape(input_index, 0);
const auto view = context.get_view_input_ggml_shape(input_index, 0);
const auto source_stride = context.get_view_input_src_stride(input_index, 0);
@@ -591,13 +646,13 @@ ov::Output<ov::Node> process_view_input_new(const NodeContext & context, int inp
}
}
- if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real() &&
- context.has_input("s_copy_active_slot_len")) {
+ if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real() && head_split) {
const auto source = context.get_view_input_src_ggml_shape(input_index, 0);
const auto view = context.get_view_input_ggml_shape(input_index, 0);
const auto source_stride = context.get_view_input_src_stride(input_index, 0);
const auto view_stride = context.get_view_input_stride(input_index, 0);
if (source.size() == 4 && view.size() == 4 && source_stride.size() == 4 && view_stride.size() == 4 &&
+ input.get_partial_shape().rank().is_static() && input.get_partial_shape().rank().get_length() == 4 &&
source[0] == 1 && view[0] == source[1] && view[1] == source[2] && view[3] > 0 &&
view[2] <= source[3] / view[3] &&
view_stride[0] == source_stride[1] && view_stride[1] == source_stride[2] &&
diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h
index 499596e6f..194f08be5 100644
--- a/ggml/src/ggml-openvino/openvino/utils.h
+++ b/ggml/src/ggml-openvino/openvino/utils.h
@@ -21,6 +21,9 @@ std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node> & node,
OutputVector rename_outputs_with_suffix(const OutputVector & outputs, const std::string & suffix);
+std::vector<float> bilinear_antialias_projection(size_t input_size, size_t output_size, bool transpose);
+ov::Output<Node> vision_reshape_target(const NodeContext & context);
+
std::pair<ov::Output<Node>, ov::Output<Node>> make_sin_cos(int32_t * rope_params,
std::shared_ptr<ov::Node> inp_pos,
std::shared_ptr<ov::Node> rope_freqs_weight = nullptr,
diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp
index 29f7f4041..fdc212178 100644
--- a/ggml/src/ggml-openvino/utils.cpp
+++ b/ggml/src/ggml-openvino/utils.cpp
@@ -10,6 +10,7 @@
#include "model-cache.h"
#include "openvino/frontend.h"
#include "openvino/input_model.h"
+#include "openvino/recurrent_replay_fusion.h"
#include <algorithm>
#include <atomic>
@@ -22,6 +23,7 @@
#include <functional>
#include <iomanip>
#include <iostream>
+#include <limits>
#include <memory>
#include <openvino/core/any.hpp>
#include <openvino/core/graph_util.hpp>
@@ -216,15 +218,11 @@ static size_t get_static_attention_size(const std::shared_ptr<GgmlOvDecoder> & g
static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurrent) {
const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled();
- uint64_t extra_cfg = 15; // Recurrent caches are writable inputs without cache Results.
-#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
- extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE") ? 0u : 1u);
-#else
- extra_cfg = extra_cfg * 131;
-#endif
+ // Vision graphs carry runtime spatial shapes and independent position inputs.
+ uint64_t extra_cfg = 19 * 131;
extra_cfg = extra_cfg * 131 + (stateful ? (recurrent ? 2u : 1u) : 0u);
extra_cfg = extra_cfg * 131 + (ggml_openvino_reduce_compile_mem_enabled() ? 1u : 0u);
- extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_KV_4D") > 0 ? 1u : 0u);
+ extra_cfg = extra_cfg * 131 + (ggml_openvino_kv_4d_enabled() ? 1u : 0u);
extra_cfg = extra_cfg * 131 + (manual_gqa_enabled ? 1u : 0u);
extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") >= 2 ? 1u : 0u);
extra_cfg = extra_cfg * 131 + (ggml_openvino_shape_from_mask_enabled() ? 1u : 0u);
@@ -311,9 +309,11 @@ static std::string compiled_graph_key(const ggml_cgraph * graph,
for (const auto & input : decoder.get_model_extra_inputs()) {
append_string(input.first);
append_string(input.second.type.get_type_name());
- append(input.second.shape.size());
- for (auto dim : input.second.shape) {
- append(dim);
+ if (input.second.parameter_shape.rank().is_static()) {
+ append_string(input.second.parameter_shape.to_string());
+ } else {
+ append(input.second.shape.size());
+ for (auto dim : input.second.shape) { append(dim); }
}
append(input.second.is_parameter);
if (!input.second.is_parameter) {
@@ -338,7 +338,7 @@ static std::string dynamic_graph_signature(const ggml_cgraph * graph,
append(value.size());
key.append(value);
};
- graph_key graph_id(graph, true);
+ graph_key graph_id(graph, true, params.is_dynamic_vision);
append(graph_id.n_nodes);
append(graph_id.n_leaves);
append_string(graph_id.first_node_name);
@@ -348,6 +348,9 @@ static std::string dynamic_graph_signature(const ggml_cgraph * graph,
}
append(params.n_rs_slots);
append(params.has_rs_rollback);
+ // A model converted from a one-token graph with one KV head cannot run more tokens (can_run_tokens()). The
+ // signature has no shapes, so the flag keeps its blob apart from the model converted again for a longer prompt.
+ append(decoder.is_token_dim_ambiguous());
append(params.mixed_rope_params);
append(params.is_cacheless_attn);
for (int layer : params.swa_layers) {
@@ -368,9 +371,17 @@ static std::string dynamic_graph_signature(const ggml_cgraph * graph,
for (const auto & [name, input] : decoder.get_model_extra_inputs()) {
append_string(name);
append_string(input.type.get_type_name());
- append(input.shape.size());
- for (auto dim : input.shape) {
- append(dim);
+ // Replay control lengths change with the batch. The compiled graph uses the declared Parameter shape.
+ if (input.is_parameter && input.parameter_shape.rank().is_static() && input.parameter_shape.is_dynamic()) {
+ append(std::numeric_limits<size_t>::max());
+ append_string(input.parameter_shape.to_string());
+ } else {
+ const auto shape = input.is_parameter && input.parameter_shape.is_static() ?
+ input.parameter_shape.to_shape() : input.shape;
+ append(shape.size());
+ for (const auto dim : shape) {
+ append(dim);
+ }
}
append(input.is_parameter);
if (!input.is_parameter) {
@@ -761,24 +772,21 @@ ov::Tensor get_ov_input_tensor(const std::shared_ptr<GgmlOvDecoder> & ggml_decod
}
}
input_tensor = cached;
- if (param_name == "sampling_rows") {
+ if (param_name.compare(0, 13, "vision_shape_") == 0 || param_name.compare(0, 12, "vision_size_") == 0) {
+ const auto & values = ggml_decoder->get_compute_params().vision_shapes.at(param_name);
+ std::copy(values.begin(), values.end(), input_tensor.data<int64_t>());
+ } else if (param_name.compare(0, 9, "vision_y_") == 0 || param_name.compare(0, 9, "vision_x_") == 0) {
+ const auto & values = ggml_decoder->get_compute_params().vision_projections.at(param_name);
+ std::copy(values.begin(), values.end(), input_tensor.data<float>());
+ } else if (param_name == "sampling_rows") {
auto * data = input_tensor.data<int64_t>();
for (const auto & row : ggml_decoder->get_compute_params().sampling_rows) {
*data++ = row.second;
}
- } else if (param_name.compare(0, 11, "rs_offsets_") == 0 || param_name.compare(0, 11, "rs_windows_") == 0) {
+ } else if (param_name.compare(0, 10, "rs_replay_") == 0) {
const auto & controls = ggml_decoder->get_compute_params();
const auto & values = controls.recurrent_controls.at(param_name);
std::copy(values.begin(), values.end(), input_tensor.data<int64_t>());
- } else if (param_name.compare(0, 10, "rs_update_") == 0) {
- const auto & controls = ggml_decoder->get_compute_params();
- const auto & write = controls.rs_writebacks.at(param_name.substr(10));
- auto data = input_tensor.data<int64_t>();
- data[0] = write.slot_begin;
- data[1] = write.seq_count >= 0 ? write.seq_count : controls.s_copy_active_slot_len;
- data[2] = write.snapshot_stride >= 0 ? write.snapshot_stride : data[1];
- // Direct GDN states contain no attention prefix.
- data[3] = 0;
} else {
if (extra_input->second.type == ov::element::i64) {
*input_tensor.data<int64_t>() = extra_input->second.value;
@@ -1252,7 +1260,8 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
// graph_key first (a few hundred us), and if the same key is already in decoder_cache
// we know the graph is not splitted (only not-splitted graphs get inserted there).
const int64_t cache_key_start_time = ggml_time_us();
- graph_key key(cgraph);
+ const bool dynamic_vision = GgmlOvDecoder::is_dynamic_vision_graph(cgraph);
+ graph_key key(cgraph, false, dynamic_vision);
const int64_t cache_key_compute_time = ggml_time_us() - cache_key_start_time;
int64_t cache_lookup_time = 0;
bool key_seen = false;
@@ -1282,7 +1291,7 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
ModelParams m_params;
ComputeParams c_params;
const int64_t graph_param_compute_start_time = ggml_time_us();
- std::tie(m_params, c_params) = GgmlOvDecoder::compute_llm_params(cgraph, is_static);
+ std::tie(m_params, c_params) = GgmlOvDecoder::compute_llm_params(cgraph, is_static, dynamic_vision);
const int64_t graph_param_compute_time = ggml_time_us() - graph_param_compute_start_time;
const bool cache_enabled = !model_is_splitted && !cache_disabled;
@@ -1308,6 +1317,7 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
{
std::shared_ptr<decoder_runtime_ctx> entry;
ModelParams old_m_params;
+ bool reconvert = false;
const int64_t cache_lookup_start_time = ggml_time_us();
if (cache_enabled) {
@@ -1353,6 +1363,12 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
if (cache_hit && !ggml_decoder->has_same_graph_io(cgraph)) {
cache_hit = false;
}
+ // A model converted from a one-token graph may have the token dim in the wrong place for more tokens
+ // (GLM-4.7-Flash -fa off: a warm-up decode, then a prompt). Convert again; that model also runs decode.
+ if (cache_hit && !ggml_decoder->can_run_tokens(c_params.input_len)) {
+ cache_hit = false;
+ reconvert = true;
+ }
}
std::vector<std::string> ov_input_names;
@@ -1477,6 +1493,14 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
// The lock is released before binding tensors or running inference.
auto shared_cache = r_ctx->compiled_cache;
std::unique_lock<std::mutex> compile_lock(shared_cache->mutex);
+ if (reconvert) {
+ // release the one-token model before compiling, so the device does not hold two copies of the weights
+ shared_cache->graphs.erase(entry->shared_key);
+ entry->ptr.reset();
+ entry->replay_writebacks.clear();
+ std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
+ r_ctx->infer_request_cache.erase(key);
+ }
auto weight_names = get_weight_names(cgraph);
ggml_decoder = std::make_shared<GgmlOvDecoder>(cgraph, m_params, c_params, weight_names,
is_static, r_ctx->stateful, model_is_splitted);
@@ -1487,8 +1511,12 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
uint64_t exact_fp = 0;
std::string blob_path, manifest_path;
if (!model_cache_dir.empty() && !model_is_splitted) {
- const uint64_t extra_cfg =
+ uint64_t extra_cfg =
ggml_openvino_model_cache_extra_cfg(r_ctx->stateful, stateful_recurrent);
+ if (ggml_decoder->get_model_extra_inputs().count("rs_replay_rows")) {
+ // The writable-input replay interface replaces bank Results with Assign sinks.
+ extra_cfg = extra_cfg * 131 + 1;
+ }
model_fp =
ggml_openvino_model_fingerprint(cgraph, device, /*fa=*/true, m_params.rope_params, 16, extra_cfg,
dynamic_graph_signature(cgraph, *ggml_decoder, m_params));
@@ -1641,8 +1669,7 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
blob_path.c_str());
return GGML_STATUS_FAILED;
}
- if (!imported && ggml_openvino_weight_buffers_released()) {
- GGML_LOG_ERROR("ggml-openvino: cannot compile a new graph after releasing host weights\n");
+ if (!imported && !ggml_openvino_restore_weight_buffers()) {
return GGML_STATUS_FAILED;
}
if (imported) {
@@ -1729,7 +1756,18 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
shared_model = compiled_model;
} // end non-imported (compile) path
+ entry->replay_writebacks.clear();
+ if (ggml_decoder->get_model_extra_inputs().count("rs_replay_rows")) {
+ constexpr auto prefix = ov::frontend::ggml::replay_cache_state_prefix;
+ for (auto state : infer_request->query_state()) {
+ const auto name = state.get_name();
+ if (name.compare(0, prefix.size(), prefix) == 0) {
+ entry->replay_writebacks.emplace_back(name.substr(prefix.size()), std::move(state));
+ }
+ }
+ }
entry->ptr = ggml_decoder;
+ entry->shared_key = shared_key;
if (!shared_key.empty() && shared_it == shared_cache->graphs.end()) {
ov_compiled_graph graph;
graph.decode = shared_model;
@@ -1904,6 +1942,14 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
}
throw;
}
+ for (const auto & [name, state] : entry->replay_writebacks) {
+ const auto bank = ggml_decoder->get_model_outputs().at(name);
+ const auto updated = state.get_state();
+ OPENVINO_ASSERT(updated.get_element_type() == GgmlOvDecoder::get_ov_type(bank) &&
+ updated.get_shape() == GgmlOvDecoder::get_shape(bank),
+ "Invalid replay cache writeback for ", name);
+ ggml_backend_tensor_set(bank, updated.data(), 0, ggml_nbytes(bank));
+ }
infer_end_time = ggml_time_us();
for (const auto & out : staged_outputs) {
std::memcpy(out.dst, out.src, out.bytes);
@@ -1939,17 +1985,14 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
}
}
- // GGML_OPENVINO_RELEASE_WEIGHTS (or GGML_OPENVINO_MEMORY_OPTIMIZE on GPU): the plugin holds its own device copy of
+ // GGML_OPENVINO_RELEASE_WEIGHTS (GPU): the plugin holds its own device copy of
// every weight after compile, so the host weight buffers can be dropped to reclaim
// RSS. Release only while holding the compilation mutex so another context cannot
- // be reading host weights during conversion/compilation. Pin the shared compiled
- // models across backend teardown; a later context can create its own request without
- // reading the dropped pages. A new, uncached graph still fails fast above.
+ // be reading host weights during conversion/compilation. A new, uncached graph
+ // writes them again from the model file first (see above).
if (cache_hit && ggml_openvino_release_weights_enabled()) {
std::lock_guard<std::mutex> compile_lock(r_ctx->compiled_cache->mutex);
- if (!ggml_openvino_weight_buffers_released()) {
- ggml_openvino_release_weight_buffers();
- }
+ ggml_openvino_release_weight_buffers();
}
return GGML_STATUS_SUCCESS;
@@ -2357,8 +2400,14 @@ static ov::AnyMap static_variant_config(const static_graph_args & a,
const decoder_runtime_ctx & e,
const GgmlOvDecoder & decoder,
bool prefill) {
- ov::AnyMap config = prefill ? ggml_openvino_npu_prefill_config(a.compile_config, decoder) :
- ggml_openvino_npu_decode_config(a.compile_config, a.device);
+ // A graph with a MoE block that translate_moe_tiled turns into the batched form also needs the NPUW properties
+ // that make NPUW isolate the experts and run only the routed ones (ggml_openvino_npu_moe_config). They are
+ // NPUW properties, so not for cacheless graphs, which compile without NPUW, and not for the static path that
+ // GGML_OPENVINO_FORCE_STATIC runs on the CPU or the GPU. The decoder finds the block once, when it is built.
+ const bool moe = !a.no_kv_cache && a.device == "NPU" && decoder.has_moe_block();
+ const ov::AnyMap base = moe ? ggml_openvino_npu_moe_config(a.compile_config) : a.compile_config;
+ ov::AnyMap config = prefill ? ggml_openvino_npu_prefill_config(base, decoder) :
+ ggml_openvino_npu_decode_config(base, a.device);
if (!a.model_cache_dir.empty()) {
config.erase("CACHE_DIR");
config.erase("CACHE_MODE");
@@ -2456,10 +2505,9 @@ static void static_load_variants(const static_graph_args & a,
}
const size_t n_compile = std::count_if(pending.begin(), pending.end(), [](const auto & p) { return !p.import; });
if (n_compile != 0) {
- // Same fail-fast as the dynamic path: once the host weight pages have been dropped they read as zeros, so a
- // compile here would bake garbage into the new model.
- if (ggml_openvino_weight_buffers_released()) {
- throw std::runtime_error("ggml-openvino: cannot compile a new graph after releasing host weights");
+ // as in the dynamic path: write the released host weights again before they are read for the compile
+ if (!ggml_openvino_restore_weight_buffers()) {
+ throw std::runtime_error("ggml-openvino: cannot write the released host weights again");
}
std::map<ov_static_variant_key, static_converted> converted;
if (a.weightless_bank && !e.weights_layout) {
@@ -2570,6 +2618,8 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
fprintf(stderr, "GGML OpenVINO profiling: static graph kind=%s, input_tokens=%lld, chunk_size=%d\n",
is_prefill ? "prefill" : "decode", static_cast<long long>(input_tokens), prefill_chunk_size);
}
+ // Compile properties for this graph: cacheless (encoder) graphs compile on the plain NPU plugin, graphs with
+ // GATED_DELTA_NET layers may switch the compiler (see npu_config.h), the others take the base config.
const ov::AnyMap compile_config = no_kv_cache ? ggml_openvino_npu_without_npuw(config) :
m_params.state_size >= 0 ? ggml_openvino_npu_gdn_config(config) :
config;
diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h
index ee170a266..b630c424a 100644
--- a/ggml/src/ggml-openvino/utils.h
+++ b/ggml/src/ggml-openvino/utils.h
@@ -1,6 +1,7 @@
#include "ggml-decoder.h"
#include "ggml-impl.h"
#include "ggml-openvino-extra.h"
+#include "ggml-openvino.h"
#include "model-cache.h"
#include <cstddef>
@@ -23,24 +24,50 @@
// graph during inference, where the same few graphs repeat for the whole session. The list of
// external input names below tells those apart more precisely, but it walks every node and every
// src slot, so it is built only when GGML_OPENVINO_FULL_GRAPH_KEY is set. Sampler row names are
-// always included to distinguish sampler configurations, even when active subsets share the packed input. Op tests run
-// many small graphs that can share a node count and end names, and need the full key.
+// always included, along with weight allocation generations. Static or unqualified image graphs
+// also include input shapes. Op tests run many small graphs that can share a node count and end
+// names, and need the full key.
struct graph_key {
int n_nodes;
int n_leaves;
std::string first_node_name;
std::string last_node_name;
- // External source descriptors "<src_name>:<src_idx>:<op_type>" and sampler row Parameter names.
+ // External source descriptors, sampler row names and image shapes.
std::vector<std::string> input_srcs;
+ // Process-local identities used only by the private cache key.
+ std::vector<size_t> weight_buffer_ids;
- graph_key(const ggml_cgraph * cgraph, bool include_inputs = false) : n_nodes(cgraph->n_nodes), n_leaves(cgraph->n_leafs) {
+ graph_key(const ggml_cgraph * cgraph, bool include_inputs = false, bool dynamic_vision = false) :
+ n_nodes(cgraph->n_nodes), n_leaves(cgraph->n_leafs) {
if (n_nodes > 0) {
first_node_name = cgraph->nodes[0]->name;
last_node_name = cgraph->nodes[n_nodes - 1]->name;
}
+ std::unordered_set<ggml_backend_buffer_t> weight_buffers;
for (int i = 0; i < n_nodes; ++i) {
const auto * node = cgraph->nodes[i];
+ if (node->op == GGML_OP_MUL_MAT && ggml_prec_get_src(node, 1) == GGML_PREC_F32) {
+ // Node precision guards are part of the compiled graph, including in the dynamic disk cache.
+ input_srcs.push_back("f32_matmul_" + std::to_string(i));
+ }
+ // A later model load may use the same graph names and shapes but new
+ // weights. Allocation generations survive pointer reuse, whereas
+ // the lightweight topology key alone would select stale Constants.
+ for (const auto * src : node->src) {
+ if (!src) {
+ continue;
+ }
+ const auto * root = src->view_src ? src->view_src : src;
+ const auto buffer = root->buffer;
+ if (buffer && buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS &&
+ weight_buffers.insert(buffer).second) {
+ const auto id = ggml_backend_openvino_buffer_get_ctx_id(buffer);
+ if (id != 0) {
+ weight_buffer_ids.push_back(id);
+ }
+ }
+ }
if (GgmlOvDecoder::is_sampling_view(node)) {
input_srcs.push_back("sampling_row_" + std::string(node->name) + "#n" + std::to_string(i));
}
@@ -49,6 +76,24 @@ struct graph_key {
if (node->flags & GGML_TENSOR_FLAG_OUTPUT) {
input_srcs.push_back("output_" + std::string(node->name) + "#n" + std::to_string(i));
}
+ // Qualified vision graphs reuse a fixed model configuration; only spatial sizes vary.
+ // Static or unqualified image graphs keep their full input shape in the key.
+ if (!dynamic_vision && (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_2D_DW ||
+ node->op == GGML_OP_IM2COL) && node->src[1] != nullptr) {
+ const auto * input = node->src[1];
+ const auto * root = input->view_src ? input->view_src : input;
+ // Gemma4 normalizes image pixels with SCALE before patch extraction.
+ while (root->op == GGML_OP_SCALE && root->src[0]) {
+ root = root->src[0]->view_src ? root->src[0]->view_src : root->src[0];
+ }
+ if (root->flags & GGML_TENSOR_FLAG_INPUT) {
+ std::string shape = "image_input_" + std::to_string(i) + ":" + root->name;
+ for (int dim = 0; dim < GGML_MAX_DIMS; ++dim) {
+ shape += ":" + std::to_string(root->ne[dim]);
+ }
+ input_srcs.push_back(std::move(shape));
+ }
+ }
}
static const bool full_key = ggml_openvino_getenv_int("GGML_OPENVINO_FULL_GRAPH_KEY") != 0;
@@ -78,7 +123,8 @@ struct graph_key {
bool operator==(const graph_key & other) const {
return n_nodes == other.n_nodes && n_leaves == other.n_leaves &&
first_node_name == other.first_node_name &&
- last_node_name == other.last_node_name && input_srcs == other.input_srcs;
+ last_node_name == other.last_node_name && input_srcs == other.input_srcs &&
+ weight_buffer_ids == other.weight_buffer_ids;
}
};
@@ -93,6 +139,9 @@ struct graph_key_hash {
for (const auto & s : key.input_srcs) {
hash ^= std::hash<std::string>{}(s) + 0x9e3779b9 + (hash << 6) + (hash >> 2);
}
+ for (const auto id : key.weight_buffer_ids) {
+ hash ^= std::hash<size_t>{}(id) + 0x9e3779b9 + (hash << 6) + (hash >> 2);
+ }
return hash;
}
};
@@ -125,6 +174,9 @@ struct decoder_runtime_ctx {
std::shared_ptr<std::mutex> mutex;
std::shared_ptr<GgmlOvDecoder> ptr;
+ // key of ptr's model in ov_compiled_model_cache, to drop it when the graph is converted again
+ std::string shared_key;
+ std::vector<std::pair<std::string, ov::VariableState>> replay_writebacks;
// Static path: the compiled models of this graph with their requests (ov_graph_compute_static).
std::map<ov_static_variant_key, ov_static_variant> variants;