diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index c6468a21898c..f7df3619c046 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -1,58 +1,162 @@ # OpenVINO Backend for llama.cpp -[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 that optimizes and deploys AI inference on Intel hardware. The [OpenVINO backend](../../ggml/src/ggml-openvino) runs GGUF model files on **Intel(R) CPUs, GPUs and NPUs**. The model files and the rest of llama.cpp need no changes. -- 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). +This page covers the build, the first run, the supported devices and models, the user variables and the known limitations. The other documents: + +| Document | Contents | +|---|---| +| [Cookbook](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md) | Recipes, one for each task: build scripts, Docker, runs, cache, memory, MoE models, speculative decoding, image input, profiling | +| [Developer documentation](../../ggml/src/ggml-openvino/dev_doc/README.md) | Internals: how the backend works, source layout, compiled model cache, KV cache binding, weight layouts | +| [OpenVINO-ENV-VARS.md](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md) | Developer variables: debug output, optimization switches, experimental and memory options, plugin properties | +| [Qwen MTP and recurrent replay](../../ggml/src/ggml-openvino/dev_doc/QWEN-MTP.md) | Deep dive: Qwen MTP speculative decoding, recurrent replay and multi-slot draft sampling | +| [OpenVINO Backend Contributing Guide](https://github.com/ravi9/llamacpp-ov-dev-guide/blob/main/contributing-llamacpp-ov.md) | How to contribute to the backend | ## Contents - [Quick Start](#quick-start) + - [Prerequisites](#prerequisites) + - [Install OpenVINO Runtime](#install-openvino-runtime) + - [Build](#build) + - [Run](#run) + - [Other ways to get the backend](#other-ways-to-get-the-backend) - [Supported Devices](#supported-devices) - [Supported Model Precisions](#supported-model-precisions) - [Supported llama.cpp Tools](#supported-llamacpp-tools) - [Validated Models](#validated-models) -- [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) + - [Advanced tuning](#advanced-tuning) - [Deprecated](#deprecated) - [Developer variables](#developer-variables) - [Known Limitations](#known-limitations) -- [Work in Progress](#work-in-progress) + - [General](#general) + - [GPU](#gpu) + - [NPU](#npu) ## Quick Start -On Ubuntu, with the [prerequisites](#prerequisites) and the [OpenVINO Runtime](#install-openvino-runtime) installed: +The steps below build llama.cpp with the OpenVINO backend and run a model on each device. [Other ways to get the backend](#other-ways-to-get-the-backend) are at the end of this section. + +### Prerequisites + +- 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). +- The build tools and OpenCL: + +
+Linux + +```bash +# Build tools (Git, CMake, Ninja) +sudo apt-get update +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 +``` + +
+ +
+Windows + +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 Ninja-build.Ninja + # OpenCL with vcpkg, in C:\vcpkg + cd C:\ + git clone https://github.com/microsoft/vcpkg + cd vcpkg + .\bootstrap-vcpkg.bat + .\vcpkg install opencl + # Optional: integrate vcpkg with Visual Studio and CMake + .\vcpkg integrate install + ``` + +
+ +### Install OpenVINO Runtime + +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. + +- 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 Command Prompt, `& "C:\Intel\openvino\setupvars.ps1"` in PowerShell. + +### Build + +
+Linux ```bash -# 1. Build git clone https://github.com/ggml-org/llama.cpp cd llama.cpp +# /opt/intel/openvino: the link that the cookbook Ubuntu build script creates. Change the path to your install directory. source /opt/intel/openvino/setupvars.sh +# Check: setupvars.sh sets OpenVINO_DIR +echo $OpenVINO_DIR cmake -B build/ReleaseOV -G Ninja -DCMAKE_BUILD_TYPE=Release -DGGML_OPENVINO=ON cmake --build build/ReleaseOV --parallel +``` + +
+ +
+Windows + +Run the commands in the x64 Native Tools Command Prompt for VS, so that the MSVC toolchain is on PATH. -# 2. Download a model +```bat +git clone https://github.com/ggml-org/llama.cpp +cd llama.cpp +REM C:\Intel\openvino: the directory junction that the cookbook Windows build script creates. Change the path to your install directory. +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 +``` + +
+ +### Run + +Download a model: + +```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 +``` + +Run the model on one device. `GGML_OPENVINO_DEVICE` selects the device. `-c` sets the context size. The default context is the training context of the model. -# 3. Run on CPU, GPU or NPU. -c sets the context size. The default is the training context of the model. +```bash +# CPU GGML_OPENVINO_DEVICE=CPU ./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 +``` + +```bash +# GPU GGML_OPENVINO_DEVICE=GPU ./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 +``` + +```bash +# NPU GGML_OPENVINO_DEVICE=NPU ./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512 ``` -- The first run of a model compiles it for the device. On the NPU, this can take minutes for a large model. +- The first run of a model compiles it for the device, so the start takes longer. Set `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` to keep the compiled model for later starts: [compiled model cache](#compiled-model-cache). - Windows, llama-server, llama-bench and NPU tuning: [Run on each device](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#run-on-each-device). + +### Other ways to get the backend + +- 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. +- Docker images (prebuilt and local builds, GPU and NPU access, llama-server): [Docker](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#docker). - One-step build scripts for Ubuntu and Windows: [Build from source](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#build-from-source). ## Supported Devices @@ -69,10 +173,13 @@ Device selection: - 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=` 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). +- 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 +The backend runs GGUF files with these weight types: + - `FP16` - `BF16` (on Intel Xeon) - `Q8_0` @@ -81,43 +188,22 @@ Device selection: - `Q4_K` - `Q5_0` - `Q5_1` -- `Q5_K` (converted at runtime, see the details below) -- `Q6_K` (converted at runtime, see the details below) +- `Q5_K` (converted at runtime, see below) +- `Q6_K` (converted at runtime, see below) +- `Q2_0` `Q4_K_M` files mix `Q4_K` tensors with `Q6_K` tensors, and sometimes `Q5_K` tensors. -
-Quantization details for each device - -**All devices:** -- `FP16` and `BF16` tensors are used as they are. -- A quantized token embedding (`token_embd.weight`) and output weight (`output.weight`) are converted to `Q8_0_C`. - -**CPU and GPU:** -- `Q4_0`, `Q4_1`, `Q4_K`, `Q5_0`, `Q5_1` and `Q8_0` tensors keep their layout: weights, scales and zero points are extracted directly. -- `Q5_K` and `Q6_K` tensors are converted to `Q8_0_C`. `GGML_OPENVINO_REQUANT_KQUANT` selects a 4-bit layout instead. - -**GPU:** -- `Q4_K`, `Q5_K` and `Q6_K` MoE expert tensors, and `Q4_0` ones whose row width is a multiple of 64, are converted to `Q4_1_64`. This lets the GPU plugin use its fused MoE op, which is much faster for prompt processing. `GGML_OPENVINO_REQUANT_KQUANT` does not change this. `GGML_OPENVINO_MOE_OP=0` turns the fused MoE op off. -- `Q5_0`, `Q5_1` and `Q8_0` MoE expert tensors are converted to `Q4_0_64` (`Q8_0_C` when the row width is not a multiple of 64). This works around a GPU plugin defect with grouped 8-bit expert weights. `GGML_OPENVINO_REQUANT_KQUANT=native` keeps them at 8 bits. - -**NPU:** -- All other quantized tensors are requantized to `Q4_0_128`, or to `Q4_0_C` when the row width is not a multiple of 128. -- 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. +How each device stores quantized weights: -**Layout names:** -- `Q8_0_C`: 8-bit, one scale per row. -- `Q4_0_128` and `Q4_0_64`: 4-bit, symmetric, one scale per 128 or 64 weights. -- `Q4_0_C`: 4-bit, symmetric, one scale per row. -- `Q4_1_64`: 4-bit, asymmetric, one scale and one zero point per 64 weights. +- CPU and GPU: by default, `Q2_0`, `Q4_0`, `Q4_1`, `Q4_K` and `Q8_0` weights keep their GGUF layout. `Q5_0`, `Q5_1`, `Q5_K` and `Q6_K` weights become 8-bit. `GGML_OPENVINO_REQUANT_KQUANT` can select 4-bit layouts instead. +- NPU: `Q2_0` weights stay 2-bit. The other quantized weights become 4-bit (`Q4_0_128`, or `Q4_0_C`). -
+Exceptions (token embedding, output weight, GPU MoE experts, NPU host gather) and the layout names: [Weight layouts](../../ggml/src/ggml-openvino/dev_doc/README.md#weight-layouts). ## Supported llama.cpp Tools -The OpenVINO backend works with the standard llama.cpp tools below. Tool coverage is not uniform across devices. +The OpenVINO backend works with the standard llama.cpp tools below. Tool coverage differs between CPU, GPU and NPU. See [Known Limitations](#known-limitations). - llama-bench - llama-cli @@ -130,16 +216,18 @@ The OpenVINO backend works with the standard llama.cpp tools below. Tool coverag ## Validated Models -The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® Core™ Ultra Series 3 (Panther Lake). The OpenVINO backend is expected to work on a broader range of [Intel hardware](https://docs.openvino.ai/2026/about-openvino/release-notes-openvino/system-requirements.html), [model precisions](#supported-model-precisions), [llama.cpp tools](#supported-llamacpp-tools) and model architectures. +The table shows the test status of each model on each device. The backend is expected to work on more [devices](#supported-devices), [model precisions](#supported-model-precisions), [llama.cpp tools](#supported-llamacpp-tools) and model architectures. -**Legend & Test Configuration:** +**Legend and test configuration:** - **Status:** ✓ = Passed | ~ = Accuracy issues | ✗ = Failed or Unsupported -- **Execution mode:** stateless (`GGML_OPENVINO_STATEFUL_EXECUTION=0`) on every device. +- **Test:** `llama-cli` with `Q4_K_M` files. The embedding models run with `llama-embedding` and `Q8_0` files. +- **Vision models:** each cell shows the status with text input. Image input fails on the NPU, see [Known Limitations](#known-limitations). +- **Execution mode:** stateless (default) on every device. - **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.
-Validated models +Validated models | Model | CPU | GPU | NPU | | :--- | :---: | :---: | :---: | @@ -194,124 +282,45 @@ The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® C | [ggml-org/bge-m3-Q8_0](https://huggingface.co/ggml-org/bge-m3-Q8_0-GGUF) | ✓ | ✓ | ✗ | | [nomic-ai/nomic-embed-text-v1.5-Q8_0](https://huggingface.co/nomic-ai/nomic-embed-text-v1.5-GGUF) | ✓ | ✓ | ✗ | -The embedding models were tested with `llama-embedding` and `Q8_0` files. -
-## 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). - -### Prerequisites - -- 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). - -
-Linux - -```bash -# Build tools (Git, CMake, Ninja) -sudo apt-get update -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 -``` - -
- -
-Windows - -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 Ninja-build.Ninja - # OpenCL with vcpkg, in C:\vcpkg - cd C:\ - git clone https://github.com/microsoft/vcpkg - cd vcpkg - .\bootstrap-vcpkg.bat - .\vcpkg install opencl - # Optional: integrate vcpkg with Visual Studio and CMake - .\vcpkg integrate install - ``` - -
- -### Install OpenVINO Runtime - -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 -# Check the setup: setupvars sets OpenVINO_DIR -source /opt/intel/openvino/setupvars.sh -echo $OpenVINO_DIR -``` - -### 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 -``` - -```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 -``` - -- 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. - -## Docker - -```bash -# 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 . -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 -``` - -Prebuilt images, the other targets, GPU and NPU access, and llama-server: [Docker](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#docker). - ## 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. +Value rules: + - The backend reads the variables once, at start. Unset or empty means the default. - 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). + +Example messages for a value that is not valid and for an unknown name: ```text ggml-openvino: GGML_OPENVINO_EXACT_ZERO_POINT=yes is not valid, use 1 (on) or 0 (off) ggml-openvino: unknown environment variable GGML_OPENVINO_DEVCE is ignored ``` +Related recipes: [Lower memory use](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#lower-memory-use), [Accuracy and quantization tuning](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#accuracy-and-quantization-tuning), [Compiled model cache](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#compiled-model-cache). + ### Basic +These variables select the device, turn on the compiled model cache, pass plugin properties and turn on profiling. + | Variable | Device | Type | Default | Description | |---|---|---|---|---| -| `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). | +| `GGML_OPENVINO_DEVICE` | all | String | `CPU` | Target device: `CPU`, `GPU`, `NPU`, or `GPU.0`, `GPU.1` with several GPUs. See [Supported Devices](#supported-devices). | +| `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` | all | String | unset | Directory for the cache of compiled models. See [Compiled model cache](#compiled-model-cache). | +| `GGML_OPENVINO_NPU_CONFIG` | NPU | String | unset | OpenVINO properties for the NPU plugin. See [Plugin properties](#plugin-properties). | +| `GGML_OPENVINO_GPU_CONFIG` | GPU | String | unset | OpenVINO properties for the GPU plugin. See [Plugin properties](#plugin-properties). | +| `GGML_OPENVINO_CPU_CONFIG` | CPU | String | unset | 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. | + +Notes: + +- `GGML_OPENVINO_DEVICE` also takes a list such as `GPU.0,GPU.1`. With `-sm layer`, the list splits a model across GPUs. See [Multiple GPUs](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#multiple-gpus). +- `GGML_OPENVINO_PROFILING` recipes: [Profiling and debug dumps](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#profiling-and-debug-dumps). ### Plugin properties @@ -319,48 +328,94 @@ ggml-openvino: unknown environment variable GGML_OPENVINO_DEVCE is ignored - 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. 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`. +- 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 removes `CACHE_DIR`. On the CPU and the GPU, it also sets `CACHE_MODE=OPTIMIZE_SPEED`. On the NPU, it also removes `CACHE_MODE` and sets `NPUW_WEIGHTS_BANK`. - OpenVINO checks the properties when the model loads. If it rejects one, the load fails and the error names the variable. -- `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). +- `NPU_COMPILER_TYPE` selects the NPU compiler. The backend default is `DRIVER`. Qwen3.5 models (`GATED_DELTA_NET` layers) compile with `PLUGIN` unless `NPU_COMPILER_TYPE` is set. Values: [NPU plugin properties](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#npu-plugin-properties). - 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 +### Compiled model cache -The defaults fit most models. The variables below trade one property for another, for example speed for accuracy. +The cache keeps compiled models on disk, so later starts of the same model load faster. `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` (see [Basic](#basic)) turns it on. Use the same model and the same settings in every run. -
-Advanced tuning variables +- 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). + +These variables change how the backend uses the cache: | Variable | Device | Type | Default | Description | |---|---|---|---|---| -| `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. | +| `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` | CPU, GPU | Boolean | `0` | Require the cached model and skip the weight upload and the compilation. | +| `GGML_OPENVINO_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Use the memory-mapped GGUF file as the model buffer, for a lower RAM peak. | +| `GGML_OPENVINO_CACHE_DIR` | all | String | unset | Directory for the cache of the OpenVINO plugin itself. | -
+Notes: -### Compiled model cache +- `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` needs mmap loading and a model that runs fully on OpenVINO. It does not work for MoE models on the CPU. +- `GGML_OPENVINO_SELF_CONTAINED_MMAP` fails if a cached model is missing. Without `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, the backend ignores it. +- `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` is the recommended cache, not `GGML_OPENVINO_CACHE_DIR`. +- On the CPU and the GPU, `GGML_OPENVINO_CACHE_DIR` sets the plugin properties `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE`. When `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` is set, the model graphs do not use it. +- On the NPU, `GGML_OPENVINO_CACHE_DIR` sets `NPUW_CACHE_DIR`. + +### Advanced tuning -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). +The defaults fit most models. The variables below trade one property for another, for example speed for accuracy. Which value to use for a model or a device: [Accuracy and quantization tuning](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#accuracy-and-quantization-tuning). + +
+Advanced tuning variables | Variable | Device | Type | Default | Description | |---|---|---|---|---| -| `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. | +| `GGML_OPENVINO_PREFILL_CHUNK_SIZE` | NPU | Integer | `256` | Tokens in one NPU prefill step. Zero or less means the default. | +| `GGML_OPENVINO_KV_ONLY_PREFILL` | NPU | Boolean | `1` | KV-only prefill for Gemma 3n, Gemma 4 E2B and Gemma 4 E4B. `0` turns it off. | +| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | Enum | `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`. | +| `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. `0` turns it off. | +| `GGML_OPENVINO_ROPE_SINCOS` | all | Enum | `auto` | Where RoPE computes cos and sin: `host`, `device`, `device_f32` or `auto`. | +| `GGML_OPENVINO_GDN_DECOMPOSE` | NPU | Boolean | auto | Translate `GATED_DELTA_NET` (Qwen3.5) into MatMul operations. Unset: on for the Lunar Lake NPU, off elsewhere. | +| `GGML_OPENVINO_MANUAL_GQA_ATTN` | all | Boolean | auto | Build grouped-query attention from separate MatMul operations. Unset: on for GPU, off for CPU and NPU. | +| `GGML_OPENVINO_REQUANT_KQUANT` | CPU, GPU | Enum | unset | Requantize `Q6_K` and `Q5_K` weights to a 4-bit layout instead of `Q8_0_C`. | +| `GGML_OPENVINO_EXACT_ZERO_POINT` | CPU, GPU | Boolean | `0` | Keep the exact zero point of asymmetric weights, not an integer one. Higher accuracy, lower speed. | + +Notes: + +- `GGML_OPENVINO_PREFILL_CHUNK_SIZE`: a larger value can make long prompts faster. It also makes the first load longer. +- `GGML_OPENVINO_KV_ONLY_PREFILL`: the prefill graph only writes the KV cache, and one decode step computes the output token. The backend skips it for models with recurrent state. Details: [KV-only prefill](../../ggml/src/ggml-openvino/dev_doc/README.md#kv-only-prefill). +- `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT`: + - When set, it also applies to a `Q4_K` or `Q5_K` token embedding. + - The 4-bit layouts use less memory and can lower accuracy. + - With `GGML_OPENVINO_NPU_HOST_GATHER` on, the backend does not convert a large table. Then only a tied output layer changes. +- `GGML_OPENVINO_NPU_HOST_GATHER`: the backend does not convert a table that it reads on the host, which lowers memory use. Details: [NPU host gather](../../ggml/src/ggml-openvino/dev_doc/README.md#npu-host-gather). +- `GGML_OPENVINO_ROPE_SINCOS`: f16 angles lose accuracy at long positions. + - `host`: f32 tables on the host. Static graphs (NPU) only, 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_REQUANT_KQUANT` values: + - `q4_asym64`: `Q6_K` and `Q5_K` to `Q4_1_64` (4-bit, asymmetric, group size 64). + - `q4_asym64_all`: also `Q4_K`, `Q8_0`, `Q5_1` and `Q5_0`. + - `q4_sym128`: `Q6_K` and `Q5_K` to `Q4_0_128` (4-bit, symmetric, group size 128). + - `q4_sym128_all`: also `Q4_K`. + - `native`: no requantization. +- `q4_asym64_all` in detail (recommended for Qwen3.6-35B-A3B `Q4_K_M`): + - It converts `Q4_K`, `Q5_K`, `Q6_K`, `Q8_0`, `Q5_1` and `Q5_0` weights to asymmetric INT4 with group size 64. This includes the dense `Q8_0` projections. + - `token_embd.weight` and `output.weight` keep symmetric channel-wise INT8. + - `Q8_0`, `Q5_1` and `Q5_0` rows whose width is not a multiple of 64 also use channel-wise INT8. + - For these source types, it follows the primary and backup precision scheme of [NNCF](https://github.com/openvinotoolkit/nncf) `INT4_ASYM` with `ratio=1.0`, `group_size=64` and `backup_mode=INT8_SYM`. + - It requantizes the GGUF values, not the original floating-point model. Floating-point weights stay unchanged. +- `GGML_OPENVINO_EXACT_ZERO_POINT`: the asymmetric weights are `Q4_1`, `Q4_K`, `Q5_1`, and `Q5_K` with `native`. MoE expert weights always use the exact zero point. + +
### Deprecated +This variable is deprecated and will be removed. + | 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`). | +| `GGML_OPENVINO_STATEFUL_EXECUTION` | CPU, GPU | Boolean | `0` | Keep the KV cache inside the OpenVINO model. Use the default, stateless execution (`0`). | + +Details: [Deprecated: stateful execution](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#deprecated-stateful-execution). ### Developer variables @@ -368,57 +423,60 @@ Debug output, switches that turn a default optimization off, experimental option ## Known Limitations -**General (all devices)** +### General - 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:** `--image-max-tokens 256`. With `-ub 128` alone, a large image can still run out of memory. - - NPU: work in progress. + - To log the unsupported ops, see [Profiling and debug dumps](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#profiling-and-debug-dumps). +- Image input is experimental. Qwen3.5, Qwen3-VL and Gemma 4 E2B image input runs on the CPU and the GPU, with the matching projector of each model. Four-slot llama-server serving was validated with the unified and the split KV cache. See [Image input](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#image-input). Internals: [Multimodal](../../ggml/src/ggml-openvino/dev_doc/README.md#multimodal). +- Audio input is a work in progress. Gemma 4 audio input is not enabled. Its preprocessing and Conformer graphs still need dynamic length and block handling, runtime padding, view and state offsets, and compiled-model reuse across input lengths. +- Qwen3-VL image input on the CPU needs a 32 GB system (peak about 14 GB of RAM). - Embedding models: reranking models are not validated. -- 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** +### GPU +- Qwen3-VL image input on a 16 GB system: the default `-ub 512` runs out of memory. + - **Workaround:** `--image-max-tokens 256`. With `-ub 128` alone, a large image can still run out of memory. See [Image input](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#image-input). - 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. 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. + - Copies between GPUs go through RAM. 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 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. + - **Workaround:** `GGML_OPENVINO_MOE_OP=0`. The output is correct, but prompt processing is much slower. See [MoE models on the GPU](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#moe-models-on-the-gpu). - `GGML_OPENVINO_GPU_CONFIG="INFERENCE_PRECISION_HINT=f32"` fails to compile. -- `llama-perplexity` with MoE models: set `-b` to the `-c` value, so that each batch holds one sequence. +- `llama-perplexity` with MoE models needs one sequence in each batch. + - **Workaround:** set `-b` to the `-c` value. See [Perplexity](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#perplexity). +- 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`). + - **Workaround:** keep `GGML_OPENVINO_ENABLE_KV_4D` unset. It is then on with OpenVINO 2026.5 or later. See [KV cache binding](../../ggml/src/ggml-openvino/dev_doc/README.md#kv-cache-binding). +- Qwen MTP serving in cache-only mode (`GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1`) needs the OpenVINO dynamic output-binding fix [openvino#39354](https://github.com/openvinotoolkit/openvino/pull/39354). The fix is on the OpenVINO master branch. It is not in a release yet. + - Imported MTP graphs need the fix even though the backend removes the recurrent cache Results. See [Speculative decoding](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#speculative-decoding). -**NPU-specific** +### NPU -- 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. +- 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 4` shows the value in use, on the `llama_context: n_ctx` line. - **Workaround:** pass `-c `, 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). +- Image input fails on the NPU because of dynamic shapes. NPU image input, also for Qwen3-VL, is a work in progress. + - **Workaround:** use the CPU or the GPU. See [Image input](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#image-input). +- `llama-server -np N` with N greater than 1 needs the unified KV cache (`--kv-unified`). 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` gives a wrong result at `-c 1024` and above with the default `-ub 512`. + - **Workaround:** set `-b` to at most `-c`, so that each batch holds one sequence. Set `-ub` to the prefill chunk size (default 256). + - MoE models such as Qwen3.6-35B-A3B: 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. + - See [Perplexity](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#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. + - **Workaround:** use the CPU or the GPU. See [Embeddings](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#embeddings). +- 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. The models run on CPU and GPU. +- `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. A 35B MoE model needs nearly all of a 32 GB system. + - **Workaround:** 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). +- The first load of a model on the NPU compiles it for the device. This can take minutes for large models. + - **Workaround:** set `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`. See [Compiled model cache](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#compiled-model-cache). +- With `GGML_OPENVINO_KV_SLICE=0`, `llama-bench -d` fails on the NPU. + - **Workaround:** keep the default (`1`). See [KV cache binding](../../ggml/src/ggml-openvino/dev_doc/README.md#kv-cache-binding). - 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, for example `-c 512`, or `-c 256` for larger models. + - **Workaround:** pass the smallest context that fits the use, for example `-c 512`, or `-c 256` for larger models. See [NPU context and prefill chunk](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#npu-context-and-prefill-chunk). - 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 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. - - 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. - -## Work in Progress - -- Performance and memory optimizations -- Accuracy validation -- Broader quantization coverage -- Support for additional model architectures +- 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`). + - **Workaround:** keep the default (`1`). diff --git a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md index 09a45d74a3eb..713643cbcb48 100644 --- a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md +++ b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md @@ -1,17 +1,12 @@ # 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). +- Quick Start, supported devices, known limitations 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 +- [Conventions](#conventions) + - [Models used](#models-used) - [Build from source](#build-from-source) - [Ubuntu build script](#ubuntu-build-script) - [Windows build script](#windows-build-script) @@ -21,35 +16,103 @@ source /opt/intel/openvino/setupvars.sh - [Windows](#windows) - [llama-server](#llama-server) - [NPU context and prefill chunk](#npu-context-and-prefill-chunk) + - [NPU plugin properties](#npu-plugin-properties) - [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) +- [Accuracy and quantization tuning](#accuracy-and-quantization-tuning) - [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) + - [MoE models on the GPU](#moe-models-on-the-gpu) - [Speculative decoding](#speculative-decoding) + - [Qwen MTP on the GPU](#qwen-mtp-on-the-gpu) + - [Muse-Glimmer-30B with a DFlash draft on the GPU](#muse-glimmer-30b-with-a-dflash-draft-on-the-gpu) - [Image input](#image-input) - [Embeddings and perplexity](#embeddings-and-perplexity) + - [Embeddings](#embeddings) + - [Perplexity](#perplexity) - [Profiling and debug dumps](#profiling-and-debug-dumps) +## Conventions + +- Run the commands from the `llama.cpp` directory. The build directory is `build/ReleaseOV`, as in the [build scripts](#build-from-source). +- Models are in `~/models` on Linux and in `C:\models` on Windows. A name in `<...>` marks a file that you supply. +- `GGML_OPENVINO_DEVICE` selects the device: `CPU` (the default), `GPU` or `NPU`. See [Supported Devices](../../../../docs/backend/OPENVINO.md#supported-devices). +- The backend info lines (settings, cache hits, spill and release messages) need `-lv 4`. `llama-bench` takes `-v` instead. +- `export`, `set` and `$env:` lines stay in effect in the shell. Start each recipe in a new shell (set up OpenVINO again), or unset its variables. +- In bash, a one-run setting goes in front of the command: `GGML_OPENVINO_DEVICE=GPU ./build/ReleaseOV/bin/llama-cli ...`. + +Set up OpenVINO in each new shell, before you build or run a source build. The paths are those of the build scripts. + +```bash +# bash (Linux) +source /opt/intel/openvino/setupvars.sh +``` + +```bat +REM Command Prompt (Windows) +call "C:\Intel\openvino\setupvars.bat" +``` + +```powershell +# PowerShell (Windows) +& "C:\Intel\openvino\setupvars.ps1" +``` + +### Models used + +The recipes use the GGUF files below. Download each file into `~/models`, for example: + +```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 +``` + +| File | Hugging Face repository | Recipes | +|---|---|---| +| `Llama-3.2-1B-Instruct-Q4_K_M.gguf` | [bartowski/Llama-3.2-1B-Instruct-GGUF][hf-llama32] | most recipes | +| `google_gemma-4-E2B-it-Q4_K_M.gguf` | [bartowski/google_gemma-4-E2B-it-GGUF][hf-gemma4] | [NPU cache](#npu-gemma-4-e2b-example), [image input](#image-input) | +| `mmproj-google_gemma-4-E2B-it-f16.gguf` | [bartowski/google_gemma-4-E2B-it-GGUF][hf-gemma4] | [image input](#image-input) | +| `Qwen3-VL-4B-Instruct-Q4_K_M.gguf`, `mmproj-F16.gguf` | [unsloth/Qwen3-VL-4B-Instruct-GGUF][hf-qwen3vl] | [image input](#image-input) | +| `Qwen_Qwen3.5-2B-Q4_K_M.gguf` | [bartowski/Qwen_Qwen3.5-2B-GGUF][hf-qwen35] | [accuracy tuning](#accuracy-and-quantization-tuning) | +| `Qwen_Qwen3.6-35B-A3B-Q4_0.gguf` | [bartowski/Qwen_Qwen3.6-35B-A3B-GGUF][hf-qwen36] | [NPU MoE](#qwen36-35b-a3b-on-the-npu), [perplexity](#perplexity) | +| `Qwen3-Embedding-0.6B-Q8_0.gguf` | [Qwen/Qwen3-Embedding-0.6B-GGUF][hf-qwen3emb] | [embeddings](#embeddings) | +| `Qwen3.6-35B-A3B-Q4_K_M.gguf` | not given: a Qwen3.5 or Qwen3.6 file with MTP weights | [Qwen MTP](#qwen-mtp-on-the-gpu) | +| `Muse-Glimmer-30B-Q4_K_M.gguf`, `.gguf` | not given | [DFlash](#muse-glimmer-30b-with-a-dflash-draft-on-the-gpu) | + +[hf-llama32]: https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF +[hf-gemma4]: https://huggingface.co/bartowski/google_gemma-4-E2B-it-GGUF +[hf-qwen3vl]: https://huggingface.co/unsloth/Qwen3-VL-4B-Instruct-GGUF +[hf-qwen35]: https://huggingface.co/bartowski/Qwen_Qwen3.5-2B-GGUF +[hf-qwen36]: https://huggingface.co/bartowski/Qwen_Qwen3.6-35B-A3B-GGUF +[hf-qwen3emb]: https://huggingface.co/Qwen/Qwen3-Embedding-0.6B-GGUF + ## Build from source +Use when: you set up a new Ubuntu or Windows machine and build llama.cpp 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. +- Save a script in the directory where the `llama.cpp` directory goes. The script clones llama.cpp there if the directory is missing. +- Each run deletes `build/ReleaseOV` and builds again. ### 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: +The script installs the build tools and the OpenCL ICD with `sudo apt-get`. It downloads OpenVINO Runtime to `/opt/intel/openvino_2026.5` and points the symlink `/opt/intel/openvino` at it. Then it builds llama.cpp with Ninja. Save it as `build-llamacpp-ov.sh`, then run it: ```bash chmod +x build-llamacpp-ov.sh ./build-llamacpp-ov.sh ``` +
+Full build script for Ubuntu (build-llamacpp-ov.sh, 107 lines) + ```bash #!/usr/bin/env bash # ============================================ @@ -98,7 +161,8 @@ if [[ ! -f "llama.cpp/CMakeLists.txt" ]]; then 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. +# 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." @@ -159,12 +223,23 @@ echo " export GGML_OPENVINO_DEVICE=CPU # or GPU / NPU" echo " ./build/ReleaseOV/bin/llama-cli -m model.gguf" ``` +
+ +Verify: the script prints `Build completed successfully!`. Then list the devices that the build sees: + +```bash +cd llama.cpp +source /opt/intel/openvino/setupvars.sh +# Each OpenVINO device shows its GGML_OPENVINO_DEVICE value +./build/ReleaseOV/bin/llama-cli --list-devices +``` + ### 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: +The script installs Git, Ninja, CMake, Visual Studio 2022 Build Tools and OpenCL (with vcpkg in `C:\vcpkg`). It downloads OpenVINO Runtime to `C:\Intel\openvino_2026.5` and points the junction `C:\Intel\openvino` at it. Then it builds llama.cpp with Ninja. Save it as `build-llamacpp-ov.bat`, then run it from Command Prompt or PowerShell: -```cmd -:: Command Prompt +```bat +REM Command Prompt build-llamacpp-ov.bat ``` @@ -173,6 +248,9 @@ build-llamacpp-ov.bat .\build-llamacpp-ov.bat ``` +
+Full build script for Windows (build-llamacpp-ov.bat, 184 lines) + ```bat @echo off setlocal enabledelayedexpansion @@ -245,7 +323,8 @@ 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 Setup OpenVINO: download & extract to C:\Intel\openvino_%OPENVINO_VERSION_MAJOR%, then point +REM C:\Intel\openvino at it via a directory junction (mklink /J). REM ============================================ if exist "%OPENVINO_INSTALL_DIR%\setupvars.bat" ( @@ -253,7 +332,7 @@ if exist "%OPENVINO_INSTALL_DIR%\setupvars.bat" ( ) else ( echo OpenVINO not found at "%OPENVINO_INSTALL_DIR%". Starting download... - curl -L -o "%OPENVINO_ZIP%" "%OPENVINO_URL%" + curl -fL -o "%OPENVINO_ZIP%" "%OPENVINO_URL%" if errorlevel 1 ( echo ERROR: Download failed. exit /b 1 @@ -359,15 +438,33 @@ 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**. +Verify: the script prints `Build completed successfully!`. Then list the devices that the build sees: + +```bat +cd llama.cpp +call "C:\Intel\openvino\setupvars.bat" +build\ReleaseOV\bin\llama-cli.exe --list-devices +``` + ## Docker -The images come from [.devops/openvino.Dockerfile](../../../../.devops/openvino.Dockerfile). Prebuilt images for `linux/amd64` are on the GitHub Container Registry: +Use when: you want to run the OpenVINO backend without a local build. + +The images come from [.devops/openvino.Dockerfile](../../../../.devops/openvino.Dockerfile). + +- The images contain OpenVINO Runtime and the user-space GPU and NPU drivers. +- The host needs only the GPU or NPU kernel driver and the device nodes: `/dev/dri` for the GPU, `/dev/accel` for the NPU. + +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 +# full: all binaries and the Python tools +# light: llama, llama-cli and llama-completion +# server: llama and 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 @@ -376,118 +473,143 @@ 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. +# base: the shared libraries, OpenVINO Runtime and the GPU and NPU drivers; no entrypoint 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. +# full: all binaries, the Python conversion scripts and gguf-py; entrypoint /app/tools.sh 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. +# light: llama, llama-cli and llama-completion; entrypoint llama-cli 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. +# server: llama and llama-server; entrypoint llama-server, with a health check on /health docker build --target=server -t llama-openvino:server -f .devops/openvino.Dockerfile . +``` + +Behind a proxy, pass the proxy to the build: -# 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 . +```bash +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`. +Verify: the light image runs `llama-cli`, so the arguments go to `llama-cli`. `--list-devices` prints the OpenVINO devices that the container sees. ```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 +# CPU only +docker run --rm llama-openvino:light --list-devices -# 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 GPU access: the list also shows GGML_OPENVINO_DEVICE=GPU +docker run --rm --device=/dev/dri --group-add=$(stat -c "%g" /dev/dri/render* | head -n 1) \ + llama-openvino:light --list-devices -# 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 +# With NPU access: the list also shows GGML_OPENVINO_DEVICE=NPU +docker run --rm --device=/dev/accel --group-add=$(stat -c "%g" /dev/accel/accel* | head -n 1) \ + llama-openvino:light --list-devices ``` -Run llama-server in a container. The server image listens on `0.0.0.0:8080`. Test it as in [llama-server](#llama-server). +Run `llama-cli` in a container. 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`. + +CPU: ```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 +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 +``` -# Run the llama-openvino:server Docker container with Intel GPU access (iGPU or dGPU) +GPU (integrated or discrete): + +```bash 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 + --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 +``` + +NPU: -# Run the llama-openvino:server Docker container with Intel NPU access +```bash 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 + --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 with the `llama-openvino:server` image (prebuilt: `ghcr.io/ggml-org/llama.cpp:server-openvino`). The server listens on `0.0.0.0:8080`. Test it with the curl commands in [llama-server](#llama-server). + +```bash +# CPU: drop --device, --group-add, -u and --env. NPU: use the NPU options of the llama-cli example, and -c 512. +docker run --rm -it -v ~/models:/models -p 8080:8080 \ + --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:server --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf ``` ## Run on each device +Set up OpenVINO in the shell first: [Conventions](#conventions). + ### Linux +GPU (CPU is the default when `GGML_OPENVINO_DEVICE` is unset): + ```bash -# If the device is unset, the CPU is used. export GGML_OPENVINO_DEVICE=GPU -# To run llama-simple: +# Check the device: (selected) marks the device in use +./build/ReleaseOV/bin/llama-cli --list-devices +# llama-simple: generate 50 tokens, then exit ./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: +# llama-bench ./build/ReleaseOV/bin/llama-bench -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf +# Chat mode (type /exit to quit) +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 +``` -# NPU +NPU: + +```bash 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: +Download a model. The commands run in Command Prompt and in PowerShell. In Windows PowerShell, `curl` is an alias of `Invoke-WebRequest`, so the command calls `curl.exe`. -```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 +```bat 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 +curl.exe -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: +GPU, in Command Prompt: -```cmd -REM Windows Command Prompt +```bat set GGML_OPENVINO_DEVICE=GPU -REM To run llama-simple: +REM llama-simple: generate 50 tokens, then exit 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: +REM llama-bench build\ReleaseOV\bin\llama-bench.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" +REM Chat mode (type /exit to quit) +build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 1024 +``` -REM NPU +NPU, in Command Prompt: + +```bat 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 ``` +GPU, in PowerShell: + ```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 +NPU, in PowerShell: + +```powershell $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 ``` @@ -497,10 +619,14 @@ build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.ggu ```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 +``` + +Verify: -# 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. +- 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: +```bash # Behind a proxy, keep localhost off the proxy export NO_PROXY=localhost,127.0.0.1 @@ -510,297 +636,584 @@ 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 with several slots: -# NPU: several slots need the unified KV cache (-kvu). Without -np, llama-server uses 4 slots with it. +```bash +# NPU: several slots need the unified KV cache (--kv-unified). +# Without -np, llama-server uses 4 slots with the unified KV cache. 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 +./build/ReleaseOV/bin/llama-server -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --port 8080 -c 1024 -np 2 --kv-unified ``` ### NPU context and prefill chunk +Use when: a model on the NPU runs out of memory, fails or runs slowly, or long prompts are slow. + +Set the context size: + ```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. +# Set -c. Without -c, llama.cpp starts from the training context of the model +# (for example 131072 for Llama 3.2 1B). --fit (on by default) can lower it to fit the memory. +# 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 +``` + +Verify: `-lv 4` shows the context in use on the `llama_context: n_ctx` line. +```bash +GGML_OPENVINO_DEVICE=NPU ./build/ReleaseOV/bin/llama-completion -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf \ + -c 512 -n 8 -no-cnv -p "Hello" -lv 4 2>&1 | grep "llama_context: n_ctx " +``` + +Set the prefill chunk size: + +```bash +export GGML_OPENVINO_DEVICE=NPU # 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 + +Use when: you select the NPU compiler, lower the memory peak of the NPU compilation, or want more NPU plugin logs. -# NPU plugin properties: the compiler in OpenVINO, one compiler thread (lower memory peak), more plugin logs +```bash +export GGML_OPENVINO_DEVICE=NPU +# NPU_COMPILER_TYPE=PLUGIN: the compiler in OpenVINO instead of the one in the NPU driver +# COMPILATION_NUM_THREADS=1: one compiler thread, for a lower memory peak +# LOG_LEVEL=LOG_INFO: more NPU plugin logs export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=1,LOG_LEVEL=LOG_INFO" +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512 -lv 4 ``` +Verify: + +- With `-lv 4`, the log shows one `GGML OpenVINO: NPU config override KEY=VALUE` line for each property. +- `LOG_LEVEL=LOG_INFO` adds the info lines of the NPU plugin. +- If OpenVINO rejects a property, the load fails, and the error names the variable. + +Notes: + +- The format and the property values: [Plugin properties](../../../../docs/backend/OPENVINO.md#plugin-properties). The properties that the backend sets: [NPU plugin properties](OpenVINO-ENV-VARS.md#npu-plugin-properties). +- `GGML_OPENVINO_NPU_CONFIG` is part of the key of the NPU compiled model cache. With the cache, a changed value selects another cache entry, and the model compiles again. + ### Multiple GPUs ```bash -# List the devices. Each OpenVINO device shows its GGML_OPENVINO_DEVICE value; (selected) marks the active one. +# List the devices. Each OpenVINO device shows its GGML_OPENVINO_DEVICE value. +# (selected) marks the active device. ./build/ReleaseOV/bin/llama-cli --list-devices +``` +```bash # 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 +``` +```bash # 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 ``` +Multi-GPU limitations (no `-sm tensor`, copies through RAM, GPUs only): [Known Limitations](../../../../docs/backend/OPENVINO.md#known-limitations). + ## 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). +- Use the same model and the same settings in every run. A changed setting selects another cache entry. The settings for CPU and GPU: [CPU and GPU](#cpu-and-gpu). How the backend builds the key: [Cache key](README.md#cache-key). ### CPU and GPU +Use when: you start the same model on the CPU or the GPU again and again. + +First run: compile the model and write the cache. + ```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. +# -lv 4 logs "model cache WROTE". Wait for it, and for the workload to complete, 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. -# Later runs (optional): cache-only mode. It requires the cached model and skips the weight upload and the compilation. +```bash +# Use the same device, model and settings as in the first run +export GGML_OPENVINO_DEVICE=GPU # or CPU +export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache 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 +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 -lv 4 ``` -- 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. +Verify: with `-lv 4`, the log shows `model cache HIT`. In cache-only mode, a missing or incompatible graph stops the run with an error. It does not compile the graph without weights. + +Cache-only mode requirements: + +- `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` is set. +- Linux or Windows. +- mmap loading: `--load-mode mmap`, or the default (`auto`) when all selected devices support mmap. Cache-only mode stops with an error with `-lm none`. +- A model that runs fully on OpenVINO, with dynamic CPU or GPU graphs. Static graphs (the NPU, or `GGML_OPENVINO_FORCE_STATIC=1`), CPU fallback, `GGML_OPENVINO_DISABLE_CACHE=1` and `GGML_OPENVINO_ENABLE_FALLBACK=1` are not supported. +- Do not use tensor validation or mlock when you want to avoid weight reads. + +Settings that must stay the same between the first run and cache-only runs, including set versus unset. A different value selects another cache entry, and cache-only mode then fails: + +- `GGML_OPENVINO_GPU_CONFIG`, `GGML_OPENVINO_CPU_CONFIG`, `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_EXACT_ZERO_POINT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_MANUAL_GQA_ATTN` +- `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_KV_SCATTER_ELEMENTS` +- `GGML_OPENVINO_GDN_NATIVE_STATE`, `GGML_OPENVINO_GDN_DECOMPOSE`, `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK` +- `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, `GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN`, `GGML_OPENVINO_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 the GPU, `GGML_OPENVINO_MOE_OP=0` +- `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE` (Qwen MTP models): not part of the 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 between the first run and cache-only runs: + +- `GGML_OPENVINO_COMPILE_MEM_SPILL` and `GGML_OPENVINO_COMPILE_MEM_SPILL_DIR`: optional in the first run, ignored in cache-only mode. +- `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`: it changes only the output bindings. +- `GGML_OPENVINO_KV_SLICE`: a runtime binding option. The same dynamic compiled graph accepts both KV tensor sizes. See [KV cache binding](README.md#kv-cache-binding). + +Notes: + +- Cache-only mode uses the settings of the current process. A different workload can need another graph. Run that workload once without cache-only mode first. +- MoE models are not written to the cache on CPU, so cache-only mode does not work for them on CPU. GPU MoE and CPU dense graph imports were tested. +- A cache hit without cache-only mode shortens the load. It uses about as much RAM as a run without the cache. +- Cache-only mode skips the weight reads of the backend only. The llama.cpp loader still reads the GGUF metadata, the tokenizer data and the tensor descriptors, and the graph is still built. Depending on its prefetch settings, the loader can read weight pages: `MAP_POPULATE` or read-ahead on Linux, `PrefetchVirtualMemory` on Windows. Loading without mmap reads all the weights. +- Windows: cache-only mode commits virtual memory for the backend buffers without touching the weight pages. Large models can still reach the system commit limit. The model-buffer size in the loader log is this virtual size. +- The cache entries are tied to the GGUF file. Replacing, copying or modifying the file invalidates them. Keep the file unchanged while the model loads and runs. +- Use the same device and a compatible OpenVINO and plugin installation. +- On CPU and GPU, each cached model holds its weights, so it can approach the model size on disk. Loading a cached model still reads its file and initializes the device. ### 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. +Use when: you start the same model on the NPU again and again. Only the first start compiles the model. + +On the NPU, the cache holds the compiled models without weights, plus one shared weights file. 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. + # 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 + # Optional: slightly less memory; may lower accuracy + export GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=q4_0_128 + # Optional: can make long prompts faster; makes the first run longer + export GGML_OPENVINO_PREFILL_CHUNK_SIZE=512 + ./build/ReleaseOV/bin/llama-cli -m ~/models/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 + # 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_DEVICE=NPU + export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache + export GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=q4_0_128 + export GGML_OPENVINO_PREFILL_CHUNK_SIZE=512 + # Optional, later runs only: use the memory-mapped GGUF file as the model buffer. + # It fails without the cache of step 1. + export GGML_OPENVINO_SELF_CONTAINED_MMAP=1 + ./build/ReleaseOV/bin/llama-cli -m ~/models/google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096 -lv 4 ``` - 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. +Use when: the RAM peak is too high while a model loads and compiles. + +While a model compiles, the GPU and CPU plugins keep their own copy of the weights. The backend keeps its copy too. On integrated GPUs, both copies are in RAM. The settings below lower that peak. They do not change the output. + +Pick the setting for your case: + +| Case | Setting | +|---|---| +| GPU or CPU, large model, Linux: the lowest peak, also when RAM is free | `GGML_OPENVINO_COMPILE_MEM_SPILL=0.1` | +| GPU or CPU, Linux: spill only when RAM runs out | `GGML_OPENVINO_COMPILE_MEM_SPILL=1` | +| GPU, Linux | nothing: `GGML_OPENVINO_RELEASE_WEIGHTS=1` is the default | +| CPU, MoE model | `GGML_OPENVINO_REDUCE_COMPILE_MEM=1` | +| All of the above at once | `GGML_OPENVINO_MEMORY_OPTIMIZE=1` | +| CPU or GPU, the same model started again and again | cache-only mode: [CPU and GPU](#cpu-and-gpu) | +| NPU, later runs from the compiled model cache | `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: [NPU: gemma-4 E2B example](#npu-gemma-4-e2b-example) | + +Spill with a cap (GPU or CPU, Linux): ```bash -# GPU or CPU, large model, Linux: keep at most 10% of the weights in RAM while the model loads and compiles. +export GGML_OPENVINO_DEVICE=GPU # or CPU +# 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): +# Optional: another spill directory (default /var/tmp), on a local disk, not tmpfs export GGML_OPENVINO_COMPILE_MEM_SPILL_DIR=$HOME/ov_spill mkdir -p $GGML_OPENVINO_COMPILE_MEM_SPILL_DIR +./build/ReleaseOV/bin/llama-cli -m ~/models/.gguf -c 1024 -lv 4 +``` -# 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: -# 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). +```bash +# 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_DEVICE=GPU # or CPU export GGML_OPENVINO_MEMORY_OPTIMIZE=1 +./build/ReleaseOV/bin/llama-cli -m ~/models/.gguf -c 1024 +``` + +Verify, with `-lv 4`: + +- Spill: the log shows `buffer spilled to ( MB, file-backed)`. With a fraction, it also shows `at most of MB of the spilled weights stay in RAM`. +- Too little disk space or a tmpfs directory gives a warning, and the backend uses RAM. +- GPU on Linux: the log shows `released MB of host weight buffers` (`GGML_OPENVINO_RELEASE_WEIGHTS=1`, the default). + +Notes: + +- `-lm none` (no mmap) does not lower the RAM in use. +- The variables, and the disk space, load time and tmpfs details of the spill: [Memory optimization](OpenVINO-ENV-VARS.md#memory-optimization). + +## Accuracy and quantization tuning + +Use when: a quantized model gives less accurate output than expected, or you trade accuracy for speed or memory. + +The defaults fit most models. Pick the setting for your case. The values and the defaults: [Advanced tuning](../../../../docs/backend/OPENVINO.md#advanced-tuning). + +| Case | Setting | +|---|---| +| GPU, `Q4_K_M` file: `Q6_K` and `Q5_K` weights in 4 bits | `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all` (`q4_asym64` does not compile on the GPU) | +| CPU or GPU: higher accuracy, at a lower speed | `GGML_OPENVINO_EXACT_ZERO_POINT=1` | +| GPU, long prompts | `GGML_OPENVINO_ROPE_SINCOS=device_f32` | +| NPU: a smaller `Q6_K` token embedding (can lower accuracy) | `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=q4_0_128` | +| CPU: try it for faster decode | `GGML_OPENVINO_MANUAL_GQA_ATTN=1` | +| Qwen3.5 on the Panther Lake NPU (for example `Qwen_Qwen3.5-2B-Q4_K_M.gguf`): try it | `GGML_OPENVINO_GDN_DECOMPOSE=1` | + +Verify: compare the greedy output without and with the setting. For a number, measure the [perplexity](#perplexity). + +```bash +# The setting (here GGML_OPENVINO_EXACT_ZERO_POINT=1) goes in front of the second command only +GGML_OPENVINO_DEVICE=GPU ./build/ReleaseOV/bin/llama-completion -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf \ + -c 512 -n 32 --temp 0 -no-cnv -p "The capital of France is" +GGML_OPENVINO_DEVICE=GPU GGML_OPENVINO_EXACT_ZERO_POINT=1 ./build/ReleaseOV/bin/llama-completion \ + -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512 -n 32 --temp 0 -no-cnv -p "The capital of France is" ``` -- 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). +Notes: + +- Each of these variables is part of the compiled model cache key. With the cache, a changed value selects another cache entry, and the model compiles again. +- To run the CPU in FP16, as the GPU and the NPU compute, see [Profiling and debug dumps](#profiling-and-debug-dumps). ## 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: +Use when: you run Qwen3.6-35B-A3B, or another MoE model with a softmax router and SwiGLU experts, on the NPU. + +Requirements: + +- OpenVINO 2026.5 or later. +- A 32 GB system, and a small context. The model needs nearly all of the RAM. The backend and NPUW each hold a copy of the weights (about 18 GB each). The NPU can address 18 GB of the shared memory. +- Tested with `Qwen_Qwen3.6-35B-A3B-Q4_0.gguf` on Panther Lake (Windows) and Lunar Lake (Windows, Ubuntu) systems with 32 GB. +- NPUW runs only the routed experts for each token, with the router on the host. See [Known Limitations](../../../../docs/backend/OPENVINO.md#known-limitations). + +Linux: ```bash export GGML_OPENVINO_DEVICE=NPU export GGML_OPENVINO_PREFILL_CHUNK_SIZE=128 +# NPUW_WEIGHTS_BANK_ALLOC=CPU: keep the NPUW copy of the weights in RAM that the CPU allocates, +# not in the NPU-addressable memory, at some cost in speed. +# NPUW_FUNCALL_ASYNC=NO and COMPILATION_NUM_THREADS=1: lower the memory peak. 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 +# --fit-target 16384: the NPU reports almost all of the RAM on Linux, +# so --fit (on by default) keeps every weight in the backend, and a 32 GB system swaps heavily. +# With a 16384 MiB target, --fit leaves part of the expert weights in the memory-mapped model file. +# The graph still runs on the NPU alone. +./build/ReleaseOV/bin/llama-cli -m ~/models/Qwen_Qwen3.6-35B-A3B-Q4_0.gguf -c 256 --fit-target 16384 ``` +Windows (Command Prompt): + ```bat -REM Windows +REM No --fit-target: the NPU reports 16 GB on Windows, so --fit leaves part of the expert weights +REM in the memory-mapped model file without it. 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 +build\ReleaseOV\bin\llama-cli.exe -m C:\models\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). +Notes: -### Muse-Glimmer-30B with a DFlash draft on the GPU +- The backend sets `NPUW_MOE_POOL_SIZE=0` and `NPUW_MOE_TOKEN_CHUNK_SIZE=16` for MoE models. Keep these values: without them, the load can hang on a 32 GB system. See [NPU plugin properties](OpenVINO-ENV-VARS.md#npu-plugin-properties). +- `NPU_COMPILER_TYPE` can stay unset. Models with `GATED_DELTA_NET` layers, such as Qwen3.6, then compile with the compiler in OpenVINO (`PLUGIN`). `NPU_COMPILER_TYPE=PREFER_PLUGIN` gives the same result. +- `llama-perplexity` with this model: see [Perplexity](#perplexity). + +### MoE models on the GPU + +Use when: a MoE model on the GPU gives wrong output. -This needs a 64 GB system. +granitemoe models (for example `granite-3.1-1b-a400m`) can give wrong output (one repeated token) after a short prompt. Turn the fused MoE op off: ```bash +# The output is correct, but prompt processing is much slower. 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 .gguf \ - --spec-type draft-dflash --spec-draft-n-max 4 +export GGML_OPENVINO_MOE_OP=0 +./build/ReleaseOV/bin/llama-cli -m ~/models/.gguf -c 1024 ``` +Verify: the answer is text, not one token repeated. + +Notes: + +- `llama-perplexity` with MoE models on the GPU: set `-b` to the `-c` value. See [Perplexity](#perplexity). +- Other MoE limitations on the GPU: [Known Limitations](../../../../docs/backend/OPENVINO.md#known-limitations). + ## 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). +### Qwen MTP on the GPU + +- MTP needs the GPU: OpenVINO replay requires dynamic stateless execution. +- Internals: [Qwen MTP and recurrent replay](QWEN-MTP.md). Limitations: [Known Limitations](../../../../docs/backend/OPENVINO.md#known-limitations). + +One slot: ```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 +./build/ReleaseOV/bin/llama-server -m ~/models/Qwen3.6-35B-A3B-Q4_K_M.gguf --spec-type draft-mtp --spec-draft-n-max 2 -np 1 +``` + +Several slots: +```bash +export GGML_OPENVINO_DEVICE=GPU +export GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all # recommended for Qwen3.6-35B-A3B Q4_K_M # 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 +./build/ReleaseOV/bin/llama-server -m ~/models/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). +Verify: + +- The server log shows `accepted / draft tokens` lines while it generates. +- Test the replay with one and with four active sequences. `test-backend-ops` does not cover the OpenVINO replay path. Send four requests at the same time to the server with `-np 4`: + +```bash +for i in 1 2 3 4; do + curl -s -X POST "http://localhost:8080/v1/chat/completions" -H "Content-Type: application/json" \ + -d '{"messages":[{"role":"user","content":"Count from 1 to 20"}],"max_tokens":100}' & +done +wait +``` + +### Muse-Glimmer-30B with a DFlash draft on the GPU + +This needs a 64 GB system. See [Known Limitations](../../../../docs/backend/OPENVINO.md#known-limitations). + +```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 ~/models/Muse-Glimmer-30B-Q4_K_M.gguf -md ~/models/.gguf \ + --spec-type draft-dflash --spec-draft-n-max 4 +``` ## Image input -Image input is experimental. It runs on CPU and GPU. Internals and limitations: [Multimodal](README.md#multimodal). +Use when: you send an image with the prompt to a vision model. Image input is experimental. It runs on CPU and GPU. -Gemma4 E2B image input on GPU or CPU: +- Internals: [Multimodal](README.md#multimodal). Limitations: [Known Limitations](../../../../docs/backend/OPENVINO.md#known-limitations). +- The projector (mmproj) file is in the same Hugging Face repository as the model. See [Models used](#models-used). + +Gemma 4 E2B image input on the GPU (or the 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. +# The chat template of the model needs --jinja. 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?" +./build/ReleaseOV/bin/llama-mtmd-cli -m ~/models/google_gemma-4-E2B-it-Q4_K_M.gguf \ + --mmproj ~/models/mmproj-google_gemma-4-E2B-it-f16.gguf --jinja -c 4096 \ + --image tools/mtmd/test-1.jpeg -p "What is the headline of this newspaper?" ``` 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 \ +./build/ReleaseOV/bin/llama-mtmd-cli -m ~/models/Qwen3-VL-4B-Instruct-Q4_K_M.gguf \ + --mmproj ~/models/mmproj-F16.gguf --jinja -c 4096 --image-max-tokens 256 \ --image tools/mtmd/test-1.jpeg -p "Describe this image in one sentence." ``` +Verify: `tools/mtmd/test-1.jpeg` is a newspaper page with the headline "MEN WALK ON MOON". The answer names the headline or the moon landing. + ## Embeddings and perplexity +### Embeddings + +Limitations: [Known Limitations](../../../../docs/backend/OPENVINO.md#known-limitations). + ```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" +export GGML_OPENVINO_DEVICE=GPU # or CPU +./build/ReleaseOV/bin/llama-embedding -m ~/models/Qwen3-Embedding-0.6B-Q8_0.gguf -p "Hello world" +``` -# Perplexity -./build/ReleaseOV/bin/llama-perplexity -m model.gguf -f wiki.test.raw -c 512 +### Perplexity -# 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 +Use when: you measure the accuracy of a model or a setting. + +Download the WikiText-2 test set once. The script writes `wikitext-2-raw/wiki.test.raw`: + +```bash +./scripts/get-wikitext-2.sh +``` -# NPU: -b at most -c (one sequence per batch), -ub equal to the prefill chunk size (default 256) +CPU or GPU: + +```bash +export GGML_OPENVINO_DEVICE=GPU # or CPU +./build/ReleaseOV/bin/llama-perplexity -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf \ + -f wikitext-2-raw/wiki.test.raw -c 512 +``` + +MoE models on the GPU: + +```bash +# Set -b to the -c value, so that each batch holds one sequence +export GGML_OPENVINO_DEVICE=GPU +./build/ReleaseOV/bin/llama-perplexity -m ~/models/.gguf \ + -f wikitext-2-raw/wiki.test.raw -c 512 -b 512 +``` + +NPU: + +```bash +# -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 +./build/ReleaseOV/bin/llama-perplexity -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf \ + -f wikitext-2-raw/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. +NPU, MoE models such as Qwen3.6-35B-A3B: + +```bash +# -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_DEVICE=NPU 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 +./build/ReleaseOV/bin/llama-perplexity -m ~/models/Qwen_Qwen3.6-35B-A3B-Q4_0.gguf \ + -f wikitext-2-raw/wiki.test.raw -c 256 ``` +- Memory settings for this model on a 32 GB system: [Qwen3.6-35B-A3B on the NPU](#qwen36-35b-a3b-on-the-npu). + +Verify: the last lines show `Final estimate: PPL = +/- `. A lower value is better. + ## Profiling and debug dumps -The variables are in [Debug output](OpenVINO-ENV-VARS.md#debug-output). +Use when: you measure where the time goes, or find the cause of a wrong result or a failure. The variables are in [Debug output](OpenVINO-ENV-VARS.md#debug-output). + +Execution timing of each graph: ```bash -# Execution timing of each graph: 1. 2 or higher also turns on OpenVINO and OpenCL profiling. +# GGML_OPENVINO_PROFILING=1: timing. 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 " ``` +Show the variables in effect (log verbosity 4): + ```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" +GGML_OPENVINO_DEVICE=GPU ./build/ReleaseOV/bin/llama-completion -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf \ + -c 512 -n 8 -no-cnv -p "Hello" -lv 4 2>&1 | grep "settings from the environment" ``` +Run the CPU in FP16, as the GPU and the NPU compute. This helps to debug the accuracy of a quantized model: + ```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 + ./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512 ``` +Find out whether a default optimization causes a wrong result: turn it off and compare the greedy output. The switches: [Switches for default optimizations](OpenVINO-ENV-VARS.md#switches-for-default-optimizations). + ```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" +export GGML_OPENVINO_DEVICE=NPU +./build/ReleaseOV/bin/llama-completion -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf \ + -c 512 -n 32 --temp 0 -no-cnv -p "The capital of France is" +GGML_OPENVINO_NPU_FAST_MASK=0 ./build/ReleaseOV/bin/llama-completion -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf \ + -c 512 -n 32 --temp 0 -no-cnv -p "The capital of France is" ``` +Dump the graphs: + ```bash -# Dump the GGML graph and the OpenVINO IR of a run +# The GGML graph (cgraph_ov.txt) and the OpenVINO IR (.xml files with timestamps). +# The files go to the current directory. GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \ - ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 + ./build/ReleaseOV/bin/llama-completion -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512 -n 4 -no-cnv -p "Hello" # 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 +GGML_OPENVINO_DEBUG_DYNAMIC_DIMS=1 ./build/ReleaseOV/bin/llama-completion -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.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 +Find unsupported ops: + +```bash +# Log unsupported ops. The lines have the WARN level. +# The default log verbosity shows them (-lv 2 or higher). +GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-completion -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf \ + -c 512 -n 16 -no-cnv -p "Hello" # 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 +GGML_OPENVINO_LOG_SUPPORTS_OP=1 ./build/ReleaseOV/bin/llama-completion -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf \ + -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep ov-supports-op +``` + +Find the cause of a failed inference: +```bash # 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 +GGML_OPENVINO_DIAG_GRAPH_IO=1 ./build/ReleaseOV/bin/llama-completion -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.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). +NPUW dumps. They need an OpenVINO developer build (`NPU_PLUGIN_DEVELOPER_BUILD`): + +```bash 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 +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512 ``` -List the properties of the installed NPU plugin (C++): +List the properties of each OpenVINO device (NPU, GPU, CPU) with their current values. The OpenVINO sample `hello_query_device` prints them: -```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() << "\n"; -} +```bash +source /opt/intel/openvino/setupvars.sh +# Build the OpenVINO C++ samples in ~/openvino_cpp_samples_build (-b selects another directory) +"$INTEL_OPENVINO_DIR"/samples/cpp/build_samples.sh +# Print every property of every available device +~/openvino_cpp_samples_build/intel64/Release/hello_query_device ``` diff --git a/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md b/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md deleted file mode 100644 index ee983ad1bca9..000000000000 --- a/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md +++ /dev/null @@ -1,94 +0,0 @@ -# Stable multi-slot MTP graph - -The MTP draft graph of Qwen3.5/Qwen3.6 keeps the same node names and candidate-output ports for every subset of active slots, so one compiled draft model serves all subsets. - -Contents: - -- [Sampler behavior](#sampler-behavior) -- [Graph layout](#graph-layout) -- [Active slots](#active-slots) -- [Runtime row selection](#runtime-row-selection) -- [Compiled models and the cache](#compiled-models-and-the-cache) -- [Reading graph dumps](#reading-graph-dumps) - -## Sampler behavior - -- 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. -- 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 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. -- 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 - -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. - -```text -MTP token IDs + input hidden state - | - 0-84: MTP layer and normalization, N active sequences - | - 85: logits [248320, N] - 86: PAD adds one safe row - | - +-- 87-91: slot 0 sampling - +-- 92-96: slot 1 sampling - +-- 97-101: slot 2 sampling - +-- 102-106: slot 3 sampling -``` - -- Each branch contains VIEW, two Reshapes, TopK (ten candidate IDs) and GET_ROWS (their scores). -- Ten is the candidate count, not the speculative-token count. -- The observed draft interface has 10 inputs and 12 outputs: eight candidate ID/score outputs, hidden state, full logits and two KV Results. - -## Active slots - -| Active slots | Sampling COMPUTE flags, slots 0-3 | 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]` | - -- 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. -- In dynamic execution, one int64 `sampling_rows` Parameter supplies the row indices. Static execution uses one `sampling_row_` 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. - -For active slots `{0,2}`, the two logits rows belong to slots 0 and 2: - -```text -sampling_rows = [0, 0, 1, 0] -slot 0 -> row 0 -> normal candidate buffers -slot 1 -> row 0 -> private scratch, ignored -slot 2 -> row 1 -> normal candidate buffers -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. -- The first import and runtime preparation still have a cost. - -## Reading graph dumps - -- 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. -- `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 deleted file mode 100644 index 1294f0f9b87f..000000000000 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ /dev/null @@ -1,103 +0,0 @@ -# Qwen recurrent cache on GPU - -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. - -- 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) -- [Debugging and profiling](#debugging-and-profiling) - -## Buffer ownership and operation boundaries - -| State | Storage and lifetime | Update path | -|---|---|---| -| Attention K/V | Full caller-owned USM allocation, sized by context and KV layout | Native stateless KV fusion when eligible; SDPA consumes the live prefix | -| Convolution `cache_r` | Caller-owned USM row bank with history and pending columns | Fused reset, original-row gather/reorder, convolution and ordered history/pending writes | -| GDN `cache_s`, `cache_spk`, `cache_spv`, `cache_spgb` | Caller-owned USM row banks with committed state and pending token inputs | Fused reset, original-row gather/reorder, GDN and ordered state/pending writes | -| Runtime controls | Reused USM host storage on GPU | Row maps, offsets and write controls remain runtime inputs | -| Protected source rows | Private device scratch | Staged before writes to protect cycles, duplicate sources and overlaps | -| Inactive sampling results | Private device-USM scratch | Discarded without touching inactive GGML output buffers | - -- Recurrent-cache size depends on slot capacity and pending-token capacity. -- Each fused cache input Parameter binds a caller-owned writable allocation. - -The GPU plugin uses two stages: - -1. It preserves the required original rows in scratch while it applies logical reset and precision rounding. -2. It computes and performs the ordered writes. - -- This order avoids overwriting a source before another destination has read it. -- Identity reorder sources need no scratch writes. -- In-place execution removes the spare full output bank, not every cache read or internal memory transaction. - -| Op | Returns | Writes | -|---|---|---| -| `RecurrentConvCacheReplayUpdate` | Convolution `[1,B,T,C]` | History and pending columns | -| `RecurrentGatedDeltaNetReplayUpdate` | Attention | Committed state and pending K, V, gate and beta | - -Both kernels write their cache inputs directly. - -## Replay graph contract - -Graph selection: - -- 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. `op_params[2]` holds the keep flag. -- A fresh prompt supplies a replay count of zero. -- 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 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_`. - -GPU fusion: - -- The GPU plugin requires the transformed model to preserve its `Result` count. Sinks express writeback separately from that output interface. -- The pass can replace the computation and remove its matched sinks and variables while keeping the Results. The internal op then writes through the original input binding. This avoids the GPU runtime changes that would be needed to alias a cache output to its input. -- The variable ID supplies the write permission. `RecurrentReplayFusion` still matches the computation, row controls, reset, reordering and writeback structure, and requires exclusive bank readers and a live computation output. -- The kernel checks for overlapping buffer ranges. - -Writeback without fusion: - -- When a sink remains, including on a GPU plugin without this pass, llama.cpp uses `query_state()` to find it and copies its state to the original GGML bank after inference. -- 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: - -- The backend builds the graph in [`openvino/op/recurrent_replay_graph.hpp`](../openvino/op/recurrent_replay_graph.hpp). -- The GPU matcher in `src/plugins/intel_gpu/src/plugin/transformations/recurrent_replay_fusion.cpp` compares it to a reference built from the OpenVINO copy of `recurrent_replay_graph.hpp` in the same directory. - -When upstream modeling changes the GGML graph: - -1. Adapt the backend recognition and check what it emits. -2. If the emitted replay pattern or its semantics change, update the reference and the relevant matcher and kernel logic with the translation. -3. Verify that the graph still fuses and that the standard-op writeback still works. - -## Convolution cache stores - -- The structural replay graph gathers history using the retained-token count, concatenates live input, and uses one grouped convolution. -- A slice selects history and pending columns for the next batch. -- `ScatterNDUpdate` produces the updated bank for the `Assign` sink. -- Row maps, replay counts and reset rows are runtime inputs. - -## 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 243a40c5cf2a..75d2aad623cf 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -1,61 +1,194 @@ # 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#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). +This file lists the developer `GGML_OPENVINO_*` variables. They are for debugging, comparisons and experiments, and they can change or be removed. + +- User variables and the rules for values: [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md#configuration). +- Commands that use these variables: [COOKBOOK.md](COOKBOOK.md). +- Default column: a literal value in backticks, unset (no value), or auto (the description gives the rule). Contents: - [Debug output](#debug-output) + - [Dumps](#dumps) + - [Logs](#logs) + - [In-process graph cache](#in-process-graph-cache) + - [NPUW dumps](#npuw-dumps) - [Switches for default optimizations](#switches-for-default-optimizations) -- [Experimental options](#experimental-options) + - [KV cache binding](#kv-cache-binding) + - [Graph and ops](#graph-and-ops) + - [NPU](#npu) - [Memory optimization](#memory-optimization) -- [NPU plugin properties](#npu-plugin-properties) -- [GPU and CPU plugin properties](#gpu-and-cpu-plugin-properties) +- [Experimental options](#experimental-options) +- [Deprecated: stateful execution](#deprecated-stateful-execution) +- [Plugin properties set by the backend](#plugin-properties-set-by-the-backend) + - [All devices](#all-devices) + - [NPU plugin properties](#npu-plugin-properties) + - [GPU and CPU plugin properties](#gpu-and-cpu-plugin-properties) - [Older variable names](#older-variable-names) ## Debug output -Examples: [Profiling and debug dumps](COOKBOOK.md#profiling-and-debug-dumps). +These variables write dumps and logs. Examples: [Profiling and debug dumps](COOKBOOK.md#profiling-and-debug-dumps). + +### Dumps + +These variables write the graphs, the OpenVINO IR and the tensor values. | Variable | Device | Type | Default | Description | |---|---|---|---|---| -| `GGML_OPENVINO_DUMP_CGRAPH` | all | Boolean | `0` | Dump the GGML compute graph to `cgraph_ov.txt`. | -| `GGML_OPENVINO_DUMP_IR` | all | Boolean | `0` | Write the OpenVINO IR files, with timestamps (`IR_naive.xml` for the small graphs of op tests). | | `GGML_OPENVINO_DEBUG_INPUT` | all | Boolean | `0` | Print the input tensors. | +| `GGML_OPENVINO_DEBUG_NODE` | all | String | unset | Add the named graph nodes as outputs of the compiled model. Separate several names with commas. | | `GGML_OPENVINO_DEBUG_OUTPUT` | all | Boolean | `0` | Print the output tensors. | -| `GGML_OPENVINO_DEBUG_NODE` | all | String | `not set` | Add the named graph nodes as outputs of the compiled model. Separate several names with commas. | -| `GGML_OPENVINO_DEBUG_DYNAMIC_DIMS` | all | Boolean | `0` | Print each graph node and its sources with their shapes when a graph is decoded. `*` marks the dynamic (token) dimension. | -| `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | all | Boolean | `0` | Print the tensor address map once. | +| `GGML_OPENVINO_DUMP_CGRAPH` | all | Boolean | `0` | Write the GGML compute graph to `cgraph_ov.txt`. | +| `GGML_OPENVINO_DUMP_IR` | all | Boolean | `0` | Write the OpenVINO IR of each converted graph to the current directory. | + +Notes: + +- `GGML_OPENVINO_DUMP_CGRAPH` writes the graph before the backend filters it to the COMPUTE nodes. Each graph call overwrites `cgraph_ov.txt`. +- `GGML_OPENVINO_DUMP_CGRAPH` also logs the replay fusion group counts: see [Testing and profiling](QWEN-MTP.md#testing-and-profiling). +- How to read `cgraph_ov.txt`: [Reading graph dumps](README.md#reading-graph-dumps). +- `GGML_OPENVINO_DUMP_IR` file names: + - Dynamic path (CPU, GPU): `model_.xml`. + - Static path (NPU, or `GGML_OPENVINO_FORCE_STATIC`): `model_prefill_.xml` and `model_decode_.xml`. + - Small graphs of op tests: `IR_naive.xml`. Each graph overwrites it. + +### Logs + +These variables log graph, op and tensor details. + +| Variable | Device | Type | Default | Description | +|---|---|---|---|---| +| `GGML_OPENVINO_DEBUG_DYNAMIC_DIMS` | all | Boolean | `0` | At graph decode, print each node and its sources with their shapes. See the notes. | +| `GGML_OPENVINO_DIAG_GRAPH_IO` | all | Boolean | `0` | When a tensor binding or `infer()` throws, log the graph key and the model and bound tensor shapes. | +| `GGML_OPENVINO_LOG_SUPPORTS_OP` | all | Integer | `0` | Log what `supports_op` accepts and rejects. `1`: summary at exit. `2`: also each call. | +| `GGML_OPENVINO_LOG_SWA_LAYERS` | all | Boolean | `0` | Log the attention extent of each layer and its sliding-window use, on an `ov-swa:` line (WARN level). | | `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` | all | Boolean | `0` | Log each op that the backend does not support, with the tensor details and the reason. | -| `GGML_OPENVINO_LOG_SUPPORTS_OP` | all | Integer | `0` | Log what `supports_op` accepts and rejects. `1`: summary at exit. `2`: also each call (the first calls are missing). | -| `GGML_OPENVINO_DIAG_GRAPH_IO` | all | Boolean | `0` | When binding a tensor or `infer()` throws, log the graph key and the shapes of the model and the bound tensors. | +| `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | all | Boolean | `0` | Print the tensor address map once. | + +Notes: + +- `GGML_OPENVINO_DEBUG_DYNAMIC_DIMS`: `*` marks the dynamic (token) dimension. +- `GGML_OPENVINO_LOG_SUPPORTS_OP=2`: the lines of the first calls are missing. These calls come before the log handler prints anything. The summary at exit counts them. +- The backend rejects some scaled matmuls (`ggml_mul_mat_ext`, `ggml_mul_mat_id_ext`) before the logging code. `GGML_OPENVINO_LOG_SUPPORTS_OP` and `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` do not log or count these rejections. + +### In-process graph cache + +These variables control the in-process cache of compiled models and decoders. + +| Variable | Device | Type | Default | Description | +|---|---|---|---|---| | `GGML_OPENVINO_DISABLE_CACHE` | all | Boolean | `0` | Turn the in-process cache of compiled models and decoders off. | -| `GGML_OPENVINO_FULL_GRAPH_KEY` | all | Boolean | `0` | Add the external inputs of a graph to the key of the in-process cache. By default the key holds the node and leaf counts, the names of the first and last nodes, and some graph markers (output flags, sampler rows, weight buffers), but not the external inputs. Use it when two different graphs could share that key. | -| `GGML_OPENVINO_LOG_SWA_LAYERS` | all | Boolean | `0` | Log the attention extent of each layer and which layers use sliding-window attention, on an `ov-swa:` line at the WARN level. | -| `GGML_OPENVINO_NPUW_DUMP_SUBS` | NPU | String | `not set` | Dump NPUW subgraphs: `YES` (all), `MIN` (unique function bodies), `last`, or indices such as `0,2`. | -| `GGML_OPENVINO_NPUW_DUMP_SUBS_DIR` | NPU | String | `not set` | Directory for the NPUW subgraph dumps. | -| `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`. | +| `GGML_OPENVINO_FULL_GRAPH_KEY` | all | Boolean | `0` | Add the external inputs of a graph to the cache key. See the notes. | + +Notes: + +- `GGML_OPENVINO_FULL_GRAPH_KEY`: use it when two different graphs could share the default key. What the default key holds: [In-process caches](README.md#in-process-caches). +- `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1` cannot be used with `GGML_OPENVINO_DISABLE_CACHE=1`: the backend aborts. + +### NPUW dumps + +These variables pass the NPUW dump options to the NPU plugin. They need an OpenVINO developer build (`NPU_PLUGIN_DEVELOPER_BUILD`). + +| Variable | Device | Type | Default | Description | +|---|---|---|---|---| +| `GGML_OPENVINO_NPUW_DUMP_IO` | NPU | String | unset | Passed to OpenVINO unchanged as `NPUW_DUMP_IO`. | +| `GGML_OPENVINO_NPUW_DUMP_SUBS` | NPU | String | unset | Dump NPUW subgraphs: `YES` (all), `MIN` (unique function bodies), `last`, or indices such as `0,2`. | +| `GGML_OPENVINO_NPUW_DUMP_SUBS_DIR` | NPU | String | unset | Directory for the NPUW subgraph dumps. | +| `GGML_OPENVINO_NPUW_DUMP_SUBS_ON_FAIL` | NPU | String | unset | Passed to OpenVINO unchanged as `NPUW_DUMP_SUBS_ON_FAIL`. | ## 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. +### KV cache binding + +These variables control how the backend binds the attention KV cache. Details: [KV cache binding](README.md#kv-cache-binding). + | 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`. 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`. | +| `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. | +| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | auto | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]` for in-place updates. See the notes. | +| `GGML_OPENVINO_GPU_KV_ROUND_UP` | GPU | Boolean | `1` | Round the attended width up on dynamic stateless GPU. `0` uses the GGML mask width. | +| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | One decode graph for each KV window. `0`: one decode graph for the whole context. See the notes. | + +Notes: + +- `GGML_OPENVINO_KV_SLICE`: `1` is on with KV window base 1024. `N` (a multiple of 256) is on with KV window base `N`. The base applies to the static NPU path; dynamic CPU and GPU graphs use the value only as on or off. +- `GGML_OPENVINO_ENABLE_KV_4D`: auto is on with OpenVINO 2026.5 or later. `0` forces it off, a positive value forces it on. The cases that do not use it are in [4-D KV binding on the GPU](README.md#4-d-kv-binding-on-the-gpu). +- `GGML_OPENVINO_NPU_BLOB_PREBUILD`: the backend builds the window graphs, or reads them from the compiled model cache, at the first call. The KV window base comes from `GGML_OPENVINO_KV_SLICE`. +- Use the same `GGML_OPENVINO_NPU_BLOB_PREBUILD` value in the run that writes the compiled model cache and in the runs that read it. + +### Graph and ops + +These variables turn off graph transformations and output bindings. + +| Variable | Device | Type | Default | Description | +|---|---|---|---|---| +| `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK` | CPU, GPU | Boolean | `0` | `1` passes the sequence count and the attended KV length as separate inputs. | +| `GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN` | GPU | Boolean | `0` | By default the operands of an element-wise op get the same rank. `1` turns this off. | +| `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE` | GPU | Boolean | `0` | `1` turns off the recurrent replay translation. Replay ops then run on another backend. | +| `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS` | GPU | Boolean | `0` | `1` stops the direct binding of output tensors in GPU buffers to the infer request. | | `GGML_OPENVINO_MOE_OP` | GPU | Boolean | `1` | `0` keeps the unfused GatherMatmul path for mixture-of-experts layers. | -| `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK` | CPU, GPU | Boolean | `0` | By default the model reads the sequence count and the attended KV length from the shape of the KQ mask, so the GPU plugin can select its fused attention kernel. `1` passes them as separate inputs. | -| `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT` | CPU, GPU | Boolean | `0` | Stateful execution only. By default the sequence axis of the KV state is moved so that new tokens are appended in place. `1` keeps the original layout. | -| `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS` | GPU | Boolean | `0` | By default an output tensor in a GPU buffer is bound directly to the infer request when its shape and type match. `1` turns this off. | -| `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE` | GPU | Boolean | `0` | `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]` 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. | + +Notes: + +- `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`: by default the model reads the two values from the KQ mask shape, so the GPU plugin can select its fused attention kernel. +- `GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN`: the rank alignment runs on every GPU graph. It works around a GPU plugin defect: an element-wise op with operands of different rank gives wrong results when the plugin fuses it into RMS norm. gemma-4 (dense) in stateful execution gave wrong output on the GPU without it. +- `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE`: for an unfused OpenVINO replay graph, keep the value `0` and use a GPU plugin without the replay fusion pass. See [GPU replay fusion](QWEN-MTP.md#gpu-replay-fusion). +- `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`: the direct binding applies when the shape and the type of the output match. + +### NPU + +These variables turn off or tune NPU-specific optimizations. + +| Variable | Device | Type | Default | Description | +|---|---|---|---|---| +| `GGML_OPENVINO_GDN_Q_SCALE` | NPU | Float | `64` | Factor of the GDN q pre-scaling. `0` or a negative value turns it off. See the notes. | +| `GGML_OPENVINO_NPU_FAST_MASK` | NPU | Boolean | `1` | Write the prefill attention mask into the input tensor, with no intermediate copy. See the notes. | +| `GGML_OPENVINO_NPU_L0_HOST_TENSORS` | NPU | Boolean | `1` | Keep the KV cache and compute buffers in Level Zero host memory. See the notes. | + +Notes: + +- `GGML_OPENVINO_GDN_Q_SCALE`: the pre-scaling keeps the GDN output above the FP16 flush-to-zero floor of the NPU. Values below `64` are raised to `64`. +- `GGML_OPENVINO_NPU_FAST_MASK` does not change the result. +- `GGML_OPENVINO_NPU_L0_HOST_TENSORS`: the plugin reads Level Zero host memory without an extra copy. If the Level Zero allocation fails, the backend uses plain RAM, or the `GGML_OPENVINO_COMPILE_MEM_SPILL` files when the spill is on. + +## Memory optimization + +These variables lower the RAM peak. They do not change the output. Commands: [Lower memory use](COOKBOOK.md#lower-memory-use). + +| Variable | Device | Type | Default | Description | +|---|---|---|---|---| +| `GGML_OPENVINO_COMPILE_MEM_SPILL` | all | Float | auto | Back the buffers in RAM (weights, KV cache, compute) with files. See the notes. | +| `GGML_OPENVINO_COMPILE_MEM_SPILL_DIR` | all | String | `/var/tmp` | Directory for the `GGML_OPENVINO_COMPILE_MEM_SPILL` files. Use real storage, not tmpfs. | +| `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | unset | Set the defaults of the other memory variables (see the notes). An explicit value wins. | +| `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | auto | Create fewer weight nodes during compilation. See the notes. | +| `GGML_OPENVINO_RELEASE_WEIGHTS` | GPU | Boolean | `1` | Release the weight buffers in RAM after compilation. `0` keeps them. See the notes. | +| `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | Buffers of this size or larger do not use Level Zero host memory. See the notes. | + +Notes: + +- `GGML_OPENVINO_MEMORY_OPTIMIZE=1` sets `GGML_OPENVINO_REDUCE_COMPILE_MEM=1`, `GGML_OPENVINO_COMPILE_MEM_SPILL=0.1` (CPU and GPU) and `GGML_OPENVINO_RELEASE_WEIGHTS=1` (GPU). +- `GGML_OPENVINO_MEMORY_OPTIMIZE=0` also sets `GGML_OPENVINO_RELEASE_WEIGHTS=0`, so on the GPU the weights stay in RAM. +- `GGML_OPENVINO_REDUCE_COMPILE_MEM` auto: the value of `GGML_OPENVINO_MEMORY_OPTIMIZE`, else `0`. +- `GGML_OPENVINO_COMPILE_MEM_SPILL` backs the buffers with files, so the kernel can drop their pages. Values: + - `0`: off. + - `1`: on, but the kernel drops the pages only when RAM runs out. The RAM peak does not change while RAM is free. + - A fraction between `0` and `1`: on. While the model loads and compiles, at most this fraction of the spilled weights stays in RAM, also when RAM is free. `0.1` keeps 10%. Needs Linux 5.4 or later. + - Unset: `0.1` with `GGML_OPENVINO_MEMORY_OPTIMIZE=1` on CPU and GPU, else `0`. +- A fraction lowers the peak the most. The pages of the model file are dropped too. 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 backend reserves the disk space when it creates the files (not for rewrites on btrfs or ZFS). It needs more than the model size, and on CPU also the KV cache. With too little space, the backend warns and uses RAM. +- `GGML_OPENVINO_COMPILE_MEM_SPILL_DIR` on tmpfs (`/tmp` on many systems): the backend warns and uses RAM. +- NPU: only an explicit `GGML_OPENVINO_COMPILE_MEM_SPILL` value turns the spill on. The spill applies only to NPU buffers without Level Zero host memory: + - With `GGML_OPENVINO_NPU_L0_HOST_TENSORS=0`: all buffers. + - With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB`. + - With `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`: the KV cache buffer. + - Buffers whose Level Zero allocation fails. +- `GGML_OPENVINO_COMPILE_MEM_SPILL` and `GGML_OPENVINO_COMPILE_MEM_SPILL_DIR` are not part of the compiled model cache key. The backend ignores both on Windows and in cache-only mode. +- `GGML_OPENVINO_RELEASE_WEIGHTS`: the compiled model keeps its own copy of the weights. Before a new compile or a host read, the backend writes the released weights again from the model file. +- `GGML_OPENVINO_RELEASE_WEIGHTS` follows `GGML_OPENVINO_MEMORY_OPTIMIZE` when that is set. It is off with `-lm none` and in cache-only mode. Linux only. +- `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` applies only with `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`. Buffers of this size or larger then use demand-zero memory, or the `GGML_OPENVINO_COMPILE_MEM_SPILL` files when the spill is on. ## Experimental options @@ -63,35 +196,58 @@ Most of these options are off by default. They are not validated for general use | Variable | Device | Type | Default | Description | |---|---|---|---|---| -| `GGML_OPENVINO_NPU_DECODE_UNFOLD` | NPU | Boolean | `0` | Set `NPUW_UNFOLD_IREQS=YES` on the decode graph only. An explicit `GGML_OPENVINO_NPUW_UNFOLD_IREQS` or `GGML_OPENVINO_NPU_CONFIG` value takes precedence. No effect on graphs with a MoE block, which get `NPUW_UNFOLD_IREQS=NO`. | -| `GGML_OPENVINO_NPU_KV_ON_DEMAND` | NPU | Boolean | `0` | Keep the ggml KV buffer non-resident and bind storage for each layer that grows with the rows in use, so a large `-c` costs memory only for the context that is reached. With `GGML_OPENVINO_NPU_BLOB_PREBUILD` and `GGML_OPENVINO_KV_SLICE` on (the defaults), K is stored head-major and V transposed, as OpenVINO GenAI does. `llama-perplexity` fails with it. | -| `GGML_OPENVINO_NPU_REQUANT_POLICY` | NPU | String | `group-128` | Layout of requantized weights: `group-128` (`Q4_0_128`) or `channel-wise` (`Q4_0_C`, lower accuracy). | -| `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK` | all | Integer | `16` | Tokens in one chunk when `GGML_OPENVINO_GDN_DECOMPOSE` is on. A power of 2 from 2 to 128; other values use `16`. | -| `GGML_OPENVINO_GDN_NATIVE_STATE` | NPU | Boolean | `0` | Keep the `GATED_DELTA_NET` state in the layout of the OpenVINO op instead of the GGML layout. Every `GATED_DELTA_NET` must then run on the OpenVINO backend; the load aborts if one would run on the CPU backend. Saved states and `GGML_OPENVINO_DEBUG_NODE` dumps hold the OpenVINO layout. `test-backend-ops` fails with it. | -| `GGML_OPENVINO_FORCE_STATIC` | CPU, GPU | Boolean | `0` | Run the static-shape path of the NPU on the CPU or the GPU, to separate translation bugs from NPU plugin or driver problems. 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_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_ENABLE_FALLBACK` | all | Boolean | `0` | Detect graphs split between OpenVINO and another backend, and translate them as partial graphs. | +| `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | all | Boolean | `0` | In stateless execution, write single KV rows with `ScatterElementsUpdate`, not `ScatterUpdate`. | +| `GGML_OPENVINO_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op. Default: `relu(x) + log1p(exp(-abs(x)))`. | +| `GGML_OPENVINO_FORCE_STATIC` | CPU, GPU | Boolean | `0` | Run the NPU static-shape path on the CPU or the GPU. See the notes. | +| `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK` | NPU | Integer | `16` | Tokens in one chunk when `GGML_OPENVINO_GDN_DECOMPOSE` is on. See the notes. | +| `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. | +| `GGML_OPENVINO_NPU_DECODE_UNFOLD` | NPU | Boolean | `0` | Set `NPUW_UNFOLD_IREQS=YES` on the decode graph only. | +| `GGML_OPENVINO_NPU_KV_ON_DEMAND` | NPU | Boolean | `0` | Keep the ggml KV buffer non-resident and bind per-layer storage that grows with the rows in use. | +| `GGML_OPENVINO_NPU_REQUANT_POLICY` | NPU | Enum | `group-128` | Layout of requantized weights: `group-128` (`Q4_0_128`) or `channel-wise` (`Q4_0_C`). | -## Memory optimization +Notes: + +- `GGML_OPENVINO_ENABLE_FALLBACK`: by default, the backend treats every graph as a complete model graph. Partial graphs do not use the compiled model cache. +- `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1` cannot be used with `GGML_OPENVINO_ENABLE_FALLBACK=1` or `GGML_OPENVINO_FORCE_STATIC=1`: the backend aborts. +- `GGML_OPENVINO_FORCE_STATIC`: use it to separate translation bugs from NPU plugin or driver problems. +- `GGML_OPENVINO_FORCE_STATIC` also runs the NPU translation of MoE blocks. It computes every expert on the CPU or the GPU and is slow. +- `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK`: a power of 2 from 2 to 128. Other values use `16`. +- `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK` applies only to graphs with static shapes: the NPU path, the `GGML_OPENVINO_FORCE_STATIC` path and op tests. +- `GGML_OPENVINO_GDN_NATIVE_STATE`: every `GATED_DELTA_NET` must then run on the OpenVINO backend. The load aborts if one would run on the CPU backend. +- With `GGML_OPENVINO_GDN_NATIVE_STATE`, saved states and `GGML_OPENVINO_DEBUG_NODE` dumps hold the OpenVINO layout. `test-backend-ops` fails with it. +- `GGML_OPENVINO_NPU_DECODE_UNFOLD`: an explicit `GGML_OPENVINO_NPUW_UNFOLD_IREQS` or `GGML_OPENVINO_NPU_CONFIG` value takes precedence. +- `GGML_OPENVINO_NPU_DECODE_UNFOLD` has no effect on graphs with a MoE block, which get `NPUW_UNFOLD_IREQS=NO`. +- `GGML_OPENVINO_NPU_KV_ON_DEMAND`: with it, a large `-c` costs memory only for the context that is reached. `llama-perplexity` fails with it. +- The KV layout of `GGML_OPENVINO_NPU_KV_ON_DEMAND`: [KV windows on the NPU](README.md#kv-windows-on-the-npu). +- `GGML_OPENVINO_NPU_REQUANT_POLICY=channel-wise` gives lower accuracy than `group-128`. + +## Deprecated: stateful execution -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). +The variable below applies only to stateful execution (`GGML_OPENVINO_STATEFUL_EXECUTION=1`), which is deprecated. See [Deprecated](../../../../docs/backend/OPENVINO.md#deprecated). | 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. | +| `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT` | CPU, GPU | Boolean | `0` | `1` keeps the original layout of the KV state. | -## NPU plugin properties +Notes: -The backend sets the properties below for the NPU. `GGML_OPENVINO_NPU_CONFIG` can change them and add others. +- `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`: by default the backend moves the sequence axis of the KV state, so new tokens are appended in place. + +## Plugin properties set by the backend + +The backend sets the OpenVINO plugin properties below. The format and the rules of `GGML_OPENVINO_NPU_CONFIG`, `GGML_OPENVINO_GPU_CONFIG` and `GGML_OPENVINO_CPU_CONFIG` are in [Plugin properties](../../../../docs/backend/OPENVINO.md#plugin-properties). + +### All devices + +The backend sets these properties on every device: -- **Backend default**: the value that the backend passes to OpenVINO when the user sets nothing. -- **OpenVINO default**: the value that OpenVINO uses when nobody sets the property. -- Values are those of OpenVINO, for example `YES` and `NO`. +- `ENABLE_PROFILING` with `GGML_OPENVINO_PROFILING=2` or higher. +- `EXECUTION_MODE_HINT` on the small graphs of op tests: `PERFORMANCE` for a graph that starts with `MUL_MAT`, `ACCURACY` for the others. + +### NPU plugin properties + +The backend sets the properties below for the NPU. `GGML_OPENVINO_NPU_CONFIG` can change them and add others. | Property | Type | Backend default | OpenVINO default | Description | |---|---|---|---|---| @@ -100,14 +256,23 @@ The backend sets the properties below for the NPU. `GGML_OPENVINO_NPU_CONFIG` ca | `NPUW_FOLD` | Boolean | `YES` | `NO` | Compile the repeating blocks of the model once and reuse them. | | `NPUW_FUNCALL_FOR_ALL` | Boolean | `YES` | `NO` | Make every part of the model a function, not only the repeating blocks. | | `NPUW_FUNCALL_ASYNC` | Boolean | `YES` | `NO` | Run a function and the preparation of the next one as a pipeline. | -| `NPUW_WEIGHTS_BANK` | String | `shared`; with `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, a bank of the model (`ggml-wl-model-` or `ggml-wl-shared-`) | empty | Name of the weights bank. Graphs with the same name share one copy of the weights. | +| `NPUW_WEIGHTS_BANK` | String | `shared` | empty | Name of the weights bank. Graphs with the same name share one copy of the weights. | | `NPUW_DQ` | Boolean | `YES` | `NO` | Apply the dynamic quantization transformations in the plugin. | | `NPUW_DQ_FULL` | Boolean | `NO` | `YES` | Apply the full dynamic quantization pipeline in the plugin. | | `NPU_COMPILER_DYNAMIC_QUANTIZATION` | Boolean | `YES` | `NO` | Dynamic quantization in the NPU compiler. | -| `NPU_COMPILER_TYPE` | String | `DRIVER` | `PREFER_PLUGIN` | The NPU compiler: `DRIVER` (in the NPU driver), `PLUGIN` (in OpenVINO) or `PREFER_PLUGIN` (`PLUGIN` when it is available, `DRIVER` if not). Models with `GATED_DELTA_NET` layers (Qwen3.5) compile with `PLUGIN` unless the user sets this property. | -| `NPUW_CACHE_DIR` | String | value of `GGML_OPENVINO_CACHE_DIR` | empty | Directory for the compiled parts. | +| `NPU_COMPILER_TYPE` | String | `DRIVER` | `PREFER_PLUGIN` | The NPU compiler: `DRIVER` (in the NPU driver), `PLUGIN` (in OpenVINO) or `PREFER_PLUGIN`. | +| `NPUW_CACHE_DIR` | String | auto | empty | Directory for the compiled parts. Auto: the value of `GGML_OPENVINO_CACHE_DIR`, when set. | -Graphs with a MoE block (softmax router and SwiGLU experts, translated into the batched form that NPUW recognises) also get the properties below. They make NPUW run only the routed experts, with the router on the host (the `HOST_ROUTED` mode of `NPUW_LLM_*_MOE_HINT`). `GGML_OPENVINO_NPU_CONFIG` can change them. +Notes: + +- `NPU_COMPILER_TYPE=PREFER_PLUGIN` uses `PLUGIN` when it is available, `DRIVER` if not. +- `NPU_COMPILER_TYPE`: models with `GATED_DELTA_NET` layers (Qwen3.5) compile with `PLUGIN` unless the user sets this property. +- `GGML_OPENVINO_CACHE_DIR` sets only `NPUW_CACHE_DIR` on the NPU, and the backend keeps the default `CACHE_MODE`. With `CACHE_MODE=OPTIMIZE_SIZE`, the NPU plugin compiles the NPUW parts with weights separation, which fails for them. +- With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`: no `CACHE_DIR` and no `CACHE_MODE`, and `NPUW_WEIGHTS_BANK` names a bank of the model (`ggml-wl-model-` or `ggml-wl-shared-`). This overrides the same properties in `GGML_OPENVINO_NPU_CONFIG`. +- Graphs without a KV cache compile without NPUW: the backend removes `NPU_USE_NPUW` and the `NPUW_*` keys for them. +- Compiled model cache on the NPU: see [NPU: gemma-4 E2B example](COOKBOOK.md#npu-gemma-4-e2b-example). + +Graphs with a MoE block (softmax router and SwiGLU experts, translated into the batched form that NPUW recognises) also get the properties below, and `NPUW_UNFOLD_IREQS=NO`. They make NPUW run only the routed experts, with the router on the host (the `HOST_ROUTED` mode of `NPUW_LLM_*_MOE_HINT`). `GGML_OPENVINO_NPU_CONFIG` can change them. | Property | Type | Backend default | OpenVINO default | Description | |---|---|---|---|---| @@ -115,42 +280,46 @@ Graphs with a MoE block (softmax router and SwiGLU experts, translated into the | `NPUW_ONLINE_ISOLATE` | String | `MOE` added | empty | Isolate the experts into their own functions. Added to a value that is already set. | | `NPUW_ONLINE_KEEP_BLOCKS_TAGGED` | String | `expert` added | empty | Keep the isolated experts even below the repeating-block threshold. | | `NPUW_ONLINE_KEEP_BLOCK_SIZE` | Integer | `4` | `10` | Smallest repeating block that is kept. | -| `NPUW_UNFOLD_IREQS` | Boolean | `NO` | `NO` | One infer request for each part. | | `NPUW_MOE_TOKEN_CHUNK_SIZE` | Integer | `16` | `0` | Tokens per expert call in prefill. `0` compiles 8 sizes (16 to 512); one small size uses less memory. | -| `NPUW_MOE_POOL_SIZE` | Integer | `0` | `8` | Infer requests per MoE layer kept for decode, each bound to a set of experts. With 40 MoE layers, the default of 8 fills the NPU memory of a 32 GB system and the load hangs. | +| `NPUW_MOE_POOL_SIZE` | Integer | `0` | `8` | Infer requests per MoE layer kept for decode, each bound to a set of experts. | + +Notes: + +- `NPUW_MOE_POOL_SIZE`: with 40 MoE layers, the OpenVINO default of 8 fills the NPU memory of a 32 GB system and the load hangs. -Other properties for `GGML_OPENVINO_NPU_CONFIG`. The backend does not set them, except in the cases that the table names. +Other properties for `GGML_OPENVINO_NPU_CONFIG`. The backend does not set them, except in the cases that the notes name. | Property | Type | Backend default | OpenVINO default | Description | |---|---|---|---|---| -| `COMPILATION_NUM_THREADS` | Integer | `not set` | number of CPU cores | Threads of the NPU compiler. A lower value lowers the host memory peak when a large model compiles. | -| `NPUW_UNFOLD_IREQS` | Boolean | `not set`; `NO` 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`. | +| `COMPILATION_NUM_THREADS` | Integer | unset | number of CPU cores | Threads of the NPU compiler. Fewer threads lower the RAM peak of a large model compile. | +| `LOG_LEVEL` | String | unset | `LOG_ERROR` | Log level of the NPU plugin, for example `LOG_INFO`. | +| `NPUW_UNFOLD_IREQS` | Boolean | auto | `NO` | One infer request for each part, also for repeating blocks. | +Notes: + +- `NPUW_UNFOLD_IREQS` auto: `NO` on graphs with a MoE block, `YES` on the decode graph with `GGML_OPENVINO_NPU_DECODE_UNFOLD=1`, else unset. A value from `GGML_OPENVINO_NPU_CONFIG` wins. - 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. 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. -- Compiled model cache on the NPU: see [NPU: gemma-4 E2B example](COOKBOOK.md#npu-gemma-4-e2b-example). +- `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, use the OpenVINO `hello_query_device` sample: see [Profiling and debug dumps](COOKBOOK.md#profiling-and-debug-dumps). -## GPU and CPU plugin properties +### 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. +- The properties in [All devices](#all-devices). 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. For example, `GGML_OPENVINO_NPU_CONFIG="NPUW_UNFOLD_IREQS=YES"` and `GGML_OPENVINO_NPUW_UNFOLD_IREQS=YES` do the same. Use the first form. +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 `GGML_OPENVINO_NPU_CONFIG`. | Variable | Device | Type | Default | Description | |---|---|---|---|---| -| `GGML_OPENVINO_NPU_COMPILE_CONFIG` | NPU | String | `not set` | Sets `NPU_COMPILATION_MODE_PARAMS`. | -| `GGML_OPENVINO_NPU_COMPILER_TYPE` | NPU | String | `not set` | Sets `NPU_COMPILER_TYPE`. | -| `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`. | +| `GGML_OPENVINO_COMPILATION_NUM_THREADS` | NPU | String | unset | Sets `COMPILATION_NUM_THREADS`. | +| `GGML_OPENVINO_NPU_COMPILE_CONFIG` | NPU | String | unset | Sets `NPU_COMPILATION_MODE_PARAMS`. | +| `GGML_OPENVINO_NPU_COMPILER_TYPE` | NPU | String | unset | Sets `NPU_COMPILER_TYPE`. | +| `GGML_OPENVINO_NPUW_FUNCALL_FOR_ALL` | NPU | String | unset | Sets `NPUW_FUNCALL_FOR_ALL`. | +| `GGML_OPENVINO_NPUW_UNFOLD_IREQS` | NPU | String | unset | Sets `NPUW_UNFOLD_IREQS`. | diff --git a/ggml/src/ggml-openvino/dev_doc/QWEN-MTP.md b/ggml/src/ggml-openvino/dev_doc/QWEN-MTP.md new file mode 100644 index 000000000000..34d3329e5b73 --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/QWEN-MTP.md @@ -0,0 +1,213 @@ +# Qwen MTP and recurrent replay + +This page covers how the OpenVINO backend runs Qwen3.5/Qwen3.6 multi-token prediction (MTP): recurrent replay on the GPU and the multi-slot draft sampling graph. Commands: [Speculative decoding](COOKBOOK.md#speculative-decoding). Terms: [Glossary](README.md#glossary). + +- 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. +- The backend finds replay groups by graph structure. It is validated with `qwen35` and `qwen35moe`, with one or more slots. +- Reference model: the [UD](README.md#glossary) Qwen3.6-35B-A3B MTP GGUF model file. +- 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). Known limitation of cache-only MTP serving: [Known Limitations](../../../../docs/backend/OPENVINO.md#known-limitations). + +Contents: + +- [Requirements](#requirements) +- [Replay graph selection](#replay-graph-selection) +- [Buffer ownership and operation boundaries](#buffer-ownership-and-operation-boundaries) +- [Replay graph contract](#replay-graph-contract) +- [Convolution cache stores](#convolution-cache-stores) +- [GPU replay fusion](#gpu-replay-fusion) +- [Stable multi-slot draft sampling](#stable-multi-slot-draft-sampling) +- [Compiled models and the cache](#compiled-models-and-the-cache) +- [Testing and profiling](#testing-and-profiling) + +## Requirements + +- Dynamic stateless GPU execution (`GGML_OPENVINO_DEVICE=GPU`). 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](README.md#kv-cache-binding). +- For Qwen3.6-35B-A3B Q4_K_M, the recommended requantization is `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all`. Details: [Advanced tuning](../../../../docs/backend/OPENVINO.md#advanced-tuning). + +## Replay graph selection + +- 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. `op_params[2]` holds the keep flag. +- A fresh prompt supplies a replay count of zero. +- 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. + +## Buffer ownership and operation boundaries + +The table shows where each state lives on the GPU and how the fused path updates it. + +| State | Storage and lifetime | Update path | +|---|---|---| +| Attention K/V | Full caller-owned USM allocation, sized by context and KV layout | Native stateless KV fusion when eligible; SDPA reads the live prefix | +| Convolution `cache_r` | Caller-owned USM bank: history and pending columns | Fused reset, original-row gather/reorder, convolution, ordered writes | +| GDN `cache_s`, `cache_sp*` | Caller-owned USM banks: committed state, pending token inputs | Fused reset, original-row gather/reorder, GDN, ordered writes | +| Runtime controls | Reused USM host storage on GPU | Row maps, offsets and write controls remain runtime inputs | +| Protected source rows | Private device scratch | Staged before writes to protect cycles, duplicate sources and overlaps | +| Inactive sampling results | Private device-USM scratch | Discarded without touching inactive GGML output buffers | + +- The GDN pending banks are `cache_spk`, `cache_spv` and `cache_spgb` (pending K, V, gate and beta). +- Ordered writes: history and pending columns for the convolution; committed state and pending K, V, gate and beta for GDN. +- Recurrent-cache size depends on slot capacity and pending-token capacity. +- Each fused cache input Parameter binds a caller-owned writable allocation. + +The GPU plugin pass emits two internal ops. They exist only with a matching OpenVINO GPU plugin build (see [GPU replay fusion](#gpu-replay-fusion)). + +| Op | Returns | Writes | +|---|---|---| +| `RecurrentConvCacheReplayUpdate` | Convolution `[1,B,T,C]` | History and pending columns | +| `RecurrentGatedDeltaNetReplayUpdate` | Attention | Committed state and pending K, V, gate and beta | + +- Both kernels write their cache inputs directly. + +## Replay graph contract + +The backend emits the replay graph only on GPU, for a dynamic, stateless graph that is not split. On other devices, and on the static or stateful path, `supports_replay_cache_banks()` (`ggml-openvino.cpp`) rejects the replay ops and their cache stores, and another GGML backend runs them. A split graph with a replay `GATED_DELTA_NET` fails in translation ("GATED_DELTA_NET replay requires a complete recurrent cache group"). `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` turns the replay translation off ([Switches for default optimizations](OpenVINO-ENV-VARS.md#switches-for-default-optimizations)). + +Standard-op graph and `Assign` sinks: + +- `RecurrentReplayFusion` (`openvino/recurrent_replay_fusion.cpp`) recognizes the GGML replay groups and translates them with standard OpenVINO 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_`. +- The backend keeps the replay subgraph, its `Loop` body and its bank inputs in FP32 under the GPU f16 inference hint. + +Writeback without fusion: + +- When a sink remains, for example on a GPU plugin without the fusion pass, the backend finds it with `query_state()` after compilation or import (`utils.cpp`). +- After each inference, the backend copies that state to the original GGML bank. + +Source of the replay pattern: + +- The backend builds the graph in [`openvino/op/recurrent_replay_graph.hpp`](../openvino/op/recurrent_replay_graph.hpp). +- The GPU plugin pass compares it to a reference built from the OpenVINO copy of `recurrent_replay_graph.hpp`. Keep the two copies in sync. + +When upstream modeling changes the GGML graph: + +1. Adapt the backend recognition and check what it emits. +2. If the emitted replay pattern or its semantics change, update the reference and the relevant matcher and kernel logic with the translation. +3. Verify that the graph still fuses and that the standard-op writeback still works. + +## Convolution cache stores + +- The structural replay graph gathers history using the retained-token count, concatenates live input, and uses one grouped convolution. +- A slice selects history and pending columns for the next batch. +- `ScatterNDUpdate` produces the updated bank for the `Assign` sink. +- Row maps, replay counts and reset rows are runtime inputs. + +## GPU replay fusion + +The fusion needs a matching OpenVINO GPU plugin build. Without it, the standard-op replay graph and the `query_state()` writeback run. On this page, "the GPU plugin pass" is the OpenVINO transformation, and `RecurrentReplayFusion` is the backend class. + +- The GPU plugin pass structurally fuses complete replay groups into its internal convolution and GDN ops. +- The GPU plugin requires the transformed model to preserve its `Result` count. Sinks express writeback separately from that output interface. +- The pass can replace the computation and remove its matched sinks and variables while keeping the Results. The internal op then writes through the original input binding. This avoids the GPU runtime changes that would be needed to alias a cache output to its input. +- The variable ID supplies the write permission. The pass still matches the computation, row controls, reset, reordering and writeback structure. It also requires exclusive bank readers and a live computation output. +- The kernel checks for overlapping buffer ranges. + +The fused GPU computation uses two stages: + +1. It preserves the required original rows in scratch while it applies logical reset and precision rounding. +2. It computes and performs the ordered writes. + +- This order avoids overwriting a source before another destination has read it. +- Identity reorder sources need no scratch writes. +- In-place execution removes the spare full output bank, not every cache read or internal memory transaction. + +## Stable multi-slot draft sampling + +The MTP draft graph keeps the same node names and candidate-output ports for every subset of active slots, so one compiled draft model serves all subsets. + +### Sampler behavior + +- 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. +- 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 (see [Buffer ownership and operation boundaries](#buffer-ownership-and-operation-boundaries)). They do not change sampler state or acceptance. +- The backend does not change the original cgraph or execute inactive stateful sampler chains. +- 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. +- Only a pure top-k chain keeps its inactive branches: VIEW, two Reshapes, TopK and GET_ROWS, with no other reader (`get_compute_graph()` in `utils.cpp`). Other chains drop the branches that have no COMPUTE flag. Static (NPU) and stateful execution drop them for every chain. + +### Graph layout + +The node indices and counts below are from an example capture: the UD Qwen3.6-35B-A3B model in cache-only mode, four slots, context 8192 and `--spec-draft-n-max 2`. Other models and settings give other numbers. + +- The captured draft graph contains 107 nodes regardless of which of the 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 the active slots. + +```text +MTP token IDs + input hidden state + | + 0-84: MTP layer and normalization, N active slots + | + 85: logits [248320, N] + 86: PAD adds one safe row + | + +-- 87-91: slot 0 sampling + +-- 92-96: slot 1 sampling + +-- 97-101: slot 2 sampling + +-- 102-106: slot 3 sampling +``` + +- Each branch contains VIEW, two Reshapes, TopK (ten candidate IDs) and GET_ROWS (their scores). +- Ten is the candidate count, not the speculative-token count. +- The draft interface of the capture has 10 inputs and 12 outputs: eight candidate ID/score outputs, hidden state, full logits and two KV Results. + +### Active slots + +The table shows the same example capture for three subsets of active slots. + +| 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]` | + +- 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. +- In dynamic execution, one int64 `sampling_rows` Parameter supplies the row indices. Static execution uses one `sampling_row_` 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. + +For active slots `{0,2}`, the two logits rows belong to slots 0 and 2: + +```text +sampling_rows = [0, 0, 1, 0] +slot 0 -> row 0 -> normal candidate buffers +slot 1 -> row 0 -> private scratch, ignored +slot 2 -> row 1 -> normal candidate buffers +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. +- `graph_key` (the key of each backend context) and the dynamic fingerprint (the blob key) leave out the COMPUTE flags, so all active subsets use one compiled draft model. +- `compiled_graph_key()` holds the node flags, including COMPUTE. It is the shared in-process key only without a cache directory, and it names the exact disk entry. A change of the active subset hits `graph_key` first. +- 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. +- Graphs with the replay interface get their own cache entries, because the interface replaces the bank Results with `Assign` sinks (an extra `extra_cfg` term in `utils.cpp`). +- Cache-only mode still requires initial preparation: prepare compatible blobs once, then use cache-only mode. A change of the active subset needs no extra preparation. +- The first import and runtime preparation still have a cost. +- Cache-only MTP serving needs an OpenVINO fix that is not in a release yet: [Known Limitations](../../../../docs/backend/OPENVINO.md#known-limitations). +- Cache internals: [Compiled model cache](README.md#compiled-model-cache). + +## Testing and profiling + +- `GGML_OPENVINO_DUMP_CGRAPH=1` also logs the number of convolution and GDN replay groups (`replay fusion: convolution, GDN groups`) when it converts a graph. An import or a `graph_key` hit logs nothing. The line has the INFO level, so llama-cli needs `-lv 4`. To read the dump, see [Reading graph dumps](README.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. To check replay with an MTP model, see [Speculative decoding](COOKBOOK.md#speculative-decoding). +- 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/README.md b/ggml/src/ggml-openvino/dev_doc/README.md index ee169e909cf9..29eadb7d9fa4 100644 --- a/ggml/src/ggml-openvino/dev_doc/README.md +++ b/ggml/src/ggml-openvino/dev_doc/README.md @@ -1,155 +1,302 @@ # 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. +This page covers the internals of the OpenVINO backend on CPU, GPU and NPU. It is for contributors. The terms are in the [Glossary](#glossary). -- 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 | +| Document | What it holds | |---|---| -| 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, 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 | +| [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md) | Quick start, devices, precisions, validated models, user variables, known limitations | +| [COOKBOOK.md](COOKBOOK.md) | Commands and scripts for each task: build, Docker, devices, cache, memory, MoE, speculative decoding, profiling | +| [OpenVINO-ENV-VARS.md](OpenVINO-ENV-VARS.md) | Developer variables: debug output, optimization switches, experimental options, memory, plugin properties | +| [QWEN-MTP.md](QWEN-MTP.md) | Qwen MTP and recurrent replay: buffer ownership, replay graph contract, GPU replay fusion, multi-slot draft sampling | -Contents of this page: +Contents: - [How the backend works](#how-the-backend-works) +- [Where to change what](#where-to-change-what) - [Source layout](#source-layout) +- [Weight layouts](#weight-layouts) - [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) +- [Reading graph dumps](#reading-graph-dumps) +- [Glossary](#glossary) ## How the backend works -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. +The scheduler sends each `ggml_cgraph` to the OpenVINO backend. The diagram shows the dynamic path (CPU, GPU). + +```text +ggml_cgraph (ops accepted by supports_op, ggml-openvino.cpp) + | +ov_graph_compute() utils.cpp + | get_compute_graph(): drop non-COMPUTE branches, keep pure top-k + +-- static (NPU, FORCE_STATIC) -> ov_graph_compute_static() + +-- dynamic (CPU, GPU) --------> ov_graph_compute_dynamic() + | is_naive() -> naive_compute(): convert and compile on every call + | graph_key hit -> reuse decoder + infer request ------------------+ + v | +GgmlOvDecoder: inputs, weights, KV cache, dims ggml-decoder.cpp | + | shared compiled model hit -> new infer request ------------------+ + | cache dir + fingerprint hit -> core.import_model() --------------+ + v | +FrontEnd::convert() -> TranslateSession openvino/ | + | translate_graph(): op_table.cpp -> op/*.cpp | + | apply_transformations(): pass_registry/{common,cpu,gpu,npu}.cpp | + v | +core.compile_model() -> export blob + manifest utils.cpp | + v | +ov::InferRequest <----------------------------------------------------------+ + | bind ggml buffers as tensors (USM on GPU) +infer() -> replay writeback (query_state) -> ggml tensors +``` + +- `ggml_backend_openvino_device_supports_op()` decides which ops the scheduler gives to the backend. See [Where to change what](#where-to-change-what). +- `get_compute_graph()` drops the nodes without the COMPUTE flag. On the dynamic stateless path, it keeps the pure top-k sampling branches. See [Stable multi-slot draft sampling](QWEN-MTP.md#stable-multi-slot-draft-sampling). +- `ggml_openvino_is_static()` selects the static path: the NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`. +- `is_naive()` is true for graphs with fewer than 20 ops and for graphs without weights, for example `test-backend-ops` graphs. `naive_compute()` translates them op by op and compiles them on every call. +- `graph_key` is the key of the cache of each backend context. A hit reuses the decoder and the infer request. See [In-process caches](#in-process-caches). +- `GgmlOvDecoder` walks the graph. It finds the inputs, outputs, weights and KV cache, and the dynamic dimensions. +- The shared compiled-model cache serves all backend contexts of the process. A hit creates a new infer request from the compiled model. +- With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, a matching fingerprint imports the blob instead of converting and compiling the graph. See [Compiled model cache](#compiled-model-cache). +- `FrontEnd::convert()` runs a `TranslateSession`, which builds an `ov::Model`. `translate_graph()` calls one translator for each node, then `apply_transformations()` runs the pass pipeline of the device. +- `core.compile_model()` compiles the model. With a cache directory, the backend exports the blob and its manifest. +- The backend binds the ggml buffers as input and output tensors. On the GPU, the backend buffers are USM device allocations, which the plugin uses in place. Small host tensors go through USM host staging tensors. +- After `infer()`, the backend copies the replay cache states back to the ggml banks. See [Replay graph contract](QWEN-MTP.md#replay-graph-contract). +- The static path follows the same stages. It compiles a prefill model with a fixed chunk (`GGML_OPENVINO_PREFILL_CHUNK_SIZE`) and one or more decode models. See [KV cache binding](#kv-cache-binding) and [KV-only prefill](#kv-only-prefill). + +## Where to change what + +The table names the files for common changes. Paths are relative to `ggml/src/ggml-openvino/`. + +| Change | Where | +|---|---| +| Add a GGML op | `openvino/op/.cpp`, `openvino/op_table.h`, `openvino/op_table.cpp`; case checks in `ggml-openvino.cpp` | +| Work around a plugin defect on one device | `openvino/pass_registry/.cpp` | +| Change NPU compile properties | `device/npu_config.cpp` | +| Change a weight layout | `ggml_openvino_get_requant_type()` in `ggml-openvino-extra.cpp`, `ggml-quants.cpp`, `device/npu_quant_policy.cpp` | +| Add an environment variable | `env_vars[]` in `ggml-openvino-extra.cpp`, plus a table row in the docs | +| Add a setting that changes the graph | `cache_settings[]` (`model-cache.cpp`); `ggml_openvino_model_cache_extra_cfg()` or, NPU static, `static_cache_base_extra()` (`utils.cpp`) | +| Change the replay pattern | `openvino/op/recurrent_replay_graph.hpp` and its OpenVINO copy | + +```cpp +// Add a GGML op +// openvino/op/my_op.cpp: the translator, in namespace ov::frontend::ggml::op +OutputVector translate_my_op(const NodeContext & context) { /* build OpenVINO nodes */ } +// openvino/op_table.h +GGML_OP_CONVERTER(translate_my_op); +// openvino/op_table.cpp, get_supported_ops() +{"GGML_OP_MY_OP", op::translate_my_op}, + +// Add an environment variable: ggml-openvino-extra.cpp, env_vars[]. Types: STR, ENUM, INT, FLOAT, BOOL. +{"GGML_OPENVINO_MY_SWITCH", env_type::BOOL}, +``` + +Notes: + +- `ggml_backend_openvino_device_supports_op_impl()` accepts every op that `get_supported_ops()` maps. Add a check there for the cases that the translator does not handle. The check returns a reason, which `GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1` logs. `GGML_OPENVINO_LOG_SUPPORTS_OP` counts the accepted and rejected ops. +- A device workaround names the plugin defect that it covers. Keep its opt-out variable next to its registration in `pass_registry/.cpp`. `openvino/pass_registry/pipeline.h` states this rule and the pass order. +- NPU compile properties are not passes. `device/npu_config.cpp` builds them. +- The backend checks the value of each variable in `env_vars[]` at start. Another `GGML_OPENVINO_*` name gives a warning. Document a user variable in [OPENVINO.md](../../../../docs/backend/OPENVINO.md#configuration) and a developer variable in [OpenVINO-ENV-VARS.md](OpenVINO-ENV-VARS.md). +- A setting that changes the converted or compiled graph must be part of the cache key, and a translation change can need a new fingerprint version. See [Cache key](#cache-key). +- A change of the replay pattern also needs the OpenVINO side. See [Replay graph contract](QWEN-MTP.md#replay-graph-contract). ## Source layout -Backend files, relative to `ggml/src/ggml-openvino/`, and OpenVINO GPU plugin parts: +Backend files, relative to `ggml/src/ggml-openvino/`: | File | Content | |---|---| +| `CMakeLists.txt` | Finds OpenVINO (Runtime, Threading) and OpenCL; builds every `*.cpp` file of the tree | | `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-openvino-extra.cpp` | Variable registry (`env_vars[]`), value checks, device selection, requant policy, KV window helpers | +| `ggml-decoder.cpp` | `GgmlOvDecoder`: finds inputs, weights and KV cache; dynamic dimensions, control inputs, output names, `cgraph_ov.txt` | +| `utils.cpp` | `ov_graph_compute()`: compute-branch filtering, static, dynamic and naive paths, compiled reuse, binding, replay writeback | +| `model-cache.cpp` | Compiled model cache on disk: fingerprint, `cache_settings[]`, manifest, NPU weights file, 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 | +| `device/npu_config.cpp` | NPU plugin properties: prefill, decode, GDN and MoE compile configs | +| `device/npu_quant_policy.cpp` | NPU weight layouts and the token embedding layout | +| `openvino/frontend.cpp` | `FrontEnd::convert()`: runs a `TranslateSession` with the op table | +| `openvino/input_model.cpp` | `InputModel`: gives the decoder to the frontend | +| `openvino/decoder.h` | `GgmlDecoder`: the decoder interface that the translators read; `GgmlOvDecoder` implements it | +| `openvino/node_context.h` | `NodeContext`: inputs, outputs and op parameters of one node, for a translator | +| `openvino/op_table.cpp` | `get_supported_ops()`: GGML op name to translator | +| `openvino/translate_session.cpp` | `translate_graph()`: model construction, sampling aliases, replay `Assign` sinks; `apply_transformations()` | +| `openvino/recurrent_replay_fusion.cpp` | `RecurrentReplayFusion`: GGML replay group recognition and standard-op replay translation | +| `openvino/utils.cpp` | Helpers for the translators: view inputs, KQ masks, RoPE sin/cos, compressed row gather | | `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 | +| `openvino/pass_registry/pipeline.h` | Pass pipeline order: common passes, device passes, execution passes | +| `openvino/pass_registry/common.cpp` | Passes for every device, and the execution passes (stateful KV, static shapes) | +| `openvino/pass_registry/{cpu,gpu,npu}.cpp` | Passes and plugin workarounds for one device | -## Compiled model cache +Local copies of internal OpenVINO declarations. The linked OpenVINO runtime provides the implementation. Keep each class layout in sync with the OpenVINO file (paths in the [OpenVINO repository](https://github.com/openvinotoolkit/openvino); `` is `src/common/transformations/include`): -`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` exports compiled graphs. Commands: [Compiled model cache](COOKBOOK.md#compiled-model-cache). +| Backend file | OpenVINO file | +|---|---| +| `openvino/op/gather_matmul.hpp` | `/ov_ops/gather_matmul.hpp` | +| `openvino/op/moe_compressed.hpp` | `src/core/dev_api/openvino/op/moe.hpp`, `/ov_ops/moe_compressed.hpp` | +| `openvino/op/selective_ssm.hpp` | `src/core/dev_api/openvino/op/selective_ssm.hpp` | +| `openvino/op/gated_delta_net.hpp` | `src/core/dev_api/openvino/op/gated_delta_net.hpp` | +| `openvino/pass/mark_dequantization_subgraph.h` | `/transformations/low_precision/mark_dequantization_subgraph.hpp` | +| `openvino/pass/mark_decompression_convert_constant_folding.h` | `/transformations/fp16_compression/mark_decompression_convert_constant_folding.hpp` | +| `openvino/rt_info/weightless_caching_attributes.hpp` | `src/core/dev_api/openvino/core/rt_info/weightless_caching_attributes.hpp` | -- 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. +OpenVINO counterparts of backend code: -The rest of this section covers CPU and GPU. +| OpenVINO part | Content | +|---|---| +| The GPU plugin pass for replay fusion | Structural matching, writable-input validation, source staging; needs a matching GPU plugin build | +| `RecurrentConvCacheReplayUpdate`, `RecurrentGatedDeltaNetReplayUpdate` | Internal GPU ops of that pass; computation in the `recurrent_cache_replay` kernels | +| OpenVINO copy of `recurrent_replay_graph.hpp` | Reference replay graph of the GPU plugin pass; keep it in sync with `openvino/op/recurrent_replay_graph.hpp` | -Cache-only mode (`GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1`): +Details: [GPU replay fusion](QWEN-MTP.md#gpu-replay-fusion). -- Allocates backend address space without filling weight pages. On Windows, this also uses system commit capacity. The model-buffer size in the loader log is this virtual size. -- Weight uploads only record the source identity. They do not read or requantize the weights. -- Skips graph conversion and compilation. Runtime buffers are still allocated and populated normally. -- Fails with an error for a missing or incompatible graph, instead of compiling with absent weights. -- Uses the settings of the current process. A different workload can still require another graph: populate it first without cache-only mode. +## Weight layouts + +The backend extracts or requantizes each quantized GGUF tensor when it builds the weight constants. The policy is `ggml_openvino_get_requant_type()` in `ggml-openvino-extra.cpp`, and `device/npu_quant_policy.cpp` on the NPU. The extraction is in `ggml-quants.cpp`. + +All devices: + +- `FP16` and `BF16` tensors are used as they are. +- A quantized token embedding (`token_embd.weight`) and output weight (`output.weight`) are converted to `Q8_0_C`, except `Q2_0`. +- `Q2_0` tensors stay 2-bit, with one scale per 64 weights, also for the token embedding and output weight. A `Q2_0` tensor that stores each scale twice (from a group-128 checkpoint) loads at group 128. +- `MXFP4` MoE expert tensors stay packed, with one E8M0 scale per 32 weights. + +CPU and GPU: + +- By default, `Q4_0`, `Q4_1`, `Q4_K` and `Q8_0` tensors keep their layout: weights, scales and zero points are extracted directly. `q4_sym128_all` and `q4_asym64_all` of `GGML_OPENVINO_REQUANT_KQUANT` requantize `Q4_K`; `q4_asym64_all` also requantizes `Q8_0`, `Q5_0` and `Q5_1` to `Q4_1_64`. +- By default, `Q5_0` and `Q5_1` tensors become 8-bit values with the same scales per 32 weights (`Q5_1` also keeps its zero points). +- `Q5_K` and `Q6_K` tensors are converted to `Q8_0_C`. `GGML_OPENVINO_REQUANT_KQUANT` selects a 4-bit layout instead, or `native`, which keeps 8-bit values with the scales per 32 (`Q5_K`) or 16 (`Q6_K`) weights. Values: [Advanced tuning](../../../../docs/backend/OPENVINO.md#advanced-tuning). +- MoE expert tensors in `Q5_0`, `Q5_1` or `Q8_0`: `q4_sym128` and `q4_sym128_all` give `Q4_0_64`, and `q4_asym64` and `q4_asym64_all` give `Q4_1_64`. + +GPU: + +- `Q4_K`, `Q5_K` and `Q6_K` MoE expert tensors, and `Q4_0` ones whose row width is a multiple of 64, are converted to `Q4_1_64`. This lets the GPU plugin use its fused MoE op (`MOECompressed`), which is much faster for prompt processing. `GGML_OPENVINO_REQUANT_KQUANT` does not change this. `GGML_OPENVINO_MOE_OP=0` turns the fused MoE op off. +- `Q5_0`, `Q5_1` and `Q8_0` MoE expert tensors are converted to `Q4_0_64` (`Q8_0_C` when the row width is not a multiple of 64). This works around a GPU plugin defect with grouped 8-bit expert weights. `GGML_OPENVINO_REQUANT_KQUANT=native` keeps them at 8 bits. + +NPU: + +- All other quantized tensors are requantized to `Q4_0_128`, or to `Q4_0_C` when the row width is not a multiple of 128. `GGML_OPENVINO_NPU_REQUANT_POLICY=channel-wise` selects `Q4_0_C` for all of them. +- 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. See [NPU host gather](#npu-host-gather). +- 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: + +- `Q8_0_C`: 8-bit, one scale per row. +- `Q4_0_128` and `Q4_0_64`: 4-bit, symmetric, one scale per 128 or 64 weights. +- `Q4_0_C`: 4-bit, symmetric, one scale per row. +- `Q4_1_64`: 4-bit, asymmetric, one scale and one zero point per 64 weights. + +## Compiled model cache -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_COMPILED_MODEL_CACHE_DIR` exports compiled graphs. This section covers the internals. Commands: [Compiled model cache](COOKBOOK.md#compiled-model-cache). Cache-only requirements and the settings that must match between runs: [CPU and GPU](COOKBOOK.md#cpu-and-gpu). -- `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_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. +### In-process caches -Settings that can differ: +- Each backend context keeps its decoders and infer requests by `graph_key` (`utils.h`). +- `graph_key` holds the node and leaf counts, the names of the first and last nodes, and markers: F32 MatMul precision guards, sampler rows, output flags, weight allocation IDs, and the input shapes of static or unqualified image graphs. +- `graph_key` does not hold the external inputs. `GGML_OPENVINO_FULL_GRAPH_KEY=1` adds them, for two graphs that could share a key ([In-process graph cache](OpenVINO-ENV-VARS.md#in-process-graph-cache)). +- On a miss, the backend looks up the shared compiled-model cache of the process. Its key is the fingerprint when a cache directory is set, otherwise `compiled_graph_key()`: topology, layouts, op parameters, constant extra inputs and weight allocation IDs. -- `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: [KV cache binding](#kv-cache-binding). +### Cache entries -Cache entries: +```text +/.blob compiled model: CPU and GPU blobs hold their weights, NPU blobs are weightless +/.manifest fingerprint, OpenVINO build, one line per weight, input and output port names +/-.weights.bin NPU: weights file shared by the weightless blobs (, : fingerprints) +/-.weights.bin.meta NPU: size record with a content hash, written after the weights file +``` -- The fingerprint uses the dynamic graph's topology, ports, model parameters, weights, settings and OpenVINO version. +- CPU and GPU: each blob holds its weights, so it can approach the model size for each compiled graph. Import still reads the blob and initializes the device. +- NPU: weightless blobs plus one shared weights file. Graphs without a KV cache (cacheless graphs) compile without NPUW, so the NPU does not cache them. +- Compatible prefill and decode graphs share one blob and manifest. A graph with different ports or incompatible shapes gets an exact entry instead (`compiled_graph_key()` with the disk-cache form). +- The backend writes the blob and the manifest to temporary files, then renames the blob first and the manifest last. So an interrupted export is not a cache hit. - 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). +- MTP draft graphs: a change of the active slot subset reuses the same compiled draft model. See [Compiled models and the cache](QWEN-MTP.md#compiled-models-and-the-cache). -### Restrictions +### Cache key -- Cache-only mode requires Linux or Windows and mmap loading (`--load-mode mmap`, or the default when all selected devices support mmap). Do not use tensor validation or mlock when trying to avoid weight reads. -- On Windows, the backend commits virtual memory for its buffers without touching weight pages. Large models can still reach the system commit limit. -- The model must execute entirely on OpenVINO, with dynamic CPU or GPU graphs and in-process caching enabled. Static (NPU) execution and CPU fallback are not supported in cache-only mode. -- GGUF metadata, tokenizer data, tensor descriptors and graph construction are still needed. The llama.cpp loader is unchanged: depending on its prefetch settings, it may request pages with `MAP_POPULATE` or read-ahead on Linux, or `PrefetchVirtualMemory` on Windows. Non-mmap loading also reads the payload before the backend sees it. -- Cache entries are identified by file identity, size, modification and change timestamps, tensor offsets, graph structure, settings and OpenVINO version. Linux uses device and inode; Windows uses volume serial and file index. Replacing, copying or modifying a GGUF model file invalidates its entries. This avoids reading weight bytes and ties the cache to the local source files. Keep those files unchanged throughout loading and inference. -- 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. +- `ggml_openvino_model_fingerprint()` (`model-cache.cpp`) hashes a version number, the graph signature, the raw values of `cache_settings[]`, a few more variables, the topology and output flags, the weights (source identity), the device, the model parameters, `extra_cfg` and the OpenVINO version. +- `cache_settings[]` (`model-cache.cpp`) lists the variables whose raw value is part of the key, including set versus unset. +- `ggml_openvino_model_cache_extra_cfg()` (`utils.cpp`) adds effective values, for example `GGML_OPENVINO_ENABLE_KV_4D` and `GGML_OPENVINO_ROPE_SINCOS`, whose default depends on the OpenVINO version or the device. +- The fingerprint also holds whether `GGML_OPENVINO_PROFILING` is `2` or more, the value of `GGML_OPENVINO_DEBUG_NODE` and, on GPU, `GGML_OPENVINO_MOE_OP=0`. +- It also holds the effective GDN decompose chunk (`0` when the decomposition is off). +- For NPU graphs with `GATED_DELTA_NET`, it also holds the GDN q pre-scale factor (`GGML_OPENVINO_GDN_Q_SCALE`, `0` when off). It also holds whether the backend selects the `PLUGIN` compiler for the graph, which it does when `NPU_COMPILER_TYPE` is not set. +- NPU static graphs also mix `static_cache_base_extra()` (`utils.cpp`) into the key: `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT`, the `GGML_OPENVINO_KV_SLICE` window base, head-major KV (`GGML_OPENVINO_NPU_KV_ON_DEMAND`), KV-only prefill, the weightless weights bank, `GGML_OPENVINO_NPU_CONFIG` and the other NPU property variables. +- Rule: a setting that changes the converted or compiled graph goes into `cache_settings[]` (raw value) or `extra_cfg` (effective value). Otherwise a run with another value imports a wrong blob. +- Rule: a translation change that makes old blobs wrong for the same key increases the version in `ggml_openvino_model_fingerprint()`. Add a comment line that names the change, as the existing lines do. -## KV cache binding +### Cache-only mode + +`GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1` (CPU and GPU): + +- Allocates backend address space without filling weight pages. +- Weight uploads only record the source identity. They do not read or requantize the weights. +- Skips graph conversion and compilation. Runtime buffers are still allocated and populated normally. +- Fails with an error for a missing or incompatible graph, instead of compiling with absent weights. -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). +### Source file identity -- `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. +- Cache entries are identified by file identity, size, modification and change timestamps, tensor offsets, graph structure, settings and OpenVINO version. The backend does not read the weight bytes to identify them. +- Linux uses device and inode; Windows uses volume serial and file index. +- A weight outside a file mapping (for example with non-mmap loading) has no file identity. A hash of its first and last 4 KiB identifies it. +- In cache-only mode, only small weights (up to 64 MiB) may be outside a file mapping, for example the Bonsai 2 Hadamard matrix that the loader builds in memory. A larger one stops the backend with a hint to use `--load-mode mmap`. -`GGML_OPENVINO_ENABLE_KV_4D`: +### Import limits -- 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. +- The manifest records the OpenVINO build. +- The CPU plugin cannot import MoE graphs with `GatherMatmul` ops. The backend writes no blob for them (`ggml_openvino_cpu_blob_importable()`). `MXFP4` MoE graphs do not use `GatherMatmul`. + +## KV cache binding + +Five variables control how the backend binds the attention KV cache. Their values and defaults are in [Switches for default optimizations](OpenVINO-ENV-VARS.md#switches-for-default-optimizations) and [Experimental options](OpenVINO-ENV-VARS.md#experimental-options). Known problems: [Known Limitations](../../../../docs/backend/OPENVINO.md#known-limitations). + +| Variable | Path | What it controls | +|---|---|---| +| `GGML_OPENVINO_ENABLE_KV_4D` | dynamic stateless GPU | 4-D binding for native in-place attention KV updates | +| `GGML_OPENVINO_KV_SLICE` | dynamic CPU and GPU | Binding of the attended prefix instead of the full allocation | +| `GGML_OPENVINO_KV_SLICE` | static NPU | Base of the compiled KV windows | +| `GGML_OPENVINO_GPU_KV_ROUND_UP` | dynamic stateless GPU | Rounding of the attended width | +| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | static NPU | One decode graph for each KV window | +| `GGML_OPENVINO_NPU_KV_ON_DEMAND` | static NPU | KV storage that grows with the rows in use | + +### 4-D KV binding on the GPU + +- `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. +- It 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. +- The default depends on the OpenVINO version. The GPU plugin updates the 4-D cache in place from OpenVINO 2026.5 ([openvino#37569](https://github.com/openvinotoolkit/openvino/pull/37569)). Older versions run this layout much slower. +- The current eligibility covers one physical stream, including unified KV. It also needs a dynamic, stateless graph that is not split (`GgmlOvDecoder::is_kvcache_4d()`). +- `-fa off` (transposed V cache) 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. Unified KV (`--kv-unified`) enables the in-place attention update for multi-slot GPU serving. - 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: +### Prefix binding on 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. +- Eligible root for `GGML_OPENVINO_KV_SLICE`: 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 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. +- Dynamic compiled blobs accept either binding, so `GGML_OPENVINO_KV_SLICE` is not part of the cache key. -`GGML_OPENVINO_KV_SLICE` and `GGML_OPENVINO_NPU_BLOB_PREBUILD` on static NPU: +### KV windows on the 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_KV_SLICE` sets the base of the compiled KV windows (`ggml_openvino_kv_slice_base()`). `0` turns the windows off. +- The window is the smallest `base * 2^k` that covers the attended length, capped by the context (`ggml_openvino_static_kv_window()`). +- 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; the extra KV rows are masked. With head-major KV (see the last item), 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. +- With `GGML_OPENVINO_NPU_BLOB_PREBUILD=1` and `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_NPU_KV_ON_DEMAND=1` with `GGML_OPENVINO_NPU_BLOB_PREBUILD` and `GGML_OPENVINO_KV_SLICE` on (the defaults): K is stored head-major (`[heads][rows][head_size]`) and V transposed (`[heads][head_size][rows]`), as OpenVINO GenAI does. Every static graph binds the whole storage, and attention uses V transposed. Sliding-window layers keep the ggml row layout (`ggml_openvino_npu_kv_head_major_enabled()`). -`GGML_OPENVINO_GPU_KV_ROUND_UP` on dynamic stateless GPU: +### Attended width on the GPU -- Controls the attended width separately from prefix binding. +- `GGML_OPENVINO_GPU_KV_ROUND_UP` controls the attended width on dynamic stateless GPU, separately from prefix binding (`ggml_openvino_gpu_kv_window()`). - `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. +- `1`: 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. @@ -175,44 +322,41 @@ On the static path (NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`), mod - 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. Commands: [Image input](COOKBOOK.md#image-input). - -- 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. - -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 preprocessing graph has no weights. It takes the naive path, which compiles it on every call. +Image input is experimental. Supported models and limits: [Known Limitations](../../../../docs/backend/OPENVINO.md#known-limitations). Commands: [Image input](COOKBOOK.md#image-input). + +- Qwen3.5 reuses its vision graph across image resolutions. `GgmlOvDecoder::is_dynamic_vision_graph()` accepts the graph: image patches (`IM2COL`), vision RoPE and attention, with only inputs and weights at the graph boundary. +- Gemma 4 uses resolution-specific encoder graphs. For such graphs, `graph_key` holds the image input shape. +- The small preprocessing graph has no weights. It takes the naive path, which compiles it on every call (`naive_compute()` in `utils.cpp`). + +## Reading graph dumps + +`GGML_OPENVINO_DUMP_CGRAPH=1` writes the GGML graph to `cgraph_ov.txt` ([Debug output](OpenVINO-ENV-VARS.md#debug-output)). The file holds only the last graph, before `get_compute_graph()`, so it also lists the branches that the backend drops. Commands: [Profiling and debug dumps](COOKBOOK.md#profiling-and-debug-dumps). + +- Each node line shows the shape, op, name, strides, buffer, the `compute` and `output` flags, and `view_offs`. +- Dump shapes use GGML order `[width, rows, dim2, dim3]`. OpenVINO reverses it. +- `view_offs` is in bytes. For example, one Qwen3.6 logits row of 248320 F32 values occupies `248320 * 4 = 993280` bytes. +- Buffer labels describe GGML storage, not the device that executes imported GPU operations. +- Enable dumps only for diagnosis. + +## Glossary + +- **Bank**: a ggml recurrent cache tensor with one row per slot, for example `cache_r` or `cache_s`. See [QWEN-MTP.md](QWEN-MTP.md#buffer-ownership-and-operation-boundaries). +- **Blob**: a compiled model that `export_model()` wrote to a file. +- **Cache entry**: a blob with its manifest, and on the NPU the shared weights file. +- **Compiled model**: an `ov::CompiledModel` in memory, from `compile_model()` or `import_model()`. +- **Dynamic path**: CPU and GPU execution. The token and KV dimensions are dynamic, so one compiled model serves different batch and context sizes. +- **GDN**: Gated Delta Net, the recurrent linear attention of Qwen3.5 and Qwen3.6 (`GGML_OP_GATED_DELTA_NET`). +- **KV window**: a KV length of `base * 2^k` rows that a static graph is compiled for. +- **MTP**: multi-token prediction. A Qwen3.5/3.6 model with MTP weights drafts tokens with its MTP layer (`--spec-type draft-mtp`). +- **Naive path**: op-by-op translation of small graphs and graphs without weights, compiled on every call. +- **NPUW**: the NPU wrapper in the OpenVINO NPU plugin. It partitions models and shares weights between compiled models through a weights bank. +- **Replay**: after MTP rejects a draft suffix, the next batch first replays the kept pending tokens through the recurrent layers. +- **SDPA**: the OpenVINO `ScaledDotProductAttention` op, which reads the attention K/V. +- **Sequence**: a llama.cpp sequence (`seq_id`). One slot runs one sequence. +- **Slot**: one of the parallel sequences that llama-server (`-np`) serves. An active slot has tokens in the current batch. +- **Static path**: NPU execution, or any device with `GGML_OPENVINO_FORCE_STATIC=1`. Shapes are fixed: a prefill model with a fixed chunk and decode models. +- **Stateless**: the default execution. The KV cache and the recurrent state stay in ggml buffers, which the backend binds as model inputs and outputs. Stateful execution (deprecated) keeps the KV cache inside the OpenVINO model. +- **UD**: Unsloth Dynamic, the quantization recipe of the Unsloth GGUF files. +- **USM**: Unified Shared Memory, the Intel OpenCL extension for device, host and shared allocations. The GPU buffers of the backend are USM device allocations.