Commit a274a3948 for llama.cpp
commit a274a3948fa5c917d54a3f28fe8af74bca513688
Author: Yamini Nimmagadda <yamini.nimmagadda@intel.com>
Date: Fri Dec 4 07:30:31 2026 -0800
openvino: CI fixes, new models, improve NPU, Q2_0 support (#33652)
* ggml-openvino : add Q2_0 and Bonsai 2 support
* openvino: enable text inference for Nemotron Lightning and LFM3
Assisted-by: Codex
* openvino: enable NPU host gather by default
* docs : host gather is on by default
* openvino: compute ELU with an accurate expm1
* ggml-openvino: compute NPU RoPE cos/sin on the host for long contexts
Assisted-by: Claude Opus 5.5
* openvino: review fixes for the NPU RoPE table
* openvino: replace the RoPE flags with GGML_OPENVINO_ROPE_SINCOS
* docs : reorganize OpenVINO docs and add a cookbook
* openvino: preserve token dimensions in Gemma 3n reductions
Assisted-by: Codex
* openvino: keep the compiled-model cache revision at 14
Assisted-by: Codex
* openvino: reject sequence-major SSM_SCAN inputs
* ggml-openvino : drop code that the ggml core does not need
* openvino: add GGML_OPENVINO_SPILL_RESIDENT to cap the spilled weights kept in RAM
Assisted-by: Claude Opus 5.5
* openvino: review fixes for GGML_OPENVINO_SPILL_RESIDENT
* openvino: take GGML_OPENVINO_SPILL_RESIDENT as a fraction
* openvino: add GGML_OPENVINO_SPILL and simplify the spill limiter
* openvino: add GGML_OPENVINO_COMPILE_MEM_SPILL
* openvino: clang-format fixes
* openvino: unwrap comments and docs per AGENTS.md
Assisted-by: Claude Code
---------
Co-authored-by: Mustafa Cavus <mustafa.cavus@intel.com>
Co-authored-by: Yu, Zijun <zijun.yu@intel.com>
Co-authored-by: Xuejun <Xuejun.Zhai@intel.com>
Co-authored-by: ravi9 <ravi.panchumarthy@intel.com>
Co-authored-by: Anisha Kulkarni <anisha.dattatraya.kulkarni@intel.com>
diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md
index 0449a5d3a..c6468a218 100644
--- a/docs/backend/OPENVINO.md
+++ b/docs/backend/OPENVINO.md
@@ -1,18 +1,10 @@
# OpenVINO Backend for llama.cpp
-> [!NOTE]
-> Performance and memory optimizations, accuracy validation, broader quantization coverage, broader operator and model support are work in progress.
+[OpenVINO](https://docs.openvino.ai/) is an open-source toolkit for optimizing and deploying AI inference on Intel hardware. The [OpenVINO backend](../../ggml/src/ggml-openvino) runs the same GGUF model files on **Intel(R) CPUs, GPUs and NPUs**, without changes to the model or the rest of llama.cpp.
-[OpenVINO](https://docs.openvino.ai/) is an open-source toolkit for optimizing and deploying high-performance AI inference, specifically designed for Intel hardware, including CPUs, GPUs (integrated and discrete), and NPUs, in the cloud, on-premises, and on the edge. The [OpenVINO backend](../../ggml/src/ggml-openvino) runs the same GGUF model files on **Intel® CPUs, GPUs and NPUs**, without changes to the model or the rest of llama.cpp.
-
-When a `ggml_cgraph` is dispatched to the OpenVINO backend, it:
-
-- Walks the GGML graph and identifies inputs, outputs, weights, and KV cache tensors.
-- Translates the GGML operations into an `ov::Model` using OpenVINO's frontend API.
-- Compiles and caches the model for the target device.
-- Binds GGML tensor memory to OpenVINO inference tensors and runs inference.
-
-For guidance on contributing to the OpenVINO backend, see the [OpenVINO Backend Contributing Guide](https://github.com/ravi9/llamacpp-ov-dev-guide/blob/main/contributing-llamacpp-ov.md).
+- Recipes for each task: [llama.cpp OpenVINO backend cookbook](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md).
+- Internals and developer options: [developer documentation](../../ggml/src/ggml-openvino/dev_doc/README.md).
+- Contributing: [OpenVINO Backend Contributing Guide](https://github.com/ravi9/llamacpp-ov-dev-guide/blob/main/contributing-llamacpp-ov.md).
## Contents
@@ -21,30 +13,24 @@ For guidance on contributing to the OpenVINO backend, see the [OpenVINO Backend
- [Supported Model Precisions](#supported-model-precisions)
- [Supported llama.cpp Tools](#supported-llamacpp-tools)
- [Validated Models](#validated-models)
-- [Build Instructions](#build-instructions)
- - [0. Prerequisites](#0-prerequisites)
- - [1. Install OpenVINO Runtime](#1-install-openvino-runtime)
- - [2. Build llama.cpp with OpenVINO Backend](#2-build-llamacpp-with-openvino-backend)
- - [Ubuntu Build Script](#ubuntu-build-script)
- - [Windows Build Script](#windows-build-script)
- - [3. Download Sample Model](#3-download-sample-model)
- - [4. Run Inference with OpenVINO Backend](#4-run-inference-with-openvino-backend)
- - [5. Docker Build](#5-docker-build)
-- [Runtime Configuration](#runtime-configuration)
+- [Build](#build)
+ - [Prerequisites](#prerequisites)
+ - [Install OpenVINO Runtime](#install-openvino-runtime)
+ - [Build llama.cpp](#build-llamacpp)
+- [Docker](#docker)
+- [Configuration](#configuration)
- [Basic](#basic)
- [Plugin properties](#plugin-properties)
- [Advanced tuning](#advanced-tuning)
- [Compiled model cache](#compiled-model-cache)
- [Deprecated](#deprecated)
- - [Debugging and development](#debugging-and-development)
- - [Example Usage](#example-usage)
- - [GPU Inference with Profiling](#gpu-inference-with-profiling)
+ - [Developer variables](#developer-variables)
- [Known Limitations](#known-limitations)
- [Work in Progress](#work-in-progress)
## Quick Start
-On Ubuntu, with the [prerequisites](#0-prerequisites) and the [OpenVINO Runtime](#1-install-openvino-runtime) installed:
+On Ubuntu, with the [prerequisites](#prerequisites) and the [OpenVINO Runtime](#install-openvino-runtime) installed:
```bash
# 1. Build
@@ -59,24 +45,31 @@ mkdir -p ~/models/
wget https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf \
-O ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
-# 3. Run on CPU, GPU or NPU
-export GGML_OPENVINO_DEVICE=GPU
-./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
+# 3. Run on CPU, GPU or NPU. -c sets the context size. The default is the training context of the model.
+GGML_OPENVINO_DEVICE=CPU ./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
+GGML_OPENVINO_DEVICE=GPU ./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
+GGML_OPENVINO_DEVICE=NPU ./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512
```
-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.
+- The first run of a model compiles it for the device. On the NPU, this can take minutes for a large model.
+- Windows, llama-server, llama-bench and NPU tuning: [Run on each device](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#run-on-each-device).
+- One-step build scripts for Ubuntu and Windows: [Build from source](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#build-from-source).
## Supported Devices
-OpenVINO backend supports the following hardware:
-
- Intel CPUs
- Intel GPUs (integrated and discrete)
- Intel NPUs
-Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvino.ai/2026/about-openvino/release-notes-openvino/system-requirements.html), the llama.cpp OpenVINO backend has been validated specifically on AI PCs such as the Intel® Core™ Ultra Series 2 (Lunar Lake) and Series 3 (Panther Lake).
+The backend is validated on AI PCs with Intel(R) Core(TM) Ultra Series 2 (Lunar Lake) and Series 3 (Panther Lake). OpenVINO supports a wider range of [Intel hardware](https://docs.openvino.ai/2026/about-openvino/release-notes-openvino/system-requirements.html).
+
+Device selection:
+
+- Select the OpenVINO device with `GGML_OPENVINO_DEVICE`, not with `-dev`. The default is the CPU.
+- With several GPUs, OpenVINO names them `GPU.0`, `GPU.1`, and so on. Set one of these names. `GPU` alone is then not available.
+- A device that is not available is an error. There is no fallback to the CPU. The error lists the available devices.
+- `llama-cli --list-devices` shows the `GGML_OPENVINO_DEVICE=<value>` of each OpenVINO device. `(selected)` marks the active one.
+- To split a model across GPUs, see [Multiple GPUs](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#multiple-gpus). GPU details: [OpenVINO GPU Device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html).
## Supported Model Precisions
@@ -110,7 +103,8 @@ Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvin
**NPU:**
- 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.
+- With `GGML_OPENVINO_NPU_HOST_GATHER` (on by default), the host reads the rows of an embedding table of 64 MiB or more from the GGUF file. A table used only for these lookups is not converted.
+- For a `Q6_K` token embedding in the NPU graph (a tied output weight, a table under 64 MiB, or with host gather off), `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:**
@@ -119,21 +113,17 @@ Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvin
- `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:**
-- `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>
## Supported llama.cpp Tools
-The OpenVINO backend works with the standard llama.cpp tools listed below. Tool coverage is not uniform across devices.
+The OpenVINO backend works with the standard llama.cpp tools below. Tool coverage is not uniform across devices.
- llama-bench
- llama-cli
- llama-completion
- llama-embedding
+- llama-mtmd-cli (image input on CPU and GPU, experimental)
- llama-perplexity
- llama-server
- llama-simple
@@ -145,7 +135,7 @@ The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® C
**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 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.
+- **Validation system:** Intel(R) Core(TM) Ultra X7 358H (Panther Lake) | 64 GB RAM | Ubuntu 26.04.1 | OpenVINO 2026.5.0 | 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>
@@ -208,27 +198,26 @@ The embedding models were tested with `llama-embedding` and `Q8_0` files.
</details>
-## Build Instructions
+## Build
+
+- Prebuilt binaries: each llama.cpp [release](https://github.com/ggml-org/llama.cpp/releases) has OpenVINO builds for Ubuntu and Windows. They include the OpenVINO runtime. Install the GPU and NPU drivers separately.
+- One-step build scripts for Ubuntu and Windows: [Build from source](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#build-from-source).
-### 0. Prerequisites
+### Prerequisites
-- Linux or Windows system with Intel hardware (CPU, GPU, or NPU)
-- **For Intel GPU or NPU Usage**: Install the appropriate hardware drivers for your Intel GPU or NPU. For detailed instructions, see: [Additional Configurations for Hardware Acceleration](https://docs.openvino.ai/2026/get-started/install-openvino/configurations.html).
+- Linux or Windows, with an Intel CPU, GPU or NPU.
+- OpenVINO Runtime 2026.5 or later. See [Install OpenVINO Runtime](#install-openvino-runtime).
+- GPU or NPU: the device drivers. See [Additional Configurations for Hardware Acceleration](https://docs.openvino.ai/2026/get-started/install-openvino/configurations.html).
<details open>
<summary><b>Linux</b></summary>
-Build tools (Git, CMake, Ninja):
-
```bash
+# Build tools (Git, CMake, Ninja)
sudo apt-get update
-sudo apt-get install -y build-essential libcurl4-openssl-dev libssl-dev libtbb12 cmake ninja-build python3-pip curl wget tar git
-```
-
-OpenCL:
-
-```bash
-sudo apt install ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd
+sudo apt-get install -y build-essential libssl-dev libtbb12 cmake ninja-build python3-pip curl wget tar git
+# OpenCL
+sudo apt-get install -y ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd
```
</details>
@@ -236,606 +225,77 @@ sudo apt install ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-op
<details>
<summary><b>Windows</b></summary>
-1. Download and install [Microsoft Visual Studio 2022 Build Tools](https://aka.ms/vs/17/release/vs_BuildTools.exe). During installation, select the **"Desktop development with C++"** workload.
-2. Install the required tools:
+1. Install [Microsoft Visual Studio 2022 Build Tools](https://aka.ms/vs/17/release/vs_BuildTools.exe) with the **Desktop development with C++** workload.
+2. Install Git, Ninja and OpenCL:
```powershell
# Windows PowerShell
winget install Git.Git
- winget install GNU.Wget
winget install Ninja-build.Ninja
- ```
-
-3. Install **OpenCL** using **vcpkg**:
-
- ```powershell
- # Windows PowerShell
+ # OpenCL with vcpkg, in C:\vcpkg
cd C:\
git clone https://github.com/microsoft/vcpkg
cd vcpkg
.\bootstrap-vcpkg.bat
.\vcpkg install opencl
- # Optional but recommended: Integrate vcpkg with Visual Studio / CMake:
+ # Optional: integrate vcpkg with Visual Studio and CMake
.\vcpkg integrate install
```
</details>
-### 1. Install OpenVINO Runtime
-
-- Follow the guide to install OpenVINO Runtime from an archive file: [Linux](https://docs.openvino.ai/2026/get-started/install-openvino/install-openvino-archive-linux.html) | [Windows](https://docs.openvino.ai/2026/get-started/install-openvino/install-openvino-archive-windows.html)
-
-- Verify OpenVINO is initialized properly:
- ```bash
- echo $OpenVINO_DIR
- ```
-
-### 2. Build llama.cpp with OpenVINO Backend
+### Install OpenVINO Runtime
-Clone the llama.cpp repository:
+Install OpenVINO Runtime 2026.5 from an archive file: [Linux](https://docs.openvino.ai/2026/get-started/install-openvino/install-openvino-archive-linux.html) | [Windows](https://docs.openvino.ai/2026/get-started/install-openvino/install-openvino-archive-windows.html). The CI and the cookbook build scripts use this version.
```bash
-git clone https://github.com/ggml-org/llama.cpp
-cd llama.cpp
+# Check the setup: setupvars sets OpenVINO_DIR
+source /opt/intel/openvino/setupvars.sh
+echo $OpenVINO_DIR
```
-Build on Linux:
+### Build llama.cpp
```bash
+# Linux. Adjust the setupvars.sh path to the OpenVINO install directory.
+git clone https://github.com/ggml-org/llama.cpp
+cd llama.cpp
source /opt/intel/openvino/setupvars.sh
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>
-
-Open **x64 Native Tools Command Prompt for VS** (so the MSVC toolchain is on `PATH`), then run:
-
```cmd
+REM Windows: x64 Native Tools Command Prompt for VS, so that the MSVC toolchain is on PATH
+git clone https://github.com/ggml-org/llama.cpp
+cd llama.cpp
C:\Intel\openvino\setupvars.bat
cmake -B build\ReleaseOV -G Ninja -DCMAKE_BUILD_TYPE=Release -DGGML_OPENVINO=ON -DCMAKE_TOOLCHAIN_FILE=C:\vcpkg\scripts\buildsystems\vcpkg.cmake
cmake --build build\ReleaseOV --parallel
```
-> [!NOTE]
-> The Windows install path is `C:\Intel\openvino` (no spaces) to avoid quoting problems some CMake/Ninja toolchains have with `C:\Program Files (x86)\...`. Adjust to wherever you installed OpenVINO Runtime. From `cmd`, run `C:\Intel\openvino\setupvars.bat`; from PowerShell, run `& "C:\Intel\openvino\setupvars.ps1"` instead. Once the build is finished you can launch the binaries from any `cmd` or `PowerShell` window after sourcing the matching `setupvars` script for that shell.
-
-</details>
-
-#### Ubuntu Build Script
-
-For Ubuntu users, the following shell script automates the prerequisite installs (build tools, OpenCL ICD), the OpenVINO Runtime download/extract/setup, and the Ninja-based llama.cpp build.
-Save the following as `build-llamacpp-ov.sh` next to where you want the `llama.cpp` folder to land, then run it:
-
-```bash
-chmod +x build-llamacpp-ov.sh
-./build-llamacpp-ov.sh
-```
-
-<details>
-<summary>Click to expand <code>build-llamacpp-ov.sh</code></summary>
-
-```bash
-#!/usr/bin/env bash
-# ============================================
-# llama.cpp OpenVINO Build Script (Ninja)
-# ============================================
-set -euo pipefail
-
-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"
-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 libssl-dev libtbb12 \
- cmake ninja-build python3-pip \
- curl wget tar git
-
-echo "============================================"
-echo "Installing OpenCL runtime + headers..."
-echo "============================================"
-sudo apt-get install -y \
- ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd
-
-cd "${SCRIPT_DIR}"
-
-# ============================================
-# Clone llama.cpp if missing
-# ============================================
-if [[ ! -f "llama.cpp/CMakeLists.txt" ]]; then
- echo "Cloning llama.cpp..."
- git clone https://github.com/ggml-org/llama.cpp
-fi
-
-# ============================================
-# Setup OpenVINO: download & extract to /opt/intel/openvino_${OPENVINO_VERSION_MAJOR},
-# then point /opt/intel/openvino at it via symlink so the active version is swappable.
-# ============================================
-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 -fL -o "${OPENVINO_TGZ}" "${OPENVINO_URL}"
-
- echo "Extracting OpenVINO to ${OPENVINO_INSTALL_DIR}..."
- sudo mkdir -p "${OPENVINO_INSTALL_DIR}"
- sudo tar -xzf "${OPENVINO_TGZ}" -C "${OPENVINO_INSTALL_DIR}" --strip-components=1
- rm -f "${OPENVINO_TGZ}"
-fi
-
-# Refresh symlink: /opt/intel/openvino -> /opt/intel/openvino_${OPENVINO_VERSION_MAJOR}
-sudo ln -sfn "${OPENVINO_INSTALL_DIR}" "${OPENVINO_LINK_DIR}"
-
-OPENVINO_ROOT="${OPENVINO_LINK_DIR}"
-echo "OpenVINO Ready: ${OPENVINO_ROOT} -> ${OPENVINO_INSTALL_DIR}"
-
-# Install OpenVINO's own runtime dependencies (one-time per system).
-if [[ -x "${OPENVINO_ROOT}/install_dependencies/install_openvino_dependencies.sh" ]]; then
- echo "============================================"
- echo "Installing OpenVINO runtime dependencies..."
- echo "============================================"
- echo "Y" | sudo -E "${OPENVINO_ROOT}/install_dependencies/install_openvino_dependencies.sh"
-fi
-
-# ============================================
-# Clean old build cache
-# ============================================
-cd "${SCRIPT_DIR}/llama.cpp"
-if [[ -d "build/ReleaseOV" ]]; then
- echo "Removing old build directory..."
- rm -rf "build/ReleaseOV"
-fi
-
-echo "============================================"
-echo "Configuring with CMake..."
-echo "============================================"
-set +u
-source "${OPENVINO_ROOT}/setupvars.sh"
-set -u
-
-cmake -B build/ReleaseOV -G Ninja \
- -DCMAKE_BUILD_TYPE=Release \
- -DGGML_OPENVINO=ON
-
-cmake --build build/ReleaseOV --parallel
-
-echo "============================================"
-echo "Build completed successfully!"
-echo "============================================"
-echo "Binaries: $(pwd)/build/ReleaseOV/bin"
-echo
-echo "NOTE: To run, source setupvars.sh and pick a device:"
-echo " source /opt/intel/openvino/setupvars.sh"
-echo " export GGML_OPENVINO_DEVICE=CPU # or GPU / NPU"
-echo " ./build/ReleaseOV/bin/llama-cli -m model.gguf"
-```
-
-> [!NOTE]
-> 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` folder to land, then run it from either **Command Prompt** or **PowerShell**:
-
-```cmd
-:: Command Prompt
-build-llamacpp-ov.bat
-```
-
-```powershell
-# PowerShell
-.\build-llamacpp-ov.bat
-```
-
-<details>
-<summary>Click to expand <code>build-llamacpp-ov.bat</code></summary>
-
-```bat
-@echo off
-setlocal enabledelayedexpansion
-
-REM ============================================
-REM llama.cpp OpenVINO Build Script (Ninja)
-REM ============================================
-
-set "OPENVINO_VERSION_MAJOR=2026.5"
-set "OPENVINO_VERSION_FULL=2026.5.0.23836.73088206582"
-
-set "SCRIPT_DIR=%~dp0"
-set "VCPKG_DIR=C:\vcpkg"
-set "OPENVINO_INSTALL_DIR=C:\Intel\openvino_%OPENVINO_VERSION_MAJOR%"
-set "OPENVINO_LINK_DIR=C:\Intel\openvino"
-set "OPENVINO_ZIP=%SCRIPT_DIR%openvino.zip"
-set "OPENVINO_EXTRACT_TMP=%SCRIPT_DIR%openvino_extract_tmp"
-set "OPENVINO_URL=https://storage.openvinotoolkit.org/repositories/openvino/packages/%OPENVINO_VERSION_MAJOR%/windows/openvino_toolkit_windows_%OPENVINO_VERSION_FULL%_x86_64.zip"
-
-echo ============================================
-echo Installing prerequisites...
-echo ============================================
-winget install --id Git.Git -e --accept-source-agreements --accept-package-agreements 2>nul
-winget install --id Ninja-build.Ninja -e --accept-source-agreements --accept-package-agreements 2>nul
-winget install --id Kitware.CMake -e --accept-source-agreements --accept-package-agreements 2>nul
-
-REM Ensure Visual Studio Build Tools are installed.
-echo Checking for Visual Studio Build Tools...
-set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"
-set "VS_INSTALLED="
-if exist "%VSWHERE%" (
- for /f "usebackq tokens=*" %%i in (`"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 2^>nul`) do (
- set "VS_INSTALLED=%%i"
- )
-)
-if defined VS_INSTALLED (
- echo Visual Studio with VC++ x86/x64 tools already present at "!VS_INSTALLED!". Skipping winget install.
-) else (
- winget install --id Microsoft.VisualStudio.2022.BuildTools -e --override "--wait --passive --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended" --accept-source-agreements --accept-package-agreements
- if errorlevel 1 (
- echo WARNING: winget could not install Visual Studio Build Tools automatically.
- echo Install manually from https://aka.ms/vs/17/release/vs_BuildTools.exe ^(select the "Desktop development with C++" workload^)
- echo and re-run this script from a "Developer Command Prompt for VS 2022".
- )
-)
-
-echo ============================================
-echo Installing OpenCL via vcpkg...
-echo ============================================
-if not exist "%VCPKG_DIR%" (
- git clone https://github.com/microsoft/vcpkg "%VCPKG_DIR%"
- cd /d "%VCPKG_DIR%"
- call bootstrap-vcpkg.bat
- call vcpkg integrate install
-)
-cd /d "%VCPKG_DIR%"
-call vcpkg install opencl
-
-cd /d "%SCRIPT_DIR%"
-
-REM ============================================
-REM Clone llama.cpp if missing
-REM ============================================
-if not exist "llama.cpp\CMakeLists.txt" (
- echo Cloning llama.cpp...
- git clone https://github.com/ggml-org/llama.cpp
-)
-
-cd /d "llama.cpp"
-set "SCRIPT_DIR=%CD%"
-
-REM ============================================
-REM Setup OpenVINO: download & extract to C:\Intel\openvino_%OPENVINO_VERSION_MAJOR%,
-REM then point C:\Intel\openvino at it via a directory junction (mklink /J).
-REM ============================================
-
-if exist "%OPENVINO_INSTALL_DIR%\setupvars.bat" (
- 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_ZIP%" "%OPENVINO_URL%"
- if errorlevel 1 (
- echo ERROR: Download failed.
- exit /b 1
- )
-
- echo Extracting OpenVINO...
- if exist "%OPENVINO_EXTRACT_TMP%" rmdir /s /q "%OPENVINO_EXTRACT_TMP%"
- mkdir "%OPENVINO_EXTRACT_TMP%"
- tar -xf "%OPENVINO_ZIP%" -C "%OPENVINO_EXTRACT_TMP%"
- if errorlevel 1 (
- echo ERROR: Extraction failed.
- exit /b 1
- )
-
- REM Move the single top-level folder contents into the versioned install dir.
- set "OPENVINO_EXTRACTED="
- for /d %%i in ("%OPENVINO_EXTRACT_TMP%\*") do set "OPENVINO_EXTRACTED=%%i"
- if not defined OPENVINO_EXTRACTED (
- echo ERROR: Could not locate extracted OpenVINO folder under "%OPENVINO_EXTRACT_TMP%".
- exit /b 1
- )
- if not exist "%OPENVINO_INSTALL_DIR%" mkdir "%OPENVINO_INSTALL_DIR%"
- xcopy /e /i /y /q "!OPENVINO_EXTRACTED!\*" "%OPENVINO_INSTALL_DIR%\" >nul
- if errorlevel 1 (
- echo ERROR: Failed to copy OpenVINO from "!OPENVINO_EXTRACTED!" to "%OPENVINO_INSTALL_DIR%".
- echo Re-run this script from an elevated Command Prompt ^(Run as administrator^) if access is denied.
- exit /b 1
- )
-
- rmdir /s /q "%OPENVINO_EXTRACT_TMP%"
- del "%OPENVINO_ZIP%"
-)
-
-REM Refresh junction: C:\Intel\openvino -> C:\Intel\openvino_<version>.
-REM `mklink /J` creates a directory junction (no admin / Developer Mode required).
-if exist "%OPENVINO_LINK_DIR%" rmdir "%OPENVINO_LINK_DIR%"
-mklink /J "%OPENVINO_LINK_DIR%" "%OPENVINO_INSTALL_DIR%" >nul
-if errorlevel 1 (
- echo ERROR: Failed to create junction "%OPENVINO_LINK_DIR%" -^> "%OPENVINO_INSTALL_DIR%".
- echo If "%OPENVINO_LINK_DIR%" already exists as a regular non-empty folder, remove it manually and re-run.
- exit /b 1
-)
-
-set "OPENVINO_ROOT=%OPENVINO_LINK_DIR%"
-echo OpenVINO Ready: %OPENVINO_ROOT% -^> %OPENVINO_INSTALL_DIR%
-
-
-echo ============================================
-echo Setting up compiler environment...
-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 * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do (
- set "VS_PATH=%%i"
- )
-)
-if defined VS_PATH (
- call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" >nul
-) else (
- echo WARNING: Visual Studio Build Tools not found. Compiler may be missing.
-)
-
-REM ============================================
-REM Clean old build cache
-REM ============================================
-if exist "build\ReleaseOV" (
- echo Removing old build directory ...
- rmdir /s /q "build\ReleaseOV"
-)
-
-echo ============================================
-echo Configuring with CMake...
-echo ============================================
-call "%OPENVINO_ROOT%\setupvars.bat" >nul 2>nul
-
-cmake -B build\ReleaseOV -G Ninja ^
- -DCMAKE_BUILD_TYPE=Release ^
- -DGGML_OPENVINO=ON ^
- -DCMAKE_TOOLCHAIN_FILE="%VCPKG_DIR%\scripts\buildsystems\vcpkg.cmake"
-
-if errorlevel 1 (
- echo If you continue to face CMAKE errors, make sure to install:
- echo winget install Microsoft.VisualStudio.2022.BuildTools
- echo Then run the "Developer Command Prompt for VS 2022" and launch this script from there.
- exit /b 1
-)
-
-cmake --build build\ReleaseOV --config Release
-if errorlevel 1 exit /b 1
-
-echo ============================================
-echo Build completed successfully!
-echo ============================================
-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 build\ReleaseOV\bin\llama-cli.exe -m model.gguf
-echo.
-
-endlocal
-```
-
-> [!NOTE]
-> 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>
-
-### 3. Download Sample Model
-
-Download a sample model for testing.
-
-```bash
-mkdir -p ~/models/
-wget https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf \
- -O ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
-```
-
-<details>
-<summary><b>Windows</b></summary>
-
-```powershell
-# Windows PowerShell
-mkdir C:\models
-Invoke-WebRequest -Uri https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf -OutFile C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf
-```
-
-```cmd
-REM Windows Command Prompt
-mkdir C:\models
-curl -L https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf -o C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf
-```
-
-</details>
+- Windows: install OpenVINO in a path without spaces, such as `C:\Intel\openvino`. Some CMake and Ninja toolchains have quoting problems with `C:\Program Files (x86)\...`.
+- Run the setupvars script of your shell in each new shell, also before you start the binaries: `setupvars.sh` in bash, `setupvars.bat` in cmd, `& "C:\Intel\openvino\setupvars.ps1"` in PowerShell.
-### 4. Run Inference with OpenVINO Backend
-
-The first run of a model converts and compiles it for the device. This takes seconds on CPU and GPU, and can take minutes on the NPU for large models. Later tokens are faster, and the [compiled model cache](#compiled-model-cache) makes later runs start faster.
-
-> [!NOTE]
-> Default context size is set to the model training context, which may be very large. For example, 131072 for Llama 3.2 1B, which may result in lower performance, especially on edge/laptop devices. Use `-c` to limit context size in supported llama.cpp tools for better performance:
-> - CPU and GPU: for example `-c 1024`.
-> - NPU: keep the context small, for example `-c 512`, or `-c 256` for larger models. Decode may slow down as the context grows.
+## Docker
```bash
-# If the device is unset, the CPU is used.
-export GGML_OPENVINO_DEVICE=GPU
-# To run llama-simple:
-./build/ReleaseOV/bin/llama-simple -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -n 50 "The story of AI is "
-# 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:
-./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
-./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512
-```
-
-<details>
-<summary><b>Windows</b></summary>
-
-```cmd
-REM Windows Command Prompt
-set GGML_OPENVINO_DEVICE=GPU
-REM To run llama-simple:
-build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -n 50 "The story of AI is "
-REM To run in chat mode:
-build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 1024
-REM To run llama-bench:
-build\ReleaseOV\bin\llama-bench.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf"
-
-REM NPU: keep the context small.
-set GGML_OPENVINO_DEVICE=NPU
-build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 512
-```
-
-```powershell
-# Windows PowerShell
-$env:GGML_OPENVINO_DEVICE = "GPU"
-build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 1024
-
-# NPU: keep the context small.
-$env:GGML_OPENVINO_DEVICE = "NPU"
-build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 512
-```
-
-</details>
-
-> [!NOTE]
-> - Select the OpenVINO device with `GGML_OPENVINO_DEVICE`, not with `-dev`.
-> - 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.
-> - See [OpenVINO GPU Device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html) for more details.
-
-### 5. Docker Build
-
-You can build and run llama.cpp with OpenVINO backend using Docker.
-
-<details>
-<summary><b>Build the images</b></summary>
-
-```bash
-# Build the base runtime image with compiled shared libraries and minimal dependencies.
-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 image with the llama, llama-cli and llama-completion executables.
+# Build the light image (llama-cli) and run it on the CPU, with the models in ~/models
docker build --target=light -t llama-openvino:light -f .devops/openvino.Dockerfile .
-
-# 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:
-docker build --build-arg http_proxy=$http_proxy --build-arg https_proxy=$https_proxy --target=server -t llama-openvino:server -f .devops/openvino.Dockerfile .
-```
-
-</details>
-
-<details>
-<summary><b>Run a container</b> (CPU, GPU, NPU)</summary>
-
-Run llama.cpp with OpenVINO backend Docker container. Save sample models in `~/models` as [shown above](#3-download-sample-model). It will be mounted to the container in the examples below.
-
-```bash
-# Run Docker container
docker run --rm -it -v ~/models:/models llama-openvino:light --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
-
-# With Intel GPU access (iGPU or dGPU)
-docker run --rm -it -v ~/models:/models \
---device=/dev/dri --group-add=$(stat -c "%g" /dev/dri/render* | head -n 1) -u $(id -u):$(id -g) \
---env=GGML_OPENVINO_DEVICE=GPU \
-llama-openvino:light --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
-
-# With Intel NPU access
-docker run --rm -it -v ~/models:/models \
---device=/dev/accel --group-add=$(stat -c "%g" /dev/accel/accel* | head -n 1) -u $(id -u):$(id -g) \
---env=GGML_OPENVINO_DEVICE=NPU \
-llama-openvino:light --no-warmup -c 512 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
-```
-
-</details>
-
-<details>
-<summary><b>Run llama-server</b> (container or local build) and test it</summary>
-
-```bash
-# Run the llama-openvino:server Docker container (CPU)
-docker run --rm -it -p 8080:8080 -v ~/models:/models llama-openvino:server --no-warmup -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 --host 0.0.0.0
-
-# Run the llama-openvino:server Docker container with Intel GPU access (iGPU or dGPU)
-docker run --rm -it -v ~/models:/models \
---device=/dev/dri --group-add=$(stat -c "%g" /dev/dri/render* | head -n 1) -u $(id -u):$(id -g) \
--p 8080:8080 --env=GGML_OPENVINO_DEVICE=GPU \
-llama-openvino:server --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --host 0.0.0.0
-
-# Run the llama-openvino:server Docker container with Intel NPU access
-docker run --rm -it -v ~/models:/models \
---device=/dev/accel --group-add=$(stat -c "%g" /dev/accel/accel* | head -n 1) -u $(id -u):$(id -g) \
--p 8080:8080 --env=GGML_OPENVINO_DEVICE=NPU \
-llama-openvino:server --no-warmup -c 512 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --host 0.0.0.0
-
-# Or Using llama-server executable
-./build/ReleaseOV/bin/llama-server -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --port 8080 -c 1024
-
-# Option 1: Open your browser to http://localhost:8080 to open Llama Chat, the built-in chat app of the llama.cpp server.
-# Option 2: In a NEW terminal, test the server with curl
-
-# If you are behind a proxy, make sure to set NO_PROXY to avoid proxy for localhost
-export NO_PROXY=localhost,127.0.0.1
-
-# Test health endpoint
-curl -f http://localhost:8080/health
-
-# Test with a simple prompt
-curl -X POST "http://localhost:8080/v1/chat/completions" -H "Content-Type: application/json" \
- -d '{"messages":[{"role":"user","content":"Write a poem about OpenVINO"}],"max_tokens":100}' | jq .
```
-</details>
+Prebuilt images, the other targets, GPU and NPU access, and llama-server: [Docker](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#docker).
-## Runtime Configuration
+## Configuration
-The backend needs no environment variable: it runs on the CPU with its defaults. Set `GGML_OPENVINO_DEVICE` to use the GPU or the NPU. All other variables are optional.
-
-```bash
-export GGML_OPENVINO_DEVICE=GPU # String
-export GGML_OPENVINO_PROFILING=1 # Integer
-export GGML_OPENVINO_EXACT_ZERO_POINT=1 # Boolean: 1 (on) or 0 (off)
-
-# Show the variables in effect (log verbosity 4)
-./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 -lv 4 2>&1 | grep "settings from the environment"
-```
+The backend needs no environment variable. It runs on the CPU with its defaults. Set `GGML_OPENVINO_DEVICE` to use the GPU or the NPU. All other variables are optional.
- The backend reads the variables once, at start. Unset or empty means the default.
-- 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:
+- Boolean values are `1` (on) and `0` (off).
+- A value that is not valid stops the backend. A `GGML_OPENVINO_*` name that the backend does not know gives a warning.
+- `-lv 4` logs the variables in effect, on the `settings from the environment` line.
+- To lower the memory that a model needs, see [Lower memory use](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#lower-memory-use).
```text
ggml-openvino: GGML_OPENVINO_EXACT_ZERO_POINT=yes is not valid, use 1 (on) or 0 (off)
@@ -846,46 +306,24 @@ ggml-openvino: unknown environment variable GGML_OPENVINO_DEVCE is ignored
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
-| `GGML_OPENVINO_DEVICE` | all | String | `CPU` | Target device: `CPU`, `GPU` or `NPU`. For several GPUs, see the [device notes](#4-run-inference-with-openvino-backend). Examples: `GGML_OPENVINO_DEVICE=NPU`, `GGML_OPENVINO_DEVICE=GPU.0,GPU.1`. |
-| `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` | all | String | `not set` | Directory for the backend's cache of compiled models. A later start with the same model and settings loads faster. See [Compiled model cache](#compiled-model-cache). Example: `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache`. |
-| `GGML_OPENVINO_NPU_CONFIG` | NPU | String | `not set` | OpenVINO properties for the NPU plugin, as comma-separated `KEY=VALUE` pairs. See [Plugin properties](#plugin-properties). Example: `GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN"`. |
-| `GGML_OPENVINO_GPU_CONFIG` | GPU | String | `not set` | OpenVINO properties for the GPU plugin, as comma-separated `KEY=VALUE` pairs. See [Plugin properties](#plugin-properties). Example: `GGML_OPENVINO_GPU_CONFIG="INFERENCE_PRECISION_HINT=f16"`. |
-| `GGML_OPENVINO_CPU_CONFIG` | CPU | String | `not set` | OpenVINO properties for the CPU plugin, as comma-separated `KEY=VALUE` pairs. See [Plugin properties](#plugin-properties). Example: `GGML_OPENVINO_CPU_CONFIG="INFERENCE_PRECISION_HINT=f16"`. |
-| `GGML_OPENVINO_PROFILING` | all | Integer | `0` | `1` logs execution timing. `2` or higher also turns on OpenVINO and OpenCL profiling. Example: `GGML_OPENVINO_PROFILING=1`. |
+| `GGML_OPENVINO_DEVICE` | all | String | `CPU` | Target device: `CPU`, `GPU`, `NPU`, or `GPU.0`, `GPU.1` with several GPUs. A list such as `GPU.0,GPU.1` with `-sm layer` splits a model across GPUs. See [device selection](#supported-devices). |
+| `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` | all | String | `not set` | Directory for the cache of compiled models. Later starts with the same model and settings load faster. See [Compiled model cache](#compiled-model-cache). |
+| `GGML_OPENVINO_NPU_CONFIG` | NPU | String | `not set` | OpenVINO properties for the NPU plugin. See [Plugin properties](#plugin-properties). |
+| `GGML_OPENVINO_GPU_CONFIG` | GPU | String | `not set` | OpenVINO properties for the GPU plugin. See [Plugin properties](#plugin-properties). |
+| `GGML_OPENVINO_CPU_CONFIG` | CPU | String | `not set` | OpenVINO properties for the CPU plugin. See [Plugin properties](#plugin-properties). |
+| `GGML_OPENVINO_PROFILING` | all | Integer | `0` | `1` logs execution timing. `2` or higher also turns on OpenVINO and OpenCL profiling. See [Profiling](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#profiling-and-debug-dumps). |
### Plugin properties
-`GGML_OPENVINO_NPU_CONFIG`, `GGML_OPENVINO_GPU_CONFIG` and `GGML_OPENVINO_CPU_CONFIG` pass OpenVINO plugin properties to the device in their name.
-
-```bash
-# Format: comma-separated KEY=VALUE pairs. The backend uses the variable of the selected device only.
-export GGML_OPENVINO_DEVICE=NPU
-export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=4"
-
-# CPU: compute in FP16, as the GPU and the NPU do. This helps to debug the accuracy of a quantized model.
-export GGML_OPENVINO_DEVICE=CPU
-export GGML_OPENVINO_CPU_CONFIG="INFERENCE_PRECISION_HINT=f16"
-```
+`GGML_OPENVINO_NPU_CONFIG`, `GGML_OPENVINO_GPU_CONFIG` and `GGML_OPENVINO_CPU_CONFIG` pass OpenVINO plugin properties to the device in their name. The backend uses the variable of the selected device only.
+- Format: comma-separated `KEY=VALUE` pairs, for example `GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=4"`.
- 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. Exception: `CACHE_DIR` and `CACHE_MODE` with `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`.
+- The backend applies the variable last, so it overrides the properties that the backend sets. Exceptions: with `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, the backend sets `CACHE_DIR` and `CACHE_MODE` itself, and on the NPU also `NPUW_WEIGHTS_BANK`.
- 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.
- - 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.
-
-```bash
-# Values: DRIVER (the compiler in the NPU driver; backend default), PLUGIN (the compiler in OpenVINO),
-# PREFER_PLUGIN (OpenVINO default: PLUGIN when it is available, DRIVER if not).
-export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN" # recommended form
-export GGML_OPENVINO_NPU_COMPILER_TYPE=PLUGIN # older name, still works
-```
+- `NPU_COMPILER_TYPE` selects the NPU compiler: `DRIVER` (in the NPU driver; backend default), `PLUGIN` (in OpenVINO) or `PREFER_PLUGIN` (`PLUGIN` when it is available, `DRIVER` if not).
+- The properties that the backend sets: [NPU](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#npu-plugin-properties), [GPU and CPU](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#gpu-and-cpu-plugin-properties).
+- All properties and their values: [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).
### Advanced tuning
@@ -896,195 +334,88 @@ The defaults fit most models. The variables below trade one property for another
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
-| `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 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. 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. |
+| `GGML_OPENVINO_PREFILL_CHUNK_SIZE` | NPU | Integer | `256` | Tokens in one NPU prefill step. A larger value can make long prompts faster and makes the first load longer. Zero or less means the default. |
+| `GGML_OPENVINO_KV_ONLY_PREFILL` | NPU | Boolean | `1` | Gemma 3n and Gemma 4 E2B/E4B: the prefill graph only writes the KV cache, and one decode step computes the output token. Not for models with recurrent state. `0` turns it off. See [KV-only prefill](../../ggml/src/ggml-openvino/dev_doc/README.md#kv-only-prefill). |
+| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | Layout of a `Q6_K` `token_embd.weight` on the NPU: `q8_0_c`, `f16`, `q4_0_128` or `q4_0_c`. When set, it also applies to `Q4_K` and `Q5_K`. The 4-bit layouts use less memory and can lower accuracy. With host gather on, a table of 64 MiB or more is not converted, so only a tied output layer changes. |
+| `GGML_OPENVINO_NPU_HOST_GATHER` | NPU | Boolean | `1` | Read the rows of embedding tables of 64 MiB or more on the host, from the GGUF data. Such a table is then not converted for the NPU. Lowers memory use. `0` turns it off. See [NPU host gather](../../ggml/src/ggml-openvino/dev_doc/README.md#npu-host-gather). |
+| `GGML_OPENVINO_ROPE_SINCOS` | all | String | `auto` | Where RoPE computes cos/sin. f16 angles lose accuracy at long positions. `host`: f32 tables on the host; static graphs (NPU), normal and NeoX RoPE only. `device`: on the device. `device_f32`: on the device with the angle in f32, for long prompts on the GPU. `auto`: `host` on the NPU, `device` elsewhere. |
+| `GGML_OPENVINO_GDN_DECOMPOSE` | all | Boolean | auto | Translate `GATED_DELTA_NET` (Qwen3.5) into MatMul operations. Static path only (NPU). Unset: on for the Lunar Lake NPU, off elsewhere. 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. 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 4 bits instead of `Q8_0_C`: `q4_asym64`, `q4_asym64_all` (also `Q4_K`, `Q8_0`, `Q5_1`, `Q5_0`), `q4_sym128`, `q4_sym128_all` (also `Q4_K`), or `native` (none). GPU with `Q4_K_M`: use `q4_asym64_all`, `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 `native`) instead of an integer one. Higher accuracy, lower speed. MoE expert weights always use it. |
</details>
### Compiled model cache
-The cache keeps compiled models on disk, so later starts of the same model load faster. Use the same model and the same settings in every run.
-
-```bash
-# CPU or GPU: the first run compiles the model and writes the cache. Later runs read it.
-export GGML_OPENVINO_DEVICE=GPU
-export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
-./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
-
-# CPU or GPU, later runs (optional): require the cached model and skip the weight upload and the compilation.
-export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1
-
-# NPU: valid cached models are imported. Otherwise the run compiles them, writes them without weights plus one
-# shared weights file, and logs a warning.
-export GGML_OPENVINO_DEVICE=NPU
-export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
-./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512
-
-# NPU, later runs (optional): use less memory. The run fails if a cached model is missing.
-export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
-```
-
-<details>
-<summary><b>Cache variables</b></summary>
+The cache keeps compiled models on disk, so later starts of the same model load faster. Use the same model and the same settings in every run. Recipes: [Compiled model cache](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#compiled-model-cache). Internals and restrictions: [Compiled model cache](../../ggml/src/ggml-openvino/dev_doc/README.md#compiled-model-cache).
| 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. 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_COMPILED_MODEL_CACHE_ONLY` | CPU, GPU | Boolean | `0` | Require the cached model and skip the weight upload and the compilation. Needs mmap loading and a model that runs fully on OpenVINO. Not for MoE models on CPU. |
+| `GGML_OPENVINO_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Use the memory-mapped GGUF file as the model buffer, which lowers the host memory peak. Fails if a cached model is missing. |
| `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/dev_doc/README.md#compiled-model-cache) for the workflow and the restrictions.
-
-</details>
-
### Deprecated
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
| `GGML_OPENVINO_STATEFUL_EXECUTION` | CPU, GPU | Boolean | `0` | **Deprecated**, to be removed. Keep the KV cache inside the OpenVINO model. Use the default, stateless execution (`0`). |
-<details>
-<summary>Limits of stateful execution</summary>
+### Developer variables
-- 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.
-- 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>
-
-### Debugging and development
-
-Debug output, switches that turn a default optimization off, experimental options and older variable names are in the [developer documentation](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md).
-
-### Example Usage
-
-#### GPU Inference with Profiling
-
-```bash
-export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
-export GGML_OPENVINO_PROFILING=1
-export GGML_OPENVINO_DEVICE=GPU
-
-./build/ReleaseOV/bin/llama-simple -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -n 50 "The story of AI is "
-```
-
-<details>
-<summary><b>Windows</b></summary>
-
-```cmd
-REM Windows Command Prompt
-set GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=C:\tmp\ov_cache
-set GGML_OPENVINO_PROFILING=1
-set GGML_OPENVINO_DEVICE=GPU
-build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -n 50 "The story of AI is "
-```
-
-```powershell
-# Windows PowerShell
-$env:GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR = "C:\tmp\ov_cache"
-$env:GGML_OPENVINO_PROFILING = "1"
-$env:GGML_OPENVINO_DEVICE = "GPU"
-build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -n 50 "The story of AI is "
-```
-
-</details>
+Debug output, switches that turn a default optimization off, experimental options, memory options and older variable names are in [OpenVINO-ENV-VARS.md](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md).
## Known Limitations
**General (all devices)**
-- 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)):
+- The backend supports a subset of GGML ops. An unsupported op, or an unsupported shape or case of an op, fails 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. Audio input is a work in progress. See [Image input](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#image-input) and [Multimodal](../../ggml/src/ggml-openvino/dev_doc/README.md#multimodal).
+- Qwen3-VL image input:
- 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`.
+ - **Workaround:** `--image-max-tokens 256`. With `-ub 128` alone, a large image can still run out of memory.
- 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`. On CPU and GPU, the perplexity is slightly higher than with the ggml CPU backend.
+- llama.cpp tool coverage is not uniform across CPU, GPU and NPU.
+- Mamba-based models (for example Falcon-H1): on CPU and GPU, the perplexity is slightly higher than with the ggml CPU backend.
**GPU-specific**
-- Muse-Glimmer-30B with a DFlash draft needs a 64 GB system (peak about 45 GB of RAM):
-
- ```bash
- export GGML_OPENVINO_DEVICE=GPU
- export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill # local disk, not tmpfs
- export GGML_OPENVINO_ROPE_F32_ANGLE=1 # long prompts
- mkdir -p $GGML_OPENVINO_SPILL_DIR
- ./build/ReleaseOV/bin/llama-server -m Muse-Glimmer-30B-Q4_K_M.gguf -md <dflash-draft>.gguf \
- --spec-type draft-dflash --spec-draft-n-max 4
- ```
+- Muse-Glimmer-30B with a DFlash draft needs a 64 GB system (peak about 45 GB of RAM). See [Muse-Glimmer-30B](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#muse-glimmer-30b-with-a-dflash-draft-on-the-gpu).
- Multiple GPUs (`GGML_OPENVINO_DEVICE=GPU.0,GPU.1` with `-sm layer`):
- - `-sm tensor` is not supported.
+ - `-sm tensor` is not supported. Context creation fails with `Context was not initialized using remote implementation`.
- Copies between GPUs go through host memory. There is no asynchronous copy and no peer-to-peer copy.
- Only GPUs can be combined. A list with several NPUs, or with a GPU and the CPU or the NPU, is rejected.
-- MoE models use the GPU plugin's fused MoE op, which runs in f16 only:
- - granitemoe models (e.g. `granite-3.1-1b-a400m`) give wrong output.
- - **Workaround:** `GGML_OPENVINO_MOE_OP=0`. Output is correct, but prompt processing is much slower.
+- MoE models run in f16 only on the GPU, with or without the fused MoE op (`GGML_OPENVINO_MOE_OP`):
+ - granitemoe models (for example `granite-3.1-1b-a400m`) can give wrong output (one repeated token) after a short prompt.
+ - **Workaround:** `GGML_OPENVINO_MOE_OP=0`. The output is correct, but prompt processing is much slower.
- `GGML_OPENVINO_GPU_CONFIG="INFERENCE_PRECISION_HINT=f32"` fails to compile.
-- `llama-perplexity` with MoE models: set `-b` to the same value as `-c`, so that each batch holds one sequence.
+- `llama-perplexity` with MoE models: set `-b` to the `-c` value, so that each batch holds one sequence.
**NPU-specific**
-- Default context resolves to the model's training context (e.g. 131072 for Llama 3.2 1B), which can OOM or fail or degrade performance on NPU. Inspect the resolved value with `-lv 3`.
- - **Workaround:** Pass an explicit `-c <N>`, e.g. `-c 512`.
-- NPU device uses a static graph with a fixed prefill chunk size (defaults to 256), configurable with `GGML_OPENVINO_PREFILL_CHUNK_SIZE`. Large prefill/batch settings may need tuning.
-- `llama-server -np > 1` (multiple parallel sequences) is not supported.
-- `llama-perplexity`: requires `-b 512` or smaller.
-- Flash attention must stay on, which is the default (`-fa auto`). With `-fa off`, the run fails on the NPU.
-- `llama-embedding` fails on the NPU.
-- Mamba-based models (e.g. Falcon-H1) fail on the NPU with `Failed to set tensor` (element type mismatch).
+- The default context is the training context of the model (for example 131072 for Llama 3.2 1B). On the NPU, this can run out of memory, fail or lower performance. `-lv 3` shows the value in use.
+ - **Workaround:** pass `-c <N>`, for example `-c 512`. See [NPU context and prefill chunk](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#npu-context-and-prefill-chunk).
+- The NPU uses a static graph with a fixed prefill chunk size (default 256), set with `GGML_OPENVINO_PREFILL_CHUNK_SIZE`. Large prefill or batch settings can need tuning.
+- `llama-server -np N` with N greater than 1 needs the unified KV cache (`-kvu`). Without it, requests fail with `n_seq > 1 is not supported on NPU`. Without `-np`, llama-server uses 4 slots with the unified KV cache. See [llama-server](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#llama-server).
+- `llama-perplexity`: set `-b` to at most `-c`, so that each batch holds one sequence, and `-ub` to the prefill chunk size (default 256). With the default `-ub 512`, the result at `-c 1024` and above is wrong. See [Embeddings and perplexity](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#embeddings-and-perplexity).
+- Flash attention must stay on, which is the default (`-fa auto`). With `-fa off`, the run fails on the NPU. llama-server with the unified KV cache turns flash attention off by itself, and that case runs.
+- Embedding models do not work on the NPU. BERT models (bge-m3, nomic-embed-text) fail. Qwen3-Embedding runs, but its embeddings differ from the CPU ones.
+- Mamba-based models (for example Falcon-H1) do not run on the NPU. The process stops with a floating-point exception (SIGFPE) during the NPU compilation.
- 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: `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=f16` and `q4_0_128` can give wrong output. Keep the default.
+ - **Workaround:** pass the smallest context that fits the use, for example `-c 512`, or `-c 256` for larger models.
- 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).
+- Lunar Lake NPU with NPU driver 1.39.1: with `GGML_OPENVINO_NPU_HOST_GATHER=0`, `gemma-4-E2B` and `gemma-4-E4B` fail to compile (`ZE_RESULT_ERROR_INVALID_ARGUMENT`). Keep the default (`1`).
+- The first load of a model on the NPU compiles it for the device. This can take minutes for large models.
+ - **Workaround:** use the [compiled model cache](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#npu-gemma-4-e2b-example).
- `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.
+ - Requires OpenVINO 2026.5 or later.
+ - A 35B MoE model needs nearly all of a 32 GB system. Use a small context and the settings in [Qwen3.6-35B-A3B on the NPU](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#qwen36-35b-a3b-on-the-npu).
- `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.
-
## Work in Progress
- Performance and memory optimizations
diff --git a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md
new file mode 100644
index 000000000..09a45d74a
--- /dev/null
+++ b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md
@@ -0,0 +1,806 @@
+# llama.cpp OpenVINO backend cookbook
+
+Recipes for the OpenVINO backend, one section per task.
+
+- Quick Start, supported devices, build basics and the user environment variables: [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md).
+- Internals: [developer documentation](README.md). Developer variables: [OpenVINO-ENV-VARS.md](OpenVINO-ENV-VARS.md).
+
+```bash
+# The examples assume a Linux build in build/ReleaseOV, models in ~/models, and OpenVINO set up in the shell
+source /opt/intel/openvino/setupvars.sh
+```
+
+## Contents
+
+- [Build from source](#build-from-source)
+ - [Ubuntu build script](#ubuntu-build-script)
+ - [Windows build script](#windows-build-script)
+- [Docker](#docker)
+- [Run on each device](#run-on-each-device)
+ - [Linux](#linux)
+ - [Windows](#windows)
+ - [llama-server](#llama-server)
+ - [NPU context and prefill chunk](#npu-context-and-prefill-chunk)
+ - [Multiple GPUs](#multiple-gpus)
+- [Compiled model cache](#compiled-model-cache)
+ - [CPU and GPU](#cpu-and-gpu)
+ - [NPU: gemma-4 E2B example](#npu-gemma-4-e2b-example)
+- [Lower memory use](#lower-memory-use)
+- [Large MoE models](#large-moe-models)
+ - [Qwen3.6-35B-A3B on the NPU](#qwen36-35b-a3b-on-the-npu)
+ - [Muse-Glimmer-30B with a DFlash draft on the GPU](#muse-glimmer-30b-with-a-dflash-draft-on-the-gpu)
+- [Speculative decoding](#speculative-decoding)
+- [Image input](#image-input)
+- [Embeddings and perplexity](#embeddings-and-perplexity)
+- [Profiling and debug dumps](#profiling-and-debug-dumps)
+
+## Build from source
+
+The scripts install the build prerequisites and OpenVINO Runtime 2026.5. Then they build llama.cpp with the OpenVINO backend in `llama.cpp/build/ReleaseOV`.
+
+- The scripts do not install the GPU and NPU drivers. The Ubuntu script installs only the `intel-opencl-icd` package of the distribution. See [Prerequisites](../../../../docs/backend/OPENVINO.md#prerequisites).
+- The scripts pin OpenVINO 2026.5 in `OPENVINO_VERSION_MAJOR` and `OPENVINO_VERSION_FULL`. Edit them to use another release.
+
+### Ubuntu build script
+
+The script installs the build tools and the OpenCL ICD, downloads and sets up OpenVINO Runtime, and builds llama.cpp with Ninja. Save it as `build-llamacpp-ov.sh` in the folder where the `llama.cpp` folder goes, then run it:
+
+```bash
+chmod +x build-llamacpp-ov.sh
+./build-llamacpp-ov.sh
+```
+
+```bash
+#!/usr/bin/env bash
+# ============================================
+# llama.cpp OpenVINO Build Script (Ninja)
+# ============================================
+set -euo pipefail
+
+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"
+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 libssl-dev libtbb12 \
+ cmake ninja-build python3-pip \
+ curl wget tar git
+
+echo "============================================"
+echo "Installing OpenCL runtime + headers..."
+echo "============================================"
+sudo apt-get install -y \
+ ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd
+
+cd "${SCRIPT_DIR}"
+
+# ============================================
+# Clone llama.cpp if missing
+# ============================================
+if [[ ! -f "llama.cpp/CMakeLists.txt" ]]; then
+ echo "Cloning llama.cpp..."
+ git clone https://github.com/ggml-org/llama.cpp
+fi
+
+# ============================================
+# Setup OpenVINO: download & extract to /opt/intel/openvino_${OPENVINO_VERSION_MAJOR}, then point /opt/intel/openvino at it via symlink so the active version is swappable.
+# ============================================
+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 -fL -o "${OPENVINO_TGZ}" "${OPENVINO_URL}"
+
+ echo "Extracting OpenVINO to ${OPENVINO_INSTALL_DIR}..."
+ sudo mkdir -p "${OPENVINO_INSTALL_DIR}"
+ sudo tar -xzf "${OPENVINO_TGZ}" -C "${OPENVINO_INSTALL_DIR}" --strip-components=1
+ rm -f "${OPENVINO_TGZ}"
+fi
+
+# Refresh symlink: /opt/intel/openvino -> /opt/intel/openvino_${OPENVINO_VERSION_MAJOR}
+sudo ln -sfn "${OPENVINO_INSTALL_DIR}" "${OPENVINO_LINK_DIR}"
+
+OPENVINO_ROOT="${OPENVINO_LINK_DIR}"
+echo "OpenVINO Ready: ${OPENVINO_ROOT} -> ${OPENVINO_INSTALL_DIR}"
+
+# Install OpenVINO's own runtime dependencies (one-time per system).
+if [[ -x "${OPENVINO_ROOT}/install_dependencies/install_openvino_dependencies.sh" ]]; then
+ echo "============================================"
+ echo "Installing OpenVINO runtime dependencies..."
+ echo "============================================"
+ echo "Y" | sudo -E "${OPENVINO_ROOT}/install_dependencies/install_openvino_dependencies.sh"
+fi
+
+# ============================================
+# Clean old build cache
+# ============================================
+cd "${SCRIPT_DIR}/llama.cpp"
+if [[ -d "build/ReleaseOV" ]]; then
+ echo "Removing old build directory..."
+ rm -rf "build/ReleaseOV"
+fi
+
+echo "============================================"
+echo "Configuring with CMake..."
+echo "============================================"
+set +u
+source "${OPENVINO_ROOT}/setupvars.sh"
+set -u
+
+cmake -B build/ReleaseOV -G Ninja \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DGGML_OPENVINO=ON
+
+cmake --build build/ReleaseOV --parallel
+
+echo "============================================"
+echo "Build completed successfully!"
+echo "============================================"
+echo "Binaries: $(pwd)/build/ReleaseOV/bin"
+echo
+echo "NOTE: To run, source setupvars.sh and pick a device:"
+echo " source /opt/intel/openvino/setupvars.sh"
+echo " export GGML_OPENVINO_DEVICE=CPU # or GPU / NPU"
+echo " ./build/ReleaseOV/bin/llama-cli -m model.gguf"
+```
+
+### Windows build script
+
+The script installs Git, Ninja, CMake, Visual Studio 2022 Build Tools and OpenCL (with vcpkg). Then it downloads OpenVINO Runtime and builds llama.cpp with Ninja. Save it as `build-llamacpp-ov.bat` in the folder where the `llama.cpp` folder goes, then run it from Command Prompt or PowerShell:
+
+```cmd
+:: Command Prompt
+build-llamacpp-ov.bat
+```
+
+```powershell
+# PowerShell
+.\build-llamacpp-ov.bat
+```
+
+```bat
+@echo off
+setlocal enabledelayedexpansion
+
+REM ============================================
+REM llama.cpp OpenVINO Build Script (Ninja)
+REM ============================================
+
+set "OPENVINO_VERSION_MAJOR=2026.5"
+set "OPENVINO_VERSION_FULL=2026.5.0.23836.73088206582"
+
+set "SCRIPT_DIR=%~dp0"
+set "VCPKG_DIR=C:\vcpkg"
+set "OPENVINO_INSTALL_DIR=C:\Intel\openvino_%OPENVINO_VERSION_MAJOR%"
+set "OPENVINO_LINK_DIR=C:\Intel\openvino"
+set "OPENVINO_ZIP=%SCRIPT_DIR%openvino.zip"
+set "OPENVINO_EXTRACT_TMP=%SCRIPT_DIR%openvino_extract_tmp"
+set "OPENVINO_URL=https://storage.openvinotoolkit.org/repositories/openvino/packages/%OPENVINO_VERSION_MAJOR%/windows/openvino_toolkit_windows_%OPENVINO_VERSION_FULL%_x86_64.zip"
+
+echo ============================================
+echo Installing prerequisites...
+echo ============================================
+winget install --id Git.Git -e --accept-source-agreements --accept-package-agreements 2>nul
+winget install --id Ninja-build.Ninja -e --accept-source-agreements --accept-package-agreements 2>nul
+winget install --id Kitware.CMake -e --accept-source-agreements --accept-package-agreements 2>nul
+
+REM Ensure Visual Studio Build Tools are installed.
+echo Checking for Visual Studio Build Tools...
+set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"
+set "VS_INSTALLED="
+if exist "%VSWHERE%" (
+ for /f "usebackq tokens=*" %%i in (`"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 2^>nul`) do (
+ set "VS_INSTALLED=%%i"
+ )
+)
+if defined VS_INSTALLED (
+ echo Visual Studio with VC++ x86/x64 tools already present at "!VS_INSTALLED!". Skipping winget install.
+) else (
+ winget install --id Microsoft.VisualStudio.2022.BuildTools -e --override "--wait --passive --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended" --accept-source-agreements --accept-package-agreements
+ if errorlevel 1 (
+ echo WARNING: winget could not install Visual Studio Build Tools automatically.
+ echo Install manually from https://aka.ms/vs/17/release/vs_BuildTools.exe ^(select the "Desktop development with C++" workload^)
+ echo and re-run this script from a "Developer Command Prompt for VS 2022".
+ )
+)
+
+echo ============================================
+echo Installing OpenCL via vcpkg...
+echo ============================================
+if not exist "%VCPKG_DIR%" (
+ git clone https://github.com/microsoft/vcpkg "%VCPKG_DIR%"
+ cd /d "%VCPKG_DIR%"
+ call bootstrap-vcpkg.bat
+ call vcpkg integrate install
+)
+cd /d "%VCPKG_DIR%"
+call vcpkg install opencl
+
+cd /d "%SCRIPT_DIR%"
+
+REM ============================================
+REM Clone llama.cpp if missing
+REM ============================================
+if not exist "llama.cpp\CMakeLists.txt" (
+ echo Cloning llama.cpp...
+ git clone https://github.com/ggml-org/llama.cpp
+)
+
+cd /d "llama.cpp"
+set "SCRIPT_DIR=%CD%"
+
+REM ============================================
+REM Setup OpenVINO: download & extract to C:\Intel\openvino_%OPENVINO_VERSION_MAJOR%, then point C:\Intel\openvino at it via a directory junction (mklink /J).
+REM ============================================
+
+if exist "%OPENVINO_INSTALL_DIR%\setupvars.bat" (
+ 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_ZIP%" "%OPENVINO_URL%"
+ if errorlevel 1 (
+ echo ERROR: Download failed.
+ exit /b 1
+ )
+
+ echo Extracting OpenVINO...
+ if exist "%OPENVINO_EXTRACT_TMP%" rmdir /s /q "%OPENVINO_EXTRACT_TMP%"
+ mkdir "%OPENVINO_EXTRACT_TMP%"
+ tar -xf "%OPENVINO_ZIP%" -C "%OPENVINO_EXTRACT_TMP%"
+ if errorlevel 1 (
+ echo ERROR: Extraction failed.
+ exit /b 1
+ )
+
+ REM Move the single top-level folder contents into the versioned install dir.
+ set "OPENVINO_EXTRACTED="
+ for /d %%i in ("%OPENVINO_EXTRACT_TMP%\*") do set "OPENVINO_EXTRACTED=%%i"
+ if not defined OPENVINO_EXTRACTED (
+ echo ERROR: Could not locate extracted OpenVINO folder under "%OPENVINO_EXTRACT_TMP%".
+ exit /b 1
+ )
+ if not exist "%OPENVINO_INSTALL_DIR%" mkdir "%OPENVINO_INSTALL_DIR%"
+ xcopy /e /i /y /q "!OPENVINO_EXTRACTED!\*" "%OPENVINO_INSTALL_DIR%\" >nul
+ if errorlevel 1 (
+ echo ERROR: Failed to copy OpenVINO from "!OPENVINO_EXTRACTED!" to "%OPENVINO_INSTALL_DIR%".
+ echo Re-run this script from an elevated Command Prompt ^(Run as administrator^) if access is denied.
+ exit /b 1
+ )
+
+ rmdir /s /q "%OPENVINO_EXTRACT_TMP%"
+ del "%OPENVINO_ZIP%"
+)
+
+REM Refresh junction: C:\Intel\openvino -> C:\Intel\openvino_<version>.
+REM `mklink /J` creates a directory junction (no admin / Developer Mode required).
+if exist "%OPENVINO_LINK_DIR%" rmdir "%OPENVINO_LINK_DIR%"
+mklink /J "%OPENVINO_LINK_DIR%" "%OPENVINO_INSTALL_DIR%" >nul
+if errorlevel 1 (
+ echo ERROR: Failed to create junction "%OPENVINO_LINK_DIR%" -^> "%OPENVINO_INSTALL_DIR%".
+ echo If "%OPENVINO_LINK_DIR%" already exists as a regular non-empty folder, remove it manually and re-run.
+ exit /b 1
+)
+
+set "OPENVINO_ROOT=%OPENVINO_LINK_DIR%"
+echo OpenVINO Ready: %OPENVINO_ROOT% -^> %OPENVINO_INSTALL_DIR%
+
+
+echo ============================================
+echo Setting up compiler environment...
+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 * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do (
+ set "VS_PATH=%%i"
+ )
+)
+if defined VS_PATH (
+ call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" >nul
+) else (
+ echo WARNING: Visual Studio Build Tools not found. Compiler may be missing.
+)
+
+REM ============================================
+REM Clean old build cache
+REM ============================================
+if exist "build\ReleaseOV" (
+ echo Removing old build directory ...
+ rmdir /s /q "build\ReleaseOV"
+)
+
+echo ============================================
+echo Configuring with CMake...
+echo ============================================
+call "%OPENVINO_ROOT%\setupvars.bat" >nul 2>nul
+
+cmake -B build\ReleaseOV -G Ninja ^
+ -DCMAKE_BUILD_TYPE=Release ^
+ -DGGML_OPENVINO=ON ^
+ -DCMAKE_TOOLCHAIN_FILE="%VCPKG_DIR%\scripts\buildsystems\vcpkg.cmake"
+
+if errorlevel 1 (
+ echo If you continue to face CMAKE errors, make sure to install:
+ echo winget install Microsoft.VisualStudio.2022.BuildTools
+ echo Then run the "Developer Command Prompt for VS 2022" and launch this script from there.
+ exit /b 1
+)
+
+cmake --build build\ReleaseOV --config Release
+if errorlevel 1 exit /b 1
+
+echo ============================================
+echo Build completed successfully!
+echo ============================================
+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 build\ReleaseOV\bin\llama-cli.exe -m model.gguf
+echo.
+
+endlocal
+```
+
+- In a new shell, run the setupvars script through the junction: `call "C:\Intel\openvino\setupvars.bat"` in cmd, or `& "C:\Intel\openvino\setupvars.ps1"` in PowerShell.
+- If winget cannot register Visual Studio Build Tools on the first run, install them once by hand. Then run the script again from an elevated **Developer Command Prompt for VS 2022**.
+
+## Docker
+
+The images come from [.devops/openvino.Dockerfile](../../../../.devops/openvino.Dockerfile). Prebuilt images for `linux/amd64` are on the GitHub Container Registry:
+
+```bash
+# full: all binaries and the Python tools; light: llama-cli and llama-completion; server: llama-server
+docker pull ghcr.io/ggml-org/llama.cpp:full-openvino
+docker pull ghcr.io/ggml-org/llama.cpp:light-openvino
+docker pull ghcr.io/ggml-org/llama.cpp:server-openvino
+```
+
+Build the images locally:
+
+```bash
+# Build the base runtime image with compiled shared libraries and minimal dependencies.
+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 image with the llama, llama-cli and llama-completion executables.
+docker build --target=light -t llama-openvino:light -f .devops/openvino.Dockerfile .
+
+# 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:
+docker build --build-arg http_proxy=$http_proxy --build-arg https_proxy=$https_proxy --target=server -t llama-openvino:server -f .devops/openvino.Dockerfile .
+```
+
+Run a container on the CPU, GPU or NPU. The examples mount the models in `~/models`. For a prebuilt image, use `ghcr.io/ggml-org/llama.cpp:light-openvino` instead of `llama-openvino:light`.
+
+```bash
+# Run the container on the CPU
+docker run --rm -it -v ~/models:/models llama-openvino:light --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
+
+# With Intel GPU access (iGPU or dGPU)
+docker run --rm -it -v ~/models:/models \
+--device=/dev/dri --group-add=$(stat -c "%g" /dev/dri/render* | head -n 1) -u $(id -u):$(id -g) \
+--env=GGML_OPENVINO_DEVICE=GPU \
+llama-openvino:light --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
+
+# With Intel NPU access
+docker run --rm -it -v ~/models:/models \
+--device=/dev/accel --group-add=$(stat -c "%g" /dev/accel/accel* | head -n 1) -u $(id -u):$(id -g) \
+--env=GGML_OPENVINO_DEVICE=NPU \
+llama-openvino:light --no-warmup -c 512 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
+```
+
+Run llama-server in a container. The server image listens on `0.0.0.0:8080`. Test it as in [llama-server](#llama-server).
+
+```bash
+# Run the llama-openvino:server Docker container (CPU)
+docker run --rm -it -p 8080:8080 -v ~/models:/models llama-openvino:server --no-warmup -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
+
+# Run the llama-openvino:server Docker container with Intel GPU access (iGPU or dGPU)
+docker run --rm -it -v ~/models:/models \
+--device=/dev/dri --group-add=$(stat -c "%g" /dev/dri/render* | head -n 1) -u $(id -u):$(id -g) \
+-p 8080:8080 --env=GGML_OPENVINO_DEVICE=GPU \
+llama-openvino:server --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
+
+# Run the llama-openvino:server Docker container with Intel NPU access
+docker run --rm -it -v ~/models:/models \
+--device=/dev/accel --group-add=$(stat -c "%g" /dev/accel/accel* | head -n 1) -u $(id -u):$(id -g) \
+-p 8080:8080 --env=GGML_OPENVINO_DEVICE=NPU \
+llama-openvino:server --no-warmup -c 512 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
+```
+
+## Run on each device
+
+### Linux
+
+```bash
+# If the device is unset, the CPU is used.
+export GGML_OPENVINO_DEVICE=GPU
+# To run llama-simple:
+./build/ReleaseOV/bin/llama-simple -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -n 50 "The story of AI is "
+# 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:
+./build/ReleaseOV/bin/llama-bench -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
+
+# NPU
+export GGML_OPENVINO_DEVICE=NPU
+./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512
+```
+
+### Windows
+
+Download a model:
+
+```powershell
+# Windows PowerShell
+mkdir C:\models
+Invoke-WebRequest -Uri https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf -OutFile C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf
+```
+
+```cmd
+REM Windows Command Prompt
+mkdir C:\models
+curl -L https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf -o C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf
+```
+
+Run it:
+
+```cmd
+REM Windows Command Prompt
+set GGML_OPENVINO_DEVICE=GPU
+REM To run llama-simple:
+build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -n 50 "The story of AI is "
+REM To run in chat mode:
+build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 1024
+REM To run llama-bench:
+build\ReleaseOV\bin\llama-bench.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf"
+
+REM NPU
+set GGML_OPENVINO_DEVICE=NPU
+build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 512
+```
+
+```powershell
+# Windows PowerShell
+$env:GGML_OPENVINO_DEVICE = "GPU"
+build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 1024
+
+# NPU
+$env:GGML_OPENVINO_DEVICE = "NPU"
+build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 512
+```
+
+### llama-server
+
+```bash
+export GGML_OPENVINO_DEVICE=GPU
+./build/ReleaseOV/bin/llama-server -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --port 8080 -c 1024
+
+# Option 1: open http://localhost:8080 in a browser for Llama Chat, the built-in chat app of llama-server.
+# Option 2: test the server with curl, from a new terminal.
+
+# Behind a proxy, keep localhost off the proxy
+export NO_PROXY=localhost,127.0.0.1
+
+# Health endpoint
+curl -f http://localhost:8080/health
+
+# A simple prompt
+curl -X POST "http://localhost:8080/v1/chat/completions" -H "Content-Type: application/json" \
+ -d '{"messages":[{"role":"user","content":"Write a poem about OpenVINO"}],"max_tokens":100}' | jq .
+
+# NPU: several slots need the unified KV cache (-kvu). Without -np, llama-server uses 4 slots with it.
+export GGML_OPENVINO_DEVICE=NPU
+./build/ReleaseOV/bin/llama-server -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --port 8080 -c 1024 -np 2 -kvu
+```
+
+### NPU context and prefill chunk
+
+```bash
+export GGML_OPENVINO_DEVICE=NPU
+
+# Set -c. The default is the training context of the model, for example 131072 for Llama 3.2 1B.
+# Keep it small on the NPU: -c 512, or -c 256 for larger models. Decode can slow down as the context grows.
+./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512
+
+# Tokens in one NPU prefill step (default 256).
+# A larger value can make long prompts faster. It also makes the first load longer.
+export GGML_OPENVINO_PREFILL_CHUNK_SIZE=512
+./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
+
+# NPU plugin properties: the compiler in OpenVINO, one compiler thread (lower memory peak), more plugin logs
+export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=1,LOG_LEVEL=LOG_INFO"
+```
+
+### Multiple GPUs
+
+```bash
+# List the devices. Each OpenVINO device shows its GGML_OPENVINO_DEVICE value; (selected) marks the active one.
+./build/ReleaseOV/bin/llama-cli --list-devices
+
+# With several GPUs, select one by name. GPU alone is not available then.
+export GGML_OPENVINO_DEVICE=GPU.1
+./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
+
+# Split a model across two GPUs by layer
+export GGML_OPENVINO_DEVICE=GPU.0,GPU.1
+./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 -sm layer
+```
+
+## Compiled model cache
+
+The cache keeps compiled models on disk, so later starts of the same model load faster.
+
+- One directory can hold the cached models of different models and settings.
+- Use the same model and the same settings in every run. A changed setting selects another cache entry. The settings: [Compiled model cache](README.md#compiled-model-cache).
+
+### CPU and GPU
+
+```bash
+# First run: compile the model and write the cache.
+# -lv 4 logs "model cache WROTE" (llama-bench: -v). Wait for it before you stop the run: an interrupted export is not cached.
+export GGML_OPENVINO_DEVICE=GPU # or CPU
+export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
+./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 -lv 4
+
+# Later runs (optional): cache-only mode. It requires the cached model and skips the weight upload and the compilation.
+export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1
+./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
+```
+
+- Cache-only mode needs mmap loading (the default) and a model that runs fully on OpenVINO.
+- MoE models are not written to the cache on CPU, so cache-only mode does not work for them on CPU.
+- A cache hit without cache-only mode shortens the load, but it uses about as much memory as a run without the cache.
+
+### NPU: gemma-4 E2B example
+
+On the NPU, the cache holds the compiled models without weights, plus one shared weights file. Only the first start compiles the model.
+
+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.
+ # The log shows the warning "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
+ # Host gather is on by default. GGML_OPENVINO_NPU_HOST_GATHER=0 turns it off.
+ 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
+ ```
+
+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. 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: use the memory-mapped GGUF file as the model buffer; fails without the cache of step 1
+ ./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
+ ```
+
+- With the default settings, the first prompt writes the prefill model of every KV window up to `-c`. Later runs with the same `-c` find a cached model for any prompt length.
+
+## Lower memory use
+
+With the default settings, the GPU and CPU plugins keep their own copy of the weights next to the copy of the backend 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.
+
+```bash
+# GPU or CPU, large model, Linux: keep at most 10% of the weights in RAM while the model loads and compiles.
+# This lowers the peak the most, also when RAM is free. The first token can come later.
+export GGML_OPENVINO_COMPILE_MEM_SPILL=0.1
+# Or without a cap: the kernel drops the spilled pages only when RAM runs out, so the peak does not change while RAM is free.
+# export GGML_OPENVINO_COMPILE_MEM_SPILL=1
+# Both back the host buffers with files in /var/tmp and write them at each start: the load takes longer, and decoding can be a little slower.
+# Needs free disk space of more than the model size, on CPU also the KV cache; with less, the backend warns and uses RAM.
+# Another directory, on a local disk (not tmpfs):
+export GGML_OPENVINO_COMPILE_MEM_SPILL_DIR=$HOME/ov_spill
+mkdir -p $GGML_OPENVINO_COMPILE_MEM_SPILL_DIR
+
+# GPU: nothing to set. The backend already releases its host copy of the weights after compilation (GGML_OPENVINO_RELEASE_WEIGHTS=1, the default).
+
+# CPU, MoE model: build fewer weight nodes during compilation.
+export GGML_OPENVINO_REDUCE_COMPILE_MEM=1
+
+# All at once: GGML_OPENVINO_MEMORY_OPTIMIZE=1 sets GGML_OPENVINO_REDUCE_COMPILE_MEM=1, GGML_OPENVINO_COMPILE_MEM_SPILL=0.1 and, on GPU, GGML_OPENVINO_RELEASE_WEIGHTS=1 (already the default).
+# Each one set on its own wins.
+export GGML_OPENVINO_MEMORY_OPTIMIZE=1
+```
+
+- The same model, started again and again: [cache-only mode](#cpu-and-gpu) skips the weight upload. `GGML_OPENVINO_COMPILE_MEM_SPILL` is optional in the first run.
+- NPU: `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` uses the memory-mapped GGUF file as the model buffer. See [NPU: gemma-4 E2B example](#npu-gemma-4-e2b-example).
+- `GGML_OPENVINO_COMPILE_MEM_SPILL` is ignored on Windows and in cache-only mode.
+- `-lm none` (no mmap) does not lower the memory in use. Cache-only mode needs mmap loading and stops with an error with `-lm none`.
+- The variables: [Memory optimization](OpenVINO-ENV-VARS.md#memory-optimization).
+
+## Large MoE models
+
+### Qwen3.6-35B-A3B on the NPU
+
+MoE models with a softmax router and SwiGLU experts run on the NPU through the MoE support of NPUW. This needs OpenVINO 2026.5 or later. 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.
+- The backend sets `NPUW_MOE_POOL_SIZE=0` and `NPUW_MOE_TOKEN_CHUNK_SIZE=16` itself for MoE models (see [NPU plugin properties](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. Windows does the same without it, because the NPU reports 16 GB there. The graph still runs on the NPU alone.
+- `llama-perplexity`: see [Embeddings and perplexity](#embeddings-and-perplexity).
+
+### Muse-Glimmer-30B with a DFlash draft on the GPU
+
+This needs a 64 GB system.
+
+```bash
+export GGML_OPENVINO_DEVICE=GPU
+export GGML_OPENVINO_COMPILE_MEM_SPILL=1
+export GGML_OPENVINO_ROPE_SINCOS=device_f32 # long prompts
+./build/ReleaseOV/bin/llama-server -m Muse-Glimmer-30B-Q4_K_M.gguf -md <dflash-draft>.gguf \
+ --spec-type draft-dflash --spec-draft-n-max 4
+```
+
+## Speculative decoding
+
+MTP, for Qwen3.5 and Qwen3.6 models with MTP weights in the GGUF file. It needs the GPU (dynamic stateless execution). Internals and limitations: [Qwen MTP](README.md#qwen-mtp).
+
+```bash
+export GGML_OPENVINO_DEVICE=GPU
+export GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all # recommended for Qwen3.6-35B-A3B Q4_K_M
+# Keep GGML_OPENVINO_KV_SLICE at its default (1)
+./build/ReleaseOV/bin/llama-server -m Qwen3.6-35B-A3B-Q4_K_M.gguf --spec-type draft-mtp --spec-draft-n-max 2
+
+# Several slots: the unified KV cache is the recommended layout on the GPU
+./build/ReleaseOV/bin/llama-server -m Qwen3.6-35B-A3B-Q4_K_M.gguf --spec-type draft-mtp --spec-draft-n-max 2 -np 4 --kv-unified
+```
+
+DFlash: see [Muse-Glimmer-30B with a DFlash draft on the GPU](#muse-glimmer-30b-with-a-dflash-draft-on-the-gpu).
+
+## Image input
+
+Image input is experimental. It runs on CPU and GPU. Internals and limitations: [Multimodal](README.md#multimodal).
+
+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
+# --image-max-tokens 256 keeps the image prefill within the memory of a 16 GB system.
+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 --image-max-tokens 256 \
+ --image tools/mtmd/test-1.jpeg -p "Describe this image in one sentence."
+```
+
+## Embeddings and perplexity
+
+```bash
+# Embeddings: CPU or GPU (embedding models do not work on the NPU)
+export GGML_OPENVINO_DEVICE=GPU
+./build/ReleaseOV/bin/llama-embedding -m embedding-model-Q8_0.gguf -p "Hello world"
+
+# Perplexity
+./build/ReleaseOV/bin/llama-perplexity -m model.gguf -f wiki.test.raw -c 512
+
+# MoE models on the GPU: set -b to the -c value, so that each batch holds one sequence
+./build/ReleaseOV/bin/llama-perplexity -m model.gguf -f wiki.test.raw -c 512 -b 512
+
+# NPU: -b at most -c (one sequence per batch), -ub equal to the prefill chunk size (default 256)
+export GGML_OPENVINO_DEVICE=NPU
+./build/ReleaseOV/bin/llama-perplexity -m model.gguf -f wiki.test.raw -c 1024 -b 1024 -ub 256
+
+# NPU, MoE models such as Qwen3.6-35B-A3B: -c at most twice GGML_OPENVINO_PREFILL_CHUNK_SIZE.
+# The output rows of the last layer must not exceed the chunk size.
+export GGML_OPENVINO_PREFILL_CHUNK_SIZE=128
+./build/ReleaseOV/bin/llama-perplexity -m Qwen_Qwen3.6-35B-A3B-Q4_0.gguf -f wiki.test.raw -c 256
+```
+
+## Profiling and debug dumps
+
+The variables are in [Debug output](OpenVINO-ENV-VARS.md#debug-output).
+
+```bash
+# Execution timing of each graph: 1. 2 or higher also turns on OpenVINO and OpenCL profiling.
+# llama-simple prints the timing lines. llama-cli needs -lv 4, llama-bench needs -v.
+export GGML_OPENVINO_DEVICE=GPU
+export GGML_OPENVINO_PROFILING=1
+./build/ReleaseOV/bin/llama-simple -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -n 50 "The story of AI is "
+```
+
+```bash
+# Show the variables in effect (log verbosity 4)
+./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 -lv 4 2>&1 | grep "settings from the environment"
+```
+
+```bash
+# CPU in FP16, as the GPU and the NPU compute. This helps to debug the accuracy of a quantized model.
+GGML_OPENVINO_DEVICE=CPU GGML_OPENVINO_CPU_CONFIG="INFERENCE_PRECISION_HINT=f16" \
+ ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
+```
+
+```bash
+# Find out whether a default optimization causes a wrong result: turn it off and compare the output
+GGML_OPENVINO_DEVICE=NPU GGML_OPENVINO_NPU_FAST_MASK=0 \
+ ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 32 --temp 0 -no-cnv -p "The capital of France is"
+```
+
+```bash
+# Dump the GGML graph and the OpenVINO IR of a run
+GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \
+ ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
+
+# Shapes of each graph node, with * at the dynamic (token) dimension. Printed to stdout.
+GGML_OPENVINO_DEBUG_DYNAMIC_DIMS=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 4 -no-cnv -p "Hello" > dims.txt
+
+# Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher).
+GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
+
+# What supports_op accepts and rejects: 1 = summary at exit, 2 = also each call
+GGML_OPENVINO_LOG_SUPPORTS_OP=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep ov-supports-op
+
+# Graph key and tensor shapes when an inference throws
+GGML_OPENVINO_DIAG_GRAPH_IO=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep DIAG
+
+# NPUW dumps. They need an OpenVINO developer build (NPU_PLUGIN_DEVELOPER_BUILD).
+export GGML_OPENVINO_DEVICE=NPU
+export GGML_OPENVINO_NPUW_DUMP_SUBS=YES
+export GGML_OPENVINO_NPUW_DUMP_SUBS_DIR=/tmp/npuw_dump # optional
+./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
+```
+
+List the properties of the installed NPU plugin (C++):
+
+```cpp
+// List the properties of the installed NPU plugin with their current values
+ov::Core core;
+for (const auto & name : core.get_property("NPU", ov::supported_properties)) {
+ std::cout << name << " = " << core.get_property("NPU", name).as<std::string>() << "\n";
+}
+```
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 22ed8bbba..ee983ad1b 100644
--- a/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md
+++ b/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md
@@ -13,20 +13,20 @@ Contents:
## Sampler behavior
-- Qwen3.5/Qwen3.6 MTP uses a pure top-k backend sampler.
+- The MTP draft (`--spec-type draft-mtp`) samples with a backend chain of one top-k sampler (k = 10). Draft backend sampling is on by default. If the backend rejects the chain, llama.cpp uses the CPU sampler for that sequence.
- 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.
+- In dynamic execution, 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.
+- Only the small sampling branches stay at configured capacity. The MTP layer and the output projection process only 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.
+- Only a pure top-k chain keeps its inactive branches: VIEW, two Reshapes, TopK and GET_ROWS, with no other reader. Other chains drop the branches that have no COMPUTE flag. Static (NPU) and stateful execution drop them for every chain.
## Graph layout
-The captured UD draft graph contains 107 nodes regardless of which of four slots are active.
+Capture conditions: cache-only mode, four slots, context 8192 and `--spec-draft-n-max 2`. The captured draft graph of the UD (Unsloth Dynamic) Qwen3.6-35B-A3B model 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.
@@ -51,26 +51,19 @@ MTP token IDs + input hidden state
## Active slots
-| Active slots | Sampling COMPUTE flags, slots 0-3 | Raw/current nodes | Old filtered nodes | Packed sampling_rows |
-|---|---|---:|---:|---|
-| 3 | `[0,0,0,1]` | 107 | 92 | `[0,0,0,0]` |
-| 0,2 | `[1,0,1,0]` | 107 | 97 | `[0,0,1,0]` |
-| All four | `[1,1,1,1]` | 107 | 107 | `[0,1,2,3]` |
+| Active slots | Sampling COMPUTE flags, slots 0-3 | Nodes | Packed sampling_rows |
+|---|---|---:|---|
+| 3 | `[0,0,0,1]` | 107 | `[0,0,0,0]` |
+| 0,2 | `[1,0,1,0]` | 107 | `[0,0,1,0]` |
+| All four | `[1,1,1,1]` | 107 | `[0,1,2,3]` |
-- 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>
+- Unselected branches stay in the graph, so every active subset uses one compiled draft model.
+- Packed entries follow the sorted branch names. This matches the slot order for slots 0-9.
## 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.
+- In dynamic execution, one int64 `sampling_rows` Parameter supplies the row indices. Static execution uses one `sampling_row_<node>` input per branch.
- 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.
@@ -87,6 +80,7 @@ slot 3 -> row 0 -> private scratch, ignored
## Compiled models and the cache
- 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 blob key and the in-process key leave out the COMPUTE flags, so all active subsets use one compiled draft model.
- 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.
@@ -97,4 +91,4 @@ slot 3 -> row 0 -> private scratch, ignored
- 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.
+- `GGML_OPENVINO_DUMP_CGRAPH=1` dumps the raw graph before the COMPUTE filter, with COMPUTE/OUTPUT flags and byte offsets. It overwrites `cgraph_ov.txt` on each call. Enable dumps only for diagnosis.
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 010ee88a3..1294f0f9b 100644
--- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md
+++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md
@@ -2,20 +2,19 @@
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.
-- Applies to `qwen35` and `qwen35moe`, with one or multiple slots.
-- Reference model: the UD Qwen3.6-35B-A3B MTP GGUF model file.
+- The backend finds replay groups by graph structure. It is validated with `qwen35` and `qwen35moe`, with one or more slots.
+- Reference model: the UD (Unsloth Dynamic) 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.
+- Attention KV binding (`GGML_OPENVINO_ENABLE_KV_4D`, `GGML_OPENVINO_KV_SLICE`, `GGML_OPENVINO_GPU_KV_ROUND_UP`): [KV cache binding](README.md#kv-cache-binding).
+- Backend files: [Source layout](README.md#source-layout). MTP sampling: [MTP-SAMPLING-GRAPH.md](MTP-SAMPLING-GRAPH.md).
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)
+- [Debugging and profiling](#debugging-and-profiling)
## Buffer ownership and operation boundaries
@@ -51,17 +50,17 @@ Both kernels write their cache inputs directly.
Graph selection:
-- Qwen selects the recurrent graph when the target context is created.
+- The llama context selects the replay graph when it 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.
+- 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. `op_params[2]` holds the keep flag.
- A fresh prompt supplies a replay count of zero.
-- Prefill microbatches longer than `n_rs_seq + 1` tokens per sequence commit their final state.
+- A ubatch commits its final state when it has one token, or more than `n_rs_seq + 1` tokens, per sequence. Other ubatches stay pending.
- 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 backend emits the replay graph only on GPU, for a dynamic, stateless graph that is not split. `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` turns it off. In all other cases, another GGML backend runs the replay ops.
- 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>`.
@@ -76,7 +75,7 @@ GPU fusion:
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.
+- The backend keeps the replay subgraph, its `Loop` body and its bank inputs in FP32 under the GPU f16 inference hint.
Source of the replay pattern:
@@ -96,71 +95,9 @@ When upstream modeling changes the GGML graph:
- `ScatterNDUpdate` produces the updated bank for the `Assign` sink.
- Row maps, replay counts and reset rows are runtime inputs.
-## Attention KV layout
-
-| 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 |
-
-`GGML_OPENVINO_ENABLE_KV_4D`:
-
-- 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.
-
-`GGML_OPENVINO_GPU_KV_ROUND_UP` on dynamic stateless GPU:
-
-- 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
-
-- 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
-
-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:
+## Debugging and profiling
+- `GGML_OPENVINO_DUMP_CGRAPH=1` also logs the number of convolution and GDN replay groups. For annotated dumps, see [Reading graph dumps](MTP-SAMPLING-GRAPH.md#reading-graph-dumps).
+- `test-backend-ops` does not cover the OpenVINO replay path. Its replay cases have no recurrent cache banks, so the backend rejects them. Check replay with a Qwen3.5 or Qwen3.6 MTP model at one and four active sequences.
- 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 67c695575..243a40c5c 100644
--- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
+++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
@@ -1,6 +1,6 @@
# OpenVINO backend environment variables for development
-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.
+The variables for users, and the rules for values, are in [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md#configuration). This file lists the other `GGML_OPENVINO_*` variables. They are for debugging, comparisons and experiments, and they can change or be removed. Commands that use them are in [COOKBOOK.md](COOKBOOK.md).
Contents:
@@ -14,6 +14,8 @@ Contents:
## Debug output
+Examples: [Profiling and debug dumps](COOKBOOK.md#profiling-and-debug-dumps).
+
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
| `GGML_OPENVINO_DUMP_CGRAPH` | all | Boolean | `0` | Dump the GGML compute graph to `cgraph_ov.txt`. |
@@ -34,39 +36,15 @@ Contents:
| `GGML_OPENVINO_NPUW_DUMP_SUBS_ON_FAIL` | NPU | String | `not set` | Passed to OpenVINO unchanged as `NPUW_DUMP_SUBS_ON_FAIL`. |
| `GGML_OPENVINO_NPUW_DUMP_IO` | NPU | String | `not set` | Passed to OpenVINO unchanged as `NPUW_DUMP_IO`. |
-```bash
-# Dump the GGML graph and the OpenVINO IR of a run
-GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \
- ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
-
-# Shapes of each graph node, with * at the dynamic (token) dimension. Printed to stdout.
-GGML_OPENVINO_DEBUG_DYNAMIC_DIMS=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 4 -no-cnv -p "Hello" > dims.txt
-
-# Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher).
-GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
-
-# What supports_op accepts and rejects: 1 = summary at exit, 2 = also each call
-GGML_OPENVINO_LOG_SUPPORTS_OP=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep ov-supports-op
-
-# Graph key and tensor shapes when an inference throws
-GGML_OPENVINO_DIAG_GRAPH_IO=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep DIAG
-
-# NPUW dumps. They need an OpenVINO developer build (NPU_PLUGIN_DEVELOPER_BUILD).
-export GGML_OPENVINO_DEVICE=NPU
-export GGML_OPENVINO_NPUW_DUMP_SUBS=YES
-export GGML_OPENVINO_NPUW_DUMP_SUBS_DIR=/tmp/npuw_dump # optional
-./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
-```
-
## Switches for default optimizations
Each variable turns off an optimization that is on by default, or sets its strength. Use them to find the cause of a wrong result or of a speed change.
| 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`. 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_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`. See [KV cache binding](README.md#kv-cache-binding). |
+| `GGML_OPENVINO_GPU_KV_ROUND_UP` | GPU | Boolean | `1` | Round the attended width up on dynamic stateless GPU. `0` uses the GGML mask width. See [KV cache binding](README.md#kv-cache-binding). |
+| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | One decode graph for each KV window (base from `GGML_OPENVINO_KV_SLICE`), built or read from the cache on the first call. `0`: one decode graph for the whole context. Use the same value when you write and read the cache. See [KV cache binding](README.md#kv-cache-binding). |
| `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. |
| `GGML_OPENVINO_GDN_Q_SCALE` | NPU | Float | `64` | Factor of the GDN q pre-scaling, which keeps the GDN output above the FP16 flush-to-zero floor of the NPU. `0` or a negative value turns it off. Values below `64` are raised to `64`. |
@@ -76,13 +54,8 @@ Each variable turns off an optimization that is on by default, or sets its stren
| `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` | `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
-GGML_OPENVINO_DEVICE=NPU GGML_OPENVINO_NPU_FAST_MASK=0 \
- ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 32 --temp 0 -no-cnv -p "The capital of France is"
-```
+| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | auto | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]` for in-place updates. Unset: on with OpenVINO 2026.5 or later. `0` forces it off, a positive value forces it on. Not used with `-fa off`, for soft-capped attention (gemma-2), or in static, stateful or split graphs. See [KV cache binding](README.md#kv-cache-binding). |
+| `GGML_OPENVINO_RELEASE_WEIGHTS` | GPU | Boolean | `1` | Release the host weight buffers after compilation. The compiled model keeps its own copy. The backend writes them again from the model file before a new compile or a host read. `0` keeps them. Follows `GGML_OPENVINO_MEMORY_OPTIMIZE` when that is set. Off with `-lm none` and in cache-only mode. Linux only. |
## Experimental options
@@ -97,69 +70,20 @@ Most of these options are off by default. They are not validated for general use
| `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. 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` | 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_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op instead of the default `relu(x) + log1p(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_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`, `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. |
-
-```bash
-# NPU cache: weightless blobs plus one shared weights file. Keep all other NPU settings the same in both runs.
-export GGML_OPENVINO_DEVICE=NPU
-export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
-./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # first run: warns "no usable cached blobs", exports
-
-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"
-```
## 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.
-
-```bash
-# GPU or CPU, large model: back the weight buffer with a file, so the kernel can drop its pages.
-# Use a directory on a local disk (not tmpfs) with free space of about the model size. Can lower prompt speed.
-export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill
-mkdir -p $GGML_OPENVINO_SPILL_DIR
-```
-
-```bash
-# GPU or CPU, the same model started again and again: compile once, then load the compiled model only.
-export GGML_OPENVINO_DEVICE=GPU # or CPU
-export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
-GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill ./build/ReleaseOV/bin/llama-cli -m model.gguf # first run writes the cache
-export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1
-./build/ReleaseOV/bin/llama-cli -m model.gguf # later runs skip the weight upload
-```
-
-```bash
-# GPU: keep the host copy of the weights after compilation (it is released by default).
-export GGML_OPENVINO_DEVICE=GPU
-export GGML_OPENVINO_RELEASE_WEIGHTS=0
-```
-
-```bash
-# CPU, MoE model: build fewer weight nodes during compilation.
-export GGML_OPENVINO_REDUCE_COMPILE_MEM=1
-```
-
-```bash
-# NPU: weightless cache, then use the memory-mapped GGUF as the model buffer.
-export GGML_OPENVINO_DEVICE=NPU
-export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
-./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 # first run writes the cache
-export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
-./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 # later runs
-```
+These variables lower the host memory peak. They do not change the output. Commands: [Lower memory use](COOKBOOK.md#lower-memory-use). `GGML_OPENVINO_RELEASE_WEIGHTS` is in [Switches for default optimizations](#switches-for-default-optimizations).
-- 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 cache-only mode stops with an error with it: cache-only mode needs mmap loading.
+| Variable | Device | Type | Default | Description |
+|---|---|---|---|---|
+| `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | unset | When set, the default of `GGML_OPENVINO_REDUCE_COMPILE_MEM`, of `GGML_OPENVINO_COMPILE_MEM_SPILL` (`1` sets `0.1`) and, on GPU, of `GGML_OPENVINO_RELEASE_WEIGHTS`. `0` also keeps the host weights on GPU. |
+| `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_COMPILE_MEM_SPILL` | CPU, GPU | Float | `0.1` with `GGML_OPENVINO_MEMORY_OPTIMIZE=1`, else `0` | Back the host buffers of the backend (weights, KV cache, compute) with files in `GGML_OPENVINO_COMPILE_MEM_SPILL_DIR`, so the kernel can drop their pages. `0`: off. `1`: on, but the kernel drops the pages only when RAM runs out, so the memory peak does not change while RAM is free. A fraction in between: on, and while the model loads and compiles, keep at most this fraction of the spilled weights in RAM, also when RAM is free (`0.1` keeps 10%, Linux 5.4 or later). A fraction lowers the peak the most; the model file's pages are dropped too, and the first token can come later, while the weights are written to disk. Each start writes the buffers to disk: the load takes longer, and decoding can be a little slower. The disk space is reserved when the files are created (not for rewrites on btrfs or ZFS): more than the model size, on CPU also the KV cache. With too little space, the backend warns and uses RAM. NPU: off unless set, and only with `GGML_OPENVINO_NPU_L0_HOST_TENSORS=0`. Not part of the cache key. Ignored on Windows and in cache-only mode. |
+| `GGML_OPENVINO_COMPILE_MEM_SPILL_DIR` | CPU, GPU | String | `/var/tmp` | Directory for the `GGML_OPENVINO_COMPILE_MEM_SPILL` files. Use real storage, not tmpfs (`/tmp` on many systems): on tmpfs, the backend warns and uses RAM. |
+| `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. |
## NPU plugin properties
@@ -203,78 +127,25 @@ Other properties for `GGML_OPENVINO_NPU_CONFIG`. The backend does not set them,
| `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`:
-
-```bash
-export GGML_OPENVINO_DEVICE=NPU
-export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=1,LOG_LEVEL=LOG_INFO"
-```
-
-<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
-ov::Core core;
-for (const auto & name : core.get_property("NPU", ov::supported_properties)) {
- std::cout << name << " = " << core.get_property("NPU", name).as<std::string>() << "\n";
-}
-```
-
-</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.
+- `NPUW_*` options, with type and default: `src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc` in the OpenVINO source. To list the properties of the installed plugin, see the C++ sample in [Profiling and debug dumps](COOKBOOK.md#profiling-and-debug-dumps).
- 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.
-
-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
- ```
+- Compiled model cache on the NPU: see [NPU: gemma-4 E2B example](COOKBOOK.md#npu-gemma-4-e2b-example).
## GPU and CPU 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.
- - 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
-GGML_OPENVINO_DEVICE=CPU GGML_OPENVINO_CPU_CONFIG="INFERENCE_PRECISION_HINT=f16" \
- ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
-```
+- `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.
All properties: [OpenVINO GPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html), [OpenVINO CPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/cpu-device.html).
## Older variable names
-Each of these variables sets one NPU property. They still work. `GGML_OPENVINO_NPU_CONFIG` sets the same properties and takes precedence when both are set.
+Each of these variables sets one NPU property. They still work. `GGML_OPENVINO_NPU_CONFIG` sets the same properties and takes precedence when both are set. For example, `GGML_OPENVINO_NPU_CONFIG="NPUW_UNFOLD_IREQS=YES"` and `GGML_OPENVINO_NPUW_UNFOLD_IREQS=YES` do the same. Use the first form.
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
@@ -283,9 +154,3 @@ Each of these variables sets one NPU property. They still work. `GGML_OPENVINO_N
| `GGML_OPENVINO_NPUW_FUNCALL_FOR_ALL` | NPU | String | `not set` | Sets `NPUW_FUNCALL_FOR_ALL`. |
| `GGML_OPENVINO_NPUW_UNFOLD_IREQS` | NPU | String | `not set` | Sets `NPUW_UNFOLD_IREQS`. |
| `GGML_OPENVINO_COMPILATION_NUM_THREADS` | NPU | String | `not set` | Sets `COMPILATION_NUM_THREADS`. |
-
-```bash
-# These two lines do the same. Use the first form.
-export GGML_OPENVINO_NPU_CONFIG="NPUW_UNFOLD_IREQS=YES"
-export GGML_OPENVINO_NPUW_UNFOLD_IREQS=YES
-```
diff --git a/ggml/src/ggml-openvino/dev_doc/README.md b/ggml/src/ggml-openvino/dev_doc/README.md
index f08f6a999..ee169e909 100644
--- a/ggml/src/ggml-openvino/dev_doc/README.md
+++ b/ggml/src/ggml-openvino/dev_doc/README.md
@@ -1,91 +1,70 @@
# OpenVINO backend developer documentation
-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).
+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 environment variables: [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md).
+- Commands for each task: [COOKBOOK.md](COOKBOOK.md).
| Document | Content |
|---|---|
-| This page | Qwen MTP, compiled model cache, KV-only prefill, NPU host gather, multimodal input |
+| This page | How the backend works, source layout, compiled model cache, KV cache binding, KV-only prefill, NPU host gather, Qwen MTP, multimodal input |
+| [COOKBOOK.md](COOKBOOK.md) | Recipes: build scripts, Docker, devices, cache, memory, large MoE models, speculative decoding, image input, perplexity, profiling and debug dumps |
| [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 |
+| [OPENVINO-RECURRENT-CACHE.md](OPENVINO-RECURRENT-CACHE.md) | Qwen recurrent cache on GPU: buffer ownership, replay graph contract, convolution cache stores |
| [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)
+- [How the backend works](#how-the-backend-works)
+- [Source layout](#source-layout)
- [Compiled model cache](#compiled-model-cache)
+- [KV cache binding](#kv-cache-binding)
- [KV-only prefill](#kv-only-prefill)
- [NPU host gather](#npu-host-gather)
+- [Qwen MTP](#qwen-mtp)
- [Multimodal](#multimodal)
-## Qwen MTP
-
-The OpenVINO backend translates Qwen recurrent replay for complete dynamic stateless GPU graphs and supports stable MTP sampling.
+## How the backend works
-Requirements:
-
-- Dynamic stateless GPU execution. OpenVINO replay requires it.
-- A GGUF model file that contains MTP weights.
+When a `ggml_cgraph` is dispatched to the OpenVINO backend, it:
-Options:
+- Walks the GGML graph and identifies inputs, outputs, weights, and KV cache tensors.
+- Translates the GGML operations into an `ov::Model` using OpenVINO's frontend API.
+- Compiles and caches the model for the target device.
+- Binds GGML tensor memory to OpenVINO inference tensors and runs inference.
-- 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).
+## Source 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.
+Backend files, relative to `ggml/src/ggml-openvino/`, and OpenVINO GPU plugin parts:
-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).
+| File | Content |
+|---|---|
+| `ggml-openvino.cpp` | Backend, device and buffer interfaces; op support checks, including the replay op checks |
+| `ggml-openvino-extra.cpp` | Registry of the environment variables, value checks and device selection |
+| `ggml-decoder.cpp` | Dynamic dimensions, control inputs, output names and the `cgraph_ov.txt` dump |
+| `utils.cpp` | Compute-branch filtering, compiled reuse, input/output binding, and replay writeback through `query_state()` |
+| `model-cache.cpp` | Compiled model cache on disk: cache key (`cache_settings[]`) and source file identity |
+| `ggml-quants.cpp` | Extraction and requantization of the GGUF weights |
+| `device/npu_config.cpp`, `device/npu_quant_policy.cpp` | NPU plugin properties and NPU weight layouts |
+| `openvino/translate_session.cpp` | Runtime sampling aliases, model construction and replay `Assign` sinks |
+| `openvino/recurrent_replay_fusion.cpp` | GGML group recognition and standard-op replay translation |
+| `openvino/op/` | One translator for each GGML op. `recurrent_replay_graph.hpp` emits the replay pattern. |
+| `openvino/pass/` | OpenVINO graph passes, for example `keep_cache_results.cpp` for the KV-only prefill |
+| OV `recurrent_replay_fusion.cpp` and `recurrent_cache_replay` | Structural matching, writable-input validation, source staging and GPU computation |
## Compiled model cache
-`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` exports compiled CPU and GPU graphs with their weights.
+`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` exports compiled graphs. Commands: [Compiled model cache](COOKBOOK.md#compiled-model-cache).
-- It bypasses the plugin-level `GGML_OPENVINO_CACHE_DIR` and uses `OPTIMIZE_SPEED`, so weightless caching is disabled.
+- CPU and GPU: each blob holds its weights. The backend drops the plugin `CACHE_DIR` and uses `CACHE_MODE=OPTIMIZE_SPEED`.
+- NPU: weightless blobs plus one shared weights file.
- One directory can hold blobs for different models and compilation settings.
+- Compatible prefill and decode graphs share one blob and manifest. A graph with different ports or incompatible shapes gets an exact entry instead.
+- An interrupted export is not a cache hit. Wait for the `model cache WROTE` message and for the workload to complete before you stop the first run.
-1. Run each intended workload once to export its dynamic graph:
+The rest of this section covers CPU and GPU.
- ```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:
+Cache-only mode (`GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1`):
- 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.
@@ -93,28 +72,29 @@ Cache-only mode:
- 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:
+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. Source: `cache_settings[]` in `model-cache.cpp`.
- `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_DISABLE_ELTWISE_RANK_ALIGN`, `GGML_OPENVINO_DEBUG_NODE`
+- `GGML_OPENVINO_ENABLE_KV_4D` and `GGML_OPENVINO_ROPE_SINCOS` (their effective values).
- `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_COMPILE_MEM_SPILL` and `GGML_OPENVINO_COMPILE_MEM_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).
+- `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: [KV cache binding](#kv-cache-binding).
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.
+- Exception: a model with one KV head whose first graph has one token. That graph gets its own entry, and a longer prompt converts it again.
- 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
@@ -124,9 +104,55 @@ Cache entries:
- 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.
+- Small weights that the loader builds in memory (up to 64 MiB, for example the Bonsai 2 Hadamard matrix) have no file identity. A hash of their first and last 4 KiB identifies them.
+- Use the same target device and a compatible OpenVINO and plugin installation. The CPU plugin cannot import MoE graphs with `GatherMatmul` ops. The backend writes no blob for them, and cache-only mode fails for MoE models on CPU. 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 cache binding
+
+This section covers how four variables bind the attention KV cache. Their table rows are in [Switches for default optimizations](OpenVINO-ENV-VARS.md#switches-for-default-optimizations).
+
+- `GGML_OPENVINO_ENABLE_KV_4D`: native stateless in-place attention updates on GPU.
+- `GGML_OPENVINO_KV_SLICE`: binding switch on dynamic CPU and GPU; base of the compiled KV windows on static NPU.
+- `GGML_OPENVINO_GPU_KV_ROUND_UP`: attended-width rounding on dynamic stateless GPU.
+- `GGML_OPENVINO_NPU_BLOB_PREBUILD`: one decode graph for each KV window on static NPU.
+
+`GGML_OPENVINO_ENABLE_KV_4D`:
+
+- Binds the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place.
+- 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.
+- Unset: on with OpenVINO 2026.5 or later, off with older versions (much slower there). `0` turns it off. `1` turns it on with older OpenVINO versions.
+- The current eligibility covers one physical stream, including unified KV. It also needs a dynamic, stateless graph that is not split. `-fa off` and soft-capped attention (gemma-2) keep the full-cache layout.
+- 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.
+- 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`).
+
+`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, and sizes the KQ masks to match.
+- 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 takes precedence. It 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` and `GGML_OPENVINO_NPU_BLOB_PREBUILD` on static NPU:
+
+- `GGML_OPENVINO_KV_SLICE` selects the base of the compiled KV windows. `1` means base 1024; an explicit multiple of 256 changes it. `0` turns the windows off. With `0`, `llama-bench -d` fails on the NPU.
+- The window is the smallest `base * 2^k` that covers the attended length, capped by the context.
+- The prefill graph is compiled at the window that covers 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 serves it.
+- `GGML_OPENVINO_NPU_BLOB_PREBUILD=1`: decode attends the smallest window that covers the next position, with one decode graph for each window. 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.
+- `GGML_OPENVINO_NPU_BLOB_PREBUILD=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 values of both variables in the run that writes the cache and in the runs that read it.
+
+`GGML_OPENVINO_GPU_KV_ROUND_UP` on dynamic stateless GPU:
+
+- 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.
+
## 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.
@@ -134,27 +160,54 @@ On the static path (NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`), mod
- 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.
+- 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.
- 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:
-
+- The first call of a graph decides. A first call with more than one output token uses the full prefill for that graph.
+- If a later 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.
- `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.
+`GGML_OPENVINO_NPU_HOST_GATHER` (NPU only, on by default; `0` turns it off) gathers the rows of large host-resident embedding tables on the host.
-- Applies to tables of at least 64 MiB with raw GGUF data.
+- Applies to tables of at least 64 MiB in host memory with raw GGUF rows: a CPU buffer, or an OpenVINO buffer with `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` set.
- 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.
+## Qwen MTP
+
+The OpenVINO backend translates Qwen recurrent replay for complete dynamic stateless GPU graphs and supports stable MTP sampling. Commands: [Speculative decoding](COOKBOOK.md#speculative-decoding).
+
+Requirements:
+
+- Dynamic stateless GPU execution. OpenVINO replay requires it.
+- A GGUF model file that contains MTP weights.
+- For several slots, the unified KV cache (`--kv-unified`) is the recommended layout. See [KV cache binding](#kv-cache-binding).
+
+`q4_asym64_all` requantization (recommended for Qwen3.6-35B-A3B Q4_K_M):
+
+- 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. The fix is on the OpenVINO master branch. It is not in a release yet.
+
+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`: [KV cache binding](#kv-cache-binding).
+- MTP sampling across active slots: [MTP-SAMPLING-GRAPH.md](MTP-SAMPLING-GRAPH.md).
+
## Multimodal
-Image input is experimental.
+Image input is experimental. Commands: [Image input](COOKBOOK.md#image-input).
-- Qwen3.5 and Gemma4 E2B image input runs on OpenVINO CPU and GPU with their matching projectors.
+- Qwen3.5, Qwen3-VL 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.
@@ -162,27 +215,4 @@ 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."
-```
+- The small preprocessing graph has no weights. It takes the naive path, which compiles it on every call.
diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp
index 31b1aa9f1..42dfeab4f 100644
--- a/ggml/src/ggml-openvino/ggml-decoder.cpp
+++ b/ggml/src/ggml-openvino/ggml-decoder.cpp
@@ -658,12 +658,13 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
const auto * concat = consumer->src[0];
if (concat->op == GGML_OP_CONCAT && concat->src[1]->op == GGML_OP_TRANSPOSE) {
const auto * seq = concat->src[1]->src[0];
- // LFM2 short convolutions gate the input first: transpose(mul(view(node), view(node))).
+ // Short convolutions may gate two views of the same projection before transposing.
if (seq->op == GGML_OP_MUL && seq->src[0]->op == GGML_OP_VIEW && seq->src[0]->src[0] == node &&
seq->src[1]->op == GGML_OP_VIEW && seq->src[1]->src[0] == node) {
seq = node;
}
- recurrent_sequence = seq == node;
+ // Mamba splits the convolution input from its packed projection.
+ recurrent_sequence = seq == node || (seq->op == GGML_OP_VIEW && seq->src[0] == 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;
@@ -942,6 +943,16 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
}
break;
}
+ case GGML_OP_MUL: {
+ const auto * norm = node->src[0];
+ const auto * weight = node->src[1];
+ if (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_RESHAPE &&
+ weight->op == GGML_OP_NONE && weight->ne[0] == norm->ne[0] && weight->ne[1] == norm->ne[1] &&
+ weight->ne[1] > 1 && weight->ne[2] == 1 && weight->ne[3] == 1 && ggml_openvino_is_gpu()) {
+ return 1;
+ }
+ break;
+ }
case GGML_OP_GATED_DELTA_NET: {
if (is_gdn_out_prescaled(node)) {
op_case = 1;
@@ -2667,7 +2678,7 @@ std::shared_ptr<ov::Node> GgmlOvDecoder::create_weight_node(ggml_tensor * tensor
// GGML_LOG_DEBUG("%s: creating new weight node for %s\n", __func__, tensor->name);
static const std::set<ggml_type> weight_types = {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0,
GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q4_K,
- GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, GGML_TYPE_MXFP4};
+ GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, GGML_TYPE_MXFP4, GGML_TYPE_Q2_0};
if (weight_types.find(tensor->type) == weight_types.end()) {
throw std::runtime_error("Unexpected weight tensor type: " + std::string(tensor->name) + " with type " +
ggml_type_name(tensor->type));
@@ -3418,6 +3429,32 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
break;
}
}
+ if (m_node_dynamic_dims[node] == -1) {
+ // A reshape can also split or merge the dynamic axis (e.g. the blockwise Hadamard rotation: [T, K] <-> [T * K / block, block]), so the stride match above finds nothing.
+ // Take the output axis that spans the same elements: the axes above it are static, and the axes up to and including it hold as many elements as in the source.
+ int64_t src_below = 1;
+ for (int i = 0; i < dynamic_dim_idx; i++) {
+ src_below *= node->src[0]->ne[i];
+ }
+ int64_t src_above = 1;
+ for (int i = dynamic_dim_idx + 1; i < GGML_MAX_DIMS; i++) {
+ src_above *= node->src[0]->ne[i];
+ }
+ const int64_t src_upto = src_below * node->src[0]->ne[dynamic_dim_idx];
+
+ int64_t dst_below = 1;
+ for (int i = 0; i < GGML_MAX_DIMS; i++) {
+ int64_t dst_above = 1;
+ for (int j = i + 1; j < GGML_MAX_DIMS; j++) {
+ dst_above *= node->ne[j];
+ }
+ if (dst_above == src_above && dst_below * node->ne[i] == src_upto) {
+ m_node_dynamic_dims[node] = i;
+ break;
+ }
+ dst_below *= node->ne[i];
+ }
+ }
if (m_node_dynamic_dims[node] == -1) {
GGML_LOG_WARN("ggml-openvino: cannot determine dynamic dim for RESHAPE node '%s'\n", node->name);
}
@@ -3533,6 +3570,8 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
case GGML_OP_TRI:
case GGML_OP_REPEAT:
case GGML_OP_DUP:
+ case GGML_OP_SQR:
+ case GGML_OP_SQRT:
// Shape-preserving elementwise ops: the dynamic dim is unchanged from src[0].
// DIV/CLAMP are used in the MoE routing-weight normalization
// (sum_rows -> clamp -> div). If they are left untracked here the dynamic
@@ -3550,9 +3589,9 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
break;
case GGML_OP_SUM_ROWS:
+ case GGML_OP_MEAN:
case GGML_OP_POOL_1D:
- // SUM_ROWS/POOL_1D change only ggml axis 0 and preserve all other axes, so the
- // dynamic dim is preserved unless it was axis 0.
+ // Only axis 0 changes. Preserve a dynamic dimension on any other axis.
m_node_dynamic_dims[node] =
(m_node_dynamic_dims[node->src[0]] == 0) ? -1 : m_node_dynamic_dims[node->src[0]];
break;
@@ -3562,7 +3601,6 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
break;
case GGML_OP_CPY:
case GGML_OP_SUM:
- case GGML_OP_MEAN:
case GGML_OP_ARANGE:
m_node_dynamic_dims[node] = -1;
break;
diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h
index ec017a8f5..762df6d29 100644
--- a/ggml/src/ggml-openvino/ggml-decoder.h
+++ b/ggml/src/ggml-openvino/ggml-decoder.h
@@ -366,7 +366,7 @@ public:
const std::map<std::string, ggml_tensor *> & get_model_outputs() const { return m_model_outputs; }
- virtual int get_ctx_size() const { return m_model_params.ctx; }
+ int get_ctx_size() const override { return m_model_params.ctx; }
virtual int get_ctx_per_seq() const { return m_model_params.ctx_per_seq; }
diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
index e9e431162..2ab49ba53 100644
--- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
+++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
@@ -128,7 +128,8 @@ constexpr env_var env_vars[] = {
// Text
{"GGML_OPENVINO_DEVICE", env_type::STR},
{"GGML_OPENVINO_CACHE_DIR", env_type::STR},
- {"GGML_OPENVINO_SPILL_DIR", env_type::STR},
+ {"GGML_OPENVINO_COMPILE_MEM_SPILL", env_type::FLOAT},
+ {"GGML_OPENVINO_COMPILE_MEM_SPILL_DIR", env_type::STR},
{"GGML_OPENVINO_DEBUG_NODE", env_type::STR},
{"GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR", env_type::STR},
{"GGML_OPENVINO_NPU_COMPILE_CONFIG", env_type::STR},
@@ -149,6 +150,7 @@ constexpr env_var env_vars[] = {
{"GGML_OPENVINO_NPU_REQUANT_POLICY", env_type::ENUM, "group-128|channel-wise"},
{"GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT", env_type::ENUM, "f16|q8_0_c|q4_0_128|q4_0_c"},
{"GGML_OPENVINO_REQUANT_KQUANT", env_type::ENUM, "q4_sym128|q4_sym128_all|q4_asym64|q4_asym64_all|native"},
+ {"GGML_OPENVINO_ROPE_SINCOS", env_type::ENUM, "auto|host|device|device_f32"},
// Numbers
{"GGML_OPENVINO_PREFILL_CHUNK_SIZE", env_type::INT},
{"GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB", env_type::INT},
@@ -184,7 +186,6 @@ constexpr env_var env_vars[] = {
{"GGML_OPENVINO_LOG_UNSUPPORTED_OPS", env_type::BOOL},
{"GGML_OPENVINO_LOG_SUPPORTS_OP", env_type::INT},
{"GGML_OPENVINO_DIAG_GRAPH_IO", env_type::BOOL},
- {"GGML_OPENVINO_ROPE_F32_ANGLE", env_type::BOOL},
{"GGML_OPENVINO_LOG_SWA_LAYERS", env_type::BOOL},
{"GGML_OPENVINO_NATIVE_SOFTPLUS", env_type::BOOL},
{"GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS", env_type::BOOL},
@@ -271,10 +272,14 @@ std::string checked_env_value(const env_var & var, const char * value) {
return std::to_string(number);
case env_type::FLOAT: {
char * end = nullptr;
- (void) std::strtof(value, &end);
+ const float number = std::strtof(value, &end);
if (end == value || !trim_spaces(end).empty()) {
GGML_ABORT("ggml-openvino: %s=%s is not valid, use a number", var.name, value);
}
+ if (std::strcmp(var.name, "GGML_OPENVINO_COMPILE_MEM_SPILL") == 0 && !(number >= 0 && number <= 1)) {
+ GGML_ABORT("ggml-openvino: %s=%s is not valid, use 0 (off), 1 (on) or a fraction in between (0.1)",
+ var.name, value);
+ }
break;
}
case env_type::BOOL:
@@ -699,7 +704,21 @@ bool ggml_openvino_npu_kv_head_major_enabled() {
}
bool ggml_openvino_npu_host_gather_enabled() {
- return ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_NPU_HOST_GATHER") != 0;
+ return ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_NPU_HOST_GATHER", 1) != 0;
+}
+
+ggml_openvino_rope_sincos_mode ggml_openvino_rope_sincos() {
+ const char * value = ggml_openvino_getenv_str("GGML_OPENVINO_ROPE_SINCOS", "auto");
+ if (strcmp(value, "host") == 0) {
+ return ggml_openvino_rope_sincos_mode::HOST;
+ }
+ if (strcmp(value, "device") == 0) {
+ return ggml_openvino_rope_sincos_mode::DEVICE;
+ }
+ if (strcmp(value, "device_f32") == 0) {
+ return ggml_openvino_rope_sincos_mode::DEVICE_F32;
+ }
+ return ggml_openvino_is_npu() ? ggml_openvino_rope_sincos_mode::HOST : ggml_openvino_rope_sincos_mode::DEVICE;
}
bool ggml_openvino_kv_only_prefill_enabled() {
@@ -958,6 +977,17 @@ bool ggml_openvino_kv_4d_enabled() {
return enabled;
}
+bool ggml_openvino_gpu_u2_matmul_broken() {
+ // OpenVINO 2026.5 and older: the GPU plugin runs oneDNN's u2 matmul in multi-token graphs so that later kernels fault (CL_OUT_OF_RESOURCES). Fixed in 2027.0.
+ static const bool broken = [] {
+ 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 < 2027;
+ }();
+ return broken && ggml_openvino_is_gpu();
+}
+
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);
@@ -1001,11 +1031,24 @@ static bool is_8bit_layout(ggml_type type) {
return type == GGML_TYPE_Q5_0 || type == GGML_TYPE_Q5_1 || type == GGML_TYPE_Q8_0;
}
+size_t ggml_openvino_u2_group_size(ggml_type type) {
+ switch (type) {
+ case GGML_TYPE_Q2_0:
+ return 64;
+ default:
+ return 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) {
return std::nullopt;
}
+ // 2-bit weights stay u2: a requant (4 bit or wider) makes them larger and loses the ternary FullyConnected path, the only one with the fused Hadamard input transform.
+ if (ggml_openvino_u2_group_size(tensor->type) != 0) {
+ return std::nullopt;
+ }
if (strncmp(tensor->name, "token_embd.weight", 17) == 0) {
if (ggml_openvino_is_npu()) {
if (auto npu_type = ggml_openvino_npu_token_embd_requant_type(tensor)) {
@@ -1276,14 +1319,21 @@ ggml_openvino_extracted_layout ggml_openvino_get_extracted_layout(const ggml_ten
case GGML_TYPE_Q5_K:
break;
+ case GGML_TYPE_Q2_0:
+ // Codes {0,1,2,3} dequantize as (code - 1) * scale. The zero point is the same for every block, so make_int2_weights emits it as a scalar and no zp array is stored (is_symmetric means "no per-block zp" here).
+ layout.is_u2 = true;
+ layout.weights_per_block = ggml_openvino_u2_group_size(tensor->type);
+ layout.is_symmetric = true;
+ break;
+
default:
// Unsupported quantization type
return layout;
}
// Calculate sizes
- // Weights: U4 = n_elements/2 bytes, U8 = n_elements bytes
- layout.weights_size = layout.is_u4 ? (n_elements / 2) : n_elements;
+ // Weights: U2 = n_elements/4 bytes, U4 = n_elements/2 bytes, U8 = n_elements bytes
+ layout.weights_size = layout.is_u2 ? (n_elements / 4) : (layout.is_u4 ? (n_elements / 2) : n_elements);
// Scales: F16 per block, except MXFP4 which stores one E8M0 byte per block.
int64_t n_blocks = n_elements / layout.weights_per_block;
diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h
index 2f805bb42..267ff32dc 100644
--- a/ggml/src/ggml-openvino/ggml-openvino-extra.h
+++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h
@@ -154,8 +154,7 @@ bool ggml_openvino_npu_l0_host_tensors_enabled();
// On by default: build the static prefill mask directly in the input tensor; GGML_OPENVINO_NPU_FAST_MASK=0 turns it off.
bool ggml_openvino_npu_fast_mask_enabled();
-// NPU-only opt-in performance toggles (all default off). Centralized here so each
-// env-var name lives in one place; see docs/backend/OPENVINO.md for semantics.
+// NPU-only performance toggles (defaults vary). Centralized here so each env-var name lives in one place; see docs/backend/OPENVINO.md for semantics.
bool ggml_openvino_npu_hfa_prefill_enabled();
bool ggml_openvino_npu_decode_unfold_enabled();
// Static path (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): prefill only the KV-writing part of the model
@@ -168,6 +167,10 @@ bool ggml_openvino_kv_only_prefill_enabled();
// binding the whole table to the NPU (NPUW lifts it to a function input, and gathering from an input that large
// costs about as much as streaming the table).
bool ggml_openvino_npu_host_gather_enabled();
+// Where ROPE computes cos/sin (GGML_OPENVINO_ROPE_SINCOS): f16 loses whole radians of the angle at long positions, which breaks long-context recall.
+// HOST: an f32 table built on the host (static graphs only), DEVICE: Sin/Cos on the device, DEVICE_F32: on the device with the angle kept in f32. "auto" is HOST on the NPU, else DEVICE.
+enum class ggml_openvino_rope_sincos_mode { DEVICE = 0, HOST = 1, DEVICE_F32 = 2 };
+ggml_openvino_rope_sincos_mode ggml_openvino_rope_sincos();
// GGML_OPENVINO_NPU_BLOB_PREBUILD (default 1), with GGML_OPENVINO_KV_SLICE on: static NPU decode also attends a KV
// window of base*2^k rows (clamped to ctx, base from GGML_OPENVINO_KV_SLICE) instead of the whole ctx, with one
@@ -280,6 +283,21 @@ void ggml_openvino_unregister_weight_buffer(const void * data);
void ggml_openvino_release_weight_buffers();
bool ggml_openvino_restore_weight_buffers();
+// With a GGML_OPENVINO_COMPILE_MEM_SPILL fraction, the limiters trim the spilled weights while the model loads, and while a scope is alive and for 10 s after; otherwise they sleep.
+// Hold one around compile_model (it reads the weights back) and around rewriting released weights.
+struct ggml_openvino_spill_trim_scope {
+ ggml_openvino_spill_trim_scope();
+ ~ggml_openvino_spill_trim_scope();
+ ggml_openvino_spill_trim_scope(const ggml_openvino_spill_trim_scope &) = delete;
+ ggml_openvino_spill_trim_scope & operator=(const ggml_openvino_spill_trim_scope &) = delete;
+};
+
+// Group size of a 2-bit type that is loaded as u2 weights, 0 for other types
+size_t ggml_openvino_u2_group_size(ggml_type type);
+
+// true if non-ternary 2-bit weights must reach the GPU as u4 (see make_int2_weights)
+bool ggml_openvino_gpu_u2_matmul_broken();
+
// 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);
@@ -357,6 +375,7 @@ struct ggml_openvino_extracted_layout {
size_t zp_offset = 0; // Offset to zero points in buffer
size_t zp_size = 0; // Size of zero points in bytes (U4 or U8)
bool is_u4; // true for U4 weights, false for U8
+ bool is_u2 = false; // true for 2-bit U2 weights (Q2_0); is_u4 is then false
int64_t weights_per_block; // weights per scale/zp block
bool is_symmetric; // true for symmetric quantization
diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp
index def89208a..848db4e08 100644
--- a/ggml/src/ggml-openvino/ggml-openvino.cpp
+++ b/ggml/src/ggml-openvino/ggml-openvino.cpp
@@ -13,7 +13,9 @@
#include <algorithm>
#include <atomic>
#include <cerrno>
+#include <chrono>
#include <climits>
+#include <condition_variable>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
@@ -33,7 +35,10 @@
#include <openvino/runtime/properties.hpp>
#include <openvino/runtime/tensor.hpp>
#include <string>
+#include <system_error>
+#include <thread>
#include <tuple>
+#include <utility>
#include <vector>
#ifdef _WIN32
@@ -47,6 +52,15 @@
# include <fcntl.h>
# include <sys/mman.h>
# include <unistd.h>
+# ifdef __linux__
+# include <linux/magic.h>
+# include <sys/vfs.h>
+# endif
+#endif
+
+// A GGML_OPENVINO_COMPILE_MEM_SPILL fraction needs MADV_PAGEOUT (Linux 5.4)
+#if defined(__linux__) && defined(MADV_PAGEOUT)
+# define GGML_OPENVINO_SPILL_LIMITER
#endif
// =====================================================
@@ -67,6 +81,201 @@
// =====================================================
namespace {
+// Live ggml_openvino_spill_trim_scope objects, and when the last one ended
+std::atomic<int> spill_scopes{0};
+std::atomic<int64_t> spill_scope_end_us{0};
+
+#ifdef GGML_OPENVINO_SPILL_LIMITER
+// GGML_OPENVINO_COMPILE_MEM_SPILL fraction: keep at most `budget` bytes of a spilled weight buffer in RAM. The kernel evicts file-backed pages only under memory pressure, so with free RAM the whole buffer stays resident.
+// A thread writes the dirty pages to the file and drops them: after every budget / 2 bytes of weight writes during load, and when the resident part exceeds the budget while a ggml_openvino_spill_trim_scope is alive and for 10 s after (the CPU plugin's first inference reads the weights too).
+class spill_resident_limiter {
+public:
+ spill_resident_limiter(void * data, size_t size, size_t budget) :
+ data_(data),
+ size_(size),
+ budget_(budget),
+ page_(static_cast<size_t>(sysconf(_SC_PAGESIZE))) {
+ thread_ = std::thread([this] { run(); });
+ }
+
+ ~spill_resident_limiter() {
+ {
+ std::lock_guard<std::mutex> lock(wake_mutex_);
+ stop_ = true;
+ }
+ wake_.notify_all();
+ thread_.join();
+ }
+
+ // Called after a write into the buffer. Written pages are resident, so the thread pages out after every budget / 2 bytes without measuring; it runs alongside because the disk write takes as long as the conversion.
+ void note_write(size_t bytes) {
+ if ((written_ += bytes) >= budget_ / 2) {
+ written_ = 0;
+ {
+ std::lock_guard<std::mutex> lock(wake_mutex_);
+ page_out_requested_ = true;
+ }
+ wake_.notify_all();
+ }
+ }
+
+private:
+ static bool in_scope() { return spill_scopes > 0 || ggml_time_us() - spill_scope_end_us < 10 * 1000 * 1000; }
+
+ // Stop at the first failed call: after a failed msync, dropping the pages could lose weights that are not on disk.
+ static void log_stop(const char * call) {
+ GGML_LOG_WARN("ggml-openvino: GGML_OPENVINO_COMPILE_MEM_SPILL: %s failed (%s), no limit from now on\n", call,
+ strerror(errno));
+ }
+
+ // Estimated from a sample, because mincore over every page takes ~65 ms for 7 GB. SIZE_MAX when mincore fails.
+ size_t resident_bytes() {
+ constexpr size_t run = 16, stride = 1024; // pages
+ unsigned char pages[run];
+ size_t sampled = 0, resident = 0;
+ for (size_t off = 0; off < size_; off += stride * page_) {
+ const size_t len = std::min(run * page_, size_ - off);
+ const size_t n = (len + page_ - 1) / page_;
+ if (mincore(static_cast<char *>(data_) + off, len, pages) != 0) {
+ log_stop("mincore");
+ return SIZE_MAX;
+ }
+ for (size_t i = 0; i < n; i++) {
+ resident += pages[i] & 1;
+ }
+ sampled += n;
+ }
+ return sampled ? static_cast<size_t>(double(resident) / sampled * size_) : 0;
+ }
+
+ // false when a call failed
+ bool page_out() {
+ // dirty file pages cannot be dropped until written back
+ if (msync(data_, size_, MS_SYNC) != 0) {
+ log_stop("msync");
+ return false;
+ }
+ if (madvise(data_, size_, MADV_PAGEOUT) != 0) {
+ log_stop("madvise(MADV_PAGEOUT)");
+ return false;
+ }
+ return true;
+ }
+
+ void run() {
+ std::unique_lock<std::mutex> lock(wake_mutex_);
+ while (!stop_) {
+ // outside of a scope only note_write brings work: the timeout only checks whether a scope started
+ const std::chrono::milliseconds wait(in_scope() ? 50 : 500);
+ wake_.wait_for(lock, wait, [this] { return stop_ || page_out_requested_; });
+ if (stop_) {
+ break;
+ }
+ const bool requested = std::exchange(page_out_requested_, false);
+ if (!requested && !in_scope()) {
+ continue;
+ }
+ lock.unlock();
+ const size_t resident = requested ? size_ : resident_bytes();
+ if (resident == SIZE_MAX || (resident > budget_ && !page_out())) {
+ return;
+ }
+ lock.lock();
+ }
+ }
+
+ void * data_;
+ size_t size_;
+ size_t budget_;
+ size_t page_;
+ size_t written_ = 0; // only the loading thread writes weights
+ std::mutex wake_mutex_;
+ std::condition_variable wake_;
+ bool stop_ = false;
+ bool page_out_requested_ = false;
+ std::thread thread_;
+};
+
+// Resident limit of a spilled buffer in bytes: the fraction of its size, at least 1 MiB. 0 (no limit) for 1, or when the limit is not smaller than the buffer.
+static size_t ggml_openvino_spill_resident_budget(size_t buffer_size, double fraction) {
+ if (!(fraction < 1)) {
+ return 0;
+ }
+ const size_t bytes = std::max<size_t>(static_cast<size_t>(buffer_size * fraction), 1024 * 1024);
+ return bytes < buffer_size ? bytes : 0;
+}
+#else
+struct spill_resident_limiter {
+ void note_write(size_t) {}
+};
+
+[[maybe_unused]] static size_t ggml_openvino_spill_resident_budget(size_t, double fraction) { // unused on Windows
+ // warn only when set explicitly, not through GGML_OPENVINO_MEMORY_OPTIMIZE
+ static std::atomic<bool> warned{false};
+ if (fraction < 1 && ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL") != nullptr &&
+ !warned.exchange(true)) {
+ GGML_LOG_WARN(
+ "ggml-openvino: a GGML_OPENVINO_COMPILE_MEM_SPILL fraction needs Linux 5.4 or later, spilling without a "
+ "limit\n");
+ }
+ return 0;
+}
+#endif
+
+#ifndef _WIN32
+// GGML_OPENVINO_COMPILE_MEM_SPILL (checked at startup): 0 off, 1 back the host buffers with files, a fraction also limits the spilled weights kept in RAM.
+// Unset: 0.1 with GGML_OPENVINO_MEMORY_OPTIMIZE=1 (not on NPU), else 0. Off in cache-only mode.
+static double ggml_openvino_spill_fraction() {
+ if (ggml_openvino_model_cache_only()) {
+ return 0;
+ }
+ if (const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL")) {
+ return std::strtod(v, nullptr);
+ }
+ return !ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0 ? 0.1 : 0;
+}
+
+// Back a buffer with an unlinked file in GGML_OPENVINO_COMPILE_MEM_SPILL_DIR via MAP_SHARED. Unlike anonymous pages, the kernel can write file-backed pages back and drop them, so the repacked weights need not stay resident next to the mmap'd GGUF.
+// Returns nullptr with a warning when the file cannot be made; the caller then uses anonymous memory.
+static void * ggml_openvino_spill_map(size_t size, const char * dir) {
+# ifdef __linux__
+ // On tmpfs or ramfs the file is RAM itself, and reserving its space below would make all of it resident at once.
+ struct statfs fs;
+ if (statfs(dir, &fs) == 0 && (fs.f_type == TMPFS_MAGIC || fs.f_type == RAMFS_MAGIC)) {
+ GGML_LOG_WARN("%s: the spill directory %s is in RAM (tmpfs), using anonymous memory\n", __func__, dir);
+ return nullptr;
+ }
+# endif
+ char path[PATH_MAX];
+ snprintf(path, sizeof(path), "%s/ggml-ov-weights-%d-XXXXXX", dir, (int) getpid());
+ const int fd = mkstemp(path);
+ if (fd < 0) {
+ GGML_LOG_WARN("%s: cannot create a spill file in %s (%s), using anonymous memory\n", __func__, dir,
+ strerror(errno));
+ return nullptr;
+ }
+ int err = unlink(path) == 0 && ftruncate(fd, (off_t) size) == 0 ? 0 : errno;
+# ifdef __linux__
+ // Reserve the disk space now: on a full disk, the first write to a page of a sparse file raises SIGBUS. A filesystem without fallocate keeps the sparse file; copy-on-write filesystems (btrfs, ZFS) can still need space on a rewrite.
+ if (err == 0 && fallocate(fd, 0, 0, (off_t) size) != 0 && errno != EOPNOTSUPP) {
+ err = errno;
+ }
+# endif
+ void * m = MAP_FAILED;
+ if (err == 0) {
+ m = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+ err = m == MAP_FAILED ? errno : 0;
+ }
+ close(fd); // the mapping keeps the file alive
+ if (err != 0) {
+ GGML_LOG_WARN("%s: cannot spill %zu MB to %s (%s), using anonymous memory\n", __func__, size / 1024 / 1024, dir,
+ strerror(err));
+ return nullptr;
+ }
+ return m;
+}
+#endif
+
// Buffer context that manages per-tensor allocations (no contiguous buffer for weights)
struct ggml_backend_openvino_buffer_context {
int device;
@@ -99,6 +308,11 @@ struct ggml_backend_openvino_buffer_context {
// data is in the weight buffer registry
bool weight_registered = false;
+ // Set for a spilled buffer with a fraction. The limiter starts at the first weight write: the buffer usage is not known at allocation, and KV cache and compute buffers must not be paged out.
+ std::unique_ptr<spill_resident_limiter> spill_limiter;
+ size_t spill_budget = 0;
+ // source mappings already evicted once under the budget
+ std::vector<uintptr_t> evicted_sources;
// One counter for both constructors: the id is part of the weight identity in the graph key, so a host-pointer
// buffer and an allocated buffer must never share one.
@@ -168,55 +382,31 @@ struct ggml_backend_openvino_buffer_context {
data = nullptr;
}
}
- if (data != nullptr) {
- // backed by the Level Zero host tensor above
- } else
+ if (data == nullptr) {
#ifndef _WIN32
- if (const char * spill_dir =
- ggml_openvino_model_cache_only() ? nullptr : ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR")) {
- // Disk-backed weight buffer: back the repacked weights with a temp file via MAP_SHARED
- // instead of anonymous memory. Anonymous pages can only be evicted to swap, so the
- // repacked buffer stays pinned alongside the mmap'd source and both are resident at once
- // -- that double residency is the load-time peak. File-backed pages are reclaimable: the
- // kernel can write them back and drop them under pressure, then re-read on demand, so RSS
- // becomes a working set rather than the whole buffer. The file is unlinked immediately,
- // so it disappears when the process exits.
- //
- // The directory must be real storage. Pointing this at a tmpfs mount (/tmp on many
- // systems) backs the "spill" with RAM and makes matters worse.
- char path[PATH_MAX];
- snprintf(path, sizeof(path), "%s/ggml-ov-weights-%d-XXXXXX", spill_dir, (int) getpid());
- int fd = mkstemp(path);
- if (fd < 0) {
- GGML_LOG_ERROR("%s: mkstemp(%s) failed: %s\n", __func__, path, strerror(errno));
- return;
- }
- unlink(path); // anonymous-but-file-backed: freed on process exit
- if (ftruncate(fd, (off_t) size) != 0) {
- GGML_LOG_ERROR("%s: ftruncate(%zu) failed: %s\n", __func__, size, strerror(errno));
- close(fd);
- return;
- }
- void * m = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
- close(fd); // the mapping keeps the file alive
- if (m == MAP_FAILED) {
- GGML_LOG_ERROR("%s: mmap(%zu) failed: %s\n", __func__, size, strerror(errno));
- return;
+ if (const double spill = ggml_openvino_spill_fraction(); spill > 0) {
+ const char * spill_dir =
+ ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL_DIR", "/var/tmp");
+ data = ggml_openvino_spill_map(size, spill_dir);
+ if (data != nullptr) {
+ spill_mapping = data;
+ spill_size = size;
+ GGML_LOG_INFO("%s: buffer spilled to %s (%zu MB, file-backed)\n", __func__, spill_dir,
+ size / 1024 / 1024);
+ spill_budget = ggml_openvino_spill_resident_budget(size, spill);
+ ov_buffer = std::make_shared<ov::Tensor>(ov::element::u8, ov::Shape{size}, data);
+ }
}
- data = m;
- spill_mapping = m;
- spill_size = size;
- GGML_LOG_INFO("%s: weight buffer spilled to %s (%zu MB, file-backed)\n", __func__, spill_dir,
- size / 1024 / 1024);
- ov_buffer = std::make_shared<ov::Tensor>(ov::element::u8, ov::Shape{size}, data);
- } else
-#endif
- {
-#ifdef _WIN32
- if (!ggml_openvino_model_cache_only() && ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR")) {
- GGML_LOG_WARN("%s: GGML_OPENVINO_SPILL_DIR is not supported on Windows, ignoring\n", __func__);
+#else
+ // only when set explicitly, not through GGML_OPENVINO_MEMORY_OPTIMIZE
+ const char * spill = ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL");
+ if (spill != nullptr && std::strtod(spill, nullptr) > 0) {
+ GGML_LOG_WARN("%s: GGML_OPENVINO_COMPILE_MEM_SPILL is not supported on Windows, ignoring\n",
+ __func__);
}
#endif
+ }
+ if (data == nullptr) {
// Anonymous OS memory reads as zero without being touched, so a buffer becomes resident only as it
// is written: a weight buffer tensor by tensor while the model loads, the host-untouched prefill
// compute buffer never.
@@ -265,6 +455,7 @@ struct ggml_backend_openvino_buffer_context {
if (kv_on_demand) {
ggml_openvino_kv_storage_unregister(data, size);
}
+ spill_limiter.reset(); // its thread reads the mapping
if (spill_mapping != nullptr) {
#ifdef _WIN32
VirtualFree(spill_mapping, 0, MEM_RELEASE);
@@ -463,6 +654,15 @@ void ggml_openvino_unregister_weight_buffer(const void * data) {
reg.buffers.end());
}
+ggml_openvino_spill_trim_scope::ggml_openvino_spill_trim_scope() {
+ spill_scopes++;
+}
+
+ggml_openvino_spill_trim_scope::~ggml_openvino_spill_trim_scope() {
+ spill_scope_end_us = ggml_time_us();
+ spill_scopes--;
+}
+
void ggml_openvino_release_weight_buffers() {
auto & reg = ov_weight_registry();
std::lock_guard<std::mutex> lock(reg.mutex);
@@ -503,6 +703,7 @@ void ggml_openvino_release_weight_buffers() {
bool ggml_openvino_restore_weight_buffers() {
auto & reg = ov_weight_registry();
std::lock_guard<std::mutex> lock(reg.mutex);
+ ggml_openvino_spill_trim_scope trim_scope;
return ov_restore_weight_buffers(reg);
}
@@ -513,6 +714,7 @@ static void ggml_openvino_keep_weight_buffers() {
if (reg.keep) {
return;
}
+ ggml_openvino_spill_trim_scope trim_scope;
if (!ov_restore_weight_buffers(reg)) {
GGML_ABORT("ggml-openvino: cannot write the released host weights again");
}
@@ -719,6 +921,47 @@ static bool ggml_openvino_range_has_locked_pages(uintptr_t first, uintptr_t last
}
#endif
+#ifdef GGML_OPENVINO_SPILL_LIMITER
+// Spilled buffer with a fraction: start the limiter at the first weight, and evict the GGUF pages once. llama.cpp maps the GGUF with MAP_POPULATE, so after the eviction each tensor is read from disk when it is converted.
+// The GGUF madvise calls are hints: with --mlock they fail and the pages stay.
+static void ggml_openvino_spill_before_weight_write(ggml_backend_openvino_buffer_context * ctx,
+ const void * data,
+ size_t size) {
+ if (ctx->spill_budget == 0) {
+ return;
+ }
+ if (!ctx->spill_limiter) { // set_tensor does not run concurrently on one buffer
+ try {
+ ctx->spill_limiter =
+ std::make_unique<spill_resident_limiter>(ctx->spill_mapping, ctx->spill_size, ctx->spill_budget);
+ } catch (const std::system_error & e) {
+ GGML_LOG_WARN("%s: cannot start the GGML_OPENVINO_COMPILE_MEM_SPILL thread (%s), no limit\n", __func__,
+ e.what());
+ ctx->spill_budget = 0;
+ return;
+ }
+ GGML_LOG_INFO(
+ "%s: at most %zu of %zu MB of the spilled weights stay in RAM (GGML_OPENVINO_COMPILE_MEM_SPILL)\n",
+ __func__, ctx->spill_budget / 1024 / 1024, ctx->spill_size / 1024 / 1024);
+ }
+ const ggml_openvino_source_mapping * mapping = ggml_openvino_find_source_mapping(data, size, ctx->source_mappings);
+ if (mapping == nullptr) {
+ return;
+ }
+ if (mapping->read_only && std::find(ctx->evicted_sources.begin(), ctx->evicted_sources.end(), mapping->begin) ==
+ ctx->evicted_sources.end()) {
+ ctx->evicted_sources.push_back(mapping->begin);
+ madvise(reinterpret_cast<void *>(mapping->begin), mapping->end - mapping->begin, MADV_PAGEOUT);
+ }
+ // read this tensor back in large requests rather than one page fault at a time
+ const uintptr_t page = (uintptr_t) sysconf(_SC_PAGESIZE);
+ const uintptr_t first = (uintptr_t) data & ~(page - 1);
+ madvise(reinterpret_cast<void *>(first), (uintptr_t) data + size - first, MADV_WILLNEED);
+}
+#else
+static void ggml_openvino_spill_before_weight_write(ggml_backend_openvino_buffer_context *, const void *, size_t) {}
+#endif
+
// A weight's GGUF bytes have been converted into its OpenVINO buffer. Pages of a read-only file mapping are clean and
// come back from the file if they are read again, so release them instead of letting them compete with the buffer for
// RAM while the model loads. Only whole pages are released, and locked pages (--load-mode mlock) are kept.
@@ -746,6 +989,12 @@ static void ggml_openvino_release_source_pages(ggml_backend_openvino_buffer_cont
VirtualUnlock(reinterpret_cast<void *>(first), last - first);
}
#elif defined(__linux__)
+# ifdef GGML_OPENVINO_SPILL_LIMITER
+ if (ctx->spill_limiter) {
+ // under a resident budget the GGUF's page cache must go too, not only this process's mapping of it
+ madvise(reinterpret_cast<void *>(first), last - first, MADV_PAGEOUT); // a hint, as above
+ }
+# endif
// MADV_DONTNEED fails on locked (mlock) memory and leaves it resident
madvise(reinterpret_cast<void *>(first), last - first, MADV_DONTNEED);
#endif
@@ -786,6 +1035,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
memcpy(tensor->data, data, size);
return;
}
+ ggml_openvino_spill_before_weight_write(ctx, data, size);
try {
auto result = process_weight_tensor(tensor, data, tensor->data);
result.weight_node->set_friendly_name(tensor->name);
@@ -811,6 +1061,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
if (!ctx->external_memory) {
ggml_openvino_release_source_pages(ctx, data, size);
}
+ if (ctx->spill_limiter) {
+ ctx->spill_limiter->note_write(ggml_nbytes(tensor));
+ }
} 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);
@@ -820,6 +1073,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
}
} else {
// Non-weight tensor (KV cache, activations, etc.) - copy data. test-backend-ops also goes here
+ if (is_weight_buffer) {
+ ggml_openvino_spill_before_weight_write(ctx, data, size);
+ }
if (ctx->is_remote) {
cl_command_queue queue = ggml_openvino_get_cl_queue(ggml_openvino_get_available_devices()[ctx->device]);
auto mem_cpy_fn = ggml_openvino_get_clEnqueueMemcpyINTEL();
@@ -840,6 +1096,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
if (is_weight_buffer && !ctx->is_remote) {
ggml_openvino_record_weight_write(buffer, tensor, offset, data, size, false);
}
+ if (is_weight_buffer && ctx->spill_limiter) {
+ ctx->spill_limiter->note_write(size);
+ }
if (ggml_openvino_extra_unchanged(ctx, tensor)) {
return;
@@ -2280,8 +2539,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
!ov::frontend::ggml::op::gdn_per_key_gate_supported()) {
reason = "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 gate for state "
"snapshots or the native state layout";
- }
- else if (op->op_params[0] > 1) {
+ } else if (op->op_params[0] > 1) {
if (ggml_openvino_is_static()) {
reason = "GATED_DELTA_NET snapshots require dynamic execution";
}
@@ -2317,6 +2575,13 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
if (ggml_openvino_is_static()) {
return {false, "SSM_SCAN requires dynamic execution"};
}
+ // x, B and C are read as token-major views (the Mamba-2 graph layout); a view with a sequence stride smaller than its token stride gives wrong results.
+ for (int i : {1, 4, 5}) {
+ const ggml_tensor * t = op->src[i];
+ if (t->ne[2] > 1 && t->ne[3] > 1 && t->nb[3] < t->nb[2]) {
+ return {false, "SSM_SCAN with sequence-major x, B or C is not supported"};
+ }
+ }
break;
}
case GGML_OP_VIEW: {
@@ -2455,7 +2720,7 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg
static std::unordered_set<ggml_type> supported_types{
GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_I64, GGML_TYPE_I32, GGML_TYPE_Q4_0,
GGML_TYPE_Q4_1, GGML_TYPE_Q4_K, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q5_K, GGML_TYPE_Q8_0, GGML_TYPE_Q6_K,
- GGML_TYPE_MXFP4};
+ GGML_TYPE_MXFP4, GGML_TYPE_Q2_0};
// derive supported op sets from the op_table map, keys in
// the map use the full macro name (e.g. "GGML_OP_ADD"), while
diff --git a/ggml/src/ggml-openvino/ggml-quants.cpp b/ggml/src/ggml-openvino/ggml-quants.cpp
index 0c0501fec..3793c6012 100644
--- a/ggml/src/ggml-openvino/ggml-quants.cpp
+++ b/ggml/src/ggml-openvino/ggml-quants.cpp
@@ -6,6 +6,7 @@
#include "ggml.h"
#include <algorithm>
+#include <atomic>
#include <cassert>
#include <cmath>
#include <cstddef>
@@ -57,6 +58,8 @@ void unpack_32_4(const uint8_t * data, uint8_t * dst) {
}
}
+constexpr size_t Q2_0_BLOCK_SIZE = 64; // QK2_0
+
constexpr size_t MXFP4_BLOCK_SIZE = 32;
constexpr size_t MXFP4_BLOCK_QS_SIZE = MXFP4_BLOCK_SIZE / 2;
constexpr size_t MXFP4_BLOCK_BYTES = sizeof(uint8_t) + MXFP4_BLOCK_QS_SIZE;
@@ -89,6 +92,47 @@ void extract_mxfp4_data(const ggml_tensor * tensor, ov::Tensor & weights_arr, ov
});
}
+// Extracts (weight, scales) from 2-bit tensors loaded as u2 (see ggml_openvino_u2_group_size). Layout: |16 bit scale|group x 2 bit codes|, code j at bits [2*(j%4), +1] of byte j/4.
+// OpenVINO packs u2 the same way, so the codes are copied as they are, in the {0,1,2,3} encoding; make_int2_weights subtracts the scalar zero point of 1.
+// scales_arr may hold one scale per several blocks (see q2_0_is_group_128); the first block's scale is kept.
+void extract_2bit_data(const ggml_tensor * tensor, size_t group_size, ov::Tensor & weights_arr, ov::Tensor & scales_arr) {
+ GGML_ASSERT(weights_arr.get_element_type() == ov::element::u2);
+
+ const size_t qs_size = group_size / 4;
+ const size_t block_bytes = sizeof(uint16_t) + qs_size;
+ const size_t n_blocks = ggml_nelements(tensor) / group_size;
+ const size_t blocks_per_scale = n_blocks / scales_arr.get_size();
+ const auto * data = static_cast<const uint8_t *>(tensor->data);
+ auto * weights = static_cast<uint8_t *>(weights_arr.data());
+ auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
+
+ ov::parallel_for(n_blocks, [&](size_t i) {
+ const uint8_t * block = data + i * block_bytes;
+ if (i % blocks_per_scale == 0) {
+ scales[i / blocks_per_scale] = ov::float16::from_bits(*((const uint16_t *) block));
+ }
+ memcpy(weights + i * qs_size, block + sizeof(uint16_t), qs_size);
+ });
+}
+
+// Q2_0 files made from group-128 ternary checkpoints store each scale twice. Such a tensor is loaded at group 128 (same values), which the GPU ternary FullyConnected kernel requires.
+bool q2_0_is_group_128(const ggml_tensor * tensor, const void * data) {
+ if (tensor->type != GGML_TYPE_Q2_0 || tensor->ne[0] % 128 != 0) {
+ return false;
+ }
+ constexpr size_t block_bytes = sizeof(uint16_t) + Q2_0_BLOCK_SIZE / 4;
+ const auto * blocks = static_cast<const uint8_t *>(data);
+ const size_t n_pairs = ggml_nelements(tensor) / 128;
+ std::atomic<bool> equal{true};
+ ov::parallel_for(n_pairs, [&](size_t i) {
+ const uint8_t * b = blocks + 2 * i * block_bytes;
+ if (memcmp(b, b + block_bytes, sizeof(uint16_t)) != 0) {
+ equal.store(false, std::memory_order_relaxed);
+ }
+ });
+ return equal.load();
+}
+
// Extracts (weight, scales, zp) from Q4_0 tensors.
// Data layout is: |16 bit scale|32 x 4bit weights|.
// When zp_arr is empty (symmetric), weights are stored as signed i4 (value - 8).
@@ -767,6 +811,75 @@ ov::Output<ov::Node> make_int4_weights(ov::Tensor & weight,
return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);
}
+// True if any u2 code is 3, i.e. the weights are not ternary {-1, 0, +1}.
+bool u2_has_code_3(const ov::Tensor & weight) {
+ const auto * data = static_cast<const uint8_t *>(weight.data());
+ const size_t size = weight.get_byte_size();
+ constexpr size_t chunk = 1 << 16;
+ std::atomic<bool> found{false};
+ ov::parallel_for((size + chunk - 1) / chunk, [&](size_t c) {
+ uint8_t acc = 0;
+ for (size_t i = c * chunk; i < std::min(size, (c + 1) * chunk); ++i) {
+ acc |= data[i] & (data[i] >> 1);
+ }
+ if (acc & 0x55) {
+ found.store(true, std::memory_order_relaxed);
+ }
+ });
+ return found.load();
+}
+
+// Decompression chain for u2 weights: (code - 1) * scale, grouped along the last axis, with one scalar zero point.
+// Ternary weights at group 128 get the zero point as an f16 Constant (the GPU ternary FullyConnected kernel needs it); others get a Convert of an integer one (oneDNN's u2 matmul needs it). Where that matmul is broken, the others are unpacked to u4 (twice the memory).
+ov::Output<ov::Node> make_int2_weights(ov::Tensor & weight, ov::Tensor & scales, size_t group_size) {
+ const ov::Shape orig_weight_shape = weight.get_shape();
+ GGML_ASSERT(!orig_weight_shape.empty());
+ GGML_ASSERT(orig_weight_shape.back() % group_size == 0);
+
+ ov::Shape packed_shape = orig_weight_shape;
+ packed_shape.back() /= group_size;
+ packed_shape.push_back(group_size);
+
+ ov::Shape scale_shape = scales.get_shape();
+ scale_shape.push_back(1);
+ scales.set_shape(scale_shape);
+
+ const bool ternary = group_size == 128 && !u2_has_code_3(weight);
+ std::shared_ptr<ov::op::v0::Constant> weights_node;
+ if (!ternary && ggml_openvino_gpu_u2_matmul_broken()) {
+ ov::Tensor codes(ov::element::u4, packed_shape);
+ const auto * src = static_cast<const uint8_t *>(weight.data());
+ auto * dst = static_cast<uint8_t *>(codes.data());
+ // 4 codes of a u2 byte become 2 u4 bytes, low code first
+ ov::parallel_for(weight.get_byte_size(), [&](size_t i) {
+ const uint8_t b = src[i];
+ dst[2 * i] = uint8_t((b & 0x3) | ((b & 0xc) << 2));
+ dst[2 * i + 1] = uint8_t(((b >> 4) & 0x3) | ((b >> 2) & 0x30));
+ });
+ weights_node = std::make_shared<ov::op::v0::Constant>(codes);
+ } else {
+ weights_node = std::make_shared<ov::op::v0::Constant>(ov::element::u2, packed_shape, weight.data(), nullptr);
+ weights_node->get_rt_info()["__gguf_tensor_holder"] = weight;
+ }
+ auto weights_f16 = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f16);
+
+ ov::Output<ov::Node> zero_point = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {1.0f});
+ if (!ternary) {
+ zero_point = std::make_shared<ov::op::v0::Convert>(
+ ov::op::v0::Constant::create(ov::element::u8, ov::Shape{}, {1}), ov::element::f16);
+ }
+ auto w_zp = std::make_shared<ov::op::v1::Subtract>(weights_f16, zero_point, ov::op::AutoBroadcastType::NUMPY);
+
+ auto scales_f16 = std::make_shared<ov::op::v0::Constant>(scales);
+ ov::Output<ov::Node> result =
+ std::make_shared<ov::op::v1::Multiply>(w_zp, scales_f16, ov::op::AutoBroadcastType::NUMPY);
+
+ auto final_shape = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_weight_shape.size()},
+ orig_weight_shape);
+ result = std::make_shared<ov::op::v1::Reshape>(result, final_shape, false);
+ return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);
+}
+
ov::Output<ov::Node> make_mxfp4_weights(ov::Tensor & weight, ov::Tensor & scales) {
const ov::Shape final_shape = weight.get_shape();
GGML_ASSERT(!final_shape.empty());
@@ -1075,6 +1188,14 @@ std::shared_ptr<ov::Node> extract_quantized_weights(const ggml_tensor * tensor,
return result;
}
+ if (const size_t group_size_2bit = ggml_openvino_u2_group_size(tensor->type)) {
+ extract_2bit_data(&temp_tensor, group_size_2bit, weights, scales);
+ const size_t group_size = ggml_nelements(tensor) / scales.get_size();
+ auto result = make_int2_weights(weights, scales, group_size).get_node_shared_ptr();
+ result->set_friendly_name(tensor->name);
+ return result;
+ }
+
// Determine block size based on tensor type
int64_t weights_per_block;
bool is_u4;
@@ -1358,13 +1479,16 @@ OvWeight process_weight_tensor(const ggml_tensor * tensor, const void * data, vo
ov::element::Type weight_type;
if (tensor->type == GGML_TYPE_MXFP4) {
weight_type = ov::element::f4e2m1;
+ } else if (layout.is_u2) {
+ weight_type = ov::element::u2;
} else if (layout.is_symmetric) {
weight_type = layout.is_u4 ? ov::element::i4 : ov::element::i8;
} else {
weight_type = layout.is_u4 ? ov::element::u4 : ov::element::u8;
}
ov::Shape scale_shape = node_shape;
- scale_shape.back() /= layout.weights_per_block;
+ // A merged Q2_0 tensor needs half the scales the layout reserves.
+ scale_shape.back() /= q2_0_is_group_128(tensor, data) ? 128 : layout.weights_per_block;
if (tensor->type == GGML_TYPE_MXFP4) {
if (tensor->ne[2] == 1 && tensor->ne[3] == 1) {
diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp
index 338b81aa5..bb1ef8969 100644
--- a/ggml/src/ggml-openvino/model-cache.cpp
+++ b/ggml/src/ggml-openvino/model-cache.cpp
@@ -147,7 +147,6 @@ static const char * cache_settings[] = {
"GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK",
"GGML_OPENVINO_KV_SCATTER_ELEMENTS",
"GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN",
- "GGML_OPENVINO_ROPE_F32_ANGLE",
};
void ggml_openvino_model_cache_init() {
@@ -170,7 +169,8 @@ void ggml_openvino_model_cache_init() {
#endif
if (cache_only) {
auto & config = ggml_openvino_get_device_config();
- config.environment_variables.erase("GGML_OPENVINO_SPILL_DIR");
+ config.environment_variables.erase("GGML_OPENVINO_COMPILE_MEM_SPILL");
+ config.environment_variables.erase("GGML_OPENVINO_COMPILE_MEM_SPILL_DIR");
config.environment_variables["GGML_OPENVINO_RELEASE_WEIGHTS"] = "0";
}
}
@@ -294,7 +294,10 @@ uint64_t ggml_openvino_source_fingerprint(const void * data, size_t size, std::v
if (const auto * m = ggml_openvino_find_source_mapping(data, size, mappings)) {
return fnv1a_u64(m->identity, m->offset + reinterpret_cast<uintptr_t>(data) - m->begin);
}
- if (ggml_openvino_model_cache_only()) {
+ // A small weight outside any file mapping was built in memory by the model loader (e.g. the Bonsai 2 Hadamard matrix). It is deterministic, and the export run identified it by the content hash below, so cache-only mode can too.
+ // Only large unmapped weights mean the model itself was not mmap-loaded.
+ constexpr size_t MAX_UNMAPPED_WEIGHT_BYTES = 64u << 20;
+ if (ggml_openvino_model_cache_only() && size > MAX_UNMAPPED_WEIGHT_BYTES) {
GGML_ABORT("ggml-openvino: could not identify mapped GGUF weight; use --load-mode mmap");
}
uint64_t h = FNV_OFFSET;
@@ -358,7 +361,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph,
// 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);
+ // Version 14 hashes the effective GGML_OPENVINO_ROPE_SINCOS (in extra_cfg) instead of GGML_OPENVINO_ROPE_F32_ANGLE.
+ h = fnv1a_u64(h, 14);
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/openvino/decoder.h b/ggml/src/ggml-openvino/openvino/decoder.h
index a26ce617b..8d314b42a 100644
--- a/ggml/src/ggml-openvino/openvino/decoder.h
+++ b/ggml/src/ggml-openvino/openvino/decoder.h
@@ -121,6 +121,9 @@ public:
virtual int32_t * get_rope_params() const = 0;
+ // KV cache size in cells (0 if unknown).
+ virtual int get_ctx_size() const { return 0; }
+
virtual int get_ssm_state_size() const = 0;
virtual std::map<std::string, std::string> get_kv_param_res_names() const = 0;
diff --git a/ggml/src/ggml-openvino/openvino/node_context.h b/ggml/src/ggml-openvino/openvino/node_context.h
index a11573216..7e978860b 100644
--- a/ggml/src/ggml-openvino/openvino/node_context.h
+++ b/ggml/src/ggml-openvino/openvino/node_context.h
@@ -169,6 +169,8 @@ public:
int get_ssm_state_size() const { return m_decoder->get_ssm_state_size(); }
+ int get_ctx_size() const { return m_decoder->get_ctx_size(); }
+
private:
std::shared_ptr<GgmlDecoder> m_decoder;
std::shared_ptr<TensorMap> & m_tensor_map;
diff --git a/ggml/src/ggml-openvino/openvino/op/cont.cpp b/ggml/src/ggml-openvino/openvino/op/cont.cpp
index 7ea7ee083..3eb3618ce 100644
--- a/ggml/src/ggml-openvino/openvino/op/cont.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/cont.cpp
@@ -17,9 +17,9 @@ 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();
+ auto input = process_view_input_new(context, 0);
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());
@@ -28,12 +28,16 @@ OutputVector translate_cont(const NodeContext & context) {
return rename_outputs_with_suffix({std::make_shared<ov::op::v1::Reshape>(input, target, false)}, context.get_name());
}
+ // A shape-preserving copy of a recurrent view keeps the runtime sequence and token axes.
+ if (!context.is_static() && !context.is_stateful() && context.get_view_input_size(0) > 0 &&
+ src_shape == dst_shape && input.get_partial_shape().compatible(dst_shape)) {
+ return {input};
+ }
+
if (context.get_op_dynamic_dim() != -1) {
dst_shape[3 - context.get_op_dynamic_dim()] = -1;
}
- auto input = process_view_input_new(context, 0);
-
ov::Output<Node> res;
res = std::make_shared<ov::op::v1::Reshape>(
input, ov::op::v0::Constant::create(ov::element::i64, {dst_shape.size()}, dst_shape), false);
diff --git a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp
index 402d14b99..4e40389a0 100644
--- a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp
@@ -221,9 +221,8 @@ OutputVector translate_get_rows(const NodeContext & context) {
auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {1});
res = std::make_shared<ov::op::v8::Gather>(data, indices, axis, 1);
} else {
- // For a tied embedding the same weight also feeds the lm_head matmul. Gathering the
- // dequantized table would give that dequantization chain a second consumer, forcing the
- // full table to be materialized; gather the packed rows instead and dequantize those.
+ // For a tied embedding the same weight also feeds the lm_head matmul: gather the packed rows and dequantize those, so the dequantized table does not get a second consumer that forces it to be materialized in full.
+ // The same holds for a 2-bit u2 table, which the plugins do not gather correctly in compressed form.
if (auto compressed = gather_compressed_rows(data, indices)) {
res = compressed;
} else {
diff --git a/ggml/src/ggml-openvino/openvino/op/mul.cpp b/ggml/src/ggml-openvino/openvino/op/mul.cpp
new file mode 100644
index 000000000..c8eeb266c
--- /dev/null
+++ b/ggml/src/ggml-openvino/openvino/op/mul.cpp
@@ -0,0 +1,39 @@
+#include "../op_table.h"
+#include "../utils.h"
+
+#include <openvino/op/constant.hpp>
+#include <openvino/op/multiply.hpp>
+#include <openvino/op/reshape.hpp>
+#include <openvino/op/shape_of.hpp>
+
+namespace ov::frontend::ggml::op {
+
+OutputVector translate_mul(const NodeContext & context) {
+ if (context.get_op_case() != 1) {
+ return translate_1to1_match_2_inputs<ov::op::v1::Multiply>(context);
+ }
+
+ num_inputs_check(context, 2, 2);
+ auto norm = process_view_input_new(context, 0);
+ auto weight = process_view_input_new(context, 1);
+ if (weight.get_element_type() != norm.get_element_type()) {
+ weight = std::make_shared<ov::op::v0::Convert>(weight, ov::element::f32);
+ norm = std::make_shared<ov::op::v0::Convert>(norm, ov::element::f32);
+ }
+
+ // The GPU RMS kernel shares one weight vector across rows. Apply weights with the groups flattened.
+ const auto weight_shape = context.get_input_shape(1).to_shape();
+ const auto width = static_cast<int64_t>(weight_shape[2] * weight_shape[3]);
+ auto norm_shape = ov::op::v0::Constant::create<int64_t>(ov::element::i64, {4}, {1, 1, -1, width});
+ auto flat_weight_shape = ov::op::v0::Constant::create<int64_t>(ov::element::i64, {4}, {1, 1, 1, width});
+ auto flat_norm = std::make_shared<ov::op::v1::Reshape>(norm, norm_shape, false);
+ auto flat_weight = std::make_shared<ov::op::v1::Reshape>(weight, flat_weight_shape, false);
+ ov::Output<ov::Node> output = std::make_shared<ov::op::v1::Multiply>(flat_norm, flat_weight);
+ if (output.get_element_type() != context.get_output_type()) {
+ output = std::make_shared<ov::op::v0::Convert>(output, context.get_output_type());
+ }
+ auto shape = std::make_shared<ov::op::v3::ShapeOf>(norm);
+ return rename_outputs_with_suffix({std::make_shared<ov::op::v1::Reshape>(output, shape, false)}, context.get_name());
+}
+
+} // namespace ov::frontend::ggml::op
diff --git a/ggml/src/ggml-openvino/openvino/op/rope.cpp b/ggml/src/ggml-openvino/openvino/op/rope.cpp
index c8703747c..6fba35f84 100644
--- a/ggml/src/ggml-openvino/openvino/op/rope.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/rope.cpp
@@ -1,16 +1,24 @@
#include "../node_context.h"
#include "../op_table.h"
#include "../utils.h"
+#include "ggml-impl.h"
+#include "ggml-openvino/ggml-openvino-extra.h"
#include <cstdint>
+#include <map>
#include <memory>
+#include <mutex>
+#include <numeric>
+#include <openvino/core/model.hpp>
#include <openvino/core/node.hpp>
#include <openvino/core/node_output.hpp>
#include <openvino/op/add.hpp>
#include <openvino/op/broadcast.hpp>
+#include <openvino/op/clamp.hpp>
#include <openvino/op/concat.hpp>
#include <openvino/op/constant.hpp>
#include <openvino/op/convert.hpp>
+#include <openvino/op/gather.hpp>
#include <openvino/op/multiply.hpp>
#include <openvino/op/reshape.hpp>
#include <openvino/op/slice.hpp>
@@ -18,6 +26,8 @@
#include <openvino/op/subtract.hpp>
#include <openvino/op/unsqueeze.hpp>
#include <openvino/op/variadic_split.hpp>
+#include <openvino/pass/constant_folding.hpp>
+#include <openvino/pass/manager.hpp>
#include <vector>
namespace ov {
@@ -25,6 +35,88 @@ namespace frontend {
namespace ggml {
namespace op {
+namespace {
+
+constexpr int TYPE_NORMAL = 0;
+constexpr int TYPE_NEOX = 1;
+constexpr int TYPE_IMROPE = 2;
+constexpr int TYPE_VISION = 3;
+constexpr int TYPE_MROPE = 4;
+
+// RoPE tables are f16 constants, one per content for the whole process, never freed (as gdn_chunk_mask). The shared NPUW weights bank identifies a constant by its data pointer and keeps it after its model is gone, so a later table at a freed address would be read as the old one.
+std::shared_ptr<ov::op::v0::Constant> rope_table_f16(const std::shared_ptr<ov::op::v0::Constant> & table) {
+ static std::mutex mutex;
+ static std::map<std::pair<std::vector<size_t>, std::vector<float>>, std::shared_ptr<ov::op::v0::Constant>> cache;
+ std::pair<std::vector<size_t>, std::vector<float>> key{table->get_shape(), table->cast_vector<float>()};
+ std::lock_guard<std::mutex> lock(mutex);
+ auto & f16 = cache[key];
+ if (!f16) {
+ f16 = std::make_shared<ov::op::v0::Constant>(ov::element::f16, table->get_shape(), key.second);
+ }
+ return f16;
+}
+
+// GGML_OPENVINO_ROPE_SINCOS=host: build make_sin_cos for positions 0..ctx-1, fold it on the host in f32, and gather the rows of inp_pos.
+// Returns false (sin_cos unset) when the table does not apply; the caller then builds the angle-based subgraph.
+bool make_rope_table(const NodeContext & context,
+ int32_t * op_params,
+ const std::shared_ptr<ov::Node> & inp_pos,
+ const std::shared_ptr<ov::Node> & rope_freqs_weight,
+ int mode,
+ int64_t head_dim,
+ std::pair<Output<Node>, Output<Node>> & sin_cos) {
+ const int64_t n_pos = context.get_ctx_size();
+ if (ggml_openvino_rope_sincos() != ggml_openvino_rope_sincos_mode::HOST || !context.is_static() ||
+ context.is_stateful() || (mode != TYPE_NORMAL && mode != TYPE_NEOX) || n_pos <= 0) {
+ return false;
+ }
+ // Frequency factors that arrive as a Parameter cannot be folded.
+ if (rope_freqs_weight && !ov::as_type_ptr<ov::op::v0::Constant>(rope_freqs_weight)) {
+ static std::once_flag warned;
+ std::call_once(warned, [] {
+ GGML_LOG_WARN(
+ "ggml-openvino: RoPE frequency factors are not a constant, so the RoPE angles are computed "
+ "on the device; long contexts may lose accuracy on the NPU\n");
+ });
+ return false;
+ }
+ const auto & pos_shape = inp_pos->get_output_partial_shape(0);
+ if (pos_shape.is_dynamic() || pos_shape.rank().get_length() != 4) {
+ return false;
+ }
+
+ // All positions, in the [1, 1, 1, n_tokens] layout of inp_pos that make_sin_cos expects.
+ std::vector<int64_t> positions(n_pos);
+ std::iota(positions.begin(), positions.end(), 0);
+ auto all_pos = std::make_shared<ov::op::v0::Constant>(inp_pos->get_output_element_type(0),
+ ov::Shape{1, 1, 1, (size_t) n_pos}, positions);
+ auto table = make_sin_cos(op_params, all_pos, rope_freqs_weight, mode, false, head_dim);
+ auto folded = std::make_shared<ov::Model>(ov::OutputVector{table.first, table.second}, ov::ParameterVector{});
+ ov::pass::Manager manager;
+ manager.register_pass<ov::pass::ConstantFolding>();
+ manager.run_passes(folded);
+ auto sin_table = ov::as_type_ptr<ov::op::v0::Constant>(folded->get_results()[0]->get_input_node_shared_ptr(0));
+ auto cos_table = ov::as_type_ptr<ov::op::v0::Constant>(folded->get_results()[1]->get_input_node_shared_ptr(0));
+ if (!sin_table || !cos_table) {
+ return false;
+ }
+
+ // f16 tables (rope_table_f16): the values are in [-1, 1] (times mscale with YaRN or attn_factor != 1), where f16 is as accurate as the f16 the NPU computes with, at half the memory.
+ // The tables are [1, n_pos, 1, n_dims / 2]; the rows of the current positions give [1, n_tokens, 1, ...]. Positions are clamped, so the padding rows of a static chunk stay inside the table.
+ Output<Node> rows = std::make_shared<ov::op::v1::Reshape>(
+ inp_pos, ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}), false);
+ rows = std::make_shared<ov::op::v0::Clamp>(rows, 0.0, static_cast<double>(n_pos - 1));
+ auto axis = ov::op::v0::Constant::create(ov::element::i64, {}, {1});
+ auto gather_rows = [&](const std::shared_ptr<ov::op::v0::Constant> & table) -> Output<Node> {
+ auto gathered = std::make_shared<ov::op::v8::Gather>(rope_table_f16(table), rows, axis);
+ return std::make_shared<ov::op::v0::Convert>(gathered, table->get_element_type());
+ };
+ sin_cos = {gather_rows(sin_table), gather_rows(cos_table)};
+ return true;
+}
+
+} // namespace
+
OutputVector translate_rope(const NodeContext & context) {
num_inputs_check(context, 2, 3);
@@ -41,12 +133,6 @@ OutputVector translate_rope(const NodeContext & context) {
const int64_t n_dims = configured_n_dims == 0 ? head_dim : configured_n_dims;
const int64_t n_offs = static_cast<int64_t>(op_params[15]);
- constexpr int TYPE_NORMAL = 0;
- constexpr int TYPE_NEOX = 1;
- constexpr int TYPE_IMROPE = 2;
- constexpr int TYPE_VISION = 3;
- constexpr int TYPE_MROPE = 4;
-
Output<Node> cos_theta_node;
Output<Node> sin_theta_node;
std::string cache_key = "rope_sin_cos";
@@ -67,7 +153,10 @@ OutputVector translate_rope(const NodeContext & context) {
if (context.get_input_size() == 3) {
rope_freqs_weight = context.get_input(2).get_node_shared_ptr();
}
- auto sin_cos = make_sin_cos(op_params, inp_pos, rope_freqs_weight, mode, false, head_dim);
+ std::pair<Output<Node>, Output<Node>> sin_cos;
+ if (!make_rope_table(context, op_params, inp_pos, rope_freqs_weight, mode, head_dim, sin_cos)) {
+ sin_cos = make_sin_cos(op_params, inp_pos, rope_freqs_weight, mode, false, head_dim);
+ }
sin_theta_node = sin_cos.first;
cos_theta_node = sin_cos.second;
context.put_shared(cache_key + "_cos", cos_theta_node);
diff --git a/ggml/src/ggml-openvino/openvino/op/unary.cpp b/ggml/src/ggml-openvino/openvino/op/unary.cpp
index 5c338ec56..08751596d 100644
--- a/ggml/src/ggml-openvino/openvino/op/unary.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/unary.cpp
@@ -9,12 +9,12 @@
#include <openvino/op/clamp.hpp>
#include <openvino/op/constant.hpp>
#include <openvino/op/convert.hpp>
-#include <openvino/op/elu.hpp>
#include <openvino/op/exp.hpp>
#include <openvino/op/gelu.hpp>
#include <openvino/op/greater.hpp>
#include <openvino/op/hard_sigmoid.hpp>
#include <openvino/op/less.hpp>
+#include <openvino/op/less_eq.hpp>
#include <openvino/op/log.hpp>
#include <openvino/op/multiply.hpp>
#include <openvino/op/negative.hpp>
@@ -30,6 +30,24 @@ namespace frontend {
namespace ggml {
namespace op {
+namespace {
+
+// expm1(x), accurate near 0 like expm1f in the ggml reference: exp(x) - 1 loses the digits of a small x, so |x| <= 0.5 uses the Taylor series (as the Metal backend does).
+ov::Output<ov::Node> expm1_accurate(const ov::Output<ov::Node> & x) {
+ const auto type = x.get_element_type();
+ auto c = [&](float v) { return ov::op::v0::Constant::create(type, ov::Shape{}, {v}); };
+ ov::Output<ov::Node> p = c(1.0f / 40320.0f);
+ for (float k : {1.0f / 5040.0f, 1.0f / 720.0f, 1.0f / 120.0f, 1.0f / 24.0f, 1.0f / 6.0f, 0.5f, 1.0f}) {
+ p = std::make_shared<ov::op::v1::Add>(std::make_shared<ov::op::v1::Multiply>(p, x), c(k));
+ }
+ auto series = std::make_shared<ov::op::v1::Multiply>(x, p);
+ auto direct = std::make_shared<ov::op::v1::Subtract>(std::make_shared<ov::op::v0::Exp>(x), c(1.0f));
+ auto small = std::make_shared<ov::op::v1::LessEqual>(std::make_shared<ov::op::v0::Abs>(x), c(0.5f));
+ return std::make_shared<ov::op::v1::Select>(small, series, direct);
+}
+
+} // namespace
+
OutputVector translate_unary_gelu(const NodeContext & context) {
num_inputs_check(context, 1, 1);
auto input = process_view_input_new(context, 0);
@@ -56,8 +74,19 @@ OutputVector translate_unary_gelu_quick(const NodeContext & context) {
OutputVector translate_unary_elu(const NodeContext & context) {
num_inputs_check(context, 1, 1);
+ // compute in f32 like the ggml reference (NPU cannot take the f32 path)
auto input = process_view_input_new(context, 0);
- auto res = std::make_shared<ov::op::v0::Elu>(input, 1.0);
+ const auto type = ggml_openvino_is_npu() ? input.get_element_type() : ov::element::f32;
+ ov::Output<ov::Node> x = input;
+ if (type != input.get_element_type()) {
+ x = std::make_shared<ov::op::v0::Convert>(input, type);
+ }
+ auto zero = ov::op::v0::Constant::create(type, ov::Shape{}, {0.0f});
+ ov::Output<ov::Node> res =
+ std::make_shared<ov::op::v1::Select>(std::make_shared<ov::op::v1::Greater>(x, zero), x, expm1_accurate(x));
+ if (type != input.get_element_type()) {
+ res = std::make_shared<ov::op::v0::Convert>(res, input.get_element_type());
+ }
return rename_outputs_with_suffix({res}, context.get_name());
}
diff --git a/ggml/src/ggml-openvino/openvino/op_table.cpp b/ggml/src/ggml-openvino/openvino/op_table.cpp
index 4983e2a7c..835249b62 100644
--- a/ggml/src/ggml-openvino/openvino/op_table.cpp
+++ b/ggml/src/ggml-openvino/openvino/op_table.cpp
@@ -14,7 +14,6 @@
#include <openvino/op/hswish.hpp>
#include <openvino/op/log.hpp>
#include <openvino/op/matmul.hpp>
-#include <openvino/op/multiply.hpp>
#include <openvino/op/negative.hpp>
#include <openvino/op/relu.hpp>
#include <openvino/op/sigmoid.hpp>
@@ -43,7 +42,7 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
{"GGML_OP_GET_ROWS", op::translate_get_rows },
{"GGML_OP_IM2COL", op::translate_im2col },
{"GGML_OP_IM2COL_3D", op::translate_im2col_3d },
- {"GGML_OP_MUL", op::translate_1to1_match_2_inputs<v1::Multiply>},
+ {"GGML_OP_MUL", op::translate_mul },
{"GGML_OP_MUL_MAT", op::translate_mulmat },
{"GGML_OP_MUL_MAT_ID", op::translate_mul_mat_id },
{"GGML_OP_PERMUTE", op::translate_permute },
diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h
index 37acac0ef..0f5305c4c 100644
--- a/ggml/src/ggml-openvino/openvino/op_table.h
+++ b/ggml/src/ggml-openvino/openvino/op_table.h
@@ -20,6 +20,7 @@ GGML_OP_CONVERTER(translate_fill);
GGML_OP_CONVERTER(translate_get_rows);
GGML_OP_CONVERTER(translate_im2col);
GGML_OP_CONVERTER(translate_im2col_3d);
+GGML_OP_CONVERTER(translate_mul);
GGML_OP_CONVERTER(translate_mulmat);
GGML_OP_CONVERTER(translate_mul_mat_id);
GGML_OP_CONVERTER(translate_moe_tiled);
diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp
index 25377fc3a..0825d9713 100644
--- a/ggml/src/ggml-openvino/openvino/utils.cpp
+++ b/ggml/src/ggml-openvino/openvino/utils.cpp
@@ -8,6 +8,8 @@
#include <ctime>
#include <memory>
#include <openvino/op/add.hpp>
+#include <openvino/op/bitwise_and.hpp>
+#include <openvino/op/bitwise_right_shift.hpp>
#include <openvino/op/clamp.hpp>
#include <openvino/op/constant.hpp>
#include <openvino/op/concat.hpp>
@@ -362,10 +364,8 @@ std::pair<ov::Output<Node>, ov::Output<Node>> make_sin_cos(int32_t * rope_params
// Convert of inp_pos. The cost is negligible: theta is a few dozen values per token, against the
// matmuls that dominate. The rotation itself and everything downstream stay f16.
//
- // Off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. It changes the RoPE of every model,
- // it is validated on one model on the GPU only, and on an f32 path the round trip below makes
- // cos and sin less accurate.
- const bool pin_angle = ggml_openvino_getenv_int("GGML_OPENVINO_ROPE_F32_ANGLE") != 0;
+ // Off by default; GGML_OPENVINO_ROPE_SINCOS=device_f32 turns it on. It changes the RoPE of every model, it is validated on one model on the GPU only, and on an f32 path the round trip below makes cos and sin less accurate.
+ const bool pin_angle = ggml_openvino_rope_sincos() == ggml_openvino_rope_sincos_mode::DEVICE_F32;
auto cos_op = std::make_shared<ov::op::v0::Cos>(theta);
auto sin_op = std::make_shared<ov::op::v0::Sin>(theta);
@@ -448,6 +448,32 @@ ov::Output<ov::Node> process_view_input(const NodeContext & context, int input_i
namespace {
+// Gather rows of a 2-bit u2 Constant [N, K/G, G] (make_int2_weights) and unpack them to i32 codes. The GPU gather kernels have no u2 input, so gather whole rows of the packed bytes and unpack only those (LSB-first, 4 codes per byte).
+std::shared_ptr<ov::Node> gather_u2_rows(const std::shared_ptr<ov::op::v0::Constant> & cnst,
+ const ov::Output<ov::Node> & indices,
+ size_t idx_rank) {
+ const auto & shape = cnst->get_shape();
+ if (shape.size() != 3 || shape[2] % 4 != 0) {
+ return nullptr;
+ }
+ auto packed = std::make_shared<ov::op::v0::Constant>(ov::element::u8, ov::Shape{shape[0], shape[1], shape[2] / 4},
+ cnst->get_data_ptr(), cnst);
+ auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
+ auto rows = std::make_shared<ov::op::v8::Gather>(packed, indices, axis);
+ auto bytes = std::make_shared<ov::op::v0::Unsqueeze>(
+ std::make_shared<ov::op::v0::Convert>(rows, ov::element::i32),
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}));
+ auto shifted = std::make_shared<ov::op::v15::BitwiseRightShift>(
+ bytes, ov::op::v0::Constant::create(ov::element::i32, {4}, {0, 2, 4, 6}));
+ auto codes = std::make_shared<ov::op::v13::BitwiseAnd>(
+ shifted, ov::op::v0::Constant::create(ov::element::i32, {}, {3}));
+ std::vector<int64_t> target(idx_rank, 0);
+ target.push_back(static_cast<int64_t>(shape[1]));
+ target.push_back(static_cast<int64_t>(shape[2]));
+ return std::make_shared<ov::op::v1::Reshape>(
+ codes, ov::op::v0::Constant::create(ov::element::i64, {target.size()}, target), true);
+}
+
// Walk a dequantization chain, gathering `indices` out of every leaf Constant that is indexed by
// the gathered axis, and rebuild the chain on top of the gathered rows. Only the node types
// make_intX_weights emits are recognized; anything else aborts the rewrite (nullptr).
@@ -470,6 +496,10 @@ std::shared_ptr<ov::Node> rebuild_on_gathered_rows(const ov::Output<ov::Node> &
type == ov::element::i8) {
saw_compressed = true;
}
+ if (type == ov::element::u2) {
+ saw_compressed = true;
+ return static_cast<int64_t>(shape[0]) == rows ? gather_u2_rows(cnst, indices, idx_rank) : nullptr;
+ }
if (shape.empty() || static_cast<int64_t>(shape[0]) != rows) {
// Scalar or already-broadcast operand (e.g. a single zero point): share it unchanged.
return cnst;
@@ -515,6 +545,23 @@ std::shared_ptr<ov::Node> rebuild_on_gathered_rows(const ov::Output<ov::Node> &
return nullptr;
}
+bool has_u2_leaf(const ov::Output<ov::Node> & out, size_t depth = 0) {
+ auto node = out.get_node_shared_ptr();
+ if (auto cnst = ov::as_type_ptr<ov::op::v0::Constant>(node)) {
+ return cnst->get_element_type() == ov::element::u2;
+ }
+ if (depth > 8 || !(ov::is_type<ov::op::v1::Reshape>(node) || ov::is_type<ov::op::v0::Convert>(node) ||
+ ov::is_type<ov::op::v1::Multiply>(node) || ov::is_type<ov::op::v1::Subtract>(node))) {
+ return false;
+ }
+ for (const auto & input : node->input_values()) {
+ if (has_u2_leaf(input, depth + 1)) {
+ return true;
+ }
+ }
+ return false;
+}
+
} // namespace
std::shared_ptr<ov::Node> gather_compressed_rows(const ov::Output<ov::Node> & weights,
@@ -528,7 +575,8 @@ std::shared_ptr<ov::Node> gather_compressed_rows(const ov::Output<ov::Node> & we
ps[1].is_dynamic() || idx_ps.rank().is_dynamic()) {
return nullptr;
}
- if (ps[0].get_length() * ps[1].get_length() < min_elements) {
+ // a u2 table takes this path at any size: some GPU plugins (OpenVINO 2026.4) turn a dequantized u2 table plus Gather into GatherCompressed, which reads u2 wrongly
+ if (ps[0].get_length() * ps[1].get_length() < min_elements && !has_u2_leaf(weights)) {
return nullptr;
}
diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h
index 194f08be5..22900dfa2 100644
--- a/ggml/src/ggml-openvino/openvino/utils.h
+++ b/ggml/src/ggml-openvino/openvino/utils.h
@@ -31,12 +31,8 @@ std::pair<ov::Output<Node>, ov::Output<Node>> make_sin_cos(int32_t * rope_params
bool stateful = false,
int64_t head_dim = 0);
-// If `weights` is a dequantization chain emitted by make_int4_weights/make_int8_weights, rebuild
-// it with `indices` gathered out of the leaf Constants, so a row lookup reads the packed rows and
-// dequantizes only those. Returns nullptr if the subgraph is not such a chain, or is too small to
-// be worth the rewrite. Used for tied embeddings, where the same weight also feeds the lm_head
-// matmul: gathering the dequantized table would give that chain a second consumer and force it to
-// be materialized in full.
+// If `weights` is a dequantization chain from make_int{2,4,8}_weights, rebuild it with `indices` gathered from the leaf Constants, so a row lookup reads and dequantizes only the packed rows. Returns nullptr if it is not such a chain, or is too small to be worth it.
+// Used for tied embeddings (a Gather of the dequantized table would give the chain a second consumer and materialize it in full) and for 2-bit u2 tables, which the plugins do not gather correctly in compressed form.
std::shared_ptr<ov::Node> gather_compressed_rows(const ov::Output<ov::Node> & weights,
const ov::Output<ov::Node> & indices);
diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp
index fdc212178..6925e8458 100644
--- a/ggml/src/ggml-openvino/utils.cpp
+++ b/ggml/src/ggml-openvino/utils.cpp
@@ -228,6 +228,8 @@ static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurren
extra_cfg = extra_cfg * 131 + (ggml_openvino_shape_from_mask_enabled() ? 1u : 0u);
extra_cfg = extra_cfg * 131 + (ggml_openvino_npu_hfa_prefill_enabled() ? 4u : 0u); // HFA input ABI v4.
extra_cfg = extra_cfg * 131 + (ggml_openvino_npu_host_gather_enabled() ? 1u : 0u);
+ // The effective GGML_OPENVINO_ROPE_SINCOS: "auto" depends on the device, so the variable alone does not identify the graph.
+ extra_cfg = extra_cfg * 131 + static_cast<uint64_t>(ggml_openvino_rope_sincos());
if (ggml_openvino_is_npu()) {
extra_cfg = extra_cfg * 131 + static_cast<uint64_t>(ggml_openvino_get_npu_requant_type());
}
@@ -1699,10 +1701,13 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
const ov::AnyMap & compile_config = model_cache_dir.empty() ? config : mc_config;
ov::CompiledModel compiled_model;
auto remote_context = ggml_openvino_get_remote_context(device);
- if (remote_context.has_value()) {
- compiled_model = core.compile_model(model, remote_context.value(), compile_config);
- } else {
- compiled_model = core.compile_model(model, device, compile_config);
+ {
+ ggml_openvino_spill_trim_scope trim_scope;
+ if (remote_context.has_value()) {
+ compiled_model = core.compile_model(model, remote_context.value(), compile_config);
+ } else {
+ compiled_model = core.compile_model(model, device, compile_config);
+ }
}
compile_end_time = ggml_time_us();
@@ -2138,6 +2143,7 @@ static void build_static_model(const static_build_args & a,
ov::AnyMap import_config = model_config;
import_config[ov::hint::model.name()] = std::shared_ptr<const ov::Model>(model);
const int64_t import_start_time = ggml_time_us();
+ ggml_openvino_spill_trim_scope trim_scope; // ov::hint::model: the import can read the weights
compiled_model = core.import_model(blob_in, device, import_config);
const int64_t import_end_time = ggml_time_us();
if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING")) {
@@ -2158,6 +2164,7 @@ static void build_static_model(const static_build_args & a,
if (a.weightless_bank) {
compile_config[ov::enable_weightless.name()] = true;
}
+ ggml_openvino_spill_trim_scope trim_scope;
compiled_model = core.compile_model(model, device, compile_config);
}
local_compile_end_time = ggml_time_us();